@zabaca/zbc 0.16.4 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,360 @@
1
+ /**
2
+ * Proposals: the one push a claimed name takes from someone not on its Signer
3
+ * List (docs/adr/0018).
4
+ *
5
+ * A Proposal is a ref under `refs/walgit/proposals/<target>/<id>` naming a
6
+ * commit its pusher wants in `refs/heads/<target>`, plus the Push Certificate
7
+ * behind it, and nothing else. There is no record, no row and no file: whether
8
+ * it is Merged is `merge-base --is-ancestor` against the target, computed on
9
+ * read from the Cache and never written down.
10
+ *
11
+ * Three questions live here and all three are pure:
12
+ *
13
+ * - `parseProposalRef` — what a ref NAMES. The target is in the ref name
14
+ * rather than derived from the commit, so `ls-remote` shows it and nothing
15
+ * has to be parsed to list what is open.
16
+ * - `checkProposalRefs` — whether the host will hold it. A Proposal aimed at
17
+ * a branch that does not exist, at something that is not a branch, or
18
+ * pointing at an object that is not a commit, is refused in `pre-receive`
19
+ * rather than stored: append-only means a ref written here can never be
20
+ * deleted, so the one moment to refuse junk is before it lands.
21
+ * - `listProposals` — what the repository HOLDS, for the read surface
22
+ * (`GET /<name>.git/proposals`). It is handed the Index's refs, the Index's
23
+ * provenance and an ancestry predicate, and it stores nothing: Merged is
24
+ * recomputed on every read, because a Proposal that became merged did so by
25
+ * someone pushing the target, and nothing told this host about it.
26
+ *
27
+ * WHO may write one is deliberately not here. That is the Signer List gate's
28
+ * question — `checkSignerAllowed` in `src/signers.ts` — because the rule is
29
+ * *whoever may read may propose*, and reading is a Reader List's answer, which
30
+ * that gate already holds. Splitting it the other way would have put half of
31
+ * ownership in this file.
32
+ *
33
+ * Off unless the instance turns it on, like every capability in this package.
34
+ * With the flag off `refs/walgit/proposals/…` is an ordinary ref namespace
35
+ * under the ordinary gate: nothing widens and nothing is validated.
36
+ */
37
+
38
+ import { flagEnabled } from '../shared/policy'
39
+ import { ZERO_OID } from '../shared/protocol'
40
+ import { git } from './git'
41
+ import type { Provenance, RefChange } from './wal-index'
42
+
43
+ /** The env flag an instance sets to take Proposals. */
44
+ export function proposalsEnabled(env: Record<string, string | undefined> = process.env): boolean {
45
+ return flagEnabled(env.WALGIT_PROPOSALS)
46
+ }
47
+
48
+ /**
49
+ * The namespace, with its trailing slash — so `startsWith` cannot match a ref
50
+ * called `refs/walgit/proposalsomething`.
51
+ */
52
+ export const PROPOSALS_PREFIX = 'refs/walgit/proposals/'
53
+
54
+ /** The branch a Proposal wants its commit in, spelled as a ref. */
55
+ export const targetRef = (target: string): string => `refs/heads/${target}`
56
+
57
+ export interface Proposal {
58
+ /** The branch this Proposal is for, WITHOUT the `refs/heads/` prefix. */
59
+ target: string
60
+ /** The pusher's word. The host assigns nothing and collisions are refused. */
61
+ id: string
62
+ }
63
+
64
+ /**
65
+ * What a ref names, or `null` when it names no Proposal.
66
+ *
67
+ * The id is the LAST segment and the target is everything before it, which is
68
+ * the only split that lets a target be a branch with slashes in it — `feat/login`
69
+ * is an ordinary branch name, and an agent proposing to one must not have to
70
+ * know this ref is parsed at all.
71
+ *
72
+ * Both halves must be non-empty, so `…/main` (no id) and `…/main/` (no id) and
73
+ * `…//fix` (no target) name nothing. That is a refusal rather than a guess:
74
+ * every one of them is a client that meant something this host cannot tell.
75
+ */
76
+ export function parseProposalRef(ref: string): Proposal | null {
77
+ if (!ref.startsWith(PROPOSALS_PREFIX)) return null
78
+ const rest = ref.slice(PROPOSALS_PREFIX.length)
79
+ const cut = rest.lastIndexOf('/')
80
+ if (cut <= 0) return null
81
+ const target = rest.slice(0, cut)
82
+ const id = rest.slice(cut + 1)
83
+ if (target === '' || id === '') return null
84
+ return { target, id }
85
+ }
86
+
87
+ /** Is this ref in the namespace at all, well-formed or not? */
88
+ export const isProposalRef = (ref: string): boolean => ref.startsWith(PROPOSALS_PREFIX)
89
+
90
+ /**
91
+ * What the shape check is asked of: the refs this repository holds, and what
92
+ * an object is.
93
+ *
94
+ * The refs come from the **Index**, not from the Cache, for the reason the gate
95
+ * reads its Signer List there — the Cache is disposable, and a target that
96
+ * existed only on whichever node happened to have materialized would make a
97
+ * refusal depend on which container answered.
98
+ *
99
+ * The object type is a subprocess against the quarantine, injected so every
100
+ * decision here is testable without a repository — the same seam
101
+ * `src/signers.ts` puts in front of its blob reader.
102
+ */
103
+ export interface ProposalSource {
104
+ /** The repository's refs, as the Index holds them: ref → oid. */
105
+ refs: Readonly<Record<string, string>>
106
+ /** `commit`, `tree`, `blob`, `tag` — or `null` for an object git cannot see. */
107
+ objectType: (oid: string) => string | null
108
+ }
109
+
110
+ /** The real object reader: the pushed objects are in the hook's object path. */
111
+ export function gitObjectType(gitDir: string): (oid: string) => string | null {
112
+ return (oid) => {
113
+ const res = git(['--git-dir', gitDir, 'cat-file', '-t', oid])
114
+ if (res.status !== 0) return null
115
+ const type = res.stdout.trim()
116
+ return type === '' ? null : type
117
+ }
118
+ }
119
+
120
+ /** Every way a Proposal can be malformed. */
121
+ export type ProposalRefusal =
122
+ /** The ref is in the namespace and names no `<target>/<id>`. */
123
+ | 'grammar'
124
+ /** `refs/heads/<target>` is not a ref this repository holds. */
125
+ | 'missing-target'
126
+ /** The target is not a branch — it names something outside `refs/heads/`. */
127
+ | 'not-a-branch'
128
+ /** The tip is a tree, a blob, a tag, or an object the host cannot see. */
129
+ | 'not-a-commit'
130
+
131
+ export type ProposalVerdict =
132
+ | { ok: true }
133
+ | { ok: false; kind: ProposalRefusal; ref: string; message: string }
134
+
135
+ /**
136
+ * Judge every Proposal ref a push writes. Refs outside the namespace are
137
+ * somebody else's question and are passed over.
138
+ *
139
+ * A DELETION is passed over too: it has no tip to be a commit and no Proposal
140
+ * to validate, and whether a ref here may be removed at all is append-only's
141
+ * answer rather than this one's. On the deployment ADR-0018 is written for
142
+ * append-only is on, so there is nothing to delete with.
143
+ *
144
+ * The first offending ref decides the push, as append-only's judge does and for
145
+ * the same reason: a push is all or nothing to git, so a second refusal would
146
+ * only make the message longer than an agent reads.
147
+ */
148
+ export function checkProposalRefs(
149
+ repoId: string,
150
+ changes: readonly RefChange[],
151
+ source: ProposalSource,
152
+ ): ProposalVerdict {
153
+ for (const change of changes) {
154
+ if (!isProposalRef(change.ref)) continue
155
+ if (change.newOid === ZERO_OID) continue
156
+
157
+ const proposal = parseProposalRef(change.ref)
158
+ if (!proposal) return refuse(repoId, 'grammar', change.ref, 'names no target and id')
159
+
160
+ if (proposal.target.startsWith('refs/')) {
161
+ return refuse(
162
+ repoId,
163
+ 'not-a-branch',
164
+ change.ref,
165
+ `its target \`${proposal.target}\` is not a branch — a Proposal names one under refs/heads/`,
166
+ )
167
+ }
168
+
169
+ const target = targetRef(proposal.target)
170
+ if (source.refs[target] === undefined) {
171
+ return refuse(repoId, 'missing-target', change.ref, `${target} does not exist here`)
172
+ }
173
+
174
+ const type = source.objectType(change.newOid)
175
+ if (type !== 'commit') {
176
+ return refuse(
177
+ repoId,
178
+ 'not-a-commit',
179
+ change.ref,
180
+ `it points at ${type ?? 'an object this host cannot read'}, not a commit`,
181
+ )
182
+ }
183
+ }
184
+ return { ok: true }
185
+ }
186
+
187
+ const refuse = (
188
+ repoId: string,
189
+ kind: ProposalRefusal,
190
+ ref: string,
191
+ why: string,
192
+ ): Extract<ProposalVerdict, { ok: false }> => ({
193
+ ok: false,
194
+ kind,
195
+ ref,
196
+ message: rejectionMessage(repoId, ref, why),
197
+ })
198
+
199
+ /**
200
+ * What a malformed Proposal reads. Product copy, like every other refusal on
201
+ * this path: an agent that cannot act on a refusal has been told nothing, and
202
+ * this one is most often read by an agent that has just learned Proposals
203
+ * exist.
204
+ */
205
+ function rejectionMessage(repoId: string, ref: string, why: string): string {
206
+ return [
207
+ `walgit: refused — ${ref} is not a Proposal ${repoId} can hold: ${why}.`,
208
+ '',
209
+ 'A Proposal is a ref naming the commit you want in an existing branch:',
210
+ '',
211
+ ` git push --signed=yes origin HEAD:${PROPOSALS_PREFIX}<branch>/<your-id>`,
212
+ '',
213
+ 'The branch is the one you want it merged into and must already exist here;',
214
+ 'the id is your own word for this change, and a taken one is refused as a',
215
+ 'non-fast-forward, so pick another. Refs here are append-only like every',
216
+ 'other, which is why a Proposal is judged before it is stored rather than',
217
+ 'after.',
218
+ '',
219
+ 'Nothing was uploaded; the repository is unchanged.',
220
+ ].join('\n')
221
+ }
222
+
223
+ // ── The read surface ────────────────────────────────────────────────────────
224
+
225
+ /**
226
+ * One Proposal, as `GET /<name>.git/proposals` reports it (docs/adr/0018).
227
+ *
228
+ * Every field is derived: the id and the target from the ref NAME, the tip from
229
+ * the Index, the pusher from the Provenance the Index already records, and
230
+ * `merged` from ancestry at the moment of the read. Nothing here is state
231
+ * walgit keeps — there is no row to go stale and nothing a Materialize could
232
+ * fail to rebuild.
233
+ */
234
+ export interface ProposalListing extends Proposal {
235
+ /** The commit the pusher wants in the target. */
236
+ tip: string
237
+ /**
238
+ * The key that signed the push that put the tip there, or `null`.
239
+ *
240
+ * `null` rather than an omitted field, because absence is an ordinary answer
241
+ * here: signing is what a deployment taking Proposals demands, but a
242
+ * repository can hold refs from before the Index recorded provenance at all,
243
+ * and a reader should not have to tell a missing key from a missing field.
244
+ */
245
+ pusher: string | null
246
+ /** Its tip is an ancestor of the target's tip. Computed, never stored. */
247
+ merged: boolean
248
+ }
249
+
250
+ /**
251
+ * Does `tip` reach `ancestorOf`? The one question `merged` is.
252
+ *
253
+ * Injected so the listing is pure and so the ONLY place that spawns git for
254
+ * this is `gitAncestry` below — the same seam `ProposalSource.objectType` puts
255
+ * in front of the hook's object reader.
256
+ */
257
+ export type Ancestry = (tip: string, ancestorOf: string) => boolean
258
+
259
+ /**
260
+ * The real predicate: `merge-base --is-ancestor` against the Cache.
261
+ *
262
+ * The Cache, deliberately, and it is the one thing on this path not read from
263
+ * the Index: the Index knows where refs point and holds no commits, so ancestry
264
+ * cannot be answered from it at all. The caller's job is to have synced the
265
+ * Cache first (`src/sync.ts`) — a cold container Materializes there, which is
266
+ * what makes an answer from a disposable disk as true as one from the log.
267
+ *
268
+ * Exit 0 is yes, 1 is no, and anything else — a commit this disk does not hold
269
+ * — is NOT merged. Reading a missing object as merged would mark a Proposal
270
+ * accepted on the strength of a failed subprocess, which is the one direction a
271
+ * later read cannot take back.
272
+ */
273
+ export function gitAncestry(gitDir: string): Ancestry {
274
+ return (tip, ancestorOf) =>
275
+ git(['--git-dir', gitDir, 'merge-base', '--is-ancestor', tip, ancestorOf]).status === 0
276
+ }
277
+
278
+ /**
279
+ * Every Proposal a repository holds, in ref order.
280
+ *
281
+ * Sorted by ref name rather than left in whatever order the Index's object
282
+ * happens to serialize, so a client diffing two reads sees only what changed.
283
+ *
284
+ * A ref in the namespace that names no `<target>/<id>` is SKIPPED rather than
285
+ * reported. `pre-receive` refuses those, so one can only be here from before
286
+ * the flag was on — and the read surface is not the place to litigate a ref
287
+ * that is already written for good.
288
+ *
289
+ * Superseded is not derived. ADR-0018 admits it "if it is free", and it is not:
290
+ * it is ancestry between every pair of Proposals to the same target, which is a
291
+ * second quadratic walk for a field nothing has asked for yet.
292
+ */
293
+ /**
294
+ * What a push MERGED, per branch it moved: the ids of Proposals to that branch
295
+ * whose tip became an ancestor of the new tip (docs/adr/0018).
296
+ *
297
+ * The Ref Event a Watcher receives carries this, so an agent watching `main`
298
+ * learns a Proposal landed from the move itself rather than by reading the
299
+ * Proposal list again — the second call this whole stream exists to avoid.
300
+ *
301
+ * NEWLY, and that is the whole of the old oid's job here: a Proposal that was
302
+ * already an ancestor before this push merged on some earlier push, and
303
+ * re-announcing it on every subsequent commit to the branch would make the
304
+ * field a report of state rather than of what happened. A branch this push
305
+ * CREATED has no before, so everything it reaches is news.
306
+ *
307
+ * Only `refs/heads/` moves are asked about, and never a deletion: a branch that
308
+ * is gone is nothing to be an ancestor of, and a Proposal aimed at it is open —
309
+ * which is what `listProposals` reads it as too.
310
+ *
311
+ * Ids are sorted and a branch that merged nothing is left out entirely, so the
312
+ * caller has nothing to decide about an empty array.
313
+ */
314
+ export function mergedProposals(
315
+ changes: readonly RefChange[],
316
+ refs: Readonly<Record<string, string>>,
317
+ isAncestor: Ancestry,
318
+ ): Record<string, string[]> {
319
+ const merged: Record<string, string[]> = {}
320
+ for (const change of changes) {
321
+ if (!change.ref.startsWith('refs/heads/')) continue
322
+ if (change.newOid === ZERO_OID) continue
323
+ const target = change.ref.slice('refs/heads/'.length)
324
+ const ids: string[] = []
325
+ for (const ref of Object.keys(refs).toSorted()) {
326
+ const proposal = parseProposalRef(ref)
327
+ if (!proposal || proposal.target !== target) continue
328
+ const tip = refs[ref]!
329
+ if (!isAncestor(tip, change.newOid)) continue
330
+ const had = change.oldOid !== undefined && change.oldOid !== ZERO_OID
331
+ if (had && isAncestor(tip, change.oldOid!)) continue
332
+ ids.push(proposal.id)
333
+ }
334
+ if (ids.length > 0) merged[change.ref] = ids
335
+ }
336
+ return merged
337
+ }
338
+
339
+ export function listProposals(
340
+ refs: Readonly<Record<string, string>>,
341
+ provenance: Readonly<Record<string, Provenance>>,
342
+ isAncestor: Ancestry,
343
+ ): ProposalListing[] {
344
+ const listings: ProposalListing[] = []
345
+ for (const ref of Object.keys(refs).toSorted()) {
346
+ const proposal = parseProposalRef(ref)
347
+ if (!proposal) continue
348
+ const tip = refs[ref]!
349
+ const targetTip = refs[targetRef(proposal.target)]
350
+ listings.push({
351
+ ...proposal,
352
+ tip,
353
+ pusher: provenance[ref]?.signer ?? null,
354
+ // A target this repository no longer holds is nothing to be an ancestor
355
+ // of, so the Proposal is open — which is also what it is.
356
+ merged: targetTip !== undefined && isAncestor(tip, targetTip),
357
+ })
358
+ }
359
+ return listings
360
+ }
@@ -24,7 +24,13 @@ import { ZERO_OID } from '../shared/protocol'
24
24
  import { walKey } from './keys'
25
25
  import { writePending, type PendingPush } from './pending'
26
26
  import { certSigner } from './push-cert'
27
- import { checkSignerAllowed, describeSigner, type GateRefusal, type PushSigner } from './signers'
27
+ import {
28
+ checkSignerAllowed,
29
+ describeSigner,
30
+ type GateRefusal,
31
+ type ProposalGate,
32
+ type PushSigner,
33
+ } from './signers'
28
34
  import type { ObjectStore } from './store'
29
35
  import { ulid } from './ulid'
30
36
  import {
@@ -258,6 +264,16 @@ export interface PublishOptions {
258
264
  * settled in one place (`hook-main`), for both askings.
259
265
  */
260
266
  signerLists?: boolean
267
+ /**
268
+ * Proposals, as the gate needs them (docs/adr/0018) — minus the Reader List,
269
+ * which is read HERE, off the Claim this attempt is publishing onto.
270
+ *
271
+ * That split is the same rule as the Signer List beside it: who may propose
272
+ * is who may read, and who may read is a fact about the repository, which can
273
+ * move while a push uploads. Handing the list in from `pre-receive` would
274
+ * judge the re-ask against a repository that no longer exists.
275
+ */
276
+ proposals?: Omit<ProposalGate, 'readers'>
261
277
  }
262
278
 
263
279
  /**
@@ -378,6 +394,10 @@ export async function publishPush(
378
394
  index.claim?.signers ?? null,
379
395
  changes,
380
396
  'publish',
397
+ {
398
+ ...(options.proposals ?? { enabled: false, privateRepos: false }),
399
+ readers: index.claim?.readers ?? null,
400
+ },
381
401
  )
382
402
  if (!verdict.ok) {
383
403
  return { ok: false, reason: 'not-allowed', kind: verdict.kind, message: verdict.message }
@@ -0,0 +1,264 @@
1
+ /**
2
+ * Per-source rate limits: bound what one visitor can spend, in a window.
3
+ *
4
+ * The size caps beside this file (`src/limits.ts`) bound how big a push may be.
5
+ * They say nothing about how OFTEN one may arrive, and the two are different
6
+ * failures: a hundred 1 MiB pushes are each individually fine, and a hundred
7
+ * new names are each individually free. One container serves every repository
8
+ * (`wrangler.jsonc`, `max_instances: 1`), so a bored visitor filling the bucket
9
+ * during a traffic spike is not merely storage — it is the queue everyone else
10
+ * is behind.
11
+ *
12
+ * ── where the verdict is reached, and where it is spoken ────────────────────
13
+ *
14
+ * Reached in `src/http.ts`, because that is the only place that sees BOTH the
15
+ * source the edge attributed the request to and the repository it names: the
16
+ * hooks are processes git spawns, three down, and a header does not reach them.
17
+ * Spoken by `pre-receive`, because a refusal at the HTTP layer is a status code
18
+ * git reports as `RPC failed; HTTP …` — a transport fault, which a client
19
+ * retries. The handler therefore hands the backend a refusal and the hook
20
+ * prints it, so an over-limit push reads exactly the way an oversized one does:
21
+ * a `remote:` reject line naming the limit and what to do next.
22
+ *
23
+ * ── what a "source" is ──────────────────────────────────────────────────────
24
+ *
25
+ * Whatever the Worker can see, which is the client IP (`cf-connecting-ip`, set
26
+ * by Cloudflare at the edge and not forgeable by a client, since the container
27
+ * is reachable only through the Worker). A request carrying no such header is
28
+ * unattributable — a direct request to the container, a local deployment — and
29
+ * is NOT limited: pooling everything walgit cannot name into one bucket would
30
+ * make the first unattributable request throttle every other one.
31
+ *
32
+ * ── the counters are in memory, deliberately ────────────────────────────────
33
+ *
34
+ * A window that a container restart forgets. The alternative is a round trip to
35
+ * the object store on every push to enforce a limit whose entire purpose is to
36
+ * make a spike cheap, and the failure direction of forgetting is a visitor
37
+ * getting one more window than it should — against a Durable Object write per
38
+ * push, forever, on every deployment that turned this on. The table is capped
39
+ * so a spike of distinct addresses cannot grow it without bound.
40
+ *
41
+ * Every limit is UNSET by default, and an unset one is not enforced and not
42
+ * advertised — `capabilitiesFrom` (`shared/capabilities.ts`) is the one reading
43
+ * both this file and the three documents take their numbers from.
44
+ */
45
+
46
+ import type { Capabilities } from '../shared/capabilities'
47
+ import { describeBytes, describeWindow } from '../shared/policy'
48
+
49
+ export interface RateLimits {
50
+ /** The window every count below is taken over, in milliseconds. */
51
+ windowMs: number
52
+ /** New repository names one source may create per window. `null` is unlimited. */
53
+ maxNewRepos: number | null
54
+ /** Pushes one source may make per window. `null` is unlimited. */
55
+ maxPushes: number | null
56
+ /** Bytes one source may push per window. `null` is unlimited. */
57
+ maxPushBytes: number | null
58
+ }
59
+
60
+ /**
61
+ * The limits this instance enforces, as the four of the capabilities this file
62
+ * cares about — a projection, exactly as `limitsOf` is, so the number a page
63
+ * prints and the number a push is refused on cannot be arrived at two ways.
64
+ */
65
+ export function rateLimitsOf(caps: Capabilities): RateLimits {
66
+ return {
67
+ windowMs: caps.rateWindowSeconds * 1000,
68
+ maxNewRepos: caps.maxNewReposPerSource,
69
+ maxPushes: caps.maxPushesPerSource,
70
+ maxPushBytes: caps.maxPushBytesPerSource,
71
+ }
72
+ }
73
+
74
+ /** Is there anything to count? Nothing is tracked when there isn't. */
75
+ export function rateLimitsEnforced(limits: RateLimits): boolean {
76
+ return limits.maxNewRepos !== null || limits.maxPushes !== null || limits.maxPushBytes !== null
77
+ }
78
+
79
+ /** Does any configured limit need to know whether the name is a new one? */
80
+ export function countsNewRepos(limits: RateLimits): boolean {
81
+ return limits.maxNewRepos !== null
82
+ }
83
+
84
+ export type RateKind = 'new-repos' | 'pushes' | 'push-bytes'
85
+
86
+ export type RateVerdict = { ok: true } | { ok: false; kind: RateKind; message: string }
87
+
88
+ export interface RateCharge {
89
+ /** The client the edge attributed this request to. */
90
+ source: string
91
+ /** The repository this push names. */
92
+ repoId: string
93
+ /** Does this push bring a name into existence? */
94
+ creating: boolean
95
+ /** Bytes this push declared, or 0 when it declared none. */
96
+ bytes: number
97
+ }
98
+
99
+ /**
100
+ * How many sources one instance remembers at once.
101
+ *
102
+ * A bound rather than a tuning knob: this table is fed by whoever shows up, so
103
+ * an unbounded one is a memory leak an attacker chooses the size of. When it is
104
+ * full the least recently seen source is dropped — which forgives it, the same
105
+ * direction a restart forgives in, and the one that cannot refuse an innocent
106
+ * client because somebody else arrived.
107
+ */
108
+ const MAX_SOURCES = 10_000
109
+
110
+ type Spend = { at: number; bytes: number; creating: boolean }
111
+
112
+ export interface SourceLimiter {
113
+ /** Judge one push and, when it is allowed, charge it to its source. */
114
+ admit(charge: RateCharge): RateVerdict
115
+ }
116
+
117
+ /**
118
+ * The window, as a table of what each source spent in it.
119
+ *
120
+ * Charged only for pushes it ALLOWS. A refused push costs the client nothing
121
+ * further, so a client that keeps retrying is refused on the same spend rather
122
+ * than digging a deeper hole it cannot see the bottom of — and the window
123
+ * therefore always describes traffic walgit actually served.
124
+ */
125
+ export function createSourceLimiter(
126
+ limits: RateLimits,
127
+ now: () => number = Date.now,
128
+ ): SourceLimiter {
129
+ const spends = new Map<string, Spend[]>()
130
+
131
+ return {
132
+ admit(charge) {
133
+ const at = now()
134
+ const since = at - limits.windowMs
135
+
136
+ // Re-inserted on every touch, so Map iteration order is least-recently
137
+ // seen first and the eviction below drops the right one.
138
+ const previous = spends.get(charge.source)
139
+ spends.delete(charge.source)
140
+ const window = (previous ?? []).filter((spend) => spend.at > since)
141
+
142
+ const verdict = judge(limits, window, charge)
143
+ if (verdict.ok) window.push({ at, bytes: charge.bytes, creating: charge.creating })
144
+
145
+ if (window.length > 0) {
146
+ spends.set(charge.source, window)
147
+ if (spends.size > MAX_SOURCES) {
148
+ const oldest = spends.keys().next()
149
+ if (!oldest.done) spends.delete(oldest.value)
150
+ }
151
+ }
152
+ return verdict
153
+ },
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Judge one push against a source's window.
159
+ *
160
+ * Creation is judged FIRST, and the reason is the same one that puts the
161
+ * per-push size cap ahead of the per-repository one: when a push trips both, the
162
+ * actionable message is the one about the thing the client chose to do. "You
163
+ * have created enough new names" tells it to push to a name it already has;
164
+ * "you have pushed enough" would send it away from the host entirely for a
165
+ * push that would have been fine under a name it already owns.
166
+ */
167
+ function judge(limits: RateLimits, window: Spend[], charge: RateCharge): RateVerdict {
168
+ const window_ = describeWindow(limits.windowMs / 1000)
169
+
170
+ if (charge.creating && limits.maxNewRepos !== null) {
171
+ const created = window.filter((spend) => spend.creating).length
172
+ if (created >= limits.maxNewRepos) {
173
+ return {
174
+ ok: false,
175
+ kind: 'new-repos',
176
+ message: tooManyNewRepos(charge.repoId, limits.maxNewRepos, window_),
177
+ }
178
+ }
179
+ }
180
+
181
+ if (limits.maxPushes !== null && window.length >= limits.maxPushes) {
182
+ return { ok: false, kind: 'pushes', message: tooManyPushes(limits.maxPushes, window_) }
183
+ }
184
+
185
+ if (limits.maxPushBytes !== null) {
186
+ const spent = window.reduce((total, spend) => total + spend.bytes, 0)
187
+ if (spent + charge.bytes > limits.maxPushBytes) {
188
+ return {
189
+ ok: false,
190
+ kind: 'push-bytes',
191
+ message: tooManyBytes(spent, charge.bytes, limits.maxPushBytes, window_),
192
+ }
193
+ }
194
+ }
195
+
196
+ return { ok: true }
197
+ }
198
+
199
+ /**
200
+ * Product copy, and the same discipline the size caps are written with: say
201
+ * which limit, say the number, and say the one thing to do next. A rate limit
202
+ * is the refusal most likely to be read by something that will simply try
203
+ * again, so each message states that waiting is the remedy and roughly what
204
+ * for.
205
+ */
206
+ function tooManyNewRepos(repoId: string, cap: number, window: string): string {
207
+ return [
208
+ `walgit: refused — ${repoId} would be your ${cap + 1}${ordinal(cap + 1)} new repository this ${window}.`,
209
+ '',
210
+ `This host lets one client create ${cap} ${plural(cap, 'repository', 'repositories')} per ${window}.`,
211
+ 'This is a walgit limit, not a network failure. Retrying now will be refused',
212
+ 'again in the same way.',
213
+ '',
214
+ 'What you can do instead:',
215
+ ` - push to a name you already created — the limit is on NEW names, not on pushes`,
216
+ ` - or wait out the ${window} and push again`,
217
+ '',
218
+ 'Nothing was uploaded; no repository was created.',
219
+ ].join('\n')
220
+ }
221
+
222
+ function tooManyPushes(cap: number, window: string): string {
223
+ return [
224
+ `walgit: refused — you have already made ${cap} ${plural(cap, 'push', 'pushes')} this ${window}.`,
225
+ '',
226
+ `This host lets one client push ${cap} ${plural(cap, 'time', 'times')} per ${window}.`,
227
+ 'This is a walgit limit, not a network failure. Retrying now will be refused',
228
+ 'again in the same way.',
229
+ '',
230
+ 'What you can do instead:',
231
+ ' - combine your work into fewer pushes: commit locally, then push once',
232
+ ` - or wait out the ${window} and push again`,
233
+ '',
234
+ 'Nothing was uploaded; the repository is unchanged.',
235
+ ].join('\n')
236
+ }
237
+
238
+ function tooManyBytes(spent: number, bytes: number, cap: number, window: string): string {
239
+ return [
240
+ `walgit: refused — this push would take you past ${describeBytes(cap)} pushed this ${window}.`,
241
+ '',
242
+ `You have pushed ${describeBytes(spent)} in the last ${window} and this push adds`,
243
+ `${describeBytes(bytes)}.`,
244
+ 'This is a walgit limit, not a network failure. Retrying now will be refused',
245
+ 'again in the same way.',
246
+ '',
247
+ 'What you can do instead:',
248
+ ' - push less at once, or leave large files out of the repository entirely',
249
+ ` - or wait out the ${window} and push again`,
250
+ '',
251
+ 'Nothing was uploaded; the repository is unchanged.',
252
+ ].join('\n')
253
+ }
254
+
255
+ const plural = (n: number, one: string, many: string) => (n === 1 ? one : many)
256
+
257
+ /** `1st`, `2nd`, `3rd`, `4th` — the suffix only, so the number reads naturally. */
258
+ function ordinal(n: number): string {
259
+ if (n % 100 >= 11 && n % 100 <= 13) return 'th'
260
+ if (n % 10 === 1) return 'st'
261
+ if (n % 10 === 2) return 'nd'
262
+ if (n % 10 === 3) return 'rd'
263
+ return 'th'
264
+ }