import { createTwoTierCache, type TwoTierCache } from "@toolctrl/shared-store"; import { getSharedStore } from "../shared-store.js"; import { apiLogger } from "../logger.js"; /** * Publisher-side handle to the subscription cache pub/sub channel. * * The API does NOT keep an L1 cache for subscriptions (every read goes * to Postgres via the legacy DB layer), so the only thing we need on * this side is the ability to PUBLISH an invalidation message that the * web replicas listen for. We piggyback on the two-tier cache helper — * its `invalidate(key)` lights up the same channel that the web * subscribers consume. * * Sym-coupled with apps/web/app/utils/services/.server/subscriptionCache.server.ts. * Namespace and channel MUST match: `subscription` / `invalidate`. */ const TTL_SECONDS = 60; // unused on this side; required by createTwoTierCache let publisherSingleton: TwoTierCache | null = null; function pubsubEnabled(): boolean { const raw = process.env.CACHE_INVALIDATION_ENABLED; if (raw === undefined || raw === null || raw === "") return true; return raw.toLowerCase() !== "false" && raw !== "0"; } function getPublisher(): TwoTierCache { if (publisherSingleton) return publisherSingleton; publisherSingleton = createTwoTierCache({ store: getSharedStore(), namespace: "subscription", ttlSeconds: TTL_SECONDS, pubsubEnabled: pubsubEnabled(), logger: { warn: (obj, msg) => apiLogger.warn(obj, msg), error: (obj, msg) => apiLogger.error(obj, msg) }, }); return publisherSingleton; } /** * Publish a subscription-invalidation for a single tenant. Resolves * once the PUBLISH has been issued; remote subscribers see the event * milliseconds later. Errors are returned (not thrown) so the caller * can swallow them and never block webhook delivery. */ export async function publishSubscriptionInvalidation(tenantId: string): Promise { if (!tenantId) return; await getPublisher().invalidate(tenantId); } /** Test seam: reset the singleton. */ export function __resetSubscriptionCachePublisherForTests(): void { publisherSingleton = null; }