@zabaca/zbc 0.25.0 → 0.27.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 +114 -0
- package/package.json +1 -1
- package/src/commands/init.ts +105 -10
- package/src/commands/secret.ts +1 -66
- package/src/commands/update.ts +77 -7
- package/src/engine/actions.ts +35 -3
- package/src/engine/on-demand.ts +9 -1
- package/src/engine/secret-outputs.ts +15 -0
- package/src/engine/secrets.ts +81 -1
- package/src/utils/copy-refresh.ts +124 -19
- package/src/utils/detect-mode.ts +1 -1
- package/src/utils/host-workspaces.ts +57 -0
- package/src/utils/subtree.ts +54 -15
- package/src/utils/template-history.ts +66 -0
- package/src/utils/vendor-audit.ts +12 -8
- package/src/utils/vendor-stamp.ts +10 -0
- package/src/utils/vendored-app.ts +3 -0
- package/templates/apps/walgit/CONTEXT.md +45 -4
- package/templates/apps/walgit/README.md +394 -11
- package/templates/apps/walgit/shared/browse.ts +61 -0
- package/templates/apps/walgit/shared/capabilities.ts +26 -0
- package/templates/apps/walgit/shared/container-env.ts +12 -0
- package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
- package/templates/apps/walgit/shared/credentials.ts +4 -0
- package/templates/apps/walgit/shared/events.ts +35 -1
- package/templates/apps/walgit/shared/instructions.ts +4 -1
- package/templates/apps/walgit/shared/landing.ts +2 -1
- package/templates/apps/walgit/shared/llms.ts +73 -5
- package/templates/apps/walgit/shared/mcp.ts +19 -3
- package/templates/apps/walgit/shared/protocol.ts +40 -3
- package/templates/apps/walgit/shared/repo-list.ts +46 -6
- package/templates/apps/walgit/shared/scoped-token.ts +500 -0
- package/templates/apps/walgit/shared/token-revocation.ts +134 -0
- package/templates/apps/walgit/shared/wal-index.ts +19 -0
- package/templates/apps/walgit/shared/webhook.ts +281 -0
- package/templates/apps/walgit/src/admin.ts +510 -0
- package/templates/apps/walgit/src/announce-main.ts +17 -9
- package/templates/apps/walgit/src/announce.ts +86 -0
- package/templates/apps/walgit/src/browse.ts +255 -2
- package/templates/apps/walgit/src/cli.ts +140 -0
- package/templates/apps/walgit/src/expire.ts +5 -0
- package/templates/apps/walgit/src/git.ts +103 -0
- package/templates/apps/walgit/src/hook-main.ts +6 -3
- package/templates/apps/walgit/src/http.ts +563 -3
- package/templates/apps/walgit/src/limits.ts +3 -0
- package/templates/apps/walgit/src/merge.ts +525 -0
- package/templates/apps/walgit/src/rate-limit.ts +51 -14
- package/templates/apps/walgit/src/server.ts +65 -1
- package/templates/apps/walgit/worker/events-do.ts +218 -3
- package/templates/apps/walgit/worker/index.ts +134 -9
- package/templates/apps/walgit/worker/mcp.ts +17 -2
- package/templates/history.json +1 -0
- package/templates/infra/modules/cloudflare/index.ts +140 -1
- package/templates/infra/modules/cloudflare-access/index.ts +176 -65
- package/templates/infra/modules/cloudflare-access/registry.json +1 -1
- package/templates/infra/modules/cloudflare-api/index.ts +56 -0
- package/templates/infra/modules/cloudflare-email/index.ts +44 -17
- package/templates/infra/modules/cloudflare-email/registry.json +1 -1
- package/templates/infra/modules/cloudflare-stored-token/index.ts +343 -0
- package/templates/infra/modules/cloudflare-stored-token/registry.json +12 -0
- package/templates/infra/modules/cloudflare-token/index.ts +46 -17
- package/templates/infra/modules/cloudflare-token/registry.json +1 -1
- package/templates/infra/modules/cloudflare-tunnel/index.ts +63 -8
- package/templates/infra/modules/cloudflare-tunnel/registry.json +1 -1
- package/templates/infra/modules/d1/index.ts +37 -35
- package/templates/infra/modules/d1/registry.json +1 -1
- package/templates/infra/modules/docker-compose-stack/index.ts +3 -1
- package/templates/infra/modules/queue/index.ts +28 -18
- package/templates/infra/modules/queue/registry.json +1 -1
- package/templates/infra/modules/r2/index.ts +20 -11
- package/templates/infra/modules/r2/registry.json +1 -1
- package/templates/infra/src/context.ts +41 -0
- package/templates/infra/src/testing.ts +19 -1
- package/templates/infra/src/types.ts +23 -0
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A merge the host performs, on a deployment that opted in (docs/adr/0022):
|
|
3
|
+
* one branch into another, by fast-forward or by squash, as a compare-and-swap
|
|
4
|
+
* on the target.
|
|
5
|
+
*
|
|
6
|
+
* **A merge is a push, not a write.** The result is built in a scratch
|
|
7
|
+
* repository that borrows the Cache's objects (`objects/info/alternates`) and
|
|
8
|
+
* pushed into the Cache over git's local transport — the path `src/admin.ts`
|
|
9
|
+
* seeds a repository through — so `pre-receive` and `reference-transaction`
|
|
10
|
+
* judge it exactly as they judge a client's push: a Signer List, append-only,
|
|
11
|
+
* the size caps, and the compare-and-swap on `index.json` that publishes it.
|
|
12
|
+
* `post-receive` then announces the move, so a Watcher and the webhook hear of
|
|
13
|
+
* it as they hear of any push. Nothing in this file writes the Index, a ref or
|
|
14
|
+
* an object into the served repository itself.
|
|
15
|
+
*
|
|
16
|
+
* **The compare-and-swap is two-layered.** The caller names the commit the
|
|
17
|
+
* target is expected to be at. It is checked against the Index first (a stale
|
|
18
|
+
* expectation costs nothing), and then held by git itself: the push carries
|
|
19
|
+
* `--force-with-lease=<target>:<expected>`, so receive-pack moves the ref only
|
|
20
|
+
* from that commit, and the publish's own CAS refuses a ref the Index moved in
|
|
21
|
+
* the meantime. Of two merges racing for one target, exactly one lands.
|
|
22
|
+
*
|
|
23
|
+
* The routing and the credential are `src/http.ts`'s; this is what the route
|
|
24
|
+
* does once it has been reached.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import * as fs from 'node:fs'
|
|
28
|
+
import * as os from 'node:os'
|
|
29
|
+
import * as path from 'node:path'
|
|
30
|
+
|
|
31
|
+
import { COMPARE_MAX_FILES, OID, resolveRef, type CompareFile } from '../shared/browse'
|
|
32
|
+
import type { ObjectStore } from '../shared/store'
|
|
33
|
+
import { loadIndex } from '../shared/wal-index'
|
|
34
|
+
import { identPart } from './admin'
|
|
35
|
+
import { compareRevs } from './browse'
|
|
36
|
+
import { gitAsync, gitAsyncWithin, type GitOptions } from './git'
|
|
37
|
+
import type { ResolvedRepo } from './repo'
|
|
38
|
+
|
|
39
|
+
/** The largest merge request body walgit will read: a message, not a payload. */
|
|
40
|
+
export const MAX_MERGE_BODY_BYTES = 64 * 1024
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* How long the file summary a merge answers with may take: ten seconds, the
|
|
44
|
+
* compare's own budget. Past it the merge still stands and answers with no
|
|
45
|
+
* summary — the summary is a courtesy, the ref move is the result.
|
|
46
|
+
*/
|
|
47
|
+
const MERGE_SUMMARY_TIMEOUT_MS = 10_000
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* How long the git work that BUILDS one merge may take, together: twenty
|
|
51
|
+
* seconds — peeling, the merge base, ancestry and a squash's three-way merge.
|
|
52
|
+
*
|
|
53
|
+
* A caller can make that work arbitrarily large (a squash of two big diverged
|
|
54
|
+
* histories), it runs on the one container that serves every clone and push,
|
|
55
|
+
* and a refusal costs it nothing to repeat — so it is bounded, and a merge
|
|
56
|
+
* that needs longer is refused (503) rather than waited out. The push itself
|
|
57
|
+
* is not under this deadline: killing a push between its upload and its
|
|
58
|
+
* publish is the one interruption the hooks are not built to be the victim of
|
|
59
|
+
* on purpose, and what it does is bounded by the size caps a push already
|
|
60
|
+
* meets.
|
|
61
|
+
*/
|
|
62
|
+
const MERGE_BUILD_TIMEOUT_MS = 20_000
|
|
63
|
+
|
|
64
|
+
/** The build deadline passed. Caught in `mergeInCache`, never thrown past it. */
|
|
65
|
+
class MergeTimedOut extends Error {}
|
|
66
|
+
|
|
67
|
+
export type MergeMethod = 'fast-forward' | 'squash'
|
|
68
|
+
|
|
69
|
+
/** A merge, as the request names it. */
|
|
70
|
+
export interface MergeRequest {
|
|
71
|
+
/** The ref whose work is merged: a branch (`feature/x`) or any Index ref. */
|
|
72
|
+
source: string
|
|
73
|
+
/** The branch that moves. `main` and `refs/heads/main` both name it. */
|
|
74
|
+
target: string
|
|
75
|
+
method: MergeMethod
|
|
76
|
+
/** The full commit id the target is expected to stand at. Required. */
|
|
77
|
+
expected: string
|
|
78
|
+
/** Squash only: the new commit's message. */
|
|
79
|
+
message?: string
|
|
80
|
+
/** Squash only: the new commit's author, who is also its committer. */
|
|
81
|
+
author?: { name: string; email: string }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export type MergeParse = { ok: true; request: MergeRequest } | { ok: false; message: string }
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Read a merge request's body. Strict, for the reason a seed is: every field
|
|
88
|
+
* ends in a git object or a ref move that cannot be taken back.
|
|
89
|
+
*/
|
|
90
|
+
export function parseMergeRequest(text: string): MergeParse {
|
|
91
|
+
let body: unknown
|
|
92
|
+
try {
|
|
93
|
+
body = JSON.parse(text)
|
|
94
|
+
} catch {
|
|
95
|
+
return { ok: false, message: 'the body is not JSON' }
|
|
96
|
+
}
|
|
97
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
|
|
98
|
+
return { ok: false, message: 'the body must be a JSON object' }
|
|
99
|
+
}
|
|
100
|
+
const fields = body as Record<string, unknown>
|
|
101
|
+
const { source, target, method, expected } = fields
|
|
102
|
+
if (typeof source !== 'string' || source === '') {
|
|
103
|
+
return { ok: false, message: '"source" must name a ref' }
|
|
104
|
+
}
|
|
105
|
+
if (typeof target !== 'string' || target === '') {
|
|
106
|
+
return { ok: false, message: '"target" must name a branch' }
|
|
107
|
+
}
|
|
108
|
+
if (method !== 'fast-forward' && method !== 'squash') {
|
|
109
|
+
return { ok: false, message: '"method" must be "fast-forward" or "squash"' }
|
|
110
|
+
}
|
|
111
|
+
// A full oid and nothing else: an abbreviation or a ref name here would make
|
|
112
|
+
// the compare-and-swap compare against something resolved on this side.
|
|
113
|
+
if (typeof expected !== 'string' || !OID.test(expected)) {
|
|
114
|
+
return {
|
|
115
|
+
ok: false,
|
|
116
|
+
message: '"expected" must be the full commit id the target stands at',
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (method === 'fast-forward') return { ok: true, request: { source, target, method, expected } }
|
|
120
|
+
|
|
121
|
+
const { message, author } = fields
|
|
122
|
+
if (typeof message !== 'string' || message.trim() === '') {
|
|
123
|
+
return { ok: false, message: 'a squash needs "message", a non-empty string' }
|
|
124
|
+
}
|
|
125
|
+
// git refuses a NUL in a commit message, and no other control character but
|
|
126
|
+
// a newline or a tab belongs in one: refused here, as the caller's mistake,
|
|
127
|
+
// rather than met as `commit-tree` failing halfway through the merge.
|
|
128
|
+
if (hasStrayControl(message)) {
|
|
129
|
+
return {
|
|
130
|
+
ok: false,
|
|
131
|
+
message: '"message" may not contain control characters other than a newline or a tab',
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (typeof author !== 'object' || author === null || Array.isArray(author)) {
|
|
135
|
+
return { ok: false, message: 'a squash needs "author": { name, email }' }
|
|
136
|
+
}
|
|
137
|
+
const { name, email } = author as Record<string, unknown>
|
|
138
|
+
if (!identPart(name) || !identPart(email)) {
|
|
139
|
+
return {
|
|
140
|
+
ok: false,
|
|
141
|
+
message:
|
|
142
|
+
'"author.name" and "author.email" must be non-empty strings without <, > or a newline',
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
ok: true,
|
|
147
|
+
request: { source, target, method, expected, message, author: { name, email } },
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** A C0 control character or DEL, other than a newline or a tab. */
|
|
152
|
+
function hasStrayControl(value: string): boolean {
|
|
153
|
+
for (let i = 0; i < value.length; i++) {
|
|
154
|
+
const code = value.charCodeAt(i)
|
|
155
|
+
if ((code < 0x20 && code !== 0x0a && code !== 0x09) || code === 0x7f) return true
|
|
156
|
+
}
|
|
157
|
+
return false
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** What one merge did, or why it did nothing. */
|
|
161
|
+
export type MergeResult =
|
|
162
|
+
| {
|
|
163
|
+
kind: 'merged'
|
|
164
|
+
repo: string
|
|
165
|
+
method: MergeMethod
|
|
166
|
+
source: { ref: string; oid: string }
|
|
167
|
+
/** The target before (`previous`, the expected commit) and after. */
|
|
168
|
+
target: { ref: string; previous: string; oid: string }
|
|
169
|
+
/** The commit the target now stands at. For a fast-forward, the source's. */
|
|
170
|
+
commit: string
|
|
171
|
+
/**
|
|
172
|
+
* What the merge changed on the target, as the compare summarises it —
|
|
173
|
+
* `null` when the summary could not be computed in time, which does not
|
|
174
|
+
* undo a merge that has already landed.
|
|
175
|
+
*/
|
|
176
|
+
summary: {
|
|
177
|
+
files: CompareFile[]
|
|
178
|
+
totals: { files: number; additions: number; deletions: number }
|
|
179
|
+
truncated: boolean
|
|
180
|
+
} | null
|
|
181
|
+
}
|
|
182
|
+
/** No Index for this name, or a ref it does not hold. */
|
|
183
|
+
| { kind: 'not-found'; message: string }
|
|
184
|
+
/** The request named something a merge cannot be: a target that is no branch. */
|
|
185
|
+
| { kind: 'invalid'; message: string }
|
|
186
|
+
/** The target is not at `expected`. Nothing was written. */
|
|
187
|
+
| { kind: 'stale'; ref: string; expected: string; actual: string }
|
|
188
|
+
/** Another write to the target won while this one was in flight. */
|
|
189
|
+
| { kind: 'contended'; ref: string; message: string }
|
|
190
|
+
| { kind: 'not-fast-forward'; ref: string }
|
|
191
|
+
/** The target already holds everything the source would bring. */
|
|
192
|
+
| { kind: 'up-to-date'; ref: string }
|
|
193
|
+
/** A squash whose three-way merge conflicts. No markers were written. */
|
|
194
|
+
| { kind: 'conflict'; paths: string[] }
|
|
195
|
+
| { kind: 'unrelated' }
|
|
196
|
+
/**
|
|
197
|
+
* The repository holds a Signer List, so only a listed key may move a ref,
|
|
198
|
+
* and the host holds none.
|
|
199
|
+
*/
|
|
200
|
+
| { kind: 'signed'; message: string }
|
|
201
|
+
/** The push's own rules refused it — a size cap, append-only, a deletion. */
|
|
202
|
+
| { kind: 'refused'; message: string }
|
|
203
|
+
/** Building the merge would take longer than `MERGE_BUILD_TIMEOUT_MS`. */
|
|
204
|
+
| { kind: 'too-large' }
|
|
205
|
+
/**
|
|
206
|
+
* The push failed for a reason that is not a rule's: receive-pack or a hook
|
|
207
|
+
* died, the store was unreachable. Nothing is known to have moved; retry.
|
|
208
|
+
*/
|
|
209
|
+
| { kind: 'unavailable'; message: string }
|
|
210
|
+
|
|
211
|
+
export interface MergeOps {
|
|
212
|
+
merge(repo: ResolvedRepo, request: MergeRequest): Promise<MergeResult>
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export interface MergeDeps {
|
|
216
|
+
store: ObjectStore
|
|
217
|
+
ensureRepo: (repo: ResolvedRepo) => ResolvedRepo
|
|
218
|
+
syncRepo: (repo: ResolvedRepo) => Promise<unknown>
|
|
219
|
+
/** `WALGIT_SIGNER_LISTS`, read once by the caller. */
|
|
220
|
+
signerLists: boolean
|
|
221
|
+
now?: () => Date
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function createMergeOps(deps: MergeDeps): MergeOps {
|
|
225
|
+
const now = () => (deps.now ?? (() => new Date()))()
|
|
226
|
+
return {
|
|
227
|
+
async merge(resolved, request) {
|
|
228
|
+
// The Index FIRST, before the Cache is touched: a name nobody has pushed
|
|
229
|
+
// to is a 404 that creates nothing, exactly as a browse of one is.
|
|
230
|
+
const { index, etag } = await loadIndex(deps.store, resolved.repoId)
|
|
231
|
+
if (etag === null) {
|
|
232
|
+
return { kind: 'not-found', message: `there is no repository "${resolved.repoId}"` }
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// The Signer List before anything about the refs: a host merge on a
|
|
236
|
+
// claimed name is refused whatever it would have done, and saying so
|
|
237
|
+
// first is the refusal its caller can act on. `pre-receive` would refuse
|
|
238
|
+
// the push anyway — the host's push carries no certificate — but only
|
|
239
|
+
// after a scratch repository and a three-way merge had been paid for, and
|
|
240
|
+
// in words about a signature the caller never had a chance to make.
|
|
241
|
+
if (deps.signerLists && index.claim) {
|
|
242
|
+
return {
|
|
243
|
+
kind: 'signed',
|
|
244
|
+
message:
|
|
245
|
+
`"${resolved.repoId}" holds a Signer List, so a ref here moves only by a push a listed key signed — ` +
|
|
246
|
+
'the host holds no such key and does not merge on a claimed name. Merge in a clone and push it signed',
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const target = resolveRef(index.refs, request.target)
|
|
251
|
+
if (target === null || OID.test(request.target)) {
|
|
252
|
+
return {
|
|
253
|
+
kind: 'not-found',
|
|
254
|
+
message: `there is no branch ${JSON.stringify(request.target)}`,
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if (!target.startsWith('refs/heads/')) {
|
|
258
|
+
return { kind: 'invalid', message: `${target} is not a branch; a merge moves a branch` }
|
|
259
|
+
}
|
|
260
|
+
const source = resolveRef(index.refs, request.source)
|
|
261
|
+
if (source === null || OID.test(request.source)) {
|
|
262
|
+
return { kind: 'not-found', message: `there is no ref ${JSON.stringify(request.source)}` }
|
|
263
|
+
}
|
|
264
|
+
if (source === target) {
|
|
265
|
+
return { kind: 'invalid', message: 'the source and the target are the same ref' }
|
|
266
|
+
}
|
|
267
|
+
const actual = index.refs[target]!
|
|
268
|
+
if (actual !== request.expected) {
|
|
269
|
+
return { kind: 'stale', ref: target, expected: request.expected, actual }
|
|
270
|
+
}
|
|
271
|
+
const sourceOid = index.refs[source]!
|
|
272
|
+
|
|
273
|
+
const repo = deps.ensureRepo(resolved)
|
|
274
|
+
await deps.syncRepo(repo)
|
|
275
|
+
return mergeInCache(deps, repo, request, {
|
|
276
|
+
target,
|
|
277
|
+
source,
|
|
278
|
+
sourceOid,
|
|
279
|
+
when: now(),
|
|
280
|
+
})
|
|
281
|
+
},
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
async function mergeInCache(
|
|
286
|
+
deps: MergeDeps,
|
|
287
|
+
repo: ResolvedRepo,
|
|
288
|
+
request: MergeRequest,
|
|
289
|
+
at: { target: string; source: string; sourceOid: string; when: Date },
|
|
290
|
+
): Promise<MergeResult> {
|
|
291
|
+
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'walgit-merge-'))
|
|
292
|
+
// No message leaving here names a directory on this machine.
|
|
293
|
+
const scrub = (text: string) =>
|
|
294
|
+
text.trim().replaceAll(scratch, '<merge>').replaceAll(repo.dir, '<repository>')
|
|
295
|
+
const gitDir = path.join(scratch, 'merge.git')
|
|
296
|
+
// Every git call that builds the merge runs under one deadline.
|
|
297
|
+
const deadline = Date.now() + MERGE_BUILD_TIMEOUT_MS
|
|
298
|
+
const timed = async (args: string[], opts: GitOptions = {}) => {
|
|
299
|
+
const res = await gitAsyncWithin(args, deadline - Date.now(), { gitDir, ...opts })
|
|
300
|
+
if (res.timedOut) throw new MergeTimedOut()
|
|
301
|
+
return res
|
|
302
|
+
}
|
|
303
|
+
const run = async (args: string[], opts: GitOptions = {}) => {
|
|
304
|
+
const res = await timed(args, opts)
|
|
305
|
+
if (res.status !== 0) {
|
|
306
|
+
throw new Error(`walgit merge: git ${args[0]} failed: ${scrub(res.stderr)}`)
|
|
307
|
+
}
|
|
308
|
+
return res.stdout
|
|
309
|
+
}
|
|
310
|
+
// `merge-base --is-ancestor`: 0 is yes, 1 is no, and anything else is git
|
|
311
|
+
// failing to walk the history, which is not an answer to the question.
|
|
312
|
+
const isAncestor = async (a: string, b: string) => {
|
|
313
|
+
const res = await timed(['merge-base', '--is-ancestor'], { operands: [a, b] })
|
|
314
|
+
if (res.status === 0) return true
|
|
315
|
+
if (res.status === 1) return false
|
|
316
|
+
throw new Error(`walgit merge: git could not walk the history: ${scrub(res.stderr)}`)
|
|
317
|
+
}
|
|
318
|
+
try {
|
|
319
|
+
await gitAsync(['init', '--bare', '--quiet'], { operands: [gitDir] })
|
|
320
|
+
// Borrow the Cache's objects rather than copy them: the merge reads every
|
|
321
|
+
// object it needs from there, and writes the few it makes (a squash's
|
|
322
|
+
// trees and merged blobs, its commit) here, where `git push` finds them
|
|
323
|
+
// and receive-pack receives them into quarantine like any pack.
|
|
324
|
+
fs.writeFileSync(
|
|
325
|
+
path.join(gitDir, 'objects', 'info', 'alternates'),
|
|
326
|
+
`${path.join(repo.dir, 'objects')}\n`,
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
// Peeled to the commit: an annotated tag as the source names a tag object.
|
|
330
|
+
const peel = async (rev: string) => {
|
|
331
|
+
const res = await timed(['rev-parse', '--verify', '--quiet'], {
|
|
332
|
+
operands: [`${rev}^{commit}`],
|
|
333
|
+
})
|
|
334
|
+
const oid = res.stdout.trim()
|
|
335
|
+
return res.status === 0 && OID.test(oid) ? oid : null
|
|
336
|
+
}
|
|
337
|
+
const sourceCommit = await peel(at.sourceOid)
|
|
338
|
+
const targetCommit = await peel(request.expected)
|
|
339
|
+
if (sourceCommit === null || targetCommit === null) {
|
|
340
|
+
return { kind: 'invalid', message: 'the source or the target is not a commit' }
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// Exit 1 with no output is "no common ancestor": two histories, both real.
|
|
344
|
+
// Anything else that is not success is git failing — a missing object, an
|
|
345
|
+
// incomplete Cache — and is not something to tell the caller about their
|
|
346
|
+
// branches.
|
|
347
|
+
const mb = await timed(['merge-base'], { operands: [targetCommit, sourceCommit] })
|
|
348
|
+
if (mb.status === 1 && mb.stdout.trim() === '') return { kind: 'unrelated' }
|
|
349
|
+
if (mb.status !== 0) {
|
|
350
|
+
throw new Error(`walgit merge: git merge-base failed: ${scrub(mb.stderr)}`)
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// Everything the source would bring is already in the target.
|
|
354
|
+
if (await isAncestor(sourceCommit, targetCommit)) {
|
|
355
|
+
return { kind: 'up-to-date', ref: at.target }
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
let commit: string
|
|
359
|
+
if (request.method === 'fast-forward') {
|
|
360
|
+
const ff = await isAncestor(targetCommit, sourceCommit)
|
|
361
|
+
if (!ff) return { kind: 'not-fast-forward', ref: at.target }
|
|
362
|
+
commit = sourceCommit
|
|
363
|
+
} else {
|
|
364
|
+
// The three-way merge, as git computes it, with no working tree and no
|
|
365
|
+
// index: `merge-tree --write-tree` writes the result tree and lists the
|
|
366
|
+
// conflicted paths, and exits 1 when there are any. With `-z
|
|
367
|
+
// --name-only --no-messages` the output is the tree, then one path per
|
|
368
|
+
// conflicted file, NUL-separated — never a marker in any file.
|
|
369
|
+
const merged = await timed(
|
|
370
|
+
['merge-tree', '--write-tree', '--name-only', '--no-messages', '-z'],
|
|
371
|
+
{ operands: [targetCommit, sourceCommit] },
|
|
372
|
+
)
|
|
373
|
+
const [tree = '', ...rest] = merged.stdout.split('\0')
|
|
374
|
+
if (merged.status === 1) {
|
|
375
|
+
const paths = [...new Set(rest.filter((name) => name !== ''))]
|
|
376
|
+
return { kind: 'conflict', paths }
|
|
377
|
+
}
|
|
378
|
+
if (merged.status !== 0 || !OID.test(tree)) {
|
|
379
|
+
throw new Error(`walgit merge: git merge-tree failed: ${scrub(merged.stderr)}`)
|
|
380
|
+
}
|
|
381
|
+
const targetTree = (await run(['rev-parse'], { operands: [`${targetCommit}^{tree}`] })).trim()
|
|
382
|
+
if (tree === targetTree) return { kind: 'up-to-date', ref: at.target }
|
|
383
|
+
|
|
384
|
+
// Author and committer are the one ident the request named, as a seed's
|
|
385
|
+
// are: the caller asked for this commit, and it should say who did.
|
|
386
|
+
const date = `${Math.floor(at.when.getTime() / 1000)} +0000`
|
|
387
|
+
const message = request.message!.endsWith('\n') ? request.message! : `${request.message}\n`
|
|
388
|
+
commit = (
|
|
389
|
+
await run(['commit-tree', tree, '-p', targetCommit, '-F', '-'], {
|
|
390
|
+
input: message,
|
|
391
|
+
env: {
|
|
392
|
+
GIT_AUTHOR_NAME: request.author!.name,
|
|
393
|
+
GIT_AUTHOR_EMAIL: request.author!.email,
|
|
394
|
+
GIT_AUTHOR_DATE: date,
|
|
395
|
+
GIT_COMMITTER_NAME: request.author!.name,
|
|
396
|
+
GIT_COMMITTER_EMAIL: request.author!.email,
|
|
397
|
+
GIT_COMMITTER_DATE: date,
|
|
398
|
+
},
|
|
399
|
+
})
|
|
400
|
+
).trim()
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// The push. The lease is the compare-and-swap git holds: receive-pack is
|
|
404
|
+
// told the target's old value is `expected`, so it moves the ref only from
|
|
405
|
+
// there, and the publish in `reference-transaction` refuses it again if
|
|
406
|
+
// the Index has moved. Every refusal a client's push could meet, this
|
|
407
|
+
// push meets in the same words.
|
|
408
|
+
const pushed = await gitAsync(
|
|
409
|
+
[
|
|
410
|
+
'push',
|
|
411
|
+
'--porcelain',
|
|
412
|
+
`--force-with-lease=${at.target}:${request.expected}`,
|
|
413
|
+
repo.dir,
|
|
414
|
+
`${commit}:${at.target}`,
|
|
415
|
+
],
|
|
416
|
+
{ gitDir },
|
|
417
|
+
)
|
|
418
|
+
if (pushed.status !== 0) {
|
|
419
|
+
const refusal = await refusalOf(
|
|
420
|
+
deps,
|
|
421
|
+
repo,
|
|
422
|
+
{ target: at.target, expected: request.expected, commit },
|
|
423
|
+
scrub(`${pushed.stdout}\n${pushed.stderr}`),
|
|
424
|
+
)
|
|
425
|
+
// `landed`: the Index already holds this merge's commit, so the push
|
|
426
|
+
// published and failed after — the merge stands, and is answered as one.
|
|
427
|
+
if (refusal !== 'landed') return refusal
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// What the merge changed on the target — the compare's summary of the new
|
|
431
|
+
// commit against the old one, without the diff text. Best-effort: the
|
|
432
|
+
// merge has landed, and a summary that ran out of time must not read as a
|
|
433
|
+
// merge that failed.
|
|
434
|
+
let summary: Extract<MergeResult, { kind: 'merged' }>['summary'] = null
|
|
435
|
+
try {
|
|
436
|
+
const compared = await compareRevs(repo.dir, targetCommit, commit, {
|
|
437
|
+
maxFiles: COMPARE_MAX_FILES,
|
|
438
|
+
maxDiffBytes: 0,
|
|
439
|
+
timeoutMs: MERGE_SUMMARY_TIMEOUT_MS,
|
|
440
|
+
})
|
|
441
|
+
if (compared !== null && typeof compared === 'object') {
|
|
442
|
+
summary = {
|
|
443
|
+
files: compared.files,
|
|
444
|
+
totals: compared.totals,
|
|
445
|
+
truncated: compared.files.length < compared.totals.files,
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
} catch {
|
|
449
|
+
summary = null
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
return {
|
|
453
|
+
kind: 'merged',
|
|
454
|
+
repo: repo.repoId,
|
|
455
|
+
method: request.method,
|
|
456
|
+
source: { ref: at.source, oid: sourceCommit },
|
|
457
|
+
target: { ref: at.target, previous: request.expected, oid: commit },
|
|
458
|
+
commit,
|
|
459
|
+
summary,
|
|
460
|
+
}
|
|
461
|
+
} catch (err) {
|
|
462
|
+
if (err instanceof MergeTimedOut) return { kind: 'too-large' }
|
|
463
|
+
throw err
|
|
464
|
+
} finally {
|
|
465
|
+
fs.rmSync(scratch, { recursive: true, force: true })
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Why the push was refused, in the caller's terms — or `'landed'`, when it was
|
|
471
|
+
* not refused at all.
|
|
472
|
+
*
|
|
473
|
+
* The Index is read again first, because it decides: if it holds this merge's
|
|
474
|
+
* commit the merge published (and something failed after); if the target
|
|
475
|
+
* moved, that is the answer whatever git said, the same 409 a stale
|
|
476
|
+
* expectation gets up front; if a Claim landed since the up-front check, it is
|
|
477
|
+
* the Signer List refusal. Otherwise git's own words decide between a lost race
|
|
478
|
+
* (a lease that no longer holds, a ref another push has locked, the publish's
|
|
479
|
+
* own compare-and-swap), a rule's refusal — passed through as it was written,
|
|
480
|
+
* a hook's `walgit:` line or git's own size-cap refusal — and anything else, which is a failure
|
|
481
|
+
* rather than a verdict and is answered as one.
|
|
482
|
+
*/
|
|
483
|
+
async function refusalOf(
|
|
484
|
+
deps: MergeDeps,
|
|
485
|
+
repo: ResolvedRepo,
|
|
486
|
+
at: { target: string; expected: string; commit: string },
|
|
487
|
+
output: string,
|
|
488
|
+
): Promise<MergeResult | 'landed'> {
|
|
489
|
+
try {
|
|
490
|
+
const { index } = await loadIndex(deps.store, repo.repoId)
|
|
491
|
+
const actual = index.refs[at.target]
|
|
492
|
+
if (actual === at.commit) return 'landed'
|
|
493
|
+
if (actual !== undefined && actual !== at.expected) {
|
|
494
|
+
return { kind: 'stale', ref: at.target, expected: at.expected, actual }
|
|
495
|
+
}
|
|
496
|
+
if (deps.signerLists && index.claim) {
|
|
497
|
+
return {
|
|
498
|
+
kind: 'signed',
|
|
499
|
+
message:
|
|
500
|
+
`"${repo.repoId}" was claimed by a Signer List while this merge was in flight, so a ref here now moves only by a push a listed key signed — ` +
|
|
501
|
+
'merge in a clone and push it signed',
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
} catch {
|
|
505
|
+
// The store is what decides; unread, git's words are all there is.
|
|
506
|
+
}
|
|
507
|
+
const lost =
|
|
508
|
+
/stale info|failed to lock|cannot lock|unable to lock|moved under this push|stayed contended|fetch first|non-fast-forward/i
|
|
509
|
+
if (lost.test(output)) {
|
|
510
|
+
return {
|
|
511
|
+
kind: 'contended',
|
|
512
|
+
ref: at.target,
|
|
513
|
+
message: `${at.target} was being moved by another write while this merge was in flight — read it again and retry`,
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
// A rule's words: a hook's `walgit:` line, or git's own refusal of a pack
|
|
517
|
+
// over `receive.maxInputSize` — the per-push size cap, which walgit sets on
|
|
518
|
+
// the Cache so an oversized pack is refused before it is read whole.
|
|
519
|
+
const said = output
|
|
520
|
+
.split('\n')
|
|
521
|
+
.map((line) => line.replace(/^remote:\s?/, '').trim())
|
|
522
|
+
.filter((line) => line.startsWith('walgit:') || /pack exceeds maximum allowed size/.test(line))
|
|
523
|
+
if (said.length > 0) return { kind: 'refused', message: said.join(' ') }
|
|
524
|
+
return { kind: 'unavailable', message: `the merge push failed: ${output}` }
|
|
525
|
+
}
|
|
@@ -22,7 +22,17 @@
|
|
|
22
22
|
*
|
|
23
23
|
* ── what a "source" is ──────────────────────────────────────────────────────
|
|
24
24
|
*
|
|
25
|
-
*
|
|
25
|
+
* The TENANT, when the request proves one: a verified scoped token
|
|
26
|
+
* (`shared/scoped-token.ts`, docs/adr/0021) carrying a `sub` claim is counted
|
|
27
|
+
* in a bucket for that `sub`, across every repository it holds a token for and
|
|
28
|
+
* every address it pushes from. Hosted agents run on shared cloud addresses, so
|
|
29
|
+
* keying them on the address would put unrelated tenants in one bucket. Only a
|
|
30
|
+
* claim the handler has VERIFIED is ever a key — an unverified token is refused
|
|
31
|
+
* long before this — and the tenant and address key spaces are kept apart
|
|
32
|
+
* (`keyOf` below), so no `sub` can share a bucket with an address.
|
|
33
|
+
*
|
|
34
|
+
* Otherwise — no scoped token, one without `sub`, or the admin credential —
|
|
35
|
+
* whatever the Worker can see, which is the client IP (`cf-connecting-ip`, set
|
|
26
36
|
* by Cloudflare at the edge and not forgeable by a client, since the container
|
|
27
37
|
* is reachable only through the Worker). A request carrying no such header is
|
|
28
38
|
* unattributable — a direct request to the container, a local deployment — and
|
|
@@ -85,9 +95,23 @@ export type RateKind = 'new-repos' | 'pushes' | 'push-bytes'
|
|
|
85
95
|
|
|
86
96
|
export type RateVerdict = { ok: true } | { ok: false; kind: RateKind; message: string }
|
|
87
97
|
|
|
98
|
+
/**
|
|
99
|
+
* Who a push is counted against: the tenant a verified scoped token names, or
|
|
100
|
+
* the address the edge attributed the request to.
|
|
101
|
+
*/
|
|
102
|
+
export type RateSource = { per: 'tenant'; sub: string } | { per: 'address'; address: string }
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The bucket a source is counted in. Prefixed by kind, so the two key spaces
|
|
106
|
+
* are disjoint: a token whose `sub` is `203.0.113.7` is not that address.
|
|
107
|
+
*/
|
|
108
|
+
function keyOf(source: RateSource): string {
|
|
109
|
+
return source.per === 'tenant' ? `tenant:${source.sub}` : `ip:${source.address}`
|
|
110
|
+
}
|
|
111
|
+
|
|
88
112
|
export interface RateCharge {
|
|
89
|
-
/**
|
|
90
|
-
source:
|
|
113
|
+
/** Who this push is counted against. */
|
|
114
|
+
source: RateSource
|
|
91
115
|
/** The repository this push names. */
|
|
92
116
|
repoId: string
|
|
93
117
|
/** Does this push bring a name into existence? */
|
|
@@ -135,15 +159,16 @@ export function createSourceLimiter(
|
|
|
135
159
|
|
|
136
160
|
// Re-inserted on every touch, so Map iteration order is least-recently
|
|
137
161
|
// seen first and the eviction below drops the right one.
|
|
138
|
-
const
|
|
139
|
-
spends.
|
|
162
|
+
const key = keyOf(charge.source)
|
|
163
|
+
const previous = spends.get(key)
|
|
164
|
+
spends.delete(key)
|
|
140
165
|
const window = (previous ?? []).filter((spend) => spend.at > since)
|
|
141
166
|
|
|
142
167
|
const verdict = judge(limits, window, charge)
|
|
143
168
|
if (verdict.ok) window.push({ at, bytes: charge.bytes, creating: charge.creating })
|
|
144
169
|
|
|
145
170
|
if (window.length > 0) {
|
|
146
|
-
spends.set(
|
|
171
|
+
spends.set(key, window)
|
|
147
172
|
if (spends.size > MAX_SOURCES) {
|
|
148
173
|
const oldest = spends.keys().next()
|
|
149
174
|
if (!oldest.done) spends.delete(oldest.value)
|
|
@@ -166,6 +191,7 @@ export function createSourceLimiter(
|
|
|
166
191
|
*/
|
|
167
192
|
function judge(limits: RateLimits, window: Spend[], charge: RateCharge): RateVerdict {
|
|
168
193
|
const window_ = describeWindow(limits.windowMs / 1000)
|
|
194
|
+
const who = charge.source.per === 'tenant' ? 'tenant' : 'client'
|
|
169
195
|
|
|
170
196
|
if (charge.creating && limits.maxNewRepos !== null) {
|
|
171
197
|
const created = window.filter((spend) => spend.creating).length
|
|
@@ -173,13 +199,13 @@ function judge(limits: RateLimits, window: Spend[], charge: RateCharge): RateVer
|
|
|
173
199
|
return {
|
|
174
200
|
ok: false,
|
|
175
201
|
kind: 'new-repos',
|
|
176
|
-
message: tooManyNewRepos(charge.repoId, limits.maxNewRepos, window_),
|
|
202
|
+
message: tooManyNewRepos(charge.repoId, limits.maxNewRepos, window_, who),
|
|
177
203
|
}
|
|
178
204
|
}
|
|
179
205
|
}
|
|
180
206
|
|
|
181
207
|
if (limits.maxPushes !== null && window.length >= limits.maxPushes) {
|
|
182
|
-
return { ok: false, kind: 'pushes', message: tooManyPushes(limits.maxPushes, window_) }
|
|
208
|
+
return { ok: false, kind: 'pushes', message: tooManyPushes(limits.maxPushes, window_, who) }
|
|
183
209
|
}
|
|
184
210
|
|
|
185
211
|
if (limits.maxPushBytes !== null) {
|
|
@@ -188,7 +214,7 @@ function judge(limits: RateLimits, window: Spend[], charge: RateCharge): RateVer
|
|
|
188
214
|
return {
|
|
189
215
|
ok: false,
|
|
190
216
|
kind: 'push-bytes',
|
|
191
|
-
message: tooManyBytes(spent, charge.bytes, limits.maxPushBytes, window_),
|
|
217
|
+
message: tooManyBytes(spent, charge.bytes, limits.maxPushBytes, window_, who),
|
|
192
218
|
}
|
|
193
219
|
}
|
|
194
220
|
}
|
|
@@ -196,6 +222,14 @@ function judge(limits: RateLimits, window: Spend[], charge: RateCharge): RateVer
|
|
|
196
222
|
return { ok: true }
|
|
197
223
|
}
|
|
198
224
|
|
|
225
|
+
type Who = 'tenant' | 'client'
|
|
226
|
+
|
|
227
|
+
/** Whose spend a refusal is about: the tenant the token names, or this client. */
|
|
228
|
+
const counted = (who: Who): string[] =>
|
|
229
|
+
who === 'tenant'
|
|
230
|
+
? ["Counted per tenant (your token's sub), across all its repositories and addresses."]
|
|
231
|
+
: []
|
|
232
|
+
|
|
199
233
|
/**
|
|
200
234
|
* Product copy, and the same discipline the size caps are written with: say
|
|
201
235
|
* which limit, say the number, and say the one thing to do next. A rate limit
|
|
@@ -203,11 +237,12 @@ function judge(limits: RateLimits, window: Spend[], charge: RateCharge): RateVer
|
|
|
203
237
|
* again, so each message states that waiting is the remedy and roughly what
|
|
204
238
|
* for.
|
|
205
239
|
*/
|
|
206
|
-
function tooManyNewRepos(repoId: string, cap: number, window: string): string {
|
|
240
|
+
function tooManyNewRepos(repoId: string, cap: number, window: string, who: Who): string {
|
|
207
241
|
return [
|
|
208
242
|
`walgit: refused — ${repoId} would be your ${cap + 1}${ordinal(cap + 1)} new repository this ${window}.`,
|
|
209
243
|
'',
|
|
210
|
-
`This host lets one
|
|
244
|
+
`This host lets one ${who} create ${cap} ${plural(cap, 'repository', 'repositories')} per ${window}.`,
|
|
245
|
+
...counted(who),
|
|
211
246
|
'This is a walgit limit, not a network failure. Retrying now will be refused',
|
|
212
247
|
'again in the same way.',
|
|
213
248
|
'',
|
|
@@ -219,11 +254,12 @@ function tooManyNewRepos(repoId: string, cap: number, window: string): string {
|
|
|
219
254
|
].join('\n')
|
|
220
255
|
}
|
|
221
256
|
|
|
222
|
-
function tooManyPushes(cap: number, window: string): string {
|
|
257
|
+
function tooManyPushes(cap: number, window: string, who: Who): string {
|
|
223
258
|
return [
|
|
224
259
|
`walgit: refused — you have already made ${cap} ${plural(cap, 'push', 'pushes')} this ${window}.`,
|
|
225
260
|
'',
|
|
226
|
-
`This host lets one
|
|
261
|
+
`This host lets one ${who} push ${cap} ${plural(cap, 'time', 'times')} per ${window}.`,
|
|
262
|
+
...counted(who),
|
|
227
263
|
'This is a walgit limit, not a network failure. Retrying now will be refused',
|
|
228
264
|
'again in the same way.',
|
|
229
265
|
'',
|
|
@@ -235,12 +271,13 @@ function tooManyPushes(cap: number, window: string): string {
|
|
|
235
271
|
].join('\n')
|
|
236
272
|
}
|
|
237
273
|
|
|
238
|
-
function tooManyBytes(spent: number, bytes: number, cap: number, window: string): string {
|
|
274
|
+
function tooManyBytes(spent: number, bytes: number, cap: number, window: string, who: Who): string {
|
|
239
275
|
return [
|
|
240
276
|
`walgit: refused — this push would take you past ${describeBytes(cap)} pushed this ${window}.`,
|
|
241
277
|
'',
|
|
242
278
|
`You have pushed ${describeBytes(spent)} in the last ${window} and this push adds`,
|
|
243
279
|
`${describeBytes(bytes)}.`,
|
|
280
|
+
...counted(who),
|
|
244
281
|
'This is a walgit limit, not a network failure. Retrying now will be refused',
|
|
245
282
|
'again in the same way.',
|
|
246
283
|
'',
|