Artifact 9e59322a492094b7a0505ca1f37e24c931a5397fec884227235c47e85e7bacc2:
- File
cmd/quarry/registrar.go
— part of check-in
[935ac1ac7d]
at
2026-11-25 19:17:57
on branch trunk
— land chat-highlights
via mac, quarry (user: dmestas, size: 149135) [annotate] [blame] [check-ins using] [more...]
package main import ( "archive/tar" "bytes" "compress/gzip" "context" "crypto/rand" "crypto/sha256" "encoding/base32" "encoding/hex" "encoding/json" "fmt" "io" "log" "net/http" "os" "path" "path/filepath" "slices" "strings" "sync" "sync/atomic" "time" "unicode/utf8" "craftdesign.group/quarry/internal/api" "craftdesign.group/quarry/internal/chat" "craftdesign.group/quarry/internal/ci" "craftdesign.group/quarry/internal/errlog" "craftdesign.group/quarry/internal/events" "craftdesign.group/quarry/internal/index" "craftdesign.group/quarry/internal/ingest" "craftdesign.group/quarry/internal/lease" "craftdesign.group/quarry/internal/obs" "craftdesign.group/quarry/internal/oltp" "craftdesign.group/quarry/internal/ops" "craftdesign.group/quarry/internal/outbound" "craftdesign.group/quarry/internal/work" "craftdesign.group/quarry/internal/xfer" "craftdesign.group/quarry/internal/zitcli" "errors" "craftdesign.group/quarry/internal/fault" ) // registrar owns a served repository's whole lifetime: its index handle, // its ingest pipeline, its sync backend, and the goroutine polling it. // // This was the body of serve's startup loop. It is a type now because a // repository can be registered while the server runs, and the loop's // shape did not survive that: it relied on `defer ix.Close()` reaching // serve's return, and on a poll goroutine that never stops. Neither is // available to an admin call, and both are leaks if a repository is ever // removed. type registrar struct { // maint is the maintenance lane; nil runs upkeep at once. maint *maintenance // createMu serializes Add's name check with the name being taken. createMu sync.Mutex // flatNames names repositories across the node, not within a // namespace (--repo-names=flat, RFC 0025). flatNames bool // schedules is each repository's scheduled workflows as of its // default tip, shared by the scheduler and the CI page. schedules *ci.ScheduleCache dir string // derived-data root reposRoot string // where repositories created through the API are placed node string // this node's id, for durable consumer names interval time.Duration ciCloneBase string // drainRepo, when set, stands in for the registered repository's // read side in drainDeferred. drainRepo func(name string) (ci.Repo, bool) ev *events.Server leases *lease.Manager jobs *jobGate // gitTestProtocol, when set, is the one protocol git may use in // place of https: a test's local upstream (#358). gitTestProtocol string // gitLocks is one *sync.Mutex per repository following a Git upstream. gitLocks sync.Map // gitSweep removes, once, the Git fetches earlier processes left. gitSweep sync.Once // gitFirstDepth, when set, replaces gitFirstDepth for tests, and // gitOnFetch sees the depth of every fetch. gitFirstDepth int gitOnFetch func(depth int) // gitFlatLimit, when set, replaces gitFlatLimit for tests, and // importServe, when set, replaces Register for a finished import. gitFlatLimit int64 importServe func(name, path string) error // githubAPI is GitHub's API root, for the description an import // copies; "" is api.github.com. Tests point it at a stand-in. githubAPI string // gitMirror is RFC 0022's per-repository push state. gitMirror gitMirrors // fossilMirror is the same for the mirror to a Fossil server. fossilMirror fossilMirrors deps *api.Deps fronter *xfer.Fronter ingestLane *work.Lane bulk *work.Lane engine *ci.Engine odb *oltp.DB // doors resolves tokens at the sync lane's Basic round and counts // the misses; nil resolves them uncounted. doors *tokenDoors // openLandings is, per repository, the open landings the fold loop // has already seen (id -> branch), so the ones a fold ADDS are the // ones that just opened and the ones it DROPS the ones that just // closed. Seeded on the first sweep without asking for anything: a // restart is not a thousand landings opening at once. landingsMu sync.Mutex openLandings map[string]map[string]string // orphansSwept is, per repository, whether cancelOrphanPairs has // completed once in this process; a pass that could not read // everything it needs is tried again on a later sweep. orphansSwept map[string]bool // landingTargets is the target each of those was last seen aimed // at (repository -> id -> target), so a retarget is noticed. landingTargets map[string]map[string]string // pipelineless remembers branch tips that have no pipelines, so the // pair sweep does not list their files again on every fold. pipelineless sync.Map // gateSeen is when the gate sweep first saw an unaccepted check-in // on a protected branch (key repo NUL hash). A forge accept records // itself a moment AFTER its merge is folded, so a sweep in that gap // read the forge's own merge as a bypass; a finding now waits // gateGrace from first sight — the forge's clock, not the check-in's // author-written date, so a future-dated push cannot wait forever. gateSeen sync.Map gateRecheck sync.Map // repo -> struct{}: a re-sweep is scheduled gateGrace time.Duration clock func() time.Time // ciTagsDefault is the fleet's verdict-tag default (RFC 0009); a // repository's own mode overrides it either way. ciTagsDefault bool // carried holds the merges carryForward wrote a verdict onto that // the index does not show yet, keyed by repository and merge hash: // a fork and its source share hashes, and each needs its own. carried sync.Map // repoQuota caps how many repositories a non-site-admin account may // administer at once (--repo-quota, default 25). Creation is open // to any account now, and an open door needs a limit; a site admin // is never subject to it. repoQuota int // codes is shared with the auth verifier's cache, so a project code // learned here is the one the push gate checks. codes map[string]string codeMu *sync.Mutex // refreshing marks the repositories whose project code is being // read again. refreshing sync.Map mu sync.Mutex running map[string]*served // private is the visibility list the read gate consults, loaded at // privAt. privGen numbers loads as they begin and privStored is the // number of the one in private, so a slow load cannot replace a // newer one. privBusy is set while a background reload runs. // privStored is zero until a load has succeeded: there is no list // to serve yet, so everything answers private (privateSet). privMu sync.RWMutex private map[string]bool privAt time.Time privGen uint64 privStored uint64 privBusy atomic.Bool privLoad func() (map[string]bool, error) // nil: odb.PrivateRepos // held is RFC 0023's takedowns, reloaded with the private set and on // the same clock; heldStored is the load it came from, zero until // one has succeeded. held map[string]oltp.Takedown heldStored uint64 // companions is store -> parent repository, loaded with held so a // takedown on the parent covers the store without a query per call // (RFC 0015 with RFC 0023). compStored is the load it came from. companions map[string]string compStored uint64 // heldLookup asks the tables directly for a repository's takedown, and // its parent when it is a companion store, while no cached load has // succeeded. nil asks odb; a test stubs it to fail. heldLookup func(repo string) (t oltp.Takedown, whose string, ok bool, err error) } // privateTTL bounds how long another node's visibility change can go // unseen here: every node shares the OLTP but caches the list. const privateTTL = 5 * time.Second // served is what a registration leaves behind that must be released. type served struct { ix *index.Index stop context.CancelFunc done chan struct{} // closed when the poll goroutine has exited } func (rg *registrar) track(name string, s *served) { rg.mu.Lock() defer rg.mu.Unlock() if rg.running == nil { rg.running = map[string]*served{} } rg.running[name] = s rg.sizeIngestQueueLocked() } // sizeIngestQueueLocked keeps the ingest lane's queue at one place per // served repository, plus one: ingest must wait, never be shed. The lane // was sized from the --repo flags alone, so every repository the registry // supplied was unaccounted for (queue=2 with dozens served). It only // grows here; boot sizes it for every pending repository up front, and // Unregister shrinks it. Needs rg.mu. func (rg *registrar) sizeIngestQueueLocked() { if rg.ingestLane != nil { rg.ingestLane.SetQueue(max(rg.ingestLane.Stats().Queue, len(rg.running)+1)) } } // Register opens a repository and starts serving it. Safe to call while // the server is running. // leafAnswer decides whether a cached leaf set may be served. It is a // function so the rule can be tested: the closure below cannot be, and // this rule is the difference between a mark that states a fact and one // that states a fact that WAS true. // // A set derived before the DAG moved is not "slightly out of date" — a // merge is precisely what retires a leaf, so the stale set's marks are // wrong exactly where the reader is looking. func leafAnswer(set map[string]bool, cachedGen, gen uint64) (map[string]bool, bool) { if set != nil && cachedGen == gen { return set, true } return nil, false } func (rg *registrar) Register(name, path string) error { // Startup binds the port only after every repository is registered, // so each repository's cost is the whole forge's downtime. Timed so // a slow one is nameable instead of merely suspected. regStart := time.Now() defer func() { if d := time.Since(regStart); d > 500*time.Millisecond { log.Printf("register %s: took %s", name, d.Round(time.Millisecond)) } }() if _, exists := rg.deps.Repos.Get(name); exists { return fmt.Errorf("repository %q is already served: %w", name, ops.ErrInvalid) } if err := os.MkdirAll(filepath.Join(rg.dir, name), 0o755); err != nil { return err } ix, err := index.Open(filepath.Join(rg.dir, name, "index.db")) if err != nil { return err } cli := zitcli.New(path) // The lease keys on the store's project code, learned via the same // boundary-clean handshake user-add uses. Doing it before anything // is published means a path that is not a repository fails here, // with the index closed again, rather than half-registering. code, cerr := xfer.ProjectCode(path) if cerr != nil { ix.Close() // A path that is not a repository is a bad REQUEST, not a server // fault. Without this it surfaced as "internal error", which // tells an operator to read the server log for what is in fact // their own typo. return fmt.Errorf("%w: %s is not a zit repository: %v", ops.ErrInvalid, path, cerr) } rg.codeMu.Lock() rg.codes[name] = code rg.codeMu.Unlock() chatKey := rg.chatKeyOf(name) // Kept in the repository's row too, which is what a claim on a code // is made against. if rg.odb != nil { if err := rg.odb.SetRepoCode(name, code); err != nil { log.Printf("register %s: recording its project code: %v", name, err) } } rg.maint.Request(name, "search check", func(ctx context.Context) error { return ix.VerifySearchContext(ctx) }) // Probed once here, not per render: the answer changes only when an // S-bearing artifact first arrives. A probe that fails leaves it // false, which withholds the fossil clone rather than offering one // that might not work. // // BOUNDED, because this runs before the server binds its port and // the cost is a function of the store's size, not a constant: the // note here used to say ~250ms, measured on small stores. On tcl it // is 116 SECONDS and on sqlite 16, so a fleet with either in it // could not answer a request for minutes after starting — the whole // forge held hostage by a detail about one clone URL. Past the // deadline the probe is simply an unanswered question, which the // false above already handles correctly. fossilClone := false probeCtx, cancelProbe := context.WithTimeout(context.Background(), 2*time.Second) if seen, err := cli.SeenSubmanifest(probeCtx); err == nil { fossilClone = !seen } else if probeCtx.Err() != nil { log.Printf("register %s: submanifest probe timed out; fossil clone withheld", name) } else { log.Printf("register %s: submanifest probe: %v", name, err) } cancelProbe() indexing := new(atomic.Bool) indexing.Store(true) // Bumped after every ingest round so memoised answers that depend // on the DAG — the leaf set below — recompute exactly when the DAG // can have changed, and never otherwise. // One warm pass per repository at a time. warmReads and indexTree // each spawn SEVERAL zit subprocesses — ls, ls-under, a cat per // file, an archive — and on a store tcl's size each takes seconds. // Launched unguarded from every round that moved the tip, the next // round started another set before the last had finished and they // stacked: 43 zit children on the demo fleet, three of them the // same ls against the same hash, with load average 546 on 14 cores. // A warm pass already running IS the warm pass; a second one is // duplicate work that makes the first one slower. var warm warmer warm.gate = productionBootGate() warm.maint, warm.store = rg.maint, name var indexingTree atomic.Bool ingestGen := new(atomic.Uint64) entry := &api.Repo{ FossilClone: fossilClone, Index: ix, Zit: cli, Code: code, Chat: chatKey, Indexing: indexing.Load, Guard: func(fn func(lease.Token) error) error { // The lease is the repository's, not the project's: two // repositories of one project hold the same code and are // written independently (repoLeaseKey). // RFC 0023: "Writes | refused for everybody" under a legal hold, // "so the evidence does not change". The one place every write // of the forge's own passes (an accept, a verdict tag, a // mirror's fetch, a repair), so one that is not gated at its // caller still stops here, with an answer and not a change. if rg.legallyHeld(name) { return errWriteHeld } return leaseRefusal(rg.leases.Guard(repoLeaseKey(name), fn)) }, } // Leaf status is zit's answer, memoised per ingest: the set only // changes when a check-in arrives. // // The memo is WARMED IN THE BACKGROUND rather than filled by the // first reader. That call is not ~10ms on a large store as this // comment used to claim — measured on sqlite it is 6.4 SECONDS, and // making one unlucky request pay it put the repository home at // 10.8s cold against 0.5s warm. It was invisible in the footer too, // because a detached context carries no timer, so the time landed // in "ops" with nothing to point at. // // A reader arriving before the warm finishes gets no leaf marks // rather than a six-second wait: the marks are decoration on a // timeline that is otherwise complete, and a page that arrives // without them is better than one that does not arrive. var leafMu sync.Mutex var leafSet map[string]bool var leafErr error var leafGen uint64 var leafWarming bool warmLeaves := func(gen uint64) { set, err := cli.Leaves(context.Background()) leafMu.Lock() leafSet, leafErr, leafGen, leafWarming = set, err, gen, false leafMu.Unlock() } entry.Leaves = func() (map[string]bool, error) { gen := ingestGen.Load() leafMu.Lock() defer leafMu.Unlock() if fresh, ok := leafAnswer(leafSet, leafGen, gen); ok { return fresh, leafErr } if !leafWarming { leafWarming = true go warmLeaves(gen) } // The DAG has moved since this set was derived, so nil rather // than the old set — even though the old set is "almost right". // // A leaf mark is not decoration, it is a claim: this check-in is // the tip of its branch and nothing follows it. The instant that // stops being true is a merge, and a merge is exactly when // somebody is looking at the timeline. Serving the previous set // then puts a ring on the two check-ins that just STOPPED being // leaves — the reader is told the branch is still open at the // moment it closed, which is the one answer the mark must never // give. // // Missing marks are the honest failure and the one this file // already accepts while cold: no ring says "not known", a wrong // ring says "still open". The warm above is already running, so // the gap lasts one derivation. return nil, leafErr } // Warm at registration so the first reader of a repository does not // find it cold either. go func() { leafMu.Lock() if leafWarming { leafMu.Unlock() return } leafWarming = true gen := ingestGen.Load() leafMu.Unlock() warmLeaves(gen) }() // The default branch is zit's resolution of "trunk" — fossil's // main-branch setting and tag propagation live there, so a repo // that renamed trunk to main answers "main". Memoised per ingest // generation like the leaf set: it changes only when the DAG does. var dbMu sync.Mutex var dbName, dbTip string var dbGen uint64 dbGen = ^uint64(0) // Warmed in the background for the same reason as the leaf set: a // subprocess on a render path is latency one reader pays for // everybody, and one running on a detached context is invisible in // the footer while still counting toward the page's total. With // both warmed, "ops minus zit" means what the ops panel says it // means — index and OLTP work — instead of hiding a subprocess. var dbWarming bool warmDefault := func(gen uint64) { tip, name, err := cli.Info(context.Background(), "trunk") dbMu.Lock() if err == nil { dbName, dbTip, dbGen = name, tip, gen } dbWarming = false dbMu.Unlock() } entry.DefaultBranch = func() (string, string) { gen := ingestGen.Load() dbMu.Lock() defer dbMu.Unlock() if dbGen == gen { return dbName, dbTip } if !dbWarming { dbWarming = true go warmDefault(gen) } // Empty means the caller falls back to the index heuristic, // which is what it already did on error. return dbName, dbTip } go func() { dbMu.Lock() if dbWarming { dbMu.Unlock() return } dbWarming = true gen := ingestGen.Load() dbMu.Unlock() warmDefault(gen) }() entry.Mirror = func(url string) (bool, error) { // zit makes this connection, so the address is judged again just // before the run (the dial cannot be hooked): a stored upstream // that is private now is refused here and the refusal recorded. if _, err := outbound.CheckUser(url); err != nil { return false, fmt.Errorf("the upstream is refused: %v", err) } var changed bool err := entry.Guard(func(tok lease.Token) error { var perr error changed, perr = cli.Pull(tok, url) return perr }) return changed, err } entry.MirrorGit = func(url string) (bool, error) { return rg.pullGit(name, path, cli, entry.Guard, url) } rg.recoverGitAtStart(name, path, cli, entry.Guard) pipe := ingest.NewPipeline(cli, rg.ev, ix, name, rg.node) if rg.maint != nil { pipe.SetMaintenance(func(task string, run func(context.Context) error) bool { return rg.maint.Request(name, task, run) }) } // In-process reindex: a rebuild, so it runs on one of the pipeline's // rebuild slots and a fleet-wide repair is staged maxRebuilds stores // at a time rather than a stampede. It does NOT take an ingest-lane // slot: it waits for the store's lock, and nothing may wait for that // holding a lane slot (see ingest.Admit). The indexing flag makes the // fleet page say what is happening; the generation bump drops every // memo derived from the shape being rebuilt. entry.Reindex = func() (int, error) { indexing.Store(true) defer indexing.Store(false) n, err := pipe.Reindex() ingestGen.Add(1) // Reset drops every derived table, and the doc rows are one of // them. Without this a rebuild leaves documentation silently // unsearchable until the next commit happens to move the tip — // which on a mirror of a quiet project is never. if err == nil { if indexingTree.CompareAndSwap(false, true) { go func() { defer indexingTree.Store(false) indexTree(cli, ix) }() } } return n, err } // A forge agent's reindex (RFC 0021 upkeep): the same rebuild, held // to what the forge can spare without anybody noticing. entry.UpkeepReindex = func() (int, error) { if !upkeepRebuild.CompareAndSwap(false, true) { return 0, fmt.Errorf("another forge agent's rebuild is running; try again when it ends: %w", ops.ErrUnavailable) } defer upkeepRebuild.Store(false) if err := upkeepRefusal(name, ingest.Rebuilds().Running, storeBytes(path)); err != nil { return 0, err } if err := upkeepSpaced(name, time.Now()); err != nil { return 0, err } defer upkeepDone(name, time.Now) return entry.Reindex() } // The store's lifetime: stop ends it, and with it the warm passes. ctx, cancel := context.WithCancel(context.Background()) var warmOnce sync.Once // afterSync is what follows any round that ran: the memo generation // and the reader-path warm. Declared first, so syncIn can use it. var afterSync func(n int, err error) (int, error) // syncIn is the round the poll runs, admitted through the ingest lane; // entry.Sync is the same round for // the write ops, which hold no lane slot. syncIn := func(admit ingest.Admit) (int, error) { return afterSync(pipe.SyncIn(admit)) } afterSync = func(n int, err error) (int, error) { // Only a round that actually ingested something can have moved // the DAG, so only that invalidates the memos hanging off it. // Bumping on every round made the poll interval the memo's // lifetime: with a two-second poll, essentially every page load // paid the cold path — 84ms against 9ms on fossil. if n > 0 { ingestGen.Add(1) } // Warm the reader's path before a reader pays for it: the memo // caches are per-process and keyed on the tip, so both a restart // and a new check-in leave the next files-page visitor holding // four cold zit subprocesses — 5.6 seconds on a store tcl's // size. After the round that moved the tip (and once at boot), // the same reads run here instead, in the background. if err == nil { fresh, atBoot := n > 0, false warmOnce.Do(func() { fresh, atBoot = true, n == 0 }) if fresh { // A warm already running is told to go round again // when it ends, so a tip moved meanwhile is warmed. // The boot one, with nothing ingested, waits its turn // on the maintenance lane. if atBoot { warm.boot(ctx, cli, ix) } else { warm.start(ctx, cli, ix) } if indexingTree.CompareAndSwap(false, true) { go func() { defer indexingTree.Store(false) indexTree(cli, ix) }() } } } return n, err } entry.Sync = func() (int, error) { return syncIn(nil) } entry.TrySync = func() (int, error) { n, err := pipe.TrySync() if errors.Is(err, ingest.ErrRoundBusy) { return n, err } return afterSync(n, err) } warmEarly(ctx, &warm, &warmOnce, cli, ix) // current is when the poller last found the store unmoved since a // round that succeeded: the index was current then, though no round // ran, because a tick skips a store whose stamp has not moved. var current atomic.Int64 entry.Health = func() api.RepoHealth { s := withCurrent(pipe.Stats(), current.Load()) h := api.RepoHealth{ RoundSeconds: s.LastRound.Seconds(), LastCount: s.LastCount, Total: s.Total, Fallbacks: s.Fallbacks, Gaps: s.Gaps, Stalled: s.Stalled, RetryAt: retryAt(s.RetryAt), LastErr: s.LastErr, Failures: s.Failures, } if !s.LastOK.IsZero() { h.LastOK = s.LastOK.Format(time.RFC3339) } if !s.LastErrAt.IsZero() { h.LastErrAt = s.LastErrAt.Format(time.RFC3339) } return h } rg.fronter.Register(name, path) // Published complete or not at all. rg.deps.Repos.Put(name, entry) // The read gate's cache moves with the repository, not with a tick // after it. // // refreshPrivate has always been called by the writes that change a // repository's VISIBILITY — Update and Delete — and once at the end // of startup. Creation was the gap: a repository that arrived // PRIVATE at runtime was served, and missing from the set the gate // consults, until a restart or an unrelated edit refreshed it. // // The window is not cosmetic. IsPrivate answers false for it, so the // canonical redirect announces the namespace to a stranger — "it is // at /r/<owner>/<name>" — which is precisely the sentence the gate // exists to withhold, and the sync gate reads the same set. The // guard was right and the cache was stale, which is why the code // looked correct while the hole was open. // // Here rather than at each call site because Register is the one // place a repository starts being served: startup, repo.add and the // clone importer all arrive through it, so the property holds by // construction instead of by remembering. rg.refreshPrivate() // Stopping the pipeline too: a round queued for a rebuild slot does // not watch the poller's context, and Unregister waits for the poller // to exit. stop := func() { cancel() pipe.Stop() } done := make(chan struct{}) rg.track(name, &served{ix: ix, stop: stop, done: done}) go rg.poll(ctx, done, name, path, cli, ix, syncIn, indexing, ¤t) return nil } // poll runs the store's initial ingest and then its round loop until the // context is cancelled. // retryAt formats the stall's next attempt, empty when not stalled. func retryAt(t time.Time) string { if t.IsZero() { return "" } return t.UTC().Format(time.RFC3339) } // sync is entry.Sync's round taking an admission (syncIn) — the round // PLUS the generation bump that lets memoised DAG answers know they may // be stale. The poll must not call // the pipeline directly, or those memos would outlive the ingest that // invalidated them. func (rg *registrar) poll(ctx context.Context, done chan struct{}, name, path string, cli *zitcli.Client, ix *index.Index, sync func(ingest.Admit) (int, error), indexing *atomic.Bool, current *atomic.Int64) { defer close(done) // SQLite running out of memory reaches here as a panic from the // driver, and a panic in this goroutine ended the process: one store // too big for its index took every store down (#357). Recovered, the // store stops ingesting and says why; the rest keep serving. defer func() { if r := recover(); r != nil { indexing.Store(false) log.Printf("ingest %s: stopped: %v", name, r) errlog.Default.ReportIn("ingest", "ingest "+name, name, "", fault.Wrap(fmt.Errorf("%v", r), "a store's ingest stopped"). Cost("this store's new check-ins are not indexed until the forge restarts; the store itself is intact and every other store is served"). With("repo", name)) } }() start := time.Now() n, err := sync(func(body func(leave func()) error) error { return rg.ingestLane.DoNamedLeavable(ctx, "first ingest", name, body) }) indexing.Store(false) switch { case errors.Is(err, ingest.ErrStopped): // Removed or shutting down while queued for a rebuild: not a failure. case errors.Is(err, ingest.ErrRoundBusy): // Another round held the store; the first tick retries. case errors.Is(err, work.ErrBusy): // Back-pressure at boot, not a failure: the round loop retries, // and journals only a store refused past ingestShedDeadline. log.Printf("initial ingest of %s deferred: the ingest lane is full", name) case err != nil: log.Printf("initial ingest of %s: %v", name, err) default: log.Printf("ingested %d artifacts from %s (%s) in %s", n, name, path, time.Since(start).Round(time.Second)) } // warmedTip is the version whose listing has already been warmed, // warmingTip whether a warm is in flight. Both belong to this poll // loop: one repository, one warm at a time, and never twice for the // same tip. var warmingTip atomic.Bool var warmedTip atomic.Value warmedTip.Store("") // time.Tick leaks its ticker; a Ticker can be stopped, which matters // now that a repository can be unregistered. tick := time.NewTicker(rg.interval) defer tick.Stop() // A round costs a zit subprocess and one of --ingest-limit lane // slots, and a store nobody has written since the last round has // nothing to ingest. With nineteen stores ticking every two seconds // through a three-wide lane, unconditional rounds kept the lane // saturated and shed the polls that mattered — quarry's own // check-ins went unseen and CI never fired. A stat is free, so the // tick reads the store's stamp and only enters the lane when it // moved. The stamp is taken BEFORE the round: a write that lands // during one is picked up by the next. var ingested storeStamp var shed shedBackoff tipGate := productionBootGate() // spreads the boot tip warm for { select { case <-ctx.Done(): return case <-tick.C: } stamp := stampStore(path) if stamp.ok && stamp == ingested && !retryDue(ix) { current.Store(time.Now().UnixNano()) continue } ran, err := rg.ingestRound(ctx, time.Now(), name, &shed, func(admit ingest.Admit) error { _, serr := sync(admit) return serr }) if !ran { continue // shed or backing off: back-pressure, handled there } if errors.Is(err, ingest.ErrRoundBusy) { // Admitted, but another round held the store: nothing was read, // so the stamp stays unrecorded and the next tick tries again. continue } if err != nil { if ctx.Err() != nil { return } // The stall already announced itself once, with the cause; // repeating it every poll interval buries the log line that // matters under hundreds that do not. if !errors.Is(err, ingest.ErrStalled) { log.Printf("ingest %s: %v", name, err) errlog.Default.ReportIn("ingest", "ingest "+name, name, "", fault.Wrap(err, "a store could not be ingested"). Cost("this store's new check-ins are not searchable or listed; the store itself is intact"). With("repo", name)) } continue } ingested = stamp // Warm the tip's listing so the repo home is never the request // that pays for it: `ls --long` costs ~4ms per file, which is // 8.5s on a 2,198-path tree. The listing is immutable per // version, so it is computed once and reused until the tip moves. // // ONLY when the tip has actually moved, and only one at a time. // This fired on EVERY poll tick as a bare goroutine whose result // was discarded — so on a store where the call takes seconds the // next tick started another before the last finished. Measured // on the demo fleet: 134 concurrent `zit ls --long`, all against // the SAME hash, load average 546 on 14 cores. A listing that is // immutable per version needs computing once per version, and // the memo behind it already knows that; what was missing was // anyone asking whether the work was already in flight. if b, ok, err := ix.TipOf("trunk"); err == nil && ok { if warmedTip.Load() != b.Tip && warmingTip.CompareAndSwap(false, true) { tip := b.Tip go func() { defer warmingTip.Store(false) if !tipGate.wait(ctx) { return } warmCtx := obs.WithReason(context.Background(), obs.ReasonWarm) if _, err := cli.Ls(warmCtx, tip); err == nil { warmedTip.Store(tip) } // The tip's listing above is what the next reader // pays for, so it runs now. The file-history index // is for a later page and waits for a quiet machine. rg.maint.Request(name, "file history", func(mctx context.Context) error { mctx, cancel := context.WithCancel(mctx) defer cancel() defer context.AfterFunc(ctx, cancel)() // The tip as of the run: a task that waited hours // indexes the store's current one. at := tip if b, ok, err := ix.TipOf("trunk"); err == nil && ok { at = b.Tip } return warmFileHistoryCtx(mctx, cli, at, name) }) }() } } rg.afterFold(name, cli, ix) } } // retryDue reports whether the index holds a check-in folded without its // changed files and due a retry (ingest's pending state). The round // that retries it runs even though nobody wrote to the store: on a quiet // repository nothing else would ever run it. One indexed lookup; the // row's backoff is what throttles it. func retryDue(ix *index.Index) bool { due, err := ix.PendingDue(time.Now()) return err == nil && due } // afterFold runs the store's jobs that react to a fold, on the node // holding its lease only. The fold itself runs on every node: each // keeps its own index. func (rg *registrar) afterFold(name string, cli *zitcli.Client, ix *index.Index) { if !rg.jobs.store(name) { return } // CI looks right after a fold, which is the moment a new // check-in becomes visible to quarry whatever brought it in. // A companion store holds no check-ins and has no pipeline // (RFC 0015): nothing to run, and nothing to wake the engine. if rg.engine.Enabled() && !rg.isCompanion(name) && !rg.ciHeld(name) { if err := ci.Trigger(rg.engine, ciStore{db: rg.odb}, name, ciRepo{ix: ix, zit: cli, mirror: rg.isMirror(name)}, rg.ciCloneBase+name); err != nil { log.Printf("ci: %s: %v", name, err) } // A tag added since the last fold (RFC 0020's tag event): after // the check-ins, so a check-in that arrives tagged runs its push // workflows first. if err := ci.TriggerTags(rg.engine, ciStore{db: rg.odb}, name, ciRepo{ix: ix, zit: cli}, rg.ciCloneBase+name); err != nil { log.Printf("ci: %s tags: %v", name, err) } } // The sweeps below write to the store (a verdict tag, a close, a // landing record). On legal hold they are skipped, silently, and run // again on the first fold after the lift. if rg.legallyHeld(name) { return } rg.gateSweep(name, ix) rg.carryForward(name, ix) rg.landingSweep(name, ix) rg.closeSweep(name, ix) rg.gitMirrorKick(name) rg.fossilMirrorKick(name) } // drainDeferred releases check-ins waiting for a worker slot on the // stores this node runs jobs for. The fold's ci.Trigger drains only // when a store changes, so on a quiet repository a wait outlived the // room that ended it (quarry#296); this runs on a timer instead. Which // repositories wait is one query on the OLTP table, so a tick costs // nothing for the ones that have none. func (rg *registrar) drainDeferred() { if rg.odb == nil || !rg.engine.Enabled() { return } repos, err := rg.odb.CIDeferredRepos() if err != nil { log.Printf("ci: deferred list: %v", err) return } for _, name := range repos { if !rg.jobs.store(name) || rg.isCompanion(name) || rg.ciHeld(name) { continue } var cr ci.Repo if rg.drainRepo != nil { var ok bool if cr, ok = rg.drainRepo(name); !ok { continue } } else { repo, ok := rg.deps.Repos.Get(name) if !ok || repo.Zit == nil || repo.Index == nil { continue } cr = ciRepo{ix: repo.Index, zit: repo.Zit} } ci.Drain(rg.engine, ciStore{db: rg.odb}, name, cr, rg.ciCloneBase+name) } } // landingSweep runs after every fold. It keeps every open landing's // merge tested (pairSweep), and tells the accepters of each landing this // fold OPENED that it is waiting on them: a landing opened by push, // which is every one zit opens, never passes through landing.open. func (rg *registrar) landingSweep(name string, ix *index.Index) { if rg.deps == nil || ix == nil { return } // Taken before the open landings are read: a merge run recorded // after it may be one whose landing the read below does not show. asOf := time.Now() open, err := ix.Landings("open", openLandingsMax) if err != nil { return } rg.landingsMu.Lock() if rg.openLandings == nil { rg.openLandings = map[string]map[string]string{} } if rg.orphansSwept == nil { rg.orphansSwept = map[string]bool{} } swept := rg.orphansSwept[name] if rg.landingTargets == nil { rg.landingTargets = map[string]map[string]string{} } seen, seeded := rg.openLandings[name] targets := rg.landingTargets[name] if !seeded || targets == nil { targets = map[string]string{} rg.landingTargets[name] = targets } if !seeded { seen = map[string]string{} for _, l := range open { seen[l.ID], targets[l.ID] = l.Branch, l.Target } rg.openLandings[name] = seen rg.landingsMu.Unlock() rg.sweepOrphans(name, ix, open, asOf, swept) rg.pairSweep(name, ix, open, nil) return } var fresh []index.LandingSummary opening := map[string]bool{} var retargeted []index.LandingSummary stillOpen := map[string]bool{} openBranch := map[string]bool{} for _, l := range open { stillOpen[l.ID], openBranch[l.Branch] = true, true if _, ok := seen[l.ID]; !ok { seen[l.ID], targets[l.ID] = l.Branch, l.Target fresh = append(fresh, l) opening[l.ID] = true } else if was, ok := targets[l.ID]; ok && was != l.Target { // Aimed at another target without a push: its merge runs // tested the old pair. It is tested as a landing opening is. targets[l.ID] = l.Target retargeted = append(retargeted, l) opening[l.ID] = true } else if !ok { targets[l.ID] = l.Target } } var closed []string for id, branch := range seen { if stillOpen[id] { continue } delete(seen, id) delete(targets, id) // A landing superseded by a newer one on the same branch is // closed, but its branch's merge is the newer one's to finish. if !openBranch[branch] { closed = append(closed, branch) } } rg.landingsMu.Unlock() rg.sweepOrphans(name, ix, open, asOf, swept) for _, l := range retargeted { rg.cancelOldPairs(name, ix, l) } rg.pairSweep(name, ix, open, opening) for _, l := range fresh { rg.deps.NotifyOpenedLanding(name, l) } for _, branch := range closed { rg.cancelClosedPairs(name, ix, branch) } } // cancelClosedPairs stops a closed landing's merge runs that are still // going. Accepted or rejected, the landing is decided: a verdict on its // merge answers nobody, and the runs hold runner slots that the check-in // the accept wrote is waiting for. Only the runs the landing sweep // started are the landing's (subject pair); a merge a push ran is the // push's (push-pair, RFC 0009 §once), its tip's verdict, and stays, as // does a run whose labels the engine cannot show. Best-effort: a run // that finishes in the race is simply done. // // If the tip is then left with nothing that passed, failed or is still // going, it is tested as itself: a branch is never left with no verdict. func (rg *registrar) cancelClosedPairs(name string, ix *index.Index, branch string) { if !rg.engine.Enabled() || rg.odb == nil { return } tip, err := ix.BranchTip(branch) if err != nil || tip == "" { return } runs, err := rg.odb.UnfinishedCIRuns() if err != nil { return } prefix := "pair:" + tip + ":" cancelled := map[string]bool{} for _, r := range runs { if r.Repo != name || !strings.HasPrefix(r.Pair, prefix) { continue } if run, err := rg.engine.Status(r.RunID); err != nil || run.Labels["subject"] != "pair" { continue } if err := rg.engine.Cancel(r.RunID); err != nil { log.Printf("ci: %s: cancelling %s's merge run %s: %v", name, branch, r.RunID, err) continue } cancelled[r.RunID] = true log.Printf("ci: %s: %s's landing closed; cancelled its merge run %s", name, branch, r.RunID) } rg.testClosedTip(name, ix, branch, tip, cancelled) } // testClosedTip tests a closed landing's branch tip as itself when // nothing passed, failed or is still going for it but the runs just // cancelled: a branch is never left with no verdict. func (rg *registrar) testClosedTip(name string, ix *index.Index, branch, tip string, cancelled map[string]bool) { if rg.tipAnswered(name, tip, cancelled) || rg.deps == nil { return } repo, ok := rg.deps.Repos.Get(name) if !ok || repo.Zit == nil { return } if err := ci.RunTip(rg.engine, ciStore{db: rg.odb}, name, ciRepo{ix: ix, zit: repo.Zit}, rg.ciCloneBase+name, ci.Checkin{Hash: tip, Branch: branch}); err != nil { log.Printf("ci: %s: testing %s's tip %.12s after its landing closed: %v", name, branch, tip, err) } } // openLandingsMax is how many open landings a sweep reads. const openLandingsMax = 500 // sweepOrphans runs cancelOrphanPairs until it has completed once for // the repository. func (rg *registrar) sweepOrphans(name string, ix *index.Index, open []index.LandingSummary, asOf time.Time, swept bool) { if swept || !rg.cancelOrphanPairs(name, ix, ix, open, asOf) { return } rg.landingsMu.Lock() rg.orphansSwept[name] = true rg.landingsMu.Unlock() } // tipReader is what cancelOrphanPairs reads of the index. type tipReader interface { BranchTip(branch string) (string, error) BranchOf(hashes []string) (map[string]string, error) } // cancelOrphanPairs is cancelClosedPairs for the landings that closed // while no process was watching (#494). The open set is this process's // memory, so a landing accepted or rejected across a restart is never // seen to close, and its merge runs stayed queued at the engine, which // hands out the oldest work first. Once per process, every unfinished // merge run of the landing sweep's (subject pair) whose branch tip no // open landing has is stopped. A tip its branch still ends at is then // tested as itself, as cancelClosedPairs does. // // A wrong cancel cannot be undone (pairSweep never restarts a tip that // has a cancelled merge), so the pass cancels nothing unless it read // everything: any read error, a list of open landings at its cap, or a // held repository ends it with false, to be tried again. Only runs // recorded before asOf, taken before open was read, are candidates: one // started since may be for a landing open does not show. func (rg *registrar) cancelOrphanPairs(name string, ix *index.Index, tips tipReader, open []index.LandingSummary, asOf time.Time) bool { if !rg.engine.Enabled() || rg.odb == nil { return true } if rg.ciHeld(name) { return false } if len(open) >= openLandingsMax { log.Printf("ci: %s: %d open landings or more; merge runs of closed landings are not looked for", name, openLandingsMax) return false } owned := map[string]bool{} for _, l := range open { tip, err := tips.BranchTip(l.Branch) if err != nil || tip == "" { log.Printf("ci: %s: looking for merge runs of closed landings: tip of %s: %v; tried again later", name, l.Branch, err) return false } owned[tip] = true } runs, err := rg.odb.UnfinishedCIRuns() if err != nil { log.Printf("ci: %s: looking for merge runs of closed landings: %v; tried again later", name, err) return false } before := asOf.UTC().Truncate(time.Second) orphans := map[string][]string{} // branch tip -> run ids for _, r := range runs { rest, ok := strings.CutPrefix(r.Pair, "pair:") tip, _, _ := strings.Cut(rest, ":") if r.Repo != name || !ok || tip == "" || owned[tip] { continue } // Recorded at second precision: a run of asOf's own second may // be newer than the read, and is kept. if t, err := time.Parse(time.RFC3339, r.Started); err != nil || !t.Before(before) { continue } orphans[tip] = append(orphans[tip], r.RunID) } if len(orphans) == 0 { return true } hashes := make([]string, 0, len(orphans)) for tip := range orphans { hashes = append(hashes, tip) } branchOf, err := tips.BranchOf(hashes) if err != nil { log.Printf("ci: %s: looking for merge runs of closed landings: %v; tried again later", name, err) return false } ends := map[string]string{} // branch tip -> its branch, when the branch still ends there for tip := range orphans { if b := branchOf[tip]; b != "" { now, err := tips.BranchTip(b) if err != nil { log.Printf("ci: %s: looking for merge runs of closed landings: tip of %s: %v; tried again later", name, b, err) return false } if now == tip { ends[tip] = b } } } complete := true for tip, ids := range orphans { cancelled := map[string]bool{} for _, id := range ids { run, err := rg.engine.Status(id) if err != nil { complete = false // asked again on a later pass continue } if run.Labels["subject"] != "pair" { continue } if err := rg.engine.Cancel(id); err != nil { complete = false log.Printf("ci: %s: cancelling orphaned merge run %s: %v", name, id, err) continue } cancelled[id] = true log.Printf("ci: %s: no open landing has %.12s; cancelled its merge run %s", name, tip, id) } if b := ends[tip]; b != "" && len(cancelled) > 0 { rg.testClosedTip(name, ix, b, tip, cancelled) } } return complete } // cancelOldPairs stops a retargeted landing's merge runs that are still // going against any pair but the one it now has: they judge a merge // that is no longer the one that lands. Only the landing's own runs // (subject pair); the starting of the new pair's runs is pairSweep's, // the same path a landing opening takes. Best-effort. func (rg *registrar) cancelOldPairs(name string, ix *index.Index, l index.LandingSummary) { if !rg.engine.Enabled() || rg.odb == nil { return } tip, _ := ix.BranchTip(l.Branch) target, _ := ix.BranchTip(l.Target) if tip == "" { return } runs, err := rg.odb.UnfinishedCIRuns() if err != nil { return } current := ci.Pair(tip, target) for _, r := range runs { if r.Repo != name || !strings.HasPrefix(r.Pair, "pair:"+tip+":") || r.Pair == current { continue } if run, err := rg.engine.Status(r.RunID); err != nil || run.Labels["subject"] != "pair" { continue } if err := rg.engine.Cancel(r.RunID); err != nil { log.Printf("ci: %s: cancelling %s's old merge run %s: %v", name, l.Branch, r.RunID, err) continue } log.Printf("ci: %s: landing retargeted onto %s; cancelled its merge run %s", name, l.Target, r.RunID) } } // tipAnswered reports whether a branch tip has a verdict, or one on its // way: a run of the tip or of a merge of it that passed, failed or is // still going, other than the runs just cancelled. func (rg *registrar) tipAnswered(name, tip string, cancelled map[string]bool) bool { own, err := rg.odb.CIRunsFor(name, tip) if err != nil { return true // cannot tell: starting more is the worse mistake } merges, err := rg.odb.CIRunsForTip(name, tip) if err != nil { return true } for _, r := range append(own, merges...) { if cancelled[r.RunID] { continue } switch { case (ci.Run{Status: r.Status}).Passed(), r.Status == "failed", !ciTerminalStatus(r.Status) && r.Status != "deferred": return true } } return false } // pairSweep keeps each open landing tested as the merge with its // target, as a pull request's checks run on its test merge (quarry#290): // a branch tip with no pair yet is merged into the target as it is and // tested. A target that moves re-runs nothing, as it re-runs nothing on // a pull request; the landing says which target tip its checks tested, // and the next push to the branch tests the merge with the target as // it is then. // // A landing opening (opening holds its id) over a tip a push already // tested as a merge (RFC 0009 §once) runs what that merge has no // verdict for, when the target tip is the same: the landing-only // pipelines, and any run that errored or was cancelled. Against a // target that has moved since, the merge is a new one and runs whole. func (rg *registrar) pairSweep(name string, ix *index.Index, open []index.LandingSummary, opening map[string]bool) { if !rg.engine.Enabled() || rg.odb == nil || rg.deps == nil || rg.ciHeld(name) { return } repo, ok := rg.deps.Repos.Get(name) if !ok || repo.Zit == nil { return } st, cr := ciStore{db: rg.odb}, ciRepo{ix: ix, zit: repo.Zit} for _, l := range open { if l.SupersededBy != "" { continue } tip, err := ix.BranchTip(l.Branch) if err != nil || tip == "" { continue } if _, none := rg.pipelineless.Load(name + "\x00" + tip); none { continue } // Any merge of the tip, cancelled ones included: a merge somebody // cancelled is not started again on every sweep. if tried, err := rg.odb.CIRunsForTip(name, tip); err != nil || (len(tried) > 0 && !opening[l.ID]) { continue } target, err := ix.BranchTip(l.Target) if err != nil || target == "" { continue } ran, err := ci.RunPairAt(rg.engine, st, name, cr, rg.ciCloneBase+name, l.Branch, tip, target) if err != nil { log.Printf("ci: %s: landing %.12s: merge of %.12s into %.12s: %v", name, l.ID, tip, target, err) continue } if !ran { rg.pipelineless.Store(name+"\x00"+tip, struct{}{}) } } } // gateSweep is the bypass tripwire (RFC 0007): a protected branch that // moved without a forge accept behind it is named, loudly, within a // poll tick — because a stock zit client can accept against the store // and the store cannot refuse it; noticing is the forge's half. func (rg *registrar) gateSweep(name string, ix *index.Index) { if rg.odb == nil { return } rules, err := rg.odb.Protections(name) if err != nil { return } for _, rule := range rules { if strings.ContainsAny(rule.Branch, "*?[") { continue // a glob names no single tip to watch; a rung for later } b, ok, err := ix.TipOf(rule.Branch) if err != nil || !ok { continue } watch, seen := rg.odb.GateWatch(name, rule.Branch) if !seen { // First sight: baseline at the tip. Retroactively flagging // history would bury the signal under old noise. _ = rg.odb.SetGateWatch(name, rule.Branch, b.Tip) continue } if watch == b.Tip { continue } fresh, err := ix.CheckinsAfter(watch, 50) if err != nil { // An unknown watermark waits for the index (a reindex part-way // through); said every round, so one that never resolves shows. log.Printf("gate: %s %s: %v", name, rule.Branch, err) continue } held := false for _, e := range fresh { if e.Branch != rule.Branch { continue } key := name + "\x00" + e.Hash if ok, _ := rg.odb.ForgeAccepted(name, e.Hash); ok { rg.gateSeen.Delete(key) continue } first, _ := rg.gateSeen.LoadOrStore(key, rg.now()) if rg.now().Sub(first.(time.Time)) < rg.grace() { held = true continue } rg.gateSeen.Delete(key) if err := rg.odb.AddGateBypass(name, rule.Branch, e.Hash, e.User); err == nil { log.Printf("gate: %s %s moved past its checks at %.12s by %s — no forge accept behind it", name, rule.Branch, e.Hash, e.User) } } if held { // Leave the watch where it is so the held check-in is looked // at again, and look again once the grace is up even if // nothing else is written to this store meanwhile. if _, busy := rg.gateRecheck.LoadOrStore(name, struct{}{}); !busy { time.AfterFunc(rg.grace()+time.Second, func() { rg.gateRecheck.Delete(name) if rg.jobs.store(name) { rg.gateSweep(name, ix) } }) } continue } _ = rg.odb.SetGateWatch(name, rule.Branch, b.Tip) } } func (rg *registrar) now() time.Time { if rg.clock != nil { return rg.clock() } return time.Now() } func (rg *registrar) grace() time.Duration { if rg.gateGrace > 0 { return rg.gateGrace } return time.Minute } // carryForward writes a premerge pair's verdict onto the merge // check-in an accept created from that pair (RFC 0009 §premerge): the // portable record says this merge was tested before it existed. Runs // after every fold; a merge already carrying a verdict is skipped, so // the write happens once. func (rg *registrar) carryForward(name string, ix *index.Index) { switch rg.odb.CITagsMode(name) { case "off": return case "on": default: if !rg.ciTagsDefault { return } } repo, ok := rg.deps.Repos.Get(name) if !ok || repo.Index == nil { return } landed, err := ix.Landings("accepted", 10) if err != nil { return } ids := make([]string, 0, len(landed)) for _, l := range landed { ids = append(ids, l.ID) } merges, err := ix.MergesForLandings(ids) if err != nil { return } for _, l := range landed { m := merges[l.ID] if m.Checkin == "" { continue } key := name + "\x00" + m.Checkin if v, verr := ix.VerdictOf(m.Checkin); verr != nil || v != "" { if v != "" { rg.carried.Delete(key) } continue } // Written on an earlier pass whose ingest failed: the tag is in // the store and the index has not caught up. The tag log is // append-only, so writing again would mint a second verdict. if _, written := rg.carried.Load(key); written { continue } parents, perr := ix.ParentsOf(m.Checkin) if perr != nil || len(parents) != 2 { continue } // The tested pair was branchTip:targetTip; parent order is not // recorded, so ask both spellings. verdict := rg.deps.PairVerdict(name, "pair:"+parents[0]+":"+parents[1], l.Target) if verdict == "" { verdict = rg.deps.PairVerdict(name, "pair:"+parents[1]+":"+parents[0], l.Target) } if verdict == "" { continue } // After a restart nothing is remembered and the index may still // be behind: the store is asked before a second verdict is minted. if repo.Zit != nil { if tags, terr := repo.Zit.ActiveTags(context.Background(), m.Checkin); terr == nil { _, pass := tags["ci-pass"] _, fail := tags["ci-fail"] if pass || fail { rg.carried.Store(key, struct{}{}) continue } } } err := repo.WriteTag(verdict, m.Checkin, "premerge") if err != nil && !errors.Is(err, api.ErrTagNotIndexed) { log.Printf("ci: carry-forward %s %.12s: %v", name, m.Checkin, err) continue } rg.carried.Store(key, struct{}{}) if err != nil { log.Printf("ci: %s %.12s %s (carried from premerge) written, index lags: %v", name, m.Checkin, verdict, err) continue } log.Printf("ci: %s %.12s %s (carried from premerge)", name, m.Checkin, verdict) } } // TriggerCI launches a repository's pipelines at a check-in — the // re-run path (RFC 0009 §triggers). Empty checkin means the tip; by is // who asked, the runs' starter. func (rg *registrar) TriggerCI(name, checkin, by string) error { if !rg.engine.Enabled() { return fmt.Errorf("no CI engine configured") } if rg.isCompanion(name) { return fmt.Errorf("%s is a forum store and has no CI", name) } if rg.ciHeld(name) { return fmt.Errorf("%s is unavailable for legal reasons and runs no CI: %w", name, ops.ErrForbidden) } repo, ok := rg.deps.Repos.Get(name) if !ok || repo.Index == nil || repo.Zit == nil { return fmt.Errorf("no repository %q", name) } return ci.RunAt(rg.engine, ciStore{db: rg.odb}, name, ciRepo{ix: repo.Index, zit: repo.Zit}, rg.ciCloneBase+name, checkin, by) } // TriggerPairCI re-runs every pipeline on a landing's merge // (ci.RerunPairAt): the Re-run on a landing and on a merge run's page. func (rg *registrar) TriggerPairCI(name, branch, branchTip, targetTip string) error { if !rg.engine.Enabled() { return fmt.Errorf("no CI engine configured") } if rg.ciHeld(name) { return fmt.Errorf("%s is unavailable for legal reasons and runs no CI: %w", name, ops.ErrForbidden) } repo, ok := rg.deps.Repos.Get(name) if !ok || repo.Index == nil || repo.Zit == nil { return fmt.Errorf("no repository %q", name) } return ci.RerunPairAt(rg.engine, ciStore{db: rg.odb}, name, ciRepo{ix: repo.Index, zit: repo.Zit}, rg.ciCloneBase+name, branch, branchTip, targetTip) } // FireSchedules launches every repository's scheduled workflows due in // minutes (quarry owns schedules: RFC 0019, RFC 0021 §runs). lead is // the fleet lease, asked again before every claim. Skipped: // companions, repositories under a takedown, repositories whose admin // said no to CI, and repositories no runner serves. func (rg *registrar) FireSchedules(minutes []time.Time, lead func() bool) { if !rg.engine.Enabled() || rg.odb == nil || len(minutes) == 0 { return } workers, werr := rg.engine.Workers() names := rg.deps.Repos.Names() rg.schedules.Retain(names) for _, name := range names { if !lead() { return } repo, ok := rg.deps.Repos.Get(name) if !ok || repo.Index == nil || repo.Zit == nil || rg.isCompanion(name) || rg.ciHeld(name) { continue } if who, _ := rg.odb.CIDeclined(name); who != "" { continue } if werr == nil && !ci.RunnerFor(workers, name, time.Now()) { continue } if err := ci.FireSchedules(rg.engine, ciStore{db: rg.odb}, rg.schedules, name, ciRepo{ix: repo.Index, zit: repo.Zit}, rg.ciCloneBase+name, minutes, lead); err != nil { log.Printf("ci: %s schedules: %v", name, err) } } } // CISchedules lists a repository's scheduled workflows from the cache // the scheduler reads, each with its next fire or why it does not, and // its last failed minute. func (rg *registrar) CISchedules(name string) ([]ci.Scheduled, error) { repo, ok := rg.deps.Repos.Get(name) if !ok || repo.Index == nil || repo.Zit == nil { return nil, fmt.Errorf("no repository %q", name) } out, err := rg.schedules.Schedules(name, ciRepo{ix: repo.Index, zit: repo.Zit}, time.Now()) if err != nil || rg.odb == nil { return out, err } for i := range out { out[i].LastFailure, out[i].LastFailureAt = rg.odb.LastScheduleFailure(name, out[i].Pipeline) } return out, nil } // isCompanion answers whether a store is some repository's forum // (RFC 0015). Without an OLTP nothing is a companion. func (rg *registrar) isCompanion(name string) bool { if rg.odb == nil { return false } _, _, ok, err := rg.odb.CompanionParent(name) return err == nil && ok } // codeOr is name's project code as the forge holds it now, or fallback. func (rg *registrar) codeOr(name, fallback string) string { rg.codeMu.Lock() defer rg.codeMu.Unlock() if c, ok := rg.codes[name]; ok && c != "" { return c } return fallback } // knownCode is name's project code as registration holds it in memory, // for xfer.Fronter.SetProjectCode: what a refused clone is told, as // Fossil's server tells it. Nothing is run to answer it. func (rg *registrar) knownCode(name string) (string, bool) { c := rg.codeOr(name, "") return c, c != "" } // refreshCode re-reads a served store's project code and makes every // holder of it say what the store says: the codes map (which feeds the // sync secret and the push guard), the registry entry's Code and the // repository's row, which is also how a claim that did not come true is // given back. The chat channel and the lease are not keyed by the code, // so adopting one moves neither. A // *Repo is immutable once published, so the entry is replaced by a copy. // Called on the request that adopted the code, before its reply, so the // pusher's next request is judged by the new code. // // A store that cannot be read now is read again shortly, and a push whose // login verifies under the code the row records heals it too (xfer's // judgeAdoption). It reports whether the store was read. func (rg *registrar) refreshCode(name, path string) bool { code, err := xfer.ProjectCode(path) if err != nil { log.Printf("adopt %s: project code: %v", name, err) rg.retryRefresh(name, path) return false } rg.codeMu.Lock() old, had := rg.codes[name] if had { rg.codes[name] = code } rg.codeMu.Unlock() if !had { return true } if rg.odb != nil { if err := rg.odb.SetRepoCode(name, code); err != nil { log.Printf("adopt %s: recording its project code: %v", name, err) } } if old == code { return true } if repo, ok := rg.deps.Repos.Get(name); ok { rg.deps.Repos.Put(name, repo.WithCode(code)) } log.Printf("adopt %s: project code is now %.12s (was %.12s)", name, code, old) return true } // retryRefresh reads the store again after a pause, a few times, so a // failure to read it once does not leave the old code in every cache. // At most one is pending per repository, and it ends by itself. func (rg *registrar) retryRefresh(name, path string) { if _, busy := rg.refreshing.LoadOrStore(name, true); busy { return } go func() { defer rg.refreshing.Delete(name) pause := time.Second for i := 0; i < 6; i++ { time.Sleep(pause) pause *= 2 if _, err := xfer.ProjectCode(path); err == nil { rg.refreshing.Delete(name) rg.refreshCode(name, path) return } } log.Printf("adopt %s: its project code could not be read again; the next push that names it heals it", name) }() } // backfillCodes records, for every Ready repository whose row has no // project code, the one its store has. Register records it for what it // serves; this reaches the rest, so no Ready row stays a possible holder // of a code nobody can name. func (rg *registrar) backfillCodes() { if rg.odb == nil { return } rows, err := rg.odb.ReadyWithoutCode() if err != nil { log.Printf("backfill project codes: %v", err) return } for name, path := range rows { code, err := xfer.ProjectCode(path) if err != nil { log.Printf("backfill project code of %s: %v", name, err) continue } if err := rg.odb.SetRepoCode(name, code); err != nil { log.Printf("backfill project code of %s: %v", name, err) } } } // repoLeaseKey is the single-writer lease key of the repository name: // its registry key, which is the same on every node and on every path // that writes (Register's guard, a proxied push, the job gate), and // which no rename changes. The lease serialises writers to one store, // and a repository has exactly one; two repositories of one project // hold the same project code and different stores, so the code is not // a key. A hash, so it is one safe token whatever the name holds. func repoLeaseKey(name string) string { sum := sha256.Sum256([]byte(name)) return "lease-" + hex.EncodeToString(sum[:16]) } // chatKeyOf is the key of name's chat channel: the one its row holds, // assigned the first time the repository is registered. A repository // with no row to keep it in gets the key its name derives, which is // the same one a later row is given. func (rg *registrar) chatKeyOf(name string) string { key := chat.RepoKey(name) if rg.odb == nil { return key } held, err := rg.odb.AssignChatKey(name, key) if err != nil { log.Printf("register %s: its chat key: %v", name, err) return key } if held == "" { return key } return held } // guardPush runs a proxied push under the repository's lease. The proxied sync is written by xfer's own zit process, // not through zitcli, so there is no call to hand the token to; the // lease is still held for its whole length. func (rg *registrar) guardPush(repo string, proxy func() error) error { rg.codeMu.Lock() _, ok := rg.codes[repo] rg.codeMu.Unlock() if !ok { return fmt.Errorf("unknown repo %q", repo) } // RFC 0023: a legal hold refuses writes "for everybody", a site admin // person included, whom the read gate admits. A disabled repository's // admins still push. if rg.legallyHeld(repo) { return errWriteHeld } return rg.leases.Guard(repoLeaseKey(repo), func(lease.Token) error { return proxy() }) } // adoption is what the sync front is given to let an empty repository // take the project code of the first project pushed into it. pathOf // finds a repository's store. func (rg *registrar) adoption(pathOf func(repo string) (string, bool)) *xfer.Adoption { return &xfer.Adoption{ Code: func(repo string) (string, bool) { rg.codeMu.Lock() defer rg.codeMu.Unlock() c, ok := rg.codes[repo] return c, ok }, // The index, not the store: nothing is run to decide it. An index // still folding, or one that cannot be read, is not "empty". Empty: func(repo string) bool { e, ok := rg.deps.Repos.Get(repo) if !ok || e.Index == nil || (e.Indexing != nil && e.Indexing()) { return false } n, err := e.Index.CheckinCount() return err == nil && n == 0 }, Recorded: func(repo string) string { if rg.odb == nil { return "" } c, _ := rg.odb.RepoCode(repo) return c }, Claim: rg.claimCode, Adopted: func(repo string) bool { path, ok := pathOf(repo) return ok && rg.refreshCode(repo, path) }, } } // claimCode gives name a project code no other repository has. Every // repository served here is compared in memory (that includes those the // command line names, which have no row), then the claim is made in the // registry in one statement against every row. Anything that cannot be // shown unused is refused. func (rg *registrar) claimCode(name, code string) xfer.Claim { if rg.odb == nil { return xfer.ClaimUnsure } rg.codeMu.Lock() for other, c := range rg.codes { if other != name && c == code { rg.codeMu.Unlock() return xfer.ClaimTaken } } rg.codeMu.Unlock() got, err := rg.odb.ClaimProjectCode(name, code) if err != nil { log.Printf("adopt %s: claiming a project code: %v", name, err) return xfer.ClaimUnsure } switch got { case oltp.CodeClaimed: return xfer.ClaimOK case oltp.CodeTaken: return xfer.ClaimTaken } return xfer.ClaimUnsure } // Unregister stops serving a repository and releases what it held. // // Order matters: drop it from the registry FIRST so no new request can // find it, then stop the poll loop and wait for it to exit, then close // the index. Closing while a fold is mid-transaction is how a "removed" // repository takes the process down with it. func (rg *registrar) Unregister(name string) error { if _, ok := rg.deps.Repos.Get(name); !ok { return fmt.Errorf("no repository %q: %w", name, ops.ErrNotFound) } rg.deps.Repos.Delete(name) rg.fronter.Unregister(name) // Upkeep queued or running for this store ends before its index closes. rg.maint.Forget(name) rg.mu.Lock() s := rg.running[name] delete(rg.running, name) if rg.ingestLane != nil { rg.ingestLane.SetQueue(len(rg.running) + 1) } rg.mu.Unlock() if s != nil { s.stop() <-s.done // Again, now the store's rounds have ended: a round that was in // flight at the first Forget may have queued line counts or a // warm since, which must not run against the index closing here // nor bring the removed store's rows back to the page. rg.maint.Forget(name) s.ix.Close() } rg.codeMu.Lock() delete(rg.codes, name) rg.codeMu.Unlock() return nil } // Add creates or adopts a repository, records it, and starts serving it. // // The order is deliberate: make the store, then persist, then serve. A // recorded repository that failed to open is visible and fixable; one // that serves without being recorded vanishes at the next restart and // leaves no trace of why. func (rg *registrar) Add(spec api.RepoSpec) (string, string, error) { if rg.odb == nil { return "", "", fmt.Errorf("no forge database: %w", ops.ErrUnavailable) } // One create at a time, from the name check to the name being taken: // the check reads addresses a concurrent create could take between // the two, and an address seen through a private team has no index // to refuse it. rg.createMu.Lock() defer rg.createMu.Unlock() // spec.Name arrives as the name asked for, which becomes the handle // within the namespace (RFC 0025); from here on it is the key, which // is the name unless something else holds that key. asked is the // request as it came, for an import that stops to ask its owner. asked := spec handle := spec.Name if err := rg.nameRefusal(spec.Namespace, handle, spec.Author); err != nil { return "", "", err } if err := rg.retryFailedImport(spec); err != nil { return "", "", err } key, err := rg.keyFor(handle) if err != nil { return "", "", err } spec.Name = key if err := rg.refuseInheritedTokens(spec.Name); err != nil { return "", "", err } // The quota is per ACCOUNT, not per request: a site admin runs the // forge's capacity and is never limited, so this only ever refuses // someone who has hit their own ceiling. // // Counted against the DEED HOLDER: an agent's repository is deeded // to its operator (claim, below), so the operator's allowance is // the one it draws on, and an agent is never a site admin. if owner := rg.deedHolder(spec.Author); owner != "" { if acct, ok := rg.odb.AccountByName(owner); !ok || !acct.Admin { n, err := rg.odb.OwnedRepoCount(owner) if err != nil { return "", "", err } if n >= rg.repoQuota { return "", "", fmt.Errorf("%w: %s already owns %d repositories, "+ "the most this forge allows", ops.ErrInvalid, owner, rg.repoQuota) } } } if spec.Path == "" { if rg.reposRoot == "" { return "", "", fmt.Errorf("%w: this node has no repositories root, so path is required "+ "(start it with --repos-root DIR)", ops.ErrInvalid) } if !spec.Create && spec.Clone == "" { return "", "", fmt.Errorf("%w: path is required when adopting an existing store", ops.ErrInvalid) } spec.Path = filepath.Join(rg.reposRoot, spec.Name) } // Making a store is the one step that leaves something behind if a // later one fails, so it is undone explicitly rather than left for // an operator to find. made := false switch { case spec.Create: if err := rg.mustBeEmpty(spec.Path); err != nil { return "", "", err } if err := zitcli.Init(context.Background(), spec.Path); err != nil { return "", "", fmt.Errorf("%w: %v", ops.ErrInvalid, err) } made = true // Seeded BEFORE the repository is registered, so the ingest // round that follows registration sees the first check-in // already there rather than racing it. if files := seedFiles(handle, spec.Description, spec.License, spec.Ignore); spec.Readme || spec.License != "" || spec.Ignore { if !spec.Readme { delete(files, "README.md") } if err := zitcli.SeedFiles(context.Background(), spec.Path, spec.Author, "Initial check-in", files); err != nil { os.RemoveAll(spec.Path) return "", "", fmt.Errorf("%w: %v", ops.ErrInvalid, err) } } case spec.Clone != "": if err := rg.mustBeEmpty(spec.Path); err != nil { return "", "", err } // An import is REGISTERED FIRST and copied afterwards. Cloning // inline meant the repository did not exist anywhere until the // last byte arrived: no row, no page, no progress, and an // operator watching the fleet saw nothing at all for the // minutes a large repository takes. Now the row is written // immediately in state Cloning, this call returns, and the copy // runs behind it — so the repository can be looked at while it // fills, and a failure has somewhere to be reported. if err := rg.odb.AddImportingRepo(spec.Name, spec.Path, spec.Description, spec.Visibility, spec.Clone); err != nil { return "", "", fmt.Errorf("%w: %v", ops.ErrInvalid, err) } if err := rg.settle(spec, handle); err != nil { return "", "", err } if spec.Mirror { rg.recordMirror(spec) } go rg.importClone(spec, asked) return spec.Name, spec.Path, nil } undo := func() { if made { os.RemoveAll(spec.Path) } } if err := rg.odb.AddRepo(spec.Name, spec.Path, spec.Description, spec.Visibility); err != nil { undo() return "", "", fmt.Errorf("%w: %v", ops.ErrInvalid, err) } if err := rg.settle(spec, handle); err != nil { undo() return "", "", err } if err := rg.Register(spec.Name, spec.Path); err != nil { if derr := rg.odb.DeleteRepo(spec.Name); derr != nil { log.Printf("repo.add %s: rollback failed: %v", spec.Name, derr) } undo() return "", "", err } if spec.Mirror && spec.Clone != "" { rg.recordMirror(spec) } return spec.Name, spec.Path, nil } // nameRefusal is nil when author may create a repository called handle // in namespace (a team; "" for their own), and otherwise why not. Add // asks it first, and the new-repository form asks it as the name is // typed (NameFree), so the two cannot disagree. // // A handle is unique within its namespace and nowhere else (RFC 0025). // The rules that kept a repository's name apart from accounts, teams and // the forge's own routes protect the KEY, which can be a path's first // segment; they are keyFor's, and a name that breaks them gets a minted // key instead of a refusal. func (rg *registrar) nameRefusal(namespace, handle, author string) error { // The name is validated BEFORE it is joined to a path, because that // is the only thing standing between a name and the filesystem. if !oltp.RepoName.MatchString(handle) { return fmt.Errorf("%w: repository name %q: use letters, digits, dot, dash, underscore", ops.ErrInvalid, handle) } if rg.odb == nil { return nil } // Flat (RFC 0025): one person, no namespaces, so a name is unique // across the node, and there is no team to make it in. if rg.flatNames { if namespace != "" { return fmt.Errorf("%w: this node names repositories without namespaces", ops.ErrInvalid) } keys, err := rg.odb.KeysNamed(handle) if err != nil { return err } for _, key := range keys { if row, found, _ := rg.odb.RepoByName(key); found && row.State == oltp.Failed && rg.failedImportOf(key, author) { continue } return fmt.Errorf("%w: repository %q already exists", ops.ErrInvalid, handle) } return nil } for _, ns := range rg.targets(namespace, author) { taken, err := rg.addressTaken(ns, handle, author) if err != nil { return err } if taken { where := ns if where == "" { where = "this forge" } return fmt.Errorf("%w: %s already has a repository called %s", ops.ErrInvalid, where, handle) } } return nil } // targets are the namespaces a new repository of author's in namespace // would appear under: where it is placed, and, while that is a private // team, its owner's, which is where readers see it (placeOf). func (rg *registrar) targets(namespace, author string) []string { owner := rg.deedHolder(author) if namespace == "" || namespace == owner { return []string{oltp.HomeNamespace(owner)} } out := []string{namespace} if t, ok := rg.odb.TeamByName(namespace); ok && t.Private { out = append(out, owner) } return out } // addressTaken says whether a repository already appears at ns/handle, // as it is stored or as readers see it, other than a failed import of // author's own, which gives way to them (retryFailedImport). func (rg *registrar) addressTaken(ns, handle, author string) (bool, error) { keys, err := rg.odb.KeysNamed(handle) if err != nil { return false, err } shown := addressesOf(rg.odb) for _, key := range keys { stored, _ := rg.odb.NamespaceOf(key) seen, _, _ := shown.Of(key) if stored != ns && seen != ns { continue } if row, found, _ := rg.odb.RepoByName(key); found && row.State == oltp.Failed && rg.failedImportOf(key, author) { continue } return true, nil } return false, nil } // keyFor is the key a new repository called handle gets: the handle // itself, unless something holds that key or it could be read as // something else in a path's first segment, and then a minted one. func (rg *registrar) keyFor(handle string) (string, error) { if rg.keyFree(handle) { return handle, nil } for range 8 { var b [5]byte if _, err := rand.Read(b[:]); err != nil { return "", err } key := oltp.RepoKeyPrefix + strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(b[:])) if rg.keyFree(key) { return key, nil } } return "", errors.New("could not mint a repository key") } // keyFree says whether key can be a new repository's key: no repository // has it (a failed import's record included), and it reads as nothing // else first in a path. A repository path's FIRST segment has to be // readable without ambiguity: /r/A/B is either the repository A with B // beneath it, or the repository B under the namespace A, and nothing may // make both true. oltp refuses an account or team named after a // repository; this refuses the reverse. func (rg *registrar) keyFree(key string) bool { if !oltp.RepoName.MatchString(key) || oltp.IsReserved(key) || strings.EqualFold(key, oltp.ForgeNamespace) { return false } if _, exists := rg.deps.Repos.Get(key); exists { return false } if _, found, err := rg.odb.RepoByName(key); err != nil || found { return false } if _, taken := rg.odb.AccountByName(key); taken { return false } return !rg.odb.TeamNameTaken(key) && !rg.odb.Tombstoned(key) } // NameFree is the new-repository form's check as a name is typed. func (rg *registrar) NameFree(namespace, name, author string) error { if rg.odb == nil { return fmt.Errorf("no forge database: %w", ops.ErrUnavailable) } return rg.nameRefusal(namespace, name, author) } // failedImportOf says whether name's failed import is author's own: the // deed is theirs, or their agent's person's. func (rg *registrar) failedImportOf(name, author string) bool { owner, err := rg.odb.OwnerOf(name) return err == nil && owner != "" && owner == rg.deedHolder(author) } // retryFailedImport clears the way for its owner to try a failed import // again under the same name. A failed import is a record, not a // repository: its store was removed when it stopped, and the row stays // only so its progress page can say why. Its owner asking for the name // again is "Start again", so the record gives way; the attempt that // follows writes a new one. Anybody else still meets the name as taken. func (rg *registrar) retryFailedImport(spec api.RepoSpec) error { keys, err := rg.odb.KeysNamed(spec.Name) if err != nil { return err } targets := rg.targets(spec.Namespace, spec.Author) for _, key := range keys { ns, _ := rg.odb.NamespaceOf(key) if !slices.Contains(targets, ns) { continue } row, found, err := rg.odb.RepoByName(key) if err != nil || !found || row.State != oltp.Failed || !rg.failedImportOf(key, spec.Author) { continue } if err := rg.odb.DeleteRepo(key); err != nil { return fmt.Errorf("clearing the failed import of %s: %w", spec.Name, err) } log.Printf("repo.add %s: %s starts a failed import again", key, spec.Author) } return nil } // recordMirror attaches the upstream a clone came from. A failed mirror // record is not worth unwinding a working repository over — it is one // admin call to fix, and the repository is already serving. func (rg *registrar) recordMirror(spec api.RepoSpec) { every := time.Duration(spec.MirrorEvery) * time.Second if every == 0 { every = 24 * time.Hour } if err := rg.odb.SetMirror(spec.Name, spec.Clone, every); err != nil { log.Printf("repo.add %s: mirror not recorded: %v", spec.Name, err) return } if spec.Git { // A mirror left without its kind would run zit pull against a Git // address on every tick: none at all is the safe failure. if err := rg.odb.SetMirrorGit(spec.Name); err != nil { log.Printf("repo.add %s: mirror kind not recorded, so no mirror: %v", spec.Name, err) if derr := rg.odb.DeleteMirror(spec.Name); derr != nil { log.Printf("repo.add %s: forgetting the mirror: %v", spec.Name, derr) } return } // A private upstream's token goes with the mirror, sealed, for // the pulls after the first import. if spec.GitToken != "" { if err := rg.odb.SetMirrorGitToken(spec.Name, spec.GitToken); err != nil { log.Printf("repo.add %s: the mirror's access token was not kept, so later pulls go anonymously: %v", spec.Name, err) } } } } // importClone copies the upstream into an already-registered row, then // moves it from Cloning to Ready. Every exit updates the row: a failure // that only logged would leave a repository claiming to be importing // with nothing importing it. asked is the request as it reached Add, // kept for an import that stops to ask its owner a question. func (rg *registrar) importClone(spec, asked api.RepoSpec) { // The bulk lane, as before: a clone is minutes of network and // memory, and admins asking for three at once should queue rather // than run unbounded. err := rg.bulk.DoNamed(context.Background(), "clone", spec.Name, func() error { if spec.Git { return rg.importGitClone(context.Background(), spec) } return zitcli.Clone(context.Background(), spec.Clone, spec.Path) }) if err != nil { why := err.Error() if errors.Is(err, work.ErrBusy) { why = "too many imports in flight; nothing was copied" } os.RemoveAll(spec.Path) // The kept request goes in BEFORE the failure: whoever reads // "failed" must also see that it can be confirmed. Written after, // a reader between the two writes saw a dead end with no way on // (CI caught it: TestALargeGitImportWaitsForItsOwner, 2026-10-31). if errors.Is(err, errTooLargeForFlat) && spec.GitToken == "" { if b, jerr := json.Marshal(asked); jerr != nil { log.Printf("import %s: keeping the request: %v", spec.Name, jerr) } else if serr := rg.odb.SetImportRetry(spec.Name, string(b)); serr != nil { log.Printf("import %s: keeping the request: %v", spec.Name, serr) } } if serr := rg.odb.SetRepoState(spec.Name, oltp.Failed, why); serr != nil { log.Printf("import %s: recording failure: %v", spec.Name, serr) } if errors.Is(err, errTooLargeForFlat) && spec.GitToken != "" { // The kept request is plain JSON, and a token is never put // in it; a confirm without the token would fetch anonymously // and fail. So this one asks to be started again instead. why = "too large for flat manifests: start again with Sub-manifests chosen, and give the access token again" if serr := rg.odb.SetRepoState(spec.Name, oltp.Failed, why); serr != nil { log.Printf("import %s: recording failure: %v", spec.Name, serr) } } // The mirror was recorded when the import was accepted, on the // expectation of a store to pull into. There is none: without // this the scheduler asked for a repository that does not exist // every tick and journalled an error each time — two thousand // of them for one refused clone (libspatialite, 2026-09-06). if spec.Mirror { if derr := rg.odb.DeleteMirror(spec.Name); derr != nil { log.Printf("import %s: forgetting mirror: %v", spec.Name, derr) } } log.Printf("import %s from %s: %v", spec.Name, spec.Clone, err) rg.importEnded(spec.Name, spec.Author, why) return } // The create may have been withdrawn while the copy ran (repo.add // rolls back when it cannot grant the owner): the row is gone, and // registering now would serve a repository nobody holds. if row, found, err := rg.odb.RepoByName(spec.Name); err == nil && (!found || row.State != oltp.Cloning) { os.RemoveAll(spec.Path) if spec.Mirror && !found { if derr := rg.odb.DeleteMirror(spec.Name); derr != nil { log.Printf("import %s: forgetting mirror: %v", spec.Name, derr) } } log.Printf("import %s: withdrawn while it copied; not served", spec.Name) return } serve := rg.Register if rg.importServe != nil { serve = rg.importServe } if err := serve(spec.Name, spec.Path); err != nil { os.RemoveAll(spec.Path) if serr := rg.odb.SetRepoState(spec.Name, oltp.Failed, err.Error()); serr != nil { log.Printf("import %s: recording failure: %v", spec.Name, serr) } log.Printf("import %s: registering: %v", spec.Name, err) rg.importEnded(spec.Name, spec.Author, err.Error()) return } if err := rg.odb.SetRepoState(spec.Name, oltp.Ready, ""); err != nil { log.Printf("import %s: marking ready: %v", spec.Name, err) } if spec.Git { rg.copyGitHubAbout(spec.Name, spec.Clone, spec.GitToken) } log.Printf("import %s from %s: complete", spec.Name, spec.Clone) rg.importEnded(spec.Name, spec.Author, "") } // ConfirmImport runs again, with sub-manifests, an import that stopped // because its history was too large for flat manifests: the request as // it was first made, through Add, which clears the failed record. func (rg *registrar) ConfirmImport(name, by string) error { missing := fmt.Errorf("no import of %q waiting for an answer: %w", name, ops.ErrNotFound) if rg.odb == nil { return missing } retry, err := rg.odb.ImportRetry(name) if err != nil { return err } if retry == "" { return missing } var spec api.RepoSpec if err := json.Unmarshal([]byte(retry), &spec); err != nil { return fmt.Errorf("import %s: the kept request: %w", name, err) } if spec.Author != by { return missing } spec.ZitOnly = true _, _, err = rg.Add(spec) return err } // importInterrupted is why an import a restart cut short failed. const importInterrupted = "interrupted by a server restart before the copy finished" // importEnded tells whoever asked for an import how it ended (why is // empty for a finished one): the progress page says so only to somebody // still watching it. func (rg *registrar) importEnded(name, to, why string) { if rg.deps == nil || rg.odb == nil { return } started := "" if row, found, err := rg.odb.RepoByName(name); err == nil && found { started = row.Created } rg.deps.NotifyImportEnded(name, to, started, why) } // Imports reports what is copying now and what failed copying. Bytes // are measured from the store on disk rather than tracked in memory, so // the number survives a reader arriving mid-import and needs no // bookkeeping the copy would have to keep up to date. func (rg *registrar) Imports() ([]api.RepoImport, error) { if rg.odb == nil { return nil, nil } rows, err := rg.odb.Repos() if err != nil { return nil, err } var out []api.RepoImport for _, r := range rows { if r.State == oltp.Ready { continue } ri := api.RepoImport{ Name: r.Name, URL: r.ImportURL, State: r.State, Error: r.ImportError, Started: r.Created, Bytes: dirBytes(r.Path), } if done, total, ok := zitcli.GitImportProgress(r.Path); ok { ri.Checkins, ri.Total = done, total } if r.State == oltp.Failed { if retry, err := rg.odb.ImportRetry(r.Name); err == nil && retry != "" { ri.Confirm = api.ImportConfirmSubmanifests } } out = append(out, ri) } return out, nil } // dirBytes totals a store's files. A missing directory is zero, not an // error: a failed import has already had its partial store removed. func dirBytes(path string) int64 { if path == "" { return 0 } var total int64 filepath.WalkDir(path, func(_ string, e os.DirEntry, err error) error { if err != nil || e.IsDir() { return nil //nolint:nilerr // an unreadable entry contributes nothing } if info, ierr := e.Info(); ierr == nil { total += info.Size() } return nil }) return total } // ReconcileImports settles rows left mid-import by a restart. A clone // runs as a CHILD of this server, so stopping the server kills it and // the row would otherwise claim to be cloning forever — which is // exactly what a deploy during an import produced. Marking them failed // is the honest state: the copy is not running, and the partial store // is removed so a retry starts clean. func (rg *registrar) ReconcileImports() { if rg.odb == nil { return } names, err := rg.odb.ImportingRepos() if err != nil { log.Printf("imports: listing interrupted: %v", err) return } for _, name := range names { row, ok, err := rg.odb.RepoByName(name) if err != nil || !ok { continue } // A Git import the restart caught after it published (in its // cache warm-up) is whole: Ready, so the registration below // serves it, with its mirror marked Git as a finished import's // is. Only a Git import leaves an import map. if row.Path != "" && gitImportPublished(row.Path) { if err := rg.odb.SetMirrorGit(name); err != nil { log.Printf("imports: %s: mirror kind: %v", name, err) } if err := rg.odb.SetRepoState(name, oltp.Ready, ""); err != nil { log.Printf("imports: settling %s: %v", name, err) continue } log.Printf("imports: %s was published before a restart; kept and served", name) if owner, err := rg.odb.OwnerOf(name); err == nil { rg.importEnded(name, owner, "") } continue } if row.Path != "" { os.RemoveAll(row.Path) } rg.forgetGitDirs(name) if err := rg.odb.SetRepoState(name, oltp.Failed, importInterrupted); err != nil { log.Printf("imports: settling %s: %v", name, err) continue } log.Printf("imports: %s was interrupted by a restart; marked failed", name) if owner, err := rg.odb.OwnerOf(name); err == nil { rg.importEnded(name, owner, importInterrupted) } } } // mustBeEmpty refuses to create or clone over existing content. Both zit // verbs create the directory themselves, so anything already there is // somebody else's, and the failure mode of guessing wrong is destroying // it on the rollback path. func (rg *registrar) mustBeEmpty(path string) error { if path == "" { return fmt.Errorf("%w: empty path", ops.ErrInvalid) } entries, err := os.ReadDir(path) if os.IsNotExist(err) { return nil } if err != nil { return fmt.Errorf("%w: %v", ops.ErrInvalid, err) } if len(entries) > 0 { return fmt.Errorf("%w: %s already exists and is not empty", ops.ErrInvalid, path) } return nil } // Remove stops serving a repository and forgets it. The store on disk // and its derived index are left alone: "stop serving this" and // "destroy this" are different intentions and only one is reversible. // refuseTakenDown keeps a repository under a takedown (RFC 0023) from // being deleted or un-served, either of which would destroy what the // takedown keeps. Asked before anything stops serving. func (rg *registrar) refuseTakenDown(name string) error { if rg.odb == nil { return nil } t, held, err := rg.odb.TakedownOf(name) if err != nil || !held { return err } if t.Strength == oltp.LegalHold { return fmt.Errorf("%w: %s is on legal hold, which keeps it as it is; lift the hold first", ops.ErrInvalid, name) } return fmt.Errorf("%w: %s is disabled for legal reasons, which keeps it; restore it first", ops.ErrInvalid, name) } func (rg *registrar) Remove(name string) error { if err := rg.refuseTakenDown(name); err != nil { return err } // A repository whose import failed has a ROW but was never served, // so there is nothing to unregister — and refusing on that basis // would make a failed import impossible to clear from anywhere but // the database. Forgetting a registration that does not exist is // the outcome the caller asked for either way. if err := rg.Unregister(name); err != nil && !errors.Is(err, ops.ErrNotFound) { return err } if rg.odb != nil { if err := rg.odb.DeleteRepo(name); err != nil { return err } } return nil } // CloseAll releases every registration — serve's shutdown path. func (rg *registrar) CloseAll() { for _, name := range rg.deps.Repos.Names() { if err := rg.Unregister(name); err != nil { log.Printf("unregister %s: %v", name, err) } } } // accountStore adapts forge OLTP to the ops layer's account seam. The // role strings cross as text because that is the API's shape; parsing // them here keeps oltp.Role out of the op surface. type accountStore struct{ db *oltp.DB } // api.AccountAdmin is reached through a runtime type assertion, so a // method missed below does not fail the build — it silently turns off // invites, resets, the lockout and the session audit TOGETHER, and the // first anybody hears of it is a surface reporting that this forge has // no invites. Assert it here, where the compiler can say so instead. var _ api.AccountAdmin = accountStore{} // The private-beta half (api.AccountAdmin). func (s accountStore) InviteAccount(name, email string, admin bool) (string, error) { return s.db.InviteAccount(name, email, admin) } // The agent ops find their half of the store by a type assertion, so a // method this adapter lacks would switch every agent door off at run // time ("no agents") instead of failing the build. var _ api.AgentStore = accountStore{} // And the site-admin flag, which would otherwise answer "unavailable". var _ api.SiteAdminStore = accountStore{} // The chat channel's bell writes through the database itself. var _ api.ChatNotifyStore = (*oltp.DB)(nil) var _ api.HighlightStore = (*oltp.DB)(nil) // So do a channel's identity links. var _ api.ChatIdentityStore = (*oltp.DB)(nil) func (s accountStore) InviteFor(token string) (string, bool) { return s.db.InviteFor(token) } func (s accountStore) RedeemInvite(token, password string) (string, error) { return s.db.RedeemInvite(token, password) } func (s accountStore) ResetPassword(name string) (string, error) { return s.db.ResetPassword(name) } func (s accountStore) SetSiteAdmin(name string, on bool, actor string) error { return s.db.SetSiteAdmin(name, on, actor) } func (s accountStore) TokenKind(token string) string { return s.db.TokenKind(token) } func (s accountStore) SetDisabled(name string, on bool) error { return s.db.SetDisabled(name, on) } func (s accountStore) Sessions(name string) ([]api.SessionInfo, error) { rows, err := s.db.Sessions(name) if err != nil { return nil, err } out := make([]api.SessionInfo, 0, len(rows)) for _, x := range rows { out = append(out, api.SessionInfo{ID: x.ID, Account: x.Account, Created: x.Created, Expires: x.Expires, LastSeen: x.LastSeen, IP: x.IP, Agent: x.Agent}) } return out, nil } func (s accountStore) EndSession(id, account string) error { return s.db.EndSessionID(id, account) } func (s accountStore) EndSessions(account string) error { return s.db.EndAccountSessions(account) } func (a accountStore) Accounts() ([]api.Account, error) { rows, err := a.db.Accounts() if err != nil { return nil, err } out := make([]api.Account, 0, len(rows)) for _, r := range rows { acct := api.Account{Name: r.Name, Admin: r.Admin, Created: r.Created, Email: r.Email, EmailPending: r.EmailPending, Disabled: r.Disabled, Pending: r.Pending, LastLogin: r.LastLogin, LastSeen: r.LastSeen, Operator: r.Operator} if !r.Admin && r.SiteOpt && a.db.InheritsSiteAdmin(r.Name) { acct.Admin, acct.AdminByInheritance = true, true } // Resolved, not stored: who answers NOW, or nobody. if r.Answerable != "" { acct.Answerable = a.db.Answerable(r.Name) } out = append(out, acct) } return out, nil } // The confirmed-address half (api.AccountEmail). func (a accountStore) AccountByName(name string) (api.Account, bool) { r, ok := a.db.AccountByName(name) if !ok { return api.Account{}, false } acct := api.Account{Name: r.Name, Admin: r.Admin, Created: r.Created, Email: r.Email, EmailPending: r.EmailPending, Disabled: r.Disabled, Pending: r.Pending, LastLogin: r.LastLogin, LastSeen: r.LastSeen, Operator: r.Operator} if !r.Admin && r.SiteOpt && a.db.InheritsSiteAdmin(r.Name) { acct.Admin, acct.AdminByInheritance = true, true } if r.Answerable != "" { acct.Answerable = a.db.Answerable(r.Name) } return acct, true } func (a accountStore) SetEmail(name, email string) error { return a.db.SetEmail(name, email) } func (a accountStore) SetPendingEmail(name, address string) (string, error) { return a.db.SetPendingEmail(name, address) } func (a accountStore) ConfirmEmail(account, code string) (string, bool, error) { return a.db.ConfirmEmail(account, code) } func (a accountStore) ClearEmail(name string) error { return a.db.ClearEmail(name) } func (a accountStore) AddAccount(name, password string, admin bool) error { return a.db.AddAccount(name, password, admin) } func (a accountStore) SetOperator(name, operator string) error { return a.db.SetOperator(name, operator) } // The agent half (api.AgentStore, RFC 0021): the agents a person // operates, their tokens, and the operator's grant. func (a accountStore) NewAgent(name, operator string, perPerson int) error { return a.db.NewAgent(name, operator, perPerson) } func (a accountStore) Agents(operator string) ([]oltp.Account, error) { return a.db.Agents(operator) } func (a accountStore) AgentCount(operator string) (int, error) { return a.db.AgentCount(operator) } func (a accountStore) Operator(name string) string { return a.db.Operator(name) } func (a accountStore) MintToken(account string, spec oltp.TokenSpec) (string, oltp.Token, error) { return a.db.MintToken(account, spec) } func (a accountStore) Tokens(account string) ([]oltp.Token, error) { return a.db.Tokens(account) } func (a accountStore) RevokeToken(account, id string) error { return a.db.RevokeToken(account, id) } func (a accountStore) SetTokenRepos(account, id string, repos []string) (oltp.Token, error) { return a.db.SetTokenRepos(account, id, repos) } func (a accountStore) RevokeAgentTokens(operator string) (int, error) { return a.db.RevokeAgentTokens(operator) } func (a accountStore) AgentGrant(operator, agent, repo, caps string) (string, bool, error) { return a.db.AgentGrant(operator, agent, repo, caps) } func (a accountStore) SetInherit(operator, agent string, on bool) error { return a.db.SetInherit(operator, agent, on) } func (a accountStore) AgentInheritHere(operator, agent, repo string) error { return a.db.AgentInheritHere(operator, agent, repo) } func (a accountStore) ClosedTo(agent string) ([]string, error) { return a.db.ClosedTo(agent) } func (a accountStore) SetSiteOpt(operator, agent string) error { return a.db.SetSiteOpt(operator, agent) } func (a accountStore) NewDedicatedAgent(name, scope, answerable string) error { return a.db.NewDedicatedAgent(name, scope, answerable) } func (a accountStore) NewScopedAgent(name, operator, scope string, perPerson int) error { return a.db.NewScopedAgent(name, operator, scope, perPerson) } func (a accountStore) SetupAgent(s oltp.AgentSetup) (oltp.AgentSetupResult, error) { return a.db.SetupAgent(s) } func (a accountStore) RetractSetup(agent, tokenID string) error { return a.db.RetractSetup(agent, tokenID) } func (a accountStore) SetupNameFree(name string) error { return a.db.SetupNameFree(name) } func (a accountStore) SetupShortfall(approver, repo, caps string) string { return a.db.SetupShortfall(approver, repo, caps) } func (a accountStore) ReissueTokens(account string) (string, oltp.Token, int, error) { return a.db.ReissueTokens(account) } func (a accountStore) PlanReissue(account string) (oltp.ReissuePlan, bool, error) { return a.db.PlanReissue(account) } func (a accountStore) ReissueAs(account string, plan oltp.ReissuePlan) (string, oltp.Token, int, error) { return a.db.ReissueAs(account, plan) } // The forge's own agents (RFC 0021, Forge agents). func (a accountStore) NewForgeAgent(name, answerable string) error { return a.db.NewForgeAgent(name, answerable) } func (a accountStore) SetForgeAgent(name, answerable string) error { return a.db.SetForgeAgent(name, answerable) } func (a accountStore) SetAnswerable(name, admin string) error { return a.db.SetAnswerable(name, admin) } func (a accountStore) Answerable(name string) string { return a.db.Answerable(name) } // VerifyPassword and SetPasswordSelf are api.AccountAuth: the // self-service half of me.passwd. No forge op sets another account's // password; that is `quarry account passwd`, on the box (#319). func (a accountStore) VerifyPassword(name, password string) bool { return a.db.VerifyPassword(name, password) } func (a accountStore) SetPasswordSelf(name, password, keep string) error { return a.db.SetPasswordSelf(name, password, keep) } func (a accountStore) DeleteAccount(name string) error { return a.db.DeleteAccount(name) } func (a accountStore) WithdrawInvite(name string) error { return a.db.WithdrawInvite(name) } func (a accountStore) InviteExpiries() (map[string]string, error) { return a.db.InviteExpiries() } func (a accountStore) LapsedInvites(before time.Time) ([]string, error) { return a.db.LapsedInvites(before) } // Grant and Revoke are the API's writes, each judged by the RFC 0008 // guard for the actor under the lock it writes with. A site admin // removing a repository's last admin is warned, not refused; anyone // else is refused. func (a accountStore) Grant(actor, account, repo, role string) (string, error) { r, err := oltp.ParseRole(role) if err != nil { return "", err } return a.db.GrantGuarded(actor, account, repo, r) } func (a accountStore) Revoke(actor, account, repo string) (string, error) { return a.db.GrantGuarded(actor, account, repo, oltp.NoRole) } func (a accountStore) GrantsFor(account string) (map[string]string, error) { grants, err := a.db.GrantsFor(account) if err != nil { return nil, err } out := make(map[string]string, len(grants)) for repo, role := range grants { out[repo] = role.String() } return out, nil } // CapsAt is account.explain's seam. An unknown account is an error, // not an empty string: the op explains people, not names. func (a accountStore) CapsAt(account, repo string) (string, string, error) { if _, found := a.db.AccountByName(account); !found { return "", "", fmt.Errorf("no such account %q", account) } stored, err := a.db.CapsOf(account, repo) if err != nil { return "", "", err } return stored, string(a.db.EffectiveCaps(account, repo)), nil } // warmSem bounds concurrent warms fleet-wide: a restart syncs every // store at once, and 23 parallel zit processes over the biggest repos // is a memory spike with no reader waiting on it. // // Four rather than two since zit 0.3.2, which cut `leaves` on sqlite // from 1.15s to 0.26s. The warm pass is a race against the first // reader — until a repository is warmed, its About panel pays ~3 zit // cats on the render path, which measured 543-775ms — so finishing the // sweep sooner is what shortens that window. Still bounded well below // the store count, because the point of the cap is to not spike memory // on the biggest repositories with nobody waiting. var warmSem = make(chan struct{}, 4) // frontSem bounds the front page's root listings fleet-wide, apart from // warmSem. The listing is what a visitor to a repository waits on (6-18 // s on pkgsrc after a restart), so it must not queue behind another // repository's activity scan or indexTree for one of warmSem's slots; // but it is a `zit ls`, so a fleet of forty repositories // still runs one at a time: a heavy tree's listing can take ~950 MB. var frontSem = make(chan struct{}, 1) // warmZit is the part of the zit client a warm pass reads through. type warmZit interface { Ls(ctx context.Context, version string) ([]zitcli.LsEntry, error) LsDir(ctx context.Context, version, under string) ([]zitcli.LsEntry, error) Cat(ctx context.Context, path, version string) ([]byte, error) } // warmIndex is the part of the index a warm pass reads through. type warmIndex interface { TipOf(branch string) (index.Branch, bool, error) DefaultBranch() string WarmActivityDays(branch string) error EventKinds() (map[string]int, error) } // warmReads performs the reads a repository's files page performs, so // the per-process memos (keyed on the immutable tip hash) are hot when // a reader arrives. Failures are irrelevant — the reader's own request // takes the cold path, exactly as if this had never run. // // In the order a visitor needs them: the root listing first (its own // bound, frontSem), then the other front-page reads, and the whole- // history activity scan last, so it cannot hold the listing back. func warmReads(ctx context.Context, zit warmZit, ix warmIndex) { if ctx.Err() != nil { return } tip, ok, err := ix.TipOf(ix.DefaultBranch()) if err == nil && ok { warmRootListing(ctx, zit, tip.Tip) } select { case warmSem <- struct{}{}: defer func() { <-warmSem }() case <-ctx.Done(): return } if err == nil && ok { lctx, cancel := context.WithTimeout(ctx, 3*time.Minute) if files, lerr := zit.Ls(lctx, tip.Tip); lerr == nil { for _, f := range files { base := strings.ToLower(path.Base(f.Name)) if strings.HasPrefix(base, "readme") || strings.HasPrefix(base, "license") || strings.HasPrefix(base, "copying") || f.Name == ".quarry/repo.json" { zit.Cat(lctx, f.Name, tip.Tip) } } } cancel() } if ctx.Err() != nil { return } // The home page's activity chart: a scan of the whole history, 4.8s // on tcl. After the first read a fold only marks it stale and it is // refreshed in the background, but a fresh process has nothing to // serve, so the first reader after every deploy paid the scan. _ = ix.WarmActivityDays("") // The dashboard's kind chips: a count of every event, 0.46s on // pkgsrc with a cold page cache. The dashboard asks every // repository, so after a deploy its first load paid them all. _, _ = ix.EventKinds() } // warmRootListing memoises the tip's root listing, the read the files // page makes first, under frontSem. func warmRootListing(ctx context.Context, zit warmZit, tip string) { if ctx.Err() != nil { return } select { case frontSem <- struct{}{}: defer func() { <-frontSem }() case <-ctx.Done(): return } lctx, cancel := context.WithTimeout(ctx, 3*time.Minute) defer cancel() zit.LsDir(lctx, tip, "") } // warmer runs one store's warm passes, one at a time. A request that // arrives while a pass runs is not dropped: the pass goes round again // when it ends, re-reading the tip, so a tip that moved meanwhile is // warmed too. type warmer struct { busy atomic.Bool again atomic.Bool // gate spreads a restart's warms over a window; nil starts at once. gate *bootGate // maint, when set, takes the boot warm: it is cache-warming nobody // has asked for yet, so it waits for a quiet machine. The warm after // a fold that moved the tip stays on start, because the first reader // after a push would otherwise pay for it. store names this // repository to the lane. maint *maintenance store string } // boot runs the warm a registered repository gets before anyone has // asked: on the maintenance lane when there is one, otherwise at once. func (w *warmer) boot(ctx context.Context, zit warmZit, ix warmIndex) { if w.maint == nil { w.start(ctx, zit, ix) return } w.maint.Request(w.store, "warm reads", func(mctx context.Context) error { mctx, cancel := context.WithCancel(mctx) defer cancel() defer context.AfterFunc(ctx, cancel)() warmReads(mctx, zit, ix) return nil }) } // start never blocks. func (w *warmer) start(ctx context.Context, zit warmZit, ix warmIndex) { if !w.busy.CompareAndSwap(false, true) { w.again.Store(true) return } go func() { if !w.gate.wait(ctx) { w.busy.Store(false) return } for { w.again.Store(false) warmReads(ctx, zit, ix) w.busy.Store(false) // A request between the check above and the release lost its // claim; take it back rather than leave it unserved. if ctx.Err() != nil || !w.again.Load() || !w.busy.CompareAndSwap(false, true) { return } } }() } // warmEarly starts a repository's front-page warm as soon as it is // registered and its index holds a tip, instead of after the first // sync round, which on pkgsrc ends 25 s or more later. It never blocks // the caller. A repository whose index is still empty is left to the // first round's warm. once is the round's warm-at-boot latch: taking // it here means that round does not run the same pass again unless it // moved the tip. The returned channel closes once the decision is made. func warmEarly(ctx context.Context, w *warmer, once *sync.Once, zit warmZit, ix warmIndex) <-chan struct{} { decided := make(chan struct{}) go func() { defer close(decided) if _, ok, err := ix.TipOf(ix.DefaultBranch()); err != nil || !ok { return } once.Do(func() {}) w.boot(ctx, zit, ix) }() return decided } // indexTree files the default branch tip's FILES into the search // index: fossil's search scope "d" for documentation, plus source, // which fossil does not search at all. // // quarry rendered both as first-class surfaces — the docs tab, the file // browser — and could find neither. A reader could open // www/quickstart.wiki and get nothing searching for it. // // One tarball, not a read per file. `cat` per path costs a subprocess // each: 2,199 files on sqlite is ~31 seconds and 2,199 store opens, // against 2.2 seconds for one archive. The tarball is the whole tree in // one pass, which is exactly the shape of the question. // // Asynchronous, on the triggers a rebuild and a moved tip already // carry. Not through dagnats: dagnats is optional — a forge without one // "simply has no CI rather than a broken one" — and search must not // inherit that. This is local derivation from the store, the same class // of work as the fold, which Reindex already routes around the bus on // purpose. func indexTree(cli *zitcli.Client, ix *index.Index) { if cli == nil || ix == nil { return } warmSem <- struct{}{} defer func() { <-warmSem }() tip, ok, err := ix.TipOf(ix.DefaultBranch()) if err != nil || !ok { return } // The tip has not moved since the last pass: the rows already // describe it. This is what makes the boot trigger cheap on a // restart that ingested nothing. if at, verr := ix.TreeVersion(); verr == nil && at == tip.Tip { return } // A store whose tip archive was over the cap is not tried again for // a while, whatever its tip does: netbsd-src's tip is 768 MB, and // each attempt built all of it, held most of a gigabyte for minutes // and threw it away, several times an hour. if treeRefusedRecently(ix, time.Now()) { return } ctx, cancel := context.WithTimeout(obs.WithReason(context.Background(), obs.ReasonTree), 15*time.Minute) defer cancel() tmp, err := os.CreateTemp("", "quarry-tree-*.tar.gz") if err != nil { return } defer os.Remove(tmp.Name()) tmp.Close() if err := cli.ArchiveTo(ctx, "tar", tip.Tip, "", tmp.Name(), treeArchiveMaxBytes); err != nil { var big *zitcli.TooLarge if errors.As(err, &big) { if rerr := ix.TreeRefused(tip.Tip, big.Bytes, time.Now()); rerr != nil { log.Printf("tree index: record refusal: %v", rerr) } log.Printf("tree index: %.12s's tip archive is %d MB, over the %d MB cap; its files are not searchable, and the next try is in %v", tip.Tip, big.Bytes>>20, big.Max>>20, treeRefusalRetry) return } log.Printf("tree index: archive %.12s: %v", tip.Tip, err) return } entries, skipped, err := readTreeArchive(tmp.Name()) if err != nil { log.Printf("tree index: read %.12s: %v", tip.Tip, err) return } written := time.Now() if err := ix.ReplaceTree(tip.Tip, entries); err != nil { log.Printf("tree index: %v", err) return } took := time.Since(written) var docs int for _, e := range entries { if e.Doc { docs++ } } log.Printf("tree index: %d files (%d documentation) at %.12s, %d skipped, written in %dms", len(entries), docs, tip.Tip, skipped, took.Milliseconds()) } // treeRefusedRecently says whether the store's tip archive was refused // for its size within treeRefusalRetry, so the indexer should not build // it again yet. A store with no refusal recorded, or one that cannot be // read, is not held back. func treeRefusedRecently(ix *index.Index, now time.Time) bool { _, at, _, ok, err := ix.TreeRefusal() return err == nil && ok && now.Sub(at) < treeRefusalRetry } // readTreeArchive turns the tip tarball into index rows, skipping what // full-text search cannot use: binaries, and files too large to be // prose or source anybody reads. func readTreeArchive(path string) (entries []index.TreeText, skipped int, err error) { f, err := os.Open(path) if err != nil { return nil, 0, err } defer f.Close() gz, err := gzip.NewReader(f) if err != nil { return nil, 0, err } defer gz.Close() tr := tar.NewReader(gz) buf := make([]byte, treeFileMaxBytes+1) for { h, rerr := tr.Next() if rerr == io.EOF { break } if rerr != nil { return nil, skipped, rerr } if h.Typeflag != tar.TypeReg || h.Size > treeFileMaxBytes { if h.Typeflag == tar.TypeReg { skipped++ } continue } // The archive names files under a top-level directory; the // index wants the repository-relative path a link uses. name := h.Name if i := strings.IndexByte(name, '/'); i >= 0 { name = name[i+1:] } if name == "" { continue } n, rerr := io.ReadFull(tr, buf[:h.Size]) if rerr != nil && rerr != io.ErrUnexpectedEOF { skipped++ continue } body := buf[:n] if !utf8.Valid(body) || bytes.IndexByte(body, 0) >= 0 { skipped++ // binary: a full-text index cannot use it continue } entries = append(entries, index.TreeText{ Path: name, Body: string(body), Doc: api.IsDocPath(name), }) } return entries, skipped, nil } // treeFileMaxBytes bounds one file, and treeArchiveMaxBytes the whole // tarball. Generous for prose and source, small against a vendored // amalgamation or a checked-in binary. const ( treeFileMaxBytes = 1 << 20 treeArchiveMaxBytes = 512 << 20 // treeRefusalRetry is how long a store whose tip archive was over // treeArchiveMaxBytes waits before the indexer builds it again. treeRefusalRetry = 7 * 24 * time.Hour ) func (rg *registrar) Update(name string, edit api.RepoEdit, by, via string) error { if rg.odb == nil { return fmt.Errorf("no forge database: %w", ops.ErrUnavailable) } // One transactional write for every setting, so the change and the // record of who made it cannot come apart, and the before-value in // that record is read where nothing can move it. The rule about // mirrorable during a private detour lives in there too: it needs // the authoritative visibility, which is the row the transaction is // already holding. if _, err := rg.odb.PatchRepo(name, oltp.RepoPatch{ Description: edit.Description, Visibility: edit.Visibility, Homepage: edit.Homepage, Topics: edit.Topics, Chat: edit.Chat, Mirrorable: edit.Mirrorable, UV: edit.UV, CIPublic: edit.CIPublic, }, by, via); err != nil { return fmt.Errorf("%w: %v", ops.ErrInvalid, err) } // Visibility is cached for the read gate, so the cache moves with // the setting rather than a tick later. A window in which a // repository is still readable after being taken private is the // feature failing, not staleness. rg.refreshPrivate() return nil } // refreshPrivate reloads the private set the read gate consults, and // returns once the new set is in place. // // Cached because the gate runs on EVERY request. This node's own // visibility writes call it directly, because a window in which a // repository is still readable after being taken private is the feature // failing, not staleness. Another node's writes reach the shared OLTP // only, so reads also reload a list older than privateTTL (privateSet). // // A failed load keeps the previous set and counts as a load for the // TTL, so a broken database is retried every privateTTL, not per read. func (rg *registrar) refreshPrivate() { load := rg.privLoader() if load == nil { return } rg.privMu.Lock() rg.privGen++ gen := rg.privGen rg.privMu.Unlock() set, err := load() var held map[string]oltp.Takedown var comps map[string]string herr := errors.New("no forge database") if rg.odb != nil { held, herr = rg.odb.Takedowns() if herr == nil { var rows []oltp.Companion if rows, herr = rg.odb.Companions(); herr == nil { comps = make(map[string]string, len(rows)) for _, c := range rows { comps[c.Store] = c.Repo } } } } rg.privMu.Lock() if gen > rg.privStored { rg.privAt = rg.now() if err == nil { rg.private, rg.privStored = set, gen } } if herr == nil && gen > rg.heldStored { rg.held, rg.heldStored = held, gen rg.companions, rg.compStored = comps, gen } rg.privMu.Unlock() if herr != nil && rg.odb != nil { log.Printf("takedowns: reload: %v", herr) } if err != nil { log.Printf("visibility: reload: %v", err) } } func (rg *registrar) privLoader() func() (map[string]bool, error) { if rg.privLoad != nil { return rg.privLoad } if rg.odb == nil { return nil } return rg.odb.PrivateRepos } // privateSet returns the cached set, and whether one has ever loaded. // One older than privateTTL starts a single background reload and is // still served meanwhile: a request never waits on the reload, and // never sees an empty set because one is running. The set is replaced // whole, never mutated, so it is safe to read after the lock is // released. func (rg *registrar) privateSet() (set map[string]bool, loaded bool) { load := rg.privLoader() if load == nil { return nil, true // no forge database: nothing can be private } rg.privMu.RLock() set, at, loaded := rg.private, rg.privAt, rg.privStored > 0 rg.privMu.RUnlock() if rg.privStale(at) && rg.privBusy.CompareAndSwap(false, true) { // Checked again now the flag is held: a reload that finished // between the read above and the swap has already stamped // privAt, and must not be followed by another. rg.privMu.RLock() at = rg.privAt rg.privMu.RUnlock() if !rg.privStale(at) { rg.privBusy.Store(false) return set, loaded } go func() { defer rg.privBusy.Store(false) rg.refreshPrivate() }() } return set, loaded } func (rg *registrar) privStale(at time.Time) bool { return rg.now().Sub(at) > privateTTL } // IsPrivate answers from the cached set refreshPrivate maintains. It is // the first half of CanRead, exposed because the web layer's canonical // redirect has to ask the question before it has resolved an identity. // // Before any load has succeeded — the boot load failed — it answers // true for every repository: the forge is hidden, not opened. func (rg *registrar) IsPrivate(repo string) bool { set, loaded := rg.privateSet() return !loaded || set[repo] } // CanRead reports whether the identity in ctx may read repo. // // Public repositories are readable by anyone, which is what keeps an // anonymous forge working. A private one requires a role on it, from a // grant or a team. A site admin is no exception (#318): the flag is s // at forge scope, never a read letter on somebody's repository. func (rg *registrar) CanRead(ctx context.Context, repo string) bool { if !rg.IsPrivate(repo) { return true } user := ops.User(ctx) if user == "" { return false } if rg.odb == nil { return false } // RFC 0004's rule for reading at all: any read letter in the // effective set, categories included. A token's set when the caller // came in on one, asked first: the resolver already stood behind // its account, and a run token (RFC 0021) has none. if tok, ok := ops.TokenOf(ctx); ok { return tok.Caps(repo).HasAny("gjoh2r") } acct, ok := rg.odb.AccountByName(user) if !ok { return false } return rg.odb.EffectiveCaps(acct.Name, repo).HasAny("gjoh2r") } // HeldRefusal is RFC 0023's answer for every surface: the sentence a // repository under a takedown gives the caller in ctx, or "" when it // serves them. A disable lets the repository's own admins through, a // hold nobody but a site admin. A site admin signed in as a person // reaches either, since judging a notice or reporting what is held // means looking at it; a token never does, a site token included, so // no machine is handed what a hold keeps. Reaching is not writing: a // site admin holds no letters on somebody's repository (#318). func (rg *registrar) HeldRefusal(ctx context.Context, repo string) string { if rg.odb == nil || repo == "" { return "" } rg.privateSet() // keeps the shared cache inside its TTL rg.privMu.RLock() t, ok := rg.held[repo] loaded := rg.heldStored > 0 && rg.compStored > 0 // A companion store answers for its parent: the takedown is on the // content, whatever name holds it. whose := repo if parent, isStore := rg.companions[repo]; isStore { whose = parent t, ok = rg.held[parent] } rg.privMu.RUnlock() if !loaded { // No load has succeeded yet: ask the table itself rather than // serve a takedown as though there were none, and refuse when // even that fails, since serving is what cannot be taken back. var err error lookup := rg.heldLookup if lookup == nil { lookup = rg.tablesHeldLookup } t, whose, ok, err = lookup(repo) if err != nil { log.Printf("takedowns: %s: %v", repo, err) if rg.sitePerson(ctx) { return "" } return (oltp.Takedown{Strength: oltp.LegalHold}).Sentence() } } if !ok || rg.sitePerson(ctx) || !t.Refuses(rg.holdsAdmin(ctx, whose)) { return "" } return t.Sentence() } // tablesHeldLookup is the uncached answer: the repository's own takedown, // or its parent's when it is a companion store. An error is the caller's // to fail closed on. Once a load has succeeded, a later reload error // keeps the last good maps (refreshPrivate stores only on success), which // is the lesser harm: the takedowns it holds stay in force. func (rg *registrar) tablesHeldLookup(repo string) (oltp.Takedown, string, bool, error) { whose := repo parent, _, isStore, err := rg.odb.CompanionParent(repo) if err != nil { return oltp.Takedown{}, repo, false, err } if isStore { whose = parent } t, ok, err := rg.odb.TakedownOf(whose) return t, whose, ok, err } // errWriteHeld is what a write to a store on legal hold is answered. var errWriteHeld error = writeHeldError{} // writeHeldError is errWriteHeld: forbidden to the ops layer, and the // hold's sentence to a sync client whose push it refused. type writeHeldError struct{} func (writeHeldError) Error() string { return "this repository is on legal hold and takes no writes: " + ops.ErrForbidden.Error() } func (writeHeldError) Unwrap() error { return ops.ErrForbidden } func (writeHeldError) PushRefusal() string { return (oltp.Takedown{Strength: oltp.LegalHold}).Sentence() } // legallyHeld says a repository is on LEGAL HOLD, the strength under which // nobody writes (RFC 0023); a disabled repository's admins still do, so // the forge's writes on their behalf go on. Same cache as the gates, and // the same fail-closed answer before its first load. func (rg *registrar) legallyHeld(name string) bool { if rg.odb == nil || name == "" { return false } rg.privateSet() rg.privMu.RLock() t, ok := rg.held[name] if parent, isStore := rg.companions[name]; isStore { t, ok = rg.held[parent] } loaded := rg.heldStored > 0 && rg.compStored > 0 rg.privMu.RUnlock() if !loaded { lookup := rg.heldLookup if lookup == nil { lookup = rg.tablesHeldLookup } var err error if t, _, ok, err = lookup(name); err != nil { return true } } return ok && t.Strength == oltp.LegalHold } // ciHeld says CI is paused for a repository: it is under either strength // of takedown (RFC 0023, "Webhooks and CI | paused | paused"). Nothing is // deleted, so the check-ins that arrive meanwhile are run when it is // lifted, by the next fold or the deferred drain. Fails closed, as the // gates do: a takedown not yet loaded is no reason to start a run. func (rg *registrar) ciHeld(name string) bool { return rg.HeldRefusal(context.Background(), name) != "" } // companionParent is the repository a companion store belongs to, "" for // a store that is not one, from the cache the gates read. func (rg *registrar) companionParent(name string) string { rg.privMu.RLock() defer rg.privMu.RUnlock() return rg.companions[name] } // TakenDownStrength is the strength of the takedown a repository is // under, whoever asks, from the cache the gates read: "" when it is up. // It marks a repository a caller may still see, and gates nothing. func (rg *registrar) TakenDownStrength(repo string) string { rg.privMu.RLock() defer rg.privMu.RUnlock() t, ok := rg.held[repo] if !ok { if parent, isStore := rg.companions[repo]; isStore { t, ok = rg.held[parent] } } if !ok { return "" } if t.Strength == oltp.LegalHold { return "hold" } return "disabled" } // sitePerson is a site admin signed in as a person, never on a token. func (rg *registrar) sitePerson(ctx context.Context) bool { if _, byToken := ops.TokenOf(ctx); byToken { return false } user := ops.User(ctx) if user == "" { return false } a, ok := rg.odb.AccountByName(user) return ok && a.Admin && a.Disabled == "" } // holdsAdmin is whether the caller holds a on repo, a token answering // for itself (RFC 0021). func (rg *registrar) holdsAdmin(ctx context.Context, repo string) bool { if tok, ok := ops.TokenOf(ctx); ok { return tok.Caps(repo).HasAny("a") } user := ops.User(ctx) if user == "" { return false } return rg.odb.EffectiveCaps(user, repo).HasAny("a") } // SyncHoldGate is HeldRefusal for the sync front, with the sync lane's // own identity: the login card, or a token in Basic. func (rg *registrar) SyncHoldGate(req *http.Request, repo, login string) string { ctx, ok := rg.syncCtx(req, login) if !ok { return (oltp.Takedown{Strength: oltp.LegalHold}).Sentence() } return rg.HeldRefusal(ctx, repo) } // syncCtx is the sync lane's identity: Basic (a token or password), // else the verified login card. false is a card signed with a token // that has gone since it verified, which reads as nobody at all. // // Uncounted: the sync front has already checked the request's Basic as // one sign-in (tokenDoors.syncSignIn) and takes a credential it refused, // or whose account is held, off the request before asking here. func (rg *registrar) syncCtx(req *http.Request, login string) (context.Context, bool) { ctx := syncIdentityCtx(req, &tokenDoors{db: rg.odb}) // The sync protocol's own credential counts as identity here. // // identityCtx reads HTTP Basic, which a browser and curl send and a // sync client does not: fossil and zit authenticate with the login // card, inside the body. So a private repository admitted anyone // with Basic and refused every real client, including the // repository's owner — "private" meaning "unclonable by everybody" // (b112b205). xfer has already verified this name against the // repository's shared secret; an unverified or absent card arrives // as "". if login != "" && ops.User(ctx) == "" { ctx = ops.WithUser(ctx, login) // A card signed with a token reads as the token, ceiling and // repositories included (RFC 0021). A token gone since the card // verified reads as nothing. if id := xfer.LoginToken(req); id != "" && rg.odb != nil { tok, ok := rg.odb.LiveToken(login, id) if !ok { return nil, false } ctx = rg.tokenDoors().tokenCtx(ctx, login, tok) } } return ctx, true } // SyncReadGate is the sync protocol's whole visibility answer: the // xfer.ReadGate installed on the fronter. It takes the SAME answer // CanRead gives the web pages, refined by a separate question mirroring // asks that ordinary reading does not — may other people keep a copy // that follows this repository, not just may THIS caller see it once. // A private repository answers no regardless of the mirrorable flag // (MayMirror enforces that); either refusal returns the same "not // found" a caller cannot distinguish from a repository that simply // is not there (RFC 0004's invisible-not-forbidden posture). func (rg *registrar) SyncReadGate(req *http.Request, repo, login string) bool { ctx, ok := rg.syncCtx(req, login) if !ok { return false } if !rg.CanRead(ctx, repo) { // Says WHO was refused, which separates "nobody identified // themselves" from "this account may not read this" — the two // cases a bare 404 makes identical, and the pair that kept a // private repository unclonable while every measurement from // outside said the same thing. who := ops.User(ctx) if who == "" { who = "an unidentified caller" } log.Printf("sync: %s: read refused: %s may not read it", repo, who) return false } if rg.odb == nil { return true } // MayMirror asks "may OTHER PEOPLE keep a copy of this", and it // answers no for every private repository by construction. Asked of // every caller it locked the door on the way in: a private // repository could not be cloned or synced by anyone at all, // including the account that owns it, which is not a policy anyone // chose — it is "other people" quietly meaning "everyone". // // A caller who has identified themselves and already satisfied // CanRead is not other people. They are someone this repository // admits, so the third-party question does not apply to them and // the flag is not theirs to be refused by. // // Anonymous callers still meet it unchanged: that is who the flag // was written for, and a public repository with mirroring off still // answers no to a stranger. if ops.User(ctx) != "" { return true } ok, err := rg.odb.MayMirror(repo) if err != nil { log.Printf("sync: mirrorable check for %s: %v", repo, err) return false } return ok } // identityCtx resolves a sync request's Basic credentials into the // context the visibility gate reads. // // The sync protocol carries its own login card, but that is verified // deeper in (and only for pushes). For the visibility question — may // this caller see the repository at all — the HTTP credential is what // is available before a single byte of the body is parsed, which is // where the decision has to be made. // syncIdentityCtx is identityCtx for the SYNC lane, where the Basic // password slot may also carry the account's sync token. // // A clone's first round has no login card to sign — the client does // not know the project code yet — so fossil answers the 401 with Basic // and zit retries with Basic, each putting the credential it holds in // the password slot. For a client set up with the sync token, that is // the token; the account password never reaches a sync client on // purpose (a push signed with it is refused). Read by identityCtx // alone, the token was a wrong password: an identified caller nobody // recognised, told 404, and every private repository was unclonable by // the token minted for it, however correctly the gate would have judged // the account (2bb5659e, measured by jva). // // Only the sync lane takes the token here. The API's Basic lane is // identityCtx itself and still wants the password: the token is the // credential for sync, and is not widened into a second password. // // RFC 0021: any live sync-scoped token of the account's opens it, by id // or, for a credential minted before tokens had ids, by its value; the // token rides the context so the visibility answer is the token's, // ceiling and repository list included. func syncIdentityCtx(req *http.Request, doors *tokenDoors) context.Context { if doors == nil { return req.Context() } ctx := identityCtx(req, doors.db) if ops.User(ctx) != "" || doors.db == nil { return ctx } tok, p := doors.resolve(req, oltp.ScopeSync) if p != resolved { return ctx } user, _, _ := req.BasicAuth() return doors.tokenCtx(ctx, user, tok) } // tokenDoors is rg.doors, or an uncounted resolver over rg.odb. func (rg *registrar) tokenDoors() *tokenDoors { if rg.doors != nil { return rg.doors } return &tokenDoors{db: rg.odb} } func identityCtx(req *http.Request, db *oltp.DB) context.Context { ctx := req.Context() user, pass, ok := req.BasicAuth() if !ok || user == "" || db == nil { return ctx } if _, authed := db.Authenticate(user, pass); !authed { return ctx } return ops.WithUser(ctx, user) } // Delete stops serving a repository and destroys it: the store on disk, // its derived index, and everything in the forge database keyed to it. // // confirm must equal the repository's name. That is the standard // pattern because it is the only one that works: a yes/no prompt is // answered reflexively, while typing the name requires having read // which repository is about to go. // // The store on disk is removed ONLY when quarry created it — that is, // when it lives under the repositories root. quarry serves stores it // did not create and does not own, and the corpus this forge runs on is // exactly that: deleting a repository named by --repo would destroy a // checkout somebody else manages. Those refuse, and say to unregister // instead. func (rg *registrar) Delete(name, confirm string) error { if rg.odb == nil { return fmt.Errorf("no forge database: %w", ops.ErrUnavailable) } if confirm != name { return fmt.Errorf("%w: type the repository's name to confirm deletion", ops.ErrInvalid) } row, found, err := rg.odb.RepoByName(name) if err != nil { return err } if !found { return fmt.Errorf("no repository %q: %w", name, ops.ErrNotFound) } if err := rg.refuseTakenDown(name); err != nil { return err } ours, err := rg.owns(row.Path) if err != nil { return err } if !ours { return fmt.Errorf("%w: %s is outside this node's repositories root, so quarry did not "+ "create it and will not delete it — use remove to stop serving it", ops.ErrInvalid, row.Path) } // Read before Unregister, which forgets it. A repository that was // never served is asked its store directly. chatKey, _ := rg.odb.ChatKey(name) // Stop serving before touching anything: Unregister waits for the // poll loop to exit and closes the index, and removing files under a // live fold is how a deletion takes the process with it. if err := rg.Unregister(name); err != nil && !errors.Is(err, ops.ErrNotFound) { return err } // What the repository left outside the forge database goes before // its registration does, so a failure here leaves the name // registered and the delete retryable, rather than a new owner // inheriting it (quarry#294). // Asked again here: a takedown placed since the check above must // still stop the delete before anything outside the database goes. if err := rg.refuseTakenDown(name); err != nil { return err } if err := rg.forget(name, chatKey); err != nil { return err } if err := rg.odb.PurgeRepo(name); err != nil { return err } rg.refreshPrivate() // Derived data first — it is rebuildable, so a failure here is // recoverable, while a half-removed store is not. if err := os.RemoveAll(filepath.Join(rg.dir, name)); err != nil { log.Printf("delete %s: derived data: %v", name, err) } rg.forgetGitDirs(name) removeErr := os.RemoveAll(row.Path) // Again, now that the caps the mint form is gated on are gone: a // token minted between the first sweep and the purge would // otherwise be the one the next repository of this name inherits. // Whatever became of the store — the name is free either way. if err := rg.revokeWorkerTokens(name); err != nil { return errors.Join(removeErr, fmt.Errorf("delete %s: the repository is gone, but a worker token "+ "minted during the delete may still be live — revoke worker group %s's tokens at the engine: %w", name, ci.GroupFor(name), err)) } return removeErr } // forget erases what a repository being deleted holds outside the forge // database: the engine's worker tokens scoped to its group, its chat // channel, its ingest cursors, consumers and store events, and its // attention events, event log and tallies. func (rg *registrar) forget(name, chatKey string) error { if err := rg.revokeWorkerTokens(name); err != nil { return fmt.Errorf("delete %s: worker tokens: %w", name, err) } // The channel is this repository's alone, so it goes with it // whatever else holds its project code. if chatKey != "" { if rg.deps != nil && rg.deps.Chat != nil { if err := rg.deps.Chat.PurgeChannel(chatKey); err != nil { return fmt.Errorf("delete %s: %w", name, err) } } if err := rg.odb.PurgeRobotLines(chatKey); err != nil { return fmt.Errorf("delete %s: robot lines: %w", name, err) } } if err := ingest.Forget(rg.ev, name, rg.node); err != nil { return fmt.Errorf("delete %s: %w", name, err) } if err := rg.ev.ForgetRepo(name); err != nil { return fmt.Errorf("delete %s: %w", name, err) } return nil } // revokeWorkerTokens revokes every live engine token scoped to the // repository's worker group. The group is derived from the name, so a // token left live would claim work in any later repository of the same // name — and satisfy its required checks. A token scoped to several // groups goes too: the engine cannot narrow one, and keeping it keeps // that reach. // // A configured engine that cannot list its tokens is a refusal, for any // reason: quarry cannot tell "none exist" from "none it can see", and // guessing the first is how a live token outlives its repository. Only // a forge with no engine at all has nothing to revoke. func (rg *registrar) revokeWorkerTokens(name string) error { if !rg.engine.Enabled() { return nil } tokens, err := rg.engine.WorkerTokens() if err != nil { return fmt.Errorf("%w: cannot list the CI engine's worker tokens to revoke %s's (%v); "+ "give quarry the engine's admin token (--dagnats-token), or revoke the tokens scoped "+ "to worker group %s at the engine, then delete again", ops.ErrUnavailable, name, err, ci.GroupFor(name)) } for _, t := range liveTokensReaching(tokens, ci.GroupFor(name)) { if err := rg.engine.RevokeWorkerToken(t.ID); err != nil { return err } } return nil } // liveTokensReaching is the live tokens among tokens that can claim work // in group: scoped to it, or (a site admin's fleet token) reaching it by // task type, since a scope admits the whole type or a namespace it // continues after a dot, and a repository's task types are // <group>.<run>. func liveTokensReaching(tokens []ci.WorkerToken, group string) []ci.WorkerToken { var out []ci.WorkerToken for _, t := range tokens { if t.RevokedAt != "" { continue } if slices.Contains(t.WorkerGroups, group) || slices.ContainsFunc(t.TaskTypePrefixes, func(p string) bool { return p == group || strings.HasPrefix(p, group+".") }) { out = append(out, t) } } return out } // refuseInheritedTokens refuses a new repository whose worker group a // live engine token already reaches (#307). The group is the name, so // such a token, left by a deleted repository of the same name whose // revocation failed or was never confirmed, would claim the newcomer's // CI work and satisfy its required checks. Fleet tokens reach every // group by design and are not counted: they are the site admin's own. // An engine that cannot list its tokens is a refusal, as at delete: // quarry cannot tell "none" from "none it can see". func (rg *registrar) refuseInheritedTokens(name string) error { if !rg.engine.Enabled() { return nil } tokens, err := rg.engine.WorkerTokens() if err != nil { return fmt.Errorf("%w: cannot ask the CI engine whether a worker token still reaches worker group %s (%v); "+ "a token left by an earlier repository named %q would run this one's CI, so the name is held until the engine answers", ops.ErrUnavailable, ci.GroupFor(name), err, name) } group := ci.GroupFor(name) for _, t := range liveTokensReaching(tokens, group) { if slices.Contains(t.WorkerGroups, group) { return fmt.Errorf("%w: worker token %s at the CI engine still reaches worker group %s, left by an earlier repository named %q; "+ "revoke it at the engine, then create this repository", ops.ErrInvalid, t.ID, group, name) } } return nil } // owns reports whether a path lies under this node's repositories root. func (rg *registrar) owns(path string) (bool, error) { if rg.reposRoot == "" { return false, nil } root, err := filepath.Abs(rg.reposRoot) if err != nil { return false, err } abs, err := filepath.Abs(path) if err != nil { return false, err } return strings.HasPrefix(abs, root+string(os.PathSeparator)), nil } // Deletable reports whether this node created the repository's store. func (rg *registrar) Deletable(name string) bool { if rg.odb == nil { return false } row, found, err := rg.odb.RepoByName(name) if err != nil || !found { return false } ours, err := rg.owns(row.Path) return err == nil && ours } // storeStamp is a store file's identity for the poll loop: the store // and its write-ahead log, by size and mtime. Reads — zit frames, ls, // cat — leave both alone; every write moves one of them. type storeStamp struct { ok bool size, walSize int64 mod, walMod time.Time } // stampStore stamps the store under path (a checkout directory holding // .zit, or the store file itself). A store the stat cannot see is not // ok, and the loop polls it every tick as it always did — going quiet // on a store that is fine but named differently would be the worse // failure. // withCurrent is a store's stats with a tick that found it unmoved // counted as a success. An idle store completes no rounds, and its last // success was read as "the poller is not completing them": every quiet // store showed behind two minutes after a restart. A tick that found // nothing new is as good as a round, while the last round held. func withCurrent(s ingest.Stats, current int64) ingest.Stats { if current == 0 || s.Failures > 0 || s.Stalled { return s } if t := time.Unix(0, current); t.After(s.LastOK) { s.LastOK = t } return s } func stampStore(path string) storeStamp { file := path if fi, err := os.Stat(path); err == nil && fi.IsDir() { file = filepath.Join(path, ".zit") } var st storeStamp fi, err := os.Stat(file) if err != nil { return st } st.ok = true st.size, st.mod = fi.Size(), fi.ModTime() if wal, err := os.Stat(file + "-wal"); err == nil { st.walSize, st.walMod = wal.Size(), wal.ModTime() } return st } // originCheckURL is the public page the promise is checked on, or "" // when the forge does not know its own public address — in which case // there is nothing to check FROM outside, and the dep is skipped. // // The root, because that is the page most readers actually receive. A // redirect to a sign-in page is followed and is still a page a reader // gets, which is the thing being asserted about. func originCheckURL(origin string) string { // Space first, then the slash: the other order leaves a trailing // slash attached to a padded value and builds "https://host//". origin = strings.TrimSuffix(strings.TrimSpace(origin), "/") if origin == "" { return "" } return origin + "/" } // claim records the deed and the namespace for a repository that has // just been registered. // // The creator owns what they create, and a repository created by a // person starts in that person's own namespace -- the personal case // needs no arranging, which is the whole point of deriving the path // from the owner. Putting it under a team is a separate, later act // with its own permission check. // // A repository created with no author is forge-held: an operator // serving a store rather than a person hosting a project. It keeps an // empty owner rather than being attributed to whoever happened to run // the command. // // Failure here is logged, not fatal. The repository exists and is // served either way, and a missing deed is recoverable by assigning // one; refusing the creation because the bookkeeping row would not // write would be the worse trade. // // A repository an AGENT creates is deeded to its operator (RFC 0021): // the agent acts and the operator owns, as with everything else an // agent does, and the namespace is the operator's handle. The // check-in's author stays the agent, which is what history shows. A // FORGE agent has no operator; one it creates is deeded to the admin // who answers for it (deedHolder), so deleting it later waits for that // admin's sign-off like any repository the agent does not hold (#359). func (rg *registrar) claim(spec api.RepoSpec) error { owner := rg.deedHolder(spec.Author) if rg.odb == nil { return nil } // Nobody holds it: it appears under the forge's namespace until // somebody stewards it (RFC 0025). if owner == "" { return rg.odb.SetNamespace(spec.Name, oltp.ForgeNamespace, spec.Author, time.Now()) } if err := rg.odb.SetOwner(spec.Name, owner); err != nil { return fmt.Errorf("recording %s as owner of %s: %w", owner, spec.Name, err) } if err := rg.odb.SetNamespace(spec.Name, owner, spec.Author, time.Now()); err != nil { return fmt.Errorf("placing %s under %s: %w", spec.Name, owner, err) } return nil } // settle gives a repository just written its owner, its place and its // name, in that order, so it never passes through an address it is not // meant for (RFC 0025): a repository made in a team is put in the team // before it takes its name, or its name would first meet its owner's own // repositories. Any step refused takes the row back out. func (rg *registrar) settle(spec api.RepoSpec, handle string) error { err := rg.claim(spec) if err == nil && spec.Namespace != "" && spec.Namespace != rg.deedHolder(spec.Author) { err = rg.odb.SetTeamRepo(spec.Namespace, spec.Name, spec.Author) } if err == nil && spec.Name != handle { err = rg.odb.SetHandle(spec.Name, handle) } if err != nil { if derr := rg.odb.DeleteRepo(spec.Name); derr != nil { log.Printf("repo.add %s: rollback failed: %v", spec.Name, derr) } return fmt.Errorf("%w: %v", ops.ErrInvalid, err) } return nil } // deedHolder is who holds the deed to a repository author creates: // the author; the operator when the author is a person's agent; the // site admin answerable for it when the author is a forge agent (RFC // 0021). "" for no author, and for an agent nobody answers for. func (rg *registrar) deedHolder(author string) string { if rg.odb == nil || author == "" { return "" } if rg.odb.IsForgeAgent(author) { return rg.odb.Answerable(author) } if rg.odb.IsAgent(author) { op := rg.odb.Operator(author) // A repository's or a team's agent creates no repositories: its // operator is a scope, not a person who could hold the deed. if strings.HasPrefix(op, "repo:") || strings.HasPrefix(op, "team:") { return "" } return op } return author } // Owner is who will own a repository author creates (deedHolder), or // a refusal when the author is an agent nobody answers for: such a // repository would have no owner but a site admin. func (rg *registrar) Owner(author string) (string, error) { owner := rg.deedHolder(author) if owner == "" && author != "" && rg.odb != nil && (rg.odb.IsAgent(author) || rg.odb.IsForgeAgent(author)) { return "", fmt.Errorf("%w: %s answers to no admin, so a repository it created would have no owner", ops.ErrForbidden, author) } return owner, nil } // leaseRefusal reports a write the lease refused as ops.ErrUnavailable, // the answer every op already turns into "try again". The lease's own // error stays in the chain: the CI poller must tell "another node // holds this store", which retrying here never fixes, from a // coordinator that is briefly unreachable. func leaseRefusal(err error) error { if errors.Is(err, lease.ErrNotHolder) || errors.Is(err, lease.ErrUnavailable) { return fmt.Errorf("%w: %w", ops.ErrUnavailable, err) } return err } // upkeepRebuild is the one forge agent's rebuild the forge runs at a // time; upkeepMaxStore the largest store an agent may rebuild unasked. // Past it a rebuild is hours and the memory a large store needs (one // took the forge down on 2026-10-13), which is an operator's call. var upkeepRebuild atomic.Bool const upkeepMaxStore = 512 << 20 // upkeepRefusal says why a forge agent's rebuild of name may not start, // with running rebuilds under way and a store of size bytes, or nil. func upkeepRefusal(name string, running int, size int64) error { if running > 0 { return fmt.Errorf("%d rebuilds are running; try again when the forge is quiet: %w", running, ops.ErrUnavailable) } if size <= 0 { return fmt.Errorf("the size of %s could not be read, so it is not rebuilt unasked: %w", name, ops.ErrUnavailable) } if size > upkeepMaxStore { return fmt.Errorf("%s is %d MiB, past the %d MiB a forge agent may rebuild unasked; a site admin can: %w", name, size>>20, int64(upkeepMaxStore)>>20, ops.ErrForbidden) } return nil } // A rebuild empties the repository's derived tables while it replays // them, so its timeline and search read thin until it ends: an agent // rebuilds one repository at most once a day, and the forge takes the // next agent's rebuild only a while after the last one ended, so no // agent walks the fleet. const ( upkeepPerRepo = 24 * time.Hour upkeepGap = 10 * time.Minute ) var upkeepLast = struct { sync.Mutex repo map[string]time.Time any time.Time }{repo: map[string]time.Time{}} // upkeepSpaced refuses a rebuild of name at now that comes too soon. func upkeepSpaced(name string, now time.Time) error { upkeepLast.Lock() defer upkeepLast.Unlock() if at, ok := upkeepLast.repo[name]; ok && now.Sub(at) < upkeepPerRepo { return fmt.Errorf("%s was rebuilt by a forge agent %s ago; once a day: %w", name, now.Sub(at).Round(time.Minute), ops.ErrUnavailable) } if !upkeepLast.any.IsZero() && now.Sub(upkeepLast.any) < upkeepGap { return fmt.Errorf("a forge agent's rebuild ended %s ago; the next waits %s: %w", now.Sub(upkeepLast.any).Round(time.Second), upkeepGap, ops.ErrUnavailable) } return nil } // upkeepDone records an agent's rebuild of name as ended. func upkeepDone(name string, now func() time.Time) { upkeepLast.Lock() defer upkeepLast.Unlock() t := now() upkeepLast.repo[name], upkeepLast.any = t, t } // storeBytes is the size of the store at path: the file, or the .zit // inside a directory. Zero when it cannot be read, which an upkeep // rebuild then attempts and fails on like any other. func storeBytes(path string) int64 { fi, err := os.Stat(path) if err != nil { return 0 } if fi.IsDir() { if fi, err = os.Stat(filepath.Join(path, ".zit")); err != nil { return 0 } } return fi.Size() } // isMirror reports a repository that tracks an upstream. func (rg *registrar) isMirror(name string) bool { if rg.deps == nil || rg.deps.Mirrors == nil { return false } _, ok, err := rg.deps.Mirrors.MirrorFor(name) return err != nil || ok }