@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/index.ts ADDED
@@ -0,0 +1,634 @@
1
+ // The object index: Git objects written into a graph, once each.
2
+ //
3
+ // An object's entity id is its SHA-1 object id, so the same object written by
4
+ // two deploys, two apps or two runs is one row — there is no lookup, no
5
+ // uniqueness constraint and nothing to reconcile. Beside each row goes an
6
+ // @yaks/key holding the same object's SHA-256 object id, so a client that asks
7
+ // for `object-format=sha256` is answered by a single read.
8
+ //
9
+ // What is A row and what is bytes. The body is the truth about a tree or a
10
+ // commit — byte for byte, because Git's ids are digests of it — so the body
11
+ // goes to the @yaks/blob store and the row keeps only what a query has to
12
+ // follow: the type and size a packfile entry header needs, the `blob{sha}`
13
+ // the bytes are stored under, and `parent` edges (commit → commit). Trees keep
14
+ // both Git bodies, so their children need no graph rows. Author, message, entry
15
+ // order and mode are all in the body already; a property for them would be a
16
+ // second copy free to drift.
17
+ //
18
+ // A git blob is the blob you already have. The bytes an app deployed are
19
+ // already in the store under their SHA-256 address; a Git blob object is those
20
+ // same bytes with a header hashed over them, so nothing is re-encoded and the
21
+ // row simply points at what is there. Naming a manifest's file twice, or
22
+ // across versions, costs an indexed read and no read of the bytes.
23
+ //
24
+ // A release is folded against the commit before it (`Base`): a directory
25
+ // whose files all stand as they did is that commit's tree again, read and
26
+ // written nowhere, and a changed one reads its two immutable bodies. So a
27
+ // release reads and writes what it changed, not the whole manifest.
28
+ //
29
+ // This module writes objects and nothing else: it never reads a packfile,
30
+ // serves HTTP, or touches a branch. Landing a manifest on a branch is
31
+ // ./refs.ts, and the row joining a commit to whatever it was built from is the
32
+ // application's own, written there alongside the moved ref.
33
+
34
+ import { type Blobs, hasher } from '@yaks/blob'
35
+ import { link } from '@yaks/edge'
36
+ import type { Bundle, Comp, Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
37
+ import { derivedEid } from '@yaks/graph/identity'
38
+ import { keyed, valueOf } from '@yaks/key'
39
+ import { line } from '@yaks/query'
40
+ import { lanes } from '@yaks/fp'
41
+ import {
42
+ type Commit,
43
+ commitBody,
44
+ commitParts,
45
+ compatibleCommit,
46
+ treeOf,
47
+ } from './commit.js'
48
+ import { sha1 } from './sha1.js'
49
+ import type { Obj } from './pack.ts'
50
+ import { BLOB, COMPAT, GITOBJ, PARENT, TREE_ENTRY } from './comp.js'
51
+ import {
52
+ concat,
53
+ framed,
54
+ header,
55
+ hex,
56
+ type Kind,
57
+ oid,
58
+ oid256,
59
+ type Oids,
60
+ } from './oid.js'
61
+ import {
62
+ DIR,
63
+ type Dir,
64
+ FILE,
65
+ type Files,
66
+ nest,
67
+ treeBody,
68
+ treeEntries,
69
+ } from './tree.js'
70
+
71
+ /** One child of a tree, named both ways. */
72
+ export type Child = { name: string; mode: string } & Oids
73
+
74
+ /** A commit to write: the same as a {@link Commit}, but with every id given
75
+ * under both hash algorithms, since the two bodies are built from the two. */
76
+ export type Mint = Omit<Commit, 'tree' | 'parents'> & {
77
+ tree: Oids
78
+ parents?: Oids[]
79
+ }
80
+
81
+ /**
82
+ * What writing objects needs from a graph: a read and an apply, nothing else.
83
+ *
84
+ * Narrower than `Graph` on purpose. The object index is the same code whether
85
+ * the graph is in this process or behind an HTTP API — a Durable Object's
86
+ * `/query` and `/apply` endpoints satisfy both of these — and a parameter that
87
+ * demanded a whole `Graph` would have forced a remote caller to invent a
88
+ * storage layer and a vocabulary it has no use for.
89
+ */
90
+ export type Writes = Pick<Graph, 'read' | 'apply'>
91
+
92
+ /** Writing objects into one graph and one byte store. */
93
+ export type Index = {
94
+ /** Keep a received object with its exact SHA-1 body and translated links. */
95
+ receive: (object: Obj, children: Map<string, Oids>) => Promise<Oids>
96
+ /** the git blob object over bytes the store already holds */
97
+ blob: (sha: string) => Promise<Oids>
98
+ /** a tree over children already written */
99
+ tree: (children: Child[]) => Promise<Oids>
100
+ /** The entries of an existing tree, with both object IDs. */
101
+ children: (tree: Oids) => Promise<Child[]>
102
+ /** a commit over a tree and parents already written */
103
+ commit: (mint: Mint) => Promise<Oids>
104
+ /** a whole deploy manifest, bottom up: every blob, every directory, and the
105
+ * root tree it returns. Given the commit before it (`base`), only what
106
+ * moved since is read or written. */
107
+ files: (manifest: Files, base?: Base) => Promise<Oids>
108
+ }
109
+
110
+ /** The commit a manifest follows: its tree, and the manifest that tree was
111
+ * made from. The tree may still be on its way, none where it could not be
112
+ * read: the files that moved since are named while it comes. */
113
+ export type Base = { tree: Oids | Promise<Oids | undefined>; files: Files }
114
+
115
+ /** Resolve a Git commit to its root tree. */
116
+ export let commitTree = async (
117
+ g: Pick<Writes, 'read'>,
118
+ bytes: Blobs,
119
+ commit: string,
120
+ ): Promise<string> => {
121
+ let [row] = await g.read(
122
+ line`.gitobj.type=commit&.${BLOB}&.entity.eid=${commit}`,
123
+ )
124
+ let sha = (row?.[BLOB] as Comp | undefined)?.sha
125
+ let body = typeof sha == 'string' ? await bytes.get(sha) : undefined
126
+ let tree = body && treeOf(body)
127
+ if (!tree) throw new Error(`git: missing commit tree ${commit}`)
128
+ return tree
129
+ }
130
+
131
+ /** List the files below a tree, without reading any file bodies. */
132
+ export let listFiles = async (
133
+ g: Pick<Writes, 'read'>,
134
+ bytes: Blobs,
135
+ tree: string,
136
+ ): Promise<Files> => (await listTrees(g, bytes, [tree])).get(tree)!
137
+
138
+ /** Objects a caller holds in hand (a push's), with each blob's address, the
139
+ * name its bytes are kept under (`carriedOf`). */
140
+ export type Carried = {
141
+ objects: ReadonlyMap<string, Obj>
142
+ addresses: ReadonlyMap<string, string>
143
+ }
144
+
145
+ /** The files below each of several trees, without reading any file bodies.
146
+ * The trees are walked together, a level at a time, so a directory or file
147
+ * they share is read once: an app's versions share most of theirs, and twenty
148
+ * of them cost about what one does. An object `carried` holds is read from
149
+ * there and not the graph, so a pushed tree lists before it is stored. */
150
+ export let listTrees = async (
151
+ g: Pick<Writes, 'read'>,
152
+ bytes: Blobs,
153
+ trees: string[],
154
+ carried?: Carried,
155
+ ): Promise<Map<string, Files>> => {
156
+ type Entry = { name: string; oid: string; dir: boolean }
157
+ let shas = new Map<string, string>()
158
+ let entries = new Map<string, Entry[]>()
159
+ let dirs = new Set(trees)
160
+ let next = new Set(trees)
161
+ let held = (id: string) => carried?.objects.get(id)
162
+ while (next.size) {
163
+ let ids = [...next]
164
+ next = new Set()
165
+ for (let id of ids) {
166
+ let address = carried?.addresses.get(id)
167
+ if (address) shas.set(id, address)
168
+ }
169
+ let asked = ids.filter((id) => !held(id))
170
+ let chunks = []
171
+ for (let i = 0; i < asked.length; i += 100) {
172
+ chunks.push(asked.slice(i, i + 100))
173
+ }
174
+ for (
175
+ let row of (await Promise.all(
176
+ chunks.map((part) =>
177
+ g.read(line`.${GITOBJ}&.${BLOB}&.entity.eid=${part}`)
178
+ ),
179
+ )).flat()
180
+ ) {
181
+ shas.set(row.entity.eid, String((row[BLOB] as Comp).sha))
182
+ }
183
+ let missing = ids.find((id) => !shas.has(id) && held(id)?.type != 'tree')
184
+ if (missing) throw new Error(`git: missing object ${missing}`)
185
+ await lanes(6)(ids.filter((id) => dirs.has(id)), async (oid) => {
186
+ let body = held(oid)?.bytes ?? await bytes.get(shas.get(oid)!)
187
+ if (!body) throw new Error(`git: missing tree body ${oid}`)
188
+ let children = treeEntries(body).map((child) => ({
189
+ name: child.name,
190
+ oid: child.oid,
191
+ dir: child.mode == DIR,
192
+ }))
193
+ entries.set(oid, children)
194
+ for (let child of children) {
195
+ if (child.dir) dirs.add(child.oid)
196
+ if (!shas.has(child.oid)) next.add(child.oid)
197
+ }
198
+ })
199
+ }
200
+ let under = (tree: string, path: string): [string, string][] =>
201
+ entries.get(tree)!.flatMap((e) =>
202
+ e.dir
203
+ ? under(e.oid, path + e.name + '/')
204
+ : [[path + e.name, shas.get(e.oid)!] as [string, string]]
205
+ )
206
+ return new Map(trees.map((t) => [t, Object.fromEntries(under(t, ''))]))
207
+ }
208
+
209
+ /**
210
+ * Each object's SHA-256 id by its SHA-1 id, for those of `oids` the graph
211
+ * holds: the compat keys off them, a hundred at a time. Asked by the key's
212
+ * own index on `key.of`, so it reads one row per object named.
213
+ */
214
+ export let names = async (
215
+ g: Pick<Writes, 'read'>,
216
+ oids: string[],
217
+ ): Promise<Map<string, string>> => {
218
+ let out = new Map<string, string>()
219
+ let unique = [...new Set(oids)]
220
+ for (let i = 0; i < unique.length; i += 100) {
221
+ let part = unique.slice(i, i + 100)
222
+ for (let b of await g.read(line`.key.of=${part}&?${COMPAT}`)) {
223
+ let name = b[COMPAT] && valueOf(b)
224
+ if (name) out.set(String((b.key as { of: string }).of), name)
225
+ }
226
+ }
227
+ return out
228
+ }
229
+
230
+ // Whether two directories hold the same files under the same names, all the
231
+ // way down: such a directory is the tree it was.
232
+ let same = (a: Dir, b: Dir): boolean =>
233
+ a.files.size == b.files.size && a.dirs.size == b.dirs.size &&
234
+ [...a.files].every(([name, sha]) => b.files.get(name) == sha) &&
235
+ [...a.dirs].every(([name, d]) => {
236
+ let was = b.dirs.get(name)
237
+ return !!was && same(d, was)
238
+ })
239
+
240
+ /**
241
+ * The entity id of a retained tree link to one child, derived from the string
242
+ * `tree_entry|<tree>|<name>`.
243
+ *
244
+ * Not @yaks/edge's own derivation, for a reason a duplicate file makes
245
+ * obvious: two names in one tree may point at one blob (two empty files, say),
246
+ * and `from|relation|to` is the same string for both, so one link would
247
+ * overwrite the other. Within a tree it is the name that is unique, so the
248
+ * name is what the id is derived from.
249
+ */
250
+ export let entryEid = (tree: Eid, name: string): Eid =>
251
+ derivedEid(`${TREE_ENTRY}|${tree}|${name}`)
252
+
253
+ let sha256 = async (bytes: Uint8Array<ArrayBuffer>): Promise<string> =>
254
+ hex(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)))
255
+
256
+ let ids = async (
257
+ type: Kind,
258
+ body: Uint8Array,
259
+ body256 = body,
260
+ ): Promise<Oids> => {
261
+ let [one, two] = await Promise.all([oid(type, body), oid256(type, body256)])
262
+ return { oid: one, oid256: two }
263
+ }
264
+
265
+ /**
266
+ * An object index over a graph that carries this package's components and a
267
+ * @yaks/blob store that holds the bytes.
268
+ *
269
+ * ```ts
270
+ * // let git = index(g, store)
271
+ * // let tree = await git.files({ 'index.html': sha })
272
+ * // let head = await git.commit({ tree, author, committer, message: 'deploy 1' })
273
+ * ```
274
+ */
275
+ export let index = (
276
+ g: Writes,
277
+ store: Blobs,
278
+ buffered = false,
279
+ ): Index & { flush: () => Promise<void> } => {
280
+ // Stores a body we built, under its own address. A blob object's bytes are
281
+ // already in the store under that same address, which is why this is only
282
+ // ever called for trees and commits.
283
+ let put = async (body: Uint8Array<ArrayBuffer>): Promise<string> => {
284
+ let sha = await sha256(body)
285
+ await store.put(sha, body)
286
+ return sha
287
+ }
288
+
289
+ // The row every object gets, plus its SHA-256 object id and parent edges.
290
+ let rows = (
291
+ oids: Oids,
292
+ type: Kind,
293
+ size: number,
294
+ sha: string,
295
+ walk: Bundle[] = [],
296
+ ): Bundle[] => [
297
+ {
298
+ entity: { eid: oids.oid },
299
+ [GITOBJ]: { type, size },
300
+ [BLOB]: { sha },
301
+ },
302
+ keyed(COMPAT, oids.oid, oids.oid256),
303
+ ...walk,
304
+ ]
305
+
306
+ type Pending = {
307
+ oid: string
308
+ bytes: number
309
+ check: boolean
310
+ save: () => Bundle[] | Promise<Bundle[]>
311
+ }
312
+ let pending = new Map<string, Pending>()
313
+ let known = new Set<string>()
314
+ let held = 0
315
+ // Find the objects already stored with one graph read. Only new objects
316
+ // need uploads, and their bodies must land before the graph names them. A
317
+ // release's batch (its app's tree and commit, its space's two trees and
318
+ // commit) is a put or two each, all sent at once: a Worker holds those past
319
+ // its six open connections until one closes, so more lanes cost nothing,
320
+ // where three made a second round of puts behind the first.
321
+ let publish = async () => {
322
+ let batch = [...pending.values()]
323
+ let checks = batch.filter((p) => p.check).map((p) => p.oid)
324
+ let found = checks.length
325
+ ? await g.read(line`.${GITOBJ}&.entity.eid=${checks}`)
326
+ : []
327
+ let exists = new Set(found.map((b) => b.entity.eid))
328
+ let fresh = batch.filter((p) => !exists.has(p.oid))
329
+ let saved = new Map<string, Bundle[]>()
330
+ await lanes(6)(fresh, async (p) => {
331
+ saved.set(p.oid, await p.save())
332
+ })
333
+ let written = fresh.flatMap((p) => saved.get(p.oid)!)
334
+ if (written.length) await g.apply(written)
335
+ for (let p of batch) {
336
+ pending.delete(p.oid)
337
+ known.add(p.oid)
338
+ held -= p.bytes
339
+ }
340
+ }
341
+ let flushing: Promise<void> | undefined
342
+ let flush = (): Promise<void> =>
343
+ flushing ??= (async () => {
344
+ while (pending.size) await publish()
345
+ })().finally(() => flushing = undefined)
346
+ let queue = (p: Pending): void | Promise<void> => {
347
+ if (!known.has(p.oid) && !pending.has(p.oid)) {
348
+ pending.set(p.oid, p)
349
+ held += p.bytes
350
+ }
351
+ if (pending.size >= 100 || held >= 8 * 1024 ** 2) return flush()
352
+ }
353
+
354
+ let write = async (
355
+ oids: Oids,
356
+ type: Kind,
357
+ body: Uint8Array<ArrayBuffer>,
358
+ walk: Bundle[] = [],
359
+ body256?: Uint8Array<ArrayBuffer>,
360
+ ): Promise<Oids> => {
361
+ let save = async () => {
362
+ let [sha] = await Promise.all([
363
+ put(body),
364
+ body256 ? put(framed(type, body256)) : undefined,
365
+ ])
366
+ return rows(oids, type, body.length, sha, walk)
367
+ }
368
+ if (buffered) {
369
+ await queue({
370
+ oid: oids.oid,
371
+ bytes: body.length + (body256?.length ?? 0),
372
+ check: true,
373
+ save,
374
+ })
375
+ return oids
376
+ }
377
+ // The object and its links are one atomic graph write. Its digest names
378
+ // immutable bytes, so finding it also means its keys and links stand.
379
+ if ((await g.read(line`.${GITOBJ}&.entity.eid=${oids.oid}`)).length) {
380
+ return oids
381
+ }
382
+ await g.apply(await save())
383
+ return oids
384
+ }
385
+
386
+ // A manifest's files are independent. Read their existing names in bounded
387
+ // batches and write new names together, so a large deploy does not make two
388
+ // serial graph round trips for every file it already committed before.
389
+ let blobs = async (shas: string[]): Promise<Map<string, Oids>> => {
390
+ let out = new Map<string, Oids>()
391
+ let unique = [...new Set(shas)]
392
+ for (let i = 0; i < unique.length; i += 100) {
393
+ let part = unique.slice(i, i + 100)
394
+ let found = await g.read(line`.gitobj.type=blob&.blob.sha=${part}`)
395
+ let byId = await names(g, found.map((b) => b.entity.eid))
396
+ for (let b of found) {
397
+ let sha = String((b[BLOB] as { sha: string }).sha)
398
+ let oid256 = byId.get(b.entity.eid)
399
+ if (oid256) out.set(sha, { oid: b.entity.eid, oid256 })
400
+ }
401
+ let fresh = []
402
+ let unseen = part.filter((sha) => !out.has(sha))
403
+ for (let i = 0; i < unseen.length; i += 6) {
404
+ fresh.push(
405
+ ...await Promise.all(
406
+ unseen.slice(i, i + 6).map(async (sha) => ({
407
+ sha,
408
+ ...await nameBlob(store, sha),
409
+ })),
410
+ ),
411
+ )
412
+ }
413
+ if (fresh.length) {
414
+ if (buffered) {
415
+ for (let { sha, size, oids } of fresh) {
416
+ await queue({
417
+ oid: oids.oid,
418
+ bytes: 0,
419
+ check: false,
420
+ save: () => rows(oids, 'blob', size, sha),
421
+ })
422
+ }
423
+ } else {
424
+ await g.apply(
425
+ fresh.flatMap(({ sha, size, oids }) =>
426
+ rows(oids, 'blob', size, sha)
427
+ ),
428
+ )
429
+ }
430
+ for (let { sha, oids } of fresh) out.set(sha, oids)
431
+ }
432
+ }
433
+ return out
434
+ }
435
+
436
+ // The Git blob object over these bytes. A manifest that repeats a file, or
437
+ // a second version of the same app, reads a row instead of the bytes.
438
+ let blob = async (sha: string): Promise<Oids> =>
439
+ (await blobs([sha])).get(sha)!
440
+
441
+ let tree = async (children: Child[]): Promise<Oids> => {
442
+ let body = treeBody(children)
443
+ let body256 = treeBody(children.map((c) => ({ ...c, oid: c.oid256 })))
444
+ let oids = await ids('tree', body, body256)
445
+ return write(oids, 'tree', body, [], body256)
446
+ }
447
+
448
+ let commit = async (mint: Mint): Promise<Oids> => {
449
+ let parents = mint.parents ?? []
450
+ let body = commitBody({
451
+ ...mint,
452
+ tree: mint.tree.oid,
453
+ parents: parents.map((p) => p.oid),
454
+ })
455
+ let body256 = commitBody({
456
+ ...mint,
457
+ tree: mint.tree.oid256,
458
+ parents: parents.map((p) => p.oid256),
459
+ })
460
+ let oids = await ids('commit', body, body256)
461
+ return write(
462
+ oids,
463
+ 'commit',
464
+ body,
465
+ parents.map((p, i) => link(oids.oid, PARENT, p.oid, i)),
466
+ )
467
+ }
468
+
469
+ let receive: Index['receive'] = async ({ type, bytes }, children) => {
470
+ let body = concat([bytes])
471
+ let named = (id: string) => {
472
+ let child = children.get(id)
473
+ if (!child) throw new Error(`git: missing compatibility ID for ${id}`)
474
+ return child.oid256
475
+ }
476
+ if (type == 'tree') {
477
+ let translated = treeBody(
478
+ treeEntries(body).map((e) => ({
479
+ ...e,
480
+ oid: named(e.oid),
481
+ })),
482
+ )
483
+ return write(
484
+ await ids(type, body, translated),
485
+ type,
486
+ body,
487
+ [],
488
+ translated,
489
+ )
490
+ }
491
+ if (type == 'commit') {
492
+ let { parents } = commitParts(body)
493
+ let translated = compatibleCommit(body, named)
494
+ let oids = await ids(type, body, translated)
495
+ return write(
496
+ oids,
497
+ type,
498
+ body,
499
+ parents.map((p, i) => link(oids.oid, PARENT, p, i)),
500
+ )
501
+ }
502
+ return write(await ids(type, body), type, body)
503
+ }
504
+
505
+ // Both native Git tree bodies carry the same names in the same order, with
506
+ // child ids in their own format. Read one object row, then bytes, regardless
507
+ // of how many unchanged entries the directory contains.
508
+ let readChildren = async (tree: Oids): Promise<Child[]> => {
509
+ if (pending.has(tree.oid)) await flush()
510
+ // The framed SHA-256 tree's byte address is its Git object id, so no
511
+ // extra graph pointer is needed to find the other body's children, and
512
+ // it is asked for beside the row that leads to the SHA-1 body.
513
+ let framed = Promise.resolve(store.get(tree.oid256))
514
+ framed.catch(() => {})
515
+ let [row] = await g.read(line`.${GITOBJ}&?${BLOB}&.entity.eid=${tree.oid}`)
516
+ let sha = String((row?.[BLOB] as Comp)?.sha ?? '')
517
+ let body = sha && await store.get(sha)
518
+ if (!body) throw new Error(`git: no bytes stored under ${sha}`)
519
+ let one = treeEntries(body)
520
+ let known: Map<string, string>
521
+ let bytes = await framed
522
+ if (bytes) {
523
+ let start = bytes.indexOf(0) + 1
524
+ let body256 = bytes.subarray(start)
525
+ let prefix = header('tree', body256.length)
526
+ if (start != prefix.length || prefix.some((b, i) => bytes[i] != b)) {
527
+ throw new Error(`git: malformed tree frame for ${tree.oid256}`)
528
+ }
529
+ let two = treeEntries(body256, 32)
530
+ if (
531
+ one.length != two.length ||
532
+ one.some((e, i) => e.name != two[i].name || e.mode != two[i].mode)
533
+ ) throw new Error(`git: tree formats disagree for ${tree.oid}`)
534
+ known = new Map(one.map((e, i) => [e.oid, two[i].oid]))
535
+ } else {
536
+ // Historical objects have only a SHA-1 body. Their compat keys supply
537
+ // the other ids; the objects themselves are never rewritten.
538
+ known = await names(g, one.map((e) => e.oid))
539
+ }
540
+ return one.map((e) => {
541
+ let oid256 = known.get(e.oid)
542
+ if (!oid256) throw new Error(`git: missing compatibility ID for ${e.oid}`)
543
+ return { ...e, oid256 }
544
+ })
545
+ }
546
+
547
+ // Bottom up: a directory has no id until every child under it has one.
548
+ // Folded against what it was (`was`), a directory that stands is its old
549
+ // tree, and a changed one takes each child that stands from its old
550
+ // entries. The files that moved are named by their bytes (`fresh`).
551
+ let fold = async (
552
+ at: Dir,
553
+ fresh: Map<string, Oids>,
554
+ was?: { dir: Dir; oids: Oids },
555
+ read?: Child[],
556
+ ): Promise<Oids> => {
557
+ if (was && same(at, was.dir)) return was.oids
558
+ let held = new Map(
559
+ was ? (read ?? await readChildren(was.oids)).map((e) => [e.name, e]) : [],
560
+ )
561
+ let stood = (name: string, sha?: string) =>
562
+ held.has(name) &&
563
+ (sha == null ? was?.dir.dirs.has(name) : was?.dir.files.get(name) == sha)
564
+ let children: Child[] = []
565
+ for (let [name, sha] of at.files) {
566
+ let oids = (stood(name, sha) && held.get(name)) || fresh.get(sha) ||
567
+ await blob(sha)
568
+ children.push({ name, mode: FILE, ...oids })
569
+ }
570
+ for (let [name, dir] of at.dirs) {
571
+ let oids = stood(name) && held.get(name)
572
+ let before = oids ? { dir: was!.dir.dirs.get(name)!, oids } : undefined
573
+ children.push({ name, mode: DIR, ...await fold(dir, fresh, before) })
574
+ }
575
+ return tree(children)
576
+ }
577
+
578
+ return {
579
+ flush,
580
+ receive,
581
+ blob,
582
+ tree,
583
+ children: readChildren,
584
+ commit,
585
+ files: async (m, base) => {
586
+ let at = nest(m)
587
+ let dir = base && nest(base.files)
588
+ // The base's root entries are read while the moved files are named:
589
+ // neither waits on the other.
590
+ let tree = Promise.resolve(base?.tree)
591
+ let root = tree.then((oids) =>
592
+ oids && dir && !same(at, dir) ? readChildren(oids) : undefined
593
+ )
594
+ root.catch(() => {})
595
+ let [fresh, oids] = await Promise.all([
596
+ blobs(
597
+ Object.entries(m).filter(([path, sha]) => base?.files[path] != sha)
598
+ .map(([, sha]) => sha),
599
+ ),
600
+ tree,
601
+ ])
602
+ // A base whose tree could not be read is followed by nothing.
603
+ if (base && !oids) fresh = await blobs(Object.values(m))
604
+ return fold(at, fresh, oids && { dir: dir!, oids }, await root)
605
+ },
606
+ }
607
+ }
608
+
609
+ let nameBlob = async (store: Blobs, sha: string) => {
610
+ if (store.open) {
611
+ let opened = await store.open(sha)
612
+ if (!opened) throw new Error(`git: no bytes stored under ${sha}`)
613
+ let { size } = opened
614
+ let one = sha1()
615
+ let two = hasher()
616
+ let prefix = header('blob', size)
617
+ one.update(prefix)
618
+ two.add(prefix)
619
+ let measured = 0
620
+ for await (let part of await opened.read()) {
621
+ measured += part.byteLength
622
+ one.update(part)
623
+ two.add(part)
624
+ }
625
+ if (measured != size) throw new Error(`git: truncated blob ${sha}`)
626
+ return {
627
+ size,
628
+ oids: { oid: hex(one.digest()), oid256: two.end(prefix.length + size) },
629
+ }
630
+ }
631
+ let bytes = await store.get(sha)
632
+ if (!bytes) throw new Error(`git: no bytes stored under ${sha}`)
633
+ return { size: bytes.length, oids: await ids('blob', bytes) }
634
+ }