@ref0/git 0.14.0 → 0.20.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 (351) hide show
  1. package/dist/auth/access-jwt.mjs +2 -2
  2. package/dist/auth/authorize.mjs +3 -3
  3. package/dist/auth/fences.d.mts +1 -2
  4. package/dist/auth/fences.mjs +3 -3
  5. package/dist/auth/grants.mjs +4 -4
  6. package/dist/auth/host-function.mjs +18 -1
  7. package/dist/auth/identify.d.mts +1 -1
  8. package/dist/auth/identify.mjs +3 -3
  9. package/dist/auth/token-cleanup.mjs +67 -0
  10. package/dist/auth/token-rows.mjs +1 -1
  11. package/dist/auth/token-text.mjs +9 -1
  12. package/dist/auth/tokens-base.d.mts +35 -0
  13. package/dist/auth/tokens-base.mjs +13 -0
  14. package/dist/auth/tokens-layer.d.mts +2 -27
  15. package/dist/auth/tokens-layer.mjs +6 -11
  16. package/dist/auth/tokens-public.d.mts +3 -3
  17. package/dist/auth/tokens.d.mts +7 -10
  18. package/dist/auth/tokens.mjs +9 -80
  19. package/dist/client/answer.mjs +21 -42
  20. package/dist/client/client.d.mts +2 -4
  21. package/dist/client/git-http.mjs +17 -7
  22. package/dist/client/local.mjs +14 -13
  23. package/dist/client/push-upload.mjs +9 -8
  24. package/dist/client/remote.mjs +8 -10
  25. package/dist/client/run-remote-helper.d.mts +1 -0
  26. package/dist/client/run-remote-helper.mjs +58 -24
  27. package/dist/client/slice-push.d.mts +1 -1
  28. package/dist/client/transport.mjs +105 -46
  29. package/dist/contracts/blobs.d.mts +55 -8
  30. package/dist/contracts/blobs.mjs +16 -2
  31. package/dist/contracts/call-allowance.d.mts +13 -0
  32. package/dist/contracts/call-allowance.mjs +44 -0
  33. package/dist/contracts/calls-spent.mjs +8 -3
  34. package/dist/contracts/client.d.mts +15 -16
  35. package/dist/contracts/commits.d.mts +24 -24
  36. package/dist/contracts/engine.d.mts +6 -1
  37. package/dist/contracts/engine.mjs +10 -1
  38. package/dist/contracts/files.d.mts +10 -10
  39. package/dist/contracts/forks.d.mts +17 -17
  40. package/dist/contracts/git-events.d.mts +29 -1
  41. package/dist/contracts/git-hooks.d.mts +1 -1
  42. package/dist/contracts/git.d.mts +21 -0
  43. package/dist/contracts/grants.d.mts +24 -4
  44. package/dist/contracts/handlers.d.mts +1 -1
  45. package/dist/contracts/lfs.d.mts +28 -2
  46. package/dist/contracts/merges.d.mts +3 -2
  47. package/dist/contracts/objects.d.mts +23 -25
  48. package/dist/contracts/queue.d.mts +40 -12
  49. package/dist/contracts/queue.mjs +3 -4
  50. package/dist/contracts/refs.d.mts +26 -23
  51. package/dist/contracts/remote.d.mts +6 -7
  52. package/dist/contracts/remote.mjs +4 -1
  53. package/dist/contracts/repos.d.mts +29 -138
  54. package/dist/contracts/repos.mjs +5 -3
  55. package/dist/contracts/result.d.mts +35 -16
  56. package/dist/contracts/result.mjs +35 -7
  57. package/dist/contracts/server.d.mts +25 -50
  58. package/dist/contracts/services.d.mts +1 -1
  59. package/dist/contracts/store.d.mts +6 -5
  60. package/dist/contracts/sync.d.mts +11 -7
  61. package/dist/contracts/sync.mjs +12 -2
  62. package/dist/contracts/tags.d.mts +10 -10
  63. package/dist/contracts/time.d.mts +3 -0
  64. package/dist/contracts/{promises.mjs → time.mjs} +1 -1
  65. package/dist/contracts/tokens.d.mts +15 -17
  66. package/dist/contracts/tokens.mjs +3 -2
  67. package/dist/contracts/topics.d.mts +1 -1
  68. package/dist/contracts/trees.d.mts +12 -12
  69. package/dist/contracts/work.d.mts +24 -13
  70. package/dist/core/access.d.mts +1 -2
  71. package/dist/core/access.mjs +20 -9
  72. package/dist/core/ancestry.d.mts +1 -0
  73. package/dist/core/asked.mjs +1 -1
  74. package/dist/core/call-names.mjs +6 -1
  75. package/dist/core/call-services.mjs +11 -3
  76. package/dist/core/events/deliver.d.mts +1 -2
  77. package/dist/core/events/deliver.mjs +43 -36
  78. package/dist/core/events/retired.mjs +119 -0
  79. package/dist/core/forks.mjs +928 -432
  80. package/dist/core/hooks/groups.mjs +1 -1
  81. package/dist/core/imports.mjs +29 -23
  82. package/dist/core/index-job.mjs +122 -34
  83. package/dist/core/index-lost.d.mts +1 -2
  84. package/dist/core/index-lost.mjs +2 -2
  85. package/dist/core/loose-tally.mjs +1 -1
  86. package/dist/core/objects/blobs.mjs +129 -3
  87. package/dist/core/objects/lines.mjs +2 -2
  88. package/dist/core/objects/merges.mjs +4 -1
  89. package/dist/core/objects/objects-layer.d.mts +1 -1
  90. package/dist/core/objects/objects-layer.mjs +3 -3
  91. package/dist/core/objects/reading.mjs +24 -13
  92. package/dist/core/objects/tags.mjs +4 -1
  93. package/dist/core/objects/trees.mjs +2 -2
  94. package/dist/core/objects/writing.mjs +2 -2
  95. package/dist/core/own-writes.mjs +1 -1
  96. package/dist/core/parts.d.mts +4 -5
  97. package/dist/core/parts.mjs +3 -8
  98. package/dist/core/promise.mjs +9 -12
  99. package/dist/core/purge.mjs +287 -83
  100. package/dist/core/push-decide.mjs +2 -0
  101. package/dist/core/push-files.d.mts +1 -1
  102. package/dist/core/push.mjs +58 -47
  103. package/dist/core/receipts.mjs +8 -3
  104. package/dist/core/ref-index-job.mjs +4 -4
  105. package/dist/core/ref-view.mjs +2 -2
  106. package/dist/core/refs.mjs +5 -5
  107. package/dist/core/registered-rows.mjs +2 -2
  108. package/dist/core/repack.mjs +36 -21
  109. package/dist/core/repo-info.mjs +3 -3
  110. package/dist/core/repos.mjs +21 -9
  111. package/dist/core/rules/commit-changes.d.mts +0 -1
  112. package/dist/core/saved-caller-views.d.mts +7 -2
  113. package/dist/core/saved-caller-views.mjs +2 -2
  114. package/dist/core/saved-callers.d.mts +19 -2
  115. package/dist/core/seam.d.mts +16 -26
  116. package/dist/core/seam.mjs +7 -28
  117. package/dist/core/tokens.mjs +1 -1
  118. package/dist/core/view.mjs +7 -15
  119. package/dist/core/work.mjs +59 -14
  120. package/dist/effect.d.mts +3 -12
  121. package/dist/effect.mjs +1 -10
  122. package/dist/engine/failures.mjs +2 -1
  123. package/dist/engine/reads.mjs +4 -4
  124. package/dist/event-streams/stream.d.mts +2 -2
  125. package/dist/event-streams/stream.mjs +37 -14
  126. package/dist/extend.d.mts +2 -3
  127. package/dist/extend.mjs +2 -1
  128. package/dist/http/answers.mjs +8 -5
  129. package/dist/http/core-parts.mjs +95 -79
  130. package/dist/http/handler.mjs +34 -7
  131. package/dist/http/node.d.mts +14 -1
  132. package/dist/http/node.mjs +56 -27
  133. package/dist/http/parts.d.mts +1 -0
  134. package/dist/http/push-upload-job.mjs +30 -26
  135. package/dist/http/push-uploads.mjs +36 -21
  136. package/dist/http/upload-pack.mjs +3 -3
  137. package/dist/index.d.mts +14 -14
  138. package/dist/index.mjs +2 -2
  139. package/dist/lfs/answer.mjs +37 -0
  140. package/dist/lfs/base.d.mts +2 -0
  141. package/dist/lfs/base.mjs +25 -1
  142. package/dist/lfs/copy.d.mts +21 -7
  143. package/dist/lfs/copy.mjs +89 -6
  144. package/dist/lfs/layer.d.mts +15 -1
  145. package/dist/lfs/layer.mjs +24 -11
  146. package/dist/lfs/locks.mjs +2 -2
  147. package/dist/lfs/objects.d.mts +1 -0
  148. package/dist/lfs/objects.mjs +87 -17
  149. package/dist/lfs/pointers.mjs +2 -2
  150. package/dist/lfs/rows.mjs +42 -8
  151. package/dist/lfs/upkeep.mjs +48 -14
  152. package/dist/lfs/wire.mjs +6 -31
  153. package/dist/merges/merges.mjs +2 -2
  154. package/dist/node.d.mts +2 -2
  155. package/dist/protocol/bytes/buffers.mjs +13 -5
  156. package/dist/protocol/bytes/reader.mjs +6 -1
  157. package/dist/protocol/bytes/streams.mjs +27 -1
  158. package/dist/protocol/diff/read.d.mts +4 -3
  159. package/dist/protocol/diff/read.mjs +8 -3
  160. package/dist/protocol/objects/lfs-pointer.d.mts +14 -2
  161. package/dist/protocol/objects/lfs-pointer.mjs +1 -3
  162. package/dist/protocol/objects/links-raw.mjs +24 -10
  163. package/dist/protocol/objects/tag.d.mts +1 -1
  164. package/dist/protocol/objects/tree.mjs +23 -6
  165. package/dist/protocol/packs/delta.d.mts +6 -3
  166. package/dist/protocol/packs/delta.mjs +96 -32
  167. package/dist/protocol/packs/idx.d.mts +2 -1
  168. package/dist/protocol/packs/idx.mjs +22 -3
  169. package/dist/protocol/packs/parts.d.mts +4 -1
  170. package/dist/protocol/packs/parts.mjs +10 -7
  171. package/dist/protocol/packs/reader.d.mts +5 -0
  172. package/dist/protocol/packs/reader.mjs +3 -2
  173. package/dist/protocol/packs/writer.mjs +26 -8
  174. package/dist/queue/advance.mjs +21 -24
  175. package/dist/queue/base.d.mts +55 -0
  176. package/dist/queue/base.mjs +44 -0
  177. package/dist/queue/calls.mjs +51 -54
  178. package/dist/queue/commit.mjs +1 -1
  179. package/dist/queue/host.d.mts +1 -15
  180. package/dist/queue/host.mjs +2 -7
  181. package/dist/queue/layer.d.mts +2 -1
  182. package/dist/queue/layer.mjs +10 -3
  183. package/dist/queue/limits.mjs +2 -0
  184. package/dist/queue/push-option.mjs +9 -24
  185. package/dist/queue/schedule.mjs +1 -1
  186. package/dist/queue/state.mjs +2 -10
  187. package/dist/queue/trim.mjs +5 -3
  188. package/dist/rest/blobs.mjs +29 -5
  189. package/dist/rest/caller.d.mts +4 -4271
  190. package/dist/rest/caller.mjs +4 -0
  191. package/dist/rest/client.d.mts +8 -5
  192. package/dist/rest/client.mjs +19 -2
  193. package/dist/rest/handlers.mjs +50 -5
  194. package/dist/rest/layer.d.mts +2 -2
  195. package/dist/rest/layer.mjs +5 -12
  196. package/dist/rest/me.d.mts +3 -432
  197. package/dist/server/check-fetch.mjs +3 -3
  198. package/dist/server/edge-node.d.mts +11 -8
  199. package/dist/server/edge-node.mjs +9 -6
  200. package/dist/server/edge.d.mts +21 -7
  201. package/dist/server/edge.mjs +32 -11
  202. package/dist/server/extension.mjs +1 -1
  203. package/dist/server/git-layer.d.mts +5 -5
  204. package/dist/server/git-layer.mjs +28 -22
  205. package/dist/server/git-namespace.d.mts +4 -3
  206. package/dist/server/git-namespace.mjs +3 -2
  207. package/dist/server/joined.d.mts +6 -18
  208. package/dist/server/joined.mjs +9 -36
  209. package/dist/server/lifecycle.mjs +18 -106
  210. package/dist/server/registry.mjs +24 -7
  211. package/dist/server/server.mjs +205 -346
  212. package/dist/signin/context.d.mts +1 -2
  213. package/dist/signin/layer.d.mts +1 -1
  214. package/dist/signin/layer.mjs +1 -1
  215. package/dist/storage/allotted.mjs +18 -3
  216. package/dist/storage/batch-upkeep.mjs +274 -0
  217. package/dist/storage/batches.d.mts +8 -0
  218. package/dist/storage/batches.mjs +344 -0
  219. package/dist/storage/calls.d.mts +1 -2
  220. package/dist/storage/calls.mjs +144 -158
  221. package/dist/storage/chunks.d.mts +9 -0
  222. package/dist/storage/chunks.mjs +297 -0
  223. package/dist/storage/clean-up.mjs +72 -9
  224. package/dist/storage/counted-bucket.mjs +4 -4
  225. package/dist/storage/fetch.d.mts +1 -0
  226. package/dist/storage/fetch.mjs +287 -210
  227. package/dist/storage/host-bucket.mjs +1 -2
  228. package/dist/storage/id-mix.mjs +19 -5
  229. package/dist/storage/index-bitmaps.mjs +9 -2
  230. package/dist/storage/index-build.d.mts +0 -1
  231. package/dist/storage/index-build.mjs +80 -23
  232. package/dist/storage/index-fetch.mjs +113 -72
  233. package/dist/storage/index-files.d.mts +3 -0
  234. package/dist/storage/index-files.mjs +10 -5
  235. package/dist/storage/index-graph.mjs +72 -22
  236. package/dist/storage/index-remap.mjs +200 -64
  237. package/dist/storage/index-whole.mjs +127 -0
  238. package/dist/storage/largest-files.mjs +1 -1
  239. package/dist/storage/layout.mjs +23 -0
  240. package/dist/storage/loose.d.mts +7 -4
  241. package/dist/storage/loose.mjs +212 -67
  242. package/dist/storage/memory-budget.mjs +16 -4
  243. package/dist/storage/merge-plan.mjs +3 -2
  244. package/dist/storage/merge-row.mjs +7 -1
  245. package/dist/storage/merge-stream.mjs +164 -25
  246. package/dist/storage/merge-walk.mjs +8 -4
  247. package/dist/storage/merge-write.mjs +1 -1
  248. package/dist/storage/merge.d.mts +1 -1
  249. package/dist/storage/merge.mjs +1 -1
  250. package/dist/storage/object-rows.d.mts +1 -0
  251. package/dist/storage/object-rows.mjs +385 -65
  252. package/dist/storage/oid-table.mjs +171 -0
  253. package/dist/storage/pack-order.mjs +8 -4
  254. package/dist/storage/pack-ranges.d.mts +1 -2
  255. package/dist/storage/pack-ranges.mjs +4 -5
  256. package/dist/storage/pack-reads.d.mts +2 -1
  257. package/dist/storage/pack-reads.mjs +158 -42
  258. package/dist/storage/pack-receive.d.mts +1 -1
  259. package/dist/storage/pack-receive.mjs +2 -2
  260. package/dist/storage/packs.d.mts +1 -1
  261. package/dist/storage/packs.mjs +136 -66
  262. package/dist/storage/placed-reads.mjs +1 -1
  263. package/dist/storage/plan-columns.d.mts +4 -0
  264. package/dist/storage/plan-columns.mjs +238 -0
  265. package/dist/storage/prune-keep.mjs +134 -41
  266. package/dist/storage/prune-walk.mjs +202 -62
  267. package/dist/storage/prune.mjs +194 -91
  268. package/dist/storage/push-allotment.mjs +91 -12
  269. package/dist/storage/push-uploads.mjs +4 -4
  270. package/dist/storage/pushed-commits.mjs +4 -2
  271. package/dist/storage/quarantine.d.mts +1 -1
  272. package/dist/storage/range-cache.mjs +125 -8
  273. package/dist/storage/ready.d.mts +1 -1
  274. package/dist/storage/ready.mjs +8 -6
  275. package/dist/storage/receive-bounds.mjs +23 -8
  276. package/dist/storage/repack-backlog.mjs +6 -3
  277. package/dist/storage/repack.d.mts +1 -1
  278. package/dist/storage/rows.d.mts +1 -1
  279. package/dist/storage/rows.mjs +1 -1
  280. package/dist/storage/runs.mjs +195 -43
  281. package/dist/storage/send-list.d.mts +1 -0
  282. package/dist/storage/send-list.mjs +54 -10
  283. package/dist/storage/single-flight.mjs +13 -7
  284. package/dist/storage/stream-whole.mjs +127 -26
  285. package/dist/storage/unpack.mjs +371 -79
  286. package/dist/storage/visible.mjs +2 -2
  287. package/dist/storage/walk.mjs +192 -38
  288. package/dist/storage/wants.mjs +5 -5
  289. package/dist/store/bodies.mjs +38 -0
  290. package/dist/store/call-count.d.mts +8 -12
  291. package/dist/store/call-count.mjs +34 -46
  292. package/dist/store/catalogue.d.mts +2 -2
  293. package/dist/store/catalogue.mjs +145 -35
  294. package/dist/store/crossing.mjs +1 -3
  295. package/dist/store/cursor-seal.d.mts +1 -2
  296. package/dist/store/cursor-seal.mjs +16 -6
  297. package/dist/store/door.mjs +183 -0
  298. package/dist/store/errors.d.mts +3 -4
  299. package/dist/store/errors.mjs +15 -33
  300. package/dist/store/git-store.mjs +25 -7
  301. package/dist/store/job-try.mjs +9 -32
  302. package/dist/store/list-job.mjs +44 -8
  303. package/dist/store/records.d.mts +3 -0
  304. package/dist/store/records.mjs +3 -0
  305. package/dist/store/repo-record.d.mts +1 -2
  306. package/dist/store/repo-record.mjs +32 -20
  307. package/dist/store/reservations.mjs +1 -1
  308. package/dist/store/scopes.mjs +11 -0
  309. package/dist/store/settle.mjs +4 -4
  310. package/dist/sync/github.mjs +3 -3
  311. package/dist/sync/import.mjs +31 -18
  312. package/dist/sync/lfs-batch.mjs +4 -5
  313. package/dist/sync/lfs-copy.mjs +17 -6
  314. package/dist/sync/mirror.mjs +34 -31
  315. package/dist/sync/said.mjs +16 -37
  316. package/dist/sync/step.mjs +33 -25
  317. package/dist/sync/tries.mjs +9 -9
  318. package/dist/topics/advance.mjs +10 -11
  319. package/dist/topics/base.d.mts +15 -0
  320. package/dist/topics/base.mjs +8 -0
  321. package/dist/topics/host.mjs +1 -1
  322. package/dist/topics/layer.d.mts +4 -9
  323. package/dist/topics/layer.mjs +2 -3
  324. package/dist/topics/members.mjs +4 -4
  325. package/dist/topics/public.d.mts +2 -1
  326. package/dist/topics/topic.mjs +2 -2
  327. package/package.json +5 -4
  328. package/dist/contracts/promises.d.mts +0 -39
  329. package/dist/core/call-names.d.mts +0 -3
  330. package/dist/core/clock.mjs +0 -18
  331. package/dist/lfs/calls.mjs +0 -26
  332. package/dist/rest/api.d.mts +0 -23
  333. package/dist/rest/blobs.d.mts +0 -833
  334. package/dist/rest/commits.d.mts +0 -3543
  335. package/dist/rest/errors.d.mts +0 -2124
  336. package/dist/rest/events.d.mts +0 -426
  337. package/dist/rest/files.d.mts +0 -1342
  338. package/dist/rest/forks.d.mts +0 -2160
  339. package/dist/rest/handlers.d.mts +0 -8
  340. package/dist/rest/merges.d.mts +0 -477
  341. package/dist/rest/queue.d.mts +0 -5917
  342. package/dist/rest/refs.d.mts +0 -2988
  343. package/dist/rest/repos.d.mts +0 -2567
  344. package/dist/rest/tags.d.mts +0 -1316
  345. package/dist/rest/tokens.d.mts +0 -2614
  346. package/dist/rest/topics.d.mts +0 -2224
  347. package/dist/rest/trees.d.mts +0 -1709
  348. package/dist/rest/work.d.mts +0 -1695
  349. package/dist/server/lifecycle.d.mts +0 -2
  350. package/dist/store/promises.d.mts +0 -11
  351. package/dist/store/promises.mjs +0 -327
@@ -1,27 +1,32 @@
1
1
  import { isRepoName } from "../contracts/ids.mjs";
2
2
  import { fail } from "../contracts/result.mjs";
3
- import { objectsFace, oneShotReads } from "../storage/calls.mjs";
3
+ import { abandonedRow, awaitingUpkeep, batchesRead, fastPath, openBatch, publication, stageRows, stageRowsCalls, stageRowsCounter, stagedBytes, storeSkew } from "../storage/batches.mjs";
4
+ import { oneShotReads } from "../storage/calls.mjs";
5
+ import { chunkCopyCalls, chunkedMoved, chunkedOf, chunkedRow, copyChunks } from "../storage/chunks.mjs";
4
6
  import { indexRowKey, isPackId, objectCollections } from "../storage/layout.mjs";
5
7
  import { noLfsPointers } from "../storage/lfs-pointers.mjs";
6
8
  import { noRows } from "../storage/object-rows.mjs";
7
9
  import { holdingsOf, swapsOf } from "../storage/repack.mjs";
10
+ import { pruneJobRow } from "../storage/repack-job.mjs";
8
11
  import { SwapsSettled, holdingKey, swapsKey } from "../storage/swap-walk.mjs";
9
12
  import { ApartRow, apartAfter, apartKey } from "../storage/repack-contained.mjs";
10
- import { coverRow, decodeLeft, leavingKey, leavingLate, leavingRow, pruneFloor } from "../storage/rows.mjs";
13
+ import { coverKey, coverRow, decodeLeft, leavingKey, leavingLate, leavingRow, pruneFloor } from "../storage/rows.mjs";
11
14
  import { entryOf, forkOf, forksCreated, heldNameAt, isCreatedKey, listLimit, namedRecordOf, reconcile } from "../store/catalogue.mjs";
12
- import { afterWrites, decodeRow, storeCall } from "../store/errors.mjs";
13
- import { decodePacks, packRow } from "../store/git-store.mjs";
15
+ import { afterWrites, decodeRow, storeCall, storeCommit } from "../store/errors.mjs";
16
+ import { decodePacks, gitStore, packRow } from "../store/git-store.mjs";
14
17
  import { appendEvents, decodeOutbox, dropUnconfirmed, emptyOutbox, outboxReads, repoEnvelope } from "../store/outbox.mjs";
15
18
  import { keptKey } from "../store/records.mjs";
16
19
  import { WholeRepo, refBytesOf, storesPeel, wholeRef, wholeRefs } from "../store/ref-rows.mjs";
17
20
  import { peeledAll } from "../storage/wants.mjs";
18
- import { commitRecord, decodeStats, heldAdd, heldStore, looseRows, readRecord, timeRow, writeRecord } from "../store/repo-record.mjs";
19
- import { afterCommit } from "../store/call-count.mjs";
21
+ import { HeldBy, commitRecord, decodeStats, heldAdd, heldStore, heldUntil, looseRows, readRecord, rootsMoved, rootsOf, timeRow, writeRecord } from "../store/repo-record.mjs";
22
+ import { noRepoRoots } from "../protocol/objects/commit.mjs";
23
+ import { afterCommit, subrequestsLeft } from "../store/call-count.mjs";
20
24
  import { listBound } from "../store/cursor-seal.mjs";
21
25
  import { settleName } from "../store/settle.mjs";
22
26
  import { rowsPut } from "./loose-tally.mjs";
23
- import { collections, looseKey, newChangeId, newInternalId, pushedKey, repoScope, selfKey } from "../store/scopes.mjs";
24
- import { alreadyExists, callerFor, contended, contendedAfterWrites, hiddenCodes, indexJobs, keyedRecord, nameMoved, openKeyed, openRepo, refIndexJobs, repoAccess, sizedRead, statsReads, unlessHidden } from "./access.mjs";
27
+ import { collections, looseKey, newChangeId, newInternalId, pushedKey, repoRootsKey, repoScope, selfKey } from "../store/scopes.mjs";
28
+ import { alreadyExists, callerFor, confirmed, contended, contendedAfterWrites, hiddenCodes, indexDeleteJobs, indexJobs, keyedRecord, nameMoved, openKeyed, openRepo, purgeJobs, refIndexJobs, repoAccess, sizedRead, statsReads, unlessHidden } from "./access.mjs";
29
+ import { asAsked } from "./asked.mjs";
25
30
  import { infoReads, repoInfo } from "./repo-info.mjs";
26
31
  import { kindsOf } from "./ancestry.mjs";
27
32
  import { isHolder } from "./names.mjs";
@@ -35,9 +40,10 @@ import { anyOwned, refViewIn } from "./ref-view.mjs";
35
40
  import { SealedObjects } from "./view.mjs";
36
41
  import { CoreParts, ObjectsParts } from "./parts.mjs";
37
42
  import { check } from "../contracts/authorize.mjs";
38
- import * as Clock$1 from "effect/Clock";
43
+ import * as Clock from "effect/Clock";
39
44
  import * as Effect from "effect/Effect";
40
45
  import { jsonBytes, limits } from "@ref0/infra";
46
+ import * as Context from "effect/Context";
41
47
  // src/core/forks.ts
42
48
  /**
43
49
  * A fork reads its source's refs and packs whole, then copies only the refs its caller sees there
@@ -51,10 +57,25 @@ const packsRead = { collection: collections.packs };
51
57
  const leavingRead = { collection: objectCollections.leaving };
52
58
  const coverRead = { collection: objectCollections.cover };
53
59
  /**
54
- * What a fork reads of its source, after its `self`: refs and packs. Its object rows are read
55
- * apart, a page at a time, by `sourceRows`, and only by a copy.
60
+ * What a fork reads of its source, after its `self`: refs, packs and roots. Its object rows are
61
+ * read apart, a page at a time, by `sourceRows`, and only by a copy.
56
62
  */
57
- const sourceReads = [refsRead, packsRead];
63
+ const sourceReads = [
64
+ refsRead,
65
+ packsRead,
66
+ repoRootsKey
67
+ ];
68
+ /**
69
+ * The fork's roots once a copy of `source` lands on `held`, its own: the source's added, as
70
+ * `rootsMoved` writes them, so no walk from a ref the copy makes readable reads past a commit
71
+ * whose parents the source never held. `undefined` when the fork holds them all already.
72
+ */
73
+ const rootsCopied = (held, source, indexed) => rootsMoved(held, {
74
+ shallow: [...source.roots],
75
+ unshallow: [],
76
+ sent: [...held]
77
+ }, indexed);
78
+ const sourceCounts = [{ collection: objectCollections.objectChunks }];
58
79
  const sourceGone = () => fail("NOT_FOUND", "The fork's source is gone");
59
80
  const cleaningUp = (fork) => fail("UNAVAILABLE", `'${fork}' is cleaning up a pack its source still lists`, { hint: "Try again in a few minutes, once its clean-up has run" });
60
81
  /**
@@ -67,17 +88,20 @@ const cleaningUp = (fork) => fail("UNAVAILABLE", `'${fork}' is cleaning up a pac
67
88
  const forkRead = /* @__PURE__ */ Effect.fnUntraced(function* (store, internalId) {
68
89
  let reconciledAt;
69
90
  for (let attempt = 0; attempt < 5; attempt += 1) {
70
- const { record, snapshot } = yield* readRecord(store, internalId, sourceReads);
91
+ yield* guardAttemptRead(1);
92
+ const { record, snapshot } = yield* readRecord(store, internalId, sourceReads, sourceCounts);
71
93
  if (record === void 0 || record.deleted === true) return yield* sourceGone();
94
+ yield* guardAttemptRead(2);
72
95
  const name = yield* heldNameAt(store, internalId, record, snapshot.version);
73
96
  if (name === "moved") continue;
74
97
  if (name === void 0 && reconciledAt === snapshot.version) return yield* sourceGone();
75
98
  if (name === void 0) {
99
+ yield* guardAttemptRead(2);
76
100
  yield* reconcile(store, internalId);
77
101
  reconciledAt = snapshot.version;
78
102
  continue;
79
103
  }
80
- const [, refs = [], packs = []] = snapshot.results;
104
+ const [, refs = [], packs = [], rootRows] = snapshot.results;
81
105
  return {
82
106
  internalId,
83
107
  record,
@@ -88,54 +112,108 @@ const forkRead = /* @__PURE__ */ Effect.fnUntraced(function* (store, internalId)
88
112
  packs: yield* decodePacks(packs)
89
113
  },
90
114
  refs,
91
- packs
115
+ packs,
116
+ hasChunks: (snapshot.counts[0] ?? 0) > 0,
117
+ roots: yield* rootsOf(rootRows)
92
118
  };
93
119
  }
94
120
  return yield* contended();
95
121
  });
96
122
  const isAlreadyThere = (error) => error.code === "ALREADY_EXISTS";
97
123
  /**
98
- * A cover add to `into`'s scope: a create's goes plainly, its record with it or after it, and an
99
- * existing fork's sync's, with `held`, is a held add, refused NOT_FOUND once the fork is gone, so a
100
- * sync that waited on its source past the fork's purge never makes its scope again (#1911).
124
+ * A create's cover rows, after its opener, as a commit, with no `by` (#1911): a purge's drop resets
125
+ * the scope to 0 and its deletes are commits at a version, so one that lands after them is refused
126
+ * in store order, whatever the clocks say, and on Turso, at a version past 0, makes no database.
127
+ * - One the create goes on from commits at the version its own last commit left, and hands it the
128
+ * version it leaves: a commit of anyone else's between, a purge's above all, refuses it, as it
129
+ * would the create's publishing commit. One that took the version it read instead would hand
130
+ * the create a version past the purge's deletes, and the create's commit would land on them.
131
+ * - One the create ends with, `coverLost`'s, reads the record first and commits at the version it
132
+ * read, again when clean-up's commit moved it between, while the record aside stands: the create
133
+ * never commits after it, so a purge part way waits out its rows as it does any drained row.
134
+ *
135
+ * No other call writes a create's scope, and `markPacks` covers each pack once, so none of its
136
+ * rows is there already.
137
+ */
138
+ const coverCommit = /* @__PURE__ */ Effect.fnUntraced(function* (into, addition, fence) {
139
+ const core = yield* CoreParts;
140
+ const put = addition.put ?? [];
141
+ if (put.length === 0) return;
142
+ const jobs = addition.jobs ?? [];
143
+ const commit = (expect) => storeCommit(core.store.commit(repoScope(into), {
144
+ id: newChangeId(),
145
+ expect,
146
+ put,
147
+ jobs
148
+ }));
149
+ if (fence.kind === "create") {
150
+ const { staged } = fence;
151
+ if (staged.version === void 0) return yield* contended();
152
+ const committed = yield* commit(staged.version);
153
+ if (!committed.ok) return yield* contended();
154
+ staged.version = committed.version;
155
+ return;
156
+ }
157
+ for (let attempt = 0; attempt < 5; attempt += 1) {
158
+ const { record, snapshot } = yield* readRecord(core.store, into);
159
+ if (record?.staged !== true || snapshot.version === 0) return yield* contended();
160
+ if ((yield* commit(snapshot.version)).ok) return;
161
+ }
162
+ return yield* contended();
163
+ });
164
+ /**
165
+ * A cover add to `into`'s scope: a create's is a commit, as `coverCommit` says, and an existing
166
+ * fork's sync's is a held add, refused NOT_FOUND once the fork is gone, so a sync that waited on
167
+ * its source past the fork's purge never makes its scope again (#1911).
101
168
  */
102
- const coverAdd = /* @__PURE__ */ Effect.fnUntraced(function* (into, addition, held) {
169
+ const coverAdd = /* @__PURE__ */ Effect.fnUntraced(function* (into, addition, fence) {
103
170
  const core = yield* CoreParts;
104
- if (held === void 0) return yield* storeCall(() => core.store.add(repoScope(into), addition));
171
+ if (fence.kind !== "sync") return yield* coverCommit(into, addition, fence);
172
+ const { held } = fence;
105
173
  return yield* heldAdd(heldStore(core.store), into, held.fetchLimits, addition).pipe(Effect.catchTag("RepoGone", () => fail("NOT_FOUND", `No repo '${held.fork}'`)));
106
174
  });
107
175
  /**
108
- * Adds, outside the version, a `leaving` row in `into`'s scope for each of `packs`, due at
176
+ * Adds a `leaving` row in `into`'s scope for each of `packs`, due at
109
177
  * `removeAt`, with `git.repack` due then, before their markers are put: so a marker no commit of
110
178
  * the fork claims, one a call that lost, gave up or stopped left, goes with the fork's clean-up
111
- * (#1490). `first`, a create's record, deleted, goes with them, so a fork whose create never
112
- * commits has upkeep to take its rows. The commit that lists a pack deletes its row. A row
113
- * another call of the fork's added first covers its marker as well, so each is added alone then.
179
+ * (#1490). A create's go after its opener, as `openAside` says, so a fork whose create never
180
+ * commits has upkeep to take its rows, and at its version, as `coverCommit` says. A sync's go
181
+ * outside the version. The commit that lists a pack deletes its row. A row another call of the
182
+ * fork's added first refuses a sync's add, so each is added alone then.
183
+ *
184
+ * With them goes a `cover` row of the try's own for each pack, under `tried`: a `leaving` row
185
+ * another call added may come due before the marker lands, and a try that stops before its reread
186
+ * would leave the marker to no row. No take before the add can have reached the try's own row, so
187
+ * whatever point the try stops at, a row names the marker, unless the put outlives the row (#1934).
114
188
  */
115
- const coverMarks = /* @__PURE__ */ Effect.fnUntraced(function* (into, packs, removeAt, first, held) {
189
+ const coverMarks = /* @__PURE__ */ Effect.fnUntraced(function* (into, packs, removeAt, tried, fence) {
116
190
  const core = yield* CoreParts;
117
191
  const leaving = packs.flatMap(({ id, ...size }) => isPackId(id) ? [leavingRow({
118
192
  id,
119
193
  ...size
120
194
  }, removeAt)] : []);
121
- const put = [...first, ...leaving];
195
+ const own = packs.flatMap(({ id, ...size }) => isPackId(id) ? [coverRow({
196
+ id,
197
+ ...size
198
+ }, tried, removeAt)] : []);
199
+ const put = [...leaving, ...own];
122
200
  if (put.length === 0) return;
123
201
  const jobs = [core.repackJobRow(removeAt)];
124
202
  const add = (rows) => coverAdd(into, {
125
203
  put: rows,
126
204
  jobs
127
- }, held);
205
+ }, fence);
128
206
  if (yield* add(put).pipe(Effect.as(true), Effect.catchIf(isAlreadyThere, () => Effect.succeed(false)))) return;
129
207
  const alone = (row) => add([row]).pipe(Effect.catchIf(isAlreadyThere, () => Effect.void));
130
208
  yield* Effect.forEach(put, alone, { discard: true });
131
209
  });
132
210
  /**
133
- * Adds, outside the version, a `cover` row in `into`'s scope for each of `packs`, due at
211
+ * Adds a `cover` row in `into`'s scope for each of `packs`, as `coverMarks` adds its own, due at
134
212
  * `removeAt`, with `git.repack` due then, under a try of its own: a marker a reread found unheld,
135
213
  * which the fork's clean-up then lets go as a `leaving` row's (#1582). The row holds the marker,
136
214
  * never the try, so the try never deletes it.
137
215
  */
138
- const coverLost = /* @__PURE__ */ Effect.fnUntraced(function* (into, packs, removeAt, held) {
216
+ const coverLost = /* @__PURE__ */ Effect.fnUntraced(function* (into, packs, removeAt, fence) {
139
217
  const core = yield* CoreParts;
140
218
  const tried = newChangeId();
141
219
  const put = packs.flatMap(({ id, ...size }) => isPackId(id) ? [coverRow({
@@ -147,31 +225,72 @@ const coverLost = /* @__PURE__ */ Effect.fnUntraced(function* (into, packs, remo
147
225
  yield* coverAdd(into, {
148
226
  put,
149
227
  jobs
150
- }, held);
228
+ }, fence);
229
+ });
230
+ /**
231
+ * A fork create's opener, before it marks a pack or stages a row: its record `aside`, deleted and
232
+ * staged, committed at version 0, with `git.repack` due at `removeAt` and `git.purge` once a sweep
233
+ * may end, so a create that never commits leaves upkeep to let its markers go and a purge to drop
234
+ * the scope with every row it staged. Answers the version it leaves, which the create's commit
235
+ * expects: a drop leaves the scope at 0, so a commit that lands after the purge's is refused in store
236
+ * order and makes nothing again, whatever the clocks say, as the cover rows it puts after are. It
237
+ * carries `removeAt` as its `by` too, so one that stalls in the store never lands after the drop.
238
+ */
239
+ const openAside = /* @__PURE__ */ Effect.fnUntraced(function* (into, aside, removeAt) {
240
+ const core = yield* CoreParts;
241
+ const put = [{
242
+ ...selfKey,
243
+ value: {
244
+ ...aside,
245
+ deleted: true,
246
+ staged: true
247
+ }
248
+ }];
249
+ const jobs = [core.repackJobRow(removeAt), ...purgeJobs(core, removeAt + storeSkew)];
250
+ const opener = {
251
+ id: newChangeId(),
252
+ expect: 0,
253
+ by: removeAt,
254
+ put,
255
+ jobs
256
+ };
257
+ const committed = yield* storeCommit(core.store.commit(repoScope(into), opener));
258
+ if (!committed.ok) return yield* contended();
259
+ return committed.version;
260
+ });
261
+ /** Whether a `leaving` or `cover` row a read found still holds its marker: there, and not taken. */
262
+ const holds = /* @__PURE__ */ Effect.fnUntraced(function* (row) {
263
+ const left = row === void 0 ? void 0 : yield* decodeLeft(row);
264
+ return left !== void 0 && left.value.taken !== true;
151
265
  });
152
266
  /**
153
267
  * Of `packs`, just marked for `into`, those whose marker no row of `into` holds now: the fork
154
- * doesn't list the pack, and its `leaving` row is gone or taken. Clean-up took or ended that row
155
- * before the marker may have landed, so its end may have missed the marker (#1582).
268
+ * doesn't list the pack, and neither its `leaving` row nor the try's own `cover` row, under
269
+ * `tried`, is there untaken. Clean-up took or ended those rows before the marker may have landed,
270
+ * so its end may have missed the marker (#1582).
156
271
  */
157
- const unheldOf = /* @__PURE__ */ Effect.fnUntraced(function* (into, packs) {
272
+ const unheldOf = /* @__PURE__ */ Effect.fnUntraced(function* (into, packs, tried) {
158
273
  const core = yield* CoreParts;
159
- const named = packs.filter(({ id }) => isPackId(id));
274
+ const named = packs.flatMap(({ id }) => isPackId(id) ? [id] : []);
160
275
  if (named.length === 0) return [];
161
- const reads = named.flatMap(({ id }) => [{
162
- collection: collections.packs,
163
- id
164
- }, {
165
- collection: objectCollections.leaving,
166
- id
167
- }]);
168
- const snapshot = yield* storeCall(() => core.store.read(repoScope(into), reads));
276
+ const reads = named.flatMap((id) => [
277
+ {
278
+ collection: collections.packs,
279
+ id
280
+ },
281
+ {
282
+ collection: objectCollections.leaving,
283
+ id
284
+ },
285
+ coverKey(id, tried)
286
+ ]);
287
+ const snapshot = yield* storeCall(core.store.read(repoScope(into), reads));
169
288
  const unheld = [];
170
- for (const [index, pack] of named.entries()) {
171
- const listed = (snapshot.results[2 * index]?.length ?? 0) > 0;
172
- const row = snapshot.results[2 * index + 1]?.[0];
173
- const left = row === void 0 ? void 0 : yield* decodeLeft(row);
174
- if (!listed && (left === void 0 || left.value.taken === true)) unheld.push(pack);
289
+ for (const [index, pack] of packs.filter(({ id }) => isPackId(id)).entries()) {
290
+ const listed = (snapshot.results[3 * index]?.length ?? 0) > 0;
291
+ const left = yield* holds(snapshot.results[3 * index + 1]?.[0]);
292
+ const own = yield* holds(snapshot.results[3 * index + 2]?.[0]);
293
+ if (!listed && !left && !own) unheld.push(pack);
175
294
  }
176
295
  return unheld;
177
296
  });
@@ -179,13 +298,14 @@ const unheldOf = /* @__PURE__ */ Effect.fnUntraced(function* (into, packs) {
179
298
  * Puts a marker named `into` on each pack the source lists that `marked` doesn't hold, then reads
180
299
  * the source again, until a read lists no pack without one: that read is the one a fork commits,
181
300
  * so no pack it lists can lose its bytes to the source's upkeep between the read and the commit.
182
- * `cover` adds each pack's `leaving` row before its marker. After each share, the rows are read
183
- * again: a marker none holds gets a `cover` row and the call fails, keeping the marker (#1582).
301
+ * `cover` adds each pack's `leaving` row and the try's own `cover` row before its marker (#1934).
302
+ * After each share, the rows are read again: a marker none holds gets a `cover` row and the call
303
+ * fails, keeping the marker (#1582).
184
304
  */
185
305
  const markPacks = /* @__PURE__ */ Effect.fnUntraced(function* (first, into, marked, cover, signal) {
186
306
  const core = yield* CoreParts;
187
307
  const { objects: sealed } = yield* ObjectsParts;
188
- const objects = objectsFace(SealedObjects.whole(sealed, forkWhole));
308
+ const objects = SealedObjects.whole(sealed, forkWhole);
189
309
  let read = first;
190
310
  for (let attempt = 0; attempt < 5; attempt += 1) {
191
311
  const unmarked = read.listed.packs.filter((pack) => !marked.has(pack.id));
@@ -200,7 +320,7 @@ const markPacks = /* @__PURE__ */ Effect.fnUntraced(function* (first, into, mark
200
320
  ...read.listed,
201
321
  packs: unmarked
202
322
  }, share);
203
- const unheld = yield* unheldOf(into, unmarked);
323
+ const unheld = yield* unheldOf(into, unmarked, cover.tried);
204
324
  if (unheld.length > 0) return yield* cover.lost(unheld);
205
325
  read = yield* forkRead(core.store, read.internalId);
206
326
  }
@@ -214,7 +334,7 @@ const markPacks = /* @__PURE__ */ Effect.fnUntraced(function* (first, into, mark
214
334
  const walkHoldings = /* @__PURE__ */ Effect.fnUntraced(function* (listed, holdings, walks, signal) {
215
335
  const { objects: sealed } = yield* ObjectsParts;
216
336
  const left = holdings.filter((holding) => !walks.settled.has(holdingKey(holding)));
217
- const { holdings: walk } = objectsFace(SealedObjects.whole(sealed, forkWhole));
337
+ const { holdings: walk } = SealedObjects.whole(sealed, forkWhole);
218
338
  const most = 200 - walks.reads;
219
339
  if (left.length === 0 || walk === void 0 || most <= 0) return;
220
340
  const input = {
@@ -307,8 +427,8 @@ const mib = 1048576;
307
427
  /**
308
428
  * `RESOURCE_EXHAUSTED`, reason `too-large`, for a copy of `source` whose commit `measured` passes
309
429
  * one commit's writes or bytes: it names each it passes, with what was measured, as a lower bound
310
- * when `atLeast`. Every storage copies a fork in one commit; `loose()`'s keeps each object as a
311
- * row of it, which `Objects.layer()` keeps in the bucket.
430
+ * when `atLeast`. Every storage copies a fork's refs and pack list in one commit, with its object
431
+ * rows only while they fit one commit's fast path: past it, `sourceRows` stages them apart.
312
432
  */
313
433
  const refuseCopy = (source, measured) => {
314
434
  const { writes, bytes, room } = measured;
@@ -317,8 +437,7 @@ const refuseCopy = (source, measured) => {
317
437
  const past = [...writes > limits.writes ? [`${takes}${writes} writes${kept(room.writes)}, past one commit's ${limits.writes} writes`] : [], ...bytes > limits.bytes ? [`${takes}${bytes} bytes${kept(room.bytes)}, past one commit's ${limits.bytes / mib} MiB`] : []];
318
438
  if (past.length === 0) return Effect.void;
319
439
  return fail("RESOURCE_EXHAUSTED", `'${source}' is too large to fork: its commit takes ${past.join(", and ")}`, {
320
- hint: "A fork is made in one commit, and this repo's copy doesn't fit one",
321
- hostHint: "A fork is copied in one commit on every storage. With loose() storage, which keeps each object as a row, use Objects.layer(), which keeps objects in the bucket",
440
+ hint: "A fork copies its source's refs, its pack list and the object rows it doesn't stage in one commit, and this repo's don't fit one",
322
441
  context: { reason: "too-large" }
323
442
  });
324
443
  };
@@ -385,40 +504,269 @@ const forkRows = (index, read, objects) => [
385
504
  ...read.packs.map(copied),
386
505
  ...objects
387
506
  ];
507
+ const noopGuard = () => Effect.void;
508
+ /** Per-attempt read guard in fiber context for `forkRead`, `forkTry`, `readSource`, and `markPacks`. */
509
+ const ChunkReadGuard = Context.Reference("@ref0/git/ChunkReadGuard", { defaultValue: () => noopGuard });
510
+ const guardAttemptRead = (readCalls) => Effect.flatMap(Effect.service(ChunkReadGuard), (guard) => guard(readCalls));
511
+ /** Store calls spent between two `subrequestsLeft()` readings (0 when uncounted). */
512
+ const callsSpent = (before, after) => before === Number.POSITIVE_INFINITY ? 0 : Math.max(0, before - after);
513
+ /** A placeholder batch ID of `newBatchId()`'s length for sizing rewritten chunk manifests up front. */
514
+ const previewBatchId = "b_0000000000000000";
515
+ const manifestPreview = (oid, chunked) => chunkedRow(oid, chunked.type, chunked.size, previewBatchId, oid);
516
+ const forkChunksPastBudget = (source, needed, allowed) => fail("RESOURCE_EXHAUSTED", `'${source}' has chunked objects needing ${needed.toLocaleString("en-US")} store calls to copy, past the ${allowed.toLocaleString("en-US")} left in this request's call budget`, {
517
+ hint: "Fork a repo with fewer large files",
518
+ hostHint: "Raise callLimits, or use Objects.layer() storage, which shares a fork's packs in the bucket without copying chunk rows",
519
+ context: {
520
+ reason: "fork-chunks-past-budget",
521
+ needed,
522
+ allowed
523
+ }
524
+ });
525
+ /**
526
+ * Refuses `fork-chunks-past-budget` when `needed` chunk-copy calls exceed what the request's
527
+ * remaining call budget allows beside `reserve` (every remaining store call on this attempt:
528
+ * the guarded read when invoked through `guardRead`, re-reads if preflight ran, opening the batch,
529
+ * staging inline rows and manifests, and the deciding commit).
530
+ */
531
+ const checkChunkBudget = /* @__PURE__ */ Effect.fnUntraced(function* (source, needed, reserve) {
532
+ const left = yield* subrequestsLeft();
533
+ const allowed = left === Number.POSITIVE_INFINITY ? left : Math.max(0, left - reserve);
534
+ if (needed > allowed) return yield* forkChunksPastBudget(source, needed, allowed);
535
+ });
536
+ /**
537
+ * Guards a read costing `readCalls` store calls when chunked objects are known (`needed > 0`).
538
+ * Refuses `fork-chunks-past-budget` before the read can exhaust the generic call limit.
539
+ */
540
+ const guardRead = (budget, readCalls, tailReserve, needed = budget.needed) => needed > 0 ? checkChunkBudget(budget.source, needed, readCalls + tailReserve) : Effect.void;
541
+ /** Per-attempt guard covering caller reads before `sourceRows` and post-copy ref/pack reads. */
542
+ const readGuardOf = (budget, openCalls, commitCalls) => (readCalls) => guardRead(budget, readCalls, openCalls() + budget.inlineCalls + budget.manifestCalls + commitCalls);
543
+ /** Guards every object read in `reads` (ref/ancestry/peel checks on sync) through `guard`. */
544
+ const guardedReads = (reads, guard) => ({
545
+ read: (listed, input) => Effect.andThen(guard(1), reads.read(listed, input)),
546
+ sizes: (listed, input) => Effect.andThen(guard(1), reads.sizes(listed, input)),
547
+ headers: (listed, input) => Effect.andThen(guard(1), reads.headers(listed, input)),
548
+ held: (listed, input) => Effect.andThen(guard(1), reads.held(listed, input)),
549
+ objects: (listed, input) => Effect.andThen(guard(1), reads.objects(listed, input)),
550
+ allotment: reads.allotment
551
+ });
388
552
  /**
389
553
  * The source's object rows at `read`'s version, of those the ones the fork at `lacking` doesn't
390
554
  * hold when it's given, a page at a time through the objects' `copyRows`, so no read passes one
391
- * answer's 16 MiB and only the copy is held: refused once those pass one commit's, as `checkCopy`
392
- * refuses. `undefined` once a page answers `moved`: the read is taken again.
555
+ * answer's 16 MiB: held while they fit one commit's fast path, and past it staged through `stage`
556
+ * in a batch of the fork's, as a push's are, with every page after, so only a page is held.
557
+ * Before opening a destination batch or copying any chunk, any pending chunked objects are
558
+ * checked against the request's remaining call budget (`fork-chunks-past-budget`), including a
559
+ * preflight scan of remaining pages when a mixed source crosses the fast path mid-enumeration, so
560
+ * a first-try refusal opens no scope and stages nothing. Preflight's complete chunk, manifest, and
561
+ * inline-stage costs are kept in `stage.budget` through replay and across retries, and every
562
+ * enumeration and preflight scan page passes through `guardRead` so no source read can exhaust the
563
+ * generic call limit. A retry refusal leaves any aside scope/batch opened on the first try to
564
+ * `openAside`'s `git.repack`/`git.purge` jobs (or `git.repack`'s batch quarantine sweep on
565
+ * sync/fetch). `undefined` once a page or chunk read answers `moved`: the read is taken again.
393
566
  */
394
- const sourceRows = /* @__PURE__ */ Effect.fnUntraced(function* (read, lacking, signal) {
567
+ const sourceRows = /* @__PURE__ */ Effect.fnUntraced(function* (read, lacking, stage, signal) {
568
+ const core = yield* CoreParts;
395
569
  const { objects: sealed } = yield* ObjectsParts;
396
- const { copyRows } = objectsFace(SealedObjects.whole(sealed, forkWhole));
570
+ const { copyRows } = SealedObjects.whole(sealed, forkWhole);
397
571
  if (copyRows === void 0) return yield* noCopyRows(read.name);
398
- const rows = [];
399
- let bytes = 0;
400
- let after;
401
- for (;;) {
572
+ const pageInput = (cursor) => {
402
573
  const input = {};
403
- if (after !== void 0) input.after = after;
574
+ if (cursor !== void 0) input.after = cursor;
404
575
  if (lacking !== void 0) input.lacking = {
405
576
  repo: lacking.internalId,
406
577
  version: lacking.version
407
578
  };
408
579
  if (signal !== void 0) input.signal = signal;
409
- const page = yield* copyRows(read.listed, input);
410
- if ("moved" in page) return void 0;
411
- if (page.rows.length > 0) bytes += jsonBytes(page.rows) - (rows.length > 0 ? 1 : 0);
412
- rows.push(...page.rows);
413
- yield* refuseCopy(read.name, {
414
- writes: rows.length + copyRoom.writes,
415
- bytes: bytes + copyRoom.bytes,
416
- room: copyRoom,
417
- atLeast: true
418
- });
419
- if (page.next === void 0) return rows;
580
+ return input;
581
+ };
582
+ const store = gitStore(core.store);
583
+ const { budget } = stage;
584
+ budget.source = read.name;
585
+ const rows = [];
586
+ const pendingChunks = [];
587
+ const seen = /* @__PURE__ */ new Set();
588
+ const bufferedCounter = stageRowsCounter();
589
+ let bufferedCounted = 0;
590
+ const bufferedInlineCalls = () => {
591
+ while (bufferedCounted < rows.length) {
592
+ const row = rows[bufferedCounted];
593
+ bufferedCounted += 1;
594
+ if (row !== void 0) bufferedCounter.add(row);
595
+ }
596
+ return bufferedCounter.calls();
597
+ };
598
+ const manifestCounter = stageRowsCounter();
599
+ let bytes = 0;
600
+ let chunkCallsNeeded = 0;
601
+ let inlineStageCalls = 0;
602
+ let staged;
603
+ let after;
604
+ let preflighted = false;
605
+ const rememberCosts = (needed, inlineCalls, manifestCalls) => {
606
+ if (needed <= 0) return;
607
+ budget.needed = Math.max(budget.needed, needed);
608
+ budget.inlineCalls = Math.max(budget.inlineCalls, inlineCalls);
609
+ budget.manifestCalls = Math.max(budget.manifestCalls, manifestCalls);
610
+ };
611
+ for (;;) {
612
+ const knownNeeded = Math.max(budget.needed, chunkCallsNeeded);
613
+ if (knownNeeded > 0) {
614
+ const knownManifestCalls = Math.max(budget.manifestCalls, manifestCounter.calls());
615
+ const pageTail = staged === void 0 ? stage.openCalls() + Math.max(budget.inlineCalls, bufferedInlineCalls()) + knownManifestCalls + stage.commitCalls : Math.max(0, budget.inlineCalls - inlineStageCalls) + knownManifestCalls + stage.commitCalls;
616
+ yield* guardRead(budget, 1, pageTail, knownNeeded);
617
+ }
618
+ const page = yield* copyRows(read.listed, pageInput(after));
619
+ if ("moved" in page) {
620
+ if (chunkCallsNeeded > 0) rememberCosts(chunkCallsNeeded, inlineStageCalls + (staged === void 0 ? bufferedInlineCalls() : 0), manifestCounter.calls());
621
+ return;
622
+ }
623
+ const fresh = page.rows.filter(({ id }) => !seen.has(id));
624
+ for (const { id } of fresh) seen.add(id);
625
+ const inline = [];
626
+ for (const row of fresh) {
627
+ const chunked = chunkedOf(row.value);
628
+ if (chunked === void 0) inline.push(row);
629
+ else {
630
+ pendingChunks.push({
631
+ oid: row.id,
632
+ chunked
633
+ });
634
+ chunkCallsNeeded += chunkCopyCalls(chunked);
635
+ manifestCounter.add(manifestPreview(row.id, chunked));
636
+ }
637
+ }
638
+ if (staged === void 0) {
639
+ rows.push(...inline);
640
+ bytes += inline.reduce((sum, row) => sum + stagedBytes(row), 0);
641
+ } else if (inline.length > 0) {
642
+ yield* stageRows(store, stage.repo, staged.batch, inline);
643
+ if (read.hasChunks || budget.needed > 0 || chunkCallsNeeded > 0) inlineStageCalls += stageRowsCalls(inline);
644
+ const more = rowsPut(inline);
645
+ staged = {
646
+ batch: staged.batch,
647
+ moved: {
648
+ objects: staged.moved.objects + more.objects,
649
+ bytes: staged.moved.bytes + more.bytes
650
+ }
651
+ };
652
+ }
653
+ if (page.next === void 0) break;
654
+ if (staged === void 0 && (rows.length > fastPath.rows || bytes > fastPath.bytes)) {
655
+ if (read.hasChunks && !preflighted) {
656
+ const beforeScan = yield* subrequestsLeft();
657
+ const scanSeen = new Set(seen);
658
+ const scanManifestCounter = manifestCounter.clone();
659
+ const firstInlineCalls = bufferedInlineCalls();
660
+ let scanChunkCalls = chunkCallsNeeded;
661
+ let remainingInlineStageCalls = 0;
662
+ let scanAfter = page.next;
663
+ while (scanAfter !== void 0) {
664
+ const scanNeeded = Math.max(budget.needed, scanChunkCalls);
665
+ if (scanNeeded > 0) {
666
+ const scanInlineCalls = Math.max(budget.inlineCalls, firstInlineCalls + remainingInlineStageCalls);
667
+ const scanManifestCalls = Math.max(budget.manifestCalls, scanManifestCounter.calls());
668
+ yield* guardRead(budget, 1, stage.openCalls() + scanInlineCalls + scanManifestCalls + stage.commitCalls, scanNeeded);
669
+ }
670
+ const scanPage = yield* copyRows(read.listed, pageInput(scanAfter));
671
+ if ("moved" in scanPage) {
672
+ if (scanChunkCalls > 0) rememberCosts(scanChunkCalls, firstInlineCalls + remainingInlineStageCalls, scanManifestCounter.calls());
673
+ return;
674
+ }
675
+ const scanFresh = scanPage.rows.filter(({ id }) => !scanSeen.has(id));
676
+ const scanInline = [];
677
+ for (const row of scanFresh) {
678
+ scanSeen.add(row.id);
679
+ const chunked = chunkedOf(row.value);
680
+ if (chunked === void 0) scanInline.push(row);
681
+ else {
682
+ scanChunkCalls += chunkCopyCalls(chunked);
683
+ scanManifestCounter.add(manifestPreview(row.id, chunked));
684
+ }
685
+ }
686
+ remainingInlineStageCalls += stageRowsCalls(scanInline);
687
+ scanAfter = scanPage.next;
688
+ }
689
+ const rereadCalls = callsSpent(beforeScan, yield* subrequestsLeft());
690
+ if (scanChunkCalls > 0) {
691
+ const scanInlineCalls = firstInlineCalls + remainingInlineStageCalls;
692
+ const scanManifestCalls = scanManifestCounter.calls();
693
+ budget.needed = scanChunkCalls;
694
+ budget.inlineCalls = scanInlineCalls;
695
+ budget.manifestCalls = scanManifestCalls;
696
+ const reserve = rereadCalls + stage.openCalls() + scanInlineCalls + scanManifestCalls + stage.commitCalls;
697
+ yield* checkChunkBudget(read.name, scanChunkCalls, reserve);
698
+ }
699
+ preflighted = true;
700
+ }
701
+ const batch = yield* stage.open();
702
+ yield* stageRows(store, stage.repo, batch, rows);
703
+ if (read.hasChunks || budget.needed > 0 || chunkCallsNeeded > 0) inlineStageCalls += bufferedInlineCalls();
704
+ staged = {
705
+ batch,
706
+ moved: rowsPut(rows)
707
+ };
708
+ rows.length = 0;
709
+ }
420
710
  after = page.next;
421
711
  }
712
+ if (pendingChunks.length > 0) {
713
+ const manifestStageCalls = manifestCounter.calls();
714
+ const bufferedCalls = staged === void 0 ? bufferedInlineCalls() : 0;
715
+ const openAndInlineCalls = staged === void 0 ? stage.openCalls() + bufferedCalls : 0;
716
+ budget.needed = chunkCallsNeeded;
717
+ budget.inlineCalls = inlineStageCalls + bufferedCalls;
718
+ budget.manifestCalls = manifestStageCalls;
719
+ const reserve = openAndInlineCalls + manifestStageCalls + stage.commitCalls;
720
+ yield* checkChunkBudget(read.name, chunkCallsNeeded, reserve);
721
+ if (staged === void 0) {
722
+ const batch = yield* stage.open();
723
+ if (rows.length > 0) {
724
+ yield* stageRows(store, stage.repo, batch, rows);
725
+ inlineStageCalls += bufferedCalls;
726
+ }
727
+ staged = {
728
+ batch,
729
+ moved: rowsPut(rows)
730
+ };
731
+ rows.length = 0;
732
+ }
733
+ const manifests = [];
734
+ let extraObjects = 0;
735
+ let extraBytes = 0;
736
+ for (const { oid, chunked } of pendingChunks) {
737
+ if (!(yield* copyChunks(store, read.listed, stage.repo, staged.batch, oid, chunked))) return void 0;
738
+ const manifest = chunkedRow(oid, chunked.type, chunked.size, staged.batch.batch, oid);
739
+ manifests.push(manifest);
740
+ const counted = chunkedMoved(manifest.value);
741
+ extraObjects += counted.objects;
742
+ extraBytes += counted.bytes;
743
+ }
744
+ yield* stageRows(store, stage.repo, staged.batch, manifests);
745
+ staged = {
746
+ batch: staged.batch,
747
+ moved: {
748
+ objects: staged.moved.objects + extraObjects,
749
+ bytes: staged.moved.bytes + extraBytes
750
+ }
751
+ };
752
+ } else {
753
+ budget.needed = 0;
754
+ budget.inlineCalls = 0;
755
+ budget.manifestCalls = 0;
756
+ if (staged === void 0 && (rows.length > fastPath.rows || bytes > fastPath.bytes)) {
757
+ const batch = yield* stage.open();
758
+ yield* stageRows(store, stage.repo, batch, rows);
759
+ staged = {
760
+ batch,
761
+ moved: rowsPut(rows)
762
+ };
763
+ rows.length = 0;
764
+ }
765
+ }
766
+ return {
767
+ rows,
768
+ staged
769
+ };
422
770
  });
423
771
  /** A fork's record, from its source's read: its branch and visibility, and what it's made from. */
424
772
  const forkRecord = (read, name, revision, holder, at, index) => {
@@ -579,6 +927,17 @@ const forkCalls = (bound) => {
579
927
  });
580
928
  /** `create`'s steps, which share the source's packs into `marked` as they go. */
581
929
  const createMarking = Effect.fnUntraced(function* (marked, repo, input) {
930
+ const held = { version: void 0 };
931
+ const openCalls = () => held.version === void 0 ? 3 : 2;
932
+ const budget = {
933
+ source: repo,
934
+ needed: 0,
935
+ inlineCalls: 0,
936
+ manifestCalls: 0
937
+ };
938
+ return yield* Effect.provideService(createWithBudget(marked, held, openCalls, budget, repo, input), ChunkReadGuard, readGuardOf(budget, openCalls, 2));
939
+ });
940
+ const createWithBudget = Effect.fnUntraced(function* (marked, held, openCalls, budget, repo, input) {
582
941
  const core = yield* CoreParts;
583
942
  const { store } = core;
584
943
  const { fetchLimits } = yield* ObjectsParts;
@@ -601,7 +960,7 @@ const forkCalls = (bound) => {
601
960
  repo: id
602
961
  }
603
962
  });
604
- const at = yield* Clock$1.currentTimeMillis;
963
+ const at = yield* Clock.currentTimeMillis;
605
964
  const kept = yield* keptKey(caller, input.key, [
606
965
  "fork",
607
966
  source,
@@ -628,46 +987,69 @@ const forkCalls = (bound) => {
628
987
  yield* authorizeRecord(caller, source, forkingName, gone);
629
988
  let taken;
630
989
  const removeAt = at + Math.max(pruneFloor, fetchLimits.milliseconds);
631
- let asideFirst = true;
990
+ const tried = newChangeId();
991
+ const open = Effect.fnUntraced(function* (read) {
992
+ if (held.version !== void 0) return;
993
+ const aside = forkRecord(read, id, revision, holder, at, core.refIndex);
994
+ held.version = yield* openAside(internalId, aside, removeAt);
995
+ });
996
+ const batches = [];
997
+ budget.source = opened.name;
998
+ const stage = (read) => ({
999
+ repo: internalId,
1000
+ open: Effect.fnUntraced(function* () {
1001
+ yield* open(read);
1002
+ const batch = yield* openBatch({
1003
+ store: gitStore(store),
1004
+ repo: internalId,
1005
+ at,
1006
+ removeAt
1007
+ });
1008
+ batches.push(batch);
1009
+ return batch;
1010
+ }),
1011
+ openCalls,
1012
+ commitCalls: 2,
1013
+ budget
1014
+ });
632
1015
  const cover = (read) => ({
633
- add: (packs) => {
634
- const aside = {
635
- ...forkRecord(read, id, revision, holder, at, core.refIndex),
636
- deleted: true
637
- };
638
- const first = asideFirst ? [{
639
- ...selfKey,
640
- value: aside
641
- }] : [];
642
- asideFirst = false;
643
- return coverMarks(internalId, packs, removeAt, first, void 0);
644
- },
645
- lost: (packs) => Effect.andThen(coverLost(internalId, packs, removeAt, void 0), () => cleaningUp(repo))
1016
+ tried,
1017
+ add: (packs) => Effect.andThen(open(read), coverMarks(internalId, packs, removeAt, tried, {
1018
+ kind: "create",
1019
+ staged: held
1020
+ })),
1021
+ lost: (packs) => Effect.andThen(coverLost(internalId, packs, removeAt, { kind: "ending" }), () => cleaningUp(repo))
646
1022
  });
647
1023
  for (let attempt = 0; taken === void 0 && attempt < 5; attempt += 1) {
648
1024
  const first = yield* sourceSized(forkRead(store, source), caller, source, forkingName, gone);
649
1025
  yield* authorizeSource(caller, first, forking(first), gone);
650
- const firstRows = yield* sourceRows(first, void 0, input.signal);
651
- if (firstRows === void 0) continue;
652
- yield* checkCopy(opened.name, forkRows(core.refIndex, first, firstRows));
1026
+ const firstCopy = yield* sourceRows(first, void 0, stage(first), input.signal);
1027
+ if (firstCopy === void 0) continue;
1028
+ yield* checkCopy(opened.name, forkRows(core.refIndex, first, firstCopy.rows));
653
1029
  const checked = yield* sourceSized(markPacks(first, internalId, marked, cover(first), input.signal), caller, source, forkingName, gone);
654
1030
  yield* authorizeSource(caller, checked, forking(checked), gone);
655
- const objects = checked.listed.version === first.listed.version ? firstRows : yield* sourceRows(checked, void 0, input.signal);
656
- if (objects !== void 0) taken = {
1031
+ const copied = checked.listed.version === first.listed.version ? firstCopy : yield* sourceRows(checked, void 0, stage(checked), input.signal);
1032
+ if (copied !== void 0) taken = {
657
1033
  read: checked,
658
- objects
1034
+ copied
659
1035
  };
660
1036
  }
661
1037
  if (taken === void 0) return yield* contended();
662
- const { objects } = taken;
1038
+ const { rows: objects, staged } = taken.copied;
663
1039
  const read = unpublished(core.publishedRefs(), yield* seenSource(caller, taken.read));
664
1040
  const record = forkRecord(read, id, revision, holder, at, core.refIndex);
665
1041
  const listing = new Set(read.listed.packs.map((pack) => pack.id));
666
- const covered = read.listed.packs.flatMap(({ id }) => isPackId(id) ? [leavingKey(id)] : []);
1042
+ const covered = [...read.listed.packs.flatMap(({ id }) => isPackId(id) ? [leavingKey(id)] : []), ...[...marked.keys()].flatMap((id) => isPackId(id) ? [coverKey(id, tried)] : [])];
667
1043
  const pushed = read.refs.length === 0 ? [] : [timeRow(pushedKey, void 0, at)];
668
- const loose = looseRows(void 0, rowsPut(objects));
1044
+ const loose = looseRows(void 0, staged?.moved ?? rowsPut(objects));
1045
+ const published = staged === void 0 ? [] : publication(staged.batch, [], staged.moved, at).put ?? [];
1046
+ const abandoned = batches.flatMap((batch) => batch === staged?.batch ? [] : [abandonedRow(batch)]);
1047
+ const rooted = yield* rootsCopied(noRepoRoots, read, []);
669
1048
  const rows = [
670
1049
  ...forkRows(core.refIndex, read, objects),
1050
+ ...rooted?.put ?? [],
1051
+ ...published,
1052
+ ...abandoned,
671
1053
  ...pushed,
672
1054
  ...loose,
673
1055
  ...unlisted(marked, listing, at)
@@ -695,6 +1077,7 @@ const forkCalls = (bound) => {
695
1077
  ...receipt.put,
696
1078
  ...appended.put
697
1079
  ];
1080
+ const ended = staged === void 0 ? covered : [...covered, staged.batch.quarantine];
698
1081
  const indexing = read.refs.length === 0 ? [] : indexJobs(core, { state: "unbuilt" });
699
1082
  const jobs = withJobs([
700
1083
  core.repackJobRow(),
@@ -707,21 +1090,25 @@ const forkCalls = (bound) => {
707
1090
  };
708
1091
  yield* checkChange(opened.name, {
709
1092
  put,
710
- delete: covered,
1093
+ delete: ended,
711
1094
  jobs
712
1095
  }, room);
713
- const written = yield* writeRecord(store, internalId, {
714
- expect: 0,
1096
+ const change = {
1097
+ expect: held.version ?? 0,
715
1098
  record,
716
1099
  put,
717
- delete: covered,
1100
+ delete: ended,
718
1101
  jobs
719
- });
1102
+ };
1103
+ const written = yield* writeRecord(store, internalId, change);
720
1104
  if (written === void 0) return yield* contended();
721
1105
  if (written.outcome === "won") return yield* afterCommit(repoInfo(caller, internalId, record, [
722
1106
  read.refs,
723
1107
  read.packs,
724
- [...pushed, ...loose]
1108
+ [...pushed, ...loose],
1109
+ [],
1110
+ [],
1111
+ rooted?.put ?? []
725
1112
  ]));
726
1113
  const dropped = dropUnconfirmed(appended.head);
727
1114
  const aside = commitRecord(store, internalId, {
@@ -731,7 +1118,13 @@ const forkCalls = (bound) => {
731
1118
  deleted: true
732
1119
  },
733
1120
  put: dropped.put,
734
- delete: [...receiptKeys(kept), ...dropped.delete]
1121
+ delete: [...receiptKeys(kept), ...dropped.delete],
1122
+ jobs: [
1123
+ core.repackJobRow(),
1124
+ pruneJobRow(at),
1125
+ ...indexDeleteJobs(core),
1126
+ ...purgeJobs(core, at)
1127
+ ]
735
1128
  });
736
1129
  const after = Effect.andThen(aside, holdersFork(caller, opened.name, source, holder));
737
1130
  const theirs = yield* afterCommit(after);
@@ -843,7 +1236,7 @@ const forkCalls = (bound) => {
843
1236
  const opened = yield* openKeyed(caller, {
844
1237
  kind: "read",
845
1238
  repo: fork
846
- }, [], keyed, internalId);
1239
+ }, [], keyed, internalId, "first-read");
847
1240
  if (opened !== void 0) return {
848
1241
  kind: "opened",
849
1242
  opened
@@ -854,9 +1247,10 @@ const forkCalls = (bound) => {
854
1247
  /**
855
1248
  * One try's read of the fork opened as `fork`: its record and rows, settled and named as the
856
1249
  * catalogue names it now, with `may` asked of `authorize` under that name. `undefined` when the
857
- * try must read again.
1250
+ * try must read again. With `asked`, the open's confirm is on this read, as `asAsked` says: the
1251
+ * first try's, after an open with `first-read`.
858
1252
  */
859
- const forkTry = Effect.fnUntraced(function* (fork, caller, internalId, kept, may) {
1253
+ const forkTry = Effect.fnUntraced(function* (fork, caller, internalId, kept, may, asked) {
860
1254
  const core = yield* CoreParts;
861
1255
  const { store } = core;
862
1256
  const reads = [
@@ -865,13 +1259,15 @@ const forkCalls = (bound) => {
865
1259
  coverRead,
866
1260
  indexRowKey,
867
1261
  apartKey,
868
- swapsKey
1262
+ swapsKey,
1263
+ repoRootsKey
869
1264
  ];
870
1265
  const hiddenFork = () => fail("NOT_FOUND", `No repo '${fork}'`);
871
1266
  const fence = core.fences(caller, {
872
1267
  internalId,
873
1268
  name: fork
874
1269
  });
1270
+ yield* guardAttemptRead(1);
875
1271
  const { record, snapshot } = yield* sourceSized(readRecord(store, internalId, [
876
1272
  ...reads,
877
1273
  ...outboxReads,
@@ -881,8 +1277,9 @@ const forkCalls = (bound) => {
881
1277
  kind: "read",
882
1278
  repo: name
883
1279
  }), hiddenFork);
1280
+ if (asked !== void 0) yield* asAsked(asked, record);
884
1281
  if (record === void 0 || record.deleted === true) return yield* fail("NOT_FOUND", `No repo '${fork}'`);
885
- const [, refRows = [], packRows = [], timeRows = [], readyRows = [], leavingRows = [], coverRows = [], indexRows = [], apartRows = [], swapsRows = []] = snapshot.results;
1282
+ const [, refRows = [], packRows = [], timeRows = [], readyRows = [], leavingRows = [], coverRows = [], indexRows = [], apartRows = [], swapsRows = [], rootRows = []] = snapshot.results;
886
1283
  const [headRows = [], cursorRows = [], ...afterOutbox] = snapshot.results.slice(1 + reads.length);
887
1284
  const keyed = receiptReads(kept).length;
888
1285
  yield* fence.check(afterOutbox.slice(keyed));
@@ -892,10 +1289,13 @@ const forkCalls = (bound) => {
892
1289
  head: outbox.head,
893
1290
  record
894
1291
  };
1292
+ yield* guardAttemptRead(1);
895
1293
  if (yield* settleName(store, repoScope(internalId), settling)) return void 0;
1294
+ yield* guardAttemptRead(2);
896
1295
  const name = yield* heldNameAt(store, internalId, record, snapshot.version);
897
1296
  if (name === "moved") return void 0;
898
1297
  if (name === void 0) {
1298
+ yield* guardAttemptRead(2);
899
1299
  yield* reconcile(store, internalId);
900
1300
  return;
901
1301
  }
@@ -927,6 +1327,7 @@ const forkCalls = (bound) => {
927
1327
  coverRows,
928
1328
  apartRows,
929
1329
  swapsRows,
1330
+ rootRows,
930
1331
  indexRow: indexRows[0]
931
1332
  },
932
1333
  receipts: afterOutbox.slice(0, keyed)
@@ -942,6 +1343,7 @@ const forkCalls = (bound) => {
942
1343
  kind: "read",
943
1344
  repo: name
944
1345
  });
1346
+ yield* guardAttemptRead(3);
945
1347
  yield* authorizeRecord(caller, upstream, readingName, sourceGone);
946
1348
  const first = yield* sourceSized(forkRead(store, upstream), caller, upstream, readingName, sourceGone);
947
1349
  yield* authorizeSource(caller, first, readingName(first.name), sourceGone);
@@ -952,9 +1354,10 @@ const forkCalls = (bound) => {
952
1354
  * commit takes, with the checked read it's from: each pack marked for the fork, then read again
953
1355
  * until a read lists none without one. `checked` decides that read, or `undefined` reads again.
954
1356
  */
955
- const copyInto = Effect.fnUntraced(function* (caller, fork, into, first, checked, signal) {
1357
+ const copyInto = Effect.fnUntraced(function* (caller, fork, into, first, checked, signal, budget) {
1358
+ const core = yield* CoreParts;
956
1359
  const { fetchLimits } = yield* ObjectsParts;
957
- const { listing, rows, marked, shared } = into;
1360
+ const { listing, rows, marked, shared, batches } = into;
958
1361
  const held = yield* Effect.forEach([...rows.leavingRows, ...rows.coverRows], decodeLeft);
959
1362
  const relistedOf = (packs) => {
960
1363
  const ids = new Set(packs.flatMap(({ id }) => listing.has(id) ? [] : [id]));
@@ -962,17 +1365,39 @@ const forkCalls = (bound) => {
962
1365
  };
963
1366
  const due = (packs) => relistedOf(packs).some(({ value }) => value.taken === true);
964
1367
  if (due(first.listed.packs)) return yield* cleaningUp(fork);
965
- const firstRows = yield* sourceRows(first, into, signal);
966
- if (firstRows === void 0) return void 0;
1368
+ const store = gitStore(core.store);
1369
+ const stage = {
1370
+ repo: into.internalId,
1371
+ open: Effect.fnUntraced(function* () {
1372
+ const batch = yield* openBatch({
1373
+ store,
1374
+ repo: into.internalId,
1375
+ at: into.at
1376
+ });
1377
+ batches.push(batch);
1378
+ return batch;
1379
+ }),
1380
+ openCalls: () => 2,
1381
+ commitCalls: 2,
1382
+ budget
1383
+ };
1384
+ const copyRows = (source) => Effect.provideService(sourceRows(source, into, stage, signal), HeldBy, heldUntil(into.at, fetchLimits));
1385
+ const firstCopy = yield* copyRows(first);
1386
+ if (firstCopy === void 0) return void 0;
967
1387
  const addedRows = first.packs.filter(({ id }) => !listing.has(id));
968
- yield* checkCopy(first.name, [...firstRows, ...addedRows]);
1388
+ yield* checkCopy(first.name, [...firstCopy.rows, ...addedRows]);
969
1389
  const removeAt = into.at + Math.max(pruneFloor, fetchLimits.milliseconds);
970
1390
  const syncHeld = {
971
- fetchLimits,
972
- fork
1391
+ kind: "sync",
1392
+ held: {
1393
+ fetchLimits,
1394
+ fork
1395
+ }
973
1396
  };
1397
+ const tried = newChangeId();
974
1398
  const cover = {
975
- add: (packs) => coverMarks(into.internalId, packs, removeAt, [], syncHeld),
1399
+ tried,
1400
+ add: (packs) => coverMarks(into.internalId, packs, removeAt, tried, syncHeld),
976
1401
  lost: (packs) => Effect.andThen(coverLost(into.internalId, packs, removeAt, syncHeld), () => cleaningUp(fork))
977
1402
  };
978
1403
  const readingName = (name) => ({
@@ -984,8 +1409,20 @@ const forkCalls = (bound) => {
984
1409
  const source = yield* seenSource(caller, marking);
985
1410
  for (const [id, pack] of marked) if (!listing.has(id)) shared.set(id, pack);
986
1411
  if (!(yield* checked(source))) return void 0;
987
- const lacked = source.listed.version === first.listed.version ? firstRows : yield* sourceRows(source, into, signal);
988
- if (lacked === void 0) return void 0;
1412
+ const copied = source.listed.version === first.listed.version ? firstCopy : yield* copyRows(source);
1413
+ if (copied === void 0) return void 0;
1414
+ const { rows: lacked, staged } = copied;
1415
+ if (staged !== void 0) {
1416
+ const counted = yield* store.read({
1417
+ scope: repoScope(into.internalId),
1418
+ reads: [batchesRead]
1419
+ });
1420
+ if (counted.version !== into.version) return void 0;
1421
+ const held = counted.results[0]?.length ?? 0;
1422
+ if (held >= 16) return yield* Effect.fail(awaitingUpkeep(held, 16));
1423
+ }
1424
+ const published = staged === void 0 ? [] : publication(staged.batch, [], staged.moved, into.at).put ?? [];
1425
+ const abandoned = batches.flatMap((batch) => batch === staged?.batch ? [] : [abandonedRow(batch)]);
989
1426
  const addable = source.listed.packs.filter(({ id }) => !listing.has(id));
990
1427
  const weighed = [...into.owned, ...addable];
991
1428
  const holdings = holdingsOf(weighed);
@@ -1029,6 +1466,8 @@ const forkCalls = (bound) => {
1029
1466
  remove,
1030
1467
  put: [
1031
1468
  ...lacked,
1469
+ ...published,
1470
+ ...abandoned,
1032
1471
  ...unlisted(shared, covered, into.at),
1033
1472
  ...swapped,
1034
1473
  ...apartAfter(found, {
@@ -1037,8 +1476,13 @@ const forkCalls = (bound) => {
1037
1476
  }),
1038
1477
  ...swapsAfter(/* @__PURE__ */ new Set([...kept, ...source.listed.packs.map(({ id }) => id)]), swapsBefore, into.walks)
1039
1478
  ],
1040
- delete: [...added.flatMap(({ id }) => isPackId(id) ? [leavingKey(id)] : []), ...held.flatMap(({ key, pack }) => key.collection === objectCollections.cover && adding.has(pack) ? [key] : [])],
1041
- rows: rowsPut(lacked)
1479
+ delete: [
1480
+ ...added.flatMap(({ id }) => isPackId(id) ? [leavingKey(id)] : []),
1481
+ ...[...marked.keys()].flatMap((id) => !listing.has(id) && isPackId(id) ? [coverKey(id, tried)] : []),
1482
+ ...held.flatMap(({ key, pack }) => key.collection === objectCollections.cover && adding.has(pack) ? [key] : []),
1483
+ ...staged === void 0 ? [] : [staged.batch.quarantine]
1484
+ ],
1485
+ rows: staged?.moved ?? rowsPut(lacked)
1042
1486
  },
1043
1487
  bytes: added.reduce((sum, pack) => sum + pack.bytes, 0),
1044
1488
  objects: added.reduce((sum, pack) => sum + pack.objects, 0),
@@ -1046,326 +1490,378 @@ const forkCalls = (bound) => {
1046
1490
  }
1047
1491
  };
1048
1492
  });
1049
- return {
1050
- create,
1051
- get,
1052
- list,
1053
- sync: Effect.fnUntraced(function* (fork, input) {
1054
- const core = yield* CoreParts;
1055
- const { objects: sealed } = yield* ObjectsParts;
1056
- const { store } = core;
1057
- const caller = callerOf(input);
1058
- const started = yield* Clock$1.currentTimeMillis;
1059
- const kept = yield* keptKey(caller, input.key, ["fork.sync", fork], started);
1060
- const looked = yield* openSync(fork, caller, kept, input.internalId);
1061
- if (looked.kind === "answered") return yield* repoAnswer(looked.receipt);
1062
- const { opened } = looked;
1063
- const of = opened.record.fork;
1064
- if (of === void 0) return yield* notAFork(fork);
1065
- const { internalId } = opened;
1066
- const objects = objectsFace(SealedObjects.whole(sealed, forkWhole));
1067
- const reads = oneShotReads(objects);
1068
- const scope = repoScope(internalId);
1069
- const shared = /* @__PURE__ */ new Map();
1070
- const walks = {
1071
- settled: /* @__PURE__ */ new Map(),
1072
- reads: 0
1493
+ const sync = (fork, input) => {
1494
+ const budget = {
1495
+ source: "",
1496
+ needed: 0,
1497
+ inlineCalls: 0,
1498
+ manifestCalls: 0
1499
+ };
1500
+ const guard = readGuardOf(budget, () => 2, 2);
1501
+ return Effect.provideService(syncWithBudget(budget, guard, fork, input), ChunkReadGuard, guard);
1502
+ };
1503
+ const syncWithBudget = Effect.fnUntraced(function* (budget, guard, fork, input) {
1504
+ const core = yield* CoreParts;
1505
+ const { objects: sealed } = yield* ObjectsParts;
1506
+ const { store } = core;
1507
+ const caller = callerOf(input);
1508
+ const started = yield* Clock.currentTimeMillis;
1509
+ const kept = yield* keptKey(caller, input.key, ["fork.sync", fork], started);
1510
+ const looked = yield* openSync(fork, caller, kept, input.internalId);
1511
+ if (looked.kind === "answered") return yield* repoAnswer(looked.receipt);
1512
+ const { opened } = looked;
1513
+ const of = opened.record.fork;
1514
+ if (of === void 0) return yield* Effect.andThen(confirmed(opened), notAFork(fork));
1515
+ const { internalId } = opened;
1516
+ const objects = SealedObjects.whole(sealed, forkWhole);
1517
+ const reads = guardedReads(oneShotReads(objects), guard);
1518
+ const scope = repoScope(internalId);
1519
+ const shared = /* @__PURE__ */ new Map();
1520
+ const batches = [];
1521
+ const walks = {
1522
+ settled: /* @__PURE__ */ new Map(),
1523
+ reads: 0
1524
+ };
1525
+ const signal = input.signal === void 0 ? {} : { signal: input.signal };
1526
+ for (let attempt = 0; attempt < 5; attempt += 1) {
1527
+ const at = yield* Clock.currentTimeMillis;
1528
+ const read = yield* forkTry(fork, caller, internalId, kept, (target, record) => authorizeSync(caller, target, record), attempt === 0 ? opened : void 0);
1529
+ if (read === void 0) continue;
1530
+ const { record, snapshot, name, outbox, rows } = read;
1531
+ const { refRows, packRows, timeRows, readyRows, leavingRows } = rows;
1532
+ const receipt = yield* heldReceipt(read.receipts, kept);
1533
+ if (receipt !== void 0) return yield* repoAnswer(receipt);
1534
+ const named = {
1535
+ ...record,
1536
+ name
1073
1537
  };
1074
- const signal = input.signal === void 0 ? {} : { signal: input.signal };
1075
- for (let attempt = 0; attempt < 5; attempt += 1) {
1076
- const at = yield* Clock$1.currentTimeMillis;
1077
- const read = yield* forkTry(fork, caller, internalId, kept, (target, record) => authorizeSync(caller, target, record));
1078
- if (read === void 0) continue;
1079
- const { record, snapshot, name, outbox, rows } = read;
1080
- const { refRows, packRows, timeRows, readyRows, leavingRows } = rows;
1081
- const receipt = yield* heldReceipt(read.receipts, kept);
1082
- if (receipt !== void 0) return yield* repoAnswer(receipt);
1083
- const named = {
1084
- ...record,
1085
- name
1086
- };
1087
- const listing = new Set(packRows.map(({ id }) => id));
1088
- const owned = yield* decodePacks(packRows);
1089
- const marked = new Map(owned.map((pack) => [pack.id, pack]));
1090
- const first = yield* readSource(caller, of.upstreamInternalId);
1091
- const sourceHead = headOf(first.record.defaultBranch);
1092
- const head = headOf(record.defaultBranch);
1093
- const forkView = yield* refViewIn(caller, {
1094
- name,
1095
- public: record.public,
1096
- internalId
1097
- });
1098
- if (!first.headSeen || !forkView.sees(head)) return yield* unseenHead(fork);
1099
- const from = yield* tipOf(refRows, head);
1100
- const to = yield* tipOf(first.refs, sourceHead);
1101
- const unchanged = Effect.gen(function* () {
1102
- const info = yield* repoInfo(caller, internalId, named, [
1103
- refRows,
1104
- packRows,
1105
- timeRows,
1106
- readyRows,
1107
- indexRowsOf(rows)
1108
- ]);
1109
- const left = unlisted(shared, /* @__PURE__ */ new Set([...listing, ...leavingRows.map(({ id }) => id)]), at);
1110
- if (kept === void 0 && left.length === 0) return info;
1111
- const receipt = receiptWrites(kept, repoKept(info), core.repackJobRow);
1112
- const upkeep = left.length === 0 ? [] : [core.repackJobRow()];
1113
- return (yield* storeCall(() => store.commit(scope, {
1114
- id: newChangeId(),
1115
- expect: snapshot.version,
1116
- put: [...receipt.put, ...left],
1117
- jobs: withJobs(upkeep, receipt.jobs)
1118
- }))).ok ? info : void 0;
1119
- });
1120
- if (to === null || to === from) {
1121
- const info = yield* unchanged;
1122
- if (info !== void 0) return info;
1123
- continue;
1124
- }
1125
- const gitsOwn = gitsOwnRef(core.hiddenRefs(), head, void 0);
1126
- if (gitsOwn !== void 0) return yield* Effect.fail(gitsOwn);
1127
- const edits = [{
1128
- ref: head,
1129
- from,
1130
- to
1131
- }];
1132
- const kinds = yield* kindsOf({
1133
- objects: reads,
1134
- listed: first.listed,
1135
- pushed: () => Effect.succeed(void 0),
1136
- edits,
1137
- ...signal
1138
- });
1139
- const [update] = kinds.updates;
1140
- const refusal = kinds.refused.get(head);
1141
- if (update === void 0) {
1142
- const info = yield* unchanged;
1143
- if (info !== void 0) return info;
1144
- continue;
1145
- }
1146
- if (refusal !== void 0) return yield* Effect.fail(refusal);
1147
- const kind = update.kind === "force" ? yield* kinds.exact(update) : update.kind;
1148
- if (kind === "force") return yield* diverged(fork);
1149
- const peeling = storesPeel(head) ? yield* peeledAll(reads, first.listed, [to]) : void 0;
1150
- const unpeelable = peeling?.refused.get(to);
1151
- if (unpeelable !== void 0) return yield* Effect.fail(unpeelable);
1152
- const into = {
1153
- internalId,
1154
- version: snapshot.version,
1155
- listing,
1156
- rows,
1157
- owned,
1158
- marked,
1159
- shared,
1160
- walks,
1161
- at
1162
- };
1163
- const tipHeld = (source) => Effect.map(tipOf(source.refs, headOf(source.record.defaultBranch)), (tip) => tip === to);
1164
- const copy = yield* copyInto(caller, fork, into, first, tipHeld, input.signal);
1165
- if (copy === void 0) continue;
1166
- const { source, added, removing, received } = copy;
1167
- const refs = yield* decodeRefs(refRows);
1168
- const decision = decidePush({
1169
- index: core.refIndex,
1170
- read: {
1171
- version: snapshot.version,
1172
- refs,
1173
- refBytes: refBytesOf(refRows),
1174
- head,
1175
- record
1176
- },
1177
- command: {
1178
- source: "api",
1179
- updates: [{
1180
- ...update,
1181
- kind
1182
- }],
1183
- atomic: true,
1184
- received,
1185
- refused: /* @__PURE__ */ new Map(),
1186
- peels: /* @__PURE__ */ new Map([[to, peeling?.peeled.get(to) ?? null]])
1187
- }
1188
- });
1189
- if (decision.kind === "answer") {
1190
- const { answer } = decision;
1191
- if (answer.kind === "error") return yield* Effect.fail(answer.error);
1192
- const [applied] = answer.value.updates;
1193
- if (applied?.kind === "rejected") return yield* Effect.fail(applied.error);
1194
- const info = yield* unchanged;
1195
- if (info !== void 0) return info;
1196
- continue;
1197
- }
1198
- const moved = [...refRows.filter(({ id }) => id !== head), {
1199
- collection: collections.refs,
1200
- id: head,
1201
- value: { oid: to }
1202
- }];
1203
- const listedRows = [...packRows.filter(({ id }) => !removing.has(id)), ...added.map(packRow)];
1204
- const times = yield* decodeStats(timeRows);
1205
- const pushed = timeRow(pushedKey, times.pushed, at);
1206
- const loose = looseRows(times.loose, received.change.rows);
1207
- const timed = [
1208
- ...timeRows.filter(({ id }) => id !== pushedKey.id && (loose.length === 0 || id !== looseKey.id)),
1209
- pushed,
1210
- ...loose
1211
- ];
1538
+ const listing = new Set(packRows.map(({ id }) => id));
1539
+ const owned = yield* decodePacks(packRows);
1540
+ const marked = new Map(owned.map((pack) => [pack.id, pack]));
1541
+ const first = yield* readSource(caller, of.upstreamInternalId);
1542
+ const sourceHead = headOf(first.record.defaultBranch);
1543
+ const head = headOf(record.defaultBranch);
1544
+ const forkView = yield* refViewIn(caller, {
1545
+ name,
1546
+ public: record.public,
1547
+ internalId
1548
+ });
1549
+ if (!first.headSeen || !forkView.sees(head)) return yield* unseenHead(fork);
1550
+ const from = yield* tipOf(refRows, head);
1551
+ const to = yield* tipOf(first.refs, sourceHead);
1552
+ const unchanged = Effect.gen(function* () {
1212
1553
  const info = yield* repoInfo(caller, internalId, named, [
1213
- moved,
1214
- listedRows,
1215
- timed,
1554
+ refRows,
1555
+ packRows,
1556
+ timeRows,
1216
1557
  readyRows,
1217
- indexRowsOf(rows)
1558
+ indexRowsOf(rows),
1559
+ rows.rootRows
1218
1560
  ]);
1219
- const keptWrites = receiptWrites(kept, repoKept(info), core.repackJobRow);
1220
- const write = newChangeId();
1221
- const events = decision.moved.map((move) => ({
1222
- type: "ref.updated",
1223
- ...repoEnvelope(caller, name),
1224
- ...move,
1225
- kind,
1226
- push: {
1227
- id: write,
1228
- ...pushCounts(core.access, decision.moved),
1229
- source: "api"
1230
- }
1231
- }));
1232
- const appended = yield* appendEvents(core.events, outbox, events, {
1233
- scope,
1234
- at
1235
- });
1236
- const leaves = received.change.put?.some(isLeavingRow) === true;
1237
- const upkeep = added.length > 0 || leaves || objects.readyShallow ? [core.repackJobRow()] : [];
1238
- const indexed = SealedObjects.whole(sealed, forkWhole).index?.status(rows.indexRow, at, listedRows.map(({ id }) => id));
1239
- const jobs = [
1240
- ...upkeep,
1241
- ...indexJobs(core, indexed),
1242
- ...refIndexJobs(core, record)
1243
- ];
1244
- const late = (yield* Clock$1.currentTimeMillis) - at;
1245
- const change = {
1246
- put: leavingLate([
1247
- ...decision.change.put,
1248
- pushed,
1249
- ...loose,
1250
- ...keptWrites.put,
1251
- ...appended.put
1252
- ], late),
1253
- delete: [...decision.change.delete, ...appended.delete],
1254
- jobs: withJobs([...jobs, ...appended.jobs], keptWrites.jobs)
1255
- };
1256
- yield* checkChange(source.name, change);
1257
- if (!(yield* storeCall(() => store.commit(scope, {
1258
- id: write,
1259
- expect: decision.expect,
1260
- ...change
1261
- }))).ok) continue;
1262
- return info;
1561
+ const left = unlisted(shared, /* @__PURE__ */ new Set([...listing, ...leavingRows.map(({ id }) => id)]), at);
1562
+ if (kept === void 0 && left.length === 0) return info;
1563
+ const receipt = receiptWrites(kept, repoKept(info), core.repackJobRow);
1564
+ const upkeep = left.length === 0 ? [] : [core.repackJobRow()];
1565
+ return (yield* storeCommit(store.commit(scope, {
1566
+ id: newChangeId(),
1567
+ expect: snapshot.version,
1568
+ put: [...receipt.put, ...left],
1569
+ jobs: withJobs(upkeep, receipt.jobs)
1570
+ }))).ok ? info : void 0;
1571
+ });
1572
+ if (to === null || to === from) {
1573
+ const info = yield* unchanged;
1574
+ if (info !== void 0) return info;
1575
+ continue;
1263
1576
  }
1264
- return yield* contended();
1265
- }),
1266
- fetch: Effect.fnUntraced(function* (fork, input) {
1267
- const core = yield* CoreParts;
1268
- const { store } = core;
1269
- const caller = callerOf(input);
1270
- const opened = yield* openRepo(caller, {
1271
- kind: "read",
1272
- repo: fork
1273
- }, [], input.internalId);
1274
- const of = opened.record.fork;
1275
- if (of === void 0) return yield* notAFork(fork);
1276
- const { internalId } = opened;
1277
- const shared = /* @__PURE__ */ new Map();
1278
- const walks = {
1279
- settled: /* @__PURE__ */ new Map(),
1280
- reads: 0
1577
+ const gitsOwn = gitsOwnRef(core.hiddenRefs(), head, void 0);
1578
+ if (gitsOwn !== void 0) return yield* Effect.fail(gitsOwn);
1579
+ const edits = [{
1580
+ ref: head,
1581
+ from,
1582
+ to
1583
+ }];
1584
+ const kinds = yield* kindsOf({
1585
+ objects: reads,
1586
+ listed: first.listed,
1587
+ pushed: () => Effect.succeed(void 0),
1588
+ edits,
1589
+ roots: first.roots,
1590
+ ...signal
1591
+ });
1592
+ const [update] = kinds.updates;
1593
+ const refusal = kinds.refused.get(head);
1594
+ if (update === void 0) {
1595
+ const info = yield* unchanged;
1596
+ if (info !== void 0) return info;
1597
+ continue;
1598
+ }
1599
+ if (refusal !== void 0) return yield* Effect.fail(refusal);
1600
+ const kind = update.kind === "force" ? yield* kinds.exact(update) : update.kind;
1601
+ if (kind === "force") return yield* diverged(fork);
1602
+ const peeling = storesPeel(head) ? yield* peeledAll(reads, first.listed, [to]) : void 0;
1603
+ const unpeelable = peeling?.refused.get(to);
1604
+ if (unpeelable !== void 0) return yield* Effect.fail(unpeelable);
1605
+ const into = {
1606
+ internalId,
1607
+ version: snapshot.version,
1608
+ listing,
1609
+ rows,
1610
+ owned,
1611
+ marked,
1612
+ shared,
1613
+ batches,
1614
+ walks,
1615
+ at
1281
1616
  };
1282
- const may = (target) => check({
1283
- caller,
1284
- operation: {
1285
- kind: "object.create",
1286
- repo: target.name
1617
+ const tipHeld = (source) => Effect.map(tipOf(source.refs, headOf(source.record.defaultBranch)), (tip) => tip === to);
1618
+ const copy = yield* copyInto(caller, fork, into, first, tipHeld, input.signal, budget);
1619
+ if (copy === void 0) continue;
1620
+ const { source, added, removing, received } = copy;
1621
+ const refs = yield* decodeRefs(refRows);
1622
+ const decision = decidePush({
1623
+ index: core.refIndex,
1624
+ read: {
1625
+ version: snapshot.version,
1626
+ refs,
1627
+ refBytes: refBytesOf(refRows),
1628
+ head,
1629
+ record
1287
1630
  },
1288
- repo: target
1631
+ command: {
1632
+ source: "api",
1633
+ updates: [{
1634
+ ...update,
1635
+ kind
1636
+ }],
1637
+ atomic: true,
1638
+ received,
1639
+ refused: /* @__PURE__ */ new Map(),
1640
+ peels: /* @__PURE__ */ new Map([[to, peeling?.peeled.get(to) ?? null]])
1641
+ }
1289
1642
  });
1290
- for (let attempt = 0; attempt < 5; attempt += 1) {
1291
- const at = yield* Clock$1.currentTimeMillis;
1292
- const read = yield* forkTry(fork, caller, internalId, void 0, may);
1293
- if (read === void 0) continue;
1294
- const { record, snapshot, rows } = read;
1295
- const listing = new Set(rows.packRows.map(({ id }) => id));
1296
- const owned = yield* decodePacks(rows.packRows);
1297
- const marked = new Map(owned.map((pack) => [pack.id, pack]));
1298
- const into = {
1299
- internalId,
1300
- version: snapshot.version,
1301
- listing,
1302
- rows,
1303
- owned,
1304
- marked,
1305
- shared,
1306
- walks,
1307
- at
1308
- };
1309
- const first = yield* readSource(caller, of.upstreamInternalId);
1310
- const copy = yield* copyInto(caller, fork, into, first, () => Effect.succeed(true), input.signal);
1311
- if (copy === void 0) continue;
1312
- const { source, added, received } = copy;
1313
- const tips = yield* decodeRefs(source.refs);
1314
- const fetched = {
1315
- source: source.name,
1316
- tips: [...tips].map(([ref, oid]) => ({
1317
- name: ref,
1318
- oid
1319
- }))
1320
- };
1321
- if (source.headSeen) fetched.head = headOf(source.record.defaultBranch);
1322
- const { put = [], delete: drop = [], remove = [] } = received.change;
1323
- if ([
1324
- added,
1325
- remove,
1326
- put,
1327
- drop
1328
- ].every(({ length }) => length === 0)) return fetched;
1329
- const refs = yield* decodeRefs(rows.refRows);
1330
- const head = headOf(record.defaultBranch);
1331
- const decision = decidePush({
1332
- index: core.refIndex,
1333
- read: {
1334
- version: snapshot.version,
1335
- refs,
1336
- refBytes: refBytesOf(rows.refRows),
1337
- head,
1338
- record
1339
- },
1340
- command: {
1341
- source: "api",
1342
- updates: [],
1343
- atomic: true,
1344
- received,
1345
- refused: /* @__PURE__ */ new Map()
1346
- }
1347
- });
1348
- if (decision.kind === "answer") {
1349
- const { answer } = decision;
1350
- return answer.kind === "error" ? yield* Effect.fail(answer.error) : fetched;
1643
+ if (decision.kind === "answer") {
1644
+ const { answer } = decision;
1645
+ if (answer.kind === "error") return yield* Effect.fail(answer.error);
1646
+ const [applied] = answer.value.updates;
1647
+ if (applied?.kind === "rejected") return yield* Effect.fail(applied.error);
1648
+ const info = yield* unchanged;
1649
+ if (info !== void 0) return info;
1650
+ continue;
1651
+ }
1652
+ const moved = [...refRows.filter(({ id }) => id !== head), {
1653
+ collection: collections.refs,
1654
+ id: head,
1655
+ value: { oid: to }
1656
+ }];
1657
+ const listedRows = [...packRows.filter(({ id }) => !removing.has(id)), ...added.map(packRow)];
1658
+ const times = yield* decodeStats(timeRows);
1659
+ const pushed = timeRow(pushedKey, times.pushed, at);
1660
+ const loose = looseRows(times.loose, received.change.rows);
1661
+ const timed = [
1662
+ ...timeRows.filter(({ id }) => id !== pushedKey.id && (loose.length === 0 || id !== looseKey.id)),
1663
+ pushed,
1664
+ ...loose
1665
+ ];
1666
+ const indexed = SealedObjects.whole(sealed, forkWhole).index?.status(rows.indexRow, at, listedRows.map(({ id }) => id));
1667
+ const held = yield* rootsOf(rows.rootRows);
1668
+ const rooted = yield* rootsCopied(held, source, indexJobs(core, indexed));
1669
+ const info = yield* repoInfo(caller, internalId, named, [
1670
+ moved,
1671
+ listedRows,
1672
+ timed,
1673
+ readyRows,
1674
+ indexRowsOf(rows),
1675
+ rooted === void 0 ? rows.rootRows : rooted.put
1676
+ ]);
1677
+ const keptWrites = receiptWrites(kept, repoKept(info), core.repackJobRow);
1678
+ const write = newChangeId();
1679
+ const events = decision.moved.map((move) => ({
1680
+ type: "ref.updated",
1681
+ ...repoEnvelope(caller, name),
1682
+ ...move,
1683
+ kind,
1684
+ push: {
1685
+ id: write,
1686
+ ...pushCounts(core.access, decision.moved),
1687
+ source: "api"
1351
1688
  }
1352
- const late = (yield* Clock$1.currentTimeMillis) - at;
1353
- const times = yield* decodeStats(rows.timeRows);
1354
- const loose = looseRows(times.loose, received.change.rows);
1355
- const change = {
1356
- ...decision.change,
1357
- put: [...leavingLate(decision.change.put, late), ...loose],
1358
- jobs: [core.repackJobRow()]
1359
- };
1360
- yield* checkChange(source.name, change);
1361
- if ((yield* storeCall(() => store.commit(repoScope(internalId), {
1689
+ }));
1690
+ const appended = yield* appendEvents(core.events, outbox, events, {
1691
+ scope,
1692
+ at
1693
+ });
1694
+ const leaves = received.change.put?.some(isLeavingRow) === true;
1695
+ const jobs = [
1696
+ ...added.length > 0 || leaves || objects.readyShallow ? [core.repackJobRow()] : [],
1697
+ ...rooted?.jobs ?? indexJobs(core, indexed),
1698
+ ...refIndexJobs(core, record)
1699
+ ];
1700
+ const late = (yield* Clock.currentTimeMillis) - at;
1701
+ const change = {
1702
+ put: leavingLate([
1703
+ ...decision.change.put,
1704
+ pushed,
1705
+ ...loose,
1706
+ ...rooted?.put ?? [],
1707
+ ...keptWrites.put,
1708
+ ...appended.put
1709
+ ], late),
1710
+ delete: [
1711
+ ...decision.change.delete,
1712
+ ...rooted?.delete ?? [],
1713
+ ...appended.delete
1714
+ ],
1715
+ jobs: withJobs([...jobs, ...appended.jobs], keptWrites.jobs)
1716
+ };
1717
+ yield* checkChange(source.name, change);
1718
+ if (!(yield* storeCommit(store.commit(scope, {
1719
+ id: write,
1720
+ expect: decision.expect,
1721
+ ...change
1722
+ }))).ok) continue;
1723
+ return info;
1724
+ }
1725
+ return yield* contended();
1726
+ });
1727
+ const fetch = (fork, input) => {
1728
+ const budget = {
1729
+ source: "",
1730
+ needed: 0,
1731
+ inlineCalls: 0,
1732
+ manifestCalls: 0
1733
+ };
1734
+ return Effect.provideService(fetchWithBudget(budget, fork, input), ChunkReadGuard, readGuardOf(budget, () => 2, 2));
1735
+ };
1736
+ const fetchWithBudget = Effect.fnUntraced(function* (budget, fork, input) {
1737
+ const core = yield* CoreParts;
1738
+ const { store } = core;
1739
+ const caller = callerOf(input);
1740
+ const opened = yield* openRepo(caller, {
1741
+ kind: "read",
1742
+ repo: fork
1743
+ }, [], input.internalId, "first-read");
1744
+ const of = opened.record.fork;
1745
+ if (of === void 0) return yield* Effect.andThen(confirmed(opened), notAFork(fork));
1746
+ const { internalId } = opened;
1747
+ const shared = /* @__PURE__ */ new Map();
1748
+ const batches = [];
1749
+ const walks = {
1750
+ settled: /* @__PURE__ */ new Map(),
1751
+ reads: 0
1752
+ };
1753
+ const may = (target) => check({
1754
+ caller,
1755
+ operation: {
1756
+ kind: "object.create",
1757
+ repo: target.name
1758
+ },
1759
+ repo: target
1760
+ });
1761
+ for (let attempt = 0; attempt < 5; attempt += 1) {
1762
+ const at = yield* Clock.currentTimeMillis;
1763
+ const read = yield* forkTry(fork, caller, internalId, void 0, may, attempt === 0 ? opened : void 0);
1764
+ if (read === void 0) continue;
1765
+ const { record, snapshot, rows } = read;
1766
+ const listing = new Set(rows.packRows.map(({ id }) => id));
1767
+ const owned = yield* decodePacks(rows.packRows);
1768
+ const marked = new Map(owned.map((pack) => [pack.id, pack]));
1769
+ const into = {
1770
+ internalId,
1771
+ version: snapshot.version,
1772
+ listing,
1773
+ rows,
1774
+ owned,
1775
+ marked,
1776
+ shared,
1777
+ batches,
1778
+ walks,
1779
+ at
1780
+ };
1781
+ const first = yield* readSource(caller, of.upstreamInternalId);
1782
+ const copy = yield* copyInto(caller, fork, into, first, () => Effect.succeed(true), input.signal, budget);
1783
+ if (copy === void 0) continue;
1784
+ const { source, added, received } = copy;
1785
+ const tips = yield* decodeRefs(source.refs);
1786
+ const fetched = {
1787
+ source: source.name,
1788
+ tips: [...tips].map(([ref, oid]) => ({
1789
+ name: ref,
1790
+ oid
1791
+ }))
1792
+ };
1793
+ if (source.headSeen) fetched.head = headOf(source.record.defaultBranch);
1794
+ const { put = [], delete: drop = [], remove = [] } = received.change;
1795
+ const indexing = indexJobs(core, { state: "unbuilt" });
1796
+ const rooted = yield* rootsCopied(yield* rootsOf(rows.rootRows), source, indexing);
1797
+ const copies = [
1798
+ added,
1799
+ remove,
1800
+ put,
1801
+ drop
1802
+ ].some(({ length }) => length > 0);
1803
+ if (!copies && rooted === void 0) return fetched;
1804
+ if (!copies && rooted !== void 0) {
1805
+ if ((yield* storeCommit(store.commit(repoScope(internalId), {
1362
1806
  id: newChangeId(),
1363
- expect: decision.expect,
1364
- ...change
1807
+ expect: snapshot.version,
1808
+ put: [...rooted.put],
1809
+ delete: [...rooted.delete],
1810
+ jobs: [...rooted.jobs]
1365
1811
  }))).ok) return fetched;
1812
+ continue;
1366
1813
  }
1367
- return yield* contended();
1368
- })
1814
+ const refs = yield* decodeRefs(rows.refRows);
1815
+ const head = headOf(record.defaultBranch);
1816
+ const decision = decidePush({
1817
+ index: core.refIndex,
1818
+ read: {
1819
+ version: snapshot.version,
1820
+ refs,
1821
+ refBytes: refBytesOf(rows.refRows),
1822
+ head,
1823
+ record
1824
+ },
1825
+ command: {
1826
+ source: "api",
1827
+ updates: [],
1828
+ atomic: true,
1829
+ received,
1830
+ refused: /* @__PURE__ */ new Map()
1831
+ }
1832
+ });
1833
+ if (decision.kind === "answer") {
1834
+ const { answer } = decision;
1835
+ return answer.kind === "error" ? yield* Effect.fail(answer.error) : fetched;
1836
+ }
1837
+ const late = (yield* Clock.currentTimeMillis) - at;
1838
+ const times = yield* decodeStats(rows.timeRows);
1839
+ const loose = looseRows(times.loose, received.change.rows);
1840
+ const change = {
1841
+ ...decision.change,
1842
+ put: [
1843
+ ...leavingLate(decision.change.put, late),
1844
+ ...loose,
1845
+ ...rooted?.put ?? []
1846
+ ],
1847
+ delete: [...decision.change.delete ?? [], ...rooted?.delete ?? []],
1848
+ jobs: [core.repackJobRow(), ...rooted?.jobs ?? []]
1849
+ };
1850
+ yield* checkChange(source.name, change);
1851
+ if ((yield* storeCommit(store.commit(repoScope(internalId), {
1852
+ id: newChangeId(),
1853
+ expect: decision.expect,
1854
+ ...change
1855
+ }))).ok) return fetched;
1856
+ }
1857
+ return yield* contended();
1858
+ });
1859
+ return {
1860
+ create,
1861
+ get,
1862
+ list,
1863
+ sync,
1864
+ fetch
1369
1865
  };
1370
1866
  };
1371
1867
  export { forkCalls, forksListBound, forksReach };