@pkcprotocol/pkc-js 0.0.146 → 0.0.148

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 (102) hide show
  1. package/README.md +88 -55
  2. package/dist/browser/clients/base-client-manager.js +14 -2
  3. package/dist/browser/clients/base-client-manager.js.map +1 -1
  4. package/dist/browser/errors.d.ts +3 -0
  5. package/dist/browser/errors.js +3 -0
  6. package/dist/browser/errors.js.map +1 -1
  7. package/dist/browser/generated-version.d.ts +1 -1
  8. package/dist/browser/generated-version.js +1 -1
  9. package/dist/browser/pkc-error.d.ts +1 -1
  10. package/dist/browser/publications/comment/comment-client-manager.d.ts +15 -3
  11. package/dist/browser/publications/comment/comment-client-manager.js +221 -10
  12. package/dist/browser/publications/comment/comment-client-manager.js.map +1 -1
  13. package/dist/browser/publications/comment/comment.js +1 -0
  14. package/dist/browser/publications/comment/comment.js.map +1 -1
  15. package/dist/browser/runtime/node/community/challenges/exclude/exclude.js +1 -1
  16. package/dist/browser/runtime/node/community/challenges/exclude/exclude.js.map +1 -1
  17. package/dist/browser/runtime/node/community/challenges/exclude/rate-limiter.d.ts +2 -2
  18. package/dist/browser/runtime/node/community/challenges/exclude/rate-limiter.js +21 -17
  19. package/dist/browser/runtime/node/community/challenges/exclude/rate-limiter.js.map +1 -1
  20. package/dist/browser/runtime/node/community/challenges/index.js +1 -1
  21. package/dist/browser/runtime/node/community/challenges/index.js.map +1 -1
  22. package/dist/browser/runtime/node/community/db-handler.d.ts +5 -1
  23. package/dist/browser/runtime/node/community/db-handler.js +64 -12
  24. package/dist/browser/runtime/node/community/db-handler.js.map +1 -1
  25. package/dist/browser/runtime/node/community/local-community/challenges.js +21 -11
  26. package/dist/browser/runtime/node/community/local-community/challenges.js.map +1 -1
  27. package/dist/browser/runtime/node/community/local-community/db-state.js +95 -13
  28. package/dist/browser/runtime/node/community/local-community/db-state.js.map +1 -1
  29. package/dist/browser/runtime/node/community/local-community/editing.js +92 -22
  30. package/dist/browser/runtime/node/community/local-community/editing.js.map +1 -1
  31. package/dist/browser/runtime/node/community/local-community/lifecycle.d.ts +2 -0
  32. package/dist/browser/runtime/node/community/local-community/lifecycle.js +72 -20
  33. package/dist/browser/runtime/node/community/local-community/lifecycle.js.map +1 -1
  34. package/dist/browser/runtime/node/community/local-community/publication-store.js +9 -0
  35. package/dist/browser/runtime/node/community/local-community/publication-store.js.map +1 -1
  36. package/dist/browser/runtime/node/community/local-community.d.ts +1 -0
  37. package/dist/browser/runtime/node/community/local-community.js +3 -0
  38. package/dist/browser/runtime/node/community/local-community.js.map +1 -1
  39. package/dist/browser/runtime/node/util.d.ts +9 -0
  40. package/dist/browser/runtime/node/util.js +141 -25
  41. package/dist/browser/runtime/node/util.js.map +1 -1
  42. package/dist/browser/test/test-util.d.ts +7 -1
  43. package/dist/browser/test/test-util.js +45 -16
  44. package/dist/browser/test/test-util.js.map +1 -1
  45. package/dist/bundled/bundle-manifest.json +40 -40
  46. package/dist/bundled/challenges.js +1 -1
  47. package/dist/bundled/chunks/{helia-for-pkc-PaZmkxgn.js → helia-for-pkc-BUVgQgXa.js} +33 -33
  48. package/dist/bundled/chunks/{local-community-CeuVhBBn.js → local-community-GWqz4s3g.js} +1 -1
  49. package/dist/bundled/chunks/{local-community-BY1ouP1-.js → local-community-dVaQtJNM.js} +292 -91
  50. package/dist/bundled/chunks/{node-BXilwSVE.js → node-fEBX1Nar.js} +162 -16
  51. package/dist/bundled/chunks/{page-sort-scoring-DgSzIxmE.js → page-sort-scoring-DbI7k_K5.js} +1 -1
  52. package/dist/bundled/chunks/{rpc-local-community-BK_HGb_u.js → rpc-local-community-ouDezuGZ.js} +146 -47
  53. package/dist/bundled/chunks/{util-Bnqvxk-6.js → util-B81IOt07.js} +4 -1
  54. package/dist/bundled/chunks/{util-DRSzW-LU.js → util-DofMBAFz.js} +1 -1
  55. package/dist/bundled/chunks/{validate-package-factories-MG5ehoSU.js → validate-package-factories-Bi1OLIPw.js} +2 -2
  56. package/dist/bundled/index.js +1 -1
  57. package/dist/bundled/page-sorts.js +1 -1
  58. package/dist/bundled/rpc/src/index.js +4 -4
  59. package/dist/node/clients/base-client-manager.js +14 -2
  60. package/dist/node/clients/base-client-manager.js.map +1 -1
  61. package/dist/node/errors.d.ts +3 -0
  62. package/dist/node/errors.js +3 -0
  63. package/dist/node/errors.js.map +1 -1
  64. package/dist/node/generated-version.d.ts +1 -1
  65. package/dist/node/generated-version.js +1 -1
  66. package/dist/node/pkc-error.d.ts +1 -1
  67. package/dist/node/publications/comment/comment-client-manager.d.ts +15 -3
  68. package/dist/node/publications/comment/comment-client-manager.js +221 -10
  69. package/dist/node/publications/comment/comment-client-manager.js.map +1 -1
  70. package/dist/node/publications/comment/comment.js +1 -0
  71. package/dist/node/publications/comment/comment.js.map +1 -1
  72. package/dist/node/runtime/node/community/challenges/exclude/exclude.js +1 -1
  73. package/dist/node/runtime/node/community/challenges/exclude/exclude.js.map +1 -1
  74. package/dist/node/runtime/node/community/challenges/exclude/rate-limiter.d.ts +2 -2
  75. package/dist/node/runtime/node/community/challenges/exclude/rate-limiter.js +21 -17
  76. package/dist/node/runtime/node/community/challenges/exclude/rate-limiter.js.map +1 -1
  77. package/dist/node/runtime/node/community/challenges/index.js +1 -1
  78. package/dist/node/runtime/node/community/challenges/index.js.map +1 -1
  79. package/dist/node/runtime/node/community/db-handler.d.ts +5 -1
  80. package/dist/node/runtime/node/community/db-handler.js +64 -12
  81. package/dist/node/runtime/node/community/db-handler.js.map +1 -1
  82. package/dist/node/runtime/node/community/local-community/challenges.js +21 -11
  83. package/dist/node/runtime/node/community/local-community/challenges.js.map +1 -1
  84. package/dist/node/runtime/node/community/local-community/db-state.js +95 -13
  85. package/dist/node/runtime/node/community/local-community/db-state.js.map +1 -1
  86. package/dist/node/runtime/node/community/local-community/editing.js +92 -22
  87. package/dist/node/runtime/node/community/local-community/editing.js.map +1 -1
  88. package/dist/node/runtime/node/community/local-community/lifecycle.d.ts +2 -0
  89. package/dist/node/runtime/node/community/local-community/lifecycle.js +72 -20
  90. package/dist/node/runtime/node/community/local-community/lifecycle.js.map +1 -1
  91. package/dist/node/runtime/node/community/local-community/publication-store.js +9 -0
  92. package/dist/node/runtime/node/community/local-community/publication-store.js.map +1 -1
  93. package/dist/node/runtime/node/community/local-community.d.ts +1 -0
  94. package/dist/node/runtime/node/community/local-community.js +3 -0
  95. package/dist/node/runtime/node/community/local-community.js.map +1 -1
  96. package/dist/node/runtime/node/util.d.ts +9 -0
  97. package/dist/node/runtime/node/util.js +141 -25
  98. package/dist/node/runtime/node/util.js.map +1 -1
  99. package/dist/node/test/test-util.d.ts +7 -1
  100. package/dist/node/test/test-util.js +45 -16
  101. package/dist/node/test/test-util.js.map +1 -1
  102. package/package.json +1 -1
@@ -5,7 +5,7 @@ import assert from "assert";
5
5
  import fs from "fs";
6
6
  import os from "os";
7
7
  import Logger from "../../../logger.js";
8
- import { deleteOldCommunityInWindows, deriveCommentIpfsFromCommentTableRow, getDefaultCommunityDbConfig } from "../util.js";
8
+ import { deleteOldCommunityInWindows, deriveCommentIpfsFromCommentTableRow, forgetCommunityThatFailedToBeDeleted, getDefaultCommunityDbConfig, removeFileRetryingWhileBusy } from "../util.js";
9
9
  import env from "../../../version.js";
10
10
  import Database from "better-sqlite3";
11
11
  import { sha256 } from "js-sha256";
@@ -57,6 +57,8 @@ export class DbHandler {
57
57
  // Advanced by every write to the publication tables (comments, votes, edits, moderations, aliases, purges). The
58
58
  // update cycle's author memo (CommunityAuthorMemo) is only reused while it stays the same.
59
59
  this._publicationWriteGeneration = 0;
60
+ // Identifies the start lock this handler holds, from lockCommunityStart until unlockCommunityStart or its loss
61
+ this._heldStartLock = undefined;
60
62
  this._community = community;
61
63
  this._transactionDepth = 0;
62
64
  this._createdTables = false;
@@ -172,10 +174,18 @@ export class DbHandler {
172
174
  const log = Logger("pkc-js:local-community:dbHandler:destroyConnection");
173
175
  this._preparedStatements.clear(); // statements belong to the connection
174
176
  if (this._db && this._db.open) {
175
- if (!this._db.readonly) {
176
- this._db.exec("PRAGMA wal_checkpoint"); // write all wal to disk
177
+ try {
178
+ if (!this._db.readonly)
179
+ this._db.exec("PRAGMA wal_checkpoint"); // write all wal to disk
180
+ }
181
+ catch (e) {
182
+ // The checkpoint throws on a file that is not a database. The connection is closed all the same:
183
+ // an open handle keeps the file locked on Windows (issue #540)
184
+ log.error("Failed to checkpoint the WAL of community", this._community.address, "before closing its DB", e);
185
+ }
186
+ finally {
187
+ this._db.close();
177
188
  }
178
- this._db.close();
179
189
  }
180
190
  if (this._keyv)
181
191
  this._keyv.disconnect();
@@ -502,18 +512,29 @@ export class DbHandler {
502
512
  for (let i = 0; i < tables.length; i++) {
503
513
  const tableName = tables[i];
504
514
  const tableExists = this._tableExists(tableName);
505
- if (!tableExists) {
515
+ const tempTableName = `${tableName}_${env.DB_VERSION}_new`;
516
+ if (!tableExists && needToMigrate && this._tableExists(tempTableName)) {
517
+ // An earlier run of this migration was killed between dropping the table and renaming its migrated copy,
518
+ // when the two were separate commits. The copy is complete (the drop only ran after it), so it becomes the
519
+ // table; creating an empty one here would lose every row
520
+ log(`Table ${tableName} is missing but its migrated copy ${tempTableName} exists. Will restore the table from it`);
521
+ this._db.exec(`ALTER TABLE ${tempTableName} RENAME TO ${tableName}`);
522
+ }
523
+ else if (!tableExists) {
506
524
  log(`Table ${tableName} does not exist. Will create schema`);
507
525
  createTableFunctions[i](tableName);
508
526
  }
509
527
  else if (tableExists && needToMigrate) {
510
528
  log(`Migrating table ${tableName} to new schema`);
511
- const tempTableName = `${tableName}_${env.DB_VERSION}_new`;
512
529
  this._db.exec(`DROP TABLE IF EXISTS ${tempTableName}`);
513
530
  createTableFunctions[i](tempTableName);
514
531
  await this._copyTable(tableName, tempTableName, currentDbVersion);
515
- this._db.exec(`DROP TABLE ${tableName}`);
516
- this._db.exec(`ALTER TABLE ${tempTableName} RENAME TO ${tableName}`);
532
+ // One commit, so a crash leaves either the old table or its migrated copy under the table's name, never
533
+ // neither (user_version is only bumped after every table, so the next start migrates again)
534
+ this._db.transaction(() => {
535
+ this._db.exec(`DROP TABLE ${tableName}`);
536
+ this._db.exec(`ALTER TABLE ${tempTableName} RENAME TO ${tableName}`);
537
+ })();
517
538
  }
518
539
  }
519
540
  this._createCommentsIndexes(); // idempotent; the migration loop above recreates the tables without them
@@ -568,8 +589,21 @@ export class DbHandler {
568
589
  this._preparedStatements.clear();
569
590
  if (needToMigrate)
570
591
  log(`Created/migrated the tables to the latest (${newDbVersion}) version and saved to path`, this._dbConfig.filename);
571
- if (backupDbPath)
572
- await fs.promises.rm(backupDbPath);
592
+ if (backupDbPath) {
593
+ // The migration is done, so a backup that can't be removed must not fail it: on Windows the file can be
594
+ // busy for a moment, and a leftover backup is harmless while a community that won't start is not
595
+ try {
596
+ await removeFileRetryingWhileBusy(backupDbPath, { log });
597
+ }
598
+ catch (e) {
599
+ log.error(`Failed to remove the pre-migration backup ${backupDbPath}. It is no longer needed and can be deleted`, e);
600
+ }
601
+ }
602
+ }
603
+ // False for a DB a migration was killed in: it drops commentUpdates first and rebuilds every table after that, so until
604
+ // the next start() finishes the migration either table can be missing
605
+ hasCommentsAndCommentUpdatesTables() {
606
+ return this._tableExists(TABLES.COMMENTS) && this._tableExists(TABLES.COMMENT_UPDATES);
573
607
  }
574
608
  _tableExists(tableName) {
575
609
  const stmt = this._db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = ?");
@@ -2963,6 +2997,8 @@ export class DbHandler {
2963
2997
  const sourceDb = new Database(oldPathString, { fileMustExist: true });
2964
2998
  await sourceDb.backup(newPathString); // backup is synchronous in better-sqlite3 v8+
2965
2999
  sourceDb.close();
3000
+ // The live DB is at the new path now. Before the old file is removed, so a failure here leaves it intact
3001
+ await forgetCommunityThatFailedToBeDeleted({ communityAddress: newDbName, pkc: this._community._pkc });
2966
3002
  if (os.type() === "Windows_NT")
2967
3003
  await deleteOldCommunityInWindows(oldPathString, this._community._pkc);
2968
3004
  else
@@ -2976,15 +3012,30 @@ export class DbHandler {
2976
3012
  this._dbConfig = { ...this._dbConfig, filename: newPathString };
2977
3013
  log(`Changed db path from (${oldPathString}) to (${newPathString})`);
2978
3014
  }
2979
- async lockCommunityStart(communityAddress = this._community.address) {
3015
+ // The lock library keeps the lock fresh from a timer. When this event loop is blocked past the lock's 10s stale
3016
+ // threshold (a VACUUM or migration of a large DB, a suspended process), another process on the same dataPath sees it
3017
+ // as stale and takes it over; the library then reports it compromised and onCompromised is called. The library also
3018
+ // reports a lock directory that disappeared (ENOENT), even one whose taker released it again. Either way this process
3019
+ // no longer holds the lock from that point on, so it must stop running the community.
3020
+ async lockCommunityStart({ onCompromised }) {
2980
3021
  const log = Logger("pkc-js:local-community:db-handler:lock:start");
3022
+ const communityAddress = this._community.address;
2981
3023
  const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
2982
3024
  const communityDbPath = path.join(this._community._pkc.dataPath, "communities", communityAddress);
3025
+ const startLock = {};
2983
3026
  try {
2984
3027
  await lockfile.lock(communityDbPath, {
2985
3028
  lockfilePath,
2986
- onCompromised: () => { } // Temporary bandaid for the moment. Should be deleted later
3029
+ onCompromised: (error) => {
3030
+ // The library can still report a lock after it was released, which is not a lock this process lost
3031
+ if (this._heldStartLock !== startLock)
3032
+ return;
3033
+ this._heldStartLock = undefined;
3034
+ log.error(`Lost the start lock of community (${communityAddress}), taken over or removed`, error);
3035
+ onCompromised(error);
3036
+ }
2987
3037
  });
3038
+ this._heldStartLock = startLock;
2988
3039
  log(`Locked the start of community (${communityAddress}) successfully`);
2989
3040
  }
2990
3041
  catch (e) {
@@ -2999,6 +3050,7 @@ export class DbHandler {
2999
3050
  async unlockCommunityStart(communityAddress = this._community.address) {
3000
3051
  const log = Logger("pkc-js:local-community:db-handler:unlock:start");
3001
3052
  log.trace(`Attempting to unlock the start of community (${communityAddress})`);
3053
+ this._heldStartLock = undefined;
3002
3054
  const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3003
3055
  const communityDbPath = path.join(this._community._pkc.dataPath, "communities", communityAddress);
3004
3056
  if (!fs.existsSync(lockfilePath) || !fs.existsSync(communityDbPath))