@smthrs/artifacts 0.0.0-stage → 1.0.0-rc.4

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 (171) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/LICENSE +21 -0
  3. package/README.md +173 -2
  4. package/dist/cjs/ArtifactBackupLease.d.ts +34 -0
  5. package/dist/cjs/ArtifactBackupLease.d.ts.map +1 -0
  6. package/dist/cjs/ArtifactBackupLease.js +175 -0
  7. package/dist/cjs/ArtifactBackupLease.js.map +7 -0
  8. package/dist/cjs/ArtifactStore.d.ts +129 -0
  9. package/dist/cjs/ArtifactStore.d.ts.map +1 -0
  10. package/dist/cjs/ArtifactStore.js +73 -0
  11. package/dist/cjs/ArtifactStore.js.map +7 -0
  12. package/dist/cjs/ArtifactStoreError.d.ts +82 -0
  13. package/dist/cjs/ArtifactStoreError.d.ts.map +1 -0
  14. package/dist/cjs/ArtifactStoreError.js +72 -0
  15. package/dist/cjs/ArtifactStoreError.js.map +7 -0
  16. package/dist/cjs/ArtifactStoreMetrics.d.ts +70 -0
  17. package/dist/cjs/ArtifactStoreMetrics.d.ts.map +1 -0
  18. package/dist/cjs/ArtifactStoreMetrics.js +51 -0
  19. package/dist/cjs/ArtifactStoreMetrics.js.map +7 -0
  20. package/dist/cjs/ArtifactSweep.d.ts +185 -0
  21. package/dist/cjs/ArtifactSweep.d.ts.map +1 -0
  22. package/dist/cjs/ArtifactSweep.js +163 -0
  23. package/dist/cjs/ArtifactSweep.js.map +7 -0
  24. package/dist/cjs/CombinedArtifacts.d.ts +103 -0
  25. package/dist/cjs/CombinedArtifacts.d.ts.map +1 -0
  26. package/dist/cjs/CombinedArtifacts.js +189 -0
  27. package/dist/cjs/CombinedArtifacts.js.map +7 -0
  28. package/dist/cjs/FileLease.d.ts +113 -0
  29. package/dist/cjs/FileLease.d.ts.map +1 -0
  30. package/dist/cjs/FileLease.js +201 -0
  31. package/dist/cjs/FileLease.js.map +7 -0
  32. package/dist/cjs/FileSystemArtifactStore.d.ts +93 -0
  33. package/dist/cjs/FileSystemArtifactStore.d.ts.map +1 -0
  34. package/dist/cjs/FileSystemArtifactStore.js +276 -0
  35. package/dist/cjs/FileSystemArtifactStore.js.map +7 -0
  36. package/dist/cjs/MemoryArtifactStore.d.ts +25 -0
  37. package/dist/cjs/MemoryArtifactStore.d.ts.map +1 -0
  38. package/dist/cjs/MemoryArtifactStore.js +84 -0
  39. package/dist/cjs/MemoryArtifactStore.js.map +7 -0
  40. package/dist/cjs/NoopArtifactStore.d.ts +17 -0
  41. package/dist/cjs/NoopArtifactStore.d.ts.map +1 -0
  42. package/dist/cjs/NoopArtifactStore.js +46 -0
  43. package/dist/cjs/NoopArtifactStore.js.map +7 -0
  44. package/dist/cjs/RemoteArtifacts.d.ts +237 -0
  45. package/dist/cjs/RemoteArtifacts.d.ts.map +1 -0
  46. package/dist/cjs/RemoteArtifacts.js +405 -0
  47. package/dist/cjs/RemoteArtifacts.js.map +7 -0
  48. package/dist/cjs/index.d.ts +65 -0
  49. package/dist/cjs/index.d.ts.map +1 -0
  50. package/dist/cjs/index.js +47 -0
  51. package/dist/cjs/index.js.map +7 -0
  52. package/dist/cjs/internal/ArtifactLocks.d.ts +30 -0
  53. package/dist/cjs/internal/ArtifactLocks.d.ts.map +1 -0
  54. package/dist/cjs/internal/ArtifactLocks.js +93 -0
  55. package/dist/cjs/internal/ArtifactLocks.js.map +7 -0
  56. package/dist/cjs/internal/ArtifactPath.d.ts +19 -0
  57. package/dist/cjs/internal/ArtifactPath.d.ts.map +1 -0
  58. package/dist/cjs/internal/ArtifactPath.js +74 -0
  59. package/dist/cjs/internal/ArtifactPath.js.map +7 -0
  60. package/dist/cjs/measureBytes.d.ts +18 -0
  61. package/dist/cjs/measureBytes.d.ts.map +1 -0
  62. package/dist/cjs/measureBytes.js +43 -0
  63. package/dist/cjs/measureBytes.js.map +7 -0
  64. package/dist/cjs/package.json +1 -0
  65. package/dist/cjs/snapshotBytes.d.ts +19 -0
  66. package/dist/cjs/snapshotBytes.d.ts.map +1 -0
  67. package/dist/cjs/snapshotBytes.js +41 -0
  68. package/dist/cjs/snapshotBytes.js.map +7 -0
  69. package/dist/cjs/validateDigest.d.ts +22 -0
  70. package/dist/cjs/validateDigest.d.ts.map +1 -0
  71. package/dist/cjs/validateDigest.js +42 -0
  72. package/dist/cjs/validateDigest.js.map +7 -0
  73. package/dist/esm/ArtifactBackupLease.d.ts +34 -0
  74. package/dist/esm/ArtifactBackupLease.d.ts.map +1 -0
  75. package/dist/esm/ArtifactBackupLease.js +117 -0
  76. package/dist/esm/ArtifactBackupLease.js.map +1 -0
  77. package/dist/esm/ArtifactStore.d.ts +129 -0
  78. package/dist/esm/ArtifactStore.d.ts.map +1 -0
  79. package/dist/esm/ArtifactStore.js +83 -0
  80. package/dist/esm/ArtifactStore.js.map +1 -0
  81. package/dist/esm/ArtifactStoreError.d.ts +82 -0
  82. package/dist/esm/ArtifactStoreError.d.ts.map +1 -0
  83. package/dist/esm/ArtifactStoreError.js +77 -0
  84. package/dist/esm/ArtifactStoreError.js.map +1 -0
  85. package/dist/esm/ArtifactStoreMetrics.d.ts +70 -0
  86. package/dist/esm/ArtifactStoreMetrics.d.ts.map +1 -0
  87. package/dist/esm/ArtifactStoreMetrics.js +77 -0
  88. package/dist/esm/ArtifactStoreMetrics.js.map +1 -0
  89. package/dist/esm/ArtifactSweep.d.ts +185 -0
  90. package/dist/esm/ArtifactSweep.d.ts.map +1 -0
  91. package/dist/esm/ArtifactSweep.js +202 -0
  92. package/dist/esm/ArtifactSweep.js.map +1 -0
  93. package/dist/esm/CombinedArtifacts.d.ts +103 -0
  94. package/dist/esm/CombinedArtifacts.d.ts.map +1 -0
  95. package/dist/esm/CombinedArtifacts.js +214 -0
  96. package/dist/esm/CombinedArtifacts.js.map +1 -0
  97. package/dist/esm/FileLease.d.ts +113 -0
  98. package/dist/esm/FileLease.d.ts.map +1 -0
  99. package/dist/esm/FileLease.js +239 -0
  100. package/dist/esm/FileLease.js.map +1 -0
  101. package/dist/esm/FileSystemArtifactStore.d.ts +93 -0
  102. package/dist/esm/FileSystemArtifactStore.d.ts.map +1 -0
  103. package/dist/esm/FileSystemArtifactStore.js +336 -0
  104. package/dist/esm/FileSystemArtifactStore.js.map +1 -0
  105. package/dist/esm/MemoryArtifactStore.d.ts +25 -0
  106. package/dist/esm/MemoryArtifactStore.d.ts.map +1 -0
  107. package/dist/esm/MemoryArtifactStore.js +67 -0
  108. package/dist/esm/MemoryArtifactStore.js.map +1 -0
  109. package/dist/esm/NoopArtifactStore.d.ts +17 -0
  110. package/dist/esm/NoopArtifactStore.d.ts.map +1 -0
  111. package/dist/esm/NoopArtifactStore.js +27 -0
  112. package/dist/esm/NoopArtifactStore.js.map +1 -0
  113. package/dist/esm/RemoteArtifacts.d.ts +237 -0
  114. package/dist/esm/RemoteArtifacts.d.ts.map +1 -0
  115. package/dist/esm/RemoteArtifacts.js +554 -0
  116. package/dist/esm/RemoteArtifacts.js.map +1 -0
  117. package/dist/esm/index.d.ts +65 -0
  118. package/dist/esm/index.d.ts.map +1 -0
  119. package/dist/esm/index.js +65 -0
  120. package/dist/esm/index.js.map +1 -0
  121. package/dist/esm/internal/ArtifactLocks.d.ts +30 -0
  122. package/dist/esm/internal/ArtifactLocks.d.ts.map +1 -0
  123. package/dist/esm/internal/ArtifactLocks.js +86 -0
  124. package/dist/esm/internal/ArtifactLocks.js.map +1 -0
  125. package/dist/esm/internal/ArtifactPath.d.ts +19 -0
  126. package/dist/esm/internal/ArtifactPath.d.ts.map +1 -0
  127. package/dist/esm/internal/ArtifactPath.js +59 -0
  128. package/dist/esm/internal/ArtifactPath.js.map +1 -0
  129. package/dist/esm/measureBytes.d.ts +18 -0
  130. package/dist/esm/measureBytes.d.ts.map +1 -0
  131. package/dist/esm/measureBytes.js +22 -0
  132. package/dist/esm/measureBytes.js.map +1 -0
  133. package/dist/esm/snapshotBytes.d.ts +19 -0
  134. package/dist/esm/snapshotBytes.d.ts.map +1 -0
  135. package/dist/esm/snapshotBytes.js +30 -0
  136. package/dist/esm/snapshotBytes.js.map +1 -0
  137. package/dist/esm/validateDigest.d.ts +22 -0
  138. package/dist/esm/validateDigest.d.ts.map +1 -0
  139. package/dist/esm/validateDigest.js +26 -0
  140. package/dist/esm/validateDigest.js.map +1 -0
  141. package/docs/README.md +200 -0
  142. package/docs/api.md +474 -0
  143. package/docs/concepts/content-addressing.md +174 -0
  144. package/docs/concepts/coordination.md +141 -0
  145. package/docs/concepts/tiers.md +147 -0
  146. package/docs/guides/fence-a-backup.md +123 -0
  147. package/docs/guides/reclaim-disk-space.md +143 -0
  148. package/docs/guides/serve-the-artifact-protocol.md +140 -0
  149. package/docs/guides/share-artifacts-across-machines.md +180 -0
  150. package/docs/guides/test-against-an-artifact-store.md +158 -0
  151. package/docs/installation.md +98 -0
  152. package/docs/quickstart.md +182 -0
  153. package/docs/troubleshooting.md +232 -0
  154. package/package.json +179 -3
  155. package/src/ArtifactBackupLease.ts +213 -0
  156. package/src/ArtifactStore.ts +152 -0
  157. package/src/ArtifactStoreError.ts +96 -0
  158. package/src/ArtifactStoreMetrics.ts +83 -0
  159. package/src/ArtifactSweep.ts +336 -0
  160. package/src/CombinedArtifacts.ts +369 -0
  161. package/src/FileLease.ts +380 -0
  162. package/src/FileSystemArtifactStore.ts +459 -0
  163. package/src/MemoryArtifactStore.ts +83 -0
  164. package/src/NoopArtifactStore.ts +30 -0
  165. package/src/RemoteArtifacts.ts +809 -0
  166. package/src/index.ts +71 -0
  167. package/src/internal/ArtifactLocks.ts +110 -0
  168. package/src/internal/ArtifactPath.ts +72 -0
  169. package/src/measureBytes.ts +28 -0
  170. package/src/snapshotBytes.ts +34 -0
  171. package/src/validateDigest.ts +31 -0
@@ -0,0 +1,554 @@
1
+ /**
2
+ * The shared artifact tier: an {@link ArtifactStore.Service} spoken over HTTP.
3
+ *
4
+ * The wire protocol mirrors Bazel's dumb-HTTP remote cache, class
5
+ * `HttpCacheClient` in `com.google.devtools.build.lib.remote.http`, which
6
+ * documents it as: "CAS (Content Addressable Storage) blobs are stored under
7
+ * the path `/cas/base16-key`", uploaded with `PUT`, downloaded with `GET`. We add
8
+ * `HEAD /cas/{digest}` for a single existence probe and
9
+ * `POST /cas/findMissing` for the batched one, because Bazel's HTTP client has
10
+ * no `findMissingDigests` at all — it answers "everything is missing" and
11
+ * re-uploads — and a batched probe is the whole reason
12
+ * `MissingDigestsFinder` exists in the gRPC client.
13
+ *
14
+ * Transport is Effect's own `HttpClient` tag. There is no lower transport in
15
+ * this repository, and there does not need to be one: the kernel already
16
+ * decorates that tag with `net:get`/`net:post` capability checks, so a remote
17
+ * artifact fetch is permission-checked like every other egress.
18
+ *
19
+ * ## Chunked uploads
20
+ *
21
+ * With `chunkBytes` set, a blob past that size travels as a sequence of
22
+ * `PUT /cas/{digest}` requests carrying `Content-Range: bytes {a}-{b}/{total}`,
23
+ * preceded by a `HEAD /cas/{digest}` existence probe and a
24
+ * `Content-Range: bytes *\/{total}` probe with an empty body. This is the
25
+ * resumable-upload shape HTTP already has: the range probe asks what prefix
26
+ * the tier holds and `308` means "keep going", with a `Range: bytes=0-{last}`
27
+ * header on the probe or on a chunk answer moving the offset.
28
+ *
29
+ * Only a `308` continues the sequence, and the completing chunk's `2xx` is
30
+ * confirmed with `HEAD` before `put` reports the digest as published. A `2xx`
31
+ * anywhere else, to the empty probe or to a chunk the tier is still owed bytes
32
+ * after, reads as a tier that ignored `Content-Range` and stored the body it
33
+ * was handed, which is what plain WebDAV `PUT` does. That tier, the one that
34
+ * answers `400`, `411`, or `416`, and the one whose `HEAD` will not confirm
35
+ * the stored length all get the same treatment: one whole-blob `PUT`, which
36
+ * overwrites the partial body the sequence left behind. So the blob always
37
+ * lands whole, and the cost of turning the dial on against a server that
38
+ * never learned about it is round trips, never a digest published over bytes
39
+ * the server does not hold.
40
+ *
41
+ * This repository's own hosted and self-hosted cache services are such
42
+ * servers: neither implements the resumable sequence, and both refuse a
43
+ * ranged `PUT` with `400`, RFC 9110 section 14.5's answer from a resource
44
+ * that does not support partial `PUT`. Against them `chunkBytes` costs the
45
+ * probe round trip and the blob travels whole, and both cap one request body
46
+ * at 16 MiB, so a blob past that cap is refused with `413` in either mode.
47
+ *
48
+ * The endpoint and its credentials arrive as **layer construction options**.
49
+ * They are capabilities, never step inputs: they are not hashed into a step
50
+ * key, journaled, or returned in a recorded result. Invalid endpoint errors are
51
+ * sanitized before they cross the boundary.
52
+ *
53
+ * @since 1.0.0-rc.0
54
+ */
55
+ import * as Duration from "effect/Duration";
56
+ import * as Effect from "effect/Effect";
57
+ import * as Layer from "effect/Layer";
58
+ import * as Option from "effect/Option";
59
+ import * as Schema from "effect/Schema";
60
+ import * as Stream from "effect/Stream";
61
+ import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";
62
+ import * as Headers from "effect/unstable/http/Headers";
63
+ import * as HttpClient from "effect/unstable/http/HttpClient";
64
+ import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
65
+ import * as ArtifactStore from "./ArtifactStore.js";
66
+ /**
67
+ * How eagerly a composition materializes shared blobs into its local store.
68
+ *
69
+ * @category models
70
+ * @since 1.0.0-rc.0
71
+ */
72
+ export const DownloadPolicy = Schema.Literals(["all", "toplevel", "minimal"]);
73
+ /**
74
+ * Every download policy, in materialization order.
75
+ *
76
+ * @category models
77
+ * @since 1.0.0-rc.0
78
+ */
79
+ export const downloadPolicies = Object.freeze(["all", "toplevel", "minimal"]);
80
+ /**
81
+ * Reads the download policy a store declares, or `undefined` for a store that
82
+ * declares none — every local store, and any foreign implementation.
83
+ *
84
+ * @category getters
85
+ * @since 1.0.0-rc.0
86
+ */
87
+ export const downloadPolicyOf = (store) => {
88
+ const declared = store.downloadPolicy;
89
+ return Schema.is(DownloadPolicy)(declared) ? declared : undefined;
90
+ };
91
+ /**
92
+ * The default download deadline. 60 seconds is Bazel's `--remote_timeout`
93
+ * default, governing the same dumb-HTTP cache protocol.
94
+ */
95
+ const defaultDownloadTimeout = Duration.seconds(60);
96
+ const defaultUploadTimeout = Duration.seconds(60);
97
+ const defaultRequestTimeout = Duration.seconds(60);
98
+ /**
99
+ * The default bound on a downloaded blob: 256 MiB. Artifacts are spilled step
100
+ * values, not media libraries; a body past this size is far more likely a
101
+ * mis-serving cache than a legitimate blob, and the dial is per-store for a
102
+ * deployment that knows better.
103
+ */
104
+ const defaultMaxDownloadBytes = 256 * 1024 * 1024;
105
+ const maxFindMissingBatchDigests = 1_000;
106
+ const maxFindMissingBodyBytes = 256 * 1024;
107
+ const encoder = new TextEncoder();
108
+ const decoder = new TextDecoder("utf-8", { fatal: true });
109
+ /**
110
+ * The credential-free part of a transport failure: the HTTP client's reason
111
+ * tag and the first operating-system error code (`ECONNREFUSED`, `ENOTFOUND`,
112
+ * `CERT_HAS_EXPIRED`) in its cause chain. Never the request, the URL, the
113
+ * headers, or free-form text, any of which may carry a credential.
114
+ */
115
+ const transportReason = (cause) => {
116
+ const reason = cause?.reason;
117
+ const tag = typeof reason?._tag === "string" ? reason._tag : undefined;
118
+ let code;
119
+ let current = reason ?? cause;
120
+ for (let depth = 0; depth < 8 && typeof current === "object" && current !== null; depth++) {
121
+ const candidate = current.code;
122
+ if (typeof candidate === "string" && /^[A-Z][A-Z0-9_]{1,63}$/.test(candidate)) {
123
+ code = candidate;
124
+ break;
125
+ }
126
+ current = current.cause;
127
+ }
128
+ const parts = [tag, code].filter((part) => part !== undefined);
129
+ return parts.length === 0 ? undefined : parts.join(" ");
130
+ };
131
+ const transportFailure = (operation, cause) => {
132
+ const reason = transportReason(cause);
133
+ return new ArtifactStore.ArtifactStoreError({
134
+ code: "transport_failed",
135
+ message: `the remote artifact tier refused ${operation}${reason === undefined ? "" : ` (${reason})`}`
136
+ });
137
+ };
138
+ const unexpectedStatus = (operation, status) => new ArtifactStore.ArtifactStoreError({
139
+ code: "transport_failed",
140
+ message: `the remote artifact tier answered ${operation} with HTTP ${status}`
141
+ });
142
+ const invalidOption = (name) => new ArtifactStore.ArtifactStoreError({
143
+ code: "invalid_configuration",
144
+ message: `invalid remote artifact option: ${name}`
145
+ });
146
+ /** The batched-probe response body. */
147
+ const FindMissingResponse = Schema.Struct({ missing: Schema.Array(Schema.String) });
148
+ /** An RFC 9110 field-name token. */
149
+ const headerName = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
150
+ /** Whether a header value carries a C0 control character or DEL, CR and LF included. */
151
+ const hasControlText = (value) => {
152
+ for (let index = 0; index < value.length; index++) {
153
+ const unit = value.charCodeAt(index);
154
+ if (unit <= 0x1f || unit === 0x7f)
155
+ return true;
156
+ }
157
+ return false;
158
+ };
159
+ const configurationFailure = (message) => new ArtifactStore.ArtifactStoreError({ code: "invalid_configuration", message });
160
+ /**
161
+ * A 2xx is success, a 404 is a miss, and everything else is a transport
162
+ * failure. Bazel's HTTP client takes the same three-way split; it is the only
163
+ * classification a dumb-HTTP cache can support, because there is no richer
164
+ * error envelope on the wire.
165
+ */
166
+ const isOk = (response) => response.status >= 200 && response.status < 300;
167
+ /**
168
+ * Builds a remote artifact store over Effect's `HttpClient`.
169
+ *
170
+ * @category constructors
171
+ * @since 1.0.0-rc.0
172
+ * @slop
173
+ */
174
+ export const make = (options) => Effect.gen(function* () {
175
+ const configured = yield* Effect.try({
176
+ try: () => {
177
+ const headers = options.headers === undefined
178
+ ? undefined
179
+ : Object.freeze(Object.fromEntries(Object.entries(options.headers).map(([name, value]) => {
180
+ // Refused here, once, rather than on every request as an opaque
181
+ // transport failure: a CRLF in a value or a space in a name can
182
+ // never become a valid header.
183
+ if (typeof value !== "string" || value.length > 16 * 1024 || hasControlText(value)) {
184
+ throw new TypeError("header value");
185
+ }
186
+ if (!headerName.test(name))
187
+ throw new TypeError("header name");
188
+ return [name, value];
189
+ })));
190
+ return {
191
+ endpoint: options.endpoint,
192
+ headers,
193
+ downloadTimeout: options.downloadTimeout,
194
+ uploadTimeout: options.uploadTimeout,
195
+ requestTimeout: options.requestTimeout,
196
+ maxDownloadBytes: options.maxDownloadBytes,
197
+ maxFindMissingResponseBytes: options.maxFindMissingResponseBytes,
198
+ chunkBytes: options.chunkBytes,
199
+ downloadPolicy: options.downloadPolicy
200
+ };
201
+ },
202
+ catch: () => invalidOption("options")
203
+ });
204
+ if (typeof configured.endpoint !== "string")
205
+ return yield* Effect.fail(invalidOption("endpoint"));
206
+ const endpoint = yield* Effect.try({
207
+ try: () => new URL(configured.endpoint),
208
+ catch: () => configurationFailure("invalid remote artifact endpoint")
209
+ });
210
+ // A self-hosted cache on this machine is reachable over plain HTTP, and
211
+ // loopback traffic never leaves the host. Only literal loopback names are
212
+ // exempt: a `*.localhost` name reaches loopback only on a resolver that
213
+ // follows RFC 6761, and one that forwards it to DNS would carry the
214
+ // credential headers over plaintext to whatever host answers.
215
+ const loopback = endpoint.hostname === "localhost" || endpoint.hostname === "127.0.0.1" ||
216
+ endpoint.hostname === "[::1]";
217
+ if (endpoint.protocol !== "https:" && !(endpoint.protocol === "http:" && loopback)) {
218
+ return yield* Effect.fail(configurationFailure("remote artifact endpoint must use HTTPS"));
219
+ }
220
+ if (endpoint.username !== "" || endpoint.password !== "" || endpoint.search !== "" || endpoint.hash !== "") {
221
+ return yield* Effect.fail(configurationFailure("remote artifact endpoint must not contain credentials, a query, or a fragment"));
222
+ }
223
+ endpoint.pathname = endpoint.pathname.replace(/\/+$/, "");
224
+ const base = endpoint.toString().replace(/\/+$/, "");
225
+ const headers = configured.headers;
226
+ const client = yield* HttpClient.HttpClient;
227
+ const credentialNames = Object.keys(headers ?? {}).map((name) => name.toLowerCase());
228
+ /**
229
+ * Protocol-owned headers are computed from each request's body and range,
230
+ * never inherited from credentials, including on a whole-blob fallback.
231
+ */
232
+ const authorized = (request) => (headers === undefined ? request : HttpClientRequest.setHeaders(request, headers)).pipe(HttpClientRequest.removeHeader("content-type"), HttpClientRequest.removeHeader("content-length"), HttpClientRequest.removeHeader("content-range"));
233
+ // The address is a URL path segment, so it is refused before it is
234
+ // interpolated and percent-encoded when it is: an address carrying a
235
+ // separator or a `..` would otherwise point this client at a different
236
+ // resource on the configured endpoint. `ArtifactStore.validateDigest` is
237
+ // the same guard the filesystem tier applies to the same untrusted input —
238
+ // a digest read back out of a durable row.
239
+ const casUrl = (digest) => `${base}/cas/${digest}`;
240
+ const scopedClient = HttpClient.withScope(client);
241
+ /**
242
+ * Keep body processing inside the exchange; abort unused responses on every exit.
243
+ *
244
+ * Redirects are never followed. A fetch-based client follows them by
245
+ * default and strips only `Authorization` on a cross-origin hop, so a
246
+ * tier answering `3xx` would otherwise receive the credential headers at
247
+ * another origin or over plain HTTP. Manual mode hands the `3xx` back,
248
+ * where it is an unexpected status (or, for `308`, the resumable-upload
249
+ * answer this protocol already speaks).
250
+ */
251
+ const send = (operation, request, use) => Effect.gen(function* () {
252
+ const redactedNames = yield* Headers.CurrentRedactedNames;
253
+ const requestInit = yield* Effect.serviceOption(FetchHttpClient.RequestInit);
254
+ return yield* scopedClient.execute(request).pipe(Effect.provideService(FetchHttpClient.RequestInit, {
255
+ ...Option.getOrUndefined(requestInit),
256
+ redirect: "manual"
257
+ }), Effect.mapError((cause) => transportFailure(operation, cause)), Effect.flatMap(use), Effect.provideService(Headers.CurrentRedactedNames, [...redactedNames, ...credentialNames]), Effect.scoped);
258
+ });
259
+ const parseDeadline = (name, input, fallback) => Effect.gen(function* () {
260
+ const parsed = Duration.fromInput(input ?? fallback);
261
+ if (Option.isNone(parsed) ||
262
+ !Number.isFinite(Duration.toMillis(parsed.value)) ||
263
+ Duration.toMillis(parsed.value) <= 0) {
264
+ return yield* Effect.fail(invalidOption(name));
265
+ }
266
+ return parsed.value;
267
+ });
268
+ const downloadDeadline = yield* parseDeadline("downloadTimeout", configured.downloadTimeout, defaultDownloadTimeout);
269
+ const uploadDeadline = yield* parseDeadline("uploadTimeout", configured.uploadTimeout, defaultUploadTimeout);
270
+ const requestDeadline = yield* parseDeadline("requestTimeout", configured.requestTimeout, defaultRequestTimeout);
271
+ const maxDownloadBytes = configured.maxDownloadBytes ?? defaultMaxDownloadBytes;
272
+ if (!Number.isSafeInteger(maxDownloadBytes) || maxDownloadBytes <= 0) {
273
+ return yield* Effect.fail(invalidOption("maxDownloadBytes"));
274
+ }
275
+ const maxFindMissingResponseBytes = configured.maxFindMissingResponseBytes ?? maxFindMissingBodyBytes;
276
+ if (!Number.isSafeInteger(maxFindMissingResponseBytes) ||
277
+ maxFindMissingResponseBytes <= 0 ||
278
+ maxFindMissingResponseBytes > maxFindMissingBodyBytes) {
279
+ return yield* Effect.fail(invalidOption("maxFindMissingResponseBytes"));
280
+ }
281
+ const chunkBytes = configured.chunkBytes;
282
+ if (chunkBytes !== undefined && (!Number.isSafeInteger(chunkBytes) || chunkBytes <= 0)) {
283
+ return yield* Effect.fail(invalidOption("chunkBytes"));
284
+ }
285
+ const downloadPolicy = configured.downloadPolicy ?? "all";
286
+ if (!Schema.is(DownloadPolicy)(downloadPolicy)) {
287
+ return yield* Effect.fail(invalidOption("downloadPolicy"));
288
+ }
289
+ const bodyTooLarge = (operation, received, bound) => new ArtifactStore.ArtifactStoreError({
290
+ code: "transport_failed",
291
+ message: `the remote artifact tier answered ${operation} with ${received} bytes, past the ${bound}-byte bound`
292
+ });
293
+ const timedOut = (operation) => new ArtifactStore.ArtifactStoreError({
294
+ code: "transport_failed",
295
+ message: `the remote artifact tier did not finish ${operation} within its configured deadline`
296
+ });
297
+ const within = (operation, deadline, effect) => effect.pipe(Effect.timeout(deadline), Effect.catchTag("TimeoutError", () => Effect.fail(timedOut(operation))));
298
+ /**
299
+ * Reads a download body incrementally, refusing it the moment it exceeds
300
+ * the size bound; a `Content-Length` that already declares the excess is
301
+ * refused before a single body byte is read. Streaming instead of
302
+ * buffering the whole body means the guard fires at most one chunk past
303
+ * the bound, never after an arbitrarily large response is in memory.
304
+ */
305
+ const readBounded = (response, operation, bound) => Effect.gen(function* () {
306
+ const declared = response.headers["content-length"];
307
+ if (declared !== undefined) {
308
+ const declaredBytes = Number(declared);
309
+ if (!/^\d+$/.test(declared) || !Number.isSafeInteger(declaredBytes)) {
310
+ return yield* Effect.fail(transportFailure(`${operation} body`));
311
+ }
312
+ if (declaredBytes > bound)
313
+ return yield* Effect.fail(bodyTooLarge(operation, declaredBytes, bound));
314
+ }
315
+ const chunks = [];
316
+ let received = 0;
317
+ yield* Stream.runForEach(response.stream, (chunk) => Effect.suspend(() => {
318
+ received += chunk.byteLength;
319
+ if (received > bound)
320
+ return Effect.fail(bodyTooLarge(operation, received, bound));
321
+ chunks.push(new Uint8Array(chunk));
322
+ return Effect.void;
323
+ })).pipe(Effect.catchTag("HttpClientError", (cause) =>
324
+ // An absent body is zero bytes, not a transport refusal: the
325
+ // digest check in `get` is the arbiter of whether empty content
326
+ // is the requested artifact.
327
+ cause.reason._tag === "EmptyBodyError"
328
+ ? Effect.void
329
+ : Effect.fail(transportFailure(`${operation} body`))));
330
+ const bytes = new Uint8Array(received);
331
+ let offset = 0;
332
+ for (const chunk of chunks) {
333
+ bytes.set(chunk, offset);
334
+ offset += chunk.byteLength;
335
+ }
336
+ return bytes;
337
+ });
338
+ /** The network half of `get`: request, status split, bounded body read. */
339
+ const download = (digest) => send("a download", authorized(HttpClientRequest.get(casUrl(digest))), (response) => Effect.gen(function* () {
340
+ if (response.status === 404) {
341
+ return yield* Effect.fail(new ArtifactStore.ArtifactMissing({ code: "artifact_missing", digest }));
342
+ }
343
+ if (!isOk(response))
344
+ return yield* Effect.fail(unexpectedStatus("a download", response.status));
345
+ return yield* readBounded(response, "a download", maxDownloadBytes);
346
+ }));
347
+ /** One whole-blob `PUT`: the protocol every dumb-HTTP CAS already speaks. */
348
+ const uploadWhole = (digest, bytes) => send("an upload", authorized(HttpClientRequest.put(casUrl(digest))).pipe(HttpClientRequest.bodyUint8Array(bytes, "application/octet-stream")), (response) => isOk(response) ? Effect.void : Effect.fail(unexpectedStatus("an upload", response.status)));
349
+ /**
350
+ * The byte after the prefix a `Range: bytes=0-{last}` header reports, or
351
+ * `undefined` when the answer names no prefix. Only a prefix starting at
352
+ * zero is usable: a tier holding a middle span has nothing this client can
353
+ * continue from, so it is treated as holding nothing.
354
+ */
355
+ const resumeOffset = (response) => {
356
+ const header = response.headers["range"];
357
+ if (header === undefined)
358
+ return undefined;
359
+ const match = /^bytes=0-(\d+)$/.exec(header.trim());
360
+ if (match === null)
361
+ return undefined;
362
+ const last = Number(match[1]);
363
+ // A prefix past the safe integer range does not survive `Number`: the
364
+ // decimal digits are rounded, so the offset it names is a number this
365
+ // client made up. It proves nothing about what the tier holds, which is
366
+ // the same as naming no prefix at all.
367
+ if (!Number.isSafeInteger(last))
368
+ return undefined;
369
+ return last + 1;
370
+ };
371
+ /**
372
+ * A tier that refuses ranged bodies, in the three ways HTTP has to say
373
+ * so. `411` and `416` refuse the body's framing; `400` is RFC 9110
374
+ * section 14.5's answer from a resource that "does not support partial
375
+ * PUT requests", and it is what both of this repository's cache services
376
+ * send. Falling back on it can mask no genuine `400`: the whole-blob
377
+ * `PUT` that follows presents the same URL, digest, and credential, so a
378
+ * real refusal comes straight back on that request.
379
+ */
380
+ const rejectsRanges = (status) => status === 400 || status === 411 || status === 416;
381
+ /**
382
+ * Whether the tier holds exactly `total` bytes under `digest`, read from
383
+ * the `Content-Length` of a `HEAD` answer.
384
+ *
385
+ * This is the only claim about a chunked transfer this client will make on
386
+ * its own behalf. A tier that answers `HEAD` without a length is not
387
+ * refused — it simply proves nothing, so the caller sends the blob whole.
388
+ */
389
+ const holdsWhole = (digest, total) => send("an existence probe", authorized(HttpClientRequest.head(casUrl(digest))), (response) => Effect.sync(() => {
390
+ if (!isOk(response))
391
+ return false;
392
+ const declared = response.headers["content-length"];
393
+ return declared !== undefined && Number(declared) === total;
394
+ }));
395
+ /**
396
+ * Sends `bytes` as `Content-Range` chunks, resuming from whatever prefix
397
+ * the tier reports. Answers `false` when the tier has not proved it stored
398
+ * the whole blob, which is the caller's signal to send it whole.
399
+ *
400
+ * A `2xx` answer is never by itself proof of that. A tier that ignores
401
+ * `Content-Range`, such as plain WebDAV `PUT`, which Bazel documents as a
402
+ * supported dumb-HTTP cache, answers every request in this sequence `201`
403
+ * while storing only the last body it was handed, which for the probe is
404
+ * zero bytes. So only a `308` continues the sequence, and the completing
405
+ * chunk's `2xx` is confirmed with `HEAD` before the caller is told the
406
+ * digest is published. Everything else falls back, and the whole-blob
407
+ * `PUT` overwrites whatever partial body the sequence left behind.
408
+ */
409
+ const uploadChunked = (digest, bytes, chunk) => Effect.gen(function* () {
410
+ const total = bytes.byteLength;
411
+ const ranged = (range, body) => send("an upload", authorized(HttpClientRequest.put(casUrl(digest))).pipe(HttpClientRequest.bodyUint8Array(body, "application/octet-stream"), HttpClientRequest.setHeader("content-range", range)),
412
+ // Only status and headers are used after the response is released.
413
+ Effect.succeed);
414
+ // A blob the tier already holds whole costs one `HEAD` and no body.
415
+ // Asking first is also what makes the probe's answer readable: a `2xx`
416
+ // to it can no longer mean "already there", so the one reading left is
417
+ // a tier that ignored the header and stored the empty body.
418
+ if (yield* holdsWhole(digest, total))
419
+ return true;
420
+ // The probe carries no bytes: it exists to learn where to start, so
421
+ // that an interrupted transfer costs one round trip rather than the
422
+ // whole blob again.
423
+ const probe = yield* ranged(`bytes */${total}`, new Uint8Array(0));
424
+ if (isOk(probe) || rejectsRanges(probe.status))
425
+ return false;
426
+ if (probe.status !== 308 && probe.status !== 404) {
427
+ return yield* Effect.fail(unexpectedStatus("an upload probe", probe.status));
428
+ }
429
+ let offset = probe.status === 308 ? resumeOffset(probe) ?? 0 : 0;
430
+ while (offset < total) {
431
+ const end = Math.min(offset + chunk, total);
432
+ const answer = yield* ranged(`bytes ${offset}-${end - 1}/${total}`, bytes.subarray(offset, end));
433
+ if (answer.status !== 308) {
434
+ // The completing chunk may answer `2xx`; anything before it may
435
+ // not, because a tier that is still owed bytes and reports success
436
+ // is a tier that is not reading the header. Both are checked
437
+ // against what the tier actually holds below.
438
+ if (end === total && isOk(answer))
439
+ break;
440
+ if (isOk(answer) || rejectsRanges(answer.status))
441
+ return false;
442
+ return yield* Effect.fail(unexpectedStatus("an upload", answer.status));
443
+ }
444
+ // A tier that reports a longer prefix than this chunk delivered has
445
+ // more than we just sent, so the next chunk starts there. Never
446
+ // backwards: an answer naming a shorter prefix would loop forever.
447
+ offset = Math.max(end, resumeOffset(answer) ?? 0);
448
+ }
449
+ return yield* holdsWhole(digest, total);
450
+ });
451
+ const put = Effect.fn("RemoteArtifacts.put")((bytes) => Effect.flatMap(ArtifactStore.snapshotBytes(bytes), (snapshot) => Effect.gen(function* () {
452
+ const digest = yield* ArtifactStore.measureBytes(snapshot);
453
+ yield* Effect.annotateCurrentSpan({ digest });
454
+ yield* within("an upload", uploadDeadline, Effect.gen(function* () {
455
+ if (chunkBytes === undefined || snapshot.byteLength <= chunkBytes) {
456
+ yield* uploadWhole(digest, snapshot);
457
+ return;
458
+ }
459
+ const transferred = yield* uploadChunked(digest, snapshot, chunkBytes);
460
+ if (!transferred)
461
+ yield* uploadWhole(digest, snapshot);
462
+ }));
463
+ return digest;
464
+ })));
465
+ const get = Effect.fn("RemoteArtifacts.get")((digest) => Effect.gen(function* () {
466
+ const validated = yield* ArtifactStore.validateDigest(digest);
467
+ yield* Effect.annotateCurrentSpan({ digest: validated });
468
+ // The deadline covers the whole exchange — request, headers, body —
469
+ // because a tier that stalls mid-body is exactly as unanswering as
470
+ // one that never accepts the connection.
471
+ const bytes = yield* within("a download", downloadDeadline, download(validated));
472
+ // The shared tier is the least trusted store there is: it is written
473
+ // by machines this one has never met. Verifying the address here means
474
+ // a mis-serving or compromised cache can waste a round trip but can
475
+ // never substitute content.
476
+ const measured = yield* ArtifactStore.measureBytes(bytes);
477
+ if (measured !== validated) {
478
+ return yield* Effect.fail(new ArtifactStore.ArtifactCorruption({
479
+ code: "artifact_corruption",
480
+ recordedDigest: validated,
481
+ measuredDigest: measured
482
+ }));
483
+ }
484
+ return bytes;
485
+ }));
486
+ const has = Effect.fn("RemoteArtifacts.has")((digest) => Effect.gen(function* () {
487
+ const validated = yield* ArtifactStore.validateDigest(digest);
488
+ yield* Effect.annotateCurrentSpan({ digest: validated });
489
+ const response = yield* within("an existence probe", requestDeadline, send("an existence probe", authorized(HttpClientRequest.head(casUrl(validated))), Effect.succeed));
490
+ if (response.status === 404)
491
+ return false;
492
+ if (!isOk(response))
493
+ return yield* Effect.fail(unexpectedStatus("an existence probe", response.status));
494
+ return true;
495
+ }));
496
+ const findMissing = Effect.fn("RemoteArtifacts.findMissing")((digests) => Effect.gen(function* () {
497
+ const requested = [...new Set(digests)];
498
+ if (requested.length === 0)
499
+ return [];
500
+ // The batch travels in a JSON body rather than a path, but an
501
+ // unusable address is still an unusable address, and the local tier
502
+ // refuses the same batch wholesale rather than probing part of it.
503
+ const validated = [];
504
+ for (const digest of requested)
505
+ validated.push(yield* ArtifactStore.validateDigest(digest));
506
+ yield* Effect.annotateCurrentSpan({ count: validated.length });
507
+ const missing = new Set();
508
+ for (let offset = 0; offset < validated.length; offset += maxFindMissingBatchDigests) {
509
+ const batch = validated.slice(offset, offset + maxFindMissingBatchDigests);
510
+ const requestBody = encoder.encode(JSON.stringify({ digests: batch }));
511
+ /* v8 ignore next 3 -- strict 64-byte digests plus the 1,000-entry batch cap make this
512
+ * at most 67,013 bytes; keep the protocol assertion beside serialization in case either invariant changes. */
513
+ if (requestBody.byteLength > maxFindMissingBodyBytes) {
514
+ return yield* Effect.fail(configurationFailure("remote artifact findMissing request exceeds 256 KiB"));
515
+ }
516
+ const decoded = yield* within("a batched existence probe", requestDeadline, send("a batched existence probe", authorized(HttpClientRequest.post(`${base}/cas/findMissing`)).pipe(HttpClientRequest.bodyUint8Array(requestBody, "application/json")), (response) => Effect.gen(function* () {
517
+ if (!isOk(response)) {
518
+ return yield* Effect.fail(unexpectedStatus("a batched existence probe", response.status));
519
+ }
520
+ const bodyBytes = yield* readBounded(response, "a batched existence probe", maxFindMissingResponseBytes);
521
+ const body = yield* Effect.try({
522
+ try: () => JSON.parse(decoder.decode(bodyBytes)),
523
+ catch: () => transportFailure("a batched existence probe body")
524
+ });
525
+ return yield* Schema.decodeUnknownEffect(FindMissingResponse)(body).pipe(Effect.mapError(() => transportFailure("a batched existence probe body")));
526
+ })));
527
+ const asked = new Set(batch);
528
+ for (const digest of decoded.missing)
529
+ if (asked.has(digest))
530
+ missing.add(digest);
531
+ }
532
+ // "The returned set is guaranteed to be a subset of `digests`"
533
+ // (`MissingDigestsFinder`). Bazel gets that from the server; we
534
+ // enforce it on this side too, because a server that answered with
535
+ // an unrequested digest would otherwise make the caller upload bytes
536
+ // it never asked about.
537
+ return validated.filter((digest) => missing.has(digest));
538
+ }));
539
+ return { put, get, has, findMissing, downloadPolicy };
540
+ });
541
+ /**
542
+ * Provides a remote artifact store as the `ArtifactStore` tag.
543
+ *
544
+ * Composing this *alone* makes every artifact read and write a network round
545
+ * trip. The intended production shape is
546
+ * {@link CombinedArtifacts.layer | CombinedArtifacts}, with this as its remote
547
+ * tier.
548
+ *
549
+ * @category layers
550
+ * @since 1.0.0-rc.0
551
+ * @slop
552
+ */
553
+ export const layer = (options) => Layer.effect(ArtifactStore.ArtifactStore)(make(options));
554
+ //# sourceMappingURL=RemoteArtifacts.js.map