Documentation
¶
Overview ¶
Package sync fills the mirror from the configured sources (Jira, and Confluence when enabled). It only ever writes to the mirror, never to Jira or Confluence, and the rules it implements are in specs/000-product/contracts/sync.md.
Index ¶
- Constants
- Variables
- func DevLinksFromPRs(prs []jira.DevPR) store.DevLinksUpdate
- func FlushAPIUsage(ctx context.Context, db *store.DB, c usageTaker, logf func(string, ...any))
- func IdentityFromConfig(cfg *config.Config) jql.Identity
- func IsRejectedCredential(err error) bool
- func MirrorStale(err error) error
- func NotifySupported() bool
- func ProjectScopeDiff(cfg *config.Config, counts map[string]int) (configuredEmpty, mirroredExtra []string)
- func ProjectScopeMismatch(cfg *config.Config, counts map[string]int) (configuredEmpty, mirroredExtra []string)
- func RefreshAgile(ctx context.Context, cfg *config.Config, db *store.DB, src string) error
- func RefreshIssue(ctx context.Context, cfg *config.Config, db *store.DB, key, src string) error
- func RefreshPage(ctx context.Context, cfg *config.Config, db *store.DB, id string) error
- func SetDefaultNotifier(n Notifier)
- func SprintIssueKeys(ctx context.Context, db *store.DB, sprintID int64) ([]string, error)
- func SyncIssue(ctx context.Context, cfg *config.Config, db *store.DB, key string, ...) error
- func SyncLinearIssue(ctx context.Context, db *store.DB, c *linear.Client, key string) error
- func SyncPage(ctx context.Context, cfg *config.Config, db *store.DB, id string) error
- func Watch(ctx context.Context, cfg *config.Config, db *store.DB, opts Options) error
- func WatchLoop(ctx context.Context, cfg *config.Config, db *store.DB, opts Options)
- type FirstSyncDoc
- type Notifier
- type OSNotifier
- type Options
- type Result
- type Throttle
Constants ¶
const ( // DefaultFetchConcurrency is the fetch pool's default width: enough to // cover a round trip's latency, few enough that a small origin is not // stamped on. It is also the ceiling's midpoint, not a tuned number — // the honest tuning pass needs the lead's after-merge benchmark. DefaultFetchConcurrency = 4 // MaxFetchConcurrency is the ceiling `--concurrency` is clamped to. // Above this the pass stops looking like one client to an operator // watching the origin's rate dashboard. MaxFetchConcurrency = 8 )
const ( KindJira = "jira" KindConfluence = "confluence" KindLinear = "linear" )
Source kinds — the Kind column of sources / sync_state rows, one value per connector. Single owner (GDK-619): every writer of the column and every comparison against it goes through these, never a bare literal.
const ( PhaseIssues = "issues" PhaseDocuments = "documents" PhaseIdle = "" )
Phase source names for Options.Phase. Callers report what the mirror is fetching; Progress carries how much. Keep these string values stable — the web client keys UI copy on them.
const ConfluenceSourceID = "confluence"
ConfluenceSourceID is the slug the wiki connector owns in sources / sync_state.
const LinearSourceID = "linear"
LinearSourceID is the slug the Linear connector owns in sources / sync_state. Mirrored item ids are "linear:<uuid>" — no built-in namespace variant: issuetap has no Linear surface, and Linear ids are uuids that cannot collide with anything numeric (the GDK-241 rationale does not apply).
const SourceID = "jira"
SourceID is the slug the Jira connector owns in `sources` and `sync_state`.
Variables ¶
var ErrFrozen = errors.New("workspace is frozen: no sync into this mirror (config \"frozen\": true)")
ErrFrozen means this workspace refuses pulls from origin (config "frozen").
var ErrIndexedLate = errors.New("sync: issue exists upstream but search has not indexed it yet")
ErrIndexedLate means the issue exists upstream (a direct GET answered) but JQL search still did not return it after the bounded retries. Jira Cloud's search index lags a write by seconds; the mirror row is untouched and the next scheduled sync picks the issue up. It is deliberately not ErrNotFound: nothing was deleted and nothing is missing.
var ErrMirrorStale = errors.New("sync: mirror stale")
ErrMirrorStale is the cause of a write-through re-read failure: the origin already accepted the write; only the mirror did not refresh. Classify with errors.Is(err, ErrMirrorStale). Error() of a wrapped value is the underlying re-read sentence verbatim — the same shape as origin.unsupportedError (GDK-685 / GDK-740). The sentinel's own text never prefixes that sentence, so SQLITE_BUSY stays recoverable via errors.As / Unwrap.
var ErrNotFound = errors.New("sync: issue not found upstream")
ErrNotFound means the upstream answered but no issue/page with that key came back: it is outside the credential's permissions, or it was just deleted.
var FetchConcurrency = DefaultFetchConcurrency
FetchConcurrency is the configured width of the fetch pools — the Confluence pass (GDK-1673) and the Jira issue pass (GDK-1674) — set by `gadak sync --concurrency` and read once per pass. A package-level knob rather than an Options field because the CLI and the server share the pass entry points. The pass clamps it to [1, MaxFetchConcurrency]; 1 is exactly the serial pass of pre-1673, pause included.
Deliberately unsynchronized: the only non-test write is cmd/gadak's flag handling, one assignment in the caller's goroutine before the first pass starts (cmd/gadak/sync.go; a serve process never writes it at all), and both reads sit at pass setup, on the same goroutine or ones spawned after that point — goroutine creation is the happens-before edge, so no read can race the write. Tests keep the same shape: assign, then run the pass.
Functions ¶
func DevLinksFromPRs ¶ added in v0.17.0
func DevLinksFromPRs(prs []jira.DevPR) store.DevLinksUpdate
DevLinksFromPRs maps dev-status pull requests onto a successful origin answer. Shared with `gadak dev link`'s post-write refresh so both paths store the same shape. A fetch error never produces this value. Author / actor / branch ride along when the origin serves them (GDK-589): Cloud's panel carries author{name} and source{branch}, issuetap adds the actor it stamped at write time; a payload without them stores empty strings.
func FlushAPIUsage ¶ added in v0.15.0
FlushAPIUsage takes the client's process-local counters and accumulates them into api_usage for the current UTC day. Jira and Confluence clients both satisfy usageTaker. One-shot sync, each Watch cycle, and `gadak api` go through this function so CLI and sync share one flush policy: a failure is logged and swallowed. api_usage is day-keyed with no source column — both connectors accumulate into the same daily row (schema contract).
func IdentityFromConfig ¶ added in v0.17.0
IdentityFromConfig is the JQL identity (email / account id) cfg carries — the "me" of currentUser() when a JQL filter is compiled. Single owner (GDK-619): filter import and `gadak views save` both read it.
func IsRejectedCredential ¶ added in v0.14.2
IsRejectedCredential reports whether err is a dead credential from any source. Transport errors (500, timeout, DNS) must stay false.
Owner of the detection rule: atlhttp.ErrAuth (what Do returns on 401/403) or any error implementing atlhttp.RejectedCredential. A third source that uses atlhttp.Do is covered without a branch here. A source that is not built on atlhttp still implements the method. Exported for the server's sync progress document — every surface reads this one rule as a code instead of matching error prose.
func MirrorStale ¶ added in v0.17.0
MirrorStale wraps a re-read failure so callers classify with errors.Is. nil stays nil; an error already in the class is returned unchanged.
func NotifySupported ¶ added in v0.21.0
func NotifySupported() bool
NotifySupported answers "can this process fire a real OS notification" for surfaces that only surface the fact (settings runtimeInfo). It is the injected notifier's capability when one exists — on desktop that is true for Windows too, which GOOS-derived logic always got wrong (GDK-1580).
func ProjectScopeDiff ¶ added in v0.19.0
func ProjectScopeDiff(cfg *config.Config, counts map[string]int) (configuredEmpty, mirroredExtra []string)
ProjectScopeDiff is the raw config↔mirror set difference behind ProjectScopeMismatch, and the single owner `gadak status` / `gadak config` warnings read too (GDK-809 surfaced the sides independently; GDK-973 folded their computation here so the surfaces can never disagree). Either side may be non-empty on its own — only the combined signature is a rename verdict.
func ProjectScopeMismatch ¶ added in v0.19.0
func ProjectScopeMismatch(cfg *config.Config, counts map[string]int) (configuredEmpty, mirroredExtra []string)
ProjectScopeMismatch is the single owner of the project-key rename/typo signature (GDK-973): a configured key the Jira mirror holds no issues under, together with a Jira-mirrored key outside the config. Either side alone is not a defect — a freshly created configured project is legitimately empty, and an unconfigured mirrored key is just out of scope — so both lists are populated or both are nil. counts comes from store.ProjectIssueCounts(db, SourceID); the post-sync warning and doctor both read this one verdict.
func RefreshAgile ¶ added in v0.22.0
RefreshAgile re-reads boards and sprints only. A sprint write changes no issue, so the pass that follows it would otherwise be a quiet tick that skips the agile listing and leaves the mirror stating the old state — gadak reporting what it wrote instead of what the origin now holds (GDK-1655, the GDK-1192 rule). The sprint_state derive inside ReplaceAgile is the same call, so `gadak sprint start|close` heals the issue rows here too — there is no second code path (GDK-1661).
src routes the re-read the way refreshIssue routes an issue re-read (GDK-1667): a Linear workspace re-lists cycles, not the Jira Agile API. The verb is not forked; the refresh is.
func RefreshIssue ¶ added in v0.17.0
RefreshIssue is the single owner of the write-through tail (CLI, including batch and create, and REST mutate / resync / attach). Both surfaces call RefreshIssue so the src routing cannot exist on one path and not the other: LinearSourceID goes to origin.Linear + SyncLinearIssue; every other src, including empty, goes to SyncIssue with default Options.
A failure is wrapped with ErrMirrorStale so every surface classifies the same class with errors.Is. Error() stays the inner re-read sentence verbatim (SQLITE_BUSY remains recoverable). handleResync still maps the wrapped error through failJira — that path is re-read only, not a landed write. CLI/REST write-through sites name the class; this function does not log or emit surface copy.
func RefreshPage ¶ added in v0.17.0
RefreshPage is the wiki write-through tail: SyncPage, then ErrMirrorStale. handlePageResync stays on SyncPage + failJira (re-read only).
func SetDefaultNotifier ¶ added in v0.21.0
func SetDefaultNotifier(n Notifier)
SetDefaultNotifier replaces the fallback notifier. Pass nil to restore OSNotifier. Write-once at process start is the intended use; later writes race only the read-side lock, never correctness of an in-flight Notify.
func SprintIssueKeys ¶ added in v0.22.0
SprintIssueKeys are the mirrored keys sitting in one sprint — what a state change has to re-read so their sprint_state column stops lying.
func SyncIssue ¶
func SyncIssue(ctx context.Context, cfg *config.Config, db *store.DB, key string, opts Options) error
SyncIssue re-reads one issue and writes it to the mirror. RefreshIssue is the write-through tail that routes here (or to SyncLinearIssue); CLI/REST must not branch on src at the call site. Ending here is what makes a row that came back from a write identical to one a scheduled sync produced — same field mapping, same derived fields, no second code path to keep in step.
func SyncLinearIssue ¶ added in v0.16.1
SyncLinearIssue re-reads one Linear issue and commits the row, the Linear counterpart of SyncIssue. RefreshIssue is the write-through tail that routes here; CLI/REST must not branch on src at the call site. Force is on for the same reason as the Jira path — the caller just wrote, so an unchanged updatedAt must not skip the refresh.
func SyncPage ¶
SyncPage re-reads one Confluence page and writes it to the mirror. Used when the desktop app closes an in-app browser tab after editing a wiki page: the rewrite moves synced_at and bumps sync_state.version so the client's next pages list / detail fetch sees the edit.
Unlike a full Confluence pass (commitBatch in confluence.go), this must not call RecordSync. A single page's lastModified must not become the source watermark — that would jump incremental sync into the future and skip every page modified in between. UpsertPages alone is enough: it rewrites the row and bumps version without advancing the watermark.
func Watch ¶
Watch runs incremental sync on an interval and reconcile on a longer one. A transport failure is logged and retried on the next tick; a rejected credential (IsRejectedCredential — atlhttp.ErrAuth or any error implementing atlhttp.RejectedCredential) records last_error, logs once, and stops retrying that source, because every further request would only burn rate budget. Jira is fatal (the loop ends). Confluence is not: Jira mirroring keeps going when only the wiki side is rejected. `gadak doctor` (sync.<id>.last_error) and sync_health read that last_error. `gadak status --json` last_error is the Jira row only. A later one-shot Run / RunConfluence with a new token still clears it. After each successful Jira cycle, new personal-feed events may produce one OS desktop notification (see notifyAfterSync); notification failures never stop the loop.
When opts.Reload is set, each cycle re-reads config so a settings edit (projects, Confluence, intervals) takes effect without restarting the process.
func WatchLoop ¶ added in v0.17.0
WatchLoop re-enters Watch until ctx is done. A rejected credential still ends Watch (no hot-loop on 401); this wait is what spaces retries until Reload sees a new credential (GDK-541).
Stop and Reload-failure messages go to opts.Log when set, otherwise to log.Printf — MCP stdout is the protocol, so those lines must use mcp.Logf via opts.Log, and workspace mounts want a profile prefix on the same hook.
Types ¶
type FirstSyncDoc ¶ added in v0.22.0
type FirstSyncDoc struct {
InProgress bool `json:"in_progress"` // always true when the doc exists
Phase string `json:"phase"` // "issues" | "documents"
Fetched int `json:"fetched"`
Total *int `json:"total,omitempty"` // omitted when the origin gave no count
// WikiPending: the wiki pass is configured and has not started (no live
// confluence row while the issues phase runs).
WikiPending bool `json:"wiki_pending,omitempty"`
StartedAt string `json:"started_at"`
}
FirstSyncDoc is the one "a first full sync is in progress" document every reader emits — `gadak status --json`, GET sync/progress/ — so the fact has a single wire shape (GDK-1677). It exists only while a first=1 row is live; a `--full` resync of a filled mirror shows nothing.
func FirstSync ¶ added in v0.22.0
FirstSync builds the doc from the mirror, not from any process's memory — a CLI-started first sync must show in a serve started later, and vice versa. nil means no first sync is in progress. Any read error also means nil: the warning this feeds is best-effort, never a failed status command.
type Notifier ¶
Notifier delivers one OS desktop notification. Exported since GDK-1580 so a shell can replace the osascript/notify-send default: desktop injects a wails notifications adapter via SetDefaultNotifier at startup, and the CLI keeps OSNotifier untouched. Implementations must never panic; callers treat every error as non-fatal and continue the sync loop.
Supported is the delivery capability: false means Notify will not actually alert anyone (Windows and other no-op platforms). notifyAfterSync must not advance last_notified_at in that case — skipped events stay pending for a later implementation.
Supported must be cheap and side-effect-free — the settings handler asks it per request (NotifySupported below) and must not hang on a permission prompt. Work that can block (service startup, authorization) belongs in Notify.
func DefaultNotifier ¶ added in v0.21.0
func DefaultNotifier() Notifier
DefaultNotifier is what a nil Options.notifier means: the injected shell notifier when one was installed, OSNotifier otherwise (the CLI path).
type OSNotifier ¶
type OSNotifier struct{}
OSNotifier uses the platform's desktop-notification command. darwin: osascript display notification; linux: notify-send; others: unsupported.
func (OSNotifier) Notify ¶
func (OSNotifier) Notify(title, body string) error
Notify implements Notifier.
func (OSNotifier) Supported ¶ added in v0.17.0
func (OSNotifier) Supported() bool
Supported reports whether this process can fire a real OS notification.
type Options ¶
type Options struct {
Full bool
Reconcile bool
// Log, when set, receives one line per committed page and per pass.
Log func(string)
// Progress, when set, is called once per committed page with the running
// totals. It exists so a caller can report progress without parsing Log.
Progress func(fetched, changed int)
// Phase, when set, is called with the connector a pass is about to run
// ("issues", "documents") and with "" when the cycle has nothing in flight.
// It exists so a caller can report *what* is being fetched; Progress carries
// how much. Watch calls it around each source; one-shot callers set it too.
Phase func(source string)
// Client is for tests and for a server that wants to share one; nil builds
// one from cfg.
Client *jira.Client
// ConfluenceClient is for tests; nil builds one from cfg when Confluence is configured.
ConfluenceClient *confluence.Client
// LinearClient is for tests; nil builds one from cfg when Linear is configured.
LinearClient *linear.Client
// Reload re-reads the config at the top of each watch cycle. Nil keeps the
// config Watch was called with. A reload error is logged and the previous
// config stays in use: a momentarily unreadable file must not stop the mirror.
Reload func() (*config.Config, error)
// Tick, when > 0, is the Watch interval. The zero value derives from
// cfg.EffectiveSyncIntervalSec() (an integer number of seconds), which is
// the production path. Tests set a sub-second Tick so they do not sit on
// that 1s floor.
Tick time.Duration
// contains filtered or unexported fields
}
Options tunes one Run or Watch cycle. A nil Client or ConfluenceClient is built from cfg; a nil notifier uses OSNotifier and never aborts the loop; a Reload error keeps the previous config so a momentarily unreadable file cannot stop the mirror.
type Result ¶
type Result struct {
Full bool
Fetched int
Changed int
Deleted int
Watermark string
// PageBodies and PageSkips are the Confluence pass's body-read tally: how
// many page bodies this pass went to the source for (a hit that turned out
// to be deleted still counts — the request was spent), and how many search
// hits pageFetchGate answered from the mirror instead. They are the answer
// to "how many bodies did that tick fetch?" — a quiet tick over an
// unchanged corpus must report PageBodies 0. Jira leaves both at 0.
PageBodies int
PageSkips int
// Skips is the Jira pass's stamp-gate tally: incremental search hits the
// mirror already held at exactly their `updated` stamp, answered without a
// build or an upsert (GDK-1075). A quiet tick reports Fetched 0 and every
// window hit here. Confluence leaves it at 0 (its gate reports PageSkips).
Skips int
// Backfilled names the projects a widened scope added and this pass read in
// full history (GDK-2051); the projects already in scope were not re-read.
Backfilled []string
}
Result is the tally of one source pass (Run or RunConfluence). Fetched/Changed/Deleted count what this pass touched. Full is true when the pass had no watermark to increment from, or the caller asked for one. Watermark is the newest upstream timestamp recorded on success.
func Run ¶
Run does one sync pass: full or incremental, plus a reconcile pass when asked for or after a full sync.
A failure leaves the pages already committed in place and does not advance the watermark, so the next run re-reads from the last known-good point (contracts/sync.md invariants 2 and 3).
An empty cfg.Projects means no project filter: the account's full visible issue set is the scope (one Search, not one per project).
func RunConfluence ¶
func RunConfluence(ctx context.Context, cfg *config.Config, db *store.DB, opts Options) (Result, error)
RunConfluence does one Confluence mirror pass: full or incremental. Page attachments ride the shared attachments table (GDK-1541); an origin that refuses the listing (issuetap: 501) degrades to "no attachments" for the pass. Version-history stamps (page_versions; never bodies) are collected when a mirrored page's current version number is not already stored. A failed history fetch is logged and does not fail the pass. Every successful pass prunes pages whose space is outside the current config/listing scope; memory.space always joins that scope (GDK-1079, joinMemorySpace). Full and scheduled reconcile passes also compare complete page listings with the mirror and delete pages gone within a kept space.
Incremental floors are per-space (spaces.watermark), but the queries are chunked: many spaces share one type=page and one type=comment CQL round trip, floored at the chunk's oldest member watermark (GDK-1074 — one CQL pair per space made a quiet 80-space tick cost 160 sequential round trips, 105 s measured). A failed chunk does not move any member's watermark, and no member ever advances past history the pass has not enumerated. A floor selects candidates, it does not decide fetches: pageFetchGate does, and an incremental tick over an unchanged space reads zero page bodies.
A failure leaves already-committed batches in place.
type Throttle ¶ added in v0.22.0
type Throttle struct {
// contains filtered or unexported fields
}
Throttle is the pool's AIMD width controller: how many fetches may be in flight right now, and how that number moves in response to the origin's 429s. One instance lives for a whole pass, so a halving earned in chunk 1 still holds in chunk 2. It carries no Confluence types — the Jira pool (GDK-1674) reuses it as is.
Multiplicative-decrease on a 429: effective = max(1, effective/2). A 429 is observed by the transport layer per response, but this controller hears about it per fetch window (meter delta around one worker's item), so two overlapping windows can each report the same throttle and halve twice. That over-reaction is accepted: the floor is 1, growth is slow by design, and the alternative — serializing window reports — costs more than an occasional extra halving on an origin that is already refusing work.
Additive-increase after throttleGrowAfter consecutive clean windows: effective+1, back toward the configured width, never past it.
Admission is a counting semaphore (a buffered channel of tokens) plus a debt count: a shrink that arrives while every token is in flight takes the tokens back as their workers release them. Every operation except Acquire is non-blocking, so a cancelled pass can never leave the controller wedged — Acquire is the only blocking point and it selects on ctx.
func (*Throttle) Acquire ¶ added in v0.22.0
Acquire takes a fetch slot, blocking until one is free. It is the only blocking operation and honors ctx, so a cancelled pass drains instead of hanging on a shrunk pool.
func (*Throttle) Configured ¶ added in v0.22.0
Configured is the pass's configured width (the --concurrency knob).
func (*Throttle) Effective ¶ added in v0.22.0
Effective is the current admission width. Reading it from a worker while others fetch is racy by design — it is the width this instant, not a promise about the next.
func (*Throttle) MinEffective ¶ added in v0.22.0
MinEffective is the lowest width AIMD sank to this pass. Equal to configured when the origin never throttled.
func (*Throttle) NoteClean ¶ added in v0.22.0
func (t *Throttle) NoteClean()
NoteClean records a fetch window with no 429. After throttleGrowAfter consecutive clean windows the width grows by one toward configured.
func (*Throttle) NoteThrottle ¶ added in v0.22.0
func (t *Throttle) NoteThrottle()
NoteThrottle records a 429 seen inside one worker's fetch window: halve the effective width, floor 1. Tokens beyond the new width are removed from the idle pool immediately and from in-flight workers as they release.