harn-stdlib 0.10.198

Embedded Harn standard library source catalog
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/** Exact release selection and cache orchestration over verified native archive installation. */
import { compare_release } from "std/semver"

/**
 * First release that publishes macOS and Linux archives as `.tar.xz`; earlier ones are `.tar.gz`.
 */
const XZ_FIRST_RELEASE = "0.10.179"

const GITHUB_REQUEST_HEADERS: dict<string, string> = {"user-agent": "harn-bootstrap"}

/** Default retry budget while release assets are still publishing. */
pub const DEFAULT_ATTEMPTS: int = 12

pub const DEFAULT_DELAY_MS: int = 10000

pub type RuntimeInstallRequest = {
  version: string,
  target: string,
  repository: string,
  cache_dir: string,
  install_dir: string,
  installer: string,
  offline?: bool,
  token?: string,
  attempts?: int,
  delay_ms?: int,
}

type ReleaseAsset = {name: string, id?: int, digest?: string}

type ReleaseMetadata = {assets: list<ReleaseAsset>}

type ReleaseApiResponse = {status: int, body: string}

type ChecksumVerification = {checksum: string, source: string, release_api?: ReleaseMetadata}

type NativeReceipt = {
  schema_version: "harn-install-v1",
  version: string,
  binary_path: string,
  binary_sha256: string,
  checksum: string,
}

type NativeEnvelope = {
  schemaVersion: int,
  ok: bool,
  data?: NativeReceipt,
  error?: {message: string},
}

pub type RuntimeReceipt = {
  schema_version: "harn-bootstrap-v1",
  version: string,
  target: string,
  binary_path: string,
  binary_sha256: string,
  checksum: string,
  source: string,
  cache_hit: bool,
  checksum_source: string,
}

/**
 * Return the unique SHA256SUMS digest for one basename, or nil when absent.
 *
 * @effects: []
 * @errors: [invalid_checksum_manifest]
 */
pub fn checksum_for_asset(manifest: string, asset: string) -> string? {
  let checksums: dict<string, string> = {}
  for line in split(manifest, "\n") {
    if trim(line) == "" {
      continue
    }
    const fields = regex_captures(r"^([a-fA-F0-9]{64})[ \t]+\*?([^/\\\x00]+)$", trim(line))[0]
    require fields != nil, "malformed SHA256SUMS line"
    const name = fields.groups[1]
    require checksums[name] == nil, "SHA256SUMS contains duplicate entry for " + name
    checksums[name] = fields.groups[0].lower()
  }
  require len(checksums) > 0, "SHA256SUMS is empty"
  return checksums[asset]
}

fn publish_immutable(fs: HarnessFs, path: string, text: string) {
  if !fs.exists(path) {
    // A competing writer may win creation; the read-back binds either outcome.
    const publication = try {
      fs.replace_text(
        path,
        text,
        {create: true, overwrite: false, create_parents: true, durability: "flush"},
      )
    }
    require is_ok(publication) || fs.exists(path), "cannot publish release metadata"
  }
  require fs.read_text(path) == text, "published checksum metadata changed for an exact release"
}

fn release_headers(request: RuntimeInstallRequest, accept: string) -> dict<string, string> {
  const headers = GITHUB_REQUEST_HEADERS + {accept: accept}
  if (request.token ?? "") != "" {
    return headers + {authorization: "Bearer ${request.token ?? ""}"}
  }
  return headers
}

fn release_api_response(
  net: HarnessNet,
  request: RuntimeInstallRequest,
  suffix: string,
  accept: string,
) -> ReleaseApiResponse {
  const url = "https://api.github.com/repos/${request.repository}/releases/${suffix}"
  const response = net.request(
    "GET",
    url,
    {timeout_ms: 60000, headers: release_headers(request, accept)},
  )
  return pick(response, ["status", "body"])
}

fn load_release_api(net: HarnessNet, request: RuntimeInstallRequest) -> ReleaseMetadata {
  const response = release_api_response(
    net,
    request,
    "tags/v${request.version}",
    "application/vnd.github+json",
  )
  require response.status != 404, "release v${request.version} is absent"
  require response.status == 200, "release metadata HTTP ${response.status}"
  return schema_expect(json_parse(response.body), schema_of(ReleaseMetadata))
}

fn release_asset(access: ReleaseMetadata, name: string) -> ReleaseAsset? {
  const matches = access.assets.filter({ record -> record.name == name })
  require len(matches) <= 1, "release has duplicate assets named ${name}"
  return matches[0]
}

fn release_asset_id(asset: ReleaseAsset) -> int {
  require asset.id != nil && asset.id > 0, "release asset ${asset.name} has no valid ID"
  return asset.id
}

fn expected_checksum(
  harness: Harness,
  request: RuntimeInstallRequest,
  metadata: string,
  base: string,
  asset: string,
) -> ChecksumVerification {
  if request.offline ?? false {
    require harness.fs.exists(metadata), "offline checksum metadata is unavailable"
    const checksum = checksum_for_asset(harness.fs.read_text(metadata), asset)
    require checksum != nil, "SHA256SUMS has no runtime asset"
    return {checksum: checksum, source: "SHA256SUMS"}
  }
  const options = {timeout_ms: 60000, headers: GITHUB_REQUEST_HEADERS}
  const pin = path_join(dirname(metadata), asset + ".sha256")
  const attempts = request.attempts ?? DEFAULT_ATTEMPTS
  const delay_ms = request.delay_ms ?? DEFAULT_DELAY_MS
  let last_failure = ""
  require attempts > 0 && delay_ms >= 0, "invalid runtime retry budget"
  for attempt in range(0, attempts) {
    const manifest = try {
      const response = harness.net.request("GET", base + "SHA256SUMS", options)
      require response.status == 200, "SHA256SUMS HTTP " + to_string(response.status)
      const checksum = checksum_for_asset(response.body, asset)
      require checksum != nil, "SHA256SUMS has no runtime asset"
      {checksum: checksum, body: response.body}
    }
    if is_ok(manifest) {
      const verified = unwrap(manifest)
      require !harness.fs.exists(pin) || trim(harness.fs.read_text(pin)) == verified.checksum,
        "SHA256SUMS disagrees with the verified asset digest"
      publish_immutable(harness.fs, metadata, verified.body)
      return {checksum: verified.checksum, source: "SHA256SUMS"}
    }
    const api_verification = try {
      const access = load_release_api(harness.net, request)
      const manifest_asset = release_asset(access, "SHA256SUMS")
      if manifest_asset != nil {
        const response = release_api_response(
          harness.net,
          request,
          "assets/${release_asset_id(manifest_asset)}",
          "application/octet-stream",
        )
        require response.status == 200, "SHA256SUMS asset API HTTP ${response.status}"
        const checksum = checksum_for_asset(response.body, asset)
        require checksum != nil, "SHA256SUMS has no runtime asset"
        {checksum: checksum, body: response.body, source: "SHA256SUMS", release_api: access}
      } else {
        const record = release_asset(access, asset)
        require record != nil, "release has no asset named ${asset}"
        const digest = record.digest ?? ""
        require regex_match(r"^sha256:[a-f0-9]{64}$", digest),
          "runtime release has no verified SHA256"
        {
          checksum: regex_replace(r"^sha256:", "", digest),
          body: nil,
          source: "release asset digest",
          release_api: access,
        }
      }
    }
    if is_ok(api_verification) {
      const verified = unwrap(api_verification)
      if verified.body != nil {
        require !harness.fs.exists(pin) || trim(harness.fs.read_text(pin)) == verified.checksum,
          "SHA256SUMS disagrees with the verified asset digest"
        publish_immutable(harness.fs, metadata, verified.body)
      } else {
        publish_immutable(harness.fs, pin, "${verified.checksum}\n")
      }
      return {
        checksum: verified.checksum,
        source: verified.source,
        release_api: verified.release_api,
      }
    }
    last_failure = "${unwrap_err(manifest)}; ${unwrap_err(api_verification)}"
    if attempt + 1 < attempts {
      harness.clock.sleep_ms(delay_ms)
    }
  }
  throw "no runtime verification source after " + to_string(attempts) + " attempts: " + last_failure
}

pub type RuntimePlan = {
  version: string,
  target: string,
  asset: string,
  cache_dir: string,
  install_dir: string,
  archive_path: string,
  metadata_path: string,
  repository: string,
  base: string,
}

/**
 * Resolve an exact version, supported target, and private cache paths.
 *
 * @effects: []
 * @errors: [invalid_runtime_request]
 */
pub fn runtime_plan(request: RuntimeInstallRequest) -> RuntimePlan {
  const version = regex_replace(r"^v", "", request.version)
  require regex_match(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$", version),
    "invalid runtime version"
  require [
    "aarch64-apple-darwin",
    "x86_64-apple-darwin",
    "aarch64-unknown-linux-gnu",
    "x86_64-unknown-linux-gnu",
    "x86_64-pc-windows-msvc",
  ]
    .contains(request.target),
    "unsupported runtime target"
  require regex_match(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$", request.repository),
    "invalid runtime release repository"
  const extension = if request.target == "x86_64-pc-windows-msvc" {
    "zip"
  } else if compare_release(version, XZ_FIRST_RELEASE) >= 0 {
    "tar.xz"
  } else {
    "tar.gz"
  }
  const asset = "harn-" + request.target + "." + extension
  const base = "https://github.com/" + request.repository + "/releases/download/v" + version + "/"
  const cache_dir = path_normalize(request.cache_dir)
  const archive = path_join(cache_dir, "downloads", version, asset)
  const metadata = path_join(cache_dir, "metadata", version, "SHA256SUMS")
  return {
    version: version,
    target: request.target,
    asset: asset,
    cache_dir: cache_dir,
    install_dir: path_normalize(request.install_dir),
    archive_path: archive,
    metadata_path: metadata,
    repository: request.repository,
    base: base,
  }
}

fn run_native_installer(
  process: HarnessProcess,
  request: RuntimeInstallRequest,
  archive: string,
  checksum: string,
  install_dir: string,
  version: string,
) -> NativeReceipt {
  const outcome = process.run(
    {
      program: request.installer,
      args: [
        "upgrade",
        "--archive",
        archive,
        "--archive-sha256",
        checksum,
        "--install-dir",
        install_dir,
        "--version",
        version,
        "--json",
      ],
      timeout_ms: 120000,
    },
  )
  const failure = trim(outcome.stderr ?? "")
  const stdout = trim(outcome.stdout ?? "")
  require stdout != "",
    if failure == "" {
    "native runtime installer failed before emitting a receipt"
  } else {
    failure
  }
  const envelope = schema_expect(json_parse(stdout), schema_of(NativeEnvelope))
  require envelope.schemaVersion == 1, "unsupported native installer schema"
  require outcome.success && envelope.ok,
    envelope.error?.message
    ?? if failure == "" {
      "runtime installation failed"
    } else {
      failure
    }
  require envelope.data != nil, "native installer returned no receipt"
  return envelope.data
}

/**
 * Download and cache one verified archive, then install it through the native CLI owner.
 *
 * @effects: [fs, net, process, clock, random]
 * @errors: [verification_failed, install_failed]
 */
pub fn install_runtime(harness: Harness, request: RuntimeInstallRequest) -> RuntimeReceipt {
  const plan = runtime_plan(request)
  const version = plan.version
  const selected = request + {version: version}
  const asset = plan.asset
  const base = plan.base
  const archive = plan.archive_path
  const metadata = plan.metadata_path
  const verified = expected_checksum(harness, selected, metadata, base, asset)
  const checksum = verified.checksum
  const options = {
    headers: GITHUB_REQUEST_HEADERS,
    retry: {
      max: request.attempts ?? DEFAULT_ATTEMPTS,
      backoff_ms: request.delay_ms ?? DEFAULT_DELAY_MS,
    },
    timeout_ms: 60000,
    max_response_bytes: 1073741824,
  }
  let cached = harness.fs.exists(archive)
  for attempt in [0, 1] {
    const candidate = if cached {
      archive
    } else {
      path_join(dirname(archive), ".harn-bootstrap-" + harness.random.uuid() + "-" + asset)
    }
    const attempt_result = try {
      if !cached {
        require !(request.offline ?? false), "offline runtime archive is unavailable"
        harness.fs.mkdir(dirname(archive))
        const direct = try {
          harness.net.download(base + asset, candidate, options)
        }
        if is_err(direct) || unwrap(direct).status != 200 {
          const access = verified.release_api ?? load_release_api(harness.net, selected)
          const record = release_asset(access, asset)
          require record != nil, "release has no asset named ${asset}"
          const url =
            "https://api.github.com/repos/${request.repository}/releases/assets/${release_asset_id(record)}"
          const response = harness.net.download(
            url,
            candidate,
            options
              + {headers: release_headers(request, "application/octet-stream")},
          )
          require response.status == 200, "runtime archive asset API HTTP ${response.status}"
        }
      }
      let receipt = run_native_installer(
        harness.process,
        request,
        candidate,
        checksum,
        plan.install_dir,
        version,
      )
      if !cached {
        const published = try {
          harness.fs.rename(candidate, archive)
        }
        if is_err(published) {
          // A concurrent downloader may already have published this exact
          // cache name. Trust it only after the native owner verifies it.
          receipt = run_native_installer(
            harness.process,
            request,
            archive,
            checksum,
            plan.install_dir,
            version,
          )
        }
      }
      return receipt
        + {
          schema_version: "harn-bootstrap-v1",
          target: request.target,
          source: base + asset,
          cache_hit: cached,
          checksum_source: verified.source,
        }
    } finally {
      if candidate != archive && harness.fs.exists(candidate) {
        harness.fs.delete(candidate)
      }
    }
    if is_err(attempt_result) {
      require cached && attempt == 0 && !(request.offline ?? false), unwrap_err(attempt_result)
      cached = false
    }
  }
  throw "runtime installation exhausted its cache recovery"
}