@ref0/git 0.11.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 (262) hide show
  1. package/dist/access/private-refs.mjs +8 -7
  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 +14 -3
  28. package/dist/contracts/git.d.mts +41 -12
  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 +30 -23
  42. package/dist/contracts/result.mjs +24 -9
  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 +90 -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.d.mts +1 -0
  54. package/dist/core/access.mjs +34 -13
  55. package/dist/core/ancestry.d.mts +9 -0
  56. package/dist/core/ancestry.mjs +6 -6
  57. package/dist/core/asked.mjs +68 -0
  58. package/dist/core/call-names.mjs +1 -0
  59. package/dist/core/call-services.mjs +2 -1
  60. package/dist/core/events/deliver.d.mts +1 -0
  61. package/dist/core/events/deliver.mjs +15 -3
  62. package/dist/core/forks.mjs +42 -16
  63. package/dist/core/imports.mjs +156 -13
  64. package/dist/core/index-job.mjs +9 -6
  65. package/dist/core/job-view.mjs +8 -9
  66. package/dist/core/mirror-rows.mjs +19 -4
  67. package/dist/core/objects/commits.mjs +16 -6
  68. package/dist/core/objects/reading.mjs +17 -9
  69. package/dist/core/parts.d.mts +8 -2
  70. package/dist/core/parts.mjs +1 -4
  71. package/dist/core/purge.mjs +76 -6
  72. package/dist/core/push-decide.mjs +1 -1
  73. package/dist/core/push-files.d.mts +12 -0
  74. package/dist/core/push-files.mjs +225 -0
  75. package/dist/core/push-repo.d.mts +8 -0
  76. package/dist/core/push-repo.mjs +56 -0
  77. package/dist/core/push.d.mts +17 -0
  78. package/dist/core/push.mjs +107 -32
  79. package/dist/core/receipts.mjs +26 -10
  80. package/dist/core/ref-view.mjs +59 -5
  81. package/dist/core/refs.mjs +18 -10
  82. package/dist/core/registered-rows.mjs +7 -5
  83. package/dist/core/repack.mjs +16 -11
  84. package/dist/core/repo-info.mjs +16 -9
  85. package/dist/core/repos.mjs +30 -14
  86. package/dist/core/saved-caller-views.d.mts +18 -0
  87. package/dist/core/saved-caller-views.mjs +17 -4
  88. package/dist/core/saved-callers-public.d.mts +3 -3
  89. package/dist/core/saved-callers-public.mjs +3 -2
  90. package/dist/core/saved-callers.d.mts +7 -0
  91. package/dist/core/seam.mjs +2 -2
  92. package/dist/core/view.d.mts +6 -0
  93. package/dist/core/view.mjs +45 -12
  94. package/dist/core/work.mjs +47 -22
  95. package/dist/effect.d.mts +3 -1
  96. package/dist/effect.mjs +3 -1
  97. package/dist/engine/reads.mjs +13 -6
  98. package/dist/engine/walk.mjs +4 -4
  99. package/dist/event-streams/event-streams.d.mts +1 -1
  100. package/dist/event-streams/event-streams.mjs +1 -1
  101. package/dist/event-streams/stream.d.mts +1 -1
  102. package/dist/event-streams/stream.mjs +1 -1
  103. package/dist/extend.d.mts +4 -3
  104. package/dist/extend.mjs +3 -2
  105. package/dist/http/answers.mjs +4 -2
  106. package/dist/http/core-parts.mjs +64 -15
  107. package/dist/http/handler.mjs +2 -2
  108. package/dist/http/node.mjs +5 -4
  109. package/dist/http/parts.d.mts +1 -0
  110. package/dist/http/push-upload-job.mjs +503 -0
  111. package/dist/http/push-uploads.d.mts +1 -0
  112. package/dist/http/push-uploads.mjs +120 -59
  113. package/dist/http/upload-pack.mjs +7 -6
  114. package/dist/index.d.mts +23 -24
  115. package/dist/index.mjs +4 -7
  116. package/dist/lfs/base.d.mts +7 -3
  117. package/dist/lfs/base.mjs +2 -1
  118. package/dist/lfs/copy.d.mts +46 -0
  119. package/dist/lfs/copy.mjs +26 -0
  120. package/dist/lfs/layer.mjs +4 -2
  121. package/dist/lfs/locks.mjs +14 -9
  122. package/dist/lfs/objects.d.mts +6 -0
  123. package/dist/lfs/objects.mjs +95 -61
  124. package/dist/lfs/rows.d.mts +13 -0
  125. package/dist/lfs/service.d.mts +1 -7
  126. package/dist/lfs/service.mjs +1 -9
  127. package/dist/lfs/upload-most.mjs +5 -5
  128. package/dist/node.d.mts +2 -2
  129. package/dist/protocol/bytes/sha256-hasher.d.mts +15 -0
  130. package/dist/protocol/bytes/sha256.d.mts +32 -0
  131. package/dist/protocol/bytes/sha256.mjs +105 -49
  132. package/dist/protocol/wire/advertisement.mjs +9 -4
  133. package/dist/protocol/wire/lines.d.mts +4 -2
  134. package/dist/protocol/wire/lines.mjs +11 -5
  135. package/dist/protocol/wire/push-uploads.mjs +13 -1
  136. package/dist/protocol/wire/v2.mjs +2 -2
  137. package/dist/protocol.d.mts +3 -1
  138. package/dist/protocol.mjs +3 -1
  139. package/dist/queue/advance.mjs +1 -1
  140. package/dist/queue/calls.mjs +21 -1
  141. package/dist/queue/host.d.mts +1 -7
  142. package/dist/queue/host.mjs +1 -7
  143. package/dist/queue/layer.mjs +1 -1
  144. package/dist/queue/trim.mjs +1 -1
  145. package/dist/rest/blobs.d.mts +16 -8
  146. package/dist/rest/blobs.mjs +1 -1
  147. package/dist/rest/caller.d.mts +49 -9
  148. package/dist/rest/caller.mjs +1 -1
  149. package/dist/rest/client.d.mts +10 -3
  150. package/dist/rest/client.mjs +4 -0
  151. package/dist/rest/commits.d.mts +272 -239
  152. package/dist/rest/errors.d.mts +24 -4
  153. package/dist/rest/events.d.mts +9 -6
  154. package/dist/rest/events.mjs +1 -2
  155. package/dist/rest/files.d.mts +112 -100
  156. package/dist/rest/forks.d.mts +146 -122
  157. package/dist/rest/handler.mjs +4 -57
  158. package/dist/rest/handlers.d.mts +1 -1
  159. package/dist/rest/handlers.mjs +18 -4
  160. package/dist/rest/layer.mjs +10 -2
  161. package/dist/rest/me.d.mts +8 -4
  162. package/dist/rest/merges.d.mts +8 -4
  163. package/dist/rest/paths.mjs +1 -0
  164. package/dist/rest/queue.d.mts +292 -236
  165. package/dist/rest/refs.d.mts +98 -69
  166. package/dist/rest/repos.d.mts +133 -105
  167. package/dist/rest/tags.d.mts +100 -88
  168. package/dist/rest/tokens.d.mts +192 -168
  169. package/dist/rest/topics.d.mts +154 -134
  170. package/dist/rest/trees.d.mts +32 -16
  171. package/dist/rest/work.d.mts +467 -20
  172. package/dist/rest/work.mjs +8 -0
  173. package/dist/server/edge-node.d.mts +9 -13
  174. package/dist/server/edge-node.mjs +9 -12
  175. package/dist/server/git-layer.d.mts +1 -6
  176. package/dist/server/git-layer.mjs +2 -2
  177. package/dist/server/git-namespace.d.mts +4 -4
  178. package/dist/server/joined.d.mts +15 -22
  179. package/dist/server/joined.mjs +5 -29
  180. package/dist/server/lifecycle.mjs +107 -23
  181. package/dist/server/registry.mjs +9 -1
  182. package/dist/server/server.mjs +139 -216
  183. package/dist/storage/budget.mjs +2 -2
  184. package/dist/storage/clean-up.mjs +13 -10
  185. package/dist/storage/fetch.mjs +13 -8
  186. package/dist/storage/file-limits.mjs +24 -0
  187. package/dist/storage/index-build.d.mts +1 -0
  188. package/dist/storage/index-build.mjs +106 -62
  189. package/dist/storage/index-fetch.mjs +16 -3
  190. package/dist/storage/index-reach.mjs +33 -5
  191. package/dist/storage/index-remap.mjs +8 -1
  192. package/dist/storage/index-shallow.mjs +5 -3
  193. package/dist/storage/largest-files.mjs +48 -0
  194. package/dist/storage/lfs-pointers.mjs +10 -1
  195. package/dist/storage/loose.mjs +3 -1
  196. package/dist/storage/memory-budget.mjs +154 -8
  197. package/dist/storage/merge-cut.mjs +5 -4
  198. package/dist/storage/pack-reads.mjs +246 -34
  199. package/dist/storage/pack-receive.mjs +83 -25
  200. package/dist/storage/packs.mjs +37 -21
  201. package/dist/storage/prune-keep.mjs +203 -34
  202. package/dist/storage/prune-seen.mjs +11 -6
  203. package/dist/storage/prune-walk.mjs +219 -81
  204. package/dist/storage/prune.mjs +629 -196
  205. package/dist/storage/push-uploads.mjs +36 -12
  206. package/dist/storage/quarantine.mjs +9 -7
  207. package/dist/storage/ready.mjs +47 -19
  208. package/dist/storage/receive-bounds.mjs +29 -8
  209. package/dist/storage/receive-state.mjs +8 -0
  210. package/dist/storage/receive-steps.mjs +71 -18
  211. package/dist/storage/repack.d.mts +1 -1
  212. package/dist/storage/repack.mjs +1 -8
  213. package/dist/storage/rows.mjs +12 -1
  214. package/dist/storage/shallow.d.mts +1 -0
  215. package/dist/storage/shallow.mjs +26 -4
  216. package/dist/storage/stream-whole.mjs +5 -2
  217. package/dist/storage/visible.mjs +29 -1
  218. package/dist/storage/walk.mjs +2 -1
  219. package/dist/store/catalogue.mjs +1 -0
  220. package/dist/store/cursor-seal-namespace.d.mts +2 -0
  221. package/dist/store/cursor-seal-public.d.mts +5 -0
  222. package/dist/store/cursor-seal-public.mjs +5 -0
  223. package/dist/store/cursor-seal.d.mts +16 -2
  224. package/dist/store/cursor-seal.mjs +26 -14
  225. package/dist/store/errors.mjs +9 -1
  226. package/dist/store/records.d.mts +2 -0
  227. package/dist/store/records.mjs +9 -6
  228. package/dist/store/repo-record.d.mts +27 -0
  229. package/dist/store/repo-record.mjs +141 -4
  230. package/dist/store/scopes.mjs +10 -2
  231. package/dist/sync/bound.d.mts +2 -0
  232. package/dist/sync/bound.mjs +11 -2
  233. package/dist/sync/github.d.mts +6 -1
  234. package/dist/sync/github.mjs +63 -42
  235. package/dist/sync/http.mjs +36 -1
  236. package/dist/sync/import.mjs +4 -2
  237. package/dist/sync/layer.mjs +6 -2
  238. package/dist/sync/lfs-batch.mjs +119 -0
  239. package/dist/sync/lfs-copy.mjs +251 -0
  240. package/dist/sync/mirror.mjs +227 -147
  241. package/dist/sync/said.mjs +204 -0
  242. package/dist/sync/smart-http.mjs +4 -2
  243. package/dist/sync/step.mjs +33 -13
  244. package/dist/sync/tries.mjs +71 -24
  245. package/dist/sync.d.mts +2 -2
  246. package/dist/topics/advance.mjs +10 -3
  247. package/dist/topics/host.mjs +1 -19
  248. package/dist/topics/layer.mjs +1 -1
  249. package/package.json +3 -8
  250. package/dist/auth/bridge.mjs +0 -30
  251. package/dist/auth/helpers.d.mts +0 -17
  252. package/dist/core/purge.d.mts +0 -8
  253. package/dist/core/registered-rows.d.mts +0 -4
  254. package/dist/core/repack.d.mts +0 -11
  255. package/dist/http/handler.d.mts +0 -2
  256. package/dist/rest/handler.d.mts +0 -21
  257. package/dist/rest.d.mts +0 -2
  258. package/dist/rest.mjs +0 -1
  259. package/dist/server/registry.d.mts +0 -16
  260. package/dist/server/server.d.mts +0 -36
  261. package/dist/storage/repack-job.d.mts +0 -3
  262. 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,7 +1,8 @@
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
+ import { ProviderRefused, saidOf } from "./said.mjs";
5
6
  import { hmacSha256 } from "../protocol/bytes/hmac-sha256.mjs";
6
7
  import * as Clock$1 from "effect/Clock";
7
8
  import * as Effect from "effect/Effect";
@@ -9,7 +10,6 @@ import * as HttpClient from "effect/http/HttpClient";
9
10
  import * as Option from "effect/Option";
10
11
  import * as Schema from "effect/Schema";
11
12
  import * as Result from "effect/Result";
12
- import * as Context from "effect/Context";
13
13
  import * as Hex from "effect/encoding/Hex";
14
14
  import * as Base64 from "effect/encoding/Base64";
15
15
  import * as HttpClientRequest from "effect/http/HttpClientRequest";
@@ -47,8 +47,18 @@ const tokenPermissions = (access) => ({
47
47
  metadata: "read"
48
48
  });
49
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
+ });
55
+ /**
56
+ * The fields of GitHub's JSON refusal kept: its `message` alone. `documentation_url` links a page
57
+ * of the docs, which says nothing of this failure, and is a URL, where userinfo could ride.
58
+ */
59
+ const githubKept = ["message"];
50
60
  /** A failure of the provider's own: its message names the call and the status, never a token. */
51
- 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" });
52
62
  /** The DER length of `size` bytes. */
53
63
  const derLength = (size) => {
54
64
  if (size < 128) return [size];
@@ -168,23 +178,28 @@ const signedBody = async (request, mac) => {
168
178
  reader.releaseLock();
169
179
  }
170
180
  };
171
- /** 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
+ */
172
187
  const github = /* @__PURE__ */ Effect.fnUntraced(function* (options) {
173
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");
174
189
  const client = yield* HttpClient.HttpClient;
175
- const clock = yield* Effect.clockWith(Effect.succeed);
176
- const context = Context.make(Clock$1.Clock, clock);
177
- const run = runnerIn(context);
178
- 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));
179
193
  const { app } = options;
180
194
  const api = (options.apiUrl ?? "https://api.github.com").replace(/\/$/, "");
181
195
  const git = (options.gitUrl ?? "https://github.com").replace(/\/$/, "");
182
- const signer = () => crypto.subtle.importKey("pkcs8", keyBytes(app.privateKey), rsaSigning, false, ["sign"]).catch(() => {
183
- 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")
184
199
  });
185
200
  /** The App's own JWT, signed with its key, for a minute short of 10. */
186
- const jwt = async () => {
187
- 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);
188
203
  const unsigned = `${encodeJson({
189
204
  alg: "RS256",
190
205
  typ: "JWT"
@@ -193,54 +208,60 @@ const github = /* @__PURE__ */ Effect.fnUntraced(function* (options) {
193
208
  exp: now + jwtSeconds,
194
209
  iss: app.appId
195
210
  })}`;
196
- const key = await signer();
197
- 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
+ });
198
216
  return `${unsigned}.${Base64Url.encode(new Uint8Array(signature))}`;
199
- };
217
+ });
200
218
  /** A token for the installation, limited to `name`, one of its account's repos, and its Git. */
201
- const tokenFor = async (name, access, signal) => {
219
+ const tokenFor = Effect.fnUntraced(function* (name, access) {
202
220
  const call = "mint a repo's installation token";
203
221
  const init = {
204
222
  method: "POST",
205
223
  headers: {
206
224
  accept: "application/vnd.github+json",
207
- authorization: `Bearer ${await jwt()}`,
225
+ authorization: `Bearer ${yield* jwt}`,
208
226
  "content-type": "application/json",
209
227
  "user-agent": "ref0-git",
210
228
  "x-github-api-version": "2022-11-28"
211
229
  },
212
- body: JSON.stringify({
213
- repositories: [name],
214
- permissions: tokenPermissions(access)
215
- })
230
+ body: tokenRequest(name, access)
216
231
  };
217
- if (signal !== void 0) init.signal = signal;
218
232
  const url = `${api}/app/installations/${encodeURIComponent(app.installationId)}/access_tokens`;
219
233
  const request = new Request(url, init);
220
- const response = await fetch(request).catch(() => {
221
- throw failed(call);
222
- });
223
- if (response.status !== 201) throw failed(call, response.status);
224
- const answer = decodeToken(await response.json().catch(() => void 0));
225
- if (Option.isNone(answer)) throw failed(call, response.status);
234
+ const response = yield* sendCharged(request).pipe(Effect.mapError(() => failed(call)));
235
+ if (response.status !== 201) {
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) }));
239
+ }
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));
226
243
  return answer.value.token;
227
- };
228
- /** `fetch`, a read sent again while GitHub's Git doesn't know the new token yet. */
229
- const transport = async (request) => {
230
- 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());
231
252
  for (const wait of propagationWaits) {
232
- const response = await fetch(request.clone());
233
253
  if (response.status !== 401) return response;
234
- await response.body?.cancel();
235
- 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());
236
257
  }
237
- return fetch(request);
238
- };
239
- const remote = async (repo, access, signal) => {
258
+ return response;
259
+ });
260
+ const remote = Effect.fnUntraced(function* (repo, access) {
240
261
  const parts = repo.split("/");
241
- 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`);
242
263
  const [, name = ""] = parts;
243
- const token = await tokenFor(name, access, signal);
264
+ const token = yield* tokenFor(name, access);
244
265
  return {
245
266
  url: `${git}/${repo}.git`,
246
267
  credentials: {
@@ -249,7 +270,7 @@ const github = /* @__PURE__ */ Effect.fnUntraced(function* (options) {
249
270
  },
250
271
  transport
251
272
  };
252
- };
273
+ });
253
274
  const provider = {
254
275
  name: githubName,
255
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);
@@ -143,9 +144,10 @@ const cancelWith = /* @__PURE__ */ Effect.fnUntraced(function* (_bound, input) {
143
144
  kind: "repo.update",
144
145
  repo: input.repo
145
146
  };
146
- const { internalId } = yield* openRepo(caller, operation, [], input.internalId);
147
+ const opened = yield* openRepo(caller, operation, [], input.internalId, "first-read");
148
+ const { internalId } = opened;
147
149
  const { store } = yield* CoreParts;
148
- const read = yield* readImport(store, internalId);
150
+ const read = yield* readImport(store, internalId, opened);
149
151
  if (read.row?.state !== "running") return yield* noImport(input.repo);
150
152
  if (read.cancelled) return;
151
153
  yield* storeCall(() => store.commit(repoScope(internalId), {
@@ -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 };