@ref0/git 0.12.0 → 0.14.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 (247) hide show
  1. package/dist/access/private-refs.mjs +3 -3
  2. package/dist/auth/auth.d.mts +2 -2
  3. package/dist/auth/auth.mjs +3 -6
  4. package/dist/auth/authorize.mjs +1 -17
  5. package/dist/auth/helpers.mjs +3 -11
  6. package/dist/auth/host-services.mjs +11 -0
  7. package/dist/auth/policy.d.mts +27 -7
  8. package/dist/auth/policy.mjs +8 -4
  9. package/dist/auth/tokens-layer.d.mts +1 -2
  10. package/dist/auth/tokens-layer.mjs +2 -3
  11. package/dist/auth/tokens-public.d.mts +3 -3
  12. package/dist/auth/tokens.d.mts +1 -8
  13. package/dist/auth/tokens.mjs +1 -8
  14. package/dist/auth.d.mts +1 -4
  15. package/dist/auth.mjs +1 -3
  16. package/dist/client/git-http.mjs +18 -4
  17. package/dist/client/push-upload.mjs +33 -7
  18. package/dist/client/remote.mjs +94 -28
  19. package/dist/client/slice-push.d.mts +1 -1
  20. package/dist/contracts/access.d.mts +8 -8
  21. package/dist/contracts/actors.d.mts +2 -34
  22. package/dist/contracts/blobs.d.mts +2 -2
  23. package/dist/contracts/client.d.mts +8 -3
  24. package/dist/contracts/commits.d.mts +10 -2
  25. package/dist/contracts/commits.mjs +9 -1
  26. package/dist/contracts/files.d.mts +2 -2
  27. package/dist/contracts/forks.d.mts +11 -1
  28. package/dist/contracts/git.d.mts +18 -7
  29. package/dist/contracts/git.mjs +3 -2
  30. package/dist/contracts/lfs.d.mts +0 -7
  31. package/dist/contracts/objects.d.mts +80 -10
  32. package/dist/contracts/operations.d.mts +3 -0
  33. package/dist/contracts/operations.mjs +12 -2
  34. package/dist/contracts/push-uploads.d.mts +44 -5
  35. package/dist/contracts/push-uploads.mjs +7 -3
  36. package/dist/contracts/refs.d.mts +28 -6
  37. package/dist/contracts/remote.mjs +1 -3
  38. package/dist/contracts/repo-records.d.mts +1 -0
  39. package/dist/contracts/repos.d.mts +90 -2
  40. package/dist/contracts/repos.mjs +29 -2
  41. package/dist/contracts/result.d.mts +23 -18
  42. package/dist/contracts/result.mjs +17 -4
  43. package/dist/contracts/rules.d.mts +22 -22
  44. package/dist/contracts/server.d.mts +28 -77
  45. package/dist/contracts/signin.d.mts +1 -1
  46. package/dist/contracts/sync.d.mts +79 -19
  47. package/dist/contracts/sync.mjs +34 -10
  48. package/dist/contracts/tokens.d.mts +1 -6
  49. package/dist/contracts/tokens.mjs +1 -2
  50. package/dist/contracts/topics.d.mts +0 -5
  51. package/dist/contracts/work.d.mts +66 -2
  52. package/dist/contracts/work.mjs +8 -1
  53. package/dist/core/access.mjs +27 -5
  54. package/dist/core/ancestry.d.mts +9 -0
  55. package/dist/core/ancestry.mjs +6 -6
  56. package/dist/core/asked.mjs +42 -4
  57. package/dist/core/call-names.mjs +1 -0
  58. package/dist/core/call-services.mjs +2 -1
  59. package/dist/core/events/deliver.mjs +10 -2
  60. package/dist/core/forks.mjs +3 -3
  61. package/dist/core/imports.mjs +147 -9
  62. package/dist/core/index-job.mjs +9 -6
  63. package/dist/core/job-view.mjs +8 -9
  64. package/dist/core/mirror-rows.mjs +19 -4
  65. package/dist/core/objects/commits.mjs +16 -6
  66. package/dist/core/parts.d.mts +6 -1
  67. package/dist/core/parts.mjs +1 -4
  68. package/dist/core/purge.mjs +76 -6
  69. package/dist/core/push-decide.mjs +1 -1
  70. package/dist/core/push-files.d.mts +12 -0
  71. package/dist/core/push-files.mjs +225 -0
  72. package/dist/core/push-repo.d.mts +8 -0
  73. package/dist/core/push-repo.mjs +56 -0
  74. package/dist/core/push.d.mts +17 -0
  75. package/dist/core/push.mjs +98 -26
  76. package/dist/core/receipts.mjs +26 -10
  77. package/dist/core/ref-view.mjs +59 -5
  78. package/dist/core/refs.mjs +13 -8
  79. package/dist/core/repack.mjs +11 -8
  80. package/dist/core/repo-info.mjs +16 -9
  81. package/dist/core/repos.mjs +30 -14
  82. package/dist/core/seam.mjs +2 -2
  83. package/dist/core/view.d.mts +6 -0
  84. package/dist/core/view.mjs +45 -12
  85. package/dist/core/work.mjs +47 -22
  86. package/dist/effect.d.mts +3 -1
  87. package/dist/effect.mjs +3 -1
  88. package/dist/engine/reads.mjs +13 -6
  89. package/dist/engine/walk.mjs +4 -4
  90. package/dist/event-streams/event-streams.d.mts +1 -1
  91. package/dist/event-streams/event-streams.mjs +1 -1
  92. package/dist/event-streams/stream.d.mts +1 -1
  93. package/dist/event-streams/stream.mjs +1 -1
  94. package/dist/extend.d.mts +3 -3
  95. package/dist/extend.mjs +2 -2
  96. package/dist/http/answers.mjs +4 -2
  97. package/dist/http/core-parts.mjs +64 -15
  98. package/dist/http/handler.mjs +2 -2
  99. package/dist/http/node.mjs +5 -4
  100. package/dist/http/parts.d.mts +1 -0
  101. package/dist/http/push-upload-job.mjs +503 -0
  102. package/dist/http/push-uploads.d.mts +1 -0
  103. package/dist/http/push-uploads.mjs +114 -56
  104. package/dist/http/upload-pack.mjs +7 -6
  105. package/dist/index.d.mts +23 -24
  106. package/dist/index.mjs +4 -7
  107. package/dist/lfs/base.d.mts +7 -3
  108. package/dist/lfs/base.mjs +2 -1
  109. package/dist/lfs/copy.d.mts +46 -0
  110. package/dist/lfs/copy.mjs +26 -0
  111. package/dist/lfs/layer.mjs +4 -2
  112. package/dist/lfs/objects.d.mts +6 -0
  113. package/dist/lfs/objects.mjs +68 -41
  114. package/dist/lfs/rows.d.mts +13 -0
  115. package/dist/lfs/service.d.mts +1 -7
  116. package/dist/lfs/service.mjs +1 -9
  117. package/dist/lfs/upload-most.mjs +5 -5
  118. package/dist/node.d.mts +2 -2
  119. package/dist/protocol/bytes/sha256-hasher.d.mts +15 -0
  120. package/dist/protocol/bytes/sha256.d.mts +32 -0
  121. package/dist/protocol/bytes/sha256.mjs +105 -49
  122. package/dist/protocol/wire/advertisement.mjs +9 -4
  123. package/dist/protocol/wire/lines.d.mts +4 -2
  124. package/dist/protocol/wire/lines.mjs +11 -5
  125. package/dist/protocol/wire/push-uploads.mjs +13 -1
  126. package/dist/protocol/wire/v2.mjs +2 -2
  127. package/dist/protocol.d.mts +3 -1
  128. package/dist/protocol.mjs +3 -1
  129. package/dist/queue/advance.mjs +1 -1
  130. package/dist/queue/host.d.mts +1 -7
  131. package/dist/queue/host.mjs +1 -7
  132. package/dist/queue/layer.mjs +1 -1
  133. package/dist/queue/trim.mjs +1 -1
  134. package/dist/rest/blobs.d.mts +31 -23
  135. package/dist/rest/blobs.mjs +1 -1
  136. package/dist/rest/caller.d.mts +49 -9
  137. package/dist/rest/caller.mjs +1 -1
  138. package/dist/rest/client.d.mts +10 -3
  139. package/dist/rest/client.mjs +4 -0
  140. package/dist/rest/commits.d.mts +273 -240
  141. package/dist/rest/errors.d.mts +24 -4
  142. package/dist/rest/events.d.mts +9 -6
  143. package/dist/rest/events.mjs +1 -2
  144. package/dist/rest/files.d.mts +127 -115
  145. package/dist/rest/forks.d.mts +121 -97
  146. package/dist/rest/handler.mjs +4 -57
  147. package/dist/rest/handlers.d.mts +1 -1
  148. package/dist/rest/handlers.mjs +18 -4
  149. package/dist/rest/layer.mjs +2 -1
  150. package/dist/rest/me.d.mts +8 -4
  151. package/dist/rest/merges.d.mts +8 -4
  152. package/dist/rest/paths.mjs +1 -0
  153. package/dist/rest/queue.d.mts +282 -226
  154. package/dist/rest/refs.d.mts +205 -176
  155. package/dist/rest/repos.d.mts +108 -80
  156. package/dist/rest/tags.d.mts +24 -12
  157. package/dist/rest/tokens.d.mts +235 -211
  158. package/dist/rest/topics.d.mts +53 -33
  159. package/dist/rest/trees.d.mts +105 -89
  160. package/dist/rest/work.d.mts +467 -20
  161. package/dist/rest/work.mjs +8 -0
  162. package/dist/server/edge-node.d.mts +9 -13
  163. package/dist/server/edge-node.mjs +9 -12
  164. package/dist/server/git-layer.d.mts +1 -6
  165. package/dist/server/git-layer.mjs +2 -2
  166. package/dist/server/git-namespace.d.mts +3 -3
  167. package/dist/server/joined.d.mts +15 -22
  168. package/dist/server/joined.mjs +5 -29
  169. package/dist/server/lifecycle.mjs +107 -23
  170. package/dist/server/registry.mjs +9 -1
  171. package/dist/server/server.mjs +133 -212
  172. package/dist/storage/budget.mjs +2 -2
  173. package/dist/storage/clean-up.mjs +13 -10
  174. package/dist/storage/fetch.mjs +13 -8
  175. package/dist/storage/file-limits.mjs +24 -0
  176. package/dist/storage/index-build.d.mts +1 -0
  177. package/dist/storage/index-build.mjs +106 -62
  178. package/dist/storage/index-fetch.mjs +16 -3
  179. package/dist/storage/index-reach.mjs +33 -5
  180. package/dist/storage/index-remap.mjs +8 -1
  181. package/dist/storage/index-shallow.mjs +5 -3
  182. package/dist/storage/largest-files.mjs +48 -0
  183. package/dist/storage/lfs-pointers.mjs +10 -1
  184. package/dist/storage/loose.mjs +3 -1
  185. package/dist/storage/memory-budget.mjs +28 -4
  186. package/dist/storage/pack-reads.mjs +8 -8
  187. package/dist/storage/pack-receive.mjs +83 -25
  188. package/dist/storage/packs.mjs +37 -21
  189. package/dist/storage/prune-keep.mjs +203 -34
  190. package/dist/storage/prune-walk.mjs +54 -16
  191. package/dist/storage/prune.mjs +629 -196
  192. package/dist/storage/push-uploads.mjs +36 -12
  193. package/dist/storage/quarantine.mjs +9 -9
  194. package/dist/storage/ready.mjs +47 -19
  195. package/dist/storage/receive-bounds.mjs +29 -8
  196. package/dist/storage/receive-state.mjs +8 -0
  197. package/dist/storage/receive-steps.mjs +71 -18
  198. package/dist/storage/repack.d.mts +1 -1
  199. package/dist/storage/repack.mjs +1 -8
  200. package/dist/storage/rows.mjs +12 -1
  201. package/dist/storage/shallow.d.mts +1 -0
  202. package/dist/storage/shallow.mjs +26 -4
  203. package/dist/storage/stream-whole.mjs +5 -2
  204. package/dist/storage/visible.mjs +29 -1
  205. package/dist/storage/walk.mjs +2 -1
  206. package/dist/store/catalogue.mjs +1 -0
  207. package/dist/store/cursor-seal-namespace.d.mts +2 -0
  208. package/dist/store/cursor-seal-public.d.mts +5 -0
  209. package/dist/store/cursor-seal-public.mjs +5 -0
  210. package/dist/store/cursor-seal.d.mts +16 -2
  211. package/dist/store/cursor-seal.mjs +26 -14
  212. package/dist/store/errors.mjs +9 -1
  213. package/dist/store/records.d.mts +2 -0
  214. package/dist/store/records.mjs +9 -6
  215. package/dist/store/repo-record.d.mts +9 -7
  216. package/dist/store/repo-record.mjs +102 -19
  217. package/dist/store/scopes.mjs +10 -2
  218. package/dist/sync/bound.d.mts +2 -0
  219. package/dist/sync/bound.mjs +11 -2
  220. package/dist/sync/github.d.mts +6 -1
  221. package/dist/sync/github.mjs +55 -43
  222. package/dist/sync/http.mjs +36 -1
  223. package/dist/sync/import.mjs +1 -0
  224. package/dist/sync/layer.mjs +6 -2
  225. package/dist/sync/lfs-batch.mjs +119 -0
  226. package/dist/sync/lfs-copy.mjs +251 -0
  227. package/dist/sync/mirror.mjs +210 -137
  228. package/dist/sync/smart-http.mjs +4 -2
  229. package/dist/sync/step.mjs +25 -5
  230. package/dist/sync/tries.mjs +45 -14
  231. package/dist/sync.d.mts +2 -2
  232. package/dist/topics/host.mjs +1 -19
  233. package/dist/topics/layer.mjs +1 -1
  234. package/package.json +3 -8
  235. package/dist/auth/bridge.mjs +0 -30
  236. package/dist/auth/helpers.d.mts +0 -17
  237. package/dist/core/purge.d.mts +0 -8
  238. package/dist/core/registered-rows.d.mts +0 -5
  239. package/dist/core/repack.d.mts +0 -11
  240. package/dist/http/handler.d.mts +0 -2
  241. package/dist/rest/handler.d.mts +0 -21
  242. package/dist/rest.d.mts +0 -2
  243. package/dist/rest.mjs +0 -1
  244. package/dist/server/registry.d.mts +0 -16
  245. package/dist/server/server.d.mts +0 -36
  246. package/dist/storage/repack-job.d.mts +0 -3
  247. package/dist/topics/host.d.mts +0 -7
@@ -29,13 +29,22 @@ const importLimits = {
29
29
  rootsMost
30
30
  };
31
31
  /**
32
+ * The most bytes of Git LFS objects one try of an import copies: the copy's step takes a batch's
33
+ * objects until the next would pass it, and an object past it alone, so a try's downloads end
34
+ * well within `importTryTimeout`, and one object, at most LFS's `largestObject`, always fits.
35
+ */
36
+ const lfsCopyBytes = 2 * 1024 ** 3;
37
+ /**
32
38
  * The most mirrors a repo holds, and the most bytes one mirror's row takes, the row whole as UTF-8
33
39
  * JSON, measured as its largest state, paused `diverged`, so a pause never takes it past.
34
40
  * `mirrors` reads every row in one store call, beside the repo's record, at most 1 MiB, so 1,000
35
41
  * rows of 4 KiB, 4 MiB, keep its read and its answer within one answer's 16 MiB `answerBytes`. The
36
42
  * longest ref, 768 bytes of `"`, takes 1,536 escaped, and its saver's actor ID, which `authorize`
37
43
  * holds to `maxActorIdLength`, 256 bytes, takes 512 so, which leaves its destination about 1,880
38
- * bytes.
44
+ * bytes. `mirrors` bounds a destination's job too, one a destination: a push saves at most
45
+ * that many, and each try reads every row in one call, asks each distinct saver among them again
46
+ * once, makes one `provider.remote` call, reads the advertisement once, and twice when an update is
47
+ * refused, and sends one push of at most that many refs.
39
48
  */
40
49
  const mirrorLimits = {
41
50
  mirrors: 1e3,
@@ -48,4 +57,4 @@ const mirrorLimits = {
48
57
  const asSync = decidingWith(hostAuthorize);
49
58
  /** The build's internal binding, including the definitions test worlds hand to their queue. */
50
59
  var SyncState = class extends (/* @__PURE__ */ Context.Service()("@ref0/git/SyncState")) {};
51
- export { SyncState, asSync, importLimits, mirrorLimits };
60
+ export { SyncState, asSync, importLimits, lfsCopyBytes, mirrorLimits };
@@ -7,5 +7,10 @@ import * as HttpClient from "effect/http/HttpClient";
7
7
  * refused before more of it is read.
8
8
  */
9
9
  export declare const webhookBodyBytes: number;
10
- /** A GitHub App provider over the host's HTTP client and clock, captured at construction. */
10
+ /**
11
+ * A GitHub App provider over the host's HTTP client, captured at construction: each call it makes
12
+ * runs in the fiber that yields it, a try's, so the token's mint and each read sent again while
13
+ * GitHub's Git doesn't know the token are charged to the try's budget, and the first send of a
14
+ * request is the one `httpOf` charges, as it charges every transport's.
15
+ */
11
16
  export declare const github: (options: SyncGitHubOptions) => Effect.Effect<SyncProvider, GitError, HttpClient.HttpClient>;
@@ -1,6 +1,6 @@
1
- import { runnerIn } from "../store/crossing.mjs";
1
+ import { CallBudget } from "../store/call-count.mjs";
2
2
  import { responseToWeb } from "./http.mjs";
3
- import { fail, gitError } from "../contracts/result.mjs";
3
+ import { fail, gitError, gitErrorFrom } from "../contracts/result.mjs";
4
4
  import { sameHash } from "../auth/token-text.mjs";
5
5
  import { ProviderRefused, saidOf } from "./said.mjs";
6
6
  import { hmacSha256 } from "../protocol/bytes/hmac-sha256.mjs";
@@ -10,7 +10,6 @@ import * as HttpClient from "effect/http/HttpClient";
10
10
  import * as Option from "effect/Option";
11
11
  import * as Schema from "effect/Schema";
12
12
  import * as Result from "effect/Result";
13
- import * as Context from "effect/Context";
14
13
  import * as Hex from "effect/encoding/Hex";
15
14
  import * as Base64 from "effect/encoding/Base64";
16
15
  import * as HttpClientRequest from "effect/http/HttpClientRequest";
@@ -48,13 +47,18 @@ const tokenPermissions = (access) => ({
48
47
  metadata: "read"
49
48
  });
50
49
  const ownerAndName = /^[\w.-]+\/[\w.-]+$/;
50
+ /** The mint's body: a token for `name` alone, with `access`'s permissions. */
51
+ const tokenRequest = (name, access) => JSON.stringify({
52
+ repositories: [name],
53
+ permissions: tokenPermissions(access)
54
+ });
51
55
  /**
52
56
  * The fields of GitHub's JSON refusal kept: its `message` alone. `documentation_url` links a page
53
57
  * of the docs, which says nothing of this failure, and is a URL, where userinfo could ride.
54
58
  */
55
59
  const githubKept = ["message"];
56
60
  /** A failure of the provider's own: its message names the call and the status, never a token. */
57
- const failed = (call, status) => /* @__PURE__ */ new Error(status === void 0 ? `GitHub didn't answer to ${call}` : `GitHub answered ${status} to ${call}`);
61
+ const failed = (call, status) => gitError("UNAVAILABLE", status === void 0 ? `GitHub didn't answer to ${call}` : `GitHub answered ${status} to ${call}`, { hint: "The job tries again" });
58
62
  /** The DER length of `size` bytes. */
59
63
  const derLength = (size) => {
60
64
  if (size < 128) return [size];
@@ -174,23 +178,28 @@ const signedBody = async (request, mac) => {
174
178
  reader.releaseLock();
175
179
  }
176
180
  };
177
- /** A GitHub App provider over the host's HTTP client and clock, captured at construction. */
181
+ /**
182
+ * A GitHub App provider over the host's HTTP client, captured at construction: each call it makes
183
+ * runs in the fiber that yields it, a try's, so the token's mint and each read sent again while
184
+ * GitHub's Git doesn't know the token are charged to the try's budget, and the first send of a
185
+ * request is the one `httpOf` charges, as it charges every transport's.
186
+ */
178
187
  const github = /* @__PURE__ */ Effect.fnUntraced(function* (options) {
179
188
  if (options.app.webhookSecret === "") return yield* fail("INVALID_ARGUMENT", "app.webhookSecret is empty, and anyone could sign a webhook with it: leave it out, or set GitHub's");
180
189
  const client = yield* HttpClient.HttpClient;
181
- const clock = yield* Effect.clockWith(Effect.succeed);
182
- const context = Context.make(Clock$1.Clock, clock);
183
- const run = runnerIn(context);
184
- const fetch = (request) => run(client.execute(HttpClientRequest.fromWeb(request)).pipe(Effect.flatMap(responseToWeb)), request.signal);
190
+ const sender = (http) => (request) => http.execute(HttpClientRequest.fromWeb(request)).pipe(Effect.flatMap(responseToWeb), Effect.mapError(() => failed("send a request")));
191
+ const send = sender(client);
192
+ const sendCharged = sender(CallBudget.charged(client));
185
193
  const { app } = options;
186
194
  const api = (options.apiUrl ?? "https://api.github.com").replace(/\/$/, "");
187
195
  const git = (options.gitUrl ?? "https://github.com").replace(/\/$/, "");
188
- const signer = () => crypto.subtle.importKey("pkcs8", keyBytes(app.privateKey), rsaSigning, false, ["sign"]).catch(() => {
189
- throw new Error("The GitHub App's private key isn't an RSA key Web Crypto takes");
196
+ const signer = Effect.tryPromise({
197
+ try: () => crypto.subtle.importKey("pkcs8", keyBytes(app.privateKey), rsaSigning, false, ["sign"]),
198
+ catch: () => gitError("INVALID_ARGUMENT", "The GitHub App's private key isn't an RSA key Web Crypto takes")
190
199
  });
191
200
  /** The App's own JWT, signed with its key, for a minute short of 10. */
192
- const jwt = async () => {
193
- const now = Math.floor(await run(Clock$1.currentTimeMillis) / 1e3);
201
+ const jwt = Effect.gen(function* () {
202
+ const now = Math.floor((yield* Clock$1.currentTimeMillis) / 1e3);
194
203
  const unsigned = `${encodeJson({
195
204
  alg: "RS256",
196
205
  typ: "JWT"
@@ -199,57 +208,60 @@ const github = /* @__PURE__ */ Effect.fnUntraced(function* (options) {
199
208
  exp: now + jwtSeconds,
200
209
  iss: app.appId
201
210
  })}`;
202
- const key = await signer();
203
- const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, encoder.encode(unsigned));
211
+ const key = yield* signer;
212
+ const signature = yield* Effect.tryPromise({
213
+ try: () => crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, encoder.encode(unsigned)),
214
+ catch: () => failed("sign the App's JWT")
215
+ });
204
216
  return `${unsigned}.${Base64Url.encode(new Uint8Array(signature))}`;
205
- };
217
+ });
206
218
  /** A token for the installation, limited to `name`, one of its account's repos, and its Git. */
207
- const tokenFor = async (name, access, signal) => {
219
+ const tokenFor = Effect.fnUntraced(function* (name, access) {
208
220
  const call = "mint a repo's installation token";
209
221
  const init = {
210
222
  method: "POST",
211
223
  headers: {
212
224
  accept: "application/vnd.github+json",
213
- authorization: `Bearer ${await jwt()}`,
225
+ authorization: `Bearer ${yield* jwt}`,
214
226
  "content-type": "application/json",
215
227
  "user-agent": "ref0-git",
216
228
  "x-github-api-version": "2022-11-28"
217
229
  },
218
- body: JSON.stringify({
219
- repositories: [name],
220
- permissions: tokenPermissions(access)
221
- })
230
+ body: tokenRequest(name, access)
222
231
  };
223
- if (signal !== void 0) init.signal = signal;
224
232
  const url = `${api}/app/installations/${encodeURIComponent(app.installationId)}/access_tokens`;
225
233
  const request = new Request(url, init);
226
- const response = await fetch(request).catch(() => {
227
- throw failed(call);
228
- });
234
+ const response = yield* sendCharged(request).pipe(Effect.mapError(() => failed(call)));
229
235
  if (response.status !== 201) {
230
- const said = await saidOf(request, response, githubKept);
231
- throw new ProviderRefused(failed(call, response.status).message, said);
236
+ const said = yield* Effect.promise(() => saidOf(request, response, githubKept));
237
+ const refused = failed(call, response.status);
238
+ return yield* Effect.fail(gitErrorFrom(refused, { cause: new ProviderRefused(refused.message, said) }));
232
239
  }
233
- const answer = decodeToken(await response.json().catch(() => void 0));
234
- if (Option.isNone(answer)) throw failed(call, response.status);
240
+ const body = yield* Effect.promise(() => response.json().catch(() => void 0));
241
+ const answer = decodeToken(body);
242
+ if (Option.isNone(answer)) return yield* Effect.fail(failed(call, response.status));
235
243
  return answer.value.token;
236
- };
237
- /** `fetch`, a read sent again while GitHub's Git doesn't know the new token yet. */
238
- const transport = async (request) => {
239
- if (request.method !== "GET") return fetch(request);
244
+ });
245
+ /**
246
+ * `send`, a read sent again while GitHub's Git doesn't know the new token yet: each send after
247
+ * the first charged here, as `httpOf` charged the first.
248
+ */
249
+ const transport = Effect.fnUntraced(function* (request) {
250
+ if (request.method !== "GET") return yield* send(request);
251
+ let response = yield* send(request.clone());
240
252
  for (const wait of propagationWaits) {
241
- const response = await fetch(request.clone());
242
253
  if (response.status !== 401) return response;
243
- await response.body?.cancel();
244
- await run(Effect.sleep(wait), request.signal);
254
+ yield* Effect.promise(async () => response.body?.cancel());
255
+ yield* Effect.sleep(wait);
256
+ response = yield* sendCharged(request.clone());
245
257
  }
246
- return fetch(request);
247
- };
248
- const remote = async (repo, access, signal) => {
258
+ return response;
259
+ });
260
+ const remote = Effect.fnUntraced(function* (repo, access) {
249
261
  const parts = repo.split("/");
250
- if (!ownerAndName.test(repo) || parts.some((part) => /^\.+$/.test(part))) throw new TypeError(`'${repo}' isn't a GitHub repo's owner/name`);
262
+ if (!ownerAndName.test(repo) || parts.some((part) => /^\.+$/.test(part))) return yield* fail("INVALID_ARGUMENT", `'${repo}' isn't a GitHub repo's owner/name`);
251
263
  const [, name = ""] = parts;
252
- const token = await tokenFor(name, access, signal);
264
+ const token = yield* tokenFor(name, access);
253
265
  return {
254
266
  url: `${git}/${repo}.git`,
255
267
  credentials: {
@@ -258,7 +270,7 @@ const github = /* @__PURE__ */ Effect.fnUntraced(function* (options) {
258
270
  },
259
271
  transport
260
272
  };
261
- };
273
+ });
262
274
  const provider = {
263
275
  name: githubName,
264
276
  remote
@@ -12,4 +12,39 @@ const responseToWeb = (response) => Effect.suspend(() => {
12
12
  headers: response.headers
13
13
  }));
14
14
  });
15
- export { responseToWeb };
15
+ /**
16
+ * `body`, cut once `signal` aborts: it errors with the signal's reason, and its source is
17
+ * cancelled, so no read of it waits past the try that sent it (#2397). A Web body outlives the
18
+ * fiber that took its response, since Effect's request drops a Web request's signal and its client
19
+ * hands the fetch's body over whole, so an interrupt never reaches a read that waits on it. The
20
+ * response is left as it came, its `redirected` and `url` with it, for the callers that read them.
21
+ */
22
+ const bodyUntil = (body, signal) => {
23
+ const reader = body.getReader();
24
+ let stop = () => {};
25
+ return new ReadableStream({
26
+ start: (controller) => {
27
+ stop = () => {
28
+ controller.error(signal.reason);
29
+ reader.cancel(signal.reason).catch(() => void 0);
30
+ };
31
+ if (signal.aborted) stop();
32
+ else signal.addEventListener("abort", stop, { once: true });
33
+ },
34
+ pull: async (controller) => {
35
+ const piece = await reader.read().catch((cause) => {
36
+ signal.removeEventListener("abort", stop);
37
+ throw cause;
38
+ });
39
+ if (signal.aborted) return;
40
+ if (!piece.done) return controller.enqueue(piece.value);
41
+ signal.removeEventListener("abort", stop);
42
+ controller.close();
43
+ },
44
+ cancel: (reason) => {
45
+ signal.removeEventListener("abort", stop);
46
+ return reader.cancel(reason);
47
+ }
48
+ });
49
+ };
50
+ export { bodyUntil, responseToWeb };
@@ -31,6 +31,7 @@ const importJobKey = "import";
31
31
  const phases = /* @__PURE__ */ new Set([
32
32
  "fetch",
33
33
  "receive",
34
+ "lfs",
34
35
  "publish"
35
36
  ]);
36
37
  const isPhase = (phase) => phases.has(phase);
@@ -2,18 +2,20 @@ import { register } from "../contracts/git.mjs";
2
2
  import { fail } from "../contracts/result.mjs";
3
3
  import { ImportJobData, MirrorJobData, Sync } from "../contracts/sync.mjs";
4
4
  import { SyncBase } from "../core/parts.mjs";
5
+ import { LfsBase } from "../lfs/base.mjs";
5
6
  import { withAudienceMemo } from "../core/ref-view.mjs";
6
7
  import { CallBudget } from "../store/call-count.mjs";
7
8
  import { importJobName, mirrorJobName } from "../store/records.mjs";
8
9
  import { importTryTimeout } from "../storage/receive-bounds.mjs";
9
10
  import { SyncState, importLimits } from "./bound.mjs";
10
11
  import { cancelWith, importWith } from "./import.mjs";
11
- import { mirrorTry, mirrorWith, mirrorsWith, removeMirrorWith } from "./mirror.mjs";
12
+ import { mirrorFailed, mirrorTry, mirrorWith, mirrorsWith, removeMirrorWith } from "./mirror.mjs";
12
13
  import { publishWith } from "./publish.mjs";
13
14
  import { importFailed, importTry } from "./step.mjs";
14
15
  import { syncRetry } from "./tries.mjs";
15
16
  import * as Effect from "effect/Effect";
16
17
  import * as HttpClient from "effect/http/HttpClient";
18
+ import * as Option from "effect/Option";
17
19
  import { Job } from "@ref0/infra";
18
20
  import * as Context from "effect/Context";
19
21
  import * as Layer from "effect/Layer";
@@ -36,10 +38,12 @@ const layerWith = (options, limits) => Layer.effectContext(Effect.gen(function*
36
38
  providers.set(provider.name, provider);
37
39
  }
38
40
  const base = yield* SyncBase;
41
+ const lfsBase = yield* Effect.serviceOption(LfsBase);
39
42
  const registration = yield* register({ name: "sync" });
40
43
  const http = CallBudget.charged(yield* HttpClient.HttpClient);
41
44
  const bound = {
42
45
  needs: Context.add(base.needs, HttpClient.HttpClient, http),
46
+ lfs: Option.isSome(lfsBase) ? lfsBase.value.copy : Effect.undefined,
43
47
  providers,
44
48
  caller: { actor: { anonymous: true } },
45
49
  limits: {
@@ -50,7 +54,7 @@ const layerWith = (options, limits) => Layer.effectContext(Effect.gen(function*
50
54
  mirrorJob: Mirror
51
55
  };
52
56
  yield* registration.addJob(Import, () => importTry(bound), { onFailure: (_data, failure) => importFailed(bound, failure) });
53
- yield* registration.addJob(Mirror, (data) => mirrorTry(bound, data));
57
+ yield* registration.addJob(Mirror, (data) => mirrorTry(bound, data), { onFailure: (data) => mirrorFailed(bound, data) });
54
58
  const run = (effect) => base.through(withAudienceMemo(Effect.provide(effect, bound.needs)));
55
59
  return Context.make(SyncState, bound).pipe(Context.add(Sync, {
56
60
  import: (input) => run(importWith(bound, input)),
@@ -0,0 +1,119 @@
1
+ import { credentialHeader } from "../client/transport.mjs";
2
+ import { gitError } from "../contracts/result.mjs";
3
+ import { BatchRequest, LfsObjectAnswer, lfsType } from "../lfs/wire.mjs";
4
+ import { boundedBytes } from "../protocol/bytes/reader.mjs";
5
+ import { decodeJson } from "../protocol/wire/json.mjs";
6
+ import { readBody } from "../store/errors.mjs";
7
+ import * as Effect from "effect/Effect";
8
+ import * as Schema from "effect/Schema";
9
+ import * as Result from "effect/Result";
10
+ /**
11
+ * The most bytes a batch's answer is read to: one of `lfsBatchMost` objects, each a link and the
12
+ * headers it's sent with, takes tens of KiB.
13
+ */
14
+ const answerBytes = 1048576;
15
+ const BatchAnswer = /* @__PURE__ */ Schema.Struct({ objects: Schema.Array(LfsObjectAnswer) });
16
+ const batchJson = /* @__PURE__ */ Schema.encodeSync(Schema.fromJsonString(BatchRequest));
17
+ /** The statuses an object's error says it's gone with: none held, or deleted. */
18
+ const goneCodes = /* @__PURE__ */ new Set([404, 410]);
19
+ /** The source's LFS API for its Git `url`, as git-lfs finds it: `<repo>.git/info/lfs`. */
20
+ const lfsEndpoint = (url) => {
21
+ const trimmed = url.replace(/\/+$/, "");
22
+ return `${trimmed.endsWith(".git") ? trimmed : `${trimmed}.git`}/info/lfs`;
23
+ };
24
+ const unreadable = (why) => gitError("UNAVAILABLE", `The source's LFS batch answer is unreadable: ${why}`, { hint: "The job tries again" });
25
+ /**
26
+ * The offers an answer's `text` makes for `wanted`, each oid once, in their order: refused unless
27
+ * it's LFS's JSON, answers each of them once at its size and names nothing else, and links each
28
+ * download by `https:` or the remote's own scheme, `remoteProtocol`.
29
+ */
30
+ const offersOf = (wanted, text, remoteProtocol) => {
31
+ const decoded = decodeJson(BatchAnswer)(text);
32
+ if (Result.isFailure(decoded)) return Result.fail(unreadable("it isn't the JSON LFS sends"));
33
+ const answers = /* @__PURE__ */ new Map();
34
+ for (const answer of decoded.success.objects) {
35
+ if (answers.has(answer.oid)) return Result.fail(unreadable(`it names ${answer.oid} twice`));
36
+ answers.set(answer.oid, answer);
37
+ }
38
+ if (answers.size !== wanted.length) return Result.fail(unreadable("it names other objects than were asked for"));
39
+ const offers = [];
40
+ for (const { oid, size } of wanted) {
41
+ const answer = answers.get(oid);
42
+ if (answer === void 0 || answer.size !== size) return Result.fail(unreadable(`it doesn't answer ${oid} at ${size} bytes`));
43
+ const download = answer.actions?.download;
44
+ if (answer.error !== void 0 || download === void 0) {
45
+ const gone = answer.error !== void 0 && goneCodes.has(answer.error.code);
46
+ offers.push({
47
+ kind: "missing",
48
+ oid,
49
+ size,
50
+ reason: gone ? "not-found" : "refused"
51
+ });
52
+ continue;
53
+ }
54
+ const protocol = URL.canParse(download.href) ? new URL(download.href).protocol : "";
55
+ if (protocol !== "https:" && protocol !== remoteProtocol) return Result.fail(unreadable(`its link for ${oid} isn't https`));
56
+ offers.push({
57
+ kind: "download",
58
+ oid,
59
+ size,
60
+ href: download.href,
61
+ header: download.header ?? {}
62
+ });
63
+ }
64
+ return Result.succeed(offers);
65
+ };
66
+ /** A request the source's API didn't answer, kept without its cause, which may hold its link. */
67
+ const unanswered = /* @__PURE__ */ gitError("UNAVAILABLE", "The source's LFS API didn't answer", { hint: "The job tries again" });
68
+ /** The source's batch refusing, by its status alone: its body may echo the credential. */
69
+ const batchRefused = (status) => gitError("UNAVAILABLE", `The source's LFS batch answered ${status}`, { hint: "The job tries again" });
70
+ /** A response's body let go, its cancel's failure no reason to fail what's already decided. */
71
+ const letGo = (response) => Effect.promise(async () => {
72
+ await response.body?.cancel().catch(() => void 0);
73
+ });
74
+ /**
75
+ * The source's offers for `wanted`, at most `lfsBatchMost` objects, asked of `remote` with its
76
+ * credentials through `send`. A source answering 404 or 501 serves no LFS API: `no-lfs`. Any other
77
+ * refusal, an answer unread or one past `answerBytes`, fails, so the job tries again.
78
+ */
79
+ const lfsDownloads = /* @__PURE__ */ Effect.fnUntraced(function* (send, remote, wanted, signal) {
80
+ if (wanted.length > 100) return yield* Effect.die(/* @__PURE__ */ new RangeError(`A batch asks at most 100 objects`));
81
+ const headers = new Headers({
82
+ accept: lfsType,
83
+ "content-type": lfsType
84
+ });
85
+ const credential = yield* credentialHeader(remote.credentials);
86
+ if (credential !== void 0) headers.set("authorization", credential);
87
+ const body = batchJson({
88
+ operation: "download",
89
+ transfers: ["basic"],
90
+ objects: wanted.map(({ oid, size }) => ({
91
+ oid,
92
+ size
93
+ })),
94
+ hash_algo: "sha256"
95
+ });
96
+ const request = new Request(`${lfsEndpoint(remote.url)}/objects/batch`, {
97
+ method: "POST",
98
+ headers,
99
+ body,
100
+ signal
101
+ });
102
+ const response = yield* Effect.mapError(send(request), () => unanswered);
103
+ if (response.status === 404 || response.status === 501) {
104
+ yield* letGo(response);
105
+ return { kind: "no-lfs" };
106
+ }
107
+ if (response.status !== 200 || response.body === null) {
108
+ yield* letGo(response);
109
+ return yield* Effect.fail(batchRefused(response.status));
110
+ }
111
+ const bytes = yield* boundedBytes(response.body, answerBytes, (reader) => readBody(() => reader.read(), () => Effect.fail(unanswered)));
112
+ if (bytes === void 0) return yield* Effect.fail(unreadable(`it's past ${answerBytes} bytes`));
113
+ const protocol = URL.canParse(remote.url) ? new URL(remote.url).protocol : "https:";
114
+ return {
115
+ kind: "offers",
116
+ offers: yield* Effect.fromResult(offersOf(wanted, new TextDecoder().decode(bytes), protocol))
117
+ };
118
+ });
119
+ export { letGo, lfsDownloads, lfsEndpoint, offersOf };