Skip to content

The VS Code of video editing, built for agents.

TypeScript

Refactor API client and job handling logic

konstantin-pauluse4c4cdad4be8
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 1875d10f..0423a789 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -2,7 +2,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-import { createTRPCClient, httpBatchLink, httpSubscriptionLink, splitLink, TRPCClientError, type TRPCLink } from "@trpc/client";
+import { createTRPCClient, httpBatchLink, TRPCClientError, type TRPCLink } from "@trpc/client";
import { observable } from "@trpc/server/observable";
import { supabase } from "./supabase";
import { showUpgradeDialog } from "@/components/upgrade-dialog";
@@ -25,39 +25,17 @@ const paymentRequiredLink: TRPCLink<AppRouter> = () => ({ next, op }) =>
return () => sub.unsubscribe();
});
-const url = `${import.meta.env.VITE_API_URL ?? ""}/api/v2/trpc`;
-
-/** The Supabase session as an Authorization header value, or undefined when signed out. */
-async function authorization(): Promise<string | undefined> {
- const session = await supabase?.auth.getSession();
- const token = session?.data.session?.access_token;
- return token ? `Bearer ${token}` : undefined;
-}
-
-/**
- * The Diffusion Studio API (v2), authenticated with the Supabase session.
- * Subscriptions (`jobs.watch`) are server-sent events, which cannot carry
- * headers, so the token travels as a connection param there.
- */
+/** The Diffusion Studio API (v2), authenticated with the Supabase session. */
export const api = createTRPCClient<AppRouter>({
links: [
paymentRequiredLink,
- splitLink({
- condition: (op) => op.type === "subscription",
- true: httpSubscriptionLink({
- url,
- connectionParams: async () => {
- const value = await authorization();
- return value ? { authorization: value } : {};
- },
- }),
- false: httpBatchLink({
- url,
- async headers() {
- const value = await authorization();
- return value ? { Authorization: value } : {};
- },
- }),
+ httpBatchLink({
+ url: `${import.meta.env.VITE_API_URL ?? ""}/api/v2/trpc`,
+ async headers() {
+ const session = await supabase?.auth.getSession();
+ const token = session?.data.session?.access_token;
+ return token ? { Authorization: `Bearer ${token}` } : {};
+ },
}),
],
});
diff --git a/apps/web/src/lib/jobs.ts b/apps/web/src/lib/jobs.ts
index 8567ba73..083083c2 100644
--- a/apps/web/src/lib/jobs.ts
+++ b/apps/web/src/lib/jobs.ts
@@ -4,64 +4,49 @@
/**
* Generation jobs on the API: everything that produces a file is one
- * `generate` call that answers with a job right away, followed to its end
- * through `jobs.watch`. The stream closes when the job ends, and every few
- * minutes on the server's side regardless; reopening it hands back the
- * current state first, so a reconnect misses nothing.
+ * `generate` call that answers with a job right away, which is then polled
+ * (`jobs.get`) until it ends.
*/
import { api } from "./api";
import type { GenerateRequestInput, Job } from "@diffusionstudio/api-contract";
-/** How often a dropped watch is reopened before the job is given up on. */
-const MAX_RETRIES = 5;
-const RETRY_DELAY = 2000;
+/** How often a running job is asked for its state. */
+const POLL_INTERVAL = 1000;
+
+/** How many polls in a row may fail before the job is given up on. */
+const MAX_FAILURES = 5;
export const isTerminal = (job: Job): boolean =>
job.status === "succeeded" || job.status === "failed" || job.status === "canceled";
+const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
+
/**
* Starts a job for `request` and follows it to its end. `onUpdate` hears
- * every state the job passes through, the first one included. Resolves with
- * the job as it ended — failed and canceled jobs included, which say why in
+ * every state the job is seen in, the first one included. Resolves with the
+ * job as it ended — failed and canceled jobs included, which say why in
* `error`; rejects only when the job could not be started or followed.
*/
export async function runJob(request: GenerateRequestInput, onUpdate: (job: Job) => void): Promise<Job> {
- const job = await api.generate.mutate({ request, idempotencyKey: crypto.randomUUID() });
+ let job = await api.generate.mutate({ request, idempotencyKey: crypto.randomUUID() });
onUpdate(job);
- return isTerminal(job) ? job : watchJob(job.id, onUpdate);
-}
-
-/** Follows job `id` until it ends. */
-export function watchJob(id: string, onUpdate: (job: Job) => void): Promise<Job> {
- return new Promise((resolve, reject) => {
- let failures = 0;
- let ended = false;
-
- const subscribe = () => {
- const subscription = api.jobs.watch.subscribe({ id }, {
- onData: ({ data }) => {
- failures = 0;
- onUpdate(data);
- if (!isTerminal(data)) return;
- ended = true;
- subscription.unsubscribe();
- resolve(data);
- },
- onError: (error) => {
- if (++failures > MAX_RETRIES) reject(error);
- else setTimeout(subscribe, RETRY_DELAY * failures);
- },
- // The server closes the stream after a while; the job goes on.
- onComplete: () => {
- if (!ended) subscribe();
- },
- });
- };
- subscribe();
- });
+ let failures = 0;
+ while (!isTerminal(job)) {
+ await sleep(POLL_INTERVAL);
+ try {
+ job = await api.jobs.get.query({ id: job.id });
+ failures = 0;
+ onUpdate(job);
+ } catch (error) {
+ if (++failures >= MAX_FAILURES) {
+ throw error;
+ }
+ }
+ }
+ return job;
}
/** Why a job did not succeed, in a sentence for the user. */