gitoria

mpackdb

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitcde6b275cde6b2751.0.8: validate indexes against the data file on open, atomic index writes, invalidate index state before compaction; tests for pk find after compaction and hard killmrecde6b275/src/IndexManager.js

22.4 KB

  1. import { writeFile, readFile, open, rename, stat } from 'node:fs/promises';
  2. import { createWriteStream } from 'node:fs';
  3. import { resolve } from 'node:path';
  4. import { deserialize } from './mpack.js';
  5. import { PrimaryKeyType, IndexType } from './MPackDB.js';
  6. const BLOCK_SIZE = 4096; // 4KB
  7. /**
  8. * Manages indexes for the database (in-memory deltas + on-disk persistence)
  9. */
  10. export class IndexManager {
  11. _dbDir;
  12. _dbName;
  13. _indexes;
  14. _indexTypes;
  15. _primaryKeyType;
  16. _persistIntervalId = null;
  17. _indexPaths = {};
  18. _deltaIndexes = {};
  19. _tombstones = {};
  20. _persistThreshold = 1000;
  21. _totalDeltaCount = 0;
  22. _coveredBytes = 0;
  23. _idxStatePath = null;
  24. _catchUpPromise = null;
  25. _runExclusive = fn => fn();
  26. /**
  27. * Creates a new IndexManager
  28. * @param {string} dbDir - Database directory path
  29. * @param {string} dbName - Database name
  30. * @param {string[]} indexes - Array of field names to index
  31. * @param {Object} indexTypes - Map of field names to IndexType
  32. * @param {number} primaryKeyType - Primary key type
  33. * @param {Object} [options]
  34. * @param {Function} [options.runExclusive] - Wraps index file writes in the db's lock
  35. */
  36. constructor(dbDir, dbName, indexes, indexTypes, primaryKeyType, { runExclusive } = {}) {
  37. this._dbDir = dbDir;
  38. this._dbName = dbName;
  39. this._indexes = indexes;
  40. this._indexTypes = indexTypes;
  41. this._primaryKeyType = primaryKeyType;
  42. if (runExclusive) this._runExclusive = runExclusive;
  43. // Index paths are deterministic and do not depend on async initialization.
  44. // Populate them immediately, then repair a missing slot on access so a
  45. // declared index can never leak readFile(undefined) to the caller.
  46. for (const field of this._indexes) this._getIndexPath(field);
  47. }
  48. _getIndexPath(field) {
  49. if (!this._indexes.includes(field)) {
  50. const configured = this._indexes.length > 0 ? this._indexes.join(', ') : '(none)';
  51. const error = new Error(`No index configured for field "${String(field)}". Configured indexes: ${configured}`);
  52. error.code = 'INDEX_NOT_FOUND';
  53. error.field = field;
  54. error.indexes = [...this._indexes];
  55. throw error;
  56. }
  57. const expectedPath = resolve(this._dbDir, `${this._dbName}.${field}.txt`);
  58. if (this._indexPaths[field] !== expectedPath) {
  59. this._indexPaths[field] = expectedPath;
  60. }
  61. return expectedPath;
  62. }
  63. /**
  64. * Initializes the index manager (rebuilds indexes from data file)
  65. * @param {string} dataPath - Path to the data file
  66. * @returns {Promise<void>}
  67. */
  68. async init(dataPath, { forceRebuild = false } = {}) {
  69. this._idxStatePath = resolve(this._dbDir, `${this._dbName}.idxstate.json`);
  70. let needRebuild = forceRebuild;
  71. for (const field of this._indexes) {
  72. this._deltaIndexes[field] = [];
  73. this._tombstones[field] = new Map();
  74. const indexPath = this._getIndexPath(field);
  75. if (needRebuild) continue;
  76. try {
  77. const stats = await stat(indexPath);
  78. if (stats.size === 0) {
  79. const dataStats = await stat(dataPath).catch(() => ({ size: 0 }));
  80. if (dataStats.size > 0) needRebuild = true;
  81. }
  82. } catch (e) {
  83. if (e.code === 'ENOENT') {
  84. const dataStats = await stat(dataPath).catch(() => ({ size: 0 }));
  85. if (dataStats.size > 0) needRebuild = true;
  86. } else {
  87. throw e;
  88. }
  89. }
  90. }
  91. // coveredBytes: how far into the data file the on-disk indexes reach.
  92. // Without it we cannot trust existing index files (another process may
  93. // have appended records it never persisted) — rebuild once to establish it.
  94. if (!needRebuild) {
  95. const state = await this._readIdxState();
  96. if (state === null) {
  97. needRebuild = true;
  98. } else {
  99. this._coveredBytes = state.coveredBytes || 0;
  100. // The state file only proves coverage if the index files really match
  101. // this data file: stores written by 1.0.6 (wrong offsets after compaction),
  102. // a crash during compaction/persist, or a replaced data file all show up here.
  103. if (!(await this._indexesLookSane(dataPath))) needRebuild = true;
  104. }
  105. }
  106. if (needRebuild) {
  107. for (const field of this._indexes) {
  108. await this._rebuildIndex(dataPath, field);
  109. }
  110. this._coveredBytes = (await stat(dataPath).catch(() => ({ size: 0 }))).size;
  111. await this._writeIdxState();
  112. }
  113. }
  114. /**
  115. * Cheap consistency check of the on-disk index files against the data file:
  116. * every index line must parse, end inside the covered part of the data file
  117. * and (sampled) point at a record whose size header equals the indexed length.
  118. * @returns {Promise<boolean>} false if the indexes must be rebuilt
  119. * @private
  120. */
  121. async _indexesLookSane(dataPath) {
  122. const size = (await stat(dataPath).catch(() => ({ size: 0 }))).size;
  123. if (this._coveredBytes > size) return false;
  124. let fh = null;
  125. try {
  126. for (const field of this._indexes) {
  127. let raw = '';
  128. try { raw = await readFile(this._getIndexPath(field), 'utf-8'); } catch (e) { if (e.code !== 'ENOENT') throw e; }
  129. const lines = raw.split('\n').filter(Boolean);
  130. const entries = this._parseIndexLines(raw, field);
  131. if (entries.length !== lines.length) return false; // torn / garbled line
  132. if (entries.length === 0) continue;
  133. if (entries.some(e => e.loc[0] < 0 || e.loc[0] + e.loc[1] > this._coveredBytes)) return false;
  134. fh ??= await open(dataPath, 'r');
  135. const SAMPLES = 256;
  136. const step = Math.max(1, Math.floor(entries.length / SAMPLES));
  137. const picks = new Set([entries.length - 1]);
  138. for (let i = 0; i < entries.length; i += step) picks.add(i);
  139. const header = Buffer.alloc(4);
  140. for (const i of picks) {
  141. const [offset, length] = entries[i].loc;
  142. const { bytesRead } = await fh.read(header, 0, 4, offset);
  143. if (bytesRead < 4 || header.readInt32LE(0) !== length) return false;
  144. }
  145. }
  146. return true;
  147. } catch (e) {
  148. return false;
  149. } finally {
  150. await fh?.close();
  151. }
  152. }
  153. async _readIdxState() {
  154. try {
  155. return JSON.parse(await readFile(this._idxStatePath, 'utf-8'));
  156. } catch (e) {
  157. return null;
  158. }
  159. }
  160. // tmp + rename: a crash mid-write must never leave a torn index file behind
  161. async _writeFileAtomic(path, content) {
  162. const tmpPath = `${path}.${process.pid}.tmp`;
  163. await writeFile(tmpPath, content, 'utf-8');
  164. await rename(tmpPath, path);
  165. }
  166. async _writeIdxState() {
  167. const tmpPath = `${this._idxStatePath}.${process.pid}.tmp`;
  168. await writeFile(tmpPath, JSON.stringify({ coveredBytes: this._coveredBytes }), 'utf-8');
  169. await rename(tmpPath, this._idxStatePath);
  170. }
  171. /**
  172. * Index records another process appended to the data file since our last
  173. * known coverage point. Called from refresh(). Append-only data makes this
  174. * a cheap incremental scan of just the new tail.
  175. * @param {string} dataPath - Path to the data file
  176. * @param {number} fileSize - Current data file size (from the caller's stat)
  177. */
  178. async catchUp(dataPath, fileSize) {
  179. if (this._idxStatePath === null) return; // not initialized yet
  180. if (fileSize <= this._coveredBytes) return;
  181. if (this._catchUpPromise) return this._catchUpPromise;
  182. this._catchUpPromise = (async () => {
  183. const from = this._coveredBytes;
  184. for await (const { doc, loc } of this._getDocsAndLocationsFromDataFile(dataPath, from)) {
  185. for (const field of this._indexes) {
  186. if (doc && doc[field] !== undefined) {
  187. this._deltaIndexes[field].push({ key: doc[field], loc });
  188. this._totalDeltaCount++;
  189. }
  190. }
  191. this._coveredBytes = Math.max(this._coveredBytes, loc[0] + loc[1]);
  192. }
  193. if (this._totalDeltaCount >= this._persistThreshold) {
  194. this.persist().catch(err => console.error('Index persist error:', err));
  195. }
  196. })();
  197. try {
  198. return await this._catchUpPromise;
  199. } finally {
  200. this._catchUpPromise = null;
  201. }
  202. }
  203. /**
  204. * The data file was replaced (external compaction): all offsets are invalid.
  205. * Drop delta/tombstone state and re-baseline from the compactor's rebuilt
  206. * index files, or rebuild if its state file is unreadable.
  207. * @param {string} dataPath - Path to the (new) data file
  208. */
  209. async resetAfterReplace(dataPath) {
  210. for (const field of this._indexes) {
  211. this._deltaIndexes[field] = [];
  212. this._tombstones[field].clear();
  213. }
  214. this._totalDeltaCount = 0;
  215. const state = await this._readIdxState();
  216. if (state !== null) {
  217. this._coveredBytes = state.coveredBytes || 0;
  218. } else {
  219. for (const field of this._indexes) {
  220. await this._rebuildIndex(dataPath, field);
  221. }
  222. this._coveredBytes = (await stat(dataPath).catch(() => ({ size: 0 }))).size;
  223. await this._writeIdxState();
  224. }
  225. }
  226. /**
  227. * Rebuilds an index from the data file
  228. * @param {string} dataPath - Path to the data file
  229. * @param {string} field - Field name to index
  230. * @returns {Promise<void>}
  231. * @private
  232. */
  233. async _rebuildIndex(dataPath, field) {
  234. const indexPath = this._getIndexPath(field);
  235. const tempIndexPath = `${indexPath}.${Date.now()}.tmp`;
  236. const writeStream = createWriteStream(tempIndexPath, { flags: 'w', encoding: 'utf-8' });
  237. const docIterator = this._getDocsAndLocationsFromDataFile(dataPath);
  238. const entries = [];
  239. for await (const { doc, loc } of docIterator) {
  240. if (doc && doc[field] !== undefined) {
  241. const key = doc[field];
  242. entries.push({ key, loc });
  243. }
  244. }
  245. // Sort entries before writing to the index file
  246. entries.sort((a, b) => this._compareKeys(a.key, b.key));
  247. for (const entry of entries) {
  248. writeStream.write(`${entry.key},${entry.loc[0]},${entry.loc[1]}\n`);
  249. }
  250. await new Promise(resolve => writeStream.end(resolve));
  251. await rename(tempIndexPath, indexPath);
  252. }
  253. /**
  254. * Generator that yields documents and their locations from the data file
  255. * @param {string} dataPath - Path to the data file
  256. * @yields {{doc: Object, loc: Array}} Document and location tuple
  257. * @private
  258. */
  259. async* _getDocsAndLocationsFromDataFile(dataPath, startOffset = 0) {
  260. let fileHandle;
  261. try {
  262. fileHandle = await open(dataPath, 'r');
  263. const stats = await fileHandle.stat();
  264. let offset = startOffset;
  265. while (offset < stats.size) {
  266. // Read size header
  267. const sizeBuffer = Buffer.alloc(4);
  268. await fileHandle.read(sizeBuffer, 0, 4, offset);
  269. const size = sizeBuffer.readInt32LE(0);
  270. if (size <= 0 || offset + size > stats.size) {
  271. break; // Corrupted or incomplete record
  272. }
  273. const docBuffer = Buffer.alloc(size);
  274. await fileHandle.read(docBuffer, 0, size, offset);
  275. const doc = deserialize(docBuffer.subarray(4));
  276. yield { doc, loc: [offset, size] };
  277. offset += size;
  278. }
  279. } catch (e) {
  280. if (e.code !== 'ENOENT') {
  281. throw e;
  282. }
  283. // if file does not exist, do nothing
  284. } finally {
  285. await fileHandle?.close();
  286. }
  287. }
  288. /**
  289. * Compares two keys for sorting
  290. * @param {any} keyA - First key
  291. * @param {any} keyB - Second key
  292. * @returns {number} -1 if keyA < keyB, 0 if equal, 1 if keyA > keyB
  293. * @private
  294. */
  295. _compareKeys(keyA, keyB) {
  296. if (typeof keyA === 'number' && typeof keyB === 'number') {
  297. return keyA - keyB;
  298. }
  299. return String(keyA).localeCompare(String(keyB));
  300. }
  301. /**
  302. * Starts automatic periodic persistence of indexes
  303. * @param {number} interval - Interval in milliseconds between auto-persists
  304. * @param {number} threshold - Number of operations before triggering auto-persist
  305. */
  306. startAutoPersist(interval, threshold) {
  307. this._persistThreshold = threshold;
  308. // Start periodic persist
  309. if (interval > 0) {
  310. this._persistIntervalId = setInterval(async () => {
  311. if (this._totalDeltaCount > 0) {
  312. await this.persist();
  313. }
  314. }, interval);
  315. // Don't keep process alive just for this timer
  316. this._persistIntervalId.unref();
  317. }
  318. }
  319. /**
  320. * Closes the index manager (persists indexes and clears interval)
  321. * @returns {Promise<void>}
  322. */
  323. async close() {
  324. if (this._persistIntervalId) {
  325. clearInterval(this._persistIntervalId);
  326. this._persistIntervalId = null;
  327. }
  328. await this.persist();
  329. }
  330. /**
  331. * Persists all in-memory index deltas to disk.
  332. * Runs under the db lock (via runExclusive): the read-merge-write below
  333. * would otherwise lose entries another process persisted in between.
  334. * @returns {Promise<void>}
  335. */
  336. async persist() {
  337. return this._runExclusive(() => this._persistLocked());
  338. }
  339. async _persistLocked() {
  340. for (const field of this._indexes) {
  341. let onDiskEntries = [];
  342. const indexPath = this._getIndexPath(field);
  343. try {
  344. const indexContent = await readFile(indexPath, 'utf-8');
  345. onDiskEntries = indexContent.trim().split('\n').filter(Boolean).map(line => {
  346. const [key, offset, length] = line.split(',');
  347. return { key: this._parseKey(key, field), loc: [parseInt(offset), parseInt(length)] };
  348. });
  349. } catch (e) {
  350. if (e.code !== 'ENOENT') throw e;
  351. }
  352. const fieldTombstones = this._tombstones[field];
  353. const validDiskEntries = onDiskEntries.filter(e => !fieldTombstones.has(e.loc[0]));
  354. // Dedupe by location — catch-up scans and cross-process persists can
  355. // both have picked up the same record
  356. const merged = new Map();
  357. for (const entry of [...validDiskEntries, ...(this._deltaIndexes[field] || [])]) {
  358. merged.set(`${entry.loc[0]}:${entry.loc[1]}`, entry);
  359. }
  360. const finalIndexData = Array.from(merged.values());
  361. finalIndexData.sort((a, b) => this._compareKeys(a.key, b.key));
  362. if (finalIndexData.length > 0) {
  363. const indexContent = finalIndexData.map(e => `${e.key},${e.loc[0]},${e.loc[1]}`).join('\n') + '\n';
  364. await this._writeFileAtomic(indexPath, indexContent);
  365. } else {
  366. await this._writeFileAtomic(indexPath, '');
  367. }
  368. // Clear the in-memory changes now that they are persisted
  369. this._deltaIndexes[field] = [];
  370. this._tombstones[field].clear();
  371. }
  372. this._totalDeltaCount = 0;
  373. // Coverage can only grow: another process's state may reach further than ours
  374. const state = await this._readIdxState();
  375. this._coveredBytes = Math.max(this._coveredBytes, state?.coveredBytes || 0);
  376. await this._writeIdxState();
  377. }
  378. /**
  379. * Parses a key based on the field's index type
  380. * @param {any} key - The key to parse
  381. * @param {string} field - Field name
  382. * @returns {any} Parsed key (number or string)
  383. * @private
  384. */
  385. _parseKey(key, field) {
  386. const indexType = this._indexTypes[field];
  387. // Use index type if specified, otherwise fall back to primary key type logic
  388. if (indexType === IndexType.NUMERIC) {
  389. const num = parseInt(key, 10);
  390. if (!isNaN(num)) return num;
  391. } else if (indexType === IndexType.LEXICAL) {
  392. return key;
  393. }
  394. // Fallback to primary key type for fields without explicit index type
  395. if (this._primaryKeyType === PrimaryKeyType.NUMBER) {
  396. const num = parseInt(key, 10);
  397. if (!isNaN(num)) return num;
  398. }
  399. return key;
  400. }
  401. _parseIndexLines(indexContent, field) {
  402. return indexContent.trim().split('\n').filter(Boolean).map(line => {
  403. const [keyStr, offset, length] = line.split(',');
  404. const locOffset = Number.parseInt(offset, 10);
  405. const locLength = Number.parseInt(length, 10);
  406. if (!Number.isSafeInteger(locOffset) || !Number.isSafeInteger(locLength) || locLength <= 0) {
  407. return null;
  408. }
  409. return {
  410. key: this._parseKey(keyStr, field),
  411. loc: [locOffset, locLength],
  412. };
  413. }).filter(Boolean);
  414. }
  415. async _readIndexEntries(field) {
  416. const indexPath = this._getIndexPath(field);
  417. try {
  418. return this._parseIndexLines(await readFile(indexPath, 'utf-8'), field);
  419. } catch (e) {
  420. if (e.code === 'ENOENT') return [];
  421. throw e;
  422. }
  423. }
  424. /**
  425. * Performs a binary search on the blocks of an index file on disk.
  426. * This is a direct port of Joshua Bloch's famously correct binary search
  427. * algorithm, adapted for file blocks.
  428. *
  429. * @param {string} field The index field to search.
  430. * @param {string|number} key The key to search for.
  431. * @returns {Promise<number>} The starting offset in the file for the linear scan.
  432. */
  433. async _binarySearchOnDisk(field, key) {
  434. return (await this._readIndexEntries(field)).length === 0 ? -1 : 0;
  435. }
  436. /**
  437. * Finds the last entry for a given field and key (checks both delta and disk)
  438. * @param {string} field - Field name
  439. * @param {any} key - Key value to search for
  440. * @returns {Promise<Object|null>} Entry object with key and loc, or null if not found
  441. */
  442. async findLastEntry(field, key) {
  443. const parsedKey = this._parseKey(key, field);
  444. const deltaIndex = this._deltaIndexes[field] || [];
  445. for (let i = deltaIndex.length - 1; i >= 0; i--) {
  446. const entry = deltaIndex[i];
  447. if (this._compareKeys(entry.key, parsedKey) === 0) {
  448. return entry;
  449. }
  450. }
  451. const onDiskEntry = await this._findLastEntryOnDisk(field, parsedKey);
  452. if (!onDiskEntry) return null;
  453. const isTombstoned = this._tombstones[field].has(onDiskEntry.loc[0]);
  454. return isTombstoned ? null : onDiskEntry;
  455. }
  456. /**
  457. * Finds the last entry for a key on disk (linear scan from binary search position)
  458. * @param {string} field - Field name
  459. * @param {any} key - Key to search for
  460. * @returns {Promise<Object|null>} Entry object or null
  461. * @private
  462. */
  463. async _findLastEntryOnDisk(field, key) {
  464. let lastMatch = null;
  465. for (const entry of await this._readIndexEntries(field)) {
  466. if (this._compareKeys(entry.key, key) === 0) {
  467. lastMatch = entry;
  468. }
  469. }
  470. return lastMatch;
  471. }
  472. /**
  473. * Adds a document to the indexes
  474. * @param {Object} doc - The document to index
  475. * @param {Array} loc - [offset, length] location in data file
  476. */
  477. insert(doc, loc) {
  478. for (const field of this._indexes) {
  479. if (doc[field] !== undefined) {
  480. this._deltaIndexes[field].push({ key: doc[field], loc });
  481. this._totalDeltaCount++;
  482. }
  483. }
  484. this._coveredBytes = Math.max(this._coveredBytes, loc[0] + loc[1]);
  485. // Auto-persist if threshold reached
  486. if (this._totalDeltaCount >= this._persistThreshold) {
  487. // Persist async without blocking
  488. this.persist().catch(err => console.error('Index persist error:', err));
  489. }
  490. }
  491. /**
  492. * Removes a document from the indexes
  493. * @param {Object} doc - The document to remove
  494. * @param {string} primaryKeyField - Primary key field name
  495. * @returns {Promise<void>}
  496. */
  497. async remove(doc, primaryKeyField) {
  498. const pkValue = doc[primaryKeyField];
  499. const deltaPkIndex = this._deltaIndexes[primaryKeyField] || [];
  500. const indexInDelta = deltaPkIndex.findIndex(e => this._compareKeys(e.key, pkValue) === 0);
  501. if (indexInDelta !== -1) {
  502. const offsetToRemove = deltaPkIndex[indexInDelta].loc[0];
  503. for (const field of this._indexes) {
  504. this._deltaIndexes[field] = (this._deltaIndexes[field] || []).filter(e => e.loc[0] !== offsetToRemove);
  505. }
  506. } else {
  507. const onDiskEntry = await this._findLastEntryOnDisk(primaryKeyField, pkValue);
  508. if (onDiskEntry) {
  509. for (const field of this._indexes) {
  510. if (doc[field] !== undefined) {
  511. this._tombstones[field].set(onDiskEntry.loc[0], true);
  512. }
  513. }
  514. }
  515. }
  516. }
  517. /**
  518. * Gets all document locations from the first index (used for full scans)
  519. * @returns {Promise<Array[]>} Array of all [offset, length] locations
  520. */
  521. async getAllLocations() {
  522. const field = this._indexes[0];
  523. const indexPath = this._getIndexPath(field);
  524. let onDiskEntries = [];
  525. try {
  526. const indexContent = await readFile(indexPath, 'utf-8');
  527. onDiskEntries = indexContent.trim().split('\n').filter(Boolean).map(line => {
  528. const [, offset, length] = line.split(',');
  529. return { loc: [parseInt(offset), parseInt(length)] };
  530. });
  531. } catch (e) {
  532. if (e.code !== 'ENOENT') throw e;
  533. }
  534. const fieldTombstones = this._tombstones[field] || new Map();
  535. const validDiskEntries = onDiskEntries.filter(e => !fieldTombstones.has(e.loc[0]));
  536. const deltaEntries = this._deltaIndexes[field] || [];
  537. const finalEntries = new Map();
  538. for (const entry of validDiskEntries) {
  539. finalEntries.set(`${entry.loc[0]}:${entry.loc[1]}`, entry.loc);
  540. }
  541. for (const entry of deltaEntries) {
  542. finalEntries.set(`${entry.loc[0]}:${entry.loc[1]}`, entry.loc);
  543. }
  544. return Array.from(finalEntries.values());
  545. }
  546. /**
  547. * Gets document locations for a given field and key
  548. * @param {string} field - Field name
  549. * @param {any} key - Key value to search for
  550. * @returns {Promise<Array[]>} Array of [offset, length] locations
  551. */
  552. async get(field, key) {
  553. const parsedKey = this._parseKey(key, field);
  554. const onDiskResults = await this._getOnDisk(field, parsedKey);
  555. const deltaResults = (this._deltaIndexes[field] || []).filter(e => this._compareKeys(e.key, parsedKey) === 0);
  556. const tombstonedOffsets = this._tombstones[field] || new Map();
  557. const finalEntries = new Map();
  558. for (const entry of onDiskResults) {
  559. if (!tombstonedOffsets.has(entry.loc[0])) {
  560. finalEntries.set(`${entry.loc[0]}:${entry.loc[1]}`, entry);
  561. }
  562. }
  563. for (const entry of deltaResults) {
  564. finalEntries.set(`${entry.loc[0]}:${entry.loc[1]}`, entry);
  565. }
  566. return Array.from(finalEntries.values());
  567. }
  568. /**
  569. * Gets all entries for a key from disk
  570. * @param {string} field - Field name
  571. * @param {any} key - Key to search for
  572. * @returns {Promise<Array>} Array of entry objects
  573. * @private
  574. */
  575. async _getOnDisk(field, key) {
  576. const results = [];
  577. for (const entry of await this._readIndexEntries(field)) {
  578. if (this._compareKeys(entry.key, key) === 0) {
  579. results.push(entry);
  580. }
  581. }
  582. return results;
  583. }
  584. /**
  585. * Yields index entries in sorted order by streaming blocks from disk.
  586. * Merges with in-memory deltas, excludes tombstones.
  587. * @param {string} field - Field name
  588. * @param {Object} [options]
  589. * @param {any} [options.from] - Start key (inclusive), uses binary search to skip ahead
  590. * @param {any} [options.to] - End key (inclusive), stops scan when exceeded
  591. * @param {'asc'|'desc'} [options.direction='asc'] - Scan direction
  592. * @yields {{key: any, loc: [number, number]}}
  593. */
  594. async *entries(field, { from, to, direction = 'asc' } = {}) {
  595. const desc = direction === 'desc';
  596. const tombstones = this._tombstones[field] || new Map();
  597. const seen = new Set();
  598. const withinRange = entry => {
  599. if (from !== undefined && this._compareKeys(entry.key, from) < 0) return false;
  600. if (to !== undefined && this._compareKeys(entry.key, to) > 0) return false;
  601. return true;
  602. };
  603. const entries = [
  604. ...(await this._readIndexEntries(field)).filter(e => !tombstones.has(e.loc[0])),
  605. ...(this._deltaIndexes[field] || []).filter(e => !tombstones.has(e.loc[0])),
  606. ]
  607. .filter(withinRange)
  608. .sort((a, b) => this._compareKeys(a.key, b.key));
  609. if (desc) entries.reverse();
  610. for (const entry of entries) {
  611. const locKey = `${entry.loc[0]}:${entry.loc[1]}`;
  612. if (seen.has(locKey)) continue;
  613. seen.add(locKey);
  614. yield entry;
  615. }
  616. }
  617. async* _getDocsByLocation(dataPath, locations) {
  618. const fileHandle = await open(dataPath, 'r');
  619. try {
  620. for (const loc of locations) {
  621. if (loc && loc.length === 2 && loc[1] > 0) {
  622. const [offset, length] = loc;
  623. const buffer = Buffer.alloc(length);
  624. await fileHandle.read(buffer, 0, length, offset);
  625. yield deserialize(buffer.subarray(4));
  626. }
  627. }
  628. } finally {
  629. await fileHandle.close();
  630. }
  631. }
  632. }
  633. export default IndexManager;

Branches

Latest commits

  • cde6b2751.0.8: validate indexes against the data file on open, atomic index writes, invalidate index state before compaction; tests for pk find after compaction and hard killmre
  • 87888725release 1.0.7caramboleyo
  • c4cdb9b6node: import prefixes (Deno compat) + pre-existing index-state WIPcaramboleyo
  • 0afb8f4bupdate now must be a callbackcaramboleyo
  • cde73eb4release 1.0.6caramboleyo
  • d01dda02add index hints, intersection, boundingBox; remove findByIndexcaramboleyo
  • b8ffc1a0release 1.0.5caramboleyo
  • d47876a1reimplemented lost features like indexed find and more testscaramboleyo
  • 7f08da9afixed insert ignoring model definitioncaramboleyo
  • 705774a9added flush before findcaramboleyo
  • b4db6391initial commitcaramboleyo