Something went wrong. Try again.
Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import { BadRequestException, Inject, Injectable, NotFoundException } from '@nestjs/common';import { BLOB_OWNERS, BLOB_STORE, type BlobOwners, type BlobRow, type BlobStore,} from '../domain/ports';
const HASH = /^[0-9a-f]{64}$/;
@Injectable()export class BlobsService { constructor( @Inject(BLOB_STORE) private readonly cas: BlobStore, @Inject(BLOB_OWNERS) private readonly owners: BlobOwners, ) {}
// Owner-scoped: a caller only resolves a blob it holds. An unknown hash and // a hash owned by someone else both look like 404, so the store is not an // existence oracle across users. async resolve(hash: string, ownerId: string | null): Promise<{ row: BlobRow; filepath: string }> { assertHash(hash); const row = this.cas.find(hash); if (!row || !(await this.owners.has(hash, ownerId))) { throw new NotFoundException('Blob not found'); } return { row, filepath: this.cas.casPath(hash) }; }
diff(hashes: string[]): string[] { for (const h of hashes) assertHash(h); return this.cas.missing(hashes); }
// The hash in the URL is a claim; the bytes prove it. async store( hash: string, bytes: Buffer, mime: string | null, ownerId: string | null, ): Promise<void> { assertHash(hash); if (!bytes.length) throw new BadRequestException('Empty blob'); if (this.cas.hashBytes(bytes) !== hash) throw new BadRequestException('Hash mismatch'); this.cas.storeBytes(bytes); this.cas.record(hash, mime, bytes.length, ownerId); await this.owners.add(hash, ownerId); }
// Record that `ownerId` holds an already-stored blob (used by the document // pipeline, which writes bytes through the CAS directly). async claim(hash: string, ownerId: string | null): Promise<void> { await this.owners.add(hash, ownerId); }
// Drop this owner's claim on each hash; delete the bytes once no owner // remains. Safe to call with hashes that were never owned. async release(hashes: (string | null | undefined)[], ownerId: string | null): Promise<void> { for (const hash of hashes) { if (!hash || !HASH.test(hash)) continue; if (await this.owners.release(hash, ownerId)) this.cas.remove(hash); } }}
function assertHash(hash: string): void { if (!HASH.test(hash)) throw new BadRequestException('Invalid blob hash');}