@zabaca/zbc 0.12.0 → 0.13.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.
- package/CHANGELOG.md +63 -0
- package/package.json +2 -1
- package/templates/apps/inbox/package.json +1 -1
- package/templates/apps/walgit/CONTEXT.md +135 -0
- package/templates/apps/walgit/Dockerfile +40 -18
- package/templates/apps/walgit/README.md +518 -55
- package/templates/apps/walgit/e2e/README.md +100 -6
- package/templates/apps/walgit/e2e/harness.ts +262 -1
- package/templates/apps/walgit/e2e/live.ts +588 -0
- package/templates/apps/walgit/e2e/scenarios.ts +367 -5
- package/templates/apps/walgit/e2e/suite.ts +5 -5
- package/templates/apps/walgit/examples/watch.ts +209 -0
- package/templates/apps/walgit/package.json +12 -3
- package/templates/apps/walgit/registry.json +6 -11
- package/templates/apps/walgit/shared/capabilities.ts +189 -0
- package/templates/apps/walgit/shared/container-env.ts +114 -0
- package/templates/apps/walgit/shared/credentials.ts +81 -0
- package/templates/apps/walgit/shared/events.ts +277 -0
- package/templates/apps/walgit/shared/landing.ts +1241 -0
- package/templates/apps/walgit/shared/llms.ts +463 -0
- package/templates/apps/walgit/shared/outbox.ts +266 -0
- package/templates/apps/walgit/shared/policy.ts +59 -0
- package/templates/apps/walgit/shared/protocol.ts +197 -0
- package/templates/apps/walgit/shared/provenance.ts +154 -0
- package/templates/apps/walgit/shared/ref-cache.ts +181 -0
- package/templates/apps/walgit/shared/telemetry.ts +219 -0
- package/templates/apps/walgit/src/announce-main.ts +37 -0
- package/templates/apps/walgit/src/announce.ts +98 -0
- package/templates/apps/walgit/src/append-only.ts +112 -0
- package/templates/apps/walgit/src/cache.ts +172 -0
- package/templates/apps/walgit/src/cli.ts +493 -0
- package/templates/apps/walgit/src/compact.ts +25 -23
- package/templates/apps/walgit/src/delete-repo.ts +237 -0
- package/templates/apps/walgit/src/expire.ts +248 -0
- package/templates/apps/walgit/src/gc.ts +8 -16
- package/templates/apps/walgit/src/git-backend.ts +29 -0
- package/templates/apps/walgit/src/git.ts +78 -0
- package/templates/apps/walgit/src/hook-main.ts +259 -17
- package/templates/apps/walgit/src/hooks.ts +4 -3
- package/templates/apps/walgit/src/http.ts +237 -45
- package/templates/apps/walgit/src/instructions.ts +240 -0
- package/templates/apps/walgit/src/keys.ts +126 -0
- package/templates/apps/walgit/src/limits.ts +158 -0
- package/templates/apps/walgit/src/materialize.bench.ts +10 -10
- package/templates/apps/walgit/src/materialize.ts +48 -40
- package/templates/apps/walgit/src/mkdir-lock.ts +66 -0
- package/templates/apps/walgit/src/orphans.ts +2 -5
- package/templates/apps/walgit/src/pending.ts +201 -0
- package/templates/apps/walgit/src/push-cert.ts +254 -0
- package/templates/apps/walgit/src/push.ts +233 -46
- package/templates/apps/walgit/src/reconcile.ts +5 -8
- package/templates/apps/walgit/src/repo.ts +22 -77
- package/templates/apps/walgit/src/server.ts +148 -26
- package/templates/apps/walgit/src/signers.ts +577 -0
- package/templates/apps/walgit/src/store-env.ts +5 -4
- package/templates/apps/walgit/src/store.ts +47 -24
- package/templates/apps/walgit/src/usage.ts +404 -0
- package/templates/apps/walgit/src/verify.ts +171 -0
- package/templates/apps/walgit/src/wal-index.ts +189 -11
- package/templates/apps/walgit/tsconfig.json +8 -2
- package/templates/apps/walgit/tsconfig.worker.json +24 -0
- package/templates/apps/walgit/worker/events-do.ts +259 -0
- package/templates/apps/walgit/worker/index.ts +572 -0
- package/templates/apps/walgit/wrangler.jsonc +95 -0
- package/templates/apps/warehouse/package.json +1 -1
- package/templates/infra/modules/cloudflare/index.ts +77 -6
- package/templates/infra/modules/fly/index.ts +150 -10
- package/templates/infra/modules/turso/index.ts +43 -3
- package/templates/infra/package.json +1 -1
- package/templates/apps/walgit/entrypoint.sh +0 -59
- package/templates/apps/walgit/fly.toml +0 -52
- package/templates/apps/walgit/src/ssh-shell.ts +0 -36
- package/templates/apps/walgit/sshd_config +0 -38
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
* See this repository's docs/adr/0007-walgit-object-storage-holds-the-log.md.
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import { SIGNERS_REF, ZERO_OID } from '../shared/protocol'
|
|
13
|
+
import { indexKey } from './keys'
|
|
12
14
|
import type { ObjectStore, PutResult } from './store'
|
|
13
15
|
|
|
14
16
|
export type WalEntryKind = 'push' | 'compaction'
|
|
@@ -44,6 +46,22 @@ export interface Tombstone {
|
|
|
44
46
|
collect_after: string
|
|
45
47
|
}
|
|
46
48
|
|
|
49
|
+
/**
|
|
50
|
+
* A repository scheduled for deletion.
|
|
51
|
+
*
|
|
52
|
+
* Deletion is deferred for the same reason a tombstone is: a clone that read
|
|
53
|
+
* this index a moment ago is still downloading the packs it names, and pulling
|
|
54
|
+
* them out from under it fails the clone with a missing object. The marker is
|
|
55
|
+
* written under compare-and-swap like everything else, so an operator asking
|
|
56
|
+
* twice does not shorten the wait — the first request's `collect_after` stands.
|
|
57
|
+
*/
|
|
58
|
+
export interface RepoDeletion {
|
|
59
|
+
/** ISO instant the operator asked for the repository to go. */
|
|
60
|
+
requested_at: string
|
|
61
|
+
/** ISO instant before which nothing under the repo prefix may be deleted. */
|
|
62
|
+
collect_after: string
|
|
63
|
+
}
|
|
64
|
+
|
|
47
65
|
export interface WalIndex {
|
|
48
66
|
version: 1
|
|
49
67
|
repo_id: string
|
|
@@ -59,8 +77,97 @@ export interface WalIndex {
|
|
|
59
77
|
* before compaction existed does not have the field; absent reads as empty.
|
|
60
78
|
*/
|
|
61
79
|
tombstones?: Tombstone[]
|
|
80
|
+
/**
|
|
81
|
+
* Set when this repository has been scheduled for deletion. Its presence is
|
|
82
|
+
* what makes the second run of `walgit delete` a collection rather than a
|
|
83
|
+
* second request.
|
|
84
|
+
*/
|
|
85
|
+
deletion?: RepoDeletion
|
|
86
|
+
/**
|
|
87
|
+
* Push provenance: ref → who signed the push that moved it to the sha `refs`
|
|
88
|
+
* currently holds, and when (docs/adr/0011).
|
|
89
|
+
*
|
|
90
|
+
* A second map beside `refs` rather than a widening of it, for three reasons
|
|
91
|
+
* that each rule out the alternatives. It is not hung off a `WalEntry`: a
|
|
92
|
+
* ref-only push appends none, so provenance would be blind to a whole class
|
|
93
|
+
* of push. It is not kept on the certificate blob: that lives on the Cache,
|
|
94
|
+
* which is wiped on restart. And it is not a richer value inside `refs`,
|
|
95
|
+
* because every existing reader of the Index — reconcile, materialize, the
|
|
96
|
+
* event handshake — would then have to change to keep reading a sha.
|
|
97
|
+
*
|
|
98
|
+
* Latest-state per ref, like everything else here: there is no provenance
|
|
99
|
+
* history, because the audit trail of *content* is the commit graph and a
|
|
100
|
+
* second ledger would be a second thing to keep true.
|
|
101
|
+
*
|
|
102
|
+
* Optional and absent when empty, so an unsigned deployment's index.json is
|
|
103
|
+
* byte-for-byte what it was before this field existed.
|
|
104
|
+
*/
|
|
105
|
+
provenance?: Record<string, Provenance>
|
|
106
|
+
/**
|
|
107
|
+
* The repository's Signer List, as the push that last moved `refs/walgit/signers`
|
|
108
|
+
* resolved it (docs/adr/0012). Absent means unclaimed, which is every
|
|
109
|
+
* repository until someone writes one.
|
|
110
|
+
*
|
|
111
|
+
* Repo-level rather than per-ref, unlike `provenance` above it: the list
|
|
112
|
+
* governs the name, not a branch.
|
|
113
|
+
*
|
|
114
|
+
* The ref is authoritative and this is a derived copy, which is safe rather
|
|
115
|
+
* than a second source of truth — it is written by the same compare-and-swap
|
|
116
|
+
* that publishes the ref move, derived from bytes in that same push, and a
|
|
117
|
+
* restore replays the ref and this field together because both live here. The
|
|
118
|
+
* copy exists because the refusal that will read it runs in `pre-receive`,
|
|
119
|
+
* which already loads the Index; resolving from the Cache instead would make
|
|
120
|
+
* ownership depend on the Cache being materialized, and the Cache is
|
|
121
|
+
* disposable by definition (ADR-0007).
|
|
122
|
+
*
|
|
123
|
+
* It cannot be derived from `provenance`, which is latest-state per ref and
|
|
124
|
+
* overwritten by every push — by the time it mattered it would name the most
|
|
125
|
+
* recent Signer rather than the founding one.
|
|
126
|
+
*/
|
|
127
|
+
claim?: Claim
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Who moved a ref, and when it landed. */
|
|
131
|
+
export interface Provenance {
|
|
132
|
+
/**
|
|
133
|
+
* The SSH key fingerprint that signed the push, as `ssh-keygen` spells it:
|
|
134
|
+
* `SHA256:` and 43 characters of base64. A key, never a user or an account —
|
|
135
|
+
* neither exists here, and naming it either would imply a registry walgit
|
|
136
|
+
* deliberately does not have.
|
|
137
|
+
*/
|
|
138
|
+
signer: string
|
|
139
|
+
/** ISO instant the push was received. */
|
|
140
|
+
ts: string
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The keys a repository's Signer List names, and when that list landed. */
|
|
144
|
+
export interface Claim {
|
|
145
|
+
/**
|
|
146
|
+
* Fingerprints, in the order the file names them and with duplicates already
|
|
147
|
+
* collapsed — the list as `parseSignerList` read it, never the raw file. What
|
|
148
|
+
* is stored is the resolved answer, so a reader never re-parses and cannot
|
|
149
|
+
* reach a different one.
|
|
150
|
+
*/
|
|
151
|
+
signers: string[]
|
|
152
|
+
/** ISO instant the push that wrote this list was received. */
|
|
153
|
+
ts: string
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* What one push records about who made it — applied by the same compare-and-swap
|
|
158
|
+
* that publishes the push, which is why they travel together rather than as two
|
|
159
|
+
* nullable tail arguments nobody can keep straight at a call site.
|
|
160
|
+
*/
|
|
161
|
+
export interface PushRecord {
|
|
162
|
+
/** The Signer of this push, or `null` for an anonymous one. */
|
|
163
|
+
provenance: Provenance | null
|
|
164
|
+
/** The Signer List this push writes, or `null` when it writes none. */
|
|
165
|
+
claim: Claim | null
|
|
62
166
|
}
|
|
63
167
|
|
|
168
|
+
/** A push that records neither. The overwhelming majority of them. */
|
|
169
|
+
const NO_RECORD: PushRecord = { provenance: null, claim: null }
|
|
170
|
+
|
|
64
171
|
/** A ref change as `reference-transaction` reports it on stdin. */
|
|
65
172
|
export interface RefChange {
|
|
66
173
|
ref: string
|
|
@@ -68,13 +175,6 @@ export interface RefChange {
|
|
|
68
175
|
newOid: string
|
|
69
176
|
}
|
|
70
177
|
|
|
71
|
-
/** The all-zeroes oid: creation when it is `oldOid`, deletion when `newOid`. */
|
|
72
|
-
export const ZERO_OID = '0'.repeat(40)
|
|
73
|
-
|
|
74
|
-
export function indexKey(repoId: string): string {
|
|
75
|
-
return `repos/${repoId}/index.json`
|
|
76
|
-
}
|
|
77
|
-
|
|
78
178
|
export function emptyIndex(repoId: string): WalIndex {
|
|
79
179
|
return {
|
|
80
180
|
version: 1,
|
|
@@ -87,9 +187,17 @@ export function emptyIndex(repoId: string): WalIndex {
|
|
|
87
187
|
}
|
|
88
188
|
}
|
|
89
189
|
|
|
90
|
-
/**
|
|
91
|
-
|
|
92
|
-
|
|
190
|
+
/**
|
|
191
|
+
* A WAL object's content address, as `WalEntry.sha256` carries it.
|
|
192
|
+
*
|
|
193
|
+
* It lives beside the field it fills rather than with whichever caller happens
|
|
194
|
+
* to compute it: the push path stamps it on upload, compaction stamps it on the
|
|
195
|
+
* pack it publishes, and materialize checks a download against it — a truncated
|
|
196
|
+
* transfer being the failure a restore actually has. Three callers, one
|
|
197
|
+
* definition of what the digest is over.
|
|
198
|
+
*/
|
|
199
|
+
export function sha256(body: Uint8Array): string {
|
|
200
|
+
return new Bun.CryptoHasher('sha256').update(body).digest('hex')
|
|
93
201
|
}
|
|
94
202
|
|
|
95
203
|
// ── Reading ─────────────────────────────────────────────────────────────────
|
|
@@ -149,14 +257,82 @@ export function applyRefChanges(
|
|
|
149
257
|
return next
|
|
150
258
|
}
|
|
151
259
|
|
|
260
|
+
/**
|
|
261
|
+
* Apply one push's provenance: the Signer of every ref it moved.
|
|
262
|
+
*
|
|
263
|
+
* The map answers exactly one question — *who moved this ref to the sha it
|
|
264
|
+
* holds now* — and both clearing rules follow from that being the question:
|
|
265
|
+
*
|
|
266
|
+
* - A deleted ref loses its entry, because the ref it described is gone.
|
|
267
|
+
* Keeping it would grow the map forever with refs nothing can look up.
|
|
268
|
+
* - An UNSIGNED push over a signed ref loses it too. The alternative is worse
|
|
269
|
+
* than useless: the ref would keep naming whoever last signed for it while
|
|
270
|
+
* pointing at a sha that key never signed, which is the Index stating
|
|
271
|
+
* something false rather than stating nothing.
|
|
272
|
+
*
|
|
273
|
+
* `undefined` when the result is empty, so the field is absent from an index no
|
|
274
|
+
* signed push has touched instead of appearing as `{}`.
|
|
275
|
+
*/
|
|
276
|
+
export function applyProvenance(
|
|
277
|
+
current: Record<string, Provenance> | undefined,
|
|
278
|
+
changes: readonly RefChange[],
|
|
279
|
+
provenance: Provenance | null,
|
|
280
|
+
): Record<string, Provenance> | undefined {
|
|
281
|
+
const next = { ...current }
|
|
282
|
+
for (const c of changes) {
|
|
283
|
+
if (provenance === null || c.newOid === ZERO_OID) delete next[c.ref]
|
|
284
|
+
else next[c.ref] = provenance
|
|
285
|
+
}
|
|
286
|
+
return Object.keys(next).length === 0 ? undefined : next
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Apply one push's Signer List, if it wrote one — and drop the claim if the
|
|
291
|
+
* push took the list ref away.
|
|
292
|
+
*
|
|
293
|
+
* Writing is gated on the push actually moving `SIGNERS_REF` in THIS set of
|
|
294
|
+
* changes, not merely on a resolved list being in hand. git updates refs one
|
|
295
|
+
* transaction at a time unless the client asked for `--atomic`, so a push
|
|
296
|
+
* moving a branch and the list together publishes across several
|
|
297
|
+
* compare-and-swaps — and writing the field in the first of them would leave
|
|
298
|
+
* the Index naming a list the ref does not yet hold, and still naming it if a
|
|
299
|
+
* later transaction is refused.
|
|
300
|
+
*
|
|
301
|
+
* The deletion rule is here rather than left to the refusal in
|
|
302
|
+
* `src/signers.ts`, even though that refusal makes it unreachable, because the
|
|
303
|
+
* refusal only exists while `WALGIT_SIGNER_LISTS` is on. A deployment that
|
|
304
|
+
* turns the flag off can delete the ref, and an Index that went on naming a
|
|
305
|
+
* list nothing holds would state something false — the same reason
|
|
306
|
+
* `applyProvenance` clears a deleted ref rather than keeping the last Signer
|
|
307
|
+
* for it.
|
|
308
|
+
*
|
|
309
|
+
* It does NOT make the derived copy self-healing, and nothing here does: only a
|
|
310
|
+
* push that moves the ref while the flag is on writes the field. A list pushed
|
|
311
|
+
* before the flag was turned on, or a ref force-moved while it was off, leaves
|
|
312
|
+
* the Index behind the ref, and the ref is the one that is authoritative.
|
|
313
|
+
*/
|
|
314
|
+
export function applyClaim(
|
|
315
|
+
current: Claim | undefined,
|
|
316
|
+
changes: readonly RefChange[],
|
|
317
|
+
claim: Claim | null,
|
|
318
|
+
): Claim | undefined {
|
|
319
|
+
const deleted = changes.some((c) => c.ref === SIGNERS_REF && c.newOid === ZERO_OID)
|
|
320
|
+
if (deleted) return undefined
|
|
321
|
+
if (claim === null) return current
|
|
322
|
+
const moves = changes.some((c) => c.ref === SIGNERS_REF && c.newOid !== ZERO_OID)
|
|
323
|
+
return moves ? claim : current
|
|
324
|
+
}
|
|
325
|
+
|
|
152
326
|
/**
|
|
153
327
|
* Build the successor index for one push: bump seq, append the entry, apply the
|
|
154
|
-
* ref changes
|
|
328
|
+
* ref changes and whatever the push recorded about who made it. Pure, so the
|
|
329
|
+
* caller can validate before anything is written.
|
|
155
330
|
*/
|
|
156
331
|
export function nextIndex(
|
|
157
332
|
current: WalIndex,
|
|
158
333
|
entry: Omit<WalEntry, 'seq'>,
|
|
159
334
|
changes: readonly RefChange[],
|
|
335
|
+
record: PushRecord = NO_RECORD,
|
|
160
336
|
): WalIndex {
|
|
161
337
|
const seq = current.seq + 1
|
|
162
338
|
return {
|
|
@@ -164,6 +340,8 @@ export function nextIndex(
|
|
|
164
340
|
seq,
|
|
165
341
|
entries: [...current.entries, { ...entry, seq }],
|
|
166
342
|
refs: applyRefChanges(current.refs, changes),
|
|
343
|
+
provenance: applyProvenance(current.provenance, changes, record.provenance),
|
|
344
|
+
claim: applyClaim(current.claim, changes, record.claim),
|
|
167
345
|
}
|
|
168
346
|
}
|
|
169
347
|
|
|
@@ -1,14 +1,20 @@
|
|
|
1
1
|
{
|
|
2
|
+
// The container half: src/ (the process) and e2e/ (the suite that drives it),
|
|
3
|
+
// both compiled against bun's ambient types. shared/ is included here AND in
|
|
4
|
+
// tsconfig.worker.json on purpose — a module in shared/ imports no runtime,
|
|
5
|
+
// and being typechecked once under @types/bun and once under
|
|
6
|
+
// @cloudflare/workers-types is what makes that a rule the build enforces
|
|
7
|
+
// rather than a comment (docs/adr/0010).
|
|
2
8
|
"compilerOptions": {
|
|
3
9
|
"target": "ES2022",
|
|
4
10
|
"module": "ESNext",
|
|
5
11
|
"moduleResolution": "bundler",
|
|
6
|
-
"lib": ["
|
|
12
|
+
"lib": ["ES2023", "DOM"],
|
|
7
13
|
"types": ["bun"],
|
|
8
14
|
"strict": true,
|
|
9
15
|
"noEmit": true,
|
|
10
16
|
"skipLibCheck": true,
|
|
11
17
|
"verbatimModuleSyntax": true
|
|
12
18
|
},
|
|
13
|
-
"include": ["src", "e2e"]
|
|
19
|
+
"include": ["src", "e2e", "shared"]
|
|
14
20
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
// worker/ imports the Cloudflare Workers runtime (Durable Objects, the
|
|
3
|
+
// Container class), whose ambient types conflict with the bun types src/ is
|
|
4
|
+
// compiled against — one program cannot hold both, so the two halves get one
|
|
5
|
+
// config each. src/ is deliberately NOT included: nothing in it ever runs in
|
|
6
|
+
// the Workers runtime.
|
|
7
|
+
//
|
|
8
|
+
// shared/ IS included, and is the only directory both programs compile. That
|
|
9
|
+
// is the enforcement mechanism for its one rule — shared/ imports no runtime
|
|
10
|
+
// — because a module there that reached for `Bun` or for a Durable Object
|
|
11
|
+
// would fail one of the two typechecks (docs/adr/0010).
|
|
12
|
+
"compilerOptions": {
|
|
13
|
+
"target": "ES2022",
|
|
14
|
+
"module": "ESNext",
|
|
15
|
+
"moduleResolution": "bundler",
|
|
16
|
+
"lib": ["ES2022"],
|
|
17
|
+
"types": ["@cloudflare/workers-types"],
|
|
18
|
+
"strict": true,
|
|
19
|
+
"noEmit": true,
|
|
20
|
+
"skipLibCheck": true,
|
|
21
|
+
"verbatimModuleSyntax": true
|
|
22
|
+
},
|
|
23
|
+
"include": ["worker", "shared"]
|
|
24
|
+
}
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The socket shell.
|
|
3
|
+
*
|
|
4
|
+
* A Durable Object because the sockets have to live somewhere with an identity:
|
|
5
|
+
* a Worker isolate is per-request and cannot hold a connection open, and a
|
|
6
|
+
* pushed ref has to reach subscribers that connected to some other isolate,
|
|
7
|
+
* possibly some other colo. One named instance is the rendezvous.
|
|
8
|
+
*
|
|
9
|
+
* It carries NO decisions. Whether a credential is good, what a `watch` message
|
|
10
|
+
* means, which sockets an announcement reaches and what goes on the wire are
|
|
11
|
+
* all `shared/events.ts`, which is pure and tested. What is left here — accept,
|
|
12
|
+
* remember, send, forget — is the part that cannot be unit-tested without a
|
|
13
|
+
* runtime, so there is deliberately nothing else in it.
|
|
14
|
+
*
|
|
15
|
+
* Sockets are accepted with `ctx.acceptWebSocket`, the hibernation API: an idle
|
|
16
|
+
* subscription evicts the isolate from memory and keeps the TCP connection, so
|
|
17
|
+
* a client that watches a quiet repository for a week costs storage, not
|
|
18
|
+
* duration. `serializeAttachment` is what survives that — an in-memory Map of
|
|
19
|
+
* subscriptions would be silently empty on the wake, and the socket would then
|
|
20
|
+
* be connected and permanently deaf.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { Container, getContainer } from '@cloudflare/containers'
|
|
24
|
+
import { DurableObject } from 'cloudflare:workers'
|
|
25
|
+
|
|
26
|
+
import {
|
|
27
|
+
type RefEvent,
|
|
28
|
+
type WatchEntry,
|
|
29
|
+
encode,
|
|
30
|
+
handshake,
|
|
31
|
+
parseAnnounce,
|
|
32
|
+
parseWatch,
|
|
33
|
+
watchCovers,
|
|
34
|
+
watchedRepos,
|
|
35
|
+
} from '../shared/events'
|
|
36
|
+
import { Outbox } from '../shared/outbox'
|
|
37
|
+
import { INTERNAL_HEADER, REFS_PATH } from '../shared/protocol'
|
|
38
|
+
import { RefCache } from '../shared/ref-cache'
|
|
39
|
+
|
|
40
|
+
/** Only the bindings this object touches — the Worker's Env is a superset. */
|
|
41
|
+
export interface EventsEnv {
|
|
42
|
+
// The BASE class, not `WalgitContainer`: that one is defined in index.ts,
|
|
43
|
+
// which imports this file, so naming it here would be a cycle. `any` was the
|
|
44
|
+
// first way around that and cost a typecheck — `DurableObjectStub<any>` sends
|
|
45
|
+
// the RPC type machinery infinitely deep (TS2589). The base is enough: all
|
|
46
|
+
// this object ever does with the binding is `fetch`.
|
|
47
|
+
WALGIT_CONTAINER: DurableObjectNamespace<Container>
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The Worker's internal call to fan an announcement out. Never client-reachable. */
|
|
51
|
+
export const BROADCAST_PATH = '/broadcast'
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* One instance serves every subscriber, addressed by this name.
|
|
55
|
+
*
|
|
56
|
+
* A single object is the simplest thing that can work and is not a ceiling
|
|
57
|
+
* worth pre-empting: a fan-out is one message per socket, and the push rate of
|
|
58
|
+
* a git host is bounded by pushes, not by subscribers.
|
|
59
|
+
*/
|
|
60
|
+
export const EVENTS_OBJECT_NAME = 'events'
|
|
61
|
+
|
|
62
|
+
export class WalgitEvents extends DurableObject<EventsEnv> {
|
|
63
|
+
/**
|
|
64
|
+
* What this object remembers about refs, so a connect for a repository it has
|
|
65
|
+
* already seen does not wake the container to be told what it just announced.
|
|
66
|
+
*
|
|
67
|
+
* In memory, never in storage (shared/ref-cache.ts): hibernation drops it,
|
|
68
|
+
* and the cost of that is one container round-trip on the next connect. The
|
|
69
|
+
* Index stays the source of truth.
|
|
70
|
+
*/
|
|
71
|
+
private readonly refs = new RefCache()
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* One outbound queue per live socket.
|
|
75
|
+
*
|
|
76
|
+
* In memory, and not serialized onto the socket: an entry only exists inside
|
|
77
|
+
* a ref's coalesce window, which is a few hundred milliseconds after an
|
|
78
|
+
* announcement — activity, not the idleness hibernation waits for. If the
|
|
79
|
+
* object were evicted mid-window anyway the queued event would go with it,
|
|
80
|
+
* and the cost is one notification the client's next handshake corrects.
|
|
81
|
+
* Serializing it would trade that for storage writes on every push.
|
|
82
|
+
*/
|
|
83
|
+
private readonly outboxes = new WeakMap<WebSocket, Outbox>()
|
|
84
|
+
|
|
85
|
+
async fetch(request: Request): Promise<Response> {
|
|
86
|
+
const url = new URL(request.url)
|
|
87
|
+
|
|
88
|
+
if (url.pathname === BROADCAST_PATH) {
|
|
89
|
+
const parsed = parseAnnounce(await request.json().catch(() => null))
|
|
90
|
+
if (!parsed.ok) return new Response(`${parsed.error}\n`, { status: 400 })
|
|
91
|
+
// Fold into the cache first: an announcement is the Index's own report of
|
|
92
|
+
// a ref that has already been made durable, which is exactly what a later
|
|
93
|
+
// handshake would go and read.
|
|
94
|
+
this.refs.apply(parsed.value)
|
|
95
|
+
const delivered = this.broadcast(parsed.value)
|
|
96
|
+
return Response.json({ ok: true, delivered })
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// The subscribe path. The Worker has already checked the credential — it
|
|
100
|
+
// holds the token list, and re-checking here would be a second copy of the
|
|
101
|
+
// gate for the two to drift apart on.
|
|
102
|
+
if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {
|
|
103
|
+
return new Response('expected a websocket upgrade\n', { status: 426 })
|
|
104
|
+
}
|
|
105
|
+
const pair = new WebSocketPair()
|
|
106
|
+
const [client, server] = [pair[0], pair[1]]
|
|
107
|
+
// Hibernation-aware accept: the handlers below are called on a fresh
|
|
108
|
+
// isolate after an idle period, rather than the isolate being kept alive.
|
|
109
|
+
this.ctx.acceptWebSocket(server)
|
|
110
|
+
return new Response(null, { status: 101, webSocket: client })
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* A client naming what it watches.
|
|
115
|
+
*
|
|
116
|
+
* The answer is current state — from this object's own copy where it has one,
|
|
117
|
+
* and otherwise from the Index through the container, which is the source of
|
|
118
|
+
* truth for refs (docs/adr/0007). Either way a subscriber's first message
|
|
119
|
+
* tells it where it stands and it never has to fetch to find out.
|
|
120
|
+
*
|
|
121
|
+
* The order is RECORD, read, answer, and both halves of that matter because
|
|
122
|
+
* reading can take a container round-trip and a push can land inside it:
|
|
123
|
+
*
|
|
124
|
+
* - recorded first, so a push during the read reaches this socket as an
|
|
125
|
+
* event rather than being fanned out to a socket that is not yet
|
|
126
|
+
* subscribed and therefore skipped;
|
|
127
|
+
* - and `RefCache` brackets the read, so the snapshot that lands cannot be
|
|
128
|
+
* older than an event already sent on this socket.
|
|
129
|
+
*
|
|
130
|
+
* Recording first means a subscriber can see an event before its handshake.
|
|
131
|
+
* That is harmless — both carry the same sha, and latest-state has no order
|
|
132
|
+
* to violate — where the reverse, a handshake claiming a sha older than the
|
|
133
|
+
* event already delivered, would leave the client believing it is current
|
|
134
|
+
* when it is a push behind.
|
|
135
|
+
*/
|
|
136
|
+
async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
|
|
137
|
+
const raw = typeof message === 'string' ? message : new TextDecoder().decode(message)
|
|
138
|
+
const parsed = parseWatch(raw)
|
|
139
|
+
if (!parsed.ok) {
|
|
140
|
+
ws.send(encode({ error: parsed.error }))
|
|
141
|
+
return
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
ws.serializeAttachment(parsed.value)
|
|
145
|
+
|
|
146
|
+
let refsByRepo: Record<string, Record<string, string>>
|
|
147
|
+
try {
|
|
148
|
+
refsByRepo = await this.currentRefs(watchedRepos(parsed.value))
|
|
149
|
+
} catch (error) {
|
|
150
|
+
ws.send(
|
|
151
|
+
encode({
|
|
152
|
+
error: `could not read current refs: ${(error as Error).message}`,
|
|
153
|
+
}),
|
|
154
|
+
)
|
|
155
|
+
return
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
ws.send(encode(handshake(parsed.value, refsByRepo)))
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
webSocketClose(ws: WebSocket): void {
|
|
162
|
+
this.outboxes.delete(ws)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
webSocketError(ws: WebSocket): void {
|
|
166
|
+
this.outboxes.delete(ws)
|
|
167
|
+
// Nothing to clean up beyond the socket itself: the subscription lives on
|
|
168
|
+
// the socket's attachment, so it goes when the socket goes.
|
|
169
|
+
try {
|
|
170
|
+
ws.close(1011, 'walgit: socket error')
|
|
171
|
+
} catch {
|
|
172
|
+
// Already gone.
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Send one announcement to every socket that asked for it. */
|
|
177
|
+
private broadcast(events: readonly RefEvent[]): number {
|
|
178
|
+
let delivered = 0
|
|
179
|
+
for (const ws of this.ctx.getWebSockets()) {
|
|
180
|
+
const watch = readWatch(ws)
|
|
181
|
+
if (!watch) continue
|
|
182
|
+
const wanted = events.filter((event) => watchCovers(watch, event))
|
|
183
|
+
if (wanted.length === 0) continue
|
|
184
|
+
// Through the outbox rather than straight to the socket: it holds each
|
|
185
|
+
// socket to at most one message per ref per window, so a ref that moves
|
|
186
|
+
// in a burst costs one message carrying the newest sha rather than one
|
|
187
|
+
// per push. A socket that has gone away mid-fan-out must not stop the
|
|
188
|
+
// ones behind it, which is why the outbox never throws.
|
|
189
|
+
//
|
|
190
|
+
// `sent` counts what went out on THIS call. An event held for its window
|
|
191
|
+
// leaves on the outbox's own timer and is not counted here — the number
|
|
192
|
+
// is a fan-out receipt, not a delivery guarantee, and the announcer only
|
|
193
|
+
// logs it.
|
|
194
|
+
delivered += this.outbox(ws).offer(wanted).sent
|
|
195
|
+
}
|
|
196
|
+
return delivered
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** This socket's queue, created on the first event it is owed. */
|
|
200
|
+
private outbox(ws: WebSocket): Outbox {
|
|
201
|
+
const existing = this.outboxes.get(ws)
|
|
202
|
+
if (existing) return existing
|
|
203
|
+
const created = new Outbox(ws)
|
|
204
|
+
this.outboxes.set(ws, created)
|
|
205
|
+
return created
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The Index's ref state for each repository — from memory where possible.
|
|
210
|
+
*
|
|
211
|
+
* A repository this object already knows is answered here and the container
|
|
212
|
+
* is never touched, which is the point: a fan-out that has been announcing
|
|
213
|
+
* pushes for a repository all day already holds its ref state, and waking a
|
|
214
|
+
* sleeping container to re-read it would be paying for an answer twice.
|
|
215
|
+
*
|
|
216
|
+
* A miss goes to the container rather than to the object store directly,
|
|
217
|
+
* because the store's credentials are the container's, not the Worker's
|
|
218
|
+
* (shared/container-env.ts) — and because `index.json` is the only place refs
|
|
219
|
+
* are authoritative.
|
|
220
|
+
*/
|
|
221
|
+
private async currentRefs(repos: string[]): Promise<Record<string, Record<string, string>>> {
|
|
222
|
+
for (const repo of this.refs.missing(repos)) {
|
|
223
|
+
// Bracketed: anything announced while the container is answering is
|
|
224
|
+
// replayed over the snapshot rather than lost behind it.
|
|
225
|
+
this.refs.beginFill(repo)
|
|
226
|
+
try {
|
|
227
|
+
this.refs.endFill(repo, await this.fetchRefs(repo))
|
|
228
|
+
} catch (error) {
|
|
229
|
+
// Left unknown rather than filled empty: the next connect pays another
|
|
230
|
+
// round-trip, which is cheaper than answering confidently with nothing.
|
|
231
|
+
this.refs.abortFill(repo)
|
|
232
|
+
throw error
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return this.refs.read(repos)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** One repository's ref state, read from the Index through the container. */
|
|
239
|
+
private async fetchRefs(repo: string): Promise<Record<string, string>> {
|
|
240
|
+
const request = new Request(
|
|
241
|
+
`https://walgit.internal${REFS_PATH}?repo=${encodeURIComponent(repo)}`,
|
|
242
|
+
{ headers: { [INTERNAL_HEADER]: '1' } },
|
|
243
|
+
)
|
|
244
|
+
const response = await getContainer(this.env.WALGIT_CONTAINER).fetch(request)
|
|
245
|
+
if (!response.ok) throw new Error(`refs lookup for ${repo}: ${response.status}`)
|
|
246
|
+
const body = (await response.json()) as { refs?: Record<string, string> }
|
|
247
|
+
return body.refs ?? {}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** The subscription a socket carries, or null if it never sent a valid one. */
|
|
252
|
+
function readWatch(ws: WebSocket): WatchEntry[] | null {
|
|
253
|
+
try {
|
|
254
|
+
const attachment = ws.deserializeAttachment() as WatchEntry[] | null
|
|
255
|
+
return Array.isArray(attachment) ? attachment : null
|
|
256
|
+
} catch {
|
|
257
|
+
return null
|
|
258
|
+
}
|
|
259
|
+
}
|