From fe392e60f5dcb838d0fe32a20fe3c5a67626c3e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fiere?= Date: Sat, 11 Jul 2026 00:32:18 +0200 Subject: [PATCH] feat: support multiple concurrent Sentry instances (#1469) --- apps/backend/internal/integrations/AGENTS.md | 1 + .../internal/orchestrator/source_sentry.go | 1 + apps/backend/internal/sentry/copy.go | 211 +++-- apps/backend/internal/sentry/copy_test.go | 327 ++++++- apps/backend/internal/sentry/handlers.go | 311 ++++--- .../internal/sentry/handlers_issue_watch.go | 36 +- apps/backend/internal/sentry/handlers_test.go | 424 +++++++-- .../backend/internal/sentry/migration_test.go | 590 +++++++++++++ apps/backend/internal/sentry/mock_client.go | 254 ++++-- .../internal/sentry/mock_client_test.go | 62 +- .../internal/sentry/mock_controller.go | 76 +- .../internal/sentry/mock_controller_test.go | 101 +++ apps/backend/internal/sentry/models.go | 106 ++- apps/backend/internal/sentry/poller.go | 8 +- .../sentry/poller_issue_watch_test.go | 47 + apps/backend/internal/sentry/poller_test.go | 64 +- apps/backend/internal/sentry/provider.go | 154 +++- apps/backend/internal/sentry/service.go | 614 +++++++------ .../internal/sentry/service_issue_watch.go | 112 ++- .../service_issue_watch_repository_test.go | 37 +- .../sentry/service_issue_watch_test.go | 392 ++++++--- apps/backend/internal/sentry/service_test.go | 812 ++++++++++++------ apps/backend/internal/sentry/store.go | 721 +++++++++++++--- .../internal/sentry/store_issue_watch.go | 81 +- apps/backend/internal/sentry/store_test.go | 414 ++++----- .../integration-copy-config.test.ts | 21 +- .../integrations/integration-copy-config.ts | 4 +- .../integrations/validated-popover.tsx | 17 +- .../sentry/sentry-instance-card.test.tsx | 42 + .../sentry/sentry-instance-card.tsx | 71 ++ .../sentry/sentry-instance-form.test.tsx | 80 ++ .../sentry/sentry-instance-form.tsx | 311 +++++++ .../sentry/sentry-issue-dialog.test.tsx | 112 +++ .../components/sentry/sentry-issue-dialog.tsx | 158 +++- .../sentry/sentry-issue-watch-dialog.test.tsx | 171 ++++ .../sentry/sentry-issue-watch-dialog.tsx | 136 ++- .../sentry/sentry-issue-watch-form.test.ts | 16 + .../sentry/sentry-issue-watch-form.ts | 31 +- .../sentry/sentry-issue-watch-table.test.tsx | 76 ++ .../sentry/sentry-issue-watch-table.tsx | 23 +- .../sentry-issue-watchers-section.test.tsx | 69 ++ .../sentry/sentry-issue-watchers-section.tsx | 21 +- .../sentry/sentry-settings.test.tsx | 162 ++++ .../web/components/sentry/sentry-settings.tsx | 546 ++++-------- .../task/task-external-link-dialog.test.tsx | 146 +++- .../task/task-external-link-dialog.tsx | 123 ++- apps/web/e2e/fixtures/test-base.ts | 5 +- apps/web/e2e/helpers/api-client.ts | 199 ++++- apps/web/e2e/pages/sentry-settings-page.ts | 48 +- .../integrations/sentry-settings.spec.ts | 105 ++- .../task/mobile-external-link-menu.spec.ts | 9 +- .../domains/sentry/use-sentry-availability.ts | 106 ++- apps/web/lib/api/domains/sentry-api.test.ts | 39 + apps/web/lib/api/domains/sentry-api.ts | 272 ++++-- apps/web/lib/types/sentry.ts | 41 +- ...0-workspace-scoped-integration-settings.md | 33 + 56 files changed, 7006 insertions(+), 2143 deletions(-) create mode 100644 apps/backend/internal/sentry/migration_test.go create mode 100644 apps/backend/internal/sentry/mock_controller_test.go create mode 100644 apps/web/components/sentry/sentry-instance-card.test.tsx create mode 100644 apps/web/components/sentry/sentry-instance-card.tsx create mode 100644 apps/web/components/sentry/sentry-instance-form.test.tsx create mode 100644 apps/web/components/sentry/sentry-instance-form.tsx create mode 100644 apps/web/components/sentry/sentry-issue-dialog.test.tsx create mode 100644 apps/web/components/sentry/sentry-issue-watch-dialog.test.tsx create mode 100644 apps/web/components/sentry/sentry-issue-watch-table.test.tsx create mode 100644 apps/web/components/sentry/sentry-issue-watchers-section.test.tsx create mode 100644 apps/web/components/sentry/sentry-settings.test.tsx create mode 100644 apps/web/lib/api/domains/sentry-api.test.ts diff --git a/apps/backend/internal/integrations/AGENTS.md b/apps/backend/internal/integrations/AGENTS.md index d364b95f30..28a4341361 100644 --- a/apps/backend/internal/integrations/AGENTS.md +++ b/apps/backend/internal/integrations/AGENTS.md @@ -26,3 +26,4 @@ This file covers both halves of the playbook (backend + frontend) so the pattern - **Issue model:** Jira uses transitions + JQL; Linear uses state IDs + structured filters. Don't merge these schemas — the upstream APIs are genuinely different. - **Watch filter persistence:** Jira stores the JQL string verbatim; Linear stores the structured `SearchFilter` as JSON in `filter_json` (Linear has no JQL equivalent). The orchestrator emits `NewJiraIssueEvent` / `NewLinearIssueEvent` respectively and dedups by issue key (Jira) vs identifier (Linear). - **Health column extras:** Linear's `linear_configs` row carries an `org_slug` captured from successful probes; Jira's row does not. +- **Sentry — multiple instances per workspace:** unlike the one-config-per-workspace integrations, `sentry_configs` is keyed by an instance `id` (UUID) with a `workspace_id` column + `UNIQUE(workspace_id, name)`, so a workspace holds several named instances. Secrets are keyed `sentry:instance::token`. Issue watches carry a nullable `sentry_instance_id` FK (`ON DELETE RESTRICT`); the bound instance is immutable. The HTTP surface is instance CRUD under `/api/v1/sentry/instances?workspace_id=` (no install-wide `/config`); deleting an in-use instance is 409 `SENTRY_INSTANCE_IN_USE`. See ADR-0030. diff --git a/apps/backend/internal/orchestrator/source_sentry.go b/apps/backend/internal/orchestrator/source_sentry.go index 1aeb020c74..ae628b8cb4 100644 --- a/apps/backend/internal/orchestrator/source_sentry.go +++ b/apps/backend/internal/orchestrator/source_sentry.go @@ -106,6 +106,7 @@ func (s *SentryWatcherSource) BuildTaskRequest(evt any) (*IssueTaskRequest, erro Description: interpolateSentryPrompt(e.Prompt, e.Issue), Metadata: map[string]interface{}{ sentryWatchMetadataKey: e.IssueWatchID, + "sentry_issue_instance_id": e.SentryInstanceID, "sentry_issue_short_id": e.Issue.ShortID, "sentry_issue_url": e.Issue.Permalink, "sentry_issue_level": e.Issue.Level, diff --git a/apps/backend/internal/sentry/copy.go b/apps/backend/internal/sentry/copy.go index 55b7c50fcc..4ee8efdd46 100644 --- a/apps/backend/internal/sentry/copy.go +++ b/apps/backend/internal/sentry/copy.go @@ -4,69 +4,180 @@ import ( "context" "errors" "fmt" - "time" + + "go.uber.org/zap" ) // ErrSameWorkspace is returned when a copy targets the same workspace it reads // from. var ErrSameWorkspace = errors.New("sentry: source and target workspaces are the same") -// ErrNothingToCopy is returned when the source workspace has no Sentry config. -var ErrNothingToCopy = errors.New("sentry: source workspace has no configuration to copy") +// ErrNothingToCopy is returned when the source workspace has no Sentry +// instances. +var ErrNothingToCopy = errors.New("sentry: source workspace has no Sentry instances to copy") -// CopyConfigToWorkspace copies the Sentry provider config and credential (auth -// token) from sourceWorkspaceID to targetWorkspaceID. Watchers are -// intentionally out of scope — only the connection settings and secret are -// duplicated. -func (s *Service) CopyConfigToWorkspace(ctx context.Context, sourceWorkspaceID, targetWorkspaceID string) (*SentryConfig, error) { - sourceWorkspaceID, err := s.normalizeWorkspaceID(sourceWorkspaceID) +type copyInput struct { + config *SentryConfig + secret string + hasSecret bool +} + +// CopyConfigToWorkspace copies every Sentry instance from sourceWorkspaceID +// into targetWorkspaceID: fresh instance IDs, secrets duplicated under the new +// per-instance keys, and names deduped against the target's existing instances. +// Issue watches are intentionally out of scope — only the connection settings +// and secrets are duplicated. Returns the newly created instances. +func (s *Service) CopyConfigToWorkspace(ctx context.Context, sourceWorkspaceID, targetWorkspaceID string) ([]*SentryConfig, error) { + if err := validateCopyWorkspaces(sourceWorkspaceID, targetWorkspaceID); err != nil { + return nil, err + } + prepared, used, err := s.prepareCopyInputs(ctx, sourceWorkspaceID, targetWorkspaceID) if err != nil { return nil, err } - targetWorkspaceID, err = s.normalizeWorkspaceID(targetWorkspaceID) + copied, err := s.createCopiedInstances(ctx, targetWorkspaceID, prepared, used) if err != nil { return nil, err } + s.finalizeCopiedInstances(copied) + return copied, nil +} + +// validateCopyWorkspaces rejects empty or identical source/target workspace +// IDs before any store access. +func validateCopyWorkspaces(sourceWorkspaceID, targetWorkspaceID string) error { + if sourceWorkspaceID == "" || targetWorkspaceID == "" { + return fmt.Errorf("%w: source and target workspace IDs are required", ErrInvalidConfig) + } if sourceWorkspaceID == targetWorkspaceID { - return nil, ErrSameWorkspace + return ErrSameWorkspace } - cfg, err := s.store.GetConfigForWorkspace(ctx, sourceWorkspaceID) - if err != nil { - return nil, fmt.Errorf("read source sentry config: %w", err) - } - if cfg == nil { - return nil, ErrNothingToCopy - } - secret, err := s.revealSecret(ctx, sourceWorkspaceID) - if err != nil { - return nil, fmt.Errorf("read source sentry secret: %w", err) - } - // An empty Secret means "keep existing" in SetConfigForWorkspace, so copying - // from a workspace without a stored token would leave the target on its old - // credential paired with the copied settings. Treat that as nothing to copy. - if secret == "" { - return nil, ErrNothingToCopy - } - req := &SetConfigRequest{ - AuthMethod: cfg.AuthMethod, - URL: cfg.URL, - Secret: secret, - } - // Mark the target unhealthy before the write so the UI doesn't briefly flash - // a stale "connected" state from the target's previous credential while the - // async probe kicked off by SetConfigForWorkspace validates the copied one. - if err := s.store.UpdateAuthHealthForWorkspace(ctx, targetWorkspaceID, false, "", time.Now().UTC()); err != nil { - return nil, fmt.Errorf("reset target sentry health: %w", err) - } - cfgOut, err := s.SetConfigForWorkspace(ctx, targetWorkspaceID, req) - if err != nil { - // The write failed, so the target's config is unchanged but we already - // flipped its health row. Re-probe asynchronously (best effort) so the row - // reflects the target's real state again rather than a spurious - // "unhealthy", without delaying the error response by the probe timeout. - // Detach from the request context, which may already be cancelled. - go s.RecordAuthHealthForWorkspace(context.Background(), targetWorkspaceID) - return nil, err - } - return cfgOut, nil + return nil +} + +// prepareCopyInputs reads every source instance and, for each, reveals its +// secret before any target-workspace mutation, plus the target's existing +// instance names to dedupe against. Aborting here means no partial target +// state to roll back. +func (s *Service) prepareCopyInputs(ctx context.Context, sourceWorkspaceID, targetWorkspaceID string) ([]copyInput, map[string]struct{}, error) { + sources, err := s.store.ListInstances(ctx, sourceWorkspaceID) + if err != nil { + return nil, nil, fmt.Errorf("read source sentry instances: %w", err) + } + if len(sources) == 0 { + return nil, nil, ErrNothingToCopy + } + existing, err := s.store.ListInstances(ctx, targetWorkspaceID) + if err != nil { + return nil, nil, fmt.Errorf("read target sentry instances: %w", err) + } + used := make(map[string]struct{}, len(existing)) + for _, inst := range existing { + used[inst.Name] = struct{}{} + } + prepared := make([]copyInput, 0, len(sources)) + for _, src := range sources { + input := copyInput{config: src} + if s.secrets != nil { + secret, ok, err := s.revealInstanceSecret(ctx, src.ID) + if err != nil { + return nil, nil, fmt.Errorf("read source sentry secret: %w", err) + } + input.secret = secret + input.hasSecret = ok + } + prepared = append(prepared, input) + } + return prepared, used, nil +} + +// createCopiedInstances copies every prepared input into the target +// workspace, rolling back all instances created by this request if any copy +// fails. +func (s *Service) createCopiedInstances(ctx context.Context, targetWorkspaceID string, prepared []copyInput, used map[string]struct{}) ([]*SentryConfig, error) { + copied := make([]*SentryConfig, 0, len(prepared)) + for _, input := range prepared { + out, err := s.copyInstance(ctx, targetWorkspaceID, input, used) + if out != nil { + copied = append(copied, out) + } + if err != nil { + return nil, s.rollbackCopiedInstances(ctx, copied, err) + } + } + return copied, nil +} + +// finalizeCopiedInstances invalidates the cached clients for the freshly copied +// instances. It deliberately fires no per-instance auth-health probe here: a +// workspace may hold arbitrarily many instances, so probing each copy inline +// would burst an unbounded number of goroutines and outbound Sentry calls. +// The copied instances instead get their first health check from the bounded +// background auth-health poller (RecordAuthHealth, concurrency-capped) on its +// next cycle. +func (s *Service) finalizeCopiedInstances(copied []*SentryConfig) { + for _, cfg := range copied { + s.invalidateClient(cfg.ID) + } +} + +// copyInstance duplicates a prepared source instance into the target workspace +// with a name deduped against used (which it updates) and a rekeyed secret. +// Health probing is left to the bounded background poller (see +// finalizeCopiedInstances). +func (s *Service) copyInstance(ctx context.Context, targetWorkspaceID string, input copyInput, used map[string]struct{}) (*SentryConfig, error) { + cfg := &SentryConfig{ + WorkspaceID: targetWorkspaceID, + Name: uniqueInstanceName(used, input.config.Name), + AuthMethod: input.config.AuthMethod, + URL: input.config.URL, + } + if err := s.store.CreateInstance(ctx, cfg); err != nil { + return nil, fmt.Errorf("create copied sentry instance: %w", err) + } + if input.hasSecret && s.secrets != nil { + if err := s.secrets.Set(ctx, secretKeyForInstance(cfg.ID), "Sentry auth token", input.secret); err != nil { + return cfg, fmt.Errorf("store copied sentry secret: %w", err) + } + cfg.HasSecret = true + } + return cfg, nil +} + +// rollbackCopiedInstances removes only instances created by the current copy +// request. It continues after cleanup errors so every created row is +// attempted, and only deletes a copied secret once its row delete actually +// succeeded — if DeleteInstance fails (e.g. the instance became referenced by +// a watch created concurrently, returning ErrInstanceInUse), that instance's +// row and secret are left fully intact rather than orphaning a live row. +func (s *Service) rollbackCopiedInstances(ctx context.Context, copied []*SentryConfig, cause error) error { + cleanupCtx := context.WithoutCancel(ctx) + var rollbackErrs []error + for i := len(copied) - 1; i >= 0; i-- { + cfg := copied[i] + if cfg == nil || cfg.ID == "" { + continue + } + if err := s.store.DeleteInstance(cleanupCtx, cfg.ID); err != nil { + rollbackErrs = append(rollbackErrs, fmt.Errorf("rollback copied sentry instance %q: %w", cfg.ID, err)) + continue + } + if s.secrets != nil { + key := secretKeyForInstance(cfg.ID) + exists, err := s.secrets.Exists(cleanupCtx, key) + if err != nil { + rollbackErrs = append(rollbackErrs, fmt.Errorf("check copied sentry secret %q during rollback: %w", cfg.ID, err)) + } else if exists { + if err := s.secrets.Delete(cleanupCtx, key); err != nil { + rollbackErrs = append(rollbackErrs, fmt.Errorf("rollback copied sentry secret %q: %w", cfg.ID, err)) + } + } + } + } + if len(rollbackErrs) == 0 { + return cause + } + cleanupErr := errors.Join(rollbackErrs...) + s.log.Warn("sentry: copy rollback cleanup failed", zap.Error(cleanupErr)) + return errors.Join(cause, cleanupErr) } diff --git a/apps/backend/internal/sentry/copy_test.go b/apps/backend/internal/sentry/copy_test.go index 14109541c7..93c8f1c720 100644 --- a/apps/backend/internal/sentry/copy_test.go +++ b/apps/backend/internal/sentry/copy_test.go @@ -4,59 +4,322 @@ import ( "context" "errors" "testing" - "time" + + "go.uber.org/zap" + "go.uber.org/zap/zaptest/observer" + + "github.com/kandev/kandev/internal/common/logger" ) -// drainProbe waits for the async auth-health probe fired by a config write. -func drainProbe(t *testing.T, f *svcFixture) { - t.Helper() - select { - case <-f.probed: - case <-time.After(2 * time.Second): - t.Fatalf("async probe hook did not fire within 2s") - } -} - -func TestCopyConfigToWorkspace_CopiesConfigAndSecret(t *testing.T) { +func TestCopyConfig_CopiesInstancesAndSecrets(t *testing.T) { f := newSvcFixture(t) ctx := context.Background() const src, dst = "ws-src", "ws-dst" + a := f.seedInstance(t, src, "SaaS", "sec-a") + f.seedInstance(t, src, "Self", "sec-b") - if _, err := f.svc.SetConfigForWorkspace(ctx, src, &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, - URL: "https://sentry.example.com", - Secret: "sen-src", - }); err != nil { - t.Fatalf("seed source: %v", err) - } - drainProbe(t, f) - - got, err := f.svc.CopyConfigToWorkspace(ctx, src, dst) + copied, err := f.svc.CopyConfigToWorkspace(ctx, src, dst) if err != nil { t.Fatalf("copy: %v", err) } - drainProbe(t, f) - if got.URL != "https://sentry.example.com" || got.AuthMethod != AuthMethodAuthToken { - t.Errorf("copied config mismatch: %+v", got) + if len(copied) != 2 { + t.Fatalf("expected 2 copied instances, got %d", len(copied)) } - v, err := f.secrets.Reveal(ctx, SecretKeyForWorkspace(dst)) - if err != nil { - t.Fatalf("reveal copied secret: %v", err) + names := map[string]bool{} + for _, c := range copied { + if c.WorkspaceID != dst { + t.Errorf("copied instance in wrong workspace: %+v", c) + } + if c.ID == a.ID { + t.Errorf("copied instance reused source ID %q", c.ID) + } + names[c.Name] = true + v, err := f.secrets.Reveal(ctx, secretKeyForInstance(c.ID)) + if err != nil || v == "" { + t.Errorf("secret not copied for %q: %v / %q", c.Name, err, v) + } } - if v != "sen-src" { - t.Errorf("secret not copied: %q", v) + if !names["SaaS"] || !names["Self"] { + t.Errorf("expected names preserved, got %v", names) } } -func TestCopyConfigToWorkspace_SameWorkspace(t *testing.T) { +func TestCopyConfig_SecretSetFailureRollsBackAllCreatedInstances(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + const src, dst = "ws-src", "ws-dst" + f.seedInstance(t, src, "First", "sec-first") + f.seedInstance(t, src, "Second", "sec-second") + existing := f.seedInstance(t, dst, "Existing", "sec-existing") + watch := newTestIssueWatch(dst) + watch.SentryInstanceID = existing.ID + if err := f.store.CreateIssueWatch(ctx, watch); err != nil { + t.Fatalf("seed target watch: %v", err) + } + + injected := errors.New("secret store unavailable") + missingDelete := errors.New("secret not found during rollback") + f.secrets.setErr = injected + f.secrets.setErrAfter = 1 // Let the first copied secret succeed; fail the second. + f.secrets.deleteMissingErr = missingDelete + _, err := f.svc.CopyConfigToWorkspace(ctx, src, dst) + if !errors.Is(err, injected) { + t.Fatalf("expected injected secret error, got %v", err) + } + if errors.Is(err, missingDelete) { + t.Fatalf("rollback attempted to delete an unstored copied secret: %v", err) + } + + target, err := f.svc.ListInstances(ctx, dst) + if err != nil { + t.Fatalf("list target after failed copy: %v", err) + } + if len(target) != 1 || target[0].ID != existing.ID { + t.Fatalf("failed copy changed target instances: %+v", target) + } + if secret, err := f.secrets.Reveal(ctx, secretKeyForInstance(existing.ID)); err != nil || secret != "sec-existing" { + t.Errorf("failed copy changed target secret: secret=%q err=%v", secret, err) + } + if watches, err := f.store.CountWatchesForInstance(ctx, existing.ID); err != nil || watches != 1 { + t.Errorf("failed copy changed target watch count: count=%d err=%v", watches, err) + } + if got := f.secrets.count(); got != 3 { + t.Errorf("failed copy left copied secrets: count=%d, want 3", got) + } +} + +func TestCopyConfig_PartialSecretSetFailureRollsBackAllCopiedSecrets(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + const src, dst = "ws-src", "ws-dst" + f.seedInstance(t, src, "First", "sec-first") + f.seedInstance(t, src, "Second", "sec-second") + existing := f.seedInstance(t, dst, "Existing", "sec-existing") + + injected := errors.New("secret store partially wrote then failed") + f.secrets.setErr = injected + f.secrets.setErrAfter = 1 // Let the first copied secret succeed; partially write the second. + f.secrets.setErrAfterWrite = true + if _, err := f.svc.CopyConfigToWorkspace(ctx, src, dst); !errors.Is(err, injected) { + t.Fatalf("expected injected secret error, got %v", err) + } + + target, err := f.svc.ListInstances(ctx, dst) + if err != nil { + t.Fatalf("list target after partial secret failure: %v", err) + } + if len(target) != 1 || target[0].ID != existing.ID { + t.Fatalf("partial secret failure changed target instances: %+v", target) + } + if got := f.secrets.count(); got != 3 { + t.Errorf("partial secret failure left copied secrets: count=%d, want 3", got) + } +} + +// TestCopyConfig_RollbackKeepsInUseInstanceIntact pins the fix: rollback must +// only delete a copied instance's secret when that instance's row delete +// actually succeeded. Here the first copied instance becomes referenced by a +// watch created concurrently (mid-copy), so its DeleteInstance call fails +// with ErrInstanceInUse during rollback; its row and secret must survive +// untouched while the still-cleanly-deletable second instance is fully +// removed. +func TestCopyConfig_RollbackKeepsInUseInstanceIntact(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + const src, dst = "ws-src", "ws-dst" + f.seedInstance(t, src, "First", "sec-first") + f.seedInstance(t, src, "Second", "sec-second") + + injected := errors.New("secret store unavailable") + f.secrets.setErr = injected + f.secrets.setErrAfter = 1 // Let the first copied secret succeed; fail the second. + var ( + watchAttached bool + firstCopiedID string + ) + f.secrets.setHook = func() { + if watchAttached { + return + } + watchAttached = true + targets, err := f.store.ListInstances(ctx, dst) + if err != nil || len(targets) != 1 { + t.Fatalf("expected exactly 1 copied instance before concurrent watch injection, got %d err=%v", len(targets), err) + } + firstCopiedID = targets[0].ID + watch := newTestIssueWatch(dst) + watch.SentryInstanceID = firstCopiedID + if err := f.store.CreateIssueWatch(ctx, watch); err != nil { + t.Fatalf("attach concurrent watch to first copied instance: %v", err) + } + } + + _, err := f.svc.CopyConfigToWorkspace(ctx, src, dst) + if !errors.Is(err, injected) { + t.Fatalf("expected injected secret error, got %v", err) + } + var inUse ErrInstanceInUse + if !errors.As(err, &inUse) { + t.Fatalf("expected joined ErrInstanceInUse from rollback row-delete failure, got %v", err) + } + + target, err := f.svc.ListInstances(ctx, dst) + if err != nil { + t.Fatalf("list target after failed copy: %v", err) + } + if len(target) != 1 || target[0].ID != firstCopiedID { + t.Fatalf("expected only the in-use first copied instance to survive rollback, got %+v", target) + } + if secret, err := f.secrets.Reveal(ctx, secretKeyForInstance(firstCopiedID)); err != nil || secret != "sec-first" { + t.Errorf("expected first copied instance's secret intact after row-delete failure, got secret=%q err=%v", secret, err) + } + if got := f.secrets.count(); got != 3 { + t.Errorf("expected 3 secrets to survive rollback (2 source + first copied instance's), got %d", got) + } +} + +// TestRollbackCopiedInstances_KeepsRowAndSecretIntactAfterRowDeleteFailure pins +// the fix: when a copied instance's row delete fails (e.g. it became +// referenced by a watch created concurrently, tripping ErrInstanceInUse), +// rollback must leave that instance's row AND secret fully intact rather than +// deleting the secret out from under a still-live row. +func TestRollbackCopiedInstances_KeepsRowAndSecretIntactAfterRowDeleteFailure(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + created := f.seedInstance(t, "ws-dst", "Copied", "sec-copied") + watch := newTestIssueWatch("ws-dst") + watch.SentryInstanceID = created.ID + if err := f.store.CreateIssueWatch(ctx, watch); err != nil { + t.Fatalf("seed watch: %v", err) + } + + core, observed := observer.New(zap.WarnLevel) + testLogger, err := logger.NewFromZap(zap.New(core)) + if err != nil { + t.Fatalf("create test logger: %v", err) + } + f.svc.log = testLogger + + cause := errors.New("copy failed") + err = f.svc.rollbackCopiedInstances(ctx, []*SentryConfig{created}, cause) + if !errors.Is(err, cause) { + t.Fatalf("expected original copy error, got %v", err) + } + var inUse ErrInstanceInUse + if !errors.As(err, &inUse) { + t.Fatalf("expected joined row cleanup error, got %v", err) + } + if _, err := f.store.GetInstance(ctx, created.ID); err != nil { + t.Errorf("row deleted despite failed row cleanup: %v", err) + } + if secret, err := f.secrets.Reveal(ctx, secretKeyForInstance(created.ID)); err != nil || secret != "sec-copied" { + t.Errorf("secret not intact after row cleanup failure: secret=%q err=%v", secret, err) + } + entries := observed.All() + if len(entries) != 1 || entries[0].Message != "sentry: copy rollback cleanup failed" { + t.Fatalf("expected one rollback cleanup warning, got %+v", entries) + } +} + +func TestCopyConfig_SourceSecretReadFailureRollsBackAllCreatedInstances(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + const src, dst = "ws-src", "ws-dst" + f.seedInstance(t, src, "First", "sec-first") + second := f.seedInstance(t, src, "Second", "sec-second") + existing := f.seedInstance(t, dst, "Existing", "sec-existing") + + injected := errors.New("source secret unavailable") + f.secrets.revealErr = injected + f.secrets.revealErrForID = secretKeyForInstance(second.ID) + if _, err := f.svc.CopyConfigToWorkspace(ctx, src, dst); !errors.Is(err, injected) { + t.Fatalf("expected injected source secret error, got %v", err) + } + + target, err := f.svc.ListInstances(ctx, dst) + if err != nil { + t.Fatalf("list target after failed copy: %v", err) + } + if len(target) != 1 || target[0].ID != existing.ID { + t.Fatalf("failed copy changed target instances: %+v", target) + } + if got := f.secrets.count(); got != 3 { + t.Errorf("failed copy left copied secrets: count=%d, want 3", got) + } +} + +func TestCopyConfig_SourceSecretReadFailurePrecedesTargetMutations(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + const src, dst = "ws-src", "ws-dst" + f.seedInstance(t, src, "First", "sec-first") + second := f.seedInstance(t, src, "Second", "sec-second") + existing := f.seedInstance(t, dst, "Existing", "sec-existing") + + sourceReadErr := errors.New("source secret unavailable") + targetSetErr := errors.New("target secret should not be stored") + f.secrets.revealErr = sourceReadErr + f.secrets.revealErrForID = secretKeyForInstance(second.ID) + f.secrets.setErr = targetSetErr + _, err := f.svc.CopyConfigToWorkspace(ctx, src, dst) + if !errors.Is(err, sourceReadErr) { + t.Fatalf("expected source read error before target mutation, got %v", err) + } + if errors.Is(err, targetSetErr) { + t.Fatalf("copy attempted target secret storage before reading all sources: %v", err) + } + + target, err := f.svc.ListInstances(ctx, dst) + if err != nil { + t.Fatalf("list target after failed source preflight: %v", err) + } + if len(target) != 1 || target[0].ID != existing.ID { + t.Fatalf("source preflight changed target instances: %+v", target) + } +} + +// TestCopyConfig_DedupNamesWithInUseTarget pins acceptance (i): copying into a +// target that already holds an instance (referenced by a watch) appends a +// name-deduped copy and leaves the target's existing instance + watch intact. +func TestCopyConfig_DedupNamesWithInUseTarget(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + const src, dst = "ws-src", "ws-dst" + f.seedInstance(t, src, "SaaS", "sec-src") + targetExisting := f.seedInstance(t, dst, "SaaS", "sec-dst") + // Target instance is in use by a watch. + w := newTestIssueWatch(dst) + w.SentryInstanceID = targetExisting.ID + if err := f.store.CreateIssueWatch(ctx, w); err != nil { + t.Fatalf("seed target watch: %v", err) + } + + copied, err := f.svc.CopyConfigToWorkspace(ctx, src, dst) + if err != nil { + t.Fatalf("copy: %v", err) + } + if len(copied) != 1 || copied[0].Name != "SaaS (2)" { + t.Fatalf("expected one deduped copy 'SaaS (2)', got %+v", copied) + } + // Target now has both instances; the original + its watch survive. + all, _ := f.svc.ListInstances(ctx, dst) + if len(all) != 2 { + t.Fatalf("expected 2 instances in target, got %d", len(all)) + } + if n, _ := f.store.CountWatchesForInstance(ctx, targetExisting.ID); n != 1 { + t.Errorf("expected target's existing watch untouched, got count %d", n) + } +} + +func TestCopyConfig_SameWorkspace(t *testing.T) { f := newSvcFixture(t) if _, err := f.svc.CopyConfigToWorkspace(context.Background(), "ws-1", "ws-1"); !errors.Is(err, ErrSameWorkspace) { t.Fatalf("expected ErrSameWorkspace, got %v", err) } } -func TestCopyConfigToWorkspace_NothingToCopy(t *testing.T) { +func TestCopyConfig_NothingToCopy(t *testing.T) { f := newSvcFixture(t) if _, err := f.svc.CopyConfigToWorkspace(context.Background(), "ws-empty", "ws-dst"); !errors.Is(err, ErrNothingToCopy) { t.Fatalf("expected ErrNothingToCopy, got %v", err) diff --git a/apps/backend/internal/sentry/handlers.go b/apps/backend/internal/sentry/handlers.go index 1728c54dde..a5ddc283b3 100644 --- a/apps/backend/internal/sentry/handlers.go +++ b/apps/backend/internal/sentry/handlers.go @@ -13,8 +13,8 @@ import ( ) // RegisterRoutes wires the Sentry HTTP handlers. The dispatcher parameter is -// accepted for signature parity with other integrations; Phase 1 has no -// WebSocket surface, so it is intentionally unused. +// accepted for signature parity with other integrations; there is no WebSocket +// surface, so it is intentionally unused. func RegisterRoutes(router *gin.Engine, _ *ws.Dispatcher, svc *Service, log *logger.Logger) { ctrl := &Controller{service: svc, logger: log} ctrl.RegisterHTTPRoutes(router) @@ -26,13 +26,18 @@ type Controller struct { logger *logger.Logger } -// RegisterHTTPRoutes attaches the Sentry HTTP endpoints to router. +// RegisterHTTPRoutes attaches the Sentry HTTP endpoints to router. Every route +// is scoped to an authoritative `?workspace_id=` query param; instance routes +// additionally 404 when the instance does not belong to that workspace. func (c *Controller) RegisterHTTPRoutes(router *gin.Engine) { api := router.Group("/api/v1/sentry") - api.GET("/config", c.httpGetConfig) - api.PUT("/config", c.httpSetConfig) - api.DELETE("/config", c.httpDeleteConfig) - api.POST("/config/test", c.httpTestConfig) + api.GET("/instances", c.httpListInstances) + api.POST("/instances", c.httpCreateInstance) + api.GET("/instances/:id", c.httpGetInstance) + api.PUT("/instances/:id", c.httpUpdateInstance) + api.DELETE("/instances/:id", c.httpDeleteInstance) + api.POST("/instances/:id/test", c.httpTestInstance) + api.POST("/test-connection", c.httpTestConnection) api.POST("/config/copy", c.httpCopyConfig) api.GET("/organizations", c.httpListOrganizations) api.GET("/projects", c.httpListProjects) @@ -41,88 +46,176 @@ func (c *Controller) RegisterHTTPRoutes(router *gin.Engine) { c.registerIssueWatchRoutes(api) } -func (c *Controller) httpGetConfig(ctx *gin.Context) { - cfg, err := c.service.GetConfigForWorkspace(ctx.Request.Context(), c.workspaceID(ctx)) +func (c *Controller) httpListInstances(ctx *gin.Context) { + workspaceID, ok := c.requireWorkspace(ctx) + if !ok { + return + } + instances, err := c.service.ListInstances(ctx.Request.Context(), workspaceID) if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + writeErr(ctx, http.StatusInternalServerError, err.Error()) return } - if cfg == nil { - ctx.Status(http.StatusNoContent) - return - } - ctx.JSON(http.StatusOK, cfg) + ctx.JSON(http.StatusOK, gin.H{"instances": instances}) } -func (c *Controller) httpSetConfig(ctx *gin.Context) { - var req SetConfigRequest +func (c *Controller) httpCreateInstance(ctx *gin.Context) { + workspaceID, ok := c.requireWorkspace(ctx) + if !ok { + return + } + var req CreateConfigRequest if err := ctx.ShouldBindJSON(&req); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) + writeBadPayload(ctx) return } - cfg, err := c.service.SetConfigForWorkspace(ctx.Request.Context(), c.workspaceID(ctx), &req) + if strings.TrimSpace(req.WorkspaceID) != "" && req.WorkspaceID != workspaceID { + writeErr(ctx, http.StatusBadRequest, "workspaceId does not match workspace_id query") + return + } + cfg, err := c.service.CreateInstance(ctx.Request.Context(), workspaceID, &req) if err != nil { - status := http.StatusInternalServerError - if errors.Is(err, ErrInvalidConfig) { - status = http.StatusBadRequest - } - ctx.JSON(status, gin.H{"error": err.Error()}) + c.writeInstanceError(ctx, err) return } ctx.JSON(http.StatusOK, cfg) } -func (c *Controller) httpDeleteConfig(ctx *gin.Context) { - if err := c.service.DeleteConfigForWorkspace(ctx.Request.Context(), c.workspaceID(ctx)); err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) +func (c *Controller) httpGetInstance(ctx *gin.Context) { + workspaceID, ok := c.requireWorkspace(ctx) + if !ok { + return + } + cfg, err := c.service.GetInstance(ctx.Request.Context(), workspaceID, ctx.Param("id")) + if err != nil { + c.writeInstanceError(ctx, err) + return + } + ctx.JSON(http.StatusOK, cfg) +} + +func (c *Controller) httpUpdateInstance(ctx *gin.Context) { + workspaceID, ok := c.requireWorkspace(ctx) + if !ok { + return + } + var req UpdateConfigRequest + if err := ctx.ShouldBindJSON(&req); err != nil { + writeBadPayload(ctx) + return + } + cfg, err := c.service.UpdateInstance(ctx.Request.Context(), workspaceID, ctx.Param("id"), &req) + if err != nil { + c.writeInstanceError(ctx, err) + return + } + ctx.JSON(http.StatusOK, cfg) +} + +func (c *Controller) httpDeleteInstance(ctx *gin.Context) { + workspaceID, ok := c.requireWorkspace(ctx) + if !ok { + return + } + if err := c.service.DeleteInstance(ctx.Request.Context(), workspaceID, ctx.Param("id")); err != nil { + c.writeInstanceError(ctx, err) return } ctx.JSON(http.StatusOK, gin.H{"deleted": true}) } -func (c *Controller) httpTestConfig(ctx *gin.Context) { - var req SetConfigRequest - if err := ctx.ShouldBindJSON(&req); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) +func (c *Controller) httpTestInstance(ctx *gin.Context) { + workspaceID, ok := c.requireWorkspace(ctx) + if !ok { return } - result, err := c.service.TestConnectionForWorkspace(ctx.Request.Context(), c.workspaceID(ctx), &req) + result, err := c.service.TestInstance(ctx.Request.Context(), workspaceID, ctx.Param("id")) if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + c.writeInstanceError(ctx, err) return } ctx.JSON(http.StatusOK, result) } -func (c *Controller) httpListOrganizations(ctx *gin.Context) { - client, err := c.service.clientFor(ctx.Request.Context(), c.workspaceID(ctx)) - if err != nil { - c.writeClientError(ctx, err) +func (c *Controller) httpTestConnection(ctx *gin.Context) { + if _, ok := c.requireWorkspace(ctx); !ok { return } - organizations, err := client.ListOrganizations(ctx.Request.Context()) + var req CreateConfigRequest + if err := ctx.ShouldBindJSON(&req); err != nil { + writeBadPayload(ctx) + return + } + result, err := c.service.TestConnectionCandidate(ctx.Request.Context(), &req) if err != nil { - c.writeClientError(ctx, err) + writeErr(ctx, http.StatusInternalServerError, err.Error()) + return + } + ctx.JSON(http.StatusOK, result) +} + +func (c *Controller) httpCopyConfig(ctx *gin.Context) { + source, ok := c.requireWorkspace(ctx) + if !ok { + return + } + var req CopyConfigRequest + if err := ctx.ShouldBindJSON(&req); err != nil { + writeBadPayload(ctx) + return + } + target := strings.TrimSpace(req.TargetWorkspaceID) + if target == "" { + writeErr(ctx, http.StatusBadRequest, "targetWorkspaceId is required") + return + } + copied, err := c.service.CopyConfigToWorkspace(ctx.Request.Context(), source, target) + if err != nil { + status := http.StatusInternalServerError + switch { + case errors.Is(err, ErrSameWorkspace), errors.Is(err, ErrNothingToCopy), errors.Is(err, ErrInvalidConfig): + status = http.StatusBadRequest + case errors.Is(err, ErrDuplicateInstanceName): + writeCoded(ctx, http.StatusConflict, err.Error(), errCodeSentryInstanceNameTaken) + return + } + writeErr(ctx, status, err.Error()) + return + } + ctx.JSON(http.StatusOK, gin.H{"instances": copied}) +} + +func (c *Controller) httpListOrganizations(ctx *gin.Context) { + workspaceID, ok := c.requireWorkspace(ctx) + if !ok { + return + } + organizations, err := c.service.ListOrganizations(ctx.Request.Context(), workspaceID, c.instanceID(ctx)) + if err != nil { + c.writeInstanceError(ctx, err) return } ctx.JSON(http.StatusOK, gin.H{"organizations": organizations}) } func (c *Controller) httpListProjects(ctx *gin.Context) { - client, err := c.service.clientFor(ctx.Request.Context(), c.workspaceID(ctx)) - if err != nil { - c.writeClientError(ctx, err) + workspaceID, ok := c.requireWorkspace(ctx) + if !ok { return } - projects, err := client.ListProjects(ctx.Request.Context()) + projects, err := c.service.ListProjects(ctx.Request.Context(), workspaceID, c.instanceID(ctx)) if err != nil { - c.writeClientError(ctx, err) + c.writeInstanceError(ctx, err) return } ctx.JSON(http.StatusOK, gin.H{"projects": projects}) } func (c *Controller) httpSearchIssues(ctx *gin.Context) { + workspaceID, ok := c.requireWorkspace(ctx) + if !ok { + return + } q := ctx.Request.URL.Query() filter := SearchFilter{ OrgSlug: q.Get("orgSlug"), @@ -133,80 +226,106 @@ func (c *Controller) httpSearchIssues(ctx *gin.Context) { Levels: trimAll(q["level"]), Statuses: trimAll(q["status"]), } - cursor := q.Get("cursor") - result, err := c.service.SearchIssuesForWorkspace(ctx.Request.Context(), c.workspaceID(ctx), filter, cursor) + result, err := c.service.SearchIssues(ctx.Request.Context(), workspaceID, c.instanceID(ctx), filter, q.Get("cursor")) if err != nil { - c.writeClientError(ctx, err) + c.writeInstanceError(ctx, err) return } ctx.JSON(http.StatusOK, result) } func (c *Controller) httpGetIssue(ctx *gin.Context) { - id := ctx.Param("id") - client, err := c.service.clientFor(ctx.Request.Context(), c.workspaceID(ctx)) - if err != nil { - c.writeClientError(ctx, err) + workspaceID, ok := c.requireWorkspace(ctx) + if !ok { return } - issue, err := client.GetIssue(ctx.Request.Context(), id) + issue, err := c.service.GetIssue(ctx.Request.Context(), workspaceID, c.instanceID(ctx), ctx.Param("id")) if err != nil { - c.writeClientError(ctx, err) + c.writeInstanceError(ctx, err) return } ctx.JSON(http.StatusOK, issue) } -func (c *Controller) workspaceID(ctx *gin.Context) string { - return strings.TrimSpace(ctx.Query("workspace_id")) +// requireWorkspace reads the authoritative `?workspace_id=` query param, +// writing a 400 and returning false when it is absent. +func (c *Controller) requireWorkspace(ctx *gin.Context) (string, bool) { + workspaceID := strings.TrimSpace(ctx.Query("workspace_id")) + if workspaceID == "" { + writeErr(ctx, http.StatusBadRequest, "workspace_id query parameter required") + return "", false + } + return workspaceID, true } -// copyConfigRequest is the payload for the copy-config endpoint. The source -// workspace comes from the workspace_id query param; the body carries the -// target. -type copyConfigRequest struct { - TargetWorkspaceID string `json:"targetWorkspaceId"` +func (c *Controller) instanceID(ctx *gin.Context) string { + return strings.TrimSpace(ctx.Query("instanceId")) } -func (c *Controller) httpCopyConfig(ctx *gin.Context) { - sourceWorkspaceID := c.workspaceID(ctx) - if sourceWorkspaceID == "" { - ctx.JSON(http.StatusBadRequest, gin.H{"error": "workspace_id query parameter required"}) - return - } - var req copyConfigRequest - if err := ctx.ShouldBindJSON(&req); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) - return - } - targetWorkspaceID := strings.TrimSpace(req.TargetWorkspaceID) - if targetWorkspaceID == "" { - ctx.JSON(http.StatusBadRequest, gin.H{"error": "targetWorkspaceId required"}) - return - } - cfg, err := c.service.CopyConfigToWorkspace(ctx.Request.Context(), sourceWorkspaceID, targetWorkspaceID) - if err != nil { - status := http.StatusInternalServerError - switch { - case errors.Is(err, ErrSameWorkspace), errors.Is(err, ErrNothingToCopy), errors.Is(err, ErrInvalidConfig): - status = http.StatusBadRequest - } - ctx.JSON(status, gin.H{"error": err.Error()}) - return - } - ctx.JSON(http.StatusOK, cfg) +// Wire-level error codes surfaced to the UI. +const ( + errCodeSentryNotConfigured = "SENTRY_NOT_CONFIGURED" + errCodeSentryInstanceRequired = "SENTRY_INSTANCE_REQUIRED" + errCodeSentryInstanceNotFound = "SENTRY_INSTANCE_NOT_FOUND" + errCodeSentryInstanceInUse = "SENTRY_INSTANCE_IN_USE" + errCodeSentryInstanceNameTaken = "SENTRY_INSTANCE_NAME_TAKEN" +) + +// Repeated gin.H keys / messages, centralized to satisfy goconst. +const ( + jsonKeyError = "error" + jsonKeyCode = "code" + badPayloadMsg = "invalid payload" +) + +// writeErr responds with a bare error message at the given status. +func writeErr(ctx *gin.Context, status int, msg string) { + ctx.JSON(status, gin.H{jsonKeyError: msg}) } -// errCodeSentryNotConfigured is the wire-level code surfaced to the UI when -// Sentry has no saved credentials. -const errCodeSentryNotConfigured = "SENTRY_NOT_CONFIGURED" +// writeBadPayload responds with a 400 for an unparseable JSON body. +func writeBadPayload(ctx *gin.Context) { + writeErr(ctx, http.StatusBadRequest, badPayloadMsg) +} + +// writeCoded responds with an error message + wire code at the given status. +func writeCoded(ctx *gin.Context, status int, msg, code string) { + ctx.JSON(status, gin.H{jsonKeyError: msg, jsonKeyCode: code}) +} + +// writeInstanceError maps the instance-scoped service errors onto HTTP status +// codes + wire codes, falling back to writeClientError for connection/API +// errors (ErrNotConfigured, APIError, generic). +func (c *Controller) writeInstanceError(ctx *gin.Context, err error) { + switch { + case errors.Is(err, ErrInstanceRequired): + writeCoded(ctx, http.StatusBadRequest, err.Error(), errCodeSentryInstanceRequired) + return + case errors.Is(err, ErrInstanceNotFound): + writeCoded(ctx, http.StatusNotFound, err.Error(), errCodeSentryInstanceNotFound) + return + case errors.Is(err, ErrDuplicateInstanceName): + writeCoded(ctx, http.StatusConflict, err.Error(), errCodeSentryInstanceNameTaken) + return + case errors.Is(err, ErrInvalidConfig): + writeErr(ctx, http.StatusBadRequest, err.Error()) + return + } + var inUse ErrInstanceInUse + if errors.As(err, &inUse) { + ctx.JSON(http.StatusConflict, gin.H{ + jsonKeyError: inUse.Error(), + jsonKeyCode: errCodeSentryInstanceInUse, + "watchCount": inUse.WatchCount, + }) + return + } + c.writeClientError(ctx, err) +} func (c *Controller) writeClientError(ctx *gin.Context, err error) { if errors.Is(err, ErrNotConfigured) { - ctx.JSON(http.StatusServiceUnavailable, gin.H{ - "error": "Sentry is not configured", - "code": errCodeSentryNotConfigured, - }) + writeCoded(ctx, http.StatusServiceUnavailable, "Sentry is not configured", errCodeSentryNotConfigured) return } var apiErr *APIError @@ -216,11 +335,11 @@ func (c *Controller) writeClientError(ctx *gin.Context, err error) { case http.StatusNotFound, http.StatusUnauthorized, http.StatusForbidden, http.StatusBadRequest: status = apiErr.StatusCode } - ctx.JSON(status, gin.H{"error": apiErr.Error()}) + writeErr(ctx, status, apiErr.Error()) return } c.logger.Warn("sentry handler error", zap.Error(err)) - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + writeErr(ctx, http.StatusInternalServerError, err.Error()) } func trimAll(xs []string) []string { diff --git a/apps/backend/internal/sentry/handlers_issue_watch.go b/apps/backend/internal/sentry/handlers_issue_watch.go index 53fea34989..7d73bf2d6c 100644 --- a/apps/backend/internal/sentry/handlers_issue_watch.go +++ b/apps/backend/internal/sentry/handlers_issue_watch.go @@ -35,7 +35,7 @@ func (c *Controller) httpListIssueWatches(ctx *gin.Context) { watches, err = c.service.ListIssueWatches(ctx.Request.Context(), workspaceID) } if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + writeErr(ctx, http.StatusInternalServerError, err.Error()) return } ctx.JSON(http.StatusOK, gin.H{"watches": watches}) @@ -44,7 +44,11 @@ func (c *Controller) httpListIssueWatches(ctx *gin.Context) { func (c *Controller) httpCreateIssueWatch(ctx *gin.Context) { var req CreateIssueWatchRequest if err := ctx.ShouldBindJSON(&req); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) + writeBadPayload(ctx) + return + } + if !workspaceMatches(ctx, req.WorkspaceID) { + writeErr(ctx, http.StatusBadRequest, "workspace_id query must match body workspaceId") return } w, err := c.service.CreateIssueWatch(ctx.Request.Context(), &req) @@ -63,7 +67,7 @@ func (c *Controller) httpGetIssueWatch(ctx *gin.Context) { return } if !workspaceMatches(ctx, w.WorkspaceID) { - ctx.JSON(http.StatusNotFound, gin.H{"error": ErrIssueWatchNotFound.Error()}) + writeErr(ctx, http.StatusNotFound, ErrIssueWatchNotFound.Error()) return } ctx.JSON(http.StatusOK, w) @@ -76,7 +80,7 @@ func (c *Controller) httpUpdateIssueWatch(ctx *gin.Context) { } var req UpdateIssueWatchRequest if err := ctx.ShouldBindJSON(&req); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) + writeBadPayload(ctx) return } w, err := c.service.UpdateIssueWatch(ctx.Request.Context(), id, &req) @@ -93,7 +97,7 @@ func (c *Controller) httpDeleteIssueWatch(ctx *gin.Context) { return } if err := c.service.DeleteIssueWatch(ctx.Request.Context(), id); err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + writeErr(ctx, http.StatusInternalServerError, err.Error()) return } ctx.JSON(http.StatusOK, gin.H{"deleted": true}) @@ -111,16 +115,16 @@ func (c *Controller) httpTriggerIssueWatch(ctx *gin.Context) { return } if !workspaceMatches(ctx, w.WorkspaceID) { - ctx.JSON(http.StatusNotFound, gin.H{"error": ErrIssueWatchNotFound.Error()}) + writeErr(ctx, http.StatusNotFound, ErrIssueWatchNotFound.Error()) return } - issues, err := c.service.CheckIssueWatch(ctx.Request.Context(), w) + instanceID, issues, err := c.service.CheckIssueWatch(ctx.Request.Context(), w) if err != nil { - c.writeClientError(ctx, err) + c.writeIssueWatchError(ctx, err) return } for _, issue := range issues { - c.service.publishNewSentryIssueEvent(ctx.Request.Context(), w, issue) + c.service.publishNewSentryIssueEvent(ctx.Request.Context(), w, instanceID, issue) } ctx.JSON(http.StatusOK, gin.H{"published": len(issues)}) } @@ -168,7 +172,7 @@ func (c *Controller) assertWatchInWorkspace(ctx *gin.Context, id string) bool { return false } if !workspaceMatches(ctx, w.WorkspaceID) { - ctx.JSON(http.StatusNotFound, gin.H{"error": ErrIssueWatchNotFound.Error()}) + writeErr(ctx, http.StatusNotFound, ErrIssueWatchNotFound.Error()) return false } return true @@ -184,11 +188,19 @@ func workspaceMatches(ctx *gin.Context, resourceWorkspace string) bool { func (c *Controller) writeIssueWatchError(ctx *gin.Context, err error) { if errors.Is(err, ErrIssueWatchNotFound) { - ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) + writeErr(ctx, http.StatusNotFound, err.Error()) + return + } + if errors.Is(err, ErrInstanceNotFound) { + writeCoded(ctx, http.StatusNotFound, err.Error(), errCodeSentryInstanceNotFound) + return + } + if errors.Is(err, ErrInstanceRequired) { + writeCoded(ctx, http.StatusBadRequest, err.Error(), errCodeSentryInstanceRequired) return } if errors.Is(err, ErrInvalidConfig) { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + writeErr(ctx, http.StatusBadRequest, err.Error()) return } c.writeClientError(ctx, err) diff --git a/apps/backend/internal/sentry/handlers_test.go b/apps/backend/internal/sentry/handlers_test.go index fa3d44bbcc..90930db856 100644 --- a/apps/backend/internal/sentry/handlers_test.go +++ b/apps/backend/internal/sentry/handlers_test.go @@ -8,6 +8,7 @@ import ( "net/http/httptest" "strings" "testing" + "time" "github.com/gin-gonic/gin" @@ -30,63 +31,209 @@ func newTestController(t *testing.T) (*Controller, *gin.Engine, *fakeClient) { return ctrl, router, client } -// seedConfig persists a singleton config + secret without going through -// Service.SetConfig (which fires an async probe we'd have to drain). -func seedConfig(t *testing.T, ctrl *Controller) { +// seedInstance persists an instance (+ optional secret) directly via the store. +func seedInstance(t *testing.T, ctrl *Controller, workspaceID, name, secret string) *SentryConfig { t.Helper() ctx := context.Background() - if err := ctrl.service.store.UpsertConfig(ctx, &SentryConfig{ - AuthMethod: AuthMethodAuthToken, - }); err != nil { - t.Fatalf("upsert: %v", err) + cfg := &SentryConfig{WorkspaceID: workspaceID, Name: name, AuthMethod: AuthMethodAuthToken, URL: DefaultSentryURL} + if err := ctrl.service.store.CreateInstance(ctx, cfg); err != nil { + t.Fatalf("seed instance: %v", err) } - if err := ctrl.service.secrets.Set(ctx, SecretKey, "sentry", "tok"); err != nil { - t.Fatalf("set secret: %v", err) + if secret != "" { + if err := ctrl.service.secrets.Set(ctx, secretKeyForInstance(cfg.ID), "sentry", secret); err != nil { + t.Fatalf("seed secret: %v", err) + } } + return cfg } -func TestHTTPGetConfig_NoConfig_Returns204(t *testing.T) { +func do(router *gin.Engine, method, target, body string) *httptest.ResponseRecorder { + var r *http.Request + if body == "" { + r = httptest.NewRequest(method, target, nil) + } else { + r = httptest.NewRequest(method, target, strings.NewReader(body)) + r.Header.Set("Content-Type", "application/json") + } + w := httptest.NewRecorder() + router.ServeHTTP(w, r) + return w +} + +func TestHTTP_ListInstances_RequiresWorkspace(t *testing.T) { _, router, _ := newTestController(t) - req := httptest.NewRequest(http.MethodGet, "/api/v1/sentry/config", nil) - w := httptest.NewRecorder() - router.ServeHTTP(w, req) - if w.Code != http.StatusNoContent { - t.Errorf("status = %d, want 204", w.Code) + if w := do(router, http.MethodGet, "/api/v1/sentry/instances", ""); w.Code != http.StatusBadRequest { + t.Errorf("expected 400 without workspace_id, got %d", w.Code) } } -func TestHTTPGetConfig_ReturnsConfig(t *testing.T) { +func TestHTTP_ListInstances_Wrapped(t *testing.T) { ctrl, router, _ := newTestController(t) - seedConfig(t, ctrl) - req := httptest.NewRequest(http.MethodGet, "/api/v1/sentry/config", nil) - w := httptest.NewRecorder() - router.ServeHTTP(w, req) + seedInstance(t, ctrl, "ws-1", "A", "tok") + seedInstance(t, ctrl, "ws-2", "B", "tok") + w := do(router, http.MethodGet, "/api/v1/sentry/instances?workspace_id=ws-1", "") if w.Code != http.StatusOK { - t.Errorf("status = %d, want 200", w.Code) + t.Fatalf("status = %d, body=%s", w.Code, w.Body.String()) + } + var resp struct { + Instances []SentryConfig `json:"instances"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v", err) + } + if len(resp.Instances) != 1 || resp.Instances[0].Name != "A" { + t.Errorf("expected only ws-1's instance, got %+v", resp.Instances) + } +} + +func TestHTTP_CreateInstance_MismatchedWorkspaceRejected(t *testing.T) { + _, router, _ := newTestController(t) + // Body workspaceId mismatches the query → 400 (acceptance e). + body := `{"workspaceId":"ws-2","name":"A","secret":"t"}` + if w := do(router, http.MethodPost, "/api/v1/sentry/instances?workspace_id=ws-1", body); w.Code != http.StatusBadRequest { + t.Errorf("expected 400 for mismatched workspaceId, got %d body=%s", w.Code, w.Body.String()) + } + // Missing workspace_id query → 400. + if w := do(router, http.MethodPost, "/api/v1/sentry/instances", `{"name":"A"}`); w.Code != http.StatusBadRequest { + t.Errorf("expected 400 without workspace_id, got %d", w.Code) + } +} + +func TestHTTP_CreateInstance_OK(t *testing.T) { + ctrl, router, _ := newTestController(t) + probed := make(chan struct{}, 4) + ctrl.service.SetProbeHook(func() { + select { + case probed <- struct{}{}: + default: + } + }) + w := do(router, http.MethodPost, "/api/v1/sentry/instances?workspace_id=ws-1", + `{"workspaceId":"ws-1","name":"SaaS","secret":"tok"}`) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body=%s", w.Code, w.Body.String()) } var cfg SentryConfig if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil { t.Fatalf("decode: %v", err) } - if cfg.AuthMethod != AuthMethodAuthToken || !cfg.HasSecret { - t.Errorf("config = %+v", cfg) + if cfg.ID == "" || cfg.Name != "SaaS" || !cfg.HasSecret { + t.Errorf("unexpected created instance: %+v", cfg) + } + select { + case <-probed: + case <-time.After(2 * time.Second): + t.Fatal("async probe did not fire") } } -func TestHTTPSearchIssues_MultiValueLevelsAndStatuses(t *testing.T) { +func TestHTTP_CreateInstance_BadJSON(t *testing.T) { + _, router, _ := newTestController(t) + if w := do(router, http.MethodPost, "/api/v1/sentry/instances?workspace_id=ws-1", "not-json"); w.Code != http.StatusBadRequest { + t.Errorf("status = %d, want 400", w.Code) + } +} + +func TestHTTP_GetInstance_CrossWorkspace404(t *testing.T) { + ctrl, router, _ := newTestController(t) + inst := seedInstance(t, ctrl, "ws-1", "A", "tok") + w := do(router, http.MethodGet, "/api/v1/sentry/instances/"+inst.ID+"?workspace_id=ws-2", "") + if w.Code != http.StatusNotFound { + t.Fatalf("expected 404 cross-workspace, got %d", w.Code) + } + if !strings.Contains(w.Body.String(), `"code":"SENTRY_INSTANCE_NOT_FOUND"`) { + t.Errorf("missing code in body: %s", w.Body.String()) + } +} + +func TestHTTP_UpdateInstance_UpdatesAndRejectsCrossWorkspace(t *testing.T) { + ctrl, router, _ := newTestController(t) + inst := seedInstance(t, ctrl, "ws-1", "Original", "tok") + body := `{"name":"Renamed","authMethod":"auth_token","url":"https://sentry.example.com"}` + + updated := do(router, http.MethodPut, "/api/v1/sentry/instances/"+inst.ID+"?workspace_id=ws-1", body) + if updated.Code != http.StatusOK { + t.Fatalf("update status = %d, body=%s", updated.Code, updated.Body.String()) + } + var cfg SentryConfig + if err := json.Unmarshal(updated.Body.Bytes(), &cfg); err != nil { + t.Fatalf("decode update: %v", err) + } + if cfg.Name != "Renamed" || cfg.URL != "https://sentry.example.com" { + t.Errorf("updated instance = %+v", cfg) + } + + crossWorkspace := do(router, http.MethodPut, "/api/v1/sentry/instances/"+inst.ID+"?workspace_id=ws-2", body) + if crossWorkspace.Code != http.StatusNotFound { + t.Fatalf("cross-workspace update status = %d, want 404; body=%s", crossWorkspace.Code, crossWorkspace.Body.String()) + } + if !strings.Contains(crossWorkspace.Body.String(), `"code":"SENTRY_INSTANCE_NOT_FOUND"`) { + t.Errorf("missing cross-workspace not-found code: %s", crossWorkspace.Body.String()) + } +} + +func TestHTTP_DeleteInstance_InUse409(t *testing.T) { + ctrl, router, _ := newTestController(t) + inst := seedInstance(t, ctrl, "ws-1", "A", "tok") + w := newTestIssueWatch("ws-1") + w.SentryInstanceID = inst.ID + if err := ctrl.service.store.CreateIssueWatch(context.Background(), w); err != nil { + t.Fatalf("seed watch: %v", err) + } + resp := do(router, http.MethodDelete, "/api/v1/sentry/instances/"+inst.ID+"?workspace_id=ws-1", "") + if resp.Code != http.StatusConflict { + t.Fatalf("expected 409, got %d body=%s", resp.Code, resp.Body.String()) + } + var body struct { + Code string `json:"code"` + WatchCount int `json:"watchCount"` + } + if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil { + t.Fatalf("decode: %v", err) + } + if body.Code != "SENTRY_INSTANCE_IN_USE" || body.WatchCount != 1 { + t.Errorf("unexpected 409 body: %+v", body) + } +} + +func TestHTTP_Browse_RequiresWorkspaceAndInstance(t *testing.T) { + ctrl, router, _ := newTestController(t) + seedInstance(t, ctrl, "ws-1", "A", "tok") + // Missing workspace_id → 400. + if w := do(router, http.MethodGet, "/api/v1/sentry/projects", ""); w.Code != http.StatusBadRequest { + t.Errorf("expected 400 without workspace_id, got %d", w.Code) + } + // Missing instanceId → 400 SENTRY_INSTANCE_REQUIRED. + w := do(router, http.MethodGet, "/api/v1/sentry/projects?workspace_id=ws-1", "") + if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), `"code":"SENTRY_INSTANCE_REQUIRED"`) { + t.Errorf("expected 400 SENTRY_INSTANCE_REQUIRED, got %d body=%s", w.Code, w.Body.String()) + } +} + +func TestHTTP_Browse_NotConfigured503(t *testing.T) { + ctrl, router, _ := newTestController(t) + // Instance with no secret → 503 SENTRY_NOT_CONFIGURED. + inst := seedInstance(t, ctrl, "ws-1", "A", "") + w := do(router, http.MethodGet, "/api/v1/sentry/projects?workspace_id=ws-1&instanceId="+inst.ID, "") + if w.Code != http.StatusServiceUnavailable { + t.Fatalf("expected 503, got %d body=%s", w.Code, w.Body.String()) + } + if !strings.Contains(w.Body.String(), `"code":"SENTRY_NOT_CONFIGURED"`) { + t.Errorf("missing code in body: %s", w.Body.String()) + } +} + +func TestHTTP_SearchIssues_ForwardsFilter(t *testing.T) { ctrl, router, client := newTestController(t) - seedConfig(t, ctrl) + inst := seedInstance(t, ctrl, "ws-1", "A", "tok") var seen SearchFilter client.searchIssuesFn = func(filter SearchFilter, _ string) (*SearchResult, error) { seen = filter return &SearchResult{IsLast: true}, nil } - req := httptest.NewRequest(http.MethodGet, - "/api/v1/sentry/issues?orgSlug=acme&projectSlug=fe&level=error&level=fatal&status=unresolved&query=boom&statsPeriod=24h", - nil) - w := httptest.NewRecorder() - router.ServeHTTP(w, req) - if w.Code != http.StatusOK { + target := "/api/v1/sentry/issues?workspace_id=ws-1&instanceId=" + inst.ID + + "&orgSlug=acme&projectSlug=fe&level=error&level=fatal&status=unresolved&query=boom&statsPeriod=24h" + if w := do(router, http.MethodGet, target, ""); w.Code != http.StatusOK { t.Fatalf("status = %d, body=%s", w.Code, w.Body.String()) } if seen.OrgSlug != "acme" || seen.ProjectSlug != "fe" || seen.Query != "boom" || seen.StatsPeriod != "24h" { @@ -100,47 +247,30 @@ func TestHTTPSearchIssues_MultiValueLevelsAndStatuses(t *testing.T) { } } -func TestHTTPGetIssue_ForwardsID(t *testing.T) { +func TestHTTP_GetIssue_ForwardsID(t *testing.T) { ctrl, router, client := newTestController(t) - seedConfig(t, ctrl) + inst := seedInstance(t, ctrl, "ws-1", "A", "tok") var seenID string client.getIssueFn = func(id string) (*SentryIssue, error) { seenID = id return &SentryIssue{ID: "99", ShortID: id}, nil } - req := httptest.NewRequest(http.MethodGet, "/api/v1/sentry/issues/PROJ-7", nil) - w := httptest.NewRecorder() - router.ServeHTTP(w, req) - if w.Code != http.StatusOK { - t.Errorf("status = %d", w.Code) + target := "/api/v1/sentry/issues/PROJ-7?workspace_id=ws-1&instanceId=" + inst.ID + if w := do(router, http.MethodGet, target, ""); w.Code != http.StatusOK { + t.Fatalf("status = %d", w.Code) } if seenID != "PROJ-7" { t.Errorf("id forwarded = %q", seenID) } } -func TestHTTPListProjects_NotConfigured_Returns503(t *testing.T) { - _, router, _ := newTestController(t) - req := httptest.NewRequest(http.MethodGet, "/api/v1/sentry/projects", nil) - w := httptest.NewRecorder() - router.ServeHTTP(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("status = %d, want 503", w.Code) - } - if !strings.Contains(w.Body.String(), `"code":"SENTRY_NOT_CONFIGURED"`) { - t.Errorf("missing code in body: %s", w.Body.String()) - } -} - -func TestHTTPListOrganizations_ReturnsOrganizations(t *testing.T) { +func TestHTTP_ListOrganizations_ReturnsWrapped(t *testing.T) { ctrl, router, client := newTestController(t) - seedConfig(t, ctrl) + inst := seedInstance(t, ctrl, "ws-1", "A", "tok") client.listOrganizationsFn = func() ([]SentryOrganization, error) { return []SentryOrganization{{ID: "1", Slug: "acme", Name: "Acme"}}, nil } - req := httptest.NewRequest(http.MethodGet, "/api/v1/sentry/organizations", nil) - w := httptest.NewRecorder() - router.ServeHTTP(w, req) + w := do(router, http.MethodGet, "/api/v1/sentry/organizations?workspace_id=ws-1&instanceId="+inst.ID, "") if w.Code != http.StatusOK { t.Fatalf("status = %d, body=%s", w.Code, w.Body.String()) } @@ -155,27 +285,148 @@ func TestHTTPListOrganizations_ReturnsOrganizations(t *testing.T) { } } -func TestHTTPListOrganizations_NotConfigured_Returns503(t *testing.T) { +func TestHTTP_TestConnection_RequiresWorkspace(t *testing.T) { _, router, _ := newTestController(t) - req := httptest.NewRequest(http.MethodGet, "/api/v1/sentry/organizations", nil) - w := httptest.NewRecorder() - router.ServeHTTP(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("status = %d, want 503", w.Code) - } - if !strings.Contains(w.Body.String(), `"code":"SENTRY_NOT_CONFIGURED"`) { - t.Errorf("missing code in body: %s", w.Body.String()) + if w := do(router, http.MethodPost, "/api/v1/sentry/test-connection", `{"secret":"t"}`); w.Code != http.StatusBadRequest { + t.Errorf("expected 400 without workspace_id, got %d", w.Code) } } -func TestHTTPSetConfig_BadJSON(t *testing.T) { - _, router, _ := newTestController(t) - req := httptest.NewRequest(http.MethodPut, "/api/v1/sentry/config", strings.NewReader("not-json")) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - router.ServeHTTP(w, req) +func TestHTTP_TestConnection_OK(t *testing.T) { + ctrl, router, client := newTestController(t) + client.testAuthFn = func() (*TestConnectionResult, error) { + return &TestConnectionResult{OK: true, DisplayName: "Alice"}, nil + } + _ = ctrl + w := do(router, http.MethodPost, "/api/v1/sentry/test-connection?workspace_id=ws-1", + `{"authMethod":"auth_token","secret":"tok","url":"https://sentry.example.com"}`) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body=%s", w.Code, w.Body.String()) + } + var res TestConnectionResult + if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil { + t.Fatalf("decode: %v", err) + } + if !res.OK { + t.Errorf("expected OK result, got %+v", res) + } +} + +func TestHTTP_CopyConfig_ReturnsWrappedList(t *testing.T) { + ctrl, router, _ := newTestController(t) + seedInstance(t, ctrl, "ws-src", "SaaS", "sec") + w := do(router, http.MethodPost, "/api/v1/sentry/config/copy?workspace_id=ws-src", + `{"targetWorkspaceId":"ws-dst"}`) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body=%s", w.Code, w.Body.String()) + } + var resp struct { + Instances []SentryConfig `json:"instances"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v", err) + } + if len(resp.Instances) != 1 || resp.Instances[0].WorkspaceID != "ws-dst" { + t.Errorf("copied = %+v", resp.Instances) + } +} + +func TestHTTP_CopyConfig_IgnoresBodySourceWorkspace(t *testing.T) { + ctrl, router, _ := newTestController(t) + seedInstance(t, ctrl, "ws-query", "Authoritative", "sec") + + w := do(router, http.MethodPost, "/api/v1/sentry/config/copy?workspace_id=ws-query", + `{"sourceWorkspaceId":"ws-body","targetWorkspaceId":"ws-dst"}`) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body=%s", w.Code, w.Body.String()) + } + var resp struct { + Instances []SentryConfig `json:"instances"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v", err) + } + if len(resp.Instances) != 1 || resp.Instances[0].Name != "Authoritative" { + t.Errorf("copied = %+v", resp.Instances) + } +} + +func TestHTTP_CopyConfig_RejectsBodyOnlySourceWorkspace(t *testing.T) { + ctrl, router, _ := newTestController(t) + seedInstance(t, ctrl, "ws-src", "SaaS", "sec") + + w := do(router, http.MethodPost, "/api/v1/sentry/config/copy", + `{"sourceWorkspaceId":"ws-src","targetWorkspaceId":"ws-dst"}`) if w.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400", w.Code) + t.Fatalf("status = %d, want 400; body=%s", w.Code, w.Body.String()) + } +} + +func TestHTTP_CopyConfig_DuplicateNameReturnsCodedConflict(t *testing.T) { + ctrl, router, _ := newTestController(t) + seedInstance(t, ctrl, "ws-src", "SaaS", "sec") + if _, err := ctrl.service.store.db.Exec(` + CREATE TRIGGER copy_duplicate_name + BEFORE INSERT ON sentry_configs + WHEN NEW.workspace_id = 'ws-dst' + BEGIN + SELECT RAISE(ABORT, 'UNIQUE constraint failed: sentry_configs.workspace_id, sentry_configs.name'); + END`); err != nil { + t.Fatalf("create duplicate trigger: %v", err) + } + + w := do(router, http.MethodPost, "/api/v1/sentry/config/copy?workspace_id=ws-src", + `{"targetWorkspaceId":"ws-dst"}`) + if w.Code != http.StatusConflict { + t.Fatalf("status = %d, want 409; body=%s", w.Code, w.Body.String()) + } + var response struct { + Code string `json:"code"` + } + if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil { + t.Fatalf("decode: %v", err) + } + if response.Code != errCodeSentryInstanceNameTaken { + t.Errorf("code = %q, want %q", response.Code, errCodeSentryInstanceNameTaken) + } +} + +// TestHTTP_CreateIssueWatch_RejectsMismatchedWorkspace pins acceptance (e) for +// watch-create. +func TestHTTP_CreateIssueWatch_RejectsMismatchedWorkspace(t *testing.T) { + ctrl, router, _ := newTestController(t) + inst := seedInstance(t, ctrl, "ws-1", "A", "tok") + body := `{"workspaceId":"ws-1","sentryInstanceId":"` + inst.ID + `","workflowId":"wf","workflowStepId":"step","filter":{"orgSlug":"acme","projectSlug":"fe"}}` + // Missing workspace_id query → 400. + if w := do(router, http.MethodPost, "/api/v1/sentry/watches/issue", body); w.Code != http.StatusBadRequest { + t.Errorf("expected 400 without workspace_id, got %d body=%s", w.Code, w.Body.String()) + } + // Mismatched workspace_id query → 400. + if w := do(router, http.MethodPost, "/api/v1/sentry/watches/issue?workspace_id=ws-2", body); w.Code != http.StatusBadRequest { + t.Errorf("expected 400 for mismatched workspace_id, got %d", w.Code) + } + // Matching → created (200). + if w := do(router, http.MethodPost, "/api/v1/sentry/watches/issue?workspace_id=ws-1", body); w.Code != http.StatusOK { + t.Errorf("expected 200 for matching workspace_id, got %d body=%s", w.Code, w.Body.String()) + } +} + +func TestHTTP_CreateIssueWatch_RequiresInstance(t *testing.T) { + _, router, _ := newTestController(t) + body := `{"workspaceId":"ws-1","workflowId":"wf","workflowStepId":"step","filter":{"orgSlug":"acme","projectSlug":"fe"}}` + + resp := do(router, http.MethodPost, "/api/v1/sentry/watches/issue?workspace_id=ws-1", body) + if resp.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400; body=%s", resp.Code, resp.Body.String()) + } + var response struct { + Code string `json:"code"` + } + if err := json.Unmarshal(resp.Body.Bytes(), &response); err != nil { + t.Fatalf("decode response: %v", err) + } + if response.Code != errCodeSentryInstanceRequired { + t.Errorf("error code = %q, want %q", response.Code, errCodeSentryInstanceRequired) } } @@ -212,8 +463,6 @@ func TestWriteClientError_GenericError(t *testing.T) { } func TestRegisterRoutes_AcceptsNilDispatcher(t *testing.T) { - // Sanity check that RegisterRoutes can be called with a real dispatcher - // without registering any WS handlers (Phase 1 has no WS surface). gin.SetMode(gin.TestMode) router := gin.New() store := newTestStore(t) @@ -223,3 +472,30 @@ func TestRegisterRoutes_AcceptsNilDispatcher(t *testing.T) { dispatcher := ws.NewDispatcher() RegisterRoutes(router, dispatcher, svc, logger.Default()) } + +// TestHTTP_TriggerIssueWatch_AmbiguousUnboundIs4xx pins the P2 fix: a manual +// trigger of an unbound watch that resolves ambiguously (multiple healthy +// instances) is routed through the issue-watch error mapper, yielding a 4xx +// (ErrInvalidConfig → 400) rather than a bare 500. +func TestHTTP_TriggerIssueWatch_AmbiguousUnboundIs4xx(t *testing.T) { + ctrl, router, _ := newTestController(t) + ctx := context.Background() + a := seedInstance(t, ctrl, "ws-1", "A", "tok") + b := seedInstance(t, ctrl, "ws-1", "B", "tok") + now := time.Now().UTC() + for _, id := range []string{a.ID, b.ID} { + if err := ctrl.service.store.UpdateAuthHealthForInstance(ctx, id, true, "", now); err != nil { + t.Fatalf("mark healthy: %v", err) + } + } + // Unbound watch: no SentryInstanceID → resolves ambiguously across the two + // healthy instances. + w := newTestIssueWatch("ws-1") + if err := ctrl.service.store.CreateIssueWatch(ctx, w); err != nil { + t.Fatalf("seed unbound watch: %v", err) + } + resp := do(router, http.MethodPost, "/api/v1/sentry/watches/issue/"+w.ID+"/trigger?workspace_id=ws-1", "") + if resp.Code < 400 || resp.Code >= 500 { + t.Fatalf("expected 4xx for ambiguous unbound-watch trigger, got %d body=%s", resp.Code, resp.Body.String()) + } +} diff --git a/apps/backend/internal/sentry/migration_test.go b/apps/backend/internal/sentry/migration_test.go new file mode 100644 index 0000000000..01a4276597 --- /dev/null +++ b/apps/backend/internal/sentry/migration_test.go @@ -0,0 +1,590 @@ +package sentry + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" + _ "github.com/mattn/go-sqlite3" + + "github.com/kandev/kandev/internal/common/logger" +) + +// workspaceScopedConfigsDDL is PR #1572's one-config-per-workspace shape +// (workspace_id PRIMARY KEY, no id column) that migrateConfigsTableToInstances +// upgrades. +const workspaceScopedConfigsDDL = ` + CREATE TABLE sentry_configs ( + workspace_id TEXT PRIMARY KEY, + auth_method TEXT NOT NULL, + url TEXT NOT NULL DEFAULT 'https://sentry.io', + last_checked_at DATETIME, + last_ok INTEGER NOT NULL DEFAULT 0, + last_error TEXT NOT NULL DEFAULT '', + created_at DATETIME NOT NULL, + updated_at DATETIME NOT NULL + );` + +// workspaceScopedWatchesDDL is the pre-instance sentry_issue_watches shape +// (workspace-scoped, no sentry_instance_id) that migrateWatchesAddInstanceColumn +// rebuilds, plus its child dedup table. +const workspaceScopedWatchesDDL = ` + CREATE TABLE sentry_issue_watches ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL, + workflow_id TEXT NOT NULL, + workflow_step_id TEXT NOT NULL, + repository_id TEXT NOT NULL DEFAULT '', + base_branch TEXT NOT NULL DEFAULT '', + filter_json TEXT NOT NULL DEFAULT '{}', + agent_profile_id TEXT NOT NULL DEFAULT '', + executor_profile_id TEXT NOT NULL DEFAULT '', + prompt TEXT NOT NULL DEFAULT '', + enabled BOOLEAN NOT NULL DEFAULT 1, + poll_interval_seconds INTEGER NOT NULL DEFAULT 300, + max_inflight_tasks INTEGER DEFAULT 5, + last_polled_at DATETIME, + last_error TEXT NOT NULL DEFAULT '', + last_error_at DATETIME, + created_at DATETIME NOT NULL, + updated_at DATETIME NOT NULL + ); + CREATE TABLE sentry_issue_watch_tasks ( + id TEXT PRIMARY KEY, + issue_watch_id TEXT NOT NULL, + issue_short_id TEXT NOT NULL, + issue_url TEXT NOT NULL, + task_id TEXT NOT NULL DEFAULT '', + created_at DATETIME NOT NULL, + UNIQUE(issue_watch_id, issue_short_id), + FOREIGN KEY(issue_watch_id) REFERENCES sentry_issue_watches(id) ON DELETE CASCADE + );` + +func openMigrationDB(t *testing.T) *sqlx.DB { + t.Helper() + db, err := sqlx.Open("sqlite3", ":memory:") + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + db.SetMaxOpenConns(1) + db.SetMaxIdleConns(1) + if _, err := db.Exec(`PRAGMA foreign_keys = ON`); err != nil { + t.Fatalf("enable foreign keys: %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + return db +} + +// seedWorkspaceScopedSchema builds the pre-instance workspace-scoped tables and +// seeds configs for ws-1 (self-hosted) and ws-2 (SaaS), watches for ws-1, ws-2 +// and ws-3 (which has NO config), plus one dedup task row for the ws-1 watch. +// Returns the ws-1/ws-2/ws-3 watch IDs. +func seedWorkspaceScopedSchema(t *testing.T, db *sqlx.DB) (w1, w2, w3 string) { + t.Helper() + now := time.Now().UTC().Truncate(time.Second) + if _, err := db.Exec(workspaceScopedConfigsDDL + workspaceScopedWatchesDDL); err != nil { + t.Fatalf("seed schema: %v", err) + } + if _, err := db.Exec(` + INSERT INTO sentry_configs (workspace_id, auth_method, url, last_checked_at, last_ok, last_error, created_at, updated_at) + VALUES ('ws-1', ?, 'https://sentry.example.com', ?, 1, 'healthy', ?, ?), + ('ws-2', ?, 'https://sentry.io', NULL, 0, '', ?, ?)`, + AuthMethodAuthToken, now, now, now, AuthMethodAuthToken, now, now); err != nil { + t.Fatalf("seed configs: %v", err) + } + w1, w2, w3 = uuid.New().String(), uuid.New().String(), uuid.New().String() + for _, watch := range []struct{ id, ws string }{{w1, "ws-1"}, {w2, "ws-2"}, {w3, "ws-3"}} { + if _, err := db.Exec(` + INSERT INTO sentry_issue_watches (id, workspace_id, workflow_id, workflow_step_id, filter_json, created_at, updated_at) + VALUES (?, ?, 'wf', 'step', '{"orgSlug":"acme","projectSlug":"fe"}', ?, ?)`, + watch.id, watch.ws, now, now); err != nil { + t.Fatalf("seed watch %s: %v", watch.ws, err) + } + } + if _, err := db.Exec(` + INSERT INTO sentry_issue_watch_tasks (id, issue_watch_id, issue_short_id, issue_url, task_id, created_at) + VALUES (?, ?, 'PROJ-1', 'https://sentry.example.com/issues/PROJ-1', 'task-1', ?)`, + uuid.New().String(), w1, now); err != nil { + t.Fatalf("seed dedup task: %v", err) + } + return w1, w2, w3 +} + +// TestMigration_WorkspaceConfigsToInstances pins acceptance (a): the +// workspace-scoped model upgrades to id-keyed instances, the per-workspace +// secret is rekeyed to the per-instance key, and every watch's +// sentry_instance_id is backfilled when its workspace has exactly one config. +func TestMigration_WorkspaceConfigsToInstances(t *testing.T) { + db := openMigrationDB(t) + w1, w2, w3 := seedWorkspaceScopedSchema(t, db) + + secrets := newFakeSecretStore() + ctx := context.Background() + _ = secrets.Set(ctx, SecretKeyForWorkspace("ws-1"), "tok", "tok-1") + _ = secrets.Set(ctx, SecretKeyForWorkspace("ws-2"), "tok", "tok-2") + + svc, _, err := Provide(db, db, secrets, nil, logger.Default()) + if err != nil { + t.Fatalf("Provide (migrate): %v", err) + } + store := svc.Store() + + // One instance per workspace config, host-derived names, health preserved. + inst1List, _ := store.ListInstances(ctx, "ws-1") + inst2List, _ := store.ListInstances(ctx, "ws-2") + if len(inst1List) != 1 || len(inst2List) != 1 { + t.Fatalf("expected one instance per workspace, got ws-1=%d ws-2=%d", len(inst1List), len(inst2List)) + } + inst1, inst2 := inst1List[0], inst2List[0] + if inst1.Name != "sentry.example.com" || inst1.URL != "https://sentry.example.com" || !inst1.LastOk { + t.Errorf("ws-1 instance not migrated faithfully: %+v", inst1) + } + if inst2.Name != "sentry.io" { + t.Errorf("ws-2 instance name = %q, want host-derived 'sentry.io'", inst2.Name) + } + + // Watches backfilled to their workspace's instance; the config-less + // workspace's watch stays unbound (NULL). + gw1, _ := store.GetIssueWatch(ctx, w1) + gw2, _ := store.GetIssueWatch(ctx, w2) + gw3, _ := store.GetIssueWatch(ctx, w3) + if gw1.SentryInstanceID != inst1.ID { + t.Errorf("ws-1 watch bound to %q, want %q", gw1.SentryInstanceID, inst1.ID) + } + if gw2.SentryInstanceID != inst2.ID { + t.Errorf("ws-2 watch bound to %q, want %q", gw2.SentryInstanceID, inst2.ID) + } + if gw3.SentryInstanceID != "" { + t.Errorf("config-less workspace watch should stay unbound, got %q", gw3.SentryInstanceID) + } + + // The dedup child row survived the watches table rebuild (FK preserved). + ids, _ := store.ListIssueWatchTaskIDs(ctx, w1) + if len(ids) != 1 || ids[0] != "task-1" { + t.Errorf("expected dedup task preserved through rebuild, got %v", ids) + } + + // Secret rekeyed from the workspace key to the per-instance key. + if got, _ := secrets.Reveal(ctx, secretKeyForInstance(inst1.ID)); got != "tok-1" { + t.Errorf("ws-1 secret not rekeyed to instance key, got %q", got) + } + if got, _ := secrets.Reveal(ctx, secretKeyForInstance(inst2.ID)); got != "tok-2" { + t.Errorf("ws-2 secret not rekeyed to instance key, got %q", got) + } +} + +// TestMigration_RerunIsIdempotent pins acceptance (c): re-running the whole +// migration + secret rekey after a completed run changes nothing. +func TestMigration_RerunIsIdempotent(t *testing.T) { + db := openMigrationDB(t) + w1, _, _ := seedWorkspaceScopedSchema(t, db) + secrets := newFakeSecretStore() + ctx := context.Background() + _ = secrets.Set(ctx, SecretKeyForWorkspace("ws-1"), "tok", "tok-1") + _ = secrets.Set(ctx, SecretKeyForWorkspace("ws-2"), "tok", "tok-2") + + svc1, _, err := Provide(db, db, secrets, nil, logger.Default()) + if err != nil { + t.Fatalf("first Provide: %v", err) + } + before, _ := svc1.Store().ListAllInstances(ctx) + boundBefore, _ := svc1.Store().GetIssueWatch(ctx, w1) + + // Re-run: a fresh NewStore + secret rekey over the same (now-migrated) DB. + store2, err := NewStore(db, db) + if err != nil { + t.Fatalf("second NewStore: %v", err) + } + migrateInstanceSecrets(store2, secrets, logger.Default()) + + after, _ := store2.ListAllInstances(ctx) + if len(after) != len(before) || len(after) != 2 { + t.Fatalf("instance count changed on rerun: before=%d after=%d", len(before), len(after)) + } + if after[0].ID != before[0].ID || after[1].ID != before[1].ID { + t.Error("instance IDs changed on rerun") + } + boundAfter, _ := store2.GetIssueWatch(ctx, w1) + if boundAfter.SentryInstanceID != boundBefore.SentryInstanceID { + t.Errorf("watch binding changed on rerun: %q -> %q", boundBefore.SentryInstanceID, boundAfter.SentryInstanceID) + } + if got, _ := secrets.Reveal(ctx, secretKeyForInstance(boundBefore.SentryInstanceID)); got != "tok-1" { + t.Errorf("secret changed on rerun, got %q", got) + } +} + +// TestMigration_CrashAfterConfigsRebuild pins the other half of acceptance (c): +// a crash after the configs table was rebuilt to the id-keyed shape but before +// the watches table gained its FK column. The next boot must complete the watch +// rebuild + backfill against the already-migrated configs. +func TestMigration_CrashAfterConfigsRebuild(t *testing.T) { + db := openMigrationDB(t) + ctx := context.Background() + now := time.Now().UTC().Truncate(time.Second) + + // Simulate the post-configs-rebuild / pre-watches-rebuild state: configs are + // already id-keyed, watches are still workspace-scoped without the FK column. + inst1, inst2 := uuid.New().String(), uuid.New().String() + if _, err := db.Exec(`CREATE TABLE sentry_configs (` + sentryConfigsColumns + `)`); err != nil { + t.Fatalf("create id-keyed configs: %v", err) + } + if _, err := db.Exec(` + INSERT INTO sentry_configs (id, workspace_id, name, auth_method, url, last_ok, last_error, created_at, updated_at) + VALUES (?, 'ws-1', 'sentry.example.com', ?, 'https://sentry.example.com', 0, '', ?, ?), + (?, 'ws-2', 'sentry.io', ?, 'https://sentry.io', 0, '', ?, ?)`, + inst1, AuthMethodAuthToken, now, now, inst2, AuthMethodAuthToken, now, now); err != nil { + t.Fatalf("seed id-keyed configs: %v", err) + } + w1, w2, w3 := uuid.New().String(), uuid.New().String(), uuid.New().String() + if _, err := db.Exec(workspaceScopedWatchesDDL); err != nil { + t.Fatalf("seed workspace-scoped watches: %v", err) + } + for _, watch := range []struct{ id, ws string }{{w1, "ws-1"}, {w2, "ws-2"}, {w3, "ws-3"}} { + if _, err := db.Exec(` + INSERT INTO sentry_issue_watches (id, workspace_id, workflow_id, workflow_step_id, filter_json, created_at, updated_at) + VALUES (?, ?, 'wf', 'step', '{}', ?, ?)`, watch.id, watch.ws, now, now); err != nil { + t.Fatalf("seed watch %s: %v", watch.ws, err) + } + } + + store, err := NewStore(db, db) + if err != nil { + t.Fatalf("resume migration: %v", err) + } + + // Configs are left untouched (no second rebuild → IDs preserved). + gi1, _ := store.GetInstance(ctx, inst1) + if gi1 == nil { + t.Fatal("existing id-keyed config was clobbered") + } + // Watches now carry the FK column, backfilled from the existing configs. + if gw1, _ := store.GetIssueWatch(ctx, w1); gw1.SentryInstanceID != inst1 { + t.Errorf("ws-1 watch bound to %q, want %q", gw1.SentryInstanceID, inst1) + } + if gw2, _ := store.GetIssueWatch(ctx, w2); gw2.SentryInstanceID != inst2 { + t.Errorf("ws-2 watch bound to %q, want %q", gw2.SentryInstanceID, inst2) + } + if gw3, _ := store.GetIssueWatch(ctx, w3); gw3.SentryInstanceID != "" { + t.Errorf("config-less workspace watch should stay unbound, got %q", gw3.SentryInstanceID) + } +} + +// experimentalWatchesDDL is the unmerged-#1469 experimental shape: +// sentry_issue_watches carries sentry_instance_id as NOT NULL DEFAULT ” with +// NO foreign key. It only ever existed on dev machines that ran that build; +// migrateWatchesAddInstanceColumn must still converge it to the nullable-FK +// shape rather than skip it because the column name happens to be present. +const experimentalWatchesDDL = ` + CREATE TABLE sentry_issue_watches ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL, + sentry_instance_id TEXT NOT NULL DEFAULT '', + workflow_id TEXT NOT NULL, + workflow_step_id TEXT NOT NULL, + repository_id TEXT NOT NULL DEFAULT '', + base_branch TEXT NOT NULL DEFAULT '', + filter_json TEXT NOT NULL DEFAULT '{}', + agent_profile_id TEXT NOT NULL DEFAULT '', + executor_profile_id TEXT NOT NULL DEFAULT '', + prompt TEXT NOT NULL DEFAULT '', + enabled BOOLEAN NOT NULL DEFAULT 1, + poll_interval_seconds INTEGER NOT NULL DEFAULT 300, + max_inflight_tasks INTEGER DEFAULT 5, + last_polled_at DATETIME, + last_error TEXT NOT NULL DEFAULT '', + last_error_at DATETIME, + created_at DATETIME NOT NULL, + updated_at DATETIME NOT NULL + ); + CREATE TABLE sentry_issue_watch_tasks ( + id TEXT PRIMARY KEY, + issue_watch_id TEXT NOT NULL, + issue_short_id TEXT NOT NULL, + issue_url TEXT NOT NULL, + task_id TEXT NOT NULL DEFAULT '', + created_at DATETIME NOT NULL, + UNIQUE(issue_watch_id, issue_short_id), + FOREIGN KEY(issue_watch_id) REFERENCES sentry_issue_watches(id) ON DELETE CASCADE + );` + +// TestMigration_ExperimentalNonNullInstanceColumnRebuilt pins the hardened +// guard: a watches table that already has sentry_instance_id but as +// NOT NULL DEFAULT ” with no foreign key is rebuilt into the nullable-FK shape +// (not skipped), converting the ” sentinel to a real backfill / NULL. +func TestMigration_ExperimentalNonNullInstanceColumnRebuilt(t *testing.T) { + db := openMigrationDB(t) + ctx := context.Background() + now := time.Now().UTC().Truncate(time.Second) + + inst1 := uuid.New().String() + if _, err := db.Exec(`CREATE TABLE sentry_configs (` + sentryConfigsColumns + `)`); err != nil { + t.Fatalf("create id-keyed configs: %v", err) + } + if _, err := db.Exec(` + INSERT INTO sentry_configs (id, workspace_id, name, auth_method, url, last_ok, last_error, created_at, updated_at) + VALUES (?, 'ws-1', 'sentry.example.com', ?, 'https://sentry.example.com', 0, '', ?, ?)`, + inst1, AuthMethodAuthToken, now, now); err != nil { + t.Fatalf("seed configs: %v", err) + } + if _, err := db.Exec(experimentalWatchesDDL); err != nil { + t.Fatalf("seed experimental watches: %v", err) + } + w1, w3 := uuid.New().String(), uuid.New().String() + // Experimental rows store the '' sentinel for the unbound case. + for _, watch := range []struct{ id, ws string }{{w1, "ws-1"}, {w3, "ws-3"}} { + if _, err := db.Exec(` + INSERT INTO sentry_issue_watches (id, workspace_id, sentry_instance_id, workflow_id, workflow_step_id, filter_json, created_at, updated_at) + VALUES (?, ?, '', 'wf', 'step', '{}', ?, ?)`, watch.id, watch.ws, now, now); err != nil { + t.Fatalf("seed watch %s: %v", watch.ws, err) + } + } + + store, err := NewStore(db, db) + if err != nil { + t.Fatalf("migrate experimental schema: %v", err) + } + + // Column is now nullable and backed by the ON DELETE RESTRICT FK to id. + nullable, err := store.columnIsNullable("sentry_issue_watches", "sentry_instance_id") + if err != nil || !nullable { + t.Errorf("sentry_instance_id nullable=%v err=%v, want nullable", nullable, err) + } + hasFK, err := store.hasForeignKey("sentry_issue_watches", "sentry_instance_id", "sentry_configs", "id", "RESTRICT") + if err != nil || !hasFK { + t.Errorf("sentry_instance_id FK present=%v err=%v, want RESTRICT FK to id", hasFK, err) + } + + // Rows re-backfilled: ws-1 to its sole instance, config-less ws-3 to NULL. + if gw1, _ := store.GetIssueWatch(ctx, w1); gw1.SentryInstanceID != inst1 { + t.Errorf("ws-1 watch bound to %q, want %q", gw1.SentryInstanceID, inst1) + } + if gw3, _ := store.GetIssueWatch(ctx, w3); gw3.SentryInstanceID != "" { + t.Errorf("config-less watch should be unbound, got %q", gw3.SentryInstanceID) + } + + // FK now enforced: deleting an in-use instance is blocked. + if _, err := db.Exec(`DELETE FROM sentry_configs WHERE id = ?`, inst1); err == nil { + t.Error("expected FK RESTRICT to block deleting an in-use instance after rebuild") + } +} + +// TestMigration_RekeyDoesNotSeedLaterSecretlessInstance ensures a completed +// legacy secret migration cannot grant an ordinary later instance the stale +// workspace or singleton token on a subsequent process start. +func TestMigration_RekeyDoesNotSeedLaterSecretlessInstance(t *testing.T) { + db := openMigrationDB(t) + seedWorkspaceScopedSchema(t, db) + ctx := context.Background() + secrets := newFakeSecretStore() + if err := secrets.Set(ctx, SecretKeyForWorkspace("ws-1"), "tok", "workspace-token"); err != nil { + t.Fatalf("seed workspace token: %v", err) + } + if err := secrets.Set(ctx, SecretKey, "tok", "singleton-token"); err != nil { + t.Fatalf("seed singleton token: %v", err) + } + + svc, _, err := Provide(db, db, secrets, nil, logger.Default()) + if err != nil { + t.Fatalf("first Provide: %v", err) + } + later := testInstance("ws-1", "Later") + if err := svc.Store().CreateInstance(ctx, later); err != nil { + t.Fatalf("create later secretless instance: %v", err) + } + + if _, _, err := Provide(db, db, secrets, nil, logger.Default()); err != nil { + t.Fatalf("restart Provide: %v", err) + } + if exists, err := secrets.Exists(ctx, secretKeyForInstance(later.ID)); err != nil { + t.Fatalf("check later instance secret: %v", err) + } else if exists { + t.Fatal("later secretless instance inherited a stale legacy token") + } +} + +// TestMigration_RekeyRetriesOriginalInstanceDespiteLaterAddition ensures a +// transient secret-store failure on the original migrated instance's rekey +// does not permanently strand it once a later, unrelated instance is added to +// the same workspace before the next restart: only the later instance is +// excluded from ever inheriting the legacy token, not the legitimate original. +func TestMigration_RekeyRetriesOriginalInstanceDespiteLaterAddition(t *testing.T) { + db := openMigrationDB(t) + seedWorkspaceScopedSchema(t, db) + ctx := context.Background() + secrets := newFakeSecretStore() + if err := secrets.Set(ctx, SecretKeyForWorkspace("ws-1"), "tok", "workspace-token"); err != nil { + t.Fatalf("seed workspace token: %v", err) + } + + secrets.setErr = errors.New("secret store unavailable") + svc, _, err := Provide(db, db, secrets, nil, logger.Default()) + if err != nil { + t.Fatalf("first Provide: %v", err) + } + instances, err := svc.Store().ListInstances(ctx, "ws-1") + if err != nil || len(instances) != 1 { + t.Fatalf("list ws-1 instances: %v %+v", err, instances) + } + original := instances[0] + if exists, _ := secrets.Exists(ctx, secretKeyForInstance(original.ID)); exists { + t.Fatal("expected the first rekey attempt to fail, but the instance key already exists") + } + + later := testInstance("ws-1", "Later") + if err := svc.Store().CreateInstance(ctx, later); err != nil { + t.Fatalf("create later secretless instance: %v", err) + } + + secrets.setErr = nil + if _, _, err := Provide(db, db, secrets, nil, logger.Default()); err != nil { + t.Fatalf("restart Provide: %v", err) + } + + if exists, err := secrets.Exists(ctx, secretKeyForInstance(original.ID)); err != nil || !exists { + t.Fatalf("expected the original instance to recover its legacy token once the transient failure cleared, exists=%v err=%v", exists, err) + } + if exists, err := secrets.Exists(ctx, secretKeyForInstance(later.ID)); err != nil || exists { + t.Fatalf("later secretless instance must still never inherit the legacy token, exists=%v err=%v", exists, err) + } +} + +// TestMigration_MultipleInstancesLeaveLegacyWatchUnbound ensures the watch +// rebuild preserves the unbound fallback when a workspace has several possible +// instance targets rather than guessing the oldest one. +func TestMigration_MultipleInstancesLeaveLegacyWatchUnbound(t *testing.T) { + db := openMigrationDB(t) + ctx := context.Background() + now := time.Now().UTC().Truncate(time.Second) + first, second := uuid.New().String(), uuid.New().String() + if _, err := db.Exec(`CREATE TABLE sentry_configs (` + sentryConfigsColumns + `)`); err != nil { + t.Fatalf("create id-keyed configs: %v", err) + } + if _, err := db.Exec(` + INSERT INTO sentry_configs (id, workspace_id, name, auth_method, url, last_ok, last_error, created_at, updated_at) + VALUES (?, 'ws-1', 'First', ?, 'https://first.example.com', 0, '', ?, ?), + (?, 'ws-1', 'Second', ?, 'https://second.example.com', 0, '', ?, ?)`, + first, AuthMethodAuthToken, now, now, + second, AuthMethodAuthToken, now.Add(time.Minute), now.Add(time.Minute)); err != nil { + t.Fatalf("seed instances: %v", err) + } + if _, err := db.Exec(workspaceScopedWatchesDDL); err != nil { + t.Fatalf("create legacy watches: %v", err) + } + watchID := uuid.New().String() + if _, err := db.Exec(` + INSERT INTO sentry_issue_watches (id, workspace_id, workflow_id, workflow_step_id, filter_json, created_at, updated_at) + VALUES (?, 'ws-1', 'wf', 'step', '{}', ?, ?)`, watchID, now, now); err != nil { + t.Fatalf("seed legacy watch: %v", err) + } + + store, err := NewStore(db, db) + if err != nil { + t.Fatalf("migrate watches: %v", err) + } + watch, err := store.GetIssueWatch(ctx, watchID) + if err != nil { + t.Fatalf("get migrated watch: %v", err) + } + if watch.SentryInstanceID != "" { + t.Fatalf("multi-instance legacy watch bound to %q, want unbound", watch.SentryInstanceID) + } +} + +// TestMigration_ExperimentalBindingSurvivesRebuild ensures a valid explicit +// binding from the experimental no-FK shape is not overwritten by backfill. +func TestMigration_ExperimentalBindingSurvivesRebuild(t *testing.T) { + db := openMigrationDB(t) + ctx := context.Background() + now := time.Now().UTC().Truncate(time.Second) + first, selected := uuid.New().String(), uuid.New().String() + if _, err := db.Exec(`CREATE TABLE sentry_configs (` + sentryConfigsColumns + `)`); err != nil { + t.Fatalf("create id-keyed configs: %v", err) + } + if _, err := db.Exec(` + INSERT INTO sentry_configs (id, workspace_id, name, auth_method, url, last_ok, last_error, created_at, updated_at) + VALUES (?, 'ws-1', 'First', ?, 'https://first.example.com', 0, '', ?, ?), + (?, 'ws-1', 'Selected', ?, 'https://selected.example.com', 0, '', ?, ?)`, + first, AuthMethodAuthToken, now, now, + selected, AuthMethodAuthToken, now.Add(time.Minute), now.Add(time.Minute)); err != nil { + t.Fatalf("seed instances: %v", err) + } + if _, err := db.Exec(experimentalWatchesDDL); err != nil { + t.Fatalf("create experimental watches: %v", err) + } + watchID := uuid.New().String() + if _, err := db.Exec(` + INSERT INTO sentry_issue_watches (id, workspace_id, sentry_instance_id, workflow_id, workflow_step_id, filter_json, created_at, updated_at) + VALUES (?, 'ws-1', ?, 'wf', 'step', '{}', ?, ?)`, watchID, selected, now, now); err != nil { + t.Fatalf("seed experimental watch: %v", err) + } + + store, err := NewStore(db, db) + if err != nil { + t.Fatalf("migrate watches: %v", err) + } + watch, err := store.GetIssueWatch(ctx, watchID) + if err != nil { + t.Fatalf("get migrated watch: %v", err) + } + if watch.SentryInstanceID != selected { + t.Fatalf("experimental binding = %q, want %q", watch.SentryInstanceID, selected) + } +} + +// TestHasForeignKey_ImplicitPrimaryKeyReference pins the NULL-`to` edge case: a +// FK declared as `REFERENCES sentry_configs` (implicit primary key, no column +// named) is reported by SQLite's foreign_key_list with a NULL `to`. hasForeignKey +// must resolve that to the single-column PK (`id`) and recognize the FK rather +// than treat the NULL as a non-match and force an unnecessary table rebuild. +func TestHasForeignKey_ImplicitPrimaryKeyReference(t *testing.T) { + db := openMigrationDB(t) + if _, err := db.Exec(`CREATE TABLE sentry_configs (` + sentryConfigsColumns + `)`); err != nil { + t.Fatalf("create configs: %v", err) + } + if _, err := db.Exec(` + CREATE TABLE child ( + id TEXT PRIMARY KEY, + sentry_instance_id TEXT, + FOREIGN KEY(sentry_instance_id) REFERENCES sentry_configs ON DELETE RESTRICT + )`); err != nil { + t.Fatalf("create child with implicit-PK FK: %v", err) + } + store := &Store{db: db, ro: db} + ok, err := store.hasForeignKey("child", "sentry_instance_id", "sentry_configs", "id", "RESTRICT") + if err != nil { + t.Fatalf("hasForeignKey error: %v", err) + } + if !ok { + t.Error("hasForeignKey = false, want true for an implicit-PK reference (REFERENCES sentry_configs)") + } +} + +// TestHasForeignKey_ImplicitCompositePrimaryKeyNoFalseMatch guards the composite +// case: an implicit reference to a table whose PRIMARY KEY spans several columns +// targets the whole key, so it must not be reported as matching a single wanted +// column. +func TestHasForeignKey_ImplicitCompositePrimaryKeyNoFalseMatch(t *testing.T) { + db := openMigrationDB(t) + if _, err := db.Exec(`CREATE TABLE parent (a TEXT, b TEXT, PRIMARY KEY(a, b))`); err != nil { + t.Fatalf("create parent: %v", err) + } + if _, err := db.Exec(` + CREATE TABLE child ( + a TEXT, + b TEXT, + FOREIGN KEY(a, b) REFERENCES parent ON DELETE RESTRICT + )`); err != nil { + t.Fatalf("create child with composite implicit-PK FK: %v", err) + } + store := &Store{db: db, ro: db} + ok, err := store.hasForeignKey("child", "a", "parent", "a", "RESTRICT") + if err != nil { + t.Fatalf("hasForeignKey error: %v", err) + } + if ok { + t.Error("hasForeignKey = true, want false: an implicit composite-PK reference must not match a single wanted column") + } +} diff --git a/apps/backend/internal/sentry/mock_client.go b/apps/backend/internal/sentry/mock_client.go index 49f24654e7..1e1d640bf9 100644 --- a/apps/backend/internal/sentry/mock_client.go +++ b/apps/backend/internal/sentry/mock_client.go @@ -7,11 +7,18 @@ import ( "sync" ) -// MockClient implements Client with in-memory data for E2E tests. A single -// shared instance per process, driven by HTTP control routes mounted in mock -// mode. +// MockClient backs the in-memory Client used by E2E tests. It is instance-aware: +// each Sentry instance has its own dataset keyed by instance ID, so a test can +// prove instance A and instance B return different data. A single shared +// MockClient per process is driven by the HTTP control routes mounted in mock +// mode; the ClientFactory hands each instance a view bound to its ID. type MockClient struct { - mu sync.RWMutex + mu sync.RWMutex + datasets map[string]*mockDataset // instance ID → dataset +} + +// mockDataset is the per-instance seeded state. +type mockDataset struct { authResult *TestConnectionResult organizations []SentryOrganization projects []SentryProject @@ -22,58 +29,88 @@ type MockClient struct { getError *APIError } -// NewMockClient seeds a default-success TestAuth so a fresh config flips to +// NewMockClient returns an empty instance-aware mock. Instances default to a +// successful TestAuth (seeded lazily) so a freshly-created instance flips to // "Authenticated" without explicit seeding. func NewMockClient() *MockClient { - return &MockClient{ - authResult: &TestConnectionResult{ - OK: true, - UserID: "mock-user", - DisplayName: "Mock User", - Email: "mock@example.com", - }, - issues: make(map[string]*SentryIssue), + return &MockClient{datasets: make(map[string]*mockDataset)} +} + +func newMockDataset() *mockDataset { + return &mockDataset{ + authResult: defaultMockAuthResult(), + issues: make(map[string]*SentryIssue), } } -// --- Client interface --- +func defaultMockAuthResult() *TestConnectionResult { + return &TestConnectionResult{ + OK: true, + UserID: "mock-user", + DisplayName: "Mock User", + Email: "mock@example.com", + } +} -func (m *MockClient) TestAuth(context.Context) (*TestConnectionResult, error) { +// dataset returns the dataset for instanceID, lazily creating it. The caller +// must hold the write lock. +func (m *MockClient) dataset(instanceID string) *mockDataset { + ds, ok := m.datasets[instanceID] + if !ok { + ds = newMockDataset() + m.datasets[instanceID] = ds + } + return ds +} + +// --- instance-scoped read operations (used by the per-instance Client view) --- + +func (m *MockClient) testAuth(instanceID string) (*TestConnectionResult, error) { m.mu.RLock() defer m.mu.RUnlock() - if m.authResult == nil { - return &TestConnectionResult{OK: false, Error: "mock: no auth result configured"}, nil + ds := m.datasets[instanceID] + if ds == nil || ds.authResult == nil { + return defaultMockAuthResult(), nil } - r := *m.authResult + r := *ds.authResult return &r, nil } -func (m *MockClient) ListOrganizations(context.Context) ([]SentryOrganization, error) { +func (m *MockClient) listOrganizations(instanceID string) ([]SentryOrganization, error) { m.mu.RLock() defer m.mu.RUnlock() - out := make([]SentryOrganization, len(m.organizations)) - copy(out, m.organizations) + ds := m.datasets[instanceID] + if ds == nil { + return nil, nil + } + out := make([]SentryOrganization, len(ds.organizations)) + copy(out, ds.organizations) return out, nil } -func (m *MockClient) ListProjects(context.Context) ([]SentryProject, error) { +func (m *MockClient) listProjects(instanceID string) ([]SentryProject, error) { m.mu.RLock() defer m.mu.RUnlock() - out := make([]SentryProject, len(m.projects)) - copy(out, m.projects) + ds := m.datasets[instanceID] + if ds == nil { + return nil, nil + } + out := make([]SentryProject, len(ds.projects)) + copy(out, ds.projects) return out, nil } -func (m *MockClient) SearchIssues(_ context.Context, filter SearchFilter, _ string) (*SearchResult, error) { +func (m *MockClient) searchIssues(instanceID string, filter SearchFilter) (*SearchResult, error) { m.mu.RLock() defer m.mu.RUnlock() - out := make([]SentryIssue, 0, len(m.issueOrder)) - for _, id := range m.issueOrder { - issue, ok := m.issues[id] - if !ok { - continue - } - if !mockMatchesFilter(issue, filter) { + ds := m.datasets[instanceID] + if ds == nil { + return &SearchResult{IsLast: true}, nil + } + out := make([]SentryIssue, 0, len(ds.issueOrder)) + for _, id := range ds.issueOrder { + issue, ok := ds.issues[id] + if !ok || !mockMatchesFilter(issue, filter) { continue } out = append(out, *issue) @@ -81,19 +118,23 @@ func (m *MockClient) SearchIssues(_ context.Context, filter SearchFilter, _ stri return &SearchResult{Issues: out, IsLast: true}, nil } -func (m *MockClient) GetIssue(_ context.Context, idOrShortID string) (*SentryIssue, error) { +func (m *MockClient) getIssue(instanceID, idOrShortID string) (*SentryIssue, error) { m.mu.RLock() defer m.mu.RUnlock() - if m.getError != nil { - err := *m.getError + ds := m.datasets[instanceID] + if ds == nil { + return nil, &APIError{StatusCode: http.StatusNotFound, Message: "issue not found: " + idOrShortID} + } + if ds.getError != nil { + err := *ds.getError return nil, &err } - if issue, ok := m.issues[idOrShortID]; ok { + if issue, ok := ds.issues[idOrShortID]; ok { cp := *issue return &cp, nil } // Fall back to numeric ID lookup so callers can use either form. - for _, i := range m.issues { + for _, i := range ds.issues { if i.ID == idOrShortID { cp := *i return &cp, nil @@ -102,13 +143,68 @@ func (m *MockClient) GetIssue(_ context.Context, idOrShortID string) (*SentryIss return nil, &APIError{StatusCode: http.StatusNotFound, Message: "issue not found: " + idOrShortID} } +// --- setters used by MockController, scoped per instance --- + +// SetAuthResult sets the auth result an instance returns from TestAuth. +func (m *MockClient) SetAuthResult(instanceID string, r *TestConnectionResult) { + m.mu.Lock() + defer m.mu.Unlock() + m.dataset(instanceID).authResult = r +} + +// SetOrganizations replaces an instance's organization list. +func (m *MockClient) SetOrganizations(instanceID string, organizations []SentryOrganization) { + m.mu.Lock() + defer m.mu.Unlock() + cp := make([]SentryOrganization, len(organizations)) + copy(cp, organizations) + m.dataset(instanceID).organizations = cp +} + +// SetProjects replaces an instance's project list. +func (m *MockClient) SetProjects(instanceID string, projects []SentryProject) { + m.mu.Lock() + defer m.mu.Unlock() + cp := make([]SentryProject, len(projects)) + copy(cp, projects) + m.dataset(instanceID).projects = cp +} + +// AddIssue appends an issue to an instance's dataset (idempotent by key). +func (m *MockClient) AddIssue(instanceID string, issue *SentryIssue) { + m.mu.Lock() + defer m.mu.Unlock() + ds := m.dataset(instanceID) + cp := *issue + key := issue.ShortID + if key == "" { + key = issue.ID + } + if _, exists := ds.issues[key]; !exists { + ds.issueOrder = append(ds.issueOrder, key) + } + ds.issues[key] = &cp +} + +// SetGetIssueError forces GetIssue on an instance to fail (nil clears it). +func (m *MockClient) SetGetIssueError(instanceID string, err *APIError) { + m.mu.Lock() + defer m.mu.Unlock() + m.dataset(instanceID).getError = err +} + +// Reset clears every instance dataset back to empty. +func (m *MockClient) Reset() { + m.mu.Lock() + defer m.mu.Unlock() + m.datasets = make(map[string]*mockDataset) +} + // mockMatchesFilter applies the filter predicates that map to a per-issue // field, so E2E tests can assert the backend forwarded the filter rather than // silently returning everything. Deliberately NOT enforced (no per-issue -// analog on SentryIssue): OrgSlug (the mock's project list is one tenant), -// Environment (issues carry no environment in our projection), and StatsPeriod -// (a relative time window, not an issue attribute). The real REST client's -// URL building for those params is covered in rest_client_test.go. +// analog on SentryIssue): OrgSlug, Environment, and StatsPeriod. The real REST +// client's URL building for those params is covered in rest_client_test.go. func mockMatchesFilter(issue *SentryIssue, f SearchFilter) bool { if f.ProjectSlug != "" && issue.ProjectSlug != f.ProjectSlug { return false @@ -136,71 +232,41 @@ func containsFold(xs []string, target string) bool { return false } -// --- Setters used by MockController --- - -func (m *MockClient) SetAuthResult(r *TestConnectionResult) { - m.mu.Lock() - defer m.mu.Unlock() - m.authResult = r +// mockInstanceClient is a Client view bound to one instance ID, delegating to +// the shared MockClient's per-instance dataset. +type mockInstanceClient struct { + shared *MockClient + instanceID string } -func (m *MockClient) SetOrganizations(organizations []SentryOrganization) { - m.mu.Lock() - defer m.mu.Unlock() - cp := make([]SentryOrganization, len(organizations)) - copy(cp, organizations) - m.organizations = cp +func (c *mockInstanceClient) TestAuth(context.Context) (*TestConnectionResult, error) { + return c.shared.testAuth(c.instanceID) } -func (m *MockClient) SetProjects(projects []SentryProject) { - m.mu.Lock() - defer m.mu.Unlock() - cp := make([]SentryProject, len(projects)) - copy(cp, projects) - m.projects = cp +func (c *mockInstanceClient) ListOrganizations(context.Context) ([]SentryOrganization, error) { + return c.shared.listOrganizations(c.instanceID) } -func (m *MockClient) AddIssue(issue *SentryIssue) { - m.mu.Lock() - defer m.mu.Unlock() - cp := *issue - key := issue.ShortID - if key == "" { - key = issue.ID - } - if _, exists := m.issues[key]; !exists { - m.issueOrder = append(m.issueOrder, key) - } - m.issues[key] = &cp +func (c *mockInstanceClient) ListProjects(context.Context) ([]SentryProject, error) { + return c.shared.listProjects(c.instanceID) } -func (m *MockClient) SetGetIssueError(err *APIError) { - m.mu.Lock() - defer m.mu.Unlock() - m.getError = err +func (c *mockInstanceClient) SearchIssues(_ context.Context, filter SearchFilter, _ string) (*SearchResult, error) { + return c.shared.searchIssues(c.instanceID, filter) } -// Reset clears every seeded value back to defaults. -func (m *MockClient) Reset() { - m.mu.Lock() - defer m.mu.Unlock() - m.authResult = &TestConnectionResult{ - OK: true, - UserID: "mock-user", - DisplayName: "Mock User", - Email: "mock@example.com", - } - m.organizations = nil - m.projects = nil - m.issues = make(map[string]*SentryIssue) - m.issueOrder = nil - m.getError = nil +func (c *mockInstanceClient) GetIssue(_ context.Context, idOrShortID string) (*SentryIssue, error) { + return c.shared.getIssue(c.instanceID, idOrShortID) } -// MockClientFactory returns a ClientFactory that always hands back the shared -// MockClient regardless of credentials. +// MockClientFactory returns a ClientFactory that hands each instance a view of +// the shared MockClient bound to that instance's ID. func MockClientFactory(shared *MockClient) ClientFactory { - return func(*SentryConfig, string) Client { - return shared + return func(cfg *SentryConfig, _ string) Client { + instanceID := "" + if cfg != nil { + instanceID = cfg.ID + } + return &mockInstanceClient{shared: shared, instanceID: instanceID} } } diff --git a/apps/backend/internal/sentry/mock_client_test.go b/apps/backend/internal/sentry/mock_client_test.go index a1a47155a9..f2a2551e44 100644 --- a/apps/backend/internal/sentry/mock_client_test.go +++ b/apps/backend/internal/sentry/mock_client_test.go @@ -6,9 +6,14 @@ import ( "testing" ) +// mockInstance returns a Client view of the shared mock bound to instanceID. +func mockInstance(m *MockClient, instanceID string) Client { + return MockClientFactory(m)(&SentryConfig{ID: instanceID}, "") +} + func TestMockClient_DefaultsToSuccessfulAuth(t *testing.T) { m := NewMockClient() - res, err := m.TestAuth(context.Background()) + res, err := mockInstance(m, "inst-1").TestAuth(context.Background()) if err != nil || !res.OK { t.Fatalf("expected OK=true by default, got %+v err=%v", res, err) } @@ -16,10 +21,10 @@ func TestMockClient_DefaultsToSuccessfulAuth(t *testing.T) { func TestMockClient_SearchFiltersByProject(t *testing.T) { m := NewMockClient() - m.AddIssue(&SentryIssue{ShortID: "FE-1", Title: "Boom", Level: "error", Status: "unresolved", ProjectSlug: "frontend"}) - m.AddIssue(&SentryIssue{ShortID: "BE-1", Title: "Crash", Level: "fatal", Status: "unresolved", ProjectSlug: "backend"}) + m.AddIssue("inst-1", &SentryIssue{ShortID: "FE-1", Title: "Boom", Level: "error", Status: "unresolved", ProjectSlug: "frontend"}) + m.AddIssue("inst-1", &SentryIssue{ShortID: "BE-1", Title: "Crash", Level: "fatal", Status: "unresolved", ProjectSlug: "backend"}) - res, err := m.SearchIssues(context.Background(), SearchFilter{ + res, err := mockInstance(m, "inst-1").SearchIssues(context.Background(), SearchFilter{ OrgSlug: "acme", ProjectSlug: "frontend", }, "") if err != nil { @@ -32,10 +37,11 @@ func TestMockClient_SearchFiltersByProject(t *testing.T) { func TestMockClient_SearchFiltersByLevelStatusQuery(t *testing.T) { m := NewMockClient() - m.AddIssue(&SentryIssue{ShortID: "A-1", Title: "Login failed", Level: "error", Status: "unresolved", ProjectSlug: "fe"}) - m.AddIssue(&SentryIssue{ShortID: "A-2", Title: "Signup failed", Level: "warning", Status: "unresolved", ProjectSlug: "fe"}) - m.AddIssue(&SentryIssue{ShortID: "A-3", Title: "Login broken", Level: "error", Status: "resolved", ProjectSlug: "fe"}) + m.AddIssue("inst-1", &SentryIssue{ShortID: "A-1", Title: "Login failed", Level: "error", Status: "unresolved", ProjectSlug: "fe"}) + m.AddIssue("inst-1", &SentryIssue{ShortID: "A-2", Title: "Signup failed", Level: "warning", Status: "unresolved", ProjectSlug: "fe"}) + m.AddIssue("inst-1", &SentryIssue{ShortID: "A-3", Title: "Login broken", Level: "error", Status: "resolved", ProjectSlug: "fe"}) + client := mockInstance(m, "inst-1") cases := []struct { name string filter SearchFilter @@ -48,7 +54,7 @@ func TestMockClient_SearchFiltersByLevelStatusQuery(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - res, err := m.SearchIssues(context.Background(), tc.filter, "") + res, err := client.SearchIssues(context.Background(), tc.filter, "") if err != nil { t.Fatalf("search: %v", err) } @@ -65,42 +71,60 @@ func TestMockClient_SearchFiltersByLevelStatusQuery(t *testing.T) { func TestMockClient_GetIssueByShortIDOrNumeric(t *testing.T) { m := NewMockClient() - m.AddIssue(&SentryIssue{ID: "99", ShortID: "PROJ-1", Title: "x"}) - if _, err := m.GetIssue(context.Background(), "PROJ-1"); err != nil { + m.AddIssue("inst-1", &SentryIssue{ID: "99", ShortID: "PROJ-1", Title: "x"}) + client := mockInstance(m, "inst-1") + if _, err := client.GetIssue(context.Background(), "PROJ-1"); err != nil { t.Errorf("short id lookup failed: %v", err) } - if _, err := m.GetIssue(context.Background(), "99"); err != nil { + if _, err := client.GetIssue(context.Background(), "99"); err != nil { t.Errorf("numeric id lookup failed: %v", err) } - if _, err := m.GetIssue(context.Background(), "missing"); err == nil { + if _, err := client.GetIssue(context.Background(), "missing"); err == nil { t.Error("expected error on missing id") } } func TestMockClient_GetIssueErrorOverride(t *testing.T) { m := NewMockClient() - m.AddIssue(&SentryIssue{ShortID: "PROJ-1"}) - m.SetGetIssueError(&APIError{StatusCode: http.StatusInternalServerError, Message: "boom"}) - if _, err := m.GetIssue(context.Background(), "PROJ-1"); err == nil { + m.AddIssue("inst-1", &SentryIssue{ShortID: "PROJ-1"}) + m.SetGetIssueError("inst-1", &APIError{StatusCode: http.StatusInternalServerError, Message: "boom"}) + if _, err := mockInstance(m, "inst-1").GetIssue(context.Background(), "PROJ-1"); err == nil { t.Error("expected forced error") } } func TestMockClient_Reset(t *testing.T) { m := NewMockClient() - m.AddIssue(&SentryIssue{ShortID: "PROJ-1"}) - m.SetProjects([]SentryProject{{Slug: "fe"}}) + m.AddIssue("inst-1", &SentryIssue{ShortID: "PROJ-1"}) + m.SetProjects("inst-1", []SentryProject{{Slug: "fe"}}) m.Reset() - res, _ := m.SearchIssues(context.Background(), SearchFilter{OrgSlug: "x"}, "") + client := mockInstance(m, "inst-1") + res, _ := client.SearchIssues(context.Background(), SearchFilter{OrgSlug: "x"}, "") if len(res.Issues) != 0 { t.Error("expected issues cleared") } - projects, _ := m.ListProjects(context.Background()) + projects, _ := client.ListProjects(context.Background()) if len(projects) != 0 { t.Error("expected projects cleared") } } +// TestMockClient_InstanceIsolation proves two instances hold independent data. +func TestMockClient_InstanceIsolation(t *testing.T) { + m := NewMockClient() + m.AddIssue("inst-a", &SentryIssue{ShortID: "A-1", Title: "from A", ProjectSlug: "fe"}) + m.AddIssue("inst-b", &SentryIssue{ShortID: "B-1", Title: "from B", ProjectSlug: "fe"}) + + aRes, _ := mockInstance(m, "inst-a").SearchIssues(context.Background(), SearchFilter{OrgSlug: "acme"}, "") + bRes, _ := mockInstance(m, "inst-b").SearchIssues(context.Background(), SearchFilter{OrgSlug: "acme"}, "") + if len(aRes.Issues) != 1 || aRes.Issues[0].ShortID != "A-1" { + t.Errorf("instance A leaked/missing data: %+v", aRes.Issues) + } + if len(bRes.Issues) != 1 || bRes.Issues[0].ShortID != "B-1" { + t.Errorf("instance B leaked/missing data: %+v", bRes.Issues) + } +} + func sameStrings(a, b []string) bool { if len(a) != len(b) { return false diff --git a/apps/backend/internal/sentry/mock_controller.go b/apps/backend/internal/sentry/mock_controller.go index 43414ada2e..d00dd425f5 100644 --- a/apps/backend/internal/sentry/mock_controller.go +++ b/apps/backend/internal/sentry/mock_controller.go @@ -1,7 +1,9 @@ package sentry import ( + "errors" "net/http" + "strings" "time" "github.com/gin-gonic/gin" @@ -11,7 +13,8 @@ import ( // MockController exposes HTTP endpoints that drive the in-memory MockClient // during E2E tests. Mounted by RegisterMockRoutes only when the service was -// built with a MockClient. +// built with a MockClient. Every data endpoint is scoped to an instance via the +// `?instanceId=` query param so tests can seed distinct datasets per instance. type MockController struct { mock *MockClient store *Store @@ -36,14 +39,28 @@ func (c *MockController) RegisterRoutes(router *gin.Engine) { api.DELETE("/reset", c.reset) } +func (c *MockController) requireInstanceID(ctx *gin.Context) (string, bool) { + instanceID := strings.TrimSpace(ctx.Query("instanceId")) + if instanceID == "" { + writeErr(ctx, http.StatusBadRequest, "instanceId query parameter required") + return "", false + } + return instanceID, true +} + +// setAuthResult seeds an instance's TestAuth response. instanceId is +// optional (unlike the other seed routes): TestConnectionCandidate builds a +// client for a not-yet-persisted config using the empty-string instance ID, +// so pre-save "Test connection" specs must be able to seed that dataset too. func (c *MockController) setAuthResult(ctx *gin.Context) { var req TestConnectionResult if err := ctx.ShouldBindJSON(&req); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) + writeBadPayload(ctx) return } + instanceID := strings.TrimSpace(ctx.Query("instanceId")) r := req - c.mock.SetAuthResult(&r) + c.mock.SetAuthResult(instanceID, &r) ctx.JSON(http.StatusOK, gin.H{"set": true}) } @@ -53,18 +70,19 @@ func (c *MockController) setAuthHealth(ctx *gin.Context) { Error string `json:"error"` } if err := ctx.ShouldBindJSON(&req); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) + writeBadPayload(ctx) return } - workspaceID := ctx.Query("workspace_id") - var err error - if workspaceID == "" { - err = c.store.UpdateAuthHealth(ctx.Request.Context(), req.OK, req.Error, time.Now().UTC()) - } else { - err = c.store.UpdateAuthHealthForWorkspace(ctx.Request.Context(), workspaceID, req.OK, req.Error, time.Now().UTC()) + instanceID, ok := c.requireInstanceID(ctx) + if !ok { + return } - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + if err := c.store.UpdateAuthHealthForInstance(ctx.Request.Context(), instanceID, req.OK, req.Error, time.Now().UTC()); err != nil { + if errors.Is(err, ErrInstanceNotFound) { + writeErr(ctx, http.StatusNotFound, err.Error()) + return + } + writeErr(ctx, http.StatusInternalServerError, err.Error()) return } ctx.JSON(http.StatusOK, gin.H{"set": true}) @@ -75,10 +93,14 @@ func (c *MockController) setOrganizations(ctx *gin.Context) { Organizations []SentryOrganization `json:"organizations"` } if err := ctx.ShouldBindJSON(&req); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) + writeBadPayload(ctx) return } - c.mock.SetOrganizations(req.Organizations) + instanceID, ok := c.requireInstanceID(ctx) + if !ok { + return + } + c.mock.SetOrganizations(instanceID, req.Organizations) ctx.JSON(http.StatusOK, gin.H{"count": len(req.Organizations)}) } @@ -87,10 +109,14 @@ func (c *MockController) setProjects(ctx *gin.Context) { Projects []SentryProject `json:"projects"` } if err := ctx.ShouldBindJSON(&req); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) + writeBadPayload(ctx) return } - c.mock.SetProjects(req.Projects) + instanceID, ok := c.requireInstanceID(ctx) + if !ok { + return + } + c.mock.SetProjects(instanceID, req.Projects) ctx.JSON(http.StatusOK, gin.H{"count": len(req.Projects)}) } @@ -99,11 +125,15 @@ func (c *MockController) addIssues(ctx *gin.Context) { Issues []SentryIssue `json:"issues"` } if err := ctx.ShouldBindJSON(&req); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) + writeBadPayload(ctx) + return + } + instanceID, ok := c.requireInstanceID(ctx) + if !ok { return } for i := range req.Issues { - c.mock.AddIssue(&req.Issues[i]) + c.mock.AddIssue(instanceID, &req.Issues[i]) } ctx.JSON(http.StatusOK, gin.H{"added": len(req.Issues)}) } @@ -114,13 +144,17 @@ func (c *MockController) setGetIssueError(ctx *gin.Context) { Message string `json:"message"` } if err := ctx.ShouldBindJSON(&req); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) + writeBadPayload(ctx) + return + } + instanceID, ok := c.requireInstanceID(ctx) + if !ok { return } if req.StatusCode == 0 { - c.mock.SetGetIssueError(nil) + c.mock.SetGetIssueError(instanceID, nil) } else { - c.mock.SetGetIssueError(&APIError{StatusCode: req.StatusCode, Message: req.Message}) + c.mock.SetGetIssueError(instanceID, &APIError{StatusCode: req.StatusCode, Message: req.Message}) } ctx.JSON(http.StatusOK, gin.H{"set": true}) } diff --git a/apps/backend/internal/sentry/mock_controller_test.go b/apps/backend/internal/sentry/mock_controller_test.go new file mode 100644 index 0000000000..fdca351dc6 --- /dev/null +++ b/apps/backend/internal/sentry/mock_controller_test.go @@ -0,0 +1,101 @@ +package sentry + +import ( + "net/http" + "testing" + + "github.com/gin-gonic/gin" + + "github.com/kandev/kandev/internal/common/logger" +) + +func TestMockController_SeedRoutesRequireInstanceID(t *testing.T) { + gin.SetMode(gin.TestMode) + router := gin.New() + ctrl := NewMockController(NewMockClient(), newTestStore(t), logger.Default()) + ctrl.RegisterRoutes(router) + + for _, tc := range []struct { + name string + method string + target string + body string + }{ + { + name: "auth health", + method: http.MethodPut, + target: "/api/v1/sentry/mock/auth-health", + body: `{"ok":true}`, + }, + { + name: "organizations", + method: http.MethodPost, + target: "/api/v1/sentry/mock/organizations", + body: `{"organizations":[]}`, + }, + { + name: "projects", + method: http.MethodPost, + target: "/api/v1/sentry/mock/projects", + body: `{"projects":[]}`, + }, + { + name: "issues", + method: http.MethodPost, + target: "/api/v1/sentry/mock/issues", + body: `{"issues":[]}`, + }, + { + name: "get issue error", + method: http.MethodPut, + target: "/api/v1/sentry/mock/get-issue-error", + body: `{"statusCode":500,"message":"upstream failed"}`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + resp := do(router, tc.method, tc.target, tc.body) + if resp.Code != http.StatusBadRequest { + t.Errorf("status = %d, want 400; body=%s", resp.Code, resp.Body.String()) + } + }) + } +} + +// TestMockController_SetAuthResult_AllowsEmptyInstanceID pins the pre-save +// "Test connection" flow: TestConnectionCandidate builds a client for a +// not-yet-persisted config (empty instance ID), so E2E specs must be able to +// seed that empty-ID dataset via /mock/auth-result without an instanceId. +func TestMockController_SetAuthResult_AllowsEmptyInstanceID(t *testing.T) { + gin.SetMode(gin.TestMode) + router := gin.New() + mock := NewMockClient() + ctrl := NewMockController(mock, newTestStore(t), logger.Default()) + ctrl.RegisterRoutes(router) + + resp := do(router, http.MethodPut, "/api/v1/sentry/mock/auth-result", `{"ok":false,"error":"invalid token"}`) + if resp.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body=%s", resp.Code, resp.Body.String()) + } + result, err := mock.testAuth("") + if err != nil { + t.Fatalf("test auth: %v", err) + } + if result.OK || result.Error != "invalid token" { + t.Errorf("candidate auth result = %+v, want seeded failure", result) + } +} + +// TestMockController_SetAuthHealth_MissingInstance404 pins the P2 fix: seeding +// auth-health for a missing/misspelled instance returns 404 (not {set:true}), +// so E2E seeding fails fast instead of silently succeeding. +func TestMockController_SetAuthHealth_MissingInstance404(t *testing.T) { + gin.SetMode(gin.TestMode) + router := gin.New() + ctrl := NewMockController(NewMockClient(), newTestStore(t), logger.Default()) + ctrl.RegisterRoutes(router) + + resp := do(router, http.MethodPut, "/api/v1/sentry/mock/auth-health?instanceId=ghost", `{"ok":true}`) + if resp.Code != http.StatusNotFound { + t.Errorf("status = %d, want 404; body=%s", resp.Code, resp.Body.String()) + } +} diff --git a/apps/backend/internal/sentry/models.go b/apps/backend/internal/sentry/models.go index f12669af70..de43db0c87 100644 --- a/apps/backend/internal/sentry/models.go +++ b/apps/backend/internal/sentry/models.go @@ -1,6 +1,9 @@ -// Package sentry implements the Sentry integration (Phase 1: configure + browse). -// A single install-wide configuration, a REST client for projects and issues, -// and the HTTP handlers that expose these capabilities to the frontend. +// Package sentry implements the Sentry integration: multiple named Sentry +// instances per workspace, a REST client for projects and issues, and the HTTP +// handlers that expose these capabilities to the frontend. Each workspace may +// hold several instances (e.g. a SaaS org plus a self-hosted host); every +// instance carries its own URL + token + auth-health, and issue-watches bind to +// exactly one instance. package sentry import ( @@ -9,24 +12,40 @@ import ( "github.com/kandev/kandev/internal/integrations/optional" ) -// AuthMethodAuthToken is the only auth method Sentry supports in Phase 1: a -// user or organization auth token sent as `Authorization: Bearer `. +// AuthMethodAuthToken is the only auth method Sentry supports: a user or +// organization auth token sent as `Authorization: Bearer `. const AuthMethodAuthToken = "auth_token" -// SecretKey is the legacy secret-store key used for the old install-wide Sentry -// token. New workspace-scoped configs use SecretKeyForWorkspace. +// SecretKey is the legacy secret-store key used for the pre-workspace +// install-wide Sentry token. Retained for the boot migration only. const SecretKey = "sentry:singleton:token" -// SecretKeyForWorkspace returns the workspace-scoped Sentry secret key. +// SecretKeyForWorkspace returns the workspace-scoped Sentry secret key used by +// the (now superseded) one-config-per-workspace model. Retained for the boot +// migration only; live reads/writes use secretKeyForInstance. func SecretKeyForWorkspace(workspaceID string) string { return "sentry:" + workspaceID + ":token" } -// SentryConfig is the workspace-scoped configuration for the Sentry -// integration. The token is stored separately in the encrypted secret store. +// secretKeyForInstance returns the per-instance Sentry secret key. The +// "instance:" segment keeps this namespace disjoint from the legacy +// singleton/workspace keys so a workspace UUID can never collide with an +// instance UUID. +func secretKeyForInstance(instanceID string) string { + return "sentry:instance:" + instanceID + ":token" +} + +// SentryConfig is a single named Sentry instance within a workspace. The token +// is stored separately in the encrypted secret store under +// secretKeyForInstance(ID). type SentryConfig struct { - WorkspaceID string `json:"workspaceId,omitempty" db:"workspace_id"` - AuthMethod string `json:"authMethod" db:"auth_method"` + // ID is the instance UUID, stable for the life of the instance and used as + // the secret key, the client-cache key, and the watch foreign key. + ID string `json:"id" db:"id"` + WorkspaceID string `json:"workspaceId" db:"workspace_id"` + // Name is the user-facing label, required and unique within a workspace. + Name string `json:"name" db:"name"` + AuthMethod string `json:"authMethod" db:"auth_method"` // URL is the base URL of the Sentry instance (e.g. https://sentry.io for // SaaS, or a self-hosted host). The REST client appends /api/0. Defaults // to the sentry.io SaaS endpoint when left blank. @@ -42,17 +61,36 @@ type SentryConfig struct { UpdatedAt time.Time `json:"updatedAt" db:"updated_at"` } -// SetConfigRequest is the payload sent by the UI to create or update the -// Sentry configuration. When Secret is empty on update, the existing secret -// is retained; when non-empty it replaces the stored value. -type SetConfigRequest struct { - AuthMethod string `json:"authMethod"` +// CreateConfigRequest is the payload sent by the UI to create a new Sentry +// instance in a workspace. +type CreateConfigRequest struct { + WorkspaceID string `json:"workspaceId"` + Name string `json:"name"` + AuthMethod string `json:"authMethod"` // URL is the Sentry instance base URL. Optional: blank defaults to the - // sentry.io SaaS endpoint, preserving the prior single-tenant behavior. + // sentry.io SaaS endpoint. URL string `json:"url"` Secret string `json:"secret"` } +// UpdateConfigRequest updates an existing instance identified by its ID. When +// Secret is empty the existing secret is retained; when non-empty it replaces +// the stored value. Name/URL/AuthMethod replace the stored values. +type UpdateConfigRequest struct { + Name string `json:"name"` + AuthMethod string `json:"authMethod"` + URL string `json:"url"` + Secret string `json:"secret"` +} + +// CopyConfigRequest copies every instance from SourceWorkspaceID into +// TargetWorkspaceID: fresh instance IDs, secrets copied under the new keys, +// names deduped, no watches carried over. +type CopyConfigRequest struct { + SourceWorkspaceID string `json:"sourceWorkspaceId"` + TargetWorkspaceID string `json:"targetWorkspaceId"` +} + // TestConnectionResult reports what the backend learned when pinging Sentry // with the supplied credentials. type TestConnectionResult struct { @@ -138,10 +176,15 @@ const ( // whenever a new matching issue appears. Mirrors the Linear/Jira shape so the // orchestrator's WatcherSource pipeline applies uniformly. type IssueWatch struct { - ID string `json:"id" db:"id"` - WorkspaceID string `json:"workspaceId" db:"workspace_id"` - WorkflowID string `json:"workflowId" db:"workflow_id"` - WorkflowStepID string `json:"workflowStepId" db:"workflow_step_id"` + ID string `json:"id" db:"id"` + WorkspaceID string `json:"workspaceId" db:"workspace_id"` + // SentryInstanceID binds the watch to exactly one Sentry instance. Empty = + // legacy unbound watch (stored as SQL NULL); the poller resolves an unbound + // watch to the workspace's sole instance at poll time. Immutable once set: + // changing instance means creating a new watch. + SentryInstanceID string `json:"sentryInstanceId" db:"-"` + WorkflowID string `json:"workflowId" db:"workflow_id"` + WorkflowStepID string `json:"workflowStepId" db:"workflow_step_id"` // RepositoryID optionally binds watcher-created tasks to a repository so the // agent launches in an isolated worktree of that repo instead of a blank // scratch checkout. Empty = unbound, which preserves the historical @@ -188,10 +231,14 @@ type IssueWatchTask struct { // issue matching a watch that has no existing dedup row. The orchestrator // consumes this to create (and optionally auto-start) a Kandev task. type NewSentryIssueEvent struct { - IssueWatchID string `json:"issueWatchId"` - WorkspaceID string `json:"workspaceId"` - WorkflowID string `json:"workflowId"` - WorkflowStepID string `json:"workflowStepId"` + IssueWatchID string `json:"issueWatchId"` + WorkspaceID string `json:"workspaceId"` + // SentryInstanceID is the instance the originating watch is bound to (empty + // for a migrated legacy watch resolved to its workspace's sole instance). + // Carried onto the created task's metadata for traceability. + SentryInstanceID string `json:"sentryInstanceId,omitempty"` + WorkflowID string `json:"workflowId"` + WorkflowStepID string `json:"workflowStepId"` // RepositoryID / BaseBranch carry the watch's optional repository binding so // the orchestrator source can populate IssueTaskRequest.Repositories without // reloading the watch row. Empty RepositoryID = unbound (repo-less task). @@ -209,7 +256,10 @@ type NewSentryIssueEvent struct { // CreateIssueWatchRequest is the payload for POST /api/v1/sentry/watches/issue. type CreateIssueWatchRequest struct { - WorkspaceID string `json:"workspaceId"` + WorkspaceID string `json:"workspaceId"` + // SentryInstanceID binds the watch to a Sentry instance. Required and must + // belong to WorkspaceID. Immutable after creation. + SentryInstanceID string `json:"sentryInstanceId"` WorkflowID string `json:"workflowId"` WorkflowStepID string `json:"workflowStepId"` RepositoryID string `json:"repositoryId"` @@ -225,6 +275,8 @@ type CreateIssueWatchRequest struct { // UpdateIssueWatchRequest is the payload for PATCH /api/v1/sentry/watches/issue/:id. // All fields are pointers so the caller can omit ones it doesn't want to change. +// Note: the bound Sentry instance is deliberately absent — instance binding is +// immutable, so changing it means creating a new watch. type UpdateIssueWatchRequest struct { WorkflowID *string `json:"workflowId,omitempty"` WorkflowStepID *string `json:"workflowStepId,omitempty"` diff --git a/apps/backend/internal/sentry/poller.go b/apps/backend/internal/sentry/poller.go index dcf5b4d965..28b742de91 100644 --- a/apps/backend/internal/sentry/poller.go +++ b/apps/backend/internal/sentry/poller.go @@ -134,10 +134,12 @@ func (p *Poller) checkIssueWatches(ctx context.Context) { if !isIssueWatchDue(w, time.Now()) { continue } - newIssues, err := p.service.CheckIssueWatch(ctx, w) + instanceID, newIssues, err := p.service.CheckIssueWatch(ctx, w) if err != nil { p.logger.Warn("sentry poller: check issue watch failed", - zap.String("watch_id", w.ID), zap.Error(err)) + zap.String("watch_id", w.ID), + zap.String("instance_id", instanceID), + zap.Error(err)) continue } for _, issue := range newIssues { @@ -145,7 +147,7 @@ func (p *Poller) checkIssueWatches(ctx context.Context) { zap.String("watch_id", w.ID), zap.String("short_id", issue.ShortID), zap.String("title", issue.Title)) - p.service.publishNewSentryIssueEvent(ctx, w, issue) + p.service.publishNewSentryIssueEvent(ctx, w, instanceID, issue) } } } diff --git a/apps/backend/internal/sentry/poller_issue_watch_test.go b/apps/backend/internal/sentry/poller_issue_watch_test.go index 86dc23237d..7acd0a753f 100644 --- a/apps/backend/internal/sentry/poller_issue_watch_test.go +++ b/apps/backend/internal/sentry/poller_issue_watch_test.go @@ -105,6 +105,53 @@ func TestPoller_CheckIssueWatches_PublishesNewIssuesOnly(t *testing.T) { } } +// TestPoller_CheckIssueWatches_PublishesResolvedInstanceIDForUnboundWatch pins +// the fix for the bug where CheckIssueWatch resolves the instance actually +// polled (via resolveWatchInstanceID) but publishNewSentryIssueEvent read +// w.SentryInstanceID directly, leaving NewSentryIssueEvent.SentryInstanceID +// empty for every unbound legacy watch. The published event must carry the +// resolved instance, not the watch's raw (possibly empty) SentryInstanceID. +func TestPoller_CheckIssueWatches_PublishesResolvedInstanceIDForUnboundWatch(t *testing.T) { + f := newPollerFixture(t) + ctx := context.Background() + cfg := f.saveConfigForWorkspace(t, "ws-1", "tok") // workspace's sole instance + + eb := bus.NewMemoryEventBus(logger.Default()) + defer eb.Close() + f.svc.SetEventBus(eb) + + sub, err := newRecordingSubscriber(eb, 1) + if err != nil { + t.Fatalf("subscribe: %v", err) + } + + w := newTestIssueWatch("ws-1") // unbound: SentryInstanceID left empty + if w.SentryInstanceID != "" { + t.Fatalf("expected unbound watch, got instance %q", w.SentryInstanceID) + } + if err := f.store.CreateIssueWatch(ctx, w); err != nil { + t.Fatalf("create watch: %v", err) + } + + f.client.searchIssuesFn = func(_ SearchFilter, _ string) (*SearchResult, error) { + return &SearchResult{ + Issues: []SentryIssue{{ShortID: "PROJ-1", Title: "first", Permalink: "https://sentry.io/issues/PROJ-1"}}, + IsLast: true, + }, nil + } + + f.poller.checkIssueWatches(ctx) + + <-sub.done + got := sub.snapshot() + if len(got) != 1 { + t.Fatalf("expected 1 published event, got %d", len(got)) + } + if got[0].SentryInstanceID != cfg.ID { + t.Errorf("published event SentryInstanceID = %q, want resolved instance %q", got[0].SentryInstanceID, cfg.ID) + } +} + func TestPoller_CheckIssueWatches_SkipsDisabled(t *testing.T) { f := newPollerFixture(t) ctx := context.Background() diff --git a/apps/backend/internal/sentry/poller_test.go b/apps/backend/internal/sentry/poller_test.go index ad9c063184..ddcc7f589d 100644 --- a/apps/backend/internal/sentry/poller_test.go +++ b/apps/backend/internal/sentry/poller_test.go @@ -30,60 +30,78 @@ func newPollerFixture(t *testing.T) *pollerFixture { return f } -// saveConfig persists the default workspace directly via store + secret fakes, -// bypassing Service.SetConfig (and its async probe). -func (f *pollerFixture) saveConfig(t *testing.T, secret string) { +// saveConfig seeds a single instance in a default workspace, bypassing +// Service.CreateInstance (and its async probe). Returns the seeded instance. +func (f *pollerFixture) saveConfig(t *testing.T, secret string) *SentryConfig { t.Helper() - f.saveConfigForWorkspace(t, "", secret) + return f.saveConfigForWorkspace(t, "ws-1", secret) } -// saveConfigForWorkspace persists a workspace config directly via store + -// secret fakes, bypassing Service.SetConfig (and its async probe). -func (f *pollerFixture) saveConfigForWorkspace(t *testing.T, workspaceID, secret string) { +// saveConfigForWorkspace seeds one instance (+ secret) in a workspace, so an +// unbound watch in that workspace resolves to it at poll time. +func (f *pollerFixture) saveConfigForWorkspace(t *testing.T, workspaceID, secret string) *SentryConfig { t.Helper() ctx := context.Background() - if err := f.store.UpsertConfigForWorkspace(ctx, workspaceID, &SentryConfig{AuthMethod: AuthMethodAuthToken}); err != nil { + cfg := &SentryConfig{WorkspaceID: workspaceID, Name: "Primary", AuthMethod: AuthMethodAuthToken, URL: DefaultSentryURL} + if err := f.store.CreateInstance(ctx, cfg); err != nil { t.Fatalf("save config: %v", err) } - key := SecretKey - if workspaceID != "" { - key = SecretKeyForWorkspace(workspaceID) - } - if err := f.secrets.Set(ctx, key, "sentry", secret); err != nil { - t.Fatalf("save secret: %v", err) + if secret != "" { + if err := f.secrets.Set(ctx, secretKeyForInstance(cfg.ID), "sentry", secret); err != nil { + t.Fatalf("save secret: %v", err) + } } + return cfg } func TestService_RecordAuthHealth_Success(t *testing.T) { f := newPollerFixture(t) - f.saveConfig(t, "tok") + cfg := f.saveConfig(t, "tok") f.client.testAuthFn = func() (*TestConnectionResult, error) { return &TestConnectionResult{OK: true}, nil } f.svc.RecordAuthHealth(context.Background()) - cfg, _ := f.store.GetConfig(context.Background()) - if cfg == nil || !cfg.LastOk { - t.Errorf("expected LastOk=true, got %+v", cfg) + got, _ := f.store.GetInstance(context.Background(), cfg.ID) + if got == nil || !got.LastOk { + t.Errorf("expected LastOk=true, got %+v", got) } } func TestService_RecordAuthHealth_Failure(t *testing.T) { f := newPollerFixture(t) - f.saveConfig(t, "tok") + cfg := f.saveConfig(t, "tok") f.client.testAuthFn = func() (*TestConnectionResult, error) { return &TestConnectionResult{OK: false, Error: "401 unauthorized"}, nil } f.svc.RecordAuthHealth(context.Background()) - cfg, _ := f.store.GetConfig(context.Background()) - if cfg.LastOk { + got, _ := f.store.GetInstance(context.Background(), cfg.ID) + if got.LastOk { t.Error("expected LastOk=false") } - if cfg.LastError != "401 unauthorized" { - t.Errorf("expected error preserved, got %q", cfg.LastError) + if got.LastError != "401 unauthorized" { + t.Errorf("expected error preserved, got %q", got.LastError) + } +} + +// TestService_RecordAuthHealth_MultipleInstances verifies the bounded worker +// pool probes every instance, not just one. +func TestService_RecordAuthHealth_MultipleInstances(t *testing.T) { + f := newPollerFixture(t) + a := f.saveConfigForWorkspace(t, "ws-1", "tok-a") + b := f.saveConfigForWorkspace(t, "ws-2", "tok-b") + f.client.testAuthFn = func() (*TestConnectionResult, error) { + return &TestConnectionResult{OK: true}, nil + } + f.svc.RecordAuthHealth(context.Background()) + for _, id := range []string{a.ID, b.ID} { + got, _ := f.store.GetInstance(context.Background(), id) + if got == nil || !got.LastOk { + t.Errorf("instance %s not probed: %+v", id, got) + } } } diff --git a/apps/backend/internal/sentry/provider.go b/apps/backend/internal/sentry/provider.go index d6c4c2ed61..170d481671 100644 --- a/apps/backend/internal/sentry/provider.go +++ b/apps/backend/internal/sentry/provider.go @@ -21,9 +21,9 @@ func MockEnabled() bool { return os.Getenv(mockEnvVar) == "true" } -// Provide builds the Sentry service. eventBus is used by the Phase 2 issue -// watcher to publish NewSentryIssueEvent for the orchestrator to consume. -// Cleanup is a no-op — the service holds only in-memory client caches. +// Provide builds the Sentry service. eventBus is used by the issue watcher to +// publish NewSentryIssueEvent for the orchestrator to consume. Cleanup is a +// no-op — the service holds only in-memory client caches. // // When KANDEV_MOCK_SENTRY=true, the service is wired to a process-wide // MockClient and the same instance is exposed via Service.MockClient() so the @@ -33,7 +33,11 @@ func Provide(writer, reader *sqlx.DB, secrets SecretStore, eventBus bus.EventBus if err != nil { return nil, nil, err } + // Two-stage secret migration mirroring the schema migration lineage: + // singleton→workspace key (kept from PR #1572), then workspace/singleton + // key→per-instance key for the multi-instance model. migrateLegacySecret(store, secrets, log) + migrateInstanceSecrets(store, secrets, log) clientFn := DefaultClientFactory var mock *MockClient if MockEnabled() { @@ -50,6 +54,10 @@ func Provide(writer, reader *sqlx.DB, secrets SecretStore, eventBus bus.EventBus return svc, cleanup, nil } +// migrateLegacySecret rekeys the pre-workspace install-wide token from the +// singleton secret key to the workspace key that received the migrated config +// row. Retained from the workspace-scoped model so the subsequent per-instance +// rekey has a workspace key to read. func migrateLegacySecret(store *Store, secrets SecretStore, log *logger.Logger) { target := store.MigratedFromWorkspace() if target == "" || secrets == nil { @@ -74,6 +82,146 @@ func migrateLegacySecret(store *Store, secrets SecretStore, log *logger.Logger) } } +// migrateInstanceSecrets rekeys a legacy workspace token only to the earliest +// (oldest by creation) instance in that workspace. The pre-instance schema +// allowed exactly one config per workspace, so that oldest instance is the +// migration's true target; a later second instance must never inherit the +// old token. Eligibility keys off creation order rather than current +// workspace cardinality, so a transient secret-store failure on the oldest +// instance's own rekey can still be retried on a later restart even after a +// second instance has since been added to the same workspace. Completed +// rekeys remove the legacy keys; cardinality guards also make a restart safe +// if a cleanup attempt previously failed. +func migrateInstanceSecrets(store *Store, secrets SecretStore, log *logger.Logger) { + if secrets == nil { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + instances, err := store.ListAllInstances(ctx) + if err != nil { + log.Warn("sentry: list instances for secret migration failed", zap.Error(err)) + return + } + oldestPerWorkspace := oldestInstanceIDPerWorkspace(instances) + allowSingleton := len(instances) == 1 + for _, inst := range instances { + if oldestPerWorkspace[inst.WorkspaceID] != inst.ID { + continue + } + rekeyInstanceSecret(ctx, secrets, inst, allowSingleton, log) + } + cleanupLegacyInstanceSecretKeys(ctx, secrets, instances, log) +} + +// oldestInstanceIDPerWorkspace returns, for each workspace, the ID of its +// earliest-created instance — the only instance ever eligible to inherit that +// workspace's legacy pre-instance secret. Ties (identical CreatedAt) resolve +// by the lexicographically smaller ID so the choice is deterministic. +func oldestInstanceIDPerWorkspace(instances []*SentryConfig) map[string]string { + oldest := make(map[string]*SentryConfig, len(instances)) + for _, inst := range instances { + cur, ok := oldest[inst.WorkspaceID] + if !ok || inst.CreatedAt.Before(cur.CreatedAt) || + (inst.CreatedAt.Equal(cur.CreatedAt) && inst.ID < cur.ID) { + oldest[inst.WorkspaceID] = inst + } + } + out := make(map[string]string, len(oldest)) + for workspaceID, inst := range oldest { + out[workspaceID] = inst.ID + } + return out +} + +func rekeyInstanceSecret(ctx context.Context, secrets SecretStore, inst *SentryConfig, allowSingleton bool, log *logger.Logger) { + instanceKey := secretKeyForInstance(inst.ID) + exists, err := secrets.Exists(ctx, instanceKey) + if err != nil { + log.Warn("sentry: instance secret existence check failed", + zap.String("instance_id", inst.ID), zap.Error(err)) + return + } + if exists { + return + } + value := revealLegacySecret(ctx, secrets, inst.WorkspaceID, allowSingleton) + if value == "" { + return + } + if err := secrets.Set(ctx, instanceKey, "Sentry auth token", value); err != nil { + log.Warn("sentry: instance secret migration failed", + zap.String("instance_id", inst.ID), zap.Error(err)) + } +} + +// cleanupLegacyInstanceSecretKeys deletes a workspace key only after every +// instance in that workspace has an instance-scoped key. The global singleton +// key is likewise removed only after every instance has been rekeyed. +func cleanupLegacyInstanceSecretKeys(ctx context.Context, secrets SecretStore, instances []*SentryConfig, log *logger.Logger) { + workspaceComplete := make(map[string]bool, len(instances)) + allComplete := len(instances) > 0 + for _, inst := range instances { + if _, ok := workspaceComplete[inst.WorkspaceID]; !ok { + workspaceComplete[inst.WorkspaceID] = true + } + exists, err := secrets.Exists(ctx, secretKeyForInstance(inst.ID)) + if err != nil { + log.Warn("sentry: instance secret existence check failed during legacy cleanup", + zap.String("instance_id", inst.ID), zap.Error(err)) + workspaceComplete[inst.WorkspaceID] = false + allComplete = false + continue + } + if !exists { + workspaceComplete[inst.WorkspaceID] = false + allComplete = false + } + } + for workspaceID, complete := range workspaceComplete { + if complete { + deleteLegacySecret(ctx, secrets, SecretKeyForWorkspace(workspaceID), log) + } + } + if allComplete { + deleteLegacySecret(ctx, secrets, SecretKey, log) + } +} + +func deleteLegacySecret(ctx context.Context, secrets SecretStore, key string, log *logger.Logger) { + exists, err := secrets.Exists(ctx, key) + if err != nil { + log.Warn("sentry: legacy secret existence check failed", zap.String("secret_key", key), zap.Error(err)) + return + } + if !exists { + return + } + if err := secrets.Delete(ctx, key); err != nil { + log.Warn("sentry: legacy secret cleanup failed", zap.String("secret_key", key), zap.Error(err)) + } +} + +// revealLegacySecret reads the pre-instance token for a workspace. The +// install-wide singleton is considered only when it has one unambiguous +// instance destination; live reads use secretKeyForInstance only. +func revealLegacySecret(ctx context.Context, secrets SecretStore, workspaceID string, allowSingleton bool) string { + keys := []string{SecretKeyForWorkspace(workspaceID)} + if allowSingleton { + keys = append(keys, SecretKey) + } + for _, key := range keys { + exists, err := secrets.Exists(ctx, key) + if err != nil || !exists { + continue + } + if value, err := secrets.Reveal(ctx, key); err == nil && value != "" { + return value + } + } + return "" +} + // RegisterMockRoutes mounts the mock control routes when the service was built // with a MockClient. No-op otherwise. func RegisterMockRoutes(router *gin.Engine, svc *Service, log *logger.Logger) { diff --git a/apps/backend/internal/sentry/service.go b/apps/backend/internal/sentry/service.go index 33bba20acf..8d8b71e984 100644 --- a/apps/backend/internal/sentry/service.go +++ b/apps/backend/internal/sentry/service.go @@ -33,19 +33,44 @@ type RepositoryLookup interface { GetRepository(ctx context.Context, id string) (workspaceID, defaultBranch string, ok bool) } -// Service orchestrates Sentry config storage, the cached client, and the -// browse operations used by the HTTP handlers. +// ErrInvalidConfig is returned when a create/update request fails validation. +var ErrInvalidConfig = errors.New("sentry: invalid configuration") + +// ErrInstanceNotFound is returned when an instance ID does not exist or does +// not belong to the requesting workspace. Callers map this to HTTP 404. +var ErrInstanceNotFound = errors.New("sentry: instance not found") + +// ErrInstanceRequired is returned when an operation needs an instance ID but +// none was supplied. Callers map this to HTTP 400. +var ErrInstanceRequired = errors.New("sentry: a Sentry instance must be selected") + +// ErrDuplicateInstanceName is returned when a create/update would collide with +// an existing instance name in the same workspace. Callers map this to HTTP 409. +var ErrDuplicateInstanceName = errors.New("sentry: an instance with this name already exists in this workspace") + +// ErrInstanceInUse is returned when an instance cannot be deleted because issue +// watches still reference it. WatchCount is the number of referencing watches +// (enabled + disabled). Callers map this to HTTP 409. +type ErrInstanceInUse struct{ WatchCount int } + +func (e ErrInstanceInUse) Error() string { + return fmt.Sprintf("sentry: instance is referenced by %d issue watch(es)", e.WatchCount) +} + +// Service orchestrates Sentry instance storage, the per-instance cached client, +// and the browse operations used by the HTTP handlers. type Service struct { store *Store secrets SecretStore log *logger.Logger mu sync.Mutex clientFn ClientFactory - clients map[string]Client + // clients caches one Client per instance ID. + clients map[string]Client // clientGen is incremented by invalidateClient each time a cached client - // is discarded. clientFor captures it before I/O and only stores a newly - // built client when the value is unchanged, preventing a stale client from - // clobbering a concurrent invalidation. + // is discarded. clientForInstance captures it before I/O and only stores a + // newly built client when the value is unchanged, preventing a stale client + // from clobbering a concurrent invalidation. clientGen map[string]uint64 probeHook func() // mockClient is non-nil only when Provide built the service with a MockClient. @@ -123,142 +148,214 @@ func (s *Service) Store() *Store { return s.store } -// GetConfig returns the singleton config enriched with a HasSecret flag. -func (s *Service) GetConfig(ctx context.Context) (*SentryConfig, error) { - workspaceID, err := s.defaultWorkspaceID() +// ListInstances returns every instance in a workspace, each enriched with a +// HasSecret flag. +func (s *Service) ListInstances(ctx context.Context, workspaceID string) ([]*SentryConfig, error) { + cfgs, err := s.store.ListInstances(ctx, workspaceID) if err != nil { return nil, err } - return s.GetConfigForWorkspace(ctx, workspaceID) + for _, cfg := range cfgs { + cfg.HasSecret = s.secretExists(ctx, cfg.ID) + } + return cfgs, nil } -// GetConfigForWorkspace returns a workspace config enriched with a HasSecret flag. -func (s *Service) GetConfigForWorkspace(ctx context.Context, workspaceID string) (*SentryConfig, error) { - workspaceID, err := s.normalizeWorkspaceID(workspaceID) +// GetInstance returns one instance enriched with a HasSecret flag, or +// ErrInstanceNotFound when the ID does not exist in the workspace. +func (s *Service) GetInstance(ctx context.Context, workspaceID, id string) (*SentryConfig, error) { + cfg, err := s.store.GetInstance(ctx, id) if err != nil { return nil, err } - cfg, err := s.store.GetConfigForWorkspace(ctx, workspaceID) - if err != nil || cfg == nil { - return cfg, err + if cfg == nil || cfg.WorkspaceID != workspaceID { + return nil, ErrInstanceNotFound } - if s.secrets == nil { - return cfg, nil - } - exists, existsErr := s.secretExists(ctx, workspaceID) - if existsErr != nil { - s.log.Warn("sentry: secret exists check failed", zap.Error(existsErr)) - } - cfg.HasSecret = exists + cfg.HasSecret = s.secretExists(ctx, cfg.ID) return cfg, nil } -// ErrInvalidConfig is returned by SetConfig when the request fails validation. -var ErrInvalidConfig = errors.New("sentry: invalid configuration") - -// SetConfig is upsert. An empty Secret on update keeps the existing token. -func (s *Service) SetConfig(ctx context.Context, req *SetConfigRequest) (*SentryConfig, error) { - workspaceID, err := s.defaultWorkspaceID() - if err != nil { +// CreateInstance validates the request, persists a new instance, stores the +// secret, and kicks off an async auth-health probe. +func (s *Service) CreateInstance(ctx context.Context, workspaceID string, req *CreateConfigRequest) (*SentryConfig, error) { + authMethod, instanceURL := req.AuthMethod, req.URL + if err := validateInstanceWrite(req.Name, &authMethod, &instanceURL); err != nil { return nil, err } - return s.SetConfigForWorkspace(ctx, workspaceID, req) -} - -// SetConfigForWorkspace is upsert for one workspace. An empty Secret on update -// keeps the existing token. -func (s *Service) SetConfigForWorkspace(ctx context.Context, workspaceID string, req *SetConfigRequest) (*SentryConfig, error) { - workspaceID, err := s.normalizeWorkspaceID(workspaceID) - if err != nil { + cfg := &SentryConfig{ + WorkspaceID: workspaceID, + Name: strings.TrimSpace(req.Name), + AuthMethod: authMethod, + URL: instanceURL, + } + if err := s.store.CreateInstance(ctx, cfg); err != nil { return nil, err } - if err := validateConfigRequest(req); err != nil { - return nil, fmt.Errorf("%w: %s", ErrInvalidConfig, err.Error()) - } - cfg := &SentryConfig{AuthMethod: req.AuthMethod, URL: req.URL} - if err := s.store.UpsertConfigForWorkspace(ctx, workspaceID, cfg); err != nil { - return nil, fmt.Errorf("upsert sentry config: %w", err) - } if req.Secret != "" && s.secrets != nil { - if err := s.secrets.Set(ctx, SecretKeyForWorkspace(workspaceID), "Sentry auth token", req.Secret); err != nil { - return nil, fmt.Errorf("store sentry secret: %w", err) + if err := s.secrets.Set(ctx, secretKeyForInstance(cfg.ID), "Sentry auth token", req.Secret); err != nil { + secretErr := fmt.Errorf("store sentry secret: %w", err) + if rollbackErr := s.store.DeleteInstance(context.WithoutCancel(ctx), cfg.ID); rollbackErr != nil { + s.invalidateClient(cfg.ID) + return nil, errors.Join(secretErr, fmt.Errorf("rollback created sentry instance: %w", rollbackErr)) + } + s.invalidateClient(cfg.ID) + return nil, secretErr } } - s.invalidateClient(workspaceID) - // Probe asynchronously so a slow Sentry doesn't stall the save response. - go func() { - s.RecordAuthHealthForWorkspace(context.Background(), workspaceID) - }() - return s.GetConfigForWorkspace(ctx, workspaceID) + s.invalidateClient(cfg.ID) + go s.RecordAuthHealthForInstance(context.WithoutCancel(ctx), cfg.ID) + return s.GetInstance(ctx, workspaceID, cfg.ID) } -// DeleteConfig removes both the config row and the stored secret. -func (s *Service) DeleteConfig(ctx context.Context) error { - workspaceID, err := s.defaultWorkspaceID() +// UpdateInstance validates and applies an update to an existing instance. An +// empty Secret keeps the existing token; a non-empty Secret replaces it. +func (s *Service) UpdateInstance(ctx context.Context, workspaceID, id string, req *UpdateConfigRequest) (*SentryConfig, error) { + existing, err := s.store.GetInstance(ctx, id) + if err != nil { + return nil, err + } + if existing == nil || existing.WorkspaceID != workspaceID { + return nil, ErrInstanceNotFound + } + authMethod, instanceURL := req.AuthMethod, req.URL + if err := validateInstanceWrite(req.Name, &authMethod, &instanceURL); err != nil { + return nil, err + } + previous := *existing + updated := previous + updated.Name = strings.TrimSpace(req.Name) + updated.AuthMethod = authMethod + updated.URL = instanceURL + if err := s.store.UpdateInstance(ctx, &updated); err != nil { + return nil, err + } + if req.Secret != "" && s.secrets != nil { + if err := s.secrets.Set(ctx, secretKeyForInstance(id), "Sentry auth token", req.Secret); err != nil { + secretErr := fmt.Errorf("store sentry secret: %w", err) + rollbackCtx := context.WithoutCancel(ctx) + // Re-fetch the persisted row rather than blindly restoring + // `previous`: a second UpdateInstance may have landed on this + // instance between our own row write above and this failed + // secret write. Only roll back when the row still matches + // exactly what this request wrote — otherwise restoring + // `previous` would silently discard that other write. + current, rereadErr := s.store.GetInstance(rollbackCtx, id) + switch { + case rereadErr != nil: + s.log.Warn("sentry: skipped update rollback, could not reload instance", + zap.String("instance_id", id), zap.Error(rereadErr)) + case current == nil || !instanceMetadataMatches(current, &updated): + s.log.Warn("sentry: skipped update rollback, instance changed concurrently", + zap.String("instance_id", id)) + default: + if rollbackErr := s.store.UpdateInstance(rollbackCtx, &previous); rollbackErr != nil { + s.invalidateClient(id) + return nil, errors.Join(secretErr, fmt.Errorf("rollback sentry instance update: %w", rollbackErr)) + } + } + s.invalidateClient(id) + return nil, secretErr + } + } + s.invalidateClient(id) + go s.RecordAuthHealthForInstance(context.WithoutCancel(ctx), id) + return s.GetInstance(ctx, workspaceID, id) +} + +// instanceMetadataMatches reports whether current's mutable columns — the +// ones Store.UpdateInstance persists (name, auth_method, url) — still equal +// what this request itself wrote in written. It backs UpdateInstance's +// rollback: a mismatch means a concurrent UpdateInstance landed on the same +// row since, so restoring a stale `previous` snapshot would clobber it. The +// last_* health columns are owned by the async poller and are intentionally +// excluded from the comparison. +func instanceMetadataMatches(current, written *SentryConfig) bool { + return current.Name == written.Name && + current.AuthMethod == written.AuthMethod && + current.URL == written.URL +} + +// DeleteInstance removes an instance, its secret, and its cached client. It +// refuses deletion when issue watches still reference the instance, returning +// ErrInstanceInUse with the watch count; the DB ON DELETE RESTRICT foreign key +// is the atomic net for a watch created between the count and the delete. +func (s *Service) DeleteInstance(ctx context.Context, workspaceID, id string) error { + existing, err := s.store.GetInstance(ctx, id) if err != nil { return err } - return s.DeleteConfigForWorkspace(ctx, workspaceID) -} - -// DeleteConfigForWorkspace removes both the config row and the stored secret. -func (s *Service) DeleteConfigForWorkspace(ctx context.Context, workspaceID string) error { - workspaceID, err := s.normalizeWorkspaceID(workspaceID) + if existing == nil || existing.WorkspaceID != workspaceID { + return ErrInstanceNotFound + } + count, err := s.store.CountWatchesForInstance(ctx, id) if err != nil { return err } - if err := s.store.DeleteConfigForWorkspace(ctx, workspaceID); err != nil { + // The workspace's sole instance also backs every unbound (NULL + // sentry_instance_id) watch: resolveWatchInstanceID resolves those to it at + // poll time, so deleting it would strand them. Count them as in-use too. + // When more than one instance remains, unbound watches stay resolvable, so + // they are not attributed to this delete. + instances, err := s.store.ListInstances(ctx, workspaceID) + if err != nil { + return err + } + if len(instances) == 1 { + unbound, err := s.store.CountUnboundIssueWatchesInWorkspace(ctx, workspaceID) + if err != nil { + return err + } + count += unbound + } + if count > 0 { + return ErrInstanceInUse{WatchCount: count} + } + if err := s.store.DeleteInstance(ctx, id); err != nil { + var inUse ErrInstanceInUse + if errors.As(err, &inUse) { + return ErrInstanceInUse{WatchCount: s.recountWatches(ctx, id)} + } return err } if s.secrets != nil { - if err := s.secrets.Delete(ctx, SecretKeyForWorkspace(workspaceID)); err != nil { + if err := s.secrets.Delete(ctx, secretKeyForInstance(id)); err != nil { s.log.Warn("sentry: secret delete failed", zap.Error(err)) } } - s.invalidateClient(workspaceID) + s.invalidateClient(id) return nil } -// TestConnection validates credentials either from a fresh SetConfigRequest -// (before persisting) or from the stored config (after saving). -func (s *Service) TestConnection(ctx context.Context, req *SetConfigRequest) (*TestConnectionResult, error) { - workspaceID, err := s.defaultWorkspaceID() - if err != nil { - return &TestConnectionResult{OK: false, Error: err.Error()}, nil +// recountWatches returns the current watch count for an instance, defaulting to +// 1 when the recount itself fails so the caller still reports "in use". +func (s *Service) recountWatches(ctx context.Context, instanceID string) int { + if n, err := s.store.CountWatchesForInstance(ctx, instanceID); err == nil { + return n } - return s.TestConnectionForWorkspace(ctx, workspaceID, req) + return 1 } -// TestConnectionForWorkspace validates credentials for one workspace. -func (s *Service) TestConnectionForWorkspace(ctx context.Context, workspaceID string, req *SetConfigRequest) (*TestConnectionResult, error) { - workspaceID, err := s.normalizeWorkspaceID(workspaceID) - if err != nil { +// TestConnectionCandidate validates arbitrary credentials supplied by the UI +// before they are persisted (the pre-save "Test connection" flow). +func (s *Service) TestConnectionCandidate(ctx context.Context, req *CreateConfigRequest) (*TestConnectionResult, error) { + authMethod, instanceURL := req.AuthMethod, req.URL + if err := prepareInstanceCredentials(&authMethod, &instanceURL); err != nil { return &TestConnectionResult{OK: false, Error: err.Error()}, nil } - cfg, secret, err := s.resolveCredentials(ctx, workspaceID, req) - if err != nil { - return &TestConnectionResult{OK: false, Error: err.Error()}, nil + if req.Secret == "" { + return &TestConnectionResult{OK: false, Error: "no auth token provided — paste one to test"}, nil } - client := s.clientFn(cfg, secret) - return client.TestAuth(ctx) + cfg := &SentryConfig{AuthMethod: authMethod, URL: instanceURL} + return s.clientFn(cfg, req.Secret).TestAuth(ctx) } -// ProbeAuth validates the stored credentials. -func (s *Service) ProbeAuth(ctx context.Context) (*TestConnectionResult, error) { - workspaceID, err := s.defaultWorkspaceID() - if err != nil { - return &TestConnectionResult{OK: false, Error: err.Error()}, nil +// TestInstance validates the stored credentials of an existing instance after +// resolving and ownership-checking it against the workspace. +func (s *Service) TestInstance(ctx context.Context, workspaceID, instanceID string) (*TestConnectionResult, error) { + if _, err := s.requireInstance(ctx, workspaceID, instanceID); err != nil { + return nil, err } - return s.ProbeAuthForWorkspace(ctx, workspaceID) -} - -// ProbeAuthForWorkspace validates the stored credentials for one workspace. -func (s *Service) ProbeAuthForWorkspace(ctx context.Context, workspaceID string) (*TestConnectionResult, error) { - workspaceID, err := s.normalizeWorkspaceID(workspaceID) - if err != nil { - return &TestConnectionResult{OK: false, Error: err.Error()}, nil - } - client, err := s.clientFor(ctx, workspaceID) + client, err := s.clientForInstance(ctx, instanceID) if err != nil { return &TestConnectionResult{OK: false, Error: err.Error()}, nil } @@ -271,42 +368,60 @@ const authProbeTimeout = 15 * time.Second // authHealthWriteTimeout bounds the DB write that persists the probe outcome. const authHealthWriteTimeout = 5 * time.Second -// SetProbeHook installs a callback fired at the end of each RecordAuthHealth -// call. Production code never sets this; tests use it to synchronise on probe -// completion without sleep-polling. +// authHealthPoolSize bounds concurrent per-instance probes so one instance on a +// 15s timeout cannot stall the whole poll while many instances are configured. +const authHealthPoolSize = 6 + +// SetProbeHook installs a callback fired at the end of each RecordAuthHealth / +// RecordAuthHealthForInstance call. Production code never sets this; tests use +// it to synchronise on probe completion without sleep-polling. func (s *Service) SetProbeHook(fn func()) { s.mu.Lock() defer s.mu.Unlock() s.probeHook = fn } -// RecordAuthHealth probes credentials and writes the outcome onto the row. +// RecordAuthHealth probes every instance's credentials through a bounded worker +// pool and writes each outcome onto its row. func (s *Service) RecordAuthHealth(ctx context.Context) { - workspaceIDs, err := s.store.ListConfigWorkspaceIDs(ctx) + instances, err := s.store.ListAllInstances(ctx) if err != nil { - s.log.Warn("sentry: list config workspaces failed", zap.Error(err)) + s.log.Warn("sentry: list instances for auth health failed", zap.Error(err)) return } - if len(workspaceIDs) == 0 { + if len(instances) == 0 { s.fireProbeHook() return } - for _, workspaceID := range workspaceIDs { - s.RecordAuthHealthForWorkspace(ctx, workspaceID) + sem := make(chan struct{}, authHealthPoolSize) + var wg sync.WaitGroup + for _, inst := range instances { + if ctx.Err() != nil { + break + } + wg.Add(1) + sem <- struct{}{} + go func(id string) { + defer wg.Done() + defer func() { <-sem }() + s.recordAuthHealthForInstance(ctx, id) + }(inst.ID) } + wg.Wait() + s.fireProbeHook() } -// RecordAuthHealthForWorkspace probes credentials and writes the outcome onto -// one workspace row. -func (s *Service) RecordAuthHealthForWorkspace(ctx context.Context, workspaceID string) { - workspaceID, normalizeErr := s.normalizeWorkspaceID(workspaceID) - if normalizeErr != nil { - s.log.Warn("sentry: resolve workspace for auth health failed", zap.Error(normalizeErr)) - return - } +// RecordAuthHealthForInstance probes one instance's credentials, writes the +// outcome, and fires the probe hook. +func (s *Service) RecordAuthHealthForInstance(ctx context.Context, instanceID string) { + s.recordAuthHealthForInstance(ctx, instanceID) + s.fireProbeHook() +} + +func (s *Service) recordAuthHealthForInstance(ctx context.Context, instanceID string) { probeCtx, cancel := context.WithTimeout(ctx, authProbeTimeout) defer cancel() - res, err := s.ProbeAuthForWorkspace(probeCtx, workspaceID) + res, err := s.probeInstance(probeCtx, instanceID) ok := err == nil && res != nil && res.OK errMsg := "" switch { @@ -319,10 +434,20 @@ func (s *Service) RecordAuthHealthForWorkspace(ctx context.Context, workspaceID // still record the failure. writeCtx, writeCancel := context.WithTimeout(context.Background(), authHealthWriteTimeout) defer writeCancel() - if updateErr := s.store.UpdateAuthHealthForWorkspace(writeCtx, workspaceID, ok, errMsg, time.Now().UTC()); updateErr != nil { + if updateErr := s.store.UpdateAuthHealthForInstance(writeCtx, instanceID, ok, errMsg, time.Now().UTC()); updateErr != nil { s.log.Warn("sentry: update auth health failed", zap.Error(updateErr)) } - s.fireProbeHook() +} + +// probeInstance builds the instance client and runs a TestAuth probe. A build +// failure (e.g. no secret) is reported as a non-OK result, not an error, so the +// health row records the cause. +func (s *Service) probeInstance(ctx context.Context, instanceID string) (*TestConnectionResult, error) { + client, err := s.clientForInstance(ctx, instanceID) + if err != nil { + return &TestConnectionResult{OK: false, Error: err.Error()}, nil + } + return client.TestAuth(ctx) } func (s *Service) fireProbeHook() { @@ -334,79 +459,78 @@ func (s *Service) fireProbeHook() { } } -// ListOrganizations returns the organizations the stored token can access. -func (s *Service) ListOrganizations(ctx context.Context) ([]SentryOrganization, error) { - workspaceID, err := s.defaultWorkspaceID() - if err != nil { - return nil, err - } - client, err := s.clientFor(ctx, workspaceID) +// ListOrganizations returns the organizations the instance's token can access. +func (s *Service) ListOrganizations(ctx context.Context, workspaceID, instanceID string) ([]SentryOrganization, error) { + client, err := s.browseClient(ctx, workspaceID, instanceID) if err != nil { return nil, err } return client.ListOrganizations(ctx) } -// ListProjects returns the projects the stored token can access. -func (s *Service) ListProjects(ctx context.Context) ([]SentryProject, error) { - workspaceID, err := s.defaultWorkspaceID() - if err != nil { - return nil, err - } - client, err := s.clientFor(ctx, workspaceID) +// ListProjects returns the projects the instance's token can access. +func (s *Service) ListProjects(ctx context.Context, workspaceID, instanceID string) ([]SentryProject, error) { + client, err := s.browseClient(ctx, workspaceID, instanceID) if err != nil { return nil, err } return client.ListProjects(ctx) } -// SearchIssues runs a filtered search. The caller supplies the org/project to -// search — there is no install-wide default to fall back on. -func (s *Service) SearchIssues(ctx context.Context, filter SearchFilter, cursor string) (*SearchResult, error) { - workspaceID, err := s.defaultWorkspaceID() - if err != nil { - return nil, err - } - return s.SearchIssuesForWorkspace(ctx, workspaceID, filter, cursor) -} - -// SearchIssuesForWorkspace runs a filtered search against one workspace's client. -func (s *Service) SearchIssuesForWorkspace(ctx context.Context, workspaceID string, filter SearchFilter, cursor string) (*SearchResult, error) { - workspaceID, err := s.normalizeWorkspaceID(workspaceID) - if err != nil { - return nil, err - } - client, err := s.clientFor(ctx, workspaceID) +// SearchIssues runs a filtered search against one instance's client. +func (s *Service) SearchIssues(ctx context.Context, workspaceID, instanceID string, filter SearchFilter, cursor string) (*SearchResult, error) { + client, err := s.browseClient(ctx, workspaceID, instanceID) if err != nil { return nil, err } return client.SearchIssues(ctx, filter, cursor) } -// GetIssue loads a single issue by short ID or numeric ID. -func (s *Service) GetIssue(ctx context.Context, idOrShortID string) (*SentryIssue, error) { - workspaceID, err := s.defaultWorkspaceID() - if err != nil { - return nil, err - } - client, err := s.clientFor(ctx, workspaceID) +// GetIssue loads a single issue by short ID or numeric ID from one instance. +func (s *Service) GetIssue(ctx context.Context, workspaceID, instanceID, idOrShortID string) (*SentryIssue, error) { + client, err := s.browseClient(ctx, workspaceID, instanceID) if err != nil { return nil, err } return client.GetIssue(ctx, idOrShortID) } -// clientFor returns the cached client, creating it if needed. -// It captures the generation counter before releasing the lock for I/O so -// that a concurrent invalidateClient call during the build window is not -// silently overwritten: if the counter changed the freshly built client is -// returned to the caller without being cached, and the next call rebuilds -// with the updated config. -func (s *Service) clientFor(ctx context.Context, workspaceID string) (Client, error) { - workspaceID, err := s.normalizeWorkspaceID(workspaceID) +// browseClient resolves and ownership-checks the instance, then returns its +// cached client. Returns ErrInstanceRequired / ErrInstanceNotFound before any +// client is built. +func (s *Service) browseClient(ctx context.Context, workspaceID, instanceID string) (Client, error) { + if _, err := s.requireInstance(ctx, workspaceID, instanceID); err != nil { + return nil, err + } + return s.clientForInstance(ctx, instanceID) +} + +// requireInstance resolves an instance and asserts it belongs to the workspace. +// Returns ErrInstanceRequired for a blank ID and ErrInstanceNotFound when the +// instance is missing or owned by another workspace. +func (s *Service) requireInstance(ctx context.Context, workspaceID, instanceID string) (*SentryConfig, error) { + if instanceID == "" { + return nil, ErrInstanceRequired + } + cfg, err := s.store.GetInstance(ctx, instanceID) if err != nil { return nil, err } + if cfg == nil || cfg.WorkspaceID != workspaceID { + return nil, ErrInstanceNotFound + } + return cfg, nil +} + +// clientForInstance returns the cached client for an instance, creating it if +// needed. It captures the generation counter before releasing the lock for I/O +// so a concurrent invalidateClient during the build window is not silently +// overwritten: if the counter changed the freshly built client is returned to +// the caller without being cached, and the next call rebuilds. +func (s *Service) clientForInstance(ctx context.Context, instanceID string) (Client, error) { + if instanceID == "" { + return nil, ErrNotConfigured + } s.mu.Lock() if s.clients == nil { s.clients = make(map[string]Client) @@ -414,15 +538,14 @@ func (s *Service) clientFor(ctx context.Context, workspaceID string) (Client, er if s.clientGen == nil { s.clientGen = make(map[string]uint64) } - if s.clients[workspaceID] != nil { - c := s.clients[workspaceID] + if c := s.clients[instanceID]; c != nil { s.mu.Unlock() return c, nil } - gen := s.clientGen[workspaceID] + gen := s.clientGen[instanceID] s.mu.Unlock() - cfg, err := s.store.GetConfigForWorkspace(ctx, workspaceID) + cfg, err := s.store.GetInstance(ctx, instanceID) if err != nil { return nil, err } @@ -431,13 +554,14 @@ func (s *Service) clientFor(ctx context.Context, workspaceID string) (Client, er } secret := "" if s.secrets != nil { - secret, err = s.revealSecret(ctx, workspaceID) - if err != nil { - return nil, fmt.Errorf("read sentry secret: %w", err) + revealed, ok, revealErr := s.revealInstanceSecret(ctx, instanceID) + if revealErr != nil { + return nil, fmt.Errorf("read sentry secret: %w", revealErr) } - if secret == "" { + if !ok { return nil, ErrNotConfigured } + secret = revealed } client := s.clientFn(cfg, secret) s.mu.Lock() @@ -448,129 +572,97 @@ func (s *Service) clientFor(ctx context.Context, workspaceID string) (Client, er if s.clientGen == nil { s.clientGen = make(map[string]uint64) } - if s.clients[workspaceID] != nil { + if c := s.clients[instanceID]; c != nil { // Another goroutine already cached a client; use that one. - return s.clients[workspaceID], nil + return c, nil } - if s.clientGen[workspaceID] != gen { + if s.clientGen[instanceID] != gen { // invalidateClient ran while we were doing I/O — the config/secret we // read is now stale. Return the client to the caller for this call only; - // the next call will rebuild with fresh credentials. + // the next call rebuilds with fresh credentials. return client, nil } - s.clients[workspaceID] = client + s.clients[instanceID] = client return client, nil } -// invalidateClient drops the cached client so the next request rebuilds it. -// The generation counter is incremented so a concurrent clientFor build does -// not restore a client built from the now-stale config. -func (s *Service) invalidateClient(workspaceID string) { +// invalidateClient drops the cached client for an instance so the next request +// rebuilds it. The generation counter is incremented so a concurrent +// clientForInstance build does not restore a client from the now-stale config. +func (s *Service) invalidateClient(instanceID string) { s.mu.Lock() if s.clients != nil { - delete(s.clients, workspaceID) + delete(s.clients, instanceID) } if s.clientGen == nil { s.clientGen = make(map[string]uint64) } - s.clientGen[workspaceID]++ + s.clientGen[instanceID]++ s.mu.Unlock() } -// resolveCredentials picks credentials for a test: inline if the request -// carries a secret, otherwise the stored secret. -func (s *Service) resolveCredentials(ctx context.Context, workspaceID string, req *SetConfigRequest) (*SentryConfig, string, error) { - cfg := &SentryConfig{AuthMethod: req.AuthMethod, URL: normalizeSentryURL(req.URL)} - if req.Secret != "" { - if cfg.URL == "" { - cfg.URL = DefaultSentryURL - } - return cfg, req.Secret, nil - } +// secretExists reports whether an instance has a stored token, distinguishing +// absence from a backend error (logged, treated as absent). +func (s *Service) secretExists(ctx context.Context, instanceID string) bool { if s.secrets == nil { - return nil, "", errors.New("no secret store configured") + return false } - secret, err := s.revealSecret(ctx, workspaceID) + exists, err := s.secrets.Exists(ctx, secretKeyForInstance(instanceID)) if err != nil { - s.log.Warn("sentry: secret reveal failed", zap.Error(err)) - return nil, "", fmt.Errorf("read sentry secret: %w", err) + s.log.Warn("sentry: secret exists check failed", zap.Error(err)) + return false } - if secret == "" { - return nil, "", errors.New("no auth token stored — paste one to test") - } - stored, storeErr := s.store.GetConfigForWorkspace(ctx, workspaceID) - if storeErr != nil { - s.log.Warn("sentry: load stored config for credential resolution failed", zap.Error(storeErr)) - } - if stored != nil { - if cfg.AuthMethod == "" { - cfg.AuthMethod = stored.AuthMethod - } - if cfg.URL == "" { - cfg.URL = stored.URL - } - } - if cfg.URL == "" { - cfg.URL = DefaultSentryURL - } - return cfg, secret, nil + return exists } -func (s *Service) defaultWorkspaceID() (string, error) { - return s.store.defaultWorkspaceID() -} - -func (s *Service) normalizeWorkspaceID(workspaceID string) (string, error) { - if workspaceID != "" { - return workspaceID, nil - } - return s.defaultWorkspaceID() -} - -func (s *Service) secretExists(ctx context.Context, workspaceID string) (bool, error) { +// revealInstanceSecret returns the stored token for an instance. ok is false +// (with a nil error) when no token is stored, so callers can map that to +// ErrNotConfigured without conflating it with a backend failure. +func (s *Service) revealInstanceSecret(ctx context.Context, instanceID string) (string, bool, error) { if s.secrets == nil { - return false, nil - } - exists, err := s.secrets.Exists(ctx, SecretKeyForWorkspace(workspaceID)) - if err != nil || exists { - return exists, err - } - return s.secrets.Exists(ctx, SecretKey) -} - -func (s *Service) revealSecret(ctx context.Context, workspaceID string) (string, error) { - if s.secrets == nil { - return "", nil - } - secret, err := s.secrets.Reveal(ctx, SecretKeyForWorkspace(workspaceID)) - if err == nil && secret != "" { - return secret, nil - } - legacy, legacyErr := s.secrets.Reveal(ctx, SecretKey) - if legacyErr == nil && legacy != "" { - return legacy, nil + return "", false, nil } + exists, err := s.secrets.Exists(ctx, secretKeyForInstance(instanceID)) if err != nil { - return "", err + return "", false, err } - return "", legacyErr + if !exists { + return "", false, nil + } + secret, err := s.secrets.Reveal(ctx, secretKeyForInstance(instanceID)) + if err != nil { + return "", false, err + } + return secret, secret != "", nil } -// validateConfigRequest normalizes and validates a config request in place: it -// defaults a blank auth method and instance URL, rejects unknown auth methods, -// and rejects URLs the HTTP client could not use (see validateSentryURL). -func validateConfigRequest(req *SetConfigRequest) error { - if req.AuthMethod == "" { - req.AuthMethod = AuthMethodAuthToken +// validateInstanceWrite validates a create/update request: a non-empty name and +// a usable auth method + URL (both normalized in place). All failures are +// wrapped in ErrInvalidConfig so the handler maps them to HTTP 400. +func validateInstanceWrite(name string, authMethod, instanceURL *string) error { + if strings.TrimSpace(name) == "" { + return fmt.Errorf("%w: name is required", ErrInvalidConfig) } - if req.AuthMethod != AuthMethodAuthToken { - return fmt.Errorf("unknown auth method: %q", req.AuthMethod) + if err := prepareInstanceCredentials(authMethod, instanceURL); err != nil { + return fmt.Errorf("%w: %s", ErrInvalidConfig, err.Error()) } - req.URL = normalizeSentryURL(req.URL) - if req.URL == "" { - req.URL = DefaultSentryURL + return nil +} + +// prepareInstanceCredentials defaults a blank auth method + URL and validates +// them in place, returning a plain error (callers wrap or surface it). +func prepareInstanceCredentials(authMethod, instanceURL *string) error { + if *authMethod == "" { + *authMethod = AuthMethodAuthToken } - return validateSentryURL(req.URL) + if *authMethod != AuthMethodAuthToken { + return fmt.Errorf("unknown auth method: %q", *authMethod) + } + *instanceURL = normalizeSentryURL(*instanceURL) + if *instanceURL == "" { + *instanceURL = DefaultSentryURL + } + return validateSentryURL(*instanceURL) } // normalizeSentryURL trims whitespace and trailing slashes and prepends diff --git a/apps/backend/internal/sentry/service_issue_watch.go b/apps/backend/internal/sentry/service_issue_watch.go index e18c614028..9e3dc9e2da 100644 --- a/apps/backend/internal/sentry/service_issue_watch.go +++ b/apps/backend/internal/sentry/service_issue_watch.go @@ -32,12 +32,19 @@ func (s *Service) CreateIssueWatch(ctx context.Context, req *CreateIssueWatchReq if err := validateIssueWatchCreate(req); err != nil { return nil, err } + if strings.TrimSpace(req.SentryInstanceID) == "" { + return nil, fmt.Errorf("%w: sentryInstanceId is required", ErrInstanceRequired) + } + if _, err := s.requireInstance(ctx, req.WorkspaceID, req.SentryInstanceID); err != nil { + return nil, err + } repositoryID, baseBranch, err := s.resolveRepositoryBinding(ctx, req.WorkspaceID, req.RepositoryID, req.BaseBranch) if err != nil { return nil, err } w := &IssueWatch{ WorkspaceID: req.WorkspaceID, + SentryInstanceID: req.SentryInstanceID, WorkflowID: req.WorkflowID, WorkflowStepID: req.WorkflowStepID, RepositoryID: repositoryID, @@ -172,19 +179,27 @@ func (s *Service) ResetIssueWatch(ctx context.Context, watchID string) (int, err return res.TasksDeleted, err } -// CheckIssueWatch runs the watch's filter once and returns the issues that -// haven't been turned into tasks yet. last_polled_at is stamped regardless of -// whether the search succeeded — a failing search still counts as "we tried". +// CheckIssueWatch runs the watch's filter once and returns the Sentry +// instance actually polled (resolved via resolveWatchInstanceID — never +// w.SentryInstanceID directly, which is empty for an unbound legacy watch) +// plus the issues that haven't been turned into tasks yet. last_polled_at is +// stamped regardless of whether the search succeeded — a failing search +// still counts as "we tried". // // Concurrency note: callers must tolerate being handed an issue that gets // stolen by a concurrent reserver. The duplicate publish is harmless — the // second reserver loses the INSERT OR IGNORE race in the orchestrator and // bails. Same pattern as the Linear / Jira watchers. -func (s *Service) CheckIssueWatch(ctx context.Context, w *IssueWatch) ([]*SentryIssue, error) { +func (s *Service) CheckIssueWatch(ctx context.Context, w *IssueWatch) (string, []*SentryIssue, error) { defer s.stampWatchLastPolled(w.ID) - client, err := s.clientFor(ctx, w.WorkspaceID) + instanceID, err := s.resolveWatchInstanceID(ctx, w) if err != nil { - return nil, err + s.stampWatchError(w.ID, err.Error()) + return "", nil, err + } + client, err := s.clientForInstance(ctx, instanceID) + if err != nil { + return instanceID, nil, err } // Intentionally reads only the first page per tick (bounded-page-per-tick // invariant, matching the Linear/Jira watchers). SearchIssues sorts results @@ -192,14 +207,14 @@ func (s *Service) CheckIssueWatch(ctx context.Context, w *IssueWatch) ([]*Sentry // on page one and are not missed by the single-page read. res, err := client.SearchIssues(ctx, w.Filter, "") if err != nil { - return nil, err + return instanceID, nil, err } seen, err := s.store.ListSeenIssueShortIDs(ctx, w.ID) if err != nil { // Skip this tick rather than treat a failed dedup read as "nothing seen": // a nil map would let the whole page (up to 100 issues) publish as events. // The next tick retries with a working dedup set. - return nil, fmt.Errorf("load dedup set for watch %s: %w", w.ID, err) + return instanceID, nil, fmt.Errorf("load dedup set for watch %s: %w", w.ID, err) } out := make([]*SentryIssue, 0, len(res.Issues)) for i := range res.Issues { @@ -209,7 +224,8 @@ func (s *Service) CheckIssueWatch(ctx context.Context, w *IssueWatch) ([]*Sentry } out = append(out, &issue) } - return out, nil + s.clearWatchError(w.ID) + return instanceID, out, nil } // stampWatchLastPolled writes the current timestamp using a fresh background @@ -224,6 +240,75 @@ func (s *Service) stampWatchLastPolled(watchID string) { } } +// resolveWatchInstanceID picks the Sentry instance a watch should poll. A +// bound watch uses its stored instance. An unbound (migrated legacy) watch +// resolves to the workspace's sole instance per ADR-0030, regardless of that +// instance's health — matching the pre-existing single-instance contract. +// When the workspace has several instances, the choice is otherwise +// ambiguous, so it narrows to the healthy subset: a single healthy instance +// wins, and zero or several healthy instances still cannot run unambiguously. +func (s *Service) resolveWatchInstanceID(ctx context.Context, w *IssueWatch) (string, error) { + if w.SentryInstanceID != "" { + return w.SentryInstanceID, nil + } + instances, err := s.store.ListInstances(ctx, w.WorkspaceID) + if err != nil { + return "", err + } + switch len(instances) { + case 0: + return "", fmt.Errorf("%w: watch is unbound and its workspace has no Sentry instance", ErrNotConfigured) + case 1: + return instances[0].ID, nil + default: + return resolveAmbiguousWatchInstance(instances) + } +} + +// resolveAmbiguousWatchInstance breaks a multi-instance tie by preferring the +// workspace's sole healthy instance; zero or several healthy instances remain +// ambiguous and require an explicit binding. +func resolveAmbiguousWatchInstance(instances []*SentryConfig) (string, error) { + healthyInstances := make([]*SentryConfig, 0, len(instances)) + for _, instance := range instances { + if instance.LastOk { + healthyInstances = append(healthyInstances, instance) + } + } + switch len(healthyInstances) { + case 1: + return healthyInstances[0].ID, nil + case 0: + return "", fmt.Errorf("%w: watch is unbound and its workspace has no healthy Sentry instance", ErrNotConfigured) + default: + return "", fmt.Errorf("%w: watch is unbound and its workspace has %d healthy Sentry instances; bind one to the watch", ErrInvalidConfig, len(healthyInstances)) + } +} + +// stampWatchError records a non-fatal poll-time failure cause on the watch row +// without disabling it, using a detached short-deadline context so a cancelled +// caller ctx does not drop the record. +func (s *Service) stampWatchError(watchID, cause string) { + ctx, cancel := context.WithTimeout(context.Background(), authHealthWriteTimeout) + defer cancel() + if err := s.store.StampIssueWatchError(ctx, watchID, cause); err != nil { + s.log.Warn("sentry: stamp watch error failed", + zap.String("watch_id", watchID), zap.Error(err)) + } +} + +// clearWatchError removes stale poll error state using a detached context so a +// successful check still clears it if the caller context is subsequently +// cancelled. +func (s *Service) clearWatchError(watchID string) { + ctx, cancel := context.WithTimeout(context.Background(), authHealthWriteTimeout) + defer cancel() + if err := s.store.ClearIssueWatchError(ctx, watchID); err != nil { + s.log.Warn("sentry: clear watch error failed", + zap.String("watch_id", watchID), zap.Error(err)) + } +} + // ReserveIssueWatchTask exposes the dedup store API to the orchestrator's // WatcherSource implementation. func (s *Service) ReserveIssueWatchTask(ctx context.Context, watchID, shortID, issueURL string) (bool, error) { @@ -243,9 +328,11 @@ func (s *Service) ReleaseIssueWatchTask(ctx context.Context, watchID, shortID st } // publishNewSentryIssueEvent emits the orchestrator-facing event for one -// freshly-observed issue. No-op when the event bus is not wired (tests, early -// boot). -func (s *Service) publishNewSentryIssueEvent(ctx context.Context, w *IssueWatch, issue *SentryIssue) { +// freshly-observed issue. instanceID must be the instance actually polled +// (CheckIssueWatch's resolved return value) rather than w.SentryInstanceID, +// which is empty for an unbound legacy watch. No-op when the event bus is not +// wired (tests, early boot). +func (s *Service) publishNewSentryIssueEvent(ctx context.Context, w *IssueWatch, instanceID string, issue *SentryIssue) { s.mu.Lock() eb := s.eventBus s.mu.Unlock() @@ -255,6 +342,7 @@ func (s *Service) publishNewSentryIssueEvent(ctx context.Context, w *IssueWatch, evt := bus.NewEvent(events.SentryNewIssue, "sentry", &NewSentryIssueEvent{ IssueWatchID: w.ID, WorkspaceID: w.WorkspaceID, + SentryInstanceID: instanceID, WorkflowID: w.WorkflowID, WorkflowStepID: w.WorkflowStepID, RepositoryID: w.RepositoryID, diff --git a/apps/backend/internal/sentry/service_issue_watch_repository_test.go b/apps/backend/internal/sentry/service_issue_watch_repository_test.go index e600d36653..dc45d4dc1d 100644 --- a/apps/backend/internal/sentry/service_issue_watch_repository_test.go +++ b/apps/backend/internal/sentry/service_issue_watch_repository_test.go @@ -19,19 +19,20 @@ func (f fakeRepoLookup) GetRepository(_ context.Context, _ string) (string, stri func TestService_CreateIssueWatch_RepositoryBinding(t *testing.T) { ctx := context.Background() - baseReq := func() *CreateIssueWatchRequest { + baseReq := func(instID string) *CreateIssueWatchRequest { return &CreateIssueWatchRequest{ - WorkspaceID: "ws-1", - WorkflowID: "wf", - WorkflowStepID: "step", - Filter: SearchFilter{OrgSlug: "acme", ProjectSlug: "frontend"}, + WorkspaceID: "ws-1", + SentryInstanceID: instID, + WorkflowID: "wf", + WorkflowStepID: "step", + Filter: SearchFilter{OrgSlug: "acme", ProjectSlug: "frontend"}, } } t.Run("default branch filled from repo", func(t *testing.T) { f := newSvcFixture(t) f.svc.SetRepositoryLookup(fakeRepoLookup{workspaceID: "ws-1", defaultBranch: "main", ok: true}) - req := baseReq() + req := baseReq(f.ensureInstance(t, "ws-1")) req.RepositoryID = "repo-1" w, err := f.svc.CreateIssueWatch(ctx, req) if err != nil { @@ -45,7 +46,7 @@ func TestService_CreateIssueWatch_RepositoryBinding(t *testing.T) { t.Run("explicit branch preserved", func(t *testing.T) { f := newSvcFixture(t) f.svc.SetRepositoryLookup(fakeRepoLookup{workspaceID: "ws-1", defaultBranch: "main", ok: true}) - req := baseReq() + req := baseReq(f.ensureInstance(t, "ws-1")) req.RepositoryID = "repo-1" req.BaseBranch = "release/v2" w, err := f.svc.CreateIssueWatch(ctx, req) @@ -60,7 +61,7 @@ func TestService_CreateIssueWatch_RepositoryBinding(t *testing.T) { t.Run("cross-workspace repo rejected", func(t *testing.T) { f := newSvcFixture(t) f.svc.SetRepositoryLookup(fakeRepoLookup{workspaceID: "ws-other", defaultBranch: "main", ok: true}) - req := baseReq() + req := baseReq(f.ensureInstance(t, "ws-1")) req.RepositoryID = "repo-1" if _, err := f.svc.CreateIssueWatch(ctx, req); !errors.Is(err, ErrInvalidConfig) { t.Fatalf("expected ErrInvalidConfig for cross-workspace repo, got %v", err) @@ -70,7 +71,7 @@ func TestService_CreateIssueWatch_RepositoryBinding(t *testing.T) { t.Run("missing repo rejected", func(t *testing.T) { f := newSvcFixture(t) f.svc.SetRepositoryLookup(fakeRepoLookup{ok: false}) - req := baseReq() + req := baseReq(f.ensureInstance(t, "ws-1")) req.RepositoryID = "ghost" if _, err := f.svc.CreateIssueWatch(ctx, req); !errors.Is(err, ErrInvalidConfig) { t.Fatalf("expected ErrInvalidConfig for missing repo, got %v", err) @@ -79,7 +80,7 @@ func TestService_CreateIssueWatch_RepositoryBinding(t *testing.T) { t.Run("unbound skips lookup and clears branch", func(t *testing.T) { f := newSvcFixture(t) // no RepositoryLookup wired - req := baseReq() + req := baseReq(f.ensureInstance(t, "ws-1")) req.BaseBranch = "ignored-without-repo" w, err := f.svc.CreateIssueWatch(ctx, req) if err != nil { @@ -97,10 +98,11 @@ func TestService_UpdateIssueWatch_RepositoryBinding(t *testing.T) { f.svc.SetRepositoryLookup(fakeRepoLookup{workspaceID: "ws-1", defaultBranch: "main", ok: true}) w, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ - WorkspaceID: "ws-1", - WorkflowID: "wf", - WorkflowStepID: "step", - Filter: SearchFilter{OrgSlug: "acme", ProjectSlug: "frontend"}, + WorkspaceID: "ws-1", + SentryInstanceID: f.ensureInstance(t, "ws-1"), + WorkflowID: "wf", + WorkflowStepID: "step", + Filter: SearchFilter{OrgSlug: "acme", ProjectSlug: "frontend"}, }) if err != nil { t.Fatalf("create: %v", err) @@ -134,7 +136,8 @@ func TestService_UpdateIssueWatch_RebindAndDeletedRepo(t *testing.T) { f.svc.SetRepositoryLookup(fakeRepoLookup{workspaceID: "ws-1", defaultBranch: "main", ok: true}) w, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ - WorkspaceID: "ws-1", WorkflowID: "wf", WorkflowStepID: "step", + WorkspaceID: "ws-1", SentryInstanceID: f.ensureInstance(t, "ws-1"), + WorkflowID: "wf", WorkflowStepID: "step", Filter: SearchFilter{OrgSlug: "acme", ProjectSlug: "frontend"}, }) if err != nil { @@ -170,9 +173,11 @@ func TestService_IssueWatch_RejectsInvalidBaseBranch(t *testing.T) { ctx := context.Background() f := newSvcFixture(t) f.svc.SetRepositoryLookup(fakeRepoLookup{workspaceID: "ws-1", defaultBranch: "main", ok: true}) + instID := f.ensureInstance(t, "ws-1") base := func() *CreateIssueWatchRequest { return &CreateIssueWatchRequest{ - WorkspaceID: "ws-1", WorkflowID: "wf", WorkflowStepID: "step", + WorkspaceID: "ws-1", SentryInstanceID: instID, + WorkflowID: "wf", WorkflowStepID: "step", Filter: SearchFilter{OrgSlug: "acme", ProjectSlug: "frontend"}, RepositoryID: "repo-1", } } diff --git a/apps/backend/internal/sentry/service_issue_watch_test.go b/apps/backend/internal/sentry/service_issue_watch_test.go index 0f3a60f86f..9bbca83a78 100644 --- a/apps/backend/internal/sentry/service_issue_watch_test.go +++ b/apps/backend/internal/sentry/service_issue_watch_test.go @@ -4,12 +4,11 @@ import ( "context" "errors" "testing" + "time" "github.com/kandev/kandev/internal/integrations/optional" ) -func intPtr(v int) *int { return &v } - // withSearchResults returns a fakeClient that always returns the given issues // for SearchIssues, ignoring the filter. func (c *fakeClient) withSearchResults(issues []SentryIssue) *fakeClient { @@ -22,48 +21,64 @@ func (c *fakeClient) withSearchResults(issues []SentryIssue) *fakeClient { func validFilter() SearchFilter { return SearchFilter{OrgSlug: "acme", ProjectSlug: "frontend"} } +func intPtr(value int) *int { + return &value +} func TestService_CreateIssueWatch_DefaultsAndValidation(t *testing.T) { f := newSvcFixture(t) ctx := context.Background() + instID := f.ensureInstance(t, "ws-1") - // Missing org/project is rejected — a watch must name what it polls. + // Bad filters are rejected before the instance check, so no instance needed. for name, filter := range map[string]SearchFilter{ "empty": {}, "org only": {OrgSlug: "acme"}, "whitespace org": {OrgSlug: " ", ProjectSlug: "frontend"}, - // Sentry has no OR form for is:, so multiple statuses would AND-combine - // into a query that matches nothing — reject at save time. - "multi status": {OrgSlug: "acme", ProjectSlug: "frontend", Statuses: []string{"unresolved", "ignored"}}, + "multi status": {OrgSlug: "acme", ProjectSlug: "frontend", Statuses: []string{"unresolved", "ignored"}}, } { if _, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ - WorkspaceID: "ws-1", - WorkflowID: "wf", - WorkflowStepID: "step", - Filter: filter, + WorkspaceID: "ws-1", SentryInstanceID: instID, + WorkflowID: "wf", WorkflowStepID: "step", Filter: filter, }); !errors.Is(err, ErrInvalidConfig) { t.Errorf("%s filter should be rejected, got %v", name, err) } } - // Happy path assigns ID + defaults Enabled=true. w, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ - WorkspaceID: "ws-1", - WorkflowID: "wf", - WorkflowStepID: "step", - Filter: validFilter(), + WorkspaceID: "ws-1", SentryInstanceID: instID, + WorkflowID: "wf", WorkflowStepID: "step", Filter: validFilter(), }) if err != nil { t.Fatalf("create: %v", err) } - if w.ID == "" { - t.Fatal("expected ID assigned") + if w.ID == "" || !w.Enabled { + t.Fatalf("unexpected created watch: %+v", w) } - if !w.Enabled { - t.Error("expected Enabled defaulted to true") + if w.SentryInstanceID != instID { + t.Errorf("expected instance %q bound, got %q", instID, w.SentryInstanceID) } - if w.Filter.OrgSlug != "acme" || w.Filter.ProjectSlug != "frontend" { - t.Errorf("filter not persisted: %+v", w.Filter) +} + +// TestService_CreateIssueWatch_InstanceValidation pins the required + owned +// contract on the bound instance. +func TestService_CreateIssueWatch_InstanceValidation(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + other := f.seedInstance(t, "ws-2", "Other", "") + + // Missing instance → ErrInstanceRequired. + if _, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ + WorkspaceID: "ws-1", WorkflowID: "wf", WorkflowStepID: "step", Filter: validFilter(), + }); !errors.Is(err, ErrInstanceRequired) { + t.Errorf("expected ErrInstanceRequired for missing instance, got %v", err) + } + // Instance from another workspace → ErrInstanceNotFound. + if _, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ + WorkspaceID: "ws-1", SentryInstanceID: other.ID, + WorkflowID: "wf", WorkflowStepID: "step", Filter: validFilter(), + }); !errors.Is(err, ErrInstanceNotFound) { + t.Errorf("expected ErrInstanceNotFound for cross-workspace instance, got %v", err) } } @@ -71,23 +86,16 @@ func TestService_UpdateIssueWatch_LegacyMultiStatusToggle(t *testing.T) { f := newSvcFixture(t) ctx := context.Background() - // Seed a legacy watch carrying multiple statuses directly through the - // store, bypassing service validation — mirrors rows created before the - // single-status rule existed. + // Seed a legacy watch (unbound, multi-status) directly through the store. w := newTestIssueWatch("ws-1") w.Filter.Statuses = []string{"unresolved", "ignored"} if err := f.store.CreateIssueWatch(ctx, w); err != nil { t.Fatalf("seed watch: %v", err) } - - // A partial update that leaves the filter untouched (the enable/disable - // toggle sends only {enabled}) must still succeed for the legacy watch. disabled := false if _, err := f.svc.UpdateIssueWatch(ctx, w.ID, &UpdateIssueWatchRequest{Enabled: &disabled}); err != nil { t.Fatalf("toggle on legacy multi-status watch should succeed, got %v", err) } - - // Patching the filter to keep multiple statuses must be rejected. bad := SearchFilter{OrgSlug: "acme", ProjectSlug: "frontend", Statuses: []string{"unresolved", "ignored"}} if _, err := f.svc.UpdateIssueWatch(ctx, w.ID, &UpdateIssueWatchRequest{Filter: &bad}); !errors.Is(err, ErrInvalidConfig) { t.Errorf("filter patch with multiple statuses should be rejected, got %v", err) @@ -97,95 +105,96 @@ func TestService_UpdateIssueWatch_LegacyMultiStatusToggle(t *testing.T) { func TestService_UpdateIssueWatch_PartialPatch(t *testing.T) { f := newSvcFixture(t) ctx := context.Background() - created, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ - WorkspaceID: "ws-1", - WorkflowID: "wf", - WorkflowStepID: "step", - Filter: validFilter(), - Prompt: "original", + WorkspaceID: "ws-1", SentryInstanceID: f.ensureInstance(t, "ws-1"), + WorkflowID: "wf", WorkflowStepID: "step", Filter: validFilter(), Prompt: "original", }) if err != nil { t.Fatalf("create: %v", err) } - - // Patch only the prompt; everything else must remain. newPrompt := "updated" - updated, err := f.svc.UpdateIssueWatch(ctx, created.ID, &UpdateIssueWatchRequest{ - Prompt: &newPrompt, - }) + updated, err := f.svc.UpdateIssueWatch(ctx, created.ID, &UpdateIssueWatchRequest{Prompt: &newPrompt}) if err != nil { t.Fatalf("update: %v", err) } if updated.Prompt != "updated" { - t.Errorf("prompt not patched: %q", updated.Prompt) + t.Errorf("prompt not updated: got %q, want %q", updated.Prompt, "updated") } - if updated.Filter.OrgSlug != "acme" || updated.WorkspaceID != created.WorkspaceID { - t.Errorf("unexpected mutation of unset fields: %+v", updated) + if updated.Filter.OrgSlug != "acme" { + t.Errorf("filter changed by prompt-only patch: got orgSlug %q, want %q", updated.Filter.OrgSlug, "acme") + } + if updated.WorkspaceID != created.WorkspaceID { + t.Errorf("workspace id changed: got %q, want %q", updated.WorkspaceID, created.WorkspaceID) } - - // Patching the filter to something empty is rejected to keep watch rows valid. empty := SearchFilter{} if _, err := f.svc.UpdateIssueWatch(ctx, created.ID, &UpdateIssueWatchRequest{Filter: &empty}); !errors.Is(err, ErrInvalidConfig) { t.Errorf("expected ErrInvalidConfig for empty filter patch, got %v", err) } } -func TestService_IssueWatch_MaxInflightTasks(t *testing.T) { +// TestService_UpdateIssueWatch_InstanceImmutable pins acceptance (g): the bound +// instance is absent from the update request, so it cannot be changed. +func TestService_UpdateIssueWatch_InstanceImmutable(t *testing.T) { f := newSvcFixture(t) ctx := context.Background() - - // A non-positive cap is rejected at create. - if _, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ - WorkspaceID: "ws-1", - WorkflowID: "wf", - WorkflowStepID: "step", - Filter: validFilter(), - MaxInflightTasks: intPtr(0), - }); !errors.Is(err, ErrInvalidConfig) { - t.Errorf("expected ErrInvalidConfig for non-positive cap, got %v", err) - } - - // A positive cap round-trips through the store. + instA := f.seedInstance(t, "ws-1", "A", "") created, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ - WorkspaceID: "ws-1", - WorkflowID: "wf", - WorkflowStepID: "step", - Filter: validFilter(), - MaxInflightTasks: intPtr(3), + WorkspaceID: "ws-1", SentryInstanceID: instA.ID, + WorkflowID: "wf", WorkflowStepID: "step", Filter: validFilter(), }) if err != nil { t.Fatalf("create: %v", err) } - reloaded, err := f.svc.GetIssueWatch(ctx, created.ID) + prompt := "changed" + updated, err := f.svc.UpdateIssueWatch(ctx, created.ID, &UpdateIssueWatchRequest{Prompt: &prompt}) if err != nil { - t.Fatalf("get: %v", err) + t.Fatalf("update: %v", err) } + if updated.SentryInstanceID != instA.ID { + t.Errorf("instance changed on update: got %q want %q", updated.SentryInstanceID, instA.ID) + } + reloaded, _ := f.store.GetIssueWatch(ctx, created.ID) + if reloaded.SentryInstanceID != instA.ID { + t.Errorf("persisted instance changed: got %q want %q", reloaded.SentryInstanceID, instA.ID) + } +} + +func TestService_IssueWatch_MaxInflightTasks(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + instID := f.ensureInstance(t, "ws-1") + base := func() *CreateIssueWatchRequest { + return &CreateIssueWatchRequest{ + WorkspaceID: "ws-1", SentryInstanceID: instID, + WorkflowID: "wf", WorkflowStepID: "step", Filter: validFilter(), + } + } + + req := base() + req.MaxInflightTasks = intPtr(0) + if _, err := f.svc.CreateIssueWatch(ctx, req); !errors.Is(err, ErrInvalidConfig) { + t.Errorf("expected ErrInvalidConfig for non-positive cap, got %v", err) + } + req = base() + req.MaxInflightTasks = intPtr(3) + created, err := f.svc.CreateIssueWatch(ctx, req) + if err != nil { + t.Fatalf("create: %v", err) + } + reloaded, _ := f.svc.GetIssueWatch(ctx, created.ID) if reloaded.MaxInflightTasks == nil || *reloaded.MaxInflightTasks != 3 { t.Fatalf("expected cap 3 persisted, got %v", reloaded.MaxInflightTasks) } - - // PATCH tri-state: omitted leaves the cap unchanged. unchanged, err := f.svc.UpdateIssueWatch(ctx, created.ID, &UpdateIssueWatchRequest{}) - if err != nil { - t.Fatalf("patch (omit): %v", err) + if err != nil || unchanged.MaxInflightTasks == nil || *unchanged.MaxInflightTasks != 3 { + t.Errorf("omitted cap should stay 3, got %v (err %v)", unchanged.MaxInflightTasks, err) } - if unchanged.MaxInflightTasks == nil || *unchanged.MaxInflightTasks != 3 { - t.Errorf("omitted cap should stay 3, got %v", unchanged.MaxInflightTasks) - } - - // PATCH tri-state: explicit null clears the cap to uncapped. uncapped, err := f.svc.UpdateIssueWatch(ctx, created.ID, &UpdateIssueWatchRequest{ MaxInflightTasks: optional.Int{Present: true, Value: nil}, }) - if err != nil { - t.Fatalf("patch (null): %v", err) + if err != nil || uncapped.MaxInflightTasks != nil { + t.Errorf("null cap should clear to uncapped, got %v (err %v)", uncapped.MaxInflightTasks, err) } - if uncapped.MaxInflightTasks != nil { - t.Errorf("null cap should clear to uncapped, got %v", *uncapped.MaxInflightTasks) - } - - // PATCH tri-state: a non-positive value is rejected. if _, err := f.svc.UpdateIssueWatch(ctx, created.ID, &UpdateIssueWatchRequest{ MaxInflightTasks: optional.Int{Present: true, Value: intPtr(-1)}, }); !errors.Is(err, ErrInvalidConfig) { @@ -196,24 +205,18 @@ func TestService_IssueWatch_MaxInflightTasks(t *testing.T) { func TestService_CreateIssueWatch_RejectsOutOfRangeInterval(t *testing.T) { f := newSvcFixture(t) ctx := context.Background() + instID := f.ensureInstance(t, "ws-1") for _, n := range []int{1, 30, 59, 3601, 86400} { - _, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ - WorkspaceID: "ws-1", - WorkflowID: "wf", - WorkflowStepID: "step", - Filter: validFilter(), - PollIntervalSeconds: n, - }) - if !errors.Is(err, ErrInvalidConfig) { + if _, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ + WorkspaceID: "ws-1", SentryInstanceID: instID, + WorkflowID: "wf", WorkflowStepID: "step", Filter: validFilter(), PollIntervalSeconds: n, + }); !errors.Is(err, ErrInvalidConfig) { t.Errorf("expected ErrInvalidConfig for pollIntervalSeconds=%d, got %v", n, err) } } - // Zero is allowed (the store coerces to default). if _, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ - WorkspaceID: "ws-1", - WorkflowID: "wf", - WorkflowStepID: "step", - Filter: validFilter(), + WorkspaceID: "ws-1", SentryInstanceID: instID, + WorkflowID: "wf", WorkflowStepID: "step", Filter: validFilter(), }); err != nil { t.Errorf("expected zero pollIntervalSeconds to be accepted, got %v", err) } @@ -223,17 +226,14 @@ func TestService_UpdateIssueWatch_RejectsEmptyWorkflowFields(t *testing.T) { f := newSvcFixture(t) ctx := context.Background() created, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ - WorkspaceID: "ws-1", WorkflowID: "wf", WorkflowStepID: "step", - Filter: validFilter(), + WorkspaceID: "ws-1", SentryInstanceID: f.ensureInstance(t, "ws-1"), + WorkflowID: "wf", WorkflowStepID: "step", Filter: validFilter(), }) if err != nil { t.Fatalf("create: %v", err) } empty := "" - for _, req := range []*UpdateIssueWatchRequest{ - {WorkflowID: &empty}, - {WorkflowStepID: &empty}, - } { + for _, req := range []*UpdateIssueWatchRequest{{WorkflowID: &empty}, {WorkflowStepID: &empty}} { if _, err := f.svc.UpdateIssueWatch(ctx, created.ID, req); !errors.Is(err, ErrInvalidConfig) { t.Errorf("expected ErrInvalidConfig for %+v, got %v", req, err) } @@ -243,8 +243,7 @@ func TestService_UpdateIssueWatch_RejectsEmptyWorkflowFields(t *testing.T) { func TestService_UpdateIssueWatch_NotFound(t *testing.T) { f := newSvcFixture(t) prompt := "x" - _, err := f.svc.UpdateIssueWatch(context.Background(), "ghost", &UpdateIssueWatchRequest{Prompt: &prompt}) - if !errors.Is(err, ErrIssueWatchNotFound) { + if _, err := f.svc.UpdateIssueWatch(context.Background(), "ghost", &UpdateIssueWatchRequest{Prompt: &prompt}); !errors.Is(err, ErrIssueWatchNotFound) { t.Errorf("expected ErrIssueWatchNotFound, got %v", err) } } @@ -252,33 +251,23 @@ func TestService_UpdateIssueWatch_NotFound(t *testing.T) { func TestService_CheckIssueWatch_FiltersAlreadySeen(t *testing.T) { f := newSvcFixture(t) ctx := context.Background() - - if _, err := f.svc.SetConfigForWorkspace(ctx, "ws-1", &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "sntrys_abc", - }); err != nil { - t.Fatalf("set config: %v", err) - } - + inst := f.seedInstance(t, "ws-1", "A", "sntrys_abc") f.client.withSearchResults([]SentryIssue{ {ShortID: "PROJ-1", Title: "one", Permalink: "https://sentry.io/issues/PROJ-1"}, {ShortID: "PROJ-2", Title: "two", Permalink: "https://sentry.io/issues/PROJ-2"}, {ShortID: "PROJ-3", Title: "three", Permalink: "https://sentry.io/issues/PROJ-3"}, }) - w, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ - WorkspaceID: "ws-1", WorkflowID: "wf", WorkflowStepID: "step", - Filter: validFilter(), + WorkspaceID: "ws-1", SentryInstanceID: inst.ID, + WorkflowID: "wf", WorkflowStepID: "step", Filter: validFilter(), }) if err != nil { t.Fatalf("create watch: %v", err) } - - // Pre-seed PROJ-2 as already turned into a task. if _, err := f.store.ReserveIssueWatchTask(ctx, w.ID, "PROJ-2", "https://sentry.io/issues/PROJ-2"); err != nil { t.Fatalf("seed reservation: %v", err) } - - got, err := f.svc.CheckIssueWatch(ctx, w) + _, got, err := f.svc.CheckIssueWatch(ctx, w) if err != nil { t.Fatalf("check: %v", err) } @@ -290,7 +279,6 @@ func TestService_CheckIssueWatch_FiltersAlreadySeen(t *testing.T) { t.Error("PROJ-2 should have been filtered as already seen") } } - refreshed, _ := f.store.GetIssueWatch(ctx, w.ID) if refreshed.LastPolledAt == nil { t.Error("expected last_polled_at stamped after check") @@ -300,19 +288,18 @@ func TestService_CheckIssueWatch_FiltersAlreadySeen(t *testing.T) { func TestService_CheckIssueWatch_StampsLastPolledOnError(t *testing.T) { f := newSvcFixture(t) ctx := context.Background() - if _, err := f.svc.SetConfig(ctx, &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "sntrys_abc", - }); err != nil { - t.Fatalf("set config: %v", err) - } + inst := f.seedInstance(t, "ws-1", "A", "sntrys_abc") f.client.searchIssuesFn = func(_ SearchFilter, _ string) (*SearchResult, error) { return nil, errors.New("upstream 500") } - w, _ := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ - WorkspaceID: "ws-1", WorkflowID: "wf", WorkflowStepID: "step", - Filter: validFilter(), + w, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ + WorkspaceID: "ws-1", SentryInstanceID: inst.ID, + WorkflowID: "wf", WorkflowStepID: "step", Filter: validFilter(), }) - if _, err := f.svc.CheckIssueWatch(ctx, w); err == nil { + if err != nil { + t.Fatalf("create: %v", err) + } + if _, _, err := f.svc.CheckIssueWatch(ctx, w); err == nil { t.Error("expected error from search to surface to caller") } refreshed, _ := f.store.GetIssueWatch(ctx, w.ID) @@ -320,3 +307,154 @@ func TestService_CheckIssueWatch_StampsLastPolledOnError(t *testing.T) { t.Error("expected last_polled_at stamped even on search failure (liveness signal)") } } + +func TestService_CheckIssueWatch_ClearsLastErrorAfterSuccess(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + inst := f.seedInstance(t, "ws-1", "A", "sntrys_abc") + w, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{ + WorkspaceID: "ws-1", SentryInstanceID: inst.ID, + WorkflowID: "wf", WorkflowStepID: "step", Filter: validFilter(), + }) + if err != nil { + t.Fatalf("create watch: %v", err) + } + if err := f.store.StampIssueWatchError(ctx, w.ID, "upstream 500"); err != nil { + t.Fatalf("stamp initial error: %v", err) + } + + f.client.withSearchResults(nil) + if _, _, err := f.svc.CheckIssueWatch(ctx, w); err != nil { + t.Fatalf("check recovered watch: %v", err) + } + reloaded, err := f.store.GetIssueWatch(ctx, w.ID) + if err != nil { + t.Fatalf("reload watch: %v", err) + } + if reloaded.LastError != "" { + t.Errorf("last error = %q, want cleared after success", reloaded.LastError) + } + if reloaded.LastErrorAt != nil { + t.Errorf("last error timestamp = %v, want cleared after success", reloaded.LastErrorAt) + } +} + +// TestService_CheckIssueWatch_ResolvesSoleInstance pins acceptance (b): an +// unbound (NULL-instance) watch resolves to its workspace's sole instance at +// poll time. +func TestService_CheckIssueWatch_ResolvesSoleInstance(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + inst := f.seedInstance(t, "ws-1", "Primary", "tok") // the sole healthy instance, with a secret + if err := f.store.UpdateAuthHealthForInstance(ctx, inst.ID, true, "", time.Now().UTC()); err != nil { + t.Fatalf("mark instance healthy: %v", err) + } + f.client.withSearchResults([]SentryIssue{ + {ShortID: "PROJ-1", Title: "one", Permalink: "https://sentry.io/issues/PROJ-1"}, + }) + // Watch created directly with a NULL instance (migrated legacy row). + w := newTestIssueWatch("ws-1") + if err := f.store.CreateIssueWatch(ctx, w); err != nil { + t.Fatalf("seed unbound watch: %v", err) + } + if w.SentryInstanceID != "" { + t.Fatalf("expected unbound watch, got instance %q", w.SentryInstanceID) + } + gotInstanceID, got, err := f.svc.CheckIssueWatch(ctx, w) + if err != nil { + t.Fatalf("check unbound watch: %v", err) + } + if gotInstanceID != inst.ID { + t.Errorf("resolved instance = %q, want sole instance %q", gotInstanceID, inst.ID) + } + if len(got) != 1 || got[0].ShortID != "PROJ-1" { + t.Fatalf("expected sole-instance resolution to return PROJ-1, got %+v", got) + } +} + +// TestService_ResolveWatchInstanceID_SoleInstanceIgnoresHealth pins the +// ADR-0030 single-instance contract: an unbound watch resolves to its +// workspace's only instance even when that instance has never been health +// probed (LastOk still false) — matching the pre-existing behavior every +// poller test's saveConfigForWorkspace helper relies on. +func TestService_ResolveWatchInstanceID_SoleInstanceIgnoresHealth(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + inst := f.seedInstance(t, "ws-1", "Primary", "tok") + + instanceID, err := f.svc.resolveWatchInstanceID(ctx, newTestIssueWatch("ws-1")) + if err != nil { + t.Fatalf("resolve watch instance: %v", err) + } + if instanceID != inst.ID { + t.Errorf("resolved instance = %q, want sole instance %q", instanceID, inst.ID) + } +} + +func TestService_ResolveWatchInstanceID_AmbiguousMultiInstancePrefersHealthy(t *testing.T) { + t.Run("selects the sole healthy instance among several", func(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + f.seedInstance(t, "ws-1", "Unhealthy", "tok") + healthy := f.seedInstance(t, "ws-1", "Healthy", "tok") + if err := f.store.UpdateAuthHealthForInstance(ctx, healthy.ID, true, "", time.Now().UTC()); err != nil { + t.Fatalf("mark instance healthy: %v", err) + } + + instanceID, err := f.svc.resolveWatchInstanceID(ctx, newTestIssueWatch("ws-1")) + if err != nil { + t.Fatalf("resolve watch instance: %v", err) + } + if instanceID != healthy.ID { + t.Errorf("resolved instance = %q, want healthy instance %q", instanceID, healthy.ID) + } + }) + + t.Run("rejects when several instances exist and none is healthy", func(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + f.seedInstance(t, "ws-1", "A", "tok") + f.seedInstance(t, "ws-1", "B", "tok") + + if _, err := f.svc.resolveWatchInstanceID(ctx, newTestIssueWatch("ws-1")); !errors.Is(err, ErrNotConfigured) { + t.Errorf("expected ErrNotConfigured with no healthy instance among several, got %v", err) + } + }) + + t.Run("rejects when multiple instances are healthy", func(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + for _, name := range []string{"A", "B"} { + instance := f.seedInstance(t, "ws-1", name, "tok") + if err := f.store.UpdateAuthHealthForInstance(ctx, instance.ID, true, "", time.Now().UTC()); err != nil { + t.Fatalf("mark %s healthy: %v", name, err) + } + } + + if _, err := f.svc.resolveWatchInstanceID(ctx, newTestIssueWatch("ws-1")); !errors.Is(err, ErrInvalidConfig) { + t.Errorf("expected ErrInvalidConfig with multiple healthy instances, got %v", err) + } + }) +} + +// TestService_CheckIssueWatch_UnboundNoInstanceStampsError pins the other half +// of acceptance (b): an unbound watch whose workspace has no instance stamps a +// last_error and skips, without disabling the watch. +func TestService_CheckIssueWatch_UnboundNoInstanceStampsError(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + w := newTestIssueWatch("ws-empty") // workspace has zero instances + if err := f.store.CreateIssueWatch(ctx, w); err != nil { + t.Fatalf("seed watch: %v", err) + } + if _, _, err := f.svc.CheckIssueWatch(ctx, w); err == nil { + t.Error("expected an error when no instance can be resolved") + } + refreshed, _ := f.store.GetIssueWatch(ctx, w.ID) + if refreshed.LastError == "" { + t.Error("expected last_error stamped when resolution fails") + } + if !refreshed.Enabled { + t.Error("watch must stay enabled (stamp + skip, not disable) so it auto-heals") + } +} diff --git a/apps/backend/internal/sentry/service_test.go b/apps/backend/internal/sentry/service_test.go index 2740e9b8ae..10c8aed16b 100644 --- a/apps/backend/internal/sentry/service_test.go +++ b/apps/backend/internal/sentry/service_test.go @@ -26,8 +26,15 @@ func (s *slowSecretStore) Reveal(ctx context.Context, id string) (string, error) } type fakeSecretStore struct { - mu sync.Mutex - secrets map[string]string + mu sync.Mutex + secrets map[string]string + setErr error + setErrAfter int + setErrAfterWrite bool + setHook func() + revealErr error + revealErrForID string + deleteMissingErr error } func newFakeSecretStore() *fakeSecretStore { @@ -37,16 +44,34 @@ func newFakeSecretStore() *fakeSecretStore { func (f *fakeSecretStore) Reveal(_ context.Context, id string) (string, error) { f.mu.Lock() defer f.mu.Unlock() + if f.revealErr != nil && (f.revealErrForID == "" || f.revealErrForID == id) { + return "", f.revealErr + } v, ok := f.secrets[id] if !ok { - return "", errors.New("not found") + return "", errors.New("secret not found: " + id) } return v, nil } +// Set runs setHook (if any) before acquiring its lock, letting a test drive a +// synchronous client build against the pre-failure row state — simulating a +// concurrent clientForInstance call racing the write this Set is about to fail. func (f *fakeSecretStore) Set(_ context.Context, id, _, value string) error { + if f.setHook != nil { + f.setHook() + } f.mu.Lock() defer f.mu.Unlock() + if f.setErr != nil { + if f.setErrAfter == 0 { + if f.setErrAfterWrite { + f.secrets[id] = value + } + return f.setErr + } + f.setErrAfter-- + } f.secrets[id] = value return nil } @@ -54,6 +79,9 @@ func (f *fakeSecretStore) Set(_ context.Context, id, _, value string) error { func (f *fakeSecretStore) Delete(_ context.Context, id string) error { f.mu.Lock() defer f.mu.Unlock() + if _, ok := f.secrets[id]; !ok && f.deleteMissingErr != nil { + return f.deleteMissingErr + } delete(f.secrets, id) return nil } @@ -64,6 +92,11 @@ func (f *fakeSecretStore) Exists(_ context.Context, id string) (bool, error) { _, ok := f.secrets[id] return ok, nil } +func (f *fakeSecretStore) count() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.secrets) +} // fakeClient is an in-memory Client for verifying service plumbing. type fakeClient struct { @@ -139,178 +172,477 @@ func newSvcFixture(t *testing.T) *svcFixture { return f } -func waitForAuthProbe(t *testing.T, f *svcFixture) *SentryConfig { +// seedInstance persists an instance + secret directly via the store/secret fake, +// bypassing Service.CreateInstance (and its async probe). +func (f *svcFixture) seedInstance(t *testing.T, workspaceID, name, secret string) *SentryConfig { + t.Helper() + cfg := &SentryConfig{WorkspaceID: workspaceID, Name: name, AuthMethod: AuthMethodAuthToken, URL: DefaultSentryURL} + if err := f.store.CreateInstance(context.Background(), cfg); err != nil { + t.Fatalf("seed instance: %v", err) + } + if secret != "" { + if err := f.secrets.Set(context.Background(), secretKeyForInstance(cfg.ID), "tok", secret); err != nil { + t.Fatalf("seed secret: %v", err) + } + } + return cfg +} + +// ensureInstance returns the ID of a workspace's sole instance, creating a +// "Primary" instance when none exists. Reused across tests that need a valid +// SentryInstanceID for a watch without minding which instance it is. +func (f *svcFixture) ensureInstance(t *testing.T, workspaceID string) string { + t.Helper() + instances, err := f.store.ListInstances(context.Background(), workspaceID) + if err != nil { + t.Fatalf("list instances: %v", err) + } + if len(instances) > 0 { + return instances[0].ID + } + return f.seedInstance(t, workspaceID, "Primary", "").ID +} + +func waitForAuthProbe(t *testing.T, f *svcFixture) { t.Helper() select { case <-f.probed: - cfg, err := f.svc.GetConfig(context.Background()) - if err != nil { - t.Fatalf("get config after probe: %v", err) - } - return cfg case <-time.After(2 * time.Second): t.Fatalf("async probe hook did not fire within 2s") - return nil } } -func TestService_SetConfig_PersistsAndStoresSecret(t *testing.T) { +func TestService_CreateInstance_PersistsAndStoresSecret(t *testing.T) { f := newSvcFixture(t) ctx := context.Background() - cfg, err := f.svc.SetConfig(ctx, &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, - Secret: "sntrys_xyz", - }) - if err != nil { - t.Fatalf("set: %v", err) - } - if cfg.AuthMethod != AuthMethodAuthToken { - t.Errorf("config not stored: %+v", cfg) - } - if !cfg.HasSecret { - t.Error("expected HasSecret=true") - } - if got, _ := f.secrets.Reveal(ctx, SecretKeyForWorkspace("default")); got != "sntrys_xyz" { - t.Errorf("secret stored = %q", got) - } -} - -func TestService_GetConfig_HidesSecretValue(t *testing.T) { - // GetConfig must surface HasSecret=true but never the secret itself. - f := newSvcFixture(t) - ctx := context.Background() - if _, err := f.svc.SetConfig(ctx, &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "secret-tok", - }); err != nil { - t.Fatalf("set: %v", err) - } - cfg, err := f.svc.GetConfig(ctx) - if err != nil || cfg == nil { - t.Fatalf("get: %v / %v", err, cfg) - } - if !cfg.HasSecret { - t.Error("expected HasSecret=true") - } -} - -func TestService_SetConfig_EmptySecret_KeepsExisting(t *testing.T) { - f := newSvcFixture(t) - ctx := context.Background() - if _, err := f.svc.SetConfig(ctx, &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "first", - }); err != nil { - t.Fatalf("initial: %v", err) - } - if _, err := f.svc.SetConfig(ctx, &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, - }); err != nil { - t.Fatalf("update: %v", err) - } - if got, _ := f.secrets.Reveal(ctx, SecretKeyForWorkspace("default")); got != "first" { - t.Errorf("secret should be preserved, got %q", got) - } -} - -func TestService_SetConfig_ProbesAsync(t *testing.T) { - f := newSvcFixture(t) f.client.testAuthFn = func() (*TestConnectionResult, error) { return &TestConnectionResult{OK: true, DisplayName: "Alice"}, nil } - if _, err := f.svc.SetConfig(context.Background(), &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "tok", - }); err != nil { - t.Fatalf("set: %v", err) + cfg, err := f.svc.CreateInstance(ctx, "ws-1", &CreateConfigRequest{ + Name: "SaaS", AuthMethod: AuthMethodAuthToken, Secret: "sntrys_xyz", + }) + if err != nil { + t.Fatalf("create: %v", err) } - cfg := waitForAuthProbe(t, f) - if !cfg.LastOk { - t.Errorf("expected LastOk=true after async probe, got %+v", cfg) + if cfg.ID == "" || cfg.WorkspaceID != "ws-1" || cfg.Name != "SaaS" { + t.Errorf("instance not stored: %+v", cfg) + } + if !cfg.HasSecret { + t.Error("expected HasSecret=true") + } + if got, _ := f.secrets.Reveal(ctx, secretKeyForInstance(cfg.ID)); got != "sntrys_xyz" { + t.Errorf("secret stored under instance key = %q", got) + } + waitForAuthProbe(t, f) + reloaded, _ := f.store.GetInstance(ctx, cfg.ID) + if !reloaded.LastOk { + t.Errorf("expected LastOk=true after async probe, got %+v", reloaded) } } -func TestService_Validation_RejectsBadAuth(t *testing.T) { +func TestService_CreateInstance_SecretSetFailureRollsBackAndAllowsRetry(t *testing.T) { f := newSvcFixture(t) - if _, err := f.svc.SetConfig(context.Background(), &SetConfigRequest{ - AuthMethod: "bogus", - }); err == nil { - t.Error("expected validation error for unknown auth method") + ctx := context.Background() + injected := errors.New("secret store unavailable") + req := &CreateConfigRequest{Name: "SaaS", Secret: "sntrys_xyz"} + + f.secrets.setErr = injected + if _, err := f.svc.CreateInstance(ctx, "ws-1", req); !errors.Is(err, injected) { + t.Fatalf("expected injected secret error, got %v", err) + } + + instances, err := f.store.ListInstances(ctx, "ws-1") + if err != nil { + t.Fatalf("list instances after failed create: %v", err) + } + if len(instances) != 0 { + t.Fatalf("failed create left %d instance(s), want 0", len(instances)) + } + + f.secrets.setErr = nil + created, err := f.svc.CreateInstance(ctx, "ws-1", req) + if err != nil { + t.Fatalf("retry same-name create: %v", err) + } + if created.Name != req.Name { + t.Errorf("retry created unexpected instance: %+v", created) + } + waitForAuthProbe(t, f) +} + +func TestService_CreateInstance_Validation(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + cases := map[string]*CreateConfigRequest{ + "missing name": {Name: "", Secret: "t"}, + "bad auth": {Name: "X", AuthMethod: "bogus"}, + "bad scheme": {Name: "X", URL: "ftp://nope"}, + "non-root url": {Name: "X", URL: "https://sentry.example.com/path"}, + } + for name, req := range cases { + if _, err := f.svc.CreateInstance(ctx, "ws-1", req); !errors.Is(err, ErrInvalidConfig) { + t.Errorf("%s: expected ErrInvalidConfig, got %v", name, err) + } } } -func TestService_Validation_DefaultsAuthMethod(t *testing.T) { +func TestService_CreateInstance_DefaultsAndNormalizesURL(t *testing.T) { f := newSvcFixture(t) - if _, err := f.svc.SetConfig(context.Background(), &SetConfigRequest{Secret: "tok"}); err != nil { - t.Fatalf("expected default auth method, got error: %v", err) + ctx := context.Background() + blank, err := f.svc.CreateInstance(ctx, "ws-1", &CreateConfigRequest{Name: "SaaS", Secret: "t"}) + if err != nil { + t.Fatalf("create blank url: %v", err) + } + if blank.URL != DefaultSentryURL { + t.Errorf("expected URL defaulted to %q, got %q", DefaultSentryURL, blank.URL) + } + host, err := f.svc.CreateInstance(ctx, "ws-1", &CreateConfigRequest{Name: "Self", URL: "sentry.example.com/", Secret: "t"}) + if err != nil { + t.Fatalf("create host url: %v", err) + } + if host.URL != "https://sentry.example.com" { + t.Errorf("expected normalized URL, got %q", host.URL) } } -func TestService_TestConnection_InlineSecret(t *testing.T) { +// TestService_UniqueName_PerWorkspace pins acceptance (h) at the service layer. +func TestService_UniqueName_PerWorkspace(t *testing.T) { f := newSvcFixture(t) + ctx := context.Background() + if _, err := f.svc.CreateInstance(ctx, "ws-1", &CreateConfigRequest{Name: "Prod", Secret: "t"}); err != nil { + t.Fatalf("first: %v", err) + } + if _, err := f.svc.CreateInstance(ctx, "ws-1", &CreateConfigRequest{Name: "Prod", Secret: "t"}); !errors.Is(err, ErrDuplicateInstanceName) { + t.Errorf("expected ErrDuplicateInstanceName, got %v", err) + } + if _, err := f.svc.CreateInstance(ctx, "ws-2", &CreateConfigRequest{Name: "Prod", Secret: "t"}); err != nil { + t.Errorf("same name in another workspace should succeed, got %v", err) + } +} + +// TestService_InstanceCRUD_ScopedPerWorkspace pins acceptance (d): an instance +// is only reachable through its owning workspace. +func TestService_InstanceCRUD_ScopedPerWorkspace(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + a := f.seedInstance(t, "ws-1", "A", "ta") + f.seedInstance(t, "ws-2", "B", "tb") + + if _, err := f.svc.GetInstance(ctx, "ws-1", a.ID); err != nil { + t.Fatalf("get own instance: %v", err) + } + // Cross-workspace GetInstance is a 404, not a leak. + if _, err := f.svc.GetInstance(ctx, "ws-2", a.ID); !errors.Is(err, ErrInstanceNotFound) { + t.Errorf("expected ErrInstanceNotFound cross-workspace, got %v", err) + } + // List is scoped. + list, err := f.svc.ListInstances(ctx, "ws-1") + if err != nil || len(list) != 1 || list[0].ID != a.ID { + t.Fatalf("ListInstances(ws-1) = %+v err=%v", list, err) + } + if !list[0].HasSecret { + t.Error("expected HasSecret=true for seeded instance") + } + // Update / delete cross-workspace are 404. + if _, err := f.svc.UpdateInstance(ctx, "ws-2", a.ID, &UpdateConfigRequest{Name: "hijack"}); !errors.Is(err, ErrInstanceNotFound) { + t.Errorf("expected ErrInstanceNotFound on cross-workspace update, got %v", err) + } + if err := f.svc.DeleteInstance(ctx, "ws-2", a.ID); !errors.Is(err, ErrInstanceNotFound) { + t.Errorf("expected ErrInstanceNotFound on cross-workspace delete, got %v", err) + } +} + +func TestService_UpdateInstance_EmptySecretKeepsExisting(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + created, err := f.svc.CreateInstance(ctx, "ws-1", &CreateConfigRequest{Name: "A", Secret: "first"}) + if err != nil { + t.Fatalf("create: %v", err) + } + waitForAuthProbe(t, f) + if _, err := f.svc.UpdateInstance(ctx, "ws-1", created.ID, &UpdateConfigRequest{Name: "A2"}); err != nil { + t.Fatalf("update: %v", err) + } + waitForAuthProbe(t, f) + if got, _ := f.secrets.Reveal(ctx, secretKeyForInstance(created.ID)); got != "first" { + t.Errorf("secret should be preserved on empty-secret update, got %q", got) + } + reloaded, _ := f.svc.GetInstance(ctx, "ws-1", created.ID) + if reloaded.Name != "A2" { + t.Errorf("name not updated: %q", reloaded.Name) + } +} + +// TestService_UpdateInstance_SecretSetFailureRestoresMetadataAndClient pins +// the metadata/secret rollback and the defensive cache invalidation that +// backs it: a client cached before the update is dropped once the update +// fails, and the next access rebuilds against the restored (not the +// attempted) configuration — closing the narrower race pinned by +// TestService_UpdateInstance_SecretSetFailureInvalidatesRacedClient below, +// where a client built during the failed window must not survive either. +func TestService_UpdateInstance_SecretSetFailureRestoresMetadataAndClient(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + created := f.seedInstance(t, "ws-1", "Original", "old-token") + + type build struct { + url string + secret string + } + var builds []build + f.svc.clientFn = func(cfg *SentryConfig, secret string) Client { + builds = append(builds, build{url: cfg.URL, secret: secret}) + return &fakeClient{} + } + cached, err := f.svc.clientForInstance(ctx, created.ID) + if err != nil { + t.Fatalf("cache original client: %v", err) + } + + injected := errors.New("secret store unavailable") + f.secrets.setErr = injected + if _, err := f.svc.UpdateInstance(ctx, "ws-1", created.ID, &UpdateConfigRequest{ + Name: "Replacement", URL: "https://replacement.example.com", Secret: "new-token", + }); !errors.Is(err, injected) { + t.Fatalf("expected injected secret error, got %v", err) + } + + stored, err := f.store.GetInstance(ctx, created.ID) + if err != nil { + t.Fatalf("reload instance after failed update: %v", err) + } + if stored == nil || stored.Name != "Original" || stored.AuthMethod != AuthMethodAuthToken || stored.URL != DefaultSentryURL { + t.Fatalf("failed update changed persisted metadata: %+v", stored) + } + if secret, err := f.secrets.Reveal(ctx, secretKeyForInstance(created.ID)); err != nil || secret != "old-token" { + t.Errorf("failed update changed persisted secret: secret=%q err=%v", secret, err) + } + + afterFailure, err := f.svc.clientForInstance(ctx, created.ID) + if err != nil { + t.Fatalf("read client after failed update: %v", err) + } + if afterFailure == cached { + t.Error("failed update did not invalidate the pre-existing cached client") + } + if len(builds) != 2 || builds[1].url != DefaultSentryURL || builds[1].secret != "old-token" { + t.Fatalf("expected the post-failure rebuild against the restored config, got %+v", builds) + } +} + +// TestService_UpdateInstance_SecretSetFailureInvalidatesRacedClient pins a +// narrower race than the previous test: a client built and cached DURING the +// failed update (after the row is temporarily persisted with the new URL but +// before the failing secret write) must not survive the rollback. Without an +// invalidation on the successful-rollback path, that stale new-URL+old-secret +// client would keep serving forever, since clientForInstance's cache check +// never re-validates against the store. +func TestService_UpdateInstance_SecretSetFailureInvalidatesRacedClient(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + created := f.seedInstance(t, "ws-1", "Original", "old-token") + + type build struct { + url string + secret string + } + var builds []build + f.svc.clientFn = func(cfg *SentryConfig, secret string) Client { + builds = append(builds, build{url: cfg.URL, secret: secret}) + return &fakeClient{} + } + f.secrets.setErr = errors.New("secret store unavailable") + f.secrets.setHook = func() { + // Runs after UpdateInstance has already persisted the new URL but + // before the secret write it's about to fail — simulating a request + // racing in during that exact window. + if _, err := f.svc.clientForInstance(ctx, created.ID); err != nil { + t.Fatalf("raced client build: %v", err) + } + } + + if _, err := f.svc.UpdateInstance(ctx, "ws-1", created.ID, &UpdateConfigRequest{ + Name: "Replacement", URL: "https://replacement.example.com", Secret: "new-token", + }); !errors.Is(err, f.secrets.setErr) { + t.Fatalf("expected injected secret error, got %v", err) + } + if len(builds) != 1 || builds[0].url != "https://replacement.example.com" || builds[0].secret != "old-token" { + t.Fatalf("expected the race to build against the temporary row, got %+v", builds) + } + + rebuilt, err := f.svc.clientForInstance(ctx, created.ID) + if err != nil { + t.Fatalf("read client after rollback: %v", err) + } + if len(builds) != 2 || builds[1].url != DefaultSentryURL || builds[1].secret != "old-token" { + t.Fatalf("expected a fresh build against the rolled-back row, got %+v", builds) + } + if rebuilt == nil { + t.Error("expected a rebuilt client, got nil") + } +} + +// TestService_UpdateInstance_SecretSetFailureSkipsRollbackOnConcurrentWrite +// pins the fix for a rollback that blindly restored the `previous` row +// snapshot even when a second, concurrent UpdateInstance had landed on the +// same instance between this request's own row write and its failed secret +// write — silently discarding that other write. The rollback must detect +// that the persisted row no longer matches what this request itself wrote +// and skip the restore, while still returning this request's own secretErr. +func TestService_UpdateInstance_SecretSetFailureSkipsRollbackOnConcurrentWrite(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + created := f.seedInstance(t, "ws-1", "Original", "old-token") + + injected := errors.New("secret store unavailable") + f.secrets.setErr = injected + f.secrets.setHook = func() { + // Runs after this UpdateInstance call has already persisted its own + // "Replacement" row but before its secret write fails — simulating a + // second UpdateInstance request landing on the same instance during + // that exact window and winning the race. + concurrent := *created + concurrent.Name = "ConcurrentWinner" + concurrent.AuthMethod = AuthMethodAuthToken + concurrent.URL = "https://concurrent.example.com" + if err := f.store.UpdateInstance(context.Background(), &concurrent); err != nil { + t.Fatalf("simulate concurrent update: %v", err) + } + } + + if _, err := f.svc.UpdateInstance(ctx, "ws-1", created.ID, &UpdateConfigRequest{ + Name: "Replacement", URL: "https://replacement.example.com", Secret: "new-token", + }); !errors.Is(err, injected) { + t.Fatalf("expected injected secret error, got %v", err) + } + + stored, err := f.store.GetInstance(ctx, created.ID) + if err != nil { + t.Fatalf("reload instance after failed update: %v", err) + } + if stored == nil || stored.Name != "ConcurrentWinner" || stored.URL != "https://concurrent.example.com" { + t.Fatalf("rollback clobbered the concurrent write: %+v", stored) + } +} + +func TestService_DeleteInstance_RemovesSecretAndCache(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + created, err := f.svc.CreateInstance(ctx, "ws-1", &CreateConfigRequest{Name: "A", Secret: "t"}) + if err != nil { + t.Fatalf("create: %v", err) + } + waitForAuthProbe(t, f) + if err := f.svc.DeleteInstance(ctx, "ws-1", created.ID); err != nil { + t.Fatalf("delete: %v", err) + } + if exists, _ := f.secrets.Exists(ctx, secretKeyForInstance(created.ID)); exists { + t.Error("expected secret removed") + } + if _, err := f.svc.GetInstance(ctx, "ws-1", created.ID); !errors.Is(err, ErrInstanceNotFound) { + t.Errorf("expected instance gone, got %v", err) + } +} + +// TestService_DeleteInstance_InUse pins acceptance (f): an instance referenced +// by a watch cannot be deleted; the error carries the watch count. +func TestService_DeleteInstance_InUse(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + inst := f.seedInstance(t, "ws-1", "A", "t") + w := newTestIssueWatch("ws-1") + w.SentryInstanceID = inst.ID + if err := f.store.CreateIssueWatch(ctx, w); err != nil { + t.Fatalf("create watch: %v", err) + } + // Add a disabled watch too — the count must include it. + w2 := newTestIssueWatch("ws-1") + w2.SentryInstanceID = inst.ID + w2.Enabled = false + if err := f.store.CreateIssueWatch(ctx, w2); err != nil { + t.Fatalf("create disabled watch: %v", err) + } + err := f.svc.DeleteInstance(ctx, "ws-1", inst.ID) + var inUse ErrInstanceInUse + if !errors.As(err, &inUse) { + t.Fatalf("expected ErrInstanceInUse, got %v", err) + } + if inUse.WatchCount != 2 { + t.Errorf("expected watch count 2 (enabled + disabled), got %d", inUse.WatchCount) + } +} + +func TestService_TestConnectionCandidate(t *testing.T) { + f := newSvcFixture(t) + var seenURL string + f.svc.clientFn = func(cfg *SentryConfig, secret string) Client { + seenURL = cfg.URL + return f.client + } called := false f.client.testAuthFn = func() (*TestConnectionResult, error) { called = true - return &TestConnectionResult{OK: true, DisplayName: "Alice"}, nil + return &TestConnectionResult{OK: true}, nil } - res, err := f.svc.TestConnection(context.Background(), &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "inline-tok", + res, err := f.svc.TestConnectionCandidate(context.Background(), &CreateConfigRequest{ + AuthMethod: AuthMethodAuthToken, Secret: "inline", URL: "https://sentry.example.com", }) - if err != nil || !called { - t.Fatalf("called=%v err=%v", called, err) + if err != nil || !called || !res.OK { + t.Fatalf("called=%v res=%+v err=%v", called, res, err) } - if !res.OK { - t.Errorf("result: %+v", res) + if seenURL != "https://sentry.example.com" { + t.Errorf("expected configured URL passed to client, got %q", seenURL) + } + // No secret → failure result, no client call. + res, err = f.svc.TestConnectionCandidate(context.Background(), &CreateConfigRequest{AuthMethod: AuthMethodAuthToken}) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if res.OK { + t.Error("expected OK=false when no secret provided") } } -func TestService_TestConnection_UsesStoredSecretWhenRequestEmpty(t *testing.T) { +func TestService_TestInstance_UsesStoredSecret(t *testing.T) { f := newSvcFixture(t) ctx := context.Background() - if _, err := f.svc.SetConfig(ctx, &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "stored", - }); err != nil { - t.Fatalf("set: %v", err) - } - waitForAuthProbe(t, f) + inst := f.seedInstance(t, "ws-1", "A", "stored") var sawSecret string f.svc.clientFn = func(_ *SentryConfig, secret string) Client { sawSecret = secret return f.client } - if _, err := f.svc.TestConnection(ctx, &SetConfigRequest{AuthMethod: AuthMethodAuthToken}); err != nil { + if _, err := f.svc.TestInstance(ctx, "ws-1", inst.ID); err != nil { t.Fatalf("test: %v", err) } if sawSecret != "stored" { t.Errorf("expected stored secret used, got %q", sawSecret) } -} - -func TestService_TestConnection_NoStoredSecret_ReturnsFailure(t *testing.T) { - f := newSvcFixture(t) - res, err := f.svc.TestConnection(context.Background(), &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, - }) - if err != nil { - t.Fatalf("unexpected err: %v", err) - } - if res.OK { - t.Error("expected OK=false when no secret stored") + // Cross-workspace test is a 404. + if _, err := f.svc.TestInstance(ctx, "ws-2", inst.ID); !errors.Is(err, ErrInstanceNotFound) { + t.Errorf("expected ErrInstanceNotFound cross-workspace, got %v", err) } } -func TestService_SearchIssues_PassesFilterThrough(t *testing.T) { +func TestService_Browse_RequireInstanceAndForwardsFilter(t *testing.T) { f := newSvcFixture(t) ctx := context.Background() - if _, err := f.svc.SetConfig(ctx, &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "t", - }); err != nil { - t.Fatalf("set: %v", err) + inst := f.seedInstance(t, "ws-1", "A", "t") + + // Missing instance ID → ErrInstanceRequired. + if _, err := f.svc.SearchIssues(ctx, "ws-1", "", SearchFilter{OrgSlug: "acme"}, ""); !errors.Is(err, ErrInstanceRequired) { + t.Errorf("expected ErrInstanceRequired for blank instanceID, got %v", err) + } + // Cross-workspace instance → ErrInstanceNotFound. + if _, err := f.svc.SearchIssues(ctx, "ws-2", inst.ID, SearchFilter{OrgSlug: "acme"}, ""); !errors.Is(err, ErrInstanceNotFound) { + t.Errorf("expected ErrInstanceNotFound cross-workspace, got %v", err) } - waitForAuthProbe(t, f) var seenOrg string f.client.searchIssuesFn = func(filter SearchFilter, _ string) (*SearchResult, error) { seenOrg = filter.OrgSlug return &SearchResult{IsLast: true}, nil } - if _, err := f.svc.SearchIssues(ctx, SearchFilter{OrgSlug: "acme"}, ""); err != nil { + if _, err := f.svc.SearchIssues(ctx, "ws-1", inst.ID, SearchFilter{OrgSlug: "acme"}, ""); err != nil { t.Fatalf("search: %v", err) } if seenOrg != "acme" { @@ -318,225 +650,133 @@ func TestService_SearchIssues_PassesFilterThrough(t *testing.T) { } } -func TestService_GetIssue_NotConfigured(t *testing.T) { +func TestService_GetIssue_NotConfiguredWhenNoSecret(t *testing.T) { f := newSvcFixture(t) - _, err := f.svc.GetIssue(context.Background(), "PROJ-1") - if !errors.Is(err, ErrNotConfigured) { - t.Errorf("expected ErrNotConfigured, got %v", err) + ctx := context.Background() + // Instance exists but has no stored secret → ErrNotConfigured (503). + inst := f.seedInstance(t, "ws-1", "A", "") + if _, err := f.svc.GetIssue(ctx, "ws-1", inst.ID, "PROJ-1"); !errors.Is(err, ErrNotConfigured) { + t.Errorf("expected ErrNotConfigured for secretless instance, got %v", err) + } + // Unknown instance → ErrInstanceNotFound (404). + if _, err := f.svc.GetIssue(ctx, "ws-1", "ghost", "PROJ-1"); !errors.Is(err, ErrInstanceNotFound) { + t.Errorf("expected ErrInstanceNotFound for unknown instance, got %v", err) } } -func TestService_DeleteConfig_RemovesSecretAndCache(t *testing.T) { +// TestService_ClientCache_PerInstanceIsolation pins acceptance (j): each +// instance caches its own client; invalidating one does not rebuild the other. +func TestService_ClientCache_PerInstanceIsolation(t *testing.T) { f := newSvcFixture(t) ctx := context.Background() - _, _ = f.svc.SetConfig(ctx, &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "t", - }) - waitForAuthProbe(t, f) - if err := f.svc.DeleteConfig(ctx); err != nil { - t.Fatalf("delete: %v", err) + a := f.seedInstance(t, "ws-1", "A", "ta") + b := f.seedInstance(t, "ws-1", "B", "tb") + + if _, err := f.svc.clientForInstance(ctx, a.ID); err != nil { + t.Fatalf("client a: %v", err) } - if exists, _ := f.secrets.Exists(ctx, SecretKey); exists { - t.Error("expected secret removed") + if _, err := f.svc.clientForInstance(ctx, b.ID); err != nil { + t.Fatalf("client b: %v", err) } - cfg, _ := f.svc.GetConfig(ctx) - if cfg != nil { - t.Errorf("expected config gone, got %+v", cfg) + if got := f.factoryHit.Load(); got != 2 { + t.Fatalf("expected 2 factory hits (one per instance), got %d", got) + } + // Cached: no new build. + _, _ = f.svc.clientForInstance(ctx, a.ID) + _, _ = f.svc.clientForInstance(ctx, b.ID) + if got := f.factoryHit.Load(); got != 2 { + t.Fatalf("expected cache hits (still 2 builds), got %d", got) + } + // Invalidate A only → A rebuilds, B stays cached. + f.svc.invalidateClient(a.ID) + _, _ = f.svc.clientForInstance(ctx, a.ID) + _, _ = f.svc.clientForInstance(ctx, b.ID) + if got := f.factoryHit.Load(); got != 3 { + t.Fatalf("expected only A to rebuild (3 total), got %d", got) } } // TestService_ClientFor_InvalidateDuringBuild verifies the TOCTOU fix: when -// invalidateClient runs while clientFor is blocked on I/O, the freshly built -// (now-stale) client must not be stored in s.client. The subsequent call must -// rebuild, hitting the factory a second time. +// invalidateClient runs while clientForInstance is blocked on I/O, the freshly +// built (now-stale) client must not be cached. The next call must rebuild. func TestService_ClientFor_InvalidateDuringBuild(t *testing.T) { - fakes := newFakeSecretStore() - _ = fakes.Set(context.Background(), SecretKeyForWorkspace("default"), "tok", "sntrys_xyz") - store := newTestStore(t) ctx := context.Background() - // Seed a config row so clientFor gets past the nil-config check. - if err := store.UpsertConfig(ctx, &SentryConfig{ - AuthMethod: AuthMethodAuthToken, - }); err != nil { - t.Fatalf("seed config: %v", err) + cfg := &SentryConfig{WorkspaceID: "ws-1", Name: "A", AuthMethod: AuthMethodAuthToken, URL: DefaultSentryURL} + if err := store.CreateInstance(ctx, cfg); err != nil { + t.Fatalf("seed instance: %v", err) } + fakes := newFakeSecretStore() + _ = fakes.Set(ctx, secretKeyForInstance(cfg.ID), "tok", "sntrys_xyz") var factoryHit atomic.Int32 client := &fakeClient{} - - // invalidateCh is closed by the Reveal hook to signal the main goroutine - // to call invalidateClient while the first clientFor is mid-I/O. - invalidateCh := make(chan struct{}) - // doneCh is closed by the Reveal hook after it has signalled. - doneCh := make(chan struct{}) - slow := &slowSecretStore{fakeSecretStore: fakes} - svc := NewService(store, slow, func(_ *SentryConfig, _ string) Client { factoryHit.Add(1) return client }, logger.Default()) + invalidateCh := make(chan struct{}) slow.revealHook = func() { - // Signal that we're mid-I/O, then wait for the invalidation to complete. close(invalidateCh) - // Give the invalidation goroutine time to run. time.Sleep(10 * time.Millisecond) - close(doneCh) } - // First clientFor call — will block in Reveal while we invalidate. errCh := make(chan error, 1) go func() { - _, err := svc.clientFor(ctx, "default") + _, err := svc.clientForInstance(ctx, cfg.ID) errCh <- err }() - - // Wait until clientFor is inside Reveal, then invalidate. <-invalidateCh - svc.invalidateClient("default") - - // Wait for the first clientFor to finish. + svc.invalidateClient(cfg.ID) if err := <-errCh; err != nil { - t.Fatalf("first clientFor: %v", err) + t.Fatalf("first clientForInstance: %v", err) } - - // The invalidation must have reset the cache, so s.client should be nil now. - // A second clientFor must hit the factory again (not return the cached stale client). - slow.revealHook = nil // no more blocking - if _, err := svc.clientFor(ctx, "default"); err != nil { - t.Fatalf("second clientFor: %v", err) + slow.revealHook = nil + if _, err := svc.clientForInstance(ctx, cfg.ID); err != nil { + t.Fatalf("second clientForInstance: %v", err) } - if got := factoryHit.Load(); got < 2 { - t.Errorf("expected factory called at least twice (once per clientFor after invalidation), got %d", got) + t.Errorf("expected factory called at least twice after invalidation, got %d", got) } } -// TestService_SetConfig_DefaultsURLToSentryIO asserts a blank instance URL is -// stored as the sentry.io SaaS default. -func TestService_SetConfig_DefaultsURLToSentryIO(t *testing.T) { - f := newSvcFixture(t) - cfg, err := f.svc.SetConfig(context.Background(), &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "tok", - }) - if err != nil { - t.Fatalf("set: %v", err) - } - if cfg.URL != DefaultSentryURL { - t.Errorf("expected URL defaulted to %q, got %q", DefaultSentryURL, cfg.URL) - } -} - -// TestService_SetConfig_NormalizesAndPersistsURL asserts a host-only URL is -// normalized (scheme added, trailing slash trimmed) before being stored. -func TestService_SetConfig_NormalizesAndPersistsURL(t *testing.T) { - f := newSvcFixture(t) - cfg, err := f.svc.SetConfig(context.Background(), &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "tok", URL: "sentry.example.com/", - }) - if err != nil { - t.Fatalf("set: %v", err) - } - if cfg.URL != "https://sentry.example.com" { - t.Errorf("expected normalized URL, got %q", cfg.URL) - } -} - -// TestService_SetConfig_RejectsMalformedURL asserts a non-http(s) URL is -// rejected at save time. -func TestService_SetConfig_RejectsMalformedURL(t *testing.T) { - f := newSvcFixture(t) - _, err := f.svc.SetConfig(context.Background(), &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "tok", URL: "ftp://nope", - }) - if err == nil { - t.Error("expected validation error for non-http(s) URL") - } -} - -// TestService_TestConnection_PassesConfiguredURL ensures a pre-save test uses -// the URL the user typed in the form, so a self-hosted instance can be -// validated before the config is persisted. -func TestService_TestConnection_PassesConfiguredURL(t *testing.T) { - f := newSvcFixture(t) - var sawURL string - f.svc.clientFn = func(cfg *SentryConfig, _ string) Client { - sawURL = cfg.URL - return f.client - } - if _, err := f.svc.TestConnection(context.Background(), &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "inline", URL: "https://sentry.example.com", - }); err != nil { - t.Fatalf("test: %v", err) - } - if sawURL != "https://sentry.example.com" { - t.Errorf("expected configured URL passed to client, got %q", sawURL) - } -} - -// TestService_TestConnection_FallsBackToStoredURL covers the post-save "Test -// connection" path (blank secret, blank URL in the request): the stored -// instance URL must be used rather than silently reverting to sentry.io. -func TestService_TestConnection_FallsBackToStoredURL(t *testing.T) { +// TestService_DeleteInstance_SoleInstanceCountsUnboundWatches pins the P1 fix: +// deleting a workspace's sole instance must be refused while unbound (NULL +// sentry_instance_id) watches exist, because resolveWatchInstanceID resolves +// them to that instance at poll time. The unbound watch does not trip the FK +// (its instance id is NULL), so the service must count it explicitly. +func TestService_DeleteInstance_SoleInstanceCountsUnboundWatches(t *testing.T) { f := newSvcFixture(t) ctx := context.Background() - if _, err := f.svc.SetConfig(ctx, &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "stored", URL: "https://sentry.example.com", - }); err != nil { - t.Fatalf("set: %v", err) + inst := f.seedInstance(t, "ws-1", "A", "t") + // Unbound watch: no SentryInstanceID → NULL in the DB. + if err := f.store.CreateIssueWatch(ctx, newTestIssueWatch("ws-1")); err != nil { + t.Fatalf("create unbound watch: %v", err) } - waitForAuthProbe(t, f) - var sawURL string - f.svc.clientFn = func(cfg *SentryConfig, _ string) Client { - sawURL = cfg.URL - return f.client + err := f.svc.DeleteInstance(ctx, "ws-1", inst.ID) + var inUse ErrInstanceInUse + if !errors.As(err, &inUse) { + t.Fatalf("expected ErrInstanceInUse for sole instance with unbound watch, got %v", err) } - if _, err := f.svc.TestConnection(ctx, &SetConfigRequest{AuthMethod: AuthMethodAuthToken}); err != nil { - t.Fatalf("test: %v", err) - } - if sawURL != "https://sentry.example.com" { - t.Errorf("expected stored URL used, got %q", sawURL) + if inUse.WatchCount != 1 { + t.Errorf("expected unbound watch counted (1), got %d", inUse.WatchCount) } } -// TestService_SetConfig_RejectsNonRootURL asserts URLs carrying a path, query, -// or fragment are rejected, so /api/0 cannot be appended to a malformed base. -func TestService_SetConfig_RejectsNonRootURL(t *testing.T) { - cases := []struct { - name string - url string - }{ - {"path", "https://sentry.example.com/some/path"}, - {"query", "https://sentry.example.com?x=1"}, - {"fragment", "https://sentry.example.com#frag"}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - f := newSvcFixture(t) - _, err := f.svc.SetConfig(context.Background(), &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "tok", URL: tc.url, - }) - if err == nil { - t.Errorf("expected rejection of non-root URL %q", tc.url) - } - }) - } -} - -// TestService_SetConfig_AllowsHostRootWithTrailingSlash guards the boundary: -// a bare host root (with or without a trailing slash) must still be accepted -// and normalized, so the non-root rejection above doesn't over-reach. -func TestService_SetConfig_AllowsHostRootWithTrailingSlash(t *testing.T) { +// TestService_DeleteInstance_UnboundNotCountedWhenMultipleInstances is the +// complement: with a second instance present, an unbound watch stays resolvable +// after one instance is removed, so it must not block that delete. +func TestService_DeleteInstance_UnboundNotCountedWhenMultipleInstances(t *testing.T) { f := newSvcFixture(t) - cfg, err := f.svc.SetConfig(context.Background(), &SetConfigRequest{ - AuthMethod: AuthMethodAuthToken, Secret: "tok", URL: "https://sentry.example.com/", - }) - if err != nil { - t.Fatalf("host root with trailing slash should be accepted: %v", err) + ctx := context.Background() + a := f.seedInstance(t, "ws-1", "A", "t") + f.seedInstance(t, "ws-1", "B", "t") + if err := f.store.CreateIssueWatch(ctx, newTestIssueWatch("ws-1")); err != nil { + t.Fatalf("create unbound watch: %v", err) } - if cfg.URL != "https://sentry.example.com" { - t.Errorf("expected trailing slash trimmed, got %q", cfg.URL) + if err := f.svc.DeleteInstance(ctx, "ws-1", a.ID); err != nil { + t.Fatalf("expected delete to succeed with a second instance present, got %v", err) } } diff --git a/apps/backend/internal/sentry/store.go b/apps/backend/internal/sentry/store.go index 323c4c4191..87d9a9c550 100644 --- a/apps/backend/internal/sentry/store.go +++ b/apps/backend/internal/sentry/store.go @@ -5,19 +5,21 @@ import ( "database/sql" "errors" "fmt" + "net/url" + "strings" "time" + "github.com/google/uuid" "github.com/jmoiron/sqlx" "github.com/kandev/kandev/internal/integrations/workspacescope" ) -// Store persists workspace-scoped Sentry configuration. The secret token is -// delegated to the shared encrypted secret store and not stored here. +// Store persists workspace-scoped Sentry instances. Each instance's secret +// token is delegated to the shared encrypted secret store and not stored here. type Store struct { db *sqlx.DB ro *sqlx.DB - defaultWorkspace workspacescope.DefaultResolver migratedToWorkspace string } @@ -30,21 +32,34 @@ func NewStore(writer, reader *sqlx.DB) (*Store, error) { return s, nil } -const createTablesSQL = ` - CREATE TABLE IF NOT EXISTS sentry_configs ( - workspace_id TEXT PRIMARY KEY, +// sentryConfigsColumns is the id-keyed multi-instance sentry_configs column +// list, shared by createTablesSQL and the workspace→instance rebuild so the two +// can never drift. +const sentryConfigsColumns = ` + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL, + name TEXT NOT NULL, auth_method TEXT NOT NULL, url TEXT NOT NULL DEFAULT 'https://sentry.io', last_checked_at DATETIME, last_ok INTEGER NOT NULL DEFAULT 0, last_error TEXT NOT NULL DEFAULT '', created_at DATETIME NOT NULL, - updated_at DATETIME NOT NULL - ); + updated_at DATETIME NOT NULL, + UNIQUE(workspace_id, name)` - CREATE TABLE IF NOT EXISTS sentry_issue_watches ( +// sentryWatchesColumns is the sentry_issue_watches column list including the +// nullable sentry_instance_id foreign key. Shared by createTablesSQL and the +// instance-column rebuild. +const sentryWatchesColumns = ` id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, + -- Bound Sentry instance. NULL = legacy unbound watch (created before a + -- workspace had an instance, or migrated from the single-config model); + -- the poller resolves an unbound watch to the workspace's sole instance + -- at poll time. ON DELETE RESTRICT so an in-use instance cannot be + -- deleted out from under a watch. + sentry_instance_id TEXT, workflow_id TEXT NOT NULL, workflow_step_id TEXT NOT NULL, -- Optional repository binding. Empty = unbound (repo-less task, the @@ -63,7 +78,16 @@ const createTablesSQL = ` last_error TEXT NOT NULL DEFAULT '', last_error_at DATETIME, created_at DATETIME NOT NULL, - updated_at DATETIME NOT NULL + updated_at DATETIME NOT NULL, + FOREIGN KEY(sentry_instance_id) REFERENCES sentry_configs(id) ON DELETE RESTRICT` + +const createTablesSQL = ` + CREATE TABLE IF NOT EXISTS sentry_configs (` + sentryConfigsColumns + ` + ); + CREATE INDEX IF NOT EXISTS idx_sentry_configs_workspace + ON sentry_configs(workspace_id); + + CREATE TABLE IF NOT EXISTS sentry_issue_watches (` + sentryWatchesColumns + ` ); CREATE INDEX IF NOT EXISTS idx_sentry_issue_watches_workspace ON sentry_issue_watches(workspace_id); @@ -85,17 +109,31 @@ const createTablesSQL = ` const singletonID = "singleton" // MigratedFromWorkspace is kept for parity with Jira/Linear provider -// migrations. It returns the workspace_id that received a legacy singleton row. +// migrations. It returns the workspace_id that received a legacy singleton row, +// so the provider secret migration can rekey the token from the singleton +// secret key to the workspace key before it is rekeyed again per instance. func (s *Store) MigratedFromWorkspace() string { return s.migratedToWorkspace } -// initSchema creates the integration tables when absent and applies the -// additive column migrations that bring older databases to the current schema. +// initSchema brings any database shape up to the id-keyed multi-instance model +// and applies the additive column migrations. Ordering matters: +// 1. legacy singleton → workspace-keyed (PR #1572's migration, kept verbatim); +// 2. workspace-keyed → id-keyed instances (this change); +// 3. createTablesSQL builds any absent table (fresh install, or the empty +// sentry_configs a watches-only migration needs to reference); +// 4. additive ALTER-ADD column migrations reach the full pre-FK watches shape; +// 5. watches table rebuild adds the nullable sentry_instance_id FK + backfill. +// +// Steps 2 and 5 are each guarded on shape detection so a crash between them +// re-runs safely. func (s *Store) initSchema() error { if err := s.migrateLegacySingletonTable(); err != nil { return err } + if err := s.migrateConfigsTableToInstances(); err != nil { + return err + } if _, err := s.db.Exec(createTablesSQL); err != nil { return err } @@ -108,7 +146,19 @@ func (s *Store) initSchema() error { if err := s.addIssueWatchLastErrorColumns(); err != nil { return err } - return s.addIssueWatchRepositoryColumns() + if err := s.addIssueWatchRepositoryColumns(); err != nil { + return err + } + if err := s.migrateWatchesAddInstanceColumn(); err != nil { + return err + } + // The instance index is created here rather than in createTablesSQL: on a + // pre-#1572 database the watches table exists without the sentry_instance_id + // column until the rebuild above adds it, so indexing that column earlier + // would fail. Idempotent for fresh installs (column already present). + _, err := s.db.Exec(`CREATE INDEX IF NOT EXISTS idx_sentry_issue_watches_instance + ON sentry_issue_watches(sentry_instance_id)`) + return err } func (s *Store) migrateLegacySingletonTable() error { @@ -187,6 +237,364 @@ func (s *Store) migrateLegacySingletonTable() error { return nil } +// legacyWorkspaceConfig is one row of the pre-instance workspace-keyed +// sentry_configs table, read before the id-keyed rebuild. +type legacyWorkspaceConfig struct { + workspaceID string + authMethod string + url string + lastCheckedAt sql.NullTime + lastOk int64 + lastError string + createdAt sql.NullTime + updatedAt sql.NullTime +} + +// migrateConfigsTableToInstances rebuilds a workspace-keyed sentry_configs +// table (PR #1572's one-config-per-workspace shape: workspace_id PRIMARY KEY, +// no id column) into the id-keyed multi-instance shape, creating exactly one +// instance per existing workspace row (id=uuid, name derived from the URL host +// with per-workspace suffixing on collision). Idempotent: a table that already +// has an id column (fresh install or a completed prior run) is left untouched, +// so a crash between this step and the watch rebuild re-runs safely. +func (s *Store) migrateConfigsTableToInstances() error { + cols, err := s.tableColumns("sentry_configs") + if err != nil { + return err + } + if len(cols) == 0 { + return nil // fresh install — createTablesSQL builds the id-keyed table. + } + if _, hasID := cols["id"]; hasID { + return nil // already id-keyed. + } + if _, hasWorkspace := cols["workspace_id"]; !hasWorkspace { + return nil // unexpected shape; the legacy-singleton path owns it. + } + legacy, err := s.readLegacyWorkspaceConfigs(cols) + if err != nil { + return err + } + usedNames := make(map[string]map[string]struct{}) + ids := make([]string, len(legacy)) + names := make([]string, len(legacy)) + for i, r := range legacy { + if usedNames[r.workspaceID] == nil { + usedNames[r.workspaceID] = make(map[string]struct{}) + } + ids[i] = uuid.New().String() + names[i] = uniqueInstanceName(usedNames[r.workspaceID], hostFromURL(r.url)) + } + tx, err := s.db.Begin() + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + if _, err := tx.Exec(`DROP TABLE sentry_configs`); err != nil { + return err + } + if _, err := tx.Exec(`CREATE TABLE sentry_configs (` + sentryConfigsColumns + `)`); err != nil { + return err + } + for i, r := range legacy { + if _, err := tx.Exec(` + INSERT INTO sentry_configs (id, workspace_id, name, auth_method, url, + last_checked_at, last_ok, last_error, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ids[i], r.workspaceID, names[i], r.authMethod, r.url, + nullableTime(r.lastCheckedAt), r.lastOk, r.lastError, + nullableTime(r.createdAt), nullableTime(r.updatedAt)); err != nil { + return err + } + } + return tx.Commit() +} + +// readLegacyWorkspaceConfigs reads every row of the workspace-keyed +// sentry_configs table, defaulting url / health columns for databases predating +// them so the rebuild always has a complete row. +func (s *Store) readLegacyWorkspaceConfigs(cols map[string]struct{}) ([]legacyWorkspaceConfig, error) { + selectCols := "workspace_id, auth_method" + if _, ok := cols["url"]; ok { + selectCols += ", url" + } else { + selectCols += ", 'https://sentry.io' AS url" + } + if healthColumnsPresent(cols) { + selectCols += ", last_checked_at, last_ok, last_error" + } else { + selectCols += ", NULL AS last_checked_at, 0 AS last_ok, '' AS last_error" + } + selectCols += ", created_at, updated_at" + rows, err := s.db.Query(`SELECT ` + selectCols + ` FROM sentry_configs ORDER BY created_at, workspace_id`) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + var out []legacyWorkspaceConfig + for rows.Next() { + var r legacyWorkspaceConfig + if err := rows.Scan(&r.workspaceID, &r.authMethod, &r.url, + &r.lastCheckedAt, &r.lastOk, &r.lastError, &r.createdAt, &r.updatedAt); err != nil { + return nil, err + } + out = append(out, r) + } + return out, rows.Err() +} + +// migrateWatchesAddInstanceColumn rebuilds sentry_issue_watches to add the +// nullable sentry_instance_id foreign key. SQLite cannot ALTER-ADD a column +// with a FOREIGN KEY clause, so the table is rebuilt: create new, copy rows, +// drop old, rename. An unbound watch is backfilled only when its workspace has +// exactly one instance; zero or multiple candidates remain NULL for the +// poll-time fallback. Existing valid experimental bindings survive the rebuild. +// The rebuild runs on a dedicated connection with foreign_keys temporarily off +// so DROP TABLE does not cascade-delete sentry_issue_watch_tasks children (the +// PRAGMA is a no-op inside a transaction and per-connection), then restores +// enforcement. Idempotent: the migration is skipped only when the column +// already has the exact nullable-FK target shape, so a crash mid-migration (or +// an older wrong-shaped column) always re-runs safely. +func (s *Store) migrateWatchesAddInstanceColumn() error { + cols, err := s.tableColumns("sentry_issue_watches") + if err != nil { + return err + } + if len(cols) == 0 { + return nil // fresh install — createTablesSQL builds the column + FK. + } + hasExistingInstanceID := false + if _, ok := cols["sentry_instance_id"]; ok { + correct, err := s.watchesInstanceColumnCorrect() + if err != nil { + return err + } + if correct { + return nil // already the nullable-FK shape. + } + // Column exists but predates the FK/nullable schema (an experimental + // pre-release build stored it as NOT NULL DEFAULT '' with no foreign + // key). Rebuild it into the correct shape while preserving a valid + // explicit binding. + hasExistingInstanceID = true + } + ctx := context.Background() + conn, err := s.db.Conn(ctx) + if err != nil { + return err + } + defer func() { _ = conn.Close() }() + if _, err := conn.ExecContext(ctx, `PRAGMA foreign_keys = OFF`); err != nil { + return err + } + // Restore enforcement on the way out regardless of outcome. + defer func() { _, _ = conn.ExecContext(ctx, `PRAGMA foreign_keys = ON`) }() + return rebuildWatchesWithInstanceColumn(ctx, conn, hasExistingInstanceID) +} + +// watchesInstanceColumnCorrect reports whether sentry_issue_watches +// .sentry_instance_id already has the target shape: a NULLABLE column backed by +// a foreign key to sentry_configs. Older experimental builds added it as +// NOT NULL DEFAULT ” without a foreign key; those must be rebuilt, not skipped. +func (s *Store) watchesInstanceColumnCorrect() (bool, error) { + nullable, err := s.columnIsNullable("sentry_issue_watches", "sentry_instance_id") + if err != nil { + return false, err + } + if !nullable { + return false, nil + } + return s.hasForeignKey("sentry_issue_watches", "sentry_instance_id", "sentry_configs", "id", "RESTRICT") +} + +// columnIsNullable reports whether a column exists and permits NULL (PRAGMA +// table_info notnull flag == 0). +func (s *Store) columnIsNullable(table, column string) (bool, error) { + rows, err := s.db.Query(fmt.Sprintf("PRAGMA table_info(%s)", table)) + if err != nil { + return false, err + } + defer func() { _ = rows.Close() }() + for rows.Next() { + var ( + cid int + name string + ctype string + notnull int + dflt sql.NullString + pk int + ) + if err := rows.Scan(&cid, &name, &ctype, ¬null, &dflt, &pk); err != nil { + return false, err + } + if name == column { + return notnull == 0, nil + } + } + return false, rows.Err() +} + +// hasForeignKey reports whether `table` has a foreign key from `column` to +// `refTable(wantRefColumn)` with the given ON DELETE rule (PRAGMA +// foreign_key_list; SQLite reports on_delete uppercased, e.g. "RESTRICT"). +func (s *Store) hasForeignKey(table, column, refTable, wantRefColumn, wantOnDelete string) (bool, error) { + rows, err := s.db.Query(fmt.Sprintf("PRAGMA foreign_key_list(%s)", table)) + if err != nil { + return false, err + } + type fkRow struct { + from string + refTbl string + to sql.NullString + onDelete string + } + var fks []fkRow + for rows.Next() { + var ( + id int + seq int + refTbl string + from string + to sql.NullString + onUpdate string + onDelete string + match string + ) + if err := rows.Scan(&id, &seq, &refTbl, &from, &to, &onUpdate, &onDelete, &match); err != nil { + _ = rows.Close() + return false, err + } + fks = append(fks, fkRow{from: from, refTbl: refTbl, to: to, onDelete: onDelete}) + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return false, err + } + if err := rows.Close(); err != nil { + return false, err + } + for _, fk := range fks { + if fk.from != column || fk.refTbl != refTable || fk.onDelete != wantOnDelete { + continue + } + toColumn := fk.to.String + if !fk.to.Valid { + // SQLite reports `to` as NULL when the FK references the referenced + // table's PRIMARY KEY implicitly (`REFERENCES sentry_configs` rather + // than `REFERENCES sentry_configs(id)`). Resolve it to the + // single-column PK — after the rows above are closed so this nested + // query never contends for a single-connection pool. + pk, err := s.singleColumnPrimaryKey(fk.refTbl) + if err != nil { + return false, err + } + toColumn = pk + } + if toColumn == wantRefColumn { + return true, nil + } + } + return false, nil +} + +// singleColumnPrimaryKey returns the primary-key column of table when it has +// exactly one; empty for a table with no primary key or a composite one. Used +// to resolve a NULL `to` in foreign_key_list, which SQLite reports when a FK +// references the referenced table's PRIMARY KEY implicitly. +func (s *Store) singleColumnPrimaryKey(table string) (string, error) { + rows, err := s.db.Query(fmt.Sprintf("PRAGMA table_info(%s)", table)) + if err != nil { + return "", err + } + defer func() { _ = rows.Close() }() + pkCols := make([]string, 0, 1) + for rows.Next() { + var ( + cid int + name string + ctype string + notnull int + dflt sql.NullString + pk int + ) + if err := rows.Scan(&cid, &name, &ctype, ¬null, &dflt, &pk); err != nil { + return "", err + } + if pk > 0 { + pkCols = append(pkCols, name) + } + } + if err := rows.Err(); err != nil { + return "", err + } + if len(pkCols) == 1 { + return pkCols[0], nil + } + return "", nil +} + +// rebuildWatchesWithInstanceColumn performs the create/copy/drop/rename table +// rebuild inside a single transaction on conn (which already has foreign_keys +// disabled). A legacy unbound watch is backfilled only when its workspace has +// exactly one instance; otherwise NULL preserves the poll-time fallback. +func rebuildWatchesWithInstanceColumn(ctx context.Context, conn *sql.Conn, hasExistingInstanceID bool) error { + instanceIDExpr := ` + CASE + WHEN (SELECT COUNT(*) FROM sentry_configs c WHERE c.workspace_id = w.workspace_id) = 1 THEN + (SELECT c.id FROM sentry_configs c WHERE c.workspace_id = w.workspace_id) + ELSE NULL + END` + if hasExistingInstanceID { + instanceIDExpr = ` + CASE + WHEN w.sentry_instance_id <> '' THEN + (SELECT c.id FROM sentry_configs c + WHERE c.id = w.sentry_instance_id AND c.workspace_id = w.workspace_id) + WHEN (SELECT COUNT(*) FROM sentry_configs c WHERE c.workspace_id = w.workspace_id) = 1 THEN + (SELECT c.id FROM sentry_configs c WHERE c.workspace_id = w.workspace_id) + ELSE NULL + END` + } + tx, err := conn.BeginTx(ctx, nil) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + if _, err := tx.ExecContext(ctx, `CREATE TABLE sentry_issue_watches_new (`+sentryWatchesColumns+`)`); err != nil { + return err + } + copySQL := ` + INSERT INTO sentry_issue_watches_new ( + id, workspace_id, sentry_instance_id, workflow_id, workflow_step_id, + repository_id, base_branch, filter_json, agent_profile_id, + executor_profile_id, prompt, enabled, poll_interval_seconds, + max_inflight_tasks, last_polled_at, last_error, last_error_at, + created_at, updated_at) + SELECT + w.id, w.workspace_id,` + instanceIDExpr + `, + w.workflow_id, w.workflow_step_id, w.repository_id, w.base_branch, + w.filter_json, w.agent_profile_id, w.executor_profile_id, w.prompt, + w.enabled, w.poll_interval_seconds, w.max_inflight_tasks, + w.last_polled_at, w.last_error, w.last_error_at, w.created_at, w.updated_at + FROM sentry_issue_watches w` + if _, err := tx.ExecContext(ctx, copySQL); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `DROP TABLE sentry_issue_watches`); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `ALTER TABLE sentry_issue_watches_new RENAME TO sentry_issue_watches`); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `CREATE INDEX IF NOT EXISTS idx_sentry_issue_watches_workspace ON sentry_issue_watches(workspace_id)`); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `CREATE INDEX IF NOT EXISTS idx_sentry_issue_watches_instance ON sentry_issue_watches(sentry_instance_id)`); err != nil { + return err + } + return tx.Commit() +} + func isLegacySingletonConfig(cols map[string]struct{}) bool { if len(cols) == 0 { return false @@ -214,12 +622,45 @@ func nullableTime(t sql.NullTime) interface{} { return t.Time } +// defaultInstanceName is the fallback instance name when a URL yields no host. +const defaultInstanceName = "Sentry" + +// hostFromURL extracts the host of a Sentry instance URL for use as a default +// instance name. Falls back to "Sentry" for a blank/unparseable URL. +func hostFromURL(rawURL string) string { + rawURL = strings.TrimSpace(rawURL) + if rawURL == "" { + return defaultInstanceName + } + u, err := url.Parse(rawURL) + if err != nil || u.Host == "" { + return defaultInstanceName + } + return u.Host +} + +// uniqueInstanceName returns a name unique within the supplied set, suffixing +// " (2)", " (3)", … on collision. The chosen name is recorded in used so the +// next call for the same workspace avoids it. +func uniqueInstanceName(used map[string]struct{}, base string) string { + if base == "" { + base = defaultInstanceName + } + name := base + for i := 2; ; i++ { + if _, taken := used[name]; !taken { + used[name] = struct{}{} + return name + } + name = fmt.Sprintf("%s (%d)", base, i) + } +} + // addIssueWatchRepositoryColumns brings older databases up to the current // schema by appending repository_id / base_branch to sentry_issue_watches when // missing. Both backfill to ” (unbound), so existing repo-less watches keep -// their behaviour. Fresh installs hit the column-already-present branch since -// createTablesSQL declares both columns. Idempotent — column lookup before each -// ALTER avoids the "duplicate column name" error. +// their behaviour. Idempotent — column lookup before each ALTER avoids the +// "duplicate column name" error. func (s *Store) addIssueWatchRepositoryColumns() error { cols, err := s.tableColumns("sentry_issue_watches") if err != nil { @@ -241,11 +682,9 @@ func (s *Store) addIssueWatchRepositoryColumns() error { return nil } -// addConfigURLColumn brings older databases up to the current schema by adding -// the url column to sentry_configs when missing. Existing rows — all SaaS -// installs, since this predates self-hosted support — backfill to the -// sentry.io default (mirrors DefaultSentryURL). A fresh install hits the -// column-already-present branch since createTablesSQL declares the column. +// addConfigURLColumn adds the url column to a workspace-keyed sentry_configs +// table when missing (a pre-self-hosted database). Retained for the upgrade +// lineage; the id-keyed table always declares url, so this is a no-op there. func (s *Store) addConfigURLColumn() error { cols, err := s.tableColumns("sentry_configs") if err != nil { @@ -263,10 +702,9 @@ func (s *Store) addConfigURLColumn() error { return nil } -// addMaxInflightTasksColumn brings older databases up to the current schema by -// adding the max_inflight_tasks column to sentry_issue_watches when missing. -// Existing rows backfill to the default (5). A fresh install hits the -// column-already-present branch since createTablesSQL declares the column. +// addMaxInflightTasksColumn adds the max_inflight_tasks column to +// sentry_issue_watches when missing, backfilling existing rows to the default +// (5). Idempotent. func (s *Store) addMaxInflightTasksColumn() error { cols, err := s.tableColumns("sentry_issue_watches") if err != nil { @@ -284,11 +722,9 @@ func (s *Store) addMaxInflightTasksColumn() error { return nil } -// addIssueWatchLastErrorColumns brings older databases up to the current -// schema by appending last_error / last_error_at to sentry_issue_watches when -// missing. Fresh installs hit the column-already-present branch since -// createTablesSQL declares both columns. Idempotent — column lookup before -// each ALTER avoids the "duplicate column name" error. +// addIssueWatchLastErrorColumns appends last_error / last_error_at to +// sentry_issue_watches when missing. Idempotent — column lookup before each +// ALTER avoids the "duplicate column name" error. func (s *Store) addIssueWatchLastErrorColumns() error { cols, err := s.tableColumns("sentry_issue_watches") if err != nil { @@ -311,7 +747,8 @@ func (s *Store) addIssueWatchLastErrorColumns() error { } // tableColumns returns the set of column names for a table via PRAGMA -// table_info, used by the lightweight ADD COLUMN migrations above. +// table_info, used by the lightweight ADD COLUMN migrations and the shape +// detection guarding the table rebuilds above. func (s *Store) tableColumns(table string) (map[string]struct{}, error) { rows, err := s.db.Query(fmt.Sprintf("PRAGMA table_info(%s)", table)) if err != nil { @@ -336,29 +773,37 @@ func (s *Store) tableColumns(table string) (map[string]struct{}, error) { return cols, rows.Err() } -const selectConfigColumns = `workspace_id, auth_method, url, +const selectInstanceColumns = `id, workspace_id, name, auth_method, url, last_checked_at, last_ok, last_error, created_at, updated_at` -// GetConfig returns the default workspace Sentry config, or nil when no row -// exists. New code should call GetConfigForWorkspace. -func (s *Store) GetConfig(ctx context.Context) (*SentryConfig, error) { - workspaceID, err := s.defaultWorkspaceID() - if err != nil { +// ListInstances returns every Sentry instance in a workspace, ordered by name. +func (s *Store) ListInstances(ctx context.Context, workspaceID string) ([]*SentryConfig, error) { + var rows []SentryConfig + if err := s.ro.SelectContext(ctx, &rows, + `SELECT `+selectInstanceColumns+` FROM sentry_configs WHERE workspace_id = ? ORDER BY name, id`, + workspaceID); err != nil { return nil, err } - return s.GetConfigForWorkspace(ctx, workspaceID) + return instancePtrs(rows), nil } -// GetConfigForWorkspace returns the Sentry config for a workspace, or nil when -// no row exists. -func (s *Store) GetConfigForWorkspace(ctx context.Context, workspaceID string) (*SentryConfig, error) { - workspaceID, err := s.resolveWorkspaceID(workspaceID) - if err != nil { +// ListAllInstances returns every instance across all workspaces. Used by the +// auth-health poller and the provider secret rekey. +func (s *Store) ListAllInstances(ctx context.Context) ([]*SentryConfig, error) { + var rows []SentryConfig + if err := s.ro.SelectContext(ctx, &rows, + `SELECT `+selectInstanceColumns+` FROM sentry_configs ORDER BY workspace_id, name, id`); err != nil { return nil, err } + return instancePtrs(rows), nil +} + +// GetInstance returns an instance by ID, or nil when no row matches. Ownership +// is checked by the service against the request's workspace. +func (s *Store) GetInstance(ctx context.Context, id string) (*SentryConfig, error) { var cfg SentryConfig - err = s.ro.GetContext(ctx, &cfg, - `SELECT `+selectConfigColumns+` FROM sentry_configs WHERE workspace_id = ?`, workspaceID) + err := s.ro.GetContext(ctx, &cfg, + `SELECT `+selectInstanceColumns+` FROM sentry_configs WHERE id = ?`, id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -368,109 +813,141 @@ func (s *Store) GetConfigForWorkspace(ctx context.Context, workspaceID string) ( return &cfg, nil } -// UpsertConfig inserts or updates the default workspace config row. The last_* health -// columns are owned by the poller and written via UpdateAuthHealth. -func (s *Store) UpsertConfig(ctx context.Context, cfg *SentryConfig) error { - workspaceID, err := s.defaultWorkspaceID() - if err != nil { - return err - } - return s.UpsertConfigForWorkspace(ctx, workspaceID, cfg) -} - -// UpsertConfigForWorkspace inserts or updates a workspace config row. -func (s *Store) UpsertConfigForWorkspace(ctx context.Context, workspaceID string, cfg *SentryConfig) error { - workspaceID, err := s.resolveWorkspaceID(workspaceID) - if err != nil { - return err +// CreateInstance inserts a new instance row. ID and timestamps are assigned +// here when unset. A duplicate (workspace_id, name) surfaces as +// ErrDuplicateInstanceName. +func (s *Store) CreateInstance(ctx context.Context, cfg *SentryConfig) error { + if cfg.ID == "" { + cfg.ID = uuid.New().String() } now := time.Now().UTC() if cfg.CreatedAt.IsZero() { cfg.CreatedAt = now } cfg.UpdatedAt = now - _, err = s.db.ExecContext(ctx, ` - INSERT INTO sentry_configs (workspace_id, auth_method, url, created_at, updated_at) - VALUES (?, ?, ?, ?, ?) - ON CONFLICT(workspace_id) DO UPDATE SET - auth_method = excluded.auth_method, - url = excluded.url, - updated_at = excluded.updated_at`, - workspaceID, cfg.AuthMethod, cfg.URL, cfg.CreatedAt, cfg.UpdatedAt) + _, err := s.db.ExecContext(ctx, ` + INSERT INTO sentry_configs (id, workspace_id, name, auth_method, url, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + cfg.ID, cfg.WorkspaceID, cfg.Name, cfg.AuthMethod, cfg.URL, cfg.CreatedAt, cfg.UpdatedAt) + if isUniqueViolation(err) { + return ErrDuplicateInstanceName + } return err } -// DeleteConfig removes the default workspace config row. -func (s *Store) DeleteConfig(ctx context.Context) error { - workspaceID, err := s.defaultWorkspaceID() +// UpdateInstance overwrites name/auth_method/url of an existing instance. The +// last_* health columns are owned by the poller. Returns ErrInstanceNotFound +// when no row matches and ErrDuplicateInstanceName on a name collision. +func (s *Store) UpdateInstance(ctx context.Context, cfg *SentryConfig) error { + cfg.UpdatedAt = time.Now().UTC() + res, err := s.db.ExecContext(ctx, ` + UPDATE sentry_configs SET name = ?, auth_method = ?, url = ?, updated_at = ? + WHERE id = ?`, + cfg.Name, cfg.AuthMethod, cfg.URL, cfg.UpdatedAt, cfg.ID) + if isUniqueViolation(err) { + return ErrDuplicateInstanceName + } if err != nil { return err } - return s.DeleteConfigForWorkspace(ctx, workspaceID) -} - -// DeleteConfigForWorkspace removes the workspace config row. -func (s *Store) DeleteConfigForWorkspace(ctx context.Context, workspaceID string) error { - workspaceID, err := s.resolveWorkspaceID(workspaceID) + n, err := res.RowsAffected() if err != nil { return err } - _, err = s.db.ExecContext(ctx, `DELETE FROM sentry_configs WHERE workspace_id = ?`, workspaceID) - return err + if n == 0 { + return ErrInstanceNotFound + } + return nil } -// HasConfig reports whether any config row exists. Used by the auth-health -// poller to decide whether to probe at all. +// DeleteInstance removes an instance row. A watch still referencing it trips +// the ON DELETE RESTRICT foreign key, surfaced as ErrInstanceInUse (the service +// fills the watch count). Returns ErrInstanceNotFound when no row matches. +func (s *Store) DeleteInstance(ctx context.Context, id string) error { + res, err := s.db.ExecContext(ctx, `DELETE FROM sentry_configs WHERE id = ?`, id) + if isForeignKeyViolation(err) { + return ErrInstanceInUse{} + } + if err != nil { + return err + } + n, err := res.RowsAffected() + if err != nil { + return err + } + if n == 0 { + return ErrInstanceNotFound + } + return nil +} + +// CountWatchesForInstance counts every watch (enabled and disabled) bound to an +// instance, used to reject deletion of an in-use instance with a friendly count. +func (s *Store) CountWatchesForInstance(ctx context.Context, instanceID string) (int, error) { + var n int + if err := s.ro.GetContext(ctx, &n, + `SELECT COUNT(*) FROM sentry_issue_watches WHERE sentry_instance_id = ?`, instanceID); err != nil { + return 0, err + } + return n, nil +} + +// CountUnboundIssueWatchesInWorkspace counts watches in a workspace that are not +// bound to any instance (sentry_instance_id IS NULL). resolveWatchInstanceID +// resolves these legacy/migrated watches to the workspace's sole instance at +// poll time, so deleting that sole instance would strand them. +func (s *Store) CountUnboundIssueWatchesInWorkspace(ctx context.Context, workspaceID string) (int, error) { + var n int + if err := s.ro.GetContext(ctx, &n, + `SELECT COUNT(*) FROM sentry_issue_watches WHERE workspace_id = ? AND sentry_instance_id IS NULL`, workspaceID); err != nil { + return 0, err + } + return n, nil +} + +// UpdateAuthHealthForInstance records the result of a credential probe on one +// instance row. +func (s *Store) UpdateAuthHealthForInstance(ctx context.Context, id string, ok bool, errMsg string, checkedAt time.Time) error { + res, err := s.db.ExecContext(ctx, ` + UPDATE sentry_configs + SET last_checked_at = ?, last_ok = ?, last_error = ? + WHERE id = ?`, + checkedAt, ok, errMsg, id) + if err != nil { + return err + } + n, err := res.RowsAffected() + if err != nil { + return err + } + if n == 0 { + return ErrInstanceNotFound + } + return nil +} + +// HasConfig reports whether any instance exists. Used by the auth-health poller +// to decide whether to probe at all. func (s *Store) HasConfig(ctx context.Context) (bool, error) { var present int - err := s.ro.GetContext(ctx, &present, - `SELECT COUNT(*) FROM sentry_configs`) - if err != nil { + if err := s.ro.GetContext(ctx, &present, `SELECT COUNT(*) FROM sentry_configs`); err != nil { return false, err } return present > 0, nil } -// ListConfigWorkspaceIDs returns every workspace with a saved Sentry config. -func (s *Store) ListConfigWorkspaceIDs(ctx context.Context) ([]string, error) { - var ids []string - if err := s.ro.SelectContext(ctx, &ids, `SELECT workspace_id FROM sentry_configs ORDER BY workspace_id`); err != nil { - return nil, err +func instancePtrs(rows []SentryConfig) []*SentryConfig { + out := make([]*SentryConfig, len(rows)) + for i := range rows { + out[i] = &rows[i] } - return ids, nil + return out } -// UpdateAuthHealth records the result of a credential probe. -func (s *Store) UpdateAuthHealth(ctx context.Context, ok bool, errMsg string, checkedAt time.Time) error { - workspaceID, err := s.defaultWorkspaceID() - if err != nil { - return err - } - return s.UpdateAuthHealthForWorkspace(ctx, workspaceID, ok, errMsg, checkedAt) +func isUniqueViolation(err error) bool { + return err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed") } -// UpdateAuthHealthForWorkspace records the result of a credential probe for a -// single workspace config row. -func (s *Store) UpdateAuthHealthForWorkspace(ctx context.Context, workspaceID string, ok bool, errMsg string, checkedAt time.Time) error { - workspaceID, err := s.resolveWorkspaceID(workspaceID) - if err != nil { - return err - } - _, err = s.db.ExecContext(ctx, ` - UPDATE sentry_configs - SET last_checked_at = ?, last_ok = ?, last_error = ? - WHERE workspace_id = ?`, - checkedAt, ok, errMsg, workspaceID) - return err -} - -func (s *Store) defaultWorkspaceID() (string, error) { - return s.defaultWorkspace.Resolve(s.db) -} - -func (s *Store) resolveWorkspaceID(workspaceID string) (string, error) { - if workspaceID != "" { - return workspaceID, nil - } - return s.defaultWorkspaceID() +func isForeignKeyViolation(err error) bool { + return err != nil && strings.Contains(err.Error(), "FOREIGN KEY constraint failed") } diff --git a/apps/backend/internal/sentry/store_issue_watch.go b/apps/backend/internal/sentry/store_issue_watch.go index 7d47f50204..74afd648ed 100644 --- a/apps/backend/internal/sentry/store_issue_watch.go +++ b/apps/backend/internal/sentry/store_issue_watch.go @@ -15,24 +15,25 @@ import ( // the way SQLite holds it. The store marshals/unmarshals at this boundary so // service callers see a typed SearchFilter and never have to think about JSON. type issueWatchRow struct { - ID string `db:"id"` - WorkspaceID string `db:"workspace_id"` - WorkflowID string `db:"workflow_id"` - WorkflowStepID string `db:"workflow_step_id"` - RepositoryID string `db:"repository_id"` - BaseBranch string `db:"base_branch"` - FilterJSON string `db:"filter_json"` - AgentProfileID string `db:"agent_profile_id"` - ExecutorProfileID string `db:"executor_profile_id"` - Prompt string `db:"prompt"` - Enabled bool `db:"enabled"` - PollIntervalSeconds int `db:"poll_interval_seconds"` - MaxInflightTasks sql.NullInt64 `db:"max_inflight_tasks"` - LastPolledAt *time.Time `db:"last_polled_at"` - LastError string `db:"last_error"` - LastErrorAt *time.Time `db:"last_error_at"` - CreatedAt time.Time `db:"created_at"` - UpdatedAt time.Time `db:"updated_at"` + ID string `db:"id"` + WorkspaceID string `db:"workspace_id"` + SentryInstanceID sql.NullString `db:"sentry_instance_id"` + WorkflowID string `db:"workflow_id"` + WorkflowStepID string `db:"workflow_step_id"` + RepositoryID string `db:"repository_id"` + BaseBranch string `db:"base_branch"` + FilterJSON string `db:"filter_json"` + AgentProfileID string `db:"agent_profile_id"` + ExecutorProfileID string `db:"executor_profile_id"` + Prompt string `db:"prompt"` + Enabled bool `db:"enabled"` + PollIntervalSeconds int `db:"poll_interval_seconds"` + MaxInflightTasks sql.NullInt64 `db:"max_inflight_tasks"` + LastPolledAt *time.Time `db:"last_polled_at"` + LastError string `db:"last_error"` + LastErrorAt *time.Time `db:"last_error_at"` + CreatedAt time.Time `db:"created_at"` + UpdatedAt time.Time `db:"updated_at"` } func (r *issueWatchRow) toIssueWatch() (*IssueWatch, error) { @@ -50,6 +51,7 @@ func (r *issueWatchRow) toIssueWatch() (*IssueWatch, error) { return &IssueWatch{ ID: r.ID, WorkspaceID: r.WorkspaceID, + SentryInstanceID: r.SentryInstanceID.String, WorkflowID: r.WorkflowID, WorkflowStepID: r.WorkflowStepID, RepositoryID: r.RepositoryID, @@ -79,6 +81,16 @@ func nullableInt(v *int) interface{} { return *v } +// nullableString converts a string into a value suitable for a nullable SQL +// column: "" becomes SQL NULL, any other value is passed through. Used for +// sentry_instance_id where NULL means a legacy unbound watch. +func nullableString(v string) interface{} { + if v == "" { + return nil + } + return v +} + func encodeFilter(f SearchFilter) (string, error) { b, err := json.Marshal(f) if err != nil { @@ -91,14 +103,14 @@ func encodeFilter(f SearchFilter) (string, error) { // SELECTs use issueWatchSelectColumns which wraps the nullable last_error in // COALESCE so older databases (pre-self-heal migration) read back as empty // strings rather than NULL. -const issueWatchInsertColumns = `id, workspace_id, workflow_id, workflow_step_id, +const issueWatchInsertColumns = `id, workspace_id, sentry_instance_id, workflow_id, workflow_step_id, repository_id, base_branch, filter_json, agent_profile_id, executor_profile_id, prompt, enabled, poll_interval_seconds, max_inflight_tasks, last_polled_at, last_error, last_error_at, created_at, updated_at` -const issueWatchSelectColumns = `id, workspace_id, workflow_id, workflow_step_id, +const issueWatchSelectColumns = `id, workspace_id, sentry_instance_id, workflow_id, workflow_step_id, COALESCE(repository_id, '') AS repository_id, COALESCE(base_branch, '') AS base_branch, filter_json, agent_profile_id, executor_profile_id, prompt, enabled, poll_interval_seconds, max_inflight_tasks, last_polled_at, @@ -123,8 +135,8 @@ func (s *Store) CreateIssueWatch(ctx context.Context, w *IssueWatch) error { } _, err = s.db.ExecContext(ctx, ` INSERT INTO sentry_issue_watches (`+issueWatchInsertColumns+`) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - w.ID, w.WorkspaceID, w.WorkflowID, w.WorkflowStepID, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + w.ID, w.WorkspaceID, nullableString(w.SentryInstanceID), w.WorkflowID, w.WorkflowStepID, w.RepositoryID, w.BaseBranch, filterJSON, w.AgentProfileID, w.ExecutorProfileID, w.Prompt, w.Enabled, w.PollIntervalSeconds, nullableInt(w.MaxInflightTasks), w.LastPolledAt, @@ -245,6 +257,31 @@ func (s *Store) DisableIssueWatchWithError(ctx context.Context, id, cause string return err } +// StampIssueWatchError records a non-fatal cause on a watch (last_error / +// last_error_at) without changing its enabled state, so the settings UI can +// surface why the most recent poll could not run while the watch keeps +// retrying. Used when an unbound watch cannot resolve a Sentry instance. +func (s *Store) StampIssueWatchError(ctx context.Context, id, cause string) error { + now := time.Now().UTC() + _, err := s.db.ExecContext(ctx, + `UPDATE sentry_issue_watches + SET last_error = ?, last_error_at = ?, updated_at = ? + WHERE id = ?`, + cause, now, now, id) + return err +} + +// ClearIssueWatchError removes the non-fatal poll error state after a +// successful watch check so the settings UI reflects current health. +func (s *Store) ClearIssueWatchError(ctx context.Context, id string) error { + _, err := s.db.ExecContext(ctx, + `UPDATE sentry_issue_watches + SET last_error = '', last_error_at = NULL, updated_at = ? + WHERE id = ? AND (last_error <> '' OR last_error_at IS NOT NULL)`, + time.Now().UTC(), id) + return err +} + // DeleteIssueWatch removes a watch and its dedup rows in a single transaction. // The explicit child DELETE guards older databases where foreign_keys may not // have been enabled at attach time. diff --git a/apps/backend/internal/sentry/store_test.go b/apps/backend/internal/sentry/store_test.go index 94a8117f34..c01b802297 100644 --- a/apps/backend/internal/sentry/store_test.go +++ b/apps/backend/internal/sentry/store_test.go @@ -3,6 +3,7 @@ package sentry import ( "context" "database/sql" + "errors" "testing" "time" @@ -19,6 +20,11 @@ func newTestStore(t *testing.T) *Store { raw.SetMaxOpenConns(1) raw.SetMaxIdleConns(1) db := sqlx.NewDb(raw, "sqlite3") + // Enforce foreign keys as production does (DSN _foreign_keys=on) so the + // ON DELETE RESTRICT net for in-use instances is exercised in tests. + if _, err := db.Exec(`PRAGMA foreign_keys = ON`); err != nil { + t.Fatalf("enable foreign keys: %v", err) + } t.Cleanup(func() { _ = db.Close() }) store, err := NewStore(db, db) if err != nil { @@ -27,54 +33,174 @@ func newTestStore(t *testing.T) *Store { return store } -func TestStore_UpsertGetDelete(t *testing.T) { - store := newTestStore(t) - ctx := context.Background() - - cfg := &SentryConfig{AuthMethod: AuthMethodAuthToken} - if err := store.UpsertConfig(ctx, cfg); err != nil { - t.Fatalf("upsert: %v", err) - } - - got, err := store.GetConfig(ctx) - if err != nil { - t.Fatalf("get: %v", err) - } - if got == nil { - t.Fatal("expected config, got nil") - } - if got.AuthMethod != cfg.AuthMethod { - t.Errorf("round-trip mismatch: %+v vs %+v", got, cfg) - } - if got.CreatedAt.IsZero() || got.UpdatedAt.IsZero() { - t.Error("timestamps not set") - } - - // Idempotent upsert does not duplicate rows. - if err := store.UpsertConfig(ctx, cfg); err != nil { - t.Fatalf("update upsert: %v", err) - } - - if err := store.DeleteConfig(ctx); err != nil { - t.Fatalf("delete: %v", err) - } - gone, err := store.GetConfig(ctx) - if err != nil { - t.Fatalf("get after delete: %v", err) - } - if gone != nil { - t.Errorf("expected nil after delete, got %+v", gone) +func testInstance(workspaceID, name string) *SentryConfig { + return &SentryConfig{ + WorkspaceID: workspaceID, + Name: name, + AuthMethod: AuthMethodAuthToken, + URL: DefaultSentryURL, } } -func TestStore_GetConfig_Missing(t *testing.T) { +func TestStore_CreateGetInstance(t *testing.T) { store := newTestStore(t) - cfg, err := store.GetConfig(context.Background()) + ctx := context.Background() + + cfg := testInstance("ws-1", "SaaS") + cfg.URL = "https://sentry.example.com" + if err := store.CreateInstance(ctx, cfg); err != nil { + t.Fatalf("create: %v", err) + } + if cfg.ID == "" { + t.Fatal("expected ID assigned") + } + if cfg.CreatedAt.IsZero() || cfg.UpdatedAt.IsZero() { + t.Error("timestamps not set") + } + + got, err := store.GetInstance(ctx, cfg.ID) + if err != nil || got == nil { + t.Fatalf("get: %v / %v", err, got) + } + if got.WorkspaceID != "ws-1" || got.Name != "SaaS" || got.URL != "https://sentry.example.com" { + t.Errorf("round-trip mismatch: %+v", got) + } +} + +func TestStore_GetInstance_Missing(t *testing.T) { + store := newTestStore(t) + got, err := store.GetInstance(context.Background(), "ghost") if err != nil { t.Fatalf("unexpected error: %v", err) } - if cfg != nil { - t.Errorf("expected nil for missing config, got %+v", cfg) + if got != nil { + t.Errorf("expected nil for missing instance, got %+v", got) + } +} + +func TestStore_ListInstances_ScopedByWorkspace(t *testing.T) { + store := newTestStore(t) + ctx := context.Background() + for _, c := range []*SentryConfig{ + testInstance("ws-1", "A"), + testInstance("ws-1", "B"), + testInstance("ws-2", "C"), + } { + if err := store.CreateInstance(ctx, c); err != nil { + t.Fatalf("create: %v", err) + } + } + got, err := store.ListInstances(ctx, "ws-1") + if err != nil { + t.Fatalf("list: %v", err) + } + if len(got) != 2 { + t.Fatalf("expected 2 instances for ws-1, got %d", len(got)) + } + for _, c := range got { + if c.WorkspaceID != "ws-1" { + t.Errorf("workspace leaked into list: %s", c.WorkspaceID) + } + } +} + +// TestStore_UniqueNamePerWorkspace pins acceptance (h): (workspace_id, name) is +// unique, but the same name is allowed in a different workspace. +func TestStore_UniqueNamePerWorkspace(t *testing.T) { + store := newTestStore(t) + ctx := context.Background() + + if err := store.CreateInstance(ctx, testInstance("ws-1", "Prod")); err != nil { + t.Fatalf("first create: %v", err) + } + if err := store.CreateInstance(ctx, testInstance("ws-1", "Prod")); !errors.Is(err, ErrDuplicateInstanceName) { + t.Fatalf("expected ErrDuplicateInstanceName for duplicate name in same workspace, got %v", err) + } + // Same name in a different workspace is fine. + if err := store.CreateInstance(ctx, testInstance("ws-2", "Prod")); err != nil { + t.Fatalf("same name in other workspace should succeed, got %v", err) + } +} + +func TestStore_UpdateInstance(t *testing.T) { + store := newTestStore(t) + ctx := context.Background() + cfg := testInstance("ws-1", "Old") + if err := store.CreateInstance(ctx, cfg); err != nil { + t.Fatalf("create: %v", err) + } + created := cfg.CreatedAt + cfg.Name = "New" + cfg.URL = "https://sentry.example.com" + if err := store.UpdateInstance(ctx, cfg); err != nil { + t.Fatalf("update: %v", err) + } + got, _ := store.GetInstance(ctx, cfg.ID) + if got.Name != "New" || got.URL != "https://sentry.example.com" { + t.Errorf("update did not persist: %+v", got) + } + if !got.CreatedAt.Equal(created) { + t.Errorf("update must not change created_at: %v vs %v", got.CreatedAt, created) + } + + // Update to a name already taken in the workspace is rejected. + other := testInstance("ws-1", "Taken") + if err := store.CreateInstance(ctx, other); err != nil { + t.Fatalf("create other: %v", err) + } + cfg.Name = "Taken" + if err := store.UpdateInstance(ctx, cfg); !errors.Is(err, ErrDuplicateInstanceName) { + t.Errorf("expected ErrDuplicateInstanceName on rename collision, got %v", err) + } + + // Update of a missing row is ErrInstanceNotFound. + ghost := testInstance("ws-1", "Ghost") + ghost.ID = "does-not-exist" + if err := store.UpdateInstance(ctx, ghost); !errors.Is(err, ErrInstanceNotFound) { + t.Errorf("expected ErrInstanceNotFound, got %v", err) + } +} + +func TestStore_DeleteInstance(t *testing.T) { + store := newTestStore(t) + ctx := context.Background() + cfg := testInstance("ws-1", "Prod") + if err := store.CreateInstance(ctx, cfg); err != nil { + t.Fatalf("create: %v", err) + } + if err := store.DeleteInstance(ctx, cfg.ID); err != nil { + t.Fatalf("delete: %v", err) + } + got, _ := store.GetInstance(ctx, cfg.ID) + if got != nil { + t.Errorf("expected instance gone, got %+v", got) + } + if err := store.DeleteInstance(ctx, cfg.ID); !errors.Is(err, ErrInstanceNotFound) { + t.Errorf("expected ErrInstanceNotFound on second delete, got %v", err) + } +} + +// TestStore_DeleteInstance_FKRestrictHolds pins the DB-level safety net from +// acceptance (f): a watch referencing an instance blocks its deletion via ON +// DELETE RESTRICT, surfaced as ErrInstanceInUse. +func TestStore_DeleteInstance_FKRestrictHolds(t *testing.T) { + store := newTestStore(t) + ctx := context.Background() + cfg := testInstance("ws-1", "Prod") + if err := store.CreateInstance(ctx, cfg); err != nil { + t.Fatalf("create instance: %v", err) + } + w := newTestIssueWatch("ws-1") + w.SentryInstanceID = cfg.ID + if err := store.CreateIssueWatch(ctx, w); err != nil { + t.Fatalf("create watch: %v", err) + } + if err := store.DeleteInstance(ctx, cfg.ID); !errors.As(err, &ErrInstanceInUse{}) { + t.Fatalf("expected ErrInstanceInUse from FK RESTRICT, got %v", err) + } + n, err := store.CountWatchesForInstance(ctx, cfg.ID) + if err != nil || n != 1 { + t.Fatalf("expected 1 referencing watch, got %d (err %v)", n, err) } } @@ -83,187 +209,83 @@ func TestStore_HasConfig(t *testing.T) { ctx := context.Background() has, _ := store.HasConfig(ctx) if has { - t.Errorf("expected HasConfig=false on empty store") + t.Error("expected HasConfig=false on empty store") } - if err := store.UpsertConfig(ctx, &SentryConfig{AuthMethod: AuthMethodAuthToken}); err != nil { - t.Fatalf("upsert: %v", err) + if err := store.CreateInstance(ctx, testInstance("ws-1", "A")); err != nil { + t.Fatalf("create: %v", err) } has, _ = store.HasConfig(ctx) if !has { - t.Errorf("expected HasConfig=true after upsert") + t.Error("expected HasConfig=true after create") } } -func TestStore_UpdateAuthHealth(t *testing.T) { +func TestStore_UpdateAuthHealthForInstance(t *testing.T) { store := newTestStore(t) ctx := context.Background() - if err := store.UpsertConfig(ctx, &SentryConfig{AuthMethod: AuthMethodAuthToken}); err != nil { - t.Fatalf("upsert: %v", err) + cfg := testInstance("ws-1", "A") + if err := store.CreateInstance(ctx, cfg); err != nil { + t.Fatalf("create: %v", err) } - - cfg, _ := store.GetConfig(ctx) - if cfg.LastCheckedAt != nil { - t.Errorf("expected nil last_checked_at on fresh row, got %v", cfg.LastCheckedAt) + got, _ := store.GetInstance(ctx, cfg.ID) + if got.LastCheckedAt != nil { + t.Errorf("expected nil last_checked_at on fresh row, got %v", got.LastCheckedAt) } - now := time.Now().UTC().Truncate(time.Second) - if err := store.UpdateAuthHealth(ctx, true, "", now); err != nil { + if err := store.UpdateAuthHealthForInstance(ctx, cfg.ID, true, "", now); err != nil { t.Fatalf("update ok: %v", err) } - cfg, _ = store.GetConfig(ctx) - if !cfg.LastOk { - t.Error("expected last_ok=true after successful probe") + got, _ = store.GetInstance(ctx, cfg.ID) + if !got.LastOk || got.LastCheckedAt == nil || !got.LastCheckedAt.Equal(now) { + t.Errorf("unexpected health state after success: %+v", got) } - if cfg.LastCheckedAt == nil || !cfg.LastCheckedAt.Equal(now) { - t.Errorf("expected last_checked_at=%v, got %v", now, cfg.LastCheckedAt) - } - - failAt := now.Add(time.Minute) - if err := store.UpdateAuthHealth(ctx, false, "401 unauthorized", failAt); err != nil { + if err := store.UpdateAuthHealthForInstance(ctx, cfg.ID, false, "401 unauthorized", now.Add(time.Minute)); err != nil { t.Fatalf("update fail: %v", err) } - cfg, _ = store.GetConfig(ctx) - if cfg.LastOk { - t.Error("expected last_ok=false after failure") - } - if cfg.LastError != "401 unauthorized" { - t.Errorf("expected last_error preserved, got %q", cfg.LastError) + got, _ = store.GetInstance(ctx, cfg.ID) + if got.LastOk || got.LastError != "401 unauthorized" { + t.Errorf("expected failure recorded, got %+v", got) } } -// TestStore_UpsertGetConfig_RoundTripsURL asserts the instance URL persists -// through an upsert/get cycle. -func TestStore_UpsertGetConfig_RoundTripsURL(t *testing.T) { +func TestStore_CountUnboundIssueWatchesInWorkspace(t *testing.T) { store := newTestStore(t) ctx := context.Background() - cfg := &SentryConfig{AuthMethod: AuthMethodAuthToken, URL: "https://sentry.example.com"} - if err := store.UpsertConfig(ctx, cfg); err != nil { - t.Fatalf("upsert: %v", err) + inst := testInstance("ws-1", "A") + if err := store.CreateInstance(ctx, inst); err != nil { + t.Fatalf("create instance: %v", err) } - got, err := store.GetConfig(ctx) - if err != nil || got == nil { - t.Fatalf("get: %v / %v", err, got) + // A bound watch must not count. + bound := newTestIssueWatch("ws-1") + bound.SentryInstanceID = inst.ID + if err := store.CreateIssueWatch(ctx, bound); err != nil { + t.Fatalf("create bound watch: %v", err) } - if got.URL != "https://sentry.example.com" { - t.Errorf("url not persisted: got %q", got.URL) + // Two unbound (NULL sentry_instance_id) watches in ws-1 must count. + for range 2 { + if err := store.CreateIssueWatch(ctx, newTestIssueWatch("ws-1")); err != nil { + t.Fatalf("create unbound watch: %v", err) + } + } + // An unbound watch in another workspace must not leak in. + if err := store.CreateIssueWatch(ctx, newTestIssueWatch("ws-2")); err != nil { + t.Fatalf("create other-workspace watch: %v", err) + } + n, err := store.CountUnboundIssueWatchesInWorkspace(ctx, "ws-1") + if err != nil { + t.Fatalf("count: %v", err) + } + if n != 2 { + t.Errorf("expected 2 unbound watches in ws-1, got %d", n) } } -func TestStore_MigrateSingletonConfigToActiveWorkspace(t *testing.T) { - raw, err := sql.Open("sqlite3", ":memory:") - if err != nil { - t.Fatalf("open sqlite: %v", err) - } - raw.SetMaxOpenConns(1) - raw.SetMaxIdleConns(1) - db := sqlx.NewDb(raw, "sqlite3") - t.Cleanup(func() { _ = db.Close() }) - - now := time.Now().UTC() - checkedAt := now.Add(-5 * time.Minute).Truncate(time.Second) - if _, err := db.Exec(` - CREATE TABLE workspaces ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - created_at TIMESTAMP NOT NULL, - updated_at TIMESTAMP NOT NULL - ); - CREATE TABLE users ( - id TEXT PRIMARY KEY, - email TEXT NOT NULL, - settings TEXT NOT NULL DEFAULT '{}', - created_at TIMESTAMP NOT NULL, - updated_at TIMESTAMP NOT NULL - ); - CREATE TABLE sentry_configs ( - id TEXT PRIMARY KEY CHECK(id = 'singleton'), - auth_method TEXT NOT NULL, - url TEXT NOT NULL DEFAULT 'https://sentry.io', - last_checked_at DATETIME, - last_ok INTEGER NOT NULL DEFAULT 0, - last_error TEXT NOT NULL DEFAULT '', - created_at DATETIME NOT NULL, - updated_at DATETIME NOT NULL - ); - INSERT INTO workspaces (id, name, created_at, updated_at) - VALUES ('ws-first', 'First', ?, ?), ('ws-active', 'Active', ?, ?); - INSERT INTO users (id, email, settings, created_at, updated_at) - VALUES ('default-user', 'default@kandev.local', '{"workspace_id":"ws-active"}', ?, ?); - INSERT INTO sentry_configs - (id, auth_method, url, last_checked_at, last_ok, last_error, created_at, updated_at) - VALUES ('singleton', ?, 'https://sentry.example.com', ?, 1, 'healthy', ?, ?); - `, now.Add(-time.Hour), now.Add(-time.Hour), now, now, now, now, AuthMethodAuthToken, checkedAt, now, now); err != nil { - t.Fatalf("seed singleton schema: %v", err) - } - - store, err := NewStore(db, db) - if err != nil { - t.Fatalf("new store: %v", err) - } - if got := store.MigratedFromWorkspace(); got != "ws-active" { - t.Fatalf("expected singleton config migrated to active workspace, got %q", got) - } - cfg, err := store.GetConfigForWorkspace(context.Background(), "ws-active") - if err != nil { - t.Fatalf("get active workspace config: %v", err) - } - if cfg == nil { - t.Fatal("expected migrated config") - } - if cfg.URL != "https://sentry.example.com" { - t.Errorf("expected migrated URL, got %q", cfg.URL) - } - if cfg.AuthMethod != AuthMethodAuthToken { - t.Errorf("expected migrated auth method %q, got %q", AuthMethodAuthToken, cfg.AuthMethod) - } - if !cfg.LastOk || cfg.LastError != "healthy" { - t.Errorf("unexpected migrated health state: %+v", cfg) - } - if cfg.LastCheckedAt == nil || !cfg.LastCheckedAt.Equal(checkedAt) { - t.Errorf("expected last_checked_at=%v, got %v", checkedAt, cfg.LastCheckedAt) - } -} - -// TestStore_MigratesURLColumn seeds a pre-self-hosted sentry_configs table (no -// url column) and verifies NewStore adds the column, backfilling the existing -// SaaS row to the sentry.io default rather than an empty string. -func TestStore_MigratesURLColumn(t *testing.T) { - raw, err := sql.Open("sqlite3", ":memory:") - if err != nil { - t.Fatalf("open sqlite: %v", err) - } - raw.SetMaxOpenConns(1) - raw.SetMaxIdleConns(1) - db := sqlx.NewDb(raw, "sqlite3") - t.Cleanup(func() { _ = db.Close() }) - - now := time.Now().UTC() - if _, err := db.Exec(` - CREATE TABLE sentry_configs ( - id TEXT PRIMARY KEY CHECK(id = 'singleton'), - auth_method TEXT NOT NULL, - last_checked_at DATETIME, - last_ok INTEGER NOT NULL DEFAULT 0, - last_error TEXT NOT NULL DEFAULT '', - created_at DATETIME NOT NULL, - updated_at DATETIME NOT NULL - )`); err != nil { - t.Fatalf("create legacy schema: %v", err) - } - if _, err := db.Exec(`INSERT INTO sentry_configs (id, auth_method, created_at, updated_at) - VALUES ('singleton', ?, ?, ?)`, AuthMethodAuthToken, now, now); err != nil { - t.Fatalf("seed legacy row: %v", err) - } - - store, err := NewStore(db, db) - if err != nil { - t.Fatalf("new store (migrate): %v", err) - } - cfg, err := store.GetConfig(context.Background()) - if err != nil || cfg == nil { - t.Fatalf("get after migrate: %v / %v", err, cfg) - } - if cfg.URL != DefaultSentryURL { - t.Errorf("expected legacy row backfilled to %q, got %q", DefaultSentryURL, cfg.URL) +// TestStore_UpdateAuthHealthForInstance_MissingInstance pins the zero-rows path: +// probing a non-existent instance surfaces ErrInstanceNotFound so the mock +// seed endpoint can fail fast instead of silently reporting success. +func TestStore_UpdateAuthHealthForInstance_MissingInstance(t *testing.T) { + store := newTestStore(t) + if err := store.UpdateAuthHealthForInstance(context.Background(), "ghost", true, "", time.Now().UTC()); !errors.Is(err, ErrInstanceNotFound) { + t.Errorf("expected ErrInstanceNotFound for missing instance, got %v", err) } } diff --git a/apps/web/components/integrations/integration-copy-config.test.ts b/apps/web/components/integrations/integration-copy-config.test.ts index 917d925849..a49f258fcd 100644 --- a/apps/web/components/integrations/integration-copy-config.test.ts +++ b/apps/web/components/integrations/integration-copy-config.test.ts @@ -1,6 +1,15 @@ -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; -import { integrationFromPathname } from "./integration-copy-config"; +import { copySentryInstances } from "@/lib/api/domains/sentry-api"; +import { copyIntegrationConfig, integrationFromPathname } from "./integration-copy-config"; + +vi.mock("@/lib/api/domains/sentry-api", () => ({ + copySentryInstances: vi.fn(), +})); + +afterEach(() => { + vi.clearAllMocks(); +}); describe("integrationFromPathname", () => { it("recognizes global integration settings routes", () => { @@ -18,3 +27,11 @@ describe("integrationFromPathname", () => { expect(integrationFromPathname("/settings/workspace/ws-1/integrations")).toBeNull(); }); }); + +describe("copyIntegrationConfig", () => { + it("scopes Sentry copies to the source workspace and sends only the target", async () => { + await copyIntegrationConfig("sentry", "ws-source", "ws-target"); + + expect(copySentryInstances).toHaveBeenCalledWith("ws-target", { workspaceId: "ws-source" }); + }); +}); diff --git a/apps/web/components/integrations/integration-copy-config.ts b/apps/web/components/integrations/integration-copy-config.ts index 84e60ecad9..6ec26fc363 100644 --- a/apps/web/components/integrations/integration-copy-config.ts +++ b/apps/web/components/integrations/integration-copy-config.ts @@ -1,7 +1,7 @@ import { copySlackConfig } from "@/lib/api/domains/slack-api"; import { copyJiraConfig } from "@/lib/api/domains/jira-api"; import { copyLinearConfig } from "@/lib/api/domains/linear-api"; -import { copySentryConfig } from "@/lib/api/domains/sentry-api"; +import { copySentryInstances } from "@/lib/api/domains/sentry-api"; import { copyGitHubWorkspaceSettings } from "@/lib/api/domains/github-api"; // IntegrationSlug is the set of integration settings pages that support copying @@ -55,7 +55,7 @@ export async function copyIntegrationConfig( await copyLinearConfig(targetWorkspaceId, options); return; case "sentry": - await copySentryConfig(targetWorkspaceId, options); + await copySentryInstances(targetWorkspaceId, options); return; case "github": await copyGitHubWorkspaceSettings(targetWorkspaceId, options); diff --git a/apps/web/components/integrations/validated-popover.tsx b/apps/web/components/integrations/validated-popover.tsx index 15d8873db2..4ccac0067b 100644 --- a/apps/web/components/integrations/validated-popover.tsx +++ b/apps/web/components/integrations/validated-popover.tsx @@ -39,6 +39,10 @@ export type ValidatedPopoverProps = { align?: "start" | "end"; headline: string; placeholder: string; + // extraFields renders integration-specific controls (e.g. a Sentry instance + // selector) between the headline and the key input. Optional; omitted by + // integrations that need only the key input. + extraFields?: ReactNode; // Validation: extract a key from the user's input. Returning null shows the // hint as an error. The hint typically reads "Paste a Jira ticket URL or // key (PROJ-123)" or similar — integration-specific copy. @@ -51,6 +55,10 @@ export type ValidatedPopoverProps = { // Submit button labels. submitLabel: string; // e.g. "Link", "Import" submittingLabel: string; // e.g. "Linking...", "Loading..." + // submitDisabled blocks submission even when the key input is non-empty (e.g. + // a required instance selector has no choice yet). Optional; defaults to + // enabled. + submitDisabled?: boolean; }; type TriggerButtonProps = Pick< @@ -122,6 +130,8 @@ type PopoverBodyProps = { submitLabel: string; submittingLabel: string; testIdPrefix?: string; + extraFields?: ReactNode; + submitDisabled?: boolean; }; function PopoverBody({ @@ -135,10 +145,13 @@ function PopoverBody({ submitLabel, submittingLabel, testIdPrefix, + extraFields, + submitDisabled, }: PopoverBodyProps) { return (
{headline}
+ {extraFields} void onSubmit()} - disabled={loading || !value.trim()} + disabled={loading || !value.trim() || !!submitDisabled} className="h-7 cursor-pointer" data-testid={testIdPrefix ? `${testIdPrefix}-submit` : undefined} > @@ -256,6 +269,8 @@ export function ValidatedPopover(props: ValidatedPopoverProps) { cleanup()); + +describe("SentryInstanceCard", () => { + it("gives each instance action a distinct accessible name", () => { + render( + <> + {}} + onDelete={() => {}} + /> + {}} + onDelete={() => {}} + /> + , + ); + + expect(screen.getByRole("button", { name: "Edit Production Sentry instance" })).toBeTruthy(); + expect(screen.getByRole("button", { name: "Delete Self-hosted Sentry instance" })).toBeTruthy(); + }); +}); diff --git a/apps/web/components/sentry/sentry-instance-card.tsx b/apps/web/components/sentry/sentry-instance-card.tsx new file mode 100644 index 0000000000..f8bffccd31 --- /dev/null +++ b/apps/web/components/sentry/sentry-instance-card.tsx @@ -0,0 +1,71 @@ +"use client"; + +import { IconPencil, IconTrash } from "@tabler/icons-react"; +import { Button } from "@kandev/ui/button"; +import { + IntegrationAuthStatusBanner, + type IntegrationAuthHealth, +} from "@/components/integrations/auth-status-banner"; +import type { SentryConfig } from "@/lib/types/sentry"; + +// configToHealth maps an instance's backend-recorded probe fields to the shared +// auth-status banner shape. Returns null (banner hidden) until a secret exists. +export function configToHealth(config: SentryConfig): IntegrationAuthHealth | null { + if (!config.hasSecret) return null; + if (!config.lastCheckedAt) return { ok: false, error: "", checkedAt: null }; + return { + ok: !!config.lastOk, + error: config.lastError ?? "", + checkedAt: new Date(config.lastCheckedAt), + }; +} + +type SentryInstanceCardProps = { + instance: SentryConfig; + onEdit: () => void; + onDelete: () => void; +}; + +// SentryInstanceCard renders one saved instance: its name, URL, per-instance +// auth-health banner, and edit/delete actions. +export function SentryInstanceCard({ instance, onEdit, onDelete }: SentryInstanceCardProps) { + return ( +
+
+
+

+ {instance.name} +

+

{instance.url}

+
+
+ + +
+
+ +
+ ); +} diff --git a/apps/web/components/sentry/sentry-instance-form.test.tsx b/apps/web/components/sentry/sentry-instance-form.test.tsx new file mode 100644 index 0000000000..95358c3b3d --- /dev/null +++ b/apps/web/components/sentry/sentry-instance-form.test.tsx @@ -0,0 +1,80 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { TooltipProvider } from "@kandev/ui/tooltip"; +import type { SentryConfig } from "@/lib/types/sentry"; + +vi.mock("@/components/toast-provider", () => ({ + useToast: () => ({ toast: vi.fn() }), +})); + +vi.mock("@/lib/api/domains/sentry-api", () => ({ + createSentryInstance: vi.fn(), + updateSentryInstance: vi.fn(), + testSentryConnection: vi.fn(), + testSentryInstance: vi.fn(), + sentryErrorCode: vi.fn(), + SENTRY_ERROR_CODES: { nameTaken: "SENTRY_INSTANCE_NAME_TAKEN" }, +})); + +import { SentryInstanceForm } from "./sentry-instance-form"; + +const savedInstance: SentryConfig = { + id: "instance-1", + workspaceId: "workspace-1", + name: "Production", + authMethod: "auth_token", + url: "https://sentry.example.com", + hasSecret: true, + lastOk: true, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", +}; + +function renderForm() { + return render( + + + , + ); +} + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +describe("SentryInstanceForm", () => { + it("requires a token before testing an edited saved URL", () => { + renderForm(); + + fireEvent.change(screen.getByTestId("sentry-edit-url-input"), { + target: { value: "https://sentry-new.example.com" }, + }); + + expect(screen.getByTestId("sentry-edit-test-button")).toHaveProperty("disabled", true); + }); + + it("labels new-instance forms without labeling edit forms", () => { + render( + + + , + ); + + expect(screen.getByTestId("sentry-add-form-heading").textContent).toBe("New Instance"); + expect(screen.getByTestId("sentry-add-form-heading").className).toContain("font-semibold"); + expect(screen.queryByTestId("sentry-edit-form-heading")).toBeNull(); + }); +}); diff --git a/apps/web/components/sentry/sentry-instance-form.tsx b/apps/web/components/sentry/sentry-instance-form.tsx new file mode 100644 index 0000000000..300985e3a0 --- /dev/null +++ b/apps/web/components/sentry/sentry-instance-form.tsx @@ -0,0 +1,311 @@ +"use client"; + +import { useCallback, useState } from "react"; +import { IconInfoCircle } from "@tabler/icons-react"; +import { Button } from "@kandev/ui/button"; +import { Input } from "@kandev/ui/input"; +import { Label } from "@kandev/ui/label"; +import { Separator } from "@kandev/ui/separator"; +import { Alert, AlertDescription } from "@kandev/ui/alert"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip"; +import { useToast } from "@/components/toast-provider"; +import { + createSentryInstance, + SENTRY_ERROR_CODES, + sentryErrorCode, + testSentryConnection, + testSentryInstance, + updateSentryInstance, +} from "@/lib/api/domains/sentry-api"; +import { + SENTRY_AUTH_METHOD, + SENTRY_DEFAULT_URL, + type SentryConfig, + type TestSentryConnectionResult, +} from "@/lib/types/sentry"; + +const FIELD = "space-y-1.5"; +const HELP = "text-xs text-muted-foreground"; + +type FormState = { name: string; url: string; secret: string }; + +function instanceToForm(instance: SentryConfig | null): FormState { + return { name: instance?.name ?? "", url: instance?.url || SENTRY_DEFAULT_URL, secret: "" }; +} + +type FieldProps = { + form: FormState; + idPrefix: string; + loading: boolean; + update: (key: K, value: FormState[K]) => void; +}; + +function NameField({ form, idPrefix, loading, update }: FieldProps) { + return ( +
+ + update("name", e.target.value)} + disabled={loading} + /> +

A label for this instance. Must be unique within the workspace.

+
+ ); +} + +function UrlField({ form, idPrefix, loading, update }: FieldProps) { + return ( +
+ + update("url", e.target.value)} + disabled={loading} + /> +

+ Base URL of your Sentry instance. Leave as {SENTRY_DEFAULT_URL} for Sentry SaaS, or point it + at a self-hosted install (e.g. https://sentry.your-company.com). +

+
+ ); +} + +function SecretField({ + form, + idPrefix, + loading, + update, + hasSavedSecret, +}: FieldProps & { hasSavedSecret: boolean }) { + return ( +
+
+ + + + + + +

Grant Read access to these scopes:

+
    +
  • + org:read{" "} + Organization — resolve the org and list issues +
  • +
  • + project:read{" "} + Project — list projects and scope searches +
  • +
  • + event:read{" "} + + Issue & Event — browse issues and run watchers + +
  • +
+
+
+
+ update("secret", e.target.value)} + disabled={loading} + /> +
+ ); +} + +function TestResultAlert({ result }: { result: TestSentryConnectionResult | null }) { + if (!result) return null; + return ( + + + {result.ok + ? `Connected as ${result.displayName || result.email || result.userId}` + : `Failed: ${result.error}`} + + + ); +} + +type UseInstanceFormArgs = { + workspaceId: string; + instance: SentryConfig | null; + form: FormState; + onSaved: (cfg: SentryConfig) => void; +}; + +function useInstanceForm({ workspaceId, instance, form, onSaved }: UseInstanceFormArgs) { + const { toast } = useToast(); + const [saving, setSaving] = useState(false); + const [testing, setTesting] = useState(false); + const [testResult, setTestResult] = useState(null); + + // A saved instance can re-test its stored token only while its URL is + // unchanged. Any typed token or URL change is a candidate configuration. + const candidateTest = !instance || !!form.secret || form.url !== instance.url; + const handleTest = useCallback(async () => { + setTesting(true); + setTestResult(null); + try { + const res = candidateTest + ? await testSentryConnection(workspaceId, { + secret: form.secret || undefined, + url: form.url || undefined, + authMethod: SENTRY_AUTH_METHOD, + }) + : await testSentryInstance(workspaceId, instance!.id); + setTestResult(res); + } catch (err) { + setTestResult({ ok: false, error: String(err) }); + } finally { + setTesting(false); + } + }, [workspaceId, instance, candidateTest, form.secret, form.url]); + + const handleSave = useCallback(async () => { + setSaving(true); + try { + const saved = instance + ? await updateSentryInstance(workspaceId, instance.id, { + name: form.name.trim(), + authMethod: SENTRY_AUTH_METHOD, + url: form.url, + secret: form.secret, + }) + : await createSentryInstance(workspaceId, { + workspaceId, + name: form.name.trim(), + authMethod: SENTRY_AUTH_METHOD, + url: form.url, + secret: form.secret, + }); + toast({ description: "Sentry instance saved", variant: "success" }); + onSaved(saved); + } catch (err) { + const message = + sentryErrorCode(err) === SENTRY_ERROR_CODES.nameTaken + ? `An instance named "${form.name.trim()}" already exists in this workspace.` + : `Save failed: ${String(err)}`; + toast({ description: message, variant: "error" }); + } finally { + setSaving(false); + } + }, [workspaceId, instance, form, toast, onSaved]); + + return { saving, testing, testResult, candidateTest, handleTest, handleSave }; +} + +type SentryInstanceFormProps = { + workspaceId: string; + // instance === null creates a new instance; otherwise the form edits it. + instance: SentryConfig | null; + // idPrefix scopes element ids + testids so the mutually-exclusive add/edit + // forms never collide (e.g. "sentry-add" vs "sentry-edit"). + idPrefix: string; + onSaved: (cfg: SentryConfig) => void; + onCancel: () => void; +}; + +export function SentryInstanceForm({ + workspaceId, + instance, + idPrefix, + onSaved, + onCancel, +}: SentryInstanceFormProps) { + const [form, setForm] = useState(() => instanceToForm(instance)); + const update = useCallback( + (key: K, value: FormState[K]) => + setForm((prev) => ({ ...prev, [key]: value })), + [], + ); + const { saving, testing, testResult, candidateTest, handleTest, handleSave } = useInstanceForm({ + workspaceId, + instance, + form, + onSaved, + }); + + const hasSavedSecret = !!instance?.hasSecret; + const missingSecret = !hasSavedSecret && !form.secret; + const requiresTestSecret = !form.secret && (candidateTest || missingSecret); + const disableSave = saving || !form.name.trim() || missingSecret; + const disableTest = testing || requiresTestSecret; + let saveLabel = instance ? "Update" : "Save"; + if (saving) saveLabel = "Saving..."; + + return ( +
+ {instance === null && ( +

+ New Instance +

+ )} + + + + + +
+ + + +
+
+ ); +} diff --git a/apps/web/components/sentry/sentry-issue-dialog.test.tsx b/apps/web/components/sentry/sentry-issue-dialog.test.tsx new file mode 100644 index 0000000000..870f74430f --- /dev/null +++ b/apps/web/components/sentry/sentry-issue-dialog.test.tsx @@ -0,0 +1,112 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { listSentryProjects, searchSentryIssues } from "@/lib/api/domains/sentry-api"; +import { useSentryInstances } from "@/hooks/domains/sentry/use-sentry-availability"; +import type { SentryConfig } from "@/lib/types/sentry"; + +vi.mock("@/lib/api/domains/sentry-api", () => ({ + listSentryProjects: vi.fn(), + searchSentryIssues: vi.fn(), +})); + +vi.mock("@/hooks/domains/sentry/use-sentry-availability", () => ({ + useSentryInstances: vi.fn(), +})); + +import { SentryIssueDialog } from "./sentry-issue-dialog"; + +const instance: SentryConfig = { + id: "shared-instance", + workspaceId: "workspace-1", + name: "Production", + authMethod: "auth_token", + url: "https://sentry.example.com", + hasSecret: true, + lastOk: true, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", +}; + +function mockAvailability() { + vi.mocked(useSentryInstances).mockReturnValue({ + loading: false, + instances: [instance], + healthy: [instance], + available: true, + state: "single", + }); +} + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +describe("SentryIssueDialog", () => { + it("clears filters and results when its workspace changes", async () => { + mockAvailability(); + vi.mocked(listSentryProjects).mockResolvedValue({ + projects: [{ id: "project-1", slug: "web", name: "Web", orgSlug: "acme" }], + } as never); + vi.mocked(searchSentryIssues).mockResolvedValue({ + issues: [ + { + id: "issue-1", + shortId: "WEB-1", + title: "Stale workspace issue", + permalink: "https://sentry.example.com/issues/1", + projectSlug: "web", + level: "error", + status: "unresolved", + }, + ], + isLast: true, + } as never); + + const view = render( + , + ); + + await waitFor(() => { + expect((screen.getByLabelText("Organization") as HTMLInputElement).value).toBe("acme"); + }); + fireEvent.change(screen.getByLabelText("Query"), { target: { value: "is:unresolved" } }); + fireEvent.click(screen.getByRole("button", { name: "Search" })); + await screen.findByText("Stale workspace issue"); + + view.rerender( + , + ); + + expect((screen.getByLabelText("Query") as HTMLInputElement).value).toBe(""); + expect(screen.queryByText("Stale workspace issue")).toBeNull(); + }); + + it("clears a stuck loading state when a workspace change interrupts an in-flight search", async () => { + mockAvailability(); + vi.mocked(listSentryProjects).mockResolvedValue({ + projects: [{ id: "project-1", slug: "web", name: "Web", orgSlug: "acme" }], + } as never); + const pendingSearch = new Promise(() => {}); + vi.mocked(searchSentryIssues).mockReturnValue(pendingSearch); + + const view = render( + , + ); + + await waitFor(() => { + expect((screen.getByLabelText("Organization") as HTMLInputElement).value).toBe("acme"); + }); + + fireEvent.click(screen.getByRole("button", { name: "Search" })); + await waitFor(() => { + expect(document.querySelector(".animate-spin")).not.toBeNull(); + }); + + view.rerender( + , + ); + + expect(document.querySelector(".animate-spin")).toBeNull(); + }); +}); diff --git a/apps/web/components/sentry/sentry-issue-dialog.tsx b/apps/web/components/sentry/sentry-issue-dialog.tsx index b7261eec3b..23b986564b 100644 --- a/apps/web/components/sentry/sentry-issue-dialog.tsx +++ b/apps/web/components/sentry/sentry-issue-dialog.tsx @@ -9,7 +9,12 @@ import { Input } from "@kandev/ui/input"; import { Label } from "@kandev/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select"; import { listSentryProjects, searchSentryIssues } from "@/lib/api/domains/sentry-api"; +import { + useSentryInstances, + type SentryAvailabilityState, +} from "@/hooks/domains/sentry/use-sentry-availability"; import type { + SentryConfig, SentryIssue, SentryLevel, SentryProject, @@ -68,9 +73,31 @@ export function SentryIssueDialog({ open, onOpenChange, workspaceId }: SentryIss ); } -type DialogState = ReturnType; +// DialogState is the browse dialog's shared view-model, passed to the filter and +// results subcomponents. Named explicitly (not ReturnType) so the contract lives +// at this module boundary. +interface DialogState { + filter: FilterState; + updateFilter: (key: K, value: FilterState[K]) => void; + projects: SentryProject[]; + issues: SentryIssue[]; + nextCursor: string | undefined; + isLast: boolean; + loading: boolean; + error: string | null; + search: (nextCursorValue?: string) => Promise; + // instanceId is the Sentry instance the browse calls are scoped to; empty + // until one is chosen (or auto-selected when the workspace has exactly one + // healthy instance). + instanceId: string; + setInstanceId: (id: string) => void; + healthy: SentryConfig[]; + instancesState: SentryAvailabilityState; +} -function useDialogState(open: boolean, workspaceId?: string) { +function useDialogState(open: boolean, workspaceId?: string): DialogState { + const { healthy, state: instancesState } = useSentryInstances(workspaceId); + const [instanceId, setInstanceId] = useState(""); const [filter, setFilter] = useState(initialFilter); const [projects, setProjects] = useState([]); const [issues, setIssues] = useState([]); @@ -82,10 +109,52 @@ function useDialogState(open: boolean, workspaceId?: string) { // Monotonic request id: only the most recent search may write results, so an // out-of-order response from a superseded search can't clobber the list. const searchSeq = useRef(0); + const previousWorkspaceId = useRef(workspaceId); + + const resetBrowseState = useCallback((clearProjects = false) => { + setFilter(initialFilter); + if (clearProjects) setProjects([]); + setIssues([]); + setNextCursor(undefined); + setIsLast(true); + setError(null); + setConfigLoaded(false); + // Invalidating the sequence makes the in-flight search's `finally` skip + // setLoading(false) by design (its result is now stale) — so this reset + // must clear loading itself, or the dialog is stuck loading forever. + setLoading(false); + searchSeq.current++; + }, []); + + // Auto-select the sole healthy instance; force an explicit pick when several; + // drop a selection that is no longer healthy. + useEffect(() => { + setInstanceId((prev) => { + if (healthy.length === 0) return ""; + if (healthy.length === 1) return healthy[0].id; + return healthy.some((i) => i.id === prev) ? prev : ""; + }); + }, [healthy]); + + // Switching instance invalidates the previous instance's filter, results and + // cursor: reset them, invalidate any in-flight search, and refetch projects. + useEffect(() => { + resetBrowseState(); + }, [instanceId, resetBrowseState]); + + // A workspace switch can retain a stale instance selection until availability + // finishes loading. Clear the browse state directly instead of waiting for + // that selection to change. + useEffect(() => { + if (previousWorkspaceId.current === workspaceId) return; + previousWorkspaceId.current = workspaceId; + resetBrowseState(true); + }, [workspaceId, resetBrowseState]); useBrowseProjects({ open, workspaceId, + instanceId, loaded: configLoaded, setFilter, setLoaded: setConfigLoaded, @@ -100,20 +169,21 @@ function useDialogState(open: boolean, workspaceId?: string) { const search = useCallback( async (nextCursorValue?: string) => { + if (!instanceId) { + setError("Select a Sentry instance to search"); + return; + } if (!filter.orgSlug) { setError("Organization slug is required"); return; } + if (!workspaceId) return; const seq = ++searchSeq.current; setLoading(true); setError(null); try { const payload = toSearchFilter(filter); - const res = await searchSentryIssues( - payload, - nextCursorValue, - workspaceId ? { workspaceId } : undefined, - ); + const res = await searchSentryIssues(workspaceId, instanceId, payload, nextCursorValue); // A newer search started while this one was in flight — drop the result. if (seq !== searchSeq.current) return; const page = res.issues ?? []; @@ -128,7 +198,7 @@ function useDialogState(open: boolean, workspaceId?: string) { if (seq === searchSeq.current) setLoading(false); } }, - [workspaceId, filter], + [workspaceId, instanceId, filter], ); return { @@ -141,6 +211,10 @@ function useDialogState(open: boolean, workspaceId?: string) { loading, error, search, + instanceId, + setInstanceId, + healthy, + instancesState, }; } @@ -159,6 +233,7 @@ function toSearchFilter(filter: FilterState): SentrySearchFilter { type BrowseProjectsArgs = { open: boolean; workspaceId: string | undefined; + instanceId: string; loaded: boolean; setFilter: (f: (prev: FilterState) => FilterState) => void; setLoaded: (v: boolean) => void; @@ -168,6 +243,7 @@ type BrowseProjectsArgs = { function useBrowseProjects({ open, workspaceId, + instanceId, loaded, setFilter, setLoaded, @@ -181,14 +257,18 @@ function useBrowseProjects({ return; } if (loaded) return; + // Without a chosen instance there is nothing to fetch; wait (leave `loaded` + // false) until one is selected. + if (!workspaceId || !instanceId) { + setProjects([]); + return; + } let cancelled = false; (async () => { try { - const res = await listSentryProjects(workspaceId ? { workspaceId } : undefined).catch( - () => ({ - projects: [] as SentryProject[], - }), - ); + const res = await listSentryProjects(workspaceId, instanceId).catch(() => ({ + projects: [] as SentryProject[], + })); if (cancelled) return; const projects = res.projects ?? []; setProjects(projects); @@ -205,12 +285,13 @@ function useBrowseProjects({ return () => { cancelled = true; }; - }, [open, workspaceId, loaded, setFilter, setLoaded, setProjects]); + }, [open, workspaceId, instanceId, loaded, setFilter, setLoaded, setProjects]); } function FiltersBar({ state }: { state: DialogState }) { return (
+ + No Sentry instances configured for this workspace. +

+ ); + } + if (instancesState === "unhealthy") { + return ( +

+ No healthy Sentry instance — check the integration settings. +

+ ); + } + if (healthy.length <= 1) return null; + return ( +
+ + +
+ ); +} + function FilterTopRow({ state }: { state: DialogState }) { const { filter, updateFilter, projects } = state; return ( @@ -367,7 +487,7 @@ function FilterChipRow({ label, options, selected, onToggle, chipClass }: ChipRo } function SearchActionRow({ state }: { state: DialogState }) { - const { filter, updateFilter, loading, search } = state; + const { filter, updateFilter, loading, search, instanceId } = state; return (
@@ -392,7 +512,7 @@ function SearchActionRow({ state }: { state: DialogState }) { type="button" size="sm" onClick={() => void search()} - disabled={loading || !filter.orgSlug} + disabled={loading || !filter.orgSlug || !instanceId} className="cursor-pointer gap-1.5" > {loading ? ( @@ -407,7 +527,7 @@ function SearchActionRow({ state }: { state: DialogState }) { } function ResultsBody({ state }: { state: DialogState }) { - const { issues, loading, error, isLast, nextCursor, search } = state; + const { issues, loading, error, isLast, nextCursor, search, instanceId } = state; const empty = useMemo(() => !loading && !error && issues.length === 0, [loading, error, issues]); return ( @@ -415,7 +535,9 @@ function ResultsBody({ state }: { state: DialogState }) { {error && } {empty && (
- No issues yet. Run a search to begin. + {instanceId + ? "No issues yet. Run a search to begin." + : "Select a Sentry instance to browse its issues."}
)} {issues.map((issue) => ( diff --git a/apps/web/components/sentry/sentry-issue-watch-dialog.test.tsx b/apps/web/components/sentry/sentry-issue-watch-dialog.test.tsx new file mode 100644 index 0000000000..24910ae7c1 --- /dev/null +++ b/apps/web/components/sentry/sentry-issue-watch-dialog.test.tsx @@ -0,0 +1,171 @@ +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + listSentryInstances, + listSentryOrganizations, + listSentryProjects, +} from "@/lib/api/domains/sentry-api"; +import type { SentryConfig, SentryIssueWatch } from "@/lib/types/sentry"; +import { SentryIssueWatchDialog } from "./sentry-issue-watch-dialog"; + +const { WORKSPACE_ID } = vi.hoisted(() => ({ WORKSPACE_ID: "ws-1" })); + +vi.mock("@/components/state-provider", () => ({ + useAppStore: (selector: (state: unknown) => unknown) => + selector({ + workspaces: { activeId: WORKSPACE_ID, items: [{ id: WORKSPACE_ID, name: "Workspace" }] }, + workflows: { items: [] }, + agentProfiles: { items: [] }, + executors: { items: [] }, + }), +})); +vi.mock("@/hooks/domains/settings/use-settings-data", () => ({ useSettingsData: vi.fn() })); +vi.mock("@/hooks/use-workflows", () => ({ useWorkflows: vi.fn() })); +vi.mock("@/hooks/use-workflow-steps", () => ({ + useWorkflowSteps: () => ({ steps: [], loading: false }), + stepPlaceholder: () => "Select workflow first", +})); +vi.mock("@/components/watcher-repository-fields", () => ({ WatcherRepositoryFields: () => null })); +vi.mock("@/components/settings/profile-edit/script-editor", () => ({ + ScriptEditor: () => null, + computeEditorHeight: () => 0, +})); +vi.mock("./sentry-issue-watch-multiselect", () => ({ + LevelMultiSelect: () => null, + StatusMultiSelect: () => null, +})); +vi.mock("./sentry-issue-watch-throttle-field", () => ({ MaxInflightTasksField: () => null })); +vi.mock("@/lib/api/domains/sentry-api", () => ({ + listSentryInstances: vi.fn(), + listSentryOrganizations: vi.fn(), + listSentryProjects: vi.fn(), +})); + +const PRIMARY_INSTANCE_ID = "instance-a"; + +function sentryInstance(id: string, name: string): SentryConfig { + return { + id, + workspaceId: WORKSPACE_ID, + name, + authMethod: "auth_token", + url: "https://sentry.io", + hasSecret: true, + lastOk: true, + createdAt: "", + updatedAt: "", + }; +} + +function legacyUnboundWatch(): SentryIssueWatch { + return { + id: "watch-1", + workspaceId: WORKSPACE_ID, + sentryInstanceId: "", + workflowId: "workflow-1", + workflowStepId: "step-1", + repositoryId: "", + baseBranch: "", + filter: { orgSlug: "acme", projectSlug: "frontend" }, + agentProfileId: "", + executorProfileId: "", + prompt: "Handle the issue.", + enabled: true, + pollIntervalSeconds: 300, + maxInflightTasks: 5, + createdAt: "", + updatedAt: "", + }; +} + +function selectTrigger(label: string): HTMLButtonElement { + const trigger = screen.getByText(label).parentElement?.querySelector("button"); + if (!(trigger instanceof HTMLButtonElement)) throw new Error(`Missing ${label} selector`); + return trigger; +} + +async function choose(label: string, option: string): Promise { + fireEvent.click(selectTrigger(label)); + fireEvent.click(await screen.findByRole("option", { name: option })); +} + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +beforeEach(() => { + vi.mocked(listSentryInstances).mockResolvedValue([ + sentryInstance(PRIMARY_INSTANCE_ID, "Production"), + sentryInstance("instance-b", "Self-hosted"), + ]); + vi.mocked(listSentryOrganizations).mockImplementation(async (_workspaceId, instanceId) => ({ + organizations: [ + { id: instanceId, slug: instanceId === PRIMARY_INSTANCE_ID ? "acme" : "globex", name: "" }, + ], + })); + vi.mocked(listSentryProjects).mockImplementation(async (_workspaceId, instanceId) => ({ + projects: [ + { + id: instanceId, + slug: instanceId === PRIMARY_INSTANCE_ID ? "frontend" : "backend", + name: instanceId === PRIMARY_INSTANCE_ID ? "Frontend" : "Backend", + orgSlug: instanceId === PRIMARY_INSTANCE_ID ? "acme" : "globex", + }, + ], + })); +}); + +describe("SentryIssueWatchDialog", () => { + it("removes the previous instance's org and project choices before the new lookup resolves", async () => { + render( + , + ); + + await waitFor(() => { + expect(listSentryInstances).toHaveBeenCalledWith(WORKSPACE_ID); + }); + + await choose("Sentry instance", "Production"); + await waitFor(() => { + expect(listSentryOrganizations).toHaveBeenCalledWith(WORKSPACE_ID, PRIMARY_INSTANCE_ID); + expect(listSentryProjects).toHaveBeenCalledWith(WORKSPACE_ID, PRIMARY_INSTANCE_ID); + }); + + await choose("Sentry instance", "Self-hosted"); + + fireEvent.click(selectTrigger("Organization slug")); + expect(screen.queryByRole("option", { name: "acme" })).toBeNull(); + fireEvent.keyDown(document, { key: "Escape" }); + + fireEvent.click(selectTrigger("Project slug")); + expect(screen.queryByRole("option", { name: "Frontend (frontend)" })).toBeNull(); + }); + + it("permits mutable updates to a legacy unbound watch while its instance remains immutable", async () => { + render( + , + ); + + await waitFor(() => { + expect((screen.getByRole("button", { name: "Update" }) as HTMLButtonElement).disabled).toBe( + false, + ); + }); + expect(selectTrigger("Sentry instance").disabled).toBe(true); + }); +}); diff --git a/apps/web/components/sentry/sentry-issue-watch-dialog.tsx b/apps/web/components/sentry/sentry-issue-watch-dialog.tsx index 2afbb9c77a..ca874eeaa8 100644 --- a/apps/web/components/sentry/sentry-issue-watch-dialog.tsx +++ b/apps/web/components/sentry/sentry-issue-watch-dialog.tsx @@ -25,7 +25,11 @@ import { ScriptEditor, computeEditorHeight, } from "@/components/settings/profile-edit/script-editor"; -import { listSentryProjects, listSentryOrganizations } from "@/lib/api/domains/sentry-api"; +import { + listSentryInstances, + listSentryProjects, + listSentryOrganizations, +} from "@/lib/api/domains/sentry-api"; import { WatcherRepositoryFields } from "@/components/watcher-repository-fields"; import { clearWorkspaceScopedForm } from "@/lib/watcher-repository-default"; import { SENTRY_ISSUE_WATCH_PLACEHOLDERS } from "./sentry-issue-watch-placeholders"; @@ -38,12 +42,13 @@ import { projectSelectItems, parseMaxInflightTasks, isWatchFormReady, - buildFilterPayload, + buildWatchPayload, formStateFromWatch, makeEmptyForm, } from "./sentry-issue-watch-form"; import type { CreateSentryIssueWatchRequest, + SentryConfig, SentryIssueWatch, SentryLevel, SentryProject, @@ -85,11 +90,16 @@ function useFormData(workspaceId: string) { return { workflows, agentProfiles: filteredAgentProfiles, allExecutorProfiles }; } -function useSentryProjects(workspaceId: string, orgSlug: string) { +function useSentryProjects(workspaceId: string, instanceId: string, orgSlug: string) { const [projects, setProjects] = useState([]); useEffect(() => { + if (!workspaceId || !instanceId) { + setProjects([]); + return; + } + setProjects([]); let cancelled = false; - listSentryProjects({ workspaceId }) + listSentryProjects(workspaceId, instanceId) .then((res) => { if (!cancelled) setProjects(res.projects ?? []); }) @@ -99,7 +109,7 @@ function useSentryProjects(workspaceId: string, orgSlug: string) { return () => { cancelled = true; }; - }, [workspaceId]); + }, [workspaceId, instanceId]); // Sentry's auth-token endpoint already filters to the user's accessible orgs; // if an orgSlug is set, restrict to projects that match. return useMemo( @@ -194,7 +204,7 @@ function FilterFields({ setForm: FormSetter; orgs: string[]; }) { - const projects = useSentryProjects(form.workspaceId, form.orgSlug); + const projects = useSentryProjects(form.workspaceId, form.sentryInstanceId, form.orgSlug); const toggleLevel = useCallback( (level: SentryLevel) => setForm((p) => ({ @@ -334,6 +344,64 @@ function WorkspacePicker({ ); } +// useWorkspaceInstances loads the workspace's Sentry instances for the required +// instance selector and auto-selects the sole instance on a fresh create. +function useWorkspaceInstances( + open: boolean, + workspaceId: string, + hasWatch: boolean, + setForm: FormSetter, +) { + const [instances, setInstances] = useState([]); + useEffect(() => { + if (!open || !workspaceId) { + setInstances([]); + return; + } + let cancelled = false; + listSentryInstances(workspaceId) + .then((list) => { + if (!cancelled) setInstances(list); + }) + .catch(() => { + if (!cancelled) setInstances([]); + }); + return () => { + cancelled = true; + }; + }, [open, workspaceId]); + useEffect(() => { + if (hasWatch || instances.length !== 1) return; + setForm((p) => (p.sentryInstanceId ? p : { ...p, sentryInstanceId: instances[0].id })); + }, [hasWatch, instances, setForm]); + return instances; +} + +function InstancePicker({ + instances, + value, + onChange, + disabled, +}: { + instances: SentryConfig[]; + value: string; + onChange: (v: string) => void; + disabled?: boolean; +}) { + const noInstances = instances.length === 0; + return ( + ({ id: i.id, label: i.name }))} + disabled={disabled || noInstances} + /> + ); +} + function AutomationFields({ form, setForm }: { form: FormState; setForm: FormSetter }) { const { workflows, agentProfiles, allExecutorProfiles } = useFormData(form.workspaceId); const { steps, loading: stepsLoading } = useWorkflowSteps(form.workflowId); @@ -428,12 +496,22 @@ function savingLabel(saving: boolean, isEdit: boolean): string { // useWatchOrgs loads the org list for the org dropdown and auto-selects the // sole org on a fresh create (with one choice there is nothing to pick). -function useWatchOrgs(open: boolean, workspaceId: string, hasWatch: boolean, setForm: FormSetter) { +function useWatchOrgs( + open: boolean, + workspaceId: string, + instanceId: string, + hasWatch: boolean, + setForm: FormSetter, +) { const [orgs, setOrgs] = useState([]); useEffect(() => { - if (!open) return; + if (!open || !instanceId) { + setOrgs([]); + return; + } + setOrgs([]); let cancelled = false; - listSentryOrganizations({ workspaceId }) + listSentryOrganizations(workspaceId, instanceId) .then((res) => { if (!cancelled) setOrgs((res.organizations ?? []).map((o) => o.slug)); }) @@ -443,7 +521,7 @@ function useWatchOrgs(open: boolean, workspaceId: string, hasWatch: boolean, set return () => { cancelled = true; }; - }, [open, workspaceId]); + }, [open, workspaceId, instanceId]); useEffect(() => { if (hasWatch || orgs.length !== 1) return; setForm((p) => (p.orgSlug ? p : { ...p, orgSlug: orgs[0] })); @@ -471,37 +549,27 @@ export function SentryIssueWatchDialog({ } }, [watch, open, workspaceId, activeWorkspaceId]); - const orgs = useWatchOrgs(open, form.workspaceId, !!watch, setForm); + const instances = useWorkspaceInstances(open, form.workspaceId, !!watch, setForm); + const orgs = useWatchOrgs(open, form.workspaceId, form.sentryInstanceId, !!watch, setForm); - const workspaceLocked = !!watch || !!workspaceId; + const workspaceLocked = true; - const canSave = isWatchFormReady(form); + const canSave = isWatchFormReady(form, { requiresInstance: !watch }); const handleSave = useCallback(async () => { const maxInflight = parseMaxInflightTasks(form.maxInflightTasks); if (maxInflight === "invalid") return; setSaving(true); try { - const filter = buildFilterPayload(form); - const payload = { - filter, - workflowId: form.workflowId, - workflowStepId: form.workflowStepId, - // Empty repositoryId clears the binding; empty base branch is sent - // verbatim so the backend fills the repo's default at save time. - repositoryId: form.repositoryId, - baseBranch: form.repositoryId ? form.baseBranch : "", - agentProfileId: form.agentProfileId, - executorProfileId: form.executorProfileId, - prompt: form.prompt, - enabled: form.enabled, - pollIntervalSeconds: form.pollInterval, - maxInflightTasks: maxInflight, - }; + const payload = buildWatchPayload(form, maxInflight); if (watch) { await onUpdate(watch.id, watch.workspaceId, payload); } else { - await onCreate({ ...payload, workspaceId: form.workspaceId }); + await onCreate({ + ...payload, + workspaceId: form.workspaceId, + sentryInstanceId: form.sentryInstanceId, + }); } onOpenChange(false); } catch { @@ -528,6 +596,14 @@ export function SentryIssueWatchDialog({ onChange={(v) => setForm((p) => clearWorkspaceScopedForm(p, v))} disabled={workspaceLocked} /> + + setForm((p) => ({ ...p, sentryInstanceId: v, orgSlug: "", projectSlug: "" })) + } + disabled={!!watch} + /> diff --git a/apps/web/components/sentry/sentry-issue-watch-form.test.ts b/apps/web/components/sentry/sentry-issue-watch-form.test.ts index bf008c6f1d..2b8738373d 100644 --- a/apps/web/components/sentry/sentry-issue-watch-form.test.ts +++ b/apps/web/components/sentry/sentry-issue-watch-form.test.ts @@ -5,6 +5,7 @@ import { maxInflightTasksString, parseMaxInflightTasks, buildFilterPayload, + isWatchFormReady, makeEmptyForm, } from "./sentry-issue-watch-form"; import type { SentryProject } from "@/lib/types/sentry"; @@ -97,3 +98,18 @@ describe("buildFilterPayload", () => { expect(filter.projectSlug).toBe("web"); }); }); + +describe("isWatchFormReady", () => { + it("allows a legacy unbound watch to update its mutable fields", () => { + const legacyUnbound = { + ...makeEmptyForm("ws-1"), + orgSlug: "acme", + projectSlug: "web", + workflowId: "workflow-1", + workflowStepId: "step-1", + sentryInstanceId: "", + }; + + expect(isWatchFormReady(legacyUnbound, { requiresInstance: false })).toBe(true); + }); +}); diff --git a/apps/web/components/sentry/sentry-issue-watch-form.ts b/apps/web/components/sentry/sentry-issue-watch-form.ts index c9022bfe48..928943d447 100644 --- a/apps/web/components/sentry/sentry-issue-watch-form.ts +++ b/apps/web/components/sentry/sentry-issue-watch-form.ts @@ -20,6 +20,8 @@ export const STATS_PERIOD_OPTIONS: { value: string; label: string }[] = [ export interface FormState { workspaceId: string; + /** The Sentry instance to poll. Required; immutable after create. */ + sentryInstanceId: string; orgSlug: string; projectSlug: string; environment: string; @@ -44,6 +46,7 @@ export interface FormState { export function makeEmptyForm(workspaceId: string): FormState { return { workspaceId, + sentryInstanceId: "", orgSlug: "", projectSlug: "", environment: "", @@ -68,6 +71,7 @@ export function formStateFromWatch(w: SentryIssueWatch): FormState { const f: SentrySearchFilter = w.filter ?? { orgSlug: "" }; return { workspaceId: w.workspaceId, + sentryInstanceId: w.sentryInstanceId ?? "", orgSlug: f.orgSlug ?? "", projectSlug: f.projectSlug ?? "", environment: f.environment ?? "", @@ -144,9 +148,13 @@ export function projectSelectItems(projects: SentryProject[], current: string): // isWatchFormReady aggregates the dialog's "can Save enable?" rule. Kept here // so the rule has one named home and the dialog stays under its line limit. -export function isWatchFormReady(form: FormState): boolean { +export function isWatchFormReady( + form: FormState, + { requiresInstance = true }: { requiresInstance?: boolean } = {}, +): boolean { return ( !!form.workspaceId && + (!requiresInstance || !!form.sentryInstanceId) && !!form.orgSlug.trim() && !!form.projectSlug.trim() && !!form.workflowId && @@ -170,3 +178,24 @@ export function buildFilterPayload(form: FormState): SentrySearchFilter { statsPeriod: form.statsPeriod || undefined, }; } + +// buildWatchPayload assembles the create/update watch fields shared by both +// paths (everything except workspaceId + sentryInstanceId, which only create +// carries). maxInflightTasks is resolved by the caller via parseMaxInflightTasks. +export function buildWatchPayload(form: FormState, maxInflightTasks: number | null) { + return { + filter: buildFilterPayload(form), + workflowId: form.workflowId, + workflowStepId: form.workflowStepId, + // Empty repositoryId clears the binding; empty base branch is sent verbatim + // so the backend fills the repo's default at save time. + repositoryId: form.repositoryId, + baseBranch: form.repositoryId ? form.baseBranch : "", + agentProfileId: form.agentProfileId, + executorProfileId: form.executorProfileId, + prompt: form.prompt, + enabled: form.enabled, + pollIntervalSeconds: form.pollInterval, + maxInflightTasks, + }; +} diff --git a/apps/web/components/sentry/sentry-issue-watch-table.test.tsx b/apps/web/components/sentry/sentry-issue-watch-table.test.tsx new file mode 100644 index 0000000000..9cf6f4592c --- /dev/null +++ b/apps/web/components/sentry/sentry-issue-watch-table.test.tsx @@ -0,0 +1,76 @@ +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { TooltipProvider } from "@kandev/ui/tooltip"; +import type { SentryIssueWatch } from "@/lib/types/sentry"; +import { SentryIssueWatchTable } from "./sentry-issue-watch-table"; + +function watch(over: Partial): SentryIssueWatch { + return { + id: "w1", + workspaceId: "ws-1", + sentryInstanceId: "inst-1", + workflowId: "wf", + workflowStepId: "step", + repositoryId: "", + baseBranch: "", + filter: { orgSlug: "acme", projectSlug: "web" }, + agentProfileId: "ap", + executorProfileId: "", + prompt: "", + enabled: true, + pollIntervalSeconds: 300, + lastPolledAt: null, + lastError: "", + lastErrorAt: null, + createdAt: "", + updatedAt: "", + ...over, + } as unknown as SentryIssueWatch; +} + +const noop = vi.fn(); + +function resolveName(id: string): string { + if (id === "inst-1") return "Production"; + if (id === "") return "—"; + return "(unavailable)"; +} + +function renderTable(watches: SentryIssueWatch[]) { + return render( + + + , + ); +} + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +describe("SentryIssueWatchTable", () => { + it("shows an Instance column, not a Workspace column (integration is workspace-scoped)", () => { + renderTable([watch({ id: "w1" })]); + expect(screen.getByText("Instance")).toBeTruthy(); + expect(screen.queryByText("Workspace")).toBeNull(); + }); + + it("renders each watch's bound instance name via the resolver", () => { + renderTable([ + watch({ id: "w1", sentryInstanceId: "inst-1" }), + watch({ id: "w2", sentryInstanceId: "inst-gone" }), + watch({ id: "w3", sentryInstanceId: "" }), + ]); + const cells = screen.getAllByTestId("watch-instance").map((c) => c.textContent); + expect(cells).toEqual(["Production", "(unavailable)", "—"]); + }); +}); diff --git a/apps/web/components/sentry/sentry-issue-watch-table.tsx b/apps/web/components/sentry/sentry-issue-watch-table.tsx index 80682f0ad0..7ab8a58b8e 100644 --- a/apps/web/components/sentry/sentry-issue-watch-table.tsx +++ b/apps/web/components/sentry/sentry-issue-watch-table.tsx @@ -11,14 +11,14 @@ import { Button } from "@kandev/ui/button"; import { Badge } from "@kandev/ui/badge"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@kandev/ui/table"; import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip"; -import { useAppStore } from "@/components/state-provider"; import type { SentryIssueWatch, SentrySearchFilter } from "@/lib/types/sentry"; type SentryIssueWatchTableProps = { watches: SentryIssueWatch[]; - // showWorkspace renders a Workspace column when the table aggregates rows - // from every workspace (install-wide settings page). - showWorkspace?: boolean; + // instanceName resolves a watch's bound sentryInstanceId to its display name. + // The table is workspace-scoped, so it shows which instance each watch polls + // (not which workspace it belongs to). + instanceName: (sentryInstanceId: string) => string; onEdit: (watch: SentryIssueWatch) => void; onDelete: (id: string, workspaceId: string) => void; onTrigger: (id: string, workspaceId: string) => void; @@ -149,16 +149,13 @@ function WatchActions({ export function SentryIssueWatchTable({ watches, - showWorkspace, + instanceName, onEdit, onDelete, onTrigger, onReset, onToggleEnabled, }: SentryIssueWatchTableProps) { - const workspaces = useAppStore((s) => s.workspaces.items); - const workspaceName = (id: string) => workspaces.find((w) => w.id === id)?.name ?? id; - if (watches.length === 0) { return (

@@ -171,7 +168,7 @@ export function SentryIssueWatchTable({ - {showWorkspace && Workspace} + Instance Filter Interval Last Polled @@ -182,11 +179,9 @@ export function SentryIssueWatchTable({ {watches.map((watch) => ( onEdit(watch)}> - {showWorkspace && ( - - {workspaceName(watch.workspaceId)} - - )} + + {instanceName(watch.sentryInstanceId)} + ({ activeId: "ws-active" as string | null })); + +vi.mock("@/components/state-provider", () => ({ + useAppStore: (sel: (s: unknown) => unknown) => + sel({ workspaces: { activeId: h.activeId, items: [] } }), +})); + +vi.mock("@/hooks/domains/sentry/use-sentry-issue-watches", () => ({ + useSentryIssueWatches: vi.fn(() => ({ + items: [], + loading: false, + create: vi.fn(), + update: vi.fn(), + remove: vi.fn(), + trigger: vi.fn(), + previewReset: vi.fn(), + reset: vi.fn(), + })), +})); + +vi.mock("@/hooks/domains/sentry/use-sentry-availability", () => ({ + useSentryInstances: vi.fn(() => ({ + instances: [], + healthy: [], + loading: false, + available: false, + state: "empty", + })), +})); + +vi.mock("@/components/toast-provider", () => ({ useToast: () => ({ toast: vi.fn() }) })); +vi.mock("./sentry-issue-watch-table", () => ({ SentryIssueWatchTable: () => null })); +vi.mock("./sentry-issue-watch-dialog", () => ({ SentryIssueWatchDialog: () => null })); +vi.mock("@/components/watches/reset-watch-dialog", () => ({ + ResetWatchDialog: () => null, + useWatchResetController: () => ({ + resetting: null, + setResetting: vi.fn(), + onOpenChange: vi.fn(), + previewLoader: vi.fn(), + confirmReset: vi.fn(), + }), +})); + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +describe("SentryIssueWatchersSection scoping", () => { + it("fetches watches only for its supplied workspace (never all workspaces)", () => { + render(); + expect(vi.mocked(useSentryIssueWatches)).toHaveBeenCalledWith("ws-active"); + // never the unscoped `undefined` that would return foreign-workspace watches + expect(vi.mocked(useSentryIssueWatches)).not.toHaveBeenCalledWith(undefined); + }); + + it("fetches watches for the routed workspace before the active workspace", () => { + render(); + expect(vi.mocked(useSentryIssueWatches)).toHaveBeenCalledWith("ws-route"); + expect(vi.mocked(useSentryIssueWatches)).not.toHaveBeenCalledWith("ws-active"); + }); +}); diff --git a/apps/web/components/sentry/sentry-issue-watchers-section.tsx b/apps/web/components/sentry/sentry-issue-watchers-section.tsx index a8412a121d..17a87e82e1 100644 --- a/apps/web/components/sentry/sentry-issue-watchers-section.tsx +++ b/apps/web/components/sentry/sentry-issue-watchers-section.tsx @@ -7,14 +7,15 @@ import { Card, CardContent } from "@kandev/ui/card"; import { SettingsSection } from "@/components/settings/settings-section"; import { useToast } from "@/components/toast-provider"; import { useSentryIssueWatches } from "@/hooks/domains/sentry/use-sentry-issue-watches"; +import { useSentryInstances } from "@/hooks/domains/sentry/use-sentry-availability"; import { ResetWatchDialog, useWatchResetController } from "@/components/watches/reset-watch-dialog"; import { SentryIssueWatchTable } from "./sentry-issue-watch-table"; import { SentryIssueWatchDialog } from "./sentry-issue-watch-dialog"; import type { SentryIssueWatch } from "@/lib/types/sentry"; -// SentryIssueWatchersSection lists watches across every workspace in a single -// flat table on the install-wide settings page. The dialog's create flow asks -// the user to pick the workspace. +// SentryIssueWatchersSection lists watches for the workspace resolved by its +// parent integration page. Creating a watch is locked to that workspace and +// requires picking one of its Sentry instances. type RawActions = { create: ReturnType["create"]; update: ReturnType["update"]; @@ -121,9 +122,17 @@ function useToastedActions({ create, update, remove, trigger, reset }: RawAction }; } -export function SentryIssueWatchersSection() { +export function SentryIssueWatchersSection({ workspaceId }: { workspaceId: string }) { const { items, loading, create, update, remove, trigger, previewReset, reset } = - useSentryIssueWatches(); + useSentryIssueWatches(workspaceId); + const { instances } = useSentryInstances(workspaceId); + const instanceName = useCallback( + (id: string) => { + if (!id) return "—"; + return instances.find((i) => i.id === id)?.name ?? "(unavailable)"; + }, + [instances], + ); const actions = useToastedActions({ create, update, remove, trigger, reset }); const [dialogOpen, setDialogOpen] = useState(false); @@ -170,7 +179,7 @@ export function SentryIssueWatchersSection() { ) : ( ({ + activeWorkspaceId: "ws-active", + setEnabled: vi.fn(), + toast: vi.fn(), + workspaces: [ + { id: "ws-active", name: "Active" }, + { id: "ws-route", name: "Route" }, + ], +})); + +vi.mock("@/components/toast-provider", () => ({ + useToast: () => ({ toast: mocks.toast }), +})); + +vi.mock("@/hooks/domains/sentry/use-sentry-enabled", () => ({ + useSentryEnabled: () => ({ enabled: true, setEnabled: mocks.setEnabled }), +})); + +vi.mock("@/hooks/domains/integrations/use-integration-availability", () => ({ + INTEGRATION_STATUS_REFRESH_MS: 1, +})); + +vi.mock("@kandev/ui/switch", () => ({ + Switch: ({ onCheckedChange: _onCheckedChange, ...props }: Record) => ( + - - {hasConfig && ( - +
+ {instances.map((instance) => + mode.kind === "edit" && mode.id === instance.id ? ( + + ) : ( + onEdit(instance.id)} + onDelete={() => onDelete(instance)} + /> + ), )}
); } -type SettingsActionsArgs = { - workspaceId: string; - form: FormState; - setConfig: (cfg: SentryConfig | null) => void; - setForm: (form: FormState) => void; - setTestResult: (r: TestSentryConnectionResult | null) => void; -}; - -function useSettingsActions({ - workspaceId, - form, - setConfig, - setForm, - setTestResult, -}: SettingsActionsArgs) { - const { toast } = useToast(); - const [saving, setSaving] = useState(false); - const [testing, setTesting] = useState(false); - - const handleTest = useCallback(async () => { - setTesting(true); - setTestResult(null); - try { - const res = await testSentryConnection(form.secret || undefined, form.url || undefined, { - workspaceId, - }); - setTestResult(res); - } catch (err) { - setTestResult({ ok: false, error: String(err) }); - } finally { - setTesting(false); - } - }, [workspaceId, form, setTestResult]); - - const handleSave = useCallback(async () => { - setSaving(true); - try { - const saved = await saveSentryConfig( - { - authMethod: SENTRY_AUTH_METHOD, - url: form.url, - secret: form.secret, - }, - { workspaceId }, - ); - setConfig(saved); - setForm(configToForm(saved)); - setTestResult(null); - toast({ description: "Sentry configuration saved", variant: "success" }); - } catch (err) { - toast({ description: `Save failed: ${String(err)}`, variant: "error" }); - } finally { - setSaving(false); - } - }, [workspaceId, form, toast, setConfig, setForm, setTestResult]); - - const handleDelete = useCallback(async () => { - if (!confirm("Remove Sentry configuration?")) return; - try { - await deleteSentryConfig({ workspaceId }); - setConfig(null); - setForm(emptyForm); - setTestResult(null); - toast({ description: "Sentry configuration removed", variant: "success" }); - } catch (err) { - toast({ description: `Delete failed: ${String(err)}`, variant: "error" }); - } - }, [workspaceId, toast, setConfig, setForm, setTestResult]); - - return { saving, testing, handleTest, handleSave, handleDelete }; -} - -function useSentrySettings(workspaceId: string) { - const { toast } = useToast(); - const [config, setConfig] = useState(null); - const [form, setForm] = useState(emptyForm); - const [loading, setLoading] = useState(true); - const [testResult, setTestResult] = useState(null); - const health = configToHealth(config); - - const load = useCallback(async () => { - setLoading(true); - try { - const cfg = (await fetchSentryConfig({ workspaceId })) ?? null; - setConfig(cfg); - setForm(configToForm(cfg)); - } catch (err) { - toast({ description: `Failed to load Sentry config: ${String(err)}`, variant: "error" }); - } finally { - setLoading(false); - } - }, [workspaceId, toast]); - - useEffect(() => { - void load(); - }, [load]); - - useEffect(() => { - const id = setInterval(() => { - fetchSentryConfig({ workspaceId }) - .then((cfg) => setConfig(cfg ?? null)) - .catch(() => { - /* transient failures are fine — next tick retries */ - }); - }, INTEGRATION_STATUS_REFRESH_MS); - return () => clearInterval(id); - }, [workspaceId]); - - const update = useCallback( - (key: K, value: FormState[K]) => - setForm((prev) => ({ ...prev, [key]: value })), - [], - ); - - const { saving, testing, handleTest, handleSave, handleDelete } = useSettingsActions({ - workspaceId, - form, - setConfig, - setForm, - setTestResult, - }); - - return { - config, - form, - loading, - saving, - testing, - testResult, - health, - update, - handleTest, - handleSave, - handleDelete, - }; -} - function EnabledPill() { const { enabled, setEnabled } = useSentryEnabled(); return ( @@ -389,41 +137,89 @@ function EnabledPill() { } export function SentryConnectionSection({ workspaceId }: { workspaceId: string }) { - const s = useSentrySettings(workspaceId); - const missingSecret = !s.config?.hasSecret && !s.form.secret; - const disableSave = s.saving || missingSecret; - const disableTest = missingSecret; + const { instances, loading, reload } = useInstanceList(workspaceId); + const { toast } = useToast(); + const [mode, setMode] = useState({ kind: "none" }); + + const closeForm = useCallback(() => setMode({ kind: "none" }), []); + const handleSaved = useCallback(async () => { + setMode({ kind: "none" }); + await reload(); + }, [reload]); + + const handleDelete = useCallback( + async (instance: SentryConfig) => { + if (!confirm(`Remove Sentry instance "${instance.name}"?`)) return; + try { + await deleteSentryInstance(workspaceId, instance.id); + toast({ description: "Sentry instance removed", variant: "success" }); + await reload(); + } catch (err) { + const watchCount = sentryInUseWatchCount(err); + if (watchCount !== null) { + const plural = watchCount === 1 ? "watch" : "watches"; + toast({ + description: `Can't delete "${instance.name}": ${watchCount} ${plural} still bound to it. Reassign or remove those watchers first.`, + variant: "error", + }); + return; + } + toast({ description: `Delete failed: ${String(err)}`, variant: "error" }); + } + }, + [workspaceId, toast, reload], + ); + + const canAddInstance = + mode.kind === "none" || + (mode.kind === "edit" && !instances.some((instance) => instance.id === mode.id)); return ( } title="Sentry integration" - description="Connect this workspace to Sentry with a user auth token. Credentials are stored encrypted server-side for the selected workspace." + description="Connect this workspace to Sentry. Add a named instance for each Sentry org or self-hosted host; credentials are stored encrypted server-side." action={} > - - - - - - - + +

+ Instances +

+ {loading && instances.length === 0 ? ( +

Loading…

+ ) : ( + setMode({ kind: "edit", id })} + onDelete={handleDelete} + onSaved={handleSaved} + onCancel={closeForm} + /> + )} + {mode.kind === "add" && ( + + )} + {canAddInstance && ( + + )}
@@ -438,9 +234,13 @@ export function SentryIntegrationPage({ workspaceId }: SentryIntegrationPageProp return (
- {(workspaceId) => } + {(resolvedWorkspaceId) => ( +
+ + +
+ )}
-
); } diff --git a/apps/web/components/task/task-external-link-dialog.test.tsx b/apps/web/components/task/task-external-link-dialog.test.tsx index e5e75bea89..856aa521b2 100644 --- a/apps/web/components/task/task-external-link-dialog.test.tsx +++ b/apps/web/components/task/task-external-link-dialog.test.tsx @@ -6,6 +6,9 @@ import { getJiraTicket } from "@/lib/api/domains/jira-api"; import { getLinearIssue } from "@/lib/api/domains/linear-api"; import { getSentryIssue } from "@/lib/api/domains/sentry-api"; import { updateTask } from "@/lib/api/domains/kanban-api"; +import { useSentryInstances } from "@/hooks/domains/sentry/use-sentry-availability"; +import type { SentryAvailability } from "@/hooks/domains/sentry/use-sentry-availability"; +import type { SentryConfig } from "@/lib/types/sentry"; import { TaskExternalLinkDialog } from "./task-external-link-dialog"; vi.mock("@/lib/api/domains/jira-api", () => ({ @@ -24,13 +27,45 @@ vi.mock("@/lib/api/domains/kanban-api", () => ({ updateTask: vi.fn(), })); +vi.mock("@/hooks/domains/sentry/use-sentry-availability", () => ({ + useSentryInstances: vi.fn(), + isHealthySentryInstance: (i: SentryConfig) => i.hasSecret && i.lastOk, +})); + const INPUT_TEST_ID = "task-external-link-input"; const SUBMIT_TEST_ID = "task-external-link-submit"; const ERROR_TEST_ID = "task-external-link-error"; +const INSTANCE_SELECT_TEST_ID = "sentry-link-instance-select"; +const NO_INSTANCE_TEST_ID = "sentry-link-no-instance"; const TASK_ID = "task-1"; const WORKSPACE_ID = "workspace-1"; const TASK_TITLE = "Fix login"; +function instance(id: string, name: string): SentryConfig { + return { + id, + workspaceId: WORKSPACE_ID, + name, + authMethod: "auth_token", + url: "https://sentry.io", + hasSecret: true, + lastOk: true, + lastError: "", + createdAt: "", + updatedAt: "", + }; +} + +function mockSentryInstances(state: SentryAvailability["state"], healthy: SentryConfig[]) { + vi.mocked(useSentryInstances).mockReturnValue({ + loading: false, + instances: healthy, + healthy, + available: healthy.length > 0, + state, + }); +} + afterEach(() => { cleanup(); vi.clearAllMocks(); @@ -52,7 +87,7 @@ function renderDialog(provider: "jira" | "linear" | "sentry" = "jira") { ); } -describe("TaskExternalLinkDialog", () => { +describe("TaskExternalLinkDialog — Jira and Linear", () => { it("validates and links a Jira ticket by updating the task title", async () => { vi.mocked(getJiraTicket).mockResolvedValue({ key: "PROJ-12" } as never); vi.mocked(updateTask).mockResolvedValue({ id: TASK_ID, title: "PROJ-12: Fix login" } as never); @@ -86,24 +121,63 @@ describe("TaskExternalLinkDialog", () => { }); expect(updateTask).toHaveBeenCalledWith(TASK_ID, { title: "ENG-20: Fix login" }); }); +}); - it("extracts and links a Sentry issue key from a numeric issue URL", async () => { +describe("TaskExternalLinkDialog — Sentry linking", () => { + it("auto-selects the sole healthy Sentry instance and links against it", async () => { + mockSentryInstances("single", [instance("inst-1", "Production")]); vi.mocked(getSentryIssue).mockResolvedValue({ shortId: "API-42" } as never); vi.mocked(updateTask).mockResolvedValue({ id: TASK_ID, title: "API-42: Fix login" } as never); renderDialog("sentry"); + // The sole instance auto-selects, so no picker is shown. + expect(screen.queryByTestId(INSTANCE_SELECT_TEST_ID)).toBeNull(); + fireEvent.change(screen.getByTestId(INPUT_TEST_ID), { target: { value: "https://sentry.io/organizations/acme/issues/123456/" }, }); fireEvent.click(screen.getByTestId(SUBMIT_TEST_ID)); + // The chosen instance id is threaded into the strict browse contract. await waitFor(() => { - expect(getSentryIssue).toHaveBeenCalledWith("123456", { workspaceId: WORKSPACE_ID }); + expect(getSentryIssue).toHaveBeenCalledWith(WORKSPACE_ID, "inst-1", "123456"); }); expect(updateTask).toHaveBeenCalledWith(TASK_ID, { title: "API-42: Fix login" }); }); + it("prompts for a Sentry instance when several are healthy and blocks submit", () => { + mockSentryInstances("multi", [ + instance("inst-1", "Production"), + instance("inst-2", "Self-hosted"), + ]); + + renderDialog("sentry"); + + // A picker is shown and submit stays disabled until an instance is chosen. + expect(screen.getByTestId(INSTANCE_SELECT_TEST_ID)).toBeTruthy(); + fireEvent.change(screen.getByTestId(INPUT_TEST_ID), { target: { value: "PROJ-1" } }); + const submit = screen.getByTestId(SUBMIT_TEST_ID) as HTMLButtonElement; + expect(submit.disabled).toBe(true); + fireEvent.click(submit); + expect(getSentryIssue).not.toHaveBeenCalled(); + }); + + it("explains and blocks linking when the workspace has no healthy Sentry instance", () => { + mockSentryInstances("empty", []); + + renderDialog("sentry"); + + expect(screen.getByTestId(NO_INSTANCE_TEST_ID)).toBeTruthy(); + fireEvent.change(screen.getByTestId(INPUT_TEST_ID), { target: { value: "PROJ-1" } }); + const submit = screen.getByTestId(SUBMIT_TEST_ID) as HTMLButtonElement; + expect(submit.disabled).toBe(true); + fireEvent.click(submit); + expect(getSentryIssue).not.toHaveBeenCalled(); + }); +}); + +describe("TaskExternalLinkDialog — validation", () => { it("shows an inline validation error for invalid input", async () => { renderDialog("jira"); @@ -124,3 +198,69 @@ describe("TaskExternalLinkDialog", () => { expect(screen.queryByTestId(ERROR_TEST_ID)).toBeNull(); }); }); + +describe("TaskExternalLinkDialog — Sentry availability", () => { + it("clears a selected Sentry instance when it is no longer healthy", async () => { + mockSentryInstances("multi", [ + instance("inst-1", "Production"), + instance("inst-2", "Self-hosted"), + ]); + renderDialog("sentry"); + + fireEvent.change(screen.getByTestId(INPUT_TEST_ID), { target: { value: "PROJ-1" } }); + fireEvent.click(screen.getByTestId(INSTANCE_SELECT_TEST_ID)); + fireEvent.click(await screen.findByRole("option", { name: "Production" })); + await waitFor(() => { + expect((screen.getByTestId(SUBMIT_TEST_ID) as HTMLButtonElement).disabled).toBe(false); + }); + + mockSentryInstances("multi", [ + instance("inst-2", "Self-hosted"), + instance("inst-3", "Staging"), + ]); + fireEvent.change(screen.getByTestId(INPUT_TEST_ID), { target: { value: "PROJ-2" } }); + + await waitFor(() => { + expect((screen.getByTestId(SUBMIT_TEST_ID) as HTMLButtonElement).disabled).toBe(true); + }); + }); +}); + +describe("TaskExternalLinkDialog — Sentry sole-instance swap", () => { + it("retargets the link when a poll swaps the sole healthy instance (state stays single)", async () => { + mockSentryInstances("single", [instance("inst-1", "Alpha")]); + vi.mocked(getSentryIssue).mockResolvedValue({ shortId: "PROJ-2" } as never); + vi.mocked(updateTask).mockResolvedValue({ id: TASK_ID, title: "PROJ-2: Fix login" } as never); + + const view = renderDialog("sentry"); + fireEvent.change(screen.getByTestId(INPUT_TEST_ID), { target: { value: "PROJ-1" } }); + await waitFor(() => { + expect((screen.getByTestId(SUBMIT_TEST_ID) as HTMLButtonElement).disabled).toBe(false); + }); + + // A polling refresh replaces the sole healthy instance (inst-1 -> inst-2) + // while availability state remains "single". The effect must retarget the + // new instance rather than link against the stale inst-1. + mockSentryInstances("single", [instance("inst-2", "Beta")]); + view.rerender( + + + + + , + ); + + fireEvent.change(screen.getByTestId(INPUT_TEST_ID), { target: { value: "PROJ-2" } }); + fireEvent.click(screen.getByTestId(SUBMIT_TEST_ID)); + + await waitFor(() => { + expect(getSentryIssue).toHaveBeenCalledWith(WORKSPACE_ID, "inst-2", "PROJ-2"); + }); + }); +}); diff --git a/apps/web/components/task/task-external-link-dialog.tsx b/apps/web/components/task/task-external-link-dialog.tsx index fa9124d1a0..39e33a4305 100644 --- a/apps/web/components/task/task-external-link-dialog.tsx +++ b/apps/web/components/task/task-external-link-dialog.tsx @@ -12,6 +12,7 @@ import { } from "@kandev/ui/dialog"; import { Input } from "@kandev/ui/input"; import { Label } from "@kandev/ui/label"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select"; import { useToast } from "@/components/toast-provider"; import { useAppStoreApi } from "@/components/state-provider"; import { getJiraTicket } from "@/lib/api/domains/jira-api"; @@ -21,6 +22,7 @@ import { updateTask } from "@/lib/api/domains/kanban-api"; import { JIRA_KEY_RE } from "@/components/jira/jira-ticket-common"; import { LINEAR_KEY_RE } from "@/components/linear/linear-issue-common"; import { extractSentryShortId } from "@/components/sentry/sentry-issue-common"; +import { useSentryInstances } from "@/hooks/domains/sentry/use-sentry-availability"; import { findTaskInSnapshots } from "@/lib/kanban/find-task"; import type { SentryIssue } from "@/lib/types/sentry"; import { buildLinkedIssueTitle } from "./task-external-link-utils"; @@ -48,8 +50,11 @@ type ProviderConfig = { validationHint: string; successLabel: string; extractKey: (raw: string) => string | null; - fetch: (key: string, workspaceId: string) => Promise; + fetch: (key: string, workspaceId: string, instanceId?: string) => Promise; resolveLinkedKey?: (requestedKey: string, result: unknown) => string; + // requiresInstance gates providers (Sentry) whose fetch must target a chosen + // instance within the workspace before it can run. + requiresInstance?: boolean; }; const SENTRY_NUMERIC_ISSUE_URL_RE = /\/issues\/(\d+)(?:[/?#]|$)/i; @@ -95,23 +100,93 @@ const PROVIDERS: Record = { validationHint: "Paste a Sentry issue URL or short ID (PROJ-123).", successLabel: "Sentry issue linked", extractKey: extractSentryIssueKey, - fetch: (key, workspaceId) => getSentryIssue(key, { workspaceId }), + fetch: (key, workspaceId, instanceId) => getSentryIssue(workspaceId, instanceId ?? "", key), resolveLinkedKey: (requestedKey, result) => isSentryIssue(result) && result.shortId ? result.shortId : requestedKey, + requiresInstance: true, }, }; -export function TaskExternalLinkDialog({ - open, - onOpenChange, - provider, - task, +// SentryLinkInstanceField resolves which Sentry instance a link targets: it +// auto-selects the sole healthy instance, prompts with a picker when several +// are healthy, and explains when none is usable. Owns the instances hook so the +// parent dialog stays provider-agnostic. +function SentryLinkInstanceField({ workspaceId, -}: TaskExternalLinkDialogProps) { + instanceId, + onChange, +}: { + workspaceId: string; + instanceId: string; + onChange: (id: string) => void; +}) { + const sentry = useSentryInstances(workspaceId); + + // Depend on a by-value signature of the healthy instance IDs rather than the + // `healthy` array identity: useSentryInstances rebuilds that array on every + // poll (new reference, usually identical contents), which would otherwise + // re-fire this effect needlessly. The signature still changes when the sole + // healthy instance is swapped (state stays "single") or a selected instance + // drops out of a "multi" set. + const healthySignature = sentry.healthy + .map((instance) => instance.id) + .sort() + .join("\n"); + + useEffect(() => { + const healthyIds = healthySignature ? healthySignature.split("\n") : []; + if (sentry.state === "single") { + onChange(healthyIds[0]); + } else if ( + sentry.state === "empty" || + sentry.state === "unhealthy" || + (instanceId !== "" && !healthyIds.includes(instanceId)) + ) { + onChange(""); + } + }, [sentry.state, healthySignature, instanceId, onChange]); + + if (sentry.state === "empty" || sentry.state === "unhealthy") { + return ( +

+ Connect a healthy Sentry instance in Settings → Integrations → Sentry to link issues. +

+ ); + } + if (sentry.state !== "multi") return null; + return ( +
+ + +
+ ); +} + +// useExternalLinkForm holds the dialog's transient state and the submit action +// (resolve key → fetch the external issue → rename the task). Extracted so the +// component body stays within the max-lines lint budget. +function useExternalLinkForm( + config: ProviderConfig, + task: TaskExternalLinkTarget, + workspaceId: string, + open: boolean, + onOpenChange: (open: boolean) => void, +) { const { toast } = useToast(); const store = useAppStoreApi(); - const config = PROVIDERS[provider]; const [input, setInput] = useState(""); + const [instanceId, setInstanceId] = useState(""); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); @@ -119,6 +194,7 @@ export function TaskExternalLinkDialog({ if (open) { setInput(""); setError(null); + setInstanceId(""); } }, [open]); @@ -128,11 +204,15 @@ export function TaskExternalLinkDialog({ setError(config.validationHint); return; } + if (config.requiresInstance && !instanceId) { + setError("Select a Sentry instance to link against."); + return; + } setSubmitting(true); setError(null); try { - const result = await config.fetch(key, workspaceId); + const result = await config.fetch(key, workspaceId, instanceId || undefined); const state = store.getState(); const latestTask = findTaskInSnapshots( task.id, @@ -152,6 +232,20 @@ export function TaskExternalLinkDialog({ } }; + return { input, setInput, instanceId, setInstanceId, submitting, error, setError, submit }; +} + +export function TaskExternalLinkDialog({ + open, + onOpenChange, + provider, + task, + workspaceId, +}: TaskExternalLinkDialogProps) { + const config = PROVIDERS[provider]; + const { input, setInput, instanceId, setInstanceId, submitting, error, setError, submit } = + useExternalLinkForm(config, task, workspaceId, open, onOpenChange); + return ( @@ -159,6 +253,13 @@ export function TaskExternalLinkDialog({ {config.title} {config.description} + {provider === "sentry" && ( + + )}
diff --git a/apps/web/e2e/fixtures/test-base.ts b/apps/web/e2e/fixtures/test-base.ts index e122f78fe5..a087536ed9 100644 --- a/apps/web/e2e/fixtures/test-base.ts +++ b/apps/web/e2e/fixtures/test-base.ts @@ -204,12 +204,9 @@ export const test = backendFixture.extend< await apiClient .rawRequest("DELETE", `/api/v1/linear/config?${scoped}`) .catch(() => undefined); - await apiClient - .rawRequest("DELETE", `/api/v1/sentry/config?${scoped}`) - .catch(() => undefined); + await apiClient.deleteAllSentryInstances(seedData.workspaceId).catch(() => undefined); await apiClient.rawRequest("DELETE", `/api/v1/jira/config`).catch(() => undefined); await apiClient.rawRequest("DELETE", `/api/v1/linear/config`).catch(() => undefined); - await apiClient.rawRequest("DELETE", `/api/v1/sentry/config`).catch(() => undefined); await Promise.all([ apiClient.mockJiraReset().catch(() => undefined), apiClient.mockLinearReset().catch(() => undefined), diff --git a/apps/web/e2e/helpers/api-client.ts b/apps/web/e2e/helpers/api-client.ts index c16e980a3b..c835837383 100644 --- a/apps/web/e2e/helpers/api-client.ts +++ b/apps/web/e2e/helpers/api-client.ts @@ -1484,14 +1484,15 @@ export class ApiClient { }); } - async setSentryConfig(payload: { + async createSentryInstance(payload: { + name: string; secret: string; url?: string; workspaceId?: string; - }): Promise { + }): Promise<{ id: string }> { const { workspaceId, ...config } = payload; - const path = await this.withActiveWorkspace("/api/v1/sentry/config", workspaceId); - return this.request("PUT", path, { + const path = await this.withActiveWorkspace("/api/v1/sentry/instances", workspaceId); + return this.request("POST", path, { authMethod: "auth_token", url: "https://sentry.io", ...config, @@ -1511,19 +1512,37 @@ export class ApiClient { ): Promise { const timeoutMs = typeof options === "number" ? options : (options.timeoutMs ?? 5_000); const workspaceId = typeof options === "number" ? undefined : options.workspaceId; - const path = await this.withActiveWorkspace(`/api/v1/${integration}/config`, workspaceId); const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { - const res = await this.rawRequest("GET", path); - if (res.ok && res.status === 200) { - const cfg = (await res.json()) as { hasSecret?: boolean; lastOk?: boolean }; - if (cfg.hasSecret && cfg.lastOk) return; - } - await new Promise((r) => setTimeout(r, 100)); + if (await this.integrationReportsHealthy(integration, workspaceId)) return; + await new Promise((resolve) => setTimeout(resolve, 100)); } throw new Error(`${integration} config never reported lastOk: true within ${timeoutMs}ms`); } + // integrationReportsHealthy probes an integration's current auth-health. + // Sentry is multi-instance (checks whether ANY instance is healthy); the + // others expose a single workspace config. + private async integrationReportsHealthy( + integration: "jira" | "linear" | "sentry", + workspaceId?: string, + ): Promise { + if (integration === "sentry") { + const path = await this.withActiveWorkspace("/api/v1/sentry/instances", workspaceId); + const res = await this.rawRequest("GET", path); + if (!res.ok || res.status !== 200) return false; + const body = (await res.json()) as { + instances?: Array<{ hasSecret?: boolean; lastOk?: boolean }>; + }; + return (body.instances ?? []).some((i) => Boolean(i.hasSecret) && Boolean(i.lastOk)); + } + const path = await this.withActiveWorkspace(`/api/v1/${integration}/config`, workspaceId); + const res = await this.rawRequest("GET", path); + if (!res.ok || res.status !== 200) return false; + const cfg = (await res.json()) as { hasSecret?: boolean; lastOk?: boolean }; + return Boolean(cfg.hasSecret) && Boolean(cfg.lastOk); + } + // --- Jira Mock Control --- async mockJiraReset(): Promise { @@ -1634,32 +1653,148 @@ export class ApiClient { await this.request("DELETE", "/api/v1/sentry/mock/reset"); } - async mockSentrySetAuthResult(result: { - ok: boolean; - userId?: string; - displayName?: string; - email?: string; - error?: string; - }): Promise { - await this.request("PUT", "/api/v1/sentry/mock/auth-result", result); + // mockSentrySetAuthResult seeds the auth-check result for one instance's mock + // dataset. Omit instanceId to target the pre-save ("") dataset used by + // test-connection before an instance exists. + async mockSentrySetAuthResult( + result: { ok: boolean; userId?: string; displayName?: string; email?: string; error?: string }, + instanceId?: string, + ): Promise { + const query = instanceId ? `?instanceId=${encodeURIComponent(instanceId)}` : ""; + await this.request("PUT", `/api/v1/sentry/mock/auth-result${query}`, result); } + // mockSentrySetAuthHealth synchronously stamps last_ok/last_error on one + // instance row, bypassing the async probe. async mockSentrySetAuthHealth(args: { + instanceId: string; ok: boolean; error?: string; - workspaceId?: string; }): Promise { - const { workspaceId, ...payload } = args; - const path = await this.withActiveWorkspace("/api/v1/sentry/mock/auth-health", workspaceId); - await this.request("PUT", path, payload); + const { instanceId, ...payload } = args; + await this.request( + "PUT", + `/api/v1/sentry/mock/auth-health?instanceId=${encodeURIComponent(instanceId)}`, + payload, + ); } - async mockSentrySetOrganizations(organizations: MockSentryOrganization[]): Promise { - await this.request("POST", "/api/v1/sentry/mock/organizations", { organizations }); + async mockSentrySetOrganizations( + instanceId: string, + organizations: MockSentryOrganization[], + ): Promise { + await this.request( + "POST", + `/api/v1/sentry/mock/organizations?instanceId=${encodeURIComponent(instanceId)}`, + { organizations }, + ); } - async mockSentrySetProjects(projects: MockSentryProject[]): Promise { - await this.request("POST", "/api/v1/sentry/mock/projects", { projects }); + async mockSentrySetProjects(instanceId: string, projects: MockSentryProject[]): Promise { + await this.request( + "POST", + `/api/v1/sentry/mock/projects?instanceId=${encodeURIComponent(instanceId)}`, + { projects }, + ); + } + + // --- Sentry instance + watch CRUD --- + + async createSentryInstance(opts: { + workspaceId: string; + name: string; + url?: string; + secret: string; + authMethod?: string; + }): Promise { + return this.request( + "POST", + `/api/v1/sentry/instances?workspace_id=${encodeURIComponent(opts.workspaceId)}`, + { + workspaceId: opts.workspaceId, + name: opts.name, + authMethod: opts.authMethod ?? "auth_token", + url: opts.url ?? "https://sentry.io", + secret: opts.secret, + }, + ); + } + + async listSentryInstances(workspaceId: string): Promise { + const { instances } = await this.request<{ instances: MockSentryInstance[] }>( + "GET", + `/api/v1/sentry/instances?workspace_id=${encodeURIComponent(workspaceId)}`, + ); + return instances ?? []; + } + + // deleteSentryInstanceRaw returns the raw Response so callers can assert the + // 409 SENTRY_INSTANCE_IN_USE (with watchCount) when a watch still binds. + async deleteSentryInstanceRaw(workspaceId: string, instanceId: string): Promise { + return this.rawRequest( + "DELETE", + `/api/v1/sentry/instances/${encodeURIComponent(instanceId)}?workspace_id=${encodeURIComponent(workspaceId)}`, + ); + } + + // deleteAllSentryInstances removes every watch (FK-protected) then every + // instance in a workspace — the per-test cleanup replacement for the removed + // /config DELETE. + async deleteAllSentryInstances(workspaceId?: string): Promise { + const watchesPath = await this.withActiveWorkspace("/api/v1/sentry/watches/issue", workspaceId); + const watchesRes = await this.rawRequest("GET", watchesPath); + if (watchesRes.ok) { + const body = (await watchesRes.json()) as { watches?: Array<{ id: string }> }; + for (const w of body.watches ?? []) { + const p = await this.withActiveWorkspace( + `/api/v1/sentry/watches/issue/${encodeURIComponent(w.id)}`, + workspaceId, + ); + await this.rawRequest("DELETE", p).catch(() => undefined); + } + } + const listPath = await this.withActiveWorkspace("/api/v1/sentry/instances", workspaceId); + const res = await this.rawRequest("GET", listPath); + if (!res.ok) return; + const body = (await res.json()) as { instances?: Array<{ id: string }> }; + for (const instance of body.instances ?? []) { + const p = await this.withActiveWorkspace( + `/api/v1/sentry/instances/${encodeURIComponent(instance.id)}`, + workspaceId, + ); + await this.rawRequest("DELETE", p).catch(() => undefined); + } + } + + async createSentryIssueWatch(opts: { + workspaceId: string; + sentryInstanceId: string; + workflowId: string; + workflowStepId: string; + agentProfileId: string; + executorProfileId?: string; + orgSlug: string; + projectSlug?: string; + prompt?: string; + pollIntervalSeconds?: number; + }): Promise<{ id: string; sentryInstanceId: string; enabled: boolean }> { + return this.request( + "POST", + `/api/v1/sentry/watches/issue?workspace_id=${encodeURIComponent(opts.workspaceId)}`, + { + workspaceId: opts.workspaceId, + sentryInstanceId: opts.sentryInstanceId, + workflowId: opts.workflowId, + workflowStepId: opts.workflowStepId, + repositoryId: "", + baseBranch: "", + filter: { orgSlug: opts.orgSlug, projectSlug: opts.projectSlug }, + agentProfileId: opts.agentProfileId, + executorProfileId: opts.executorProfileId ?? "", + prompt: opts.prompt ?? "Investigate {{issue.title}}", + pollIntervalSeconds: opts.pollIntervalSeconds ?? 300, + }, + ); } // --- Linear issue watch CRUD --- @@ -2052,3 +2187,13 @@ export type MockLinearIssue = { export type MockSentryOrganization = { id: string; slug: string; name: string }; export type MockSentryProject = { id: string; slug: string; name: string; orgSlug: string }; + +// MockSentryInstance is the subset of a created instance the e2e helpers read. +export type MockSentryInstance = { + id: string; + workspaceId: string; + name: string; + url: string; + hasSecret: boolean; + lastOk: boolean; +}; diff --git a/apps/web/e2e/pages/sentry-settings-page.ts b/apps/web/e2e/pages/sentry-settings-page.ts index 3f66bbaf65..bfaf5b5add 100644 --- a/apps/web/e2e/pages/sentry-settings-page.ts +++ b/apps/web/e2e/pages/sentry-settings-page.ts @@ -1,24 +1,46 @@ import { type Locator, type Page } from "@playwright/test"; +// SentrySettingsPage drives the multi-instance Sentry settings UI: an instance +// list of cards plus mutually-exclusive add/edit forms. export class SentrySettingsPage { - readonly urlInput: Locator; - readonly secretInput: Locator; - readonly testButton: Locator; - readonly saveButton: Locator; - readonly deleteButton: Locator; - readonly statusBanner: Locator; + readonly addInstanceButton: Locator; + readonly cards: Locator; + readonly noInstances: Locator; + readonly addNameInput: Locator; + readonly addUrlInput: Locator; + readonly addSecretInput: Locator; + readonly addTestButton: Locator; + readonly addSaveButton: Locator; constructor(private page: Page) { - this.urlInput = page.getByTestId("sentry-url-input"); - this.secretInput = page.getByTestId("sentry-secret-input"); - this.testButton = page.getByTestId("sentry-test-button"); - this.saveButton = page.getByTestId("sentry-save-button"); - this.deleteButton = page.getByTestId("sentry-delete-button"); - this.statusBanner = page.getByTestId("integration-auth-status-banner"); + this.addInstanceButton = page.getByTestId("sentry-add-instance-button"); + this.cards = page.getByTestId("sentry-instance-card"); + this.noInstances = page.getByTestId("sentry-no-instances"); + this.addNameInput = page.getByTestId("sentry-add-name-input"); + this.addUrlInput = page.getByTestId("sentry-add-url-input"); + this.addSecretInput = page.getByTestId("sentry-add-secret-input"); + this.addTestButton = page.getByTestId("sentry-add-test-button"); + this.addSaveButton = page.getByTestId("sentry-add-save-button"); } async goto() { await this.page.goto("/settings/integrations/sentry"); - await this.secretInput.waitFor({ state: "visible" }); + // The "Add instance" button renders whenever no form is open — present in + // both the empty and populated states, so it is a reliable ready signal. + await this.addInstanceButton.waitFor({ state: "visible" }); + } + + async addInstance(name: string, secret: string, url?: string) { + await this.addInstanceButton.click(); + await this.addNameInput.fill(name); + if (url) await this.addUrlInput.fill(url); + await this.addSecretInput.fill(secret); + await this.addSaveButton.click(); + } + + // cardByName scopes to the card whose visible name matches, so per-instance + // assertions (banner, delete) target the right card. + cardByName(name: string): Locator { + return this.cards.filter({ hasText: name }); } } diff --git a/apps/web/e2e/tests/integrations/sentry-settings.spec.ts b/apps/web/e2e/tests/integrations/sentry-settings.spec.ts index 211abd016a..1de9b695d5 100644 --- a/apps/web/e2e/tests/integrations/sentry-settings.spec.ts +++ b/apps/web/e2e/tests/integrations/sentry-settings.spec.ts @@ -3,68 +3,87 @@ import { SentrySettingsPage } from "../../pages/sentry-settings-page"; const TOKEN = "sntrys_xxx"; -test.describe("Sentry settings", () => { - // The settings page configures only the auth token; org/project are chosen - // per-watcher and per-browse, not stored install-wide. This covers the - // connect → save → validated flow and persistence of the saved token. - test("connects, saves, and reports a healthy token", async ({ testPage, apiClient }) => { +test.describe("Sentry settings — instances", () => { + // The settings page manages a LIST of named instances per workspace. This + // covers add → the card appears → the backend probe flips it healthy. + test("adds a named instance and reports it healthy", async ({ testPage, apiClient }) => { await apiClient.mockSentryReset(); - await apiClient.mockSentrySetAuthResult({ - ok: true, - userId: "u-1", - displayName: "Sentry Tester", - email: "tester@example.com", - }); const settings = new SentrySettingsPage(testPage); await settings.goto(); - // Connection test surfaces inline success ("Connected as "). - await settings.secretInput.fill(TOKEN); - await settings.testButton.click(); - await expect(testPage.getByText(/Connected as Sentry Tester/)).toBeVisible(); + // The add form pre-fills the SaaS URL default. + await settings.addInstanceButton.click(); + await expect(settings.addUrlInput).toHaveValue("https://sentry.io"); - // Save persists the secret and triggers the auth-health probe that flips - // lastOk -> true. - await settings.saveButton.click(); - await expect(settings.saveButton).toHaveText(/Update/i); + await settings.addNameInput.fill("Production"); + await settings.addSecretInput.fill(TOKEN); + await settings.addSaveButton.click(); + + // The instance now renders as a card. Its async probe (unseeded mock = OK) + // flips lastOk true; reload to pick up the health banner deterministically. + await expect(settings.cardByName("Production")).toBeVisible(); await apiClient.waitForIntegrationAuthHealthy("sentry"); - - // Reload: the saved token survives (placeholder shows the masked state and - // the action becomes "Update"/"Remove configuration"). await settings.goto(); - await expect(settings.saveButton).toHaveText(/Update/i); - await expect(settings.deleteButton).toBeVisible(); + await expect( + settings.cardByName("Production").getByTestId("integration-auth-status-banner"), + ).toHaveAttribute("data-state", "ok"); }); - // Self-hosted support: the instance URL defaults to sentry.io, accepts a - // custom host, and persists across reload via the saved config. - test("defaults the instance URL and persists a self-hosted URL", async ({ + // Two instances coexist in one workspace; a watcher bound to one FK-protects + // it, so deleting that instance is blocked (409 SENTRY_INSTANCE_IN_USE with a + // watch count) while the unbound instance deletes cleanly. + test("blocks deleting an instance a watcher still uses", async ({ testPage, apiClient, + seedData, }) => { await apiClient.mockSentryReset(); - await apiClient.mockSentrySetAuthResult({ - ok: true, - userId: "u-2", - displayName: "Self Hosted", + const primary = await apiClient.createSentryInstance({ + workspaceId: seedData.workspaceId, + name: "Primary", + secret: TOKEN, + }); + const secondary = await apiClient.createSentryInstance({ + workspaceId: seedData.workspaceId, + name: "Secondary", + url: "https://sentry.acme.example.com", + secret: TOKEN, + }); + await apiClient.mockSentrySetAuthHealth({ instanceId: primary.id, ok: true }); + await apiClient.mockSentrySetAuthHealth({ instanceId: secondary.id, ok: true }); + + // Bind a watch to the primary instance only. + await apiClient.createSentryIssueWatch({ + workspaceId: seedData.workspaceId, + sentryInstanceId: primary.id, + workflowId: seedData.workflowId, + workflowStepId: seedData.startStepId, + agentProfileId: seedData.agentProfileId, + orgSlug: "acme", + projectSlug: "web", }); + // API contract: delete-in-use rejects 409 and reports the blocking count. + const res = await apiClient.deleteSentryInstanceRaw(seedData.workspaceId, primary.id); + expect(res.status).toBe(409); + const body = (await res.json()) as { code?: string; watchCount?: number }; + expect(body.code).toBe("SENTRY_INSTANCE_IN_USE"); + expect(body.watchCount).toBe(1); + + // UI: the delete is surfaced as an error and the primary card survives; the + // watcher-free secondary deletes cleanly. const settings = new SentrySettingsPage(testPage); await settings.goto(); + await expect(settings.cards).toHaveCount(2); + testPage.on("dialog", (d) => d.accept()); - // The URL field is pre-filled with the SaaS default. - await expect(settings.urlInput).toHaveValue("https://sentry.io"); + await settings.cardByName("Primary").getByTestId("sentry-instance-delete-button").click(); + await expect(testPage.getByText(/still bound to it/i)).toBeVisible(); + await expect(settings.cardByName("Primary")).toBeVisible(); - // Point it at a self-hosted instance and save with a token. - await settings.urlInput.fill("https://sentry.acme.example.com"); - await settings.secretInput.fill(TOKEN); - await settings.saveButton.click(); - await expect(settings.saveButton).toHaveText(/Update/i); - await apiClient.waitForIntegrationAuthHealthy("sentry"); - - // Reload: the custom instance URL round-trips through the saved config. - await settings.goto(); - await expect(settings.urlInput).toHaveValue("https://sentry.acme.example.com"); + await settings.cardByName("Secondary").getByTestId("sentry-instance-delete-button").click(); + await expect(settings.cardByName("Secondary")).toHaveCount(0); + await expect(settings.cardByName("Primary")).toBeVisible(); }); }); diff --git a/apps/web/e2e/tests/task/mobile-external-link-menu.spec.ts b/apps/web/e2e/tests/task/mobile-external-link-menu.spec.ts index 7f35c531d9..8de47cc0ef 100644 --- a/apps/web/e2e/tests/task/mobile-external-link-menu.spec.ts +++ b/apps/web/e2e/tests/task/mobile-external-link-menu.spec.ts @@ -13,11 +13,16 @@ test.describe("Mobile sidebar — external link menu", () => { secret: "api-token-value", }); await apiClient.setLinearConfig({ secret: "lin_api_xxx" }); - await apiClient.setSentryConfig({ secret: "sntrys_xxx" }); + const sentry = await apiClient.createSentryInstance({ + workspaceId: seedData.workspaceId, + name: "Sentry", + secret: "sntrys_xxx", + }); + await apiClient.mockSentrySetAuthHealth({ instanceId: sentry.id, ok: true }); await Promise.all([ apiClient.waitForIntegrationAuthHealthy("jira"), apiClient.waitForIntegrationAuthHealthy("linear"), - apiClient.waitForIntegrationAuthHealthy("sentry"), + apiClient.waitForIntegrationAuthHealthy("sentry", { workspaceId: seedData.workspaceId }), ]); const task = await apiClient.seedTask(seedData.workspaceId, "Mobile external link task", { diff --git a/apps/web/hooks/domains/sentry/use-sentry-availability.ts b/apps/web/hooks/domains/sentry/use-sentry-availability.ts index 38ffc6ee70..0fbff8f147 100644 --- a/apps/web/hooks/domains/sentry/use-sentry-availability.ts +++ b/apps/web/hooks/domains/sentry/use-sentry-availability.ts @@ -1,28 +1,92 @@ "use client"; -import { useCallback } from "react"; -import { fetchSentryConfig } from "@/lib/api/domains/sentry-api"; -import { - useIntegrationAuthed, - useIntegrationAvailable, -} from "../integrations/use-integration-availability"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { listSentryInstances } from "@/lib/api/domains/sentry-api"; +import type { SentryConfig } from "@/lib/types/sentry"; +import { INTEGRATION_STATUS_REFRESH_MS } from "../integrations/use-integration-availability"; import { useSentryEnabled } from "./use-sentry-enabled"; -export function useSentryAuthed(workspaceId?: string | null): boolean { - const fetchConfig = useCallback( - async () => (await fetchSentryConfig(workspaceId ? { workspaceId } : undefined)) ?? null, - [workspaceId], - ); - return useIntegrationAuthed(fetchConfig); +// isHealthySentryInstance is the single definition of a usable instance: +// credentials are stored AND the most recent backend probe succeeded. +export function isHealthySentryInstance(instance: SentryConfig): boolean { + return instance.hasSecret && instance.lastOk; } -export function useSentryAvailable(workspaceId?: string | null): boolean { - const fetchConfig = useCallback( - async () => (await fetchSentryConfig(workspaceId ? { workspaceId } : undefined)) ?? null, - [workspaceId], - ); - return useIntegrationAvailable({ - useEnabled: useSentryEnabled, - fetchConfig, - }); +// SentryAvailabilityState distinguishes the shapes the browse surfaces care +// about: still loading, no instances at all, instances but none healthy, one +// healthy (auto-select), or several healthy (must prompt). +export type SentryAvailabilityState = "loading" | "empty" | "unhealthy" | "single" | "multi"; + +export type SentryAvailability = { + loading: boolean; + // instances is every instance in the workspace; healthy is the subset that is + // authenticated and passing its health probe. + instances: SentryConfig[]; + healthy: SentryConfig[]; + // available gates whether Sentry entry points render: toggle on AND at least + // one healthy instance. + available: boolean; + state: SentryAvailabilityState; +}; + +// useSentryInstances polls a workspace's Sentry instances (respecting the +// per-workspace enabled toggle) and derives the availability state the browse +// surfaces and settings banner consume. Fetches are request-versioned so a slow +// response for a previous workspace can't clobber a newer one. +export function useSentryInstances(workspaceId?: string | null): SentryAvailability { + const { enabled, loaded } = useSentryEnabled(); + const active = loaded && enabled && !!workspaceId; + const [instances, setInstances] = useState([]); + const [loading, setLoading] = useState(true); + const requestId = useRef(0); + + useEffect(() => { + if (!active || !workspaceId) { + // Drop any state carried over from a previous workspace / enabled toggle + // so a disabled integration shows no stale instances. + setInstances([]); + setLoading(false); + return; + } + setLoading(true); + setInstances([]); + let cancelled = false; + const refresh = async () => { + const current = ++requestId.current; + try { + const list = await listSentryInstances(workspaceId); + if (cancelled || current !== requestId.current) return; + setInstances(list); + } catch { + if (cancelled || current !== requestId.current) return; + setInstances([]); + } finally { + if (!cancelled && current === requestId.current) setLoading(false); + } + }; + void refresh(); + const id = setInterval(() => void refresh(), INTEGRATION_STATUS_REFRESH_MS); + return () => { + cancelled = true; + clearInterval(id); + }; + }, [active, workspaceId]); + + return useMemo(() => { + const healthy = instances.filter(isHealthySentryInstance); + const available = active && healthy.length >= 1; + let state: SentryAvailabilityState; + if (loading) state = "loading"; + else if (instances.length === 0) state = "empty"; + else if (healthy.length === 0) state = "unhealthy"; + else if (healthy.length === 1) state = "single"; + else state = "multi"; + return { loading, instances, healthy, available, state }; + }, [active, instances, loading]); +} + +// useSentryAvailable is the boolean gate that shows/hides Sentry entry points: +// the workspace toggle is on AND at least one instance is healthy. +export function useSentryAvailable(workspaceId?: string | null): boolean { + return useSentryInstances(workspaceId).available; } diff --git a/apps/web/lib/api/domains/sentry-api.test.ts b/apps/web/lib/api/domains/sentry-api.test.ts new file mode 100644 index 0000000000..21c9c6825c --- /dev/null +++ b/apps/web/lib/api/domains/sentry-api.test.ts @@ -0,0 +1,39 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("@/lib/config", () => ({ + getBackendConfig: () => ({ apiBaseUrl: "http://api.test" }), +})); + +import { copySentryInstances } from "./sentry-api"; + +type FetchInput = Parameters[0]; +type FetchInit = Parameters[1]; + +const fetchSpy = vi.fn<[FetchInput, FetchInit?], Promise>(); + +beforeEach(() => { + fetchSpy.mockReset(); + vi.stubGlobal("fetch", fetchSpy); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("copySentryInstances", () => { + it("scopes the copy to its source workspace and sends only the target in JSON", async () => { + fetchSpy.mockResolvedValueOnce( + new Response(JSON.stringify({ instances: [] }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }), + ); + + await copySentryInstances("ws-target", { workspaceId: "ws-source" }); + + const [url, init] = fetchSpy.mock.calls.at(-1) ?? []; + expect(String(url)).toBe("http://api.test/api/v1/sentry/config/copy?workspace_id=ws-source"); + expect(init?.method).toBe("POST"); + expect(JSON.parse(String(init?.body))).toEqual({ targetWorkspaceId: "ws-target" }); + }); +}); diff --git a/apps/web/lib/api/domains/sentry-api.ts b/apps/web/lib/api/domains/sentry-api.ts index 09d8b3a85a..c343d22e1e 100644 --- a/apps/web/lib/api/domains/sentry-api.ts +++ b/apps/web/lib/api/domains/sentry-api.ts @@ -1,5 +1,7 @@ -import { fetchJson, type ApiRequestOptions } from "../client"; +import { ApiError, fetchJson, type ApiRequestOptions } from "../client"; import type { + CopySentryConfigRequest, + CreateSentryConfigRequest, CreateSentryIssueWatchRequest, SentryConfig, SentryIssue, @@ -8,93 +10,203 @@ import type { SentryProject, SentrySearchFilter, SentrySearchResult, - SetSentryConfigRequest, TestSentryConnectionResult, + UpdateSentryConfigRequest, UpdateSentryIssueWatchRequest, } from "@/lib/types/sentry"; -type WorkspaceApiOptions = ApiRequestOptions & { workspaceId?: string }; +const BASE = "/api/v1/sentry"; -function withWorkspace(path: string, options?: WorkspaceApiOptions): string { - if (!options?.workspaceId) return path; - const separator = path.includes("?") ? "&" : "?"; - return `${path}${separator}workspace_id=${encodeURIComponent(options.workspaceId)}`; +// SENTRY_ERROR_CODES are the wire-level `code` discriminators the backend +// stamps on structured error bodies so the UI can react without matching on +// human-readable error text. +export const SENTRY_ERROR_CODES = { + instanceRequired: "SENTRY_INSTANCE_REQUIRED", + instanceNotFound: "SENTRY_INSTANCE_NOT_FOUND", + instanceInUse: "SENTRY_INSTANCE_IN_USE", + nameTaken: "SENTRY_INSTANCE_NAME_TAKEN", + notConfigured: "SENTRY_NOT_CONFIGURED", +} as const; + +// sentryErrorCode extracts the backend `code` from a failed request, or null +// when the rejection is not an ApiError or carries no code. +export function sentryErrorCode(err: unknown): string | null { + if (!(err instanceof ApiError)) return null; + const body = err.body; + if (body && typeof body === "object" && "code" in body) { + const code = body.code; + return typeof code === "string" ? code : null; + } + return null; } -function requestOptions(options?: WorkspaceApiOptions): ApiRequestOptions | undefined { - if (!options) return undefined; - const { workspaceId: _workspaceId, ...rest } = options; - return rest; +// sentryInUseWatchCount returns the count of watches blocking a delete when the +// error is a 409 SENTRY_INSTANCE_IN_USE, else null. +export function sentryInUseWatchCount(err: unknown): number | null { + if (!(err instanceof ApiError) || err.status !== 409) return null; + if (sentryErrorCode(err) !== SENTRY_ERROR_CODES.instanceInUse) return null; + const body = err.body; + if (body && typeof body === "object" && "watchCount" in body) { + const count = body.watchCount; + return typeof count === "number" ? count : null; + } + return null; } -// fetchSentryConfig returns undefined when the backend responds 204 (no config yet). -export async function fetchSentryConfig( - options?: WorkspaceApiOptions, -): Promise { - return fetchJson( - withWorkspace(`/api/v1/sentry/config`, options), - requestOptions(options), +// withParams appends non-empty query params to a path, respecting any existing +// query string. +function withParams(path: string, params: Record): string { + const search = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value) search.set(key, value); + } + const query = search.toString(); + if (!query) return path; + return `${path}${path.includes("?") ? "&" : "?"}${query}`; +} + +// --- Instances (per-workspace named Sentry configs) --- + +// listSentryInstances returns every Sentry instance configured in a workspace. +export async function listSentryInstances(workspaceId: string, options?: ApiRequestOptions) { + const res = await fetchJson<{ instances: SentryConfig[] }>( + withParams(`${BASE}/instances`, { workspace_id: workspaceId }), + options, + ); + return res.instances ?? []; +} + +// getSentryInstance fetches one instance by id, scoped to its workspace. +export async function getSentryInstance( + workspaceId: string, + id: string, + options?: ApiRequestOptions, +) { + return fetchJson( + withParams(`${BASE}/instances/${encodeURIComponent(id)}`, { workspace_id: workspaceId }), + options, ); } -export async function saveSentryConfig( - payload: SetSentryConfigRequest, - options?: WorkspaceApiOptions, +// createSentryInstance adds a new named instance to a workspace. +export async function createSentryInstance( + workspaceId: string, + payload: CreateSentryConfigRequest, + options?: ApiRequestOptions, ) { - return fetchJson(withWorkspace(`/api/v1/sentry/config`, options), { - ...requestOptions(options), - init: { ...(options?.init ?? {}), method: "PUT", body: JSON.stringify(payload) }, + return fetchJson(withParams(`${BASE}/instances`, { workspace_id: workspaceId }), { + ...options, + init: { ...(options?.init ?? {}), method: "POST", body: JSON.stringify(payload) }, }); } -export async function deleteSentryConfig(options?: WorkspaceApiOptions) { - return fetchJson<{ deleted: boolean }>(withWorkspace(`/api/v1/sentry/config`, options), { - ...requestOptions(options), - init: { ...(options?.init ?? {}), method: "DELETE" }, - }); -} - -export async function testSentryConnection( - secret?: string, - url?: string, - options?: WorkspaceApiOptions, +// updateSentryInstance replaces an instance's name/url/auth (and, when a +// non-empty secret is supplied, its stored token). +export async function updateSentryInstance( + workspaceId: string, + id: string, + payload: UpdateSentryConfigRequest, + options?: ApiRequestOptions, ) { - const payload: { secret?: string; url?: string } = {}; - if (secret) payload.secret = secret; - if (url) payload.url = url; - return fetchJson( - withWorkspace(`/api/v1/sentry/config/test`, options), + return fetchJson( + withParams(`${BASE}/instances/${encodeURIComponent(id)}`, { workspace_id: workspaceId }), { - ...requestOptions(options), - init: { - ...(options?.init ?? {}), - method: "POST", - body: JSON.stringify(payload), - }, + ...options, + init: { ...(options?.init ?? {}), method: "PUT", body: JSON.stringify(payload) }, }, ); } -// copySentryConfig copies the Sentry config + credential from the workspace in -// options (source) to targetWorkspaceId. -export async function copySentryConfig(targetWorkspaceId: string, options?: WorkspaceApiOptions) { - return fetchJson(withWorkspace(`/api/v1/sentry/config/copy`, options), { - ...requestOptions(options), - init: { ...(options?.init ?? {}), method: "POST", body: JSON.stringify({ targetWorkspaceId }) }, - }); -} - -export async function listSentryOrganizations(options?: WorkspaceApiOptions) { - return fetchJson<{ organizations: SentryOrganization[] }>( - withWorkspace(`/api/v1/sentry/organizations`, options), - requestOptions(options), +// deleteSentryInstance removes an instance. Rejects with a 409 +// SENTRY_INSTANCE_IN_USE (carrying watchCount) when watches still bind to it. +export async function deleteSentryInstance( + workspaceId: string, + id: string, + options?: ApiRequestOptions, +) { + return fetchJson<{ deleted: boolean }>( + withParams(`${BASE}/instances/${encodeURIComponent(id)}`, { workspace_id: workspaceId }), + { + ...options, + init: { ...(options?.init ?? {}), method: "DELETE" }, + }, ); } -export async function listSentryProjects(options?: WorkspaceApiOptions) { +// testSentryInstance pings Sentry with a saved instance's stored credentials. +export async function testSentryInstance( + workspaceId: string, + id: string, + options?: ApiRequestOptions, +) { + return fetchJson( + withParams(`${BASE}/instances/${encodeURIComponent(id)}/test`, { workspace_id: workspaceId }), + { ...options, init: { ...(options?.init ?? {}), method: "POST" } }, + ); +} + +// testSentryConnection pings Sentry with ad-hoc credentials (before an instance +// is saved) to validate a token/URL pair. +export async function testSentryConnection( + workspaceId: string, + creds: { secret?: string; url?: string; authMethod?: string }, + options?: ApiRequestOptions, +) { + const payload: { secret?: string; url?: string; authMethod?: string } = {}; + if (creds.secret) payload.secret = creds.secret; + if (creds.url) payload.url = creds.url; + if (creds.authMethod) payload.authMethod = creds.authMethod; + return fetchJson( + withParams(`${BASE}/test-connection`, { workspace_id: workspaceId }), + { + ...options, + init: { ...(options?.init ?? {}), method: "POST", body: JSON.stringify(payload) }, + }, + ); +} + +// copySentryInstances copies every instance (and its credential) from the +// source workspace (options.workspaceId) into the target workspace in the +// JSON body, returning the newly-created instances. The source workspace is +// authoritative for this route, so options.workspaceId is required — +// mirrors copyGitHubWorkspaceSettings's convention for consistency. +export async function copySentryInstances( + targetWorkspaceId: string, + options: { workspaceId: string } & ApiRequestOptions, +) { + const { workspaceId: sourceWorkspaceId, ...requestOptions } = options; + const payload: Pick = { targetWorkspaceId }; + const res = await fetchJson<{ instances: SentryConfig[] }>( + withParams(`${BASE}/config/copy`, { workspace_id: sourceWorkspaceId }), + { + ...requestOptions, + init: { ...(requestOptions.init ?? {}), method: "POST", body: JSON.stringify(payload) }, + }, + ); + return res.instances ?? []; +} + +// --- Browse (org/project/issue lookups scoped to one instance) --- + +export async function listSentryOrganizations( + workspaceId: string, + instanceId: string, + options?: ApiRequestOptions, +) { + return fetchJson<{ organizations: SentryOrganization[] }>( + withParams(`${BASE}/organizations`, { workspace_id: workspaceId, instanceId }), + options, + ); +} + +export async function listSentryProjects( + workspaceId: string, + instanceId: string, + options?: ApiRequestOptions, +) { return fetchJson<{ projects: SentryProject[] }>( - withWorkspace(`/api/v1/sentry/projects`, options), - requestOptions(options), + withParams(`${BASE}/projects`, { workspace_id: workspaceId, instanceId }), + options, ); } @@ -109,23 +221,32 @@ function appendFilter(search: URLSearchParams, filter: SentrySearchFilter): void } export async function searchSentryIssues( + workspaceId: string, + instanceId: string, filter: SentrySearchFilter, cursor?: string, - options?: WorkspaceApiOptions, + options?: ApiRequestOptions, ) { const search = new URLSearchParams(); + search.set("workspace_id", workspaceId); + search.set("instanceId", instanceId); appendFilter(search, filter); if (cursor) search.set("cursor", cursor); - return fetchJson( - withWorkspace(`/api/v1/sentry/issues?${search.toString()}`, options), - requestOptions(options), - ); + return fetchJson(`${BASE}/issues?${search.toString()}`, options); } -export async function getSentryIssue(idOrShortId: string, options?: WorkspaceApiOptions) { +export async function getSentryIssue( + workspaceId: string, + instanceId: string, + idOrShortId: string, + options?: ApiRequestOptions, +) { return fetchJson( - withWorkspace(`/api/v1/sentry/issues/${encodeURIComponent(idOrShortId)}`, options), - requestOptions(options), + withParams(`${BASE}/issues/${encodeURIComponent(idOrShortId)}`, { + workspace_id: workspaceId, + instanceId, + }), + options, ); } @@ -156,10 +277,13 @@ export async function createSentryIssueWatch( payload: CreateSentryIssueWatchRequest, options?: ApiRequestOptions, ) { - return fetchJson(`/api/v1/sentry/watches/issue`, { - ...options, - init: { ...(options?.init ?? {}), method: "POST", body: JSON.stringify(payload) }, - }); + return fetchJson( + withParams(`${BASE}/watches/issue`, { workspace_id: payload.workspaceId }), + { + ...options, + init: { ...(options?.init ?? {}), method: "POST", body: JSON.stringify(payload) }, + }, + ); } export async function updateSentryIssueWatch( diff --git a/apps/web/lib/types/sentry.ts b/apps/web/lib/types/sentry.ts index 7e4a867116..53d281b01d 100644 --- a/apps/web/lib/types/sentry.ts +++ b/apps/web/lib/types/sentry.ts @@ -8,7 +8,12 @@ export const SENTRY_AUTH_METHOD: SentryAuthMethod = "auth_token"; export const SENTRY_DEFAULT_URL = "https://sentry.io"; export interface SentryConfig { - workspaceId?: string; + // ID is the instance UUID: stable for the life of the instance, used as the + // secret key, client-cache key, and issue-watch foreign key. + id: string; + workspaceId: string; + // Name is the user-facing label, required and unique within a workspace. + name: string; authMethod: SentryAuthMethod; url: string; hasSecret: boolean; @@ -19,12 +24,33 @@ export interface SentryConfig { updatedAt: string; } -export interface SetSentryConfigRequest { +// CreateSentryConfigRequest creates a new named Sentry instance in a workspace. +export interface CreateSentryConfigRequest { + workspaceId: string; + name: string; authMethod: SentryAuthMethod; url: string; secret: string; } +// UpdateSentryConfigRequest updates an existing instance by ID. A blank secret +// keeps the stored value; a non-empty secret replaces it. Name/URL/AuthMethod +// always replace the stored values. +export interface UpdateSentryConfigRequest { + name: string; + authMethod: SentryAuthMethod; + url: string; + secret: string; +} + +// CopySentryConfigRequest copies every instance from the source workspace into +// the target workspace: fresh IDs, secrets copied under new keys, names deduped, +// no watches carried over. +export interface CopySentryConfigRequest { + sourceWorkspaceId: string; + targetWorkspaceId: string; +} + export interface TestSentryConnectionResult { ok: boolean; userId?: string; @@ -86,6 +112,12 @@ export interface SentrySearchResult { export interface SentryIssueWatch { id: string; workspaceId: string; + /** + * The Sentry instance this watch polls. Immutable after create — changing it + * means creating a new watch. Empty string = legacy unbound watch (resolved + * to the workspace's sole instance at poll time). + */ + sentryInstanceId: string; workflowId: string; workflowStepId: string; /** @@ -110,6 +142,11 @@ export interface SentryIssueWatch { export interface CreateSentryIssueWatchRequest { workspaceId: string; + /** + * The Sentry instance to poll. Required and must belong to `workspaceId`. + * Immutable after creation. + */ + sentryInstanceId: string; workflowId: string; workflowStepId: string; /** Optional repository binding; empty/omitted = unbound (repo-less task). */ diff --git a/docs/decisions/0030-workspace-scoped-integration-settings.md b/docs/decisions/0030-workspace-scoped-integration-settings.md index 6828b2b9a0..27b7e591ca 100644 --- a/docs/decisions/0030-workspace-scoped-integration-settings.md +++ b/docs/decisions/0030-workspace-scoped-integration-settings.md @@ -72,6 +72,39 @@ task-creating pollers. active workspace route state. Install-wide `/config` semantics are deprecated for integrations that support workspace-scoped settings. +## Sentry: multiple named instances per workspace + +Sentry extends the workspace-scoped baseline: a workspace may hold **several +named Sentry instances** (e.g. a sentry.io SaaS org plus a self-hosted host), +not a single config. This deliberately diverges from the Jira/Linear/GitLab +one-config-per-workspace shape — teams commonly watch issues across more than +one Sentry deployment from the same workspace. + +- `sentry_configs` is keyed by an instance `id` (UUID) with a `workspace_id` + column and `UNIQUE(workspace_id, name)`; the secret lives under + `sentry:instance::token`, disjoint from the legacy + `sentry::token` / `sentry:singleton:token` namespaces so a + workspace UUID can never collide with an instance UUID. +- `sentry_issue_watches.sentry_instance_id` is a nullable FK to + `sentry_configs(id)` with `ON DELETE RESTRICT`. NULL marks a migrated legacy + watch; the poller resolves it to the workspace's sole instance at poll time, + or disables it with a recorded error when zero/many instances exist. The + bound instance is **immutable** — changing it means creating a new watch. +- The HTTP surface is instance CRUD under `/api/v1/sentry/instances` with an + authoritative `?workspace_id=`; the instance must belong to that workspace or + the request 404s. Browse endpoints require `workspace_id` + `instanceId`. + Install-wide `/config` GET/PUT/DELETE is removed; `/config/copy` copies a + workspace's instances (new ids, copied secrets, no watches, deduped names). +- Deleting an instance that still has watches returns 409 + `SENTRY_INSTANCE_IN_USE` (with `watchCount`); the FK RESTRICT is the atomic + backstop behind the friendly count. + +Startup migration chains singleton → workspace-config → per-instance: main's +existing legacy-singleton→workspace step runs first, then each workspace config +row becomes one instance (name derived from the URL host, deduped per +workspace), watches backfill to that instance, and the secret is re-keyed +idempotently (crash-safe: derivable from the post-migration instance rows). + ## Alternatives Considered ### Keep GitHub settings global