@fedify/fedify 2.4.0-dev.1490 → 2.4.0-dev.1508
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/README.md +7 -5
- package/dist/{assert-OguE97r2.mjs → assert-DvVHoIZ0.mjs} +1 -1
- package/dist/{assert_instance_of-DBC5X09g.mjs → assert_instance_of-CxoC8bVq.mjs} +1 -1
- package/dist/{assert_not_equals-DkVK8oqV.mjs → assert_not_equals-C8vcTTA3.mjs} +1 -1
- package/dist/{assert_rejects-DN60FHPX.mjs → assert_rejects-DAdaaIWM.mjs} +2 -2
- package/dist/{assert_strict_equals-XEgZAlrj.mjs → assert_strict_equals-BzqyKuYL.mjs} +1 -1
- package/dist/{assert_throws-BOkhLGYc.mjs → assert_throws-zN79lgIC.mjs} +1 -1
- package/dist/{builder-CwwQRArg.mjs → builder-DlWCek6Z.mjs} +23 -3
- package/dist/codec-CmlPqjNX.mjs +103 -0
- package/dist/compat/mod.d.cts +1 -1
- package/dist/compat/mod.d.ts +1 -1
- package/dist/compat/outgoing-jsonld.test.mjs +3 -3
- package/dist/compat/public-audience.test.mjs +3 -3
- package/dist/compat/transformers.test.mjs +5 -5
- package/dist/{context-DVoTs_wM.mjs → context-BBRTgkrs.mjs} +8 -2
- package/dist/{context-BU6jSQdo.d.ts → context-BF5B4ZDk.d.ts} +529 -259
- package/dist/{context-BBVLF7lx.d.cts → context-CYF8X0ft.d.cts} +530 -259
- package/dist/{deno-Yohf1ISx.mjs → deno-nexucTAX.mjs} +1 -1
- package/dist/{docloader-B6DFWEOx.mjs → docloader-DAdEN549.mjs} +3 -3
- package/dist/federation/builder.test.mjs +5 -5
- package/dist/federation/circuit-breaker.test.mjs +5 -5
- package/dist/federation/collection.test.mjs +3 -3
- package/dist/federation/handler.test.mjs +13 -13
- package/dist/federation/idempotency.test.mjs +6 -6
- package/dist/federation/inbox.test.mjs +3 -3
- package/dist/federation/keycache.test.mjs +5 -5
- package/dist/federation/kv.test.mjs +3 -3
- package/dist/federation/metrics.test.mjs +4 -4
- package/dist/federation/middleware.test.mjs +200 -19
- package/dist/federation/mod.cjs +3 -259
- package/dist/federation/mod.d.cts +4 -4
- package/dist/federation/mod.d.ts +4 -4
- package/dist/federation/mod.js +1 -257
- package/dist/federation/mq.test.mjs +103 -261
- package/dist/federation/negotiation.test.mjs +4 -4
- package/dist/federation/retry.test.mjs +3 -3
- package/dist/federation/router.test.mjs +5 -5
- package/dist/federation/send.test.mjs +10 -10
- package/dist/federation/tasks/codec.test.d.mts +2 -0
- package/dist/federation/tasks/codec.test.mjs +292 -0
- package/dist/federation/tasks/enqueue.test.d.mts +2 -0
- package/dist/federation/tasks/enqueue.test.mjs +992 -0
- package/dist/federation/tasks/tasks.test.d.mts +2 -0
- package/dist/federation/tasks/tasks.test.mjs +555 -0
- package/dist/federation/temporal.test.mjs +4 -4
- package/dist/federation/webfinger.test.mjs +6 -6
- package/dist/{http-C3eJp_Ha.cjs → http-BCj9dlA_.cjs} +1 -1
- package/dist/{http-BqSm-f2G.js → http-Dv3147TL.js} +1 -1
- package/dist/{http-BeDlAH97.mjs → http-inQqS3yx.mjs} +4 -4
- package/dist/{key-DNBTcjuV.mjs → key-CGrr6-I2.mjs} +2 -2
- package/dist/{kv-cache-Crq8nvSV.js → kv-cache-C2oTEXyb.js} +1 -1
- package/dist/{kv-cache-b2HaCLC-.mjs → kv-cache-C3qkFkbt.mjs} +1 -1
- package/dist/{kv-cache-CGJMNSs-.cjs → kv-cache-c8X6svwE.cjs} +1 -1
- package/dist/{ld-CQlFhsU6.mjs → ld-fnWaNT8y.mjs} +3 -3
- package/dist/{metrics-B6RKtTLt.mjs → metrics-C5hMINAa.mjs} +1 -1
- package/dist/{middleware-CQygcRYE.mjs → middleware-CQlq6ykI.mjs} +1 -1
- package/dist/{middleware-CBM9vGYg.cjs → middleware-DeVzbg1I.cjs} +690 -30
- package/dist/{middleware-CsxoclmN.mjs → middleware-Dl2nyVgB.mjs} +306 -46
- package/dist/{middleware-B3vFLcCh.js → middleware-vQ_ZpgcX.js} +679 -31
- package/dist/{mod-vPYVoa5n.d.ts → mod-4WGAuR6X.d.ts} +1 -1
- package/dist/{mod-C0F6kvgS.d.cts → mod-BHEB3xhE.d.cts} +1 -1
- package/dist/mod.cjs +6 -6
- package/dist/mod.d.cts +5 -5
- package/dist/mod.d.ts +5 -5
- package/dist/mod.js +5 -5
- package/dist/mq-03vS-C9P.mjs +276 -0
- package/dist/{mq-D8uSFzxe.d.cts → mq-B5_hohs7.d.ts} +34 -0
- package/dist/{mq-D-nlpY04.d.ts → mq-DXMt_qCY.d.cts} +34 -0
- package/dist/nodeinfo/client.test.mjs +3 -3
- package/dist/nodeinfo/handler.test.mjs +5 -5
- package/dist/nodeinfo/types.test.mjs +4 -4
- package/dist/otel/exporter.test.mjs +3 -3
- package/dist/{outgoing-jsonld-L_DbOaFe.mjs → outgoing-jsonld-BNL8AC14.mjs} +1 -1
- package/dist/{owner-B1FnbZ1w.mjs → owner-Bq2eZyO_.mjs} +2 -2
- package/dist/{proof-ChmZL5rY.cjs → proof-Buz7I8wj.cjs} +1 -1
- package/dist/{proof-BhNTn0HE.js → proof-CTG9azxN.js} +1 -1
- package/dist/{proof-BUuvq0ia.mjs → proof-DZCjcFCd.mjs} +5 -5
- package/dist/{send-Dq-Ofquk.mjs → send-B253S5gN.mjs} +3 -3
- package/dist/sig/accept.test.mjs +1 -1
- package/dist/sig/http.test.mjs +8 -8
- package/dist/sig/key.test.mjs +6 -6
- package/dist/sig/ld.test.mjs +7 -7
- package/dist/sig/mod.cjs +2 -2
- package/dist/sig/mod.js +2 -2
- package/dist/sig/owner.test.mjs +6 -6
- package/dist/sig/proof.test.mjs +8 -8
- package/dist/{std__assert-BBjXFNOb.mjs → std__assert-Dh6uLf_q.mjs} +4 -4
- package/dist/{temporal-C-vrfOld.mjs → temporal-d6TshGjq.mjs} +1 -1
- package/dist/testing/mod.d.mts +1037 -8
- package/dist/testing/mod.mjs +3 -2
- package/dist/testing-Dy-WhqpN.mjs +77 -0
- package/dist/utils/docloader.test.mjs +6 -6
- package/dist/utils/kv-cache.test.mjs +1 -1
- package/dist/utils/mod.cjs +1 -1
- package/dist/utils/mod.js +1 -1
- package/package.json +9 -7
- /package/dist/{accept-CPkZzmGN.mjs → accept-CgDcxvjV.mjs} +0 -0
- /package/dist/{activity-listener-tztVvlNb.mjs → activity-listener-BeTGV3wc.mjs} +0 -0
- /package/dist/{assert_equals-C-ZRDbaf.mjs → assert_equals-PBVKNMJd.mjs} +0 -0
- /package/dist/{circuit-breaker-CSWsyoef.mjs → circuit-breaker-hJBB6jwA.mjs} +0 -0
- /package/dist/{client-ByXmQhYD.mjs → client-B_A6mfn3.mjs} +0 -0
- /package/dist/{collection-Cc3DVAhE.mjs → collection-Dp5ky45w.mjs} +0 -0
- /package/dist/{keycache-BeU0LCII.mjs → keycache-CaOR6NYg.mjs} +0 -0
- /package/dist/{keys-DGu1NFwu.mjs → keys-CSYsOMFG.mjs} +0 -0
- /package/dist/{kv-rV3vodCc.mjs → kv-CIvR3Non.mjs} +0 -0
- /package/dist/{negotiation-DDstyBvc.mjs → negotiation-m_L2nyS3.mjs} +0 -0
- /package/dist/{public-audience-Cvbr2Gzt.mjs → public-audience-c9zmYKgA.mjs} +0 -0
- /package/dist/{retry-CXg_MBI-.mjs → retry-DI4O-zYl.mjs} +0 -0
- /package/dist/{types-J53Kw7so.mjs → types-BFowWFTT.mjs} +0 -0
|
@@ -2,10 +2,10 @@ const { Temporal } = require("@js-temporal/polyfill");
|
|
|
2
2
|
const { URLPattern } = require("urlpattern-polyfill");
|
|
3
3
|
const require_chunk = require("./chunk-DDcVe30Y.cjs");
|
|
4
4
|
const require_transformers = require("./transformers-NeAONrAq.cjs");
|
|
5
|
-
const require_http = require("./http-
|
|
6
|
-
const require_proof = require("./proof-
|
|
5
|
+
const require_http = require("./http-BCj9dlA_.cjs");
|
|
6
|
+
const require_proof = require("./proof-Buz7I8wj.cjs");
|
|
7
7
|
const require_types = require("./types-KC4QAoxe.cjs");
|
|
8
|
-
const require_kv_cache = require("./kv-cache-
|
|
8
|
+
const require_kv_cache = require("./kv-cache-c8X6svwE.cjs");
|
|
9
9
|
let _logtape_logtape = require("@logtape/logtape");
|
|
10
10
|
let _fedify_uri_template = require("@fedify/uri-template");
|
|
11
11
|
let _fedify_vocab = require("@fedify/vocab");
|
|
@@ -18,6 +18,7 @@ let _fedify_vocab_runtime_jsonld = require("@fedify/vocab-runtime/jsonld");
|
|
|
18
18
|
_fedify_vocab_runtime_jsonld = require_chunk.__toESM(_fedify_vocab_runtime_jsonld, 1);
|
|
19
19
|
let _fedify_webfinger = require("@fedify/webfinger");
|
|
20
20
|
let _opentelemetry_sdk_metrics = require("@opentelemetry/sdk-metrics");
|
|
21
|
+
let devalue = require("devalue");
|
|
21
22
|
let node_url = require("node:url");
|
|
22
23
|
//#region src/federation/activity-listener.ts
|
|
23
24
|
var ActivityListenerSet = class {
|
|
@@ -108,6 +109,7 @@ var FederationBuilderImpl = class {
|
|
|
108
109
|
idempotencyStrategy;
|
|
109
110
|
collectionTypeIds;
|
|
110
111
|
collectionCallbacks;
|
|
112
|
+
taskDefinitions;
|
|
111
113
|
/**
|
|
112
114
|
* Symbol registry for unique identification of unnamed symbols.
|
|
113
115
|
*/
|
|
@@ -118,6 +120,7 @@ var FederationBuilderImpl = class {
|
|
|
118
120
|
this.objectTypeIds = {};
|
|
119
121
|
this.collectionCallbacks = {};
|
|
120
122
|
this.collectionTypeIds = {};
|
|
123
|
+
this.taskDefinitions = /* @__PURE__ */ new Map();
|
|
121
124
|
}
|
|
122
125
|
/**
|
|
123
126
|
* Builds the federation object.
|
|
@@ -156,6 +159,7 @@ var FederationBuilderImpl = class {
|
|
|
156
159
|
f.unverifiedActivityHandler = this.unverifiedActivityHandler;
|
|
157
160
|
f.outboxPermanentFailureHandler = this.outboxPermanentFailureHandler;
|
|
158
161
|
f.idempotencyStrategy = this.idempotencyStrategy;
|
|
162
|
+
f.taskDefinitions = new Map(this.taskDefinitions);
|
|
159
163
|
return f;
|
|
160
164
|
}
|
|
161
165
|
_getTracer() {
|
|
@@ -288,6 +292,23 @@ var FederationBuilderImpl = class {
|
|
|
288
292
|
setWebFingerLinksDispatcher(dispatcher) {
|
|
289
293
|
this.webFingerLinksDispatcher = dispatcher;
|
|
290
294
|
}
|
|
295
|
+
defineTask(name, options) {
|
|
296
|
+
if (this.taskDefinitions.has(name)) throw new TypeError(`Task ${JSON.stringify(name)} is already defined.`);
|
|
297
|
+
const handle = {
|
|
298
|
+
name,
|
|
299
|
+
schema: options.schema
|
|
300
|
+
};
|
|
301
|
+
this.taskDefinitions.set(name, {
|
|
302
|
+
name,
|
|
303
|
+
schema: options.schema,
|
|
304
|
+
handle,
|
|
305
|
+
handler: options.handler,
|
|
306
|
+
onError: options.onError,
|
|
307
|
+
retryPolicy: options.retryPolicy,
|
|
308
|
+
queue: options.queue
|
|
309
|
+
});
|
|
310
|
+
return handle;
|
|
311
|
+
}
|
|
291
312
|
/**
|
|
292
313
|
* The RFC 6570 template-literal `path` overloads were removed for
|
|
293
314
|
* type-checking efficiency, so the URI variable types can no longer be
|
|
@@ -1393,7 +1414,7 @@ function acceptsJsonLd(request) {
|
|
|
1393
1414
|
}
|
|
1394
1415
|
//#endregion
|
|
1395
1416
|
//#region src/federation/temporal.ts
|
|
1396
|
-
function isPlainObject(value) {
|
|
1417
|
+
function isPlainObject$1(value) {
|
|
1397
1418
|
return typeof value === "object" && value != null && !Array.isArray(value);
|
|
1398
1419
|
}
|
|
1399
1420
|
function normalizeDateTimeLiteral(value) {
|
|
@@ -1431,11 +1452,11 @@ const QUESTION_CLOSED_IRI = "https://www.w3.org/ns/activitystreams#closed";
|
|
|
1431
1452
|
const XSD_DATE_TIME_IRI = "http://www.w3.org/2001/XMLSchema#dateTime";
|
|
1432
1453
|
function hasMalformedExpandedDateTimeLiteral(value) {
|
|
1433
1454
|
if (Array.isArray(value)) return value.some(hasMalformedExpandedDateTimeLiteral);
|
|
1434
|
-
return isPlainObject(value) && "@value" in value && isMalformedDateTimeLiteral(value["@value"]);
|
|
1455
|
+
return isPlainObject$1(value) && "@value" in value && isMalformedDateTimeLiteral(value["@value"]);
|
|
1435
1456
|
}
|
|
1436
1457
|
function hasMalformedExpandedQuestionClosedLiteral(value) {
|
|
1437
1458
|
if (Array.isArray(value)) return value.some(hasMalformedExpandedQuestionClosedLiteral);
|
|
1438
|
-
if (!isPlainObject(value) || !("@value" in value)) return false;
|
|
1459
|
+
if (!isPlainObject$1(value) || !("@value" in value)) return false;
|
|
1439
1460
|
const literal = value["@value"];
|
|
1440
1461
|
if (typeof literal === "boolean") return false;
|
|
1441
1462
|
if (typeof literal !== "string") return false;
|
|
@@ -1445,11 +1466,11 @@ function hasMalformedExpandedQuestionClosedLiteral(value) {
|
|
|
1445
1466
|
}
|
|
1446
1467
|
function hasMalformedExpandedDurationLiteral(value) {
|
|
1447
1468
|
if (Array.isArray(value)) return value.some(hasMalformedExpandedDurationLiteral);
|
|
1448
|
-
return isPlainObject(value) && "@value" in value && isMalformedDurationLiteral(value["@value"]);
|
|
1469
|
+
return isPlainObject$1(value) && "@value" in value && isMalformedDurationLiteral(value["@value"]);
|
|
1449
1470
|
}
|
|
1450
1471
|
function hasMalformedKnownTemporalLiteralInternal(value, visited) {
|
|
1451
1472
|
if (Array.isArray(value)) return value.some((item) => hasMalformedKnownTemporalLiteralInternal(item, visited));
|
|
1452
|
-
if (!isPlainObject(value)) return false;
|
|
1473
|
+
if (!isPlainObject$1(value)) return false;
|
|
1453
1474
|
if (visited.has(value)) return false;
|
|
1454
1475
|
visited.add(value);
|
|
1455
1476
|
if ("@value" in value) return false;
|
|
@@ -3553,6 +3574,529 @@ function createExponentialBackoffPolicy(options = {}) {
|
|
|
3553
3574
|
};
|
|
3554
3575
|
}
|
|
3555
3576
|
//#endregion
|
|
3577
|
+
//#region src/federation/tasks/codec.ts
|
|
3578
|
+
/**
|
|
3579
|
+
* Serializes and deserializes task payloads for the queue, preserving
|
|
3580
|
+
* `@fedify/vocab` objects across the wire by reducing them to JSON-LD and
|
|
3581
|
+
* rebuilding them on the worker with the bound {@link TaskCodecLoaders}.
|
|
3582
|
+
* @internal
|
|
3583
|
+
*/
|
|
3584
|
+
var TaskCodec = class TaskCodec {
|
|
3585
|
+
options;
|
|
3586
|
+
constructor(options) {
|
|
3587
|
+
this.options = options;
|
|
3588
|
+
}
|
|
3589
|
+
/** Serializes `data`, encoding any vocabulary object as its JSON-LD. */
|
|
3590
|
+
serialize = (data) => (0, devalue.stringifyAsync)(data, { Vocab: this.#stringifyVocab });
|
|
3591
|
+
/** Deserializes `raw`, rebuilding any encoded vocabulary object. */
|
|
3592
|
+
deserialize = (raw) => this.#revive(/* @__PURE__ */ new Map())((0, devalue.parse)(raw, { Vocab: VocabHolder.from }));
|
|
3593
|
+
/** Validates `data` against `schema`, then serializes it. */
|
|
3594
|
+
encode = async (schema, data) => this.serialize(await TaskCodec.validate(schema, data));
|
|
3595
|
+
/** Deserializes `raw`, then validates the result against `schema`. */
|
|
3596
|
+
decode = async (schema, raw) => TaskCodec.validate(schema, await this.deserialize(raw));
|
|
3597
|
+
/** Validates `data` against `schema`, returning its parsed output. */
|
|
3598
|
+
static validate = async (schema, data) => getValueIfSchema(await schema["~standard"].validate(data));
|
|
3599
|
+
#stringifyVocab = (value) => isVocab(value) && this.#toWire(value);
|
|
3600
|
+
#toWire = async (value) => ({
|
|
3601
|
+
kind: value instanceof _fedify_vocab.Link ? "link" : "object",
|
|
3602
|
+
jsonLd: await value.toJsonLd({
|
|
3603
|
+
format: "expand",
|
|
3604
|
+
...this.options
|
|
3605
|
+
})
|
|
3606
|
+
});
|
|
3607
|
+
#revive = (seen) => {
|
|
3608
|
+
const inner = async (node) => {
|
|
3609
|
+
if (node === null || typeof node !== "object") return node;
|
|
3610
|
+
if (seen.has(node)) return seen.get(node);
|
|
3611
|
+
for (const reviver of this.#classRevivers) {
|
|
3612
|
+
const out = reviver(seen, inner, node);
|
|
3613
|
+
if (out !== void 0) return await out;
|
|
3614
|
+
}
|
|
3615
|
+
return node;
|
|
3616
|
+
};
|
|
3617
|
+
return inner;
|
|
3618
|
+
};
|
|
3619
|
+
#classRevivers = [
|
|
3620
|
+
classReviver(isInstanceOf(VocabHolder), ({ kind, jsonLd }) => kind === "link" ? _fedify_vocab.Link.fromJsonLd(jsonLd, this.options) : _fedify_vocab.Object.fromJsonLd(jsonLd, this.options), () => {}),
|
|
3621
|
+
classReviver(isInstanceOf(Array), () => [], async (revive, node, arr) => {
|
|
3622
|
+
for (const item of await Array.fromAsync(node, revive)) arr.push(item);
|
|
3623
|
+
}),
|
|
3624
|
+
classReviver(isInstanceOf(Map), () => /* @__PURE__ */ new Map(), async (revive, node, map) => {
|
|
3625
|
+
for (const [k, v] of node) map.set(await revive(k), await revive(v));
|
|
3626
|
+
}),
|
|
3627
|
+
classReviver(isInstanceOf(Set), () => /* @__PURE__ */ new Set(), async (revive, node, set) => {
|
|
3628
|
+
for (const v of await Array.fromAsync(node, revive)) set.add(v);
|
|
3629
|
+
}),
|
|
3630
|
+
classReviver(isPlainObject, () => ({}), async (revive, node, obj) => {
|
|
3631
|
+
for (const [k, v] of globalThis.Object.entries(node)) obj[k] = await revive(v);
|
|
3632
|
+
})
|
|
3633
|
+
];
|
|
3634
|
+
};
|
|
3635
|
+
const isVocab = (value) => value instanceof _fedify_vocab.Object || value instanceof _fedify_vocab.Link;
|
|
3636
|
+
const isPlainObject = (value) => value === null || typeof value !== "object" ? false : isObjectPrototype(globalThis.Object.getPrototypeOf(value));
|
|
3637
|
+
const isObjectPrototype = (proto) => proto === null || proto === globalThis.Object.prototype;
|
|
3638
|
+
const isInstanceOf = (cls) => (v) => v instanceof cls;
|
|
3639
|
+
function getValueIfSchema(result) {
|
|
3640
|
+
assertSchema(result);
|
|
3641
|
+
return result.value;
|
|
3642
|
+
}
|
|
3643
|
+
function assertSchema(result) {
|
|
3644
|
+
if (result.issues && result.issues.length > 0) throw new TypeError(`Task data failed schema validation: ${JSON.stringify(result.issues)}`);
|
|
3645
|
+
}
|
|
3646
|
+
/**
|
|
3647
|
+
* A vocabulary object parked by the synchronous decode reviver, held until
|
|
3648
|
+
* the async revive pass can `fromJsonLd()` it back into an instance.
|
|
3649
|
+
*/
|
|
3650
|
+
var VocabHolder = class VocabHolder {
|
|
3651
|
+
kind;
|
|
3652
|
+
jsonLd;
|
|
3653
|
+
constructor(kind, jsonLd) {
|
|
3654
|
+
this.kind = kind;
|
|
3655
|
+
this.jsonLd = jsonLd;
|
|
3656
|
+
}
|
|
3657
|
+
static from = ({ kind, jsonLd }) => new VocabHolder(kind, jsonLd);
|
|
3658
|
+
};
|
|
3659
|
+
/**
|
|
3660
|
+
* Ties a container filter to its empty-shell `init` and child-filling `set`
|
|
3661
|
+
* through one type parameter—a correlation the heterogeneous reviver list
|
|
3662
|
+
* cannot carry, which previously forced `@ts-ignore` at the dispatch site.
|
|
3663
|
+
*/
|
|
3664
|
+
const classReviver = (filter, init, set) => (seen, revive, node) => {
|
|
3665
|
+
if (!filter(node)) return void 0;
|
|
3666
|
+
return (async () => {
|
|
3667
|
+
const out = await init(node);
|
|
3668
|
+
seen.set(node, out);
|
|
3669
|
+
await set(revive, node, out);
|
|
3670
|
+
return out;
|
|
3671
|
+
})();
|
|
3672
|
+
};
|
|
3673
|
+
//#endregion
|
|
3674
|
+
//#region src/federation/mq.ts
|
|
3675
|
+
/**
|
|
3676
|
+
* A message queue that processes messages in the same process.
|
|
3677
|
+
* Do not use this in production as it does neither persist messages nor
|
|
3678
|
+
* distribute them across multiple processes.
|
|
3679
|
+
*
|
|
3680
|
+
* @since 0.5.0
|
|
3681
|
+
*/
|
|
3682
|
+
var InProcessMessageQueue = class {
|
|
3683
|
+
#messages;
|
|
3684
|
+
#monitors;
|
|
3685
|
+
#pollIntervalMs;
|
|
3686
|
+
#delayedMessages;
|
|
3687
|
+
/**
|
|
3688
|
+
* Tracks which ordering keys are currently being processed to ensure
|
|
3689
|
+
* sequential processing for messages with the same key.
|
|
3690
|
+
*/
|
|
3691
|
+
#processingKeys;
|
|
3692
|
+
/**
|
|
3693
|
+
* In-process message queue does not provide native retry mechanisms.
|
|
3694
|
+
* @since 1.7.0
|
|
3695
|
+
*/
|
|
3696
|
+
nativeRetrial = false;
|
|
3697
|
+
/**
|
|
3698
|
+
* In-process message queue does not deduplicate messages natively.
|
|
3699
|
+
* @since 2.4.0
|
|
3700
|
+
*/
|
|
3701
|
+
nativeDeduplication = false;
|
|
3702
|
+
/**
|
|
3703
|
+
* Constructs a new {@link InProcessMessageQueue} with the given options.
|
|
3704
|
+
* @param options Additional options for the in-process message queue.
|
|
3705
|
+
*/
|
|
3706
|
+
constructor(options = {}) {
|
|
3707
|
+
this.#messages = [];
|
|
3708
|
+
this.#monitors = {};
|
|
3709
|
+
this.#pollIntervalMs = Temporal.Duration.from(options.pollInterval ?? { seconds: 5 }).total("millisecond");
|
|
3710
|
+
this.#delayedMessages = 0;
|
|
3711
|
+
this.#processingKeys = /* @__PURE__ */ new Set();
|
|
3712
|
+
}
|
|
3713
|
+
enqueue(message, options) {
|
|
3714
|
+
const delay = options?.delay == null ? 0 : Math.max(options.delay.total("millisecond"), 0);
|
|
3715
|
+
if (delay > 0) {
|
|
3716
|
+
this.#delayedMessages++;
|
|
3717
|
+
setTimeout(() => {
|
|
3718
|
+
this.#delayedMessages--;
|
|
3719
|
+
this.#enqueueReady(message, options);
|
|
3720
|
+
}, delay);
|
|
3721
|
+
return Promise.resolve();
|
|
3722
|
+
}
|
|
3723
|
+
this.#enqueueReady(message, options);
|
|
3724
|
+
return Promise.resolve();
|
|
3725
|
+
}
|
|
3726
|
+
#enqueueReady(message, options) {
|
|
3727
|
+
const orderingKey = options?.orderingKey ?? null;
|
|
3728
|
+
this.#messages.push({
|
|
3729
|
+
message,
|
|
3730
|
+
orderingKey
|
|
3731
|
+
});
|
|
3732
|
+
this.#notifyMonitors();
|
|
3733
|
+
}
|
|
3734
|
+
#notifyMonitors() {
|
|
3735
|
+
for (const monitorId in this.#monitors) this.#monitors[monitorId]();
|
|
3736
|
+
}
|
|
3737
|
+
enqueueMany(messages, options) {
|
|
3738
|
+
if (messages.length === 0) return Promise.resolve();
|
|
3739
|
+
const delay = options?.delay == null ? 0 : Math.max(options.delay.total("millisecond"), 0);
|
|
3740
|
+
if (delay > 0) {
|
|
3741
|
+
const delayedCount = messages.length;
|
|
3742
|
+
const deferredMessages = [...messages];
|
|
3743
|
+
this.#delayedMessages += delayedCount;
|
|
3744
|
+
setTimeout(() => {
|
|
3745
|
+
this.#delayedMessages -= delayedCount;
|
|
3746
|
+
this.#enqueueManyReady(deferredMessages, options);
|
|
3747
|
+
}, delay);
|
|
3748
|
+
return Promise.resolve();
|
|
3749
|
+
}
|
|
3750
|
+
this.#enqueueManyReady(messages, options);
|
|
3751
|
+
return Promise.resolve();
|
|
3752
|
+
}
|
|
3753
|
+
#enqueueManyReady(messages, options) {
|
|
3754
|
+
const orderingKey = options?.orderingKey ?? null;
|
|
3755
|
+
for (const message of messages) this.#messages.push({
|
|
3756
|
+
message,
|
|
3757
|
+
orderingKey
|
|
3758
|
+
});
|
|
3759
|
+
this.#notifyMonitors();
|
|
3760
|
+
}
|
|
3761
|
+
async listen(handler, options = {}) {
|
|
3762
|
+
const signal = options.signal;
|
|
3763
|
+
while (signal == null || !signal.aborted) {
|
|
3764
|
+
const idx = this.#messages.findIndex((m) => m.orderingKey == null || !this.#processingKeys.has(m.orderingKey));
|
|
3765
|
+
if (idx >= 0) {
|
|
3766
|
+
const { message, orderingKey } = this.#messages.splice(idx, 1)[0];
|
|
3767
|
+
if (orderingKey != null) this.#processingKeys.add(orderingKey);
|
|
3768
|
+
try {
|
|
3769
|
+
await handler(message);
|
|
3770
|
+
} finally {
|
|
3771
|
+
if (orderingKey != null) this.#processingKeys.delete(orderingKey);
|
|
3772
|
+
}
|
|
3773
|
+
} else if (this.#messages.length === 0) await this.#wait(this.#pollIntervalMs, signal);
|
|
3774
|
+
else await this.#wait(10, signal);
|
|
3775
|
+
}
|
|
3776
|
+
}
|
|
3777
|
+
getDepth() {
|
|
3778
|
+
const ready = this.#messages.length;
|
|
3779
|
+
const delayed = this.#delayedMessages;
|
|
3780
|
+
return Promise.resolve({
|
|
3781
|
+
queued: ready + delayed,
|
|
3782
|
+
ready,
|
|
3783
|
+
delayed
|
|
3784
|
+
});
|
|
3785
|
+
}
|
|
3786
|
+
#wait(ms, signal) {
|
|
3787
|
+
let timer = null;
|
|
3788
|
+
return Promise.any([new Promise((resolve) => {
|
|
3789
|
+
signal?.addEventListener("abort", () => {
|
|
3790
|
+
if (timer != null) clearTimeout(timer);
|
|
3791
|
+
resolve();
|
|
3792
|
+
}, { once: true });
|
|
3793
|
+
const monitorId = crypto.randomUUID();
|
|
3794
|
+
this.#monitors[monitorId] = () => {
|
|
3795
|
+
delete this.#monitors[monitorId];
|
|
3796
|
+
if (timer != null) clearTimeout(timer);
|
|
3797
|
+
resolve();
|
|
3798
|
+
};
|
|
3799
|
+
}), new Promise((resolve) => timer = setTimeout(resolve, ms))]);
|
|
3800
|
+
}
|
|
3801
|
+
};
|
|
3802
|
+
/**
|
|
3803
|
+
* A message queue that processes messages in parallel. It takes another
|
|
3804
|
+
* {@link MessageQueue}, and processes messages in parallel up to a certain
|
|
3805
|
+
* number of workers.
|
|
3806
|
+
*
|
|
3807
|
+
* Actually, it's rather a decorator than a queue itself.
|
|
3808
|
+
*
|
|
3809
|
+
* Note that the workers do not run in truly parallel, in the sense that they
|
|
3810
|
+
* are not running in separate threads or processes. They are running in the
|
|
3811
|
+
* same process, but are scheduled to run in parallel. Hence, this is useful
|
|
3812
|
+
* for I/O-bound tasks, but not for CPU-bound tasks, which is okay for Fedify's
|
|
3813
|
+
* workloads.
|
|
3814
|
+
*
|
|
3815
|
+
* When using `ParallelMessageQueue`, the ordering guarantee is preserved
|
|
3816
|
+
* *only if* the underlying queue implementation delivers messages in a wrapper
|
|
3817
|
+
* format that includes the `__fedify_ordering_key__` property. Currently,
|
|
3818
|
+
* only `DenoKvMessageQueue` and `WorkersMessageQueue` use this format.
|
|
3819
|
+
* For other queue implementations (e.g., `InProcessMessageQueue`,
|
|
3820
|
+
* `RedisMessageQueue`, `PostgresMessageQueue`, `SqliteMessageQueue`,
|
|
3821
|
+
* `AmqpMessageQueue`), the ordering key cannot be detected by
|
|
3822
|
+
* `ParallelMessageQueue`, so ordering guarantees are handled by those
|
|
3823
|
+
* implementations directly rather than at the `ParallelMessageQueue` level.
|
|
3824
|
+
*
|
|
3825
|
+
* Messages with the same ordering key will never be processed concurrently
|
|
3826
|
+
* by different workers, ensuring sequential processing within each key.
|
|
3827
|
+
* Messages with different ordering keys (or no ordering key) can still be
|
|
3828
|
+
* processed in parallel.
|
|
3829
|
+
*
|
|
3830
|
+
* @since 1.0.0
|
|
3831
|
+
*/
|
|
3832
|
+
var ParallelMessageQueue = class ParallelMessageQueue {
|
|
3833
|
+
queue;
|
|
3834
|
+
workers;
|
|
3835
|
+
/**
|
|
3836
|
+
* Inherits the native retry capability from the wrapped queue.
|
|
3837
|
+
* @since 1.7.0
|
|
3838
|
+
*/
|
|
3839
|
+
nativeRetrial;
|
|
3840
|
+
/**
|
|
3841
|
+
* Inherits the native deduplication capability from the wrapped queue.
|
|
3842
|
+
* @since 2.4.0
|
|
3843
|
+
*/
|
|
3844
|
+
nativeDeduplication;
|
|
3845
|
+
getDepth;
|
|
3846
|
+
/**
|
|
3847
|
+
* Tracks which ordering keys are currently being processed to ensure
|
|
3848
|
+
* sequential processing for messages with the same key.
|
|
3849
|
+
*/
|
|
3850
|
+
#processingKeys = /* @__PURE__ */ new Set();
|
|
3851
|
+
/**
|
|
3852
|
+
* Pending messages waiting for their ordering key to become available.
|
|
3853
|
+
*/
|
|
3854
|
+
#pendingMessages = [];
|
|
3855
|
+
/**
|
|
3856
|
+
* Constructs a new {@link ParallelMessageQueue} with the given queue and
|
|
3857
|
+
* number of workers.
|
|
3858
|
+
* @param queue The message queue to use under the hood. Note that
|
|
3859
|
+
* {@link ParallelMessageQueue} cannot be nested.
|
|
3860
|
+
* @param workers The number of workers to process messages in parallel.
|
|
3861
|
+
* @throws {TypeError} If the given queue is an instance of
|
|
3862
|
+
* {@link ParallelMessageQueue}.
|
|
3863
|
+
*/
|
|
3864
|
+
constructor(queue, workers) {
|
|
3865
|
+
if (queue instanceof ParallelMessageQueue) throw new TypeError("Cannot nest ParallelMessageQueue.");
|
|
3866
|
+
this.queue = queue;
|
|
3867
|
+
this.workers = workers;
|
|
3868
|
+
this.nativeRetrial = queue.nativeRetrial;
|
|
3869
|
+
this.nativeDeduplication = queue.nativeDeduplication;
|
|
3870
|
+
if (queue.getDepth != null) this.getDepth = () => queue.getDepth();
|
|
3871
|
+
}
|
|
3872
|
+
enqueue(message, options) {
|
|
3873
|
+
return this.queue.enqueue(message, options);
|
|
3874
|
+
}
|
|
3875
|
+
async enqueueMany(messages, options) {
|
|
3876
|
+
if (this.queue.enqueueMany == null) {
|
|
3877
|
+
if (messages.length === 1) {
|
|
3878
|
+
await this.queue.enqueue(messages[0], options);
|
|
3879
|
+
return;
|
|
3880
|
+
}
|
|
3881
|
+
if (options?.deduplicationKey != null) throw new TypeError("Cannot enqueue a batch with a deduplicationKey: the wrapped queue does not implement enqueueMany, so ParallelMessageQueue would have to fan out to individual enqueue() calls that cannot share one deduplicationKey atomically. Wrap a queue that implements enqueueMany instead.");
|
|
3882
|
+
const errors = (await Promise.allSettled(messages.map((message) => this.queue.enqueue(message, options)))).filter((r) => r.status === "rejected").map((r) => r.reason);
|
|
3883
|
+
if (errors.length > 1) throw new AggregateError(errors, "Failed to enqueue messages.");
|
|
3884
|
+
else if (errors.length === 1) throw errors[0];
|
|
3885
|
+
return;
|
|
3886
|
+
}
|
|
3887
|
+
await this.queue.enqueueMany(messages, options);
|
|
3888
|
+
}
|
|
3889
|
+
/**
|
|
3890
|
+
* Extracts ordering key from a message if present.
|
|
3891
|
+
*
|
|
3892
|
+
* This method only works for queue implementations that deliver messages
|
|
3893
|
+
* in the wrapper format with `__fedify_ordering_key__` property. Currently,
|
|
3894
|
+
* only `DenoKvMessageQueue` and `WorkersMessageQueue` use this format.
|
|
3895
|
+
*
|
|
3896
|
+
* For other queue implementations (`InProcessMessageQueue`,
|
|
3897
|
+
* `RedisMessageQueue`, `PostgresMessageQueue`, `SqliteMessageQueue`,
|
|
3898
|
+
* `AmqpMessageQueue`), messages are delivered as raw payloads without the
|
|
3899
|
+
* wrapper, so the ordering key cannot be detected here. Those
|
|
3900
|
+
* implementations handle ordering guarantees internally.
|
|
3901
|
+
*/
|
|
3902
|
+
#extractOrderingKey(message) {
|
|
3903
|
+
if (message != null && typeof message === "object") {
|
|
3904
|
+
if ("__fedify_ordering_key__" in message) return message.__fedify_ordering_key__;
|
|
3905
|
+
}
|
|
3906
|
+
}
|
|
3907
|
+
listen(handler, options = {}) {
|
|
3908
|
+
const workers = /* @__PURE__ */ new Map();
|
|
3909
|
+
return this.queue.listen(async (message) => {
|
|
3910
|
+
while (workers.size >= this.workers) {
|
|
3911
|
+
const consumedId = await Promise.any(workers.values());
|
|
3912
|
+
workers.delete(consumedId);
|
|
3913
|
+
}
|
|
3914
|
+
const workerId = crypto.randomUUID();
|
|
3915
|
+
const orderingKey = this.#extractOrderingKey(message);
|
|
3916
|
+
if (orderingKey != null && this.#processingKeys.has(orderingKey)) await new Promise((resolve) => {
|
|
3917
|
+
this.#pendingMessages.push({
|
|
3918
|
+
message,
|
|
3919
|
+
orderingKey,
|
|
3920
|
+
resolve
|
|
3921
|
+
});
|
|
3922
|
+
});
|
|
3923
|
+
if (orderingKey != null) this.#processingKeys.add(orderingKey);
|
|
3924
|
+
const promise = this.#work(workerId, handler, message, orderingKey);
|
|
3925
|
+
workers.set(workerId, promise);
|
|
3926
|
+
}, options);
|
|
3927
|
+
}
|
|
3928
|
+
async #work(workerId, handler, message, orderingKey) {
|
|
3929
|
+
await this.#sleep(0);
|
|
3930
|
+
try {
|
|
3931
|
+
await handler(message);
|
|
3932
|
+
} finally {
|
|
3933
|
+
if (orderingKey != null) {
|
|
3934
|
+
this.#processingKeys.delete(orderingKey);
|
|
3935
|
+
const pendingIdx = this.#pendingMessages.findIndex((p) => p.orderingKey === orderingKey);
|
|
3936
|
+
if (pendingIdx >= 0) this.#pendingMessages.splice(pendingIdx, 1)[0].resolve();
|
|
3937
|
+
}
|
|
3938
|
+
}
|
|
3939
|
+
return workerId;
|
|
3940
|
+
}
|
|
3941
|
+
#sleep(ms) {
|
|
3942
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
3943
|
+
}
|
|
3944
|
+
};
|
|
3945
|
+
//#endregion
|
|
3946
|
+
//#region src/federation/tasks/enqueue.ts
|
|
3947
|
+
/**
|
|
3948
|
+
* The enqueue pipeline for custom background tasks. `ContextImpl.enqueueTask`
|
|
3949
|
+
* and `ContextImpl.enqueueTaskMany` delegate to {@link enqueueTasks} so the
|
|
3950
|
+
* handle validation, deduplication planning, payload encoding, and queue
|
|
3951
|
+
* dispatch live in one cohesive place instead of one oversized method.
|
|
3952
|
+
*
|
|
3953
|
+
* @module
|
|
3954
|
+
*/
|
|
3955
|
+
/**
|
|
3956
|
+
* Validates the task handle, plans deduplication, encodes every payload, then
|
|
3957
|
+
* dispatches the resulting messages to the queue. A single item flows through
|
|
3958
|
+
* the same pipeline as a batch, so {@link Context.enqueueTask} and
|
|
3959
|
+
* {@link Context.enqueueTaskMany} share one implementation.
|
|
3960
|
+
* @template TContextData The context data to pass to the {@link Context}.
|
|
3961
|
+
* @template TData The type of the task payload, inferred from the task's schema.
|
|
3962
|
+
* @param ctx The enqueueing dependencies assembled by `ContextImpl`.
|
|
3963
|
+
* @param task The handle returned by `defineTask()`.
|
|
3964
|
+
* @param items The payloads to enqueue, in order.
|
|
3965
|
+
* @param options The enqueue options governing delay, ordering, and dedup.
|
|
3966
|
+
* @internal
|
|
3967
|
+
*/
|
|
3968
|
+
const enqueueTasks = (ctx) => async function(task, items, options) {
|
|
3969
|
+
const def = ctx.federation.taskDefinitions.get(task.name);
|
|
3970
|
+
if (def == null || def.handle !== task) throw new TypeError(`Task ${JSON.stringify(task.name)} is not defined on this federation; pass a handle returned by its defineTask().`);
|
|
3971
|
+
const queue = ctx.federation.resolveTaskQueue(task.name);
|
|
3972
|
+
if (queue == null) throw new TypeError("No message queue is configured for tasks; pass `queue` to createFederation() or to defineTask().");
|
|
3973
|
+
if (items.length < 1) return;
|
|
3974
|
+
const plan = planDeduplication(ctx, queue, task.name, options, items.length);
|
|
3975
|
+
const messages = await Promise.all(items.map(encodeTaskMessage(ctx.codec, ctx.origin, task, options)));
|
|
3976
|
+
const claim = await claimDeduplication(ctx, plan, task.name);
|
|
3977
|
+
if (!claim.proceed) return;
|
|
3978
|
+
if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueInternal(ctx.data);
|
|
3979
|
+
try {
|
|
3980
|
+
await dispatch(queue, messages, {
|
|
3981
|
+
delay: getDurationIfDefined(options.delay),
|
|
3982
|
+
orderingKey: options.orderingKey,
|
|
3983
|
+
deduplicationKey: claim.forwardedDeduplicationKey
|
|
3984
|
+
});
|
|
3985
|
+
} catch (error) {
|
|
3986
|
+
if (claim.rollback != null) try {
|
|
3987
|
+
await claim.rollback();
|
|
3988
|
+
} catch (rollbackError) {
|
|
3989
|
+
logger$1.warn("Failed to roll back the deduplication marker for task {taskName} after a failed enqueue; it will expire by TTL. {rollbackError}", {
|
|
3990
|
+
taskName: task.name,
|
|
3991
|
+
rollbackError
|
|
3992
|
+
});
|
|
3993
|
+
}
|
|
3994
|
+
throw error;
|
|
3995
|
+
}
|
|
3996
|
+
};
|
|
3997
|
+
const getDurationIfDefined = (item) => item == null ? void 0 : Temporal.Duration.from(item);
|
|
3998
|
+
/**
|
|
3999
|
+
* Decides how a `deduplicationKey` (if any) is honored: forwarded to a native
|
|
4000
|
+
* queue, claimed via `cas`, or—when neither is available—dropped or rejected
|
|
4001
|
+
* per the federation's `taskDeduplicationFallback`. Throws the fail-fast
|
|
4002
|
+
* `TypeError`s so they precede the encode.
|
|
4003
|
+
*/
|
|
4004
|
+
function planDeduplication(ctx, queue, taskName, options, itemCount) {
|
|
4005
|
+
if (options.deduplicationKey == null) return { kind: "none" };
|
|
4006
|
+
const key = options.deduplicationKey;
|
|
4007
|
+
const native = queue.nativeDeduplication === true;
|
|
4008
|
+
const canCas = ctx.federation.kv.cas != null;
|
|
4009
|
+
const canBatchAtomically = queue.enqueueMany != null && !(queue instanceof ParallelMessageQueue && queue.queue.enqueueMany == null);
|
|
4010
|
+
if (itemCount > 1 && !canBatchAtomically && (native || canCas)) throw new TypeError(`Task ${JSON.stringify(taskName)} was enqueued as a batch with a deduplicationKey, but its message queue does not implement enqueueMany; a multi-item batch cannot be deduplicated atomically without it. Implement enqueueMany on the queue, or enqueue the tasks individually with enqueueTask().`);
|
|
4011
|
+
if (native) return {
|
|
4012
|
+
kind: "native",
|
|
4013
|
+
key
|
|
4014
|
+
};
|
|
4015
|
+
if (canCas) return {
|
|
4016
|
+
kind: "cas",
|
|
4017
|
+
key
|
|
4018
|
+
};
|
|
4019
|
+
if (ctx.federation.taskDeduplicationFallback === "closed") throw new TypeError("deduplicationKey was set but the message queue does not declare nativeDeduplication and the key-value store exposes no conditional write (cas); set taskDeduplicationFallback to \"open\" to proceed without deduplication, or use a backend that supports it.");
|
|
4020
|
+
return {
|
|
4021
|
+
kind: "open",
|
|
4022
|
+
key
|
|
4023
|
+
};
|
|
4024
|
+
}
|
|
4025
|
+
/**
|
|
4026
|
+
* Executes the planned deduplication once the payloads are encoded. A native
|
|
4027
|
+
* plan forwards its key to the queue; a `cas` plan claims the marker and stops
|
|
4028
|
+
* the enqueue when it loses the race; an `open` plan logs and proceeds.
|
|
4029
|
+
* @returns Whether to proceed, and the key (if any) to forward to the queue.
|
|
4030
|
+
*/
|
|
4031
|
+
async function claimDeduplication(ctx, plan, taskName) {
|
|
4032
|
+
switch (plan.kind) {
|
|
4033
|
+
case "native": return {
|
|
4034
|
+
proceed: true,
|
|
4035
|
+
forwardedDeduplicationKey: plan.key
|
|
4036
|
+
};
|
|
4037
|
+
case "cas": {
|
|
4038
|
+
const cacheKey = [...ctx.federation.kvPrefixes.taskDeduplication, plan.key];
|
|
4039
|
+
const token = crypto.randomUUID();
|
|
4040
|
+
if (!await ctx.federation.kv.cas(cacheKey, void 0, token, { ttl: ctx.federation.taskDeduplicationTtl })) return { proceed: false };
|
|
4041
|
+
return {
|
|
4042
|
+
proceed: true,
|
|
4043
|
+
rollback: async () => {
|
|
4044
|
+
await ctx.federation.kv.cas(cacheKey, token, void 0);
|
|
4045
|
+
}
|
|
4046
|
+
};
|
|
4047
|
+
}
|
|
4048
|
+
case "open": logger$1.debug("deduplicationKey {deduplicationKey} for task {taskName} ignored: the message queue declares no nativeDeduplication and the key-value store has no cas; proceeding (taskDeduplicationFallback is \"open\").", {
|
|
4049
|
+
deduplicationKey: plan.key,
|
|
4050
|
+
taskName
|
|
4051
|
+
});
|
|
4052
|
+
case "none": return { proceed: true };
|
|
4053
|
+
default: throw new TypeError(`Unknown deduplication plan: ${JSON.stringify(plan)}`);
|
|
4054
|
+
}
|
|
4055
|
+
}
|
|
4056
|
+
/**
|
|
4057
|
+
* Sends the encoded messages to the queue, picking the bulk path when the
|
|
4058
|
+
* queue implements `enqueueMany` and otherwise fanning out parallel single
|
|
4059
|
+
* enqueues. The fan-out drops `deduplicationKey`, which is only ever set for a
|
|
4060
|
+
* native plan that the bulk paths already cover.
|
|
4061
|
+
*/
|
|
4062
|
+
async function dispatch(queue, messages, options) {
|
|
4063
|
+
if (messages.length === 1) await queue.enqueue(messages[0], options);
|
|
4064
|
+
else if (queue.enqueueMany != null) await queue.enqueueMany(messages, options);
|
|
4065
|
+
else {
|
|
4066
|
+
const fanoutOptions = {
|
|
4067
|
+
delay: options.delay,
|
|
4068
|
+
orderingKey: options.orderingKey
|
|
4069
|
+
};
|
|
4070
|
+
await Promise.all(messages.map((m) => queue.enqueue(m, fanoutOptions)));
|
|
4071
|
+
}
|
|
4072
|
+
}
|
|
4073
|
+
/**
|
|
4074
|
+
* Builds the per-payload encoder: validates and serializes the payload, then
|
|
4075
|
+
* stamps the message envelope with a fresh id, the context's origin, and the
|
|
4076
|
+
* active trace context. Curried so the batch encode reuses one bound encoder.
|
|
4077
|
+
*/
|
|
4078
|
+
const encodeTaskMessage = (codec, origin, task, options) => async (data) => {
|
|
4079
|
+
const encoded = await codec.encode(task.schema, data);
|
|
4080
|
+
const carrier = {};
|
|
4081
|
+
_opentelemetry_api.propagation.inject(_opentelemetry_api.context.active(), carrier);
|
|
4082
|
+
return {
|
|
4083
|
+
type: "task",
|
|
4084
|
+
id: crypto.randomUUID(),
|
|
4085
|
+
baseUrl: origin,
|
|
4086
|
+
taskName: task.name,
|
|
4087
|
+
data: encoded,
|
|
4088
|
+
started: Temporal.Now.instant().toString(),
|
|
4089
|
+
attempt: 0,
|
|
4090
|
+
orderingKey: options.orderingKey,
|
|
4091
|
+
traceContext: carrier
|
|
4092
|
+
};
|
|
4093
|
+
};
|
|
4094
|
+
const logger$1 = (0, _logtape_logtape.getLogger)([
|
|
4095
|
+
"fedify",
|
|
4096
|
+
"federation",
|
|
4097
|
+
"task"
|
|
4098
|
+
]);
|
|
4099
|
+
//#endregion
|
|
3556
4100
|
//#region src/federation/webfinger.ts
|
|
3557
4101
|
const logger = (0, _logtape_logtape.getLogger)([
|
|
3558
4102
|
"fedify",
|
|
@@ -3886,9 +4430,8 @@ var FederationImpl = class extends FederationBuilderImpl {
|
|
|
3886
4430
|
inboxQueue;
|
|
3887
4431
|
outboxQueue;
|
|
3888
4432
|
fanoutQueue;
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
fanoutQueueStarted;
|
|
4433
|
+
taskQueue;
|
|
4434
|
+
startedQueues;
|
|
3892
4435
|
manuallyStartQueue;
|
|
3893
4436
|
origin;
|
|
3894
4437
|
documentLoaderFactory;
|
|
@@ -3902,6 +4445,10 @@ var FederationImpl = class extends FederationBuilderImpl {
|
|
|
3902
4445
|
skipSignatureVerification;
|
|
3903
4446
|
outboxRetryPolicy;
|
|
3904
4447
|
inboxRetryPolicy;
|
|
4448
|
+
taskRetryPolicy;
|
|
4449
|
+
taskQueueResolution;
|
|
4450
|
+
taskDeduplicationTtl;
|
|
4451
|
+
taskDeduplicationFallback;
|
|
3905
4452
|
circuitBreaker;
|
|
3906
4453
|
activityTransformers;
|
|
3907
4454
|
_tracerProvider;
|
|
@@ -3941,20 +4488,24 @@ var FederationImpl = class extends FederationBuilderImpl {
|
|
|
3941
4488
|
httpMessageSignaturesSpec: ["_fedify", "httpMessageSignaturesSpec"],
|
|
3942
4489
|
acceptSignatureNonce: ["_fedify", "acceptSignatureNonce"],
|
|
3943
4490
|
circuitBreaker: ["_fedify", "circuit"],
|
|
4491
|
+
taskDeduplication: ["_fedify", "taskDeduplication"],
|
|
3944
4492
|
...options.kvPrefixes ?? {}
|
|
3945
4493
|
};
|
|
3946
4494
|
if (options.queue == null) {
|
|
3947
4495
|
this.inboxQueue = void 0;
|
|
3948
4496
|
this.outboxQueue = void 0;
|
|
3949
4497
|
this.fanoutQueue = void 0;
|
|
4498
|
+
this.taskQueue = void 0;
|
|
3950
4499
|
} else if ("enqueue" in options.queue && "listen" in options.queue) {
|
|
3951
4500
|
this.inboxQueue = options.queue;
|
|
3952
4501
|
this.outboxQueue = options.queue;
|
|
3953
4502
|
this.fanoutQueue = options.queue;
|
|
4503
|
+
this.taskQueue = void 0;
|
|
3954
4504
|
} else {
|
|
3955
4505
|
this.inboxQueue = options.queue.inbox;
|
|
3956
4506
|
this.outboxQueue = options.queue.outbox;
|
|
3957
4507
|
this.fanoutQueue = options.queue.fanout;
|
|
4508
|
+
this.taskQueue = options.queue.task;
|
|
3958
4509
|
}
|
|
3959
4510
|
if (options.circuitBreaker !== false && this.outboxQueue != null) {
|
|
3960
4511
|
this.circuitBreaker = new CircuitBreaker({
|
|
@@ -3975,9 +4526,7 @@ var FederationImpl = class extends FederationBuilderImpl {
|
|
|
3975
4526
|
]).warn("The configured key-value store does not support CAS; outbound delivery circuit breaker updates may race under concurrent workers.");
|
|
3976
4527
|
}
|
|
3977
4528
|
}
|
|
3978
|
-
this.
|
|
3979
|
-
this.outboxQueueStarted = false;
|
|
3980
|
-
this.fanoutQueueStarted = false;
|
|
4529
|
+
this.startedQueues = /* @__PURE__ */ new Set();
|
|
3981
4530
|
this.manuallyStartQueue = options.manuallyStartQueue ?? false;
|
|
3982
4531
|
if (options.origin != null) if (typeof options.origin === "string") {
|
|
3983
4532
|
if (!URL.canParse(options.origin) || !options.origin.match(/^https?:\/\//)) throw new TypeError(`Invalid origin: ${JSON.stringify(options.origin)}`);
|
|
@@ -4059,6 +4608,10 @@ var FederationImpl = class extends FederationBuilderImpl {
|
|
|
4059
4608
|
this.inboxChallengePolicy = options.inboxChallengePolicy;
|
|
4060
4609
|
this.outboxRetryPolicy = options.outboxRetryPolicy ?? createExponentialBackoffPolicy();
|
|
4061
4610
|
this.inboxRetryPolicy = options.inboxRetryPolicy ?? createExponentialBackoffPolicy();
|
|
4611
|
+
this.taskRetryPolicy = options.taskRetryPolicy ?? createExponentialBackoffPolicy();
|
|
4612
|
+
this.taskQueueResolution = options.taskQueueResolution ?? "fallback";
|
|
4613
|
+
this.taskDeduplicationTtl = Temporal.Duration.from(options.taskDeduplicationTtl ?? { hours: 1 });
|
|
4614
|
+
this.taskDeduplicationFallback = options.taskDeduplicationFallback ?? "open";
|
|
4062
4615
|
this.activityTransformers = options.activityTransformers ?? require_transformers.getDefaultActivityTransformers();
|
|
4063
4616
|
this._tracerProvider = options.tracerProvider;
|
|
4064
4617
|
if (benchmarkMode) {
|
|
@@ -4107,28 +4660,33 @@ var FederationImpl = class extends FederationBuilderImpl {
|
|
|
4107
4660
|
_getTracer() {
|
|
4108
4661
|
return this.tracerProvider.getTracer(require_http.name, require_http.version);
|
|
4109
4662
|
}
|
|
4663
|
+
resolveTaskQueue(taskName) {
|
|
4664
|
+
const resolved = this.taskDefinitions.get(taskName)?.queue ?? this.taskQueue;
|
|
4665
|
+
if (resolved != null) return resolved;
|
|
4666
|
+
return this.taskQueueResolution === "strict" ? void 0 : this.outboxQueue;
|
|
4667
|
+
}
|
|
4110
4668
|
async _startQueueInternal(ctxData, signal, queue) {
|
|
4111
|
-
|
|
4669
|
+
const taskQueue = this.taskQueue ?? (this.taskQueueResolution === "fallback" ? this.outboxQueue : void 0);
|
|
4670
|
+
const customQueues = this.taskDefinitions.values().map((def) => ["task", def.queue]);
|
|
4671
|
+
const targets = [
|
|
4672
|
+
["inbox", this.inboxQueue],
|
|
4673
|
+
["outbox", this.outboxQueue],
|
|
4674
|
+
["fanout", this.fanoutQueue],
|
|
4675
|
+
["task", taskQueue],
|
|
4676
|
+
...customQueues
|
|
4677
|
+
];
|
|
4112
4678
|
const logger = (0, _logtape_logtape.getLogger)([
|
|
4113
4679
|
"fedify",
|
|
4114
4680
|
"federation",
|
|
4115
4681
|
"queue"
|
|
4116
4682
|
]);
|
|
4117
4683
|
const promises = [];
|
|
4118
|
-
|
|
4119
|
-
|
|
4120
|
-
this.
|
|
4121
|
-
|
|
4122
|
-
|
|
4123
|
-
|
|
4124
|
-
logger.debug("Starting an outbox task worker.");
|
|
4125
|
-
this.outboxQueueStarted = true;
|
|
4126
|
-
promises.push(this.outboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
|
|
4127
|
-
}
|
|
4128
|
-
if (this.fanoutQueue != null && this.fanoutQueue !== this.inboxQueue && this.fanoutQueue !== this.outboxQueue && (queue == null || queue === "fanout") && !this.fanoutQueueStarted) {
|
|
4129
|
-
logger.debug("Starting a fanout task worker.");
|
|
4130
|
-
this.fanoutQueueStarted = true;
|
|
4131
|
-
promises.push(this.fanoutQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
|
|
4684
|
+
for (const [role, target] of targets) {
|
|
4685
|
+
if (target == null || !(queue == null || queue === role)) continue;
|
|
4686
|
+
if (this.startedQueues.has(target)) continue;
|
|
4687
|
+
this.startedQueues.add(target);
|
|
4688
|
+
logger.debug("Starting a {role} queue worker.", { role });
|
|
4689
|
+
promises.push(target.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
|
|
4132
4690
|
}
|
|
4133
4691
|
await Promise.all(promises);
|
|
4134
4692
|
}
|
|
@@ -4251,7 +4809,7 @@ var FederationImpl = class extends FederationBuilderImpl {
|
|
|
4251
4809
|
}
|
|
4252
4810
|
});
|
|
4253
4811
|
});
|
|
4254
|
-
}
|
|
4812
|
+
} else if (message.type === "task") await this.#listenTaskMessage(contextData, message);
|
|
4255
4813
|
});
|
|
4256
4814
|
}
|
|
4257
4815
|
async #listenFanoutMessage(data, message) {
|
|
@@ -4815,6 +5373,77 @@ var FederationImpl = class extends FederationBuilderImpl {
|
|
|
4815
5373
|
listenerSpan.end();
|
|
4816
5374
|
});
|
|
4817
5375
|
}
|
|
5376
|
+
async #listenTaskMessage(contextData, message) {
|
|
5377
|
+
const logger = (0, _logtape_logtape.getLogger)([
|
|
5378
|
+
"fedify",
|
|
5379
|
+
"federation",
|
|
5380
|
+
"task"
|
|
5381
|
+
]);
|
|
5382
|
+
const def = this.taskDefinitions.get(message.taskName);
|
|
5383
|
+
if (def == null) {
|
|
5384
|
+
logger.warn("Received a custom task {taskName} with no registered handler; dropping.", { taskName: message.taskName });
|
|
5385
|
+
return;
|
|
5386
|
+
}
|
|
5387
|
+
const context = this.#createContext(new URL(message.baseUrl), contextData);
|
|
5388
|
+
let data;
|
|
5389
|
+
try {
|
|
5390
|
+
data = await context.codec.decode(def.schema, message.data);
|
|
5391
|
+
} catch (error) {
|
|
5392
|
+
logger.error("Custom task {taskName} payload could not be decoded or validated; dropping:\n{error}", {
|
|
5393
|
+
taskName: message.taskName,
|
|
5394
|
+
error
|
|
5395
|
+
});
|
|
5396
|
+
return;
|
|
5397
|
+
}
|
|
5398
|
+
try {
|
|
5399
|
+
await def.handler(context, data);
|
|
5400
|
+
} catch (error) {
|
|
5401
|
+
if (def.onError != null) try {
|
|
5402
|
+
await def.onError(context, error, data);
|
|
5403
|
+
} catch (onErrorError) {
|
|
5404
|
+
logger.error("onError for custom task {taskName} threw:\n{error}", {
|
|
5405
|
+
taskName: message.taskName,
|
|
5406
|
+
error: onErrorError
|
|
5407
|
+
});
|
|
5408
|
+
}
|
|
5409
|
+
const queue = this.resolveTaskQueue(def.name);
|
|
5410
|
+
if (queue?.nativeRetrial) throw error;
|
|
5411
|
+
const retryPolicy = def.retryPolicy ?? this.taskRetryPolicy;
|
|
5412
|
+
let elapsedTime = Temporal.Duration.from({ seconds: 0 });
|
|
5413
|
+
try {
|
|
5414
|
+
elapsedTime = Temporal.Instant.from(message.started).until(Temporal.Now.instant());
|
|
5415
|
+
} catch (parseError) {
|
|
5416
|
+
logger.error("Custom task {taskName} has an unparsable started time {started}; treating elapsedTime as zero:\n{error}", {
|
|
5417
|
+
taskName: message.taskName,
|
|
5418
|
+
started: message.started,
|
|
5419
|
+
error: parseError
|
|
5420
|
+
});
|
|
5421
|
+
}
|
|
5422
|
+
const delay = retryPolicy({
|
|
5423
|
+
elapsedTime,
|
|
5424
|
+
attempts: message.attempt
|
|
5425
|
+
});
|
|
5426
|
+
if (delay != null && queue != null) {
|
|
5427
|
+
logger.error("Custom task {taskName} failed (attempt #{attempt}); retry...:\n{error}", {
|
|
5428
|
+
taskName: message.taskName,
|
|
5429
|
+
attempt: message.attempt,
|
|
5430
|
+
error
|
|
5431
|
+
});
|
|
5432
|
+
const retryMessage = {
|
|
5433
|
+
...message,
|
|
5434
|
+
attempt: message.attempt + 1
|
|
5435
|
+
};
|
|
5436
|
+
await queue.enqueue(retryMessage, {
|
|
5437
|
+
delay: clampNegativeDelay(delay),
|
|
5438
|
+
orderingKey: message.orderingKey
|
|
5439
|
+
});
|
|
5440
|
+
} else logger.error("Custom task {taskName} failed after {attempt} attempts; giving up:\n{error}", {
|
|
5441
|
+
taskName: message.taskName,
|
|
5442
|
+
attempt: message.attempt,
|
|
5443
|
+
error
|
|
5444
|
+
});
|
|
5445
|
+
}
|
|
5446
|
+
}
|
|
4818
5447
|
startQueue(contextData, options = {}) {
|
|
4819
5448
|
return this._startQueueInternal(contextData, options.signal, options.queue);
|
|
4820
5449
|
}
|
|
@@ -5399,6 +6028,7 @@ var ContextImpl = class ContextImpl {
|
|
|
5399
6028
|
documentLoader;
|
|
5400
6029
|
contextLoader;
|
|
5401
6030
|
invokedFromActorKeyPairsDispatcher;
|
|
6031
|
+
#codec;
|
|
5402
6032
|
constructor({ url, federation, data, documentLoader, contextLoader, invokedFromActorKeyPairsDispatcher }) {
|
|
5403
6033
|
this.url = url;
|
|
5404
6034
|
this.federation = federation;
|
|
@@ -5407,6 +6037,18 @@ var ContextImpl = class ContextImpl {
|
|
|
5407
6037
|
this.contextLoader = contextLoader;
|
|
5408
6038
|
this.invokedFromActorKeyPairsDispatcher = invokedFromActorKeyPairsDispatcher;
|
|
5409
6039
|
}
|
|
6040
|
+
/**
|
|
6041
|
+
* A {@link TaskCodec} bound to this context's loaders, used to encode
|
|
6042
|
+
* and decode custom task payloads. Lazily created and cached so a context
|
|
6043
|
+
* that never enqueues or dispatches a task pays nothing.
|
|
6044
|
+
* @internal
|
|
6045
|
+
*/
|
|
6046
|
+
get codec() {
|
|
6047
|
+
return this.#codec ??= new TaskCodec(this);
|
|
6048
|
+
}
|
|
6049
|
+
get #enqueueTasks() {
|
|
6050
|
+
return enqueueTasks(this);
|
|
6051
|
+
}
|
|
5410
6052
|
clone(data) {
|
|
5411
6053
|
return new ContextImpl({
|
|
5412
6054
|
url: this.url,
|
|
@@ -5725,6 +6367,12 @@ var ContextImpl = class ContextImpl {
|
|
|
5725
6367
|
allowPrivateAddress: this.federation.allowPrivateAddress
|
|
5726
6368
|
});
|
|
5727
6369
|
}
|
|
6370
|
+
async enqueueTask(task, data, options = {}) {
|
|
6371
|
+
await this.#enqueueTasks(task, [data], options);
|
|
6372
|
+
}
|
|
6373
|
+
async enqueueTaskMany(task, payloads, options = {}) {
|
|
6374
|
+
await this.#enqueueTasks(task, payloads, options);
|
|
6375
|
+
}
|
|
5728
6376
|
sendActivity(sender, recipients, activity, options = {}) {
|
|
5729
6377
|
return this.tracerProvider.getTracer(require_http.name, require_http.version).startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
|
|
5730
6378
|
kind: this.federation.outboxQueue == null || options.immediate ? _opentelemetry_api.SpanKind.CLIENT : _opentelemetry_api.SpanKind.PRODUCER,
|
|
@@ -6441,6 +7089,18 @@ Object.defineProperty(exports, "CircuitBreaker", {
|
|
|
6441
7089
|
return CircuitBreaker;
|
|
6442
7090
|
}
|
|
6443
7091
|
});
|
|
7092
|
+
Object.defineProperty(exports, "InProcessMessageQueue", {
|
|
7093
|
+
enumerable: true,
|
|
7094
|
+
get: function() {
|
|
7095
|
+
return InProcessMessageQueue;
|
|
7096
|
+
}
|
|
7097
|
+
});
|
|
7098
|
+
Object.defineProperty(exports, "ParallelMessageQueue", {
|
|
7099
|
+
enumerable: true,
|
|
7100
|
+
get: function() {
|
|
7101
|
+
return ParallelMessageQueue;
|
|
7102
|
+
}
|
|
7103
|
+
});
|
|
6444
7104
|
Object.defineProperty(exports, "SendActivityError", {
|
|
6445
7105
|
enumerable: true,
|
|
6446
7106
|
get: function() {
|