Agent displays a spinning indicator that waits for a workspace agent to connect.
(ctx context.Context, writer io.Writer, agentID uuid.UUID, opts AgentOptions)
| 44 | |
| 45 | // Agent displays a spinning indicator that waits for a workspace agent to connect. |
| 46 | func Agent(ctx context.Context, writer io.Writer, agentID uuid.UUID, opts AgentOptions) error { |
| 47 | ctx, cancel := context.WithCancel(ctx) |
| 48 | defer cancel() |
| 49 | |
| 50 | if opts.FetchInterval == 0 { |
| 51 | opts.FetchInterval = 500 * time.Millisecond |
| 52 | } |
| 53 | if opts.FetchLogs == nil { |
| 54 | opts.FetchLogs = func(_ context.Context, _ uuid.UUID, _ int64, _ bool) (<-chan []codersdk.WorkspaceAgentLog, io.Closer, error) { |
| 55 | c := make(chan []codersdk.WorkspaceAgentLog) |
| 56 | close(c) |
| 57 | return c, closeFunc(func() error { return nil }), nil |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | fetchedAgent := make(chan fetchAgentResult, 1) |
| 62 | go func() { |
| 63 | t := time.NewTimer(0) |
| 64 | defer t.Stop() |
| 65 | |
| 66 | startTime := time.Now() |
| 67 | baseInterval := opts.FetchInterval |
| 68 | |
| 69 | for { |
| 70 | select { |
| 71 | case <-ctx.Done(): |
| 72 | return |
| 73 | case <-t.C: |
| 74 | agent, err := opts.Fetch(ctx, agentID) |
| 75 | select { |
| 76 | case <-fetchedAgent: |
| 77 | default: |
| 78 | } |
| 79 | if err != nil { |
| 80 | fetchedAgent <- fetchAgentResult{err: xerrors.Errorf("fetch workspace agent: %w", err)} |
| 81 | return |
| 82 | } |
| 83 | fetchedAgent <- fetchAgentResult{agent: agent} |
| 84 | |
| 85 | // Adjust the interval based on how long we've been waiting. |
| 86 | elapsed := time.Since(startTime) |
| 87 | currentInterval := GetProgressiveInterval(baseInterval, elapsed) |
| 88 | t.Reset(currentInterval) |
| 89 | } |
| 90 | } |
| 91 | }() |
| 92 | fetch := func(ctx context.Context) (codersdk.WorkspaceAgent, error) { |
| 93 | select { |
| 94 | case <-ctx.Done(): |
| 95 | return codersdk.WorkspaceAgent{}, ctx.Err() |
| 96 | case f := <-fetchedAgent: |
| 97 | if f.err != nil { |
| 98 | return codersdk.WorkspaceAgent{}, f.err |
| 99 | } |
| 100 | return f.agent, nil |
| 101 | } |
| 102 | } |
| 103 |