@pkcprotocol/pkc-js 0.0.149 → 0.0.150

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 (76) hide show
  1. package/dist/browser/errors.d.ts +1 -0
  2. package/dist/browser/errors.js +1 -0
  3. package/dist/browser/errors.js.map +1 -1
  4. package/dist/browser/generated-version.d.ts +1 -1
  5. package/dist/browser/generated-version.js +1 -1
  6. package/dist/browser/helia/helia-for-pkc.js +15 -10
  7. package/dist/browser/helia/helia-for-pkc.js.map +1 -1
  8. package/dist/browser/helia/util.d.ts +3 -2
  9. package/dist/browser/helia/util.js +17 -7
  10. package/dist/browser/helia/util.js.map +1 -1
  11. package/dist/browser/pkc-error.d.ts +1 -1
  12. package/dist/browser/runtime/node/community/local-community/cleanup.js +3 -0
  13. package/dist/browser/runtime/node/community/local-community/cleanup.js.map +1 -1
  14. package/dist/browser/runtime/node/community/local-community/comment-updates.js +30 -62
  15. package/dist/browser/runtime/node/community/local-community/comment-updates.js.map +1 -1
  16. package/dist/browser/runtime/node/community/local-community/post-updates-bucket.d.ts +7 -5
  17. package/dist/browser/runtime/node/community/local-community/post-updates-bucket.js +122 -121
  18. package/dist/browser/runtime/node/community/local-community/post-updates-bucket.js.map +1 -1
  19. package/dist/browser/runtime/node/community/local-community/unixfs-directory-patch.d.ts +20 -0
  20. package/dist/browser/runtime/node/community/local-community/unixfs-directory-patch.js +231 -0
  21. package/dist/browser/runtime/node/community/local-community/unixfs-directory-patch.js.map +1 -0
  22. package/dist/browser/runtime/node/community/local-community.d.ts +1 -1
  23. package/dist/browser/runtime/node/community/local-community.js +3 -4
  24. package/dist/browser/runtime/node/community/local-community.js.map +1 -1
  25. package/dist/browser/util.d.ts +1 -12
  26. package/dist/browser/util.js +0 -53
  27. package/dist/browser/util.js.map +1 -1
  28. package/dist/bundled/bundle-manifest.json +135 -121
  29. package/dist/bundled/challenges.js +1 -1
  30. package/dist/bundled/chunks/{helia-for-pkc-8iett8xl.js → helia-for-pkc-1sdkdugl.js} +43 -42
  31. package/dist/bundled/chunks/{local-community-ChZZa9bm.js → local-community-BGml0_JD.js} +1 -1
  32. package/dist/bundled/chunks/{local-community-BlBIYSsF.js → local-community-Dadvhqoi.js} +406 -188
  33. package/dist/bundled/chunks/{node-BH_HrtON.js → node-DOdTF4o2.js} +5 -5
  34. package/dist/bundled/chunks/{page-sort-scoring-NpdjWYfa.js → page-sort-scoring-DozAWSgg.js} +1 -1
  35. package/dist/bundled/chunks/{rpc-local-community-Byj5ZmMa.js → rpc-local-community-DaCMetml.js} +3 -3
  36. package/dist/bundled/chunks/src-66iuMY_4.js +2 -0
  37. package/dist/bundled/chunks/{src-evzEHW9W.js → src-BSYNGtIQ.js} +2 -44
  38. package/dist/bundled/chunks/{src-CNab3O7M.js → src-CAvdjq_i.js} +2 -2
  39. package/dist/bundled/chunks/{src-Bj5iE3qB.js → src-DIOHVUq9.js} +5 -4
  40. package/dist/bundled/chunks/src-DeIT_BDx.js +44 -0
  41. package/dist/bundled/chunks/{src-ltPxiZKf.js → src-NvrGEL7T.js} +2 -1
  42. package/dist/bundled/chunks/{util-DmmLFRbV.js → util-B9XQRGR7.js} +19 -7
  43. package/dist/bundled/chunks/{util-CUZ1U2Go.js → util-BUFRgvXt.js} +4 -45
  44. package/dist/bundled/chunks/{validate-package-factories-CkU4qFQx.js → validate-package-factories-NPflVcyZ.js} +2 -2
  45. package/dist/bundled/index.js +1 -1
  46. package/dist/bundled/page-sorts.js +1 -1
  47. package/dist/bundled/rpc/src/index.js +4 -4
  48. package/dist/node/errors.d.ts +1 -0
  49. package/dist/node/errors.js +1 -0
  50. package/dist/node/errors.js.map +1 -1
  51. package/dist/node/generated-version.d.ts +1 -1
  52. package/dist/node/generated-version.js +1 -1
  53. package/dist/node/helia/helia-for-pkc.js +15 -10
  54. package/dist/node/helia/helia-for-pkc.js.map +1 -1
  55. package/dist/node/helia/util.d.ts +3 -2
  56. package/dist/node/helia/util.js +17 -7
  57. package/dist/node/helia/util.js.map +1 -1
  58. package/dist/node/pkc-error.d.ts +1 -1
  59. package/dist/node/runtime/node/community/local-community/cleanup.js +3 -0
  60. package/dist/node/runtime/node/community/local-community/cleanup.js.map +1 -1
  61. package/dist/node/runtime/node/community/local-community/comment-updates.js +30 -62
  62. package/dist/node/runtime/node/community/local-community/comment-updates.js.map +1 -1
  63. package/dist/node/runtime/node/community/local-community/post-updates-bucket.d.ts +7 -5
  64. package/dist/node/runtime/node/community/local-community/post-updates-bucket.js +122 -121
  65. package/dist/node/runtime/node/community/local-community/post-updates-bucket.js.map +1 -1
  66. package/dist/node/runtime/node/community/local-community/unixfs-directory-patch.d.ts +20 -0
  67. package/dist/node/runtime/node/community/local-community/unixfs-directory-patch.js +231 -0
  68. package/dist/node/runtime/node/community/local-community/unixfs-directory-patch.js.map +1 -0
  69. package/dist/node/runtime/node/community/local-community.d.ts +1 -1
  70. package/dist/node/runtime/node/community/local-community.js +3 -4
  71. package/dist/node/runtime/node/community/local-community.js.map +1 -1
  72. package/dist/node/util.d.ts +1 -12
  73. package/dist/node/util.js +0 -53
  74. package/dist/node/util.js.map +1 -1
  75. package/package.json +3 -1
  76. package/dist/bundled/chunks/src-BC60-Q7v.js +0 -2
@@ -1,6 +1,8 @@
1
1
  import { CID } from "multiformats/cid";
2
2
  import Logger from "../../../../logger.js";
3
+ import { PKCError } from "../../../../pkc-error.js";
3
4
  import { statMfsPathSafely } from "../../../../util.js";
5
+ import { patchUnixFsDirectory } from "./unixfs-directory-patch.js";
4
6
  // Time budget for each MFS and import call: a repo gc holds MFS writes off for its whole run (kubo
5
7
  // 0.43), and on a large repo that is minutes, not seconds.
6
8
  const MFS_OP_TIMEOUT_MS = 10 * 60 * 1000;
@@ -8,13 +10,8 @@ const MFS_OP_TIMEOUT_MS = 10 * 60 * 1000;
8
10
  // (name + cid, boxo's SizeEstimationLinks), then a HAMT with 256-wide shards
9
11
  const MFS_SHARD_SPLIT_THRESHOLD_BYTES = 256 * 1024;
10
12
  export const POST_UPDATES_BUCKET_NEXT_SUFFIX = ".next";
11
- // A bucket is rebuilt when a slice has at least this many posts in it; below that the files are
12
- // written one by one. The rebuild's fixed cost is reading the bucket's links and building its
13
- // directory (about 2 s for 17,857 posts, less for a basic directory), the per-file write costs about
14
- // 20 ms of daemon CPU on a sharded bucket (ipfs/boxo#1226) and well under 1 ms on a basic one, so
15
- // the two meet at a couple of hundred posts; the 1M-comment bench (17,857 posts, 2,000-row slices)
16
- // ran with this value. An instance field on LocalCommunity so a test can lower it.
17
- export const POST_UPDATES_NODE_BUILT_BUCKET_MIN_POSTS = 200;
13
+ // How many times a bucket is swapped in before giving up on MFS holding what was swapped
14
+ const MAX_ATTEMPTS_TO_SWAP_POST_UPDATES_BUCKET = 4;
18
15
  const isAbsentPathError = (error) => error instanceof Error && error.message.includes("file does not exist");
19
16
  async function statMfsPathOrUndefined(kuboRpcClient, path, log) {
20
17
  try {
@@ -26,50 +23,9 @@ async function statMfsPathOrUndefined(kuboRpcClient, path, log) {
26
23
  throw error;
27
24
  }
28
25
  }
29
- // The entries of a UnixFS directory as its dag-pb links (name, cid and the link's Tsize), walking the
30
- // shards of a HAMT. `ipfs ls` reports a size of 0 for a directory entry whether or not it resolves
31
- // the children, and the entries here are the posts' directories, so the links are read from the
32
- // blocks themselves to carry their Tsize over unchanged.
33
- async function listUnixFsDirectoryLinks(kubo, directoryCid) {
34
- const { UnixFS } = await import("ipfs-unixfs");
35
- const links = [];
36
- const walk = async (cid) => {
37
- const node = (await kubo.dag.get(cid, { timeout: MFS_OP_TIMEOUT_MS })).value;
38
- if (!isPbNode(node))
39
- throw Error(`Expected a dag-pb directory node at ${cid.toString()}`);
40
- const unixfs = UnixFS.unmarshal(node.Data);
41
- if (unixfs.type === "hamt-sharded-directory") {
42
- // A shard names its links <2 hex chars of the bucket index><entry name>; a bare index is a sub-shard
43
- const prefixLength = Math.max(1, Math.ceil(Math.log2(Number(unixfs.fanout ?? 256)) / 4));
44
- for (const link of node.Links) {
45
- if (link.Name.length === prefixLength)
46
- await walk(link.Hash);
47
- else
48
- links.push({ name: link.Name.slice(prefixLength), cid: link.Hash, size: BigInt(link.Tsize ?? 0) });
49
- }
50
- }
51
- else if (unixfs.type === "directory") {
52
- for (const link of node.Links)
53
- links.push({ name: link.Name, cid: link.Hash, size: BigInt(link.Tsize ?? 0) });
54
- }
55
- else
56
- throw Error(`Expected a UnixFS directory at ${cid.toString()}, got ${unixfs.type}`);
57
- };
58
- await walk(directoryCid);
59
- return links;
60
- }
61
- function isPbNode(value) {
62
- if (typeof value !== "object" || value === null)
63
- return false;
64
- const node = value;
65
- return (node.Data instanceof Uint8Array &&
66
- Array.isArray(node.Links) &&
67
- node.Links.every((link) => typeof link?.Name === "string" && (link.Tsize === undefined || typeof link.Tsize === "number") && link.Hash instanceof CID));
68
- }
69
- // Builds the bucket directory: a `<postCid>/update` file per changed post, and every other entry linked
70
- // as the live bucket links it. Returns the bucket's root and every block that does not exist yet (the
71
- // changed posts' files and directories, and the bucket's own node or shards).
72
- async function buildPostUpdatesBucketDag({ existingLinks, changedPosts }) {
26
+ // The posts' `<postCid>/update` files, as the bucket's entries for them (each a `<postCid>` directory
27
+ // holding the file) and the blocks those are made of
28
+ async function buildPostUpdateFiles(posts) {
73
29
  const { importer } = await import("ipfs-unixfs-importer");
74
30
  const blocks = new Map();
75
31
  const blockstore = {
@@ -78,50 +34,24 @@ async function buildPostUpdatesBucketDag({ existingLinks, changedPosts }) {
78
34
  return cid;
79
35
  }
80
36
  };
37
+ const entries = [];
81
38
  // The same layout kubo's MFS gives files written into it: CIDv0, dag-pb leaves of 256 KiB, 174 links per node
82
- const layoutOptions = {
39
+ for await (const entry of importer(posts.map((post) => ({ path: `${post.postCid}/update`, content: post.updateFileBytes })), blockstore, {
83
40
  profile: "unixfs-v0-2015",
84
41
  cidVersion: 0,
85
42
  rawLeaves: false,
86
43
  reduceSingleLeafToSelf: true,
87
- shardSplitThresholdBytes: MFS_SHARD_SPLIT_THRESHOLD_BYTES
88
- };
89
- // The changed posts' `<postCid>/update` files and their `<postCid>` directories
90
- const postDirectoryLinks = new Map();
91
- for await (const entry of importer(changedPosts.map((post) => ({ path: `${post.postCid}/update`, content: post.updateFileBytes })), blockstore, { ...layoutOptions, wrapWithDirectory: false }))
92
- if (entry.path && !entry.path.includes("/"))
93
- postDirectoryLinks.set(entry.path, { name: entry.path, cid: entry.cid, size: entry.size });
94
- if (postDirectoryLinks.size !== changedPosts.length)
95
- throw Error(`Built ${postDirectoryLinks.size} post directories for ${changedPosts.length} changed posts`);
96
- // The bucket itself: every entry is a known link, so the file builder just hands the link back instead
97
- // of building anything. The importer only looks at the links' names and cids to decide on sharding.
98
- const bucketName = "bucket";
99
- const knownLinks = new Map();
100
- for (const link of existingLinks)
101
- knownLinks.set(`${bucketName}/${link.name}`, link);
102
- for (const link of postDirectoryLinks.values())
103
- knownLinks.set(`${bucketName}/${link.name}`, link);
104
- let root;
105
- for await (const entry of importer([...knownLinks.keys()].map((path) => ({ path, content: new Uint8Array(0) })), blockstore, {
106
- ...layoutOptions,
107
- wrapWithDirectory: false,
108
- fileBuilder: async (file) => {
109
- for await (const chunk of file.content)
110
- void chunk;
111
- const link = file.path ? knownLinks.get(file.path) : undefined;
112
- if (!link)
113
- throw Error(`No known link for bucket entry ${file.path}`);
114
- return { cid: link.cid, size: link.size, path: file.path };
115
- }
44
+ shardSplitThresholdBytes: MFS_SHARD_SPLIT_THRESHOLD_BYTES,
45
+ wrapWithDirectory: false
116
46
  }))
117
- if (entry.path === bucketName)
118
- root = entry.cid;
119
- if (!root)
120
- throw Error("The rebuilt postUpdates bucket has no root");
121
- return { root, blocks: [...blocks.values()] };
47
+ if (entry.path && !entry.path.includes("/"))
48
+ entries.push({ name: entry.path, cid: entry.cid, size: Number(entry.size) });
49
+ if (entries.length !== posts.length)
50
+ throw Error(`Built ${entries.length} post directories for ${posts.length} posts`);
51
+ return { entries, blocks: [...blocks.values()] };
122
52
  }
123
- // A CARv1: a dag-cbor header naming the root, then each block as varint(length) + cid bytes + block bytes
124
- async function encodeCarV1(root, blocks) {
53
+ // A CARv1: a dag-cbor header naming the roots, then each block as varint(length) + cid bytes + block bytes
54
+ export async function encodeCarV1(roots, blocks) {
125
55
  const dagCbor = await import("@ipld/dag-cbor");
126
56
  const varint = (value) => {
127
57
  const out = [];
@@ -132,7 +62,7 @@ async function encodeCarV1(root, blocks) {
132
62
  out.push(value);
133
63
  return Uint8Array.from(out);
134
64
  };
135
- const header = dagCbor.encode({ roots: [root], version: 1 });
65
+ const header = dagCbor.encode({ roots, version: 1 });
136
66
  const parts = [varint(header.length), header];
137
67
  for (const { cid, bytes } of blocks)
138
68
  parts.push(varint(cid.bytes.length + bytes.length), cid.bytes, bytes);
@@ -144,6 +74,33 @@ async function encodeCarV1(root, blocks) {
144
74
  }
145
75
  return car;
146
76
  }
77
+ // What the import pins while a bucket is being swapped in: one or more manifest nodes that link the blocks
78
+ // the swap adds, and nothing else.
79
+ //
80
+ // Pinning the new bucket's root instead, which is what a CAR import offers, makes the daemon walk the whole
81
+ // bucket to pin it: 195 ms of a 213 ms write of one post into a bucket of 18,000. And the root cannot be
82
+ // pinned before its blocks are there (`block put --pin` does that without a walk): a pin whose blocks are
83
+ // missing makes every repo gc on the daemon abort and `pin ls` hang, for as long as it exists, and a cycle
84
+ // cut off mid-import leaves it behind.
85
+ //
86
+ // A manifest links each changed post's directory, which the pin follows down to the post's file, and each
87
+ // rebuilt node of the bucket's own directory as a raw block. The same bytes under the raw codec are a leaf
88
+ // to the pinner, so it does not follow them into the rest of the bucket, and they are the same block to
89
+ // the daemon, whose blockstore and gc go by multihash. The pin is complete the moment the import returns,
90
+ // and one left behind by a process that died holds this swap's new blocks and no more.
91
+ const SWAP_PIN_MANIFEST_MAX_LINKS = 4000; // about 160 KiB a manifest
92
+ const RAW_CODEC = 0x55;
93
+ async function buildSwapPinManifests({ postEntries, directoryNodes }) {
94
+ const dagPb = await import("@ipld/dag-pb");
95
+ const { sha256 } = await import("multiformats/hashes/sha2");
96
+ const pinned = [...postEntries.map((entry) => entry.cid), ...directoryNodes.map((node) => CID.createV1(RAW_CODEC, node.cid.multihash))];
97
+ const manifests = [];
98
+ for (let index = 0; index < pinned.length; index += SWAP_PIN_MANIFEST_MAX_LINKS) {
99
+ const bytes = dagPb.encode(dagPb.prepare({ Links: pinned.slice(index, index + SWAP_PIN_MANIFEST_MAX_LINKS).map((cid) => ({ Name: "", Hash: cid })) }));
100
+ manifests.push({ cid: CID.createV1(dagPb.code, await sha256.digest(bytes)), bytes });
101
+ }
102
+ return manifests;
103
+ }
147
104
  // Finishes or discards a swap that an earlier process left half done. Returns the live bucket's stat,
148
105
  // or undefined when the bucket does not exist yet.
149
106
  async function recoverInterruptedBucketSwap(kuboRpcClient, bucketPath, log) {
@@ -161,46 +118,90 @@ async function recoverInterruptedBucketSwap(kuboRpcClient, bucketPath, log) {
161
118
  // The swap stopped between taking the live bucket down and moving the new one in
162
119
  log(`Finishing the interrupted swap of ${nextPath} into ${bucketPath}`);
163
120
  await kubo.files.mv(nextPath, bucketPath, { flush: true, timeout: MFS_OP_TIMEOUT_MS });
164
- live = next;
121
+ // Read back like any other swap: the caller takes what this returns for what MFS holds
122
+ live = await statMfsPathOrUndefined(kuboRpcClient, bucketPath, log);
123
+ if (!live?.cid.equals(next.cid))
124
+ throw Error(`MFS holds ${live?.cid.toString()} at ${bucketPath} after the interrupted swap of ${next.cid.toString()} was finished`);
165
125
  }
166
- // Its root was pinned for the swap and never unpinned
167
- await kubo.pin.rm(next.cid, { timeout: MFS_OP_TIMEOUT_MS }).catch(() => undefined);
168
126
  }
169
127
  return live;
170
128
  }
171
- // Writes one slice's posts into one bucket by rebuilding the bucket. Returns the posts the bucket kept
172
- // from before, so the caller can re-check them against the DB the way it re-checks the slice's own posts.
173
- export async function rebuildPostUpdatesBucket({ community, bucketPath, posts }) {
174
- const log = Logger("pkc-js:local-community:sync:rebuildPostUpdatesBucket");
129
+ // Writes the given posts' CommentUpdate files into one bucket, and returns once MFS holds them.
130
+ export async function writePostUpdatesToBucket({ community, bucketPath, posts }) {
131
+ const log = Logger("pkc-js:local-community:sync:writePostUpdatesToBucket");
175
132
  const kuboRpcClient = community._clientsManager.getDefaultKuboRpcClient();
176
133
  const kubo = kuboRpcClient._client;
177
134
  const nextPath = bucketPath + POST_UPDATES_BUCKET_NEXT_SUFFIX;
178
- const live = await recoverInterruptedBucketSwap(kuboRpcClient, bucketPath, log);
179
- const changedPostCids = new Set(posts.map((post) => post.postCid));
180
- // A post purged since the live bucket was written is gone from the DB, and its entry is being removed
181
- // by the purge (or sits in _mfsPathsToRemove): it must not be carried into the new bucket
182
- const existingLinks = live
183
- ? (await listUnixFsDirectoryLinks(kubo, live.cid)).filter((link) => !changedPostCids.has(link.name) && community._dbHandler.commentExistsInDb(link.name))
184
- : [];
185
- const { root, blocks } = await buildPostUpdatesBucketDag({ existingLinks, changedPosts: posts });
186
- const car = await encodeCarV1(root, blocks);
187
- for await (const result of kubo.dag.import([car], { pinRoots: true, timeout: MFS_OP_TIMEOUT_MS }))
188
- if (result.root.pinErrorMsg)
189
- throw Error(`Failed to pin the rebuilt bucket ${root.toString()}: ${result.root.pinErrorMsg}`);
190
- log(`Built bucket ${bucketPath} in node: ${posts.length} posts written, ${existingLinks.length} kept, ${blocks.length} new blocks (${car.length} bytes), root ${root.toString()}`);
191
- try {
192
- // Every step flushes: the new bucket must be on disk under the MFS root before the live one goes
193
- await kubo.files.cp(`/ipfs/${root.toString()}`, nextPath, { parents: true, flush: true, timeout: MFS_OP_TIMEOUT_MS });
135
+ const { entries, blocks: fileBlocks } = await buildPostUpdateFiles(posts);
136
+ // The bucket's nodes read from the daemon and the ones built here, so a later attempt reads nothing twice
137
+ const bucketBlocks = new Map();
138
+ const getBlock = async (cid) => {
139
+ const key = cid.toString();
140
+ let bytes = bucketBlocks.get(key);
141
+ if (!bytes) {
142
+ bytes = await kubo.block.get(cid, { timeout: MFS_OP_TIMEOUT_MS });
143
+ bucketBlocks.set(key, bytes);
144
+ }
145
+ return bytes;
146
+ };
147
+ let live = await recoverInterruptedBucketSwap(kuboRpcClient, bucketPath, log);
148
+ let bucketExisted = false;
149
+ for (let attempt = 1;; attempt++) {
194
150
  if (live)
195
- await kubo.files.rm(bucketPath, { recursive: true, timeout: MFS_OP_TIMEOUT_MS });
196
- await kubo.files.mv(nextPath, bucketPath, { flush: true, timeout: MFS_OP_TIMEOUT_MS });
197
- }
198
- finally {
199
- // Referenced from the MFS root now (or abandoned beside it, where the next write cleans it up)
200
- await kubo.pin
201
- .rm(root, { timeout: MFS_OP_TIMEOUT_MS })
202
- .catch((error) => log.error(`Failed to unpin the rebuilt bucket root ${root.toString()}`, error));
151
+ bucketExisted = true;
152
+ // A bucket that existed and is gone must not be answered by building one that holds these posts only
153
+ else if (bucketExisted)
154
+ throw new PKCError("ERR_POST_UPDATES_BUCKET_SWAP_WAS_LOST", { communityAddress: community.address, bucketPath, attempt });
155
+ const { cid: root, newBlocks } = await patchUnixFsDirectory({
156
+ directoryCid: live?.cid,
157
+ entriesToPut: entries,
158
+ getBlock,
159
+ shardSplitThresholdBytes: MFS_SHARD_SPLIT_THRESHOLD_BYTES
160
+ });
161
+ // The bucket in MFS links every post's new file already: nothing to write, or a swap whose result
162
+ // differs from what was swapped in only by what somebody else changed since (a purge removing its post)
163
+ if (live && root.equals(live.cid))
164
+ return;
165
+ if (attempt > MAX_ATTEMPTS_TO_SWAP_POST_UPDATES_BUCKET)
166
+ throw new PKCError("ERR_POST_UPDATES_BUCKET_SWAP_WAS_LOST", {
167
+ communityAddress: community.address,
168
+ bucketPath,
169
+ attempts: attempt - 1,
170
+ bucketCidInMfs: live?.cid.toString(),
171
+ bucketCidWithThePosts: root.toString()
172
+ });
173
+ for (const block of newBlocks)
174
+ bucketBlocks.set(block.cid.toString(), block.bytes);
175
+ // The new blocks must survive a repo gc (another community's cycle, or the daemon's own) until the
176
+ // bucket hangs off the MFS root, so the import pins them. See buildSwapPinManifests for what is pinned.
177
+ const manifests = await buildSwapPinManifests({ postEntries: entries, directoryNodes: newBlocks });
178
+ const car = await encodeCarV1(manifests.map((manifest) => manifest.cid), [...manifests, ...fileBlocks, ...newBlocks]);
179
+ try {
180
+ for await (const result of kubo.dag.import([car], { pinRoots: true, timeout: MFS_OP_TIMEOUT_MS }))
181
+ if (result.root.pinErrorMsg)
182
+ throw Error(`Failed to pin the new blocks of bucket ${bucketPath} (${result.root.cid.toString()}): ${result.root.pinErrorMsg}`);
183
+ log(`Bucket ${bucketPath}: ${posts.length} posts written, ${newBlocks.length} of the bucket's nodes rebuilt (${car.length} bytes imported), root ${root.toString()}`);
184
+ // Every step flushes: the new bucket must be on disk under the MFS root before the live one goes
185
+ await kubo.files.cp(`/ipfs/${root.toString()}`, nextPath, { parents: true, flush: true, timeout: MFS_OP_TIMEOUT_MS });
186
+ if (live)
187
+ await kubo.files.rm(bucketPath, { recursive: true, timeout: MFS_OP_TIMEOUT_MS });
188
+ await kubo.files.mv(nextPath, bucketPath, { flush: true, timeout: MFS_OP_TIMEOUT_MS });
189
+ }
190
+ finally {
191
+ // Referenced from the MFS root now, or abandoned. "not pinned" is the import itself having failed.
192
+ for (const manifest of manifests)
193
+ await kubo.pin.rm(manifest.cid, { timeout: MFS_OP_TIMEOUT_MS }).catch((error) => {
194
+ if (!(error instanceof Error && error.message.includes("not pinned")))
195
+ log.error(`Failed to unpin ${manifest.cid.toString()}, which pinned the new blocks of bucket ${bucketPath}`, error);
196
+ });
197
+ }
198
+ // The daemon reported every step as done. Kubo has reported MFS changes as done that MFS then did
199
+ // not hold (ipfs/kubo#11494), so the bucket is read back by its cid, which is known exactly.
200
+ const swapped = await statMfsPathOrUndefined(kuboRpcClient, bucketPath, log);
201
+ if (swapped?.cid.equals(root))
202
+ return;
203
+ log.error(`Bucket ${bucketPath} is ${swapped?.cid.toString()} in MFS after ${root.toString()} was swapped in (attempt ${attempt}), checking it for the posts' files`);
204
+ live = await recoverInterruptedBucketSwap(kuboRpcClient, bucketPath, log);
203
205
  }
204
- return { keptPostCids: existingLinks.map((link) => link.name) };
205
206
  }
206
207
  //# sourceMappingURL=post-updates-bucket.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"post-updates-bucket.js","sourceRoot":"","sources":["../../../../../../src/runtime/browser/community/local-community/post-updates-bucket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,MAAM,MAAM,uBAAuB,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AA6BxD,mGAAmG;AACnG,2DAA2D;AAC3D,MAAM,iBAAiB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAEzC,qGAAqG;AACrG,6EAA6E;AAC7E,MAAM,+BAA+B,GAAG,GAAG,GAAG,IAAI,CAAC;AAEnD,MAAM,CAAC,MAAM,+BAA+B,GAAG,OAAO,CAAC;AAEvD,gGAAgG;AAChG,8FAA8F;AAC9F,qGAAqG;AACrG,kGAAkG;AAClG,mGAAmG;AACnG,mFAAmF;AACnF,MAAM,CAAC,MAAM,wCAAwC,GAAG,GAAG,CAAC;AAI5D,MAAM,iBAAiB,GAAG,CAAC,KAAc,EAAE,EAAE,CAAC,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC;AAEtH,KAAK,UAAU,sBAAsB,CAAC,aAA4B,EAAE,IAAY,EAAE,GAAW;IACzF,IAAI,CAAC;QACD,OAAO,MAAM,iBAAiB,CAAC,EAAE,aAAa,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC;IACjE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,IAAI,iBAAiB,CAAC,KAAK,CAAC;YAAE,OAAO,SAAS,CAAC;QAC/C,MAAM,KAAK,CAAC;IAChB,CAAC;AACL,CAAC;AAED,sGAAsG;AACtG,mGAAmG;AACnG,gGAAgG;AAChG,yDAAyD;A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AC3F,CAAC;YAAS,CAAC;QACP,+FAA+F;QAC/F,MAAM,IAAI,CAAC,GAAG;aACT,EAAE,CAAC,IAAI,EAAE,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC;aACxC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,2CAA2C,IAAI,CAAC,QAAQ,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC;IAC1G,CAAC;IACD,OAAO,EAAE,YAAY,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AACpE,CAAC"}
1
+ {"version":3,"file":"post-updates-bucket.js","sourceRoot":"","sources":["../../../../../../src/runtime/browser/community/local-community/post-updates-bucket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,MAAM,MAAM,uBAAuB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,oBAAoB,EAA+C,MAAM,6BAA6B,CAAC;AA8BhH,mGAAmG;AACnG,2DAA2D;AAC3D,MAAM,iBAAiB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAEzC,qGAAqG;AACrG,6EAA6E;AAC7E,MAAM,+BAA+B,GAAG,GAAG,GAAG,IAAI,CAAC;AAEnD,MAAM,CAAC,MAAM,+BAA+B,GAAG,OAAO,CAAC;AAEvD,yFAAyF;AACzF,MAAM,wCAAwC,GAAG,CAAC,CAAC;AAInD,MAAM,iBAAiB,GAAG,CAAC,KAAc,EAAE,EAAE,CAAC,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC;AAEtH,KAAK,UAAU,sBAAsB,CAAC,aAA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AAC;YAAE,OAAO;QACtC,GAAG,CAAC,KAAK,CACL,UAAU,UAAU,OAAO,OAAO,EAAE,GAAG,CAAC,QAAQ,EAAE,iBAAiB,IAAI,CAAC,QAAQ,EAAE,4BAA4B,OAAO,qCAAqC,CAC7J,CAAC;QACF,IAAI,GAAG,MAAM,4BAA4B,CAAC,aAAa,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;IAC9E,CAAC;AACL,CAAC"}
@@ -0,0 +1,20 @@
1
+ import { CID } from "multiformats/cid";
2
+ export type UnixFsDirectoryEntry = {
3
+ name: string;
4
+ cid: CID;
5
+ size: number;
6
+ };
7
+ export type UnixFsBlock = {
8
+ cid: CID;
9
+ bytes: Uint8Array;
10
+ };
11
+ export declare function patchUnixFsDirectory({ directoryCid, entriesToPut, namesToRemove, getBlock, shardSplitThresholdBytes }: {
12
+ directoryCid: CID | undefined;
13
+ entriesToPut: UnixFsDirectoryEntry[];
14
+ namesToRemove?: string[];
15
+ getBlock: (cid: CID) => Promise<Uint8Array>;
16
+ shardSplitThresholdBytes: number;
17
+ }): Promise<{
18
+ cid: CID;
19
+ newBlocks: UnixFsBlock[];
20
+ }>;
@@ -0,0 +1,231 @@
1
+ import { CID } from "multiformats/cid";
2
+ import { sha256 } from "multiformats/hashes/sha2";
3
+ import * as dagPb from "@ipld/dag-pb";
4
+ import { murmur3128 } from "@multiformats/murmur3";
5
+ import { UnixFS } from "ipfs-unixfs";
6
+ import pLimit from "p-limit";
7
+ const HAMT_FANOUT = 256n;
8
+ const HAMT_HASH_TYPE_MURMUR3_X64_64 = 0x22n;
9
+ // One hash byte per level, and go's implementation only uses the first 8 bytes of the hash
10
+ const HAMT_MAX_DEPTH = 8;
11
+ const HAMT_SLOT_PREFIX_LENGTH = 2;
12
+ const SHARD_FETCH_CONCURRENCY = 32;
13
+ const textEncoder = new TextEncoder();
14
+ class HamtShard {
15
+ constructor(stored) {
16
+ this.slots = new Map();
17
+ this.stored = stored;
18
+ this.loaded = stored === undefined;
19
+ }
20
+ }
21
+ export async function patchUnixFsDirectory({ directoryCid, entriesToPut, namesToRemove = [], getBlock, shardSplitThresholdBytes }) {
22
+ const cidVersion = directoryCid?.version ?? 0;
23
+ const newBlocks = [];
24
+ const storeNode = async (node) => {
25
+ const bytes = dagPb.encode(dagPb.prepare(node));
26
+ const cid = CID.create(cidVersion, dagPb.code, await sha256.digest(bytes));
27
+ newBlocks.push({ cid, bytes });
28
+ return { cid, bytes };
29
+ };
30
+ const slotsByName = new Map();
31
+ const slotsOf = async (name) => {
32
+ let slots = slotsByName.get(name);
33
+ if (!slots) {
34
+ slots = (await murmur3128.encode(textEncoder.encode(name))).subarray(0, HAMT_MAX_DEPTH);
35
+ slotsByName.set(name, slots);
36
+ }
37
+ return slots;
38
+ };
39
+ const slotAt = async (name, depth) => {
40
+ if (depth >= HAMT_MAX_DEPTH)
41
+ throw Error(`The HAMT is deeper than ${HAMT_MAX_DEPTH} levels at entry ${name}`);
42
+ return (await slotsOf(name))[depth];
43
+ };
44
+ const loadShard = async (shard) => {
45
+ if (shard.loaded)
46
+ return;
47
+ shard.loading ??= (async () => {
48
+ const stored = shard.stored;
49
+ const node = dagPb.decode(await getBlock(stored.cid));
50
+ readHamtShardMetadata(node, stored.cid);
51
+ for (const link of node.Links) {
52
+ const linkName = link.Name ?? "";
53
+ const slot = parseInt(linkName.slice(0, HAMT_SLOT_PREFIX_LENGTH), 16);
54
+ if (linkName.length < HAMT_SLOT_PREFIX_LENGTH || !Number.isInteger(slot))
55
+ throw Error(`HAMT shard ${stored.cid.toString()} has a link without a slot prefix: "${linkName}"`);
56
+ const child = { cid: CID.decode(link.Hash.bytes), size: link.Tsize ?? 0 };
57
+ shard.slots.set(slot, linkName.length === HAMT_SLOT_PREFIX_LENGTH
58
+ ? new HamtShard(child)
59
+ : { name: linkName.slice(HAMT_SLOT_PREFIX_LENGTH), ...child });
60
+ }
61
+ shard.loaded = true;
62
+ })();
63
+ await shard.loading;
64
+ };
65
+ const putEntry = async (shard, depth, entry) => {
66
+ await loadShard(shard);
67
+ const slot = await slotAt(entry.name, depth);
68
+ const occupant = shard.slots.get(slot);
69
+ if (occupant instanceof HamtShard) {
70
+ if (!(await putEntry(occupant, depth + 1, entry)))
71
+ return false;
72
+ }
73
+ else if (!occupant || occupant.name === entry.name) {
74
+ if (occupant && occupant.cid.equals(entry.cid) && occupant.size === entry.size)
75
+ return false;
76
+ shard.slots.set(slot, entry);
77
+ }
78
+ else {
79
+ // Two names on one slot: both move a level down, as deep as their hashes keep agreeing
80
+ const subShard = new HamtShard();
81
+ await putEntry(subShard, depth + 1, occupant);
82
+ await putEntry(subShard, depth + 1, entry);
83
+ shard.slots.set(slot, subShard);
84
+ }
85
+ shard.stored = undefined;
86
+ return true;
87
+ };
88
+ const removeEntry = async (shard, depth, name) => {
89
+ await loadShard(shard);
90
+ const slot = await slotAt(name, depth);
91
+ const occupant = shard.slots.get(slot);
92
+ if (!occupant)
93
+ return false;
94
+ if (occupant instanceof HamtShard) {
95
+ if (!(await removeEntry(occupant, depth + 1, name)))
96
+ return false;
97
+ // A sub-shard left with one entry gives it back to its parent. As the recursion unwinds this
98
+ // repeats at every level, so the entry ends up where a directory built without the removed
99
+ // name would have it.
100
+ if (occupant.slots.size === 0)
101
+ shard.slots.delete(slot);
102
+ else if (occupant.slots.size === 1) {
103
+ const [onlyOccupant] = occupant.slots.values();
104
+ if (!(onlyOccupant instanceof HamtShard))
105
+ shard.slots.set(slot, onlyOccupant);
106
+ }
107
+ }
108
+ else {
109
+ if (occupant.name !== name)
110
+ return false;
111
+ shard.slots.delete(slot);
112
+ }
113
+ shard.stored = undefined;
114
+ return true;
115
+ };
116
+ const storeShard = async (shard, metadata) => {
117
+ if (shard.stored)
118
+ return shard.stored;
119
+ const links = [];
120
+ let highestSlot = -1;
121
+ for (const slot of shard.slots.keys())
122
+ if (slot > highestSlot)
123
+ highestSlot = slot;
124
+ // The occupied slots, one bit each, as a big-endian number without leading zero bytes
125
+ const bitfield = new Uint8Array(highestSlot < 0 ? 0 : (highestSlot >> 3) + 1);
126
+ let linkedSize = 0;
127
+ for (const [slot, occupant] of shard.slots) {
128
+ bitfield[bitfield.length - 1 - (slot >> 3)] |= 1 << (slot & 7);
129
+ const prefix = slot.toString(16).toUpperCase().padStart(HAMT_SLOT_PREFIX_LENGTH, "0");
130
+ const link = occupant instanceof HamtShard
131
+ ? { Name: prefix, ...(await storeShard(occupant)) }
132
+ : { Name: prefix + occupant.name, cid: occupant.cid, size: occupant.size };
133
+ links.push({ Name: link.Name, Hash: link.cid, Tsize: link.size });
134
+ linkedSize += link.size;
135
+ }
136
+ const data = new UnixFS({
137
+ type: "hamt-sharded-directory",
138
+ data: bitfield,
139
+ fanout: HAMT_FANOUT,
140
+ hashType: HAMT_HASH_TYPE_MURMUR3_X64_64,
141
+ mode: metadata?.mode,
142
+ mtime: metadata?.mtime
143
+ }).marshal();
144
+ const { cid, bytes } = await storeNode({ Data: data, Links: links });
145
+ shard.stored = { cid, size: bytes.length + linkedSize };
146
+ return shard.stored;
147
+ };
148
+ // Reads the shards on the changed names' paths concurrently, so that the changes, which have to be
149
+ // applied one after the other, find them loaded
150
+ const loadShardsOnPathsOf = async (root, names) => {
151
+ const limit = pLimit(SHARD_FETCH_CONCURRENCY);
152
+ await Promise.all(names.map((name) => limit(async () => {
153
+ let shard = root;
154
+ for (let depth = 0; depth < HAMT_MAX_DEPTH; depth++) {
155
+ await loadShard(shard);
156
+ const occupant = shard.slots.get(await slotAt(name, depth));
157
+ if (!(occupant instanceof HamtShard))
158
+ return;
159
+ shard = occupant;
160
+ }
161
+ })));
162
+ };
163
+ const patchHamt = async (root, metadata) => {
164
+ await loadShardsOnPathsOf(root, [...namesToRemove, ...entriesToPut.map((entry) => entry.name)]);
165
+ for (const name of namesToRemove)
166
+ await removeEntry(root, 0, name);
167
+ for (const entry of entriesToPut)
168
+ await putEntry(root, 0, entry);
169
+ return (await storeShard(root, metadata)).cid;
170
+ };
171
+ const entries = new Map();
172
+ let metadata = {};
173
+ if (directoryCid) {
174
+ const node = dagPb.decode(await getBlock(directoryCid));
175
+ if (!node.Data)
176
+ throw Error(`Expected a UnixFS directory at ${directoryCid.toString()}, got a node without data`);
177
+ const unixfs = UnixFS.unmarshal(node.Data);
178
+ metadata = { mode: unixfs.mode, mtime: unixfs.mtime };
179
+ if (unixfs.type === "hamt-sharded-directory") {
180
+ const cid = await patchHamt(new HamtShard({ cid: directoryCid, size: 0 }), metadata);
181
+ return { cid, newBlocks };
182
+ }
183
+ if (unixfs.type !== "directory")
184
+ throw Error(`Expected a UnixFS directory at ${directoryCid.toString()}, got ${unixfs.type}`);
185
+ for (const link of node.Links) {
186
+ const name = link.Name ?? "";
187
+ entries.set(name, { name, cid: CID.decode(link.Hash.bytes), size: link.Tsize ?? 0 });
188
+ }
189
+ }
190
+ // A basic directory: one block holding every link
191
+ let changed = directoryCid === undefined;
192
+ for (const name of namesToRemove)
193
+ if (entries.delete(name))
194
+ changed = true;
195
+ for (const entry of entriesToPut) {
196
+ const existing = entries.get(entry.name);
197
+ if (existing && existing.cid.equals(entry.cid) && existing.size === entry.size)
198
+ continue;
199
+ entries.set(entry.name, entry);
200
+ changed = true;
201
+ }
202
+ if (!changed)
203
+ return { cid: directoryCid, newBlocks };
204
+ let linksBytes = 0;
205
+ for (const entry of entries.values())
206
+ linksBytes += textEncoder.encode(entry.name).length + entry.cid.bytes.length;
207
+ if (linksBytes > shardSplitThresholdBytes) {
208
+ const root = new HamtShard();
209
+ for (const entry of entries.values())
210
+ await putEntry(root, 0, entry);
211
+ return { cid: (await storeShard(root, metadata)).cid, newBlocks };
212
+ }
213
+ const { cid } = await storeNode({
214
+ Data: new UnixFS({ type: "directory", mode: metadata.mode, mtime: metadata.mtime }).marshal(),
215
+ Links: [...entries.values()].map((entry) => ({ Name: entry.name, Hash: entry.cid, Tsize: entry.size }))
216
+ });
217
+ return { cid, newBlocks };
218
+ }
219
+ function readHamtShardMetadata(node, cid) {
220
+ if (!node.Data)
221
+ throw Error(`Expected a HAMT shard at ${cid.toString()}, got a node without data`);
222
+ const unixfs = UnixFS.unmarshal(node.Data);
223
+ if (unixfs.type !== "hamt-sharded-directory")
224
+ throw Error(`Expected a HAMT shard at ${cid.toString()}, got ${unixfs.type}`);
225
+ // The hash type is not checked: ipfs-unixfs does not hand it back when it reads a node, and murmur3-x64-64
226
+ // is the only one any implementation writes
227
+ if (unixfs.fanout !== HAMT_FANOUT)
228
+ throw Error(`HAMT shard ${cid.toString()} has fanout ${unixfs.fanout}, only ${HAMT_FANOUT} is supported`);
229
+ return unixfs;
230
+ }
231
+ //# sourceMappingURL=unixfs-directory-patch.js.map