54b98ed9eb
* feat(jira): add Jira integration for ticket browsing, import, and task linking Adds a workspace-scoped Atlassian Cloud integration: per-workspace settings (site URL, email, API token or session cookie), encrypted secret storage, and a REST client for tickets, projects, search, and transitions. A background poller probes credentials on a 90s cadence and the keepalive runs immediately on save so the UI's connected indicator updates without delay. The /jira page provides ticket browsing with filter pills, custom JQL, saved views (including JQL), and configurable task-launch presets that prefill TaskCreateDialog. JiraLinkButton on the task top bar links an existing task to a ticket by prepending its key to the title; the ticket popover surfaces details, transitions, and re-auth prompts on session expiry. Topbar shows separate icon buttons for GitHub and Jira when each is configured. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(jira): address PR review feedback - Token-based pagination (pageToken/isLast) replaces broken offset/total pagination - Race-fix in service.clientFor: re-check cache after acquiring write lock - sync.Mutex guards poller started/cancel state against concurrent Start/Stop - Channel-based + atomic.Int32 test sync replaces time.Sleep polling in poller_test - Async auth probe on SetConfig with detached context.Background goroutine - Distinguish 4xx vs 5xx in httpSetConfig via ErrInvalidConfig sentinel - Propagate 4xx APIErrors from ListTransitions in GetTicket - Distinguish "not found" from real errors in jiraSecretAdapter.Exists - Log secret Exists errors instead of swallowing - walkADF: handle softBreak (was only hardBreak despite the doc-comment) - Consolidate JIRA_KEY_RE in jira-ticket-common; remove duplicates - ticket-row imports formatRelative/statusBadgeClass from common - isFilterState type guard validates SavedView.filters shape - task-presets readStorage preserves user's "cleared all" intent (returns []) - task-presets-section gates draft sync on `loaded` to avoid wiping in-progress edits - jira-api: caller `init` no longer overrides method/body via spread order - jira-settings: disable Test button when no saved/typed secret Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(jira): record auth probe failure even when probe ctx expires - RecordAuthHealth now uses a fresh context.Background-derived ctx with a 5s timeout for the UpdateAuthHealth DB write, so a probe that consumes its full 15s deadline still persists the failure (greptile P1). - SetConfig goroutine drops its redundant outer timeout — RecordAuthHealth manages its own probe timeout, so context.Background is enough. - Add Service.SetProbeHook so tests can synchronize on probe completion; service_test waitForAuthProbe now blocks on the hook channel instead of time.Sleep polling. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(jira): address coderabbit review feedback (round 3) - url.PathEscape ticketKey in GetTicket/ListTransitions/DoTransition paths to harden against malicious keys ('../../foo', 'KEY?override=x'). - factoryHit on the test fixture is now sync/atomic.Int32; the async probe goroutine spawned by SetConfig races the test thread under -race. - GetConfig logs Reveal failures (was silently dropped, leaving the UI to show "no expiry info" indistinguishably from a freshly-saved cookie). - DeleteConfig logs secret-delete errors instead of swallowing them. - clientFor distinguishes a secret-store failure from "not configured" so the UI doesn't render the configure-CTA for transient backend errors. - Unify ErrNotConfigured wire code: HTTP and WebSocket both return "JIRA_NOT_CONFIGURED" via a shared constant. - JiraLinkButton strips a leading "PROJ-123: " before re-prefixing so re-linking a task replaces the prefix instead of stacking it. - jira-settings clears testResult on save/delete so the alert reflects only the currently-saved credentials. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test(jira): cover Reveal error path in clientFor Reveal-error case is distinct from "no config row" — the former wraps the underlying error, the latter returns ErrNotConfigured. Without this test the changed contract has no regression coverage. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(jira): route secret adapter Set through Exists Treating every Get error as "not found" turned a transient DB error on an existing row into a constraint-violation Create that masked the real cause. Reuse Exists so the "secret not found:" prefix is the only path that falls through to Create. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test(jira): cover jiraSecretAdapter.Set branching Routing Set through Exists changed the contract: a transient DB error in Get now propagates instead of cascading into a constraint-violation Create. Add three tests so a future refactor cannot regress this without CI catching it. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(jira): split Reveal errors and guard Save for new configs - resolveCredentials now mirrors the clientFor split: a Reveal error surfaces as `read jira secret: %w` with a warn log instead of collapsing into "no token stored — paste one to test". - disableSave gains the same missing-secret guard as disableTest so a brand-new config can no longer POST an empty secret and leave the workspace stuck with hasSecret=false. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Kandev Agent <agent@kandev.dev> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
178 lines
5.6 KiB
Go
178 lines
5.6 KiB
Go
package jira
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
)
|
|
|
|
// Store persists Jira workspace configurations. Secret values are delegated to
|
|
// the shared encrypted secret store and not stored here.
|
|
type Store struct {
|
|
db *sqlx.DB
|
|
ro *sqlx.DB
|
|
}
|
|
|
|
// NewStore creates a new Store and initializes the schema if needed.
|
|
func NewStore(writer, reader *sqlx.DB) (*Store, error) {
|
|
s := &Store{db: writer, ro: reader}
|
|
if err := s.initSchema(); err != nil {
|
|
return nil, fmt.Errorf("jira schema init: %w", err)
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
const createTablesSQL = `
|
|
CREATE TABLE IF NOT EXISTS jira_configs (
|
|
workspace_id TEXT PRIMARY KEY,
|
|
site_url TEXT NOT NULL,
|
|
email TEXT NOT NULL DEFAULT '',
|
|
auth_method TEXT NOT NULL,
|
|
default_project_key TEXT NOT NULL DEFAULT '',
|
|
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
|
|
);
|
|
`
|
|
|
|
// addedColumns lists columns introduced after the initial schema. SQLite has no
|
|
// portable `ADD COLUMN IF NOT EXISTS`, so we ask sqlite_master for the existing
|
|
// CREATE TABLE statement and only ALTER when the column name is missing.
|
|
var addedColumns = []struct {
|
|
name string
|
|
sql string
|
|
}{
|
|
{"last_checked_at", "ALTER TABLE jira_configs ADD COLUMN last_checked_at DATETIME"},
|
|
{"last_ok", "ALTER TABLE jira_configs ADD COLUMN last_ok INTEGER NOT NULL DEFAULT 0"},
|
|
{"last_error", "ALTER TABLE jira_configs ADD COLUMN last_error TEXT NOT NULL DEFAULT ''"},
|
|
}
|
|
|
|
func (s *Store) initSchema() error {
|
|
if _, err := s.db.Exec(createTablesSQL); err != nil {
|
|
return err
|
|
}
|
|
return s.migrateAddedColumns()
|
|
}
|
|
|
|
// migrateAddedColumns applies ALTER TABLE statements for columns introduced
|
|
// after the initial schema. Existing databases created with the old CREATE
|
|
// TABLE need these columns backfilled; new databases already have them from
|
|
// createTablesSQL and the ALTERs are skipped.
|
|
func (s *Store) migrateAddedColumns() error {
|
|
existing, err := s.tableColumns("jira_configs")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, col := range addedColumns {
|
|
if _, ok := existing[col.name]; ok {
|
|
continue
|
|
}
|
|
if _, err := s.db.Exec(col.sql); err != nil {
|
|
return fmt.Errorf("add column %s: %w", col.name, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
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 {
|
|
return nil, err
|
|
}
|
|
defer func() { _ = rows.Close() }()
|
|
cols := make(map[string]struct{})
|
|
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 nil, err
|
|
}
|
|
cols[name] = struct{}{}
|
|
}
|
|
return cols, rows.Err()
|
|
}
|
|
|
|
const selectConfigColumns = `workspace_id, site_url, email, auth_method, default_project_key,
|
|
last_checked_at, last_ok, last_error, created_at, updated_at`
|
|
|
|
// GetConfig returns the Jira config for a workspace, or nil when no row exists.
|
|
func (s *Store) GetConfig(ctx context.Context, workspaceID string) (*JiraConfig, error) {
|
|
var cfg JiraConfig
|
|
err := s.ro.GetContext(ctx, &cfg,
|
|
`SELECT `+selectConfigColumns+` FROM jira_configs WHERE workspace_id = ?`, workspaceID)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &cfg, nil
|
|
}
|
|
|
|
// UpsertConfig inserts or updates the config row for a workspace. It never
|
|
// touches the secret store — callers must persist the token separately. The
|
|
// last_* health columns are deliberately not touched here; the poller owns
|
|
// those and writes them via UpdateAuthHealth.
|
|
func (s *Store) UpsertConfig(ctx context.Context, cfg *JiraConfig) error {
|
|
now := time.Now().UTC()
|
|
if cfg.CreatedAt.IsZero() {
|
|
cfg.CreatedAt = now
|
|
}
|
|
cfg.UpdatedAt = now
|
|
_, err := s.db.ExecContext(ctx, `
|
|
INSERT INTO jira_configs (workspace_id, site_url, email, auth_method, default_project_key, created_at, updated_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT(workspace_id) DO UPDATE SET
|
|
site_url = excluded.site_url,
|
|
email = excluded.email,
|
|
auth_method = excluded.auth_method,
|
|
default_project_key = excluded.default_project_key,
|
|
updated_at = excluded.updated_at`,
|
|
cfg.WorkspaceID, cfg.SiteURL, cfg.Email, cfg.AuthMethod, cfg.DefaultProjectKey, cfg.CreatedAt, cfg.UpdatedAt)
|
|
return err
|
|
}
|
|
|
|
// DeleteConfig removes the Jira config row for a workspace. Secrets must be
|
|
// cleared separately by the caller.
|
|
func (s *Store) DeleteConfig(ctx context.Context, workspaceID string) error {
|
|
_, err := s.db.ExecContext(ctx, `DELETE FROM jira_configs WHERE workspace_id = ?`, workspaceID)
|
|
return err
|
|
}
|
|
|
|
// ListConfiguredWorkspaces returns the IDs of all workspaces that have a Jira
|
|
// config row. Used by the auth-health poller to know which workspaces to probe.
|
|
func (s *Store) ListConfiguredWorkspaces(ctx context.Context) ([]string, error) {
|
|
var ids []string
|
|
err := s.ro.SelectContext(ctx, &ids,
|
|
`SELECT workspace_id FROM jira_configs ORDER BY workspace_id`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return ids, nil
|
|
}
|
|
|
|
// UpdateAuthHealth records the result of a credential probe for a workspace.
|
|
// errMsg is the empty string when ok is true. If the workspace row no longer
|
|
// exists (e.g. the user removed the config concurrently with the poller), the
|
|
// update is a silent no-op rather than an error.
|
|
func (s *Store) UpdateAuthHealth(ctx context.Context, workspaceID string, ok bool, errMsg string, checkedAt time.Time) error {
|
|
_, err := s.db.ExecContext(ctx, `
|
|
UPDATE jira_configs
|
|
SET last_checked_at = ?, last_ok = ?, last_error = ?
|
|
WHERE workspace_id = ?`,
|
|
checkedAt, ok, errMsg, workspaceID)
|
|
return err
|
|
}
|