@ref0/git 0.20.0 → 0.25.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.
Files changed (378) hide show
  1. package/dist/access/private-refs.mjs +1 -1
  2. package/dist/auth/access-jwt.mjs +3 -3
  3. package/dist/auth/auth-namespace.d.mts +3 -3
  4. package/dist/auth/auth-namespace.mjs +3 -2
  5. package/dist/auth/auth.d.mts +3 -3
  6. package/dist/auth/auth.mjs +9 -8
  7. package/dist/auth/authorize.mjs +1 -1
  8. package/dist/auth/fences.d.mts +1 -1
  9. package/dist/auth/host-function.mjs +1 -1
  10. package/dist/auth/host-services.mjs +4 -6
  11. package/dist/auth/identify.d.mts +1 -1
  12. package/dist/auth/identify.mjs +6 -0
  13. package/dist/auth/token-cleanup.mjs +2 -2
  14. package/dist/auth/token-rows.mjs +6 -1
  15. package/dist/auth/token-text.mjs +1 -1
  16. package/dist/auth/tokens-base.d.mts +1 -1
  17. package/dist/auth/tokens.d.mts +1 -1
  18. package/dist/auth/tokens.mjs +1 -1
  19. package/dist/client/client.d.mts +15 -7
  20. package/dist/client/client.mjs +21 -12
  21. package/dist/client/git-http.mjs +1 -1
  22. package/dist/client/local.mjs +60 -24
  23. package/dist/client/negotiate.mjs +3 -3
  24. package/dist/client/push-upload.mjs +26 -10
  25. package/dist/client/remote.mjs +4 -3
  26. package/dist/client/run-remote-helper.d.mts +2 -2
  27. package/dist/client/run-remote-helper.mjs +6 -6
  28. package/dist/client/slice-push.d.mts +1 -1
  29. package/dist/client/transport.mjs +3 -3
  30. package/dist/contracts/blobs.d.mts +3 -3
  31. package/dist/contracts/blobs.mjs +1 -1
  32. package/dist/contracts/calls-spent.mjs +5 -33
  33. package/dist/contracts/client.d.mts +15 -14
  34. package/dist/contracts/commits.d.mts +4 -4
  35. package/dist/contracts/commits.mjs +1 -1
  36. package/dist/contracts/engine.d.mts +2 -2
  37. package/dist/contracts/events.d.mts +1 -1
  38. package/dist/contracts/events.mjs +1 -1
  39. package/dist/contracts/files.d.mts +4 -4
  40. package/dist/contracts/files.mjs +1 -1
  41. package/dist/contracts/forks.d.mts +4 -4
  42. package/dist/contracts/forks.mjs +1 -1
  43. package/dist/contracts/git-hooks.d.mts +1 -1
  44. package/dist/contracts/git.d.mts +9 -5
  45. package/dist/contracts/grants.d.mts +1 -1
  46. package/dist/contracts/merges.d.mts +1 -1
  47. package/dist/contracts/object-values.d.mts +1 -0
  48. package/dist/contracts/object-values.mjs +16 -1
  49. package/dist/contracts/objects.d.mts +20 -17
  50. package/dist/contracts/opaque.mjs +1 -1
  51. package/dist/contracts/operations.mjs +1 -1
  52. package/dist/contracts/queue.d.mts +208 -44
  53. package/dist/contracts/queue.mjs +5 -5
  54. package/dist/contracts/refs.d.mts +5 -5
  55. package/dist/contracts/refs.mjs +1 -1
  56. package/dist/contracts/remote.d.mts +3 -6
  57. package/dist/contracts/repos.d.mts +3 -3
  58. package/dist/contracts/repos.mjs +1 -1
  59. package/dist/contracts/result.d.mts +10 -7
  60. package/dist/contracts/result.mjs +8 -3
  61. package/dist/contracts/rules.d.mts +2 -2
  62. package/dist/contracts/server.d.mts +8 -10
  63. package/dist/contracts/services.d.mts +6 -9
  64. package/dist/contracts/services.mjs +1 -2
  65. package/dist/contracts/signin.d.mts +1 -1
  66. package/dist/contracts/store.d.mts +2 -2
  67. package/dist/contracts/sync.d.mts +63 -6
  68. package/dist/contracts/sync.mjs +3 -2
  69. package/dist/contracts/tags.d.mts +3 -3
  70. package/dist/contracts/tags.mjs +1 -1
  71. package/dist/contracts/tokens.d.mts +2 -2
  72. package/dist/contracts/tokens.mjs +1 -1
  73. package/dist/contracts/topics.d.mts +9 -9
  74. package/dist/contracts/trees.d.mts +4 -4
  75. package/dist/contracts/trees.mjs +1 -1
  76. package/dist/contracts/work.d.mts +4 -4
  77. package/dist/contracts/work.mjs +2 -2
  78. package/dist/core/access.d.mts +1 -1
  79. package/dist/core/ancestry.mjs +30 -34
  80. package/dist/core/{promise.mjs → call-groups.mjs} +7 -30
  81. package/dist/core/call-services.mjs +1 -1
  82. package/dist/core/events/deliver.d.mts +2 -2
  83. package/dist/core/events/deliver.mjs +3 -3
  84. package/dist/core/events/retired.mjs +1 -1
  85. package/dist/core/forks.mjs +5 -5
  86. package/dist/core/hooks/groups.mjs +2 -2
  87. package/dist/core/imports.mjs +101 -21
  88. package/dist/core/index-job.mjs +14 -9
  89. package/dist/core/index-lost.d.mts +1 -1
  90. package/dist/core/loose-tally.mjs +38 -15
  91. package/dist/core/merge-parts.d.mts +17 -4
  92. package/dist/core/merge-parts.mjs +7 -2
  93. package/dist/core/mirror-rows.mjs +31 -1
  94. package/dist/core/objects/blobs.mjs +8 -10
  95. package/dist/core/objects/files.mjs +20 -17
  96. package/dist/core/objects/objects-layer.mjs +1 -1
  97. package/dist/core/objects/peel.mjs +1 -7
  98. package/dist/core/objects/reading.mjs +19 -18
  99. package/dist/core/objects/tree-edits.mjs +1 -1
  100. package/dist/core/objects/trees.mjs +257 -58
  101. package/dist/core/objects/writing.mjs +3 -9
  102. package/dist/core/own-writes.mjs +1 -1
  103. package/dist/core/parts.d.mts +8 -1
  104. package/dist/core/parts.mjs +8 -4
  105. package/dist/core/purge.mjs +31 -18
  106. package/dist/core/push.d.mts +2 -2
  107. package/dist/core/push.mjs +125 -94
  108. package/dist/core/receipts.d.mts +2 -2
  109. package/dist/core/receipts.mjs +9 -2
  110. package/dist/core/ref-index-job.mjs +4 -4
  111. package/dist/core/ref-view.mjs +74 -31
  112. package/dist/core/refs.mjs +3 -3
  113. package/dist/core/repack.mjs +25 -30
  114. package/dist/core/repo-info.mjs +1 -1
  115. package/dist/core/repos.mjs +1 -1
  116. package/dist/core/rules/changes.mjs +18 -40
  117. package/dist/core/rules/check.mjs +6 -5
  118. package/dist/core/rules/commit-changes.mjs +3 -15
  119. package/dist/core/rules/context.d.mts +3 -3
  120. package/dist/core/rules/context.mjs +18 -14
  121. package/dist/core/rules/fetch.mjs +1 -1
  122. package/dist/core/rules/protect.mjs +30 -17
  123. package/dist/core/saved-caller-views.d.mts +1 -1
  124. package/dist/core/saved-caller-views.mjs +3 -3
  125. package/dist/core/saved-callers.d.mts +1 -1
  126. package/dist/core/saved-callers.mjs +1 -1
  127. package/dist/core/seam.d.mts +1 -2
  128. package/dist/core/view.d.mts +6 -3
  129. package/dist/core/view.mjs +11 -10
  130. package/dist/core/work.mjs +2 -2
  131. package/dist/engine/allotted-xdiff.mjs +3 -16
  132. package/dist/engine/combined.d.mts +3 -0
  133. package/dist/engine/combined.mjs +200 -185
  134. package/dist/engine/content.d.mts +2 -2
  135. package/dist/engine/content.mjs +1 -1
  136. package/dist/engine/merge.mjs +7 -9
  137. package/dist/engine/reads.d.mts +2 -2
  138. package/dist/engine/reads.mjs +22 -14
  139. package/dist/engine/xdiff.d.mts +1 -1
  140. package/dist/engine/xdiff.mjs +1 -1
  141. package/dist/event-streams/event-streams.d.mts +1 -1
  142. package/dist/event-streams/event-streams.mjs +1 -1
  143. package/dist/event-streams/stream.d.mts +2 -2
  144. package/dist/event-streams/stream.mjs +3 -3
  145. package/dist/extend.d.mts +2 -6
  146. package/dist/extend.mjs +1 -5
  147. package/dist/http/core-parts.mjs +83 -26
  148. package/dist/http/handler.mjs +54 -9
  149. package/dist/http/parts.d.mts +1 -0
  150. package/dist/http/push-upload-job.mjs +138 -24
  151. package/dist/http/push-uploads.mjs +2 -2
  152. package/dist/http/receive-pack.mjs +14 -53
  153. package/dist/http/request-snapshot.mjs +258 -0
  154. package/dist/http/upload-pack.mjs +23 -18
  155. package/dist/index.d.mts +29 -21
  156. package/dist/index.mjs +11 -2
  157. package/dist/lfs/base.d.mts +1 -1
  158. package/dist/lfs/copy.d.mts +49 -1
  159. package/dist/lfs/copy.mjs +135 -22
  160. package/dist/lfs/layer.d.mts +4 -3
  161. package/dist/lfs/layer.mjs +4 -5
  162. package/dist/lfs/locks.mjs +2 -2
  163. package/dist/lfs/objects.d.mts +1 -1
  164. package/dist/lfs/objects.mjs +3 -3
  165. package/dist/lfs/pointers.mjs +1 -1
  166. package/dist/lfs/rows.d.mts +1 -1
  167. package/dist/lfs/rows.mjs +11 -4
  168. package/dist/lfs/upkeep.mjs +40 -9
  169. package/dist/lfs/uploaded.mjs +1 -1
  170. package/dist/lfs/wire.mjs +1 -1
  171. package/dist/merges/merges.mjs +17 -2
  172. package/dist/protocol/bytes/buffers.d.mts +1 -1
  173. package/dist/protocol/bytes/buffers.mjs +1 -1
  174. package/dist/protocol/bytes/deflate.d.mts +1 -1
  175. package/dist/protocol/bytes/deflate.mjs +1 -1
  176. package/dist/protocol/bytes/inflate.d.mts +1 -1
  177. package/dist/protocol/bytes/inflate.mjs +1 -1
  178. package/dist/protocol/bytes/sha1.d.mts +1 -1
  179. package/dist/protocol/bytes/sha1.mjs +1 -1
  180. package/dist/protocol/diff/read.d.mts +2 -1
  181. package/dist/protocol/diff/read.mjs +102 -8
  182. package/dist/protocol/packs/graph.mjs +1 -1
  183. package/dist/protocol/packs/idx.d.mts +1 -1
  184. package/dist/protocol/packs/idx.mjs +1 -1
  185. package/dist/protocol/packs/parts.mjs +1 -1
  186. package/dist/protocol/packs/reader.d.mts +1 -1
  187. package/dist/protocol/packs/reader.mjs +1 -1
  188. package/dist/protocol/packs/write-error.d.mts +1 -1
  189. package/dist/protocol/packs/write-error.mjs +1 -1
  190. package/dist/protocol/packs/writer.mjs +3 -3
  191. package/dist/protocol/wire/advertisement.d.mts +1 -1
  192. package/dist/protocol/wire/advertisement.mjs +3 -2
  193. package/dist/protocol/wire/fetch.d.mts +1 -1
  194. package/dist/protocol/wire/fetch.mjs +1 -1
  195. package/dist/protocol/wire/lines.d.mts +9 -1
  196. package/dist/protocol/wire/lines.mjs +28 -1
  197. package/dist/protocol/wire/push-uploads.mjs +10 -7
  198. package/dist/protocol/wire/receive-pack.d.mts +1 -1
  199. package/dist/protocol/wire/receive-pack.mjs +1 -1
  200. package/dist/protocol/wire/report-status.d.mts +1 -1
  201. package/dist/protocol/wire/report-status.mjs +1 -1
  202. package/dist/protocol/wire/v2.d.mts +1 -1
  203. package/dist/protocol/wire/v2.mjs +1 -1
  204. package/dist/queue/advance.mjs +31 -24
  205. package/dist/queue/base.d.mts +5 -3
  206. package/dist/queue/calls.mjs +5 -5
  207. package/dist/queue/commit.mjs +1 -1
  208. package/dist/queue/host.d.mts +1 -1
  209. package/dist/queue/layer.d.mts +0 -1
  210. package/dist/queue/layer.mjs +9 -5
  211. package/dist/queue/schedule.mjs +1 -1
  212. package/dist/queue/search.mjs +1 -1
  213. package/dist/queue/state.mjs +1 -1
  214. package/dist/queue/trim.mjs +2 -2
  215. package/dist/rest/client.d.mts +1 -1
  216. package/dist/rest/client.mjs +6 -6
  217. package/dist/rest/errors.mjs +1 -1
  218. package/dist/rest/handler.mjs +2 -2
  219. package/dist/rest/handlers.mjs +16 -6
  220. package/dist/rest/layer.mjs +1 -1
  221. package/dist/rest/listen.mjs +2 -2
  222. package/dist/rest/refs.mjs +1 -1
  223. package/dist/server/edge.mjs +27 -3
  224. package/dist/server/git-layer.d.mts +1 -2
  225. package/dist/server/git-layer.mjs +4 -5
  226. package/dist/server/lifecycle.mjs +1 -1
  227. package/dist/server/registry.mjs +2 -8
  228. package/dist/server/server.mjs +62 -43
  229. package/dist/signin/context.d.mts +1 -1
  230. package/dist/signin/context.mjs +1 -1
  231. package/dist/signin/forms.mjs +1 -1
  232. package/dist/signin/grants.d.mts +2 -2
  233. package/dist/signin/grants.mjs +1 -1
  234. package/dist/signin/wire.mjs +1 -1
  235. package/dist/storage/allotted.mjs +4 -9
  236. package/dist/storage/batch-upkeep.mjs +31 -12
  237. package/dist/storage/batches.d.mts +2 -3
  238. package/dist/storage/batches.mjs +52 -49
  239. package/dist/storage/budget.mjs +23 -1
  240. package/dist/storage/calls.d.mts +1 -1
  241. package/dist/storage/calls.mjs +41 -43
  242. package/dist/storage/charged-cache.mjs +180 -0
  243. package/dist/storage/chunks.d.mts +3 -3
  244. package/dist/storage/chunks.mjs +121 -8
  245. package/dist/storage/counted-bucket.mjs +32 -10
  246. package/dist/storage/fetch-row-cache.d.mts +6 -0
  247. package/dist/storage/fetch-row-cache.mjs +211 -0
  248. package/dist/storage/fetch.d.mts +1 -0
  249. package/dist/storage/fetch.mjs +54 -242
  250. package/dist/storage/held-types.d.mts +0 -1
  251. package/dist/storage/host-bucket.mjs +9 -4
  252. package/dist/storage/index-bitmaps.mjs +77 -49
  253. package/dist/storage/index-build.d.mts +2 -3
  254. package/dist/storage/index-build.mjs +248 -48
  255. package/dist/storage/index-fetch.d.mts +3 -1
  256. package/dist/storage/index-fetch.mjs +60 -21
  257. package/dist/storage/index-graph.mjs +1 -1
  258. package/dist/storage/index-layers.mjs +55 -25
  259. package/dist/storage/index-reach.mjs +15 -22
  260. package/dist/storage/index-whole.d.mts +7 -0
  261. package/dist/storage/index-whole.mjs +145 -37
  262. package/dist/storage/largest-files.mjs +1 -7
  263. package/dist/storage/layout.mjs +17 -1
  264. package/dist/storage/lfs-pointers.mjs +1 -6
  265. package/dist/storage/link-join.mjs +55 -16
  266. package/dist/storage/list-source.d.mts +7 -0
  267. package/dist/storage/list-source.mjs +288 -0
  268. package/dist/storage/loose.d.mts +8 -8
  269. package/dist/storage/loose.mjs +157 -91
  270. package/dist/storage/memory-budget.mjs +226 -22
  271. package/dist/storage/merge-cut.mjs +9 -6
  272. package/dist/storage/merge-fence.mjs +1 -1
  273. package/dist/storage/merge-row.mjs +1 -1
  274. package/dist/storage/merge.d.mts +2 -3
  275. package/dist/storage/merge.mjs +2 -2
  276. package/dist/storage/object-rows.d.mts +3 -3
  277. package/dist/storage/object-rows.mjs +179 -38
  278. package/dist/storage/pack-order.mjs +97 -44
  279. package/dist/storage/pack-ranges.mjs +44 -16
  280. package/dist/storage/pack-reads.d.mts +5 -3
  281. package/dist/storage/pack-reads.mjs +236 -72
  282. package/dist/storage/pack-receive.d.mts +1 -2
  283. package/dist/storage/pack-receive.mjs +21 -17
  284. package/dist/storage/packs.d.mts +1 -1
  285. package/dist/storage/packs.mjs +477 -116
  286. package/dist/storage/placed-reads.mjs +33 -16
  287. package/dist/storage/prune-seen.mjs +1 -1
  288. package/dist/storage/prune-walk.mjs +1 -1
  289. package/dist/storage/prune.mjs +4 -31
  290. package/dist/storage/push-allotment.mjs +26 -14
  291. package/dist/storage/push-uploads.mjs +195 -57
  292. package/dist/storage/pushed-commits.mjs +20 -1
  293. package/dist/storage/quarantine.d.mts +2 -3
  294. package/dist/storage/range-cache.mjs +175 -40
  295. package/dist/storage/raw-ids.mjs +39 -10
  296. package/dist/storage/ready.d.mts +2 -3
  297. package/dist/storage/ready.mjs +114 -38
  298. package/dist/storage/receive-bounds.mjs +31 -9
  299. package/dist/storage/receive-cache.d.mts +7 -0
  300. package/dist/storage/receive-cache.mjs +147 -0
  301. package/dist/storage/receive-files.mjs +1 -1
  302. package/dist/storage/receive-links.mjs +1 -1
  303. package/dist/storage/receive-state.d.mts +2 -2
  304. package/dist/storage/receive-state.mjs +6 -8
  305. package/dist/storage/receive-steps.d.mts +20 -0
  306. package/dist/storage/receive-steps.mjs +298 -13
  307. package/dist/storage/repack-backlog.mjs +1 -6
  308. package/dist/storage/repack-contained.mjs +2 -2
  309. package/dist/storage/repack-job.mjs +1 -1
  310. package/dist/storage/repack.d.mts +2 -3
  311. package/dist/storage/repack.mjs +54 -9
  312. package/dist/storage/request-cache.mjs +57 -0
  313. package/dist/storage/roots.mjs +1 -24
  314. package/dist/storage/rows.d.mts +2 -2
  315. package/dist/storage/rows.mjs +1 -1
  316. package/dist/storage/runs.d.mts +2 -2
  317. package/dist/storage/runs.mjs +1 -1
  318. package/dist/storage/send-list.mjs +62 -25
  319. package/dist/storage/stream-whole.mjs +84 -63
  320. package/dist/storage/swap-walk.mjs +1 -1
  321. package/dist/storage/unpack.mjs +878 -450
  322. package/dist/storage/visible.mjs +110 -32
  323. package/dist/storage/walk.mjs +1 -0
  324. package/dist/storage/wants.mjs +22 -58
  325. package/dist/store/call-count.d.mts +2 -2
  326. package/dist/store/call-count.mjs +24 -11
  327. package/dist/store/catalogue.d.mts +1 -1
  328. package/dist/store/catalogue.mjs +19 -7
  329. package/dist/store/crossing.mjs +1 -7
  330. package/dist/store/cursor-seal.d.mts +1 -1
  331. package/dist/store/cursor-seal.mjs +1 -1
  332. package/dist/store/door.mjs +9 -4
  333. package/dist/store/errors.d.mts +2 -2
  334. package/dist/store/errors.mjs +107 -19
  335. package/dist/store/git-store.mjs +7 -2
  336. package/dist/store/job-try.mjs +90 -9
  337. package/dist/store/list-job.mjs +10 -34
  338. package/dist/store/outbox.d.mts +2 -2
  339. package/dist/store/outbox.mjs +2 -2
  340. package/dist/store/queue-jobs.mjs +6 -12
  341. package/dist/store/records.d.mts +2 -2
  342. package/dist/store/records.mjs +2 -2
  343. package/dist/store/ref-rows.d.mts +2 -2
  344. package/dist/store/ref-rows.mjs +2 -2
  345. package/dist/store/repo-record.d.mts +2 -2
  346. package/dist/store/repo-record.mjs +3 -3
  347. package/dist/store/request-snapshot.mjs +5 -0
  348. package/dist/store/reservations.mjs +2 -2
  349. package/dist/store/topic-jobs.mjs +5 -11
  350. package/dist/sync/bound.d.mts +3 -3
  351. package/dist/sync/bound.mjs +10 -7
  352. package/dist/sync/github.mjs +65 -67
  353. package/dist/sync/http.mjs +1 -1
  354. package/dist/sync/import.mjs +201 -66
  355. package/dist/sync/layer.d.mts +1 -1
  356. package/dist/sync/layer.mjs +6 -6
  357. package/dist/sync/lfs-batch.mjs +1 -1
  358. package/dist/sync/lfs-copy.mjs +175 -15
  359. package/dist/sync/mirror.mjs +5 -10
  360. package/dist/sync/said.mjs +1 -1
  361. package/dist/sync/step.mjs +268 -86
  362. package/dist/sync/tries.mjs +25 -6
  363. package/dist/sync.d.mts +2 -2
  364. package/dist/sync.mjs +2 -2
  365. package/dist/topics/advance.mjs +3 -3
  366. package/dist/topics/calls.mjs +1 -1
  367. package/dist/topics/layer.d.mts +15 -14
  368. package/dist/topics/members.mjs +1 -1
  369. package/dist/topics/topic.mjs +1 -1
  370. package/package.json +3 -13
  371. package/dist/auth/helpers.mjs +0 -17
  372. package/dist/auth.d.mts +0 -5
  373. package/dist/auth.mjs +0 -5
  374. package/dist/core/rules/commit-changes.d.mts +0 -12
  375. package/dist/effect.d.mts +0 -9
  376. package/dist/effect.mjs +0 -7
  377. package/dist/server/joined.d.mts +0 -70
  378. package/dist/server/joined.mjs +0 -41
@@ -1,57 +1,75 @@
1
- import { gitError } from "../contracts/result.mjs";
1
+ import { fail, gitError } from "../contracts/result.mjs";
2
2
  import { BufferError, BufferMeter } from "../protocol/bytes/buffers.mjs";
3
3
  import { hexOf } from "../protocol/bytes/hex.mjs";
4
4
  import { joinedBytes } from "../protocol/bytes/joined.mjs";
5
5
  import { nativeSha1Hasher } from "../protocol/bytes/sha1-hasher.mjs";
6
6
  import { fsckObject } from "../protocol/objects/fsck.mjs";
7
7
  import { rawLinks } from "../protocol/objects/links-raw.mjs";
8
- import { objectId } from "../protocol/objects/object.mjs";
8
+ import { emptyTree, objectId } from "../protocol/objects/object.mjs";
9
9
  import { readTagTarget } from "../protocol/objects/tag.mjs";
10
10
  import { DeltaRun, appliedDelta, deltaResultSize } from "../protocol/packs/delta.mjs";
11
11
  import { PackError, PackTransportError, boundedSource, readPack } from "../protocol/packs/reader.mjs";
12
+ import { deltaPartBytes, fastPath, stagedBytes, stagedDeltaKey, stagedKey } from "./batches.mjs";
12
13
  import { ChunkWriter, chunkRawBytes, chunkedMoved, chunkedOf, fitsRow, wholeObjectId } from "./chunks.mjs";
13
14
  import { checkedFilesRefused, checkedOverflow, fsckRefusal, receiveChecked } from "./fsck.mjs";
15
+ import { LargestFiles } from "./largest-files.mjs";
16
+ import { ReceivedPointers } from "./lfs-pointers.mjs";
14
17
  import { boundaryNotInPack, linkReader, objectMissing, segmentCut, segmentTooLarge, shallowLinks, shallowRoot, tagTargetMissing, wrongType } from "./links.mjs";
15
- import { receiveLinksAskedBatch } from "./receive-bounds.mjs";
16
- import { objectRow, rowValueBytes } from "./object-rows.mjs";
18
+ import { objectOfRow, objectRow, rowValueBytes } from "./object-rows.mjs";
19
+ import "./receive-bounds.mjs";
20
+ import { rootsOf } from "./roots.mjs";
21
+ import { limits } from "@ref0/infra";
17
22
  import * as Effect from "effect/Effect";
23
+ import * as Predicate from "effect/Predicate";
18
24
  import * as Result from "effect/Result";
19
- import { limits } from "@ref0/infra";
25
+ import * as Base64 from "effect/encoding/Base64";
20
26
  // src/storage/unpack.ts
21
- /** One commit's size as JSON, as every store holds it: a push's rows and its refs share it. */
22
- const commitBytes = 8388608;
27
+ /** Internal inflated-byte cap per receive (pack entries, thin bases read once, and delta results). */
28
+ const maxInflatedBytes = 268435456;
29
+ /** The bytes of resolved base objects kept in memory by the receive's LRU. */
30
+ const baseLruBytes = 16777216;
31
+ /** Pending delta instructions held in memory before spilling to `stagedDeltas`. */
32
+ const pendingHeldMost = 25165824;
33
+ /** Maximum known serialized bytes requested in one Phase B round read call. */
34
+ const roundReadBytes = 7340032;
35
+ /** Spilled resolution rounds allowed before refusing `delta-chain-too-deep` (Git's `pack.depth` cap). */
36
+ const deltaRoundsMost = 4095;
37
+ /** Estimated JSON bytes for a base64-encoded row holding `raw` raw bytes. */
38
+ const encodedBytes = (raw) => Math.ceil(raw * 4 / 3) + 64;
23
39
  /** Where the large object at `offset` puts its chunks, which a receive's batch holds once. */
24
40
  const partAt = (offset) => `p${offset}`;
25
41
  /** What the reader may hold besides the entries it hands on: its inflater and buffers. */
26
42
  const readerBytes = 1048576;
27
- const tooLarge = (bytes, most) => gitError("RESOURCE_EXHAUSTED", `push takes ${bytes.toLocaleString("en-US")} bytes as rows; this server takes ${most.toLocaleString("en-US")}`, {
43
+ const fmtBytes = (bytes) => bytes.toLocaleString("en-US");
44
+ const packBucketHint = "Use Objects.layer() storage, which keeps a push's objects in the bucket";
45
+ const largeBucketHint = "Use Objects.layer() storage, which keeps a large object in the bucket";
46
+ const tooLarge = (bytes, most) => gitError("RESOURCE_EXHAUSTED", `push takes ${fmtBytes(bytes)} bytes; this server takes ${fmtBytes(most)}`, {
28
47
  hint: "Push fewer objects at a time",
29
- hostHint: "Use Objects.layer() storage, which keeps a push's objects in the bucket",
48
+ hostHint: packBucketHint,
30
49
  context: { reason: "too-large" }
31
50
  });
32
- /** A push whose objects, resolved whole, pass a commit before their rows are made: as `tooLarge`. */
33
- const resolvedTooLarge = (bytes, most) => gitError("RESOURCE_EXHAUSTED", `push's objects take more than ${bytes.toLocaleString("en-US")} bytes whole; this server takes ${most.toLocaleString("en-US")}`, {
34
- hint: "Push fewer objects at a time",
35
- hostHint: "Use Objects.layer() storage, which keeps a push's objects in the bucket",
36
- context: { reason: "too-large" }
51
+ /** A push whose spilled pending deltas need more than `most` resolution rounds. */
52
+ const deltaChainTooDeep = (most) => gitError("RESOURCE_EXHAUSTED", `push's delta chain needs more than ${fmtBytes(most)} resolution rounds`, {
53
+ hint: "Repack with a lower pack.depth and push again",
54
+ hostHint: packBucketHint,
55
+ context: {
56
+ reason: "delta-chain-too-deep",
57
+ most
58
+ }
37
59
  });
38
60
  /** An object whose row passes one row's 1 MiB: `RESOURCE_EXHAUSTED`, reason `object-too-large`. */
39
- const rowTooLarge = (oid, bytes) => gitError("RESOURCE_EXHAUSTED", `object ${oid} takes ${bytes.toLocaleString("en-US")} bytes as a row; one row holds ${limits.valueBytes.toLocaleString("en-US")}`, {
40
- hostHint: "Use Objects.layer() storage, which keeps a large object in the bucket",
61
+ const rowTooLarge = (oid, bytes) => gitError("RESOURCE_EXHAUSTED", `object ${oid} takes ${fmtBytes(bytes)} bytes as a row; one row holds ${fmtBytes(limits.valueBytes)}`, {
62
+ hostHint: largeBucketHint,
41
63
  context: { reason: "object-too-large" }
42
64
  });
43
- /** An object past `most`, the bytes one object takes: `RESOURCE_EXHAUSTED`, reason `too-large`. */
44
- const fileTooLarge = (bytes, most) => gitError("RESOURCE_EXHAUSTED", `push has an object of ${bytes.toLocaleString("en-US")} bytes; this server takes ${most.toLocaleString("en-US")} per object`, {
65
+ /** An object past `most`, the bytes one object takes: `RESOURCE_EXHAUSTED`, reason `object-too-large`. */
66
+ const fileTooLarge = (bytes, most) => gitError("RESOURCE_EXHAUSTED", `push has an object of ${fmtBytes(bytes)} bytes; this server takes ${fmtBytes(most)} per object`, {
45
67
  hint: objectPastHint,
46
- hostHint: "Use Objects.layer() storage, which keeps a large object in the bucket",
68
+ hostHint: largeBucketHint,
47
69
  context: { reason: "object-too-large" }
48
70
  });
49
- /** Objects past one row passing `most` in all, a delta's results among them: as `fileTooLarge`. */
50
- const largeTooLarge = (bytes, most) => gitError("RESOURCE_EXHAUSTED", `push's large objects take more than ${bytes.toLocaleString("en-US")} bytes; this server takes ${most.toLocaleString("en-US")} in all`, {
51
- hint: "Push fewer large files at a time",
52
- hostHint: "Use Objects.layer() storage, which keeps a push's objects in the bucket",
53
- context: { reason: "too-large" }
54
- });
71
+ /** A pack whose header counts more objects than its push declared or its unpack cap allows. */
72
+ const pastDeclared = (count) => gitError("INVALID_ARGUMENT", `The pack's header counts ${count} objects, past what its push said`, { hint: "Push again" });
55
73
  /** A pack holding an object twice, refused as Git's receive with fsck refuses it, by `index-pack --strict`. */
56
74
  const twiceInPack = (oid) => gitError("INVALID_ARGUMENT", `The pack is malformed: the same object ${oid} appears twice in the pack`, { hint: "Push again, with each object once" });
57
75
  /** An `OFS_DELTA` entry where a storage takes `REF_DELTA` only, the same at any size of push. */
@@ -75,317 +93,53 @@ const readFailure = (error) => {
75
93
  });
76
94
  return error;
77
95
  };
78
- /** A receive's `Admit`, with its count of the bytes its objects past a row take. */
79
- const admission = (large) => {
80
- let largeBytes = 0;
81
- return (type, size) => {
82
- if (large === void 0) return Effect.succeed(false);
83
- if (size > large.fileBytes) return Effect.fail(fileTooLarge(size, large.fileBytes));
84
- if (fitsRow(type, size)) return Effect.succeed(false);
85
- largeBytes += size;
86
- return largeBytes > large.totalBytes ? Effect.fail(largeTooLarge(largeBytes, large.totalBytes)) : Effect.succeed(true);
87
- };
88
- };
89
- /**
90
- * Every entry of the pack, read whole, within `most` inflated bytes in all, but for an object past
91
- * one row where `input.large` takes one: a blob is written as chunks as it's read, and a tree,
92
- * commit or tag is held whole beside them. A pack whose header counts more than `objects` entries
93
- * is refused before its first.
94
- */
95
- const readEntries = /* @__PURE__ */ Effect.fnUntraced(function* (input, most, admit) {
96
- const { large } = input;
97
- const entries = [];
98
- const chunked = [];
99
- let current;
100
- let pieces = [];
101
- let held = 0;
102
- let writer;
103
- let whole;
104
- const largeEntry = Effect.fnUntraced(function* (entry, type, takes) {
105
- if (type === "blob") {
106
- writer = yield* ChunkWriter.make(type, entry.size, partAt(entry.offset), takes.stage);
107
- return;
108
- }
109
- yield* takes.hold(entry.size);
110
- whole = {
111
- bytes: new Uint8Array(entry.size),
112
- filled: 0
113
- };
114
- });
115
- const sink = {
116
- begin: ({ count }) => count > input.limits.objects ? Effect.fail(input.tooMany(count)) : Effect.void,
117
- entry: (entry) => {
118
- if (entry.kind === "ofs" && input.offsetDeltas === "refuse") return Effect.fail(ofsRefused);
119
- current = entry;
120
- pieces = [];
121
- writer = void 0;
122
- whole = void 0;
123
- if (large === void 0 || entry.base !== void 0) return void 0;
124
- const type = entry.kind;
125
- return Effect.flatMap(admit(type, entry.size), (past) => past ? largeEntry(entry, type, large) : Effect.void);
126
- },
127
- data: (bytes) => {
128
- if (writer !== void 0) return writer.write(bytes);
129
- if (whole !== void 0) {
130
- if (whole.filled + bytes.byteLength > whole.bytes.byteLength) return Effect.fail(malformedPack("an object passes its size"));
131
- whole.bytes.set(bytes, whole.filled);
132
- whole.filled += bytes.byteLength;
133
- return Effect.void;
134
- }
135
- held += bytes.byteLength;
136
- if (held > most) return Effect.fail(tooLarge(held, most));
137
- pieces.push(bytes.slice());
138
- return Effect.void;
139
- },
140
- entryEnd: () => {
141
- const streamed = writer;
142
- const entry = current;
143
- current = void 0;
144
- writer = void 0;
145
- if (streamed !== void 0 && entry !== void 0) {
146
- const { type, size, part } = streamed;
147
- return Effect.map(streamed.end(), (oid) => {
148
- chunked.push({
149
- oid,
150
- type,
151
- size,
152
- part,
153
- offset: entry.offset
154
- });
155
- });
156
- }
157
- const body = whole;
158
- whole = void 0;
159
- if (body !== void 0 && body.filled !== body.bytes.byteLength) return Effect.fail(malformedPack(`an object of ${body.bytes.byteLength} bytes ended at ${body.filled}`));
160
- return Effect.sync(() => {
161
- if (entry !== void 0) {
162
- const read = body === void 0 ? {
163
- entry,
164
- data: joinedBytes(pieces)
165
- } : {
166
- entry,
167
- data: body.bytes,
168
- large: true
169
- };
170
- entries.push(read);
171
- }
172
- pieces = [];
173
- });
174
- }
175
- };
176
- const meter = new BufferMeter(readerBytes);
177
- const source = boundedSource(input.receive.pack, /* @__PURE__ */ new Uint8Array(0), meter);
178
- const objectBytes = large === void 0 ? most : Math.max(most, large.fileBytes);
179
- return {
180
- entries,
181
- chunked,
182
- bytes: (yield* readPack(source, nativeSha1Hasher(), sink, {
183
- objectBytes,
184
- deltaBytes: most
185
- }, meter).pipe(Effect.mapError(readFailure), Effect.ensuring(source.cancel))).bytes
186
- };
187
- });
188
- /** Where a delta waits: its base's offset in the pack, or its base's ID. */
189
- const waitKey = (entry) => {
190
- if (entry.base === void 0) return void 0;
191
- return entry.base.kind === "offset" ? `o:${entry.base.offset}` : `r:${entry.base.oid}`;
192
- };
193
- /**
194
- * Each entry as a whole object: a whole entry hashed, a delta applied to its base, an earlier
195
- * entry by offset, one by ID in the pack, or one the repo holds. A delta left without its base
196
- * refuses the pack, and so do objects past `most` bytes in all, as each delta's is made, and an
197
- * object twice. Where `input.large` takes one, a delta that makes a blob past one row writes it
198
- * as chunks as it applies, holding one; one of a tree, commit or tag is held whole, its bytes
199
- * taken first; and a chunked base is read back whole, taken first too, past `fileBytes` never.
200
- * Each result is admitted by `admit` before it's made. An entry's body becomes its object's, uncopied.
201
- */
202
- const resolve = /* @__PURE__ */ Effect.fnUntraced(function* (input, read, most, admit) {
203
- const { large } = input;
204
- const resolved = {
205
- objects: /* @__PURE__ */ new Map(),
206
- chunked: /* @__PURE__ */ new Map(),
207
- large: /* @__PURE__ */ new Map()
208
- };
209
- const waiting = /* @__PURE__ */ new Map();
210
- const ready = [];
211
- let unresolved = 0;
212
- let made = 0;
213
- const own = Effect.fnUntraced(function* (oid) {
214
- if (resolved.objects.has(oid) || resolved.chunked.has(oid)) return yield* Effect.fail(twiceInPack(oid));
215
- });
216
- for (const each of read.entries) {
217
- const key = waitKey(each.entry);
218
- if (key === void 0) {
219
- const type = each.entry.kind;
220
- const bytes = each.data;
221
- if (each.large === void 0) made += bytes.byteLength;
222
- const object = {
223
- oid: each.large === void 0 ? yield* objectId({
224
- type,
225
- bytes
226
- }) : yield* wholeObjectId(type, bytes),
227
- type,
228
- bytes
229
- };
230
- ready.push(each.large === void 0 ? {
231
- offset: each.entry.offset,
232
- object
233
- } : {
234
- offset: each.entry.offset,
235
- object,
236
- large: true
237
- });
238
- } else {
239
- waiting.set(key, [...waiting.get(key) ?? [], each]);
240
- unresolved += 1;
96
+ /** Bounded byte-size LRU cache of resolved whole objects used as delta bases. */
97
+ var BaseLru = class {
98
+ #entries = /* @__PURE__ */ new Map();
99
+ #limit;
100
+ #used = 0;
101
+ constructor(limit) {
102
+ this.#limit = limit;
103
+ }
104
+ has(oid) {
105
+ return this.#entries.has(oid);
106
+ }
107
+ get(oid) {
108
+ const got = this.#entries.get(oid);
109
+ if (got !== void 0) {
110
+ this.#entries.delete(oid);
111
+ this.#entries.set(oid, got);
241
112
  }
113
+ return got;
242
114
  }
243
- for (const each of read.chunked) ready.push({
244
- offset: each.offset,
245
- chunked: each
246
- });
247
- const malformed = (delta, message) => malformedPack(`the delta at ${delta.entry.offset}: ${message}`);
248
- const streamed = Effect.fnUntraced(function* (base, delta, size, takes) {
249
- const writer = yield* ChunkWriter.make("blob", size, partAt(delta.entry.offset), takes.stage);
250
- let waitingBytes = [];
251
- let waitingSize = 0;
252
- const run = new DeltaRun({
253
- instructions: (() => {
254
- let given = false;
255
- return () => given ? void 0 : (given = true, delta.data);
256
- })(),
257
- baseSize: base.byteLength,
258
- base: (offset, length) => base.subarray(offset, offset + length)
259
- }, {
260
- size: () => {},
261
- write: (bytes) => {
262
- waitingBytes.push(bytes.slice());
263
- waitingSize += bytes.byteLength;
264
- return waitingSize >= chunkRawBytes;
265
- }
266
- }, takes.fileBytes);
267
- for (;;) {
268
- const ran = run.run();
269
- for (const bytes of waitingBytes) yield* writer.write(bytes);
270
- waitingBytes = [];
271
- waitingSize = 0;
272
- if (ran === "paused") continue;
273
- if (Result.isFailure(ran)) return yield* Effect.fail(malformed(delta, ran.failure.message));
274
- return yield* writer.end();
115
+ set(oid, object) {
116
+ const size = object.bytes.byteLength;
117
+ if (size > this.#limit) return;
118
+ const existing = this.#entries.get(oid);
119
+ if (existing !== void 0) {
120
+ this.#used -= existing.bytes.byteLength;
121
+ this.#entries.delete(oid);
275
122
  }
276
- });
277
- const applied = Effect.fnUntraced(function* (base, delta) {
278
- const type = base.type;
279
- const offset = delta.entry.offset;
280
- const size = deltaResultSize(delta.data);
281
- if ((size === void 0 ? false : yield* admit(type, size)) && size !== void 0) {
282
- const takes = large;
283
- if (type === "blob") return {
284
- offset,
285
- chunked: {
286
- oid: yield* streamed(base.bytes, delta, size, takes),
287
- type,
288
- size,
289
- part: partAt(offset)
290
- }
291
- };
292
- yield* takes.hold(size);
293
- const whole = appliedDelta(base.bytes, delta.data, takes.fileBytes);
294
- if (Result.isFailure(whole)) return yield* Effect.fail(malformed(delta, whole.failure.message));
295
- const bytes = whole.success;
296
- return {
297
- offset,
298
- object: {
299
- oid: yield* wholeObjectId(type, bytes),
300
- type,
301
- bytes
302
- },
303
- large: true
304
- };
123
+ this.#entries.set(oid, object);
124
+ this.#used += size;
125
+ for (const [evictedOid, oldest] of this.#entries) {
126
+ if (this.#used <= this.#limit) break;
127
+ this.#entries.delete(evictedOid);
128
+ this.#used -= oldest.bytes.byteLength;
305
129
  }
306
- const result = appliedDelta(base.bytes, delta.data, most);
307
- if (Result.isFailure(result)) return yield* Effect.fail(malformed(delta, result.failure.message));
308
- made += result.success.byteLength;
309
- if (made > most) return yield* Effect.fail(resolvedTooLarge(made, most));
310
- const bytes = result.success;
311
- return {
312
- offset,
313
- object: {
314
- oid: yield* objectId({
315
- type,
316
- bytes
317
- }),
318
- type,
319
- bytes
320
- }
321
- };
322
- });
323
- const settle = Effect.fnUntraced(function* () {
324
- for (let next = ready.pop(); next !== void 0; next = ready.pop()) {
325
- const oid = "chunked" in next ? next.chunked.oid : next.object.oid;
326
- if (next.offset !== void 0) {
327
- yield* own(oid);
328
- if ("chunked" in next) resolved.chunked.set(oid, next.chunked);
329
- else {
330
- resolved.objects.set(oid, next.object);
331
- if (next.large === true) resolved.large.set(oid, partAt(next.offset));
332
- }
333
- }
334
- const keys = next.offset === void 0 ? [`r:${oid}`] : [`o:${next.offset}`, `r:${oid}`];
335
- const deltas = keys.flatMap((key) => waiting.get(key) ?? []);
336
- for (const key of keys) waiting.delete(key);
337
- if (deltas.length === 0) continue;
338
- const base = "chunked" in next ? {
339
- type: next.chunked.type,
340
- bytes: yield* stagedBase(next.chunked)
341
- } : next.object;
342
- for (const delta of deltas) {
343
- ready.push(yield* applied(base, delta));
344
- unresolved -= 1;
345
- }
346
- }
347
- });
348
- const stagedBase = Effect.fnUntraced(function* (object) {
349
- const takes = large;
350
- yield* takes.hold(object.size);
351
- return yield* takes.staged(object);
352
- });
353
- yield* settle();
354
- const outside = [...waiting.keys()].flatMap((key) => key.startsWith("r:") ? [key.slice(2)] : []);
355
- const bases = outside.length === 0 ? /* @__PURE__ */ new Map() : yield* input.held(outside);
356
- for (const base of bases.values()) ready.push({
357
- offset: void 0,
358
- object: base
359
- });
360
- yield* settle();
361
- if (unresolved > 0) return yield* Effect.fail(gitError("INVALID_ARGUMENT", `pack has ${unresolved} unresolved deltas`, { hint: "Push again, with every object the pack needs" }));
362
- return resolved;
363
- });
364
- /**
365
- * `INVALID_ARGUMENT` for the first object Git 2.53's fsck refuses a push for: one of the pack's
366
- * own, or a `.gitmodules` or `.gitattributes` one of its trees names, in the pack or the repo.
367
- */
368
- const fscked = /* @__PURE__ */ Effect.fnUntraced(function* (input, { objects, chunked }) {
369
- const checked = receiveChecked();
370
- for (const object of objects.values()) {
371
- const fault = fsckObject(object, checked);
372
- if (fault !== void 0) return yield* Effect.fail(fsckRefusal(object.oid, fault));
373
- const overflow = checkedOverflow(checked);
374
- if (overflow !== void 0) return yield* Effect.fail(overflow);
375
130
  }
376
- const pushed = (oid) => {
377
- const object = objects.get(oid);
378
- const large = chunked.get(oid);
379
- if (object !== void 0 || large === void 0 || input.large === void 0) return Effect.succeed(object);
380
- const takes = input.large;
381
- return Effect.map(Effect.andThen(takes.hold(large.size), takes.staged(large)), (bytes) => ({
382
- oid,
383
- type: large.type,
384
- bytes
385
- }));
386
- };
387
- yield* checkedFilesRefused(checked, pushed, input.held);
388
- });
131
+ clear() {
132
+ this.#entries.clear();
133
+ this.#used = 0;
134
+ }
135
+ };
136
+ const stagedLoss = (id) => fail("DATA_LOSS", `Staged row '${id}' is missing`);
137
+ /** Decodes one `stagedDeltas` row `{ data: base64 }` back to raw delta instructions. */
138
+ const decodeDeltaPart = (row, id) => {
139
+ const value = row?.value;
140
+ const decoded = Predicate.isObject(value) && "data" in value && Predicate.isString(value.data) ? Base64.decode(value.data) : void 0;
141
+ return decoded !== void 0 && Result.isSuccess(decoded) ? Effect.succeed(decoded.success) : stagedLoss(id);
142
+ };
389
143
  /**
390
144
  * The links of a commit or a tag, from its first lines alone, never its message: a commit's tree
391
145
  * and parents by `rawLinks`, which reads what `linksOf` does of any object fsck passes
@@ -414,31 +168,697 @@ const headLinks = (object) => {
414
168
  })));
415
169
  };
416
170
  /**
417
- * `INVALID_ARGUMENT` unless every object the pack's own name is in it or the repo, of the type its
418
- * link says, and `shallowRoot` when a shallow client's commit names parents neither holds. A
419
- * partial pack may leave out both, but for its tags' objects, which Git's server sends with them
420
- * through any depth or filter: a missing one is `tagTargetMissing`, as the stored receive says. An
421
- * import segment's boundary is its own commits, and their parents it leaves out are never asked of
422
- * the repo; those it holds are checked as any link is.
423
- *
424
- * It holds no list of every link: a tree's are read an entry at a time, a commit's or a tag's from
425
- * its first lines, those in the pack are checked as they come, and those outside it are asked of
426
- * the repo by their headers `receiveLinksAskedBatch` at a time. The first missing one is refused
427
- * as it's found, and the first of the wrong type, by its place among them, once none is missing.
171
+ * A received pack unpacked in a streaming pass (Phase A) plus bounded delta resolution (Phase B):
172
+ * - Wire bytes are counted before inflation against `limits.bytes`.
173
+ * - Inflated bytes (pack entries, thin bases read once, and delta results) are counted against
174
+ * `maxInflatedBytes` (256 MiB); delta result sizes are checked before allocation.
175
+ * - Whole objects and ready deltas are hashed, fsck'd, and streamed to the single `BatchStager`
176
+ * once the push passes `fastPath` (keeping inline pushes under `fastPath` batch-free).
177
+ * - Pending deltas stay in memory up to `pendingHeld` (24 MiB) and spill past it to `stagedDeltas`
178
+ * through the same `BatchStager`.
179
+ * - Phase B resolves in-memory subtrees with zero calls, streams thin bases via `eachHeld`, and
180
+ * resolves spilled deltas in rounds of <= 7 MiB with OFS descendant prefetch, capped at
181
+ * `deltaRoundsMost` (4,095) rounds before refusing `delta-chain-too-deep`.
428
182
  */
429
- const connected = /* @__PURE__ */ Effect.fnUntraced(function* (input, { objects, chunked }) {
430
- const partial = input.receive.partial === true;
431
- const shallow = new Set(input.receive.shallow);
432
- const boundary = new Set(input.receive.boundary);
183
+ const unpackObjects = /* @__PURE__ */ Effect.fnUntraced(function* (input) {
184
+ const { receive, limits: limits$1, large, staging, memory } = input;
185
+ if (receive.objects > limits$1.objects) return yield* Effect.fail(input.tooMany(receive.objects));
186
+ const past = segmentTooLarge(receive);
187
+ if (past !== void 0) return yield* Effect.fail(past);
188
+ const inflatedCap = input.inflatedBytes ?? 268435456;
189
+ const pendingCap = input.pendingHeld ?? 25165824;
190
+ const roundCap = input.roundBytes ?? 7340032;
191
+ const inlineBytesCap = input.stageBytes ?? fastPath.bytes;
192
+ const roundsCap = input.roundsMost ?? 4095;
193
+ const lru = memory?.lru ?? new BaseLru(input.lruBytes ?? 16777216);
194
+ const growMem = (bytes) => memory === void 0 ? Effect.void : memory.grow(bytes);
195
+ const shrinkMem = (bytes) => memory?.shrink(bytes);
196
+ const pageCap = () => memory?.page(roundCap) ?? roundCap;
197
+ const stagedRowKey = (oid) => stagedKey(activeStager.opened.batch, oid);
198
+ const eachExternal = (oids, take) => input.eachHeld !== void 0 ? input.eachHeld(oids, take) : Effect.flatMap(input.held(oids), (m) => Effect.forEach(m.values(), take, { discard: true }));
199
+ let inflated = 0;
200
+ const chargeInflated = (bytes) => {
201
+ inflated += bytes;
202
+ return inflated > inflatedCap ? Effect.fail(tooLarge(inflated, inflatedCap)) : Effect.void;
203
+ };
204
+ const headers = /* @__PURE__ */ new Map();
205
+ const offsetToOid = /* @__PURE__ */ new Map();
206
+ const chunked = /* @__PURE__ */ new Map();
207
+ const commits = [];
208
+ const headEntries = [];
209
+ const packTrees = [];
210
+ const largest = new LargestFiles();
211
+ const pointers = new ReceivedPointers();
212
+ const checked = receiveChecked();
213
+ let inlineRows = [];
214
+ const inlineByOid = /* @__PURE__ */ new Map();
215
+ let inlineStagedBytes = 0;
216
+ let inlineHeld = 0;
217
+ let activeStager;
218
+ const moved = {
219
+ objects: 0,
220
+ bytes: 0
221
+ };
222
+ const ensureStager = Effect.fnUntraced(function* () {
223
+ if (activeStager !== void 0) return activeStager;
224
+ if (staging === void 0) return yield* Effect.fail(tooLarge(inlineStagedBytes, fastPath.bytes));
225
+ const stager = yield* staging.stager();
226
+ activeStager = stager;
227
+ shrinkMem(inlineHeld);
228
+ inlineHeld = 0;
229
+ for (const row of inlineRows) yield* stager.push(row);
230
+ inlineRows = [];
231
+ inlineByOid.clear();
232
+ inlineStagedBytes = 0;
233
+ return stager;
234
+ });
235
+ const emitChunkedManifest = (item) => {
236
+ const row = large.row(item);
237
+ const counted = chunkedMoved(chunkedOf(row.value));
238
+ moved.objects += counted.objects;
239
+ moved.bytes += counted.bytes;
240
+ return Effect.flatMap(ensureStager(), (stager) => stager.push(row));
241
+ };
242
+ const waitingByOffset = /* @__PURE__ */ new Map();
243
+ const waitingByOid = /* @__PURE__ */ new Map();
244
+ let nextSeq = 0;
245
+ let pendingBytes = 0;
246
+ let unresolved = 0;
247
+ const enqueuePending = (delta) => {
248
+ unresolved += 1;
249
+ const put = (map, key) => {
250
+ const list = map.get(key);
251
+ if (list === void 0) map.set(key, [delta]);
252
+ else list.push(delta);
253
+ };
254
+ if (delta.base.kind === "offset") put(waitingByOffset, delta.base.offset);
255
+ else put(waitingByOid, delta.base.oid);
256
+ };
257
+ /** Looks up an already-resolved object in memory (LRU, inline buffer, or unflushed stager buffer). */
258
+ const readInMemory = (oid) => {
259
+ const cached = lru.get(oid) ?? inlineByOid.get(oid);
260
+ if (cached !== void 0) return Effect.succeed(cached);
261
+ const buffered = activeStager?.bufferedRow(oid);
262
+ return buffered !== void 0 && chunkedOf(buffered.value) === void 0 ? objectOfRow(buffered) : Effect.succeed(void 0);
263
+ };
264
+ const readChunked = (item) => {
265
+ const takes = large;
266
+ lru.clear();
267
+ return Effect.flatMap(takes.hold(item.size), () => Effect.map(takes.staged(item), (bytes) => ({
268
+ oid: item.oid,
269
+ type: item.type,
270
+ bytes
271
+ })));
272
+ };
273
+ const readLocal = (oid) => Effect.flatMap(readInMemory(oid), (inMem) => {
274
+ if (inMem !== void 0) return Effect.succeed(inMem);
275
+ const largeObj = chunked.get(oid);
276
+ return largeObj !== void 0 && large !== void 0 ? readChunked(largeObj) : Effect.succeed(void 0);
277
+ });
278
+ /** Reads an already-resolved own object from memory, `large.staged`, or flushed `stagedObjects`. */
279
+ const readOwnObject = (oid) => Effect.flatMap(readLocal(oid), (local) => local !== void 0 || activeStager === void 0 || staging === void 0 || !headers.has(oid) ? Effect.succeed(local) : Effect.flatMap(staging.readStaged([stagedRowKey(oid)]), ([row]) => row === void 0 ? Effect.succeed(void 0) : objectOfRow(row)));
280
+ const recordWhole = Effect.fnUntraced(function* (offset, object, isChunkedNonBlob) {
281
+ const { oid, type, bytes } = object;
282
+ if (headers.has(oid)) return yield* Effect.fail(twiceInPack(oid));
283
+ const fault = fsckObject(object, checked);
284
+ if (fault !== void 0) return yield* Effect.fail(fsckRefusal(oid, fault));
285
+ const overflow = checkedOverflow(checked);
286
+ if (overflow !== void 0) return yield* Effect.fail(overflow);
287
+ const size = bytes.byteLength;
288
+ headers.set(oid, {
289
+ type,
290
+ size
291
+ });
292
+ offsetToOid.set(offset, oid);
293
+ if (type === "blob") {
294
+ largest.add(oid, size);
295
+ yield* pointers.add(oid, bytes);
296
+ } else if (type === "tree") packTrees.push(oid);
297
+ else {
298
+ const links = yield* Effect.fromResult(headLinks(object));
299
+ headEntries.push({
300
+ oid,
301
+ type,
302
+ links
303
+ });
304
+ if (type === "commit") commits.push({
305
+ oid,
306
+ parents: links.slice(1).map((link) => link.oid)
307
+ });
308
+ }
309
+ if (isChunkedNonBlob) {
310
+ const part = partAt(offset);
311
+ const writer = yield* ChunkWriter.make(type, size, part, large.stage);
312
+ yield* writer.write(bytes);
313
+ yield* writer.end();
314
+ const item = {
315
+ oid,
316
+ type,
317
+ size,
318
+ part
319
+ };
320
+ chunked.set(oid, item);
321
+ yield* emitChunkedManifest(item);
322
+ } else {
323
+ const row = objectRow(object);
324
+ const valueBytes = rowValueBytes(row.value);
325
+ if (valueBytes > limits.valueBytes) return yield* Effect.fail(rowTooLarge(oid, valueBytes));
326
+ moved.objects += 1;
327
+ moved.bytes += valueBytes;
328
+ if (activeStager !== void 0) yield* activeStager.push(row);
329
+ else {
330
+ const rowSize = stagedBytes(row);
331
+ const inlineDelta = rowSize + size;
332
+ if (staging !== void 0 && (inlineRows.length + 1 > fastPath.rows || inlineStagedBytes + rowSize > inlineBytesCap || memory?.tryGrow(inlineDelta) === false)) yield* (yield* ensureStager()).push(row);
333
+ else {
334
+ if (staging === void 0) yield* growMem(inlineDelta);
335
+ inlineRows.push(row);
336
+ inlineByOid.set(oid, object);
337
+ inlineStagedBytes += rowSize;
338
+ inlineHeld += inlineDelta;
339
+ }
340
+ }
341
+ }
342
+ lru.set(oid, object);
343
+ return {
344
+ oid,
345
+ offset,
346
+ object
347
+ };
348
+ });
349
+ const recordChunkedBlob = (offset, item) => {
350
+ const { oid, type, size } = item;
351
+ if (headers.has(oid)) return Effect.fail(twiceInPack(oid));
352
+ headers.set(oid, {
353
+ type,
354
+ size
355
+ });
356
+ offsetToOid.set(offset, oid);
357
+ chunked.set(oid, item);
358
+ largest.add(oid, size);
359
+ return Effect.as(emitChunkedManifest(item), {
360
+ oid,
361
+ offset,
362
+ item
363
+ });
364
+ };
365
+ const resolveDelta = Effect.fnUntraced(function* (base, offset, instructions, shrinkBytes) {
366
+ const malformed = (message) => malformedPack(`the delta at ${offset}: ${message}`);
367
+ const type = base.type;
368
+ const size = deltaResultSize(instructions);
369
+ if (size !== void 0) {
370
+ if (large !== void 0 && size > large.fileBytes) return yield* Effect.fail(fileTooLarge(size, large.fileBytes));
371
+ if (inflated + size > inflatedCap) return yield* Effect.fail(tooLarge(inflated + size, inflatedCap));
372
+ if (large !== void 0 && !fitsRow(type, size)) {
373
+ yield* chargeInflated(size);
374
+ if (type === "blob") {
375
+ const part = partAt(offset);
376
+ const writer = yield* ChunkWriter.make("blob", size, part, large.stage);
377
+ let waitingBytes = [];
378
+ let waitingSize = 0;
379
+ let given = false;
380
+ const run = new DeltaRun({
381
+ instructions: () => given ? void 0 : (given = true, instructions),
382
+ baseSize: base.bytes.byteLength,
383
+ base: (at, length) => base.bytes.subarray(at, at + length)
384
+ }, {
385
+ size: () => {},
386
+ write: (bytes) => {
387
+ waitingBytes.push(bytes.slice());
388
+ waitingSize += bytes.byteLength;
389
+ return waitingSize >= chunkRawBytes;
390
+ }
391
+ }, large.fileBytes);
392
+ for (;;) {
393
+ const ran = run.run();
394
+ for (const bytes of waitingBytes) yield* writer.write(bytes);
395
+ waitingBytes = [];
396
+ waitingSize = 0;
397
+ if (ran === "paused") continue;
398
+ if (Result.isFailure(ran)) return yield* Effect.fail(malformed(ran.failure.message));
399
+ const oid = yield* writer.end();
400
+ shrinkMem(shrinkBytes);
401
+ return yield* recordChunkedBlob(offset, {
402
+ oid,
403
+ type,
404
+ size,
405
+ part
406
+ });
407
+ }
408
+ }
409
+ lru.clear();
410
+ yield* large.hold(size);
411
+ const whole = appliedDelta(base.bytes, instructions, large.fileBytes);
412
+ if (Result.isFailure(whole)) return yield* Effect.fail(malformed(whole.failure.message));
413
+ const bytes = whole.success;
414
+ const oid = yield* wholeObjectId(type, bytes);
415
+ shrinkMem(shrinkBytes);
416
+ return yield* recordWhole(offset, {
417
+ oid,
418
+ type,
419
+ bytes
420
+ }, true);
421
+ }
422
+ }
423
+ const remaining = Math.max(0, inflatedCap - inflated);
424
+ const maxResult = large === void 0 ? Math.min(remaining, limits.valueBytes) : remaining;
425
+ const result = appliedDelta(base.bytes, instructions, maxResult);
426
+ if (Result.isFailure(result)) {
427
+ if (result.failure.fault === "too big" && size !== void 0) {
428
+ if (large === void 0 && !fitsRow(type, size)) return yield* Effect.fail(rowTooLarge(emptyTree, size));
429
+ return yield* Effect.fail(tooLarge(inflated + size, inflatedCap));
430
+ }
431
+ return yield* Effect.fail(malformed(result.failure.message));
432
+ }
433
+ const bytes = result.success;
434
+ yield* chargeInflated(bytes.byteLength);
435
+ const oid = yield* objectId({
436
+ type,
437
+ bytes
438
+ });
439
+ if (large === void 0 && !fitsRow(type, bytes.byteLength)) return yield* Effect.fail(rowTooLarge(oid, rowValueBytes(objectRow({
440
+ oid,
441
+ type,
442
+ bytes
443
+ }).value)));
444
+ shrinkMem(shrinkBytes);
445
+ return yield* recordWhole(offset, {
446
+ oid,
447
+ type,
448
+ bytes
449
+ }, false);
450
+ });
451
+ const readyForSpilled = /* @__PURE__ */ new Set();
452
+ const readyOffsetsForSpilled = /* @__PURE__ */ new Set();
453
+ /** Takes in-memory pending children of `base`, leaving any spilled children in the waiting maps. */
454
+ const takeInMemoryChildren = (oid, offset) => {
455
+ const taken = [];
456
+ const pull = (map, key, ready) => {
457
+ const list = map.get(key);
458
+ if (list === void 0) return;
459
+ const kept = [];
460
+ for (const delta of list) if (delta.data !== void 0) {
461
+ pendingBytes -= delta.data.byteLength;
462
+ unresolved -= 1;
463
+ taken.push(delta);
464
+ } else kept.push(delta);
465
+ if (kept.length === 0) map.delete(key);
466
+ else {
467
+ map.set(key, kept);
468
+ ready.add(key);
469
+ }
470
+ };
471
+ pull(waitingByOid, oid, readyForSpilled);
472
+ if (offset !== void 0) pull(waitingByOffset, offset, readyOffsetsForSpilled);
473
+ return taken;
474
+ };
475
+ const baseOfSeed = (seed) => "object" in seed ? Effect.succeed(seed.object) : readChunked(seed.item);
476
+ /** Zero-call iterative DFS over in-memory pending descendants, materializing one sibling at a time. */
477
+ const resolveInMemoryTree = Effect.fnUntraced(function* (seed) {
478
+ const first = takeInMemoryChildren(seed.oid, seed.offset);
479
+ if (first.length === 0) return;
480
+ const stack = [{
481
+ oid: seed.oid,
482
+ base: yield* baseOfSeed(seed),
483
+ list: first,
484
+ at: 0
485
+ }];
486
+ while (stack.length > 0) {
487
+ const frame = stack[stack.length - 1];
488
+ if (frame.at >= frame.list.length) {
489
+ stack.pop();
490
+ continue;
491
+ }
492
+ const base = frame.base ?? (yield* readOwnObject(frame.oid));
493
+ if (base === void 0) {
494
+ stack.pop();
495
+ continue;
496
+ }
497
+ frame.base = base;
498
+ const delta = frame.list[frame.at++];
499
+ const data = delta.data;
500
+ const recorded = yield* resolveDelta(base, delta.offset, data, data.byteLength);
501
+ const grandkids = takeInMemoryChildren(recorded.oid, recorded.offset);
502
+ if (grandkids.length === 0) continue;
503
+ if (frame.at >= frame.list.length) stack.pop();
504
+ else if (headers.has(frame.oid)) frame.base = void 0;
505
+ stack.push({
506
+ oid: recorded.oid,
507
+ base: yield* baseOfSeed(recorded),
508
+ list: grandkids,
509
+ at: 0
510
+ });
511
+ }
512
+ });
513
+ const walk = (seed) => Effect.flatMap(seed, resolveInMemoryTree);
514
+ let pieces = [];
515
+ let chunkWriter;
516
+ let wholeBuf;
517
+ let spill;
518
+ let directBase;
519
+ const resetEntry = () => {
520
+ pieces = [];
521
+ chunkWriter = void 0;
522
+ wholeBuf = void 0;
523
+ spill = void 0;
524
+ directBase = void 0;
525
+ };
526
+ const flushSpillPart = Effect.fnUntraced(function* (active, force) {
527
+ while (active.bytes >= 768e3 || force && active.bytes > 0) {
528
+ const joined = joinedBytes(active.buf);
529
+ const take = Math.min(joined.byteLength, deltaPartBytes);
530
+ const rest = joined.subarray(take);
531
+ yield* (yield* ensureStager()).pushDelta(active.seq, active.parts.length, joined.subarray(0, take));
532
+ active.parts.push(take);
533
+ active.buf = rest.byteLength > 0 ? [rest] : [];
534
+ active.bytes = rest.byteLength;
535
+ }
536
+ });
537
+ memory?.free?.(ensureStager, [waitingByOid, waitingByOffset], (bytes) => {
538
+ pendingBytes -= bytes;
539
+ }, () => inlineHeld > 0);
540
+ const sink = {
541
+ begin: ({ count }) => count > limits$1.objects ? Effect.fail(input.tooMany(count)) : count > receive.objects ? Effect.fail(pastDeclared(count)) : Effect.void,
542
+ entry: (entry) => {
543
+ if (entry.kind === "ofs" && input.offsetDeltas === "refuse") return Effect.fail(ofsRefused);
544
+ resetEntry();
545
+ if (entry.base !== void 0) {
546
+ if (large === void 0 && entry.size > 7340032) return Effect.fail(rowTooLarge(emptyTree, entry.size));
547
+ const base = entry.base;
548
+ const baseOid = base.kind === "offset" ? offsetToOid.get(base.offset) : base.oid;
549
+ return Effect.flatMap(baseOid === void 0 ? Effect.succeed(void 0) : readInMemory(baseOid), (inMem) => {
550
+ if (inMem !== void 0) {
551
+ directBase = inMem;
552
+ return growMem(entry.size);
553
+ }
554
+ const canHold = pendingBytes + entry.size <= pendingCap;
555
+ return Effect.map(memory === void 0 ? Effect.succeed(canHold) : memory.delta(entry.size, canHold, Math.min(entry.size, deltaPartBytes)), (hold) => {
556
+ if (!hold) spill = {
557
+ seq: nextSeq++,
558
+ offset: entry.offset,
559
+ base,
560
+ size: entry.size,
561
+ parts: [],
562
+ buf: [],
563
+ bytes: 0
564
+ };
565
+ });
566
+ });
567
+ }
568
+ const type = entry.kind;
569
+ if (large !== void 0) {
570
+ if (entry.size > large.fileBytes) return Effect.fail(fileTooLarge(entry.size, large.fileBytes));
571
+ if (!fitsRow(type, entry.size)) {
572
+ if (inflated + entry.size > inflatedCap) return Effect.fail(tooLarge(inflated + entry.size, inflatedCap));
573
+ if (type === "blob") return Effect.map(ChunkWriter.make(type, entry.size, partAt(entry.offset), large.stage), (writer) => {
574
+ chunkWriter = writer;
575
+ });
576
+ lru.clear();
577
+ return Effect.map(large.hold(entry.size), () => {
578
+ wholeBuf = {
579
+ bytes: new Uint8Array(entry.size),
580
+ at: 0
581
+ };
582
+ });
583
+ }
584
+ } else if (!fitsRow(type, entry.size)) return Effect.fail(rowTooLarge(emptyTree, entry.size));
585
+ },
586
+ data: (bytes) => {
587
+ const over = chargeInflated(bytes.byteLength);
588
+ if (inflated > inflatedCap) return over;
589
+ if (chunkWriter !== void 0) return chunkWriter.write(bytes);
590
+ if (wholeBuf !== void 0) {
591
+ if (wholeBuf.at + bytes.byteLength > wholeBuf.bytes.byteLength) return Effect.fail(malformedPack("an object passes its size"));
592
+ wholeBuf.bytes.set(bytes, wholeBuf.at);
593
+ wholeBuf.at += bytes.byteLength;
594
+ return Effect.void;
595
+ }
596
+ if (spill !== void 0) {
597
+ spill.buf.push(bytes.slice());
598
+ spill.bytes += bytes.byteLength;
599
+ return spill.bytes >= 768e3 ? flushSpillPart(spill, false) : Effect.void;
600
+ }
601
+ pieces.push(bytes.slice());
602
+ return Effect.void;
603
+ },
604
+ entryEnd: Effect.fnUntraced(function* (entry) {
605
+ const streamed = chunkWriter;
606
+ const body = wholeBuf;
607
+ const spilling = spill;
608
+ const baseReady = directBase;
609
+ const entryPieces = pieces;
610
+ resetEntry();
611
+ if (streamed !== void 0) {
612
+ const oid = yield* streamed.end();
613
+ return yield* walk(recordChunkedBlob(entry.offset, {
614
+ oid,
615
+ type: streamed.type,
616
+ size: streamed.size,
617
+ part: streamed.part
618
+ }));
619
+ }
620
+ if (body !== void 0) {
621
+ if (body.at !== body.bytes.byteLength) return yield* Effect.fail(malformedPack(`an object of ${body.bytes.byteLength} bytes ended at ${body.at}`));
622
+ const type = entry.kind;
623
+ const oid = yield* wholeObjectId(type, body.bytes);
624
+ return yield* walk(recordWhole(entry.offset, {
625
+ oid,
626
+ type,
627
+ bytes: body.bytes
628
+ }, true));
629
+ }
630
+ if (spilling !== void 0) {
631
+ yield* flushSpillPart(spilling, true);
632
+ shrinkMem(Math.min(spilling.size, deltaPartBytes));
633
+ enqueuePending(spilling);
634
+ if (spilling.base.kind === "offset") {
635
+ if (offsetToOid.has(spilling.base.offset)) readyOffsetsForSpilled.add(spilling.base.offset);
636
+ } else if (headers.has(spilling.base.oid)) readyForSpilled.add(spilling.base.oid);
637
+ return;
638
+ }
639
+ if (entry.base !== void 0) {
640
+ const data = joinedBytes(entryPieces);
641
+ if (baseReady !== void 0) return yield* walk(resolveDelta(baseReady, entry.offset, data, data.byteLength));
642
+ pendingBytes += data.byteLength;
643
+ enqueuePending({
644
+ seq: nextSeq++,
645
+ offset: entry.offset,
646
+ base: entry.base,
647
+ size: data.byteLength,
648
+ data
649
+ });
650
+ return;
651
+ }
652
+ const type = entry.kind;
653
+ const bytes = joinedBytes(entryPieces);
654
+ const oid = yield* objectId({
655
+ type,
656
+ bytes
657
+ });
658
+ return yield* walk(recordWhole(entry.offset, {
659
+ oid,
660
+ type,
661
+ bytes
662
+ }, false));
663
+ })
664
+ };
665
+ const meter = new BufferMeter(readerBytes);
666
+ const rawSource = boundedSource(receive.pack, /* @__PURE__ */ new Uint8Array(0), meter);
667
+ const wireCap = receive.objects === 0 ? Math.max(limits$1.bytes, 32) : limits$1.bytes;
668
+ let wireBytes = 0;
669
+ const objectBytes = large === void 0 ? inflatedCap : Math.max(inflatedCap, large.fileBytes);
670
+ const packRead = yield* readPack({ read: Effect.flatMap(rawSource.read, (chunk) => {
671
+ if (chunk === void 0) return Effect.succeed(void 0);
672
+ const total = wireBytes += chunk.byteLength;
673
+ return total > wireCap ? Effect.fail(tooLarge(total, wireCap)) : Effect.succeed(chunk);
674
+ }) }, nativeSha1Hasher(), sink, {
675
+ objectBytes,
676
+ deltaBytes: inflatedCap
677
+ }, meter).pipe(Effect.mapError(readFailure), Effect.ensuring(rawSource.cancel));
678
+ const externalBases = /* @__PURE__ */ new Map();
679
+ const baseOf = (item) => item.oid ?? offsetToOid.get(item.offset);
680
+ let rounds = 0;
681
+ const drainSpilledRounds = Effect.fnUntraced(function* () {
682
+ while (readyForSpilled.size > 0 || readyOffsetsForSpilled.size > 0) {
683
+ const wave = [];
684
+ let needsSpillRound = false;
685
+ const take = (delta, item) => {
686
+ if (delta.data !== void 0) pendingBytes -= delta.data.byteLength;
687
+ else needsSpillRound = true;
688
+ unresolved -= 1;
689
+ wave.push(item);
690
+ };
691
+ const drainReady = (ready, map, oidOf) => {
692
+ for (const key of ready) {
693
+ const list = map.get(key);
694
+ const baseOid = oidOf(key);
695
+ if (list === void 0 || baseOid === void 0) continue;
696
+ map.delete(key);
697
+ const start = wave.length;
698
+ for (const delta of list) take(delta, {
699
+ delta,
700
+ oid: baseOid
701
+ });
702
+ for (let i = start; i < wave.length; i++) {
703
+ const parent = wave[i].delta;
704
+ const kids = waitingByOffset.get(parent.offset);
705
+ if (kids === void 0) continue;
706
+ waitingByOffset.delete(parent.offset);
707
+ for (const kid of kids) take(kid, {
708
+ delta: kid,
709
+ offset: parent.offset
710
+ });
711
+ }
712
+ }
713
+ ready.clear();
714
+ };
715
+ drainReady(readyForSpilled, waitingByOid, (oid) => oid);
716
+ drainReady(readyOffsetsForSpilled, waitingByOffset, (offset) => offsetToOid.get(offset));
717
+ if (wave.length === 0) break;
718
+ if (needsSpillRound) {
719
+ rounds += 1;
720
+ if (rounds > roundsCap) return yield* Effect.fail(deltaChainTooDeep(roundsCap));
721
+ }
722
+ for (let waveAt = 0; waveAt < wave.length;) {
723
+ const page = [];
724
+ const pageBases = /* @__PURE__ */ new Set();
725
+ let pageBytes = 0;
726
+ while (waveAt < wave.length) {
727
+ const item = wave[waveAt];
728
+ const oid = baseOf(item);
729
+ let bytes = item.delta.data === void 0 ? encodedBytes(item.delta.size) : 0;
730
+ if (oid !== void 0 && !pageBases.has(oid) && !lru.has(oid) && !chunked.has(oid) && !inlineByOid.has(oid) && activeStager?.bufferedRow(oid) === void 0) {
731
+ const size = headers.get(oid)?.size ?? externalBases.get(oid) ?? 0;
732
+ if (size > 0) bytes += encodedBytes(size);
733
+ }
734
+ if (page.length > 0 && pageBytes + bytes > pageCap()) break;
735
+ page.push(item);
736
+ if (oid !== void 0) pageBases.add(oid);
737
+ pageBytes += bytes;
738
+ waveAt += 1;
739
+ }
740
+ let pageHeld = 0;
741
+ if (page.length === 1 && large !== void 0) {
742
+ const only = page[0].delta;
743
+ if (only.data === void 0 && only.size > roundCap) yield* large.hold(only.size - roundCap);
744
+ }
745
+ const fetchedBases = /* @__PURE__ */ new Map();
746
+ const fetchedInstructions = /* @__PURE__ */ new Map();
747
+ const missingExternal = [];
748
+ const toRead = [];
749
+ for (const { delta } of page) {
750
+ if (delta.data !== void 0) {
751
+ fetchedInstructions.set(delta.seq, delta.data);
752
+ continue;
753
+ }
754
+ yield* growMem(delta.size);
755
+ pageHeld += delta.size;
756
+ const buf = new Uint8Array(delta.size);
757
+ fetchedInstructions.set(delta.seq, buf);
758
+ let at = 0;
759
+ for (const [partIdx, rawSize] of (delta.parts ?? []).entries()) {
760
+ const buffered = activeStager?.bufferedDelta(delta.seq, partIdx);
761
+ if (buffered !== void 0) buf.set(buffered, at);
762
+ else toRead.push({
763
+ key: stagedDeltaKey(activeStager.opened.batch, delta.seq, partIdx),
764
+ bytes: encodedBytes(rawSize),
765
+ buf,
766
+ offset: at
767
+ });
768
+ at += rawSize;
769
+ }
770
+ }
771
+ for (const oid of pageBases) {
772
+ const local = yield* readLocal(oid);
773
+ if (local !== void 0) {
774
+ fetchedBases.set(oid, local);
775
+ continue;
776
+ }
777
+ if (externalBases.has(oid)) {
778
+ missingExternal.push(oid);
779
+ continue;
780
+ }
781
+ const header = headers.get(oid);
782
+ if (header !== void 0 && activeStager !== void 0) toRead.push({
783
+ key: stagedRowKey(oid),
784
+ bytes: encodedBytes(header.size),
785
+ oid
786
+ });
787
+ }
788
+ if (toRead.length > 0 && staging !== void 0) for (let at = 0; at < toRead.length;) {
789
+ const batch = [];
790
+ let bytes = 0;
791
+ while (at < toRead.length) {
792
+ const item = toRead[at];
793
+ if (batch.length > 0 && bytes + item.bytes > roundCap) break;
794
+ batch.push(item);
795
+ bytes += item.bytes;
796
+ at += 1;
797
+ }
798
+ const rows = yield* staging.readStaged(batch.map(({ key }) => key));
799
+ for (const [i, item] of batch.entries()) {
800
+ const row = rows[i];
801
+ if ("oid" in item) {
802
+ if (row === void 0) return yield* stagedLoss(item.oid);
803
+ const obj = yield* objectOfRow(row);
804
+ yield* growMem(obj.bytes.byteLength);
805
+ pageHeld += obj.bytes.byteLength;
806
+ fetchedBases.set(obj.oid, obj);
807
+ lru.set(obj.oid, obj);
808
+ } else item.buf.set(yield* decodeDeltaPart(row, item.key.id), item.offset);
809
+ }
810
+ }
811
+ const runItem = (item, base) => {
812
+ const instructions = fetchedInstructions.get(item.delta.seq);
813
+ if (instructions === void 0) return Effect.void;
814
+ fetchedInstructions.delete(item.delta.seq);
815
+ return walk(resolveDelta(base, item.delta.offset, instructions, item.delta.data?.byteLength ?? 0));
816
+ };
817
+ if (missingExternal.length > 0) yield* eachExternal(missingExternal, (base) => {
818
+ lru.set(base.oid, base);
819
+ return Effect.forEach(page, (item) => baseOf(item) === base.oid ? runItem(item, base) : Effect.void, { discard: true });
820
+ });
821
+ for (const item of page) {
822
+ if (!fetchedInstructions.has(item.delta.seq)) continue;
823
+ const baseOid = baseOf(item);
824
+ const base = baseOid === void 0 ? void 0 : fetchedBases.get(baseOid) ?? (yield* readOwnObject(baseOid));
825
+ if (base !== void 0) yield* runItem(item, base);
826
+ }
827
+ shrinkMem(pageHeld);
828
+ }
829
+ }
830
+ });
831
+ for (const offset of waitingByOffset.keys()) if (offsetToOid.has(offset)) readyOffsetsForSpilled.add(offset);
832
+ for (const oid of waitingByOid.keys()) if (headers.has(oid)) readyForSpilled.add(oid);
833
+ yield* drainSpilledRounds();
834
+ const outsideOids = [...waitingByOid.keys()].filter((oid) => !headers.has(oid));
835
+ if (outsideOids.length > 0) {
836
+ yield* eachExternal(outsideOids, (base) => Effect.flatMap(chargeInflated(base.bytes.byteLength), () => {
837
+ externalBases.set(base.oid, base.bytes.byteLength);
838
+ lru.set(base.oid, base);
839
+ return Effect.map(resolveInMemoryTree({
840
+ oid: base.oid,
841
+ offset: void 0,
842
+ object: base
843
+ }), () => {
844
+ if (waitingByOid.has(base.oid)) readyForSpilled.add(base.oid);
845
+ });
846
+ }));
847
+ yield* drainSpilledRounds();
848
+ }
849
+ if (unresolved > 0) return yield* Effect.fail(gitError("INVALID_ARGUMENT", `pack has ${unresolved} unresolved deltas`, { hint: "Push again, with every object the pack needs" }));
850
+ yield* checkedFilesRefused(checked, readOwnObject, input.held);
851
+ const partial = receive.partial === true;
852
+ const shallow = new Set(receive.shallow);
853
+ const boundary = new Set(receive.boundary);
433
854
  const parents = [];
434
855
  const tagged = /* @__PURE__ */ new Map();
435
- for (const oid of boundary) if (objects.get(oid)?.type !== "commit") return yield* Effect.fail(boundaryNotInPack(oid));
436
- const segment = segmentCut(input.receive.cutMost);
437
- const inPack = (oid) => objects.has(oid) || chunked.has(oid);
438
- const packType = (oid) => oid === "4b825dc642cb6eb9a060e54bf8d69288fbee4904" ? "tree" : objects.get(oid)?.type ?? chunked.get(oid)?.type;
856
+ for (const oid of boundary) if (headers.get(oid)?.type !== "commit") return yield* Effect.fail(boundaryNotInPack(oid));
857
+ const segment = segmentCut(receive.cutMost);
858
+ const inPack = (oid) => headers.has(oid);
439
859
  let wrong;
440
- let count = 0;
441
- let waiting = [];
860
+ let linkCount = 0;
861
+ let waitingLinks = [];
442
862
  const asked = /* @__PURE__ */ new Map();
443
863
  const typed = (at, link, type) => {
444
864
  if (type !== link.type && (wrong === void 0 || at < wrong.at)) wrong = {
@@ -446,121 +866,129 @@ const connected = /* @__PURE__ */ Effect.fnUntraced(function* (input, { objects,
446
866
  error: wrongType(link, type)
447
867
  };
448
868
  };
449
- const added = (link) => {
450
- const at = count;
451
- count += 1;
452
- const type = packType(link.oid) ?? asked.get(link.oid);
453
- if (type !== void 0) typed(at, link, type);
454
- else waiting.push({
455
- at,
456
- link
457
- });
458
- return waiting.length >= receiveLinksAskedBatch;
459
- };
460
- const check = Effect.fnUntraced(function* (missing) {
461
- const batch = waiting;
462
- waiting = [];
463
- const unknown = [...new Set(batch.map(({ link }) => link.oid))];
464
- const headers = unknown.length === 0 ? /* @__PURE__ */ new Map() : yield* input.headers(unknown);
869
+ const checkLinks = Effect.fnUntraced(function* (missing) {
870
+ if (waitingLinks.length === 0) return;
871
+ const batch = waitingLinks;
872
+ waitingLinks = [];
873
+ const repoHeaders = yield* input.headers([...new Set(batch.map(({ link }) => link.oid))]);
465
874
  for (const { at, link } of batch) {
466
- const type = headers.get(link.oid)?.type;
875
+ const type = repoHeaders.get(link.oid)?.type;
467
876
  if (type === void 0) return yield* Effect.fail(missing(link));
468
877
  typed(at, link, type);
469
878
  }
470
- for (const [oid, { type }] of headers) if (asked.size < 1e5) asked.set(oid, type);
879
+ for (const [oid, { type }] of repoHeaders) if (asked.size < 1e5) asked.set(oid, type);
471
880
  });
472
881
  const missingLink = (link) => partial ? tagTargetMissing(link.oid, tagged.get(link.oid)) : objectMissing(link.oid);
473
- for (const oid of input.receive.needs ?? []) if (added({
882
+ const queueLink = (link, missing = missingLink) => {
883
+ const at = linkCount++;
884
+ const type = link.oid === "4b825dc642cb6eb9a060e54bf8d69288fbee4904" ? "tree" : headers.get(link.oid)?.type ?? asked.get(link.oid);
885
+ if (type !== void 0) typed(at, link, type);
886
+ else waitingLinks.push({
887
+ at,
888
+ link
889
+ });
890
+ return waitingLinks.length >= 1e3 ? checkLinks(missing) : Effect.void;
891
+ };
892
+ const trackRoots = !partial && receive.boundary === void 0;
893
+ const namedInPack = /* @__PURE__ */ new Set();
894
+ let outside = trackRoots ? /* @__PURE__ */ new Set() : void 0;
895
+ const trackLink = (oid) => {
896
+ if (headers.has(oid)) namedInPack.add(oid);
897
+ else if (oid !== "4b825dc642cb6eb9a060e54bf8d69288fbee4904" && outside !== void 0) {
898
+ if (outside.size >= 1e5) outside = void 0;
899
+ else outside.add(oid);
900
+ }
901
+ };
902
+ for (const oid of receive.needs ?? []) yield* queueLink({
474
903
  oid,
475
904
  type: "commit"
476
- })) yield* check(missingLink);
477
- for (const object of objects.values()) {
478
- if (partial && object.type !== "tag") continue;
479
- if (object.type === "tree") {
480
- const next = linkReader(object);
905
+ });
906
+ for (const entry of headEntries) {
907
+ if (partial && entry.type !== "tag") continue;
908
+ if (trackRoots) for (const link of entry.links) trackLink(link.oid);
909
+ const split = shallowLinks(entry, entry.links, shallow);
910
+ if (partial) for (const link of split.needed) tagged.set(link.oid, entry.oid);
911
+ const cut = shallowLinks(entry, split.needed, boundary);
912
+ for (const link of cut.needed) yield* queueLink(link);
913
+ for (const parent of cut.parents) {
914
+ const pastCut = segment.add(entry.oid, parent.oid);
915
+ if (pastCut !== void 0) return yield* Effect.fail(pastCut);
916
+ if (inPack(parent.oid)) yield* queueLink(parent);
917
+ }
918
+ for (const parent of split.parents) parents.push(parent);
919
+ }
920
+ if (!partial && packTrees.length > 0) {
921
+ const checkTreeObject = Effect.fnUntraced(function* (tree) {
922
+ const next = linkReader(tree);
481
923
  for (let read = next();; read = next()) {
482
924
  if (Result.isFailure(read)) return yield* Effect.fail(read.failure);
483
925
  if (read.success === void 0) break;
484
- if (added(read.success)) yield* check(missingLink);
926
+ if (trackRoots) trackLink(read.success.oid);
927
+ yield* queueLink(read.success);
485
928
  }
486
- continue;
929
+ });
930
+ const evictedTrees = [];
931
+ for (const oid of packTrees) {
932
+ const largeTree = chunked.get(oid);
933
+ const tree = (yield* readInMemory(oid)) ?? (largeTree !== void 0 && large !== void 0 ? {
934
+ oid,
935
+ type: "tree",
936
+ bytes: yield* large.staged(largeTree)
937
+ } : void 0);
938
+ if (tree !== void 0) yield* checkTreeObject(tree);
939
+ else evictedTrees.push(oid);
487
940
  }
488
- const split = shallowLinks(object, yield* Effect.fromResult(headLinks(object)), shallow);
489
- if (partial) for (const link of split.needed) tagged.set(link.oid, object.oid);
490
- const cut = shallowLinks(object, split.needed, boundary);
491
- for (const link of cut.needed) if (added(link)) yield* check(missingLink);
492
- for (const parent of cut.parents) {
493
- const past = segment.add(object.oid, parent.oid);
494
- if (past !== void 0) return yield* Effect.fail(past);
495
- if (inPack(parent.oid) && added(parent)) yield* check(missingLink);
941
+ if (evictedTrees.length > 0 && activeStager !== void 0 && staging !== void 0) for (let at = 0; at < evictedTrees.length;) {
942
+ const page = [];
943
+ let pageBytes = 0;
944
+ while (at < evictedTrees.length) {
945
+ const oid = evictedTrees[at];
946
+ const est = encodedBytes(headers.get(oid)?.size ?? 0);
947
+ if (page.length > 0 && pageBytes + est > pageCap()) break;
948
+ page.push(oid);
949
+ pageBytes += est;
950
+ at += 1;
951
+ }
952
+ yield* growMem(pageBytes);
953
+ const rows = yield* staging.readStaged(page.map(stagedRowKey));
954
+ for (const [i, oid] of page.entries()) {
955
+ const row = rows[i];
956
+ if (row === void 0) return yield* stagedLoss(oid);
957
+ yield* checkTreeObject(yield* objectOfRow(row));
958
+ }
959
+ shrinkMem(pageBytes);
496
960
  }
497
- for (const parent of split.parents) parents.push(parent);
498
961
  }
499
- yield* check(missingLink);
500
- for (const parent of parents) if (added(parent)) yield* check(() => shallowRoot());
501
- yield* check(() => shallowRoot());
962
+ yield* checkLinks(missingLink);
963
+ for (const parent of parents) yield* queueLink(parent, shallowRoot);
964
+ yield* checkLinks(shallowRoot);
502
965
  if (wrong !== void 0) return yield* Effect.fail(wrong.error);
503
- return segment.leftOut(inPack);
504
- });
505
- /**
506
- * A received pack as rows, one per object, for its push's commit: each entry read and resolved,
507
- * each object checked as Git's fsck checks it and parsed, and every object they name present, of
508
- * the type its link says. Refused whole, before any row, past `limits` or for an object whose row
509
- * passes 1 MiB, for a malformed or unresolved pack, an `OFS_DELTA` where `offsetDeltas` refuses
510
- * one, an object fsck refuses, or a missing or mistyped object.
511
- */
512
- const unpackObjects = /* @__PURE__ */ Effect.fnUntraced(function* (input) {
513
- const { receive, limits: limits$1 } = input;
514
- if (receive.objects > limits$1.objects) return yield* Effect.fail(input.tooMany(receive.objects));
515
- const past = segmentTooLarge(receive);
516
- if (past !== void 0) return yield* Effect.fail(past);
517
- const admit = admission(input.large);
518
- const read = yield* readEntries(input, limits$1.bytes, admit);
519
- const resolved = yield* resolve(input, read, limits$1.bytes, admit);
520
- yield* fscked(input, resolved);
521
- const cut = yield* connected(input, resolved);
522
- const { objects } = resolved;
523
- const chunked = [...resolved.chunked.values()];
524
- for (const [oid, part] of resolved.large) {
525
- const takes = input.large;
526
- const object = objects.get(oid);
527
- const writer = yield* ChunkWriter.make(object.type, object.bytes.byteLength, part, takes.stage);
528
- yield* writer.write(object.bytes);
529
- yield* writer.end();
530
- chunked.push({
531
- oid,
532
- type: object.type,
533
- size: object.bytes.byteLength,
534
- part
535
- });
536
- }
537
- const rows = [...objects.values()].flatMap((object) => resolved.large.has(object.oid) ? [] : [objectRow(object)]);
538
- let valuesBytes = 0;
539
- for (const row of rows) {
540
- const valueBytes = rowValueBytes(row.value);
541
- if (valueBytes > limits.valueBytes) return yield* Effect.fail(rowTooLarge(row.id, valueBytes));
542
- valuesBytes += valueBytes;
543
- }
544
- const rowBytes = rows.reduce((sum, row) => sum + JSON.stringify(row).length, 0);
545
- if (rowBytes > limits$1.bytes) return yield* Effect.fail(tooLarge(rowBytes, limits$1.bytes));
546
- const moved = {
547
- objects: rows.length,
548
- bytes: valuesBytes
966
+ if (activeStager !== void 0) yield* activeStager.flush();
967
+ const readRows = (oids) => activeStager === void 0 || staging === void 0 || oids.length === 0 ? Effect.succeed(oids.map(() => void 0)) : staging.readStaged(oids.map(stagedRowKey));
968
+ const own = {
969
+ headers,
970
+ commits,
971
+ readRow: (oid) => headers.has(oid) ? Effect.map(readRows([oid]), ([row]) => row) : Effect.succeed(void 0),
972
+ readRows
549
973
  };
550
- const chunkedRows = input.large === void 0 ? [] : chunked.map(input.large.row);
551
- for (const row of chunkedRows) {
552
- const counted = chunkedMoved(chunkedOf(row.value));
553
- moved.objects += counted.objects;
554
- moved.bytes += counted.bytes;
555
- }
556
- return {
557
- objects: [...objects.values()],
558
- chunked,
559
- count: objects.size + resolved.chunked.size,
560
- rows: [...rows, ...chunkedRows],
974
+ const roots = trackRoots ? rootsOf(headers.keys(), (oid) => namedInPack.has(oid)) : void 0;
975
+ const unpacked = {
976
+ inlineObjects: [...inlineByOid.values()],
977
+ inlineRows,
978
+ staged: activeStager !== void 0,
979
+ own,
980
+ chunked: [...chunked.values()],
981
+ count: headers.size,
561
982
  moved,
562
- bytes: read.bytes,
563
- cut
983
+ bytes: packRead.bytes,
984
+ cut: segment.leftOut(inPack),
985
+ lfsPointers: pointers.finish(),
986
+ largest: largest.finish()
564
987
  };
988
+ if (roots !== void 0) {
989
+ unpacked.roots = roots;
990
+ if (outside !== void 0) unpacked.outside = [...outside];
991
+ }
992
+ return unpacked;
565
993
  });
566
- export { commitBytes, malformedPack, ofsRefused, readFailure, rowTooLarge, unpackObjects };
994
+ export { baseLruBytes, deltaChainTooDeep, deltaRoundsMost, malformedPack, maxInflatedBytes, ofsRefused, pastDeclared, pendingHeldMost, readFailure, roundReadBytes, rowTooLarge, unpackObjects };