@milkenjoyer/toolchain 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.
@@ -0,0 +1,291 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { extname } from "node:path";
3
+
4
+ import { NodeServices } from "@effect/platform-node";
5
+ import * as Config from "effect/Config";
6
+ import * as Effect from "effect/Effect";
7
+ import { FileSystem } from "effect/FileSystem";
8
+ import * as Schema from "effect/Schema";
9
+
10
+ import { invalid, message, Request, Result } from "./proof-run.ts";
11
+ import type { Domain, Outcome } from "./proof-run.ts";
12
+ import { prove } from "./z3.ts";
13
+
14
+ const Callable = Schema.declare(
15
+ (value: unknown): value is (...args: unknown[]) => unknown =>
16
+ typeof value === "function"
17
+ );
18
+ const Body = Schema.Union([
19
+ Schema.Struct({
20
+ kind: Schema.Literal("every"),
21
+ inputs: Schema.Record(Schema.String, Schema.Unknown),
22
+ holds: Callable,
23
+ }),
24
+ Schema.Struct({
25
+ kind: Schema.Literal("z3"),
26
+ inputs: Schema.Record(Schema.String, Schema.Unknown),
27
+ model: Callable,
28
+ code: Callable,
29
+ holds: Callable,
30
+ assume: Schema.optionalKey(Callable),
31
+ }),
32
+ ]);
33
+ const Literal = Schema.Union([
34
+ Schema.Struct({
35
+ kind: Schema.Literal("int"),
36
+ min: Schema.Number,
37
+ max: Schema.Number,
38
+ }),
39
+ Schema.Struct({ kind: Schema.Literal("uint"), bits: Schema.Number }),
40
+ ]);
41
+ const JsonBounds = Schema.Struct({
42
+ type: Schema.Literal("integer"),
43
+ minimum: Schema.optionalKey(Schema.Number),
44
+ maximum: Schema.optionalKey(Schema.Number),
45
+ exclusiveMinimum: Schema.optionalKey(Schema.Number),
46
+ exclusiveMaximum: Schema.optionalKey(Schema.Number),
47
+ });
48
+ const enumerate = (
49
+ domains: ReadonlyArray<Domain>,
50
+ holds: (at: Record<string, number>) => unknown,
51
+ deadline: number,
52
+ seconds: number
53
+ ): Outcome => {
54
+ const late = (checked: number) =>
55
+ invalid(
56
+ `every checked ${checked} of ${count} inputs before its ${seconds} s budget ran out`
57
+ );
58
+ let checked = 0;
59
+ const count = domains.reduce(
60
+ (n, d) => n * (BigInt(d.max) - BigInt(d.min) + 1n),
61
+ 1n
62
+ );
63
+ if (count > 4294967296n)
64
+ return invalid(
65
+ `inputs span ${count} values; every checks at most 4294967296, so prove it with z3`
66
+ );
67
+ const at: Record<string, number> = Object.fromEntries(
68
+ domains.map((d) => [d.name, d.min])
69
+ );
70
+ for (;;) {
71
+ try {
72
+ if (holds(at) !== true) return { _tag: "Counterexample", at };
73
+ } catch (error) {
74
+ return { _tag: "Throws", at, message: message(error) };
75
+ }
76
+ checked++;
77
+ if ((checked & 0xfff) === 0 && performance.now() > deadline)
78
+ return late(checked);
79
+ let i = domains.length - 1;
80
+ while (i >= 0) {
81
+ const d = domains[i];
82
+ if (d && (at[d.name] ?? d.max) < d.max) {
83
+ at[d.name] = (at[d.name] ?? d.min) + 1;
84
+ break;
85
+ }
86
+ if (d) at[d.name] = d.min;
87
+ i--;
88
+ }
89
+ if (i < 0) break;
90
+ }
91
+ if (performance.now() > deadline) return late(checked);
92
+ return {
93
+ _tag: "Proved",
94
+ detail: `checked every one of ${count} inputs`,
95
+ seconds: 0,
96
+ };
97
+ };
98
+ const evaluate = async (
99
+ request: Request,
100
+ paths: ReadonlyArray<string>,
101
+ loaded: Set<string>,
102
+ snapshot: (paths: string[]) => void,
103
+ started: number
104
+ ): Promise<Outcome> => {
105
+ let imported: unknown;
106
+ try {
107
+ imported = await import(request.proof);
108
+ } finally {
109
+ snapshot([...loaded]);
110
+ }
111
+ let body: typeof Body.Type;
112
+ try {
113
+ const module = Schema.decodeUnknownSync(
114
+ Schema.Struct({ default: Schema.Unknown })
115
+ )(imported);
116
+ body = Schema.decodeUnknownSync(Body)(module.default);
117
+ } catch {
118
+ return invalid("the default export is not every(...) or z3(...)");
119
+ }
120
+ if (body.kind !== request.kind)
121
+ return invalid(
122
+ `specs.json says ${request.kind} but the file exports ${body.kind}(...)`
123
+ );
124
+ const exports: unknown[] = [];
125
+ for (const file of paths) {
126
+ const covered: unknown = await import(file);
127
+ exports.push(
128
+ ...Object.values(
129
+ Schema.decodeUnknownSync(Schema.Record(Schema.String, Schema.Unknown))(
130
+ covered
131
+ )
132
+ )
133
+ );
134
+ }
135
+ const domains: Domain[] = [];
136
+ for (const [name, input] of Object.entries(body.inputs)) {
137
+ if (body.kind === "z3" && !Schema.isSchema(input)) {
138
+ try {
139
+ const literal = Schema.decodeUnknownSync(Literal)(input);
140
+ if (literal.kind === "uint") {
141
+ if (
142
+ !Number.isInteger(literal.bits) ||
143
+ literal.bits < 1 ||
144
+ literal.bits > 53
145
+ )
146
+ return invalid(
147
+ `input ${name}: uint needs a bit width from 1 to 53`
148
+ );
149
+ domains.push({
150
+ name,
151
+ ...literal,
152
+ min: 0,
153
+ max: 2 ** literal.bits - 1,
154
+ });
155
+ } else {
156
+ if (
157
+ !Number.isSafeInteger(literal.min) ||
158
+ !Number.isSafeInteger(literal.max) ||
159
+ literal.min > literal.max
160
+ )
161
+ return invalid(
162
+ `input ${name}: int needs safe integer bounds with min <= max`
163
+ );
164
+ domains.push({ name, ...literal });
165
+ }
166
+ continue;
167
+ } catch {
168
+ return invalid(
169
+ `input ${name}: expected an integer schema, int(...) or uint(...)`
170
+ );
171
+ }
172
+ }
173
+ if (!exports.includes(input))
174
+ return invalid(
175
+ `input ${name}: its schema is not exported by a file this proof covers, so the range may be narrower than the code enforces`
176
+ );
177
+ let json: unknown = input;
178
+ try {
179
+ if (!Schema.isSchema(input)) throw new Error("not a schema");
180
+ const doc = Schema.toJsonSchemaDocument(Schema.toType(input));
181
+ json = doc.schema;
182
+ const ref = Schema.decodeUnknownOption(
183
+ Schema.Struct({ $ref: Schema.String })
184
+ )(json);
185
+ if (ref._tag === "Some") {
186
+ const key = ref.value.$ref.split("/").at(-1) ?? "";
187
+ json = doc.definitions[key.replaceAll("~1", "/").replaceAll("~0", "~")];
188
+ }
189
+ const bounds = Schema.decodeUnknownSync(JsonBounds)(json);
190
+ const min = Math.max(
191
+ bounds.minimum ?? -Infinity,
192
+ bounds.exclusiveMinimum === undefined
193
+ ? -Infinity
194
+ : Math.floor(bounds.exclusiveMinimum) + 1
195
+ );
196
+ const max = Math.min(
197
+ bounds.maximum ?? Infinity,
198
+ bounds.exclusiveMaximum === undefined
199
+ ? Infinity
200
+ : Math.ceil(bounds.exclusiveMaximum) - 1
201
+ );
202
+ if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || min > max)
203
+ throw new Error("unbounded");
204
+ domains.push({ name, kind: "int", min, max });
205
+ } catch {
206
+ return invalid(
207
+ `input ${name}: every needs an integer schema with a minimum and a maximum, found ${JSON.stringify(json)}`
208
+ );
209
+ }
210
+ }
211
+ return body.kind === "every"
212
+ ? enumerate(
213
+ domains,
214
+ body.holds,
215
+ started + request.timeoutSeconds * 1000,
216
+ request.timeoutSeconds
217
+ )
218
+ : await prove(request, body, domains, started);
219
+ };
220
+ const run = Effect.gen(function* () {
221
+ const fs = yield* FileSystem;
222
+ const request = yield* Schema.decodeEffect(Schema.fromJsonString(Request))(
223
+ yield* Config.String("FORMAL_PROOF")
224
+ );
225
+ const started = performance.now();
226
+ const loaded = new Set<string>();
227
+ const paths = request.covers.filter((f) =>
228
+ /\.(?:[cm]?[jt]s|[jt]sx)$/u.test(f)
229
+ );
230
+ Bun.plugin({
231
+ name: "formal-proof",
232
+ setup(build) {
233
+ if (paths.length === 0) return;
234
+ const filter = new RegExp(
235
+ `^(?:${paths.map((p) => p.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")).join("|")})$`,
236
+ "u"
237
+ );
238
+ build.onLoad({ filter }, async ({ path }) => {
239
+ const file = realpathSync(path);
240
+ if (!request.covers.includes(file)) return undefined;
241
+ loaded.add(file);
242
+ const text = await Bun.file(file).text();
243
+ const extension = extname(file);
244
+ const loader =
245
+ extension === ".tsx"
246
+ ? "tsx"
247
+ : extension === ".jsx"
248
+ ? "jsx"
249
+ : /\.[cm]?js$/u.test(extension)
250
+ ? "js"
251
+ : "ts";
252
+ return {
253
+ contents:
254
+ request.edit?.file === file
255
+ ? text.replace(
256
+ request.edit.find,
257
+ () => request.edit?.replace ?? ""
258
+ )
259
+ : text,
260
+ loader,
261
+ };
262
+ });
263
+ },
264
+ });
265
+ let snapshot: string[] = [];
266
+ const outcome = yield* Effect.tryPromise({
267
+ try: () =>
268
+ evaluate(
269
+ request,
270
+ paths,
271
+ loaded,
272
+ (paths) => {
273
+ snapshot = paths;
274
+ },
275
+ started
276
+ ),
277
+ catch: (error) => invalid(message(error)),
278
+ }).pipe(Effect.catch((error) => Effect.succeed(error)));
279
+ const timed =
280
+ outcome._tag === "Proved"
281
+ ? { ...outcome, seconds: (performance.now() - started) / 1000 }
282
+ : outcome;
283
+ yield* fs.writeFileString(
284
+ request.result,
285
+ yield* Schema.encodeEffect(Schema.fromJsonString(Result))({
286
+ loaded: snapshot,
287
+ outcome: timed,
288
+ })
289
+ );
290
+ });
291
+ await Effect.runPromise(run.pipe(Effect.provide(NodeServices.layer)));
@@ -0,0 +1,119 @@
1
+ import * as Effect from "effect/Effect";
2
+ import * as Result from "effect/Result";
3
+ import * as Schema from "effect/Schema";
4
+ import * as SchemaIssue from "effect/SchemaIssue";
5
+
6
+ const RepoPath = Schema.String.check(
7
+ Schema.isPattern(/^(?!\/)(?!(?:.*\/)?\.\.(?:\/|$))[^\0\\]+$/u)
8
+ );
9
+ const OperatorName = Schema.String.check(
10
+ Schema.isPattern(/^[A-Za-z_][A-Za-z0-9_]*$/u)
11
+ );
12
+ const Common = {
13
+ synced: Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u)),
14
+ covers: Schema.NonEmptyArray(Schema.NonEmptyString),
15
+ };
16
+ const Runtime = {
17
+ ...Common,
18
+ timeoutSeconds: Schema.Int.check(
19
+ Schema.isBetween({ minimum: 1, maximum: 1800 })
20
+ ).pipe(Schema.withDecodingDefaultKey(Effect.succeed(60))),
21
+ };
22
+ const Proof = {
23
+ ...Runtime,
24
+ witnesses: Schema.NonEmptyArray(OperatorName).check(
25
+ Schema.makeFilter(
26
+ (names) =>
27
+ new Set(names).size === names.length || "witnesses must be unique"
28
+ )
29
+ ),
30
+ breaks: Schema.Array(
31
+ Schema.Struct({
32
+ violates: OperatorName,
33
+ find: Schema.NonEmptyString,
34
+ replace: Schema.String,
35
+ file: Schema.optionalKey(RepoPath),
36
+ })
37
+ ).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
38
+ };
39
+ export const Entry = Schema.Union([
40
+ Schema.Struct({
41
+ ...Proof,
42
+ mode: Schema.Literal("gate"),
43
+ traces: Schema.optionalKey(
44
+ Schema.Struct({
45
+ seed: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
46
+ depth: Schema.Int.check(
47
+ Schema.isBetween({ minimum: 1, maximum: 10000 })
48
+ ),
49
+ count: Schema.Int.check(
50
+ Schema.isBetween({ minimum: 1, maximum: 100000 })
51
+ ),
52
+ steer: Schema.optionalKey(
53
+ Schema.Record(
54
+ OperatorName,
55
+ Schema.Int.check(Schema.isBetween({ minimum: 2, maximum: 1000 }))
56
+ )
57
+ ),
58
+ conformance: RepoPath,
59
+ })
60
+ ),
61
+ }),
62
+ Schema.Struct({ ...Proof, mode: Schema.Literal("manual") }),
63
+ Schema.Struct({ ...Common, mode: Schema.Literal("library") }),
64
+ ]);
65
+ const ArithmeticCommon = {
66
+ covers: Common.covers,
67
+ timeoutSeconds: Runtime.timeoutSeconds,
68
+ breaks: Schema.NonEmptyArray(
69
+ Schema.Struct({
70
+ file: RepoPath,
71
+ find: Schema.NonEmptyString,
72
+ replace: Schema.String,
73
+ })
74
+ ),
75
+ };
76
+ const ArithmeticProof = Schema.Union([
77
+ Schema.Struct({ ...ArithmeticCommon, kind: Schema.Literal("every") }),
78
+ Schema.Struct({
79
+ ...ArithmeticCommon,
80
+ kind: Schema.Literal("z3"),
81
+ samples: Schema.Int.check(
82
+ Schema.isBetween({ minimum: 10000, maximum: 1000000 })
83
+ ).pipe(Schema.withDecodingDefaultKey(Effect.succeed(10000))),
84
+ }),
85
+ ]);
86
+ export const SpecsFile = Schema.Struct({
87
+ critical: Schema.NonEmptyArray(Schema.NonEmptyString),
88
+ arithmetic: Schema.optionalKey(Schema.Array(Schema.NonEmptyString)),
89
+ proofs: Schema.Record(
90
+ RepoPath.check(Schema.isPattern(/\.proof\.ts$/u)),
91
+ ArithmeticProof
92
+ ).pipe(Schema.withDecodingDefaultKey(Effect.succeed({}))),
93
+ specs: Schema.Record(RepoPath.check(Schema.isPattern(/\.tla$/u)), Entry),
94
+ kani: Schema.Record(
95
+ RepoPath.check(Schema.isPattern(/\.rs$/u)),
96
+ Schema.Struct({ ...Runtime, mode: Schema.Literals(["gate", "manual"]) })
97
+ ).pipe(Schema.withDecodingDefaultKey(Effect.succeed({}))),
98
+ });
99
+ export type SpecsFile = Omit<typeof SpecsFile.Type, "critical"> & {
100
+ readonly critical: ReadonlyArray<string>;
101
+ };
102
+ export const decode = (raw: string) => {
103
+ let file: SpecsFile = { critical: [], specs: {}, kani: {}, proofs: {} };
104
+ let decodeErrors: ReadonlyArray<string> = [];
105
+ const decoded = Schema.decodeResult(Schema.fromJsonString(SpecsFile))(raw, {
106
+ errors: "all",
107
+ onExcessProperty: "error",
108
+ });
109
+ if (Result.isSuccess(decoded)) file = decoded.success;
110
+ else
111
+ decodeErrors = SchemaIssue.makeFormatterStandardSchemaV1()(
112
+ decoded.failure.issue
113
+ ).issues.map(({ message, path: at = [] }) =>
114
+ at.length === 0
115
+ ? message
116
+ : `${at.map((key) => `[${JSON.stringify(typeof key === "object" ? key.key : key)}]`).join("")}: ${message}`
117
+ );
118
+ return { file, decodeErrors };
119
+ };
@@ -2,86 +2,14 @@ import * as Effect from "effect/Effect";
2
2
  import { FileSystem } from "effect/FileSystem";
3
3
  import { Path } from "effect/Path";
4
4
  import { ChildProcess } from "effect/process";
5
- import * as Result from "effect/Result";
6
- import * as Schema from "effect/Schema";
7
- import * as SchemaIssue from "effect/SchemaIssue";
8
5
  import * as Stream from "effect/Stream";
9
6
 
10
7
  import { parseCfg } from "./cfg.ts";
11
8
  import type { Cfg, CfgError } from "./cfg.ts";
12
9
  import type { Semantics } from "./semantics.ts";
10
+ import { decode, type SpecsFile, type Entry } from "./specs-file.ts";
13
11
  import { FormalError, Tla } from "./tla.ts";
14
12
 
15
- const RepoPath = Schema.String.check(
16
- Schema.isPattern(/^(?!\/)(?!(?:.*\/)?\.\.(?:\/|$))[^\0\\]+$/u)
17
- );
18
- const OperatorName = Schema.String.check(
19
- Schema.isPattern(/^[A-Za-z_][A-Za-z0-9_]*$/u)
20
- );
21
- const Common = {
22
- synced: Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u)),
23
- covers: Schema.NonEmptyArray(Schema.NonEmptyString),
24
- };
25
- const Runtime = {
26
- ...Common,
27
- timeoutSeconds: Schema.Int.check(
28
- Schema.isBetween({ minimum: 1, maximum: 1800 })
29
- ).pipe(Schema.withDecodingDefaultKey(Effect.succeed(60))),
30
- };
31
- const Proof = {
32
- ...Runtime,
33
- witnesses: Schema.NonEmptyArray(OperatorName).check(
34
- Schema.makeFilter(
35
- (names) =>
36
- new Set(names).size === names.length || "witnesses must be unique"
37
- )
38
- ),
39
- breaks: Schema.Array(
40
- Schema.Struct({
41
- violates: OperatorName,
42
- find: Schema.NonEmptyString,
43
- replace: Schema.String,
44
- file: Schema.optionalKey(RepoPath),
45
- })
46
- ).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
47
- };
48
- const Entry = Schema.Union([
49
- Schema.Struct({
50
- ...Proof,
51
- mode: Schema.Literal("gate"),
52
- traces: Schema.optionalKey(
53
- Schema.Struct({
54
- seed: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
55
- depth: Schema.Int.check(
56
- Schema.isBetween({ minimum: 1, maximum: 10000 })
57
- ),
58
- count: Schema.Int.check(
59
- Schema.isBetween({ minimum: 1, maximum: 100000 })
60
- ),
61
- steer: Schema.optionalKey(
62
- Schema.Record(
63
- OperatorName,
64
- Schema.Int.check(Schema.isBetween({ minimum: 2, maximum: 1000 }))
65
- )
66
- ),
67
- conformance: RepoPath,
68
- })
69
- ),
70
- }),
71
- Schema.Struct({ ...Proof, mode: Schema.Literal("manual") }),
72
- Schema.Struct({ ...Common, mode: Schema.Literal("library") }),
73
- ]);
74
- const SpecsFile = Schema.Struct({
75
- critical: Schema.NonEmptyArray(Schema.NonEmptyString),
76
- specs: Schema.Record(RepoPath.check(Schema.isPattern(/\.tla$/u)), Entry),
77
- kani: Schema.Record(
78
- RepoPath.check(Schema.isPattern(/\.rs$/u)),
79
- Schema.Struct({ ...Runtime, mode: Schema.Literals(["gate", "manual"]) })
80
- ).pipe(Schema.withDecodingDefaultKey(Effect.succeed({}))),
81
- });
82
- type SpecsFile = Omit<typeof SpecsFile.Type, "critical"> & {
83
- readonly critical: ReadonlyArray<string>;
84
- };
85
13
  export type Analysis =
86
14
  | { readonly _tag: "Parsed"; readonly semantics: Semantics }
87
15
  | { readonly _tag: "Unparsed"; readonly output: string };
@@ -123,23 +51,11 @@ export const load = Effect.fn("formal.load")(function* (root: string) {
123
51
  files.split("\0").filter(Boolean),
124
52
  (file) => fs.exists(path.join(root, file))
125
53
  );
126
- let file: SpecsFile = { critical: [], specs: {}, kani: {} };
54
+ let file: SpecsFile = { critical: [], specs: {}, kani: {}, proofs: {} };
127
55
  let decodeErrors: ReadonlyArray<string> = [];
128
56
  if (yield* fs.exists(path.join(root, "specs.json"))) {
129
57
  const raw = yield* fs.readFileString(path.join(root, "specs.json"));
130
- const decoded = Schema.decodeResult(Schema.fromJsonString(SpecsFile))(raw, {
131
- errors: "all",
132
- onExcessProperty: "error",
133
- });
134
- if (Result.isSuccess(decoded)) file = decoded.success;
135
- else
136
- decodeErrors = SchemaIssue.makeFormatterStandardSchemaV1()(
137
- decoded.failure.issue
138
- ).issues.map(({ message, path: at = [] }) =>
139
- at.length === 0
140
- ? message
141
- : `${at.map((key) => `[${JSON.stringify(typeof key === "object" ? key.key : key)}]`).join("")}: ${message}`
142
- );
58
+ ({ file, decodeErrors } = decode(raw));
143
59
  }
144
60
  const modules = tracked.filter((f) => f.endsWith(".tla"));
145
61
  const configs = tracked.filter(
package/src/formal/tla.ts CHANGED
@@ -11,6 +11,7 @@ import * as Layer from "effect/Layer";
11
11
  import * as Option from "effect/Option";
12
12
  import { Path } from "effect/Path";
13
13
  import { ChildProcess, ChildProcessSpawner } from "effect/process";
14
+ import * as Result from "effect/Result";
14
15
  import * as Stream from "effect/Stream";
15
16
 
16
17
  import { fromXml } from "./semantics.ts";
@@ -52,12 +53,18 @@ type Formatted =
52
53
  const pins = [
53
54
  {
54
55
  file: "tla2tools-1.8.0.jar",
55
- url: "https://github.com/tlaplus/tlaplus/releases/download/v1.8.0/tla2tools.jar",
56
+ urls: [
57
+ "https://github.com/tlaplus/tlaplus/releases/download/v1.8.0/tla2tools.jar",
58
+ "https://api.github.com/repos/tlaplus/tlaplus/releases/assets/718777374",
59
+ ],
56
60
  sha256: "e1f11b75c4b5bc4478ba0ac5cb6ae28e40a01b0016bc33e0aa97da22dfdbcd7f",
57
61
  },
58
62
  {
59
63
  file: "CommunityModules-deps-202611060952.jar",
60
- url: "https://github.com/tlaplus/CommunityModules/releases/download/202611060952/CommunityModules-deps-202611060952.jar",
64
+ urls: [
65
+ "https://github.com/tlaplus/CommunityModules/releases/download/202611060952/CommunityModules-deps-202611060952.jar",
66
+ "https://api.github.com/repos/tlaplus/CommunityModules/releases/assets/716678698",
67
+ ],
61
68
  sha256: "a3b27c40f1fb5085f30c6ead37e918457f8cfc62c1e50a1dc668ef592ad2b5fb",
62
69
  },
63
70
  ];
@@ -119,25 +126,37 @@ const make = Effect.gen(function* () {
119
126
  prefix: `.${pin.file}.`,
120
127
  suffix: ".part",
121
128
  });
122
- const bytes = yield* HttpClient.get(pin.url).pipe(
123
- Effect.flatMap((response) =>
124
- response.status === 200
125
- ? response.arrayBuffer.pipe(Effect.mapError(error))
126
- : Effect.fail(
127
- new FormalError({
128
- message: pin.url + ": HTTP " + response.status,
129
- })
130
- )
131
- ),
132
- Effect.map((buffer) => new Uint8Array(buffer)),
133
- Effect.timeout("120 seconds"),
134
- Effect.provide(FetchHttpClient.layer)
135
- );
129
+ const { url, bytes } = yield* Effect.gen(function* () {
130
+ const failures: string[] = [];
131
+ for (const url of pin.urls) {
132
+ const result = yield* HttpClient.get(url, {
133
+ headers: { Accept: "application/octet-stream" },
134
+ }).pipe(
135
+ Effect.flatMap((response) =>
136
+ response.status === 200
137
+ ? response.arrayBuffer.pipe(Effect.mapError(error))
138
+ : Effect.fail(
139
+ new FormalError({
140
+ message: `HTTP ${response.status}`,
141
+ })
142
+ )
143
+ ),
144
+ Effect.map((buffer) => new Uint8Array(buffer)),
145
+ Effect.timeout("120 seconds"),
146
+ Effect.provide(FetchHttpClient.layer),
147
+ Effect.result
148
+ );
149
+ if (Result.isSuccess(result))
150
+ return { url, bytes: result.success };
151
+ failures.push(`${url}: ${error(result.failure).message}`);
152
+ }
153
+ return yield* new FormalError({ message: failures.join("; ") });
154
+ });
136
155
  yield* fs.writeFile(temp, bytes);
137
156
  const actual = digest(bytes);
138
157
  if (actual !== pin.sha256)
139
158
  return yield* new FormalError({
140
- message: `${pin.url} has sha256 ${actual}, expected ${pin.sha256}`,
159
+ message: `${url} has sha256 ${actual}, expected ${pin.sha256}`,
141
160
  });
142
161
  return yield* fs.rename(temp, file);
143
162
  })