import { moduleHooks } from 'spacetime:sys@2.0'; import { AlgebraicType } from '../../lib/algebraic_type.ts'; import BinaryReader from '../../lib/binary_reader.ts'; import type { ConnectionId } from '../../lib/connection_id.ts'; import { Identity } from '../../lib/identity.ts'; import type { AuthCtx, JwtClaims, ReducerCtx } from '../../lib/reducers.ts'; import type { UntypedSchemaDef } from '../../lib/schema.ts'; import { Timestamp } from '../../lib/timestamp.ts'; import type { TimeDuration } from '../../lib/time_duration.ts'; import { type HttpRequest, type HttpResponse, } from '../../lib/autogen/types.ts'; import type { Table } from '../../lib/table.ts'; import type { DbView } from '../db_view.ts'; import { Headers, type HttpClient, type RequestOptions, } from '../http_internal.ts'; import { deserializeHeaders, serializeHeaders, serializeMethod, SyncResponse, } from '../http_shared.ts'; import { makeTableView, ReducerCtxImpl } from '../runtime.ts'; import type { ProcedureCtx } from '../procedures.ts'; import { ProcedureCtxImpl } from '../procedures.ts'; import { makeRandomFromSeed } from '../rng.ts'; import type { Schema } from '../schema.ts'; import type { AnonymousViewCtx, ViewCtx } from '../views.ts'; import { makeQueryBuilder, getQueryAccessorName, toSql, type Query, } from '../query.ts'; import { TestDatastoreBackend } from './backend.ts'; import { loadTestRuntime, type TestRuntimeContext, type TestRuntimeTx, } from './runtime.ts'; const freeze = Object.freeze; const nextSeed = Symbol('nextSeed'); const rawModuleDefCache = new WeakMap< Schema, WeakMap >(); export interface ModuleTestHarness { readonly db: DbView; readonly clock: TestClock; readonly rng: TestRng; readonly moduleIdentity: Identity; withReducerTx(auth: TestAuth, body: (ctx: ReducerCtx) => T): T; procedureContext(auth: TestAuth): ProcedureCtx; procedureContextBuilder(auth: TestAuth): ProcedureContextBuilder; viewContext(auth: TestAuth): ViewCtx; anonymousViewContext(): AnonymousViewCtx; runQuery(query: Query): Row[]; } export class TestClock { #now: Timestamp; constructor(timestamp: Timestamp = Timestamp.UNIX_EPOCH) { this.#now = timestamp; } now(): Timestamp { return this.#now; } set(timestamp: Timestamp): void { this.#now = timestamp; } advance(duration: TimeDuration): void { this.#now = new Timestamp(this.#now.microsSinceUnixEpoch + duration.micros); } } export class TestRng { #seed: number | bigint | Uint8Array | null; #source: ReturnType; constructor(seed: number | bigint | Uint8Array | null = null) { this.#seed = seed; this.#source = makeRandomFromSeed(seedToBigInt(seed)); } seed(): number | bigint | Uint8Array | null { return this.#seed; } setSeed(seed: number | bigint | Uint8Array): void { this.#seed = seed; this.#source = makeRandomFromSeed(seedToBigInt(seed)); } clearSeed(): void { this.#seed = null; this.#source = makeRandomFromSeed(0n); } [nextSeed](): bigint { return this.#source.bigintInRange(0n, (1n << 64n) - 1n); } } function seedToBigInt(seed: number | bigint | Uint8Array | null): bigint { if (seed == null) return 0n; if (typeof seed === 'bigint') return seed; if (typeof seed === 'number') return BigInt(seed); let value = 0n; const len = Math.min(seed.byteLength, 8); for (let i = 0; i < len; i++) { value |= BigInt(seed[i]) << BigInt(i * 8); } return value; } class TestAuthImpl { private constructor( readonly kind: 'internal' | 'authenticated', readonly connectionId: ConnectionId | null, readonly jwtPayload: string | null ) {} static internal(): TestAuthImpl { return new TestAuthImpl('internal', null, null); } static fromJwtPayload( jwtPayload: string, connectionId: ConnectionId ): TestAuthImpl { return new TestAuthImpl('authenticated', connectionId, jwtPayload); } } export type TestAuth = TestAuthImpl; export const TestAuth = TestAuthImpl; /** * What a test HTTP responder returns: the response's status, headers and * version, plus its body, which `Response.text()`, `.json()` and `.bytes()` * then read. Omitting `body` gives an empty one. */ export type TestHttpResponse = HttpResponse & { body?: string | Uint8Array; }; export type TestHttpResponder = ( test: ModuleTestHarness, req: HttpRequest, body: Uint8Array ) => TestHttpResponse; export interface ProcedureContextBuilder { http(responder: TestHttpResponder): this; hooks(hooks: ProcedureTestHooks): this; build(): ProcedureCtx; } export class ProcedureTestHooks { #afterTxCommit: Array<(test: ModuleTestHarness) => void> = []; #onSleep: Array<(test: ModuleTestHarness, wakeTime: Timestamp) => void> = []; afterTxCommit(hook: (test: ModuleTestHarness) => void): this { this.#afterTxCommit.push(hook); return this; } onSleep( hook: (test: ModuleTestHarness, wakeTime: Timestamp) => void ): this { this.#onSleep.push(hook); return this; } runAfterTxCommit(test: ModuleTestHarness) { for (const hook of this.#afterTxCommit) hook(test); } runOnSleep(test: ModuleTestHarness, wakeTime: Timestamp) { for (const hook of this.#onSleep) hook(test, wakeTime); } } export function createProcedureTestHooks() { return new ProcedureTestHooks(); } export function createModuleTestHarness( schema: Schema, moduleExports: Record, opts: { moduleIdentity?: Identity; clock?: TestClock; rngSeed?: bigint | number | Uint8Array | null; } = {} ): ModuleTestHarness { const rawModuleDef = describeModule(schema, moduleExports); const moduleIdentity = opts.moduleIdentity ?? Identity.zero(); const runtime = loadTestRuntime(); const runtimeContext = runtime.createContext( rawModuleDef, moduleIdentity.__identity__ ); return new ModuleTestHarnessImpl( schema, runtimeContext, moduleIdentity, opts.clock ?? new TestClock(), new TestRng(opts.rngSeed ?? null) ); } function describeModule( schema: Schema, moduleExports: Record ): Uint8Array { let schemaCache = rawModuleDefCache.get(schema); if (!schemaCache) { schemaCache = new WeakMap(); rawModuleDefCache.set(schema, schemaCache); } let rawModuleDef = schemaCache.get(moduleExports); if (!rawModuleDef) { const hooks = schema[moduleHooks](moduleExports); rawModuleDef = hooks.__describe_module__(); schemaCache.set(moduleExports, rawModuleDef); } return rawModuleDef; } class ModuleTestHarnessImpl implements ModuleTestHarness { readonly clock: TestClock; readonly rng: TestRng; readonly moduleIdentity: Identity; readonly db: DbView; #schema: Schema; #runtime: TestRuntimeContext; #backend: TestDatastoreBackend; constructor( schema: Schema, runtime: TestRuntimeContext, moduleIdentity: Identity, clock: TestClock, rng: TestRng ) { this.#schema = schema; this.#runtime = runtime; this.moduleIdentity = moduleIdentity; this.clock = clock; this.rng = rng; this.#backend = new TestDatastoreBackend( runtime, runtime, moduleIdentity.__identity__ ); this.db = makeDbView(schema, this.#backend); } withReducerTx(auth: TestAuth, body: (ctx: ReducerCtx) => T): T { const tx = this.#runtime.beginTx(); const backend = this.#backend.withTransaction(tx); const sender = this.#sender(auth); if (auth.jwtPayload && auth.connectionId) { backend.setJwtPayload( auth.connectionId.__connection_id__, auth.jwtPayload ); } try { const ctx = new ReducerCtxImpl( sender, this.clock.now(), auth.connectionId, makeDbView(this.#schema, backend), backend, this.#authCtx(auth, sender), makeRandomFromSeed(this.rng[nextSeed]()) ); const ret = body(ctx as unknown as ReducerCtx); this.#runtime.commitTx(tx, 'DropEventTableRows'); return ret; } catch (e) { this.#runtime.abortTx(tx); throw e; } } procedureContext(auth: TestAuth): ProcedureCtx { return this.procedureContextBuilder(auth).build(); } procedureContextBuilder(auth: TestAuth): ProcedureContextBuilder { return new ProcedureContextBuilderImpl(this, auth); } viewContext(auth: TestAuth): ViewCtx { return freeze({ sender: this.#sender(auth), db: this.db, from: makeQueryBuilder(this.#schema.schemaType), }) as ViewCtx; } anonymousViewContext(): AnonymousViewCtx { return freeze({ db: this.db, from: makeQueryBuilder(this.#schema.schemaType), }) as AnonymousViewCtx; } runQuery(query: Query): Row[] { const sql = toSql(query); const accessorName = getQueryAccessorName(query); const table = this.#schema.schemaType.tables[accessorName]; if (!table) throw new Error(`query source table not found: ${accessorName}`); const rowType = this.#schema.typespace.types[table.tableDef.productTypeRef]; const rowDeserializer = AlgebraicType.makeDeserializer( rowType, this.#schema.typespace ); return this.#runtime .runQuery(sql, this.moduleIdentity.__identity__) .map(row => rowDeserializer(new BinaryReader(row))) as Row[]; } makeProcedureContext( auth: TestAuth, hooks: ProcedureTestHooks, responder: TestHttpResponder | undefined ): ProcedureCtx { const sender = this.#sender(auth); const procedureSeed = this.rng[nextSeed](); const backend = new ProcedureTestBackend( this, this.#runtime, this.#backend, this.moduleIdentity.__identity__, hooks ); if (auth.jwtPayload && auth.connectionId) { backend.setJwtPayload( auth.connectionId.__connection_id__, auth.jwtPayload ); } return new ProcedureCtxImpl( sender, this.clock.now(), auth.connectionId, () => makeDbView(this.#schema, backend.currentBackend()), backend, makeHttpClient(this, responder), duration => this.#sleep(duration, hooks), makeRandomFromSeed(procedureSeed), makeRandomFromSeed(procedureSeed ^ 0xa53d5eedc01dca11n) ) as ProcedureCtx; } #sender(auth: TestAuth): Identity { if (auth.kind === 'internal') return this.moduleIdentity; if (!auth.jwtPayload || !auth.connectionId) { throw new Error( 'authenticated test auth requires a JWT payload and connection id' ); } const validated = this.#runtime.validateJwtPayload( auth.jwtPayload, auth.connectionId.__connection_id__ ); return new Identity(validated.senderHex); } #sleep(duration: TimeDuration, hooks: ProcedureTestHooks): void { const wakeTime = new Timestamp( this.clock.now().microsSinceUnixEpoch + duration.micros ); hooks.runOnSleep(this, wakeTime); if (this.clock.now().microsSinceUnixEpoch < wakeTime.microsSinceUnixEpoch) { this.clock.set(wakeTime); } } #authCtx(auth: TestAuth, sender: Identity): AuthCtx { if (auth.kind === 'internal') { return freeze({ isInternal: true, hasJWT: false, jwt: null }); } const payload = JSON.parse(auth.jwtPayload!) as Record; const jwt: JwtClaims = freeze({ rawPayload: auth.jwtPayload!, subject: payload.sub as string, issuer: payload.iss as string, audience: payload.aud == null ? [] : typeof payload.aud === 'string' ? [payload.aud] : (payload.aud as string[]), identity: sender, fullPayload: payload as any, }); return freeze({ isInternal: false, hasJWT: true, jwt }); } } class ProcedureContextBuilderImpl implements ProcedureContextBuilder { #hooks = new ProcedureTestHooks(); #responder: TestHttpResponder | undefined; constructor( private readonly test: ModuleTestHarnessImpl, private readonly auth: TestAuth ) {} http(responder: TestHttpResponder): this { this.#responder = responder; return this; } hooks(hooks: ProcedureTestHooks): this { this.#hooks = hooks; return this; } build(): ProcedureCtx { return this.test.makeProcedureContext( this.auth, this.#hooks, this.#responder ); } } class ProcedureTestBackend< S extends UntypedSchemaDef, > extends TestDatastoreBackend { #ctx: TestRuntimeContext; #tx: TestRuntimeTx | null = null; constructor( private readonly test: ModuleTestHarness, ctx: TestRuntimeContext, base: TestDatastoreBackend, moduleIdentity: bigint, private readonly hooks: ProcedureTestHooks ) { super(ctx, ctx, moduleIdentity); this.#ctx = ctx; void base; void hooks; } currentBackend(): TestDatastoreBackend { return this.#tx ? this.withTransaction(this.#tx) : this; } procedureStartMutTx(): bigint { this.#tx = this.#ctx.beginTx(); return this.test.clock.now().microsSinceUnixEpoch; } procedureCommitMutTx(): void { if (!this.#tx) throw new Error('no active procedure transaction'); const tx = this.#tx; this.#tx = null; this.#ctx.commitTx(tx); this.hooks.runAfterTxCommit(this.test); } procedureAbortMutTx(): void { if (!this.#tx) return; const tx = this.#tx; this.#tx = null; this.#ctx.abortTx(tx); } } function makeDbView( schema: Schema, backend: TestDatastoreBackend ): DbView { return freeze( Object.fromEntries( Object.values(schema.schemaType.tables).map(table => [ table.accessorName, makeTableView( schema.typespace, table.tableDef, backend, '', table.isOutbox ) as Table, ]) ) ) as DbView; } function makeHttpClient( test: ModuleTestHarness, responder: TestHttpResponder | undefined ): HttpClient { const encoder = new TextEncoder(); return freeze({ fetch(url: URL | string, init: RequestOptions = {}) { if (!responder) { throw new Error('no test HTTP responder configured'); } const headers = new Headers(init.headers as any); const request: HttpRequest = freeze({ method: serializeMethod(init.method), headers: serializeHeaders(headers), timeout: init.timeout, uri: `${url}`, version: { tag: 'Http11' as const }, }); const body = init.body == null ? new Uint8Array() : typeof init.body === 'string' ? encoder.encode(init.body) : new Uint8Array(init.body as any); const response = responder(test, request, body); return new SyncResponse(response.body ?? null, { status: response.code, statusText: '', headers: deserializeHeaders(response.headers), version: response.version, }); }, }); }