@pkcprotocol/pkc-js 0.0.153 → 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 (96) hide show
  1. package/README.md +21 -1
  2. package/dist/browser/errors.d.ts +4 -2
  3. package/dist/browser/errors.js +4 -2
  4. package/dist/browser/errors.js.map +1 -1
  5. package/dist/browser/generated-version.d.ts +1 -1
  6. package/dist/browser/generated-version.js +1 -1
  7. package/dist/browser/pkc-error.d.ts +1 -1
  8. package/dist/browser/publications/comment/comment.d.ts +1 -0
  9. package/dist/browser/publications/comment/comment.js +57 -12
  10. package/dist/browser/publications/comment/comment.js.map +1 -1
  11. package/dist/browser/publications/publication.d.ts +8 -1
  12. package/dist/browser/publications/publication.js +393 -146
  13. package/dist/browser/publications/publication.js.map +1 -1
  14. package/dist/browser/publications/types.d.ts +1 -0
  15. package/dist/browser/rpc/src/index.js +12 -5
  16. package/dist/browser/rpc/src/index.js.map +1 -1
  17. package/dist/browser/runtime/node/blockstore.d.ts +2 -2
  18. package/dist/browser/runtime/node/blockstore.js +2 -2
  19. package/dist/browser/runtime/node/community/db-handler.d.ts +5 -7
  20. package/dist/browser/runtime/node/community/db-handler.js +79 -82
  21. package/dist/browser/runtime/node/community/db-handler.js.map +1 -1
  22. package/dist/browser/runtime/node/community/local-community/cleanup.js +62 -12
  23. package/dist/browser/runtime/node/community/local-community/cleanup.js.map +1 -1
  24. package/dist/browser/runtime/node/community/local-community/db-state.d.ts +1 -1
  25. package/dist/browser/runtime/node/community/local-community/db-state.js +31 -39
  26. package/dist/browser/runtime/node/community/local-community/db-state.js.map +1 -1
  27. package/dist/browser/runtime/node/community/local-community/editing.js +71 -22
  28. package/dist/browser/runtime/node/community/local-community/editing.js.map +1 -1
  29. package/dist/browser/runtime/node/community/local-community/ipns-publishing.js +1 -1
  30. package/dist/browser/runtime/node/community/local-community/ipns-publishing.js.map +1 -1
  31. package/dist/browser/runtime/node/community/local-community/lifecycle.d.ts +0 -2
  32. package/dist/browser/runtime/node/community/local-community/lifecycle.js +50 -72
  33. package/dist/browser/runtime/node/community/local-community/lifecycle.js.map +1 -1
  34. package/dist/browser/runtime/node/community/local-community.d.ts +4 -2
  35. package/dist/browser/runtime/node/community/local-community.js +11 -7
  36. package/dist/browser/runtime/node/community/local-community.js.map +1 -1
  37. package/dist/browser/runtime/node/community/start-lock.d.ts +14 -5
  38. package/dist/browser/runtime/node/community/start-lock.js +153 -10
  39. package/dist/browser/runtime/node/community/start-lock.js.map +1 -1
  40. package/dist/browser/runtime/node/util.js +18 -10
  41. package/dist/browser/runtime/node/util.js.map +1 -1
  42. package/dist/bundled/bundle-manifest.json +35 -44
  43. package/dist/bundled/challenges.js +1 -1
  44. package/dist/bundled/chunks/{helia-for-pkc-COJ3xMF9.js → helia-for-pkc-CG9YohPs.js} +4 -4
  45. package/dist/bundled/chunks/{local-community-BTx2HxIm.js → local-community-CaQmhX8D.js} +1 -1
  46. package/dist/bundled/chunks/{local-community-CflGu_ET.js → local-community-V8_VyEhO.js} +217 -162
  47. package/dist/bundled/chunks/{node-B0b6lAIX.js → node-c4vpD2VN.js} +340 -172
  48. package/dist/bundled/chunks/{page-sort-scoring-DAMnUmDY.js → page-sort-scoring-d1frahfd.js} +1 -1
  49. package/dist/bundled/chunks/{rpc-local-community-Cy03QajY.js → rpc-local-community-DDAibWpE.js} +144 -1431
  50. package/dist/bundled/chunks/{util-C4y8KHmp.js → util-B_dKP7Te.js} +1 -1
  51. package/dist/bundled/chunks/{util-D7AtfLYH.js → util-BwEIge-b.js} +5 -3
  52. package/dist/bundled/chunks/{validate-package-factories-EH9ydbPR.js → validate-package-factories-DfpNf4oq.js} +2 -2
  53. package/dist/bundled/index.js +1 -1
  54. package/dist/bundled/page-sorts.js +1 -1
  55. package/dist/bundled/rpc/src/index.js +14 -9
  56. package/dist/node/errors.d.ts +4 -2
  57. package/dist/node/errors.js +4 -2
  58. package/dist/node/errors.js.map +1 -1
  59. package/dist/node/generated-version.d.ts +1 -1
  60. package/dist/node/generated-version.js +1 -1
  61. package/dist/node/pkc-error.d.ts +1 -1
  62. package/dist/node/publications/comment/comment.d.ts +1 -0
  63. package/dist/node/publications/comment/comment.js +57 -12
  64. package/dist/node/publications/comment/comment.js.map +1 -1
  65. package/dist/node/publications/publication.d.ts +8 -1
  66. package/dist/node/publications/publication.js +393 -146
  67. package/dist/node/publications/publication.js.map +1 -1
  68. package/dist/node/publications/types.d.ts +1 -0
  69. package/dist/node/rpc/src/index.js +12 -5
  70. package/dist/node/rpc/src/index.js.map +1 -1
  71. package/dist/node/runtime/node/blockstore.d.ts +2 -2
  72. package/dist/node/runtime/node/blockstore.js +2 -2
  73. package/dist/node/runtime/node/community/db-handler.d.ts +5 -7
  74. package/dist/node/runtime/node/community/db-handler.js +79 -82
  75. package/dist/node/runtime/node/community/db-handler.js.map +1 -1
  76. package/dist/node/runtime/node/community/local-community/cleanup.js +62 -12
  77. package/dist/node/runtime/node/community/local-community/cleanup.js.map +1 -1
  78. package/dist/node/runtime/node/community/local-community/db-state.d.ts +1 -1
  79. package/dist/node/runtime/node/community/local-community/db-state.js +31 -39
  80. package/dist/node/runtime/node/community/local-community/db-state.js.map +1 -1
  81. package/dist/node/runtime/node/community/local-community/editing.js +71 -22
  82. package/dist/node/runtime/node/community/local-community/editing.js.map +1 -1
  83. package/dist/node/runtime/node/community/local-community/ipns-publishing.js +1 -1
  84. package/dist/node/runtime/node/community/local-community/ipns-publishing.js.map +1 -1
  85. package/dist/node/runtime/node/community/local-community/lifecycle.d.ts +0 -2
  86. package/dist/node/runtime/node/community/local-community/lifecycle.js +50 -72
  87. package/dist/node/runtime/node/community/local-community/lifecycle.js.map +1 -1
  88. package/dist/node/runtime/node/community/local-community.d.ts +4 -2
  89. package/dist/node/runtime/node/community/local-community.js +11 -7
  90. package/dist/node/runtime/node/community/local-community.js.map +1 -1
  91. package/dist/node/runtime/node/community/start-lock.d.ts +14 -5
  92. package/dist/node/runtime/node/community/start-lock.js +153 -10
  93. package/dist/node/runtime/node/community/start-lock.js.map +1 -1
  94. package/dist/node/runtime/node/util.js +18 -10
  95. package/dist/node/runtime/node/util.js.map +1 -1
  96. package/package.json +1 -2
@@ -9,8 +9,7 @@ import { deleteOldCommunityInWindows, deriveCommentIpfsFromCommentTableRow, forg
9
9
  import env from "../../../version.js";
10
10
  import Database from "better-sqlite3";
11
11
  import { sha256 } from "js-sha256";
12
- import lockfile from "@pkcprotocol/proper-lock-file";
13
- import { isCommunityStartLocked } from "./start-lock.js";
12
+ import { getStartLockPath, isCommunityStartLocked, releaseStartLock, takeStartLock } from "./start-lock.js";
14
13
  import { isDefaultChallengeStructure } from "./local-community/defaults.js";
15
14
  import { addAllCidsUnderPurgedCommentToBeRemoved } from "./local-community/cleanup.js";
16
15
  import { updateDbInternalState } from "./local-community/db-state.js";
@@ -57,8 +56,8 @@ export class DbHandler {
57
56
  // Advanced by every write to the publication tables (comments, votes, edits, moderations, aliases, purges). The
58
57
  // update cycle's author memo (CommunityAuthorMemo) is only reused while it stays the same.
59
58
  this._publicationWriteGeneration = 0;
60
- // Identifies the start lock this handler holds, from lockCommunityStart until unlockCommunityStart or its loss
61
- this._heldStartLock = undefined;
59
+ // The address whose start lock this handler's connection holds, from lockCommunityStart until unlockCommunityStart
60
+ this._startLockAddress = undefined;
62
61
  this._community = community;
63
62
  this._transactionDepth = 0;
64
63
  this._createdTables = false;
@@ -143,7 +142,10 @@ export class DbHandler {
143
142
  catch (e) {
144
143
  await this.initDbIfNeeded();
145
144
  log.error(`Community (${this._community.address}) failed to create/migrate tables. Current db version (${this.getDbVersion()}), latest db version (${env.DB_VERSION}). Error`, e);
146
- await this.destoryConnection();
145
+ // A start() that fails here holds the start lock on this connection, and its stop() releases the lock and
146
+ // closes the connection
147
+ if (this._startLockAddress === undefined)
148
+ this.destoryConnection();
147
149
  throw e;
148
150
  }
149
151
  hideClassPrivateProps(this);
@@ -172,6 +174,18 @@ export class DbHandler {
172
174
  }
173
175
  destoryConnection() {
174
176
  const log = Logger("pkc-js:local-community:dbHandler:destroyConnection");
177
+ // The start lock lives on this connection (see start-lock.ts), so closing it releases the lock: another process
178
+ // could then start the community next to this one. stop() releases the lock before it gets here, so anything
179
+ // else that does is a caller that took a starting or started community for a stopped one. The connection stays
180
+ // open and the lock held. Under vitest it throws, so a test that reaches such a path fails.
181
+ if (this.holdsStartLock()) {
182
+ const error = new Error(`Refused to close the DB connection of community (${this._startLockAddress}) while it holds the community's start lock (issue #561)`);
183
+ log.error(error);
184
+ if (process.env["VITEST"])
185
+ throw error;
186
+ return;
187
+ }
188
+ this._startLockAddress = undefined;
175
189
  this._preparedStatements.clear(); // statements belong to the connection
176
190
  if (this._db && this._db.open) {
177
191
  try {
@@ -482,16 +496,13 @@ export class DbHandler {
482
496
  const dbExistsAlready = fs.existsSync(dbPath);
483
497
  if (needToMigrate) {
484
498
  if (dbExistsAlready && currentDbVersion > 0) {
485
- this.destoryConnection();
486
499
  backupDbPath = path.join(path.dirname(dbPath), ".backup_before_migration", `${path.basename(dbPath)}.${currentDbVersion}.${timestamp()}`);
487
500
  log(`Copying db ${path.basename(dbPath)} to ${backupDbPath} before migration`);
488
501
  if (!fs.existsSync(path.dirname(backupDbPath)))
489
502
  await fs.promises.mkdir(path.dirname(backupDbPath), { recursive: true });
490
- const sourceDb = new Database(dbPath, { fileMustExist: true });
491
- await sourceDb.backup(backupDbPath); // Use better-sqlite3's native backup method
492
- sourceDb.close();
493
- this._db = new Database(dbPath);
494
- this._db.pragma("journal_mode = WAL");
503
+ // Through the open connection, which is not closed: start() migrates while holding the start lock, and
504
+ // the lock lives on this connection (see start-lock.ts)
505
+ await this._db.backup(backupDbPath);
495
506
  }
496
507
  this._db.exec("PRAGMA foreign_keys = OFF");
497
508
  const tablesToDrop = ["challengeRequests", "challenges", "challengeAnswers", "challengeVerifications", "signers"];
@@ -3008,6 +3019,10 @@ export class DbHandler {
3008
3019
  await deleteOldCommunityInWindows(oldPathString, this._community._pkc);
3009
3020
  else
3010
3021
  await fs.promises.rm(oldPathString, { force: true });
3022
+ // No community lives at the old address any more, so its start lock sidecar goes too. Not while the old
3023
+ // file is still there, which it is on Windows when it could not be removed yet (see start-lock.ts)
3024
+ if (!fs.existsSync(oldPathString))
3025
+ await fs.promises.rm(getStartLockPath({ dataPath, communityAddress: oldDbName }), { force: true });
3011
3026
  }
3012
3027
  }
3013
3028
  catch (error) {
@@ -3017,93 +3032,75 @@ export class DbHandler {
3017
3032
  this._dbConfig = { ...this._dbConfig, filename: newPathString };
3018
3033
  log(`Changed db path from (${oldPathString}) to (${newPathString})`);
3019
3034
  }
3020
- // The lock library keeps the lock fresh from a timer. When this event loop is blocked past the lock's 10s stale
3021
- // threshold (a VACUUM or migration of a large DB, a suspended process), another process on the same dataPath sees it
3022
- // as stale and takes it over; the library then reports it compromised and onCompromised is called. The library also
3023
- // reports a lock directory that disappeared (ENOENT), even one whose taker released it again. Either way this process
3024
- // no longer holds the lock from that point on, so it must stop running the community.
3025
- async lockCommunityStart({ onCompromised }) {
3035
+ // Takes the community's start lock on this handler's connection (see start-lock.ts), which holds it until
3036
+ // unlockCommunityStart(). Closing the connection would release it too, which destoryConnection() refuses to do
3037
+ // silently. A process that dies releases it without any of this running.
3038
+ async lockCommunityStart() {
3026
3039
  const log = Logger("pkc-js:local-community:db-handler:lock:start");
3027
3040
  const communityAddress = this._community.address;
3028
- const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3029
- const communityDbPath = path.join(this._community._pkc.dataPath, "communities", communityAddress);
3030
- const startLock = {};
3031
- try {
3032
- await lockfile.lock(communityDbPath, {
3033
- lockfilePath,
3034
- onCompromised: (error) => {
3035
- // The library can still report a lock after it was released, which is not a lock this process lost
3036
- if (this._heldStartLock !== startLock)
3037
- return;
3038
- this._heldStartLock = undefined;
3039
- log.error(`Lost the start lock of community (${communityAddress}), taken over or removed`, error);
3040
- onCompromised(error);
3041
- }
3042
- });
3043
- this._heldStartLock = startLock;
3044
- log(`Locked the start of community (${communityAddress}) successfully`);
3045
- }
3046
- catch (e) {
3047
- if (e instanceof Error && e.message === "Lock file is already being held")
3048
- throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { communityAddress: communityAddress, error: e });
3049
- else {
3050
- log(`Error while trying to lock start of community (${communityAddress}): ${e}`);
3051
- throw e;
3052
- }
3053
- }
3054
- }
3055
- async unlockCommunityStart(communityAddress = this._community.address) {
3041
+ const dataPath = this._community._pkc.dataPath;
3042
+ await this.initDbIfNeeded();
3043
+ // The lock directory of the mtime lock this one replaced, left by a process that was killed before an upgrade.
3044
+ // Removed before the lock is taken: nothing may fail or wait between taking the lock and returning, since a
3045
+ // start() that fails here has not entered the started state, whose teardown is what releases the lock
3046
+ await fs.promises.rm(path.join(dataPath, "communities", `${communityAddress}.start.lock`), { recursive: true, force: true });
3047
+ if (!takeStartLock({ db: this._db, dataPath, communityAddress }))
3048
+ throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { communityAddress });
3049
+ // The connection was opened some awaits ago. Another process that deleted or renamed the community since has
3050
+ // moved its DB away and removed its sidecar, and the lock just taken is on a new sidecar, for a community with
3051
+ // no DB at its path: it would run, publish and write to a file nothing reads again. Given back at once (no
3052
+ // await since the lock was taken), and the sidecar with it, as nothing is left for it to guard.
3053
+ if (!fs.existsSync(path.join(dataPath, "communities", communityAddress))) {
3054
+ releaseStartLock({ db: this._db, dataPath, communityAddress });
3055
+ fs.rmSync(getStartLockPath({ dataPath, communityAddress }), { force: true });
3056
+ throw new PKCError("CAN_NOT_LOAD_LOCAL_COMMUNITY_IF_DB_DOES_NOT_EXIST", { communityAddress, dataPath });
3057
+ }
3058
+ this._startLockAddress = communityAddress;
3059
+ log(`Locked the start of community (${communityAddress}) successfully`);
3060
+ }
3061
+ // Whether this handler's connection holds the community's start lock, i.e. this instance is starting or started
3062
+ holdsStartLock() {
3063
+ return this._startLockAddress !== undefined && this._db?.open === true;
3064
+ }
3065
+ async unlockCommunityStart() {
3056
3066
  const log = Logger("pkc-js:local-community:db-handler:unlock:start");
3057
- log.trace(`Attempting to unlock the start of community (${communityAddress})`);
3058
- this._heldStartLock = undefined;
3059
- const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3060
- const communityDbPath = path.join(this._community._pkc.dataPath, "communities", communityAddress);
3061
- if (!fs.existsSync(lockfilePath) || !fs.existsSync(communityDbPath))
3067
+ const communityAddress = this._startLockAddress;
3068
+ if (communityAddress === undefined)
3062
3069
  return;
3063
- try {
3064
- await lockfile.unlock(communityDbPath, { lockfilePath });
3065
- log(`Unlocked start of community (${communityAddress})`);
3066
- }
3067
- catch (e) {
3068
- log(`Error while trying to unlock start of community (${communityAddress}): ${e}`);
3069
- throw e;
3070
- }
3070
+ this._startLockAddress = undefined;
3071
+ if (!this._db?.open)
3072
+ return; // the lock went with the connection
3073
+ releaseStartLock({ db: this._db, dataPath: this._community._pkc.dataPath, communityAddress });
3074
+ log(`Unlocked start of community (${communityAddress})`);
3071
3075
  }
3072
3076
  async isCommunityStartLocked(communityAddress = this._community.address) {
3073
3077
  return isCommunityStartLocked({ dataPath: this._community._pkc.dataPath, communityAddress });
3074
3078
  }
3075
- // Community state lock
3076
- async lockCommunityState() {
3077
- const log = Logger("pkc-js:local-community:db-handler:lock:lockCommunityState");
3078
- const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
3079
- const communityDbPath = path.join(this._community._pkc.dataPath, "communities", this._community.address);
3079
+ // Runs `write` as one write transaction on the community DB: SQLite lets one connection write at a time, across
3080
+ // processes too, and the lock is the kernel's, so a killed writer leaves nothing behind. `write` must be synchronous
3081
+ // (issue #417). A transaction that is already open on this connection is joined. Used for a read-modify-write of
3082
+ // the community's internal state, which a lock file guarded before (issue #561).
3083
+ runInWriteTransaction(write) {
3084
+ if (this._db.inTransaction)
3085
+ return write();
3080
3086
  try {
3081
- await lockfile.lock(communityDbPath, {
3082
- lockfilePath,
3083
- retries: 5,
3084
- onCompromised: () => { }
3085
- });
3087
+ this._db.exec("BEGIN IMMEDIATE");
3086
3088
  }
3087
3089
  catch (e) {
3088
- log.error(`Error when attempting to lock community state`, this._community.address, e);
3089
- if (e instanceof Error && e.message === "Lock file is already being held")
3090
+ // another connection kept writing for longer than this connection's busy timeout
3091
+ if (typeof e.code === "string" && e.code.startsWith("SQLITE_BUSY"))
3090
3092
  throw new PKCError("ERR_COMMUNITY_STATE_LOCKED", { communityAddress: this._community.address, error: e });
3091
- // Not sure, do we need to throw error here
3093
+ throw e;
3092
3094
  }
3093
- }
3094
- async unlockCommunityState() {
3095
- const log = Logger("pkc-js:local-community:db-handler:lock:unlockCommunityState");
3096
- const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
3097
- const communityDbPath = path.join(this._community._pkc.dataPath, "communities", this._community.address);
3098
- if (!fs.existsSync(lockfilePath))
3099
- return;
3100
3095
  try {
3101
- await lockfile.unlock(communityDbPath, { lockfilePath });
3096
+ const result = write();
3097
+ this._db.exec("COMMIT");
3098
+ return result;
3102
3099
  }
3103
3100
  catch (e) {
3104
- log.error(`Error when attempting to unlock community state`, this._community.address, e);
3105
- if (e instanceof Error && "code" in e && e.code !== "ENOTACQUIRED")
3106
- throw e;
3101
+ if (this._db.inTransaction)
3102
+ this._db.exec("ROLLBACK");
3103
+ throw e;
3107
3104
  }
3108
3105
  }
3109
3106
  communityDbExists() {