Merge pull request #275 from sosedoff/close-idle-sessions

Automatically close idle sessions
This commit is contained in:
Dan Sosedoff 2017-09-22 23:01:01 -05:00 committed by GitHub
commit 8bd6f08794
3 changed files with 54 additions and 0 deletions

View File

@ -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()
}
}

View File

@ -196,6 +196,11 @@ func Run() {
util.StartProfiler()
}
// Start session cleanup worker
if options.Sessions {
go api.StartSessionCleanup()
}
startServer()
openPage()
handleSignals()

View File

@ -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)