Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

5.1 KB
Raw Blame
/**
 * Fire a single backend policy run for one file and record it. Shared by the auto-run engine (which
 * dispatches file-producing policies and their chain) and the classification policy (which dispatches
 * its own AI escalation), so both take one bounded dispatch slot and record runs the same way.
 */

import { fileStorage } from "@editor/services/fileStorage";
import {
  runStoredPolicy,
  resolvePolicyRunTarget,
} from "@editor/services/policyApi";
import {
  acquireDispatchSlot,
  releaseDispatchSlot,
} from "@editor/components/policies/dispatchSemaphore";
import {
  markDispatched,
  recordRunStart,
} from "@editor/components/policies/policyRunStore";
import type { DispatchableFileId } from "@editor/components/policies/policyLocalPass";
import type { StirlingFile } from "@editor/types/fileContext";
import { extractErrorMessage } from "@editor/utils/toolErrorHandler";
import { generateId } from "@editor/utils/generateId";

/** Wait for an upload's bytes to land in IndexedDB (~5s): the stub surfaces in the
 *  file list before its bytes are committed, so an eager fetch would miss the file. */
const FILE_WAIT_TRIES = 20;
const FILE_WAIT_MS = 250;

const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

/** Dispatch a file and record the attempt, including request failures so required policies block it. */
export async function runPolicyOnFile(
  policyKey: string,
  backendId: string,
  // Branded, so a file whose classification is locked cannot be dispatched: the only
  // way to obtain one is dispatchableFileId(), which refuses locked stubs.
  fileId: DispatchableFileId,
  fileName: string,
  // Chained (downstream) dispatch — jumps the dispatch queue so a file mid-chain
  // finishes its flow before new files start (see acquireDispatchSlot).
  priority = false,
  externalOutput = false,
): Promise<void> {
  // A freshly-uploaded file's bytes are written to IndexedDB asynchronously, so
  // its stub can appear in the file list a beat before getStirlingFile resolves
  // it. Wait briefly rather than bail — and DON'T mark dispatched until we hold
  // the file, or a too-early miss would skip enforcement on that file forever.
  // (The caller's in-flight guard prevents double-dispatch during this wait.)
  // A transient IndexedDB error is treated as a miss (not a throw), so it retries
  // and then marks dispatched rather than rejecting into a hot re-dispatch loop.
  const tryGetFile = async (): Promise<StirlingFile | null> => {
    try {
      return await fileStorage.getStirlingFile(fileId);
    } catch {
      return null;
    }
  };
  let file = await tryGetFile();
  for (let i = 0; i < FILE_WAIT_TRIES && !file; i++) {
    await delay(FILE_WAIT_MS);
    file = await tryGetFile();
  }
  // Reinforces the branded parameter at the boundary: read from the persisted stub rather
  // than the caller's word, so an authoritative classification stays settled whichever
  // route reached here.
  const persisted = await fileStorage
    .getStirlingFileStub(fileId)
    .catch(() => null);
  if (persisted?.classificationLocked === true) return;
  if (!file) {
    // File genuinely gone (removed before it could run) — mark so we don't loop.
    markDispatched(policyKey, fileId);
    return;
  }
  await dispatchPolicyFile(
    policyKey,
    backendId,
    file,
    fileId,
    priority,
    externalOutput,
    fileName,
  );
}

/** Submit a copy; external delivery records activity without importing results into the editor. */
export async function dispatchPolicyFile(
  policyKey: string,
  backendId: string,
  file: File,
  fileId?: string,
  priority = false,
  externalOutput = false,
  fileName = file.name,
): Promise<void> {
  // Bounded upload window — see MAX_CONCURRENT_DISPATCHES. Only the POST is
  // gated; the IDB wait above never holds a slot.
  const target = resolvePolicyRunTarget();
  await acquireDispatchSlot(priority);
  const startedAt = Date.now();
  try {
    // Recorded against a document this browser can resolve. One file per run, which is the only
    // shape the server keeps a reference for.
    const runId = await runStoredPolicy(
      backendId,
      [file],
      fileId,
      "background",
    );
    // recordRunStart marks this (policy, file) dispatched as it records the run.
    recordRunStart({
      runId,
      policyKey,
      fileId: fileId ?? "",
      fileName,
      externalOutput,
      fileSize: file.size,
      target,
      status: "PENDING",
      outputs: [],
      error: null,
      startedAt,
    });
  } catch (err) {
    // No server run ID is available. The terminal local record blocks required-policy inputs
    // and exposes manual recovery without sending status polls for an invented server run.
    recordRunStart({
      runId: `dispatch-failed:${generateId()}`,
      policyKey,
      fileId: fileId ?? "",
      fileName,
      fileSize: file.size,
      target,
      externalOutput,
      status: "FAILED",
      outputs: [],
      error: extractErrorMessage(err),
      startedAt,
    });
    console.debug(
      `[PolicyAutoRun] Failed to dispatch policy ${policyKey} (${backendId}):`,
      err,
    );
  } finally {
    releaseDispatchSlot();
  }
}