forked from coder/coder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkspaceagentconnwatch.go
More file actions
86 lines (73 loc) · 2.26 KB
/
Copy pathworkspaceagentconnwatch.go
File metadata and controls
86 lines (73 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package workspacesdk
import (
"context"
"fmt"
"github.com/google/uuid"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/wsjson"
"github.com/coder/websocket"
)
type WatchErrorCode int
const (
_ WatchErrorCode = iota // Ensure that zero value is not a valid code
WatchErrorTooManyAgents
WatchErrorNameNotFound
WatchErrorNoAgents
WatchErrorServerShutdown
WatchErrorDatabase
WatchErrorInternal
)
type ConnectionWatchEvent struct {
Error *WatchError `json:"error"`
BuildUpdate *BuildUpdate `json:"build_update,omitempty"`
AgentUpdate *AgentUpdate `json:"agent_update,omitempty"`
}
type WatchError struct {
Code WatchErrorCode `json:"code"`
Retryable bool `json:"retryable"`
Message string `json:"message"`
Details string `json:"details,omitempty"`
}
func (e *WatchError) Error() string {
if e.Details != "" {
return fmt.Sprintf("%s: %s", e.Message, e.Details)
}
return e.Message
}
type BuildUpdate struct {
Transition codersdk.WorkspaceTransition `json:"transition"`
JobStatus codersdk.ProvisionerJobStatus `json:"job_status"`
}
type AgentUpdate struct {
Lifecycle codersdk.WorkspaceAgentLifecycle `json:"lifecycle"`
ID uuid.UUID `json:"id" format:"uuid"`
}
func (c *Client) WorkspaceAgentConnectionWatch(
dialCtx context.Context, workspaceID uuid.UUID, agentName string,
) (
dec *wsjson.Decoder[ConnectionWatchEvent], err error,
) {
wsOptions := &websocket.DialOptions{
HTTPClient: c.client.HTTPClient,
// Need to disable compression to avoid a data-race.
CompressionMode: websocket.CompressionDisabled,
}
c.client.SessionTokenProvider.SetDialOption(wsOptions)
watchURL, err := c.client.URL.Parse(fmt.Sprintf("/api/v2/workspaces/%s/agent-connection-watch", workspaceID))
if err != nil {
return nil, xerrors.Errorf("parse url: %w", err)
}
if agentName != "" {
q := watchURL.Query()
q.Set("agent_name", agentName)
watchURL.RawQuery = q.Encode()
}
// nolint:bodyclose
conn, res, err := websocket.Dial(dialCtx, watchURL.String(), wsOptions)
if err != nil {
bodyErr := codersdk.ReadBodyAsError(res)
return nil, bodyErr
}
return wsjson.NewDecoder[ConnectionWatchEvent](conn, websocket.MessageText, c.client.Logger()), nil
}