@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
@@ -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 {
@@ -345,7 +359,8 @@ export class DbHandler {
345
359
  lastReplyTimestamp INTEGER NULLABLE,
346
360
  postUpdatesBucket INTEGER NULLABLE,
347
361
  publishedToPostUpdatesMFS INTEGER NOT NULL, -- BOOLEAN (0/1)
348
- insertedAt INTEGER NOT NULL
362
+ insertedAt INTEGER NOT NULL,
363
+ extraProps TEXT NULLABLE -- JSON: unknown keys of the signed record (issue #572); a snapshot, this table is rebuilt on every DB_VERSION bump
349
364
  )
350
365
  `);
351
366
  }
@@ -481,16 +496,13 @@ export class DbHandler {
481
496
  const dbExistsAlready = fs.existsSync(dbPath);
482
497
  if (needToMigrate) {
483
498
  if (dbExistsAlready && currentDbVersion > 0) {
484
- this.destoryConnection();
485
499
  backupDbPath = path.join(path.dirname(dbPath), ".backup_before_migration", `${path.basename(dbPath)}.${currentDbVersion}.${timestamp()}`);
486
500
  log(`Copying db ${path.basename(dbPath)} to ${backupDbPath} before migration`);
487
501
  if (!fs.existsSync(path.dirname(backupDbPath)))
488
502
  await fs.promises.mkdir(path.dirname(backupDbPath), { recursive: true });
489
- const sourceDb = new Database(dbPath, { fileMustExist: true });
490
- await sourceDb.backup(backupDbPath); // Use better-sqlite3's native backup method
491
- sourceDb.close();
492
- this._db = new Database(dbPath);
493
- 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);
494
506
  }
495
507
  this._db.exec("PRAGMA foreign_keys = OFF");
496
508
  const tablesToDrop = ["challengeRequests", "challenges", "challengeAnswers", "challengeVerifications", "signers"];
@@ -1055,8 +1067,8 @@ export class DbHandler {
1055
1067
  const columnNames = this._getColumnNames(TABLES.COMMENT_UPDATES);
1056
1068
  const stmt = this._prepareCached(`
1057
1069
  INSERT INTO ${TABLES.COMMENT_UPDATES}
1058
- (cid, edit, upvoteCount, downvoteCount, replyCount, childCount, number, postNumber, flairs, spoiler, nsfw, pinned, locked, archived, removed, approved, reason, updatedAt, protocolVersion, signature, author, replies, lastChildCid, lastReplyTimestamp, postUpdatesBucket, publishedToPostUpdatesMFS, insertedAt)
1059
- VALUES (@cid, @edit, @upvoteCount, @downvoteCount, @replyCount, @childCount, @number, @postNumber, @flairs, @spoiler, @nsfw, @pinned, @locked, @archived, @removed, @approved, @reason, @updatedAt, @protocolVersion, @signature, @author, @replies, @lastChildCid, @lastReplyTimestamp, @postUpdatesBucket, @publishedToPostUpdatesMFS, @insertedAt)
1070
+ (cid, edit, upvoteCount, downvoteCount, replyCount, childCount, number, postNumber, flairs, spoiler, nsfw, pinned, locked, archived, removed, approved, reason, updatedAt, protocolVersion, signature, author, replies, lastChildCid, lastReplyTimestamp, postUpdatesBucket, publishedToPostUpdatesMFS, insertedAt, extraProps)
1071
+ VALUES (@cid, @edit, @upvoteCount, @downvoteCount, @replyCount, @childCount, @number, @postNumber, @flairs, @spoiler, @nsfw, @pinned, @locked, @archived, @removed, @approved, @reason, @updatedAt, @protocolVersion, @signature, @author, @replies, @lastChildCid, @lastReplyTimestamp, @postUpdatesBucket, @publishedToPostUpdatesMFS, @insertedAt, @extraProps)
1060
1072
  ON CONFLICT(cid) DO UPDATE SET
1061
1073
  edit = excluded.edit, upvoteCount = excluded.upvoteCount, downvoteCount = excluded.downvoteCount, replyCount = excluded.replyCount, childCount = excluded.childCount,
1062
1074
  number = COALESCE(excluded.number, ${TABLES.COMMENT_UPDATES}.number),
@@ -1066,7 +1078,8 @@ export class DbHandler {
1066
1078
  signature = excluded.signature, author = excluded.author, replies = excluded.replies, lastChildCid = excluded.lastChildCid,
1067
1079
  lastReplyTimestamp = excluded.lastReplyTimestamp, postUpdatesBucket = excluded.postUpdatesBucket,
1068
1080
  publishedToPostUpdatesMFS = excluded.publishedToPostUpdatesMFS,
1069
- insertedAt = excluded.insertedAt
1081
+ insertedAt = excluded.insertedAt,
1082
+ extraProps = excluded.extraProps
1070
1083
  `);
1071
1084
  const defaults = mapToObj(columnNames, (column) => [column, null]);
1072
1085
  const upsertMany = this._db.transaction((items) => {
@@ -1202,7 +1215,10 @@ export class DbHandler {
1202
1215
  // The column set of a page entry: every CommentIpfs column plus extraProps, and every CommentUpdate column
1203
1216
  // unless the caller excludes some (a flat page drops `replies`). Compiled mappers are cached per column set.
1204
1217
  _pageEntryMapper(commentUpdateFieldsToExclude, existingOnly = false) {
1205
- const commentUpdateCols = keys(commentUpdateFieldsToExclude ? omit(CommentUpdateSchema.shape, commentUpdateFieldsToExclude) : CommentUpdateSchema.shape);
1218
+ const commentUpdateCols = [
1219
+ ...keys(commentUpdateFieldsToExclude ? omit(CommentUpdateSchema.shape, commentUpdateFieldsToExclude) : CommentUpdateSchema.shape),
1220
+ "extraProps" // the signed record's unknown keys, spread back by the mapper (comment-update-row.ts)
1221
+ ];
1206
1222
  const commentIpfsCols = [...keys(CommentIpfsSchema.shape), "extraProps"];
1207
1223
  return this._positionalMapperFor({
1208
1224
  commentIpfsCols: existingOnly ? this._existingColumns(TABLES.COMMENTS, commentIpfsCols) : commentIpfsCols,
@@ -3003,6 +3019,10 @@ export class DbHandler {
3003
3019
  await deleteOldCommunityInWindows(oldPathString, this._community._pkc);
3004
3020
  else
3005
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 });
3006
3026
  }
3007
3027
  }
3008
3028
  catch (error) {
@@ -3012,93 +3032,75 @@ export class DbHandler {
3012
3032
  this._dbConfig = { ...this._dbConfig, filename: newPathString };
3013
3033
  log(`Changed db path from (${oldPathString}) to (${newPathString})`);
3014
3034
  }
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 }) {
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() {
3021
3039
  const log = Logger("pkc-js:local-community:db-handler:lock:start");
3022
3040
  const communityAddress = this._community.address;
3023
- const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3024
- const communityDbPath = path.join(this._community._pkc.dataPath, "communities", communityAddress);
3025
- const startLock = {};
3026
- try {
3027
- await lockfile.lock(communityDbPath, {
3028
- lockfilePath,
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
- }
3037
- });
3038
- this._heldStartLock = startLock;
3039
- log(`Locked the start of community (${communityAddress}) successfully`);
3040
- }
3041
- catch (e) {
3042
- if (e instanceof Error && e.message === "Lock file is already being held")
3043
- throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { communityAddress: communityAddress, error: e });
3044
- else {
3045
- log(`Error while trying to lock start of community (${communityAddress}): ${e}`);
3046
- throw e;
3047
- }
3048
- }
3049
- }
3050
- 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() {
3051
3066
  const log = Logger("pkc-js:local-community:db-handler:unlock:start");
3052
- log.trace(`Attempting to unlock the start of community (${communityAddress})`);
3053
- this._heldStartLock = undefined;
3054
- const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3055
- const communityDbPath = path.join(this._community._pkc.dataPath, "communities", communityAddress);
3056
- if (!fs.existsSync(lockfilePath) || !fs.existsSync(communityDbPath))
3067
+ const communityAddress = this._startLockAddress;
3068
+ if (communityAddress === undefined)
3057
3069
  return;
3058
- try {
3059
- await lockfile.unlock(communityDbPath, { lockfilePath });
3060
- log(`Unlocked start of community (${communityAddress})`);
3061
- }
3062
- catch (e) {
3063
- log(`Error while trying to unlock start of community (${communityAddress}): ${e}`);
3064
- throw e;
3065
- }
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})`);
3066
3075
  }
3067
3076
  async isCommunityStartLocked(communityAddress = this._community.address) {
3068
3077
  return isCommunityStartLocked({ dataPath: this._community._pkc.dataPath, communityAddress });
3069
3078
  }
3070
- // Community state lock
3071
- async lockCommunityState() {
3072
- const log = Logger("pkc-js:local-community:db-handler:lock:lockCommunityState");
3073
- const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
3074
- 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();
3075
3086
  try {
3076
- await lockfile.lock(communityDbPath, {
3077
- lockfilePath,
3078
- retries: 5,
3079
- onCompromised: () => { }
3080
- });
3087
+ this._db.exec("BEGIN IMMEDIATE");
3081
3088
  }
3082
3089
  catch (e) {
3083
- log.error(`Error when attempting to lock community state`, this._community.address, e);
3084
- 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"))
3085
3092
  throw new PKCError("ERR_COMMUNITY_STATE_LOCKED", { communityAddress: this._community.address, error: e });
3086
- // Not sure, do we need to throw error here
3093
+ throw e;
3087
3094
  }
3088
- }
3089
- async unlockCommunityState() {
3090
- const log = Logger("pkc-js:local-community:db-handler:lock:unlockCommunityState");
3091
- const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
3092
- const communityDbPath = path.join(this._community._pkc.dataPath, "communities", this._community.address);
3093
- if (!fs.existsSync(lockfilePath))
3094
- return;
3095
3095
  try {
3096
- await lockfile.unlock(communityDbPath, { lockfilePath });
3096
+ const result = write();
3097
+ this._db.exec("COMMIT");
3098
+ return result;
3097
3099
  }
3098
3100
  catch (e) {
3099
- log.error(`Error when attempting to unlock community state`, this._community.address, e);
3100
- if (e instanceof Error && "code" in e && e.code !== "ENOTACQUIRED")
3101
- throw e;
3101
+ if (this._db.inTransaction)
3102
+ this._db.exec("ROLLBACK");
3103
+ throw e;
3102
3104
  }
3103
3105
  }
3104
3106
  communityDbExists() {