I'm trying to create a session manager for a asyncrounous http server. I have a 
table with all created sessions. Each session should be deleted after a certain 
time if there are no user requests. The following prototype code (I don't know 
if it's correct) creates the sessions, but then when the timeout occurs it 
delete the session and stops. How can I check if sessions have already expired 
at regular intervals and continue processing the requests?
    
    
    import asynchttpserver, asyncdispatch
    import tables
    import times
    import oids
    
    type
      Session = object
        map: TableRef[string, string]
        request_time: DateTime
        callback: proc (id: string): Future[void] {.gcsafe.}
    
    var sessions = newTable[string, Session]()
    
    const sessionTimeout = 30
    
    proc sessions_manager() {.async.} =
      while true:
        await sleepAsync(1000)
        echo "check for sessions timeout..."
        for key, value in sessions:
          if (now() - sessions[key].request_time).inSeconds > sessionTimeout:
            echo "session id timeout:", key
            await sessions[key].callback(key)
            echo "the session will be deleted:", key
            sessions.del(key)
    
    proc cb(req: Request) {.async,gcsafe.} =
      
      echo sessions
      
      proc timeout_session(id: string) {.async.} =
        echo "expired session:", id
      
      let session_id = genOid()
      var session = Session(
        map: newTable[string, string](),
        request_time: now(),
        callback: timeout_session
      )
      session.map["login"] = "test"
      session.map["password"] = "123456789"
      sessions[$session_id] = session
      
      await req.respond(Http200, "Hello World")
    
    
    proc main() =
      let server = newAsyncHttpServer()
      
      discard sessions_manager()
      
      waitFor server.serve(Port(8080), cb)
    
    main()
    
    
    Run

Reply via email to