diff options
-rw-r--r-- | src/lib.go | 55 |
1 files changed, 48 insertions, 7 deletions
@@ -41,23 +41,35 @@ const pingFrequency = time.Duration(30) * time.Second const pongMaxLatency = time.Duration(5) * time.Second - +// type UUID string + type Channel struct { } -type Context struct { - db *sql.DB - tx chan int -} - type Connection struct { conn net.Conn replyChan chan string + lastReadFrom time.Time + lastWrittenTo time.Time // id *UUID id string isAuthenticated bool } +type User struct { + connections []Connection +} + +type State struct { + users map[string]*User +} + +type Context struct { + db *sql.DB + state State + tx chan int +} + type MessageParams struct { Middle []string Trailing string @@ -247,6 +259,8 @@ func ActionFnFor(command string) func(*Context, Message) { } func ProcessMessage(ctx *Context, connection *Connection, rawMessage string) { + connection.lastReadFrom = time.Now() + msg, err := ParseMessage(rawMessage) if err != nil { g.Info( @@ -295,22 +309,49 @@ func WriteLoop(ctx *Context, connection *Connection) { EmitWriteToClientError() continue } + + connection.lastWrittenTo = time.Now() } EmitActiveConnection.Dec() connection.conn.Close() } +func Kill(ctx *Context, connection *Connection) { + // lock? + delete(ctx.state.users, connection.id) + // unlock? + close(connection.replyChan) + connection.conn.Close() // Ignore errors? +} + +const PingWindow = 30 * time.Second func PingLoop(ctx *Context, connection *Connection) { - // fmt.Println("PingLoop") + for { + time.Sleep(PingWindow) + if (time.Since(connection.lastReadFrom) <= PingWindow) { + continue + } + + if ((connection.lastWrittenTo.Sub(connection.lastReadFrom)) <= PingWindow) { + connection.replyChan <- "PING" + continue + } + + Kill(ctx, connection) + break + } } func HandleConnection(ctx *Context, conn net.Conn) { EmitActiveConnection.Inc() // FIXME: WaitGroup here? + now := time.Now() connection := Connection { conn: conn, isAuthenticated: false, + lastReadFrom: now, + lastWrittenTo: now, } go ReadLoop(ctx, &connection) go WriteLoop(ctx, &connection) |