feat(server): registry snapshot() — effective storage config with provenance

This commit is contained in:
jubnl
2026-08-20 07:58:10 +02:00
parent 261c67d572
commit 5dc78dd5cf
2 changed files with 119 additions and 3 deletions
@@ -22,6 +22,19 @@ export interface ResolvedCategory {
backendName: string;
}
export type BackendSource = 'built-in' | 'env' | 'settings';
export interface BackendSnapshot {
name: string;
type: 'local' | 's3' | 'mirror';
source: BackendSource;
/** Stored options — secret fields still encrypted; masking is the admin layer's job. */
options: Record<string, string | number | string[]>;
}
export interface RegistrySnapshot {
backends: BackendSnapshot[];
categories: Record<StorageCategory, { backend: string; source: 'default' | 'settings' }>;
}
interface LocalBackendConfig {
name: string;
type: 'local';
@@ -51,6 +64,7 @@ type BackendConfig = LocalBackendConfig | MirrorBackendConfig | S3BackendConfig;
interface RegistryState {
drivers: Map<string, StorageDriver>;
categories: Map<StorageCategory, { backendName: string; keyPrefix: string }>;
snapshot: RegistrySnapshot;
}
const BACKENDS_KEY = 'storage.backends';
@@ -136,6 +150,12 @@ export class StorageRegistryService implements OnModuleInit {
return { driver, keyPrefix: assignment.keyPrefix, backendName: assignment.backendName };
}
/** The effective world with provenance — the admin GET renders from this. */
snapshot(): RegistrySnapshot {
if (!this.state) throw new StorageBackendError('storage registry not initialized');
return this.state.snapshot;
}
/** Driver-agnostic global scratch space (data/tmp). */
tempDir(): string {
return GLOBAL_TEMP_DIR;
@@ -251,17 +271,27 @@ export class StorageRegistryService implements OnModuleInit {
const backends = new Map<string, BackendConfig>();
backends.set('uploads-local', { name: 'uploads-local', type: 'local', options: { root: DEFAULT_UPLOADS_ROOT } });
backends.set('backups-local', { name: 'backups-local', type: 'local', options: { root: DEFAULT_BACKUPS_ROOT } });
const backendSources = new Map<string, BackendSource>([
['uploads-local', 'built-in'],
['backups-local', 'built-in'],
]);
if (placePhotoDir) {
backends.set('place-photos-local', { name: 'place-photos-local', type: 'local', options: { root: placePhotoDir } });
backendSources.set('place-photos-local', 'env');
}
for (const config of parseBackendList(settings.backends)) {
backends.set(config.name, config);
backendSources.set(config.name, 'settings');
}
for (const config of parseBackendList(settings.backends)) backends.set(config.name, config);
const categoryBackends = new Map<StorageCategory, string>();
for (const category of STORAGE_CATEGORIES) categoryBackends.set(category, 'uploads-local');
categoryBackends.set('backups', 'backups-local');
if (placePhotoDir) categoryBackends.set('photos-google', 'place-photos-local');
const categorySources = new Map<StorageCategory, 'default' | 'settings'>();
for (const [category, backendName] of parseCategoryMap(settings.categories)) {
categoryBackends.set(category, backendName);
categorySources.set(category, 'settings');
}
// 3. Validate the merged config as a whole.
@@ -311,8 +341,25 @@ export class StorageRegistryService implements OnModuleInit {
}
fs.mkdirSync(GLOBAL_TEMP_DIR, { recursive: true });
// 6. Single-assignment swap — callers mid-operation keep their instances.
return { drivers, categories };
// 6. The effective world with provenance — assembled from the same merged
// maps, so it always matches what drivers/categories actually resolve to.
const snapshot: RegistrySnapshot = {
backends: [...backends.values()].map((config) => ({
name: config.name,
type: config.type,
source: backendSources.get(config.name) ?? 'settings',
options: { ...config.options },
})),
categories: Object.fromEntries(
[...categoryBackends.entries()].map(([category, backendName]) => [
category,
{ backend: backendName, source: categorySources.get(category) ?? 'default' },
]),
) as RegistrySnapshot['categories'],
};
// 7. Single-assignment swap — callers mid-operation keep their instances.
return { drivers, categories, snapshot };
}
}
@@ -590,3 +590,72 @@ describe('seed-once storage-config.json import', () => {
expect(second.resolve('backups').backendName).toBe('nas');
});
});
// ── snapshot() — effective world with provenance ──────────────────────────────
describe('snapshot()', () => {
it('reports built-ins, env backends, and settings entries with their sources', () => {
const photoDir = makeTmpDir();
const nasRoot = makeTmpDir();
const { registry, uploadsRoot } = makeRegistry({
placePhotoDir: photoDir,
backends: [{ name: 'nas-backups', type: 'local', options: { root: nasRoot } }],
categories: { backups: 'nas-backups' },
});
const snap = registry.snapshot();
const byName = new Map(snap.backends.map((b) => [b.name, b]));
// uploads-local is overridden by the helper's settings row → source 'settings'
expect(byName.get('uploads-local')).toMatchObject({ type: 'local', source: 'settings', options: { root: uploadsRoot } });
expect(byName.get('backups-local')).toMatchObject({ source: 'built-in' });
expect(byName.get('place-photos-local')).toMatchObject({ source: 'env', options: { root: photoDir } });
expect(byName.get('nas-backups')).toMatchObject({ source: 'settings' });
expect(snap.categories.backups).toEqual({ backend: 'nas-backups', source: 'settings' });
expect(snap.categories.files).toEqual({ backend: 'uploads-local', source: 'default' });
expect(snap.categories['photos-google']).toEqual({ backend: 'place-photos-local', source: 'default' });
expect(Object.keys(snap.categories).sort()).toEqual([...STORAGE_CATEGORIES].sort());
});
it('reports pure built-in defaults when no settings rows exist', () => {
const { registry } = makeRegistry({ boot: false });
testDb.prepare("DELETE FROM app_settings WHERE key = 'storage.backends'").run();
registry.onModuleInit();
const snap = registry.snapshot();
expect(snap.backends.map((b) => [b.name, b.source])).toEqual([
['uploads-local', 'built-in'],
['backups-local', 'built-in'],
]);
});
it('keeps encrypted secrets encrypted in the snapshot (never plaintext)', () => {
const cipher = encrypt_api_key('sk-secret');
const { registry } = makeRegistry({
backends: [
{
name: 'off-box',
type: 's3',
options: {
endpoint: 'http://127.0.0.1:9000',
bucket: 'trek',
accessKeyId: 'ak',
secretAccessKey: cipher,
},
},
],
categories: { backups: 'off-box' },
});
const offBox = registry.snapshot().backends.find((b) => b.name === 'off-box')!;
expect(offBox.options.secretAccessKey).toBe(cipher); // byte-identical ciphertext
expect(offBox.options).toMatchObject({ region: 'us-east-1', retries: 1 }); // schema defaults visible
});
it('shows the last-good world after an invalid reload (snapshot = live state)', () => {
vi.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
const { registry } = makeRegistry();
const before = registry.snapshot();
setSetting('storage.categories', 'garbage {');
registry.reload();
expect(registry.snapshot()).toEqual(before);
});
});