diff --git a/pkg/api/session_cleanup.go b/pkg/api/session_cleanup.go new file mode 100644 index 0000000..5951521 --- /dev/null +++ b/pkg/api/session_cleanup.go @@ -0,0 +1,45 @@ +package api + +import ( + "log" + "time" + + "github.com/sosedoff/pgweb/pkg/command" +) + +func cleanupIdleSessions() { + ids := []string{} + + // Figure out which sessions are idle + for id, client := range DbSessions { + if client.IsIdle() { + ids = append(ids, id) + } + } + + // Close and delete idle sessions + if len(ids) == 0 { + return + } + log.Println("Closing", len(ids), "idle sessions") + for _, id := range ids { + // TODO: concurrent map edit will trigger panic + if err := DbSessions[id].Close(); err == nil { + delete(DbSessions, id) + } + } +} + +func StartSessionCleanup() { + ticker := time.NewTicker(time.Minute) + + for { + <-ticker.C + + if command.Opts.Debug { + log.Println("Triggering idle session deletion") + } + + cleanupIdleSessions() + } +} diff --git a/pkg/cli/cli.go b/pkg/cli/cli.go index a42be62..9b5887c 100644 --- a/pkg/cli/cli.go +++ b/pkg/cli/cli.go @@ -196,6 +196,11 @@ func Run() { util.StartProfiler() } + // Start session cleanup worker + if options.Sessions { + go api.StartSessionCleanup() + } + startServer() openPage() handleSignals() diff --git a/pkg/client/client.go b/pkg/client/client.go index 5b7ecb8..cb7dd33 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -363,6 +363,10 @@ func (client *Client) Close() error { return nil } +func (client *Client) IsIdle() bool { + return time.Since(client.lastQueryTime).Hours() > 1 +} + // Fetch all rows as strings for a single column func (client *Client) fetchRows(q string) ([]string, error) { res, err := client.query(q)