The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { createHash } from "node:crypto"; |
| 2 | import { constants, type BigIntStats } from "node:fs"; |
| 3 | import { lstat, open, realpath } from "node:fs/promises"; |
| 4 | import * as Data from "effect/Data"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Stream from "effect/Stream"; |
| 7 | |
| 8 | const READ_CHUNK_BYTES = 64 * 1024; |
| 9 | |
| 10 | export interface VerifiedFile { |
| 11 | readonly _tag: "VerifiedFile" | "ArtifactFile"; |
| 12 | readonly path: string; |
| 13 | readonly size: number; |
| 14 | readonly mode: number; |
| 15 | readonly identity: { |
| 16 | readonly dev: string; |
| 17 | readonly ino: string; |
| 18 | readonly size: string; |
| 19 | readonly mtimeNs: string; |
| 20 | readonly ctimeNs: string; |
| 21 | }; |
| 22 | } |
| 23 | |
| 24 | export interface ArtifactFile extends VerifiedFile { |
| 25 | readonly _tag: "ArtifactFile"; |
| 26 | readonly sha256: string; |
| 27 | readonly cleanup: Effect.Effect<void>; |
| 28 | } |
| 29 | |
| 30 | const toError = (message: string, cause: unknown) => new Error(message, { cause }); |
| 31 | |
| 32 | export class ArtifactFileError extends Data.TaggedError("ArtifactFileError")<{ |
| 33 | readonly message: string; |
| 34 | readonly cause?: unknown; |
| 35 | }> {} |
| 36 | |
| 37 | const toArtifactFileError = (message: string) => (cause: unknown) => |
| 38 | new ArtifactFileError({ message: cause instanceof Error ? cause.message : message, cause }); |
| 39 | |
| 40 | const isSameIdentity = (stat: BigIntStats, identity: VerifiedFile["identity"]) => |
| 41 | stat.isFile() && |
| 42 | stat.dev.toString() === identity.dev && |
| 43 | stat.ino.toString() === identity.ino && |
| 44 | stat.size.toString() === identity.size && |
| 45 | stat.mtimeNs.toString() === identity.mtimeNs && |
| 46 | stat.ctimeNs.toString() === identity.ctimeNs; |
| 47 | |
| 48 | const identityFrom = (stat: BigIntStats): VerifiedFile["identity"] => ({ |
| 49 | dev: stat.dev.toString(), |
| 50 | ino: stat.ino.toString(), |
| 51 | size: stat.size.toString(), |
| 52 | mtimeNs: stat.mtimeNs.toString(), |
| 53 | ctimeNs: stat.ctimeNs.toString(), |
| 54 | }); |
| 55 | |
| 56 | const validateLimit = (maxBytes: number) => { |
| 57 | if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) { |
| 58 | throw new Error("Artifact maxBytes must be a positive safe integer."); |
| 59 | } |
| 60 | }; |
| 61 | |
| 62 | const validateStat = ( |
| 63 | stat: BigIntStats, |
| 64 | maxBytes: number, |
| 65 | description: string, |
| 66 | allowEmpty: boolean, |
| 67 | ) => { |
| 68 | if (!stat.isFile()) { |
| 69 | throw new Error(`${description} must be a regular file.`); |
| 70 | } |
| 71 | if (!allowEmpty && stat.size <= 0n) { |
| 72 | throw new Error(`${description} must be non-empty.`); |
| 73 | } |
| 74 | if (stat.size > BigInt(maxBytes) || stat.size > BigInt(Number.MAX_SAFE_INTEGER)) { |
| 75 | throw new Error(`${description} exceeds the ${maxBytes} byte upload safety limit.`); |
| 76 | } |
| 77 | }; |
| 78 | |
| 79 | async function* readVerifiedChunks(artifact: VerifiedFile): AsyncGenerator<Uint8Array> { |
| 80 | const handle = await open(artifact.path, constants.O_RDONLY | constants.O_NOFOLLOW); |
| 81 | try { |
| 82 | const before = await handle.stat({ bigint: true }); |
| 83 | if (!isSameIdentity(before, artifact.identity)) { |
| 84 | throw new Error( |
| 85 | "Prisma deployment artifact changed after it was validated; rebuild or reselect the artifact before deploying.", |
| 86 | ); |
| 87 | } |
| 88 | |
| 89 | let remaining = artifact.size; |
| 90 | while (remaining > 0) { |
| 91 | const buffer = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining)); |
| 92 | const { bytesRead } = await handle.read(buffer, 0, buffer.byteLength, null); |
| 93 | if (bytesRead === 0) { |
| 94 | throw new Error("Prisma deployment artifact was truncated while it was being read."); |
| 95 | } |
| 96 | remaining -= bytesRead; |
| 97 | yield new Uint8Array(buffer.buffer, buffer.byteOffset, bytesRead); |
| 98 | } |
| 99 | |
| 100 | const trailing = Buffer.allocUnsafe(1); |
| 101 | const { bytesRead: trailingBytes } = await handle.read(trailing, 0, trailing.byteLength, null); |
| 102 | const after = await handle.stat({ bigint: true }); |
| 103 | if (trailingBytes !== 0 || !isSameIdentity(after, artifact.identity)) { |
| 104 | throw new Error( |
| 105 | "Prisma deployment artifact changed while it was being read; rebuild or reselect the artifact before deploying.", |
| 106 | ); |
| 107 | } |
| 108 | } finally { |
| 109 | await handle.close(); |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | const inspectVerifiedFilePromise = async ( |
| 114 | inputPath: string, |
| 115 | maxBytes: number, |
| 116 | options?: { |
| 117 | readonly allowEmpty?: boolean; |
| 118 | readonly description?: string; |
| 119 | }, |
| 120 | ) => { |
| 121 | validateLimit(maxBytes); |
| 122 | const description = options?.description ?? "File"; |
| 123 | const inputStat = await lstat(inputPath, { bigint: true }); |
| 124 | if (inputStat.isSymbolicLink()) { |
| 125 | throw new Error( |
| 126 | `${description} must not be a symbolic link; provide the regular file directly.`, |
| 127 | ); |
| 128 | } |
| 129 | validateStat(inputStat, maxBytes, description, options?.allowEmpty ?? false); |
| 130 | const canonicalPath = await realpath(inputPath); |
| 131 | const stat = await lstat(canonicalPath, { bigint: true }); |
| 132 | validateStat(stat, maxBytes, description, options?.allowEmpty ?? false); |
| 133 | if (!isSameIdentity(stat, identityFrom(inputStat))) { |
| 134 | throw new Error( |
| 135 | `${description} changed while it was being validated; retry with a stable file.`, |
| 136 | ); |
| 137 | } |
| 138 | return { |
| 139 | _tag: "VerifiedFile" as const, |
| 140 | path: canonicalPath, |
| 141 | size: Number(stat.size), |
| 142 | mode: Number(stat.mode), |
| 143 | identity: identityFrom(stat), |
| 144 | } satisfies VerifiedFile; |
| 145 | }; |
| 146 | |
| 147 | export const inspectVerifiedFile = ( |
| 148 | inputPath: string, |
| 149 | maxBytes: number, |
| 150 | options?: { |
| 151 | readonly allowEmpty?: boolean; |
| 152 | readonly description?: string; |
| 153 | }, |
| 154 | ) => |
| 155 | Effect.tryPromise({ |
| 156 | try: () => inspectVerifiedFilePromise(inputPath, maxBytes, options), |
| 157 | catch: toArtifactFileError("Failed to validate file."), |
| 158 | }); |
| 159 | |
| 160 | export const inspectArtifactFile = ( |
| 161 | inputPath: string, |
| 162 | maxBytes: number, |
| 163 | options?: { |
| 164 | readonly cleanup?: Effect.Effect<void>; |
| 165 | readonly description?: string; |
| 166 | }, |
| 167 | ) => |
| 168 | Effect.tryPromise({ |
| 169 | try: async (signal) => { |
| 170 | const description = options?.description ?? "Prisma deployment artifact"; |
| 171 | const verified = await inspectVerifiedFilePromise(inputPath, maxBytes, { |
| 172 | description, |
| 173 | }); |
| 174 | const hash = createHash("sha256"); |
| 175 | for await (const chunk of readVerifiedChunks(verified)) { |
| 176 | if (signal.aborted) { |
| 177 | throw new Error("Prisma deployment artifact validation was aborted."); |
| 178 | } |
| 179 | hash.update(chunk); |
| 180 | } |
| 181 | return { |
| 182 | ...verified, |
| 183 | _tag: "ArtifactFile" as const, |
| 184 | sha256: hash.digest("hex"), |
| 185 | cleanup: options?.cleanup ?? Effect.void, |
| 186 | } satisfies ArtifactFile; |
| 187 | }, |
| 188 | catch: toArtifactFileError("Failed to validate Prisma deployment artifact."), |
| 189 | }); |
| 190 | |
| 191 | export const artifactFileStream = (artifact: ArtifactFile) => |
| 192 | Stream.fromAsyncIterable(readVerifiedChunks(artifact), (cause) => |
| 193 | cause instanceof Error ? cause : toError("Failed to stream Prisma deployment artifact.", cause), |
| 194 | ); |
| 195 | |
| 196 | export const verifiedFileChunks = (file: VerifiedFile) => readVerifiedChunks(file); |
| 197 | |
| 198 | export const readArtifactFile = (artifact: ArtifactFile) => |
| 199 | Effect.gen(function* () { |
| 200 | const bytes = new Uint8Array(artifact.size); |
| 201 | let offset = 0; |
| 202 | yield* Stream.runForEach(artifactFileStream(artifact), (chunk) => |
| 203 | Effect.sync(() => { |
| 204 | bytes.set(chunk, offset); |
| 205 | offset += chunk.byteLength; |
| 206 | }), |
| 207 | ); |
| 208 | if (offset !== artifact.size) { |
| 209 | return yield* new ArtifactFileError({ |
| 210 | message: "Prisma deployment artifact length changed while it was being read.", |
| 211 | }); |
| 212 | } |
| 213 | return bytes; |
| 214 | }); |