Connect establishes a connection to coderd.
()
| 76 | |
| 77 | // Connect establishes a connection to coderd. |
| 78 | func (s *Server) connect() { |
| 79 | defer s.logger.Debug(s.lifecycleCtx, "connect loop exited") |
| 80 | defer s.wg.Done() |
| 81 | |
| 82 | logConnect := s.logger.With(slog.F("context", "aibridged.server")).Debug |
| 83 | // An exponential back-off occurs when the connection is failing to dial. |
| 84 | // This is to prevent server spam in case of a coderd outage. |
| 85 | connectLoop: |
| 86 | for retrier := retry.New(50*time.Millisecond, 10*time.Second); retrier.Wait(s.lifecycleCtx); { |
| 87 | // It's possible for the aibridge daemon to be shut down |
| 88 | // before the wait is complete! |
| 89 | if s.isShutdown() { |
| 90 | return |
| 91 | } |
| 92 | s.logger.Debug(s.lifecycleCtx, "dialing coderd") |
| 93 | client, err := s.clientDialer(s.lifecycleCtx) |
| 94 | if err != nil { |
| 95 | if errors.Is(err, context.Canceled) { |
| 96 | return |
| 97 | } |
| 98 | var sdkErr *codersdk.Error |
| 99 | // If something is wrong with our auth, stop trying to connect. |
| 100 | if errors.As(err, &sdkErr) && sdkErr.StatusCode() == http.StatusForbidden { |
| 101 | s.logger.Error(s.lifecycleCtx, "not authorized to dial coderd", slog.Error(err)) |
| 102 | return |
| 103 | } |
| 104 | if s.isShutdown() { |
| 105 | return |
| 106 | } |
| 107 | s.logger.Warn(s.lifecycleCtx, "coderd client failed to dial", slog.Error(err)) |
| 108 | continue |
| 109 | } |
| 110 | |
| 111 | // TODO: log this with INFO level when we implement external aibridge daemons. |
| 112 | logConnect(s.lifecycleCtx, "successfully connected to coderd") |
| 113 | retrier.Reset() |
| 114 | s.initConnectionOnce.Do(func() { |
| 115 | close(s.initConnectionCh) |
| 116 | }) |
| 117 | |
| 118 | // Serve the client until we are closed or it disconnects. |
| 119 | for { |
| 120 | select { |
| 121 | case <-s.lifecycleCtx.Done(): |
| 122 | client.DRPCConn().Close() |
| 123 | return |
| 124 | case <-client.DRPCConn().Closed(): |
| 125 | logConnect(s.lifecycleCtx, "connection to coderd closed") |
| 126 | continue connectLoop |
| 127 | case s.clientCh <- client: |
| 128 | continue |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | func (s *Server) Client() (DRPCClient, error) { |
| 135 | select { |