bb36cb9e01
* refactor: move integrations to top-level settings with install-wide configs Jira and Linear configurations are now install-wide singletons rather than per-workspace duplicates, and the GitHub/Jira/Linear settings pages live under /settings/integrations instead of being nested inside each workspace. Issue and PR watchers stay per-workspace via a workspace switcher inside each integration page. Backend ships one-shot migrations that promote the most-recently-updated row and copy its secret onto the new global key. * fix: address review feedback on integrations refactor Fix migration crash on installs whose jira_configs predate the auth-health columns by selecting only guaranteed-present legacy columns and falling back to defaults for the rest. Cover the empty-legacy-table and pre-health-columns upgrade paths with new store tests. On the frontend, refactor useIntegrationEnabled to take string parameters instead of an inline options object so getSnapshot stays referentially stable across renders, and stop dispatching a misleading no-op sync event when localStorage.setItem fails in private mode. * fix: hydrate workspace list on integration settings pages The integration pages wrapped their content in a fresh StateProvider, which created a nested store scope with an empty initial state and shadowed the settings layout's hydrated workspace list. WorkspaceScopedSection then saw zero workspaces and rendered the "Create a workspace to configure this integration" empty state even when the user had workspaces. Drop the redundant StateProvider from the jira and linear pages so they share the layout's store. The github page switches to StateHydrator so it can still seed the GitHub OAuth status without resetting the rest of the store. * refactor(integrations): flatten watcher tables, pick workspace in create dialog Hiding watchers behind a workspace switcher made the list invisible at a glance — a user with multiple workspaces had to flip between each one to see what was configured. Replace the switcher with a flat table that lists every watch across every workspace, with a Workspace column for context, and move workspace selection into the create dialog so the user picks once when the watcher is born. Backend: jira list-issue-watches and github list-review-watches / list-issue-watches accept the workspace_id query param as optional; when omitted, the corresponding store ListAll* method returns rows across every workspace. Per-row mutations still require workspace_id as the IDOR guard. Frontend: useReviewWatches / useIssueWatches / useJiraIssueWatches gain a three-state contract — string for one workspace, undefined for all workspaces, null to skip fetching. Watch tables grow an optional showWorkspace column. Watch dialogs accept an optional workspaceId prop; when absent, the dialog renders a workspace dropdown for the create flow (disabled when editing existing rows so refs aren't orphaned). Github review-watch-dialog crossed the 600-line lint cap so the prompt editor moved to review-watch-prompt-field.tsx. * fix(integrations): make watcher step dropdown reactive across workspace switches Switching to a workspace whose workflows had to be fetched left the workflow step dropdown stuck — the user could pick a workflow but the step Select either showed the previous workflow's steps or appeared inert. The cause was the per-dialog useWorkflowSteps hook deferring its empty-state reset via Promise.resolve().then(() => setSteps([])) to dodge a setState-in-effect lint rule, which let stale steps survive into the next render and gave Radix nothing to anchor the popover to during the in-flight fetch. Hoist the hook into a shared useWorkflowSteps that resets via React's official setState-during-render pattern, exposes a loading flag, and returns a stepPlaceholder helper so the Select can render "Loading steps…" or "No steps in this workflow" instead of an empty popover. The Step Select is now also disabled while loading or when there are no steps, making the state of the dropdown unambiguous. * fix: address PR review feedback on integrations refactor Backend: - linear migration: add column-presence guard mirroring the Jira fix so installs that upgraded from the original Linear schema (without org_slug / last_checked_at / last_ok / last_error) don't crash startup with "no such column"; add TestStore_MigrateLegacyPerWorkspaceTable_PreHealthColumns - jira/handlers.go: drop the now-unused errMsgWorkspaceIDRequired constant that was failing golangci-lint - jira/mock_controller_test.go (new): cover setAuthHealth happy-path and invalid-JSON-rejection so the singleton-shaped payload is locked in Frontend: - useIntegrationAvailable: gate the auth-health probe on loaded && enabled so disabled integrations don't poll /config every 90s - use-workflow-steps: initialize loading to !!workflowId so edit-mode opens show "Loading steps…" instead of "No steps in this workflow" before the first fetch lands - use-workflow-steps.test.ts (new): cover the empty/non-empty workflowId, workflow switch, fetch error, and stepPlaceholder branches - use-linear-enabled.test: tighten the legacy-key migration assertion to pin the migrated value rather than just verifying key cleanup --------- Co-authored-by: Kandev Agent <agent@kandev.dev>
196 lines
5.5 KiB
Go
196 lines
5.5 KiB
Go
package jira
|
|
|
|
import (
|
|
"context"
|
|
"sync"
|
|
"time"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"github.com/kandev/kandev/internal/common/logger"
|
|
"github.com/kandev/kandev/internal/integrations/healthpoll"
|
|
)
|
|
|
|
// defaultIssuePollTickInterval is how often the issue-watch loop wakes up to
|
|
// look at every enabled watcher. The actual JQL is only re-run for a watcher
|
|
// when its per-watch `PollIntervalSeconds` has elapsed since `LastPolledAt`,
|
|
// so this is the *minimum* granularity, not the *actual* cadence. 60 seconds
|
|
// matches the smallest interval the UI accepts; the gating check then rate-
|
|
// limits each individual watcher.
|
|
const defaultIssuePollTickInterval = 60 * time.Second
|
|
|
|
// Poller drives two background loops sharing a single Service:
|
|
// - auth health: probes stored credentials so the UI can show connect status.
|
|
// Delegated to internal/integrations/healthpoll for the loop semantics.
|
|
// - issue watches: runs each enabled watcher's JQL and emits NewJiraIssueEvent
|
|
// for every matching ticket the orchestrator hasn't yet seen. Jira-specific
|
|
// and stays local.
|
|
//
|
|
// Both loops are cancelled together via Stop.
|
|
type Poller struct {
|
|
service *Service
|
|
logger *logger.Logger
|
|
auth *healthpoll.Poller
|
|
issueInterval time.Duration
|
|
issueTickHook func() // tests use this to observe each issue-watch tick.
|
|
|
|
// mu guards started/cancel/wg against concurrent Start/Stop calls.
|
|
mu sync.Mutex
|
|
cancelIssueLoop context.CancelFunc
|
|
wg sync.WaitGroup
|
|
started bool
|
|
}
|
|
|
|
// NewPoller returns a poller using the default cadences.
|
|
func NewPoller(svc *Service, log *logger.Logger) *Poller {
|
|
if svc == nil {
|
|
return nil
|
|
}
|
|
return &Poller{
|
|
service: svc,
|
|
logger: log,
|
|
auth: healthpoll.New("jira", svcProber{svc}, log),
|
|
issueInterval: defaultIssuePollTickInterval,
|
|
}
|
|
}
|
|
|
|
// SetIssueTickHook installs a callback fired at the end of each issue-watch
|
|
// tick. Production code never sets this; tests use it to wait for a tick
|
|
// without sleep-polling.
|
|
func (p *Poller) SetIssueTickHook(fn func()) {
|
|
p.mu.Lock()
|
|
p.issueTickHook = fn
|
|
p.mu.Unlock()
|
|
}
|
|
|
|
// Start launches both background loops. Calling Start more than once without
|
|
// Stop is a no-op. A nil receiver is also a no-op so callers don't have to
|
|
// nil-check around `NewPoller(nil, log).Start(ctx)` patterns.
|
|
func (p *Poller) Start(ctx context.Context) {
|
|
if p == nil {
|
|
return
|
|
}
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
if p.started || p.service == nil {
|
|
return
|
|
}
|
|
p.started = true
|
|
issueCtx, cancel := context.WithCancel(ctx)
|
|
p.cancelIssueLoop = cancel
|
|
p.auth.Start(ctx)
|
|
p.wg.Add(1)
|
|
go p.issueWatchLoop(issueCtx)
|
|
}
|
|
|
|
// Stop cancels both loops and waits for them to drain. A nil receiver is a
|
|
// no-op so callers using the `defer p.Stop()` pattern alongside a possibly-
|
|
// nil `NewPoller(svc, log)` don't have to nil-check.
|
|
func (p *Poller) Stop() {
|
|
if p == nil {
|
|
return
|
|
}
|
|
p.mu.Lock()
|
|
if !p.started {
|
|
p.mu.Unlock()
|
|
return
|
|
}
|
|
cancel := p.cancelIssueLoop
|
|
p.mu.Unlock()
|
|
if cancel != nil {
|
|
cancel()
|
|
}
|
|
p.auth.Stop()
|
|
p.wg.Wait()
|
|
p.mu.Lock()
|
|
p.started = false
|
|
p.mu.Unlock()
|
|
}
|
|
|
|
// issueWatchLoop drives the periodic JQL-poll → publish-event flow. Unlike
|
|
// the auth loop, this one waits a full interval before its first tick so the
|
|
// backend doesn't hammer JIRA the moment it starts.
|
|
func (p *Poller) issueWatchLoop(ctx context.Context) {
|
|
defer p.wg.Done()
|
|
ticker := time.NewTicker(p.issueInterval)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
p.checkIssueWatches(ctx)
|
|
p.fireIssueTickHook()
|
|
}
|
|
}
|
|
}
|
|
|
|
func (p *Poller) checkIssueWatches(ctx context.Context) {
|
|
watches, err := p.service.Store().ListEnabledIssueWatches(ctx)
|
|
if err != nil {
|
|
p.logger.Warn("jira poller: list enabled issue watches failed", zap.Error(err))
|
|
return
|
|
}
|
|
if len(watches) == 0 {
|
|
return
|
|
}
|
|
for _, w := range watches {
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
if !isIssueWatchDue(w, time.Now()) {
|
|
continue
|
|
}
|
|
newTickets, err := p.service.CheckIssueWatch(ctx, w)
|
|
if err != nil {
|
|
p.logger.Debug("jira poller: check issue watch failed",
|
|
zap.String("watch_id", w.ID), zap.Error(err))
|
|
continue
|
|
}
|
|
for _, t := range newTickets {
|
|
p.logger.Info("new jira issue found for watch",
|
|
zap.String("watch_id", w.ID),
|
|
zap.String("issue_key", t.Key),
|
|
zap.String("summary", t.Summary))
|
|
p.service.publishNewJiraIssueEvent(ctx, w, t)
|
|
}
|
|
}
|
|
}
|
|
|
|
// isIssueWatchDue reports whether enough time has passed since the watch was
|
|
// last polled to re-run its JQL on this tick. A watch with no LastPolledAt
|
|
// (never polled, or DB row freshly created) is always due. PollIntervalSeconds
|
|
// <= 0 falls back to the default — the same normalisation the store applies on
|
|
// write — so a corrupt row never blocks polling forever.
|
|
func isIssueWatchDue(w *IssueWatch, now time.Time) bool {
|
|
if w.LastPolledAt == nil {
|
|
return true
|
|
}
|
|
interval := w.PollIntervalSeconds
|
|
if interval <= 0 {
|
|
interval = DefaultIssueWatchPollInterval
|
|
}
|
|
return now.Sub(*w.LastPolledAt) >= time.Duration(interval)*time.Second
|
|
}
|
|
|
|
func (p *Poller) fireIssueTickHook() {
|
|
p.mu.Lock()
|
|
hook := p.issueTickHook
|
|
p.mu.Unlock()
|
|
if hook != nil {
|
|
hook()
|
|
}
|
|
}
|
|
|
|
// svcProber adapts *Service to healthpoll.Prober without leaking the shared
|
|
// interface into Service's public API.
|
|
type svcProber struct{ svc *Service }
|
|
|
|
func (s svcProber) HasConfig(ctx context.Context) (bool, error) {
|
|
return s.svc.Store().HasConfig(ctx)
|
|
}
|
|
|
|
func (s svcProber) RecordAuthHealth(ctx context.Context) {
|
|
s.svc.RecordAuthHealth(ctx)
|
|
}
|