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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([sharing-annotationssync-cache-bucket-asset-keys]): /simplify pass on listBucketAssetKeys cache
[._.]/ Adam Eivybd74daa1f3df
diff --git a/server/services/sharing/annotationsSync.js b/server/services/sharing/annotationsSync.jsindex ac41890cde..80d8ca3a9e 100644--- a/server/services/sharing/annotationsSync.js+++ b/server/services/sharing/annotationsSync.js@@ -33,11 +33,9 @@ let installed = false;* per flush. With the cache the steady-state cost drops to one `stat` per* bucket.*- * @type {Map<string, { manifestsMtimeMs: number, manifestKeys: Set<string> }>}+ * @type {Map<string, { manifestsMtimeMs: number | null, 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@@ -47,15 +45,31 @@ const MANIFESTS_DIR_ABSENT = -1;* 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.+ * legacy v1 dir scan is small and runs uncached. Callers must treat the+ * returned Set as read-only — the cache may hand back the same Set instance+ * to subsequent callers when the legacy fall-through adds nothing (the+ * common v2-only path), so mutating it would poison the next cache hit.*/async function listBucketAssetKeys(bucketPath) {const manifestsDir = join(bucketPath, 'manifests');- const dirStat = await stat(manifestsDir).catch(() => null);- const manifestsMtimeMs = dirStat ? dirStat.mtimeMs : MANIFESTS_DIR_ABSENT;+ // ENOENT (dir not created yet) is normal; null is a stable cache key.+ // Other errors (EACCES, EIO) are surfaced via a warning + uncached scan so+ // a real permission/IO problem is observable instead of being swallowed+ // into a phantom `unknown` mtime.+ let manifestsMtimeMs = null;+ let cacheable = true;+ const dirStat = await stat(manifestsDir).catch((err) => err);+ if (dirStat instanceof Error) {+ if (dirStat.code !== 'ENOENT') {+ console.error(`⚠️ sharing.annotations: stat(${manifestsDir}) failed code=${dirStat.code}: ${dirStat.message}`);+ cacheable = false;+ }+ } else {+ manifestsMtimeMs = dirStat.mtimeMs;+ }let manifestKeys;- const cached = manifestKeysCache.get(bucketPath);+ const cached = cacheable ? manifestKeysCache.get(bucketPath) : null;if (cached && cached.manifestsMtimeMs === manifestsMtimeMs) {manifestKeys = cached.manifestKeys;} else {@@ -74,26 +88,29 @@ async function listBucketAssetKeys(bucketPath) {manifestKeys.add(`${kind}:${item.ref}`);}}));- manifestKeysCache.set(bucketPath, { manifestsMtimeMs, manifestKeys });+ if (cacheable) 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);+ // Layer on the legacy v1 dir scan (small; runs every call). The common+ // v2-native bucket has no `assets/{images,videos}/` so we return the+ // cached Set unmodified and avoid the per-call copy entirely.+ let legacyKeys = null;for (const [subdir, kind] of [['images', 'image'], ['videos', 'video']]) {const dir = join(bucketPath, 'assets', subdir);if (!existsSync(dir)) continue;const files = await readdir(dir).catch(() => []);for (const f of files) {if (f.endsWith('.metadata.json')) continue;- keys.add(`${kind}:${f}`);+ if (!legacyKeys) legacyKeys = new Set();+ legacyKeys.add(`${kind}:${f}`);}}- return keys;+ if (!legacyKeys) return manifestKeys;+ return new Set([...manifestKeys, ...legacyKeys]);}/** Test hook — reset the per-bucket manifest-keys cache between cases. */-export function _resetBucketAssetKeysCache() {+export function __resetBucketAssetKeysCache() {manifestKeysCache.clear();}diff --git a/server/services/sharing/annotationsSync.test.js b/server/services/sharing/annotationsSync.test.jsindex 15b2cddb47..e1ea79c4cd 100644--- a/server/services/sharing/annotationsSync.test.js+++ b/server/services/sharing/annotationsSync.test.js@@ -71,7 +71,7 @@ describe('sharing/annotationsSync.exportAnnotationsToBucket', () => {fileStore.clear();writeCalls.length = 0;writeManifestMock.mockClear();- svc._resetBucketAssetKeysCache();+ svc.__resetBucketAssetKeysCache();statMock.mockReset();statMock.mockResolvedValue({ mtimeMs: 1 });});@@ -200,7 +200,7 @@ describe('sharing/annotationsSync.listBucketAssetKeys cache', () => {fileStore.clear();writeCalls.length = 0;writeManifestMock.mockClear();- svc._resetBucketAssetKeysCache();+ svc.__resetBucketAssetKeysCache();statMock.mockReset();statMock.mockResolvedValue({ mtimeMs: 100 });});@@ -285,6 +285,62 @@ describe('sharing/annotationsSync.listBucketAssetKeys cache', () => {expect(fsp.readdir).toHaveBeenCalledTimes(4);});+ it('skips caching when stat fails with a non-ENOENT error so the real fault stays observable', async () => {+ const { listManifestFilenames, readManifest } = await import('./manifest.js');+ const eacces = Object.assign(new Error('EACCES'), { code: 'EACCES' });+ statMock.mockRejectedValue(eacces);+ listManifestFilenames.mockClear();+ readManifest.mockClear();+ listManifestFilenames.mockResolvedValue(['a.manifest.json']);+ readManifest.mockResolvedValue({ assetRefs: [{ kind: 'image', ref: 'a.png' }], collection: null });+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ 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');++ // Both calls re-scan because EACCES poisons caching for this bucket.+ expect(listManifestFilenames).toHaveBeenCalledTimes(2);+ expect(errSpy).toHaveBeenCalled();+ errSpy.mockRestore();+ });++ it('layers legacy v1 keys onto the manifest set without polluting the cache for the next call', async () => {+ // First call has v1 dirs populated → returned Set contains the v1 key.+ // Second call has v1 dirs empty → returned Set must NOT contain the v1+ // key. If the legacy fall-through had `.add()`d into the cached manifest+ // set instead of allocating a fresh union Set, the second call would+ // still see the stale v1 key. We probe this by feeding an annotation+ // that ONLY matches the v1 key: it should write on call 1 (legacy+ // present) and skip on call 2 (legacy gone, manifest set untouched).+ const fs = await import('fs');+ const fsp = await import('fs/promises');+ 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 });++ fs.existsSync.mockReturnValue(true);+ fsp.readdir.mockResolvedValueOnce(['rogue.png']).mockResolvedValueOnce([]);+ const ann = { 'image:rogue.png': { starred: true, note: 'hi', updatedAt: '2026-01-01T00:00:00.000Z' } };+ const r1 = await svc.exportAnnotationsToBucket(bucket(), ann, 'local-instance');+ expect(r1.skipped).toBe(false); // v1 fall-through provided the matching key++ // v1 dirs disappear (deleted between flushes); cached manifest set must+ // not have absorbed the v1 key on the prior call.+ fs.existsSync.mockReturnValue(false);+ fsp.readdir.mockResolvedValue([]);+ // Drop the prior record so the late-stage tombstone path doesn't write.+ fileStore.delete('/mock/bucket/records/media-annotations/local-instance.json');+ const r2 = await svc.exportAnnotationsToBucket(bucket(), ann, 'local-instance');+ expect(r2.skipped).toBe(true);+ expect(r2.reason).toBe('no-annotations-for-bucket');+ // Manifest parse stays cached across both calls — the mutation defense+ // does not compromise the hit rate.+ expect(listManifestFilenames).toHaveBeenCalledTimes(1);+ });+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