* refactor(ui): replace anchor tags with next/link in SidebarNavLink and UserMenu Update SidebarNavLink to use next/link for navigation instead of anchor tags, ensuring proper routing and improved accessibility in Next.js. Refactor UserMenu to remove legacy Link wrappers and directly use SidebarNavLink for signin and signup links. This streamlines navigation components and aligns with Next.js best practices. * fix(pdf): handle non-zero viewport origins and improve layout model ordering Update normalizeTextItemsForLayout to correctly apply viewport transforms, including non-zero page origins, ensuring accurate mapping of PDF text items to top-left coordinates. Refactor runLayoutModel to implement a custom order sequence builder for layout regions using model order logits, improving region ordering consistency with model semantics. Update related tests to cover viewport transform edge cases. * refactor(pdf): improve text normalization with font ascent and vertical overlap logic Enhance text normalization by incorporating font ascent and descent data to more accurately position glyphs, especially for decorative initials. Update merge logic to better detect line membership using vertical overlap, ensuring drop caps and overlapping glyphs are merged correctly. Extend tests to cover these layout scenarios. * style(range): redesign slider with precision gauge and ruler ticks Revamp the range input to feature a minimalist "precision gauge" style. Introduce a hairline rail, ruler notches for discrete steps, and a slim needle thumb. Add CSS variables and logic for per-instance tick sizing and coloring. Remove bulky inline class-based styling in favor of centralized CSS for improved maintainability and visual clarity. * refactor(ui): modularize PDF loader and range slider visuals Move PDF layout scan visualization and range slider styles into dedicated CSS modules, isolating their styles from the global scope. Integrate PdfLayoutScan component into the PDF viewer loader UI for animated parse progress. Refactor progress bars to use a reusable progress-fill class with animated sheen effect. Update range input to use CSS module for precision gauge styling. * style(reader): remove grid overlay from PdfLayoutScan visualization * refactor(api): add staleness detection for inflight worker operation states Integrate isWorkerOperationStateStale checks into document parse API endpoints to ensure inflight worker operation states are not reused if stale. Introduce helper for staleness detection and corresponding unit tests. Enhance SSE event streaming with keepalive intervals and improve progress acknowledgment error handling. * feat(worker): recover and fail stale in-flight pdf ops on startup Add orphaned operation recovery logic to detect and mark stale in-flight pdf_layout jobs as failed during worker startup. Extend OperationStateStore with listOpStates for state enumeration. Update tests and documentation to cover recovery behavior and new environment variable COMPUTE_PDF_JOB_ATTEMPTS. * refactor(worker): distinguish staleness thresholds for running and queued pdf ops Update orphan recovery logic to apply separate timeouts for 'running' and 'queued' pdf_layout operations. Adjust tests to verify that only stale 'running' operations are failed, while stale 'queued' operations remain untouched. * feat(worker): extend orphan recovery to handle whisper_align ops and improve logging Update orphan recovery to detect and fail stale 'running' whisper_align operations in addition to pdf_layout. Refactor recovery logic to generalize staleness checks across operation kinds and enhance log output with detailed operation info. Expand tests to verify correct handling of both whisper_align and pdf_layout operations in running and queued states. * refactor(control-plane): introduce revision-based CAS for operation state updates Add revision tracking and compare-and-set (CAS) semantics to operation state stores, enabling atomic state transitions and preventing lost updates. Extend the OperationStateStore interface with getOpStateRecord and compareAndSetOpState methods. Update orchestrator and worker runtime to utilize CAS for marking operations as failed only if the state is unchanged. Enhance in-memory, JetStream, and test control plane implementations to support revision logic. This change improves concurrency safety and correctness of operation state management across distributed components. * feat(ui): add parse failure state to PDF layout scan animation Display a distinct "parse halted" visual state in the PDF layout scan component and PDF viewer page when parsing fails. The loader animation is replaced by a static, dimmed page with an alert glyph and updated styling, ensuring users are not misled by an active animation after a failure. CSS and component logic updated to support the new state. * feat(worker): extract orphaned operation recovery to module with periodic sweep Move orphaned operation recovery logic into a dedicated orphan-recovery module, introducing a periodic sweep timer that triggers recovery every 15 seconds while the worker is connected. Refactor runtime to delegate orphan detection and handling to the new module, improving modularity and maintainability. Add unit tests for orphan-recovery to ensure correctness. * fix(ui): adjust PDF viewer layout and update parse loader description * refactor(pdf): streamline layout model region extraction and update test coverage - Replace custom order sequence logic with softmax-based class selection in runLayoutModel - Remove unused sigmoid and buildOrderSequence functions - Simplify detection loop to filter and map regions directly - Add targeted tests for layout model extraction logic - Update CSS animation naming for consistency - Clarify test description and add inline comments for orphan recovery scenario * fix(pdf): add strict validation for layout model output shapes and extend test coverage Add explicit error handling for invalid or inconsistent pred_boxes and logits array lengths in runLayoutModel to prevent silent failures. Expand test suite to verify correct region filtering and error scenarios, ensuring only labeled regions are returned and malformed outputs are handled robustly.
355 lines
12 KiB
TypeScript
355 lines
12 KiB
TypeScript
import { createHash } from 'node:crypto';
|
|
import { AckPolicy, DeliverPolicy, ReplayPolicy, type JetStreamClient, type JetStreamManager } from '@nats-io/jetstream';
|
|
import { nanos } from '@nats-io/transport-node';
|
|
import type {
|
|
OperationEvent,
|
|
OperationEventStream,
|
|
OperationQueue,
|
|
OperationState,
|
|
OperationStateStore,
|
|
QueuedOperation,
|
|
} from '@openreader/compute-core/control-plane';
|
|
import type {
|
|
PdfLayoutJobRequest,
|
|
WhisperAlignJobRequest,
|
|
WorkerOperationKind,
|
|
} from '@openreader/compute-core/api-contracts';
|
|
import { createJsonCodec } from './json-codec';
|
|
|
|
export interface KvEntryLike {
|
|
operation?: string;
|
|
value: Uint8Array;
|
|
revision: number;
|
|
}
|
|
|
|
export interface KvStoreLike {
|
|
get(key: string): Promise<KvEntryLike | null>;
|
|
put(key: string, data: Uint8Array): Promise<unknown>;
|
|
create(key: string, data: Uint8Array): Promise<unknown>;
|
|
update(key: string, data: Uint8Array, version: number): Promise<unknown>;
|
|
keys(filter?: string | string[]): Promise<AsyncIterable<string>>;
|
|
}
|
|
|
|
function toErrorMessage(error: unknown): string {
|
|
if (error instanceof Error && error.message) return error.message;
|
|
return String(error);
|
|
}
|
|
|
|
function isCasConflictError(error: unknown): boolean {
|
|
const message = toErrorMessage(error).toLowerCase();
|
|
return message.includes('wrong last sequence') || message.includes('key exists') || message.includes('wrong last');
|
|
}
|
|
|
|
function isPut(entry: KvEntryLike | null): entry is KvEntryLike {
|
|
return Boolean(entry && entry.operation === 'PUT');
|
|
}
|
|
|
|
interface OpIndexEntry {
|
|
opId: string;
|
|
}
|
|
|
|
export const OP_EVENTS_SUBJECT_PREFIX = 'ops.events';
|
|
export const OP_EVENTS_SUBJECT_WILDCARD = `${OP_EVENTS_SUBJECT_PREFIX}.*`;
|
|
|
|
export function hashOpKey(opKey: string): string {
|
|
return createHash('sha256').update(opKey).digest('hex');
|
|
}
|
|
|
|
export function opIndexKvKey(opKey: string): string {
|
|
return `op_index.${hashOpKey(opKey)}`;
|
|
}
|
|
|
|
export function opStateKvKey(opId: string): string {
|
|
return `op_state.${opId}`;
|
|
}
|
|
|
|
export function opEventsSubject(opId: string): string {
|
|
return `${OP_EVENTS_SUBJECT_PREFIX}.${opId}`;
|
|
}
|
|
|
|
export interface JetStreamOperationStateStoreDeps {
|
|
getKv: () => Promise<KvStoreLike>;
|
|
}
|
|
|
|
export class JetStreamOperationStateStore<Result = unknown> implements OperationStateStore<Result> {
|
|
private readonly getKv: () => Promise<KvStoreLike>;
|
|
private readonly opStateCodec = createJsonCodec<OperationState<Result>>();
|
|
private readonly opIndexCodec = createJsonCodec<OpIndexEntry>();
|
|
|
|
constructor(deps: JetStreamOperationStateStoreDeps) {
|
|
this.getKv = deps.getKv;
|
|
}
|
|
|
|
async getOpState(opId: string): Promise<OperationState<Result> | null> {
|
|
const record = await this.getOpStateRecord(opId);
|
|
return record?.state ?? null;
|
|
}
|
|
|
|
async getOpStateRecord(opId: string): Promise<{ state: OperationState<Result>; revision: number } | null> {
|
|
const kv = await this.getKv();
|
|
const entry = await kv.get(opStateKvKey(opId));
|
|
if (!isPut(entry)) return null;
|
|
return {
|
|
state: this.opStateCodec.decode(entry.value),
|
|
revision: entry.revision,
|
|
};
|
|
}
|
|
|
|
async putOpState(state: OperationState<Result>): Promise<void> {
|
|
const kv = await this.getKv();
|
|
await kv.put(opStateKvKey(state.opId), this.opStateCodec.encode(state));
|
|
}
|
|
|
|
async compareAndSetOpState(input: {
|
|
opId: string;
|
|
expectedRevision: number;
|
|
newState: OperationState<Result>;
|
|
}): Promise<boolean> {
|
|
const kv = await this.getKv();
|
|
try {
|
|
await kv.update(
|
|
opStateKvKey(input.opId),
|
|
this.opStateCodec.encode(input.newState),
|
|
input.expectedRevision,
|
|
);
|
|
return true;
|
|
} catch (error) {
|
|
if (isCasConflictError(error)) return false;
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async listOpStates(): Promise<OperationState<Result>[]> {
|
|
const kv = await this.getKv();
|
|
const keys = await kv.keys('op_state.*');
|
|
const states: OperationState<Result>[] = [];
|
|
for await (const key of keys) {
|
|
const entry = await kv.get(key);
|
|
if (!isPut(entry)) continue;
|
|
states.push(this.opStateCodec.decode(entry.value));
|
|
}
|
|
return states;
|
|
}
|
|
|
|
async getOpIndex(opKey: string): Promise<{ opId: string } | null> {
|
|
const kv = await this.getKv();
|
|
const entry = await kv.get(opIndexKvKey(opKey));
|
|
if (!isPut(entry)) return null;
|
|
return this.opIndexCodec.decode(entry.value);
|
|
}
|
|
|
|
async compareAndSetOpIndex(input: {
|
|
opKey: string;
|
|
newOpId: string;
|
|
expectedOpId: string | null;
|
|
}): Promise<boolean> {
|
|
const kv = await this.getKv();
|
|
const key = opIndexKvKey(input.opKey);
|
|
const value = this.opIndexCodec.encode({ opId: input.newOpId });
|
|
|
|
if (input.expectedOpId === null) {
|
|
try {
|
|
await kv.create(key, value);
|
|
return true;
|
|
} catch (error) {
|
|
if (isCasConflictError(error)) return false;
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
const current = await kv.get(key);
|
|
if (!isPut(current)) return false;
|
|
const decoded = this.opIndexCodec.decode(current.value);
|
|
if (decoded.opId !== input.expectedOpId) return false;
|
|
|
|
try {
|
|
await kv.update(key, value, current.revision);
|
|
return true;
|
|
} catch (error) {
|
|
if (isCasConflictError(error)) return false;
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
export interface JetStreamOperationEventStreamDeps {
|
|
getJs: () => Promise<Pick<JetStreamClient, 'publish' | 'consumers'>>;
|
|
getJsm: () => Promise<Pick<JetStreamManager, 'consumers'>>;
|
|
eventsStreamName: string;
|
|
inactiveThresholdMs?: number;
|
|
}
|
|
|
|
export class JetStreamOperationEventStream<Result = unknown> implements OperationEventStream<Result> {
|
|
private readonly getJs: () => Promise<Pick<JetStreamClient, 'publish' | 'consumers'>>;
|
|
private readonly getJsm: () => Promise<Pick<JetStreamManager, 'consumers'>>;
|
|
private readonly eventsStreamName: string;
|
|
private readonly inactiveThresholdNanos: number;
|
|
private readonly opStateCodec = createJsonCodec<OperationState<Result>>();
|
|
|
|
constructor(deps: JetStreamOperationEventStreamDeps) {
|
|
this.getJs = deps.getJs;
|
|
this.getJsm = deps.getJsm;
|
|
this.eventsStreamName = deps.eventsStreamName;
|
|
this.inactiveThresholdNanos = nanos((deps.inactiveThresholdMs ?? 60_000));
|
|
}
|
|
|
|
async append(opId: string, snapshot: OperationState<Result>): Promise<OperationEvent<Result>> {
|
|
const js = await this.getJs();
|
|
const encoder = new TextEncoder();
|
|
const ack = await js.publish(opEventsSubject(opId), encoder.encode(JSON.stringify(snapshot)));
|
|
return {
|
|
eventId: ack.seq,
|
|
snapshot,
|
|
};
|
|
}
|
|
|
|
private async createConsumer(input: {
|
|
opId: string;
|
|
sinceEventId?: number;
|
|
replayOnly: boolean;
|
|
}): Promise<{ name: string; js: Pick<JetStreamClient, 'publish' | 'consumers'> }> {
|
|
const js = await this.getJs();
|
|
const jsm = await this.getJsm();
|
|
const subject = opEventsSubject(input.opId);
|
|
const since = Math.max(0, Math.floor(input.sinceEventId ?? 0));
|
|
const name = `op_events_${input.opId.slice(0, 12)}_${crypto.randomUUID().replaceAll('-', '').slice(0, 12)}`;
|
|
const config = {
|
|
name,
|
|
ack_policy: AckPolicy.None,
|
|
deliver_policy: since > 0 ? DeliverPolicy.StartSequence : (input.replayOnly ? DeliverPolicy.All : DeliverPolicy.New),
|
|
replay_policy: ReplayPolicy.Instant,
|
|
filter_subject: subject,
|
|
max_deliver: 1,
|
|
inactive_threshold: this.inactiveThresholdNanos,
|
|
...(since > 0 ? { opt_start_seq: since + 1 } : {}),
|
|
};
|
|
await jsm.consumers.add(this.eventsStreamName, config);
|
|
return { name, js };
|
|
}
|
|
|
|
private async deleteConsumer(name: string): Promise<void> {
|
|
const jsm = await this.getJsm();
|
|
await jsm.consumers.delete(this.eventsStreamName, name).catch(() => undefined);
|
|
}
|
|
|
|
async listSince(opId: string, sinceEventId: number, limit = 200): Promise<OperationEvent<Result>[]> {
|
|
const boundedLimit = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : 200;
|
|
const { name, js } = await this.createConsumer({
|
|
opId,
|
|
sinceEventId,
|
|
replayOnly: true,
|
|
});
|
|
try {
|
|
const consumer = await js.consumers.get(this.eventsStreamName, name);
|
|
const output: OperationEvent<Result>[] = [];
|
|
while (output.length < boundedLimit) {
|
|
const msg = await consumer.next({ expires: 250 });
|
|
if (!msg) break;
|
|
output.push({
|
|
eventId: msg.seq,
|
|
snapshot: this.opStateCodec.decode(msg.data),
|
|
});
|
|
}
|
|
return output;
|
|
} finally {
|
|
await this.deleteConsumer(name);
|
|
}
|
|
}
|
|
|
|
async subscribe(input: {
|
|
opId: string;
|
|
sinceEventId?: number;
|
|
onEvent: (event: OperationEvent<Result>) => void | Promise<void>;
|
|
onError?: (error: unknown) => void;
|
|
}): Promise<() => void> {
|
|
const { name, js } = await this.createConsumer({
|
|
opId: input.opId,
|
|
sinceEventId: input.sinceEventId,
|
|
replayOnly: false,
|
|
});
|
|
const consumer = await js.consumers.get(this.eventsStreamName, name);
|
|
const messages = await consumer.consume();
|
|
let closed = false;
|
|
|
|
void (async () => {
|
|
try {
|
|
for await (const msg of messages) {
|
|
if (closed) break;
|
|
try {
|
|
await input.onEvent({
|
|
eventId: msg.seq,
|
|
snapshot: this.opStateCodec.decode(msg.data),
|
|
});
|
|
} catch (error) {
|
|
input.onError?.(error);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
if (!closed) input.onError?.(error);
|
|
} finally {
|
|
if (!closed) {
|
|
closed = true;
|
|
await this.deleteConsumer(name);
|
|
}
|
|
}
|
|
})();
|
|
|
|
return () => {
|
|
if (closed) return;
|
|
closed = true;
|
|
void messages.close().catch(() => undefined);
|
|
void this.deleteConsumer(name);
|
|
};
|
|
}
|
|
}
|
|
|
|
export interface JetStreamOperationQueueDeps<TPayload> {
|
|
getJs: () => Promise<Pick<JetStreamClient, 'publish'>>;
|
|
whisperSubject: string;
|
|
layoutSubject: string;
|
|
onEnqueued?: (job: QueuedOperation<TPayload>) => Promise<void> | void;
|
|
}
|
|
|
|
export class JetStreamOperationQueue implements OperationQueue<WhisperAlignJobRequest | PdfLayoutJobRequest> {
|
|
private readonly getJs: () => Promise<Pick<JetStreamClient, 'publish'>>;
|
|
private readonly whisperSubject: string;
|
|
private readonly layoutSubject: string;
|
|
private readonly onEnqueued?: (job: QueuedOperation<WhisperAlignJobRequest | PdfLayoutJobRequest>) => Promise<void> | void;
|
|
private readonly whisperCodec = createJsonCodec<QueuedOperation<WhisperAlignJobRequest>>();
|
|
private readonly layoutCodec = createJsonCodec<QueuedOperation<PdfLayoutJobRequest>>();
|
|
|
|
constructor(deps: JetStreamOperationQueueDeps<WhisperAlignJobRequest | PdfLayoutJobRequest>) {
|
|
this.getJs = deps.getJs;
|
|
this.whisperSubject = deps.whisperSubject;
|
|
this.layoutSubject = deps.layoutSubject;
|
|
this.onEnqueued = deps.onEnqueued;
|
|
}
|
|
|
|
async enqueue(job: QueuedOperation<WhisperAlignJobRequest | PdfLayoutJobRequest>): Promise<void> {
|
|
const js = await this.getJs();
|
|
if (job.kind === 'whisper_align') {
|
|
await js.publish(
|
|
this.whisperSubject,
|
|
this.whisperCodec.encode(job as QueuedOperation<WhisperAlignJobRequest>),
|
|
);
|
|
} else if (job.kind === 'pdf_layout') {
|
|
await js.publish(
|
|
this.layoutSubject,
|
|
this.layoutCodec.encode(job as QueuedOperation<PdfLayoutJobRequest>),
|
|
);
|
|
} else {
|
|
const exhaustive: never = job.kind;
|
|
throw new Error(`Unsupported operation kind: ${String(exhaustive)}`);
|
|
}
|
|
|
|
await this.onEnqueued?.(job);
|
|
}
|
|
|
|
async claimNext(_kind: WorkerOperationKind): Promise<QueuedOperation<WhisperAlignJobRequest | PdfLayoutJobRequest> | null> {
|
|
throw new Error('JetStreamOperationQueue.claimNext is not used by the worker runtime');
|
|
}
|
|
|
|
size(): number {
|
|
return 0;
|
|
}
|
|
}
|