2016-09-15 06:41:57 +05:30
|
|
|
package sql
|
|
|
|
|
|
|
|
import (
|
2016-10-05 01:27:21 +05:30
|
|
|
"context"
|
2016-09-15 06:41:57 +05:30
|
|
|
"fmt"
|
2016-10-05 01:27:21 +05:30
|
|
|
"log"
|
2016-09-15 06:41:57 +05:30
|
|
|
"time"
|
2016-10-05 01:27:21 +05:30
|
|
|
|
|
|
|
"github.com/coreos/dex/storage"
|
2016-09-15 06:41:57 +05:30
|
|
|
)
|
|
|
|
|
|
|
|
type gc struct {
|
|
|
|
now func() time.Time
|
|
|
|
conn *conn
|
|
|
|
}
|
|
|
|
|
|
|
|
func (gc gc) run() error {
|
2016-10-05 01:27:21 +05:30
|
|
|
for _, table := range []string{"auth_request", "auth_code"} {
|
2016-09-15 06:41:57 +05:30
|
|
|
_, err := gc.conn.Exec(`delete from `+table+` where expiry < $1`, gc.now())
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("gc %s: %v", table, err)
|
|
|
|
}
|
|
|
|
// TODO(ericchiang): when we have levelled logging print how many rows were gc'd
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2016-10-05 01:27:21 +05:30
|
|
|
|
|
|
|
type withCancel struct {
|
|
|
|
storage.Storage
|
|
|
|
cancel context.CancelFunc
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w withCancel) Close() error {
|
|
|
|
w.cancel()
|
|
|
|
return w.Storage.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func withGC(conn *conn, now func() time.Time) storage.Storage {
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
run := (gc{now, conn}).run
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-time.After(time.Second * 30):
|
|
|
|
if err := run(); err != nil {
|
|
|
|
log.Printf("gc failed: %v", err)
|
|
|
|
}
|
|
|
|
case <-ctx.Done():
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
return withCancel{conn, cancel}
|
|
|
|
}
|