@@ -601,7 +601,7 @@ func (api *API) workspaceAgentCoordinate(rw http.ResponseWriter, r *http.Request
601601 Valid : true ,
602602 }
603603 disconnectedAt := workspaceAgent .DisconnectedAt
604- updateConnectionTimes := func () error {
604+ updateConnectionTimes := func (ctx context. Context ) error {
605605 err = api .Database .UpdateWorkspaceAgentConnectionByID (ctx , database.UpdateWorkspaceAgentConnectionByIDParams {
606606 ID : workspaceAgent .ID ,
607607 FirstConnectedAt : firstConnectedAt ,
@@ -620,15 +620,23 @@ func (api *API) workspaceAgentCoordinate(rw http.ResponseWriter, r *http.Request
620620 }
621621
622622 defer func () {
623+ // If connection closed then context will be canceled, try to
624+ // ensure our final update is sent. By waiting at most the agent
625+ // inactive disconnect timeout we ensure that we don't block but
626+ // also guarantee that the agent will be considered disconnected
627+ // by normal status check.
628+ ctx , cancel := context .WithTimeout (api .ctx , api .AgentInactiveDisconnectTimeout )
629+ defer cancel ()
630+
623631 disconnectedAt = sql.NullTime {
624632 Time : database .Now (),
625633 Valid : true ,
626634 }
627- _ = updateConnectionTimes ()
628- _ = api .Pubsub . Publish ( watchWorkspaceChannel ( build .WorkspaceID ), [] byte {} )
635+ _ = updateConnectionTimes (ctx )
636+ api .publishWorkspaceUpdate ( ctx , build .WorkspaceID )
629637 }()
630638
631- err = updateConnectionTimes ()
639+ err = updateConnectionTimes (ctx )
632640 if err != nil {
633641 _ = conn .Close (websocket .StatusGoingAway , err .Error ())
634642 return
@@ -668,7 +676,7 @@ func (api *API) workspaceAgentCoordinate(rw http.ResponseWriter, r *http.Request
668676 Time : database .Now (),
669677 Valid : true ,
670678 }
671- err = updateConnectionTimes ()
679+ err = updateConnectionTimes (ctx )
672680 if err != nil {
673681 _ = conn .Close (websocket .StatusGoingAway , err .Error ())
674682 return
0 commit comments