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-exporter-cache-sourcefile-hash-by-mtime]): cache exporter asset hashes by sourcePath+mtime+size

[._.]/ Adam Eivy7a07fb119625
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3ef93f3edb..30d810f8a5 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Per-bucket exporter hash cache.** Subscription re-exports of large series no longer re-hash every referenced asset to confirm "blob already there." A new `<bucket>/assets/blobs/.index.json` sidecar maps `<sourcePath>:<mtimeMs>:<size> → <hash>` so `server/services/sharing/exporter.js#copyAssetIfPresent` skips both `sha256File` (multi-GB stream read) and the redundant `copyFile` when the cache hit's blob is still on disk. mtime change invalidates automatically because it's part of the key. A 200MB re-export drops from ~200MB of disk reads to a single JSON load + stat per asset.
+
## Changed
- **First-run no longer silently flips :5555 from HTTP to self-signed HTTPS.** `scripts/setup-cert.js` ran on every `npm start` and, when Tailscale was unavailable, auto-generated a self-signed cert — breaking the documented `http://localhost:5555` URL and forcing a browser click-through. It now only auto-generates a self-signed cert when (a) the user explicitly passes `--self-signed`, or (b) a self-signed cert is already present (renewal path). Fresh installs without Tailscale stay HTTP-only on :5555 so the URL in the README and in `setup.sh`'s final banner just works. `setup.sh`'s "Access at:" banner is now cert-aware — when HTTPS got provisioned it prints the loopback HTTP mirror (`http://localhost:5553`) and the Tailscale hostname instead of the broken `http://localhost:5555`.
diff --git a/server/services/sharing/buckets.js b/server/services/sharing/buckets.js
index e98e53bb4e..fb244c0360 100644
--- a/server/services/sharing/buckets.js
+++ b/server/services/sharing/buckets.js
@@ -101,6 +101,9 @@ export function bucketBlobSidecarPath(bucketPath, hash) {
if (!isHexHash(hash)) throw makeErr(`Invalid asset hash: ${hash}`, ERR_VALIDATION);
return join(bucketBlobsDir(bucketPath), `${hash}.metadata.json`);
}
+// Sidecar mapping `<sourcePath>:<mtimeMs>:<size> → <hash>` so the exporter can
+// skip `sha256File` + `copyFile` on re-export of unchanged assets.
+export function bucketBlobIndexPath(bucketPath) { return join(bucketBlobsDir(bucketPath), '.index.json'); }
export function imageSidecarName(filename) { return filename.replace(IMAGE_EXT_RE, '') + '.metadata.json'; }
/** Lay out the canonical bucket structure (idempotent). */
diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.js
index 8779647642..dac7e25b1a 100644
--- a/server/services/sharing/exporter.js
+++ b/server/services/sharing/exporter.js
@@ -19,7 +19,7 @@ import { join, basename } from 'path';
import { copyFile, readFile, writeFile, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { PATHS, ensureDir, atomicWrite, readJSONFile, sha256File } from '../../lib/fileUtils.js';
-import { getBucket, ensureBucketLayout, bucketBlobsDir, bucketBlobPath, bucketBlobSidecarPath, imageSidecarName } from './buckets.js';
+import { getBucket, ensureBucketLayout, bucketBlobsDir, bucketBlobPath, bucketBlobSidecarPath, bucketBlobIndexPath, imageSidecarName, isHexHash } from './buckets.js';
import { buildManifest, writeManifest, pruneBucketManifests } from './manifest.js';
import { listSeries, getSeries } from '../pipeline/series.js';
import { listIssues } from '../pipeline/issues.js';
@@ -72,22 +72,67 @@ const ASSET_SOURCE_DIRS = Object.freeze({
'image-ref': PATHS.imageRefs,
});
-async function copyAssetIfPresent(filename, kind, bucketPath) {
+/**
+ * Per-bucket sidecar mapping `<sourcePath>:<mtimeMs>:<size> → <hash>` so a
+ * re-export of an unchanged asset skips both `sha256File` (multi-GB stream
+ * read) and the redundant `copyFile`. mtime change invalidates because it's
+ * part of the key. The cache lives next to the blobs so it shares lifetime
+ * with the bucket. See `[sharing-exporter-cache-sourcefile-hash-by-mtime]`.
+ *
+ * `withAssetHashCache` owns the load/mutate/save lifetime: it loads once,
+ * runs the body, and only writes when entries were added. Pre-write, it
+ * re-reads from disk and merges so a sibling exporter (e.g. `exportByKind`
+ * fanning out parallel `exportSeries` against the same bucket) doesn't get
+ * its accumulated entries clobbered — same-key collisions converge to the
+ * same hash since the hash derives from bytes and the key embeds mtime+size.
+ */
+async function loadAssetHashCache(bucketPath) {
+ const raw = await readJSONFile(bucketBlobIndexPath(bucketPath), {}, { logError: false });
+ return (raw && typeof raw === 'object' && !Array.isArray(raw)) ? raw : {};
+}
+
+// Per-bucket cache-write tail — serializes the re-load → merge → atomicWrite
+// step so two concurrent exporters (e.g. `exportByKind` fanning out parallel
+// `exportSeries`) accumulate entries instead of clobbering. Mirrors the
+// `issueWriteTail` pattern in `pipeline/issues.js`.
+const cacheWriteTails = new Map();
+
+async function withAssetHashCache(bucketPath, fn) {
+ const cache = await loadAssetHashCache(bucketPath);
+ const initialKeys = Object.keys(cache).length;
+ const result = await fn(cache);
+ if (Object.keys(cache).length !== initialKeys) {
+ const prevTail = cacheWriteTails.get(bucketPath) || Promise.resolve();
+ const tail = prevTail.then(async () => {
+ const onDisk = await loadAssetHashCache(bucketPath);
+ await atomicWrite(bucketBlobIndexPath(bucketPath), { ...onDisk, ...cache });
+ });
+ cacheWriteTails.set(bucketPath, tail);
+ await tail;
+ }
+ return result;
+}
+
+async function copyAssetIfPresent(filename, kind, bucketPath, cache) {
if (!filename || typeof filename !== 'string') return null;
const base = basename(filename);
if (!base || base !== filename) return null; // refuse path traversal
const sourceDir = ASSET_SOURCE_DIRS[kind] || PATHS.images;
await ensureDir(bucketBlobsDir(bucketPath));
const sourcePath = join(sourceDir, base);
- if (!existsSync(sourcePath)) {
+ const info = await stat(sourcePath).catch(() => null);
+ if (!info) {
console.log(`⚠️ sharing.exporter: asset not found locally, skipping: ${sourcePath}`);
return null;
}
- const hash = await sha256File(sourcePath);
- const blobPath = bucketBlobPath(bucketPath, hash);
- if (!existsSync(blobPath)) {
- await copyFile(sourcePath, blobPath);
+ const cacheKey = `${sourcePath}:${info.mtimeMs}:${info.size}`;
+ let hash = cache && isHexHash(cache[cacheKey]) ? cache[cacheKey] : null;
+ if (!hash || !existsSync(bucketBlobPath(bucketPath, hash))) {
+ hash = await sha256File(sourcePath);
+ if (cache) cache[cacheKey] = hash;
}
+ const blobPath = bucketBlobPath(bucketPath, hash);
+ if (!existsSync(blobPath)) await copyFile(sourcePath, blobPath);
if (kind === 'image') {
const sidecarSource = join(sourceDir, imageSidecarName(base));
if (existsSync(sidecarSource)) {
@@ -149,7 +194,7 @@ async function jobFromSidecar(jobId) {
* per-image `.metadata.json` sidecar for jobs older than the 24h archive TTL.
* Returns the asset refs (image filenames) discovered.
*/
-async function exportMediaJobAndAsset(jobId, bucketPath, mediaRecordsDir) {
+async function exportMediaJobAndAsset(jobId, bucketPath, mediaRecordsDir, cache) {
if (!jobId || !isStr(jobId)) return [];
const job = getJob(jobId) || await jobFromSidecar(jobId);
if (!job) {
@@ -174,20 +219,20 @@ async function exportMediaJobAndAsset(jobId, bucketPath, mediaRecordsDir) {
// result.filename is the canonical single-output shape; some video paths use
// result.videoPath / result.thumbnail; handle both defensively.
if (job.result?.filename) {
- const ref = await copyAssetIfPresent(job.result.filename, assetKind, bucketPath);
+ const ref = await copyAssetIfPresent(job.result.filename, assetKind, bucketPath, cache);
if (ref) refs.push(ref);
}
if (job.result?.videoPath) {
// videoPath is a filesystem path; we only need its basename here since
// copyAssetIfPresent rebuilds the source dir.
- const ref = await copyAssetIfPresent(basename(job.result.videoPath), 'video', bucketPath);
+ const ref = await copyAssetIfPresent(basename(job.result.videoPath), 'video', bucketPath, cache);
if (ref) refs.push(ref);
}
if (Array.isArray(job.result?.images)) {
for (const im of job.result.images) {
const fname = im?.filename || im?.path;
if (!fname) continue;
- const ref = await copyAssetIfPresent(basename(fname), assetKind, bucketPath);
+ const ref = await copyAssetIfPresent(basename(fname), assetKind, bucketPath, cache);
if (ref) refs.push(ref);
}
}
@@ -372,13 +417,15 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {
// Copy media-job records + their assets — run all four groups in parallel.
const mediaRecordsDir = join(bucket.path, 'records', 'media');
- const [jobRefGroups, imageRefs, videoRefs, imageRefRefs] = await Promise.all([
- Promise.all([...allJobIds].map((jobId) => exportMediaJobAndAsset(jobId, bucket.path, mediaRecordsDir))),
- Promise.all([...allImageFiles].map((f) => copyAssetIfPresent(f, 'image', bucket.path))),
- Promise.all([...allVideoFiles].map((f) => copyAssetIfPresent(f, 'video', bucket.path))),
- Promise.all([...allImageRefFiles].map((f) => copyAssetIfPresent(f, 'image-ref', bucket.path))),
- ]);
- const assetRefs = [...jobRefGroups.flat(), ...imageRefs.filter(Boolean), ...videoRefs.filter(Boolean), ...imageRefRefs.filter(Boolean)];
+ const assetRefs = await withAssetHashCache(bucket.path, async (cache) => {
+ const [jobRefGroups, imageRefs, videoRefs, imageRefRefs] = await Promise.all([
+ Promise.all([...allJobIds].map((jobId) => exportMediaJobAndAsset(jobId, bucket.path, mediaRecordsDir, cache))),
+ Promise.all([...allImageFiles].map((f) => copyAssetIfPresent(f, 'image', bucket.path, cache))),
+ Promise.all([...allVideoFiles].map((f) => copyAssetIfPresent(f, 'video', bucket.path, cache))),
+ Promise.all([...allImageRefFiles].map((f) => copyAssetIfPresent(f, 'image-ref', bucket.path, cache))),
+ ]);
+ return [...jobRefGroups.flat(), ...imageRefs.filter(Boolean), ...videoRefs.filter(Boolean), ...imageRefRefs.filter(Boolean)];
+ });
const manifest = { ...manifestStub, recordIds, assetRefs };
const filename = await writeManifest(bucket.path, manifest);
@@ -432,13 +479,15 @@ export async function exportUniverse(universeId, bucketId, opts = {}) {
const allImageRefFiles = new Set(universeRefs.directImageRefFilenames);
const mediaRecordsDir = join(bucket.path, 'records', 'media');
- const [jobRefGroups, imageRefs, videoRefs, imageRefRefs] = await Promise.all([
- Promise.all([...allJobIds].map((jobId) => exportMediaJobAndAsset(jobId, bucket.path, mediaRecordsDir))),
- Promise.all([...allImageFiles].map((f) => copyAssetIfPresent(f, 'image', bucket.path))),
- Promise.all([...allVideoFiles].map((f) => copyAssetIfPresent(f, 'video', bucket.path))),
- Promise.all([...allImageRefFiles].map((f) => copyAssetIfPresent(f, 'image-ref', bucket.path))),
- ]);
- const assetRefs = [...jobRefGroups.flat(), ...imageRefs.filter(Boolean), ...videoRefs.filter(Boolean), ...imageRefRefs.filter(Boolean)];
+ const assetRefs = await withAssetHashCache(bucket.path, async (cache) => {
+ const [jobRefGroups, imageRefs, videoRefs, imageRefRefs] = await Promise.all([
+ Promise.all([...allJobIds].map((jobId) => exportMediaJobAndAsset(jobId, bucket.path, mediaRecordsDir, cache))),
+ Promise.all([...allImageFiles].map((f) => copyAssetIfPresent(f, 'image', bucket.path, cache))),
+ Promise.all([...allVideoFiles].map((f) => copyAssetIfPresent(f, 'video', bucket.path, cache))),
+ Promise.all([...allImageRefFiles].map((f) => copyAssetIfPresent(f, 'image-ref', bucket.path, cache))),
+ ]);
+ return [...jobRefGroups.flat(), ...imageRefs.filter(Boolean), ...videoRefs.filter(Boolean), ...imageRefRefs.filter(Boolean)];
+ });
const manifest = { ...manifestStub, recordIds: [universe.id], assetRefs };
const filename = await writeManifest(bucket.path, manifest);
@@ -486,12 +535,14 @@ export async function exportMedia(items, bucketId) {
return [{ ref, kind, job: getJob(baseId) }];
});
const recordIds = resolved.filter((r) => r.job).map((r) => r.job.id);
- const results = await Promise.all(resolved.map(async (r) => {
- if (r.job) return exportMediaJobAndAsset(r.job.id, bucket.path, mediaRecordsDir);
- const copied = await copyAssetIfPresent(r.ref, r.kind, bucket.path);
- return copied ? [copied] : [];
- }));
- const assetRefs = results.flat();
+ const assetRefs = await withAssetHashCache(bucket.path, async (cache) => {
+ const results = await Promise.all(resolved.map(async (r) => {
+ if (r.job) return exportMediaJobAndAsset(r.job.id, bucket.path, mediaRecordsDir, cache);
+ const copied = await copyAssetIfPresent(r.ref, r.kind, bucket.path, cache);
+ return copied ? [copied] : [];
+ }));
+ return results.flat();
+ });
const manifest = { ...manifestStub, recordIds, assetRefs };
const filename = await writeManifest(bucket.path, manifest);
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index eda6e73aab..675e4f33b5 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -9,7 +9,7 @@
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-import { mkdtempSync, rmSync, writeFileSync, existsSync, mkdirSync, readFileSync } from 'fs';
+import { mkdtempSync, rmSync, writeFileSync, existsSync, mkdirSync, readFileSync, statSync, utimesSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { createHash } from 'crypto';
@@ -1094,9 +1094,10 @@ describe('sharing round-trip', () => {
await mediaCollections.addItem(collB.id, { kind: 'image', ref: 'beta.png' });
const expB = await exporter.exportUniverse(uniB.id, bucket.id);
- // Both manifests point at the same blob path; only one on-disk file exists.
+ // Both manifests point at the same blob path; only one on-disk blob file exists
+ // (the dotfile `.index.json` is the per-bucket source→hash cache, not a blob).
expect(fs.existsSync(join(tempBucket, 'assets', 'blobs', hash))).toBe(true);
- expect(fs.readdirSync(join(tempBucket, 'assets', 'blobs'))).toEqual([hash]);
+ expect(fs.readdirSync(join(tempBucket, 'assets', 'blobs')).filter((f) => !f.startsWith('.'))).toEqual([hash]);
// Each manifest's assetRef carries the hash + its own original filename.
const mA = JSON.parse(fs.readFileSync(join(tempBucket, 'manifests', expA.filename), 'utf-8'));
@@ -1382,4 +1383,70 @@ describe('sharing round-trip', () => {
expect(replay.skipped).toBe(true);
expect(replay.reason).toBe('already-processed');
});
+
+ it('writes <bucket>/assets/blobs/.index.json mapping sourcePath:mtime:size → hash and invalidates on mtime change', async () => {
+ const bucket = await buckets.createBucket({ name: 'CacheBucket', path: tempBucket, mode: 'auto-merge' });
+ const sourcePath = join(tempData, 'images', 'fakeasset.png'); // seeded as 'PNGSTUB' in beforeEach
+
+ // Single-asset export — exportMedia falls through to copyAssetIfPresent (getJob is mocked → null).
+ await exporter.exportMedia([{ kind: 'image', ref: 'fakeasset.png' }], bucket.id);
+
+ const indexPath = join(tempBucket, 'assets', 'blobs', '.index.json');
+ expect(existsSync(indexPath)).toBe(true);
+
+ const initialStat = statSync(sourcePath);
+ const initialKey = `${sourcePath}:${initialStat.mtimeMs}:${initialStat.size}`;
+ const initialHash = sha256Hex('PNGSTUB');
+ const idx1 = JSON.parse(readFileSync(indexPath, 'utf-8'));
+ expect(idx1[initialKey]).toBe(initialHash);
+
+ // Re-export unchanged file → cache hit → no new keys → index file not rewritten.
+ // Assert the index file's mtime is unchanged (dirty-flag short-circuits the write).
+ const indexMtimeBefore = statSync(indexPath).mtimeMs;
+ await new Promise((r) => setTimeout(r, 5));
+ await exporter.exportMedia([{ kind: 'image', ref: 'fakeasset.png' }], bucket.id);
+ expect(statSync(indexPath).mtimeMs).toBe(indexMtimeBefore);
+
+ // Bumping mtime alone (same bytes, same size) creates a new cache key — old entry stays,
+ // new entry covers the post-touch stat. The hash is unchanged because the bytes are the same.
+ const future = new Date(initialStat.mtimeMs + 60_000);
+ utimesSync(sourcePath, future, future);
+ await exporter.exportMedia([{ kind: 'image', ref: 'fakeasset.png' }], bucket.id);
+ const touchedStat = statSync(sourcePath);
+ const touchedKey = `${sourcePath}:${touchedStat.mtimeMs}:${touchedStat.size}`;
+ expect(touchedKey).not.toBe(initialKey);
+ const idx2 = JSON.parse(readFileSync(indexPath, 'utf-8'));
+ expect(idx2[touchedKey]).toBe(initialHash);
+
+ // Mutating content invalidates and records a fresh hash.
+ writeFileSync(sourcePath, 'PNGSTUB-v2');
+ await exporter.exportMedia([{ kind: 'image', ref: 'fakeasset.png' }], bucket.id);
+ const mutatedStat = statSync(sourcePath);
+ const mutatedKey = `${sourcePath}:${mutatedStat.mtimeMs}:${mutatedStat.size}`;
+ const idx3 = JSON.parse(readFileSync(indexPath, 'utf-8'));
+ expect(idx3[mutatedKey]).toBe(sha256Hex('PNGSTUB-v2'));
+ // Mutated bytes also land in the bucket under the new hash (content-addressed).
+ expect(existsSync(join(tempBucket, 'assets', 'blobs', sha256Hex('PNGSTUB-v2')))).toBe(true);
+ });
+
+ it('parallel exports against the same bucket merge cache entries instead of clobbering (exportByKind fanout)', async () => {
+ const bucket = await buckets.createBucket({ name: 'MergeBucket', path: tempBucket, mode: 'auto-merge' });
+ // Two distinct assets, both seeded with distinct bytes so they hash differently.
+ writeFileSync(join(tempData, 'images', 'parallelA.png'), 'PARALLEL_A');
+ writeFileSync(join(tempData, 'images', 'parallelB.png'), 'PARALLEL_B');
+ // Two singleton media exports run in parallel — each loads its own cache view,
+ // each saves with merge-on-save. Both new keys must survive in the persisted index.
+ await Promise.all([
+ exporter.exportMedia([{ kind: 'image', ref: 'parallelA.png' }], bucket.id),
+ exporter.exportMedia([{ kind: 'image', ref: 'parallelB.png' }], bucket.id),
+ ]);
+ const indexPath = join(tempBucket, 'assets', 'blobs', '.index.json');
+ const idx = JSON.parse(readFileSync(indexPath, 'utf-8'));
+ const statA = statSync(join(tempData, 'images', 'parallelA.png'));
+ const statB = statSync(join(tempData, 'images', 'parallelB.png'));
+ const keyA = `${join(tempData, 'images', 'parallelA.png')}:${statA.mtimeMs}:${statA.size}`;
+ const keyB = `${join(tempData, 'images', 'parallelB.png')}:${statB.mtimeMs}:${statB.size}`;
+ expect(idx[keyA]).toBe(sha256Hex('PARALLEL_A'));
+ expect(idx[keyB]).toBe(sha256Hex('PARALLEL_B'));
+ });
});