|
| 1 | +import * as Data from 'effect/Data' |
| 2 | +import * as Effect from 'effect/Effect' |
| 3 | +import * as HttpClient from 'effect/http/HttpClient' |
| 4 | +import * as HttpClientRequest from 'effect/http/HttpClientRequest' |
| 5 | +import * as HttpClientResponse from 'effect/http/HttpClientResponse' |
| 6 | +import * as Schedule from 'effect/Schedule' |
| 7 | +import * as Schema from 'effect/Schema' |
| 8 | +import { createHash } from 'node:crypto' |
| 9 | +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises' |
| 10 | +import { homedir } from 'node:os' |
| 11 | +import path from 'node:path' |
| 12 | +import { arch } from 'node:process' |
| 13 | +import { gunzipSync } from 'node:zlib' |
| 14 | + |
| 15 | +const REPOSITORY = 'allaboutapps/integresql' |
| 16 | + |
| 17 | +const V1_1_0_LAYER_DIGESTS: Readonly<Record<string, string>> = { |
| 18 | + x64: 'sha256:8e4268615a42a8e45def4ecc7397241c9b598c3731e4c0a0c951c39e0c48093c', |
| 19 | + arm64: 'sha256:77ba01934c00eb411a42df97af551d904dcc02b8d3db1027101378923f32aab3', |
| 20 | +} |
| 21 | + |
| 22 | +const CACHE = path.join(homedir(), '.cache', 'agent', 'integresql-layers') |
| 23 | + |
| 24 | +const BLOCK = 512 |
| 25 | + |
| 26 | +export class IntegresqlUnavailable extends Data.TaggedError('IntegresqlUnavailable')<{ readonly reason: string }> { |
| 27 | + override get message(): string { |
| 28 | + return `the pinned IntegreSQL binary is unavailable: ${this.reason}` |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +const unavailable = (cause: unknown) => |
| 33 | + new IntegresqlUnavailable({ reason: cause instanceof Error ? cause.message : String(cause) }) |
| 34 | + |
| 35 | +const digestOf = (bytes: Uint8Array): string => `sha256:${createHash('sha256').update(bytes).digest('hex')}` |
| 36 | + |
| 37 | +const entryOf = (archive: Uint8Array, name: string): Uint8Array | undefined => { |
| 38 | + let offset = 0 |
| 39 | + while (offset + BLOCK <= archive.length) { |
| 40 | + const header = Buffer.from(archive.subarray(offset, offset + BLOCK)) |
| 41 | + const nameEnd = header.indexOf(0) |
| 42 | + const entry = header.toString('latin1', 0, nameEnd === -1 || nameEnd > 100 ? 100 : nameEnd).replace(/^\.\//, '') |
| 43 | + if (entry === '') return undefined |
| 44 | + const size = Number.parseInt(header.toString('latin1', 124, 136).replace(/\0/g, '').trim(), 8) |
| 45 | + const data = offset + BLOCK |
| 46 | + if (entry === name) return archive.subarray(data, data + size) |
| 47 | + offset = data + Math.ceil(size / BLOCK) * BLOCK |
| 48 | + } |
| 49 | + return undefined |
| 50 | +} |
| 51 | + |
| 52 | +const TokenAnswer = Schema.Struct({ token: Schema.String }) |
| 53 | + |
| 54 | +const pulled = Effect.fnUntraced( |
| 55 | + function*(digest: string) { |
| 56 | + const client = yield* HttpClient.HttpClient |
| 57 | + const { token } = yield* client.get(`https://ghcr.io/token?scope=repository:${REPOSITORY}:pull`).pipe( |
| 58 | + Effect.flatMap(HttpClientResponse.filterStatusOk), |
| 59 | + Effect.flatMap(HttpClientResponse.schemaBodyJson(TokenAnswer)), |
| 60 | + ) |
| 61 | + const response = yield* client.execute( |
| 62 | + HttpClientRequest.get(`https://ghcr.io/v2/${REPOSITORY}/blobs/${digest}`).pipe( |
| 63 | + HttpClientRequest.bearerToken(token), |
| 64 | + ), |
| 65 | + ).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)) |
| 66 | + return new Uint8Array(yield* response.arrayBuffer) |
| 67 | + }, |
| 68 | + Effect.retry({ schedule: Schedule.exponential('1 second'), times: 4 }), |
| 69 | + Effect.mapError(unavailable), |
| 70 | +) |
| 71 | + |
| 72 | +const cached = (file: string) => |
| 73 | + Effect.promise(() => readFile(file).then((bytes) => new Uint8Array(bytes), () => undefined)) |
| 74 | + |
| 75 | +const kept = (file: string, blob: Uint8Array) => |
| 76 | + Effect.tryPromise({ |
| 77 | + try: async () => { |
| 78 | + await mkdir(CACHE, { recursive: true }) |
| 79 | + const staged = `${file}.${process.pid}.partial` |
| 80 | + await writeFile(staged, blob) |
| 81 | + await rename(staged, file) |
| 82 | + }, |
| 83 | + catch: unavailable, |
| 84 | + }) |
| 85 | + |
| 86 | +const layerOf = Effect.fnUntraced(function*(digest: string) { |
| 87 | + const file = path.join(CACHE, digest.slice('sha256:'.length)) |
| 88 | + const hit = yield* cached(file) |
| 89 | + if (hit && digestOf(hit) === digest) return hit |
| 90 | + const blob = yield* pulled(digest) |
| 91 | + if (digestOf(blob) !== digest) { |
| 92 | + return yield* new IntegresqlUnavailable({ reason: `the pulled layer is ${digestOf(blob)}, not ${digest}` }) |
| 93 | + } |
| 94 | + yield* kept(file, blob) |
| 95 | + return blob |
| 96 | +}) |
| 97 | + |
| 98 | +export const integresqlBinary = Effect.gen(function*() { |
| 99 | + const digest = V1_1_0_LAYER_DIGESTS[arch] |
| 100 | + if (!digest) return yield* new IntegresqlUnavailable({ reason: `no pinned layer for ${arch}` }) |
| 101 | + const blob = yield* layerOf(digest) |
| 102 | + const archive = yield* Effect.try({ try: () => gunzipSync(blob), catch: unavailable }) |
| 103 | + const binary = entryOf(archive, 'integresql') |
| 104 | + if (!binary) return yield* new IntegresqlUnavailable({ reason: `layer ${digest} holds no /integresql` }) |
| 105 | + return binary |
| 106 | +}) |
0 commit comments