@yaks/git 0.0.0-stage → 0.2.36

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.
Files changed (183) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +754 -2
  3. package/_dist/address.d.ts +6 -0
  4. package/_dist/address.d.ts.map +1 -0
  5. package/_dist/checkout_vocab.d.ts +3 -0
  6. package/_dist/checkout_vocab.d.ts.map +1 -0
  7. package/_dist/cites.d.ts +48 -0
  8. package/_dist/cites.d.ts.map +1 -0
  9. package/_dist/commit.d.ts +36 -0
  10. package/_dist/commit.d.ts.map +1 -0
  11. package/_dist/comp.d.ts +29 -0
  12. package/_dist/comp.d.ts.map +1 -0
  13. package/_dist/door.d.ts +29 -0
  14. package/_dist/door.d.ts.map +1 -0
  15. package/_dist/format.d.ts +2 -0
  16. package/_dist/format.d.ts.map +1 -0
  17. package/_dist/hold.d.ts +6 -0
  18. package/_dist/hold.d.ts.map +1 -0
  19. package/_dist/host.d.ts +126 -0
  20. package/_dist/host.d.ts.map +1 -0
  21. package/_dist/http.d.ts +33 -0
  22. package/_dist/http.d.ts.map +1 -0
  23. package/_dist/import.d.ts +13 -0
  24. package/_dist/import.d.ts.map +1 -0
  25. package/_dist/index.d.ts +80 -0
  26. package/_dist/index.d.ts.map +1 -0
  27. package/_dist/land.d.ts +77 -0
  28. package/_dist/land.d.ts.map +1 -0
  29. package/_dist/mod.d.ts +73 -0
  30. package/_dist/mod.d.ts.map +1 -0
  31. package/_dist/objects.d.ts +40 -0
  32. package/_dist/objects.d.ts.map +1 -0
  33. package/_dist/oid.d.ts +24 -0
  34. package/_dist/oid.d.ts.map +1 -0
  35. package/_dist/pack-store.d.ts +9 -0
  36. package/_dist/pack-store.d.ts.map +1 -0
  37. package/_dist/pack.d.ts +26 -0
  38. package/_dist/pack.d.ts.map +1 -0
  39. package/_dist/pkt.d.ts +14 -0
  40. package/_dist/pkt.d.ts.map +1 -0
  41. package/_dist/placement.d.ts +4 -0
  42. package/_dist/placement.d.ts.map +1 -0
  43. package/_dist/plugin.d.ts +43 -0
  44. package/_dist/plugin.d.ts.map +1 -0
  45. package/_dist/project.d.ts +20 -0
  46. package/_dist/project.d.ts.map +1 -0
  47. package/_dist/push.d.ts +42 -0
  48. package/_dist/push.d.ts.map +1 -0
  49. package/_dist/refs.d.ts +81 -0
  50. package/_dist/refs.d.ts.map +1 -0
  51. package/_dist/rewrite.d.ts +35 -0
  52. package/_dist/rewrite.d.ts.map +1 -0
  53. package/_dist/service.d.ts +35 -0
  54. package/_dist/service.d.ts.map +1 -0
  55. package/_dist/sha1.d.ts +11 -0
  56. package/_dist/sha1.d.ts.map +1 -0
  57. package/_dist/source.d.ts +12 -0
  58. package/_dist/source.d.ts.map +1 -0
  59. package/_dist/tools.d.ts +11 -0
  60. package/_dist/tools.d.ts.map +1 -0
  61. package/_dist/tree.d.ts +28 -0
  62. package/_dist/tree.d.ts.map +1 -0
  63. package/_dist/unpack.d.ts +5 -0
  64. package/_dist/unpack.d.ts.map +1 -0
  65. package/_dist/vocab.d.ts +8 -0
  66. package/_dist/vocab.d.ts.map +1 -0
  67. package/_dist/workspace.d.ts +17 -0
  68. package/_dist/workspace.d.ts.map +1 -0
  69. package/address.js +9 -0
  70. package/address.js.map +1 -0
  71. package/address.ts +15 -0
  72. package/cache.js +9 -0
  73. package/cache.js.map +1 -0
  74. package/cache.ts +6 -0
  75. package/checkout.js +18 -0
  76. package/checkout.js.map +1 -0
  77. package/checkout.ts +24 -0
  78. package/checkout_vocab.js +14 -0
  79. package/checkout_vocab.js.map +1 -0
  80. package/checkout_vocab.ts +11 -0
  81. package/cites.js +189 -0
  82. package/cites.js.map +1 -0
  83. package/cites.ts +206 -0
  84. package/commit.js +128 -0
  85. package/commit.js.map +1 -0
  86. package/commit.ts +183 -0
  87. package/comp.js +94 -0
  88. package/comp.js.map +1 -0
  89. package/comp.ts +111 -0
  90. package/deno.json +1 -0
  91. package/door.js +88 -0
  92. package/door.js.map +1 -0
  93. package/door.ts +142 -0
  94. package/format.js +43 -0
  95. package/format.js.map +1 -0
  96. package/format.ts +49 -0
  97. package/hold.js +17 -0
  98. package/hold.js.map +1 -0
  99. package/hold.ts +21 -0
  100. package/host.js +1024 -0
  101. package/host.js.map +1 -0
  102. package/host.ts +1140 -0
  103. package/http.js +268 -0
  104. package/http.js.map +1 -0
  105. package/http.ts +329 -0
  106. package/import.js +141 -0
  107. package/import.js.map +1 -0
  108. package/import.ts +128 -0
  109. package/index.js +496 -0
  110. package/index.js.map +1 -0
  111. package/index.ts +634 -0
  112. package/land.js +788 -0
  113. package/land.js.map +1 -0
  114. package/land.ts +871 -0
  115. package/mod.js +73 -0
  116. package/mod.js.map +1 -0
  117. package/mod.ts +74 -0
  118. package/objects.js +331 -0
  119. package/objects.js.map +1 -0
  120. package/objects.ts +390 -0
  121. package/oid.js +50 -0
  122. package/oid.js.map +1 -0
  123. package/oid.ts +83 -0
  124. package/pack-index.js +103 -0
  125. package/pack-index.js.map +1 -0
  126. package/pack-index.ts +104 -0
  127. package/pack-store.js +216 -0
  128. package/pack-store.js.map +1 -0
  129. package/pack-store.ts +292 -0
  130. package/pack.js +121 -0
  131. package/pack.js.map +1 -0
  132. package/pack.ts +146 -0
  133. package/package.json +78 -4
  134. package/pkt.js +73 -0
  135. package/pkt.js.map +1 -0
  136. package/pkt.ts +93 -0
  137. package/placement.js +44 -0
  138. package/placement.js.map +1 -0
  139. package/placement.ts +38 -0
  140. package/plugin.js +66 -0
  141. package/plugin.js.map +1 -0
  142. package/plugin.ts +88 -0
  143. package/process-cwd.py +57 -0
  144. package/project.js +142 -0
  145. package/project.js.map +1 -0
  146. package/project.ts +151 -0
  147. package/push.js +401 -0
  148. package/push.js.map +1 -0
  149. package/push.ts +451 -0
  150. package/refs.js +176 -0
  151. package/refs.js.map +1 -0
  152. package/refs.ts +285 -0
  153. package/rewrite.js +176 -0
  154. package/rewrite.js.map +1 -0
  155. package/rewrite.ts +173 -0
  156. package/service.js +104 -0
  157. package/service.js.map +1 -0
  158. package/service.ts +194 -0
  159. package/sha1.js +115 -0
  160. package/sha1.js.map +1 -0
  161. package/sha1.ts +146 -0
  162. package/source.js +100 -0
  163. package/source.js.map +1 -0
  164. package/source.ts +116 -0
  165. package/spare.js +108 -0
  166. package/spare.js.map +1 -0
  167. package/spare.ts +94 -0
  168. package/tools.js +278 -0
  169. package/tools.js.map +1 -0
  170. package/tools.ts +310 -0
  171. package/tree.js +105 -0
  172. package/tree.js.map +1 -0
  173. package/tree.ts +132 -0
  174. package/unpack.js +207 -0
  175. package/unpack.js.map +1 -0
  176. package/unpack.ts +210 -0
  177. package/vocab.js +20 -0
  178. package/vocab.js.map +1 -0
  179. package/vocab.json +386 -0
  180. package/vocab.ts +22 -0
  181. package/workspace.js +449 -0
  182. package/workspace.js.map +1 -0
  183. package/workspace.ts +445 -0
package/push.ts ADDED
@@ -0,0 +1,451 @@
1
+ import { holding } from '@yaks/blob'
2
+ import { type Clock, system } from '@yaks/fp'
3
+ import { commitParts } from './commit.js'
4
+ import { concat } from './oid.js'
5
+ import type { Kind } from './oid.js'
6
+ import type { Obj } from './pack.ts'
7
+ import { DIR, type Entry, treeEntries } from './tree.js'
8
+ import type { Objects } from './objects.ts'
9
+ import { RECEIVE, type Ref, type Refs } from './http.js'
10
+ import { FLUSH, mark, pkt, read as packets } from './pkt.js'
11
+ import { BadPush, PACK_LIMIT, type ReadObject, unpack } from './unpack.js'
12
+
13
+ export let ZERO: string = '0'.repeat(40)
14
+
15
+ export type Update = { name: string; before: string | null; after: string }
16
+ export type Push = {
17
+ update: Update
18
+ objects: Map<string, Obj>
19
+ read: ReadObject
20
+ /** what an object is, answered without reading it where a pushed or
21
+ * replaced tree names it */
22
+ kind: (id: string) => Promise<Kind | undefined>
23
+ }
24
+ export type Receiver = {
25
+ branch: string
26
+ base?: string
27
+ accept: (push: Push) => Promise<void>
28
+ /** a stage of receiving, on the host's clock */
29
+ time?: <T>(stage: string, work: () => Promise<T>) => Promise<T>
30
+ /** How long the host can wait for the final report before sending the
31
+ * unpack status and streaming the rest. Called after pack validation. */
32
+ streamAfter?: () => { ms: number; clock?: Clock } | undefined
33
+ }
34
+
35
+ let text = new TextDecoder()
36
+ let git = (type: string, body: Uint8Array<ArrayBuffer> | ReadableStream) =>
37
+ new Response(body, {
38
+ headers: {
39
+ 'content-type': `application/x-git-receive-pack-${type}`,
40
+ 'cache-control': 'no-cache, no-store',
41
+ },
42
+ })
43
+
44
+ /** The answer to `GET <repo>/info/refs?service=git-receive-pack`. `listed`
45
+ * hears the refs it advertised, as a host warms what the push will read. */
46
+ export let advertiseReceive = async (
47
+ refs: Refs,
48
+ listed: (refs: Ref[]) => void = () => {},
49
+ ): Promise<Response> => {
50
+ let current = await refs.list()
51
+ listed(current)
52
+ return advertised(current)
53
+ }
54
+
55
+ let advertised = (listed: Ref[]) => {
56
+ if (!listed.length) listed = [{ name: 'capabilities^{}', oid: ZERO }]
57
+ return git(
58
+ 'advertisement',
59
+ concat([
60
+ pkt(`# service=${RECEIVE}\n`),
61
+ mark(FLUSH),
62
+ ...listed.map(({ name, oid }, i) =>
63
+ pkt(
64
+ `${oid} ${name}${
65
+ i
66
+ ? ''
67
+ : '\0report-status ofs-delta no-thin object-format=sha1 agent=yaks'
68
+ }\n`,
69
+ )
70
+ ),
71
+ mark(FLUSH),
72
+ ]),
73
+ )
74
+ }
75
+
76
+ let request = (bytes: Uint8Array) => {
77
+ let at = 0
78
+ let commands: string[] = []
79
+ for (;;) {
80
+ let length = text.decode(bytes.subarray(at, at + 4))
81
+ if (!/^[0-9a-f]{4}$/.test(length)) {
82
+ throw new BadPush('invalid command framing')
83
+ }
84
+ if (length == '0000') return { commands, pack: bytes.subarray(at + 4) }
85
+ let end = at + parseInt(length, 16)
86
+ if (end <= at + 4 || end > bytes.length || commands.length >= 100) {
87
+ throw new BadPush('invalid command list')
88
+ }
89
+ let [line] = packets(bytes.subarray(at, end))
90
+ commands.push((line as string).split('\0', 1)[0])
91
+ at = end
92
+ }
93
+ }
94
+
95
+ let id = '[0-9a-f]{40}'
96
+ let command = new RegExp(`^(${id}) (${id}) (refs/[^\\s\\x00-\\x1f\\x7f]+)$`)
97
+ let lineOf = (line: string): Update => {
98
+ let parsed = command.exec(line)
99
+ if (!parsed) throw new BadPush('invalid ref update')
100
+ let [, before, after, name] = parsed
101
+ return { before: before == ZERO ? null : before, after, name }
102
+ }
103
+
104
+ let safe = (s: string) => s.replace(/[\r\n\0]/g, ' ').slice(0, 4000)
105
+ let unpackStatus = (status: string) => pkt(`unpack ${safe(status)}\n`)
106
+ let refStatus = (updates: Update[], reason = '') =>
107
+ concat([
108
+ ...updates.map(({ name }) =>
109
+ pkt(reason ? `ng ${name} ${safe(reason)}\n` : `ok ${name}\n`)
110
+ ),
111
+ mark(FLUSH),
112
+ ])
113
+ let result = (updates: Update[], reason = '', unpacked = 'ok') =>
114
+ git('result', concat([unpackStatus(unpacked), refStatus(updates, reason)]))
115
+
116
+ let reporting = async (
117
+ status: Promise<Uint8Array<ArrayBuffer>>,
118
+ after: ReturnType<NonNullable<Receiver['streamAfter']>>,
119
+ ) => {
120
+ let first = unpackStatus('ok')
121
+ if (!after) return git('result', concat([first, await status]))
122
+ let time = after.clock ?? system
123
+ let pending = Promise.withResolvers<null>()
124
+ let cancel = time.after(after.ms, () => pending.resolve(null))
125
+ let rest = await Promise.race([status, pending.promise]).finally(cancel)
126
+ if (rest) return git('result', concat([first, rest]))
127
+ let reading = true
128
+ return git(
129
+ 'result',
130
+ new ReadableStream<Uint8Array>({
131
+ start: (out) => out.enqueue(first),
132
+ pull: async (out) => {
133
+ let last = await status
134
+ if (!reading) return
135
+ out.enqueue(last)
136
+ out.close()
137
+ },
138
+ cancel: () => {
139
+ reading = false
140
+ },
141
+ }),
142
+ )
143
+ }
144
+
145
+ // The trees and commits of the pushes this isolate took lately, by id: the
146
+ // trees the next push replaces are nearly always the last one's, and an
147
+ // object's id names its bytes, so they are read from here before the store.
148
+ // Values only, never a promise, and at most RECENT bytes, oldest out first.
149
+ let RECENT = 4 * 1024 ** 2
150
+ let recent = new Map<string, Obj>()
151
+ let recentBytes = 0
152
+ let remember = (pushed: ReadonlyMap<string, Obj>) => {
153
+ for (let [id, object] of pushed) {
154
+ if (object.type == 'blob' || object.bytes.length > RECENT / 8) continue
155
+ if (recent.has(id)) recent.delete(id)
156
+ else recentBytes += object.bytes.length
157
+ recent.set(id, object)
158
+ }
159
+ for (let [id, object] of recent) {
160
+ if (recentBytes <= RECENT) break
161
+ recent.delete(id)
162
+ recentBytes -= object.bytes.length
163
+ }
164
+ }
165
+
166
+ // The trees under a root a push reads ahead of what it replaced, at most.
167
+ let WARM = 16
168
+
169
+ /** Reads into this isolate's memory what a push onto `refs` reads first, a
170
+ * level at a time: each tip's commit, its root tree, and the trees directly
171
+ * in that (a space's `apps`). The client builds its pack between the
172
+ * advertisement and its push, which a host spends on these. */
173
+ export let warm = async (refs: Ref[], objects: Objects): Promise<void> => {
174
+ let level = async (ids: string[]) => {
175
+ let wanted = [...new Set(ids)].filter((id) => !recent.has(id))
176
+ let got = new Map<string, Obj>()
177
+ let i = 0
178
+ if (wanted.length) {
179
+ for await (let object of objects.read(wanted)) {
180
+ got.set(wanted[i++], object)
181
+ }
182
+ }
183
+ remember(got)
184
+ return ids.flatMap((id) => recent.get(id) ?? got.get(id) ?? [])
185
+ }
186
+ let commits = await level(
187
+ refs.map((ref) => ref.oid).filter((oid) => oid != ZERO),
188
+ )
189
+ let roots = await level(commits.map((c) => commitParts(c.bytes).tree))
190
+ await level(
191
+ roots.flatMap((root) =>
192
+ treeEntries(root.bytes).filter((e) => e.mode == DIR).slice(0, WARM)
193
+ .map((e) => e.oid)
194
+ ),
195
+ )
196
+ }
197
+
198
+ // What a push may name without carrying: an object the repository holds
199
+ // that its refs reach, so a push can't borrow an object of somebody else's
200
+ // repository from the store every repository shares. Nearly every such object
201
+ // sits where it was, in the tree the push's own tree replaced at the same
202
+ // path, so those trees are read first, a level at a time, and their entries
203
+ // are the proof (`beside`). Only an object found nowhere near is looked for
204
+ // in the tips' whole snapshots, then in their history. Each object is read
205
+ // once, however many times it is asked for. What a proven object names is
206
+ // proven as soon as that object is read, without waiting for the rest of the
207
+ // walk: a push's changes read the replaced trees from the top, a level at a
208
+ // time, while the walk goes on below them.
209
+ let retained = (
210
+ refs: Ref[],
211
+ objects: Objects,
212
+ pushed: () => Map<string, Obj> | undefined,
213
+ ) => {
214
+ let accessible: Promise<Set<string>> | undefined
215
+ let snapshots: Promise<Set<string>> | undefined
216
+ let near: Promise<Map<string, Kind>> | undefined
217
+ let got = new Map<string, Promise<Obj | undefined>>()
218
+ let roots = new Set(refs.map((r) => r.oid))
219
+ // Every id an object read here names: each was proven before it was read.
220
+ let named = new Set<string>()
221
+ let load = (id: string) => {
222
+ let one = got.get(id)
223
+ if (!one) {
224
+ let kept = recent.get(id)
225
+ one = (kept ? Promise.resolve(kept) : (async () => {
226
+ for await (let object of objects.read([id])) return object
227
+ })()).then((object) => {
228
+ if (object) { for (let link of links(object)) named.add(link) }
229
+ return object
230
+ })
231
+ got.set(id, one)
232
+ }
233
+ return one
234
+ }
235
+ let nearby = () => {
236
+ let all = pushed()
237
+ if (!all) return undefined
238
+ return near ??= beside(all, roots, (ids) => Promise.all(ids.map(load)))
239
+ }
240
+ let proven = async (id: string) => {
241
+ if (roots.has(id) || named.has(id)) return true
242
+ if ((await nearby())?.has(id)) return true
243
+ snapshots ??= objects.snapshots?.([...roots]).then((ids) => new Set(ids))
244
+ if ((await snapshots)?.has(id)) return true
245
+ accessible ??= objects.reach([...roots]).then((ids) => new Set(ids))
246
+ return (await accessible).has(id)
247
+ }
248
+ let read: ReadObject = async (id) => {
249
+ if (await proven(id)) return await load(id)
250
+ }
251
+ // What an object is, from the tree that names it where one does, without
252
+ // reading the object.
253
+ let kind = async (id: string): Promise<Kind | undefined> =>
254
+ (await nearby())?.get(id) ?? (await read(id))?.type
255
+ return { read, kind }
256
+ }
257
+
258
+ // The ids a commit or a tree names: its tree and parents, or its entries.
259
+ let links = (object: Obj): string[] => {
260
+ if (object.type == 'tree') return treeEntries(object.bytes).map((e) => e.oid)
261
+ if (object.type != 'commit') return []
262
+ let { tree, parents } = commitParts(object.bytes)
263
+ return [tree, ...parents]
264
+ }
265
+
266
+ // Every object named by a tree a push replaced, and what each is: the trees of
267
+ // the pushed commits' parents the refs reach, and below them each tree the
268
+ // push replaced with one of its own at the same name.
269
+ let beside = async (
270
+ pushed: Map<string, Obj>,
271
+ roots: Set<string>,
272
+ load: (ids: string[]) => Promise<(Obj | undefined)[]>,
273
+ ): Promise<Map<string, Kind>> => {
274
+ let near = new Map<string, Kind>()
275
+ let parts = (obj: Obj) => {
276
+ try {
277
+ return commitParts(obj.bytes)
278
+ } catch {
279
+ throw new BadPush('invalid commit body')
280
+ }
281
+ }
282
+ let commits = [...pushed.values()].filter((o) => o.type == 'commit')
283
+ .map(parts)
284
+ let outside = [
285
+ ...new Set(
286
+ commits.flatMap((c) => c.parents).filter((p) =>
287
+ !pushed.has(p) && roots.has(p)
288
+ ),
289
+ ),
290
+ ]
291
+ let held = new Map<string, Obj | undefined>()
292
+ let fetched = async (ids: string[]) => {
293
+ let wanted = [...new Set(ids)].filter((id) =>
294
+ !pushed.has(id) && !held.has(id)
295
+ )
296
+ let found = await load(wanted)
297
+ wanted.forEach((id, i) => held.set(id, found[i]))
298
+ }
299
+ let get = (id: string) => pushed.get(id) ?? held.get(id)
300
+ await fetched(outside)
301
+ let pairs: [string, string][] = []
302
+ for (let { tree, parents } of commits) {
303
+ for (let parent of parents) {
304
+ let body = get(parent)
305
+ if (body?.type != 'commit') continue
306
+ let was = parts(body).tree
307
+ near.set(was, 'tree')
308
+ pairs.push([tree, was])
309
+ }
310
+ }
311
+ while (pairs.length) {
312
+ await fetched(pairs.map(([, was]) => was))
313
+ let next: [string, string][] = []
314
+ for (let [now, was] of pairs) {
315
+ let old = get(was)
316
+ if (old?.type != 'tree') continue
317
+ let byName = new Map<string, Entry>()
318
+ for (let entry of treeEntries(old.bytes)) {
319
+ near.set(entry.oid, entry.mode == DIR ? 'tree' : 'blob')
320
+ byName.set(entry.name, entry)
321
+ }
322
+ let fresh = pushed.get(now)
323
+ if (fresh?.type != 'tree' || now == was) continue
324
+ for (let entry of treeEntries(fresh.bytes)) {
325
+ let prior = byName.get(entry.name)
326
+ if (
327
+ entry.mode == DIR && prior?.mode == DIR && prior.oid != entry.oid &&
328
+ pushed.has(entry.oid)
329
+ ) next.push([entry.oid, prior.oid])
330
+ }
331
+ }
332
+ pairs = next
333
+ }
334
+ return near
335
+ }
336
+
337
+ let advances = async (update: Update, read: ReadObject) => {
338
+ let next = [update.after]
339
+ let seen = new Set<string>()
340
+ for (let oid of next) {
341
+ if (seen.has(oid)) continue
342
+ seen.add(oid)
343
+ // The branch's own tip is a stored commit: reaching it needs no read.
344
+ if (oid == update.before) return
345
+ let commit = await read(oid)
346
+ if (commit?.type != 'commit') throw new BadPush(`missing commit ${oid}`)
347
+ if (!update.before) return
348
+ try {
349
+ next.push(...commitParts(commit.bytes).parents)
350
+ } catch {
351
+ throw new BadPush('invalid commit body')
352
+ }
353
+ }
354
+ throw new BadPush('non-fast-forward; pull before pushing again')
355
+ }
356
+
357
+ /** Receive one ref update over smart HTTP. The host advances its guarded ref
358
+ * only after the associated write succeeds. */
359
+ export let receivePack = async (
360
+ req: Request,
361
+ refs: Refs,
362
+ objects: Objects,
363
+ receiver: Receiver,
364
+ ): Promise<Response> => {
365
+ if (req.method != 'POST') return new Response(null, { status: 405 })
366
+ if (
367
+ req.headers.get('content-type')?.split(';', 1)[0] !=
368
+ 'application/x-git-receive-pack-request'
369
+ ) {
370
+ return new Response(null, { status: 415 })
371
+ }
372
+ let updates: Update[] = []
373
+ let phase = 'unpack'
374
+ try {
375
+ let input = req.body ?? new Blob([]).stream()
376
+ if (req.headers.get('content-encoding') == 'gzip') {
377
+ input = input.pipeThrough(new DecompressionStream('gzip'))
378
+ }
379
+ let body = await holding({ stream: input }, PACK_LIMIT).catch((error) => {
380
+ if (
381
+ error instanceof TypeError &&
382
+ req.headers.get('content-encoding') == 'gzip'
383
+ ) {
384
+ throw new BadPush('invalid compressed push request')
385
+ }
386
+ throw error
387
+ })
388
+ if (!(body instanceof Uint8Array)) {
389
+ await body.stream.cancel()
390
+ return new Response('git: push exceeds size limit\n', { status: 413 })
391
+ }
392
+ let { commands, pack } = request(body)
393
+ updates = commands.map(lineOf)
394
+ phase = 'ref'
395
+ let [update] = updates
396
+ if (!update) return result([], '', 'missing ref update')
397
+ if (updates.length != 1 || update.name != receiver.branch) {
398
+ throw new BadPush(`push to ${receiver.branch}`)
399
+ }
400
+ if (update.after == ZERO) {
401
+ throw new BadPush('deleting the branch is not supported')
402
+ }
403
+ let listed = await refs.list()
404
+ if (
405
+ (listed.find((r) => r.name == update.name)?.oid ?? null) != update.before
406
+ ) {
407
+ throw new BadPush('branch moved; pull before pushing again')
408
+ }
409
+ if (update.before == update.after) return result(updates)
410
+ let time = receiver.time ?? ((_, work) => work())
411
+ let pushed: Map<string, Obj> | undefined
412
+ let existing = retained(listed, objects, () => pushed)
413
+ phase = 'unpack'
414
+ pushed = pack.length
415
+ ? await time('unpack', () => unpack(pack, existing.read))
416
+ : new Map<string, Obj>()
417
+ let held = pushed
418
+ let read: ReadObject = async (oid) =>
419
+ held.get(oid) ?? await existing.read(oid)
420
+ let kind = async (oid: string) =>
421
+ held.get(oid)?.type ?? await existing.kind(oid)
422
+ phase = 'ref'
423
+ await time('advances', async () => {
424
+ await advances(update, read)
425
+ let base = listed.find((r) => r.name == receiver.base)?.oid
426
+ if (base && base != update.before) {
427
+ await advances({ ...update, before: base }, read)
428
+ }
429
+ })
430
+ let status = receiver.accept({ update, objects: held, read, kind }).then(
431
+ () => (remember(held), refStatus(updates)),
432
+ (error) => {
433
+ if (!(error instanceof BadPush)) throw error
434
+ return refStatus(updates, error.message)
435
+ },
436
+ )
437
+ return await reporting(status, receiver.streamAfter?.())
438
+ } catch (e) {
439
+ if (!(e instanceof BadPush)) throw e
440
+ return result(updates, e.message, phase == 'unpack' ? e.message : 'ok')
441
+ }
442
+ }
443
+
444
+ export { BadPush } from './unpack.js'
445
+ export { carriedOf, importPush } from './import.js'
446
+ export {
447
+ namesAt,
448
+ projectCommit,
449
+ pushChanges,
450
+ pushedCommits,
451
+ } from './project.js'
package/refs.js ADDED
@@ -0,0 +1,176 @@
1
+ // Where a branch points, and how a manifest lands on it: the one step between
2
+ // "here are some files" and "this repository has a new commit".
3
+ //
4
+ // A ref is A row, one per repository and branch name ({@link refEid}), so
5
+ // moving a branch updates the row that is already there rather than adding a
6
+ // second row someone has to notice is stale. It is the one part of a
7
+ // repository that belongs to exactly one repository — objects are named by the
8
+ // digest of their own bytes and are therefore global — which is why the ref
9
+ // graph and the object graph are two separate arguments here ({@link Repo})
10
+ // and may be two separate stores.
11
+ //
12
+ // A landing holds what A commit needs and nothing else: the manifest, the two
13
+ // signatures, the message. The parent is not among them — it is read from the
14
+ // ref, so a commit written by whatever watches for releases and a commit
15
+ // written later by a repair pass are built the same way and land on the same
16
+ // chain.
17
+ //
18
+ // Writing A commit is repeatable, which is what makes a repair pass cheap:
19
+ // every id is a digest of the bytes, and the bytes are the manifest and the
20
+ // timestamps the caller hands over, so landing the same release twice produces
21
+ // the same objects. What it must not do twice is append — hence `beside`,
22
+ // where the caller writes the rows it has already checked are not there.
23
+ import { openedOf } from "@yaks/blob";
24
+ import { Stale } from "@yaks/graph/errors";
25
+ import { token } from "@yaks/graph/sha256";
26
+ import { line } from "@yaks/query";
27
+ import { treeOf } from "./commit.js";
28
+ import { BLOB, REF, refEid } from "./comp.js";
29
+ import { MAIN } from "./http.js";
30
+ import { index, names } from "./index.js";
31
+ // Reads a reference property in either of the two forms a store returns: the
32
+ // bare eid that a read inside a transaction gives, and the `{eid, name}`
33
+ // object that a read over a store's HTTP API gives, which names what the
34
+ // reference points at as it goes. One reader, so a branch reads the same
35
+ // however the graph was reached.
36
+ let id = (v)=>typeof v == 'string' ? v : String(v?.eid ?? '');
37
+ /**
38
+ * Where a branch points: the commit its ref names, or `null` before the first
39
+ * commit. This is all of `ls-refs` on the server's side, so whatever mounts
40
+ * the HTTP handlers reads a branch through this rather than by querying the
41
+ * row itself.
42
+ */ export let refAt = async (refs, app, name = MAIN)=>{
43
+ let [row] = await refs.read(line`.entity.eid=${refEid(app, name)}`);
44
+ return id(row?.[REF]?.commit) || null;
45
+ };
46
+ /** An object already written, with both its ids: its SHA-1 id is the row's own
47
+ * eid, and its SHA-256 id is in the @yaks/key beside it. */ let named = async (g, oid)=>{
48
+ let name = (await names(g, [
49
+ oid
50
+ ])).get(oid);
51
+ return name ? {
52
+ oid,
53
+ oid256: name
54
+ } : null;
55
+ };
56
+ /** What a commit is folded against: its tree, read off its body, and the
57
+ * manifest the caller says it was made from. */ let based = async (repo, commit, was, held)=>{
58
+ let files = await was(commit);
59
+ if (!files) return;
60
+ let read = async ()=>{
61
+ let [row] = await repo.objects.read(line`.gitobj.type=commit&?${BLOB}&.entity.eid=${commit}`);
62
+ let body = row && await repo.bytes.get(String(row[BLOB]?.sha));
63
+ let tree = body && treeOf(body);
64
+ return tree && await named(repo.objects, tree) || undefined;
65
+ };
66
+ return {
67
+ tree: held ?? read(),
68
+ files
69
+ };
70
+ };
71
+ /** The row that points a branch at a commit. */ export let moved = (app, name, commit)=>({
72
+ entity: {
73
+ eid: refEid(app, name)
74
+ },
75
+ [REF]: {
76
+ app,
77
+ name,
78
+ commit
79
+ }
80
+ });
81
+ /** Advance a ref only from the tip its writer read. */ export let advancing = (repo, name, before, after)=>({
82
+ ...moved(repo, name, after),
83
+ $was: {
84
+ ref: {
85
+ commit: token(before)
86
+ }
87
+ }
88
+ });
89
+ /** A ref held at the tip its writer read, moving nothing: the write it rides
90
+ * in is refused once another writer has moved the ref. */ export let unmoved = (repo, name, at)=>({
91
+ entity: {
92
+ eid: refEid(repo, name)
93
+ },
94
+ $was: {
95
+ ref: {
96
+ commit: token(at)
97
+ }
98
+ }
99
+ });
100
+ /** Whether a guarded ref write lost to another writer. */ export let refMoved = (error, ref)=>error instanceof Stale && error.eid == ref && error.comp == REF && error.prop == 'commit';
101
+ /**
102
+ * One manifest as a commit on a branch: every object it needs written, the
103
+ * branch pointed at it, and whatever the caller passes in `beside` written in
104
+ * that same transaction. Returns the commit's two ids.
105
+ *
106
+ * The parent is wherever the branch points now, read here rather than passed
107
+ * in by the caller, so the chain follows the order the releases actually
108
+ * happened in.
109
+ */ export let commitOnto = async (repo, l)=>{
110
+ let name = l.branch ?? MAIN;
111
+ let at = await refAt(repo.refs, l.app, name);
112
+ let { commit } = await prepareCommit(repo, l, at);
113
+ await repo.refs.apply([
114
+ ...l.beside?.(commit) ?? [],
115
+ moved(l.app, name, commit.oid)
116
+ ]);
117
+ return commit;
118
+ };
119
+ /** Build several objects with batched graph writes. Their bodies are kept
120
+ * before a batch can publish pointers to them. A blob named over `held` bytes
121
+ * is hashed from them, never read back from the store, and nothing is
122
+ * published before `kept` has landed, so the caller's puts and the batch's
123
+ * work go on at once. */ export let preparing = async (repo, build, { held, kept } = {})=>{
124
+ let { objects, bytes } = repo;
125
+ let git = index(kept ? {
126
+ read: objects.read,
127
+ apply: async (rows)=>(await kept, objects.apply(rows))
128
+ } : objects, held?.size ? inHand(bytes, held) : bytes, true);
129
+ let result = await build(git);
130
+ await git.flush();
131
+ return result;
132
+ };
133
+ // A byte store that answers `held` from memory.
134
+ let inHand = (bytes, held)=>({
135
+ ...bytes,
136
+ has: (sha)=>held.has(sha) || bytes.has(sha),
137
+ get: (sha)=>held.get(sha) ?? bytes.get(sha),
138
+ ...bytes.open && {
139
+ open: (sha)=>{
140
+ let body = held.get(sha);
141
+ return body ? Promise.resolve(openedOf(body)) : bytes.open(sha);
142
+ }
143
+ }
144
+ });
145
+ /** Build a commit with the object writer the caller is already using. A
146
+ * caller holding the published parent can supply its commit and tree IDs,
147
+ * and one still reading who made the change hands its author as a promise:
148
+ * the tree is made meanwhile, and only the commit waits for it. */ export let buildCommit = (repo, l, at)=>async (git)=>{
149
+ let held = typeof at == 'string' ? undefined : at;
150
+ let oid = typeof at == 'string' ? at : held?.commit.oid;
151
+ // The parent's other id is asked for while its tree is read and followed.
152
+ let naming = typeof at == 'string' ? named(repo.objects, at) : held?.commit;
153
+ let base = oid && l.was ? await based(repo, oid, l.was, held?.tree) : undefined;
154
+ let [parent, tree, author] = await Promise.all([
155
+ naming,
156
+ git.files(l.files, base),
157
+ l.author
158
+ ]);
159
+ if (at && !parent) throw new Error(`git: missing parent ${at}`);
160
+ let commit = await git.commit({
161
+ tree,
162
+ parents: parent ? [
163
+ parent
164
+ ] : [],
165
+ author,
166
+ committer: l.committer,
167
+ message: l.message,
168
+ headers: l.headers
169
+ });
170
+ return {
171
+ commit,
172
+ tree
173
+ };
174
+ };
175
+ /** Write immutable objects before the caller's transaction moves its refs. */ export let prepareCommit = (repo, l, at, had)=>preparing(repo, buildCommit(repo, l, at), had);
176
+ //# sourceMappingURL=refs.js.map
package/refs.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"refs.js","sources":["./refs.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,gEAAgE;AAChE,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,qEAAqE;AACrE,+EAA+E;AAC/E,4EAA4E;AAC5E,4EAA4E;AAC5E,kCAAkC;AAClC,EAAE;AACF,8EAA8E;AAC9E,8EAA8E;AAC9E,yEAAyE;AACzE,6EAA6E;AAC7E,SAAS;AACT,EAAE;AACF,2EAA2E;AAC3E,4EAA4E;AAC5E,+EAA+E;AAC/E,0EAA0E;AAC1E,yEAAyE;AAEzE,SAAqB,QAAQ,0BAA+B;AAE5D,SAAS,KAAK,kCAAuC;AACrD,SAAS,KAAK,kCAAuC;AACrD,SAAS,IAAI,2BAAgC;AAC7C,SAAS,MAAM,sBAA+B;AAC9C,SAAS,IAAI,EAAE,GAAG,EAAE,MAAM,oBAAmB;AAC7C,SAAS,IAAI,oBAAmB;AAChC,SAAoB,KA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