@leed-ai/git-gateway-backend-artifacts 0.1.0 → 0.1.1-next.20261122230525
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.
- package/dist/artifacts-backend.js +15 -8
- package/dist/artifacts-backend.js.map +1 -1
- package/dist/artifacts-errors.d.ts +11 -0
- package/dist/artifacts-errors.js +18 -1
- package/dist/artifacts-errors.js.map +1 -1
- package/dist/artifacts-git-reads.d.ts +2 -2
- package/dist/artifacts-git-reads.js +8 -3
- package/dist/artifacts-git-reads.js.map +1 -1
- package/package.json +1 -1
- package/src/artifacts-backend.ts +23 -13
- package/src/artifacts-errors.ts +19 -0
- package/src/artifacts-git-reads.ts +9 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { releaseHandle } from "./artifacts-binding.js";
|
|
2
|
-
import { artifactsErrorCode, isRepoNotFound, toGatewayError } from "./artifacts-errors.js";
|
|
2
|
+
import { artifactsErrorCode, isRepoNotFound, isWrongKind, toGatewayError } from "./artifacts-errors.js";
|
|
3
3
|
import { blobIdAt, isUnserializableBlob, readBlobOverGit } from "./artifacts-git-reads.js";
|
|
4
4
|
import { toContractCommit, toStorageTreeEntry } from "./artifacts-mapping.js";
|
|
5
5
|
import { ArtifactsCommit, ArtifactsCreateResult, ArtifactsRepoInfo, ArtifactsToken, ArtifactsTreeEntry } from "./schemas/artifacts-binding-results.js";
|
|
@@ -88,7 +88,7 @@ var ArtifactsBackend = class {
|
|
|
88
88
|
const repo = parseStorageInput(RepoName, name);
|
|
89
89
|
const id = parseStorageInput(Sha, sha);
|
|
90
90
|
return this.#withRepo(repo, "readCommit", async (handle) => {
|
|
91
|
-
const metadata = await this.#readTyped(async () => handle.readCommit(id), [async () => handle.readBlob(id), async () => handle.readTree(id)]);
|
|
91
|
+
const metadata = await this.#readTyped(id, async () => handle.readCommit(id), [async () => handle.readBlob(id), async () => handle.readTree(id)]);
|
|
92
92
|
return metadata === null ? null : toContractCommit(parseHost(ArtifactsCommit, metadata));
|
|
93
93
|
});
|
|
94
94
|
}
|
|
@@ -96,7 +96,7 @@ var ArtifactsBackend = class {
|
|
|
96
96
|
const repo = parseStorageInput(RepoName, name);
|
|
97
97
|
const id = parseStorageInput(Sha, sha);
|
|
98
98
|
return this.#withRepo(repo, "readTree", async (handle) => {
|
|
99
|
-
const entries = await this.#readTyped(async () => handle.readTree(id), [async () => handle.readBlob(id), async () => handle.readCommit(id)]);
|
|
99
|
+
const entries = await this.#readTyped(id, async () => handle.readTree(id), [async () => handle.readBlob(id), async () => handle.readCommit(id)]);
|
|
100
100
|
return entries === null ? null : z.array(ArtifactsTreeEntry).parse(entries).map(toStorageTreeEntry);
|
|
101
101
|
});
|
|
102
102
|
}
|
|
@@ -107,6 +107,7 @@ var ArtifactsBackend = class {
|
|
|
107
107
|
try {
|
|
108
108
|
return await bytesOf(await handle.readBlob(id));
|
|
109
109
|
} catch (error) {
|
|
110
|
+
if (isWrongKind(error, id)) return null;
|
|
110
111
|
if (!isUnserializableBlob(error)) throw error;
|
|
111
112
|
return readBlobOverGit(await this.gitRemote(repo, "read"), id);
|
|
112
113
|
}
|
|
@@ -123,6 +124,7 @@ var ArtifactsBackend = class {
|
|
|
123
124
|
path: file
|
|
124
125
|
}));
|
|
125
126
|
} catch (error) {
|
|
127
|
+
if (isWrongKind(error, revision)) return null;
|
|
126
128
|
if (!isUnserializableBlob(error)) throw error;
|
|
127
129
|
const blob = await blobIdAt(handle, revision, file);
|
|
128
130
|
return blob === null ? null : readBlobOverGit(await this.gitRemote(repo, "read"), blob);
|
|
@@ -172,15 +174,20 @@ var ArtifactsBackend = class {
|
|
|
172
174
|
}
|
|
173
175
|
}
|
|
174
176
|
/**
|
|
175
|
-
* Reads
|
|
176
|
-
*
|
|
177
|
-
* from a real failure by the
|
|
177
|
+
* Reads object `id` as one kind. The binding answers null for a missing id but throws when the id
|
|
178
|
+
* names an object of another kind; that case is null too, as the contract requires. It is told
|
|
179
|
+
* apart from a real failure by the message saying so ({@link isWrongKind}: what the live binding
|
|
180
|
+
* and the simulator send), else, for an INTERNAL_ERROR or an error whose code did not survive, by
|
|
181
|
+
* the object being readable as one of the other kinds (`probes`). Anything else, or a probe that
|
|
182
|
+
* finds nothing, rethrows the original failure.
|
|
178
183
|
*/
|
|
179
|
-
async #readTyped(read, probes) {
|
|
184
|
+
async #readTyped(id, read, probes) {
|
|
180
185
|
try {
|
|
181
186
|
return await read();
|
|
182
187
|
} catch (error) {
|
|
183
|
-
if (
|
|
188
|
+
if (isWrongKind(error, id)) return null;
|
|
189
|
+
const code = artifactsErrorCode(error);
|
|
190
|
+
if (code !== null && code !== "INTERNAL_ERROR") throw error;
|
|
184
191
|
for (const probe of probes) if (await probe().catch((probeError) => isUnserializableBlob(probeError) ? true : null) !== null) return null;
|
|
185
192
|
throw error;
|
|
186
193
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"artifacts-backend.js","names":[],"sources":["../src/artifacts-backend.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport { isGatewayError } from '@leed-ai/git-gateway-contract/gateway-error';\nimport type { Commit } from '@leed-ai/git-gateway-contract/schemas/commit';\nimport { FilePath, RepoName, Revision } from '@leed-ai/git-gateway-contract/schemas/names';\nimport { Sha } from '@leed-ai/git-gateway-contract/schemas/sha';\nimport { GitAccess, GitRemote } from '@leed-ai/git-gateway-contract/storage/git-remote';\nimport type { StorageBackend } from '@leed-ai/git-gateway-contract/storage/storage-backend';\nimport { parseStorageInput } from '@leed-ai/git-gateway-contract/storage/storage-input';\nimport { StorageLogOptions, StorageRef } from '@leed-ai/git-gateway-contract/storage/storage-read';\nimport {\n CreateStorageRepoOptions,\n StorageRepoInfo,\n} from '@leed-ai/git-gateway-contract/storage/storage-repo-info';\nimport type { StorageTreeEntry } from '@leed-ai/git-gateway-contract/storage/storage-tree-entry';\nimport { z } from 'zod';\n\nimport {\n releaseHandle,\n type ArtifactsNamespaceBinding,\n type ArtifactsRepoHandle,\n} from './artifacts-binding.ts';\nimport { artifactsErrorCode, isRepoNotFound, toGatewayError } from './artifacts-errors.ts';\nimport { blobIdAt, isUnserializableBlob, readBlobOverGit } from './artifacts-git-reads.ts';\nimport { toContractCommit, toStorageTreeEntry } from './artifacts-mapping.ts';\nimport {\n ArtifactsCommit,\n ArtifactsCreateResult,\n ArtifactsRepoInfo,\n ArtifactsToken,\n ArtifactsTreeEntry,\n} from './schemas/artifacts-binding-results.ts';\n\n/** Options of an {@link ArtifactsBackend}. */\nexport interface ArtifactsBackendOptions {\n /** The Artifacts binding, `env.ARTIFACTS`. */\n readonly binding: ArtifactsNamespaceBinding;\n /** Lifetime of the tokens gitRemote() mints, in seconds: 60–31536000, default 300. */\n readonly tokenTtlSeconds?: number;\n}\n\nconst TokenTtl = z.int().min(60).max(31_536_000);\n/**\n * The name the binding resolves for a StorageRef. The live binding resolves short names (\"main\",\n * \"v1\", a commit id) and answers nothing for fully qualified ones (\"refs/heads/main\" → no commits),\n * so the \"refs/heads/\" or \"refs/tags/\" prefix is dropped. The binding then resolves the name as git\n * does a short name, so a tag and a branch sharing one name cannot be told apart.\n */\nexport function bindingRef(ref: string): string {\n return ref.replace(/^refs\\/(?:heads|tags)\\//, '');\n}\n\nconst bytesOf = async (blob: Blob | null): Promise<Uint8Array | null> =>\n blob === null ? null : new Uint8Array(await blob.arrayBuffer());\n\n/** Parses a host result; a mismatch means the host answered something the contract cannot use. */\nfunction parseHost<S extends z.ZodType>(schema: S, value: unknown): z.output<S> {\n return schema.parse(value);\n}\n\n/**\n * A {@link StorageBackend} over a Cloudflare Artifacts namespace, through the Workers binding:\n * repository lifecycle (create, info, delete), reads (readCommit, readTree, readBlob, readFile,\n * log) and per-call tokens for the repository's git remote. Artifacts has no write or ref API, so\n * every write is a git-receive-pack push to {@link gitRemote}; refs are resolved through the\n * binding's log. Every binding result is parsed with Zod; binding errors become GatewayErrors.\n * Where the binding cannot carry a Blob back (wrangler's remote binding under `wrangler dev`),\n * readBlob and readFile fall back to fetching the blob over the repository's git remote.\n */\nexport class ArtifactsBackend implements StorageBackend {\n readonly #binding: ArtifactsNamespaceBinding;\n readonly #ttl: number;\n\n constructor(options: ArtifactsBackendOptions) {\n this.#binding = options.binding;\n this.#ttl = TokenTtl.parse(options.tokenTtlSeconds ?? 300);\n }\n\n async createRepo(name: string, options: CreateStorageRepoOptions = {}): Promise<StorageRepoInfo> {\n const repo = parseStorageInput(RepoName, name);\n const { defaultBranch } = parseStorageInput(CreateStorageRepoOptions, options);\n try {\n const created = parseHost(\n ArtifactsCreateResult,\n await this.#binding.create(repo, { setDefaultBranch: defaultBranch }),\n );\n return await this.#withRepo(repo, 'createRepo', async (handle) => {\n // The initial write token is never handed out; revoking it is hygiene, so a failure to\n // revoke (the token then simply expires) does not fail the creation.\n await handle.revokeToken(created.token).catch(() => false);\n return this.#info(parseHost(ArtifactsRepoInfo, await handle.info()));\n });\n } catch (error) {\n throw toGatewayError(repo, 'createRepo', error);\n }\n }\n\n async deleteRepo(name: string): Promise<void> {\n const repo = parseStorageInput(RepoName, name);\n try {\n await this.#binding.delete(repo);\n } catch (error) {\n if (!isRepoNotFound(error, repo)) throw toGatewayError(repo, 'deleteRepo', error);\n }\n }\n\n async repoInfo(name: string): Promise<StorageRepoInfo | null> {\n const repo = parseStorageInput(RepoName, name);\n try {\n return await this.#withRepo(repo, 'repoInfo', async (handle) =>\n this.#info(parseHost(ArtifactsRepoInfo, await handle.info())),\n );\n } catch (error) {\n if (isGatewayError(error, 'repo_not_found')) return null;\n throw error;\n }\n }\n\n async resolveRef(name: string, ref: string): Promise<string | null> {\n const repo = parseStorageInput(RepoName, name);\n const parsed = parseStorageInput(StorageRef, ref);\n return this.#withRepo(repo, 'resolveRef', async (handle) => {\n const [head] = z.array(ArtifactsCommit).parse(await handle.log({ ref: bindingRef(parsed), limit: 1 }));\n return head?.hash ?? null;\n });\n }\n\n async readCommit(name: string, sha: string): Promise<Commit | null> {\n const repo = parseStorageInput(RepoName, name);\n const id = parseStorageInput(Sha, sha);\n return this.#withRepo(repo, 'readCommit', async (handle) => {\n const metadata = await this.#readTyped(\n async () => handle.readCommit(id),\n [async () => handle.readBlob(id), async () => handle.readTree(id)],\n );\n return metadata === null ? null : toContractCommit(parseHost(ArtifactsCommit, metadata));\n });\n }\n\n async readTree(name: string, sha: string): Promise<StorageTreeEntry[] | null> {\n const repo = parseStorageInput(RepoName, name);\n const id = parseStorageInput(Sha, sha);\n return this.#withRepo(repo, 'readTree', async (handle) => {\n const entries = await this.#readTyped(\n async () => handle.readTree(id),\n [async () => handle.readBlob(id), async () => handle.readCommit(id)],\n );\n return entries === null ? null : z.array(ArtifactsTreeEntry).parse(entries).map(toStorageTreeEntry);\n });\n }\n\n async readBlob(name: string, sha: string): Promise<Uint8Array | null> {\n const repo = parseStorageInput(RepoName, name);\n const id = parseStorageInput(Sha, sha);\n return this.#withRepo(repo, 'readBlob', async (handle) => {\n try {\n return await bytesOf(await handle.readBlob(id));\n } catch (error) {\n if (!isUnserializableBlob(error)) throw error;\n return readBlobOverGit(await this.gitRemote(repo, 'read'), id);\n }\n });\n }\n\n async readFile(name: string, ref: string, path: string): Promise<Uint8Array | null> {\n const repo = parseStorageInput(RepoName, name);\n const revision = parseStorageInput(Revision, ref);\n const file = parseStorageInput(FilePath, path);\n // A Revision is a commit id or a short branch name, which is what the binding resolves.\n return this.#withRepo(repo, 'readFile', async (handle) => {\n try {\n return await bytesOf(await handle.readFile({ ref: revision, path: file }));\n } catch (error) {\n if (!isUnserializableBlob(error)) throw error;\n const blob = await blobIdAt(handle, revision, file);\n return blob === null ? null : readBlobOverGit(await this.gitRemote(repo, 'read'), blob);\n }\n });\n }\n\n async log(name: string, ref: string, options: StorageLogOptions): Promise<Commit[]> {\n const repo = parseStorageInput(RepoName, name);\n const revision = parseStorageInput(Revision, ref);\n const { limit, offset } = parseStorageInput(StorageLogOptions, options);\n return this.#withRepo(repo, 'log', async (handle) => {\n const commits = z.array(ArtifactsCommit).parse(await handle.log({ ref: revision, limit, offset }));\n return Promise.all(commits.map(toContractCommit));\n });\n }\n\n async gitRemote(name: string, access: string): Promise<GitRemote> {\n const repo = parseStorageInput(RepoName, name);\n const scope = parseStorageInput(GitAccess, access);\n return this.#withRepo(repo, 'gitRemote', async (handle) => {\n const [info, token] = await Promise.all([handle.info(), handle.createToken(scope, this.#ttl)]);\n const parsedToken = parseHost(ArtifactsToken, token);\n return GitRemote.parse({\n url: parseHost(ArtifactsRepoInfo, info).remote,\n headers: { Authorization: `Bearer ${parsedToken.plaintext}` },\n expiresAt: new Date(parsedToken.expiresAt).toISOString(),\n });\n });\n }\n\n /** Runs `work` with a handle on the repository, releasing it after; failures become GatewayErrors. */\n async #withRepo<T>(\n repo: string,\n what: string,\n work: (handle: ArtifactsRepoHandle) => Promise<T>,\n ): Promise<T> {\n let handle: ArtifactsRepoHandle;\n try {\n handle = await this.#binding.get(repo);\n } catch (error) {\n throw toGatewayError(repo, what, error);\n }\n try {\n return await work(handle);\n } catch (error) {\n throw toGatewayError(repo, what, error);\n } finally {\n releaseHandle(handle);\n }\n }\n\n /**\n * Reads an object of one kind. The binding answers null for a missing id but throws\n * INTERNAL_ERROR when the id names an object of another kind; that case is null too, told apart\n * from a real failure by the object being readable as one of the other kinds (`probes`).\n */\n async #readTyped(\n read: () => Promise<unknown>,\n probes: readonly (() => Promise<unknown>)[],\n ): Promise<unknown> {\n try {\n return await read();\n } catch (error) {\n if (artifactsErrorCode(error) !== 'INTERNAL_ERROR') throw error;\n for (const probe of probes) {\n // A Blob that could not be carried back (wrangler's remote binding) was still found.\n const found = await probe().catch((probeError: unknown) =>\n isUnserializableBlob(probeError) ? true : null,\n );\n if (found !== null) return null;\n }\n throw error;\n }\n }\n\n #info(info: ArtifactsRepoInfo): StorageRepoInfo {\n return StorageRepoInfo.parse({\n name: info.name,\n defaultBranch: info.defaultBranch,\n createdAt: new Date(info.createdAt).toISOString(),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAwCA,MAAM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AAM;EACR;CACF;CAEA,MAAM,MAA0C;EAC9C,OAAO,gBAAgB,MAAM;GAC3B,MAAM,KAAK;GACX,eAAe,KAAK;GACpB,WAAW,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,YAAY;EAClD,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"artifacts-backend.js","names":[],"sources":["../src/artifacts-backend.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport { isGatewayError } from '@leed-ai/git-gateway-contract/gateway-error';\nimport type { Commit } from '@leed-ai/git-gateway-contract/schemas/commit';\nimport { FilePath, RepoName, Revision } from '@leed-ai/git-gateway-contract/schemas/names';\nimport { Sha } from '@leed-ai/git-gateway-contract/schemas/sha';\nimport { GitAccess, GitRemote } from '@leed-ai/git-gateway-contract/storage/git-remote';\nimport type { StorageBackend } from '@leed-ai/git-gateway-contract/storage/storage-backend';\nimport { parseStorageInput } from '@leed-ai/git-gateway-contract/storage/storage-input';\nimport { StorageLogOptions, StorageRef } from '@leed-ai/git-gateway-contract/storage/storage-read';\nimport {\n CreateStorageRepoOptions,\n StorageRepoInfo,\n} from '@leed-ai/git-gateway-contract/storage/storage-repo-info';\nimport type { StorageTreeEntry } from '@leed-ai/git-gateway-contract/storage/storage-tree-entry';\nimport { z } from 'zod';\n\nimport {\n releaseHandle,\n type ArtifactsNamespaceBinding,\n type ArtifactsRepoHandle,\n} from './artifacts-binding.ts';\nimport { artifactsErrorCode, isRepoNotFound, isWrongKind, toGatewayError } from './artifacts-errors.ts';\nimport { blobIdAt, isUnserializableBlob, readBlobOverGit } from './artifacts-git-reads.ts';\nimport { toContractCommit, toStorageTreeEntry } from './artifacts-mapping.ts';\nimport {\n ArtifactsCommit,\n ArtifactsCreateResult,\n ArtifactsRepoInfo,\n ArtifactsToken,\n ArtifactsTreeEntry,\n} from './schemas/artifacts-binding-results.ts';\n\n/** Options of an {@link ArtifactsBackend}. */\nexport interface ArtifactsBackendOptions {\n /** The Artifacts binding, `env.ARTIFACTS`. */\n readonly binding: ArtifactsNamespaceBinding;\n /** Lifetime of the tokens gitRemote() mints, in seconds: 60–31536000, default 300. */\n readonly tokenTtlSeconds?: number;\n}\n\nconst TokenTtl = z.int().min(60).max(31_536_000);\n/**\n * The name the binding resolves for a StorageRef. The live binding resolves short names (\"main\",\n * \"v1\", a commit id) and answers nothing for fully qualified ones (\"refs/heads/main\" → no commits),\n * so the \"refs/heads/\" or \"refs/tags/\" prefix is dropped. The binding then resolves the name as git\n * does a short name, so a tag and a branch sharing one name cannot be told apart.\n */\nexport function bindingRef(ref: string): string {\n return ref.replace(/^refs\\/(?:heads|tags)\\//, '');\n}\n\nconst bytesOf = async (blob: Blob | null): Promise<Uint8Array | null> =>\n blob === null ? null : new Uint8Array(await blob.arrayBuffer());\n\n/** Parses a host result; a mismatch means the host answered something the contract cannot use. */\nfunction parseHost<S extends z.ZodType>(schema: S, value: unknown): z.output<S> {\n return schema.parse(value);\n}\n\n/**\n * A {@link StorageBackend} over a Cloudflare Artifacts namespace, through the Workers binding:\n * repository lifecycle (create, info, delete), reads (readCommit, readTree, readBlob, readFile,\n * log) and per-call tokens for the repository's git remote. Artifacts has no write or ref API, so\n * every write is a git-receive-pack push to {@link gitRemote}; refs are resolved through the\n * binding's log. Every binding result is parsed with Zod; binding errors become GatewayErrors.\n * Where the binding cannot carry a Blob back (wrangler's remote binding under `wrangler dev`),\n * readBlob and readFile fall back to fetching the blob over the repository's git remote.\n */\nexport class ArtifactsBackend implements StorageBackend {\n readonly #binding: ArtifactsNamespaceBinding;\n readonly #ttl: number;\n\n constructor(options: ArtifactsBackendOptions) {\n this.#binding = options.binding;\n this.#ttl = TokenTtl.parse(options.tokenTtlSeconds ?? 300);\n }\n\n async createRepo(name: string, options: CreateStorageRepoOptions = {}): Promise<StorageRepoInfo> {\n const repo = parseStorageInput(RepoName, name);\n const { defaultBranch } = parseStorageInput(CreateStorageRepoOptions, options);\n try {\n const created = parseHost(\n ArtifactsCreateResult,\n await this.#binding.create(repo, { setDefaultBranch: defaultBranch }),\n );\n return await this.#withRepo(repo, 'createRepo', async (handle) => {\n // The initial write token is never handed out; revoking it is hygiene, so a failure to\n // revoke (the token then simply expires) does not fail the creation.\n await handle.revokeToken(created.token).catch(() => false);\n return this.#info(parseHost(ArtifactsRepoInfo, await handle.info()));\n });\n } catch (error) {\n throw toGatewayError(repo, 'createRepo', error);\n }\n }\n\n async deleteRepo(name: string): Promise<void> {\n const repo = parseStorageInput(RepoName, name);\n try {\n await this.#binding.delete(repo);\n } catch (error) {\n if (!isRepoNotFound(error, repo)) throw toGatewayError(repo, 'deleteRepo', error);\n }\n }\n\n async repoInfo(name: string): Promise<StorageRepoInfo | null> {\n const repo = parseStorageInput(RepoName, name);\n try {\n return await this.#withRepo(repo, 'repoInfo', async (handle) =>\n this.#info(parseHost(ArtifactsRepoInfo, await handle.info())),\n );\n } catch (error) {\n if (isGatewayError(error, 'repo_not_found')) return null;\n throw error;\n }\n }\n\n async resolveRef(name: string, ref: string): Promise<string | null> {\n const repo = parseStorageInput(RepoName, name);\n const parsed = parseStorageInput(StorageRef, ref);\n return this.#withRepo(repo, 'resolveRef', async (handle) => {\n const [head] = z.array(ArtifactsCommit).parse(await handle.log({ ref: bindingRef(parsed), limit: 1 }));\n return head?.hash ?? null;\n });\n }\n\n async readCommit(name: string, sha: string): Promise<Commit | null> {\n const repo = parseStorageInput(RepoName, name);\n const id = parseStorageInput(Sha, sha);\n return this.#withRepo(repo, 'readCommit', async (handle) => {\n const metadata = await this.#readTyped(id, async () => handle.readCommit(id), [\n async () => handle.readBlob(id),\n async () => handle.readTree(id),\n ]);\n return metadata === null ? null : toContractCommit(parseHost(ArtifactsCommit, metadata));\n });\n }\n\n async readTree(name: string, sha: string): Promise<StorageTreeEntry[] | null> {\n const repo = parseStorageInput(RepoName, name);\n const id = parseStorageInput(Sha, sha);\n return this.#withRepo(repo, 'readTree', async (handle) => {\n const entries = await this.#readTyped(id, async () => handle.readTree(id), [\n async () => handle.readBlob(id),\n async () => handle.readCommit(id),\n ]);\n return entries === null ? null : z.array(ArtifactsTreeEntry).parse(entries).map(toStorageTreeEntry);\n });\n }\n\n async readBlob(name: string, sha: string): Promise<Uint8Array | null> {\n const repo = parseStorageInput(RepoName, name);\n const id = parseStorageInput(Sha, sha);\n return this.#withRepo(repo, 'readBlob', async (handle) => {\n try {\n return await bytesOf(await handle.readBlob(id));\n } catch (error) {\n // The binding documents null for an id that is not a blob; an error saying so is null too.\n if (isWrongKind(error, id)) return null;\n if (!isUnserializableBlob(error)) throw error;\n return readBlobOverGit(await this.gitRemote(repo, 'read'), id);\n }\n });\n }\n\n async readFile(name: string, ref: string, path: string): Promise<Uint8Array | null> {\n const repo = parseStorageInput(RepoName, name);\n const revision = parseStorageInput(Revision, ref);\n const file = parseStorageInput(FilePath, path);\n // A Revision is a commit id or a short branch name, which is what the binding resolves.\n return this.#withRepo(repo, 'readFile', async (handle) => {\n try {\n return await bytesOf(await handle.readFile({ ref: revision, path: file }));\n } catch (error) {\n // A revision naming a tree or a blob is a revision that does not exist.\n if (isWrongKind(error, revision)) return null;\n if (!isUnserializableBlob(error)) throw error;\n const blob = await blobIdAt(handle, revision, file);\n return blob === null ? null : readBlobOverGit(await this.gitRemote(repo, 'read'), blob);\n }\n });\n }\n\n async log(name: string, ref: string, options: StorageLogOptions): Promise<Commit[]> {\n const repo = parseStorageInput(RepoName, name);\n const revision = parseStorageInput(Revision, ref);\n const { limit, offset } = parseStorageInput(StorageLogOptions, options);\n return this.#withRepo(repo, 'log', async (handle) => {\n const commits = z.array(ArtifactsCommit).parse(await handle.log({ ref: revision, limit, offset }));\n return Promise.all(commits.map(toContractCommit));\n });\n }\n\n async gitRemote(name: string, access: string): Promise<GitRemote> {\n const repo = parseStorageInput(RepoName, name);\n const scope = parseStorageInput(GitAccess, access);\n return this.#withRepo(repo, 'gitRemote', async (handle) => {\n const [info, token] = await Promise.all([handle.info(), handle.createToken(scope, this.#ttl)]);\n const parsedToken = parseHost(ArtifactsToken, token);\n return GitRemote.parse({\n url: parseHost(ArtifactsRepoInfo, info).remote,\n headers: { Authorization: `Bearer ${parsedToken.plaintext}` },\n expiresAt: new Date(parsedToken.expiresAt).toISOString(),\n });\n });\n }\n\n /** Runs `work` with a handle on the repository, releasing it after; failures become GatewayErrors. */\n async #withRepo<T>(\n repo: string,\n what: string,\n work: (handle: ArtifactsRepoHandle) => Promise<T>,\n ): Promise<T> {\n let handle: ArtifactsRepoHandle;\n try {\n handle = await this.#binding.get(repo);\n } catch (error) {\n throw toGatewayError(repo, what, error);\n }\n try {\n return await work(handle);\n } catch (error) {\n throw toGatewayError(repo, what, error);\n } finally {\n releaseHandle(handle);\n }\n }\n\n /**\n * Reads object `id` as one kind. The binding answers null for a missing id but throws when the id\n * names an object of another kind; that case is null too, as the contract requires. It is told\n * apart from a real failure by the message saying so ({@link isWrongKind}: what the live binding\n * and the simulator send), else, for an INTERNAL_ERROR or an error whose code did not survive, by\n * the object being readable as one of the other kinds (`probes`). Anything else, or a probe that\n * finds nothing, rethrows the original failure.\n */\n async #readTyped(\n id: string,\n read: () => Promise<unknown>,\n probes: readonly (() => Promise<unknown>)[],\n ): Promise<unknown> {\n try {\n return await read();\n } catch (error) {\n if (isWrongKind(error, id)) return null;\n const code = artifactsErrorCode(error);\n if (code !== null && code !== 'INTERNAL_ERROR') throw error;\n for (const probe of probes) {\n // A Blob that could not be carried back (wrangler's remote binding) was still found.\n const found = await probe().catch((probeError: unknown) =>\n isUnserializableBlob(probeError) ? true : null,\n );\n if (found !== null) return null;\n }\n throw error;\n }\n }\n\n #info(info: ArtifactsRepoInfo): StorageRepoInfo {\n return StorageRepoInfo.parse({\n name: info.name,\n defaultBranch: info.defaultBranch,\n createdAt: new Date(info.createdAt).toISOString(),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAwCA,MAAM,WAAW,EAAE,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,OAAU;;;;;;;AAO/C,SAAgB,WAAW,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AM,CAAC,CAAC,OAAO,eACjC,qBAAqB,UAAU,IAAI,OAAO,IAC5C,MACc,MAAM,OAAO;GAE7B,MAAM;EACR;CACF;CAEA,MAAM,MAA0C;EAC9C,OAAO,gBAAgB,MAAM;GAC3B,MAAM,KAAK;GACX,eAAe,KAAK;GACpB,WAAW,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,YAAY;EAClD,CAAC;CACH;AACF"}
|
|
@@ -17,6 +17,17 @@ export declare function isAlreadyExists(thrown: unknown, repo: string): boolean;
|
|
|
17
17
|
* accepted.
|
|
18
18
|
*/
|
|
19
19
|
export declare function isRepoNotFound(thrown: unknown, repo: string): boolean;
|
|
20
|
+
/**
|
|
21
|
+
* Whether a failure of a binding read of object `sha` says only that the id names an object of
|
|
22
|
+
* another kind (a blob read as a tree, a tree read as a commit). The binding documents
|
|
23
|
+
* INTERNAL_ERROR for that case without saying which, so the message is what tells it apart from a
|
|
24
|
+
* real failure. The live binding was seen to throw "Invalid object requested. SHA must identify a
|
|
25
|
+
* commit or a tree. <sha> is a blob." (optionally after an "ArtifactsError: " prefix) and the local
|
|
26
|
+
* simulator "Git object <sha> is a blob, not a tree". So a message naming this id as "<sha> is a
|
|
27
|
+
* <kind>", or one saying "Invalid object requested" with "must identify a", is accepted; anything
|
|
28
|
+
* else is not, so an outage is never mistaken for a missing object.
|
|
29
|
+
*/
|
|
30
|
+
export declare function isWrongKind(thrown: unknown, sha: string): boolean;
|
|
20
31
|
/**
|
|
21
32
|
* Translates a failure of a binding call on repository `repo` into a GatewayError: NOT_FOUND is
|
|
22
33
|
* repo_not_found (also when only the numeric code or the message says so, see
|
package/dist/artifacts-errors.js
CHANGED
|
@@ -46,6 +46,23 @@ function isRepoNotFound(thrown, repo) {
|
|
|
46
46
|
return typeof message === "string" && new RegExp(String.raw`^(?:ArtifactsError: )?repository not found: ${escapeRegExp(repo)}\.?$`, "i").test(message.trim());
|
|
47
47
|
}
|
|
48
48
|
/**
|
|
49
|
+
* Whether a failure of a binding read of object `sha` says only that the id names an object of
|
|
50
|
+
* another kind (a blob read as a tree, a tree read as a commit). The binding documents
|
|
51
|
+
* INTERNAL_ERROR for that case without saying which, so the message is what tells it apart from a
|
|
52
|
+
* real failure. The live binding was seen to throw "Invalid object requested. SHA must identify a
|
|
53
|
+
* commit or a tree. <sha> is a blob." (optionally after an "ArtifactsError: " prefix) and the local
|
|
54
|
+
* simulator "Git object <sha> is a blob, not a tree". So a message naming this id as "<sha> is a
|
|
55
|
+
* <kind>", or one saying "Invalid object requested" with "must identify a", is accepted; anything
|
|
56
|
+
* else is not, so an outage is never mistaken for a missing object.
|
|
57
|
+
*/
|
|
58
|
+
function isWrongKind(thrown, sha) {
|
|
59
|
+
if (typeof thrown !== "object" || thrown === null) return false;
|
|
60
|
+
const message = Reflect.get(thrown, "message");
|
|
61
|
+
if (typeof message !== "string") return false;
|
|
62
|
+
if (new RegExp(String.raw`\b${escapeRegExp(sha)} is an? (?:commit|tree|blob|tag)\b`, "i").test(message)) return true;
|
|
63
|
+
return /\binvalid object requested\b/i.test(message) && /\bmust identify an? /i.test(message);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
49
66
|
* Translates a failure of a binding call on repository `repo` into a GatewayError: NOT_FOUND is
|
|
50
67
|
* repo_not_found (also when only the numeric code or the message says so, see
|
|
51
68
|
* {@link isRepoNotFound}), ALREADY_EXISTS is repo_exists (for createRepo also when only the numeric code or
|
|
@@ -60,6 +77,6 @@ function toGatewayError(repo, what, thrown) {
|
|
|
60
77
|
if (code === "ALREADY_EXISTS" || what === "createRepo" && isAlreadyExists(thrown, repo)) return repoExists(repo);
|
|
61
78
|
return storageUnavailable(`Artifacts ${what}`, thrown);
|
|
62
79
|
}
|
|
63
|
-
export { artifactsErrorCode, isAlreadyExists, isRepoNotFound, toGatewayError };
|
|
80
|
+
export { artifactsErrorCode, isAlreadyExists, isRepoNotFound, isWrongKind, toGatewayError };
|
|
64
81
|
|
|
65
82
|
//# sourceMappingURL=artifacts-errors.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"artifacts-errors.js","names":[],"sources":["../src/artifacts-errors.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport { isGatewayError } from '@leed-ai/git-gateway-contract/gateway-error';\nimport {\n repoExists,\n repoNotFound,\n storageUnavailable,\n} from '@leed-ai/git-gateway-contract/storage/storage-errors';\n\nimport { ArtifactsBindingError } from './schemas/artifacts-binding-results.ts';\n\n/** The Artifacts error code of something thrown, or null when it is not an Artifacts error. */\nexport function artifactsErrorCode(thrown: unknown): string | null {\n if (typeof thrown !== 'object' || thrown === null) return null;\n const parsed = ArtifactsBindingError.safeParse({\n code: Reflect.get(thrown, 'code'),\n message: Reflect.get(thrown, 'message'),\n });\n return parsed.success ? parsed.data.code : null;\n}\n\n/** The REST API's numeric code for \"already exists\", which the binding's ArtifactsError carries. */\nconst ALREADY_EXISTS_NUMERIC = 10201;\n\nconst escapeRegExp = (text: string): string => text.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n\n/**\n * Whether a failure of `create(repo)` says the repository already exists. The binding documents\n * code ALREADY_EXISTS (numeric 10201), and the local simulator sends it; the live binding was seen\n * to throw an error whose code did not survive, with only the message \"repo already exists:\n * <name>\". So the code, then the numeric code, then exactly that message naming this repository\n * (optionally after an \"ArtifactsError: \" prefix) are accepted.\n */\nexport function isAlreadyExists(thrown: unknown, repo: string): boolean {\n if (artifactsErrorCode(thrown) === 'ALREADY_EXISTS') return true;\n if (typeof thrown !== 'object' || thrown === null) return false;\n if (Reflect.get(thrown, 'numericCode') === ALREADY_EXISTS_NUMERIC) return true;\n const message: unknown = Reflect.get(thrown, 'message');\n return (\n typeof message === 'string' &&\n new RegExp(String.raw`^(?:ArtifactsError: )?repo already exists: ${escapeRegExp(repo)}$`, 'i').test(\n message.trim(),\n )\n );\n}\n\n/** The REST API's numeric code for \"not found\", which the binding's ArtifactsError carries. */\nconst NOT_FOUND_NUMERIC = 10200;\n\n/**\n * Whether a failure of a binding call on `repo` says the repository does not exist. The binding\n * documents code NOT_FOUND (numeric 10200), and the local simulator sends it; the live binding was\n * seen to throw an error whose code did not survive, with only the message \"Repository not found:\n * <name>.\" So the code, then the numeric code, then exactly that message naming this repository\n * (optionally after an \"ArtifactsError: \" prefix, with or without the closing period) are\n * accepted.\n */\nexport function isRepoNotFound(thrown: unknown, repo: string): boolean {\n if (artifactsErrorCode(thrown) === 'NOT_FOUND') return true;\n if (typeof thrown !== 'object' || thrown === null) return false;\n if (Reflect.get(thrown, 'numericCode') === NOT_FOUND_NUMERIC) return true;\n const message: unknown = Reflect.get(thrown, 'message');\n return (\n typeof message === 'string' &&\n new RegExp(String.raw`^(?:ArtifactsError: )?repository not found: ${escapeRegExp(repo)}\\.?$`, 'i').test(\n message.trim(),\n )\n );\n}\n\n/**\n * Translates a failure of a binding call on repository `repo` into a GatewayError: NOT_FOUND is\n * repo_not_found (also when only the numeric code or the message says so, see\n * {@link isRepoNotFound}), ALREADY_EXISTS is repo_exists (for createRepo also when only the numeric code or\n * the message says so, see {@link isAlreadyExists}), everything else (in-progress states,\n * MEMORY_LIMIT, INTERNAL_ERROR, unparsable results) is storage_unavailable. GatewayErrors pass\n * through unchanged.\n */\nexport function toGatewayError(repo: string, what: string, thrown: unknown): Error {\n if (isGatewayError(thrown) && thrown instanceof Error) return thrown;\n const code = artifactsErrorCode(thrown);\n if (isRepoNotFound(thrown, repo)) return repoNotFound(repo);\n if (code === 'ALREADY_EXISTS' || (what === 'createRepo' && isAlreadyExists(thrown, repo)))\n return repoExists(repo);\n return storageUnavailable(`Artifacts ${what}`, thrown);\n}\n"],"mappings":";;;;;AAWA,SAAgB,mBAAmB,QAAgC;CACjE,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO;CAC1D,MAAM,SAAS,sBAAsB,UAAU;EAC7C,MAAM,QAAQ,IAAI,QAAQ,MAAM;EAChC,SAAS,QAAQ,IAAI,QAAQ,SAAS;CACxC,CAAC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AAM;AACvD"}
|
|
1
|
+
{"version":3,"file":"artifacts-errors.js","names":[],"sources":["../src/artifacts-errors.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport { isGatewayError } from '@leed-ai/git-gateway-contract/gateway-error';\nimport {\n repoExists,\n repoNotFound,\n storageUnavailable,\n} from '@leed-ai/git-gateway-contract/storage/storage-errors';\n\nimport { ArtifactsBindingError } from './schemas/artifacts-binding-results.ts';\n\n/** The Artifacts error code of something thrown, or null when it is not an Artifacts error. */\nexport function artifactsErrorCode(thrown: unknown): string | null {\n if (typeof thrown !== 'object' || thrown === null) return null;\n const parsed = ArtifactsBindingError.safeParse({\n code: Reflect.get(thrown, 'code'),\n message: Reflect.get(thrown, 'message'),\n });\n return parsed.success ? parsed.data.code : null;\n}\n\n/** The REST API's numeric code for \"already exists\", which the binding's ArtifactsError carries. */\nconst ALREADY_EXISTS_NUMERIC = 10201;\n\nconst escapeRegExp = (text: string): string => text.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n\n/**\n * Whether a failure of `create(repo)` says the repository already exists. The binding documents\n * code ALREADY_EXISTS (numeric 10201), and the local simulator sends it; the live binding was seen\n * to throw an error whose code did not survive, with only the message \"repo already exists:\n * <name>\". So the code, then the numeric code, then exactly that message naming this repository\n * (optionally after an \"ArtifactsError: \" prefix) are accepted.\n */\nexport function isAlreadyExists(thrown: unknown, repo: string): boolean {\n if (artifactsErrorCode(thrown) === 'ALREADY_EXISTS') return true;\n if (typeof thrown !== 'object' || thrown === null) return false;\n if (Reflect.get(thrown, 'numericCode') === ALREADY_EXISTS_NUMERIC) return true;\n const message: unknown = Reflect.get(thrown, 'message');\n return (\n typeof message === 'string' &&\n new RegExp(String.raw`^(?:ArtifactsError: )?repo already exists: ${escapeRegExp(repo)}$`, 'i').test(\n message.trim(),\n )\n );\n}\n\n/** The REST API's numeric code for \"not found\", which the binding's ArtifactsError carries. */\nconst NOT_FOUND_NUMERIC = 10200;\n\n/**\n * Whether a failure of a binding call on `repo` says the repository does not exist. The binding\n * documents code NOT_FOUND (numeric 10200), and the local simulator sends it; the live binding was\n * seen to throw an error whose code did not survive, with only the message \"Repository not found:\n * <name>.\" So the code, then the numeric code, then exactly that message naming this repository\n * (optionally after an \"ArtifactsError: \" prefix, with or without the closing period) are\n * accepted.\n */\nexport function isRepoNotFound(thrown: unknown, repo: string): boolean {\n if (artifactsErrorCode(thrown) === 'NOT_FOUND') return true;\n if (typeof thrown !== 'object' || thrown === null) return false;\n if (Reflect.get(thrown, 'numericCode') === NOT_FOUND_NUMERIC) return true;\n const message: unknown = Reflect.get(thrown, 'message');\n return (\n typeof message === 'string' &&\n new RegExp(String.raw`^(?:ArtifactsError: )?repository not found: ${escapeRegExp(repo)}\\.?$`, 'i').test(\n message.trim(),\n )\n );\n}\n\n/**\n * Whether a failure of a binding read of object `sha` says only that the id names an object of\n * another kind (a blob read as a tree, a tree read as a commit). The binding documents\n * INTERNAL_ERROR for that case without saying which, so the message is what tells it apart from a\n * real failure. The live binding was seen to throw \"Invalid object requested. SHA must identify a\n * commit or a tree. <sha> is a blob.\" (optionally after an \"ArtifactsError: \" prefix) and the local\n * simulator \"Git object <sha> is a blob, not a tree\". So a message naming this id as \"<sha> is a\n * <kind>\", or one saying \"Invalid object requested\" with \"must identify a\", is accepted; anything\n * else is not, so an outage is never mistaken for a missing object.\n */\nexport function isWrongKind(thrown: unknown, sha: string): boolean {\n if (typeof thrown !== 'object' || thrown === null) return false;\n const message: unknown = Reflect.get(thrown, 'message');\n if (typeof message !== 'string') return false;\n if (new RegExp(String.raw`\\b${escapeRegExp(sha)} is an? (?:commit|tree|blob|tag)\\b`, 'i').test(message))\n return true;\n return /\\binvalid object requested\\b/i.test(message) && /\\bmust identify an? /i.test(message);\n}\n\n/**\n * Translates a failure of a binding call on repository `repo` into a GatewayError: NOT_FOUND is\n * repo_not_found (also when only the numeric code or the message says so, see\n * {@link isRepoNotFound}), ALREADY_EXISTS is repo_exists (for createRepo also when only the numeric code or\n * the message says so, see {@link isAlreadyExists}), everything else (in-progress states,\n * MEMORY_LIMIT, INTERNAL_ERROR, unparsable results) is storage_unavailable. GatewayErrors pass\n * through unchanged.\n */\nexport function toGatewayError(repo: string, what: string, thrown: unknown): Error {\n if (isGatewayError(thrown) && thrown instanceof Error) return thrown;\n const code = artifactsErrorCode(thrown);\n if (isRepoNotFound(thrown, repo)) return repoNotFound(repo);\n if (code === 'ALREADY_EXISTS' || (what === 'createRepo' && isAlreadyExists(thrown, repo)))\n return repoExists(repo);\n return storageUnavailable(`Artifacts ${what}`, thrown);\n}\n"],"mappings":";;;;;AAWA,SAAgB,mBAAmB,QAAgC;CACjE,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO;CAC1D,MAAM,SAAS,sBAAsB,UAAU;EAC7C,MAAM,QAAQ,IAAI,QAAQ,MAAM;EAChC,SAAS,QAAQ,IAAI,QAAQ,SAAS;CACxC,CAAC;CACD,OAAO,OAAO,UAAU,OAAO,KAAK,OAAO;AAC7C;;AAGA,MAAM,yBAAyB;AAE/B,MAAM,gBAAgB,SAAyB,KAAK,WAAW,uBAAuB,OAAO,GAAG,KAAK;;;;;;;;AASrG,SAAgB,gBAAgB,QAAiB,MAAuB;CACtE,IAAI,mBAAmB,MAAM,MAAM,kBAAkB,OAAO;CAC5D,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO;CAC1D,IAAI,QAAQ,IAAI,QAAQ,aAAa,MAAM,wBAAwB,OAAO;CAC1E,MAAM,UAAmB,QAAQ,IAAI,QAAQ,SAAS;CACtD,OACE,OAAO,YAAY,YACnB,IAAI,OAAO,OAAO,GAAG,8CAA8C,aAAa,IAAI,EAAE,IAAI,GAAG,CAAC,CAAC,KAC7F,QAAQ,KAAK,CACf;AAEJ;;AAGA,MAAM,oBAAoB;;;;;;;;;AAU1B,SAAgB,eAAe,QAAiB,MAAuB;CACrE,IAAI,mBAAmB,MAAM,MAAM,aAAa,OAAO;CACvD,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO;CAC1D,IAAI,QAAQ,IAAI,QAAQ,aAAa,MAAM,mBAAmB,OAAO;CACrE,MAAM,UAAmB,QAAQ,IAAI,QAAQ,SAAS;CACtD,OACE,OAAO,YAAY,YACnB,IAAI,OAAO,OAAO,GAAG,+CAA+C,aAAa,IAAI,EAAE,OAAO,GAAG,CAAC,CAAC,KACjG,QAAQ,KAAK,CACf;AAEJ;;;;;;;;;;;AAYA,SAAgB,YAAY,QAAiB,KAAsB;CACjE,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO;CAC1D,MAAM,UAAmB,QAAQ,IAAI,QAAQ,SAAS;CACtD,IAAI,OAAO,YAAY,UAAU,OAAO;CACxC,IAAI,IAAI,OAAO,OAAO,GAAG,KAAK,aAAa,GAAG,EAAE,qCAAqC,GAAG,CAAC,CAAC,KAAK,OAAO,GACpG,OAAO;CACT,OAAO,gCAAgC,KAAK,OAAO,KAAK,wBAAwB,KAAK,OAAO;AAC9F;;;;;;;;;AAUA,SAAgB,eAAe,MAAc,MAAc,QAAwB;CACjF,IAAI,eAAe,MAAM,KAAK,kBAAkB,OAAO,OAAO;CAC9D,MAAM,OAAO,mBAAmB,MAAM;CACtC,IAAI,eAAe,QAAQ,IAAI,GAAG,OAAO,aAAa,IAAI;CAC1D,IAAI,SAAS,oBAAqB,SAAS,gBAAgB,gBAAgB,QAAQ,IAAI,GACrF,OAAO,WAAW,IAAI;CACxB,OAAO,mBAAmB,aAAa,QAAQ,MAAM;AACvD"}
|
|
@@ -17,8 +17,8 @@ export declare function readBlobOverGit(remote: GitRemote, sha: string): Promise
|
|
|
17
17
|
/**
|
|
18
18
|
* The id of the blob at `path` in `revision` (a commit id or a short branch name), found through
|
|
19
19
|
* the binding's own commit and tree reads, which carry plain data even where Blobs cannot travel.
|
|
20
|
-
* Null when the revision, a directory on the way or the file does not exist,
|
|
21
|
-
* directory or submodule.
|
|
20
|
+
* Null when the revision, a directory on the way or the file does not exist, the revision names a
|
|
21
|
+
* tree or a blob, or the path names a directory or submodule.
|
|
22
22
|
*/
|
|
23
23
|
export declare function blobIdAt(handle: ArtifactsRepoHandle, revision: string, path: string): Promise<string | null>;
|
|
24
24
|
//# sourceMappingURL=artifacts-git-reads.d.ts.map
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isWrongKind } from "./artifacts-errors.js";
|
|
1
2
|
import { ArtifactsCommit, ArtifactsTreeEntry } from "./schemas/artifacts-binding-results.js";
|
|
2
3
|
import { z } from "zod";
|
|
3
4
|
import { isCoreError } from "@leed-ai/git-gateway-core/core-error";
|
|
@@ -34,8 +35,8 @@ async function readBlobOverGit(remote, sha) {
|
|
|
34
35
|
/**
|
|
35
36
|
* The id of the blob at `path` in `revision` (a commit id or a short branch name), found through
|
|
36
37
|
* the binding's own commit and tree reads, which carry plain data even where Blobs cannot travel.
|
|
37
|
-
* Null when the revision, a directory on the way or the file does not exist,
|
|
38
|
-
* directory or submodule.
|
|
38
|
+
* Null when the revision, a directory on the way or the file does not exist, the revision names a
|
|
39
|
+
* tree or a blob, or the path names a directory or submodule.
|
|
39
40
|
*/
|
|
40
41
|
async function blobIdAt(handle, revision, path) {
|
|
41
42
|
let commitId = revision;
|
|
@@ -47,7 +48,11 @@ async function blobIdAt(handle, revision, path) {
|
|
|
47
48
|
commitId = head?.hash ?? null;
|
|
48
49
|
}
|
|
49
50
|
if (commitId === null) return null;
|
|
50
|
-
const
|
|
51
|
+
const found = commitId;
|
|
52
|
+
const commit = await handle.readCommit(found).catch((error) => {
|
|
53
|
+
if (isWrongKind(error, found)) return null;
|
|
54
|
+
throw error;
|
|
55
|
+
});
|
|
51
56
|
if (commit === null) return null;
|
|
52
57
|
let tree = ArtifactsCommit.parse(commit).treeHash;
|
|
53
58
|
const segments = path.split("/");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"artifacts-git-reads.js","names":[],"sources":["../src/artifacts-git-reads.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport type { GitRemote } from '@leed-ai/git-gateway-contract/storage/git-remote';\nimport { isCoreError } from '@leed-ai/git-gateway-core/core-error';\nimport { GitHttpClient } from '@leed-ai/git-gateway-core/smart-http/git-http-client';\nimport { z } from 'zod';\n\nimport type { ArtifactsRepoHandle } from './artifacts-binding.ts';\nimport { ArtifactsCommit, ArtifactsTreeEntry } from './schemas/artifacts-binding-results.ts';\n\nconst SHA = /^[0-9a-f]{40}$/;\n\n/**\n * Whether a binding call failed only because its result, a Blob, could not be carried back. That\n * is what wrangler's remote Artifacts binding (`\"remote\": true` under `wrangler dev`) does for\n * readBlob and readFile: its proxy cannot serialize a Blob (\"Cannot serialize value: [object\n * Blob]\"). The native binding in production returns the Blob and never takes this path.\n */\nexport function isUnserializableBlob(thrown: unknown): boolean {\n if (typeof thrown !== 'object' || thrown === null) return false;\n const message: unknown = Reflect.get(thrown, 'message');\n return typeof message === 'string' && message.includes('Cannot serialize value: [object Blob]');\n}\n\n/**\n * A blob's bytes read over the repository's git remote instead of the binding: one upload-pack\n * request wanting just that id (a blob reaches nothing, so the pack holds that object alone),\n * read with the core pack reader. Null when the server does not have the id (refused\n * in-protocol, \"not our ref\") or it is not a blob. HTTP failures propagate.\n */\nexport async function readBlobOverGit(remote: GitRemote, sha: string): Promise<Uint8Array | null> {\n try {\n const { objects } = await new GitHttpClient(remote).fetchPack({ wants: [sha] });\n const object = objects.find((candidate) => candidate.sha === sha);\n return object?.type === 'blob' ? object.data : null;\n } catch (error) {\n if (isCoreError(error, 'remote_error')) return null;\n throw error;\n }\n}\n\n/**\n * The id of the blob at `path` in `revision` (a commit id or a short branch name), found through\n * the binding's own commit and tree reads, which carry plain data even where Blobs cannot travel.\n * Null when the revision, a directory on the way or the file does not exist,
|
|
1
|
+
{"version":3,"file":"artifacts-git-reads.js","names":[],"sources":["../src/artifacts-git-reads.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport type { GitRemote } from '@leed-ai/git-gateway-contract/storage/git-remote';\nimport { isCoreError } from '@leed-ai/git-gateway-core/core-error';\nimport { GitHttpClient } from '@leed-ai/git-gateway-core/smart-http/git-http-client';\nimport { z } from 'zod';\n\nimport type { ArtifactsRepoHandle } from './artifacts-binding.ts';\nimport { isWrongKind } from './artifacts-errors.ts';\nimport { ArtifactsCommit, ArtifactsTreeEntry } from './schemas/artifacts-binding-results.ts';\n\nconst SHA = /^[0-9a-f]{40}$/;\n\n/**\n * Whether a binding call failed only because its result, a Blob, could not be carried back. That\n * is what wrangler's remote Artifacts binding (`\"remote\": true` under `wrangler dev`) does for\n * readBlob and readFile: its proxy cannot serialize a Blob (\"Cannot serialize value: [object\n * Blob]\"). The native binding in production returns the Blob and never takes this path.\n */\nexport function isUnserializableBlob(thrown: unknown): boolean {\n if (typeof thrown !== 'object' || thrown === null) return false;\n const message: unknown = Reflect.get(thrown, 'message');\n return typeof message === 'string' && message.includes('Cannot serialize value: [object Blob]');\n}\n\n/**\n * A blob's bytes read over the repository's git remote instead of the binding: one upload-pack\n * request wanting just that id (a blob reaches nothing, so the pack holds that object alone),\n * read with the core pack reader. Null when the server does not have the id (refused\n * in-protocol, \"not our ref\") or it is not a blob. HTTP failures propagate.\n */\nexport async function readBlobOverGit(remote: GitRemote, sha: string): Promise<Uint8Array | null> {\n try {\n const { objects } = await new GitHttpClient(remote).fetchPack({ wants: [sha] });\n const object = objects.find((candidate) => candidate.sha === sha);\n return object?.type === 'blob' ? object.data : null;\n } catch (error) {\n if (isCoreError(error, 'remote_error')) return null;\n throw error;\n }\n}\n\n/**\n * The id of the blob at `path` in `revision` (a commit id or a short branch name), found through\n * the binding's own commit and tree reads, which carry plain data even where Blobs cannot travel.\n * Null when the revision, a directory on the way or the file does not exist, the revision names a\n * tree or a blob, or the path names a directory or submodule.\n */\nexport async function blobIdAt(\n handle: ArtifactsRepoHandle,\n revision: string,\n path: string,\n): Promise<string | null> {\n let commitId: string | null = revision;\n if (!SHA.test(revision)) {\n const [head] = z.array(ArtifactsCommit).parse(await handle.log({ ref: revision, limit: 1 }));\n commitId = head?.hash ?? null;\n }\n if (commitId === null) return null;\n const found = commitId;\n const commit = await handle.readCommit(found).catch((error: unknown) => {\n // A revision naming a tree or a blob is a revision that does not exist.\n if (isWrongKind(error, found)) return null;\n throw error;\n });\n if (commit === null) return null;\n let tree = ArtifactsCommit.parse(commit).treeHash;\n const segments = path.split('/');\n for (const [index, segment] of segments.entries()) {\n const listed = await handle.readTree(tree);\n if (listed === null) return null;\n const entry = z\n .array(ArtifactsTreeEntry)\n .parse(listed)\n .find((candidate) => candidate.name === segment);\n if (entry === undefined) return null;\n const last = index === segments.length - 1;\n if (last) return entry.type === 'tree' || entry.type === 'gitlink' ? null : entry.hash;\n if (entry.type !== 'tree') return null;\n tree = entry.hash;\n }\n return null;\n}\n"],"mappings":";;;;;;AAUA,MAAM,MAAM;;;;;;;AAQZ,SAAgB,qBAAqB,QAA0B;CAC7D,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO;CAC1D,MAAM,UAAmB,QAAQ,IAAI,QAAQ,SAAS;CACtD,OAAO,OAAO,YAAY,YAAY,QAAQ,SAAS,uCAAuC;AAChG;;;;;;;AAQA,eAAsB,gBAAgB,QAAmB,KAAyC;CAChG,IAAI;EACF,MAAM,EAAE,YAAY,MAAM,IAAI,cAAc,MAAM,CAAC,CAAC,UAAU,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC;EAC9E,MAAM,SAAS,QAAQ,MAAM,cAAc,UAAU,QAAQ,GAAG;EAChE,OAAO,QAAQ,SAAS,SAAS,OAAO,OAAO;CACjD,SAAS,OAAO;EACd,IAAI,YAAY,OAAO,cAAc,GAAG,OAAO;EAC/C,MAAM;CACR;AACF;;;;;;;AAQA,eAAsB,SACpB,QACA,UACA,MACwB;CACxB,IAAI,WAA0B;CAC9B,IAAI,CAAC,IAAI,KAAK,QAAQ,GAAG;EACvB,MAAM,CAAC,QAAQ,EAAE,MAAM,eAAe,CAAC,CAAC,MAAM,MAAM,OAAO,IAAI;GAAE,KAAK;GAAU,OAAO;EAAE,CAAC,CAAC;EAC3F,WAAW,MAAM,QAAQ;CAC3B;CACA,IAAI,aAAa,MAAM,OAAO;CAC9B,MAAM,QAAQ;CACd,MAAM,SAAS,MAAM,OAAO,WAAW,KAAK,CAAC,CAAC,OAAO,UAAmB;EAEtE,IAAI,YAAY,OAAO,KAAK,GAAG,OAAO;EACtC,MAAM;CACR,CAAC;CACD,IAAI,WAAW,MAAM,OAAO;CAC5B,IAAI,OAAO,gBAAgB,MAAM,MAAM,CAAC,CAAC;CACzC,MAAM,WAAW,KAAK,MAAM,GAAG;CAC/B,KAAK,MAAM,CAAC,OAAO,YAAY,SAAS,QAAQ,GAAG;EACjD,MAAM,SAAS,MAAM,OAAO,SAAS,IAAI;EACzC,IAAI,WAAW,MAAM,OAAO;EAC5B,MAAM,QAAQ,EACX,MAAM,kBAAkB,CAAC,CACzB,MAAM,MAAM,CAAC,CACb,MAAM,cAAc,UAAU,SAAS,OAAO;EACjD,IAAI,UAAU,KAAA,GAAW,OAAO;EAEhC,IADa,UAAU,SAAS,SAAS,GAC/B,OAAO,MAAM,SAAS,UAAU,MAAM,SAAS,YAAY,OAAO,MAAM;EAClF,IAAI,MAAM,SAAS,QAAQ,OAAO;EAClC,OAAO,MAAM;CACf;CACA,OAAO;AACT"}
|
package/package.json
CHANGED
package/src/artifacts-backend.ts
CHANGED
|
@@ -19,7 +19,7 @@ import {
|
|
|
19
19
|
type ArtifactsNamespaceBinding,
|
|
20
20
|
type ArtifactsRepoHandle,
|
|
21
21
|
} from './artifacts-binding.ts';
|
|
22
|
-
import { artifactsErrorCode, isRepoNotFound, toGatewayError } from './artifacts-errors.ts';
|
|
22
|
+
import { artifactsErrorCode, isRepoNotFound, isWrongKind, toGatewayError } from './artifacts-errors.ts';
|
|
23
23
|
import { blobIdAt, isUnserializableBlob, readBlobOverGit } from './artifacts-git-reads.ts';
|
|
24
24
|
import { toContractCommit, toStorageTreeEntry } from './artifacts-mapping.ts';
|
|
25
25
|
import {
|
|
@@ -128,10 +128,10 @@ export class ArtifactsBackend implements StorageBackend {
|
|
|
128
128
|
const repo = parseStorageInput(RepoName, name);
|
|
129
129
|
const id = parseStorageInput(Sha, sha);
|
|
130
130
|
return this.#withRepo(repo, 'readCommit', async (handle) => {
|
|
131
|
-
const metadata = await this.#readTyped(
|
|
132
|
-
async () => handle.
|
|
133
|
-
|
|
134
|
-
);
|
|
131
|
+
const metadata = await this.#readTyped(id, async () => handle.readCommit(id), [
|
|
132
|
+
async () => handle.readBlob(id),
|
|
133
|
+
async () => handle.readTree(id),
|
|
134
|
+
]);
|
|
135
135
|
return metadata === null ? null : toContractCommit(parseHost(ArtifactsCommit, metadata));
|
|
136
136
|
});
|
|
137
137
|
}
|
|
@@ -140,10 +140,10 @@ export class ArtifactsBackend implements StorageBackend {
|
|
|
140
140
|
const repo = parseStorageInput(RepoName, name);
|
|
141
141
|
const id = parseStorageInput(Sha, sha);
|
|
142
142
|
return this.#withRepo(repo, 'readTree', async (handle) => {
|
|
143
|
-
const entries = await this.#readTyped(
|
|
144
|
-
async () => handle.
|
|
145
|
-
|
|
146
|
-
);
|
|
143
|
+
const entries = await this.#readTyped(id, async () => handle.readTree(id), [
|
|
144
|
+
async () => handle.readBlob(id),
|
|
145
|
+
async () => handle.readCommit(id),
|
|
146
|
+
]);
|
|
147
147
|
return entries === null ? null : z.array(ArtifactsTreeEntry).parse(entries).map(toStorageTreeEntry);
|
|
148
148
|
});
|
|
149
149
|
}
|
|
@@ -155,6 +155,8 @@ export class ArtifactsBackend implements StorageBackend {
|
|
|
155
155
|
try {
|
|
156
156
|
return await bytesOf(await handle.readBlob(id));
|
|
157
157
|
} catch (error) {
|
|
158
|
+
// The binding documents null for an id that is not a blob; an error saying so is null too.
|
|
159
|
+
if (isWrongKind(error, id)) return null;
|
|
158
160
|
if (!isUnserializableBlob(error)) throw error;
|
|
159
161
|
return readBlobOverGit(await this.gitRemote(repo, 'read'), id);
|
|
160
162
|
}
|
|
@@ -170,6 +172,8 @@ export class ArtifactsBackend implements StorageBackend {
|
|
|
170
172
|
try {
|
|
171
173
|
return await bytesOf(await handle.readFile({ ref: revision, path: file }));
|
|
172
174
|
} catch (error) {
|
|
175
|
+
// A revision naming a tree or a blob is a revision that does not exist.
|
|
176
|
+
if (isWrongKind(error, revision)) return null;
|
|
173
177
|
if (!isUnserializableBlob(error)) throw error;
|
|
174
178
|
const blob = await blobIdAt(handle, revision, file);
|
|
175
179
|
return blob === null ? null : readBlobOverGit(await this.gitRemote(repo, 'read'), blob);
|
|
@@ -223,18 +227,24 @@ export class ArtifactsBackend implements StorageBackend {
|
|
|
223
227
|
}
|
|
224
228
|
|
|
225
229
|
/**
|
|
226
|
-
* Reads
|
|
227
|
-
*
|
|
228
|
-
* from a real failure by the
|
|
230
|
+
* Reads object `id` as one kind. The binding answers null for a missing id but throws when the id
|
|
231
|
+
* names an object of another kind; that case is null too, as the contract requires. It is told
|
|
232
|
+
* apart from a real failure by the message saying so ({@link isWrongKind}: what the live binding
|
|
233
|
+
* and the simulator send), else, for an INTERNAL_ERROR or an error whose code did not survive, by
|
|
234
|
+
* the object being readable as one of the other kinds (`probes`). Anything else, or a probe that
|
|
235
|
+
* finds nothing, rethrows the original failure.
|
|
229
236
|
*/
|
|
230
237
|
async #readTyped(
|
|
238
|
+
id: string,
|
|
231
239
|
read: () => Promise<unknown>,
|
|
232
240
|
probes: readonly (() => Promise<unknown>)[],
|
|
233
241
|
): Promise<unknown> {
|
|
234
242
|
try {
|
|
235
243
|
return await read();
|
|
236
244
|
} catch (error) {
|
|
237
|
-
if (
|
|
245
|
+
if (isWrongKind(error, id)) return null;
|
|
246
|
+
const code = artifactsErrorCode(error);
|
|
247
|
+
if (code !== null && code !== 'INTERNAL_ERROR') throw error;
|
|
238
248
|
for (const probe of probes) {
|
|
239
249
|
// A Blob that could not be carried back (wrangler's remote binding) was still found.
|
|
240
250
|
const found = await probe().catch((probeError: unknown) =>
|
package/src/artifacts-errors.ts
CHANGED
|
@@ -67,6 +67,25 @@ export function isRepoNotFound(thrown: unknown, repo: string): boolean {
|
|
|
67
67
|
);
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
+
/**
|
|
71
|
+
* Whether a failure of a binding read of object `sha` says only that the id names an object of
|
|
72
|
+
* another kind (a blob read as a tree, a tree read as a commit). The binding documents
|
|
73
|
+
* INTERNAL_ERROR for that case without saying which, so the message is what tells it apart from a
|
|
74
|
+
* real failure. The live binding was seen to throw "Invalid object requested. SHA must identify a
|
|
75
|
+
* commit or a tree. <sha> is a blob." (optionally after an "ArtifactsError: " prefix) and the local
|
|
76
|
+
* simulator "Git object <sha> is a blob, not a tree". So a message naming this id as "<sha> is a
|
|
77
|
+
* <kind>", or one saying "Invalid object requested" with "must identify a", is accepted; anything
|
|
78
|
+
* else is not, so an outage is never mistaken for a missing object.
|
|
79
|
+
*/
|
|
80
|
+
export function isWrongKind(thrown: unknown, sha: string): boolean {
|
|
81
|
+
if (typeof thrown !== 'object' || thrown === null) return false;
|
|
82
|
+
const message: unknown = Reflect.get(thrown, 'message');
|
|
83
|
+
if (typeof message !== 'string') return false;
|
|
84
|
+
if (new RegExp(String.raw`\b${escapeRegExp(sha)} is an? (?:commit|tree|blob|tag)\b`, 'i').test(message))
|
|
85
|
+
return true;
|
|
86
|
+
return /\binvalid object requested\b/i.test(message) && /\bmust identify an? /i.test(message);
|
|
87
|
+
}
|
|
88
|
+
|
|
70
89
|
/**
|
|
71
90
|
* Translates a failure of a binding call on repository `repo` into a GatewayError: NOT_FOUND is
|
|
72
91
|
* repo_not_found (also when only the numeric code or the message says so, see
|
|
@@ -5,6 +5,7 @@ import { GitHttpClient } from '@leed-ai/git-gateway-core/smart-http/git-http-cli
|
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
|
|
7
7
|
import type { ArtifactsRepoHandle } from './artifacts-binding.ts';
|
|
8
|
+
import { isWrongKind } from './artifacts-errors.ts';
|
|
8
9
|
import { ArtifactsCommit, ArtifactsTreeEntry } from './schemas/artifacts-binding-results.ts';
|
|
9
10
|
|
|
10
11
|
const SHA = /^[0-9a-f]{40}$/;
|
|
@@ -41,8 +42,8 @@ export async function readBlobOverGit(remote: GitRemote, sha: string): Promise<U
|
|
|
41
42
|
/**
|
|
42
43
|
* The id of the blob at `path` in `revision` (a commit id or a short branch name), found through
|
|
43
44
|
* the binding's own commit and tree reads, which carry plain data even where Blobs cannot travel.
|
|
44
|
-
* Null when the revision, a directory on the way or the file does not exist,
|
|
45
|
-
* directory or submodule.
|
|
45
|
+
* Null when the revision, a directory on the way or the file does not exist, the revision names a
|
|
46
|
+
* tree or a blob, or the path names a directory or submodule.
|
|
46
47
|
*/
|
|
47
48
|
export async function blobIdAt(
|
|
48
49
|
handle: ArtifactsRepoHandle,
|
|
@@ -55,7 +56,12 @@ export async function blobIdAt(
|
|
|
55
56
|
commitId = head?.hash ?? null;
|
|
56
57
|
}
|
|
57
58
|
if (commitId === null) return null;
|
|
58
|
-
const
|
|
59
|
+
const found = commitId;
|
|
60
|
+
const commit = await handle.readCommit(found).catch((error: unknown) => {
|
|
61
|
+
// A revision naming a tree or a blob is a revision that does not exist.
|
|
62
|
+
if (isWrongKind(error, found)) return null;
|
|
63
|
+
throw error;
|
|
64
|
+
});
|
|
59
65
|
if (commit === null) return null;
|
|
60
66
|
let tree = ArtifactsCommit.parse(commit).treeHash;
|
|
61
67
|
const segments = path.split('/');
|