Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([sharing-annotationssync-cache-bucket-asset-keys]): cache listBucketAssetKeys per manifests-dir mtime

[._.]/ Adam Eivy4d9e030f61c8
diff --git a/server/services/sharing/annotationsSync.js b/server/services/sharing/annotationsSync.js
index aaeb8d467f..ac41890cde 100644
--- a/server/services/sharing/annotationsSync.js
+++ b/server/services/sharing/annotationsSync.js
@@ -7,7 +7,7 @@
*/
import { join } from 'path';
-import { readdir } from 'fs/promises';
+import { readdir, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { listBuckets } from './buckets.js';
@@ -21,31 +21,65 @@ const DEBOUNCE_MS = 2000;
let pendingTimer = null;
let installed = false;
+/**
+ * Cache of manifest-derived asset keys per bucket, invalidated by the
+ * `manifests/` directory's mtime. Every manifest write goes through
+ * `atomicWrite` (temp + rename), and every archive sweep uses `rename`, both
+ * of which bump the directory mtime — so the mtime is the cheapest available
+ * signal that "the set of manifests in this bucket has changed."
+ *
+ * Without the cache, every 2s annotation flush re-reads + re-parses every
+ * manifest in every auto-merge bucket — fan-out is O(buckets × manifests)
+ * per flush. With the cache the steady-state cost drops to one `stat` per
+ * bucket.
+ *
+ * @type {Map<string, { manifestsMtimeMs: number, manifestKeys: Set<string> }>}
+ */
+const manifestKeysCache = new Map();
+/** Sentinel: manifests dir doesn't exist yet. */
+const MANIFESTS_DIR_ABSENT = -1;
+
/**
* Set of `${kind}:${filename}` keys for every asset referenced by any manifest
* in the bucket. v2's content-addressed `assets/blobs/<hash>` paths don't
* carry filenames, so the manifests are the only source-of-truth for which
* user-facing filenames the bucket holds; the legacy `assets/{images,videos}/`
* scan covers v1 buckets that never wrote a manifest's `hash` field.
+ *
+ * The manifests-side scan is cached per (bucket, manifests-dir mtime); the
+ * legacy v1 dir scan is small and runs uncached.
*/
async function listBucketAssetKeys(bucketPath) {
- const keys = new Set();
- const filenames = await listManifestFilenames(bucketPath);
- await Promise.all(filenames.map(async (filename) => {
- const m = await readManifest(bucketPath, filename).catch(() => null);
- for (const ref of m?.assetRefs || []) {
- if (!ref?.ref || typeof ref.ref !== 'string') continue;
- const kind = ref.kind === 'video' ? 'video' : 'image';
- keys.add(`${kind}:${ref.ref}`);
- }
- for (const item of m?.collection?.items || []) {
- if (!item?.ref || typeof item.ref !== 'string') continue;
- const kind = item.kind === 'video' ? 'video' : 'image';
- keys.add(`${kind}:${item.ref}`);
- }
- }));
- // Legacy v1 buckets predate manifest-as-authority: fall through to a
- // direct dir scan so existing buckets still advertise their assets.
+ const manifestsDir = join(bucketPath, 'manifests');
+ const dirStat = await stat(manifestsDir).catch(() => null);
+ const manifestsMtimeMs = dirStat ? dirStat.mtimeMs : MANIFESTS_DIR_ABSENT;
+
+ let manifestKeys;
+ const cached = manifestKeysCache.get(bucketPath);
+ if (cached && cached.manifestsMtimeMs === manifestsMtimeMs) {
+ manifestKeys = cached.manifestKeys;
+ } else {
+ manifestKeys = new Set();
+ const filenames = await listManifestFilenames(bucketPath);
+ await Promise.all(filenames.map(async (filename) => {
+ const m = await readManifest(bucketPath, filename).catch(() => null);
+ for (const ref of m?.assetRefs || []) {
+ if (!ref?.ref || typeof ref.ref !== 'string') continue;
+ const kind = ref.kind === 'video' ? 'video' : 'image';
+ manifestKeys.add(`${kind}:${ref.ref}`);
+ }
+ for (const item of m?.collection?.items || []) {
+ if (!item?.ref || typeof item.ref !== 'string') continue;
+ const kind = item.kind === 'video' ? 'video' : 'image';
+ manifestKeys.add(`${kind}:${item.ref}`);
+ }
+ }));
+ manifestKeysCache.set(bucketPath, { manifestsMtimeMs, manifestKeys });
+ }
+
+ // Copy so callers can't mutate the cached set, then layer on the legacy
+ // v1 dir scan (small; runs every call).
+ const keys = new Set(manifestKeys);
for (const [subdir, kind] of [['images', 'image'], ['videos', 'video']]) {
const dir = join(bucketPath, 'assets', subdir);
if (!existsSync(dir)) continue;
@@ -58,6 +92,11 @@ async function listBucketAssetKeys(bucketPath) {
return keys;
}
+/** Test hook — reset the per-bucket manifest-keys cache between cases. */
+export function _resetBucketAssetKeysCache() {
+ manifestKeysCache.clear();
+}
+
export async function exportAnnotationsToBucket(bucket, localAnnotations, senderInstanceId) {
if (bucket.mode !== 'auto-merge') return { skipped: true, reason: 'not-auto-merge' };
const recordDir = join(bucket.path, 'records', 'media-annotations');
diff --git a/server/services/sharing/annotationsSync.test.js b/server/services/sharing/annotationsSync.test.js
index 0343cc42c6..15b2cddb47 100644
--- a/server/services/sharing/annotationsSync.test.js
+++ b/server/services/sharing/annotationsSync.test.js
@@ -51,10 +51,13 @@ vi.mock('fs', async () => {
return { ...actual, existsSync: vi.fn(() => false) };
});
-// Stub `assets/{images,videos}` readdir to return [] (legacy v1 fallback).
+// Stub `assets/{images,videos}` readdir to return [] (legacy v1 fallback) and
+// `stat` so the manifests-dir mtime can be driven from individual tests (used
+// by the cache hit/miss assertions).
+const statMock = vi.fn(async () => ({ mtimeMs: 1 }));
vi.mock('fs/promises', async () => {
const actual = await vi.importActual('fs/promises');
- return { ...actual, readdir: vi.fn(async () => []) };
+ return { ...actual, readdir: vi.fn(async () => []), stat: statMock };
});
const svc = await import('./annotationsSync.js');
@@ -68,6 +71,9 @@ describe('sharing/annotationsSync.exportAnnotationsToBucket', () => {
fileStore.clear();
writeCalls.length = 0;
writeManifestMock.mockClear();
+ svc._resetBucketAssetKeysCache();
+ statMock.mockReset();
+ statMock.mockResolvedValue({ mtimeMs: 1 });
});
async function stubBucketAssets(bucketPath, keys) {
@@ -188,3 +194,113 @@ describe('sharing/annotationsSync.exportAnnotationsToBucket', () => {
expect(res).toEqual({ skipped: true, reason: 'not-auto-merge' });
});
});
+
+describe('sharing/annotationsSync.listBucketAssetKeys cache', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ writeCalls.length = 0;
+ writeManifestMock.mockClear();
+ svc._resetBucketAssetKeysCache();
+ statMock.mockReset();
+ statMock.mockResolvedValue({ mtimeMs: 100 });
+ });
+
+ it('reuses parsed manifests on the next flush when manifests-dir mtime is unchanged', async () => {
+ const { listManifestFilenames, readManifest } = await import('./manifest.js');
+ listManifestFilenames.mockClear();
+ readManifest.mockClear();
+ listManifestFilenames.mockResolvedValue(['a.manifest.json']);
+ readManifest.mockResolvedValue({ assetRefs: [{ kind: 'image', ref: 'a.png' }], collection: null });
+
+ const ann = { 'image:a.png': { starred: true, note: 'hi', updatedAt: '2026-01-01T00:00:00.000Z' } };
+ await svc.exportAnnotationsToBucket(bucket(), ann, 'local-instance');
+ await svc.exportAnnotationsToBucket(bucket(), ann, 'local-instance');
+ await svc.exportAnnotationsToBucket(bucket(), ann, 'local-instance');
+
+ // Three flushes — the manifests-dir mtime never moved, so the manifest
+ // parse only ran on the first call. The other two are cache hits.
+ expect(listManifestFilenames).toHaveBeenCalledTimes(1);
+ expect(readManifest).toHaveBeenCalledTimes(1);
+ });
+
+ it('invalidates when manifests-dir mtime advances (new/removed manifest)', async () => {
+ const { listManifestFilenames, readManifest } = await import('./manifest.js');
+ listManifestFilenames.mockClear();
+ readManifest.mockClear();
+ listManifestFilenames.mockResolvedValue(['a.manifest.json']);
+ readManifest.mockResolvedValue({ assetRefs: [{ kind: 'image', ref: 'a.png' }], collection: null });
+
+ const ann = { 'image:a.png': { starred: true, note: 'hi', updatedAt: '2026-01-01T00:00:00.000Z' } };
+ await svc.exportAnnotationsToBucket(bucket(), ann, 'local-instance');
+ // Bucket gains a new manifest — atomicWrite's temp+rename bumps the dir
+ // mtime. The next flush must re-scan.
+ statMock.mockResolvedValue({ mtimeMs: 200 });
+ listManifestFilenames.mockResolvedValue(['a.manifest.json', 'b.manifest.json']);
+ await svc.exportAnnotationsToBucket(bucket(), ann, 'local-instance');
+
+ expect(listManifestFilenames).toHaveBeenCalledTimes(2);
+ expect(readManifest).toHaveBeenCalledTimes(3); // 1 first call + 2 on re-scan
+ });
+
+ it('keeps separate cache entries per bucket path', async () => {
+ const { listManifestFilenames, readManifest } = await import('./manifest.js');
+ listManifestFilenames.mockClear();
+ readManifest.mockClear();
+ listManifestFilenames.mockResolvedValue(['a.manifest.json']);
+ readManifest.mockResolvedValue({ assetRefs: [{ kind: 'image', ref: 'a.png' }], collection: null });
+
+ const ann = { 'image:a.png': { starred: true, note: 'hi', updatedAt: '2026-01-01T00:00:00.000Z' } };
+ await svc.exportAnnotationsToBucket(bucket({ path: '/mock/bucket-A' }), ann, 'local-instance');
+ await svc.exportAnnotationsToBucket(bucket({ path: '/mock/bucket-B' }), ann, 'local-instance');
+ await svc.exportAnnotationsToBucket(bucket({ path: '/mock/bucket-A' }), ann, 'local-instance');
+ await svc.exportAnnotationsToBucket(bucket({ path: '/mock/bucket-B' }), ann, 'local-instance');
+
+ // Two cache misses (one per bucket), two cache hits.
+ expect(listManifestFilenames).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not cache the legacy v1 assets-dir fallthrough across calls', async () => {
+ // v1 buckets have no manifests at all — `listManifestFilenames` returns []
+ // and the only key source is the assets/{images,videos} dir scan. That
+ // scan must run every call so newly-dropped legacy files are picked up
+ // without needing a manifest-dir mtime bump.
+ const fs = await import('fs');
+ const fsp = await import('fs/promises');
+ const { listManifestFilenames } = await import('./manifest.js');
+ listManifestFilenames.mockClear();
+ listManifestFilenames.mockResolvedValue([]);
+ fs.existsSync.mockReturnValue(true);
+ fsp.readdir.mockClear();
+ fsp.readdir.mockResolvedValueOnce(['a.png']).mockResolvedValueOnce([]);
+ fsp.readdir.mockResolvedValueOnce(['a.png', 'b.png']).mockResolvedValueOnce([]);
+
+ const ann = { 'image:a.png': { starred: true, note: 'hi', updatedAt: '2026-01-01T00:00:00.000Z' } };
+ const r1 = await svc.exportAnnotationsToBucket(bucket(), ann, 'local-instance');
+ const r2 = await svc.exportAnnotationsToBucket(bucket(), ann, 'local-instance');
+ fs.existsSync.mockReturnValue(false);
+ expect(r1.skipped).toBe(false);
+ expect(r2.skipped).toBe(false);
+ // Each call scans both image+video dirs (4 readdir calls total over 2
+ // flushes). If the legacy scan were incorrectly cached this would be 2.
+ expect(fsp.readdir).toHaveBeenCalledTimes(4);
+ });
+
+ it('treats an absent manifests dir as a stable cache key', async () => {
+ // Brand-new bucket with no manifests/ dir yet — stat rejects with ENOENT.
+ // We still want cache reuse so repeated flushes against the same empty
+ // bucket don't keep re-running listManifestFilenames.
+ const { listManifestFilenames, readManifest } = await import('./manifest.js');
+ statMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
+ listManifestFilenames.mockClear();
+ readManifest.mockClear();
+ listManifestFilenames.mockResolvedValue([]);
+
+ const ann = { 'image:a.png': { starred: true, note: 'hi', updatedAt: '2026-01-01T00:00:00.000Z' } };
+ await svc.exportAnnotationsToBucket(bucket(), ann, 'local-instance');
+ await svc.exportAnnotationsToBucket(bucket(), ann, 'local-instance');
+
+ // listManifestFilenames runs once on the first call; second call hits the
+ // cache even though the dir doesn't exist on disk.
+ expect(listManifestFilenames).toHaveBeenCalledTimes(1);
+ });
+});