Line data Source code
1 : import { AsyncValue } from '../utils/async_value.js';
2 : import { TaskVariant } from './computation_types.js';
3 : import { ComputationAction, SCHEDULE_TASK } from './computation_state.js';
4 : import { Dispatch } from '../utils/variant.js';
5 : import { LoggableException } from '../platform/logger/logger.js';
6 : import type { EmbeddedClientContext } from '../platform/database/embedded_database.js';
7 :
8 : /// Executes the query of a task, e.g. to track it as a query of the connection of the table.
9 : /// The query runs with the client context that execute receives, e.g. to attribute it in the Hyper log.
10 : export type ComputeQueryExecution = <T>(
11 : queryText: string,
12 : execute: (clientContext: EmbeddedClientContext | null) => Promise<T>,
13 : ) => Promise<T>;
14 :
15 : /// Execute the query of a task without tracking it
16 1 : export const executeDirectly: ComputeQueryExecution = (_queryText, execute) => execute(null);
17 :
18 : /// The task variant of a task type
19 : type TaskOf<T extends TaskVariant['type']> = Extract<TaskVariant, { type: T }>;
20 : /// The result of a task type
21 : type TaskResultOf<T extends TaskVariant['type']> = TaskOf<T>['result'] extends AsyncValue<infer R, LoggableException> ? R : never;
22 :
23 : /// Schedule a task with the scheduler and wait for its result
24 1 : export function scheduleTask<T extends TaskVariant['type']>(type: T, task: TaskOf<T>['value'], dispatch: Dispatch<ComputationAction>): Promise<TaskResultOf<T>> {
25 1 : const result = new AsyncValue<TaskResultOf<T>, LoggableException>();
26 : // TypeScript doesn't narrow the variant from the generic task type
27 1 : const variant = { type, value: task, result } as unknown as TaskOf<T>;
28 1 : dispatch({ type: SCHEDULE_TASK, value: variant });
29 1 : return result.getValue();
30 1 : }
|