changeset 131:af114cf64822

Added some reference counting to open db connection to not forcefully close them when system is under pressure. TODO: check if this race free (it should).
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Thu, 28 Jun 2018 17:13:02 +0200
parents 13b82701b1fb
children 61f86d069259
files auth/connection.go
diffstat 1 files changed, 16 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- a/auth/connection.go	Thu Jun 28 16:59:16 2018 +0200
+++ b/auth/connection.go	Thu Jun 28 17:13:02 2018 +0200
@@ -20,8 +20,9 @@
 	user     string
 	password string
 
-	access time.Time
-	db     *sql.DB
+	access   time.Time
+	db       *sql.DB
+	refCount int
 }
 
 func (c *Connection) set(user, password string) {
@@ -157,14 +158,16 @@
 	return con
 }
 
-func trim(cp *ConnectionPool) {
+func (cp *ConnectionPool) trim(conn *Connection) {
+
+	conn.refCount--
 
 	least := time.Now()
 	var count int
 	var oldest *Connection
 
 	for _, con := range cp.conns {
-		if con.db != nil {
+		if con.db != nil && con.refCount <= 0 {
 			if con.access.Before(least) {
 				least = con.access
 				oldest = con
@@ -173,10 +176,8 @@
 		}
 	}
 	if count > maxOpen {
-		oldest.db.Close()
-		oldest.db = nil
+		oldest.close()
 	}
-	return
 }
 
 func (cp *ConnectionPool) Do(token string, fn func(*sql.DB) error) error {
@@ -196,6 +197,7 @@
 		}
 		con.access = time.Now()
 		if con.db != nil {
+			con.refCount++
 			res <- result{con: con}
 			return
 		}
@@ -206,6 +208,8 @@
 			return
 		}
 		con.db = db
+		con.refCount++
+		res <- result{con: con}
 	}
 
 	r := <-res
@@ -214,7 +218,11 @@
 		return r.err
 	}
 
-	defer func() { cp.cmds <- trim }()
+	defer func() {
+		cp.cmds <- func(cp *ConnectionPool) {
+			cp.trim(r.con)
+		}
+	}()
 
 	return fn(r.con.db)
 }