MCPcopy Create free account
hub / github.com/EvoMap/evolver / getLastEventId

Function getLastEventId

src/gep/assetStore.js:393–449  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

391const LAST_EVENT_MAX_CHUNK = 4 * 1024 * 1024;
392
393function getLastEventId() {
394 try {
395 const p = eventsPath();
396 if (!fs.existsSync(p)) return null;
397 const stat = fs.statSync(p);
398 if (stat.size === 0) return null;
399
400 const cap = Math.min(stat.size, LAST_EVENT_MAX_CHUNK);
401 let chunkSize = Math.min(stat.size, LAST_EVENT_INITIAL_CHUNK);
402
403 const fd = fs.openSync(p, 'r');
404 try {
405 while (true) {
406 const buf = Buffer.alloc(chunkSize);
407 const readPos = stat.size - chunkSize;
408 fs.readSync(fd, buf, 0, chunkSize, readPos);
409
410 // Drop the trailing newline(s) the writer appends so lastIndexOf('\n')
411 // points to the boundary BEFORE the final line, not at end-of-file.
412 const trimmedTail = buf.toString('utf8').replace(/\n+$/, '');
413 const lastNl = trimmedTail.lastIndexOf('\n');
414
415 // The chunk fully contains the last line when either we read from the
416 // start of the file, or we found a newline that bounds the line on
417 // the left. Otherwise the final line is bigger than the current chunk
418 // and we must grow.
419 if (readPos > 0 && lastNl < 0) {
420 if (chunkSize < cap) {
421 chunkSize = Math.min(cap, chunkSize * 2);
422 continue;
423 }
424 return null;
425 }
426
427 const lastLine = (lastNl >= 0 ? trimmedTail.slice(lastNl + 1) : trimmedTail).trim();
428 if (!lastLine) return null;
429
430 let last;
431 try {
432 last = JSON.parse(lastLine);
433 } catch (parseErr) {
434 if (chunkSize < cap) {
435 chunkSize = Math.min(cap, chunkSize * 2);
436 continue;
437 }
438 throw parseErr;
439 }
440 return last && typeof last.id === 'string' ? last.id : null;
441 }
442 } finally {
443 fs.closeSync(fd);
444 }
445 } catch (e) {
446 console.warn('[AssetStore] Failed to read last event ID:', e && e.message || e);
447 return null;
448 }
449}
450

Callers 1

assetStore.test.jsFile · 0.85

Calls 2

eventsPathFunction · 0.85
parseMethod · 0.80

Tested by

no test coverage detected