| 35 | } |
| 36 | |
| 37 | func (a *AppsAPI) BatchUpdateAppHealths(ctx context.Context, req *agentproto.BatchUpdateAppHealthRequest) (*agentproto.BatchUpdateAppHealthResponse, error) { |
| 38 | a.Log.Debug(ctx, "got batch app health update", |
| 39 | slog.F("agent_id", a.AgentID.String()), |
| 40 | slog.F("updates", req.Updates), |
| 41 | ) |
| 42 | |
| 43 | if len(req.Updates) == 0 { |
| 44 | return &agentproto.BatchUpdateAppHealthResponse{}, nil |
| 45 | } |
| 46 | |
| 47 | apps, err := a.Database.GetWorkspaceAppsByAgentID(ctx, a.AgentID) |
| 48 | if err != nil { |
| 49 | return nil, xerrors.Errorf("get workspace apps by agent ID %q: %w", a.AgentID, err) |
| 50 | } |
| 51 | |
| 52 | var newApps []database.WorkspaceApp |
| 53 | for _, update := range req.Updates { |
| 54 | updateID, err := uuid.FromBytes(update.Id) |
| 55 | if err != nil { |
| 56 | return nil, xerrors.Errorf("parse workspace app ID %q: %w", update.Id, err) |
| 57 | } |
| 58 | |
| 59 | old := func() *database.WorkspaceApp { |
| 60 | for _, app := range apps { |
| 61 | if app.ID == updateID { |
| 62 | return &app |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | return nil |
| 67 | }() |
| 68 | if old == nil { |
| 69 | return nil, xerrors.Errorf("workspace app ID %q not found", updateID) |
| 70 | } |
| 71 | |
| 72 | if old.HealthcheckUrl == "" { |
| 73 | return nil, xerrors.Errorf("workspace app %q (%q) does not have healthchecks enabled", updateID, old.Slug) |
| 74 | } |
| 75 | |
| 76 | var newHealth database.WorkspaceAppHealth |
| 77 | switch update.Health { |
| 78 | case agentproto.AppHealth_DISABLED: |
| 79 | newHealth = database.WorkspaceAppHealthDisabled |
| 80 | case agentproto.AppHealth_INITIALIZING: |
| 81 | newHealth = database.WorkspaceAppHealthInitializing |
| 82 | case agentproto.AppHealth_HEALTHY: |
| 83 | newHealth = database.WorkspaceAppHealthHealthy |
| 84 | case agentproto.AppHealth_UNHEALTHY: |
| 85 | newHealth = database.WorkspaceAppHealthUnhealthy |
| 86 | default: |
| 87 | return nil, xerrors.Errorf("unknown health status %q for app %q (%q)", update.Health, updateID, old.Slug) |
| 88 | } |
| 89 | |
| 90 | // Don't bother updating if the value hasn't changed. |
| 91 | if old.Health == newHealth { |
| 92 | continue |
| 93 | } |
| 94 | old.Health = newHealth |