MCPcopy Index your code
hub / github.com/coder/coder / dialWithLazyValidation

Function dialWithLazyValidation

coderd/x/chatd/dialvalidation.go:45–182  ·  view source on GitHub ↗

dialWithLazyValidation dials an agent and only consults the database if the original dial is slow or fails quickly. This keeps the common path free of latest-build lookups while still repairing stale bindings. Outcomes: - The dial succeeds before delay, so validation is skipped. - The timer fires a

(
	ctx context.Context,
	agentID uuid.UUID,
	workspaceID uuid.UUID,
	dialFn DialFunc,
	validateFn ValidateFunc,
	delay time.Duration,
)

Source from the content-addressed store, hash-verified

43// - The dial fails before delay, so validation runs immediately and either
44// switches to a different agent or retries the current one once.
45func dialWithLazyValidation(
46 ctx context.Context,
47 agentID uuid.UUID,
48 workspaceID uuid.UUID,
49 dialFn DialFunc,
50 validateFn ValidateFunc,
51 delay time.Duration,
52) (DialResult, error) {
53 wrapErr := func(err error) error {
54 return xerrors.Errorf("dial with lazy validation: %w", err)
55 }
56
57 dialCtx, dialCancel := context.WithCancel(ctx)
58 results := make(chan dialOut, 1)
59 go func() {
60 conn, release, err := dialFn(dialCtx, agentID)
61 results <- dialOut{conn: conn, release: release, err: err}
62 }()
63
64 drained := false
65 defer func() {
66 dialCancel()
67 if drained {
68 return
69 }
70 // Drain without blocking the caller. dialFn may take time to honor
71 // cancellation, but any late-arriving successful connection still needs to
72 // be released.
73 go func() {
74 result := <-results
75 if result.err == nil && result.release != nil {
76 result.release()
77 }
78 }()
79 }()
80
81 resultForAgent := func(dialedAgentID uuid.UUID, result dialOut, switched bool) DialResult {
82 return DialResult{
83 Conn: result.conn,
84 Release: result.release,
85 AgentID: dialedAgentID,
86 WasSwitched: switched,
87 }
88 }
89 dialAgent := func(targetAgentID uuid.UUID, switched bool) (DialResult, error) {
90 conn, release, err := dialFn(ctx, targetAgentID)
91 if err != nil {
92 return DialResult{}, wrapErr(err)
93 }
94 return resultForAgent(targetAgentID, dialOut{conn: conn, release: release}, switched), nil
95 }
96 preferReadyOriginalDial := func() (DialResult, bool) {
97 select {
98 case result := <-results:
99 drained = true
100 if result.err != nil {
101 return DialResult{}, false
102 }

Calls 6

releaseMethod · 0.80
ErrMethod · 0.80
StopMethod · 0.65
ErrorfMethod · 0.45
DoneMethod · 0.45
IsMethod · 0.45