@pkcprotocol/pkc-js 0.0.152 → 0.0.154

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 (132) hide show
  1. package/README.md +21 -1
  2. package/dist/browser/clients/rpc-client/schema.d.ts +1 -1
  3. package/dist/browser/clients/rpc-client/schema.js +1 -1
  4. package/dist/browser/clients/rpc-client/schema.js.map +1 -1
  5. package/dist/browser/errors.d.ts +4 -2
  6. package/dist/browser/errors.js +4 -2
  7. package/dist/browser/errors.js.map +1 -1
  8. package/dist/browser/generated-version.d.ts +1 -1
  9. package/dist/browser/generated-version.js +1 -1
  10. package/dist/browser/pkc-error.d.ts +1 -1
  11. package/dist/browser/publications/comment/comment.d.ts +1 -0
  12. package/dist/browser/publications/comment/comment.js +57 -12
  13. package/dist/browser/publications/comment/comment.js.map +1 -1
  14. package/dist/browser/publications/comment/schema.d.ts +1 -0
  15. package/dist/browser/publications/comment/schema.js +6 -2
  16. package/dist/browser/publications/comment/schema.js.map +1 -1
  17. package/dist/browser/publications/publication.d.ts +8 -1
  18. package/dist/browser/publications/publication.js +393 -146
  19. package/dist/browser/publications/publication.js.map +1 -1
  20. package/dist/browser/publications/types.d.ts +1 -0
  21. package/dist/browser/rpc/src/index.js +12 -5
  22. package/dist/browser/rpc/src/index.js.map +1 -1
  23. package/dist/browser/runtime/node/blockstore.d.ts +2 -2
  24. package/dist/browser/runtime/node/blockstore.js +2 -2
  25. package/dist/browser/runtime/node/community/challenges/validate-challenge-result.js +7 -2
  26. package/dist/browser/runtime/node/community/challenges/validate-challenge-result.js.map +1 -1
  27. package/dist/browser/runtime/node/community/comment-update-row.d.ts +9 -0
  28. package/dist/browser/runtime/node/community/comment-update-row.js +49 -0
  29. package/dist/browser/runtime/node/community/comment-update-row.js.map +1 -0
  30. package/dist/browser/runtime/node/community/db-handler.d.ts +5 -7
  31. package/dist/browser/runtime/node/community/db-handler.js +89 -87
  32. package/dist/browser/runtime/node/community/db-handler.js.map +1 -1
  33. package/dist/browser/runtime/node/community/db-row-parser.js +15 -1
  34. package/dist/browser/runtime/node/community/db-row-parser.js.map +1 -1
  35. package/dist/browser/runtime/node/community/local-community/cleanup.js +62 -12
  36. package/dist/browser/runtime/node/community/local-community/cleanup.js.map +1 -1
  37. package/dist/browser/runtime/node/community/local-community/comment-updates.js +17 -8
  38. package/dist/browser/runtime/node/community/local-community/comment-updates.js.map +1 -1
  39. package/dist/browser/runtime/node/community/local-community/db-state.d.ts +1 -1
  40. package/dist/browser/runtime/node/community/local-community/db-state.js +31 -39
  41. package/dist/browser/runtime/node/community/local-community/db-state.js.map +1 -1
  42. package/dist/browser/runtime/node/community/local-community/editing.js +71 -22
  43. package/dist/browser/runtime/node/community/local-community/editing.js.map +1 -1
  44. package/dist/browser/runtime/node/community/local-community/ipns-publishing.js +1 -1
  45. package/dist/browser/runtime/node/community/local-community/ipns-publishing.js.map +1 -1
  46. package/dist/browser/runtime/node/community/local-community/lifecycle.d.ts +0 -2
  47. package/dist/browser/runtime/node/community/local-community/lifecycle.js +50 -72
  48. package/dist/browser/runtime/node/community/local-community/lifecycle.js.map +1 -1
  49. package/dist/browser/runtime/node/community/local-community.d.ts +4 -2
  50. package/dist/browser/runtime/node/community/local-community.js +11 -7
  51. package/dist/browser/runtime/node/community/local-community.js.map +1 -1
  52. package/dist/browser/runtime/node/community/start-lock.d.ts +14 -5
  53. package/dist/browser/runtime/node/community/start-lock.js +153 -10
  54. package/dist/browser/runtime/node/community/start-lock.js.map +1 -1
  55. package/dist/browser/runtime/node/util.js +20 -11
  56. package/dist/browser/runtime/node/util.js.map +1 -1
  57. package/dist/browser/signer/signatures.js +12 -6
  58. package/dist/browser/signer/signatures.js.map +1 -1
  59. package/dist/browser/version.js +1 -1
  60. package/dist/bundled/bundle-manifest.json +36 -44
  61. package/dist/bundled/challenges.js +1 -1
  62. package/dist/bundled/chunks/{helia-for-pkc-DSBGaWoX.js → helia-for-pkc-CG9YohPs.js} +35 -35
  63. package/dist/bundled/chunks/{local-community-CKRKoJii.js → local-community-CaQmhX8D.js} +1 -1
  64. package/dist/bundled/chunks/{local-community-nvuF7v2h.js → local-community-V8_VyEhO.js} +302 -203
  65. package/dist/bundled/chunks/{node-POly7vn3.js → node-c4vpD2VN.js} +340 -172
  66. package/dist/bundled/chunks/{page-sort-scoring-B12LzU3B.js → page-sort-scoring-d1frahfd.js} +1 -1
  67. package/dist/bundled/chunks/{rpc-local-community-BpvBPdXg.js → rpc-local-community-DDAibWpE.js} +154 -1437
  68. package/dist/bundled/chunks/{util-BjNpPYD5.js → util-B_dKP7Te.js} +1 -1
  69. package/dist/bundled/chunks/{util-sMOCDTgY.js → util-BwEIge-b.js} +9 -6
  70. package/dist/bundled/chunks/{validate-package-factories-DC853tZf.js → validate-package-factories-DfpNf4oq.js} +2 -2
  71. package/dist/bundled/index.js +1 -1
  72. package/dist/bundled/page-sorts.js +1 -1
  73. package/dist/bundled/rpc/src/index.js +14 -9
  74. package/dist/node/clients/rpc-client/schema.d.ts +1 -1
  75. package/dist/node/clients/rpc-client/schema.js +1 -1
  76. package/dist/node/clients/rpc-client/schema.js.map +1 -1
  77. package/dist/node/errors.d.ts +4 -2
  78. package/dist/node/errors.js +4 -2
  79. package/dist/node/errors.js.map +1 -1
  80. package/dist/node/generated-version.d.ts +1 -1
  81. package/dist/node/generated-version.js +1 -1
  82. package/dist/node/pkc-error.d.ts +1 -1
  83. package/dist/node/publications/comment/comment.d.ts +1 -0
  84. package/dist/node/publications/comment/comment.js +57 -12
  85. package/dist/node/publications/comment/comment.js.map +1 -1
  86. package/dist/node/publications/comment/schema.d.ts +1 -0
  87. package/dist/node/publications/comment/schema.js +6 -2
  88. package/dist/node/publications/comment/schema.js.map +1 -1
  89. package/dist/node/publications/publication.d.ts +8 -1
  90. package/dist/node/publications/publication.js +393 -146
  91. package/dist/node/publications/publication.js.map +1 -1
  92. package/dist/node/publications/types.d.ts +1 -0
  93. package/dist/node/rpc/src/index.js +12 -5
  94. package/dist/node/rpc/src/index.js.map +1 -1
  95. package/dist/node/runtime/node/blockstore.d.ts +2 -2
  96. package/dist/node/runtime/node/blockstore.js +2 -2
  97. package/dist/node/runtime/node/community/challenges/validate-challenge-result.js +7 -2
  98. package/dist/node/runtime/node/community/challenges/validate-challenge-result.js.map +1 -1
  99. package/dist/node/runtime/node/community/comment-update-row.d.ts +9 -0
  100. package/dist/node/runtime/node/community/comment-update-row.js +49 -0
  101. package/dist/node/runtime/node/community/comment-update-row.js.map +1 -0
  102. package/dist/node/runtime/node/community/db-handler.d.ts +5 -7
  103. package/dist/node/runtime/node/community/db-handler.js +89 -87
  104. package/dist/node/runtime/node/community/db-handler.js.map +1 -1
  105. package/dist/node/runtime/node/community/db-row-parser.js +15 -1
  106. package/dist/node/runtime/node/community/db-row-parser.js.map +1 -1
  107. package/dist/node/runtime/node/community/local-community/cleanup.js +62 -12
  108. package/dist/node/runtime/node/community/local-community/cleanup.js.map +1 -1
  109. package/dist/node/runtime/node/community/local-community/comment-updates.js +17 -8
  110. package/dist/node/runtime/node/community/local-community/comment-updates.js.map +1 -1
  111. package/dist/node/runtime/node/community/local-community/db-state.d.ts +1 -1
  112. package/dist/node/runtime/node/community/local-community/db-state.js +31 -39
  113. package/dist/node/runtime/node/community/local-community/db-state.js.map +1 -1
  114. package/dist/node/runtime/node/community/local-community/editing.js +71 -22
  115. package/dist/node/runtime/node/community/local-community/editing.js.map +1 -1
  116. package/dist/node/runtime/node/community/local-community/ipns-publishing.js +1 -1
  117. package/dist/node/runtime/node/community/local-community/ipns-publishing.js.map +1 -1
  118. package/dist/node/runtime/node/community/local-community/lifecycle.d.ts +0 -2
  119. package/dist/node/runtime/node/community/local-community/lifecycle.js +50 -72
  120. package/dist/node/runtime/node/community/local-community/lifecycle.js.map +1 -1
  121. package/dist/node/runtime/node/community/local-community.d.ts +4 -2
  122. package/dist/node/runtime/node/community/local-community.js +11 -7
  123. package/dist/node/runtime/node/community/local-community.js.map +1 -1
  124. package/dist/node/runtime/node/community/start-lock.d.ts +14 -5
  125. package/dist/node/runtime/node/community/start-lock.js +153 -10
  126. package/dist/node/runtime/node/community/start-lock.js.map +1 -1
  127. package/dist/node/runtime/node/util.js +20 -11
  128. package/dist/node/runtime/node/util.js.map +1 -1
  129. package/dist/node/signer/signatures.js +12 -6
  130. package/dist/node/signer/signatures.js.map +1 -1
  131. package/dist/node/version.js +1 -1
  132. package/package.json +1 -2
@@ -19,6 +19,8 @@ import { decodeRpcChallengeAnswerPubsubMsg, decodeRpcChallengePubsubMsg, decodeR
19
19
  import { PublicationClientsManager } from "./publication-client-manager.js";
20
20
  import { buildRuntimeAuthor } from "./publication-author.js";
21
21
  import { buildRuntimeCommunityFields, getCommunityNameFromWire, normalizeCommunityInputFromCommunity } from "./publication-community.js";
22
+ // The providerUrl of an exchange whose request went straight to a started local community. It names no pubsub client
23
+ const LOCAL_COMMUNITY_PROVIDER = "publishing directly to local community instance";
22
24
  class Publication extends TypedEmitter {
23
25
  constructor(pkc) {
24
26
  super();
@@ -30,6 +32,22 @@ class Publication extends TypedEmitter {
30
32
  // Initialized (not just declared) so hideClassPrivateProps sees it and keeps it out of JSON.
31
33
  this._signedWithKnownCommunityFields = undefined;
32
34
  this._challengeExchanges = {};
35
+ // A publication instance runs one challenge exchange. It is spent once publish() gets past pre-flight (the community
36
+ // fetch, signing, the signature hook), which is the point from which a request can leave this instance, or once
37
+ // stop() ends a publish() that was called. From then on publish() rejects with
38
+ // ERR_PUBLICATION_PUBLISH_ALREADY_CALLED whatever came of the exchange, and a retry is a new instance. A second
39
+ // exchange on the same instance crossed with the first one's requests, watchdog, verdict and teardown. A publish()
40
+ // that rejected during pre-flight has no exchange to cross with, so it does not spend the instance
41
+ this._isPublishSpent = false;
42
+ // True while a publish() call is running, pre-flight included, so a second call next to it rejects too
43
+ this._isPublishCallRunning = false;
44
+ // What ended this instance's publish: the community's verdict, a failure (no response, every provider threw, an
45
+ // unreadable verification, a request a local community or the RPC server rejected) or stop(). Whichever is recorded
46
+ // first is the end. The others then change nothing, and the work publish() still has awaiting (the community fetch,
47
+ // the RPC publish call, the publish loop, a message being verified or decrypted) stops changing this instance.
48
+ // stop() is not cancellation: without this, an await that resolved after stop() overwrote the stopped states, and a
49
+ // verdict that arrived while a failure was being torn down was written and then overwritten by that failure
50
+ this._publishEndedBy = undefined; // initialised so hideClassPrivateProps hides it
33
51
  this._rpcPublishSubscriptionId = undefined;
34
52
  this._pkc = pkc;
35
53
  this._updatePublishingStateWithEmission("stopped");
@@ -159,9 +177,17 @@ class Publication extends TypedEmitter {
159
177
  };
160
178
  }
161
179
  async _handleRpcChallengeVerification(verification, runtimeFields) {
162
- const log = Logger("pkc-js:publication:_handleRpcChallengeVerification");
163
- if (verification.comment)
164
- await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(verification);
180
+ // The caller recorded this verdict as the end of the publish, so it lands also after a stop() during the await below
181
+ if (verification.comment) {
182
+ try {
183
+ await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(verification);
184
+ }
185
+ catch (e) {
186
+ Logger("pkc-js:publication:_handleRpcChallengeVerification").error("The comment in a successful challenge verification does not verify", e);
187
+ await this._tearDownThenWriteFailure(e);
188
+ return;
189
+ }
190
+ }
165
191
  if (this instanceof Comment && runtimeFields)
166
192
  deepMergeRuntimeFields(this, runtimeFields);
167
193
  this._setRpcClientState("stopped");
@@ -174,23 +200,9 @@ class Publication extends TypedEmitter {
174
200
  args: [verification, this instanceof Comment && verification.comment ? this : undefined]
175
201
  }
176
202
  });
177
- // The exchange is over. This path does its own teardown instead of going through
178
- // _postSucessOrFailurePublishing, and without this every publication an RPC client verified
179
- // stayed in pkc._publishingPublications (and in memory) until pkc.destroy(): Comment.stop()
180
- // only reaches Publication.stop() while publishing, so nothing removed it afterwards
181
- this._unregisterFromPkcOncePublishWorkSettles();
182
- if (this._rpcPublishSubscriptionId) {
183
- // Cleared synchronously before the awaited unsubscribe so the deferred
184
- // attach-and-replay timer from _publishWithRpc (#314) sees the teardown immediately
185
- const subscriptionId = this._rpcPublishSubscriptionId;
186
- this._rpcPublishSubscriptionId = undefined;
187
- try {
188
- await this._pkc._pkcRpcClient.unsubscribe(subscriptionId);
189
- }
190
- catch (e) {
191
- log.error("Failed to unsubscribe from publication publish", e);
192
- }
193
- }
203
+ // The exchange is over. End it through the funnel like the pubsub path does: it unsubscribes, unregisters from
204
+ // pkc._publishingPublications and ends the publish run
205
+ await this._postSucessOrFailurePublishing();
194
206
  }
195
207
  async _handleIncomingChallengePubsubMessage(msg) {
196
208
  const log = Logger("pkc-js:publication:_handleIncomingChallengePubsubMessage");
@@ -201,16 +213,17 @@ class Publication extends TypedEmitter {
201
213
  communityChallengeSignerAddress: this._communityChallengeMsgSignerAddress(),
202
214
  validateTimestampRange: true
203
215
  });
216
+ if (this._hasPublishEnded())
217
+ return; // ended while the signature was checked
204
218
  if (!challengeMsgValidity.valid) {
205
219
  const error = new PKCError("ERR_CHALLENGE_SIGNATURE_IS_INVALID", {
206
220
  pubsubMsg: msg,
207
221
  reason: challengeMsgValidity.reason
208
222
  });
209
- log.error("received challenge message with invalid signature", error.toString());
210
- this._changePublicationStateEmitEventEmitStateChangeEvent({
211
- newPublishingState: "failed",
212
- event: { name: "error", args: [error] }
213
- });
223
+ // Anyone on the topic can read our challengeRequestId and send a challenge for it. A message the community
224
+ // did not sign says nothing about this exchange, so it is logged and dropped: emitting it as an "error", or
225
+ // moving publishingState to "failed", would let any peer raise errors on a publication that then succeeds
226
+ log.error("Dropping a challenge message with an invalid signature", error.toString());
214
227
  return;
215
228
  }
216
229
  log(`Received encrypted challenges. Will decrypt and emit them on "challenge" event. User shoud publish solution by calling publishChallengeAnswers`);
@@ -222,6 +235,8 @@ class Publication extends TypedEmitter {
222
235
  decryptedRawString = await decryptEd25519AesGcm(msg.encrypted, pubsubSigner.privateKey, this._community.encryption.publicKey);
223
236
  }
224
237
  catch (e) {
238
+ if (this._hasPublishEnded())
239
+ return;
225
240
  const pkcError = new PKCError("ERR_PUBLICATION_FAILED_TO_DECRYPT_CHALLENGE", { decryptErr: e });
226
241
  log.error("could not decrypt challengemessage.encrypted", pkcError.toString());
227
242
  this._changePublicationStateEmitEventEmitStateChangeEvent({
@@ -235,6 +250,8 @@ class Publication extends TypedEmitter {
235
250
  decryptedJson = await parseJsonWithPKCErrorIfFails(decryptedRawString);
236
251
  }
237
252
  catch (e) {
253
+ if (this._hasPublishEnded())
254
+ return;
238
255
  log.error("could not parse decrypted challengemessage.encrypted as a json", String(e));
239
256
  this._changePublicationStateEmitEventEmitStateChangeEvent({
240
257
  newPublishingState: "failed",
@@ -247,6 +264,8 @@ class Publication extends TypedEmitter {
247
264
  decryptedChallenge = parseDecryptedChallengeWithPKCErrorIfItFails(decryptedJson);
248
265
  }
249
266
  catch (e) {
267
+ if (this._hasPublishEnded())
268
+ return;
250
269
  log.error("could not parse z challengemessage.encrypted as a json", String(e));
251
270
  this._changePublicationStateEmitEventEmitStateChangeEvent({
252
271
  newPublishingState: "failed",
@@ -266,6 +285,8 @@ class Publication extends TypedEmitter {
266
285
  log.trace("Received a copy of a challenge that was already handled, ignoring it");
267
286
  return;
268
287
  }
288
+ if (this._hasPublishEnded())
289
+ return; // ended while it was decrypted
269
290
  this._challengeExchanges[msg.challengeRequestId.toString()].challenge = decryptedChallengeMsg;
270
291
  this._updatePublishingStateWithEmission("waiting-challenge-answers");
271
292
  const challengeTopic = this._community?.pubsubTopic;
@@ -284,16 +305,16 @@ class Publication extends TypedEmitter {
284
305
  communityChallengeSignerAddress: this._communityChallengeMsgSignerAddress(),
285
306
  validateTimestampRange: true
286
307
  });
308
+ if (this._hasPublishEnded())
309
+ return; // ended while the signature was checked
287
310
  if (!signatureValidation.valid) {
288
311
  const error = new PKCError("ERR_CHALLENGE_VERIFICATION_SIGNATURE_IS_INVALID", {
289
312
  pubsubMsg: msg,
290
313
  reason: signatureValidation.reason
291
314
  });
292
- log.error("Publication received a challenge verification with invalid signature", error);
293
- this._changePublicationStateEmitEventEmitStateChangeEvent({
294
- newPublishingState: "failed",
295
- event: { name: "error", args: [error] }
296
- });
315
+ // Like an invalid challenge: anyone on the topic can send one for our challengeRequestId, and it is not the
316
+ // community's verdict, so it is logged and dropped
317
+ log.error("Dropping a challenge verification with an invalid signature", error);
297
318
  return;
298
319
  }
299
320
  let decryptedChallengeVerification;
@@ -315,7 +336,7 @@ class Publication extends TypedEmitter {
315
336
  challenegVerificationMsg: msg
316
337
  });
317
338
  log.error("could not decrypt challengeverification.encrypted", pkcError);
318
- this.emit("error", pkcError);
339
+ await this._endExchangeWithUnreadableChallengeVerification({ verification: msg, error: pkcError });
319
340
  return;
320
341
  }
321
342
  let decryptedJson;
@@ -324,7 +345,7 @@ class Publication extends TypedEmitter {
324
345
  }
325
346
  catch (e) {
326
347
  log.error("could not parse decrypted challengeverification.encrypted as a json", e);
327
- this.emit("error", e);
348
+ await this._endExchangeWithUnreadableChallengeVerification({ verification: msg, error: e });
328
349
  return;
329
350
  }
330
351
  try {
@@ -332,7 +353,7 @@ class Publication extends TypedEmitter {
332
353
  }
333
354
  catch (e) {
334
355
  log.error("could not parse challengeverification.encrypted due to invalid schema", e);
335
- this.emit("error", e);
356
+ await this._endExchangeWithUnreadableChallengeVerification({ verification: msg, error: e });
336
357
  return;
337
358
  }
338
359
  }
@@ -352,9 +373,20 @@ class Publication extends TypedEmitter {
352
373
  log.trace("Received a copy of a challenge verification that was already handled, ignoring it");
353
374
  return;
354
375
  }
376
+ // The verdict is the end of this publish unless a failure or stop() ended it while it was being decrypted. Once
377
+ // recorded it lands, also if stop() runs during the awaits below
378
+ if (!this._claimPublishEnd("verification"))
379
+ return;
355
380
  this._challengeExchanges[msg.challengeRequestId.toString()].challengeVerification = challengeVerificationMsg;
356
381
  if (decryptedChallengeVerification?.comment) {
357
- await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(decryptedChallengeVerification);
382
+ try {
383
+ await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(decryptedChallengeVerification);
384
+ }
385
+ catch (e) {
386
+ log.error("The comment in a successful challenge verification does not verify", e);
387
+ await this._tearDownThenWriteFailure(e);
388
+ return;
389
+ }
358
390
  log("Updated the props of this instance with challengeverification.encrypted");
359
391
  }
360
392
  Object.values(this._challengeExchanges).forEach((exchange) => this._updatePubsubState("stopped", exchange.providerUrl));
@@ -368,6 +400,51 @@ class Publication extends TypedEmitter {
368
400
  });
369
401
  await this._postSucessOrFailurePublishing();
370
402
  }
403
+ // A success verification the community signed but whose encrypted part we cannot read. The exchange is over and the
404
+ // no-response watchdog stopped watching once the challenge arrived, so end it here rather than stay "publishing" and
405
+ // subscribed for good. It ends as failed: we cannot see what the community stored, so there is no result (for a
406
+ // comment, not even its cid) to report as succeeded
407
+ async _endExchangeWithUnreadableChallengeVerification({ verification, error }) {
408
+ const exchange = this._challengeExchanges[verification.challengeRequestId.toString()];
409
+ // A copy delivered by another provider ended it already (#349), or a failure or stop() did while it was decrypted
410
+ if (exchange.challengeVerification || this._hasPublishEnded())
411
+ return;
412
+ exchange.challengeVerification = verification;
413
+ await this._endPublishWithFailure(() => this._changePublicationStateEmitEventEmitStateChangeEvent({
414
+ newPublishingState: "failed",
415
+ event: { name: "error", args: [error] }
416
+ }));
417
+ }
418
+ _claimPublishEnd(endedBy) {
419
+ if (this._publishEndedBy)
420
+ return false;
421
+ this._publishEndedBy = endedBy;
422
+ return true;
423
+ }
424
+ // Asked by the work a publish() started, after each of its awaits, and by the handlers of incoming messages
425
+ _hasPublishEnded() {
426
+ return this._publishEndedBy !== undefined || this._pkc.destroyed;
427
+ }
428
+ // Ends the publish as a failure, unless a verdict or stop() already ended it: then nothing is written and undefined is
429
+ // returned. The teardown comes first and awaits an unsubscribe, during which the subscription still delivers. The end
430
+ // is recorded before it, so a verdict that arrives in that window is dropped instead of being written and then
431
+ // overwritten by writeFailure, which writes "failed" and emits the error
432
+ async _endPublishWithFailure(writeFailure) {
433
+ if (!this._claimPublishEnd("failure"))
434
+ return undefined;
435
+ await this._postSucessOrFailurePublishing();
436
+ return writeFailure();
437
+ }
438
+ // For a success verification that was recorded as the end of the publish and then turns out to be unusable: the
439
+ // comment the community returned does not verify. Like a verification that cannot be read, there is no result to
440
+ // report as succeeded, and nothing else would end the publication, which stayed "publishing" and subscribed
441
+ async _tearDownThenWriteFailure(error) {
442
+ await this._postSucessOrFailurePublishing();
443
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
444
+ newPublishingState: "failed",
445
+ event: { name: "error", args: [error] }
446
+ });
447
+ }
371
448
  async _handleChallengeExchange(pubsubMsg) {
372
449
  const log = Logger("pkc-js:publication:handleChallengeExchange");
373
450
  let decodedJson;
@@ -433,6 +510,15 @@ class Publication extends TypedEmitter {
433
510
  challengeAnswers: toEncryptAnswers.challengeAnswers
434
511
  });
435
512
  }
513
+ // A verdict, a failure or stop() ended the exchange: an answer published now would reach nobody who is waiting
514
+ // for it, and used to move a stopped publication to "waiting-challenge-verification"
515
+ if (this._publishEndedBy)
516
+ throw new PKCError("ERR_PUBLICATION_CHALLENGE_EXCHANGE_ENDED", {
517
+ publicationType: this.getType(),
518
+ state: this.state,
519
+ publishingState: this.publishingState,
520
+ endedBy: this._publishEndedBy
521
+ });
436
522
  const challengeExchangesWithChallenge = Object.values(this._challengeExchanges).filter((exchange) => exchange.challenge);
437
523
  if (challengeExchangesWithChallenge.length === 0)
438
524
  throw Error("No challenge exchanges with challenge");
@@ -474,9 +560,24 @@ class Publication extends TypedEmitter {
474
560
  challengeExchange.challengeAnswerPublishInFlight = false;
475
561
  throw e;
476
562
  }
563
+ const throwIfExchangeEnded = () => {
564
+ if (!this._publishEndedBy)
565
+ return;
566
+ challengeExchange.challengeAnswerPublishInFlight = false;
567
+ throw new PKCError("ERR_PUBLICATION_CHALLENGE_EXCHANGE_ENDED", {
568
+ publicationType: this.getType(),
569
+ state: this.state,
570
+ publishingState: this.publishingState,
571
+ endedBy: this._publishEndedBy
572
+ });
573
+ };
574
+ // The exchange can have ended while the answer was being encrypted and signed
575
+ throwIfExchangeEnded();
477
576
  // TODO should be handling multiple providers with publishing challenge answer?
478
577
  // For now, let's just publish to the provider that got us the challenge and its request
479
578
  this._updatePublishingStateWithEmission("publishing-challenge-answer");
579
+ // A publishingstatechange listener can have called stop() for the state just emitted
580
+ throwIfExchangeEnded();
480
581
  this._updatePubsubState("publishing-challenge-answer", challengeExchange.providerUrl);
481
582
  if (this._publishingToLocalCommunity) {
482
583
  try {
@@ -486,8 +587,11 @@ class Publication extends TypedEmitter {
486
587
  this._challengeExchanges[challengeExchange.challengeRequest.challengeRequestId.toString()].challengeAnswerPublishError =
487
588
  e;
488
589
  challengeExchange.challengeAnswerPublishInFlight = false;
489
- this._updatePublishingStateWithEmission("failed");
490
- this._updatePubsubState("stopped", challengeExchange.providerUrl);
590
+ // Not when the publish ended while the answer was being published: that end settled the states
591
+ if (!this._publishEndedBy) {
592
+ this._updatePublishingStateWithEmission("failed");
593
+ this._updatePubsubState("stopped", challengeExchange.providerUrl);
594
+ }
491
595
  throw e;
492
596
  }
493
597
  }
@@ -499,8 +603,11 @@ class Publication extends TypedEmitter {
499
603
  this._challengeExchanges[challengeExchange.challengeRequest.challengeRequestId.toString()].challengeAnswerPublishError =
500
604
  e;
501
605
  challengeExchange.challengeAnswerPublishInFlight = false;
502
- this._updatePublishingStateWithEmission("failed");
503
- this._updatePubsubState("stopped", challengeExchange.providerUrl);
606
+ // Not when the publish ended while the answer was being published: that end settled the states
607
+ if (!this._publishEndedBy) {
608
+ this._updatePublishingStateWithEmission("failed");
609
+ this._updatePubsubState("stopped", challengeExchange.providerUrl);
610
+ }
504
611
  throw e;
505
612
  }
506
613
  }
@@ -512,12 +619,18 @@ class Publication extends TypedEmitter {
512
619
  decryptedChallengeAnswer;
513
620
  this._challengeExchanges[challengeExchange.challengeRequest.challengeRequestId.toString()].challengeAnswerPublishTimestamp =
514
621
  timestamp();
515
- this._updatePublishingStateWithEmission("waiting-challenge-verification");
516
- const challengeTopic = this._community?.pubsubTopic;
517
- const providers = Object.entries(this._clientsManager.pubsubProviderSubscriptions)
518
- .filter(([, pubsubTopics]) => typeof challengeTopic === "string" && pubsubTopics.includes(challengeTopic))
519
- .map(([provider]) => provider);
520
- providers.forEach((provider) => this._updatePubsubState("waiting-challenge-verification", provider));
622
+ // stop() ran while the answer was being published: the publication is stopped and waits for nothing
623
+ if (this._publishEndedBy === "stop")
624
+ return;
625
+ // A verdict that was recorded meanwhile already wrote the final states
626
+ if (!this._publishEndedBy) {
627
+ this._updatePublishingStateWithEmission("waiting-challenge-verification");
628
+ const challengeTopic = this._community?.pubsubTopic;
629
+ const providers = Object.entries(this._clientsManager.pubsubProviderSubscriptions)
630
+ .filter(([, pubsubTopics]) => typeof challengeTopic === "string" && pubsubTopics.includes(challengeTopic))
631
+ .map(([provider]) => provider);
632
+ providers.forEach((provider) => this._updatePubsubState("waiting-challenge-verification", provider));
633
+ }
521
634
  log(`Responded to challenge with answers`, challengeAnswers);
522
635
  this.emit("challengeanswer", decryptedChallengeAnswer);
523
636
  }
@@ -626,9 +739,12 @@ class Publication extends TypedEmitter {
626
739
  // goes on to use it for update() after being stopped.
627
740
  async _cancelBackgroundCommunityRefresh() {
628
741
  this._communityFetchAbortController?.abort(new PKCError("ERR_GET_COMMUNITY_ABORTED", { publicationType: this.getType(), communityAddress: this.communityAddress }));
629
- if (this._backgroundCommunityRefresh)
630
- await this._backgroundCommunityRefresh;
742
+ // Reset before the drain, not after it: the refresh keeps the aborted signal it was given, and a publish() or
743
+ // update() called right after a stop() that was not awaited must not be handed that aborted signal
744
+ const refresh = this._backgroundCommunityRefresh;
631
745
  this._resetCommunityFetchAbortSignal();
746
+ if (refresh)
747
+ await refresh;
632
748
  }
633
749
  _resetCommunityFetchAbortSignal() {
634
750
  this._communityFetchAbortController = undefined;
@@ -647,12 +763,6 @@ class Publication extends TypedEmitter {
647
763
  this._beginPublishRun();
648
764
  return this._publishRunWaitSignal;
649
765
  }
650
- // True once the run that handed out runSignal is over. Takes the run's own signal, not the current
651
- // controller: stop() followed by publish() in the same tick installs the next run's controller before
652
- // the previous run's waits wake up, and they must still see their own run as over
653
- _isPublishRunOver(runSignal) {
654
- return this._pkc.destroyed || runSignal.aborted;
655
- }
656
766
  // Fresh cache entry first, then a community instance this PKC keeps updating or running (its own loop
657
767
  // keeps the record current), then a stale cache entry, which _fetchCommunityForPublishing refreshes
658
768
  _getCommunityCache() {
@@ -741,10 +851,20 @@ class Publication extends TypedEmitter {
741
851
  return this._clientsManager.fetchCommunityForPublishingWithCacheGuard();
742
852
  }
743
853
  async stop() {
854
+ // Ends the publish, unless a verdict or a failure already did: that end still lands, with its own final
855
+ // publishingState, which this stop() must not replace with "stopped". An instance that was never published has no
856
+ // publish to end and stays publishable
857
+ const wasPublishCalled = this._isPublishSpent || this._isPublishCallRunning;
858
+ if (wasPublishCalled)
859
+ this._isPublishSpent = true; // also a publish() that stop() catches in pre-flight
860
+ const endedByThisStop = wasPublishCalled ? this._claimPublishEnd("stop") : true;
744
861
  // Abort first, so the drain below unwinds an in-flight fetch instead of waiting it out. Only
745
862
  // stop() does this, never the success funnel: a refresh fired to warm a stale cache should
746
863
  // still finish after a publish succeeds.
747
864
  this._communityFetchAbortController?.abort(new PKCError("ERR_GET_COMMUNITY_ABORTED", { publicationType: this.getType(), communityAddress: this.communityAddress }));
865
+ // With no publish to end, a publish() may follow this stop() before it resolves, and it needs a live signal
866
+ if (!wasPublishCalled)
867
+ this._resetCommunityFetchAbortSignal();
748
868
  try {
749
869
  await this._postSucessOrFailurePublishing();
750
870
  }
@@ -754,17 +874,22 @@ class Publication extends TypedEmitter {
754
874
  // fast. In a finally because pkc.destroy() catches a rejecting stop() and then clears
755
875
  // _publishingPublications, so a cleanup failure would otherwise leave the refresh
756
876
  // running past teardown, which is the exact thing this is here to prevent.
757
- if (this._backgroundCommunityRefresh)
877
+ // Only a publish this stop() ended has a refresh to drain: one that started since is not this stop()'s to wait for
878
+ if (wasPublishCalled && this._backgroundCommunityRefresh)
758
879
  await this._backgroundCommunityRefresh;
759
- this._updatePublishingStateWithEmission("stopped");
880
+ // A stop() that had no publish to end leaves a publish() that started since alone
881
+ const publishStartedSinceThisStop = !wasPublishCalled && (this._isPublishSpent || this._isPublishCallRunning);
882
+ if (endedByThisStop && !publishStartedSinceThisStop)
883
+ this._updatePublishingStateWithEmission("stopped");
760
884
  }
761
885
  }
762
886
  _isAllAttemptsExhausted(maxNumOfChallengeExchanges) {
763
887
  // When all providers failed to publish
764
888
  // OR they're done with waiting
765
- if (Object.keys(this._challengeExchanges).length !== maxNumOfChallengeExchanges)
889
+ const challengeExchanges = Object.values(this._challengeExchanges);
890
+ if (challengeExchanges.length !== maxNumOfChallengeExchanges)
766
891
  return false;
767
- return Object.values(this._challengeExchanges).every((exchange) => {
892
+ return challengeExchanges.every((exchange) => {
768
893
  // An exchange that received a challenge or a verification is alive: the community is
769
894
  // talking to us on it, however old its request is. Request age only measures silence
770
895
  // (issue #340).
@@ -788,8 +913,9 @@ class Publication extends TypedEmitter {
788
913
  // re-established a subscription after teardown already ran its unsubscribe, so returning
789
914
  // without undoing it leaves it dangling on the provider. Returns true when the caller should
790
915
  // abandon this provider (issue #270).
916
+ // The same holds when the publish ended any other way while subscribing (a verdict on an earlier provider's request).
791
917
  async _abandonProviderIfStoppedWhileSubscribing(providerUrl) {
792
- if (!this._pkc.destroyed && this.state !== "stopped")
918
+ if (!this._hasPublishEnded() && this.state !== "stopped")
793
919
  return false;
794
920
  const log = Logger("pkc-js:publication:publish:_abandonProviderIfStoppedWhileSubscribing");
795
921
  log("Publication was stopped while subscribing to pubsub, will not publish a challenge request", providerUrl);
@@ -817,7 +943,10 @@ class Publication extends TypedEmitter {
817
943
  const log = Logger("pkc-js:publication:_postSucessOrFailurePublishing");
818
944
  this._publishRunAbortController?.abort();
819
945
  this._unregisterFromPkcOncePublishWorkSettles();
820
- this._setStateWithEmission("stopped");
946
+ // Only a publication that is still publishing. After a verdict the state is "stopped" already, and a listener of
947
+ // that verdict may have started the comment's update loop since ("updating"), which this must not undo
948
+ if (this.state === "publishing")
949
+ this._setStateWithEmission("stopped");
821
950
  if (this._rpcPublishSubscriptionId) {
822
951
  // Cleared synchronously before the awaited unsubscribe so the deferred
823
952
  // attach-and-replay timer from _publishWithRpc (#314) sees the teardown immediately
@@ -875,6 +1004,10 @@ class Publication extends TypedEmitter {
875
1004
  async _handleIncomingChallengeVerificationFromRpc(args) {
876
1005
  const { challengeVerification: encoded, runtimeFields } = args.params.result;
877
1006
  const decoded = decodeRpcChallengeVerificationPubsubMsg(encoded);
1007
+ // The verdict is the end of this publish, unless a failure the server reported (or stop()) already ended it and is
1008
+ // still unsubscribing: this subscription delivers until the server answers that call
1009
+ if (!this._claimPublishEnd("verification"))
1010
+ return;
878
1011
  this._challengeExchanges[decoded.challengeRequestId.toString()] = {
879
1012
  ...this._challengeExchanges[decoded.challengeRequestId.toString()],
880
1013
  challengeVerification: decoded
@@ -895,12 +1028,30 @@ class Publication extends TypedEmitter {
895
1028
  async _handleIncomingErrorFromRpc(args) {
896
1029
  const log = Logger("pkc-js:publication:publish:_publishWithRpc:_handleIncomingErrorFromRpc");
897
1030
  const error = args.params.result;
898
- if (error.details?.newPublishingState)
899
- this._updatePublishingStateNoEmission(error.details.newPublishingState);
900
- if (error.details?.publishThrowError) {
901
- log.error("RPC server threw an error on publish(), will stop publication", error);
1031
+ // The server's publish() threw, or its publication stopped with this error: either way the publish ended there, so
1032
+ // end it here too, or this instance stays publishing, registered and subscribed until stop(). An error that left
1033
+ // the server's publication publishing (a challenge answer that could not be published) is one the caller can
1034
+ // still act on
1035
+ const endedOnServer = error.details?.publishThrowError || error.details?.newState === "stopped";
1036
+ if (endedOnServer) {
1037
+ if (!this._claimPublishEnd("failure")) {
1038
+ // A verdict or stop() already ended it. An error the server only emitted is still the caller's to see
1039
+ if (!error.details?.publishThrowError)
1040
+ this.emit("error", error);
1041
+ return;
1042
+ }
1043
+ log.error("The publication failed on the RPC server, will stop publication", error);
902
1044
  await this._postSucessOrFailurePublishing();
1045
+ // The error first, then the state change, the order a publication emits them in. The server's own state
1046
+ // change follows its error and is ignored from here on (see _publishWithRpc)
1047
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
1048
+ newPublishingState: error.details?.newPublishingState ?? "failed",
1049
+ event: { name: "error", args: [error] }
1050
+ });
1051
+ return;
903
1052
  }
1053
+ if (error.details?.newPublishingState)
1054
+ this._updatePublishingStateNoEmission(error.details.newPublishingState);
904
1055
  this.emit("error", error);
905
1056
  }
906
1057
  async _publishWithRpc() {
@@ -919,7 +1070,28 @@ class Publication extends TypedEmitter {
919
1070
  // Each publish method expects its specific type, but toJSONPubsubRequestToEncrypt() returns the correct shape at runtime
920
1071
  const publishFn = pubNameToPublishFunction[this.getType()];
921
1072
  const { subscriptionId } = await publishFn.bind(rpcClient)(this.toJSONPubsubRequestToEncrypt());
1073
+ if (this._hasPublishEnded()) {
1074
+ // stop() ran while the server was starting this publish and found no subscription id to unsubscribe. The
1075
+ // server answers only after its publish() started, so drop the subscription here or its events reach a
1076
+ // stopped instance that nothing tracks any more
1077
+ try {
1078
+ await rpcClient.unsubscribe(subscriptionId);
1079
+ }
1080
+ catch (e) {
1081
+ Logger("pkc-js:publication:publish:_publishWithRpc").error("Failed to unsubscribe from a publish stopped while starting", e);
1082
+ }
1083
+ return;
1084
+ }
922
1085
  this._rpcPublishSubscriptionId = subscriptionId;
1086
+ // The RPC client removes these handlers only once an unsubscribe call returns, so the subscription still delivers
1087
+ // events after stop(), while its unsubscribe is pending. Like the pubsub messages of a stopped publication, they
1088
+ // are ignored: a verdict used to land on the stopped publication
1089
+ // The same goes for a publish that failed: the server's remaining events, such as the state change that follows
1090
+ // its error, would land in the middle of the teardown or after it
1091
+ const unlessStopped = (handler) => (args) => {
1092
+ if (this._publishEndedBy !== "stop" && this._publishEndedBy !== "failure")
1093
+ return handler(args);
1094
+ };
923
1095
  // Deferred so a listener attached synchronously after `await publish()` resolves still
924
1096
  // receives events the server emitted before the publish response (#314); see
925
1097
  // attachSubscriptionHandlersDeferred for the mechanism
@@ -927,13 +1099,13 @@ class Publication extends TypedEmitter {
927
1099
  subscriptionId,
928
1100
  isStale: () => this._rpcPublishSubscriptionId !== subscriptionId,
929
1101
  attach: (subscription) => subscription
930
- .on("challengerequest", this._handleIncomingChallengeRequestFromRpc.bind(this))
931
- .on("challenge", this._handleIncomingChallengeFromRpc.bind(this))
932
- .on("challengeanswer", this._handleIncomingChallengeAnswerFromRpc.bind(this))
933
- .on("challengeverification", this._handleIncomingChallengeVerificationFromRpc.bind(this))
934
- .on("publishingstatechange", this._handleIncomingPublishingStateFromRpc.bind(this))
935
- .on("statechange", this._handleIncomingStateFromRpc.bind(this))
936
- .on("error", this._handleIncomingErrorFromRpc.bind(this)),
1102
+ .on("challengerequest", unlessStopped(this._handleIncomingChallengeRequestFromRpc.bind(this)))
1103
+ .on("challenge", unlessStopped(this._handleIncomingChallengeFromRpc.bind(this)))
1104
+ .on("challengeanswer", unlessStopped(this._handleIncomingChallengeAnswerFromRpc.bind(this)))
1105
+ .on("challengeverification", unlessStopped(this._handleIncomingChallengeVerificationFromRpc.bind(this)))
1106
+ .on("publishingstatechange", unlessStopped(this._handleIncomingPublishingStateFromRpc.bind(this)))
1107
+ .on("statechange", unlessStopped(this._handleIncomingStateFromRpc.bind(this)))
1108
+ .on("error", unlessStopped(this._handleIncomingErrorFromRpc.bind(this))),
937
1109
  // Pre-deferral a replay throw rejected publish(); the helper contains it (log,
938
1110
  // surface as an "error" event, stop)
939
1111
  replayErrorContainment: {
@@ -1002,8 +1174,11 @@ class Publication extends TypedEmitter {
1002
1174
  this._validateCommunityFields();
1003
1175
  }
1004
1176
  catch (e) {
1005
- this._setStateWithEmission("stopped");
1006
- this._updatePublishingStateWithEmission("failed");
1177
+ // A fetch aborted by stop() rejects after stop() settled the states, which must stay "stopped"
1178
+ if (!this._hasPublishEnded()) {
1179
+ this._setStateWithEmission("stopped");
1180
+ this._updatePublishingStateWithEmission("failed");
1181
+ }
1007
1182
  throw e;
1008
1183
  }
1009
1184
  }
@@ -1043,14 +1218,14 @@ class Publication extends TypedEmitter {
1043
1218
  return contexts;
1044
1219
  }
1045
1220
  async _handleNotReceivingResponseToChallengeRequest({ providers, currentPubsubProviderIndex, acceptedChallengeTypes }) {
1046
- // The run this watchdog belongs to; every check below asks about this run, never the current one
1221
+ // Aborted once the publish run is over, so the waits below end with it
1047
1222
  const runSignal = this._getPublishRunWaitSignal();
1048
1223
  await sleepUntilTimeoutOrAbort(this._publishToDifferentProviderThresholdSeconds * 1000, runSignal);
1049
1224
  // pkc.destroy() and the end of the run (verification, failure, stop()) abort the sleep above, so
1050
1225
  // neither teardown nor garbage collection waits it out. Bail before doing any re-publish work:
1051
1226
  // otherwise we'd create a signer on a destroyed pkc (throwing ERR_PKC_IS_DESTROYED), re-publish a
1052
1227
  // stopped publication, or re-subscribe/re-dial peers that nothing is left to tear down.
1053
- if (this._isPublishRunOver(runSignal))
1228
+ if (this._hasPublishEnded())
1054
1229
  return;
1055
1230
  if (this._didWeReceiveChallengeOrChallengeVerification())
1056
1231
  return;
@@ -1062,15 +1237,16 @@ class Publication extends TypedEmitter {
1062
1237
  if (this._isAllAttemptsExhausted(providers.length)) {
1063
1238
  // pkc-js tried all providers and still no response is received
1064
1239
  log.error(`Failed to receive any response for publication`, this.getType());
1065
- await this._postSucessOrFailurePublishing();
1066
- const error = new PKCError("ERR_PUBSUB_DID_NOT_RECEIVE_RESPONSE_AFTER_PUBLISHING_CHALLENGE_REQUEST", {
1067
- challengeExchanges: this._challengeExchangesFormattedForErrors(),
1068
- publishToDifferentProviderThresholdSeconds: this._publishToDifferentProviderThresholdSeconds,
1069
- providerHeliaContexts: this._libp2pJsClientHeliaContexts()
1070
- });
1071
- this._changePublicationStateEmitEventEmitStateChangeEvent({
1072
- newPublishingState: "failed",
1073
- event: { name: "error", args: [error] }
1240
+ await this._endPublishWithFailure(() => {
1241
+ const error = new PKCError("ERR_PUBSUB_DID_NOT_RECEIVE_RESPONSE_AFTER_PUBLISHING_CHALLENGE_REQUEST", {
1242
+ challengeExchanges: this._challengeExchangesFormattedForErrors(),
1243
+ publishToDifferentProviderThresholdSeconds: this._publishToDifferentProviderThresholdSeconds,
1244
+ providerHeliaContexts: this._libp2pJsClientHeliaContexts()
1245
+ });
1246
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
1247
+ newPublishingState: "failed",
1248
+ event: { name: "error", args: [error] }
1249
+ });
1074
1250
  });
1075
1251
  }
1076
1252
  else if (this.state === "stopped") {
@@ -1078,19 +1254,17 @@ class Publication extends TypedEmitter {
1078
1254
  await this._postSucessOrFailurePublishing();
1079
1255
  }
1080
1256
  else {
1081
- if (currentPubsubProviderIndex + 1 === providers.length) {
1082
- log.error(`Failed to receive any response for publication`, this.getType(), "after publishing to all providers", providers);
1083
- await this._postSucessOrFailurePublishing();
1084
- }
1085
- else {
1257
+ if (currentPubsubProviderIndex + 1 < providers.length) {
1086
1258
  // let's publish to the next provider
1087
1259
  log(`Re-publishing publication after ${this._publishToDifferentProviderThresholdSeconds}s of not receiving challenge from provider (${currentPubsubProvider})`);
1088
1260
  currentPubsubProviderIndex += 1;
1089
1261
  while (!this._didWeReceiveChallengeOrChallengeVerification() && currentPubsubProviderIndex < providers.length) {
1090
1262
  const providerUrl = providers[currentPubsubProviderIndex];
1091
- if (this._isPublishRunOver(runSignal))
1263
+ if (this._hasPublishEnded())
1092
1264
  return;
1093
1265
  const challengeRequest = await this._generateChallengeRequestToPublish(providerUrl, acceptedChallengeTypes);
1266
+ if (this._hasPublishEnded())
1267
+ return;
1094
1268
  this._updatePublishingStateWithEmission("publishing-challenge-request");
1095
1269
  this._updatePubsubState("subscribing-pubsub", providerUrl);
1096
1270
  try {
@@ -1103,6 +1277,8 @@ class Publication extends TypedEmitter {
1103
1277
  timestamp();
1104
1278
  }
1105
1279
  catch (e) {
1280
+ if (this._hasPublishEnded())
1281
+ return;
1106
1282
  log.error("Failed to publish challenge request using provider ", providerUrl, e);
1107
1283
  this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishError = e;
1108
1284
  continue;
@@ -1110,6 +1286,8 @@ class Publication extends TypedEmitter {
1110
1286
  finally {
1111
1287
  currentPubsubProviderIndex += 1;
1112
1288
  }
1289
+ if (this._hasPublishEnded())
1290
+ return;
1113
1291
  const decryptedRequest = this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequest;
1114
1292
  // The first request's challenge can land while the retry's publish call is still
1115
1293
  // in flight; the publication is then already waiting for answers (or verified) and
@@ -1122,34 +1300,41 @@ class Publication extends TypedEmitter {
1122
1300
  this.emit("challengerequest", decryptedRequest);
1123
1301
  if (currentPubsubProviderIndex !== providers.length)
1124
1302
  await sleepUntilTimeoutOrAbort(this._publishToDifferentProviderThresholdSeconds * 1000, runSignal);
1125
- if (this._isPublishRunOver(runSignal))
1303
+ if (this._hasPublishEnded())
1126
1304
  return;
1127
1305
  }
1128
- await sleepUntilTimeoutOrAbort(this._setProviderFailureThresholdSeconds * 1000, runSignal);
1129
- if (this._isPublishRunOver(runSignal))
1130
- return;
1131
- // Kept although stop() now ends the wait above through the run signal: a stopped
1132
- // publication must not be treated as a failure and emit ERR_ALL_PUBSUB_PROVIDERS_THROW_ERRORS.
1133
- // The enclosing `else` narrowed `this.state` to exclude "stopped", but stop() during the
1134
- // awaited wait above can have set it since, so widen back to the field's declared type.
1135
- if (this.state === "stopped")
1136
- return;
1137
- // A challenge (or the verification itself) can arrive during the wait above. That
1138
- // exchange is live and the no-response watchdog has nothing left to decide: the
1139
- // publication stays subscribed for its verification, exactly like a publication whose
1140
- // challenge arrived before any retry (issue #340).
1141
- if (this._didWeReceiveChallengeOrChallengeVerification()) {
1142
- log(`Received a challenge or challenge verification while waiting for retried providers, will keep the exchange alive`);
1143
- return;
1144
- }
1145
- if (this._isAllAttemptsExhausted(providers.length)) {
1146
- // Read before the cleanup below, and say what actually happened. A request that
1147
- // reached pubsub and was met with silence may still be accepted by a community
1148
- // that is slow or busy (issue #362), so that is "no response", never "all
1149
- // providers threw". Only when no request could be published at all is the
1150
- // publication known not to have reached the community.
1151
- const aRequestWasPublished = this._wasAnyChallengeRequestPublished();
1152
- await this._postSucessOrFailurePublishing();
1306
+ }
1307
+ else {
1308
+ // The request is held by the last provider (the ones before it threw), so there is nobody left to
1309
+ // retry with. Give it the same failure wait as a retried request below. Stopping here instead left the
1310
+ // publication stopped with publishingState "waiting-challenge" and no error
1311
+ log(`No response from the last provider (${currentPubsubProvider}), will wait for it until the failure threshold`);
1312
+ }
1313
+ await sleepUntilTimeoutOrAbort(this._setProviderFailureThresholdSeconds * 1000, runSignal);
1314
+ if (this._hasPublishEnded())
1315
+ return;
1316
+ // Kept although stop() now ends the wait above through the run signal: a stopped
1317
+ // publication must not be treated as a failure and emit ERR_ALL_PUBSUB_PROVIDERS_THROW_ERRORS.
1318
+ // The enclosing `else` narrowed `this.state` to exclude "stopped", but stop() during the
1319
+ // awaited wait above can have set it since, so widen back to the field's declared type.
1320
+ if (this.state === "stopped")
1321
+ return;
1322
+ // A challenge (or the verification itself) can arrive during the wait above. That
1323
+ // exchange is live and the no-response watchdog has nothing left to decide: the
1324
+ // publication stays subscribed for its verification, exactly like a publication whose
1325
+ // challenge arrived before any retry (issue #340).
1326
+ if (this._didWeReceiveChallengeOrChallengeVerification()) {
1327
+ log(`Received a challenge or challenge verification while waiting for retried providers, will keep the exchange alive`);
1328
+ return;
1329
+ }
1330
+ if (this._isAllAttemptsExhausted(providers.length)) {
1331
+ // Read before the cleanup below, and say what actually happened. A request that
1332
+ // reached pubsub and was met with silence may still be accepted by a community
1333
+ // that is slow or busy (issue #362), so that is "no response", never "all
1334
+ // providers threw". Only when no request could be published at all is the
1335
+ // publication known not to have reached the community.
1336
+ const aRequestWasPublished = this._wasAnyChallengeRequestPublished();
1337
+ await this._endPublishWithFailure(() => {
1153
1338
  const allAttemptsFailedError = aRequestWasPublished
1154
1339
  ? new PKCError("ERR_PUBSUB_DID_NOT_RECEIVE_RESPONSE_AFTER_PUBLISHING_CHALLENGE_REQUEST", {
1155
1340
  challengeExchanges: this._challengeExchangesFormattedForErrors(),
@@ -1168,8 +1353,8 @@ class Publication extends TypedEmitter {
1168
1353
  newPublishingState: "failed",
1169
1354
  event: { name: "error", args: [allAttemptsFailedError] }
1170
1355
  });
1171
- return;
1172
- }
1356
+ });
1357
+ return;
1173
1358
  }
1174
1359
  }
1175
1360
  }
@@ -1188,6 +1373,8 @@ class Publication extends TypedEmitter {
1188
1373
  const log = Logger("pkc-js:publication:publish:_publishWithLocalCommunity");
1189
1374
  log("Community is local, will not publish over pubsub, and instead will publish directly to the community by accessing pkc._startedCommunities");
1190
1375
  const communityChallengeListener = async (challenge) => {
1376
+ if (this._hasPublishEnded())
1377
+ return;
1191
1378
  if (challenge.challengeRequestId.toString() === challengeRequest.challengeRequestId.toString()) {
1192
1379
  // need to remove encrypted fields from challenge otherwise _handleIncomingChallengePubsubMessage will throw
1193
1380
  const encryptedFields = ["challenges"];
@@ -1196,12 +1383,18 @@ class Publication extends TypedEmitter {
1196
1383
  }
1197
1384
  };
1198
1385
  community.on("challenge", communityChallengeListener);
1386
+ // The handling of the community's verdict, which records it only after its signature is checked. Set synchronously
1387
+ // on the emission, so a rejection that follows the verdict can wait for it
1388
+ let verificationHandling;
1199
1389
  const communityChallengeVerificationListener = async (decryptedChallengeVerification) => {
1390
+ if (this._hasPublishEnded())
1391
+ return;
1200
1392
  if (decryptedChallengeVerification.challengeRequestId.toString() === challengeRequest.challengeRequestId.toString()) {
1201
1393
  log("Received a challenge verification from the local community", decryptedChallengeVerification);
1202
1394
  // need to remove publicatioon fields from challenge verification otherwise verifyChallengeVerification will throw
1203
1395
  const publicationFieldsToRemove = ["comment", "commentUpdate"];
1204
- await this._handleIncomingChallengeVerificationPubsubMessage(omit(decryptedChallengeVerification, publicationFieldsToRemove));
1396
+ verificationHandling = this._handleIncomingChallengeVerificationPubsubMessage(omit(decryptedChallengeVerification, publicationFieldsToRemove));
1397
+ await verificationHandling;
1205
1398
  }
1206
1399
  };
1207
1400
  community.on("challengeverification", communityChallengeVerificationListener);
@@ -1214,10 +1407,25 @@ class Publication extends TypedEmitter {
1214
1407
  challengeRequestPublishTimestamp: timestamp()
1215
1408
  };
1216
1409
  })
1217
- .catch((e) => {
1410
+ .catch(async (e) => {
1218
1411
  log.error("Failed to handle challenge request with local community", e);
1219
- this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishError = e;
1220
- throw e;
1412
+ const challengeRequestId = challengeRequest.challengeRequestId.toString();
1413
+ this._challengeExchanges[challengeRequestId].challengeRequestPublishError = e;
1414
+ // A request the community could not decrypt or parse gets a failed verdict right before this rejection. That
1415
+ // verdict ends the publish, so wait for its handling (a rejection of it still rejects the listener above)
1416
+ await verificationHandling?.catch(() => { });
1417
+ // Without a verdict, nothing else can end the publish: the listeners above are removed once this settles. It
1418
+ // used to stay "publishing" and registered until stop(), and the rejection was unhandled. After a verdict or
1419
+ // a stop() this writes nothing
1420
+ try {
1421
+ await this._endPublishWithFailure(() => this._changePublicationStateEmitEventEmitStateChangeEvent({
1422
+ newPublishingState: "failed",
1423
+ event: { name: "error", args: [e] }
1424
+ }));
1425
+ }
1426
+ catch (endError) {
1427
+ log.error("Failed to end the exchange the local community rejected", endError);
1428
+ }
1221
1429
  })
1222
1430
  .finally(() => {
1223
1431
  community.removeListener("challenge", communityChallengeListener);
@@ -1225,9 +1433,21 @@ class Publication extends TypedEmitter {
1225
1433
  });
1226
1434
  }
1227
1435
  async publish() {
1436
+ // One challenge exchange per instance, see _isPublishSpent
1437
+ if (this._isPublishSpent || this._isPublishCallRunning) {
1438
+ const exchanges = Object.values(this._challengeExchanges);
1439
+ throw new PKCError("ERR_PUBLICATION_PUBLISH_ALREADY_CALLED", {
1440
+ publicationType: this.getType(),
1441
+ state: this.state,
1442
+ publishingState: this.publishingState,
1443
+ receivedChallenge: exchanges.some((exchange) => exchange.challenge),
1444
+ receivedChallengeVerification: exchanges.some((exchange) => exchange.challengeVerification)
1445
+ });
1446
+ }
1228
1447
  this._validatePublicationFields();
1229
- // A previous stop() left the signal aborted, which would cancel this attempt's community
1230
- // fetch before it started.
1448
+ this._isPublishCallRunning = true;
1449
+ // An earlier stop() left the signal aborted, which would cancel this publish's community fetch before it
1450
+ // started.
1231
1451
  if (this._getCommunityFetchAbortSignal().aborted)
1232
1452
  this._resetCommunityFetchAbortSignal();
1233
1453
  this._beginPublishRun();
@@ -1252,6 +1472,9 @@ class Publication extends TypedEmitter {
1252
1472
  this._publishRunAbortController?.abort();
1253
1473
  throw e;
1254
1474
  }
1475
+ finally {
1476
+ this._isPublishCallRunning = false;
1477
+ }
1255
1478
  }
1256
1479
  async _publishAfterRegistering() {
1257
1480
  const log = Logger("pkc-js:publication:publish");
@@ -1269,29 +1492,41 @@ class Publication extends TypedEmitter {
1269
1492
  await this._signPublicationWithCommunityFields();
1270
1493
  }
1271
1494
  await this._validateSignatureHook();
1495
+ // Stopped during the steps above: stop() settled the states, so do not start an exchange behind it
1496
+ if (this._hasPublishEnded())
1497
+ return;
1498
+ // Pre-flight is over. From here a request can leave this instance, so it cannot publish again
1499
+ this._isPublishSpent = true;
1272
1500
  if (this._pkc._pkcRpcClient)
1273
1501
  return this._publishWithRpc();
1274
1502
  const options = { acceptedChallengeTypes: [] };
1275
1503
  const startedCommunity = findStartedCommunity(this._pkc, { publicKey: this.communityPublicKey, name: this.communityName });
1276
1504
  if (startedCommunity) {
1277
- return this._publishWithLocalCommunity(startedCommunity, await this._generateChallengeRequestToPublish("publishing directly to local community instance", options.acceptedChallengeTypes));
1505
+ const challengeRequest = await this._generateChallengeRequestToPublish(LOCAL_COMMUNITY_PROVIDER, options.acceptedChallengeTypes);
1506
+ if (this._hasPublishEnded())
1507
+ return;
1508
+ return this._publishWithLocalCommunity(startedCommunity, challengeRequest);
1278
1509
  }
1279
1510
  // Only the network path needs a challenge topic. Fail fast before touching pubsub so a client
1280
1511
  // can disable its reply UI instead of timing out against a topic nobody runs (issue #229).
1281
1512
  if (typeof this._community?.pubsubTopic !== "string") {
1282
- await this._postSucessOrFailurePublishing();
1283
- const error = new PKCError("ERR_COMMUNITY_CHALLENGE_EXCHANGE_DISABLED", {
1284
- communityAddress: this._community?.address ?? this.communityAddress,
1285
- communityName: this._community?.name ?? this.communityName,
1286
- communityPublicKey: this._community?.publicKey ?? this.communityPublicKey,
1287
- publicationType: this.getType()
1288
- });
1289
- log.error("Community has its challenge exchange disabled, will not publish", this.getType(), error);
1290
- this._changePublicationStateEmitEventEmitStateChangeEvent({
1291
- newPublishingState: "failed",
1292
- event: { name: "error", args: [error] }
1513
+ const disabledError = await this._endPublishWithFailure(() => {
1514
+ const error = new PKCError("ERR_COMMUNITY_CHALLENGE_EXCHANGE_DISABLED", {
1515
+ communityAddress: this._community?.address ?? this.communityAddress,
1516
+ communityName: this._community?.name ?? this.communityName,
1517
+ communityPublicKey: this._community?.publicKey ?? this.communityPublicKey,
1518
+ publicationType: this.getType()
1519
+ });
1520
+ log.error("Community has its challenge exchange disabled, will not publish", this.getType(), error);
1521
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
1522
+ newPublishingState: "failed",
1523
+ event: { name: "error", args: [error] }
1524
+ });
1525
+ return error;
1293
1526
  });
1294
- throw error;
1527
+ if (disabledError)
1528
+ throw disabledError;
1529
+ return; // stop() ended the publish first
1295
1530
  }
1296
1531
  // Discovered only once the network path is certain: neither the local shortcut above nor the
1297
1532
  // disabled-exchange fast-fail publishes over pubsub, so neither should demand a provider.
@@ -1300,6 +1535,8 @@ class Publication extends TypedEmitter {
1300
1535
  while (!this._didWeReceiveChallengeOrChallengeVerification() && currentPubsubProviderIndex < providers.length) {
1301
1536
  const providerUrl = providers[currentPubsubProviderIndex];
1302
1537
  const challengeRequest = await this._generateChallengeRequestToPublish(providerUrl, options.acceptedChallengeTypes);
1538
+ if (this._hasPublishEnded())
1539
+ return;
1303
1540
  this._updatePublishingStateWithEmission("publishing-challenge-request");
1304
1541
  this._updatePubsubState("subscribing-pubsub", providerUrl);
1305
1542
  try {
@@ -1312,27 +1549,37 @@ class Publication extends TypedEmitter {
1312
1549
  this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishTimestamp = timestamp();
1313
1550
  }
1314
1551
  catch (e) {
1552
+ if (this._hasPublishEnded())
1553
+ return; // stopped meanwhile: a clean exit, not a failure
1315
1554
  this._updatePubsubState("stopped", providerUrl);
1316
1555
  log.error("Failed to publish challenge request using provider ", providerUrl, e);
1317
1556
  currentPubsubProviderIndex += 1;
1318
1557
  this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishError = e;
1319
1558
  if (this._isAllAttemptsExhausted(providers.length)) {
1320
- await this._postSucessOrFailurePublishing();
1321
- const allAttemptsFailedError = new PKCError("ERR_ALL_PUBSUB_PROVIDERS_THROW_ERRORS", {
1322
- challengeExchanges: this._challengeExchangesFormattedForErrors(),
1323
- pubsubTopic: this._community?.pubsubTopic,
1324
- providerHeliaContexts: this._libp2pJsClientHeliaContexts()
1325
- });
1326
- log.error("All attempts to publish", this.getType(), "has failed", allAttemptsFailedError);
1327
- this._changePublicationStateEmitEventEmitStateChangeEvent({
1328
- newPublishingState: "failed",
1329
- event: { name: "error", args: [allAttemptsFailedError] }
1559
+ const failure = await this._endPublishWithFailure(() => {
1560
+ const allAttemptsFailedError = new PKCError("ERR_ALL_PUBSUB_PROVIDERS_THROW_ERRORS", {
1561
+ challengeExchanges: this._challengeExchangesFormattedForErrors(),
1562
+ pubsubTopic: this._community?.pubsubTopic,
1563
+ providerHeliaContexts: this._libp2pJsClientHeliaContexts()
1564
+ });
1565
+ log.error("All attempts to publish", this.getType(), "has failed", allAttemptsFailedError);
1566
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
1567
+ newPublishingState: "failed",
1568
+ event: { name: "error", args: [allAttemptsFailedError] }
1569
+ });
1570
+ return allAttemptsFailedError;
1330
1571
  });
1331
- throw allAttemptsFailedError;
1572
+ if (failure)
1573
+ throw failure;
1574
+ return; // stop() ended the publish first
1332
1575
  }
1333
1576
  else
1334
1577
  continue;
1335
1578
  }
1579
+ // stop() landed while the request was being published and already settled the states and unsubscribed, or
1580
+ // the community's verdict did: waiting for a challenge, or starting the no-response watchdog, would undo that
1581
+ if (this._hasPublishEnded())
1582
+ return;
1336
1583
  const decryptedRequest = this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequest;
1337
1584
  this._updatePubsubState("waiting-challenge", providerUrl);
1338
1585
  this._updatePublishingStateWithEmission("waiting-challenge");