@@ -899,18 +899,8 @@ func (q *fakeQuerier) GetAuthorizedWorkspaces(ctx context.Context, arg database.
899
899
900
900
var hasAgentMatched bool
901
901
for _ , wa := range workspaceAgents {
902
- switch arg .HasAgent {
903
- case "connected" :
904
- hasAgentMatched = wa .LastConnectedAt .Valid
905
- case "connecting" :
906
- hasAgentMatched = ! wa .FirstConnectedAt .Valid
907
- case "disconnected" :
908
- hasAgentMatched = (wa .DisconnectedAt .Valid && wa .DisconnectedAt .Time .After (wa .LastConnectedAt .Time )) ||
909
- (wa .LastConnectedAt .Valid && wa .LastConnectedAt .Time .Add (time .Duration (arg .AgentInactiveDisconnectTimeoutSeconds )* time .Second ).Before (database .Now ()))
910
- case "timeout" :
911
- hasAgentMatched = ! wa .FirstConnectedAt .Valid &&
912
- wa .CreatedAt .Add (time .Duration (wa .ConnectionTimeoutSeconds )* time .Second ).Before (database .Now ())
913
- }
902
+ mapped := mapAgentStatus (wa , arg .AgentInactiveDisconnectTimeoutSeconds )
903
+ hasAgentMatched = mapped == arg .HasAgent
914
904
break // only 1 agent is expected
915
905
}
916
906
@@ -957,6 +947,38 @@ func (q *fakeQuerier) GetAuthorizedWorkspaces(ctx context.Context, arg database.
957
947
return convertToWorkspaceRows (workspaces , int64 (beforePageCount )), nil
958
948
}
959
949
950
+ func mapAgentStatus (dbAgent database.WorkspaceAgent , agentInactiveDisconnectTimeoutSeconds int64 ) string {
951
+ var status string
952
+ connectionTimeout := time .Duration (dbAgent .ConnectionTimeoutSeconds ) * time .Second
953
+ switch {
954
+ case ! dbAgent .FirstConnectedAt .Valid :
955
+ switch {
956
+ case connectionTimeout > 0 && database .Now ().Sub (dbAgent .CreatedAt ) > connectionTimeout :
957
+ // If the agent took too long to connect the first time,
958
+ // mark it as timed out.
959
+ status = "timeout"
960
+ default :
961
+ // If the agent never connected, it's waiting for the compute
962
+ // to start up.
963
+ status = "connecting"
964
+ }
965
+ case dbAgent .DisconnectedAt .Time .After (dbAgent .LastConnectedAt .Time ):
966
+ // If we've disconnected after our last connection, we know the
967
+ // agent is no longer connected.
968
+ status = "disconnected"
969
+ case database .Now ().Sub (dbAgent .LastConnectedAt .Time ) > time .Duration (agentInactiveDisconnectTimeoutSeconds )* time .Second :
970
+ // The connection died without updating the last connected.
971
+ status = "disconnected"
972
+ case dbAgent .LastConnectedAt .Valid :
973
+ // The agent should be assumed connected if it's under inactivity timeouts
974
+ // and last connected at has been properly set.
975
+ status = "connected"
976
+ default :
977
+ panic ("unknown agent status: " + status )
978
+ }
979
+ return status
980
+ }
981
+
960
982
func convertToWorkspaceRows (workspaces []database.Workspace , count int64 ) []database.GetWorkspacesRow {
961
983
rows := make ([]database.GetWorkspacesRow , len (workspaces ))
962
984
for i , w := range workspaces {
0 commit comments