@classytic/arc 2.46.0 → 2.47.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/dist/{EventTransport-DNgD9NP4.mjs → EventTransport-BHKy4_Bi.mjs} +4 -4
- package/dist/{HookSystem-DRbPzEcP.mjs → HookSystem-CAIDVoKC.mjs} +2 -2
- package/dist/{ResourceRegistry-Douk51fa.mjs → ResourceRegistry-23Ml6FNe.mjs} +2 -2
- package/dist/{acquire-RbtvDg9s.mjs → acquire-DoFX06fm.mjs} +1 -1
- package/dist/{actionPermissions-De0AJ7hm.mjs → actionPermissions-DXrlWHHK.mjs} +13 -13
- package/dist/audit/index.d.mts +1 -1
- package/dist/audit/index.mjs +4 -4
- package/dist/auth/audit.mjs +1 -1
- package/dist/auth/index.d.mts +1 -1
- package/dist/auth/index.mjs +7 -7
- package/dist/auth/redis-session.mjs +1 -1
- package/dist/{authorizationDecision-DeZMrHcm.mjs → authorizationDecision-DYiubkYw.mjs} +4 -4
- package/dist/{boundedMap-2WBh3gM9.mjs → boundedMap-CtdzpJ3X.mjs} +1 -1
- package/dist/{buildHandler-DxVOOBpw.mjs → buildHandler-CARdmPNo.mjs} +4 -4
- package/dist/cache/index.mjs +4 -4
- package/dist/{caching-BYRwYrUo.mjs → caching-QRiryDLs.mjs} +2 -2
- package/dist/{claimed-DYlELdnm.mjs → claimed-BLecr1j3.mjs} +1 -1
- package/dist/cleanup/index.d.mts +1 -1
- package/dist/cleanup/index.mjs +4 -4
- package/dist/cli/commands/describe.d.mts +1 -1
- package/dist/cli/commands/describe.mjs +3 -3
- package/dist/cli/commands/docs.mjs +3 -3
- package/dist/cli/commands/doctor.mjs +1 -1
- package/dist/cli/commands/generate.mjs +2 -2
- package/dist/cli/commands/init.mjs +2 -2
- package/dist/cli/commands/introspect.mjs +2 -2
- package/dist/cli/index.mjs +3 -3
- package/dist/{constants-CHZMUwBW.mjs → constants-Cx7BcnHT.mjs} +1 -1
- package/dist/context/index.mjs +5 -5
- package/dist/core/index.d.mts +2 -2
- package/dist/core/index.mjs +7 -7
- package/dist/{core-D9rS2BxO.mjs → core-0WyMuo0f.mjs} +3 -3
- package/dist/{createActionRouter-0qkCRzTL.mjs → createActionRouter-mLAGbpDV.mjs} +6 -6
- package/dist/{createAggregationRouter-CUf5Esd9.mjs → createAggregationRouter-BEAjn3dA.mjs} +7 -7
- package/dist/{createApp-DZIXfDKD.mjs → createApp-QDP4vYWH.mjs} +29 -29
- package/dist/{createMcpServer-DeVpqQF-.d.mts → createMcpServer-DzXHX0SO.d.mts} +1 -1
- package/dist/{defineAggregation-bmKQ4NmC.mjs → defineAggregation-CFNfvz-C.mjs} +1 -1
- package/dist/{defineResource-CGmdmGwh.mjs → defineResource-BROJmhzJ.mjs} +10 -8
- package/dist/discovery/index.mjs +1 -1
- package/dist/docs/index.d.mts +1 -1
- package/dist/docs/index.mjs +3 -3
- package/dist/{elevation-CzhqAyVN.mjs → elevation-DrXeEWWk.mjs} +5 -5
- package/dist/encryption/index.mjs +3 -3
- package/dist/{errorHandler-dFyGOEoB.mjs → errorHandler-BiBXtxj4.mjs} +3 -3
- package/dist/{errors-BY8vzlP4.mjs → errors-DnrUChAy.mjs} +1 -1
- package/dist/{eventPlugin-eMhAPtQA.mjs → eventPlugin-BhKLUe7H.mjs} +8 -8
- package/dist/{eventTypes-Do2KYeJx.mjs → eventTypes-CCIRGakw.mjs} +2 -2
- package/dist/events/index.d.mts +2 -2
- package/dist/events/index.mjs +8 -7
- package/dist/events/transports/redis-stream-entry.mjs +4 -4
- package/dist/events/transports/redis.mjs +2 -2
- package/dist/factory/index.d.mts +3 -3
- package/dist/factory/index.mjs +6 -6
- package/dist/{fastify-augmentation-Dtn0IIRn.d.mts → fastify-augmentation-bzkWPt1f.d.mts} +2 -2
- package/dist/{fields-LnbCcvsw.mjs → fields-CYdpcV73.mjs} +1 -1
- package/dist/{filter-merge-BAWi019Q.mjs → filter-merge-6kasezRH.mjs} +1 -1
- package/dist/{generate-oXoDnpJf.mjs → generate-DUkcbc4r.mjs} +2 -2
- package/dist/{headers-DBd3Qheo.mjs → headers-KxhrKevA.mjs} +2 -2
- package/dist/{health-BlJu9GXS.mjs → health-CRJg3IIq.mjs} +1 -1
- package/dist/{health-Dp-3EC9o.mjs → health-jkYNdobJ.mjs} +1 -1
- package/dist/hooks/index.d.mts +1 -1
- package/dist/hooks/index.mjs +2 -2
- package/dist/http-cache/index.d.mts +211 -0
- package/dist/http-cache/index.mjs +605 -0
- package/dist/http-cache/purgers/cloudflare.d.mts +13 -0
- package/dist/http-cache/purgers/cloudflare.mjs +46 -0
- package/dist/http-cache/purgers/fastly.d.mts +12 -0
- package/dist/http-cache/purgers/fastly.mjs +47 -0
- package/dist/http-cache/testing/index.d.mts +68 -0
- package/dist/http-cache/testing/index.mjs +168 -0
- package/dist/idempotency/index.mjs +8 -8
- package/dist/idempotency/redis.mjs +2 -2
- package/dist/{index-BTxzJ_MN.d.mts → index-BxZS-8So.d.mts} +2 -2
- package/dist/{index-DyJFTJLA.d.mts → index-Cy2-QffW.d.mts} +9 -0
- package/dist/{index-CUdaoCYt.d.mts → index-D1X_C_qz.d.mts} +2 -2
- package/dist/{index-Bqfo8hLz.d.mts → index-DFCCQ9AE.d.mts} +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +11 -11
- package/dist/{init-BOaNkLYb.mjs → init-CACwpktI.mjs} +1 -1
- package/dist/integrations/event-gateway.mjs +2 -2
- package/dist/integrations/index.d.mts +1 -1
- package/dist/integrations/index.mjs +1 -1
- package/dist/integrations/jobs/index.mjs +3 -3
- package/dist/integrations/mcp/index.d.mts +3 -3
- package/dist/integrations/mcp/index.mjs +2 -2
- package/dist/integrations/mcp/testing.d.mts +2 -2
- package/dist/integrations/mcp/testing.mjs +2 -2
- package/dist/integrations/streamline.mjs +3 -3
- package/dist/integrations/webhooks.d.mts +1 -1
- package/dist/integrations/webhooks.mjs +4 -3
- package/dist/integrations/websocket-pushref-redis.mjs +1 -1
- package/dist/integrations/websocket-redis.mjs +1 -1
- package/dist/integrations/websocket.mjs +2 -2
- package/dist/{jsonBody-DpRpKR_K.mjs → jsonBody-CzDBkCme.mjs} +2 -2
- package/dist/{keys-FBz6Ull-.mjs → keys-Cbwf6r1B.mjs} +1 -1
- package/dist/{loadResources-Bx1sKPnF.mjs → loadResources-Kr6vuljv.mjs} +3 -3
- package/dist/{loadResourcesFromEntry-b_jcqbxh.mjs → loadResourcesFromEntry-D2e0qoDR.mjs} +2 -2
- package/dist/logger/index.mjs +2 -2
- package/dist/{logger-CbFcIEBZ.mjs → logger-C110X5Yz.mjs} +1 -1
- package/dist/{mcpPlugin-yix548XX.mjs → mcpPlugin-4lIPr9OJ.mjs} +22 -22
- package/dist/{memory-Bgw5dn8N.mjs → memory-D9qkhXiB.mjs} +3 -3
- package/dist/{metrics-CZDQWVjS.mjs → metrics-B-qrrWfI.mjs} +3 -3
- package/dist/middleware/index.d.mts +1 -1
- package/dist/middleware/index.mjs +3 -3
- package/dist/migrations/index.mjs +2 -2
- package/dist/{module-Dsc_nKL5.mjs → module-BD8xHgrz.mjs} +1 -1
- package/dist/{multiTenant-XCxAUlru.d.mts → multiTenant-KZj8j1uJ.d.mts} +1 -1
- package/dist/{multipartBody-B85ek8Kj.mjs → multipartBody-qU7KCn1l.mjs} +1 -1
- package/dist/{observeSend-BK-JN1jK.mjs → observeSend-BnPtTotW.mjs} +1 -1
- package/dist/{openapi-Co7hl073.mjs → openapi-DoVa5SVP.mjs} +6 -6
- package/dist/outbox-admin/index.mjs +5 -5
- package/dist/{outbox-module-XvUThpqn.d.mts → outbox-module-5Mnwcycy.d.mts} +1 -1
- package/dist/outbox-module-DyITEIop.mjs +297 -0
- package/dist/permissions/index.mjs +7 -7
- package/dist/{permissions-A1oKtpiC.mjs → permissions-BBy4bOGi.mjs} +9 -9
- package/dist/{pipe-Czpw9U2n.mjs → pipe-BOm2o4UA.mjs} +2 -2
- package/dist/pipeline/index.d.mts +1 -1
- package/dist/pipeline/index.mjs +2 -2
- package/dist/{plan-KVseuBCL.mjs → plan-DDIGwuxr.mjs} +1 -1
- package/dist/{plugin-DTWt_8C3.mjs → plugin-Bn4D_0XK.mjs} +48 -24
- package/dist/plugins/index.d.mts +2 -2
- package/dist/plugins/index.mjs +17 -17
- package/dist/plugins/response-cache.mjs +4 -4
- package/dist/plugins/tracing-entry.mjs +2 -2
- package/dist/{pluralize-msB9X3yw.mjs → pluralize-ClEjcKlG.mjs} +1 -1
- package/dist/policy.types-DPqToKG1.d.mts +50 -0
- package/dist/presets/filesUpload.d.mts +1 -1
- package/dist/presets/filesUpload.mjs +5 -5
- package/dist/presets/index.d.mts +2 -2
- package/dist/presets/index.mjs +2 -2
- package/dist/presets/multiTenant.d.mts +1 -1
- package/dist/presets/multiTenant.mjs +5 -5
- package/dist/presets/search.d.mts +1 -1
- package/dist/presets/search.mjs +2 -2
- package/dist/{presets-qKCehiJM.mjs → presets-DK2jh5YR.mjs} +4 -4
- package/dist/{projection-ClBqtsIw.mjs → projection-BHH-sXyS.mjs} +2 -2
- package/dist/purger.types-2wNJK_89.mjs +24 -0
- package/dist/purger.types-DvPp4-yd.d.mts +26 -0
- package/dist/{queryCachePlugin-3gJj5Rbz.mjs → queryCachePlugin-Ckqe98AM.mjs} +6 -6
- package/dist/{rateLimitKey-Kro---xl.mjs → rateLimitKey-CWAjlqcN.mjs} +1 -1
- package/dist/{realtime-Ber8uJN2.mjs → realtime-BIJi9USY.mjs} +11 -11
- package/dist/registry/index.d.mts +2 -2
- package/dist/registry/index.mjs +3 -3
- package/dist/{registry-BA-_vFYk.mjs → registry-y9ZA-R_J.mjs} +2 -2
- package/dist/{outbox-module-mg9kDYkd.mjs → relay-BNrC1CEP.mjs} +5 -299
- package/dist/{renewingLease-CMY8YOcc.mjs → renewingLease-CS43br5E.mjs} +1 -1
- package/dist/{replyHelpers-DK9P_XSz.mjs → replyHelpers-oZDzakGb.mjs} +2 -2
- package/dist/{requestContext-GYO_0gEw.mjs → requestContext-fWb_YaV2.mjs} +1 -1
- package/dist/{requirement-DeNjZIH3.mjs → requirement--2hWyyHi.mjs} +1 -1
- package/dist/{resourceRateLimit-tHLbrtWc.mjs → resourceRateLimit-1WbcyMZY.mjs} +2 -2
- package/dist/{rolldown-runtime-Kv1fZdLg.mjs → rolldown-runtime-yH2lHMo_.mjs} +1 -1
- package/dist/{routeValidator-C_H5NanI.mjs → routeValidator-BSlRIA5c.mjs} +1 -1
- package/dist/{runtimeCapabilities-DWqbxkyw.mjs → runtimeCapabilities-CYCEtU1W.mjs} +1 -1
- package/dist/{schedules-eO_RzhCU.mjs → schedules-B5WGlYIT.mjs} +5 -5
- package/dist/{schemaConverter-DBJrPZN4.mjs → schemaConverter-DtNvts-6.mjs} +2 -2
- package/dist/{schemaIR-CEScKT2v.mjs → schemaIR-uS_RHqa3.mjs} +2 -2
- package/dist/schemas/index.mjs +1 -1
- package/dist/scim/index.mjs +2 -2
- package/dist/scope/index.mjs +5 -5
- package/dist/{scope-B-Sm9m_E.mjs → scope-BwVLSyNG.mjs} +4 -4
- package/dist/{shutdown-DzLFbe27.mjs → shutdown-BJiJN7FT.mjs} +1 -1
- package/dist/{simpleEqualityMatcher-DOJhwQ8g.mjs → simpleEqualityMatcher-DGRLq-1k.mjs} +1 -1
- package/dist/{sse-2972pVwV.mjs → sse-B_50llZu.mjs} +7 -7
- package/dist/{sseStream-AWLEeNV-.mjs → sseStream-BjSo9Ult.mjs} +2 -2
- package/dist/{store-helpers-VzjgVTkM.mjs → store-helpers-D-n5cwy5.mjs} +1 -1
- package/dist/{streaming-DvraWW6x.mjs → streaming-Dcgqa-hH.mjs} +1 -1
- package/dist/{subscriberIdentity-Bya56jsg.mjs → subscriberIdentity-C9KhIXTF.mjs} +1 -1
- package/dist/{tenancy-DSa_0hhw.mjs → tenancy-COrhjPRZ.mjs} +2 -2
- package/dist/{tenantPreparation-BrpkQre3.mjs → tenantPreparation-BElWHytd.mjs} +4 -4
- package/dist/testing/cleanupStoreContract.mjs +1 -1
- package/dist/testing/index.d.mts +3 -3
- package/dist/testing/index.mjs +11 -11
- package/dist/testing/outboxStoreContract.mjs +2 -2
- package/dist/testing/requiredPorts.mjs +2 -2
- package/dist/testing/storageContract.mjs +1 -1
- package/dist/{timing-6rQTuCwg.mjs → timing-CaxKbRk_.mjs} +1 -1
- package/dist/{transactionContext-DaxYUEgH.mjs → transactionContext-8qKON0Nk.mjs} +1 -1
- package/dist/{typeGuards-UKnX8wPX.mjs → typeGuards-DVjVSsXO.mjs} +1 -1
- package/dist/types/index.d.mts +1 -1
- package/dist/types/index.mjs +1 -1
- package/dist/types/storage.mjs +1 -1
- package/dist/{types-CuGjhn83.mjs → types-DZHqOuJE.mjs} +4 -4
- package/dist/{types-BYEb_dLW.d.mts → types-DeLiuaNv.d.mts} +1 -1
- package/dist/usage/index.mjs +4 -4
- package/dist/{userHelpers-oX5_mOVs.mjs → userHelpers-_eGj6kf0.mjs} +1 -1
- package/dist/utils/index.d.mts +1 -1
- package/dist/utils/index.mjs +12 -12
- package/dist/{utils-CjjGOT4E.mjs → utils-Dd6MWpye.mjs} +5 -5
- package/dist/{validate-4RlTKOJb.mjs → validate-BaF5wd0x.mjs} +3 -3
- package/dist/{versioning-Dk2-19La.mjs → versioning-DyV7mwtK.mjs} +3 -3
- package/dist/{workScope-DoBsoVo4.mjs → workScope-CmCBUmPR.mjs} +2 -2
- package/package.json +48 -20
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
/*! @classytic/arc v2.47.0 | MIT | https://classytic.com */
|
|
2
|
+
import { t as hasEvents } from "../typeGuards-DVjVSsXO.mjs";
|
|
3
|
+
import { n as chunkTags, t as CachePurgeError } from "../purger.types-2wNJK_89.mjs";
|
|
4
|
+
import { r as exponentialBackoff, t as EventOutbox } from "../relay-BNrC1CEP.mjs";
|
|
5
|
+
import fp from "fastify-plugin";
|
|
6
|
+
import { createEvent } from "@classytic/primitives/events";
|
|
7
|
+
// src/http-cache/invalidation/delivery.ts
|
|
8
|
+
/** In-process delivery: one purger call per batch. A failure is reported and the batch is dropped. */
|
|
9
|
+
function batchedDelivery() {
|
|
10
|
+
let ctx;
|
|
11
|
+
return {
|
|
12
|
+
kind: "batched",
|
|
13
|
+
start(c) {
|
|
14
|
+
ctx = c;
|
|
15
|
+
},
|
|
16
|
+
async deliver(batch) {
|
|
17
|
+
if (!ctx) throw new Error("[arc] httpCache delivery used before start");
|
|
18
|
+
await ctx.purger.purgeTags(batch.tags, { mode: batch.mode });
|
|
19
|
+
},
|
|
20
|
+
drain: async () => {},
|
|
21
|
+
stop: async () => {}
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** A tag every major CDN accepts: printable ASCII, no space or comma, at most 1,024 characters; de-duplicated. */
|
|
25
|
+
function normalizeTags(tags) {
|
|
26
|
+
if (!tags) return [];
|
|
27
|
+
const out = /* @__PURE__ */ new Set();
|
|
28
|
+
for (const raw of tags) {
|
|
29
|
+
if (typeof raw !== "string") continue;
|
|
30
|
+
const tag = raw.trim();
|
|
31
|
+
if (!tag || tag.length > 1024 || !/^[\x21-\x7e]+$/.test(tag) || tag.includes(",")) continue;
|
|
32
|
+
out.add(tag);
|
|
33
|
+
}
|
|
34
|
+
return [...out];
|
|
35
|
+
}
|
|
36
|
+
/** `<resource>` and `<resource>:<id>`: the convention responses carry and purges target. */
|
|
37
|
+
function resourceTags(resource, id) {
|
|
38
|
+
return id === void 0 || id === null || id === "" ? [resource] : [resource, `${resource}:${String(id)}`];
|
|
39
|
+
}
|
|
40
|
+
/** The document inside a CRUD reply, enveloped (`{ data }`) or bare. */
|
|
41
|
+
function documentOf(body) {
|
|
42
|
+
if (body && typeof body === "object" && "data" in body) return body.data;
|
|
43
|
+
return body;
|
|
44
|
+
}
|
|
45
|
+
/** Every tag a response carries: derived from its resource, then the policy's own. */
|
|
46
|
+
function responseTags(policy, request, body) {
|
|
47
|
+
const tags = [];
|
|
48
|
+
const resource = policy.resource;
|
|
49
|
+
if (resource) {
|
|
50
|
+
const id = resource.op === "get" ? request.params?.id : void 0;
|
|
51
|
+
tags.push(...resourceTags(resource.name, id));
|
|
52
|
+
if (resource.op === "get" && resource.extra) tags.push(...resource.extra(documentOf(body)) ?? []);
|
|
53
|
+
}
|
|
54
|
+
if (policy.tags) tags.push(...typeof policy.tags === "function" ? policy.tags(request, body) ?? [] : policy.tags);
|
|
55
|
+
return normalizeTags(tags);
|
|
56
|
+
}
|
|
57
|
+
/** Join tags under the header cap; reports how many were dropped. */
|
|
58
|
+
function tagHeaderValue(tags, separator) {
|
|
59
|
+
let value = "";
|
|
60
|
+
for (let i = 0; i < tags.length; i++) {
|
|
61
|
+
const next = value ? `${value}${separator}${tags[i]}` : tags[i];
|
|
62
|
+
if (next.length > 16e3) return {
|
|
63
|
+
value,
|
|
64
|
+
dropped: tags.length - i
|
|
65
|
+
};
|
|
66
|
+
value = next;
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
value,
|
|
70
|
+
dropped: 0
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
// src/http-cache/invalidation/invalidator.ts
|
|
74
|
+
/**
|
|
75
|
+
* Queues tags, de-duplicates them per window, and delivers one batch per mode, split to the purger's
|
|
76
|
+
* per-call limit. A tag queued hard and soft in one window is purged hard. Never throws to a caller.
|
|
77
|
+
*/
|
|
78
|
+
function createInvalidator(opts) {
|
|
79
|
+
const queued = {
|
|
80
|
+
hard: /* @__PURE__ */ new Set(),
|
|
81
|
+
soft: /* @__PURE__ */ new Set()
|
|
82
|
+
};
|
|
83
|
+
let timer;
|
|
84
|
+
let chain = Promise.resolve();
|
|
85
|
+
const softCapable = opts.purger.capabilities?.softPurge === true;
|
|
86
|
+
async function send(batch) {
|
|
87
|
+
const started = Date.now();
|
|
88
|
+
try {
|
|
89
|
+
await opts.delivery.deliver(batch);
|
|
90
|
+
if (opts.delivery.kind === "durable") opts.enqueued(batch, Date.now() - started);
|
|
91
|
+
else opts.report(batch, "sent", Date.now() - started);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
opts.report(batch, "failed", Date.now() - started, error);
|
|
94
|
+
opts.log.error({
|
|
95
|
+
err: error,
|
|
96
|
+
tags: batch.tags,
|
|
97
|
+
mode: batch.mode,
|
|
98
|
+
delivery: opts.delivery.kind
|
|
99
|
+
}, opts.delivery.kind === "durable" ? "httpCache: could not persist an invalidation; content stays cached until its TTL" : "httpCache: purge failed; content stays cached until its TTL");
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function flush() {
|
|
103
|
+
if (timer) {
|
|
104
|
+
clearTimeout(timer);
|
|
105
|
+
timer = void 0;
|
|
106
|
+
}
|
|
107
|
+
const hard = [...queued.hard];
|
|
108
|
+
const soft = [...queued.soft].filter((t) => !queued.hard.has(t));
|
|
109
|
+
queued.hard.clear();
|
|
110
|
+
queued.soft.clear();
|
|
111
|
+
const batches = [];
|
|
112
|
+
const groups = softCapable ? [["hard", hard], ["soft", soft]] : [["hard", [...hard, ...soft]]];
|
|
113
|
+
for (const [mode, tags] of groups) for (const chunk of chunkTags(tags, opts.purger.capabilities?.maxTagsPerCall)) if (chunk.length) batches.push({
|
|
114
|
+
tags: chunk,
|
|
115
|
+
mode
|
|
116
|
+
});
|
|
117
|
+
chain = chain.then(async () => {
|
|
118
|
+
for (const batch of batches) await send(batch);
|
|
119
|
+
await opts.delivery.drain();
|
|
120
|
+
});
|
|
121
|
+
return chain;
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
invalidate(input, mode = "hard") {
|
|
125
|
+
const tags = normalizeTags(typeof input === "string" ? [input] : input);
|
|
126
|
+
if (!tags.length) return;
|
|
127
|
+
for (const tag of tags) queued[mode].add(tag);
|
|
128
|
+
if (!timer) {
|
|
129
|
+
timer = setTimeout(() => void flush(), opts.windowMs);
|
|
130
|
+
timer.unref?.();
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
flush,
|
|
134
|
+
pending: () => [.../* @__PURE__ */ new Set([...queued.hard, ...queued.soft])]
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
// src/http-cache/invalidation/sources.ts
|
|
138
|
+
const SUFFIX_MODE = {
|
|
139
|
+
created: "soft",
|
|
140
|
+
updated: "soft",
|
|
141
|
+
deleted: "hard"
|
|
142
|
+
};
|
|
143
|
+
/**
|
|
144
|
+
* The tags a CRUD event invalidates for a cached resource: `<resource>` (its lists) and `<resource>:<id>`,
|
|
145
|
+
* plus the resource's extra tags for the document. Updates and creates purge soft (stale copy served while
|
|
146
|
+
* one request refreshes); deletes purge hard.
|
|
147
|
+
*/
|
|
148
|
+
function tagsForCrudEvent(event, resources) {
|
|
149
|
+
const dot = event.type.lastIndexOf(".");
|
|
150
|
+
if (dot === -1) return void 0;
|
|
151
|
+
const mode = SUFFIX_MODE[event.type.slice(dot + 1)];
|
|
152
|
+
if (!mode) return void 0;
|
|
153
|
+
const meta = event.meta;
|
|
154
|
+
const qualified = typeof meta.resource === "string" ? meta.resource : event.type.slice(0, dot);
|
|
155
|
+
const bare = qualified.includes(":") ? qualified.slice(qualified.lastIndexOf(":") + 1) : qualified;
|
|
156
|
+
const name = resources.has(qualified) ? qualified : resources.has(bare) ? bare : void 0;
|
|
157
|
+
if (!name) return void 0;
|
|
158
|
+
const tags = resourceTags(name, meta.resourceId);
|
|
159
|
+
const extra = resources.get(name)?.extra;
|
|
160
|
+
if (extra) tags.push(...extra(event.payload?.data) ?? []);
|
|
161
|
+
return {
|
|
162
|
+
tags,
|
|
163
|
+
mode
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/** Subscribe the invalidator to resource CRUD events (automatic) and to explicit `purgeOn` patterns. */
|
|
167
|
+
async function wireInvalidationSources(fastify, opts) {
|
|
168
|
+
const wantsAuto = opts.autoPurge && opts.resources.size > 0;
|
|
169
|
+
const explicit = Object.entries(opts.purgeOn ?? {});
|
|
170
|
+
if (!wantsAuto && !explicit.length) return [];
|
|
171
|
+
if (!hasEvents(fastify)) {
|
|
172
|
+
if (explicit.length) throw new Error("[arc] httpCache.purgeOn needs the events plugin registered before httpCache");
|
|
173
|
+
fastify.log.warn({ resources: [...opts.resources.keys()] }, "httpCache: resources declare httpCache but the events plugin is absent; writes will not purge, entries expire at their TTL");
|
|
174
|
+
return [];
|
|
175
|
+
}
|
|
176
|
+
const off = [];
|
|
177
|
+
if (wantsAuto) off.push(await fastify.events.subscribe("*", async (event) => {
|
|
178
|
+
const hit = tagsForCrudEvent(event, opts.resources);
|
|
179
|
+
if (hit) opts.invalidator.invalidate(hit.tags, hit.mode);
|
|
180
|
+
}));
|
|
181
|
+
for (const [pattern, toTags] of explicit) off.push(await fastify.events.subscribe(pattern, async (event) => {
|
|
182
|
+
const out = toTags(event);
|
|
183
|
+
if (!out) return;
|
|
184
|
+
if (Array.isArray(out)) opts.invalidator.invalidate(out, "hard");
|
|
185
|
+
else {
|
|
186
|
+
const chosen = out;
|
|
187
|
+
opts.invalidator.invalidate(chosen.tags, chosen.mode);
|
|
188
|
+
}
|
|
189
|
+
}));
|
|
190
|
+
return off;
|
|
191
|
+
}
|
|
192
|
+
// src/http-cache/observability.ts
|
|
193
|
+
const reasonKind = (reason) => reason.includes(":") ? reason.slice(0, reason.indexOf(":")) : reason;
|
|
194
|
+
function createStats() {
|
|
195
|
+
const stats = {
|
|
196
|
+
responses: {
|
|
197
|
+
public: 0,
|
|
198
|
+
private: {
|
|
199
|
+
header: 0,
|
|
200
|
+
cookie: 0,
|
|
201
|
+
scope: 0,
|
|
202
|
+
classifier: 0,
|
|
203
|
+
status: 0,
|
|
204
|
+
"set-cookie": 0
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
purges: {
|
|
208
|
+
enqueued: 0,
|
|
209
|
+
sent: 0,
|
|
210
|
+
failed: 0,
|
|
211
|
+
tags: 0
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
return {
|
|
215
|
+
decision(cacheable, reason) {
|
|
216
|
+
if (cacheable) stats.responses.public++;
|
|
217
|
+
else if (reason) stats.responses.private[reasonKind(reason)]++;
|
|
218
|
+
},
|
|
219
|
+
purge(event) {
|
|
220
|
+
stats.purges[event.outcome]++;
|
|
221
|
+
if (event.outcome !== "failed") stats.purges.tags += event.tags.length;
|
|
222
|
+
},
|
|
223
|
+
snapshot(pending) {
|
|
224
|
+
return {
|
|
225
|
+
responses: {
|
|
226
|
+
public: stats.responses.public,
|
|
227
|
+
private: { ...stats.responses.private }
|
|
228
|
+
},
|
|
229
|
+
purges: { ...stats.purges },
|
|
230
|
+
pending
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
// src/http-cache/policy/cache-key.ts
|
|
236
|
+
/** Query parameters that never change a response: marketing and click identifiers. */
|
|
237
|
+
const DEFAULT_IGNORED_QUERY = [
|
|
238
|
+
"utm_*",
|
|
239
|
+
"fbclid",
|
|
240
|
+
"gclid",
|
|
241
|
+
"msclkid",
|
|
242
|
+
"mc_cid",
|
|
243
|
+
"mc_eid",
|
|
244
|
+
"_ga"
|
|
245
|
+
];
|
|
246
|
+
function ignored(name, patterns) {
|
|
247
|
+
return patterns.some((p) => p.endsWith("*") ? name.startsWith(p.slice(0, -1)) : name === p);
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* The one URL a response is cached under: tracking parameters dropped, the rest sorted. Equal content,
|
|
251
|
+
* equal key, so a CDN stores one copy instead of one per campaign link.
|
|
252
|
+
*/
|
|
253
|
+
function canonicalUrl(url, opts = {}) {
|
|
254
|
+
const q = url.indexOf("?");
|
|
255
|
+
if (q === -1) return url;
|
|
256
|
+
const path = url.slice(0, q);
|
|
257
|
+
const patterns = opts.ignore ?? DEFAULT_IGNORED_QUERY;
|
|
258
|
+
const kept = [...new URLSearchParams(url.slice(q + 1)).entries()].filter(([name]) => !ignored(name, patterns));
|
|
259
|
+
if (opts.sort !== false) kept.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
|
|
260
|
+
const query = new URLSearchParams(kept).toString();
|
|
261
|
+
return query ? `${path}?${query}` : path;
|
|
262
|
+
}
|
|
263
|
+
// src/http-cache/policy/directives.ts
|
|
264
|
+
const seconds = (n) => Math.max(0, Math.floor(n ?? 0));
|
|
265
|
+
/** Headers for a reply a shared cache may store. One function, so every tier reads one decision. */
|
|
266
|
+
function publicHeaders(policy, opts = {}) {
|
|
267
|
+
const cdn = seconds(policy.cdn);
|
|
268
|
+
const browser = ["public", `max-age=${seconds(policy.browser)}`];
|
|
269
|
+
if (opts.sMaxAge !== false) browser.push(`s-maxage=${cdn}`);
|
|
270
|
+
if (policy.staleIfError) browser.push(`stale-if-error=${seconds(policy.staleIfError)}`);
|
|
271
|
+
const headers = { "cache-control": browser.join(", ") };
|
|
272
|
+
if (opts.cdnCacheControl !== false) {
|
|
273
|
+
const edge = [`max-age=${cdn}`];
|
|
274
|
+
if (policy.staleWhileRevalidate) edge.push(`stale-while-revalidate=${seconds(policy.staleWhileRevalidate)}`);
|
|
275
|
+
if (policy.staleIfError) edge.push(`stale-if-error=${seconds(policy.staleIfError)}`);
|
|
276
|
+
headers["cdn-cache-control"] = edge.join(", ");
|
|
277
|
+
}
|
|
278
|
+
return headers;
|
|
279
|
+
}
|
|
280
|
+
/** Headers for a reply no shared cache may store. */
|
|
281
|
+
function privateHeaders(reason) {
|
|
282
|
+
return reason === "status" ? { "cache-control": "no-store" } : { "cache-control": "private, no-store" };
|
|
283
|
+
}
|
|
284
|
+
/** A policy that cannot be honoured fails at registration, never on a request. */
|
|
285
|
+
function assertPolicy(policy, where) {
|
|
286
|
+
if (typeof policy.cdn !== "number" || !Number.isFinite(policy.cdn) || policy.cdn <= 0) throw new Error(`[arc] httpCache ${where}: cdn must be a positive number of seconds`);
|
|
287
|
+
for (const key of [
|
|
288
|
+
"browser",
|
|
289
|
+
"staleWhileRevalidate",
|
|
290
|
+
"staleIfError"
|
|
291
|
+
]) {
|
|
292
|
+
const n = policy[key];
|
|
293
|
+
if (n !== void 0 && (typeof n !== "number" || !Number.isFinite(n) || n < 0)) throw new Error(`[arc] httpCache ${where}: ${key} must be zero or more seconds`);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
// src/http-cache/policy/privacy.ts
|
|
297
|
+
const DEFAULT_PRIVATE_HEADERS = [
|
|
298
|
+
"authorization",
|
|
299
|
+
"x-api-key",
|
|
300
|
+
"x-organization-id"
|
|
301
|
+
];
|
|
302
|
+
function cookieNames(header) {
|
|
303
|
+
if (!header) return [];
|
|
304
|
+
return (Array.isArray(header) ? header.join(";") : header).split(";").map((part) => part.split("=")[0]?.trim() ?? "").filter(Boolean);
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Private when ANY signal of a caller is present: a credential header, a cookie outside the allowlist, a
|
|
308
|
+
* non-public arc scope, or the host's classifier. Reasons name the signal, never its value.
|
|
309
|
+
*/
|
|
310
|
+
function classifyPrivacy(request, opts = {}) {
|
|
311
|
+
const headers = request.headers;
|
|
312
|
+
for (const name of opts.privateHeaders ?? DEFAULT_PRIVATE_HEADERS) {
|
|
313
|
+
const key = name.toLowerCase();
|
|
314
|
+
if (headers[key] !== void 0) return {
|
|
315
|
+
private: true,
|
|
316
|
+
reason: `header:${key}`
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
const allowed = new Set(opts.publicCookies ?? []);
|
|
320
|
+
const cookie = cookieNames(headers.cookie).find((name) => !allowed.has(name));
|
|
321
|
+
if (cookie) return {
|
|
322
|
+
private: true,
|
|
323
|
+
reason: `cookie:${cookie}`
|
|
324
|
+
};
|
|
325
|
+
const scope = request.scope;
|
|
326
|
+
if (scope?.kind !== void 0 && scope.kind !== "public") return {
|
|
327
|
+
private: true,
|
|
328
|
+
reason: `scope:${scope.kind}`
|
|
329
|
+
};
|
|
330
|
+
if (opts.classify && !opts.classify(request)) return {
|
|
331
|
+
private: true,
|
|
332
|
+
reason: "classifier"
|
|
333
|
+
};
|
|
334
|
+
return { private: false };
|
|
335
|
+
}
|
|
336
|
+
// src/http-cache/purgers/basic.ts
|
|
337
|
+
/** Purges nothing: the default for development and tests. */
|
|
338
|
+
const noopPurger = {
|
|
339
|
+
name: "noop",
|
|
340
|
+
purgeTags: async () => {}
|
|
341
|
+
};
|
|
342
|
+
/** Records every call: assert purges in tests without a CDN. */
|
|
343
|
+
function createMemoryPurger(capabilities) {
|
|
344
|
+
const calls = [];
|
|
345
|
+
return {
|
|
346
|
+
purger: {
|
|
347
|
+
name: "memory",
|
|
348
|
+
...capabilities ? { capabilities } : {},
|
|
349
|
+
purgeTags: async (tags, { mode }) => {
|
|
350
|
+
calls.push({
|
|
351
|
+
tags: [...tags],
|
|
352
|
+
mode
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
},
|
|
356
|
+
calls
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Purge several tiers at once (CDN + in-process + a second CDN). Each child gets its own chunking and
|
|
361
|
+
* soft-purge support; all are attempted, and any failure rejects with every error.
|
|
362
|
+
*/
|
|
363
|
+
function composePurgers(...purgers) {
|
|
364
|
+
if (!purgers.length) throw new Error("[arc] composePurgers needs at least one purger");
|
|
365
|
+
return {
|
|
366
|
+
name: `compose(${purgers.map((p) => p.name).join(",")})`,
|
|
367
|
+
capabilities: { softPurge: true },
|
|
368
|
+
async purgeTags(tags, { mode }) {
|
|
369
|
+
const errors = (await Promise.allSettled(purgers.map(async (p) => {
|
|
370
|
+
const childMode = mode === "soft" && p.capabilities?.softPurge ? "soft" : "hard";
|
|
371
|
+
for (const chunk of chunkTags(tags, p.capabilities?.maxTagsPerCall)) await p.purgeTags(chunk, { mode: childMode });
|
|
372
|
+
}))).flatMap((r) => r.status === "rejected" ? [r.reason] : []);
|
|
373
|
+
if (errors.length) throw new AggregateError(errors, `${errors.length} of ${purgers.length} purgers failed`);
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
// src/http-cache/enforce/http-cache.plugin.ts
|
|
378
|
+
const kBody = Symbol("arc.httpCache.body");
|
|
379
|
+
const kSkip = Symbol("arc.httpCache.skip");
|
|
380
|
+
const httpCachePluginImpl = async (fastify, opts = {}) => {
|
|
381
|
+
const purger = opts.purger ?? noopPurger;
|
|
382
|
+
const delivery = opts.delivery ?? batchedDelivery();
|
|
383
|
+
const rules = opts.rules ?? [];
|
|
384
|
+
rules.forEach((rule, i) => {
|
|
385
|
+
if (!rule.match.startsWith("/")) throw new Error(`[arc] httpCache rules[${i}]: match must start with '/'`);
|
|
386
|
+
assertPolicy(rule, `rules[${i}]`);
|
|
387
|
+
});
|
|
388
|
+
if (opts.cors && !/^https?:\/\/[^/]+$/.test(opts.cors.origin)) throw new Error("[arc] httpCache cors.origin must be a scheme and host, e.g. https://shop.example.com");
|
|
389
|
+
const tagHeader = opts.tagHeader ?? {
|
|
390
|
+
name: "Cache-Tag",
|
|
391
|
+
separator: ","
|
|
392
|
+
};
|
|
393
|
+
const stats = createStats();
|
|
394
|
+
const observer = opts.observer;
|
|
395
|
+
const resources = /* @__PURE__ */ new Map();
|
|
396
|
+
const report = (batch, outcome, durationMs, error) => {
|
|
397
|
+
const event = {
|
|
398
|
+
tags: batch.tags,
|
|
399
|
+
mode: batch.mode,
|
|
400
|
+
delivery: delivery.kind,
|
|
401
|
+
outcome,
|
|
402
|
+
durationMs,
|
|
403
|
+
error
|
|
404
|
+
};
|
|
405
|
+
stats.purge(event);
|
|
406
|
+
observer?.onPurge?.(event);
|
|
407
|
+
};
|
|
408
|
+
const invalidator = createInvalidator({
|
|
409
|
+
purger,
|
|
410
|
+
delivery,
|
|
411
|
+
windowMs: opts.batchWindowMs ?? 100,
|
|
412
|
+
report,
|
|
413
|
+
enqueued: (batch, durationMs) => {
|
|
414
|
+
const event = {
|
|
415
|
+
tags: batch.tags,
|
|
416
|
+
mode: batch.mode,
|
|
417
|
+
delivery: delivery.kind,
|
|
418
|
+
outcome: "enqueued",
|
|
419
|
+
durationMs
|
|
420
|
+
};
|
|
421
|
+
stats.purge(event);
|
|
422
|
+
observer?.onPurge?.(event);
|
|
423
|
+
},
|
|
424
|
+
log: fastify.log
|
|
425
|
+
});
|
|
426
|
+
await delivery.start({
|
|
427
|
+
purger,
|
|
428
|
+
report,
|
|
429
|
+
log: fastify.log
|
|
430
|
+
});
|
|
431
|
+
fastify.decorateRequest(kBody, null);
|
|
432
|
+
fastify.decorateRequest(kSkip, false);
|
|
433
|
+
fastify.addHook("onRoute", (route) => {
|
|
434
|
+
const policy = route.config?.httpCache;
|
|
435
|
+
if (!policy) return;
|
|
436
|
+
assertPolicy(policy, `on ${String(route.method)} ${route.url}`);
|
|
437
|
+
if (policy.resource) resources.set(policy.resource.name, { ...policy.resource.extra ? { extra: policy.resource.extra } : {} });
|
|
438
|
+
});
|
|
439
|
+
const policyFor = (request) => {
|
|
440
|
+
if (request.method !== "GET" && request.method !== "HEAD") return void 0;
|
|
441
|
+
const own = (request.routeOptions?.config)?.httpCache;
|
|
442
|
+
if (own) return own;
|
|
443
|
+
const path = request.url.split("?")[0] ?? request.url;
|
|
444
|
+
return rules.find((rule) => path.startsWith(rule.match));
|
|
445
|
+
};
|
|
446
|
+
if (opts.canonicalQuery) {
|
|
447
|
+
const canonical = opts.canonicalQuery;
|
|
448
|
+
fastify.addHook("onRequest", (request, reply, done) => {
|
|
449
|
+
if (!policyFor(request)) return done();
|
|
450
|
+
const target = canonicalUrl(request.url, canonical);
|
|
451
|
+
if (target === request.url) return done();
|
|
452
|
+
request[kSkip] = true;
|
|
453
|
+
reply.code(301).header("location", target).header("cache-control", "public, max-age=3600").send();
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
fastify.addHook("preSerialization", (request, _reply, payload, done) => {
|
|
457
|
+
request[kBody] = payload;
|
|
458
|
+
done(null, payload);
|
|
459
|
+
});
|
|
460
|
+
fastify.addHook("onSend", (request, reply, payload, done) => {
|
|
461
|
+
if (request[kSkip]) return done(null, payload);
|
|
462
|
+
const policy = policyFor(request);
|
|
463
|
+
if (!policy) return done(null, payload);
|
|
464
|
+
const privacy = classifyPrivacy(request, opts.privacy);
|
|
465
|
+
let reason;
|
|
466
|
+
if (privacy.private) reason = privacy.reason;
|
|
467
|
+
else if (reply.statusCode < 200 || reply.statusCode >= 300) reason = "status";
|
|
468
|
+
else if (reply.hasHeader("set-cookie")) reason = "set-cookie";
|
|
469
|
+
if (reason) {
|
|
470
|
+
if (reason === "set-cookie") request.log.warn({ url: request.url }, "httpCache: a cacheable reply set a cookie; served private");
|
|
471
|
+
for (const [name, value] of Object.entries(privateHeaders(reason))) reply.header(name, value);
|
|
472
|
+
reply.removeHeader("cdn-cache-control");
|
|
473
|
+
reply.removeHeader(tagHeader.name);
|
|
474
|
+
stats.decision(false, reason);
|
|
475
|
+
observer?.onDecision?.({
|
|
476
|
+
url: request.url,
|
|
477
|
+
cacheable: false,
|
|
478
|
+
reason
|
|
479
|
+
});
|
|
480
|
+
return done(null, payload);
|
|
481
|
+
}
|
|
482
|
+
for (const [name, value] of Object.entries(publicHeaders(policy, opts.headers))) reply.header(name, value);
|
|
483
|
+
let body = request[kBody];
|
|
484
|
+
if (body == null && typeof payload === "string") try {
|
|
485
|
+
body = JSON.parse(payload);
|
|
486
|
+
} catch {
|
|
487
|
+
body = void 0;
|
|
488
|
+
}
|
|
489
|
+
const tags = responseTags(policy, request, body);
|
|
490
|
+
if (tags.length) {
|
|
491
|
+
const { value, dropped } = tagHeaderValue(tags, tagHeader.separator);
|
|
492
|
+
if (dropped) request.log.warn({
|
|
493
|
+
url: request.url,
|
|
494
|
+
dropped
|
|
495
|
+
}, "httpCache: tag header over 16 KB; extra tags dropped");
|
|
496
|
+
reply.header(tagHeader.name, value);
|
|
497
|
+
}
|
|
498
|
+
if (opts.cors) {
|
|
499
|
+
reply.header("access-control-allow-origin", opts.cors.origin);
|
|
500
|
+
reply.removeHeader("access-control-allow-credentials");
|
|
501
|
+
}
|
|
502
|
+
stats.decision(true);
|
|
503
|
+
observer?.onDecision?.({
|
|
504
|
+
url: request.url,
|
|
505
|
+
cacheable: true
|
|
506
|
+
});
|
|
507
|
+
return done(null, payload);
|
|
508
|
+
});
|
|
509
|
+
fastify.decorate("httpCache", {
|
|
510
|
+
invalidate: (tags, options) => invalidator.invalidate(tags, options?.mode ?? "hard"),
|
|
511
|
+
flush: () => invalidator.flush(),
|
|
512
|
+
pending: () => invalidator.pending(),
|
|
513
|
+
stats: () => stats.snapshot(invalidator.pending().length)
|
|
514
|
+
});
|
|
515
|
+
let unsubscribe = [];
|
|
516
|
+
fastify.addHook("onReady", async () => {
|
|
517
|
+
unsubscribe = await wireInvalidationSources(fastify, {
|
|
518
|
+
invalidator,
|
|
519
|
+
resources,
|
|
520
|
+
autoPurge: opts.autoPurge !== false,
|
|
521
|
+
...opts.purgeOn ? { purgeOn: opts.purgeOn } : {}
|
|
522
|
+
});
|
|
523
|
+
});
|
|
524
|
+
fastify.addHook("onClose", async () => {
|
|
525
|
+
for (const off of unsubscribe) off();
|
|
526
|
+
await invalidator.flush();
|
|
527
|
+
await delivery.stop();
|
|
528
|
+
});
|
|
529
|
+
};
|
|
530
|
+
const httpCachePlugin = fp(httpCachePluginImpl, {
|
|
531
|
+
name: "arc-http-cache",
|
|
532
|
+
fastify: "5.x"
|
|
533
|
+
});
|
|
534
|
+
// src/http-cache/invalidation/durable.ts
|
|
535
|
+
/**
|
|
536
|
+
* Durable invalidation over arc's transactional outbox.
|
|
537
|
+
*
|
|
538
|
+
* Each batch is saved as an `arc.http-cache.invalidate` event; a private `EventOutbox` relays it to the
|
|
539
|
+
* purger, so purges inherit the outbox's leases, exponential backoff and dead-letter. Use a store on the
|
|
540
|
+
* application database in production: a batch then survives a CDN outage and a process crash between
|
|
541
|
+
* enqueue and delivery. Pinned by `tests/http-cache/durable-delivery.test.ts`.
|
|
542
|
+
*/
|
|
543
|
+
const INVALIDATE_EVENT = "arc.http-cache.invalidate";
|
|
544
|
+
function durableDelivery(options) {
|
|
545
|
+
if (!options.store) throw new Error("[arc] durableDelivery: store is required");
|
|
546
|
+
const maxAttempts = options.maxAttempts ?? 8;
|
|
547
|
+
if (!Number.isInteger(maxAttempts) || maxAttempts < 1) throw new Error("[arc] durableDelivery: maxAttempts must be >= 1");
|
|
548
|
+
let ctx;
|
|
549
|
+
let outbox;
|
|
550
|
+
let timer;
|
|
551
|
+
let running = Promise.resolve();
|
|
552
|
+
const transport = {
|
|
553
|
+
name: "arc-http-cache",
|
|
554
|
+
async publish(event) {
|
|
555
|
+
if (!ctx) throw new Error("[arc] durableDelivery relay ran before start");
|
|
556
|
+
const batch = event.payload;
|
|
557
|
+
const started = Date.now();
|
|
558
|
+
try {
|
|
559
|
+
await ctx.purger.purgeTags(batch.tags, { mode: batch.mode });
|
|
560
|
+
ctx.report(batch, "sent", Date.now() - started);
|
|
561
|
+
} catch (error) {
|
|
562
|
+
ctx.report(batch, "failed", Date.now() - started, error);
|
|
563
|
+
throw error;
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
const relay = () => {
|
|
568
|
+
if (!outbox) return running;
|
|
569
|
+
running = running.then(() => outbox?.relayBatch()).catch((error) => ctx?.log.error({ err: error }, "httpCache: relay pass failed"));
|
|
570
|
+
return running;
|
|
571
|
+
};
|
|
572
|
+
return {
|
|
573
|
+
kind: "durable",
|
|
574
|
+
start(c) {
|
|
575
|
+
ctx = c;
|
|
576
|
+
outbox = new EventOutbox({
|
|
577
|
+
store: options.store,
|
|
578
|
+
transport,
|
|
579
|
+
batchSize: options.batchSize ?? 50,
|
|
580
|
+
leaseMs: options.leaseMs ?? 3e4,
|
|
581
|
+
consumerId: options.consumerId ?? "arc-http-cache",
|
|
582
|
+
failurePolicy: ({ attempts }) => attempts >= maxAttempts ? { deadLetter: true } : { retryAt: options.retryDelayMs ? new Date(Date.now() + options.retryDelayMs(attempts)) : exponentialBackoff({ attempt: attempts }) }
|
|
583
|
+
});
|
|
584
|
+
timer = setInterval(() => void relay(), options.pollMs ?? 1e3);
|
|
585
|
+
timer.unref?.();
|
|
586
|
+
},
|
|
587
|
+
async deliver(batch) {
|
|
588
|
+
if (!outbox) throw new Error("[arc] httpCache delivery used before start");
|
|
589
|
+
await outbox.store(createEvent(INVALIDATE_EVENT, {
|
|
590
|
+
tags: [...batch.tags],
|
|
591
|
+
mode: batch.mode
|
|
592
|
+
}));
|
|
593
|
+
relay();
|
|
594
|
+
},
|
|
595
|
+
async drain() {
|
|
596
|
+
await relay();
|
|
597
|
+
},
|
|
598
|
+
async stop() {
|
|
599
|
+
if (timer) clearInterval(timer);
|
|
600
|
+
timer = void 0;
|
|
601
|
+
await running;
|
|
602
|
+
}
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
export { CachePurgeError, DEFAULT_IGNORED_QUERY, DEFAULT_PRIVATE_HEADERS, INVALIDATE_EVENT, batchedDelivery, canonicalUrl, classifyPrivacy, composePurgers, createMemoryPurger, durableDelivery, httpCachePlugin, noopPurger, normalizeTags, privateHeaders, publicHeaders, resourceTags, tagsForCrudEvent };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
|
|
2
|
+
import { n as CachePurger } from "../../purger.types-DvPp4-yd.mjs";
|
|
3
|
+
export interface CloudflarePurgerOptions {
|
|
4
|
+
zoneId: string;
|
|
5
|
+
apiToken: string;
|
|
6
|
+
/** Tags per API call. Default 30. */
|
|
7
|
+
maxTagsPerCall?: number;
|
|
8
|
+
/** Injected for tests and other runtimes. Default `globalThis.fetch`. */
|
|
9
|
+
fetch?: typeof fetch;
|
|
10
|
+
/** Default `https://api.cloudflare.com/client/v4`. */
|
|
11
|
+
apiBase?: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function createCloudflarePurger(options: CloudflarePurgerOptions): CachePurger;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/*! @classytic/arc v2.47.0 | MIT | https://classytic.com */
|
|
2
|
+
import { t as CachePurgeError } from "../../purger.types-2wNJK_89.mjs";
|
|
3
|
+
// src/http-cache/purgers/cloudflare.ts
|
|
4
|
+
/**
|
|
5
|
+
* Cloudflare purge-by-tag (`Cache-Tag`). Needs an API token scoped to Zone > Cache Purge only.
|
|
6
|
+
*
|
|
7
|
+
* Cloudflare has no soft purge by tag, so soft purges are sent hard. 30 tags per call is the
|
|
8
|
+
* free-plan-safe default. Failures throw `CachePurgeError` with Cloudflare's error codes, never the token.
|
|
9
|
+
*/
|
|
10
|
+
function createCloudflarePurger(options) {
|
|
11
|
+
if (!options.zoneId?.trim()) throw new Error("[arc] createCloudflarePurger: zoneId is required");
|
|
12
|
+
if (!options.apiToken?.trim()) throw new Error("[arc] createCloudflarePurger: apiToken is required");
|
|
13
|
+
const size = options.maxTagsPerCall ?? 30;
|
|
14
|
+
if (!Number.isInteger(size) || size < 1) throw new Error("[arc] createCloudflarePurger: maxTagsPerCall must be a positive integer");
|
|
15
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
16
|
+
if (typeof doFetch !== "function") throw new Error("[arc] createCloudflarePurger: no fetch implementation available");
|
|
17
|
+
const url = `${options.apiBase ?? "https://api.cloudflare.com/client/v4"}/zones/${encodeURIComponent(options.zoneId)}/purge_cache`;
|
|
18
|
+
return {
|
|
19
|
+
name: "cloudflare",
|
|
20
|
+
capabilities: {
|
|
21
|
+
softPurge: false,
|
|
22
|
+
maxTagsPerCall: size
|
|
23
|
+
},
|
|
24
|
+
async purgeTags(tags) {
|
|
25
|
+
let res;
|
|
26
|
+
try {
|
|
27
|
+
res = await doFetch(url, {
|
|
28
|
+
method: "POST",
|
|
29
|
+
headers: {
|
|
30
|
+
authorization: `Bearer ${options.apiToken}`,
|
|
31
|
+
"content-type": "application/json"
|
|
32
|
+
},
|
|
33
|
+
body: JSON.stringify({ tags })
|
|
34
|
+
});
|
|
35
|
+
} catch {
|
|
36
|
+
throw new CachePurgeError("cloudflare", "Cloudflare purge request could not be sent");
|
|
37
|
+
}
|
|
38
|
+
const body = await res.json().catch(() => void 0);
|
|
39
|
+
if (!res.ok || body?.success !== true) {
|
|
40
|
+
const codes = (body?.errors ?? []).map((e) => e.code).filter((c) => typeof c === "number");
|
|
41
|
+
throw new CachePurgeError("cloudflare", `Cloudflare purge refused (HTTP ${res.status})`, res.status, codes);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export { createCloudflarePurger };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
|
|
2
|
+
import { n as CachePurger } from "../../purger.types-DvPp4-yd.mjs";
|
|
3
|
+
export interface FastlyPurgerOptions {
|
|
4
|
+
serviceId: string;
|
|
5
|
+
apiKey: string;
|
|
6
|
+
/** Keys per call. Default 256 (Fastly's bulk limit). */
|
|
7
|
+
maxTagsPerCall?: number;
|
|
8
|
+
fetch?: typeof fetch;
|
|
9
|
+
/** Default `https://api.fastly.com`. */
|
|
10
|
+
apiBase?: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function createFastlyPurger(options: FastlyPurgerOptions): CachePurger;
|