Spaces:
Sleeping
Sleeping
Commit ·
d594446
1
Parent(s): 9eafa48
fix(storage): skip integration suite safely, tighten list contract, drop expand
Browse filesFiles changed (8)
- src/lib/server/storage/hf-bucket-store.ts+13-18
- src/lib/server/storage/local-fs-store.ts+2-1
- src/lib/server/storage/prefixed-store.ts+2-1
- src/lib/server/storage/store.ts+9-3
- tests/integration/env.ts+3-1
- tests/integration/hf-bucket-store.test.ts+7-1
- tests/unit/storage/local-fs-store.test.ts+2-3
- tests/unit/storage/prefixed-store.test.ts+4
12345678929 unmodified lines39404142434413 unmodified lines585960616263642 unmodified lines6768697071727374757677787980818283848586import { commit, copyFile, deleteFiles, downloadFile, listFiles, uploadFiles } from '@huggingface/hub';import { assertValidPath, type BucketStore, type StoreEntry } from './store';function statusOf(e: unknown): number | undefined {return typeof e === 'object' && e !== null ? (e as { statusCode?: number }).statusCode : undefined;}function toBlob(bytes: Uint8Array, type?: string): Blob {return new Blob([bytes as unknown as BlobPart], type ? { type } : undefined);29 unmodified lines});}async append(path: string, bytes: Uint8Array): Promise<void> {assertValidPath(path);const original = await downloadFile({ ...this.auth, path });13 unmodified lines});} catch (e) {console.warn(`[hf-bucket-store] edit-append failed for ${path}; falling back to full rewrite`, e);const existing = new Uint8Array(await original.arrayBuffer());const joined = new Uint8Array(existing.length + bytes.length);joined.set(existing, 0);joined.set(bytes, existing.length);2 unmodified lines}async list(prefix: string): Promise<StoreEntry[]> {const dir = prefix.replace(/\/+$/, '');const out: StoreEntry[] = [];try {for await (const entry of listFiles({ ...this.auth, path: dir || undefined, recursive: true, expand: true })) {if (entry.type !== 'file' || !entry.path.startsWith(prefix)) continue;out.push({path: entry.path,size: entry.size,uploadedAt: entry.uploadedAt ? new Date(entry.uploadedAt) : undefined});}} catch (e) {if (statusOf(e) === 404) return [];throw e;}return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));}1234529 unmodified lines353637383940414243444513 unmodified lines5960616263646566672 unmodified lines707172737475767778798081import { commit, copyFile, deleteFiles, downloadFile, listFiles, uploadFiles } from '@huggingface/hub';import { assertValidPath, assertValidPrefix, type BucketStore, type StoreEntry } from './store';function toBlob(bytes: Uint8Array, type?: string): Blob {return new Blob([bytes as unknown as BlobPart], type ? { type } : undefined);29 unmodified lines});}/*** The `edit` commit is not a compare-and-swap: a concurrent writer committing between* the download below and the commit would be overwritten. The writer guard keeps this* window small but does not eliminate it — this backend assumes a single writer.*/async append(path: string, bytes: Uint8Array): Promise<void> {assertValidPath(path);const original = await downloadFile({ ...this.auth, path });13 unmodified lines});} catch (e) {console.warn(`[hf-bucket-store] edit-append failed for ${path}; falling back to full rewrite`, e);const latest = await downloadFile({ ...this.auth, path });if (!latest) return this.put(path, bytes, 'application/x-ndjson');const existing = new Uint8Array(await latest.arrayBuffer());const joined = new Uint8Array(existing.length + bytes.length);joined.set(existing, 0);joined.set(bytes, existing.length);2 unmodified lines}async list(prefix: string): Promise<StoreEntry[]> {assertValidPrefix(prefix);const dir = prefix.replace(/\/+$/, '');const out: StoreEntry[] = [];for await (const entry of listFiles({ ...this.auth, path: dir || undefined, recursive: true })) {if (entry.type !== 'file' || !entry.path.startsWith(prefix)) continue;out.push({ path: entry.path, size: entry.size });}return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));}
123456737 unmodified lines454647484950import { randomUUID } from 'node:crypto';import { appendFile, copyFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';import { dirname, join, relative, sep } from 'node:path';import { assertValidPath, type BucketStore, type StoreEntry } from './store';function hasCode(e: unknown, ...codes: string[]): boolean {return typeof e === 'object' && e !== null && codes.includes((e as { code?: string }).code ?? '');37 unmodified lines}async list(prefix: string): Promise<StoreEntry[]> {const out: StoreEntry[] = [];const walk = async (dir: string): Promise<void> => {let entries;123456737 unmodified lines45464748495051import { randomUUID } from 'node:crypto';import { appendFile, copyFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';import { dirname, join, relative, sep } from 'node:path';import { assertValidPath, assertValidPrefix, type BucketStore, type StoreEntry } from './store';function hasCode(e: unknown, ...codes: string[]): boolean {return typeof e === 'object' && e !== null && codes.includes((e as { code?: string }).code ?? '');37 unmodified lines}async list(prefix: string): Promise<StoreEntry[]> {assertValidPrefix(prefix);const out: StoreEntry[] = [];const walk = async (dir: string): Promise<void> => {let entries;
123426 unmodified lines313233343536import { assertValidPath, type BucketStore, type StoreEntry } from './store';/*** Confines another store to `<prefix>/`, so several apps (or test runs) can share one26 unmodified linesreturn this.inner.append(this.full(path), bytes);}async list(prefix: string): Promise<StoreEntry[]> {const entries = await this.inner.list(this.prefix + prefix);return entries.map((e) => ({ ...e, path: e.path.slice(this.prefix.length) }));}123426 unmodified lines31323334353637import { assertValidPath, assertValidPrefix, type BucketStore, type StoreEntry } from './store';/*** Confines another store to `<prefix>/`, so several apps (or test runs) can share one26 unmodified linesreturn this.inner.append(this.full(path), bytes);}async list(prefix: string): Promise<StoreEntry[]> {assertValidPrefix(prefix);const entries = await this.inner.list(this.prefix + prefix);return entries.map((e) => ({ ...e, path: e.path.slice(this.prefix.length) }));}
19 unmodified lines20212223242526272813 unmodified lines424344454619 unmodified lines*/append(path: string, bytes: Uint8Array): Promise<void>;/*** Lists files whose path starts with `prefix`, sorted by path. The prefix is matched* literally against the full path (`'events'` also matches `eventsX/…`); callers* should pass a trailing `/` to match only within a directory.*/list(prefix: string): Promise<StoreEntry[]>;/** Deletes objects; missing ones are ignored. */13 unmodified lines}}export const encodeText = (s: string): Uint8Array => new TextEncoder().encode(s);export const decodeText = (b: Uint8Array): string => new TextDecoder().decode(b);19 unmodified lines202122232425262713 unmodified lines41424344454647484950515219 unmodified lines*/append(path: string, bytes: Uint8Array): Promise<void>;/*** Lists files whose path starts with `prefix`, sorted by path. The prefix must be `''`* (the whole store) or end with `/`, so it always matches within a directory.*/list(prefix: string): Promise<StoreEntry[]>;/** Deletes objects; missing ones are ignored. */13 unmodified lines}}/** Validates a `list` prefix: either `''` or a valid path followed by `/`. */export function assertValidPrefix(prefix: string): void {if (prefix === '') return;if (!prefix.endsWith('/')) throw new Error(`Invalid prefix: ${prefix}`);assertValidPath(prefix.slice(0, -1));}export const encodeText = (s: string): Uint8Array => new TextEncoder().encode(s);export const decodeText = (b: Uint8Array): string => new TextDecoder().decode(b);
9 unmodified lines101112131415169 unmodified lines}for (const line of text.split('\n')) {const m = /^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line);if (m && !(m[1] in process.env)) process.env[m[1]] = m[2].replace(/^["']|["']$/g, '');}}9 unmodified lines1011121314151617189 unmodified lines}for (const line of text.split('\n')) {const m = /^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line);if (!m || m[1] in process.env) continue;const raw = m[2];process.env[m[1]] = /^["']/.test(raw) ? raw.replace(/^["']|["']$/g, '') : raw.split(/\s+#/)[0].trim();}}
9 unmodified lines1011121314151632 unmodified lines4950515253549 unmodified linesdescribe.skipIf(!creds)('HfBucketStore against the real bucket',() => {const store = new PrefixedStore(new HfBucketStore(creds!.bucket, creds!.token), `test/${ulid()}`);afterAll(async () => {await store.wipe();32 unmodified linesexpect(decodeText((await store.get('backups/ledger.jsonl'))!)).toBe('{"n":1}\n{"n":2}\n');});it('deletes, ignoring missing paths', async () => {await store.delete(['a.json', 'never-existed.txt']);expect(await store.get('a.json')).toBeNull();9 unmodified lines10111213141516171832 unmodified lines515253545556575859609 unmodified linesdescribe.skipIf(!creds)('HfBucketStore against the real bucket',() => {const store = creds? new PrefixedStore(new HfBucketStore(creds.bucket, creds.token), `test/${ulid()}`): (undefined as unknown as PrefixedStore);afterAll(async () => {await store.wipe();32 unmodified linesexpect(decodeText((await store.get('backups/ledger.jsonl'))!)).toBe('{"n":1}\n{"n":2}\n');});it('rejects a copy of a missing source', async () => {await expect(store.copy('does-not-exist.txt', 'x.txt')).rejects.toThrow();});it('deletes, ignoring missing paths', async () => {await store.delete(['a.json', 'never-existed.txt']);expect(await store.get('a.json')).toBeNull();
84 unmodified lines8586878889909192939495969784 unmodified linesexpect(entries.some((e) => e.path.endsWith('.tmp'))).toBe(false);});it('distinguishes list("events") from list("events/")', async () => {await store.put('events/a.json', enc('a'));await store.put('eventsX/b.json', enc('b'));const withSlash = await store.list('events/');expect(withSlash.map((e) => e.path)).toEqual(['events/a.json']);const withoutSlash = await store.list('events');expect(withoutSlash.map((e) => e.path)).toEqual(['events/a.json', 'eventsX/b.json']);});it('treats a directory path as missing for get and delete', async () => {84 unmodified lines85868788899091929394959684 unmodified linesexpect(entries.some((e) => e.path.endsWith('.tmp'))).toBe(false);});it('lists only within a directory and rejects a prefix without a trailing slash', async () => {await store.put('events/a.json', enc('a'));await store.put('eventsX/b.json', enc('b'));const withSlash = await store.list('events/');expect(withSlash.map((e) => e.path)).toEqual(['events/a.json']);await expect(store.list('events')).rejects.toThrow(/Invalid prefix/);});it('treats a directory path as missing for get and delete', async () => {
34 unmodified lines35363738394034 unmodified linesexpect((await b.list('events/')).map((e) => e.path)).toEqual(['events/9.json']);});it('appends, copies and deletes inside the prefix', async () => {await a.append('ledger.jsonl', encodeText('x\n'));await a.append('ledger.jsonl', encodeText('y\n'));34 unmodified lines3536373839404142434434 unmodified linesexpect((await b.list('events/')).map((e) => e.path)).toEqual(['events/9.json']);});it('rejects a list prefix without a trailing slash', async () => {await expect(a.list('events')).rejects.toThrow(/Invalid prefix/);});it('appends, copies and deletes inside the prefix', async () => {await a.append('ledger.jsonl', encodeText('x\n'));await a.append('ledger.jsonl', encodeText('y\n'));
src/lib/server/storage/hf-bucket-store.ts+13-18
src/lib/server/storage/local-fs-store.ts+2-1
src/lib/server/storage/prefixed-store.ts+2-1
src/lib/server/storage/store.ts+9-3
tests/integration/env.ts+3-1
tests/integration/hf-bucket-store.test.ts+7-1
tests/unit/storage/local-fs-store.test.ts+2-3
tests/unit/storage/prefixed-store.test.ts+4