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