vidnavigator 1.0.5 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/jobs.ts ADDED
@@ -0,0 +1,215 @@
1
+ import { AsyncJobError } from './models';
2
+ import { VidNavigatorError, TaskTimeoutError } from './errors';
3
+ import { buildApiError } from './http';
4
+
5
+ /**
6
+ * Status of an async task. `completed` and `failed` are terminal; anything else (today only
7
+ * `processing`) means the task is still running.
8
+ */
9
+ export type TaskStatus = 'processing' | 'completed' | 'failed' | (string & {});
10
+
11
+ /** Minimal shape of every polled task (async jobs and TikTok tasks). */
12
+ export interface PollableTask {
13
+ task_id: string;
14
+ task_status: TaskStatus;
15
+ error?: AsyncJobError | null;
16
+ }
17
+
18
+ export interface PollOptions<TTask = PollableTask> {
19
+ /** Delay between polls once the task has run for 10 seconds, in ms. Default 3000. Polling is free and not rate-limited. */
20
+ intervalMs?: number;
21
+ /** Poll every second during the first 10 seconds so short clips return fast. Default true. */
22
+ fastStart?: boolean;
23
+ /**
24
+ * Stop waiting after this many ms and throw {@link TaskTimeoutError} (which carries `task_id`).
25
+ * The job keeps running server-side. Default 30 minutes; `0` waits forever.
26
+ */
27
+ timeoutMs?: number;
28
+ /** Stop waiting early. The job keeps running server-side. */
29
+ signal?: AbortSignal;
30
+ /** Called with every polled task snapshot, including the final one. */
31
+ onPoll?: (task: TTask) => void;
32
+ }
33
+
34
+ export const DEFAULT_POLL_INTERVAL_MS = 3000;
35
+ export const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;
36
+ const FAST_START_WINDOW_MS = 10_000;
37
+ const FAST_START_INTERVAL_MS = 1000;
38
+
39
+ export function isTerminal(status: TaskStatus): boolean {
40
+ return status === 'completed' || status === 'failed';
41
+ }
42
+
43
+ function abortError(task_id: string): VidNavigatorError {
44
+ const err = new VidNavigatorError(`Stopped waiting for task ${task_id} (aborted); the job keeps running server-side`);
45
+ err.task_id = task_id;
46
+ return err;
47
+ }
48
+
49
+ function sleep(ms: number, task_id: string, signal?: AbortSignal): Promise<void> {
50
+ return new Promise((resolve, reject) => {
51
+ if (signal?.aborted) return reject(abortError(task_id));
52
+ const onAbort = () => {
53
+ clearTimeout(timer);
54
+ reject(abortError(task_id));
55
+ };
56
+ const timer = setTimeout(() => {
57
+ signal?.removeEventListener('abort', onAbort);
58
+ resolve();
59
+ }, ms);
60
+ signal?.addEventListener('abort', onAbort, { once: true });
61
+ });
62
+ }
63
+
64
+ /** Poll `fetchTask` until `task_status` is `completed` or `failed`, and return that final snapshot. */
65
+ export async function pollUntilDone<TTask extends PollableTask>(
66
+ task_id: string,
67
+ fetchTask: () => Promise<TTask>,
68
+ options: PollOptions<TTask> = {}
69
+ ): Promise<TTask> {
70
+ const intervalMs = options.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;
71
+ const fastStart = options.fastStart ?? true;
72
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
73
+ const started = Date.now();
74
+
75
+ let task = await withTaskId(task_id, fetchTask);
76
+ options.onPoll?.(task);
77
+ while (!isTerminal(task.task_status)) {
78
+ const elapsed = Date.now() - started;
79
+ const delay =
80
+ fastStart && elapsed < FAST_START_WINDOW_MS ? Math.min(FAST_START_INTERVAL_MS, intervalMs) : intervalMs;
81
+ if (timeoutMs > 0 && elapsed + delay > timeoutMs) {
82
+ throw new TaskTimeoutError(
83
+ `Task ${task_id} still ${task.task_status} after ${Math.round(elapsed / 1000)}s. ` +
84
+ `It keeps running server-side; resume it with this task_id (results are kept 1 hour after it finishes).`,
85
+ task_id
86
+ );
87
+ }
88
+ await sleep(delay, task_id, options.signal);
89
+ task = await withTaskId(task_id, fetchTask);
90
+ options.onPoll?.(task);
91
+ }
92
+ return task;
93
+ }
94
+
95
+ /** Run `fn`, tagging any SDK error it throws with `task_id` so the job can always be resumed. */
96
+ async function withTaskId<T>(task_id: string, fn: () => Promise<T>): Promise<T> {
97
+ try {
98
+ return await fn();
99
+ } catch (error) {
100
+ if (error instanceof VidNavigatorError && !error.task_id) error.task_id = task_id;
101
+ throw error;
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Build the error for a `failed` task from its `error` object (`error`, `message`, `http_status`),
107
+ * using the same class the API would have used for that status. Carries `task_id`.
108
+ */
109
+ export function errorFromFailedTask(task: PollableTask): VidNavigatorError {
110
+ const info = task.error;
111
+ let err: VidNavigatorError;
112
+ if (info?.http_status) {
113
+ err = buildApiError(info.http_status, {
114
+ error: info.error,
115
+ message: info.message ?? `Task ${task.task_id} failed`,
116
+ task_id: task.task_id,
117
+ });
118
+ } else {
119
+ const message = info?.message ?? 'no error details returned';
120
+ err = new VidNavigatorError(`Task ${task.task_id} failed: ${message}`, undefined, info?.error, info?.message, task);
121
+ }
122
+ err.task_id = task.task_id;
123
+ return err;
124
+ }
125
+
126
+ export interface JobInfo {
127
+ task_id: string;
128
+ job_type: string;
129
+ check_status_url?: string;
130
+ /** Where the result notification will be POSTed, or `null` when no webhook applies. */
131
+ webhook_url?: string | null;
132
+ expires_at?: string;
133
+ }
134
+
135
+ /**
136
+ * Handle to a submitted async job. Use it to run many jobs at once: submit them all, then
137
+ * `await job.result()` on each (or check `await job.status()` yourself).
138
+ *
139
+ * Polling always works, whether or not a webhook is configured.
140
+ */
141
+ export class Job<TTask extends PollableTask, TResult> {
142
+ readonly task_id: string;
143
+ readonly job_type: string;
144
+ readonly check_status_url?: string;
145
+ readonly webhook_url?: string | null;
146
+ readonly expires_at?: string;
147
+ /** Most recent task snapshot fetched by `status()`, `refresh()`, `wait()` or `result()`. */
148
+ task?: TTask;
149
+
150
+ private readonly fetchTask: () => Promise<TTask>;
151
+ private readonly toResult: (task: TTask) => Promise<TResult>;
152
+
153
+ constructor(
154
+ info: JobInfo,
155
+ fetchTask: () => Promise<TTask>,
156
+ toResult: (task: TTask) => Promise<TResult>
157
+ ) {
158
+ this.task_id = info.task_id;
159
+ this.job_type = info.job_type;
160
+ this.check_status_url = info.check_status_url;
161
+ this.webhook_url = info.webhook_url;
162
+ this.expires_at = info.expires_at;
163
+ this.fetchTask = async () => {
164
+ const task = await fetchTask();
165
+ this.task = task;
166
+ return task;
167
+ };
168
+ this.toResult = toResult;
169
+ }
170
+
171
+ /** Poll once and return the full task snapshot. */
172
+ async refresh(): Promise<TTask> {
173
+ return withTaskId(this.task_id, this.fetchTask);
174
+ }
175
+
176
+ /** Poll once and return the current `task_status`. */
177
+ async status(): Promise<TaskStatus> {
178
+ return (await this.refresh()).task_status;
179
+ }
180
+
181
+ /** Poll until the task is `completed` or `failed` and return the final snapshot. Does not throw on `failed`. */
182
+ async wait(options?: PollOptions<TTask>): Promise<TTask> {
183
+ return pollUntilDone(this.task_id, this.fetchTask, options);
184
+ }
185
+
186
+ /**
187
+ * Wait for the job and return its result. Throws the error from the task's `error` object when it
188
+ * failed, or {@link TaskTimeoutError} on timeout. Every error carries `task_id`.
189
+ */
190
+ async result(options?: PollOptions<TTask>): Promise<TResult> {
191
+ const task = await this.wait(options);
192
+ if (task.task_status === 'failed') throw errorFromFailedTask(task);
193
+ return withTaskId(this.task_id, () => this.toResult(task));
194
+ }
195
+ }
196
+
197
+ /**
198
+ * An async operation, callable as a blocking one-liner, with `.submit()` for a non-blocking
199
+ * {@link Job} handle and `.resume(task_id)` to reattach to a job you already submitted.
200
+ */
201
+ export interface JobOperation<TInput, TTask extends PollableTask, TResult> {
202
+ /** Submit, poll until finished, and return the result. */
203
+ (input: TInput, options?: RunOptions<TTask>): Promise<TResult>;
204
+ /** Submit and return a {@link Job} handle immediately. */
205
+ submit(input: TInput, options?: SubmitOptions): Promise<Job<TTask, TResult>>;
206
+ /** Reattach to a submitted job by `task_id` (e.g. from a {@link TaskTimeoutError}). Makes no request. */
207
+ resume(task_id: string, options?: SubmitOptions): Job<TTask, TResult>;
208
+ }
209
+
210
+ export interface SubmitOptions {
211
+ /** Attach a `usage` block to the result. Billing happens in the background, so usage is read when polling. */
212
+ include_usage?: boolean;
213
+ }
214
+
215
+ export type RunOptions<TTask = PollableTask> = SubmitOptions & PollOptions<TTask>;
@@ -0,0 +1,136 @@
1
+ import { UsageBlock } from './Usage';
2
+ import { VideoInfo, VideoInfoJSON } from './VideoInfo';
3
+
4
+ /** Async job kinds returned by the `/transcribe/async`, `/extract/video/async` and `/tweet/statement/async` endpoints. */
5
+ export type AsyncJobType = 'transcribe' | 'extract_video' | 'tweet_statement';
6
+
7
+ /** `processing` = accepted and being worked on. `completed` and `failed` are terminal. */
8
+ export type AsyncTaskStatus = 'processing' | 'completed' | 'failed';
9
+
10
+ /**
11
+ * Present when `task_status === 'failed'`. Carries the same `error` code and HTTP status
12
+ * the synchronous endpoint would have returned (e.g. `video_too_long` / 400).
13
+ */
14
+ export interface AsyncJobError {
15
+ error?: string;
16
+ message?: string;
17
+ http_status?: number;
18
+ }
19
+
20
+ /**
21
+ * Delivery state of a job's webhook. `null` when no webhook was configured.
22
+ * The webhook URL itself is never echoed back.
23
+ */
24
+ export interface AsyncJobWebhookStatus {
25
+ status?: 'pending' | 'delivered' | 'failed';
26
+ /** Delivery attempts made (max 5). */
27
+ attempts?: number;
28
+ /** HTTP status your endpoint returned on the last attempt. */
29
+ response_status?: number | null;
30
+ last_error?: string | null;
31
+ delivered_at?: string | null;
32
+ }
33
+
34
+ export interface AsyncJobAcceptedJSON {
35
+ task_id: string;
36
+ task_status: 'processing';
37
+ job_type?: AsyncJobType;
38
+ expires_at?: string;
39
+ check_status_url?: string;
40
+ webhook_url?: string | null;
41
+ message?: string;
42
+ docs_url?: string;
43
+ }
44
+
45
+ /** 202 response from an async submit endpoint. Poll with the matching `get...AsyncJob(task_id)` method. */
46
+ export class AsyncJobAccepted {
47
+ task_id: string;
48
+ task_status: 'processing';
49
+ job_type?: AsyncJobType;
50
+ /** Provisional submit-time bound; pushed out to finish time + 1 hour once the job completes. */
51
+ expires_at?: string;
52
+ /** Relative URL to poll for status and the result. */
53
+ check_status_url?: string;
54
+ /** The URL this job's result will be POSTed to, or `null` if no webhook applies. */
55
+ webhook_url?: string | null;
56
+ message?: string;
57
+ docs_url?: string;
58
+
59
+ constructor(data: AsyncJobAcceptedJSON) {
60
+ this.task_id = data.task_id;
61
+ this.task_status = data.task_status;
62
+ this.job_type = data.job_type;
63
+ this.expires_at = data.expires_at;
64
+ this.check_status_url = data.check_status_url;
65
+ this.webhook_url = data.webhook_url;
66
+ this.message = data.message;
67
+ this.docs_url = data.docs_url;
68
+ }
69
+
70
+ static fromJSON(json: AsyncJobAcceptedJSON): AsyncJobAccepted {
71
+ return new AsyncJobAccepted(json);
72
+ }
73
+ }
74
+
75
+ export interface AsyncJobJSON {
76
+ task_id: string;
77
+ task_status: AsyncTaskStatus;
78
+ job_type?: string;
79
+ request?: Record<string, unknown>;
80
+ created_at?: string;
81
+ started_at?: string | null;
82
+ completed_at?: string | null;
83
+ expires_at?: string;
84
+ check_status_url?: string;
85
+ webhook?: AsyncJobWebhookStatus | null;
86
+ result?: any;
87
+ /** `extract_video` jobs, once completed: the `video_info` the synchronous endpoint returns. */
88
+ video_info?: VideoInfoJSON;
89
+ error?: AsyncJobError | null;
90
+ }
91
+
92
+ /**
93
+ * State of an async job, returned by the `get...AsyncJob(task_id)` pollers.
94
+ * `result` is populated only when `task_status === 'completed'` and is parsed into the same
95
+ * shape the synchronous endpoint returns; `error` is populated only when `task_status === 'failed'`.
96
+ */
97
+ export class AsyncJob<TResult> {
98
+ task_id: string;
99
+ task_status: AsyncTaskStatus;
100
+ job_type?: string;
101
+ /** Echo of the submitted parameters (`webhook_url` is never echoed). */
102
+ request?: Record<string, unknown>;
103
+ created_at?: string;
104
+ started_at?: string | null;
105
+ completed_at?: string | null;
106
+ /** Results are deleted after this time (1 hour after the job finishes). */
107
+ expires_at?: string;
108
+ check_status_url?: string;
109
+ webhook?: AsyncJobWebhookStatus | null;
110
+ result: TResult | null;
111
+ /** `extract_video` jobs, once completed: metadata of the video the data was extracted from. */
112
+ video_info?: VideoInfo;
113
+ error: AsyncJobError | null;
114
+ /** Per-call usage, populated only when polled with `include_usage: true` and `task_status === 'completed'`. */
115
+ usage?: UsageBlock;
116
+
117
+ constructor(data: AsyncJobJSON, parseResult: (raw: any) => TResult) {
118
+ this.task_id = data.task_id;
119
+ this.task_status = data.task_status;
120
+ this.job_type = data.job_type;
121
+ this.request = data.request;
122
+ this.created_at = data.created_at;
123
+ this.started_at = data.started_at;
124
+ this.completed_at = data.completed_at;
125
+ this.expires_at = data.expires_at;
126
+ this.check_status_url = data.check_status_url;
127
+ this.webhook = data.webhook;
128
+ this.result = data.result !== undefined && data.result !== null ? parseResult(data.result) : null;
129
+ this.video_info = data.video_info ? VideoInfo.fromJSON(data.video_info) : undefined;
130
+ this.error = data.error ?? null;
131
+ }
132
+
133
+ static fromJSON<T>(json: AsyncJobJSON, parseResult: (raw: any) => T): AsyncJob<T> {
134
+ return new AsyncJob<T>(json, parseResult);
135
+ }
136
+ }