@fedify/fedify 2.5.0-dev.2687 → 2.5.0-dev.2710

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 (244) hide show
  1. package/dist/federation/mod.cjs +1 -1
  2. package/dist/federation/mod.js +1 -1
  3. package/dist/{federation-pFFwPyoZ.cjs → federation-JvzYDx0P.cjs} +3 -3
  4. package/dist/{http-CXX-QPzs.cjs → http-BG5cDmTS.cjs} +1 -1
  5. package/dist/{http-T7h9GBAN.js → http-MUf125Jc.js} +1 -1
  6. package/dist/{kv-cache-C6XX_fwz.cjs → kv-cache-A2po7h0_.cjs} +1 -1
  7. package/dist/{kv-cache-EFcb1kkU.js → kv-cache-CbWc1BZA.js} +1 -1
  8. package/dist/{middleware-Bj91r7r2.js → middleware-DzzdJ7Wz.js} +3 -3
  9. package/dist/mod.cjs +4 -4
  10. package/dist/mod.js +4 -4
  11. package/dist/{portable-collection-Do5QA2oy.js → portable-collection-CAer9RWN.js} +1 -1
  12. package/dist/{portable-collection-BOl9oKrt.cjs → portable-collection-d8w7TCn9.cjs} +1 -1
  13. package/dist/sig/mod.cjs +2 -2
  14. package/dist/sig/mod.js +2 -2
  15. package/dist/utils/mod.cjs +1 -1
  16. package/dist/utils/mod.js +1 -1
  17. package/package.json +22 -9
  18. package/skills/fedify/SKILL.md +10 -0
  19. package/dist/accept-CPVqki78.mjs +0 -145
  20. package/dist/activity-listener-CELFAodc.mjs +0 -44
  21. package/dist/assert-D1Eafmd_.mjs +0 -23
  22. package/dist/assert_equals-Z6IcEbWU.mjs +0 -987
  23. package/dist/assert_exists-cffSpJ7X.mjs +0 -28
  24. package/dist/assert_false-CPdRnc3E.mjs +0 -23
  25. package/dist/assert_greater_or_equal-BlafOF4-.mjs +0 -31
  26. package/dist/assert_instance_of-mrXWWNY-.mjs +0 -37
  27. package/dist/assert_not_equals-CpPK2t89.mjs +0 -30
  28. package/dist/assert_rejects-CTptdYck.mjs +0 -39
  29. package/dist/assert_strict_equals-CYvBmkpC.mjs +0 -42
  30. package/dist/assert_throws-BYITOvPO.mjs +0 -74
  31. package/dist/assertion_error-B-cx0fFA.mjs +0 -31
  32. package/dist/audience-CHQ-FlLD.mjs +0 -95
  33. package/dist/builder-D1FP_5nQ.mjs +0 -911
  34. package/dist/circuit-breaker-XJ53md4S.mjs +0 -544
  35. package/dist/circuit-breaker-test-utils-DW6YC_Pe.mjs +0 -14
  36. package/dist/client-5SIFzW3q.mjs +0 -441
  37. package/dist/codec-C6rTrpIp.mjs +0 -147
  38. package/dist/collection-CnnP1UAv.mjs +0 -44
  39. package/dist/compat/outgoing-jsonld.test.d.mts +0 -2
  40. package/dist/compat/outgoing-jsonld.test.mjs +0 -257
  41. package/dist/compat/public-audience.test.d.mts +0 -2
  42. package/dist/compat/public-audience.test.mjs +0 -187
  43. package/dist/compat/secured-document.test.d.mts +0 -2
  44. package/dist/compat/secured-document.test.mjs +0 -58
  45. package/dist/compat/transformers.test.d.mts +0 -2
  46. package/dist/compat/transformers.test.mjs +0 -62
  47. package/dist/compound-proof-DSHhnOEW.mjs +0 -1019
  48. package/dist/context-LgGFFSz7.mjs +0 -146
  49. package/dist/deno-C50ikGBU.mjs +0 -8
  50. package/dist/dist-_geWsuaI.mjs +0 -189
  51. package/dist/docloader-BY-SEID0.mjs +0 -136
  52. package/dist/esm-BHXXx4Wx.mjs +0 -1233
  53. package/dist/exporter-DVG68ozH.mjs +0 -263
  54. package/dist/federation/audience.test.d.mts +0 -2
  55. package/dist/federation/audience.test.mjs +0 -130
  56. package/dist/federation/builder.test.d.mts +0 -2
  57. package/dist/federation/builder.test.mjs +0 -396
  58. package/dist/federation/circuit-breaker.test.d.mts +0 -2
  59. package/dist/federation/circuit-breaker.test.mjs +0 -1277
  60. package/dist/federation/collection.test.d.mts +0 -2
  61. package/dist/federation/collection.test.mjs +0 -21
  62. package/dist/federation/compound-fanout.test.d.mts +0 -2
  63. package/dist/federation/compound-fanout.test.mjs +0 -231
  64. package/dist/federation/handler-compound-proof.test.d.mts +0 -2
  65. package/dist/federation/handler-compound-proof.test.mjs +0 -384
  66. package/dist/federation/handler.test.d.mts +0 -2
  67. package/dist/federation/handler.test.mjs +0 -5445
  68. package/dist/federation/hashlink-media.test.d.mts +0 -2
  69. package/dist/federation/hashlink-media.test.mjs +0 -422
  70. package/dist/federation/idempotency.test.d.mts +0 -2
  71. package/dist/federation/idempotency.test.mjs +0 -207
  72. package/dist/federation/inbox-actorless.test.d.mts +0 -2
  73. package/dist/federation/inbox-actorless.test.mjs +0 -522
  74. package/dist/federation/inbox-authentication.test.d.mts +0 -2
  75. package/dist/federation/inbox-authentication.test.mjs +0 -220
  76. package/dist/federation/inbox-report.test.d.mts +0 -2
  77. package/dist/federation/inbox-report.test.mjs +0 -719
  78. package/dist/federation/inbox-view.test.d.mts +0 -2
  79. package/dist/federation/inbox-view.test.mjs +0 -369
  80. package/dist/federation/inbox.test.d.mts +0 -2
  81. package/dist/federation/inbox.test.mjs +0 -139
  82. package/dist/federation/keycache.test.d.mts +0 -2
  83. package/dist/federation/keycache.test.mjs +0 -337
  84. package/dist/federation/kv.test.d.mts +0 -2
  85. package/dist/federation/kv.test.mjs +0 -88
  86. package/dist/federation/metrics.test.d.mts +0 -2
  87. package/dist/federation/metrics.test.mjs +0 -634
  88. package/dist/federation/middleware.test.d.mts +0 -2
  89. package/dist/federation/middleware.test.mjs +0 -9314
  90. package/dist/federation/mq.test.d.mts +0 -2
  91. package/dist/federation/mq.test.mjs +0 -591
  92. package/dist/federation/negotiation.test.d.mts +0 -2
  93. package/dist/federation/negotiation.test.mjs +0 -18
  94. package/dist/federation/outbound-body.test.d.mts +0 -2
  95. package/dist/federation/outbound-body.test.mjs +0 -149
  96. package/dist/federation/outbound-capture.test.d.mts +0 -2
  97. package/dist/federation/outbound-capture.test.mjs +0 -394
  98. package/dist/federation/outbound-dispatch.test.d.mts +0 -2
  99. package/dist/federation/outbound-dispatch.test.mjs +0 -368
  100. package/dist/federation/outbound-document.test.d.mts +0 -2
  101. package/dist/federation/outbound-document.test.mjs +0 -171
  102. package/dist/federation/outbound-provenance.test.d.mts +0 -2
  103. package/dist/federation/outbound-provenance.test.mjs +0 -543
  104. package/dist/federation/outbound-report.test.d.mts +0 -2
  105. package/dist/federation/outbound-report.test.mjs +0 -5475
  106. package/dist/federation/outbound-workers.test.d.mts +0 -2
  107. package/dist/federation/outbound-workers.test.mjs +0 -64
  108. package/dist/federation/outbound-workflow.test.d.mts +0 -2
  109. package/dist/federation/outbound-workflow.test.mjs +0 -154
  110. package/dist/federation/outgoing-proof.test.d.mts +0 -2
  111. package/dist/federation/outgoing-proof.test.mjs +0 -933
  112. package/dist/federation/portable-actor.test.d.mts +0 -2
  113. package/dist/federation/portable-actor.test.mjs +0 -496
  114. package/dist/federation/portable-chain.test.d.mts +0 -2
  115. package/dist/federation/portable-chain.test.mjs +0 -370
  116. package/dist/federation/portable-collection.test.d.mts +0 -2
  117. package/dist/federation/portable-collection.test.mjs +0 -832
  118. package/dist/federation/portable-delivery.test.d.mts +0 -2
  119. package/dist/federation/portable-delivery.test.mjs +0 -845
  120. package/dist/federation/portable-gateway-keys.test.d.mts +0 -2
  121. package/dist/federation/portable-gateway-keys.test.mjs +0 -692
  122. package/dist/federation/portable-inbox.test.d.mts +0 -2
  123. package/dist/federation/portable-inbox.test.mjs +0 -1960
  124. package/dist/federation/portable-parse-uri.test.d.mts +0 -2
  125. package/dist/federation/portable-parse-uri.test.mjs +0 -348
  126. package/dist/federation/portable-route-activity.test.d.mts +0 -2
  127. package/dist/federation/portable-route-activity.test.mjs +0 -259
  128. package/dist/federation/portable.test.d.mts +0 -2
  129. package/dist/federation/portable.test.mjs +0 -1072
  130. package/dist/federation/retry.test.d.mts +0 -2
  131. package/dist/federation/retry.test.mjs +0 -42
  132. package/dist/federation/router.test.d.mts +0 -2
  133. package/dist/federation/router.test.mjs +0 -123
  134. package/dist/federation/send.test.d.mts +0 -2
  135. package/dist/federation/send.test.mjs +0 -1421
  136. package/dist/federation/tasks/codec.test.d.mts +0 -2
  137. package/dist/federation/tasks/codec.test.mjs +0 -302
  138. package/dist/federation/tasks/enqueue.test.d.mts +0 -2
  139. package/dist/federation/tasks/enqueue.test.mjs +0 -1095
  140. package/dist/federation/tasks/tasks.test.d.mts +0 -2
  141. package/dist/federation/tasks/tasks.test.mjs +0 -1229
  142. package/dist/federation/temporal.test.d.mts +0 -2
  143. package/dist/federation/temporal.test.mjs +0 -71
  144. package/dist/federation/webfinger.test.d.mts +0 -2
  145. package/dist/federation/webfinger.test.mjs +0 -944
  146. package/dist/http-BXbQQZDM.mjs +0 -1449
  147. package/dist/inbox-authentication-CgonVRkg.mjs +0 -198
  148. package/dist/inbox-cS97XzOD.mjs +0 -399
  149. package/dist/inbox-view-D-d0Ar6o.mjs +0 -385
  150. package/dist/key-owner-evidence-APB6NpSk.mjs +0 -108
  151. package/dist/keycache-N2opu4-3.mjs +0 -221
  152. package/dist/keys-DIJNHW-Y.mjs +0 -120
  153. package/dist/kv-DBRWVx3Q.mjs +0 -104
  154. package/dist/kv-DCHkaJ9-.mjs +0 -92
  155. package/dist/kv-cache-fgbLHGVL.mjs +0 -121
  156. package/dist/ld-BpkhkDGj.mjs +0 -1752
  157. package/dist/map-local-context-conflict-DOYEEJ3u.mjs +0 -204
  158. package/dist/map-local-create-note-B0SeXJms.mjs +0 -214
  159. package/dist/metrics-Uqf8GomB.mjs +0 -818
  160. package/dist/middleware-DcXzz-YK.mjs +0 -9971
  161. package/dist/middleware-DgwZkvJR.mjs +0 -5
  162. package/dist/mq-eF96QxUT.mjs +0 -288
  163. package/dist/negotiation-BAKO9nih.mjs +0 -96
  164. package/dist/nodeinfo/client.test.d.mts +0 -2
  165. package/dist/nodeinfo/client.test.mjs +0 -1364
  166. package/dist/nodeinfo/handler.test.d.mts +0 -2
  167. package/dist/nodeinfo/handler.test.mjs +0 -94
  168. package/dist/nodeinfo/types.test.d.mts +0 -2
  169. package/dist/nodeinfo/types.test.mjs +0 -192
  170. package/dist/otel/exporter.test.d.mts +0 -2
  171. package/dist/otel/exporter.test.mjs +0 -887
  172. package/dist/outbound-body-CckPA5gc.mjs +0 -83
  173. package/dist/outbound-capture-DVgnRzlf.mjs +0 -184
  174. package/dist/outbound-document-BMgwLXTY.mjs +0 -179
  175. package/dist/outgoing-jsonld-4IJqPYos.mjs +0 -205
  176. package/dist/owner-BVenIFg1.mjs +0 -267
  177. package/dist/portable-collection-DIk9gpjL.mjs +0 -418
  178. package/dist/portable-key-C7pVaHNR.mjs +0 -549
  179. package/dist/portable-key-id-Ca30-hOa.mjs +0 -248
  180. package/dist/proof-BlfZ95--.mjs +0 -1420
  181. package/dist/public-audience--klBIOk1.mjs +0 -197
  182. package/dist/retry-zX5xw5e0.mjs +0 -34
  183. package/dist/router-u5O5KCQr.mjs +0 -156
  184. package/dist/secured-document-CxzZZ9nL.mjs +0 -35
  185. package/dist/send-DEGHPGFk.mjs +0 -710
  186. package/dist/sig/accept.test.d.mts +0 -2
  187. package/dist/sig/accept.test.mjs +0 -416
  188. package/dist/sig/compound-proof-discovery.test.d.mts +0 -2
  189. package/dist/sig/compound-proof-discovery.test.mjs +0 -331
  190. package/dist/sig/compound-proof-producer.test.d.mts +0 -2
  191. package/dist/sig/compound-proof-producer.test.mjs +0 -107
  192. package/dist/sig/compound-proof-verification.test.d.mts +0 -2
  193. package/dist/sig/compound-proof-verification.test.mjs +0 -1017
  194. package/dist/sig/compound-proof.test.d.mts +0 -2
  195. package/dist/sig/compound-proof.test.mjs +0 -411
  196. package/dist/sig/http.test.d.mts +0 -2
  197. package/dist/sig/http.test.mjs +0 -3328
  198. package/dist/sig/key-owner-evidence.test.d.mts +0 -2
  199. package/dist/sig/key-owner-evidence.test.mjs +0 -100
  200. package/dist/sig/key.test.d.mts +0 -2
  201. package/dist/sig/key.test.mjs +0 -1250
  202. package/dist/sig/ld.test.d.mts +0 -2
  203. package/dist/sig/ld.test.mjs +0 -1044
  204. package/dist/sig/mitra-receive-interop.test.d.mts +0 -2
  205. package/dist/sig/mitra-receive-interop.test.mjs +0 -260
  206. package/dist/sig/mitra-send-interop.test.d.mts +0 -2
  207. package/dist/sig/mitra-send-interop.test.mjs +0 -461
  208. package/dist/sig/owner.test.d.mts +0 -2
  209. package/dist/sig/owner.test.mjs +0 -202
  210. package/dist/sig/portable-collection.test.d.mts +0 -2
  211. package/dist/sig/portable-collection.test.mjs +0 -697
  212. package/dist/sig/portable-interop.test.d.mts +0 -2
  213. package/dist/sig/portable-interop.test.mjs +0 -156
  214. package/dist/sig/portable-key-id.test.d.mts +0 -2
  215. package/dist/sig/portable-key-id.test.mjs +0 -67
  216. package/dist/sig/portable-key.test.d.mts +0 -2
  217. package/dist/sig/portable-key.test.mjs +0 -1438
  218. package/dist/sig/proof.test.d.mts +0 -2
  219. package/dist/sig/proof.test.mjs +0 -2638
  220. package/dist/sig/tootik-request-interop.test.d.mts +0 -2
  221. package/dist/sig/tootik-request-interop.test.mjs +0 -190
  222. package/dist/sig/tootik-send-interop.test.d.mts +0 -2
  223. package/dist/sig/tootik-send-interop.test.mjs +0 -331
  224. package/dist/sig/verification.test.d.mts +0 -2
  225. package/dist/sig/verification.test.mjs +0 -310
  226. package/dist/std__assert-DvMDRPes.mjs +0 -8
  227. package/dist/tasks-BCUmQbbz.mjs +0 -77
  228. package/dist/temporal-B4oQ8HpW.mjs +0 -95
  229. package/dist/testing/context.test.d.mts +0 -2
  230. package/dist/testing/context.test.mjs +0 -19
  231. package/dist/testing/kv.test.d.mts +0 -2
  232. package/dist/testing/kv.test.mjs +0 -101
  233. package/dist/testing/mod.d.mts +0 -6099
  234. package/dist/testing/mod.mjs +0 -9
  235. package/dist/testing-vrnD5Uaa.mjs +0 -8
  236. package/dist/types-DE_LV1JB.mjs +0 -46
  237. package/dist/utils/docloader.test.d.mts +0 -2
  238. package/dist/utils/docloader.test.mjs +0 -1076
  239. package/dist/utils/kv-cache.test.d.mts +0 -2
  240. package/dist/utils/kv-cache.test.mjs +0 -261
  241. package/dist/verification-C3954hQh.mjs +0 -5
  242. package/dist/verification-Dpfcw8ml.mjs +0 -105
  243. package/dist/vocab/cjs.test.d.mts +0 -2
  244. package/dist/vocab/cjs.test.mjs +0 -27
@@ -1,1421 +0,0 @@
1
- import "temporal-polyfill";
2
- import "urlpattern-polyfill";
3
- globalThis.addEventListener = () => {};
4
- import { t as esm_default } from "../esm-BHXXx4Wx.mjs";
5
- import { t as MemoryKvStore } from "../kv-DCHkaJ9-.mjs";
6
- import { t as assertEquals } from "../assert_equals-Z6IcEbWU.mjs";
7
- import { t as assertFalse } from "../assert_false-CPdRnc3E.mjs";
8
- import { t as assertGreaterOrEqual } from "../assert_greater_or_equal-BlafOF4-.mjs";
9
- import { t as assertInstanceOf } from "../assert_instance_of-mrXWWNY-.mjs";
10
- import { t as assertNotEquals } from "../assert_not_equals-CpPK2t89.mjs";
11
- import "../std__assert-DvMDRPes.mjs";
12
- import { t as assertRejects } from "../assert_rejects-CTptdYck.mjs";
13
- import { t as assert } from "../assert-D1Eafmd_.mjs";
14
- import { p as verifyRequest } from "../http-BXbQQZDM.mjs";
15
- import { i as rsaPrivateKey2, n as ed25519PrivateKey, s as rsaPublicKey2, t as ed25519Multikey } from "../keys-DIJNHW-Y.mjs";
16
- import { t as doesActorOwnKey } from "../owner-BVenIFg1.mjs";
17
- import { i as sendActivity, n as extractInboxes, r as fetchWithValidatedRedirects, t as SendActivityError } from "../send-DEGHPGFk.mjs";
18
- import { t as FedifySpanExporter } from "../exporter-DVG68ozH.mjs";
19
- import { configure, getLogger, reset, withContext } from "@logtape/logtape";
20
- import { Activity, Application, Endpoints, Group, Person, Service } from "@fedify/vocab";
21
- import { FetchError, UrlError } from "@fedify/vocab-runtime";
22
- import { createTestMeterProvider, createTestTracerProvider, mockDocumentLoader, test } from "@fedify/fixture";
23
- import { openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal";
24
- import { AggregationTemporality, InMemoryMetricExporter, MeterProvider, PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
25
- import { AsyncLocalStorage } from "node:async_hooks";
26
- //#region src/federation/send.test.ts
27
- function sendDirect(options) {
28
- return sendActivity(options, { openHop: openDirectFetch });
29
- }
30
- test("extractInboxes()", () => {
31
- const recipients = [
32
- new Person({
33
- id: new URL("https://example.com/alice"),
34
- inbox: new URL("https://example.com/alice/inbox"),
35
- endpoints: new Endpoints({ sharedInbox: new URL("https://example.com/inbox") })
36
- }),
37
- new Application({
38
- id: new URL("https://example.com/app"),
39
- inbox: new URL("https://example.com/app/inbox"),
40
- endpoints: new Endpoints({ sharedInbox: new URL("https://example.com/inbox") })
41
- }),
42
- new Group({
43
- id: new URL("https://example.org/group"),
44
- inbox: new URL("https://example.org/group/inbox")
45
- }),
46
- new Service({
47
- id: new URL("https://example.net/service"),
48
- inbox: new URL("https://example.net/service/inbox"),
49
- endpoints: new Endpoints({ sharedInbox: new URL("https://example.net/inbox") })
50
- })
51
- ];
52
- let inboxes = extractInboxes({ recipients });
53
- assertEquals(inboxes, {
54
- "https://example.com/alice/inbox": {
55
- actorIds: /* @__PURE__ */ new Set(["https://example.com/alice"]),
56
- sharedInbox: false
57
- },
58
- "https://example.com/app/inbox": {
59
- actorIds: /* @__PURE__ */ new Set(["https://example.com/app"]),
60
- sharedInbox: false
61
- },
62
- "https://example.org/group/inbox": {
63
- actorIds: /* @__PURE__ */ new Set(["https://example.org/group"]),
64
- sharedInbox: false
65
- },
66
- "https://example.net/service/inbox": {
67
- actorIds: /* @__PURE__ */ new Set(["https://example.net/service"]),
68
- sharedInbox: false
69
- }
70
- });
71
- inboxes = extractInboxes({
72
- recipients,
73
- preferSharedInbox: true
74
- });
75
- assertEquals(inboxes, {
76
- "https://example.com/inbox": {
77
- actorIds: /* @__PURE__ */ new Set(["https://example.com/alice", "https://example.com/app"]),
78
- sharedInbox: true
79
- },
80
- "https://example.org/group/inbox": {
81
- actorIds: /* @__PURE__ */ new Set(["https://example.org/group"]),
82
- sharedInbox: false
83
- },
84
- "https://example.net/inbox": {
85
- actorIds: /* @__PURE__ */ new Set(["https://example.net/service"]),
86
- sharedInbox: true
87
- }
88
- });
89
- inboxes = extractInboxes({
90
- recipients,
91
- excludeBaseUris: [new URL("https://foo.bar/")]
92
- });
93
- assertEquals(inboxes, {
94
- "https://example.com/alice/inbox": {
95
- actorIds: /* @__PURE__ */ new Set(["https://example.com/alice"]),
96
- sharedInbox: false
97
- },
98
- "https://example.com/app/inbox": {
99
- actorIds: /* @__PURE__ */ new Set(["https://example.com/app"]),
100
- sharedInbox: false
101
- },
102
- "https://example.org/group/inbox": {
103
- actorIds: /* @__PURE__ */ new Set(["https://example.org/group"]),
104
- sharedInbox: false
105
- },
106
- "https://example.net/service/inbox": {
107
- actorIds: /* @__PURE__ */ new Set(["https://example.net/service"]),
108
- sharedInbox: false
109
- }
110
- });
111
- inboxes = extractInboxes({
112
- recipients,
113
- excludeBaseUris: [new URL("https://example.com/")]
114
- });
115
- assertEquals(inboxes, {
116
- "https://example.org/group/inbox": {
117
- actorIds: /* @__PURE__ */ new Set(["https://example.org/group"]),
118
- sharedInbox: false
119
- },
120
- "https://example.net/service/inbox": {
121
- actorIds: /* @__PURE__ */ new Set(["https://example.net/service"]),
122
- sharedInbox: false
123
- }
124
- });
125
- inboxes = extractInboxes({
126
- recipients,
127
- preferSharedInbox: true,
128
- excludeBaseUris: [new URL("https://example.com/")]
129
- });
130
- assertEquals(inboxes, {
131
- "https://example.org/group/inbox": {
132
- actorIds: /* @__PURE__ */ new Set(["https://example.org/group"]),
133
- sharedInbox: false
134
- },
135
- "https://example.net/inbox": {
136
- actorIds: /* @__PURE__ */ new Set(["https://example.net/service"]),
137
- sharedInbox: true
138
- }
139
- });
140
- });
141
- test("sendActivity()", async (t) => {
142
- esm_default.spyGlobal();
143
- let httpSigVerified = null;
144
- let request = null;
145
- esm_default.post("https://example.com/inbox", async (cl) => {
146
- httpSigVerified = false;
147
- request = cl.request.clone();
148
- const options = {
149
- documentLoader: mockDocumentLoader,
150
- contextLoader: mockDocumentLoader
151
- };
152
- const key = await verifyRequest(request, options);
153
- const activity = await Activity.fromJsonLd(await request.json(), options);
154
- if (key != null && await doesActorOwnKey(activity, key, options)) httpSigVerified = true;
155
- if (httpSigVerified) return new Response("", { status: 202 });
156
- return new Response("", { status: 401 });
157
- });
158
- await t.step("success", async () => {
159
- const activity = {
160
- "@context": "https://www.w3.org/ns/activitystreams",
161
- "type": "Create",
162
- "id": "https://example.com/activity",
163
- "actor": "https://example.com/person"
164
- };
165
- await sendDirect({
166
- activity,
167
- keys: [{
168
- privateKey: rsaPrivateKey2,
169
- keyId: rsaPublicKey2.id
170
- }],
171
- inbox: new URL("https://example.com/inbox"),
172
- headers: new Headers({ "X-Test": "test" })
173
- });
174
- assert(httpSigVerified);
175
- assertNotEquals(request, null);
176
- assertEquals(request?.method, "POST");
177
- assertEquals(request?.url, "https://example.com/inbox");
178
- assertEquals(request?.headers.get("Content-Type"), "application/activity+json");
179
- assertEquals(request?.headers.get("X-Test"), "test");
180
- httpSigVerified = null;
181
- await assertRejects(() => sendDirect({
182
- activity: {
183
- ...activity,
184
- actor: "https://example.com/person2"
185
- },
186
- keys: [{
187
- privateKey: ed25519PrivateKey,
188
- keyId: ed25519Multikey.id
189
- }],
190
- inbox: new URL("https://example.com/inbox")
191
- }));
192
- assertFalse(httpSigVerified);
193
- assertNotEquals(request, null);
194
- assertEquals(request?.method, "POST");
195
- assertEquals(request?.url, "https://example.com/inbox");
196
- assertEquals(request?.headers.get("Content-Type"), "application/activity+json");
197
- });
198
- esm_default.post("https://example.com/inbox2", {
199
- status: 500,
200
- headers: { "Retry-After": "120" },
201
- body: "something went wrong"
202
- });
203
- await t.step("failure", async () => {
204
- const activity = {
205
- "@context": "https://www.w3.org/ns/activitystreams",
206
- "type": "Create",
207
- "id": "https://example.com/activity",
208
- "actor": "https://example.com/person"
209
- };
210
- await assertRejects(() => sendDirect({
211
- activity,
212
- activityId: "https://example.com/activity",
213
- keys: [{
214
- privateKey: rsaPrivateKey2,
215
- keyId: rsaPublicKey2.id
216
- }],
217
- inbox: new URL("https://example.com/inbox2")
218
- }), Error, "Failed to send activity https://example.com/activity to https://example.com/inbox2 (500 Internal Server Error):\nsomething went wrong");
219
- });
220
- await t.step("failure throws SendActivityError", async () => {
221
- const activity = {
222
- "@context": "https://www.w3.org/ns/activitystreams",
223
- "type": "Create",
224
- "id": "https://example.com/activity",
225
- "actor": "https://example.com/person"
226
- };
227
- try {
228
- await sendDirect({
229
- activity,
230
- activityId: "https://example.com/activity",
231
- keys: [{
232
- privateKey: rsaPrivateKey2,
233
- keyId: rsaPublicKey2.id
234
- }],
235
- inbox: new URL("https://example.com/inbox2")
236
- });
237
- assert(false, "Should have thrown");
238
- } catch (e) {
239
- assertInstanceOf(e, SendActivityError);
240
- assertEquals(e.statusCode, 500);
241
- assertEquals(e.inbox, new URL("https://example.com/inbox2"));
242
- assertEquals(e.responseBody, "something went wrong");
243
- assertEquals(e.responseHeaders.get("Retry-After"), "120");
244
- }
245
- });
246
- await t.step("signed challenge retry transport errors throw FetchError", async () => {
247
- const activity = {
248
- "@context": "https://www.w3.org/ns/activitystreams",
249
- "type": "Create",
250
- "id": "https://example.com/activity",
251
- "actor": "https://example.com/person"
252
- };
253
- const failure = /* @__PURE__ */ new TypeError("challenge retry connection reset");
254
- let requestCount = 0;
255
- esm_default.post("https://example.com/inbox-challenge-reset", () => {
256
- requestCount++;
257
- if (requestCount === 1) return new Response("Unauthorized", {
258
- status: 401,
259
- headers: { "Accept-Signature": "sig1=(\"@method\" \"@target-uri\" \"@authority\" \"content-digest\");created;nonce=\"retry-nonce\"" }
260
- });
261
- throw failure;
262
- });
263
- const error = await assertRejects(() => sendDirect({
264
- activity,
265
- activityId: "https://example.com/activity",
266
- keys: [{
267
- privateKey: rsaPrivateKey2,
268
- keyId: rsaPublicKey2.id
269
- }],
270
- inbox: new URL("https://example.com/inbox-challenge-reset")
271
- }), FetchError, "challenge retry connection reset");
272
- assertEquals(error.url.href, "https://example.com/inbox-challenge-reset");
273
- assertEquals(error.cause, failure);
274
- assertEquals(requestCount, 2);
275
- });
276
- esm_default.post("https://example.com/inbox-gone", {
277
- status: 410,
278
- body: "Gone"
279
- });
280
- await t.step("410 Gone throws SendActivityError", async () => {
281
- const activity = {
282
- "@context": "https://www.w3.org/ns/activitystreams",
283
- "type": "Create",
284
- "id": "https://example.com/activity",
285
- "actor": "https://example.com/person"
286
- };
287
- try {
288
- await sendDirect({
289
- activity,
290
- activityId: "https://example.com/activity",
291
- keys: [{
292
- privateKey: rsaPrivateKey2,
293
- keyId: rsaPublicKey2.id
294
- }],
295
- inbox: new URL("https://example.com/inbox-gone")
296
- });
297
- assert(false, "Should have thrown");
298
- } catch (e) {
299
- assertInstanceOf(e, SendActivityError);
300
- assertEquals(e.statusCode, 410);
301
- assertEquals(e.inbox, new URL("https://example.com/inbox-gone"));
302
- assertEquals(e.responseBody, "Gone");
303
- }
304
- });
305
- esm_default.post("https://example.com/inbox-notfound", {
306
- status: 404,
307
- body: "Not Found"
308
- });
309
- await t.step("404 Not Found throws SendActivityError", async () => {
310
- const activity = {
311
- "@context": "https://www.w3.org/ns/activitystreams",
312
- "type": "Create",
313
- "id": "https://example.com/activity",
314
- "actor": "https://example.com/person"
315
- };
316
- try {
317
- await sendDirect({
318
- activity,
319
- activityId: "https://example.com/activity",
320
- keys: [{
321
- privateKey: rsaPrivateKey2,
322
- keyId: rsaPublicKey2.id
323
- }],
324
- inbox: new URL("https://example.com/inbox-notfound")
325
- });
326
- assert(false, "Should have thrown");
327
- } catch (e) {
328
- assertInstanceOf(e, SendActivityError);
329
- assertEquals(e.statusCode, 404);
330
- assertEquals(e.inbox, new URL("https://example.com/inbox-notfound"));
331
- assertEquals(e.responseBody, "Not Found");
332
- }
333
- });
334
- const longErrorBody = "x".repeat(1500);
335
- esm_default.post("https://example.com/inbox-long-error", {
336
- status: 500,
337
- body: longErrorBody
338
- });
339
- await t.step("long error response body is truncated", async () => {
340
- const activity = {
341
- "@context": "https://www.w3.org/ns/activitystreams",
342
- "type": "Create",
343
- "id": "https://example.com/activity",
344
- "actor": "https://example.com/person"
345
- };
346
- try {
347
- await sendDirect({
348
- activity,
349
- activityId: "https://example.com/activity",
350
- keys: [{
351
- privateKey: rsaPrivateKey2,
352
- keyId: rsaPublicKey2.id
353
- }],
354
- inbox: new URL("https://example.com/inbox-long-error")
355
- });
356
- assert(false, "Should have thrown");
357
- } catch (e) {
358
- assertInstanceOf(e, SendActivityError);
359
- assertEquals(e.statusCode, 500);
360
- assertEquals(e.inbox, new URL("https://example.com/inbox-long-error"));
361
- const expectedTruncated = "x".repeat(1024) + "… (truncated)";
362
- assertEquals(e.responseBody, expectedTruncated);
363
- assertEquals(e.message.includes("… (truncated)"), true);
364
- }
365
- });
366
- await t.step("short error response body is not truncated", async () => {
367
- const activity = {
368
- "@context": "https://www.w3.org/ns/activitystreams",
369
- "type": "Create",
370
- "id": "https://example.com/activity",
371
- "actor": "https://example.com/person"
372
- };
373
- try {
374
- await sendDirect({
375
- activity,
376
- activityId: "https://example.com/activity",
377
- keys: [{
378
- privateKey: rsaPrivateKey2,
379
- keyId: rsaPublicKey2.id
380
- }],
381
- inbox: new URL("https://example.com/inbox2")
382
- });
383
- assert(false, "Should have thrown");
384
- } catch (e) {
385
- assertInstanceOf(e, SendActivityError);
386
- assertEquals(e.responseBody, "something went wrong");
387
- assertEquals(e.message.includes("… (truncated)"), false);
388
- }
389
- });
390
- const exactLimitBody = "y".repeat(1024);
391
- esm_default.post("https://example.com/inbox-exact-limit", {
392
- status: 500,
393
- body: exactLimitBody
394
- });
395
- await t.step("error response body exactly at limit is not truncated", async () => {
396
- const activity = {
397
- "@context": "https://www.w3.org/ns/activitystreams",
398
- "type": "Create",
399
- "id": "https://example.com/activity",
400
- "actor": "https://example.com/person"
401
- };
402
- try {
403
- await sendDirect({
404
- activity,
405
- activityId: "https://example.com/activity",
406
- keys: [{
407
- privateKey: rsaPrivateKey2,
408
- keyId: rsaPublicKey2.id
409
- }],
410
- inbox: new URL("https://example.com/inbox-exact-limit")
411
- });
412
- assert(false, "Should have thrown");
413
- } catch (e) {
414
- assertInstanceOf(e, SendActivityError);
415
- assertEquals(e.responseBody, exactLimitBody);
416
- assertEquals(e.message.includes("… (truncated)"), false);
417
- }
418
- });
419
- esm_default.hardReset();
420
- });
421
- test("sendActivity() records OpenTelemetry span events", async (t) => {
422
- const [tracerProvider, exporter] = createTestTracerProvider();
423
- esm_default.spyGlobal();
424
- await t.step("successful send", async () => {
425
- esm_default.get("https://example.com/", { status: 404 });
426
- esm_default.post("https://example.com/inbox", { status: 202 });
427
- await sendDirect({
428
- activity: {
429
- "@context": "https://www.w3.org/ns/activitystreams",
430
- type: "Create",
431
- id: "https://example.com/activity",
432
- actor: "https://example.com/person"
433
- },
434
- activityId: "https://example.com/activity",
435
- activityType: "https://www.w3.org/ns/activitystreams#Create",
436
- keys: [{
437
- keyId: new URL("https://example.com/person#key"),
438
- privateKey: rsaPrivateKey2
439
- }],
440
- inbox: new URL("https://example.com/inbox"),
441
- tracerProvider
442
- });
443
- const spans = exporter.getSpans("activitypub.send_activity");
444
- assertEquals(spans.length, 1);
445
- const span = spans[0];
446
- assertEquals(span.attributes["activitypub.activity.id"], "https://example.com/activity");
447
- assertEquals(span.attributes["activitypub.activity.type"], "https://www.w3.org/ns/activitystreams#Create");
448
- const events = exporter.getEvents("activitypub.send_activity", "activitypub.activity.sent");
449
- assertEquals(events.length, 1);
450
- const event = events[0];
451
- assert(event.attributes != null);
452
- assertEquals(event.attributes["activitypub.inbox.url"], "https://example.com/inbox");
453
- assertEquals(event.attributes["activitypub.activity.id"], "https://example.com/activity");
454
- assertEquals(event.attributes["activitypub.activity.type"], "https://www.w3.org/ns/activitystreams#Create");
455
- assertEquals(event.attributes["activitypub.actor.id"], "https://example.com/person");
456
- assertEquals(event.attributes["activitypub.activity.json"], void 0);
457
- exporter.clear();
458
- esm_default.hardReset();
459
- });
460
- });
461
- function createActivity(id) {
462
- return {
463
- "@context": "https://www.w3.org/ns/activitystreams",
464
- type: "Create",
465
- id,
466
- actor: "https://example.com/person"
467
- };
468
- }
469
- function deliveryParams(activityId, inbox, tracerProvider) {
470
- return {
471
- activity: createActivity(activityId),
472
- activityId,
473
- activityType: "https://www.w3.org/ns/activitystreams#Create",
474
- keys: [{
475
- keyId: new URL("https://example.com/person#key"),
476
- privateKey: rsaPrivateKey2
477
- }],
478
- inbox: new URL(inbox),
479
- tracerProvider
480
- };
481
- }
482
- test("sendActivity() aligns the LogTape context with its own span", async (t) => {
483
- const [tracerProvider, exporter] = createTestTracerProvider();
484
- esm_default.spyGlobal();
485
- const records = [];
486
- await reset();
487
- try {
488
- await configure({
489
- sinks: { buffer: (record) => records.push(record) },
490
- filters: {},
491
- loggers: [{
492
- category: [],
493
- sinks: ["buffer"],
494
- lowestLevel: "debug"
495
- }, {
496
- category: ["logtape", "meta"],
497
- sinks: []
498
- }],
499
- contextLocalStorage: new AsyncLocalStorage()
500
- });
501
- const outerContext = {
502
- requestId: "outer-request",
503
- traceId: "outer0000000000000000000000sentinel",
504
- spanId: "outer00000sentinel"
505
- };
506
- await t.step("a warning logged during a successful send matches the resulting TraceActivityRecord", async () => {
507
- try {
508
- esm_default.post("https://example.com/inbox-warn", { status: 202 });
509
- await withContext({ requestId: "outer-request-warn" }, async () => {
510
- await sendDirect({
511
- ...deliveryParams("https://example.com/activity/warn", "https://example.com/inbox-warn", tracerProvider),
512
- keys: [{
513
- keyId: ed25519Multikey.id,
514
- privateKey: ed25519PrivateKey
515
- }]
516
- });
517
- });
518
- const span = exporter.getSpan("activitypub.send_activity");
519
- assert(span != null);
520
- const { traceId, spanId } = span.spanContext();
521
- const fedifyExporter = new FedifySpanExporter(new MemoryKvStore());
522
- await new Promise((resolve) => {
523
- fedifyExporter.export([span], () => resolve());
524
- });
525
- const [record] = await fedifyExporter.getActivitiesByTraceId(traceId);
526
- assert(record != null);
527
- assertEquals(record.direction, "outbound");
528
- assertEquals(record.spanId, spanId);
529
- const warnLog = records.find((r) => String(r.rawMessage).startsWith("No supported key found to sign"));
530
- assert(warnLog != null);
531
- assertEquals(warnLog.properties.spanId, record.spanId);
532
- assertEquals(warnLog.properties.traceId, record.traceId);
533
- assertEquals(warnLog.properties.requestId, "outer-request-warn");
534
- } finally {
535
- exporter.clear();
536
- records.length = 0;
537
- esm_default.hardReset();
538
- esm_default.spyGlobal();
539
- }
540
- });
541
- await t.step("a failed delivery's error log matches its own span, and the outer context is restored once the rejection propagates", async () => {
542
- try {
543
- esm_default.post("https://example.com/inbox-failing", {
544
- status: 500,
545
- body: "Internal Server Error"
546
- });
547
- await withContext(outerContext, async () => {
548
- await assertRejects(() => sendDirect(deliveryParams("https://example.com/activity/failing", "https://example.com/inbox-failing", tracerProvider)), SendActivityError);
549
- getLogger([
550
- "fedify",
551
- "federation",
552
- "send.test"
553
- ]).info("after failure");
554
- });
555
- const span = exporter.getSpan("activitypub.send_activity");
556
- assert(span != null);
557
- const { traceId, spanId } = span.spanContext();
558
- const fedifyExporter = new FedifySpanExporter(new MemoryKvStore());
559
- await new Promise((resolve) => {
560
- fedifyExporter.export([span], () => resolve());
561
- });
562
- assertEquals(await fedifyExporter.getActivitiesByTraceId(traceId), []);
563
- const failureLog = records.find((r) => String(r.rawMessage).startsWith("Failed to send activity {activityId} to {inbox} ({status}"));
564
- assert(failureLog != null);
565
- assertEquals(failureLog.properties.spanId, spanId);
566
- assertEquals(failureLog.properties.traceId, traceId);
567
- assertEquals(failureLog.properties.requestId, outerContext.requestId);
568
- const afterLog = records.find((r) => r.rawMessage === "after failure");
569
- assert(afterLog != null);
570
- assertEquals(afterLog.properties.requestId, outerContext.requestId);
571
- assertEquals(afterLog.properties.traceId, outerContext.traceId);
572
- assertEquals(afterLog.properties.spanId, outerContext.spanId);
573
- } finally {
574
- exporter.clear();
575
- records.length = 0;
576
- esm_default.hardReset();
577
- esm_default.spyGlobal();
578
- }
579
- });
580
- await t.step("outer context is restored after a successful send", async () => {
581
- try {
582
- esm_default.post("https://example.com/inbox-ok", { status: 202 });
583
- await withContext(outerContext, async () => {
584
- await sendDirect(deliveryParams("https://example.com/activity/ok", "https://example.com/inbox-ok", tracerProvider));
585
- getLogger([
586
- "fedify",
587
- "federation",
588
- "send.test"
589
- ]).info("after success");
590
- });
591
- const span = exporter.getSpan("activitypub.send_activity");
592
- assert(span != null);
593
- const { spanId } = span.spanContext();
594
- const afterLog = records.find((r) => r.rawMessage === "after success");
595
- assert(afterLog != null);
596
- assertNotEquals(afterLog.properties.spanId, spanId);
597
- assertEquals(afterLog.properties.requestId, outerContext.requestId);
598
- assertEquals(afterLog.properties.traceId, outerContext.traceId);
599
- assertEquals(afterLog.properties.spanId, outerContext.spanId);
600
- } finally {
601
- exporter.clear();
602
- records.length = 0;
603
- esm_default.hardReset();
604
- esm_default.spyGlobal();
605
- }
606
- });
607
- await t.step("concurrent deliveries do not leak context into each other", async () => {
608
- try {
609
- let arrived = 0;
610
- let release = () => {};
611
- const gate = new Promise((resolve) => {
612
- release = resolve;
613
- });
614
- const handler = () => async () => {
615
- arrived++;
616
- if (arrived >= 2) release();
617
- await gate;
618
- return {
619
- status: 500,
620
- body: "Internal Server Error"
621
- };
622
- };
623
- esm_default.post("https://example.com/inbox-concurrent-a", handler());
624
- esm_default.post("https://example.com/inbox-concurrent-b", handler());
625
- const [resultA, resultB] = await Promise.allSettled([sendDirect(deliveryParams("https://example.com/activity/a", "https://example.com/inbox-concurrent-a", tracerProvider)).finally(release), sendDirect(deliveryParams("https://example.com/activity/b", "https://example.com/inbox-concurrent-b", tracerProvider)).finally(release)]);
626
- assertEquals(resultA.status, "rejected");
627
- assertEquals(resultB.status, "rejected");
628
- const spans = exporter.getSpans("activitypub.send_activity");
629
- assertEquals(spans.length, 2);
630
- const spanA = spans.find((s) => s.attributes["activitypub.activity.id"] === "https://example.com/activity/a");
631
- const spanB = spans.find((s) => s.attributes["activitypub.activity.id"] === "https://example.com/activity/b");
632
- assert(spanA != null && spanB != null);
633
- assertNotEquals(spanA.spanContext().spanId, spanB.spanContext().spanId);
634
- const logA = records.find((r) => r.properties.activityId === "https://example.com/activity/a" && String(r.rawMessage).startsWith("Failed to send activity"));
635
- const logB = records.find((r) => r.properties.activityId === "https://example.com/activity/b" && String(r.rawMessage).startsWith("Failed to send activity"));
636
- assert(logA != null && logB != null);
637
- assertEquals(logA.properties.spanId, spanA.spanContext().spanId);
638
- assertEquals(logB.properties.spanId, spanB.spanContext().spanId);
639
- assertEquals(logA.properties.traceId, spanA.spanContext().traceId);
640
- assertEquals(logB.properties.traceId, spanB.spanContext().traceId);
641
- assertNotEquals(logA.properties.spanId, logB.properties.spanId);
642
- } finally {
643
- exporter.clear();
644
- records.length = 0;
645
- esm_default.hardReset();
646
- }
647
- });
648
- } finally {
649
- await reset();
650
- esm_default.hardReset();
651
- }
652
- });
653
- test("sendActivity() validates the initial policy before serializing", async () => {
654
- const [meterProvider, recorder] = createTestMeterProvider();
655
- let serialized = false;
656
- await assertRejects(() => sendActivity({
657
- activity: { toJSON() {
658
- serialized = true;
659
- throw new Error("must not serialize");
660
- } },
661
- keys: [],
662
- inbox: new URL("http://127.0.0.1/inbox"),
663
- meterProvider
664
- }), UrlError);
665
- assertFalse(serialized);
666
- assertEquals(recorder.getMeasurements("activitypub.delivery.sent"), []);
667
- });
668
- test("sendActivity() closes the initial session when serialization fails", async () => {
669
- const [meterProvider, recorder] = createTestMeterProvider();
670
- const url = "https://example.com/lifecycle/serialization-failure";
671
- const hops = recordHops(() => ({
672
- status: 202,
673
- body: "Accepted"
674
- }));
675
- const failure = /* @__PURE__ */ new Error("serialization failed");
676
- assertEquals(await assertRejects(() => sendActivity({
677
- activity: { toJSON() {
678
- throw failure;
679
- } },
680
- keys: [],
681
- inbox: new URL(url),
682
- meterProvider
683
- }, { openHop: hops.openHop }), Error, "serialization failed"), failure);
684
- assertEquals(hops.events, [`open ${url}`, `close ${url}`]);
685
- assertEquals(recorder.getMeasurements("activitypub.delivery.sent"), []);
686
- hops.assertInvariants();
687
- });
688
- test("sendActivity() records OpenTelemetry delivery metrics", async (t) => {
689
- const [meterProvider, recorder] = createTestMeterProvider();
690
- esm_default.spyGlobal();
691
- await t.step("successful send", async () => {
692
- esm_default.post("https://metrics.example:8443/inbox/path?x=1", { status: 202 });
693
- await sendActivity({
694
- activity: {
695
- "@context": "https://www.w3.org/ns/activitystreams",
696
- type: "Create",
697
- id: "https://example.com/activity",
698
- actor: "https://example.com/person"
699
- },
700
- activityId: "https://example.com/activity",
701
- activityType: "https://www.w3.org/ns/activitystreams#Create",
702
- keys: [],
703
- allowPrivateAddress: true,
704
- inbox: new URL("https://metrics.example:8443/inbox/path?x=1"),
705
- meterProvider
706
- });
707
- const sent = recorder.getMeasurements("activitypub.delivery.sent");
708
- assertEquals(sent.length, 1);
709
- assertEquals(sent[0].type, "counter");
710
- assertEquals(sent[0].value, 1);
711
- assertEquals(sent[0].attributes["activitypub.remote.host"], "metrics.example:8443");
712
- assertEquals(sent[0].attributes["activitypub.activity.type"], "https://www.w3.org/ns/activitystreams#Create");
713
- assertEquals(sent[0].attributes["activitypub.delivery.success"], true);
714
- const durations = recorder.getMeasurements("activitypub.delivery.duration");
715
- assertEquals(durations.length, 1);
716
- assertEquals(durations[0].type, "histogram");
717
- assertGreaterOrEqual(durations[0].value, 0);
718
- assertEquals(durations[0].attributes["activitypub.remote.host"], "metrics.example:8443");
719
- assertEquals(durations[0].attributes["activitypub.activity.type"], "https://www.w3.org/ns/activitystreams#Create");
720
- assertEquals(durations[0].attributes["activitypub.delivery.success"], true);
721
- recorder.clear();
722
- esm_default.hardReset();
723
- });
724
- await t.step("failed HTTP response", async () => {
725
- esm_default.spyGlobal();
726
- esm_default.post("https://metrics.example/inbox", {
727
- status: 500,
728
- body: "failed"
729
- });
730
- const activity = {
731
- "@context": "https://www.w3.org/ns/activitystreams",
732
- type: "Follow",
733
- id: "https://example.com/follow",
734
- actor: "https://example.com/person"
735
- };
736
- await assertRejects(() => sendActivity({
737
- activity,
738
- activityId: "https://example.com/follow",
739
- activityType: "https://www.w3.org/ns/activitystreams#Follow",
740
- keys: [],
741
- allowPrivateAddress: true,
742
- inbox: new URL("https://metrics.example/inbox"),
743
- meterProvider
744
- }), SendActivityError);
745
- const sent = recorder.getMeasurements("activitypub.delivery.sent");
746
- assertEquals(sent.length, 1);
747
- assertEquals(sent[0].attributes["activitypub.delivery.success"], false);
748
- assertEquals(sent[0].attributes["activitypub.activity.type"], "https://www.w3.org/ns/activitystreams#Follow");
749
- assertEquals(sent[0].attributes["activitypub.remote.host"], "metrics.example");
750
- const durations = recorder.getMeasurements("activitypub.delivery.duration");
751
- assertEquals(durations.length, 1);
752
- assertGreaterOrEqual(durations[0].value, 0);
753
- assertEquals(durations[0].attributes["activitypub.remote.host"], "metrics.example");
754
- assertEquals(durations[0].attributes["activitypub.activity.type"], "https://www.w3.org/ns/activitystreams#Follow");
755
- assertEquals(durations[0].attributes["activitypub.delivery.success"], false);
756
- recorder.clear();
757
- esm_default.hardReset();
758
- });
759
- });
760
- test("sendActivity() exports delivery metrics through OpenTelemetry SDK", async () => {
761
- const exporter = new InMemoryMetricExporter(AggregationTemporality.CUMULATIVE);
762
- const meterProvider = new MeterProvider({ readers: [new PeriodicExportingMetricReader({
763
- exporter,
764
- exportIntervalMillis: 6e4
765
- })] });
766
- esm_default.spyGlobal();
767
- esm_default.post("https://sdk-metrics.example/inbox", { status: 202 });
768
- try {
769
- await sendActivity({
770
- activity: {
771
- "@context": "https://www.w3.org/ns/activitystreams",
772
- type: "Create",
773
- id: "https://example.com/activity",
774
- actor: "https://example.com/person"
775
- },
776
- activityId: "https://example.com/activity",
777
- activityType: "https://www.w3.org/ns/activitystreams#Create",
778
- keys: [],
779
- allowPrivateAddress: true,
780
- inbox: new URL("https://sdk-metrics.example/inbox"),
781
- meterProvider
782
- });
783
- await meterProvider.forceFlush();
784
- const sent = exporter.getMetrics().flatMap((resourceMetrics) => resourceMetrics.scopeMetrics).flatMap((scopeMetrics) => scopeMetrics.metrics).find((metric) => metric.descriptor.name === "activitypub.delivery.sent");
785
- assert(sent != null);
786
- assertEquals(sent.dataPoints.length, 1);
787
- assertEquals(sent.dataPoints[0].attributes["activitypub.remote.host"], "sdk-metrics.example");
788
- } finally {
789
- try {
790
- await meterProvider.shutdown();
791
- } finally {
792
- esm_default.hardReset();
793
- }
794
- }
795
- });
796
- for (const signed of [false, true]) {
797
- const keys = [{
798
- privateKey: signed ? rsaPrivateKey2 : ed25519PrivateKey,
799
- keyId: signed ? rsaPublicKey2.id : ed25519Multikey.id
800
- }];
801
- test(`sendActivity() validates destinations (signed: ${signed})`, async (t) => {
802
- const activity = {
803
- type: "Create",
804
- id: "https://example.com/activity"
805
- };
806
- const publicInbox = "https://8.8.8.8/inbox";
807
- const privateInbox = "http://127.0.0.1/inbox";
808
- for (const target of [
809
- privateInbox,
810
- "http://169.254.169.254/",
811
- "http://[::1]/"
812
- ]) await t.step(`rejects ${target} before fetching`, async () => {
813
- esm_default.mockGlobal().catch(202);
814
- try {
815
- await assertRejects(() => sendActivity({
816
- activity,
817
- keys,
818
- inbox: new URL(target)
819
- }), UrlError);
820
- assertEquals(esm_default.callHistory.calls().length, 0);
821
- } finally {
822
- esm_default.hardReset();
823
- }
824
- });
825
- for (const status of [
826
- 301,
827
- 302,
828
- 303,
829
- 307,
830
- 308
831
- ]) for (const allowPrivateAddress of [false, true]) await t.step(`${status} private redirect, opt-in: ${allowPrivateAddress}`, async () => {
832
- esm_default.mockGlobal();
833
- esm_default.route(publicInbox, {
834
- status,
835
- headers: { Location: privateInbox }
836
- });
837
- esm_default.route(privateInbox, 202);
838
- try {
839
- const send = () => sendActivity({
840
- activity,
841
- keys,
842
- inbox: new URL(publicInbox),
843
- allowPrivateAddress
844
- });
845
- if (allowPrivateAddress) {
846
- await send();
847
- const calls = esm_default.callHistory.calls(privateInbox);
848
- assertEquals(calls.length, 1);
849
- const request = calls[0].request;
850
- const preservesBody = signed || status === 307 || status === 308;
851
- assertEquals(request.method, preservesBody ? "POST" : "GET");
852
- assertEquals(await request.clone().text(), preservesBody ? JSON.stringify(activity) : "");
853
- } else {
854
- await assertRejects(send, UrlError);
855
- assertEquals(esm_default.callHistory.calls(privateInbox).length, 0);
856
- }
857
- } finally {
858
- esm_default.hardReset();
859
- }
860
- });
861
- await t.step("rejects a private destination after a public redirect", async () => {
862
- esm_default.mockGlobal().route(publicInbox, {
863
- status: 307,
864
- headers: { Location: "/next" }
865
- }).route("https://8.8.8.8/next", {
866
- status: 308,
867
- headers: { Location: privateInbox }
868
- }).route(privateInbox, 202);
869
- try {
870
- await assertRejects(() => sendActivity({
871
- activity,
872
- keys,
873
- inbox: new URL(publicInbox)
874
- }), UrlError);
875
- assertEquals(esm_default.callHistory.calls(privateInbox).length, 0);
876
- } finally {
877
- esm_default.hardReset();
878
- }
879
- });
880
- await t.step("limits redirect loops", async () => {
881
- esm_default.mockGlobal().route(publicInbox, {
882
- status: 307,
883
- headers: { Location: publicInbox }
884
- });
885
- try {
886
- await assertRejects(() => sendActivity({
887
- activity,
888
- keys,
889
- inbox: new URL(publicInbox)
890
- }));
891
- assert(esm_default.callHistory.calls().length <= 21);
892
- } finally {
893
- esm_default.hardReset();
894
- }
895
- });
896
- await t.step("allows a direct private inbox with opt-in", async () => {
897
- esm_default.mockGlobal().route(privateInbox, 202);
898
- try {
899
- await sendActivity({
900
- activity,
901
- keys,
902
- inbox: new URL(privateInbox),
903
- allowPrivateAddress: true
904
- });
905
- assertEquals(esm_default.callHistory.calls(privateInbox).length, 1);
906
- } finally {
907
- esm_default.hardReset();
908
- }
909
- });
910
- await t.step("allows relative public redirects", async () => {
911
- esm_default.mockGlobal().route(publicInbox, {
912
- status: 307,
913
- headers: { Location: "/next" }
914
- }).route("https://8.8.8.8/next", 202);
915
- try {
916
- await sendActivity({
917
- activity,
918
- keys,
919
- inbox: new URL(publicInbox)
920
- });
921
- assertEquals(esm_default.callHistory.calls("https://8.8.8.8/next").length, 1);
922
- } finally {
923
- esm_default.hardReset();
924
- }
925
- });
926
- });
927
- }
928
- for (const signed of [false, true]) test(`sendActivity() classifies DNS failures (signed: ${signed})`, async (t) => {
929
- const activity = {
930
- type: "Create",
931
- id: "https://example.com/activity"
932
- };
933
- const destination = "https://delivery.invalid/inbox";
934
- const publicInbox = "https://8.8.8.8/inbox";
935
- const keys = signed ? [{
936
- privateKey: rsaPrivateKey2,
937
- keyId: rsaPublicKey2.id
938
- }] : [];
939
- for (const result of [
940
- "throws",
941
- "empty",
942
- "cname",
943
- "private"
944
- ]) for (const redirected of [false, true]) await t.step(`${result}, redirected: ${redirected}`, async () => {
945
- const [meterProvider, recorder] = createTestMeterProvider();
946
- const resolverError = /* @__PURE__ */ new Error("Resolver unavailable");
947
- const lookups = [];
948
- const lookup = (hostname) => {
949
- lookups.push(hostname);
950
- assertEquals(hostname, "delivery.invalid");
951
- if (result === "throws") return Promise.reject(resolverError);
952
- return Promise.resolve(result === "empty" ? [] : [{
953
- address: result === "private" ? "127.0.0.1" : "alias.invalid.",
954
- family: 4
955
- }]);
956
- };
957
- try {
958
- esm_default.mockGlobal().catch(202);
959
- if (redirected) esm_default.route(publicInbox, {
960
- status: 307,
961
- headers: { Location: destination }
962
- });
963
- const send = () => sendActivity({
964
- activity,
965
- activityType: "https://www.w3.org/ns/activitystreams#Create",
966
- meterProvider,
967
- keys,
968
- inbox: new URL(redirected ? publicInbox : destination)
969
- }, { openHop: (url) => openPublicFetch(url, { lookup }) });
970
- if (result === "private") assertEquals((await assertRejects(send, UrlError)).reason, "disallowed");
971
- else {
972
- const error = await assertRejects(send, FetchError);
973
- assertEquals(error.url.href, destination);
974
- assertInstanceOf(error.cause, UrlError);
975
- assertEquals(error.cause.reason, "dns");
976
- assertEquals(error.cause.cause, result === "throws" ? resolverError : void 0);
977
- }
978
- const expectedCount = result === "private" && !redirected ? 0 : 1;
979
- const sent = recorder.getMeasurements("activitypub.delivery.sent");
980
- const durations = recorder.getMeasurements("activitypub.delivery.duration");
981
- assertEquals(sent.length, expectedCount);
982
- assertEquals(durations.length, expectedCount);
983
- if (expectedCount === 1) {
984
- assertEquals(sent[0].value, 1);
985
- assertEquals(sent[0].attributes, {
986
- "activitypub.remote.host": redirected ? "8.8.8.8" : "delivery.invalid",
987
- "activitypub.activity.type": "https://www.w3.org/ns/activitystreams#Create",
988
- "activitypub.delivery.success": false
989
- });
990
- assertEquals(durations[0].attributes, sent[0].attributes);
991
- assertGreaterOrEqual(durations[0].value, 0);
992
- }
993
- assertEquals(lookups, ["delivery.invalid"]);
994
- assertEquals(esm_default.callHistory.calls(destination).length, 0);
995
- assertEquals(esm_default.callHistory.calls().length, redirected ? 1 : 0);
996
- } finally {
997
- esm_default.hardReset();
998
- }
999
- });
1000
- });
1001
- const lifecycleActivity = {
1002
- "@context": "https://www.w3.org/ns/activitystreams",
1003
- type: "Create",
1004
- id: "https://example.com/activity",
1005
- actor: "https://example.com/person"
1006
- };
1007
- const signedKeys = [{
1008
- privateKey: rsaPrivateKey2,
1009
- keyId: rsaPublicKey2.id
1010
- }];
1011
- const unsignedKeys = [{
1012
- privateKey: ed25519PrivateKey,
1013
- keyId: ed25519Multikey.id
1014
- }];
1015
- test("sendActivity() cancels a successful response body", async (t) => {
1016
- for (const signed of [true, false]) await t.step(`signed: ${signed}`, async () => {
1017
- const inbox = "https://example.com/lifecycle/inbox";
1018
- const hops = recordHops(() => ({
1019
- status: 202,
1020
- body: "Accepted"
1021
- }));
1022
- await sendActivity({
1023
- activity: lifecycleActivity,
1024
- keys: signed ? signedKeys : unsignedKeys,
1025
- inbox: new URL(inbox)
1026
- }, { openHop: hops.openHop });
1027
- assertEquals(hops.events, [
1028
- `open ${inbox}`,
1029
- `fetch #1 ${inbox}`,
1030
- "cancel #1",
1031
- `close ${inbox}`
1032
- ]);
1033
- hops.assertInvariants();
1034
- });
1035
- });
1036
- test("sendActivity() reads at most 1 KiB of an error response body", async (t) => {
1037
- for (const signed of [true, false]) await t.step(`signed: ${signed}`, async () => {
1038
- const inbox = "https://example.com/lifecycle/error";
1039
- const hops = recordHops(() => ({
1040
- status: 500,
1041
- body: "x".repeat(4096)
1042
- }));
1043
- const error = await assertRejects(() => sendActivity({
1044
- activity: lifecycleActivity,
1045
- activityId: lifecycleActivity.id,
1046
- keys: signed ? signedKeys : unsignedKeys,
1047
- inbox: new URL(inbox)
1048
- }, { openHop: hops.openHop }), SendActivityError);
1049
- assertEquals(error.responseBody, "x".repeat(1024) + "… (truncated)");
1050
- assert(error.message.includes("… (truncated)"));
1051
- assertEquals(hops.events, [
1052
- `open ${inbox}`,
1053
- `fetch #1 ${inbox}`,
1054
- "cancel #1",
1055
- ...signed ? [`fetch #2 ${inbox}`, "cancel #2"] : [],
1056
- `close ${inbox}`
1057
- ]);
1058
- hops.assertInvariants();
1059
- });
1060
- });
1061
- test("sendActivity() closes each redirect hop before opening the next", async (t) => {
1062
- for (const [signed, status] of [[true, 307], [false, 308]]) await t.step(`signed: ${signed}, ${status}`, async () => {
1063
- const inbox = "https://example.com/lifecycle/redirect";
1064
- const next = "https://example.com/lifecycle/redirected";
1065
- const hops = recordHops((request) => request.url === inbox ? {
1066
- status,
1067
- headers: { Location: next },
1068
- body: "Moved"
1069
- } : {
1070
- status: 202,
1071
- body: "Accepted"
1072
- });
1073
- await sendActivity({
1074
- activity: lifecycleActivity,
1075
- keys: signed ? signedKeys : unsignedKeys,
1076
- inbox: new URL(inbox)
1077
- }, { openHop: hops.openHop });
1078
- assertEquals(hops.events, [
1079
- `open ${inbox}`,
1080
- `fetch #1 ${inbox}`,
1081
- "cancel #1",
1082
- `close ${inbox}`,
1083
- `open ${next}`,
1084
- `fetch #2 ${next}`,
1085
- "cancel #2",
1086
- `close ${next}`
1087
- ]);
1088
- assertEquals(hops.requests[1].method, "POST");
1089
- assertEquals(await hops.requests[1].text(), JSON.stringify(lifecycleActivity));
1090
- hops.assertInvariants();
1091
- });
1092
- });
1093
- async function captureLogs(fn) {
1094
- const records = [];
1095
- await configure({
1096
- sinks: { buffer: (record) => records.push(record) },
1097
- loggers: [{
1098
- category: "fedify",
1099
- sinks: ["buffer"],
1100
- lowestLevel: "debug"
1101
- }, {
1102
- category: ["logtape", "meta"],
1103
- sinks: []
1104
- }],
1105
- reset: true
1106
- });
1107
- try {
1108
- await fn();
1109
- await new Promise((resolve) => setTimeout(resolve, 0));
1110
- } finally {
1111
- await reset();
1112
- }
1113
- return records;
1114
- }
1115
- function getCancelFailureUrls(records) {
1116
- return records.flatMap((r) => r.rawMessage === "Failed to cancel the response body from {url}: {error}" ? [r.properties.url] : []);
1117
- }
1118
- test("fetchWithValidatedRedirects() logs a redirect body failing to cancel and follows the redirect", async (t) => {
1119
- const url = "https://example.com/lifecycle/cancel-failure";
1120
- const next = "https://example.com/lifecycle/cancel-failure-final";
1121
- const respond = (_, index) => index === 1 ? {
1122
- status: 302,
1123
- headers: { Location: next },
1124
- body: "Found",
1125
- failCancel: true
1126
- } : {
1127
- status: 202,
1128
- body: "Accepted"
1129
- };
1130
- await t.step("fetchWithValidatedRedirects()", async () => {
1131
- const hops = recordHops(respond);
1132
- let result;
1133
- const records = await captureLogs(async () => {
1134
- result = await fetchWithValidatedRedirects(new Request(url, {
1135
- method: "POST",
1136
- body: "activity"
1137
- }), hops.openHop, (response) => response.text());
1138
- });
1139
- assertEquals(result, "Accepted");
1140
- assertEquals(hops.events, [
1141
- `open ${url}`,
1142
- `fetch #1 ${url}`,
1143
- "cancel #1",
1144
- `close ${url}`,
1145
- `open ${next}`,
1146
- `fetch #2 ${next}`,
1147
- "consumed #2",
1148
- `close ${next}`
1149
- ]);
1150
- assertEquals(getCancelFailureUrls(records), [url]);
1151
- hops.assertInvariants();
1152
- });
1153
- for (const signed of [true, false]) await t.step(`signed sendActivity(): ${signed}`, async () => {
1154
- const hops = recordHops(respond);
1155
- const records = await captureLogs(() => sendActivity({
1156
- activity: lifecycleActivity,
1157
- keys: signed ? signedKeys : unsignedKeys,
1158
- inbox: new URL(url)
1159
- }, { openHop: hops.openHop }));
1160
- assertEquals(hops.events, [
1161
- `open ${url}`,
1162
- `fetch #1 ${url}`,
1163
- "cancel #1",
1164
- `close ${url}`,
1165
- `open ${next}`,
1166
- `fetch #2 ${next}`,
1167
- "cancel #2",
1168
- `close ${next}`
1169
- ]);
1170
- assertEquals(getCancelFailureUrls(records), [url]);
1171
- hops.assertInvariants();
1172
- });
1173
- });
1174
- test("fetchWithValidatedRedirects() closes the session when consuming fails", async () => {
1175
- const url = "https://example.com/lifecycle/consume-failure";
1176
- const hops = recordHops(() => ({
1177
- status: 200,
1178
- body: "x".repeat(1024)
1179
- }));
1180
- await assertRejects(() => fetchWithValidatedRedirects(new Request(url, {
1181
- method: "POST",
1182
- body: "activity"
1183
- }), hops.openHop, () => Promise.reject(/* @__PURE__ */ new Error("consume failed"))), Error, "consume failed");
1184
- assertEquals(hops.events, [
1185
- `open ${url}`,
1186
- `fetch #1 ${url}`,
1187
- "cancel #1 by close",
1188
- `close ${url}`
1189
- ]);
1190
- hops.assertInvariants();
1191
- });
1192
- test("sendActivity() logs a successful response body failing to cancel", async (t) => {
1193
- for (const signed of [true, false]) await t.step(`signed: ${signed}`, async () => {
1194
- const inbox = "https://example.com/lifecycle/cancel-failure-inbox";
1195
- const hops = recordHops(() => ({
1196
- status: 202,
1197
- body: "Accepted",
1198
- failCancel: true
1199
- }));
1200
- const records = await captureLogs(() => sendActivity({
1201
- activity: lifecycleActivity,
1202
- keys: signed ? signedKeys : unsignedKeys,
1203
- inbox: new URL(inbox)
1204
- }, { openHop: hops.openHop }));
1205
- assertEquals(hops.events, [
1206
- `open ${inbox}`,
1207
- `fetch #1 ${inbox}`,
1208
- "cancel #1",
1209
- `close ${inbox}`
1210
- ]);
1211
- assertEquals(getCancelFailureUrls(records), [inbox]);
1212
- hops.assertInvariants();
1213
- });
1214
- });
1215
- test("sendActivity() is not blocked by a body cancellation that never settles", async (t) => {
1216
- for (const signed of [true, false]) await t.step(`signed: ${signed}`, async () => {
1217
- const inbox = "https://example.com/lifecycle/hanging-cancel";
1218
- const next = "https://example.com/lifecycle/hanging-cancel-final";
1219
- const hops = recordHops((request) => request.url === inbox ? {
1220
- status: 302,
1221
- headers: { Location: next },
1222
- body: "Found",
1223
- hangCancel: true
1224
- } : {
1225
- status: 202,
1226
- body: "Accepted",
1227
- hangCancel: true
1228
- });
1229
- await sendActivity({
1230
- activity: lifecycleActivity,
1231
- keys: signed ? signedKeys : unsignedKeys,
1232
- inbox: new URL(inbox)
1233
- }, { openHop: hops.openHop });
1234
- assertEquals(hops.events, [
1235
- `open ${inbox}`,
1236
- `fetch #1 ${inbox}`,
1237
- "cancel #1",
1238
- `close ${inbox}`,
1239
- `open ${next}`,
1240
- `fetch #2 ${next}`,
1241
- "cancel #2",
1242
- `close ${next}`
1243
- ]);
1244
- hops.assertInvariants();
1245
- });
1246
- await t.step("truncated error body", async () => {
1247
- const inbox = "https://example.com/lifecycle/hanging-error";
1248
- const hops = recordHops(() => ({
1249
- status: 500,
1250
- body: "x".repeat(4096),
1251
- hangCancel: true
1252
- }));
1253
- assertEquals((await assertRejects(() => sendActivity({
1254
- activity: lifecycleActivity,
1255
- keys: unsignedKeys,
1256
- inbox: new URL(inbox)
1257
- }, { openHop: hops.openHop }), SendActivityError)).responseBody, "x".repeat(1024) + "… (truncated)");
1258
- assertEquals(hops.events, [
1259
- `open ${inbox}`,
1260
- `fetch #1 ${inbox}`,
1261
- "cancel #1",
1262
- `close ${inbox}`
1263
- ]);
1264
- hops.assertInvariants();
1265
- });
1266
- });
1267
- test("sendActivity() completes with responses cloned by fetch-mock", async (t) => {
1268
- for (const signed of [true, false]) await t.step(`signed: ${signed}`, async () => {
1269
- esm_default.spyGlobal();
1270
- try {
1271
- esm_default.post("https://example.com/tee/inbox", () => new Response("Moved", {
1272
- status: 307,
1273
- headers: { Location: "https://example.com/tee/final" }
1274
- }));
1275
- esm_default.post("https://example.com/tee/final", () => new Response("Accepted", { status: 202 }));
1276
- esm_default.post("https://example.com/tee/error", () => new Response("x".repeat(4096), { status: 404 }));
1277
- const keys = signed ? signedKeys : unsignedKeys;
1278
- await sendDirect({
1279
- activity: lifecycleActivity,
1280
- keys,
1281
- inbox: new URL("https://example.com/tee/inbox")
1282
- });
1283
- assertEquals(esm_default.callHistory.calls("https://example.com/tee/final").length, 1);
1284
- const error = await assertRejects(() => sendDirect({
1285
- activity: lifecycleActivity,
1286
- keys,
1287
- inbox: new URL("https://example.com/tee/error")
1288
- }), SendActivityError);
1289
- assertEquals(error.statusCode, 404);
1290
- assertEquals(error.responseBody, "x".repeat(1024) + "… (truncated)");
1291
- } finally {
1292
- esm_default.hardReset();
1293
- }
1294
- });
1295
- });
1296
- function createRecordedResponse(events, index, init, cancelSuffix = () => "") {
1297
- const bytes = new TextEncoder().encode(init.body ?? "");
1298
- const chunkSize = init.chunkSize ?? 256;
1299
- let offset = 0;
1300
- let settled = false;
1301
- const body = new ReadableStream({
1302
- pull(controller) {
1303
- if (offset >= bytes.length) {
1304
- settled = true;
1305
- events.push(`consumed #${index}`);
1306
- controller.close();
1307
- return;
1308
- }
1309
- controller.enqueue(bytes.slice(offset, offset + chunkSize));
1310
- offset += chunkSize;
1311
- },
1312
- cancel() {
1313
- settled = true;
1314
- events.push(`cancel #${index}${cancelSuffix()}`);
1315
- if (init.failCancel) throw new Error(`cancel #${index} failed`);
1316
- if (init.hangCancel) return new Promise(() => {});
1317
- }
1318
- }, { highWaterMark: 0 });
1319
- return {
1320
- response: new Response(body, {
1321
- status: init.status ?? 200,
1322
- headers: init.headers
1323
- }),
1324
- settled: () => settled
1325
- };
1326
- }
1327
- function recordHops(respond) {
1328
- const events = [];
1329
- const requests = [];
1330
- const unsettledAtClose = [];
1331
- let opens = 0;
1332
- let closes = 0;
1333
- let fetches = 0;
1334
- return {
1335
- events,
1336
- requests,
1337
- openHop(url) {
1338
- opens++;
1339
- events.push(`open ${url}`);
1340
- const tracked = [];
1341
- let closed = false;
1342
- let closing = false;
1343
- return Promise.resolve({
1344
- url: new URL(url),
1345
- async fetch(input, init) {
1346
- if (closed) throw new TypeError("The session is closed.");
1347
- const request = new Request(input instanceof Request ? input.clone() : input, init);
1348
- const index = ++fetches;
1349
- requests.push(request);
1350
- events.push(`fetch #${index} ${request.url}`);
1351
- const recorded = createRecordedResponse(events, index, await respond(request, index), () => closing ? " by close" : "");
1352
- tracked.push({
1353
- ...recorded,
1354
- index
1355
- });
1356
- return recorded.response;
1357
- },
1358
- close() {
1359
- if (closed) return Promise.resolve();
1360
- closed = true;
1361
- closes++;
1362
- closing = true;
1363
- for (const { response, settled, index } of tracked) {
1364
- if (settled()) continue;
1365
- if (response.body?.locked) unsettledAtClose.push(index);
1366
- else response.body?.cancel().catch(() => {});
1367
- }
1368
- events.push(`close ${url}`);
1369
- return Promise.resolve();
1370
- }
1371
- });
1372
- },
1373
- assertInvariants() {
1374
- assertEquals(opens, closes);
1375
- assertEquals(unsettledAtClose, []);
1376
- }
1377
- };
1378
- }
1379
- test("sendActivity() bounds a stalled diagnostic preview without changing HTTP failure", async () => {
1380
- const inbox = new URL("https://example.com/lifecycle/stalled-error");
1381
- let reads = 0;
1382
- let cancels = 0;
1383
- let closed = 0;
1384
- let submissions = 0;
1385
- const body = new ReadableStream({
1386
- pull(controller) {
1387
- if (reads++ === 0) controller.enqueue(new TextEncoder().encode("partial error"));
1388
- },
1389
- cancel() {
1390
- cancels++;
1391
- return new Promise(() => {});
1392
- }
1393
- }, { highWaterMark: 0 });
1394
- const error = await assertRejects(() => sendActivity({
1395
- activity: lifecycleActivity,
1396
- keys: unsignedKeys,
1397
- inbox
1398
- }, { openHop: () => Promise.resolve({
1399
- url: inbox,
1400
- fetch: () => {
1401
- submissions++;
1402
- return Promise.resolve(new Response(body, {
1403
- status: 503,
1404
- headers: { "Retry-After": "1" }
1405
- }));
1406
- },
1407
- close: () => {
1408
- closed++;
1409
- assertFalse(body.locked);
1410
- return Promise.resolve();
1411
- }
1412
- }) }), SendActivityError);
1413
- assertEquals(error.statusCode, 503);
1414
- assertEquals(error.responseBody, "partial error… (timed out)");
1415
- assertEquals(error.responseHeaders.get("Retry-After"), "1");
1416
- assertEquals(submissions, 1);
1417
- assertEquals(cancels, 1);
1418
- assertEquals(closed, 1);
1419
- });
1420
- //#endregion
1421
- export {};