import { test } from 'node:test' import assert from 'node:assert/strict' import { DatabaseSync } from 'node:sqlite' import { uploadVideoBounded, inspectVideoJob, type VideoApi, type VideoJob, } from '../src/video-upload-engine.ts' import { videoStore } from '../src/video-upload-store.ts' const p = { uploadKey: 'test-job', sourceId: 'original-source', sourceUrl: 'https://source.test/file?private=DO_NOT_STORE', confirm: true, } function fixture() { const db = new DatabaseSync(':memory:') const store = videoStore({ sql: async (q, b = []) => ({ rows: db.prepare(q).all(...(b as any[])) }), }) const bytes = new Uint8Array(11).map((_, i) => i) let registered = 0, parts = 0, finished = 0, etag = '"v1"', owner = 'urn:li:person:fixture', state = 'AVAILABLE' const api: VideoApi = { store, sourceFetch: async (_u, init) => { if (init?.method === 'HEAD') return new Response(null, { headers: { etag, 'content-length': '11' } }) const range = new Headers(init?.headers).get('range')! const m = /bytes=(\d+)-(\d+)/.exec(range)! const a = +m[1], b = +m[2] return new Response(bytes.slice(a, b + 1), { status: 206, headers: { etag, 'content-range': `bytes ${a}-${b}/11` }, }) }, owner: async () => owner, register: async () => { registered++ return { value: { video: 'urn:li:video:fixture', uploadToken: 'DO_NOT_STORE_TOKEN', uploadInstructions: [ { firstByte: 0, lastByte: 5, uploadUrl: 'https://www.linkedin.com/upload?private=DO_NOT_STORE', }, { firstByte: 6, lastByte: 10, uploadUrl: 'https://www.linkedin.com/upload?private=DO_NOT_STORE', }, ], }, } }, part: async (_u, b) => { parts++ return 'etag-' + parts }, finalize: async () => { finished++ }, status: async () => state, } return { api, db, counts: () => ({ registered, parts, finished }), setEtag: (e) => (etag = e), setOwner: (o) => (owner = o), setState: (s) => (state = s), } } test('bounded parts checkpoint acknowledgements; repeated call never uploads/posts again', async () => { const f = fixture() try { assert.equal((await uploadVideoBounded(p, f.api)).state, 'available') assert.equal((await uploadVideoBounded(p, f.api)).state, 'available') assert.deepEqual(f.counts(), { registered: 1, parts: 2, finished: 1 }) const persisted = JSON.stringify(f.db.prepare('select * from linkedin_upload_jobs_v1').all()) assert(!persisted.includes('DO_NOT_STORE')) assert(!persisted.includes('https://')) assert.equal((await f.api.store.get(p.uploadKey))?.ackOffset, 11) } finally { f.db.close() } }) test('lost final response resumes through status only', async () => { const f = fixture() f.api.finalize = async () => { throw new Error('private URL must not escape') } try { await assert.rejects( uploadVideoBounded(p, f.api), (e) => !String(e).includes('private URL') && /checkpoint preserved/.test(String(e)), ) assert.equal((await uploadVideoBounded(p, f.api)).state, 'available') assert.equal(f.counts().registered, 1) } finally { f.db.close() } }) test('unknown registration result never creates a second session', async () => { const f = fixture() let calls = 0 f.api.register = async () => { calls++ throw new Error('lost') } try { await assert.rejects(uploadVideoBounded(p, f.api)) assert.equal((await uploadVideoBounded(p, f.api)).state, 'needs_reconciliation') assert.equal(calls, 1) } finally { f.db.close() } }) test('changed source/account/sourceId fail before more writes', async () => { for (const mode of ['etag', 'owner', 'sourceId', 'sourceUrl']) { const f = fixture() try { await uploadVideoBounded(p, f.api) if (mode === 'etag') f.setEtag('"v2"') if (mode === 'owner') f.setOwner('urn:li:person:other') await assert.rejects( uploadVideoBounded( { ...p, ...(mode === 'sourceId' ? { sourceId: 'other' } : {}), ...(mode === 'sourceUrl' ? { sourceUrl: 'https://other.test/video' } : {}), }, f.api, ), /changed/, ) assert.equal(f.counts().registered, 1) } finally { f.db.close() } } }) test('missing validator, partial ranges, oversized provider part and 429 never trigger retries', async () => { for (const mode of ['validator', 'partial', 'oversize', '429']) { const f = fixture() try { if (mode === 'validator') f.setEtag('W/"weak"') if (mode === 'partial') { const original = f.api.sourceFetch f.api.sourceFetch = async (u, i) => i?.method === 'HEAD' ? original(u, i) : new Response('x', { status: 206, headers: { etag: '"v1"', 'content-range': 'bytes 0-5/11' }, }) } if (mode === 'oversize') f.api.register = async () => ({ video: 'urn:li:video:fixture', uploadInstructions: [{ firstByte: 0, lastByte: 9 * 1024 * 1024, uploadUrl: 'sensitive' }], }) if (mode === '429') { f.api.part = async () => { throw Object.assign(new Error('rate limited'), { status: 429 }) } } await assert.rejects(uploadVideoBounded(p, f.api)) assert(f.counts().registered <= 1) assert.equal(f.counts().finished, 0) } finally { f.db.close() } } }) test('SQL checkpoint creation and CAS exclude conflicting writers', async () => { const f = fixture() try { const j: VideoJob = { key: 'other', identity: 'i', owner: 'o', size: 1, phase: 'starting', version: 0, partIds: [], ackOffset: 0, } assert(await f.api.store.insert(j)) assert(!(await f.api.store.insert(j))) assert(await f.api.store.save(j, 0)) assert.equal(await f.api.store.save(j, 0), null) } finally { f.db.close() } }) test('manual 308 sources are disposed before registration; AbortError and 401 never retry mutations', async () => { const f = fixture() let cancelled = false f.api.sourceFetch = async () => new Response( new ReadableStream({ cancel() { cancelled = true }, }), { status: 308, headers: { location: 'https://untrusted.test' } }, ) try { await assert.rejects(uploadVideoBounded(p, f.api)) assert(cancelled) assert.equal(f.counts().registered, 0) } finally { f.db.close() } for (const code of ['AbortError', '401']) { const g = fixture() g.setState('WAITING_UPLOAD') let n = 0 g.api.part = async () => { n++ throw Object.assign(new Error('stopped'), { name: code, status: 401 }) } try { await assert.rejects(uploadVideoBounded(p, g.api)) assert.equal(n, 1) assert.equal((await uploadVideoBounded(p, g.api)).state, 'needs_reconciliation') assert.equal(n, 1) } finally { g.db.close() } } })