@pkcprotocol/pkc-js 0.0.154 → 0.0.155

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 (172) hide show
  1. package/README.md +2 -2
  2. package/dist/browser/clients/rpc-client/schema.js +2 -2
  3. package/dist/browser/clients/rpc-client/schema.js.map +1 -1
  4. package/dist/browser/community/remote-community.js +8 -2
  5. package/dist/browser/community/remote-community.js.map +1 -1
  6. package/dist/browser/community/schema.js +4 -0
  7. package/dist/browser/community/schema.js.map +1 -1
  8. package/dist/browser/community-list/community-list.js +3 -2
  9. package/dist/browser/community-list/community-list.js.map +1 -1
  10. package/dist/browser/errors.d.ts +14 -0
  11. package/dist/browser/errors.js +14 -0
  12. package/dist/browser/errors.js.map +1 -1
  13. package/dist/browser/generated-version.d.ts +1 -1
  14. package/dist/browser/generated-version.js +1 -1
  15. package/dist/browser/pkc/pkc.js +13 -4
  16. package/dist/browser/pkc/pkc.js.map +1 -1
  17. package/dist/browser/pkc-error.d.ts +1 -1
  18. package/dist/browser/publications/comment/comment.js +25 -9
  19. package/dist/browser/publications/comment/comment.js.map +1 -1
  20. package/dist/browser/publications/comment/crosspost-runtime.js +10 -2
  21. package/dist/browser/publications/comment/crosspost-runtime.js.map +1 -1
  22. package/dist/browser/publications/comment/schema.d.ts +1 -1
  23. package/dist/browser/publications/comment/schema.js +30 -1
  24. package/dist/browser/publications/comment/schema.js.map +1 -1
  25. package/dist/browser/publications/publication.d.ts +4 -0
  26. package/dist/browser/publications/publication.js +135 -38
  27. package/dist/browser/publications/publication.js.map +1 -1
  28. package/dist/browser/rpc/src/index.js +3 -3
  29. package/dist/browser/rpc/src/index.js.map +1 -1
  30. package/dist/browser/runtime/browser/util.d.ts +3 -1
  31. package/dist/browser/runtime/browser/util.js +8 -2
  32. package/dist/browser/runtime/browser/util.js.map +1 -1
  33. package/dist/browser/runtime/node/blockstore.d.ts +2 -2
  34. package/dist/browser/runtime/node/blockstore.js +2 -2
  35. package/dist/browser/runtime/node/community/challenges/validate-challenge-result.js +2 -1
  36. package/dist/browser/runtime/node/community/challenges/validate-challenge-result.js.map +1 -1
  37. package/dist/browser/runtime/node/community/communities-registry.d.ts +96 -0
  38. package/dist/browser/runtime/node/community/communities-registry.js +964 -0
  39. package/dist/browser/runtime/node/community/communities-registry.js.map +1 -0
  40. package/dist/browser/runtime/node/community/db-handler.d.ts +3 -0
  41. package/dist/browser/runtime/node/community/db-handler.js +82 -35
  42. package/dist/browser/runtime/node/community/db-handler.js.map +1 -1
  43. package/dist/browser/runtime/node/community/local-community/editing.js +16 -8
  44. package/dist/browser/runtime/node/community/local-community/editing.js.map +1 -1
  45. package/dist/browser/runtime/node/community/local-community/lifecycle.js +68 -19
  46. package/dist/browser/runtime/node/community/local-community/lifecycle.js.map +1 -1
  47. package/dist/browser/runtime/node/community/local-community/publication-validation.d.ts +1 -2
  48. package/dist/browser/runtime/node/community/local-community/publication-validation.js +23 -0
  49. package/dist/browser/runtime/node/community/local-community/publication-validation.js.map +1 -1
  50. package/dist/browser/runtime/node/community/local-community.d.ts +2 -1
  51. package/dist/browser/runtime/node/community/local-community.js +5 -9
  52. package/dist/browser/runtime/node/community/local-community.js.map +1 -1
  53. package/dist/browser/runtime/node/community/pkc-instance-lock.d.ts +17 -0
  54. package/dist/browser/runtime/node/community/pkc-instance-lock.js +142 -0
  55. package/dist/browser/runtime/node/community/pkc-instance-lock.js.map +1 -0
  56. package/dist/browser/runtime/node/storage.js +5 -0
  57. package/dist/browser/runtime/node/storage.js.map +1 -1
  58. package/dist/browser/runtime/node/util.d.ts +4 -6
  59. package/dist/browser/runtime/node/util.js +32 -278
  60. package/dist/browser/runtime/node/util.js.map +1 -1
  61. package/dist/browser/schema/schema-util.js +18 -4
  62. package/dist/browser/schema/schema-util.js.map +1 -1
  63. package/dist/browser/signer/author-wallet-proof.d.ts +19 -0
  64. package/dist/browser/signer/author-wallet-proof.js +89 -0
  65. package/dist/browser/signer/author-wallet-proof.js.map +1 -0
  66. package/dist/browser/signer/signatures.js +29 -0
  67. package/dist/browser/signer/signatures.js.map +1 -1
  68. package/dist/browser/test/test-util.d.ts +12 -0
  69. package/dist/browser/test/test-util.js +23 -0
  70. package/dist/browser/test/test-util.js.map +1 -1
  71. package/dist/browser/unknown-props.d.ts +24 -0
  72. package/dist/browser/unknown-props.js +95 -0
  73. package/dist/browser/unknown-props.js.map +1 -0
  74. package/dist/browser/util.js +7 -0
  75. package/dist/browser/util.js.map +1 -1
  76. package/dist/browser/version.js +1 -1
  77. package/dist/bundled/bundle-manifest.json +47 -40
  78. package/dist/bundled/challenges.js +1 -1
  79. package/dist/bundled/chunks/{helia-for-pkc-CG9YohPs.js → helia-for-pkc-Oiy9zYBR.js} +4 -4
  80. package/dist/bundled/chunks/{local-community-CaQmhX8D.js → local-community-BlJfnxcr.js} +1 -1
  81. package/dist/bundled/chunks/{local-community-V8_VyEhO.js → local-community-PMJTbzmG.js} +128 -57
  82. package/dist/bundled/chunks/{node-c4vpD2VN.js → node-Bf1DjAFe.js} +161 -49
  83. package/dist/bundled/chunks/{page-sort-scoring-d1frahfd.js → page-sort-scoring-DVAvzj4W.js} +1 -1
  84. package/dist/bundled/chunks/{rpc-local-community-DDAibWpE.js → rpc-local-community-BqJ_olvR.js} +4482 -1673
  85. package/dist/bundled/chunks/{util-B_dKP7Te.js → util-BpiQT2hV.js} +1 -1
  86. package/dist/bundled/chunks/{util-BwEIge-b.js → util-N_HlPQHv.js} +62 -16
  87. package/dist/bundled/chunks/{validate-package-factories-DfpNf4oq.js → validate-package-factories-DoC8xXMu.js} +2 -2
  88. package/dist/bundled/index.js +1 -1
  89. package/dist/bundled/page-sorts.js +1 -1
  90. package/dist/bundled/rpc/src/index.js +5 -6
  91. package/dist/node/clients/rpc-client/schema.js +2 -2
  92. package/dist/node/clients/rpc-client/schema.js.map +1 -1
  93. package/dist/node/community/remote-community.js +8 -2
  94. package/dist/node/community/remote-community.js.map +1 -1
  95. package/dist/node/community/schema.js +4 -0
  96. package/dist/node/community/schema.js.map +1 -1
  97. package/dist/node/community-list/community-list.js +3 -2
  98. package/dist/node/community-list/community-list.js.map +1 -1
  99. package/dist/node/errors.d.ts +14 -0
  100. package/dist/node/errors.js +14 -0
  101. package/dist/node/errors.js.map +1 -1
  102. package/dist/node/generated-version.d.ts +1 -1
  103. package/dist/node/generated-version.js +1 -1
  104. package/dist/node/pkc/pkc.js +13 -4
  105. package/dist/node/pkc/pkc.js.map +1 -1
  106. package/dist/node/pkc-error.d.ts +1 -1
  107. package/dist/node/publications/comment/comment.js +25 -9
  108. package/dist/node/publications/comment/comment.js.map +1 -1
  109. package/dist/node/publications/comment/crosspost-runtime.js +10 -2
  110. package/dist/node/publications/comment/crosspost-runtime.js.map +1 -1
  111. package/dist/node/publications/comment/schema.d.ts +1 -1
  112. package/dist/node/publications/comment/schema.js +30 -1
  113. package/dist/node/publications/comment/schema.js.map +1 -1
  114. package/dist/node/publications/publication.d.ts +4 -0
  115. package/dist/node/publications/publication.js +135 -38
  116. package/dist/node/publications/publication.js.map +1 -1
  117. package/dist/node/rpc/src/index.js +3 -3
  118. package/dist/node/rpc/src/index.js.map +1 -1
  119. package/dist/node/runtime/browser/util.d.ts +3 -1
  120. package/dist/node/runtime/browser/util.js +8 -2
  121. package/dist/node/runtime/browser/util.js.map +1 -1
  122. package/dist/node/runtime/node/blockstore.d.ts +2 -2
  123. package/dist/node/runtime/node/blockstore.js +2 -2
  124. package/dist/node/runtime/node/community/challenges/validate-challenge-result.js +2 -1
  125. package/dist/node/runtime/node/community/challenges/validate-challenge-result.js.map +1 -1
  126. package/dist/node/runtime/node/community/communities-registry.d.ts +96 -0
  127. package/dist/node/runtime/node/community/communities-registry.js +964 -0
  128. package/dist/node/runtime/node/community/communities-registry.js.map +1 -0
  129. package/dist/node/runtime/node/community/db-handler.d.ts +3 -0
  130. package/dist/node/runtime/node/community/db-handler.js +82 -35
  131. package/dist/node/runtime/node/community/db-handler.js.map +1 -1
  132. package/dist/node/runtime/node/community/local-community/editing.js +16 -8
  133. package/dist/node/runtime/node/community/local-community/editing.js.map +1 -1
  134. package/dist/node/runtime/node/community/local-community/lifecycle.js +68 -19
  135. package/dist/node/runtime/node/community/local-community/lifecycle.js.map +1 -1
  136. package/dist/node/runtime/node/community/local-community/publication-validation.d.ts +1 -2
  137. package/dist/node/runtime/node/community/local-community/publication-validation.js +23 -0
  138. package/dist/node/runtime/node/community/local-community/publication-validation.js.map +1 -1
  139. package/dist/node/runtime/node/community/local-community.d.ts +2 -1
  140. package/dist/node/runtime/node/community/local-community.js +5 -9
  141. package/dist/node/runtime/node/community/local-community.js.map +1 -1
  142. package/dist/node/runtime/node/community/pkc-instance-lock.d.ts +17 -0
  143. package/dist/node/runtime/node/community/pkc-instance-lock.js +142 -0
  144. package/dist/node/runtime/node/community/pkc-instance-lock.js.map +1 -0
  145. package/dist/node/runtime/node/storage.js +5 -0
  146. package/dist/node/runtime/node/storage.js.map +1 -1
  147. package/dist/node/runtime/node/util.d.ts +4 -6
  148. package/dist/node/runtime/node/util.js +32 -278
  149. package/dist/node/runtime/node/util.js.map +1 -1
  150. package/dist/node/schema/schema-util.js +18 -4
  151. package/dist/node/schema/schema-util.js.map +1 -1
  152. package/dist/node/signer/author-wallet-proof.d.ts +19 -0
  153. package/dist/node/signer/author-wallet-proof.js +89 -0
  154. package/dist/node/signer/author-wallet-proof.js.map +1 -0
  155. package/dist/node/signer/signatures.js +29 -0
  156. package/dist/node/signer/signatures.js.map +1 -1
  157. package/dist/node/test/test-util.d.ts +12 -0
  158. package/dist/node/test/test-util.js +23 -0
  159. package/dist/node/test/test-util.js.map +1 -1
  160. package/dist/node/unknown-props.d.ts +24 -0
  161. package/dist/node/unknown-props.js +95 -0
  162. package/dist/node/unknown-props.js.map +1 -0
  163. package/dist/node/util.js +7 -0
  164. package/dist/node/util.js.map +1 -1
  165. package/dist/node/version.js +1 -1
  166. package/package.json +3 -2
  167. package/dist/browser/runtime/node/community/start-lock.d.ts +0 -17
  168. package/dist/browser/runtime/node/community/start-lock.js +0 -161
  169. package/dist/browser/runtime/node/community/start-lock.js.map +0 -1
  170. package/dist/node/runtime/node/community/start-lock.d.ts +0 -17
  171. package/dist/node/runtime/node/community/start-lock.js +0 -161
  172. package/dist/node/runtime/node/community/start-lock.js.map +0 -1
@@ -0,0 +1,964 @@
1
+ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readSync, realpathSync, rmSync, statSync, watch as fsWatch } from "node:fs";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import Database from "better-sqlite3";
5
+ import Logger from "../../../logger.js";
6
+ import { STORAGE_KEYS } from "../../../constants.js";
7
+ import { areEquivalentNames, isEthAliasDomain, isStringDomain, normalizeEthAliasDomain } from "../../../domain-util.js";
8
+ import { doesCommunitiesEntryMatch, toCommunitiesEntry } from "../../../community/communities-entry-util.js";
9
+ import { getInstanceLockPath, getInstanceLocksPath, instanceIdOfLockFile, isInstanceLockHeldSync, releaseInstanceLock, takeInstanceLock } from "./pkc-instance-lock.js";
10
+ // The local communities of a data path, and which PKC instance has started each (issue #585).
11
+ //
12
+ // One row per community DB file in dataPath/communities, in two tables of dataPath/storage.db, which every PKC
13
+ // instance on the data path opens. pkc.communities, pkc.createCommunity, community.started and the RPC server all read
14
+ // it. Before, they were derived from the directory: every load, creation and start of one community listed the whole
15
+ // directory, which with 10,000 communities is 40,000 entries, and `started` was a lock file per community.
16
+ //
17
+ // - The DB files are the truth and the registry is their index. A file without a row gets one, a row without a file
18
+ // is removed. Creating a community writes its file first and its row second, so a crash in between heals the same
19
+ // way a file copied in by hand is picked up.
20
+ // - `startedBy` is the one thing only the registry knows: the id of the PKC instance that started the community. A
21
+ // community is started when that instance's lock is held (see pkc-instance-lock.ts). start() claims the row in one
22
+ // write transaction, which SQLite makes atomic across processes, and takes it over from an instance that died.
23
+ // - The directory is listed once, when monitoring starts, and again only for a filesystem event that does not say
24
+ // which file it is about. Any other event is about one file: ignored when that file has a row and is still there,
25
+ // registered when it has none.
26
+ // - SQLite does not notify another process of a write, and a killed process writes nothing. So what another instance
27
+ // did (create, delete, rename, start, stop, die) reaches this one on a timer, every COMMUNITIES_REGISTRY_TICK_MS:
28
+ // the rows changed since the last read, and a try of the lock of every other instance that has communities
29
+ // started. What this instance does itself is applied at once. Only the list is late: start() and createCommunity()
30
+ // read the tables.
31
+ export const COMMUNITIES_REGISTRY_TICK_MS = 2000;
32
+ // How many files of the directory are registered in one write transaction
33
+ export const COMMUNITIES_REGISTRY_RECONCILE_BATCH_SIZE = 100;
34
+ const COMMUNITIES_TABLE = "localCommunities";
35
+ const CHANGES_TABLE = "localCommunitiesChanges";
36
+ // How many changes are kept for instances that have not read them yet. An instance that falls further behind reads
37
+ // every row again
38
+ const CHANGES_KEPT = 65_536;
39
+ const CHANGES_PRUNE_EVERY = 4096;
40
+ // A lock file younger than this may belong to an instance that has created it and not locked it yet
41
+ const INSTANCE_LOCK_MIN_AGE_TO_SWEEP_MS = 60_000;
42
+ // Files in dataPath/communities that are never a community DB: SQLite's own companions, and the lock files of the
43
+ // designs before this one
44
+ const FILE_SUFFIXES_TO_IGNORE = [".lock", ".lock.db", "-journal", "-shm", "-wal"];
45
+ const LEGACY_START_LOCK_SUFFIXES = [".start.lock.db", ".start.lock"];
46
+ // What reading a DB's identity fails with when the file itself may be fine. SQLITE_CANTOPEN is also what SQLite makes of
47
+ // a process that is out of file descriptors
48
+ const ERROR_CODES_OF_A_READ_THAT_MAY_PASS = [
49
+ "SQLITE_BUSY",
50
+ "SQLITE_LOCKED",
51
+ "SQLITE_CANTOPEN",
52
+ "SQLITE_IOERR",
53
+ "SQLITE_PROTOCOL",
54
+ "EMFILE",
55
+ "ENFILE"
56
+ ];
57
+ // How many times the timer reads again the identity of a DB whose read failed for a reason that may pass
58
+ const IDENTITY_READ_RETRIES = 5;
59
+ const isIgnoredFilename = (filename) => FILE_SUFFIXES_TO_IGNORE.some((suffix) => filename.endsWith(suffix));
60
+ // A community DB this process is creating or moving into place right now, by absolute path. The filesystem events of
61
+ // its writes are not acted on: the creator registers the file itself once it is complete. Without this every write of
62
+ // a creation opened the half-written DB to look for its identity. Counted, since two calls may create the same DB
63
+ const filesBeingWrittenByThisProcess = new Map();
64
+ // Marks a community DB as being created or moved into place by this process, until the returned function is called
65
+ export function markCommunityDbAsBeingWritten({ dataPath, communityAddress }) {
66
+ const filePath = path.resolve(getDbFilePath(dataPath, communityAddress));
67
+ filesBeingWrittenByThisProcess.set(filePath, (filesBeingWrittenByThisProcess.get(filePath) ?? 0) + 1);
68
+ let done = false;
69
+ return () => {
70
+ if (done)
71
+ return;
72
+ done = true;
73
+ const count = (filesBeingWrittenByThisProcess.get(filePath) ?? 1) - 1;
74
+ if (count <= 0)
75
+ filesBeingWrittenByThisProcess.delete(filePath);
76
+ else
77
+ filesBeingWrittenByThisProcess.set(filePath, count);
78
+ };
79
+ }
80
+ // An address is given by whoever calls createCommunity, an RPC client included, and is the filename of the DB. One with
81
+ // a path in it would reach files outside dataPath/communities ("../storage.db"), or below it ("deleted/<address>")
82
+ function isPlainFilename(filename) {
83
+ return (filename.length > 0 &&
84
+ filename !== "." &&
85
+ filename !== ".." &&
86
+ !filename.includes("/") &&
87
+ !filename.includes("\\") &&
88
+ !filename.includes("\0") &&
89
+ path.basename(filename) === filename);
90
+ }
91
+ function getDbFilePath(dataPath, communityAddress) {
92
+ if (!isPlainFilename(communityAddress))
93
+ throw Error(`A community DB can't be stored under an address that is not a filename (${communityAddress})`);
94
+ return path.join(dataPath, "communities", communityAddress);
95
+ }
96
+ // What a row is looked up by. An .eth/.bso name is one name in any case and in either spelling (issue #424), and its
97
+ // DB is stored under the name as it was typed. Any other address is itself
98
+ function lookupKeyOf(communityAddress) {
99
+ return isEthAliasDomain(communityAddress) ? normalizeEthAliasDomain(communityAddress.toLowerCase()) : communityAddress;
100
+ }
101
+ // The filename a file is stored under. On a filesystem that ignores case a file is found under any spelling of its
102
+ // name, and must have one row
103
+ function filenameAsStored(filePath) {
104
+ const filename = path.basename(filePath);
105
+ try {
106
+ const stored = path.basename(realpathSync.native(filePath));
107
+ return stored.toLowerCase() === filename.toLowerCase() ? stored : filename; // not the target of a link
108
+ }
109
+ catch {
110
+ return filename;
111
+ }
112
+ }
113
+ // Whether there is no file at this path. A file that could not be looked at is not gone
114
+ function isFileGone(filePath) {
115
+ try {
116
+ return !statSync(filePath).isFile();
117
+ }
118
+ catch (e) {
119
+ return e instanceof Error && "code" in e && (e.code === "ENOENT" || e.code === "ENOTDIR");
120
+ }
121
+ }
122
+ // Identifies the file itself, not its content: a DB that is deleted and created again under the same filename is
123
+ // another file, with another identity. The inode alone is reused by some filesystems right after a delete
124
+ function getFileId(filePath) {
125
+ try {
126
+ const stat = statSync(filePath, { bigint: true });
127
+ if (!stat.isFile())
128
+ return undefined;
129
+ return `${stat.ino}:${stat.birthtimeNs}`;
130
+ }
131
+ catch {
132
+ return undefined;
133
+ }
134
+ }
135
+ // "could-not-read" when the file is there and its header could not be read (the process is out of file descriptors)
136
+ function isSqliteFile(filePath) {
137
+ try {
138
+ // Look for the SQLite file header "SQLite format 3\0"
139
+ const fd = openSync(filePath, "r");
140
+ const buffer = Buffer.alloc(16);
141
+ try {
142
+ readSync(fd, buffer, 0, 16, 0);
143
+ }
144
+ finally {
145
+ closeSync(fd); // must run whatever readSync throws, or the fd leaks (#380)
146
+ }
147
+ return buffer.toString().startsWith("SQLite format 3");
148
+ }
149
+ catch (e) {
150
+ // ENOENT is expected: the file can be removed between the event and the read (community delete)
151
+ if (e instanceof Error && "code" in e && e.code === "ENOENT")
152
+ return false;
153
+ Logger("pkc-js:communities-registry").error(`Failed to check whether ${filePath} is a SQLite file, skipping it for now`, e);
154
+ return "could-not-read";
155
+ }
156
+ }
157
+ // Reads the identity key from the DB's internal record. A delegated community is identified by its anchor, not by the
158
+ // minter it signs with. The name is not read from the DB but taken from the filename, which is the community's address,
159
+ // i.e. its name when it has one (issue #430): a rename moves the file before it writes the new name into the DB.
160
+ // No publicKey if the DB can't be read yet (mid-creation, mid-migration, corrupt). `failureMayPass` when the read failed
161
+ // for a reason that has nothing to do with what is in the file: it is locked, the process is out of file descriptors
162
+ function readCommunityPublicKeyFromDb(dbPath) {
163
+ const log = Logger("pkc-js:communities-registry:readCommunityPublicKeyFromDb");
164
+ let db;
165
+ try {
166
+ db = new Database(dbPath, { readonly: true, fileMustExist: true });
167
+ const row = db.prepare("SELECT value FROM keyv WHERE key = ?").get(`keyv:${STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY]}`);
168
+ const internalState = row ? JSON.parse(row.value)?.value : undefined;
169
+ const publicKey = internalState?.anchor?.publicKey ?? internalState?.signer?.address;
170
+ if (typeof publicKey !== "string") {
171
+ log(`Community DB (${dbPath}) has no internal state yet, leaving it out of pkc.communities for now`);
172
+ return { failureMayPass: false };
173
+ }
174
+ return { publicKey, failureMayPass: false };
175
+ }
176
+ catch (e) {
177
+ log.error(`Failed to read the identity of community DB (${dbPath}), leaving it out of pkc.communities for now`, e);
178
+ const code = e instanceof Error && "code" in e && typeof e.code === "string" ? e.code : "";
179
+ return { failureMayPass: ERROR_CODES_OF_A_READ_THAT_MAY_PASS.some((passing) => code.startsWith(passing)) };
180
+ }
181
+ finally {
182
+ db?.close();
183
+ }
184
+ }
185
+ const identityOfRow = (row) => isStringDomain(row.address) ? { name: row.address, publicKey: row.publicKey } : { publicKey: row.publicKey };
186
+ // The filenames a lookup identifier may be stored under: itself, and for an .eth/.bso name both spellings
187
+ function filenamesOfIdentifier(identifier) {
188
+ if (!isEthAliasDomain(identifier))
189
+ return [identifier];
190
+ const withoutTld = identifier.toLowerCase().slice(0, -4);
191
+ return [...new Set([identifier, `${withoutTld}.bso`, `${withoutTld}.eth`])];
192
+ }
193
+ export class CommunitiesRegistry {
194
+ constructor({ dataPath }) {
195
+ this.instanceId = randomUUID();
196
+ this._closed = false;
197
+ this._log = Logger("pkc-js:communities-registry");
198
+ this._lookupStatements = new Map();
199
+ this._rows = new Map();
200
+ // The rows that have an identity, i.e. that are listed, sorted by address, and the entry of each at the same index
201
+ this._sortedAddresses = [];
202
+ this._entries = [];
203
+ this._listIsOutdated = false;
204
+ this._lastSeq = 0;
205
+ // Whether each other instance that has communities started is alive, as of the last time its lock was tried
206
+ this._otherInstancesAlive = new Map();
207
+ this._startedCountByInstance = new Map();
208
+ // The DBs whose identity could not be read for a reason that may pass, and how many more times the timer tries
209
+ this._identityReadsToRetry = new Map();
210
+ // The communities this instance has stopped whose release could not be written (see releaseStart)
211
+ this._releasesToWriteAgain = new Set();
212
+ this.dataPath = dataPath;
213
+ mkdirSync(dataPath, { recursive: true });
214
+ this._db = new Database(path.join(dataPath, "storage.db"));
215
+ // Readers and the one writer do not block each other in WAL mode, and several instances read and write here.
216
+ // NORMAL: a commit is not synced to disk on its own. A power loss may then lose the last commits, which costs
217
+ // nothing here: the rows are rebuilt from the DB files, and whoever had started a community is gone with the power
218
+ this._db.pragma("journal_mode = WAL");
219
+ this._db.pragma("synchronous = NORMAL");
220
+ this._db.exec(`
221
+ CREATE TABLE IF NOT EXISTS ${COMMUNITIES_TABLE} (
222
+ address TEXT PRIMARY KEY,
223
+ publicKey TEXT,
224
+ fileId TEXT,
225
+ startedBy TEXT,
226
+ lookupKey TEXT
227
+ ) WITHOUT ROWID;
228
+ CREATE INDEX IF NOT EXISTS ${COMMUNITIES_TABLE}_publicKey ON ${COMMUNITIES_TABLE} (publicKey);
229
+ CREATE INDEX IF NOT EXISTS ${COMMUNITIES_TABLE}_startedBy ON ${COMMUNITIES_TABLE} (startedBy) WHERE startedBy IS NOT NULL;
230
+ CREATE TABLE IF NOT EXISTS ${CHANGES_TABLE} (seq INTEGER PRIMARY KEY AUTOINCREMENT, address TEXT NOT NULL);
231
+ `);
232
+ this._addLookupKeyColumnIfMissing();
233
+ this._db.exec(`CREATE INDEX IF NOT EXISTS ${COMMUNITIES_TABLE}_lookupKey ON ${COMMUNITIES_TABLE} (lookupKey)`);
234
+ this._selectRow = this._db.prepare(`SELECT address, publicKey, fileId, startedBy FROM ${COMMUNITIES_TABLE} WHERE address = ?`);
235
+ this._selectAllRows = this._db.prepare(`SELECT address, publicKey, fileId, startedBy FROM ${COMMUNITIES_TABLE}`);
236
+ this._upsertIdentity = this._db.prepare(`INSERT INTO ${COMMUNITIES_TABLE} (address, publicKey, fileId, lookupKey) VALUES (?, ?, ?, ?)
237
+ ON CONFLICT (address) DO UPDATE SET publicKey = excluded.publicKey, fileId = excluded.fileId, lookupKey = excluded.lookupKey`);
238
+ this._deleteRow = this._db.prepare(`DELETE FROM ${COMMUNITIES_TABLE} WHERE address = ?`);
239
+ this._setStartedBy = this._db.prepare(`UPDATE ${COMMUNITIES_TABLE} SET startedBy = ? WHERE address = ?`);
240
+ this._releaseStartedBy = this._db.prepare(`UPDATE ${COMMUNITIES_TABLE} SET startedBy = NULL WHERE address = ? AND startedBy = ?`);
241
+ this._clearInstance = this._db.prepare(`UPDATE ${COMMUNITIES_TABLE} SET startedBy = NULL WHERE startedBy = ?`);
242
+ this._insertChange = this._db.prepare(`INSERT INTO ${CHANGES_TABLE} (address) VALUES (?)`);
243
+ this._insertChangesOfInstance = this._db.prepare(`INSERT INTO ${CHANGES_TABLE} (address) SELECT address FROM ${COMMUNITIES_TABLE} WHERE startedBy = ?`);
244
+ this._pruneChanges = this._db.prepare(`DELETE FROM ${CHANGES_TABLE} WHERE seq <= ?`);
245
+ this._selectChangeBounds = this._db.prepare(`SELECT min(seq) AS minSeq, max(seq) AS maxSeq FROM ${CHANGES_TABLE}`);
246
+ this._selectChangedAddresses = this._db.prepare(`SELECT DISTINCT address FROM ${CHANGES_TABLE} WHERE seq > ?`);
247
+ takeInstanceLock({ db: this._db, lockPath: getInstanceLockPath({ dataPath, instanceId: this.instanceId }) });
248
+ }
249
+ // The table of a data path that ran this registry before its rows had a lookup key
250
+ _addLookupKeyColumnIfMissing() {
251
+ const columns = this._db.pragma(`table_info(${COMMUNITIES_TABLE})`);
252
+ if (columns.some((column) => column.name === "lookupKey"))
253
+ return;
254
+ this._db
255
+ .transaction(() => {
256
+ // another instance may have added it since
257
+ const columnsNow = this._db.pragma(`table_info(${COMMUNITIES_TABLE})`);
258
+ if (columnsNow.some((column) => column.name === "lookupKey"))
259
+ return;
260
+ this._db.exec(`ALTER TABLE ${COMMUNITIES_TABLE} ADD COLUMN lookupKey TEXT`);
261
+ const setLookupKey = this._db.prepare(`UPDATE ${COMMUNITIES_TABLE} SET lookupKey = ? WHERE address = ?`);
262
+ for (const { address } of this._db.prepare(`SELECT address FROM ${COMMUNITIES_TABLE}`).all())
263
+ setLookupKey.run(lookupKeyOf(address), address);
264
+ })
265
+ .immediate();
266
+ }
267
+ get closed() {
268
+ return this._closed;
269
+ }
270
+ // ---- the list of a PKC instance ----
271
+ // Lists the directory once, starts the watcher and the timer, and calls onChange with the list, now and whenever it
272
+ // changes afterwards
273
+ startMonitoring({ onChange }) {
274
+ if (this._closed)
275
+ throw Error("The communities registry of this PKC instance is closed");
276
+ if (this._onChange)
277
+ throw Error("The communities registry of this PKC instance is monitoring already");
278
+ const communitiesPath = path.join(this.dataPath, "communities");
279
+ mkdirSync(communitiesPath, { recursive: true });
280
+ this._onChange = onChange;
281
+ // Watching before the directory is listed: a DB that is put in it while it is listed is in the listing or in an
282
+ // event. An event is delivered after this function has returned, never in the middle of it
283
+ this._watcher = fsWatch(communitiesPath, { persistent: false }, (eventType, filename) => {
284
+ // Runs in the watcher callback, where a throw is uncaught
285
+ try {
286
+ if (typeof filename !== "string")
287
+ this._reconcileWithDirectory();
288
+ else
289
+ this._onFileEvent(eventType, filename);
290
+ this._emitListIfOutdated();
291
+ }
292
+ catch (error) {
293
+ this._log.error("Failed to follow a change in", communitiesPath, eventType, filename, error);
294
+ }
295
+ });
296
+ this._watcher.on("error", (error) => this._log.error("The watcher of", communitiesPath, "failed", error));
297
+ this._timer = setInterval(() => {
298
+ try {
299
+ this.readChangesOfOtherInstances();
300
+ }
301
+ catch (error) {
302
+ this._log.error("Failed to read what other PKC instances changed in the communities registry", error);
303
+ }
304
+ }, COMMUNITIES_REGISTRY_TICK_MS);
305
+ this._timer.unref();
306
+ this._sweepInstanceLocksOfDeadInstances();
307
+ this._reloadAllRows();
308
+ this._reconcileWithDirectory();
309
+ this._clearDeadInstances();
310
+ this._listIsOutdated = true; // a PKC waits for its first list, also when it is empty
311
+ this._emitListIfOutdated();
312
+ }
313
+ // What the timer runs. Public so a caller that can't wait for the timer may run it now
314
+ readChangesOfOtherInstances() {
315
+ if (this._closed || !this._onChange)
316
+ return;
317
+ const { minSeq, maxSeq } = this._selectChangeBounds.get();
318
+ if (maxSeq !== null && maxSeq > this._lastSeq) {
319
+ // changes this instance has not read were pruned: read everything
320
+ if (minSeq !== null && minSeq > this._lastSeq + 1)
321
+ this._reloadAllRows();
322
+ else {
323
+ const changed = this._selectChangedAddresses.all(this._lastSeq);
324
+ for (const { address } of changed)
325
+ this._mirrorRow(address, this._selectRow.get(address));
326
+ this._lastSeq = maxSeq;
327
+ }
328
+ }
329
+ this._readAgainIdentitiesThatFailedToBeRead();
330
+ for (const address of [...this._releasesToWriteAgain])
331
+ this.releaseStart(address);
332
+ this._clearDeadInstances();
333
+ this._emitListIfOutdated();
334
+ }
335
+ // ---- lookups ----
336
+ // The filename (the address the DB is stored under) of the local community matching a lookup by address, name or
337
+ // identity key, or undefined if there is none. A DB whose identity can't be read yet still matches by filename,
338
+ // when every supplied identifier is that filename
339
+ findAddress(lookup) {
340
+ if (this._closed)
341
+ return undefined;
342
+ const identifiers = [lookup.address, lookup.name, lookup.publicKey].filter((id) => typeof id === "string");
343
+ if (identifiers.length === 0)
344
+ return undefined;
345
+ const filenames = [...new Set(identifiers.flatMap(filenamesOfIdentifier))].filter(isPlainFilename);
346
+ const matchesFilename = (filename) => identifiers.every((id) => areEquivalentNames(filename, id));
347
+ const rowMatches = (row) => row.publicKey !== null
348
+ ? doesCommunitiesEntryMatch(identityOfRow({ ...row, publicKey: row.publicKey }), lookup)
349
+ : matchesFilename(row.address);
350
+ const lookupKeys = [...new Set(identifiers.map(lookupKeyOf))];
351
+ for (const row of this._selectRowsByLookupKeyOrPublicKey({ lookupKeys, publicKeys: identifiers })) {
352
+ if (!rowMatches(row))
353
+ continue;
354
+ if (existsSync(getDbFilePath(this.dataPath, row.address)))
355
+ return row.address;
356
+ // the file was removed without this instance being told, yet. Unless it is there after all
357
+ const rowNow = this._removeRowIfFileIsGone(row.address);
358
+ this._emitListIfOutdated();
359
+ if (rowNow && rowMatches(rowNow))
360
+ return rowNow.address;
361
+ }
362
+ // A DB file that has no row yet: another process created it or somebody copied it in, and its filesystem event
363
+ // has not arrived (on macOS it arrives late)
364
+ for (const filename of filenames) {
365
+ if (isIgnoredFilename(filename) || this._selectRow.get(filename))
366
+ continue;
367
+ // Nothing is written for a community that is not local, which is what most lookups are about: a write
368
+ // waits for whoever is writing to storage.db, and fails when that takes too long
369
+ const dbFilePath = getDbFilePath(this.dataPath, filename);
370
+ if (!existsSync(dbFilePath))
371
+ continue;
372
+ // Found under another spelling than it is stored under, on a filesystem that ignores case: only a name
373
+ // that ignores case is the same community, and a row it has under its own spelling did not match above
374
+ const storedAs = filenameAsStored(dbFilePath);
375
+ if (storedAs !== filename && (!areEquivalentNames(storedAs, filename) || this._selectRow.get(storedAs)))
376
+ continue;
377
+ const registered = this._registerFile(storedAs);
378
+ this._emitListIfOutdated();
379
+ if (registered && rowMatches(registered))
380
+ return storedAs;
381
+ }
382
+ return undefined;
383
+ }
384
+ // Whether a community DB is stored under exactly this address
385
+ hasCommunityDb(communityAddress) {
386
+ if (!isPlainFilename(communityAddress))
387
+ return false;
388
+ const dbFilePath = getDbFilePath(this.dataPath, communityAddress);
389
+ if (!existsSync(dbFilePath))
390
+ return false;
391
+ // Still answered after close(), from the file: something of a destroyed PKC may run a moment longer
392
+ if (this._closed)
393
+ return isSqliteFile(dbFilePath) === true;
394
+ if (this._selectRow.get(communityAddress))
395
+ return true;
396
+ if (isSqliteFile(dbFilePath) !== true || filenameAsStored(dbFilePath) !== communityAddress)
397
+ return false;
398
+ // A DB without a row, e.g. of a creation whose registration failed: registered now. The DB is there whether
399
+ // or not that works
400
+ if (!filesBeingWrittenByThisProcess.has(path.resolve(dbFilePath))) {
401
+ try {
402
+ this._registerFile(communityAddress);
403
+ this._emitListIfOutdated();
404
+ }
405
+ catch (error) {
406
+ this._log.error("Failed to register the community DB found without a row", communityAddress, error);
407
+ }
408
+ }
409
+ return true;
410
+ }
411
+ // ---- changes this instance makes ----
412
+ // Reads the identity of the DB file stored under this address and writes its row. Called by whoever has just created
413
+ // or moved the file, so the community is listed when their call returns
414
+ registerCommunity(communityAddress) {
415
+ if (this._closed)
416
+ return;
417
+ this._registerFile(communityAddress);
418
+ this._emitListIfOutdated();
419
+ }
420
+ // Removes the row of a community whose DB file the caller has deleted or moved away
421
+ unregisterCommunity(communityAddress) {
422
+ if (this._closed)
423
+ return;
424
+ this._removeRow(communityAddress);
425
+ this._emitListIfOutdated();
426
+ }
427
+ // A rename has moved the DB file from one address to another (issue #430): one change of the list, not two
428
+ renameCommunity({ oldAddress, newAddress }) {
429
+ if (this._closed)
430
+ return;
431
+ this._write(() => {
432
+ this._removeRow(oldAddress);
433
+ this._registerFile(newAddress);
434
+ });
435
+ this._emitListIfOutdated();
436
+ }
437
+ // ---- started ----
438
+ // Claims the community for this instance. Returns false when a live instance has it started, this one included.
439
+ // A claim left by an instance that died is taken over.
440
+ claimStart(communityAddress) {
441
+ if (this._closed)
442
+ throw Error("The communities registry of this PKC instance is closed");
443
+ const claimed = this._write(() => {
444
+ let row = this._selectRow.get(communityAddress);
445
+ if (!row) {
446
+ this._registerFile(communityAddress, { evenIfNotACommunityDb: true });
447
+ row = this._selectRow.get(communityAddress);
448
+ }
449
+ // its own claim, unless that is one it has given up and could not write the release of
450
+ if (row.startedBy === this.instanceId && !this._releasesToWriteAgain.has(communityAddress))
451
+ return false;
452
+ if (row.startedBy !== null && row.startedBy !== this.instanceId && this._isOtherInstanceAliveNow(row.startedBy))
453
+ return false;
454
+ this._setStartedBy.run(this.instanceId, communityAddress);
455
+ this._recordChange(communityAddress);
456
+ return true;
457
+ });
458
+ if (claimed && this._releasesToWriteAgain.delete(communityAddress))
459
+ this._mirrorStartedAgain(communityAddress);
460
+ this._emitListIfOutdated();
461
+ return claimed;
462
+ }
463
+ // Does not throw when the release can't be written (storage.db locked by another process for longer than SQLite
464
+ // waits): the community is stopped all the same. The claim would stay, in the name of a live instance, and nothing
465
+ // could start the community until this process ended. So the release is written again on the timer, and until then
466
+ // this instance does not count the claim as one
467
+ releaseStart(communityAddress) {
468
+ if (this._closed)
469
+ return;
470
+ try {
471
+ this._write(() => {
472
+ if (this._releaseStartedBy.run(communityAddress, this.instanceId).changes > 0)
473
+ this._recordChange(communityAddress);
474
+ });
475
+ this._releasesToWriteAgain.delete(communityAddress);
476
+ }
477
+ catch (error) {
478
+ this._releasesToWriteAgain.add(communityAddress);
479
+ this._mirrorStartedAgain(communityAddress);
480
+ this._log.error("Failed to write that community", communityAddress, "is stopped, will try again", error);
481
+ }
482
+ this._emitListIfOutdated();
483
+ }
484
+ // Whether a live instance has the community started, this one included
485
+ isStarted(communityAddress) {
486
+ if (this._closed)
487
+ return false;
488
+ const startedBy = this._selectRow.get(communityAddress)?.startedBy ?? null;
489
+ if (startedBy === null)
490
+ return false;
491
+ if (startedBy === this.instanceId)
492
+ return !this._releasesToWriteAgain.has(communityAddress);
493
+ return this._isOtherInstanceAliveNow(startedBy);
494
+ }
495
+ // For a community this instance is running: whether it is still this instance's. "taken" means another live
496
+ // instance has claimed it, which can only follow from this instance having lost its claim while running. A claim
497
+ // that is merely gone (its row was removed and written again, e.g. around a file event of another process) is
498
+ // written back.
499
+ confirmStart(communityAddress) {
500
+ if (this._closed)
501
+ return "owned";
502
+ const row = this._selectRow.get(communityAddress);
503
+ if (row?.startedBy === this.instanceId)
504
+ return "owned";
505
+ if (row && row.startedBy !== null && this._isOtherInstanceAliveNow(row.startedBy))
506
+ return "taken";
507
+ if (!row && !existsSync(getDbFilePath(this.dataPath, communityAddress)))
508
+ return "owned"; // nothing to claim
509
+ const stillOwned = this._write(() => {
510
+ const current = this._selectRow.get(communityAddress);
511
+ if (current?.startedBy === this.instanceId)
512
+ return true;
513
+ if (current && current.startedBy !== null && this._isOtherInstanceAliveNow(current.startedBy))
514
+ return false;
515
+ if (!current)
516
+ this._registerFile(communityAddress, { evenIfNotACommunityDb: true });
517
+ this._setStartedBy.run(this.instanceId, communityAddress);
518
+ this._recordChange(communityAddress);
519
+ return true;
520
+ });
521
+ this._emitListIfOutdated();
522
+ return stillOwned ? "owned" : "taken";
523
+ }
524
+ // ---- lifetime ----
525
+ // Releases every community this instance still has claimed, and its lock. The instance is gone afterwards
526
+ close() {
527
+ if (this._closed)
528
+ return;
529
+ this._closed = true;
530
+ if (this._timer)
531
+ clearInterval(this._timer);
532
+ this._watcher?.close();
533
+ this._onChange = undefined;
534
+ const lockPath = getInstanceLockPath({ dataPath: this.dataPath, instanceId: this.instanceId });
535
+ try {
536
+ if (this._db.open) {
537
+ this._db.exec("BEGIN IMMEDIATE");
538
+ this._insertChangesOfInstance.run(this.instanceId);
539
+ this._clearInstance.run(this.instanceId);
540
+ this._db.exec("COMMIT");
541
+ }
542
+ }
543
+ catch (error) {
544
+ if (this._db.inTransaction)
545
+ this._db.exec("ROLLBACK");
546
+ this._log.error("Failed to release the communities of a closing PKC instance", error);
547
+ }
548
+ try {
549
+ releaseInstanceLock({ db: this._db, lockPath });
550
+ }
551
+ catch (error) {
552
+ this._log.error("Failed to release the lock of a closing PKC instance", error);
553
+ }
554
+ if (this._db.open)
555
+ this._db.close();
556
+ }
557
+ // ---- internals ----
558
+ _write(write) {
559
+ if (this._db.inTransaction)
560
+ return write();
561
+ this._db.exec("BEGIN IMMEDIATE");
562
+ try {
563
+ const result = write();
564
+ this._db.exec("COMMIT");
565
+ return result;
566
+ }
567
+ catch (e) {
568
+ if (this._db.inTransaction)
569
+ this._db.exec("ROLLBACK");
570
+ // The copy may hold what the rolled back transaction wrote
571
+ if (this._onChange)
572
+ this._reloadAllRows();
573
+ throw e;
574
+ }
575
+ }
576
+ // Tells the other instances that the row of this address changed, and applies the change to this instance's copy
577
+ _recordChange(communityAddress) {
578
+ const seq = Number(this._insertChange.run(communityAddress).lastInsertRowid);
579
+ if (seq % CHANGES_PRUNE_EVERY === 0)
580
+ this._pruneChanges.run(seq - CHANGES_KEPT);
581
+ if (this._onChange)
582
+ this._mirrorRow(communityAddress, this._selectRow.get(communityAddress));
583
+ }
584
+ _removeRow(communityAddress) {
585
+ this._write(() => {
586
+ if (this._deleteRow.run(communityAddress).changes > 0)
587
+ this._recordChange(communityAddress);
588
+ else if (this._onChange)
589
+ this._mirrorRow(communityAddress, undefined);
590
+ });
591
+ }
592
+ // Removes the row of a DB file that was seen to be gone. Looked at again inside the write transaction: what was seen
593
+ // is old by then, and another instance may have created the file and registered it since. Its row was deleted
594
+ // otherwise, and the community left every list while its creator ran it
595
+ // Returns the row the address is left with, if any. A file that can't be looked at is not gone: its row stays, and
596
+ // the start claim in it
597
+ _removeRowIfFileIsGone(communityAddress) {
598
+ return this._write(() => {
599
+ if (isFileGone(getDbFilePath(this.dataPath, communityAddress))) {
600
+ this._removeRow(communityAddress);
601
+ return undefined;
602
+ }
603
+ return this._registerFile(communityAddress) ?? this._selectRow.get(communityAddress);
604
+ });
605
+ }
606
+ // Writes the row of the DB file stored under this address, from the file. Returns the row, or undefined when there
607
+ // is no such file or it is not a SQLite database. `evenIfNotACommunityDb` writes a row all the same, without an
608
+ // identity: start() claims a community by its row.
609
+ // The file is read inside the write transaction, so two instances registering one file do so one after the other.
610
+ // Read outside of it, an instance that had read a DB while it was still being created could write "no identity"
611
+ // over the identity its creator had registered since, and the community was gone from every list
612
+ _registerFile(communityAddress, { evenIfNotACommunityDb = false } = {}) {
613
+ const dbFilePath = getDbFilePath(this.dataPath, communityAddress);
614
+ return this._write(() => {
615
+ const fileId = getFileId(dbFilePath) ?? null;
616
+ const header = fileId !== null ? isSqliteFile(dbFilePath) : false;
617
+ const isCommunityDb = header === true;
618
+ const existing = this._selectRow.get(communityAddress);
619
+ if (!isCommunityDb && !evenIfNotACommunityDb) {
620
+ // a file that could not be opened to look at its header is looked at again, like one whose DB could not
621
+ if (header !== "could-not-read")
622
+ this._identityReadsToRetry.delete(communityAddress);
623
+ else if (this._onChange && !this._identityReadsToRetry.has(communityAddress))
624
+ this._identityReadsToRetry.set(communityAddress, IDENTITY_READ_RETRIES);
625
+ if (this._onChange)
626
+ this._mirrorRow(communityAddress, existing);
627
+ return undefined;
628
+ }
629
+ const identityRead = isCommunityDb
630
+ ? readCommunityPublicKeyFromDb(dbFilePath)
631
+ : { failureMayPass: header === "could-not-read" };
632
+ let publicKey = identityRead.publicKey ?? null;
633
+ // a read that failed says nothing about a file whose identity is known
634
+ if (publicKey === null && existing && existing.fileId === fileId)
635
+ publicKey = existing.publicKey;
636
+ // Nothing else reads it again: a community that is not started is not written to, so no event follows
637
+ if (publicKey !== null || !identityRead.failureMayPass)
638
+ this._identityReadsToRetry.delete(communityAddress);
639
+ else if (this._onChange && !this._identityReadsToRetry.has(communityAddress))
640
+ this._identityReadsToRetry.set(communityAddress, IDENTITY_READ_RETRIES);
641
+ if (!existing || existing.publicKey !== publicKey || existing.fileId !== fileId) {
642
+ this._upsertIdentity.run(communityAddress, publicKey, fileId, lookupKeyOf(communityAddress));
643
+ this._recordChange(communityAddress);
644
+ }
645
+ else if (this._onChange)
646
+ this._mirrorRow(communityAddress, existing); // written by another instance
647
+ return this._selectRow.get(communityAddress);
648
+ });
649
+ }
650
+ _selectRowsByLookupKeyOrPublicKey({ lookupKeys, publicKeys }) {
651
+ const key = `${lookupKeys.length}:${publicKeys.length}`;
652
+ let statement = this._lookupStatements.get(key);
653
+ if (!statement) {
654
+ const placeholders = (count) => Array.from({ length: count }, () => "?").join(", ");
655
+ statement = this._db.prepare(`SELECT address, publicKey, fileId, startedBy FROM ${COMMUNITIES_TABLE}
656
+ WHERE lookupKey IN (${placeholders(lookupKeys.length)}) OR publicKey IN (${placeholders(publicKeys.length)})
657
+ ORDER BY address`);
658
+ this._lookupStatements.set(key, statement);
659
+ }
660
+ return statement.all(...lookupKeys, ...publicKeys);
661
+ }
662
+ _isOtherInstanceAliveNow(instanceId) {
663
+ return isInstanceLockHeldSync(getInstanceLockPath({ dataPath: this.dataPath, instanceId }));
664
+ }
665
+ // One event of the watcher that names its file
666
+ _onFileEvent(eventType, filename) {
667
+ if (isIgnoredFilename(filename))
668
+ return;
669
+ const dbFilePath = getDbFilePath(this.dataPath, filename);
670
+ if (filesBeingWrittenByThisProcess.has(path.resolve(dbFilePath)))
671
+ return;
672
+ const row = this._rows.get(filename);
673
+ // A write to a DB that is listed changes nothing the registry holds, and every started community writes to its
674
+ // DB at each checkpoint. A "rename" is the file appearing or disappearing
675
+ if (row && row.publicKey !== null && eventType !== "rename")
676
+ return;
677
+ const fileId = getFileId(dbFilePath);
678
+ if (fileId === undefined) {
679
+ // gone, or not a file. Asked of the table, not the copy: another instance may have registered it
680
+ if (row || this._selectRow.get(filename))
681
+ this._removeRowIfFileIsGone(filename);
682
+ return;
683
+ }
684
+ if (row && row.publicKey !== null && row.fileId === fileId)
685
+ return; // the file this instance knows
686
+ this._registerFile(filename);
687
+ }
688
+ // The one place that lists the directory. Registers the files that have no row, removes the rows that have no file,
689
+ // and reads again the identity of the DBs that had none
690
+ _reconcileWithDirectory() {
691
+ const communitiesPath = path.join(this.dataPath, "communities");
692
+ const filenames = new Set();
693
+ for (const dirent of readdirSync(communitiesPath, { withFileTypes: true })) {
694
+ if (LEGACY_START_LOCK_SUFFIXES.some((suffix) => dirent.name.endsWith(suffix))) {
695
+ // the lock of the design before this one: a file or a directory per community
696
+ try {
697
+ rmSync(path.join(communitiesPath, dirent.name), { recursive: true, force: true });
698
+ }
699
+ catch (error) {
700
+ this._log.error("Failed to remove the start lock of an older version", dirent.name, error);
701
+ }
702
+ continue;
703
+ }
704
+ // Only regular files can be community DBs. Subdirectories live here too (`deleted/`, `.backup_before_migration/`)
705
+ if (dirent.isFile() && !isIgnoredFilename(dirent.name))
706
+ filenames.add(dirent.name);
707
+ }
708
+ // In steps, each its own write transaction: registering a file opens it, and the first PKC on a data path of an
709
+ // older version registers every file. As one transaction that kept every other process from writing to
710
+ // storage.db for longer than SQLite waits (5 s), which fails a start() there. A file is still read inside the
711
+ // transaction that writes its row (see _registerFile)
712
+ const filenamesInOrder = [...filenames];
713
+ for (let i = 0; i < filenamesInOrder.length; i += COMMUNITIES_REGISTRY_RECONCILE_BATCH_SIZE)
714
+ this._write(() => {
715
+ for (const filename of filenamesInOrder.slice(i, i + COMMUNITIES_REGISTRY_RECONCILE_BATCH_SIZE)) {
716
+ const dbFilePath = getDbFilePath(this.dataPath, filename);
717
+ if (filesBeingWrittenByThisProcess.has(path.resolve(dbFilePath)))
718
+ continue;
719
+ const row = this._selectRow.get(filename);
720
+ if (!row || row.publicKey === null || row.fileId !== getFileId(dbFilePath))
721
+ this._registerFile(filename);
722
+ else if (this._onChange)
723
+ this._mirrorRow(filename, row);
724
+ }
725
+ });
726
+ this._write(() => {
727
+ for (const { address } of this._selectAllRows.all()) {
728
+ if (filenames.has(address))
729
+ continue;
730
+ if (isPlainFilename(address))
731
+ this._removeRowIfFileIsGone(address);
732
+ else
733
+ this._removeRow(address); // never the row of a file in this directory
734
+ }
735
+ });
736
+ }
737
+ // What the timer does for the DBs whose identity could not be read for a reason that may pass
738
+ _readAgainIdentitiesThatFailedToBeRead() {
739
+ for (const [address, retriesLeft] of [...this._identityReadsToRetry]) {
740
+ try {
741
+ this._registerFile(address);
742
+ }
743
+ catch (error) {
744
+ this._log.error("Failed to read again the identity of community DB", address, error);
745
+ }
746
+ if (!this._identityReadsToRetry.has(address))
747
+ continue; // read, or not a community DB any more
748
+ if (retriesLeft <= 1)
749
+ this._identityReadsToRetry.delete(address);
750
+ else
751
+ this._identityReadsToRetry.set(address, retriesLeft - 1);
752
+ }
753
+ }
754
+ // The lock files of instances that died without removing theirs
755
+ _sweepInstanceLocksOfDeadInstances() {
756
+ const locksPath = getInstanceLocksPath(this.dataPath);
757
+ let filenames;
758
+ try {
759
+ filenames = readdirSync(locksPath);
760
+ }
761
+ catch {
762
+ return;
763
+ }
764
+ for (const filename of filenames) {
765
+ const instanceId = instanceIdOfLockFile(filename);
766
+ if (instanceId === undefined || instanceId === this.instanceId)
767
+ continue;
768
+ const lockPath = path.join(locksPath, filename);
769
+ try {
770
+ if (Date.now() - statSync(lockPath).mtimeMs < INSTANCE_LOCK_MIN_AGE_TO_SWEEP_MS)
771
+ continue;
772
+ if (!isInstanceLockHeldSync(lockPath))
773
+ rmSync(lockPath, { force: true });
774
+ }
775
+ catch (error) {
776
+ this._log.error("Failed to check the lock file of another PKC instance", lockPath, error);
777
+ }
778
+ }
779
+ }
780
+ // Tries the lock of every other instance that has communities started, and releases the communities of those that
781
+ // are gone
782
+ _clearDeadInstances() {
783
+ for (const instanceId of [...this._startedCountByInstance.keys()]) {
784
+ if (instanceId === this.instanceId)
785
+ continue;
786
+ const alive = this._isOtherInstanceAliveNow(instanceId);
787
+ this._otherInstancesAlive.set(instanceId, alive);
788
+ if (alive)
789
+ continue;
790
+ this._write(() => {
791
+ // tried again inside the write transaction, where no start() of that instance can be half done
792
+ if (this._isOtherInstanceAliveNow(instanceId))
793
+ return;
794
+ this._insertChangesOfInstance.run(instanceId);
795
+ this._clearInstance.run(instanceId);
796
+ });
797
+ for (const row of [...this._rows.values()])
798
+ if (row.startedBy === instanceId)
799
+ this._mirrorRow(row.address, this._selectRow.get(row.address), { startedMayHaveChanged: true });
800
+ rmSync(getInstanceLockPath({ dataPath: this.dataPath, instanceId }), { force: true });
801
+ }
802
+ for (const instanceId of [...this._otherInstancesAlive.keys()])
803
+ if (!this._startedCountByInstance.has(instanceId))
804
+ this._otherInstancesAlive.delete(instanceId);
805
+ }
806
+ _reloadAllRows() {
807
+ this._db.transaction(() => {
808
+ this._lastSeq = this._selectChangeBounds.get().maxSeq ?? 0;
809
+ const rows = this._selectAllRows.all();
810
+ this._rows = new Map(rows.map((row) => [row.address, row]));
811
+ })();
812
+ this._startedCountByInstance.clear();
813
+ for (const row of this._rows.values())
814
+ if (row.startedBy !== null)
815
+ this._startedCountByInstance.set(row.startedBy, (this._startedCountByInstance.get(row.startedBy) ?? 0) + 1);
816
+ this._sortedAddresses = [...this._rows.values()]
817
+ .filter((row) => row.publicKey !== null)
818
+ .map((row) => row.address)
819
+ .sort();
820
+ this._entries = this._sortedAddresses.map((address) => this._entryOfRow(this._rows.get(address)));
821
+ this._listIsOutdated = true;
822
+ }
823
+ // `started` of this address changed in this instance's list without its row changing (see releaseStart)
824
+ _mirrorStartedAgain(communityAddress) {
825
+ const row = this._rows.get(communityAddress);
826
+ if (this._onChange && row)
827
+ this._mirrorRow(communityAddress, row, { startedMayHaveChanged: true });
828
+ }
829
+ // The entry of pkc.communities for a row, or undefined for a row that is not listed
830
+ _entryOfRow(row) {
831
+ if (!row || row.publicKey === null)
832
+ return undefined;
833
+ return toCommunitiesEntry({ ...identityOfRow({ ...row, publicKey: row.publicKey }), started: this._isRowStarted(row) });
834
+ }
835
+ // Applies the current row of one address (undefined: it has none) to this instance's copy
836
+ _mirrorRow(communityAddress, row, { startedMayHaveChanged = false } = {}) {
837
+ const before = this._rows.get(communityAddress);
838
+ if (!startedMayHaveChanged &&
839
+ Boolean(before) === Boolean(row) &&
840
+ before?.publicKey === row?.publicKey &&
841
+ before?.startedBy === row?.startedBy &&
842
+ before?.fileId === row?.fileId)
843
+ return;
844
+ if (before?.startedBy) {
845
+ const count = (this._startedCountByInstance.get(before.startedBy) ?? 1) - 1;
846
+ if (count <= 0)
847
+ this._startedCountByInstance.delete(before.startedBy);
848
+ else
849
+ this._startedCountByInstance.set(before.startedBy, count);
850
+ }
851
+ if (row?.startedBy)
852
+ this._startedCountByInstance.set(row.startedBy, (this._startedCountByInstance.get(row.startedBy) ?? 0) + 1);
853
+ if (row)
854
+ this._rows.set(communityAddress, row);
855
+ else
856
+ this._rows.delete(communityAddress);
857
+ const wasListed = before !== undefined && before.publicKey !== null;
858
+ const entry = this._entryOfRow(row);
859
+ if (!wasListed && !entry)
860
+ return;
861
+ const index = this._indexOfSortedAddress(communityAddress);
862
+ if (!wasListed && entry) {
863
+ this._sortedAddresses.splice(index, 0, communityAddress);
864
+ this._entries.splice(index, 0, entry);
865
+ }
866
+ else if (wasListed && !entry) {
867
+ this._sortedAddresses.splice(index, 1);
868
+ this._entries.splice(index, 1);
869
+ }
870
+ else if (entry) {
871
+ const listed = this._entries[index];
872
+ if (listed.publicKey === entry.publicKey && listed.started === entry.started)
873
+ return;
874
+ this._entries[index] = entry;
875
+ }
876
+ this._listIsOutdated = true;
877
+ }
878
+ // Where this address is in the sorted list, or where it belongs when it is not in it
879
+ _indexOfSortedAddress(communityAddress) {
880
+ let low = 0;
881
+ let high = this._sortedAddresses.length;
882
+ while (low < high) {
883
+ const middle = (low + high) >>> 1;
884
+ if (this._sortedAddresses[middle] < communityAddress)
885
+ low = middle + 1;
886
+ else
887
+ high = middle;
888
+ }
889
+ return low;
890
+ }
891
+ _isRowStarted(row) {
892
+ if (row.startedBy === null)
893
+ return false;
894
+ if (row.startedBy === this.instanceId)
895
+ return !this._releasesToWriteAgain.has(row.address);
896
+ let alive = this._otherInstancesAlive.get(row.startedBy);
897
+ if (alive === undefined) {
898
+ alive = this._isOtherInstanceAliveNow(row.startedBy);
899
+ this._otherInstancesAlive.set(row.startedBy, alive);
900
+ }
901
+ return alive;
902
+ }
903
+ _emitListIfOutdated() {
904
+ if (!this._listIsOutdated || !this._onChange || this._db.inTransaction)
905
+ return;
906
+ this._listIsOutdated = false;
907
+ try {
908
+ // A copy: this array keeps changing, and what a PKC was given as its list must not
909
+ this._onChange(this._entries.slice());
910
+ }
911
+ catch (error) {
912
+ // A `communitieschange` listener of the user threw. Whatever changed the list (a start, a stop, a creation)
913
+ // has been written, and must not fail on it: a start that threw here kept a claim nothing released
914
+ this._log.error("A listener of the list of local communities threw", error);
915
+ }
916
+ }
917
+ }
918
+ // Whether a live PKC instance has the community started, asked without being an instance: by a tool, a test, or a
919
+ // process that only wants to know. Reads the registry and tries the lock of the instance it names
920
+ export function isCommunityStartLockedSync({ dataPath, communityAddress }) {
921
+ const storagePath = path.join(dataPath, "storage.db");
922
+ if (!existsSync(storagePath))
923
+ return false;
924
+ let startedBy;
925
+ const db = new Database(storagePath, { readonly: true, fileMustExist: true });
926
+ try {
927
+ startedBy = db.prepare(`SELECT startedBy FROM ${COMMUNITIES_TABLE} WHERE address = ?`).get(communityAddress)?.startedBy;
928
+ }
929
+ catch (e) {
930
+ // a data path no PKC instance has kept communities in yet
931
+ if (e instanceof Error && e.message.includes("no such table"))
932
+ return false;
933
+ throw e;
934
+ }
935
+ finally {
936
+ db.close();
937
+ }
938
+ if (typeof startedBy !== "string")
939
+ return false;
940
+ return isInstanceLockHeldSync(getInstanceLockPath({ dataPath, instanceId: startedBy }));
941
+ }
942
+ export async function isCommunityStartLocked(args) {
943
+ return isCommunityStartLockedSync(args);
944
+ }
945
+ // One registry per PKC instance, made when it is first asked for. Keyed by the object, so that a test may stand in for
946
+ // a PKC with any object that has a dataPath
947
+ const registries = new WeakMap();
948
+ export function getCommunitiesRegistry(pkc) {
949
+ let registry = registries.get(pkc);
950
+ if (!registry) {
951
+ if (typeof pkc.dataPath !== "string")
952
+ throw Error("pkc.dataPath needs to be defined to keep local communities");
953
+ registry = new CommunitiesRegistry({ dataPath: pkc.dataPath });
954
+ registries.set(pkc, registry);
955
+ }
956
+ return registry;
957
+ }
958
+ // Closes the registry of an object that stood in for a PKC and forgets it, so its connection to storage.db does not
959
+ // outlive it. A PKC closes its own when it is destroyed
960
+ export function closeCommunitiesRegistry(pkc) {
961
+ registries.get(pkc)?.close();
962
+ registries.delete(pkc);
963
+ }
964
+ //# sourceMappingURL=communities-registry.js.map