Files

62 lines
2.6 KiB
TypeScript

// SPDX-License-Identifier: LicenseRef-ConusAI-Template-1.0
// The OCR path of a test: the real `@conusai-sdk/ocr` client (through kit-platform's `DocumentReader`)
// over HTTP to the fake platform of @conusai-kit/testing, which accepts a job and answers it as the
// platform's job API does. Nothing here stands in for the OCR path; `observed` only watches it, and can
// make one call fail the way a network does, which the fake platform has no way to do.
import { type DocumentOcr, sdkDocumentOcr } from "@app/modules/documents"
import { createDocumentReader } from "@conusai-kit/platform"
import { startFakePlatform } from "@conusai-kit/testing/fake-platform"
export type FakePlatform = Awaited<ReturnType<typeof startFakePlatform>>
export interface ObservedOcr extends DocumentOcr {
/** Every document accepted, with the idempotency key it came with. */
readonly submitted: Array<{ jobId: number; filename: string; idempotencyKey: string }>
/** Every `wait`, by job id: a retried job must resume its job and not submit another. */
readonly waited: number[]
/** The next `wait` throws this, once, before asking the platform anything. */
failWaitOnce(error: Error): void
}
export function observed(inner: DocumentOcr): ObservedOcr {
const submitted: ObservedOcr["submitted"] = []
const waited: number[] = []
let nextWait: Error | undefined
return {
submitted,
waited,
failWaitOnce(error) {
nextWait = error
},
async submit(bytes, options) {
const accepted = await inner.submit(bytes, options)
// The same key is the same job on the platform; a repeat is not a second submission.
if (!submitted.some((entry) => entry.jobId === accepted.jobId)) {
submitted.push({ jobId: accepted.jobId, filename: options.filename, idempotencyKey: options.idempotencyKey })
}
return accepted
},
page: (jobId, page, options) => inner.page(jobId, page, options),
async wait(jobId, options) {
waited.push(jobId)
if (nextWait) {
const error = nextWait
nextWait = undefined
throw error
}
return inner.wait(jobId, options)
},
}
}
/** A fake platform that reads every document as `document`, and the app-side OCR port over it. */
export async function startOcr(
document: Record<string, unknown>,
): Promise<{ platform: FakePlatform; ocr: ObservedOcr }> {
const platform = await startFakePlatform()
platform.ocr.setDocument(document)
const reader = createDocumentReader({ CONUSAI_API_URL: `${platform.url}/api`, CONUSAI_API_TOKEN: "deployment-token" })
return { platform, ocr: observed(sdkDocumentOcr(reader, { intervalMs: 1 })) }
}