openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
177 lines (176 loc) • 7.03 kB
JavaScript
import { t as hasNonEmptyString } from "./string-coerce-CCIiB4H7.mjs";
import { n as ignoreMissingPath } from "./errno-DFcoqIT9.mjs";
import { _ as resolveDeliveryQueueMediaDir } from "./paths-DAcAg5aV.mjs";
import { a as getOrLoadSqliteDatabaseAdmissionForPath } from "./sqlite-database-admission-DQIqro3d.mjs";
import { y as oldestDeliveryQueueMediaStageAdmission } from "./delivery-queue-sqlite.types-B7uW265Q.mjs";
import { a as generateSecureUuid } from "./secure-random-CW5OZnK1.mjs";
import { t as isPassThroughRemoteMediaSource } from "./media-source-url-DetR5dMr.mjs";
import { t as captureDeliveryQueueStateContext } from "./delivery-queue-state-context-Cxp-xMAQ.mjs";
import { l as executeDeliveryQueueOperation } from "./delivery-queue-sqlite-lyIJZlO0.mjs";
import { t as buildOutboundMediaLoadOptions } from "./load-options-DWp5hboI.mjs";
import { i as spoolRelativePath, n as collectEntrySpoolPaths, r as payloadMediaSources, t as ARTIFACT_NAME_RE } from "./delivery-queue-media-paths-Bhk9Ljz0.mjs";
import { n as loadWebMedia } from "./web-media-CX3Hvr6c.mjs";
import path from "node:path";
import fs from "node:fs/promises";
import { fileStore } from "@openclaw/fs-safe/store";
//#region src/infra/outbound/delivery-queue-media-staging.ts
async function createDeliveryQueueMediaRetention(e, t, n, r) {
const i = {
id: generateSecureUuid(),
enqueuedAt: Date.now()
};
return executeDeliveryQueueOperation(r, n, {
type: "deliveryQueue.createMediaRetention",
input: {
artifacts: [...e],
entryKind: t,
prepared: i
}
});
}
/** Release a stage or recovery lease after its owner settles. */
async function cancelDeliveryQueueMediaRetention(e, t, n) {
if (!e) return;
await executeDeliveryQueueOperation(n, t, {
type: "deliveryQueue.cancelMediaRetention",
input: { id: e }
});
}
/** Captures staging expiry and all media custody on the same connection. */
async function loadDeliveryQueueMediaRetentionSnapshot(e, t) {
return executeDeliveryQueueOperation(t, e.stateDir, {
type: "deliveryQueue.mediaRetentionSnapshot",
input: { expireBeforeMs: e.expireBeforeMs }
});
}
//#endregion
//#region src/infra/outbound/delivery-queue-media-spool.ts
const ARTIFACT_EXT_RE = /^\.[A-Za-z0-9]{1,10}$/;
const PART_SUFFIX = ".part";
const ORPHAN_GRACE_MS = 864e5;
function openSpoolStore(e, t) {
return fileStore({
rootDir: resolveDeliveryQueueMediaDir(e),
dirMode: 448,
mode: 384,
maxBytes: t
});
}
function resolveArtifactExtension(e) {
const t = path.extname(e.split("?")[0] ?? "");
return ARTIFACT_EXT_RE.test(t) ? t.toLowerCase() : "";
}
/** Remote and data sources carry their own bytes; only local paths need queue custody. */
function isSpoolableSource(e) {
return !isPassThroughRemoteMediaSource(e) && !/^data:/i.test(e);
}
/**
* Copies local media into queue custody and rewrites only the queue payloads.
* The same loader and capability as the live send authorize every source.
*/
async function stageQueuePayloadMedia(e, t) {
const n = t?.stateDir ?? e.stateDir;
if (e.payloads.some((e) => e.sensitiveMedia === true && payloadMediaSources(e).length > 0)) return {
status: "not-durable",
reason: "sensitive-media"
};
const r = path.resolve(resolveDeliveryQueueMediaDir(n));
const i = e.artifactFormat === "command-owner-v1" ? "c1-" : e.artifactFormat === "session-generation-v1" ? "g1-" : "";
const a = /* @__PURE__ */ new Map();
for (const t of e.payloads.flatMap(payloadMediaSources)) if (isSpoolableSource(t) && !a.has(t)) a.set(t, path.join(r, `${i}${generateSecureUuid()}${resolveArtifactExtension(t)}`));
const o = [...a.values()];
const s = o.length > 0 ? await createDeliveryQueueMediaRetention(o, "outbound-media-stage", n, t) : void 0;
const c = openSpoolStore(n, e.maxBytes);
const l = /* @__PURE__ */ new Set();
const stageSource = async (t) => {
const n = a.get(t);
if (!n) throw new Error(`Delivery queue media source was not planned: ${t}`);
if (l.has(t)) return n;
const r = await loadWebMedia(t, buildOutboundMediaLoadOptions({
maxBytes: e.maxBytes,
mediaAccess: e.mediaAccess,
mediaLocalRoots: e.mediaAccess?.localRoots,
mediaReadFile: e.mediaAccess?.readFile
}));
const i = path.basename(n);
const o = `${i}${PART_SUFFIX}`;
try {
await c.write(o, r.buffer, { maxBytes: e.maxBytes });
await (await c.root()).move(o, i, { overwrite: false });
l.add(t);
} catch (e) {
await c.remove(o).catch(() => void 0);
throw e;
}
return n;
};
const u = [];
try {
for (const t of e.payloads) {
if (!payloadMediaSources(t).some(isSpoolableSource)) {
u.push(t);
continue;
}
const e = { ...t };
if (hasNonEmptyString(t.mediaUrl) && isSpoolableSource(t.mediaUrl)) e.mediaUrl = await stageSource(t.mediaUrl);
if (t.mediaUrls) {
const n = [];
for (const e of t.mediaUrls) n.push(hasNonEmptyString(e) && isSpoolableSource(e) ? await stageSource(e) : e);
e.mediaUrls = n;
}
u.push(e);
}
} catch (e) {
await cancelDeliveryQueueMediaRetention(s, n, t);
await releaseSpoolArtifacts(o, n);
throw e;
}
return {
status: "staged",
payloads: u,
artifacts: o,
...s ? { mediaStageId: s } : {}
};
}
/** Discards spool artifacts whose durable row is already gone. Never throws. */
async function releaseSpoolArtifacts(e, t) {
for (const n of e) {
const e = spoolRelativePath(n, t);
if (e) try {
await openSpoolStore(t).remove(e);
} catch {}
}
}
/**
* Removes old unreferenced spool files. Pending-row references always win over
* age; the grace covers the stage-before-row-commit crash window and bounds all
* final and partial artifacts that never acquire a row.
*/
async function pruneOrphanedDeliveryQueueMedia(e, t) {
const n = t ?? captureDeliveryQueueStateContext(e?.stateDir);
const r = n.stateDir;
const i = (e?.nowMs ?? Date.now()) - ORPHAN_GRACE_MS;
const a = path.resolve(resolveDeliveryQueueMediaDir(r));
let o;
const loadRetainedPaths = async () => {
const e = await loadDeliveryQueueMediaRetentionSnapshot({ expireBeforeMs: i }, n);
o = new Set(e.stagedArtifacts.concat(e.payloads.flatMap((e) => collectEntrySpoolPaths(e, r))).map((e) => path.resolve(e)));
return o;
};
const s = await fs.readdir(a, { withFileTypes: true }).catch(ignoreMissingPath);
for (const e of s ?? []) {
if (!e.isFile() || !ARTIFACT_NAME_RE.test(e.name)) continue;
const t = path.join(a, e.name);
if (o?.has(t)) continue;
const n = await fs.stat(t).catch(ignoreMissingPath);
if (!n || n.mtimeMs > i) continue;
if ((o ?? await loadRetainedPaths()).has(t)) continue;
await releaseSpoolArtifacts([t], r);
}
if (!o) {
const e = getOrLoadSqliteDatabaseAdmissionForPath(n.workerContext.admission.databasePath, oldestDeliveryQueueMediaStageAdmission, () => void 0);
if (e === void 0 || e !== null && e <= i) await loadRetainedPaths();
}
}
//#endregion
export { createDeliveryQueueMediaRetention as a, cancelDeliveryQueueMediaRetention as i, releaseSpoolArtifacts as n, stageQueuePayloadMedia as r, pruneOrphanedDeliveryQueueMedia as t };