Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kody/linkedin

Identity, generic requests, and guarded posting through the saved LinkedIn OAuth integration.

FollowFork

Files

video-upload-engine.ts

222 lines · 6.9 KB · TypeScript
/** Checkpoints deliberately contain no source/presigned URL or upload token. */
export type VideoJob = {
	key: string
	identity: string
	owner: string
	size: number
	phase: string
	version: number
	video?: string
	partIds: string[]
	ackOffset: number
}
export type VideoStore = {
	get(key: string): Promise<VideoJob | null>
	insert(job: VideoJob): Promise<boolean>
	save(job: VideoJob, version: number): Promise<VideoJob | null>
}
export type VideoApi = {
	store: VideoStore
	sourceFetch: typeof fetch
	owner(): Promise<string>
	register(size: number): Promise<any>
	part(url: string, bytes: Uint8Array): Promise<string>
	finalize(video: string, token: string, ids: string[]): Promise<unknown>
	status(video: string): Promise<string>
}
const MAX_PART = 8 * 1024 * 1024
function label(s: string) {
	if (!/^[a-zA-Z0-9._-]{1,100}$/.test(s))
		throw new Error('uploadKey and sourceId must be non-secret opaque labels (letters/digits/._-)')
	return s
}
const hash = async (s: string) =>
	Array.from(
		new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s))),
		(x) => x.toString(16).padStart(2, '0'),
	).join('')
function status(j: VideoJob, state = j.phase) {
	return {
		uploadKey: j.key,
		videoUrn: j.video ?? null,
		state,
		ackOffset: j.ackOffset,
		totalBytes: j.size,
		parts: j.partIds.length,
		next:
			state === 'available'
				? 'Upload complete; posting is a separate explicit action.'
				: state === 'processing'
					? 'Check this same uploadKey again; never re-register.'
					: 'Reconcile this same video. No capability URLs or tokens are persisted; incomplete byte transfer cannot automatically resume after process loss.',
	}
}
export async function inspectVideoJob(key: string, api: VideoApi) {
	const j = await api.store.get(label(key))
	if (!j) throw new Error('Upload job not found')
	if (j.owner !== (await api.owner()))
		throw new Error('Upload account changed; refusing reconciliation')
	if (!j.video) return status(j, 'needs_reconciliation')
	let state: string
	try {
		state = await api.status(j.video)
	} catch {
		return status(j, 'needs_reconciliation')
	}
	return status(
		j,
		state === 'AVAILABLE'
			? 'available'
			: state === 'PROCESSING'
				? 'processing'
				: 'needs_reconciliation',
	)
}
export async function uploadVideoBounded(
	p: {
		uploadKey: string
		sourceId: string
		sourceUrl: string
		confirm?: boolean
		dryRun?: boolean
	},
	api: VideoApi,
) {
	const key = label(p.uploadKey)
	label(p.sourceId)
	if (p.dryRun)
		return {
			dryRun: true,
			uploadKey: key,
			maxPartBytes: MAX_PART,
			posts: false,
			requiresStrongEtag: true,
		}
	if (p.confirm !== true) throw new Error('confirm: true is required to upload, never to post')
	let source: URL
	try {
		source = new URL(p.sourceUrl)
	} catch {
		throw new Error('HTTPS sourceUrl required')
	}
	if (p.sourceUrl.includes('{{') || source.protocol !== 'https:')
		throw new Error('HTTPS sourceUrl required')
	let head: Response
	try {
		head = await api.sourceFetch(source.toString(), { method: 'HEAD', redirect: 'manual' })
	} catch {
		throw new Error('Source identity unavailable; no registration performed')
	}
	const etag = head.headers.get('etag')
	const length = head.headers.get('content-length')
	const size = Number(length)
	await head.body?.cancel()
	if (
		!head.ok ||
		!etag ||
		etag.includes('{{') ||
		etag.startsWith('W/') ||
		!/^"[^"\r\n]+"$/.test(etag) ||
		!length ||
		!/^\d+$/.test(length) ||
		!Number.isSafeInteger(size) ||
		size <= 0
	)
		throw new Error(
			'Source requires strong ETag and known positive size; no registration performed',
		)
	const owner = await api.owner()
	const identity = await hash(JSON.stringify([owner, p.sourceId, source.toString(), size, etag]))
	let job = await api.store.get(key)
	if (job) {
		if (job.identity !== identity || job.owner !== owner)
			throw new Error('Upload source/account/options changed; no mutation performed')
		return inspectVideoJob(key, api)
	}
	job = { key, identity, owner, size, phase: 'starting', version: 0, partIds: [], ackOffset: 0 }
	if (!(await api.store.insert(job)))
		throw new Error('Another run owns this uploadKey; no registration performed')
	const save = async (patch: Partial<VideoJob>) => {
		const next = await api.store.save({ ...job!, ...patch }, job!.version)
		if (!next) throw new Error('Checkpoint conflict; stopped')
		job = next
	}
	try {
		const raw = await api.register(size)
		const r = raw.value ?? raw
		if (typeof r.video !== 'string' || !/^urn:li:video:[A-Za-z0-9_-]+$/.test(r.video))
			throw new Error('Invalid registration')
		await save({ video: r.video, phase: 'uploading' })
		if (!Array.isArray(r.uploadInstructions) || !r.uploadInstructions.length)
			throw new Error('Missing instructions')
		let next = 0
		for (const part of r.uploadInstructions) {
			if (
				!Number.isSafeInteger(part.firstByte) ||
				!Number.isSafeInteger(part.lastByte) ||
				part.firstByte !== next ||
				part.lastByte < next ||
				part.lastByte >= size ||
				part.lastByte - next + 1 > MAX_PART
			)
				throw new Error('Invalid provider part ranges')
			next = part.lastByte + 1
		}
		if (next !== size) throw new Error('Incomplete provider part ranges')
		for (const part of r.uploadInstructions) {
			const resp = await api.sourceFetch(source.toString(), {
				headers: { range: `bytes=${part.firstByte}-${part.lastByte}`, 'if-match': etag },
				redirect: 'manual',
			})
			const expected = part.lastByte - part.firstByte + 1
			const range = `bytes ${part.firstByte}-${part.lastByte}/${size}`
			if (
				resp.status !== 206 ||
				resp.headers.get('content-range') !== range ||
				resp.headers.get('etag') !== etag
			) {
				await resp.body?.cancel()
				throw new Error('Source identity/range changed')
			}
			const bytes = new Uint8Array(expected)
			let used = 0
			const reader = resp.body?.getReader()
			if (!reader) throw new Error('Missing source part')
			try {
				for (;;) {
					const x = await reader.read()
					if (x.done) break
					if (used + x.value.length > expected) throw new Error('Oversized source part')
					bytes.set(x.value, used)
					used += x.value.length
				}
				if (used !== expected) throw new Error('Partial source part')
			} finally {
				await reader.cancel().catch(() => {})
				reader.releaseLock()
			}
			const id = await api.part(part.uploadUrl, bytes)
			if (
				typeof id !== 'string' ||
				!id ||
				id.length > 512 ||
				id.includes('://') ||
				id.includes('{{')
			)
				throw new Error('Missing provider part acknowledgement')
			await save({ partIds: [...job!.partIds, id], ackOffset: part.lastByte + 1 })
		}
		await save({ phase: 'finalizing' })
		await api.finalize(
			job!.video!,
			typeof r.uploadToken === 'string' ? r.uploadToken : '',
			job!.partIds,
		)
		await save({ phase: 'finalized' })
		return inspectVideoJob(key, api)
	} catch {
		throw new Error(
			'Upload stopped; checkpoint preserved. Inspect this uploadKey before any replacement. No automatic registration/finalization retry; no post was created.',
		)
	}
}