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

@kentcdodds/google

Google helpers for Gmail, Calendar, Drive, People, YouTube (including upload), and Analytics.

FollowFork

Files

mock-youtube.ts

217 lines · 9.8 KB · TypeScript
/**
 * Synthetic origins for upload tests. No network, no credentials, no real media.
 * - createMockSource: a Range origin that generates bytes deterministically on the fly
 *   (so multi-GB sources cost no memory), with fault injection.
 * - createMockResumableSink: a YouTube resumable endpoint that hashes what it receives in
 *   order, counts session creates and video inserts, and injects faults.
 */
import { createHash, createHmac } from 'node:crypto'
import { DatabaseSync } from 'node:sqlite'

export function byteAt(i: number): number {
	return (i * 31 + (i >>> 11)) & 0xff
}
export function fillBytes(out: Uint8Array, start: number) {
	for (let i = 0; i < out.length; i++) out[i] = byteAt(start + i)
}
export function expectedSha256(total: number, block = 4 * 1024 * 1024): string {
	const h = createHash('sha256')
	const buf = new Uint8Array(block)
	for (let o = 0; o < total; o += block) {
		const n = Math.min(block, total - o)
		const view = n === block ? buf : buf.subarray(0, n)
		fillBytes(view, o)
		h.update(view)
	}
	return h.digest('hex')
}

export type SourceFault = { kind: 'status'; status: number } | { kind: 'ignore-range' } | { kind: 'truncate' } | { kind: 'bad-content-range' } | { kind: 'throw' } | { kind: 'change-etag' } | { kind: 'drop-etag' } | { kind: 'drop-last-modified' }

export function createMockSource(total: number, opts: { etag?: string; lastModified?: string; faults?: Map<number, SourceFault>; streamPieces?: number; offset?: number } = {}) {
	let n = 0
	let etag = opts.etag ?? '"v1"'
	const requests: string[] = []
	const fetchFn = async (_url: string, init: RequestInit = {}) => {
		n += 1
		const range = new Headers(init.headers).get('range') ?? ''
		requests.push(range)
		const fault = opts.faults?.get(n)
		if (fault?.kind === 'throw') throw new TypeError('network down')
		if (fault?.kind === 'status') return new Response('nope', { status: fault.status })
		if (fault?.kind === 'change-etag') etag = '"v2"'
		const m = /^bytes=(\d+)-(\d+)$/.exec(range)
		if (!m || fault?.kind === 'ignore-range') {
			return new Response(new ReadableStream({ pull(c) { c.close() } }), { status: 200, headers: { 'content-length': String(total), etag } })
		}
		const start = Number(m[1])
		const end = Math.min(Number(m[2]), total - 1)
		let len = end - start + 1
		const headers: Record<string, string> = { 'content-range': `bytes ${start}-${end}/${total}`, etag }
		if (opts.lastModified) headers['last-modified'] = opts.lastModified
		if (fault?.kind === 'drop-etag') delete headers.etag
		if (fault?.kind === 'drop-last-modified') delete headers['last-modified']
		if (fault?.kind === 'bad-content-range') headers['content-range'] = `bytes ${start + 1}-${end}/${total}`
		if (fault?.kind === 'truncate') len = Math.floor(len / 2)
		const pieces = opts.streamPieces ?? 4
		const pieceLen = Math.max(1, Math.ceil(len / pieces))
		let sent = 0
		const body = new ReadableStream<Uint8Array>({
			pull(c) {
				if (sent >= len) return c.close()
				const k = Math.min(pieceLen, len - sent)
				const piece = new Uint8Array(k)
				fillBytes(piece, start + sent + (opts.offset ?? 0))
				sent += k
				c.enqueue(piece)
			},
		})
		return new Response(body, { status: 206, headers })
	}
	return { fetch: fetchFn, requests, get count() { return n } }
}

export type SinkFault =
	| { kind: 'status'; status: number; body?: string }
	/** Throw before the sink records anything. */
	| { kind: 'drop-before' }
	/** Record the bytes (or create the session) then throw: a lost response. */
	| { kind: 'drop-after' }
	/** Accept only this many bytes of the chunk. */
	| { kind: 'partial'; keep: number }
	/** 308 without Range header for this PUT (nothing persisted). */
	| { kind: 'no-range' }

export const CHANNEL_ID = 'UC' + 'k'.repeat(22)

export function createMockResumableSink(opts: { channelId?: string; faults?: Map<string, SinkFault>; expireAfterPuts?: number } = {}) {
	const channelId = opts.channelId ?? CHANNEL_ID
	const sessions = new Map<string, { total: number; ack: number; hash: ReturnType<typeof createHash>; videoId: string | null; expired: boolean }>()
	const stats = { posts: 0, puts: 0, statusQueries: 0, inserts: 0, cancelledBodies: 0, bodiesReturned: 0, sessionsCreated: 0, videos: [] as string[] }
	let putIndex = 0
	const fault = (key: string) => opts.faults?.get(key)
	const tracked = (body: BodyInit | null, init: ResponseInit) => {
		stats.bodiesReturned += 1
		let sent = false
		const stream = new ReadableStream({
			pull(c) {
				if (!sent && body) c.enqueue(new TextEncoder().encode(String(body)))
				sent = true
				c.close()
			},
			cancel() {
				stats.cancelledBodies += 1
			},
		}, { highWaterMark: 0 })
		return new Response(stream, init)
	}
	const complete = (s: { videoId: string | null }) => json({ id: s.videoId, snippet: { channelId, title: 't' }, status: { uploadStatus: 'uploaded' } }, 201)
	const json = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json' } })

	const fetchFn = async (url: string, init: RequestInit = {}) => {
		const headers = new Headers(init.headers)
		const u = new URL(url)
		if (u.pathname.endsWith('/youtube/v3/channels')) return json({ items: [{ id: channelId, snippet: { title: 'Kody', customUrl: '@kodykoala' }, contentDetails: { relatedPlaylists: { uploads: 'UU' } }, statistics: {} }] })
		if (u.pathname.endsWith('/youtube/v3/videos') && (init.method ?? 'GET') === 'GET') {
			const id = u.searchParams.get('id')
			return json({ items: stats.videos.includes(id!) ? [{ id, snippet: { channelId }, status: { uploadStatus: 'processed', privacyStatus: 'private' }, contentDetails: { duration: 'PT7M51S' } }] : [] })
		}
		if (init.method === 'POST' && u.pathname === '/upload/youtube/v3/videos') {
			stats.posts += 1
			const f = fault(`post:${stats.posts}`)
			if (f?.kind === 'drop-before') throw new TypeError('connection reset before request was sent')
			if (f?.kind === 'status') return json({ error: { message: f.body ?? 'err' } }, f.status)
			const total = Number(headers.get('x-upload-content-length'))
			const id = 'SESS' + stats.posts + 'x' + Math.random().toString(36).slice(2)
			sessions.set(id, { total, ack: 0, hash: createHash('sha256'), videoId: null, expired: false })
			stats.sessionsCreated += 1
			if (f?.kind === 'drop-after') throw new TypeError('connection reset after request was sent')
			return tracked('', { status: 200, headers: { location: `https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&upload_id=${id}` } })
		}
		if (init.method === 'PUT' && u.pathname === '/upload/youtube/v3/videos') {
			if (init.redirect !== 'manual') throw new Error('test: upload PUTs must use redirect: manual')
			const s = sessions.get(u.searchParams.get('upload_id') ?? '')
			if (!s || s.expired) return json({ error: { message: 'not found' } }, 404)
			const cr = headers.get('content-range') ?? ''
			const rangeHeader = () => (s.ack > 0 ? { range: `bytes=0-${s.ack - 1}` } : {})
			if (/^bytes \*\/\d+$/.test(cr)) {
				stats.statusQueries += 1
				const f = fault(`status:${stats.statusQueries}`)
				if (f?.kind === 'status') return json({ error: { message: 'x' } }, f.status)
				if (s.videoId) return complete(s)
				return tracked('', { status: 308, headers: rangeHeader() })
			}
			putIndex += 1
			stats.puts += 1
			if (opts.expireAfterPuts && stats.puts > opts.expireAfterPuts) {
				s.expired = true
				return json({ error: { message: 'gone' } }, 410)
			}
			const f = fault(`put:${putIndex}`)
			if (f?.kind === 'drop-before') throw new TypeError('socket hang up (bytes may have reached origin)')
			if (f?.kind === 'status') return json({ error: { message: f.body ?? 'err' } }, f.status)
			const m = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(cr)
			if (!m) return json({ error: { message: 'bad range' } }, 400)
			const start = Number(m[1])
			const body = new Uint8Array(init.body as ArrayBuffer)
			if (body.byteLength !== Number(m[2]) - start + 1) return json({ error: { message: 'length mismatch' } }, 400)
			if (start !== s.ack) return tracked('', { status: 308, headers: rangeHeader() })
			if (f?.kind === 'no-range') {
				// YouTube semantics: 308 without Range = nothing persisted for this session.
				s.ack = 0
				s.hash = createHash('sha256')
				return tracked('', { status: 308 })
			}
			const keep = f?.kind === 'partial' ? f.keep : body.byteLength
			s.hash.update(body.subarray(0, keep))
			s.ack += keep
			if (s.ack === s.total) {
				const vid = ('vid' + stats.posts + 'abcdefghijk').slice(0, 11)
				s.videoId = vid
				stats.inserts += 1
				stats.videos.push(vid)
				if (f?.kind === 'drop-after') throw new TypeError('response lost after final chunk')
				return complete(s)
			}
			if (f?.kind === 'drop-after') throw new TypeError('response lost after chunk')
			return tracked('', { status: 308, headers: rangeHeader() })
		}
		return json({ error: { message: 'unexpected ' + url } }, 500)
	}
	return {
		fetch: fetchFn,
		stats,
		sessions,
		receivedSha256(): string[] {
			return [...sessions.values()].filter((s) => s.ack === s.total).map((s) => s.hash.copy().digest('hex'))
		},
	}
}

/** packageStorage().sql-compatible surface over node:sqlite (real SQL semantics incl. RETURNING). */
export function createSqliteStorage() {
	const db = new DatabaseSync(':memory:')
	return {
		db,
		async sql(query: string, params: unknown[] = []) {
			const stmt = db.prepare(query)
			if (/^\s*(SELECT|INSERT|UPDATE|DELETE)/i.test(query) && (/RETURNING/i.test(query) || /^\s*SELECT/i.test(query))) return { rows: stmt.all(...(params as any[])) }
			stmt.run(...(params as any[]))
			return { rows: [] }
		},
		dump(): string {
			return JSON.stringify(db.prepare('SELECT * FROM youtube_upload_jobs_v1').all())
		},
	}
}

export function createTestSigner(key = 'test-root-key-never-real') {
	let calls = 0
	return {
		get calls() { return calls },
		async sign(input: { message: string }) {
			calls += 1
			return createHmac('sha256', key).update(input.message).digest('hex')
		},
	}
}