Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

refactor: migrate default Site ownership and bind historical storage revisions

HoshinoSuzumiBot6eab85c2cb7e
diff --git a/package.json b/package.json
index 60a55d2e..06f00432 100644
--- a/package.json
+++ b/package.json
@@ -16,7 +16,7 @@
"db:check": "drizzle-kit check",
"db:up": "drizzle-kit up",
"db:generate": "drizzle-kit generate",
- "db:migrate": "drizzle-kit migrate",
+ "db:migrate": "node --experimental-strip-types scripts/migrate-database.ts",
"build": "NODE_OPTIONS=\"--max-old-space-size=8192\" nuxt build",
"build:deps": "pnpm --filter @chronoframe/webgl-image build",
"dev": "run-p dev:dep dev:wait-only",
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 8fb82707..419f3129 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -144,3 +144,5 @@ export * from './settings.ts'
export * from './uploads.ts'
export * from './access.ts'
export * from './upload-preparation.ts'
+
+export * from './site.ts'
diff --git a/packages/core/src/site.ts b/packages/core/src/site.ts
new file mode 100644
index 00000000..216fd849
--- /dev/null
+++ b/packages/core/src/site.ts
@@ -0,0 +1,14 @@
+/** A trusted application boundary supplies this context; never accept a caller-selected header. */
+export interface SiteContext {
+ readonly id: number
+}
+export const DEFAULT_SITE: SiteContext = Object.freeze({ id: 1 })
+export function assertSiteContext(site: SiteContext): void {
+ if (!site || !Number.isSafeInteger(site.id) || site.id < 1)
+ throw new RangeError('A valid Site context is required')
+}
+/** Length framing prevents key collisions when logical keys contain separators. */
+export function siteCacheKey(site: SiteContext, key: string): string {
+ assertSiteContext(site)
+ return `site:${site.id}:${key.length}:${key}`
+}
diff --git a/packages/database/migrations/0018_site_ownership.sql b/packages/database/migrations/0018_site_ownership.sql
new file mode 100644
index 00000000..fb7802fb
--- /dev/null
+++ b/packages/database/migrations/0018_site_ownership.sql
@@ -0,0 +1,256 @@
+CREATE TABLE workspaces (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL);
+--> statement-breakpoint
+CREATE TABLE sites (id INTEGER PRIMARY KEY AUTOINCREMENT, workspace_id INTEGER NOT NULL REFERENCES workspaces(id), name TEXT NOT NULL);
+--> statement-breakpoint
+CREATE TABLE memberships (workspace_id INTEGER NOT NULL REFERENCES workspaces(id), user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, role TEXT NOT NULL CHECK(role IN ('admin','member')), PRIMARY KEY(workspace_id,user_id));
+--> statement-breakpoint
+INSERT INTO workspaces(id,name) VALUES (1,'Default Workspace');
+--> statement-breakpoint
+INSERT INTO sites(id,workspace_id,name) VALUES (1,1,'Default Site');
+--> statement-breakpoint
+INSERT INTO memberships(workspace_id,user_id,role) SELECT 1,id,CASE WHEN is_admin = 1 THEN 'admin' ELSE 'member' END FROM users;
+--> statement-breakpoint
+CREATE TRIGGER default_user_membership AFTER INSERT ON users BEGIN INSERT OR IGNORE INTO memberships(workspace_id,user_id,role) VALUES(1,NEW.id,CASE WHEN NEW.is_admin = 1 THEN 'admin' ELSE 'member' END); END;
+--> statement-breakpoint
+ALTER TABLE photos ADD COLUMN site_id INTEGER NOT NULL DEFAULT 1 REFERENCES sites(id);
+--> statement-breakpoint
+CREATE INDEX idx_photos_site ON photos(site_id);
+--> statement-breakpoint
+CREATE TRIGGER photos_site_immutable BEFORE UPDATE OF site_id ON photos WHEN NEW.site_id != OLD.site_id BEGIN SELECT RAISE(ABORT,'site ownership is immutable'); END;
+--> statement-breakpoint
+ALTER TABLE albums ADD COLUMN site_id INTEGER NOT NULL DEFAULT 1 REFERENCES sites(id);
+--> statement-breakpoint
+CREATE INDEX idx_albums_site ON albums(site_id);
+--> statement-breakpoint
+CREATE TRIGGER albums_site_immutable BEFORE UPDATE OF site_id ON albums WHEN NEW.site_id != OLD.site_id BEGIN SELECT RAISE(ABORT,'site ownership is immutable'); END;
+--> statement-breakpoint
+ALTER TABLE album_photos ADD COLUMN site_id INTEGER NOT NULL DEFAULT 1 REFERENCES sites(id);
+--> statement-breakpoint
+CREATE INDEX idx_album_photos_site ON album_photos(site_id);
+--> statement-breakpoint
+CREATE TRIGGER album_photos_site_immutable BEFORE UPDATE OF site_id ON album_photos WHEN NEW.site_id != OLD.site_id BEGIN SELECT RAISE(ABORT,'site ownership is immutable'); END;
+--> statement-breakpoint
+ALTER TABLE photo_access_keys ADD COLUMN site_id INTEGER NOT NULL DEFAULT 1 REFERENCES sites(id);
+--> statement-breakpoint
+CREATE INDEX idx_photo_access_keys_site ON photo_access_keys(site_id);
+--> statement-breakpoint
+CREATE TRIGGER photo_access_keys_site_immutable BEFORE UPDATE OF site_id ON photo_access_keys WHEN NEW.site_id != OLD.site_id BEGIN SELECT RAISE(ABORT,'site ownership is immutable'); END;
+--> statement-breakpoint
+ALTER TABLE photo_reactions ADD COLUMN site_id INTEGER NOT NULL DEFAULT 1 REFERENCES sites(id);
+--> statement-breakpoint
+CREATE INDEX idx_photo_reactions_site ON photo_reactions(site_id);
+--> statement-breakpoint
+CREATE TRIGGER photo_reactions_site_immutable BEFORE UPDATE OF site_id ON photo_reactions WHEN NEW.site_id != OLD.site_id BEGIN SELECT RAISE(ABORT,'site ownership is immutable'); END;
+--> statement-breakpoint
+ALTER TABLE pipeline_queue ADD COLUMN site_id INTEGER NOT NULL DEFAULT 1 REFERENCES sites(id);
+--> statement-breakpoint
+CREATE INDEX idx_pipeline_queue_site ON pipeline_queue(site_id);
+--> statement-breakpoint
+CREATE TRIGGER pipeline_queue_site_immutable BEFORE UPDATE OF site_id ON pipeline_queue WHEN NEW.site_id != OLD.site_id BEGIN SELECT RAISE(ABORT,'site ownership is immutable'); END;
+--> statement-breakpoint
+ALTER TABLE settings ADD COLUMN site_id INTEGER NOT NULL DEFAULT 1 REFERENCES sites(id);
+--> statement-breakpoint
+CREATE INDEX idx_settings_site ON settings(site_id);
+--> statement-breakpoint
+CREATE TRIGGER settings_site_immutable BEFORE UPDATE OF site_id ON settings WHEN NEW.site_id != OLD.site_id BEGIN SELECT RAISE(ABORT,'site ownership is immutable'); END;
+--> statement-breakpoint
+ALTER TABLE settings_storage_providers ADD COLUMN site_id INTEGER NOT NULL DEFAULT 1 REFERENCES sites(id);
+--> statement-breakpoint
+CREATE INDEX idx_settings_storage_providers_site ON settings_storage_providers(site_id);
+--> statement-breakpoint
+CREATE TRIGGER settings_storage_providers_site_immutable BEFORE UPDATE OF site_id ON settings_storage_providers WHEN NEW.site_id != OLD.site_id BEGIN SELECT RAISE(ABORT,'site ownership is immutable'); END;
+--> statement-breakpoint
+DROP INDEX idx_namespace_key;
+--> statement-breakpoint
+CREATE UNIQUE INDEX idx_namespace_key ON settings(site_id,namespace,key);
+--> statement-breakpoint
+ALTER TABLE settings_storage_providers ADD COLUMN revision INTEGER NOT NULL DEFAULT 1;
+--> statement-breakpoint
+CREATE TABLE storage_connection_versions (connection_id INTEGER NOT NULL, revision INTEGER NOT NULL, site_id INTEGER NOT NULL REFERENCES sites(id), config TEXT NOT NULL, PRIMARY KEY(connection_id,revision));
+--> statement-breakpoint
+INSERT INTO storage_connection_versions SELECT id,revision,site_id,config FROM settings_storage_providers;
+--> statement-breakpoint
+CREATE TRIGGER storage_version_insert AFTER INSERT ON settings_storage_providers BEGIN INSERT INTO storage_connection_versions VALUES(NEW.id,NEW.revision,NEW.site_id,NEW.config); END;
+--> statement-breakpoint
+CREATE TRIGGER storage_version_update AFTER UPDATE OF config ON settings_storage_providers WHEN NEW.config != OLD.config BEGIN UPDATE settings_storage_providers SET revision=OLD.revision+1 WHERE id=NEW.id; INSERT INTO storage_connection_versions VALUES(NEW.id,OLD.revision+1,NEW.site_id,NEW.config); END;
+--> statement-breakpoint
+CREATE TRIGGER storage_history_immutable BEFORE UPDATE ON storage_connection_versions BEGIN SELECT RAISE(ABORT,'storage history is immutable'); END;
+--> statement-breakpoint
+ALTER TABLE photos ADD COLUMN storage_connection_id INTEGER;
+--> statement-breakpoint
+ALTER TABLE photos ADD COLUMN storage_revision INTEGER NOT NULL DEFAULT 1;
+--> statement-breakpoint
+ALTER TABLE photos ADD COLUMN source_version INTEGER NOT NULL DEFAULT 1;
+--> statement-breakpoint
+UPDATE photos SET storage_connection_id=(SELECT p.id FROM settings_storage_providers p JOIN settings s ON s.site_id=p.site_id AND s.namespace='storage' AND s.key='provider' AND CAST(s.value AS INTEGER)=p.id WHERE p.site_id=photos.site_id LIMIT 1);
+--> statement-breakpoint
+ALTER TABLE pipeline_queue ADD COLUMN storage_connection_id INTEGER;
+--> statement-breakpoint
+ALTER TABLE pipeline_queue ADD COLUMN storage_revision INTEGER NOT NULL DEFAULT 1;
+--> statement-breakpoint
+ALTER TABLE pipeline_queue ADD COLUMN source_version INTEGER NOT NULL DEFAULT 1;
+--> statement-breakpoint
+UPDATE pipeline_queue SET storage_connection_id=(SELECT p.id FROM settings_storage_providers p JOIN settings s ON s.site_id=p.site_id AND s.namespace='storage' AND s.key='provider' AND CAST(s.value AS INTEGER)=p.id WHERE p.site_id=pipeline_queue.site_id LIMIT 1);
+--> statement-breakpoint
+CREATE TRIGGER album_photos_same_site_insert BEFORE INSERT ON album_photos WHEN (NEW.album_id IS NOT NULL AND NOT EXISTS(SELECT 1 FROM albums WHERE id=NEW.album_id AND site_id=NEW.site_id)) OR (NEW.photo_id IS NOT NULL AND NOT EXISTS(SELECT 1 FROM photos WHERE id=NEW.photo_id AND site_id=NEW.site_id)) BEGIN SELECT RAISE(ABORT,'cross-site or missing relation'); END;
+--> statement-breakpoint
+CREATE TRIGGER album_photos_same_site_update BEFORE UPDATE ON album_photos WHEN (NEW.album_id IS NOT NULL AND NOT EXISTS(SELECT 1 FROM albums WHERE id=NEW.album_id AND site_id=NEW.site_id)) OR (NEW.photo_id IS NOT NULL AND NOT EXISTS(SELECT 1 FROM photos WHERE id=NEW.photo_id AND site_id=NEW.site_id)) BEGIN SELECT RAISE(ABORT,'cross-site or missing relation'); END;
+--> statement-breakpoint
+CREATE TRIGGER photo_access_keys_same_site_insert BEFORE INSERT ON photo_access_keys WHEN (NEW.photo_id IS NOT NULL AND NOT EXISTS(SELECT 1 FROM photos WHERE id=NEW.photo_id AND site_id=NEW.site_id)) BEGIN SELECT RAISE(ABORT,'cross-site or missing relation'); END;
+--> statement-breakpoint
+CREATE TRIGGER photo_access_keys_same_site_update BEFORE UPDATE ON photo_access_keys WHEN (NEW.photo_id IS NOT NULL AND NOT EXISTS(SELECT 1 FROM photos WHERE id=NEW.photo_id AND site_id=NEW.site_id)) BEGIN SELECT RAISE(ABORT,'cross-site or missing relation'); END;
+--> statement-breakpoint
+CREATE TRIGGER photo_reactions_same_site_insert BEFORE INSERT ON photo_reactions WHEN (NEW.photo_id IS NOT NULL AND NOT EXISTS(SELECT 1 FROM photos WHERE id=NEW.photo_id AND site_id=NEW.site_id)) BEGIN SELECT RAISE(ABORT,'cross-site or missing relation'); END;
+--> statement-breakpoint
+CREATE TRIGGER photo_reactions_same_site_update BEFORE UPDATE ON photo_reactions WHEN (NEW.photo_id IS NOT NULL AND NOT EXISTS(SELECT 1 FROM photos WHERE id=NEW.photo_id AND site_id=NEW.site_id)) BEGIN SELECT RAISE(ABORT,'cross-site or missing relation'); END;
+--> statement-breakpoint
+CREATE TRIGGER albums_same_site_insert BEFORE INSERT ON albums WHEN (NEW.cover_photo_id IS NOT NULL AND NOT EXISTS(SELECT 1 FROM photos WHERE id=NEW.cover_photo_id AND site_id=NEW.site_id)) BEGIN SELECT RAISE(ABORT,'cross-site or missing relation'); END;
+--> statement-breakpoint
+CREATE TRIGGER albums_same_site_update BEFORE UPDATE ON albums WHEN (NEW.cover_photo_id IS NOT NULL AND NOT EXISTS(SELECT 1 FROM photos WHERE id=NEW.cover_photo_id AND site_id=NEW.site_id)) BEGIN SELECT RAISE(ABORT,'cross-site or missing relation'); END;
+--> statement-breakpoint
+CREATE TRIGGER photos_same_site_insert BEFORE INSERT ON photos WHEN NEW.storage_connection_id IS NOT NULL AND NOT EXISTS(SELECT 1 FROM storage_connection_versions WHERE connection_id=NEW.storage_connection_id AND revision=NEW.storage_revision AND site_id=NEW.site_id) BEGIN SELECT RAISE(ABORT,'cross-site or missing relation'); END;
+--> statement-breakpoint
+CREATE TRIGGER photos_same_site_update BEFORE UPDATE ON photos WHEN NEW.storage_connection_id IS NOT NULL AND NOT EXISTS(SELECT 1 FROM storage_connection_versions WHERE connection_id=NEW.storage_connection_id AND revision=NEW.storage_revision AND site_id=NEW.site_id) BEGIN SELECT RAISE(ABORT,'cross-site or missing relation'); END;
+--> statement-breakpoint
+CREATE TRIGGER pipeline_queue_same_site_insert BEFORE INSERT ON pipeline_queue WHEN NEW.storage_connection_id IS NOT NULL AND NOT EXISTS(SELECT 1 FROM storage_connection_versions WHERE connection_id=NEW.storage_connection_id AND revision=NEW.storage_revision AND site_id=NEW.site_id) BEGIN SELECT RAISE(ABORT,'cross-site or missing relation'); END;
+--> statement-breakpoint
+CREATE TRIGGER pipeline_queue_same_site_update BEFORE UPDATE ON pipeline_queue WHEN NEW.storage_connection_id IS NOT NULL AND NOT EXISTS(SELECT 1 FROM storage_connection_versions WHERE connection_id=NEW.storage_connection_id AND revision=NEW.storage_revision AND site_id=NEW.site_id) BEGIN SELECT RAISE(ABORT,'cross-site or missing relation'); END;
+--> statement-breakpoint
+DROP TRIGGER photos_access_keys_insert;
+--> statement-breakpoint
+DROP TRIGGER photos_access_keys_update;
+--> statement-breakpoint
+CREATE TRIGGER `photos_access_keys_insert`
+AFTER INSERT ON `photos`
+BEGIN
+ INSERT OR IGNORE INTO `photo_access_keys` (`access_key`, `photo_id`, `site_id`)
+ WITH RECURSIVE
+ `raw`(`value`, `kind`) AS (
+ SELECT NEW.`id`, 'id'
+ UNION ALL SELECT NEW.`storage_key`, 'path'
+ UNION ALL SELECT NEW.`thumbnail_key`, 'path'
+ UNION ALL SELECT NEW.`original_url`, 'path'
+ UNION ALL SELECT NEW.`thumbnail_url`, 'path'
+ UNION ALL SELECT NEW.`live_photo_video_key`, 'path'
+ UNION ALL SELECT NEW.`live_photo_video_url`, 'path'
+ ),
+ `present`(`value`, `kind`) AS (
+ SELECT `value`, `kind` FROM `raw`
+ WHERE `value` IS NOT NULL AND `value` != ''
+ ),
+ `slashed`(`value`, `kind`, `absolute`, `step`) AS (
+ SELECT
+ CASE
+ WHEN `kind` = 'id' THEN `value`
+ WHEN lower(`value`) LIKE 'http://%' OR lower(`value`) LIKE 'https://%' THEN `value`
+ ELSE replace(`value`, char(92), '/')
+ END,
+ `kind`,
+ CASE
+ WHEN `kind` = 'id' THEN 1
+ WHEN lower(`value`) LIKE 'http://%' OR lower(`value`) LIKE 'https://%' THEN 1
+ ELSE 0
+ END,
+ 0
+ FROM `present`
+ UNION ALL
+ SELECT replace(`value`, '//', '/'), `kind`, `absolute`, `step` + 1
+ FROM `slashed`
+ WHERE `absolute` = 0 AND instr(`value`, '//') > 0 AND `step` < 64
+ ),
+ `stable`(`value`, `kind`, `absolute`) AS (
+ SELECT `value`, `kind`, `absolute` FROM `slashed`
+ WHERE `absolute` = 1 OR instr(`value`, '//') = 0 OR `step` = 64
+ ),
+ `derived`(`access_key`) AS (
+ SELECT `value` FROM `present`
+ UNION ALL
+ SELECT ltrim(`value`, '/') FROM `stable`
+ WHERE `absolute` = 0 AND ltrim(`value`, '/') != ''
+ UNION ALL
+ SELECT ltrim(substr(`value`, 10), '/') FROM `stable`
+ WHERE `absolute` = 0
+ AND `kind` = 'path'
+ AND `value` LIKE '/storage/%'
+ AND ltrim(substr(`value`, 10), '/') != ''
+ UNION ALL
+ SELECT ltrim(substr(`value`, 8), '/') FROM `stable`
+ WHERE `absolute` = 0
+ AND `kind` = 'path'
+ AND `value` LIKE '/image/%'
+ AND ltrim(substr(`value`, 8), '/') != ''
+ )
+ SELECT DISTINCT `access_key`, NEW.`id`, NEW.`site_id` FROM `derived`
+ WHERE `access_key` IS NOT NULL AND `access_key` != '';
+END;
+--> statement-breakpoint
+CREATE TRIGGER `photos_access_keys_update`
+AFTER UPDATE ON `photos`
+BEGIN
+ DELETE FROM `photo_access_keys` WHERE `photo_id` = OLD.`id`;
+ INSERT OR IGNORE INTO `photo_access_keys` (`access_key`, `photo_id`, `site_id`)
+ WITH RECURSIVE
+ `raw`(`value`, `kind`) AS (
+ SELECT NEW.`id`, 'id'
+ UNION ALL SELECT NEW.`storage_key`, 'path'
+ UNION ALL SELECT NEW.`thumbnail_key`, 'path'
+ UNION ALL SELECT NEW.`original_url`, 'path'
+ UNION ALL SELECT NEW.`thumbnail_url`, 'path'
+ UNION ALL SELECT NEW.`live_photo_video_key`, 'path'
+ UNION ALL SELECT NEW.`live_photo_video_url`, 'path'
+ ),
+ `present`(`value`, `kind`) AS (
+ SELECT `value`, `kind` FROM `raw`
+ WHERE `value` IS NOT NULL AND `value` != ''
+ ),
+ `slashed`(`value`, `kind`, `absolute`, `step`) AS (
+ SELECT
+ CASE
+ WHEN `kind` = 'id' THEN `value`
+ WHEN lower(`value`) LIKE 'http://%' OR lower(`value`) LIKE 'https://%' THEN `value`
+ ELSE replace(`value`, char(92), '/')
+ END,
+ `kind`,
+ CASE
+ WHEN `kind` = 'id' THEN 1
+ WHEN lower(`value`) LIKE 'http://%' OR lower(`value`) LIKE 'https://%' THEN 1
+ ELSE 0
+ END,
+ 0
+ FROM `present`
+ UNION ALL
+ SELECT replace(`value`, '//', '/'), `kind`, `absolute`, `step` + 1
+ FROM `slashed`
+ WHERE `absolute` = 0 AND instr(`value`, '//') > 0 AND `step` < 64
+ ),
+ `stable`(`value`, `kind`, `absolute`) AS (
+ SELECT `value`, `kind`, `absolute` FROM `slashed`
+ WHERE `absolute` = 1 OR instr(`value`, '//') = 0 OR `step` = 64
+ ),
+ `derived`(`access_key`) AS (
+ SELECT `value` FROM `present`
+ UNION ALL
+ SELECT ltrim(`value`, '/') FROM `stable`
+ WHERE `absolute` = 0 AND ltrim(`value`, '/') != ''
+ UNION ALL
+ SELECT ltrim(substr(`value`, 10), '/') FROM `stable`
+ WHERE `absolute` = 0
+ AND `kind` = 'path'
+ AND `value` LIKE '/storage/%'
+ AND ltrim(substr(`value`, 10), '/') != ''
+ UNION ALL
+ SELECT ltrim(substr(`value`, 8), '/') FROM `stable`
+ WHERE `absolute` = 0
+ AND `kind` = 'path'
+ AND `value` LIKE '/image/%'
+ AND ltrim(substr(`value`, 8), '/') != ''
+ )
+ SELECT DISTINCT `access_key`, NEW.`id`, NEW.`site_id` FROM `derived`
+ WHERE `access_key` IS NOT NULL AND `access_key` != '';
+END;
+--> statement-breakpoint
+CREATE TRIGGER default_user_membership_role AFTER UPDATE OF is_admin ON users BEGIN UPDATE memberships SET role=CASE WHEN NEW.is_admin=1 THEN 'admin' ELSE 'member' END WHERE workspace_id=1 AND user_id=NEW.id; END;
+--> statement-breakpoint
+CREATE TRIGGER site_workspace_immutable BEFORE UPDATE OF workspace_id ON sites WHEN NEW.workspace_id != OLD.workspace_id BEGIN SELECT RAISE(ABORT,'site workspace is immutable'); END;
+--> statement-breakpoint
+CREATE TRIGGER storage_history_delete BEFORE DELETE ON storage_connection_versions BEGIN SELECT RAISE(ABORT,'storage history is immutable'); END;
diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json
index 36979a8d..48f920b6 100644
--- a/packages/database/migrations/meta/_journal.json
+++ b/packages/database/migrations/meta/_journal.json
@@ -127,6 +127,13 @@
"when": 1792307735436,
"tag": "0017_location_components",
"breakpoints": true
+ },
+ {
+ "idx": 18,
+ "version": "6",
+ "when": 1792307736436,
+ "tag": "0018_site_ownership",
+ "breakpoints": true
}
]
}
diff --git a/packages/database/src/connection.ts b/packages/database/src/connection.ts
index 262fc344..c56b4514 100644
--- a/packages/database/src/connection.ts
+++ b/packages/database/src/connection.ts
@@ -1,8 +1,10 @@
import { mkdirSync } from 'node:fs'
+import { randomUUID } from 'node:crypto'
+import { sql } from 'drizzle-orm'
+import { readMigrationFiles } from 'drizzle-orm/migrator'
import { dirname } from 'node:path'
import Database from 'better-sqlite3'
import { drizzle } from 'drizzle-orm/better-sqlite3'
-import { migrate } from 'drizzle-orm/better-sqlite3/migrator'
import * as schema from './schema.ts'
export const tables = schema
@@ -42,7 +44,7 @@ export function openDatabase(options: DatabaseOptions) {
sqlite.pragma('temp_store = MEMORY')
const db = drizzle(sqlite, { schema })
if (options.migrationsFolder)
- migrate(db, { migrationsFolder: options.migrationsFolder })
+ migrateDatabase(db, options.migrationsFolder, options.filename)
return {
db,
/** SQLite backup includes committed WAL data and does not mutate the source. */
@@ -70,3 +72,52 @@ export function persistenceErrorCode(error: unknown) {
return 'retryable'
return 'internal'
}
+
+/** Back up existing files before an unapplied migration; validate relations before committing. */
+export function migrateDatabase(
+ db: AppDatabase,
+ migrationsFolder: string,
+ filename?: string,
+) {
+ const journal = db.get<{ present: number }>(
+ sql`SELECT 1 AS present FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`,
+ )
+ const applied = journal
+ ? (db.get<{ timestamp: number }>(
+ sql`SELECT max(created_at) AS timestamp FROM __drizzle_migrations`,
+ )?.timestamp ?? 0)
+ : 0
+ const pending = readMigrationFiles({ migrationsFolder }).some(
+ (m) => m.folderMillis > applied,
+ )
+ const existing = db.get<{ present: number }>(
+ sql`SELECT 1 AS present FROM sqlite_master WHERE type='table' AND name='photos'`,
+ )
+ if (pending && existing && filename && filename !== ':memory:') {
+ const backup = `${filename}.pre-migration-${Date.now()}-${randomUUID()}.sqlite3`
+ db.run(sql`VACUUM INTO ${backup}`)
+ }
+ if (!pending) return
+ db.run(sql`PRAGMA foreign_keys = OFF`)
+ try {
+ db.transaction(() => {
+ db.run(
+ sql`CREATE TABLE IF NOT EXISTS __drizzle_migrations (id SERIAL PRIMARY KEY, hash TEXT NOT NULL, created_at NUMERIC)`,
+ )
+ for (const migration of readMigrationFiles({ migrationsFolder })) {
+ if (migration.folderMillis <= applied) continue
+ for (const statement of migration.sql)
+ if (statement.trim()) db.run(sql.raw(statement))
+ db.run(
+ sql`INSERT INTO __drizzle_migrations(hash,created_at) VALUES (${migration.hash},${migration.folderMillis})`,
+ )
+ }
+ if (db.all(sql`PRAGMA foreign_key_check`).length)
+ throw new Error(
+ 'Migration violates database relations; restore the pre-migration backup',
+ )
+ })
+ } finally {
+ db.run(sql`PRAGMA foreign_keys = ON`)
+ }
+}
diff --git a/packages/database/src/dto.ts b/packages/database/src/dto.ts
index 89a5bd2a..57362500 100644
--- a/packages/database/src/dto.ts
+++ b/packages/database/src/dto.ts
@@ -23,8 +23,14 @@ export function toPhotoDto(photo: PhotoRow): Photo {
thumbnailKey: photo.thumbnailKey,
fileSize: photo.fileSize,
lastModified: photo.lastModified,
- originalUrl: photo.originalUrl,
- thumbnailUrl: photo.thumbnailUrl,
+ originalUrl:
+ photo.storageConnectionId != null && photo.originalUrl
+ ? `/image/__photo__/${encodeURIComponent(photo.id)}/original`
+ : photo.originalUrl,
+ thumbnailUrl:
+ photo.storageConnectionId != null && photo.thumbnailUrl
+ ? `/image/__photo__/${encodeURIComponent(photo.id)}/thumbnail`
+ : photo.thumbnailUrl,
thumbnailHash: photo.thumbnailHash,
tags: photo.tags,
exif: photo.exif,
@@ -35,7 +41,10 @@ export function toPhotoDto(photo: PhotoRow): Photo {
locationName: photo.locationName,
geocoding: photo.geocoding,
isLivePhoto: photo.isLivePhoto,
- livePhotoVideoUrl: photo.livePhotoVideoUrl,
+ livePhotoVideoUrl:
+ photo.storageConnectionId != null && photo.livePhotoVideoUrl
+ ? `/image/__photo__/${encodeURIComponent(photo.id)}/live`
+ : photo.livePhotoVideoUrl,
livePhotoVideoKey: photo.livePhotoVideoKey,
}
}
diff --git a/packages/database/src/photo-persistence.ts b/packages/database/src/photo-persistence.ts
new file mode 100644
index 00000000..aef7ee9b
--- /dev/null
+++ b/packages/database/src/photo-persistence.ts
@@ -0,0 +1,88 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { type SiteContext } from '@chronoframe/core'
+import { requireSite } from './site-repository.ts'
+import { and, eq, max } from 'drizzle-orm'
+import type { AppDatabase } from './connection.ts'
+import * as tables from './schema.ts'
+import { QueueWarningCode } from '@chronoframe/contracts/queue'
+
+export type AlbumAssignmentResult =
+ | 'no-album'
+ | typeof QueueWarningCode.AlbumMissing
+ | 'already-added'
+ | 'added'
+
+export function createPhotoPersistenceRepository(
+ db: AppDatabase,
+ site: SiteContext,
+) {
+ requireSite(db, site)
+ return {
+ persist: (
+ photo: typeof tables.photos.$inferInsert,
+ albumId?: number,
+ ): AlbumAssignmentResult =>
+ db.transaction((tx) => {
+ if (photo.siteId !== undefined && photo.siteId !== site.id)
+ throw new RangeError('Photo belongs to a different Site')
+ const ownedPhoto = { ...photo, siteId: site.id }
+ tx.insert(tables.photos)
+ .values(ownedPhoto)
+ .onConflictDoUpdate({ target: tables.photos.id, set: ownedPhoto })
+ .run()
+
+ if (albumId === undefined) return 'no-album'
+
+ const album = tx
+ .select({ id: tables.albums.id })
+ .from(tables.albums)
+ .where(
+ siteAnd(
+ eq(tables.albums.id, albumId),
+ siteEq(tables.albums.siteId, site.id),
+ ),
+ )
+ .get()
+ if (!album) return QueueWarningCode.AlbumMissing
+
+ const existing = tx
+ .select({ id: tables.albumPhotos.id })
+ .from(tables.albumPhotos)
+ .where(
+ siteAnd(
+ and(
+ eq(tables.albumPhotos.albumId, albumId),
+ eq(tables.albumPhotos.photoId, photo.id),
+ ),
+ siteEq(tables.albumPhotos.siteId, site.id),
+ ),
+ )
+ .get()
+ if (existing) return 'already-added'
+
+ const last = tx
+ .select({ position: max(tables.albumPhotos.position) })
+ .from(tables.albumPhotos)
+ .where(
+ siteAnd(
+ eq(tables.albumPhotos.albumId, albumId),
+ siteEq(tables.albumPhotos.siteId, site.id),
+ ),
+ )
+ .get()
+
+ const insertResult = tx
+ .insert(tables.albumPhotos)
+ .values({
+ siteId: site.id,
+ albumId,
+ photoId: photo.id,
+ position: (last?.position ?? 1000000) + 10,
+ })
+ .onConflictDoNothing()
+ .run()
+
+ return insertResult.changes > 0 ? 'added' : 'already-added'
+ }),
+ }
+}
diff --git a/packages/database/src/repositories.ts b/packages/database/src/repositories.ts
index a7b03dd6..911dd07e 100644
--- a/packages/database/src/repositories.ts
+++ b/packages/database/src/repositories.ts
@@ -1,3 +1,5 @@
export * from './sqlite-resources.ts'
export * from './sqlite-mutations.ts'
export * from './sqlite-uploads.ts'
+export * from './site-repository.ts'
+export * from './photo-persistence.ts'
diff --git a/packages/database/src/schema.ts b/packages/database/src/schema.ts
index e89c81e7..1c439b06 100644
--- a/packages/database/src/schema.ts
+++ b/packages/database/src/schema.ts
@@ -47,35 +47,73 @@ export const users = sqliteTable('users', {
isAdmin: integer('is_admin').default(0).notNull(),
})
-export const photos = sqliteTable('photos', {
- id: text('id').primaryKey().unique(),
- title: text('title'),
- description: text('description'),
- width: integer('width'),
- height: integer('height'),
- aspectRatio: real('aspect_ratio'),
- dateTaken: text('date_taken'),
- storageKey: text('storage_key'),
- thumbnailKey: text('thumbnail_key'),
- fileSize: integer('file_size'),
- lastModified: text('last_modified'),
- originalUrl: text('original_url'),
- thumbnailUrl: text('thumbnail_url'),
- thumbnailHash: text('thumbnail_hash'),
- tags: text('tags', { mode: 'json' }).$type<string[]>(),
- exif: text('exif', { mode: 'json' }).$type<NeededExif>(),
- // 地理位置信息
- latitude: real('latitude'),
- longitude: real('longitude'),
- country: text('country'),
- city: text('city'),
- locationName: text('location_name'),
- geocoding: text('geocoding', { mode: 'json' }).$type<NormalizedLocation>(),
- // LivePhoto 相关字段
- isLivePhoto: integer('is_live_photo').default(0).notNull(),
- livePhotoVideoUrl: text('live_photo_video_url'),
- livePhotoVideoKey: text('live_photo_video_key'),
+export const workspaces = sqliteTable('workspaces', {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+ name: text('name').notNull(),
+})
+export const sites = sqliteTable('sites', {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+ workspaceId: integer('workspace_id')
+ .notNull()
+ .references(() => workspaces.id),
+ name: text('name').notNull(),
})
+export const memberships = sqliteTable(
+ 'memberships',
+ {
+ workspaceId: integer('workspace_id')
+ .notNull()
+ .references(() => workspaces.id),
+ userId: integer('user_id')
+ .notNull()
+ .references(() => users.id, { onDelete: 'cascade' }),
+ role: text('role', { enum: ['admin', 'member'] }).notNull(),
+ },
+ (t) => [primaryKey({ columns: [t.workspaceId, t.userId] })],
+)
+const siteColumn = () =>
+ integer('site_id')
+ .notNull()
+ .default(1)
+ .references(() => sites.id)
+
+export const photos = sqliteTable(
+ 'photos',
+ {
+ storageConnectionId: integer('storage_connection_id'),
+ storageRevision: integer('storage_revision').notNull().default(1),
+ sourceVersion: integer('source_version').notNull().default(1),
+ siteId: siteColumn(),
+ id: text('id').primaryKey().unique(),
+ title: text('title'),
+ description: text('description'),
+ width: integer('width'),
+ height: integer('height'),
+ aspectRatio: real('aspect_ratio'),
+ dateTaken: text('date_taken'),
+ storageKey: text('storage_key'),
+ thumbnailKey: text('thumbnail_key'),
+ fileSize: integer('file_size'),
+ lastModified: text('last_modified'),
+ originalUrl: text('original_url'),
+ thumbnailUrl: text('thumbnail_url'),
+ thumbnailHash: text('thumbnail_hash'),
+ tags: text('tags', { mode: 'json' }).$type<string[]>(),
+ exif: text('exif', { mode: 'json' }).$type<NeededExif>(),
+ // 地理位置信息
+ latitude: real('latitude'),
+ longitude: real('longitude'),
+ country: text('country'),
+ city: text('city'),
+ locationName: text('location_name'),
+ geocoding: text('geocoding', { mode: 'json' }).$type<NormalizedLocation>(),
+ // LivePhoto 相关字段
+ isLivePhoto: integer('is_live_photo').default(0).notNull(),
+ livePhotoVideoUrl: text('live_photo_video_url'),
+ livePhotoVideoKey: text('live_photo_video_key'),
+ },
+ (t) => [index('idx_photos_site').on(t.siteId)],
+)
// One row per string an image request may use to identify a photo: the photo
// id, each storage key, each public URL, and the tidied form of those paths.
@@ -84,12 +122,14 @@ export const photos = sqliteTable('photos', {
export const photoAccessKeys = sqliteTable(
'photo_access_keys',
{
+ siteId: siteColumn(),
accessKey: text('access_key').notNull(),
photoId: text('photo_id')
.notNull()
.references(() => photos.id, { onDelete: 'cascade' }),
},
(t) => [
+ index('idx_photo_access_keys_site').on(t.siteId),
primaryKey({ columns: [t.accessKey, t.photoId] }),
index('idx_photo_access_keys_photo_id').on(t.photoId),
],
@@ -98,6 +138,10 @@ export const photoAccessKeys = sqliteTable(
export const pipelineQueue = sqliteTable(
'pipeline_queue',
{
+ storageConnectionId: integer('storage_connection_id'),
+ storageRevision: integer('storage_revision').notNull().default(1),
+ sourceVersion: integer('source_version').notNull().default(1),
+ siteId: siteColumn(),
id: integer('id').primaryKey({ autoIncrement: true }),
payload: text('payload', { mode: 'json' })
.$type<PipelineQueuePayload>()
@@ -142,6 +186,7 @@ export const pipelineQueue = sqliteTable(
completedAt: integer('completed_at', { mode: 'timestamp' }),
},
(t) => [
+ index('idx_pipeline_queue_site').on(t.siteId),
index('idx_pipeline_queue_pending')
.on(sql`${t.priority} DESC`, t.createdAt, t.id)
.where(sql`${t.status} = 'pending'`),
@@ -149,50 +194,72 @@ export const pipelineQueue = sqliteTable(
)
// 照片表态表
-export const photoReactions = sqliteTable('photo_reactions', {
- id: integer('id').primaryKey({ autoIncrement: true }),
- photoId: text('photo_id')
- .notNull()
- .references(() => photos.id, { onDelete: 'cascade' }),
- reactionType: text('reaction_type', {
- enum: ['like', 'love', 'amazing', 'funny', 'wow', 'sad', 'fire', 'sparkle'],
- }).notNull(),
- // 使用指纹而不是 IP 地址,更准确且支持匿名用户
- fingerprint: text('fingerprint').notNull(),
- ipAddress: text('ip_address'),
- userAgent: text('user_agent'),
- createdAt: integer('created_at', { mode: 'timestamp' })
- .notNull()
- .default(sql`(unixepoch())`),
- updatedAt: integer('updated_at', { mode: 'timestamp' })
- .notNull()
- .default(sql`(unixepoch())`),
-})
+export const photoReactions = sqliteTable(
+ 'photo_reactions',
+ {
+ siteId: siteColumn(),
+ id: integer('id').primaryKey({ autoIncrement: true }),
+ photoId: text('photo_id')
+ .notNull()
+ .references(() => photos.id, { onDelete: 'cascade' }),
+ reactionType: text('reaction_type', {
+ enum: [
+ 'like',
+ 'love',
+ 'amazing',
+ 'funny',
+ 'wow',
+ 'sad',
+ 'fire',
+ 'sparkle',
+ ],
+ }).notNull(),
+ // 使用指纹而不是 IP 地址,更准确且支持匿名用户
+ fingerprint: text('fingerprint').notNull(),
+ ipAddress: text('ip_address'),
+ userAgent: text('user_agent'),
+ createdAt: integer('created_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer('updated_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ },
+ (t) => [index('idx_photo_reactions_site').on(t.siteId)],
+)
// 相簿表
-export const albums = sqliteTable('albums', {
- id: integer('id').primaryKey({ autoIncrement: true }),
- title: text('title').notNull(),
- description: text('description'),
- coverPhotoId: text('cover_photo_id').references(() => photos.id, {
- onDelete: 'set null',
- }),
- isHidden: integer('is_hidden', { mode: 'boolean' }).default(false).notNull(),
- passwordHash: text('password_hash'),
- // Album sort position (ascending; smaller value appears first)
- position: real('position').notNull().default(0),
- createdAt: integer('created_at', { mode: 'timestamp' })
- .notNull()
- .default(sql`(unixepoch())`),
- updatedAt: integer('updated_at', { mode: 'timestamp' })
- .notNull()
- .default(sql`(unixepoch())`),
-})
+export const albums = sqliteTable(
+ 'albums',
+ {
+ siteId: siteColumn(),
+ id: integer('id').primaryKey({ autoIncrement: true }),
+ title: text('title').notNull(),
+ description: text('description'),
+ coverPhotoId: text('cover_photo_id').references(() => photos.id, {
+ onDelete: 'set null',
+ }),
+ isHidden: integer('is_hidden', { mode: 'boolean' })
+ .default(false)
+ .notNull(),
+ passwordHash: text('password_hash'),
+ // Album sort position (ascending; smaller value appears first)
+ position: real('position').notNull().default(0),
+ createdAt: integer('created_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer('updated_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ },
+ (t) => [index('idx_albums_site').on(t.siteId)],
+)
// 相簿-照片 多对多关系表
export const albumPhotos = sqliteTable(
'album_photos',
{
+ siteId: siteColumn(),
id: integer('id').primaryKey({ autoIncrement: true }),
albumId: integer('album_id')
.notNull()
@@ -206,6 +273,7 @@ export const albumPhotos = sqliteTable(
.default(sql`(unixepoch())`),
},
(t) => [
+ index('idx_album_photos_site').on(t.siteId),
uniqueIndex('album_photos_album_photo_unique').on(t.albumId, t.photoId),
],
)
@@ -213,6 +281,7 @@ export const albumPhotos = sqliteTable(
export const settings = sqliteTable(
'settings',
{
+ siteId: siteColumn(),
id: integer('id').primaryKey({ autoIncrement: true }),
namespace: text('namespace').notNull().default('common'),
key: text('key').notNull(),
@@ -240,12 +309,17 @@ export const settings = sqliteTable(
onDelete: 'set null',
}),
},
- (t) => [uniqueIndex('idx_namespace_key').on(t.namespace, t.key)],
+ (t) => [
+ index('idx_settings_site').on(t.siteId),
+ uniqueIndex('idx_namespace_key').on(t.siteId, t.namespace, t.key),
+ ],
)
export const settings_storage_providers = sqliteTable(
'settings_storage_providers',
{
+ revision: integer('revision').notNull().default(1),
+ siteId: siteColumn(),
id: integer('id').primaryKey({ autoIncrement: true }),
name: text('name').notNull(),
provider: text('provider', {
@@ -259,4 +333,16 @@ export const settings_storage_providers = sqliteTable(
.notNull()
.default(sql`(unixepoch())`),
},
+ (t) => [index('idx_settings_storage_providers_site').on(t.siteId)],
+)
+
+export const storageConnectionVersions = sqliteTable(
+ 'storage_connection_versions',
+ {
+ connectionId: integer('connection_id').notNull(),
+ revision: integer('revision').notNull(),
+ siteId: siteColumn(),
+ config: text('config', { mode: 'json' }).$type<StorageConfig>().notNull(),
+ },
+ (t) => [primaryKey({ columns: [t.connectionId, t.revision] })],
)
diff --git a/packages/database/src/site-repository.ts b/packages/database/src/site-repository.ts
new file mode 100644
index 00000000..dc4127b9
--- /dev/null
+++ b/packages/database/src/site-repository.ts
@@ -0,0 +1,64 @@
+import { and, eq } from 'drizzle-orm'
+import { assertSiteContext, type SiteContext } from '@chronoframe/core'
+import { tables, type AppDatabase } from './connection.ts'
+
+/** Fail closed when an entry supplies a missing or nonexistent Site. */
+export function requireSite(db: AppDatabase, site: SiteContext) {
+ assertSiteContext(site)
+ if (
+ !db
+ .select({ id: tables.sites.id })
+ .from(tables.sites)
+ .where(eq(tables.sites.id, site.id))
+ .get()
+ )
+ throw new RangeError('Site not found')
+}
+
+/** Internal ownership information is deliberately separate from browser resource DTOs. */
+export function createSiteRepository(db: AppDatabase, site: SiteContext) {
+ requireSite(db, site)
+ return {
+ async photoReference(id: string) {
+ return (
+ db
+ .select({
+ storageConnectionId: tables.photos.storageConnectionId,
+ storageRevision: tables.photos.storageRevision,
+ sourceVersion: tables.photos.sourceVersion,
+ })
+ .from(tables.photos)
+ .where(
+ and(eq(tables.photos.siteId, site.id), eq(tables.photos.id, id)),
+ )
+ .get() ?? null
+ )
+ },
+ async storageVersion(connectionId: number, revision: number) {
+ const row = db
+ .select()
+ .from(tables.storageConnectionVersions)
+ .where(
+ and(
+ eq(tables.storageConnectionVersions.siteId, site.id),
+ eq(tables.storageConnectionVersions.connectionId, connectionId),
+ eq(tables.storageConnectionVersions.revision, revision),
+ ),
+ )
+ .get()
+ return row?.config ?? null
+ },
+ async settings(namespace: string) {
+ return db
+ .select()
+ .from(tables.settings)
+ .where(
+ and(
+ eq(tables.settings.siteId, site.id),
+ eq(tables.settings.namespace, namespace),
+ ),
+ )
+ .all()
+ },
+ }
+}
diff --git a/packages/database/src/sqlite-mutations.ts b/packages/database/src/sqlite-mutations.ts
index 64927bb4..dc15abfd 100644
--- a/packages/database/src/sqlite-mutations.ts
+++ b/packages/database/src/sqlite-mutations.ts
@@ -1,3 +1,6 @@
+import { requireSite } from './site-repository.ts'
+import { type SiteContext } from '@chronoframe/core'
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
import { and, eq, min } from 'drizzle-orm'
import type {
AlbumWriteRepository,
@@ -9,14 +12,21 @@ import { toAlbumDto, toPhotoDto } from './dto.ts'
/** Keep album row and membership changes inside synchronous SQLite transactions. */
export function createSqliteAlbumWriteRepository(
db: AppDatabase,
+ site: SiteContext,
): AlbumWriteRepository {
+ requireSite(db, site)
return {
async exists(id) {
return Boolean(
db
.select({ id: tables.albums.id })
.from(tables.albums)
- .where(eq(tables.albums.id, id))
+ .where(
+ siteAnd(
+ eq(tables.albums.id, id),
+ siteEq(tables.albums.siteId, site.id),
+ ),
+ )
.get(),
)
},
@@ -25,16 +35,22 @@ export function createSqliteAlbumWriteRepository(
const row = tx
.select({ min: min(tables.albums.position) })
.from(tables.albums)
+ .where(siteEq(tables.albums.siteId, site.id))
.get()
const album = tx
.insert(tables.albums)
- .values({ ...data, position: (row?.min ?? 1000) - 1000 })
+ .values({
+ ...data,
+ siteId: site.id,
+ position: (row?.min ?? 1000) - 1000,
+ })
.returning()
.get()
photoIds.forEach((photoId, index) =>
tx
.insert(tables.albumPhotos)
.values({
+ siteId: site.id,
albumId: album.id,
photoId,
position: 1000000 + (index + 1) * 10,
@@ -50,18 +66,37 @@ export function createSqliteAlbumWriteRepository(
const exists = tx
.select({ id: tables.albums.id })
.from(tables.albums)
- .where(eq(tables.albums.id, id))
+ .where(
+ siteAnd(
+ eq(tables.albums.id, id),
+ siteEq(tables.albums.siteId, site.id),
+ ),
+ )
.get()
if (!exists) return null
- tx.update(tables.albums).set(data).where(eq(tables.albums.id, id)).run()
+ tx.update(tables.albums)
+ .set(data)
+ .where(
+ siteAnd(
+ eq(tables.albums.id, id),
+ siteEq(tables.albums.siteId, site.id),
+ ),
+ )
+ .run()
if (photoIds !== undefined) {
tx.delete(tables.albumPhotos)
- .where(eq(tables.albumPhotos.albumId, id))
+ .where(
+ siteAnd(
+ eq(tables.albumPhotos.albumId, id),
+ siteEq(tables.albumPhotos.siteId, site.id),
+ ),
+ )
.run()
photoIds.forEach((photoId, index) =>
tx
.insert(tables.albumPhotos)
.values({
+ siteId: site.id,
albumId: id,
photoId,
position: 1000000 + (index + 1) * 10,
@@ -74,7 +109,12 @@ export function createSqliteAlbumWriteRepository(
tx
.select()
.from(tables.albums)
- .where(eq(tables.albums.id, id))
+ .where(
+ siteAnd(
+ eq(tables.albums.id, id),
+ siteEq(tables.albums.siteId, site.id),
+ ),
+ )
.get()!,
)
})
@@ -85,14 +125,31 @@ export function createSqliteAlbumWriteRepository(
!tx
.select({ id: tables.albums.id })
.from(tables.albums)
- .where(eq(tables.albums.id, id))
+ .where(
+ siteAnd(
+ eq(tables.albums.id, id),
+ siteEq(tables.albums.siteId, site.id),
+ ),
+ )
.get()
)
return false
tx.delete(tables.albumPhotos)
- .where(eq(tables.albumPhotos.albumId, id))
+ .where(
+ siteAnd(
+ eq(tables.albumPhotos.albumId, id),
+ siteEq(tables.albumPhotos.siteId, site.id),
+ ),
+ )
+ .run()
+ tx.delete(tables.albums)
+ .where(
+ siteAnd(
+ eq(tables.albums.id, id),
+ siteEq(tables.albums.siteId, site.id),
+ ),
+ )
.run()
- tx.delete(tables.albums).where(eq(tables.albums.id, id)).run()
return true
})
},
@@ -102,7 +159,12 @@ export function createSqliteAlbumWriteRepository(
tx
.update(tables.albums)
.set({ position: index * 1000 })
- .where(eq(tables.albums.id, id))
+ .where(
+ siteAnd(
+ eq(tables.albums.id, id),
+ siteEq(tables.albums.siteId, site.id),
+ ),
+ )
.run(),
)
})
@@ -117,17 +179,24 @@ export function createSqliteAlbumWriteRepository(
!tx
.select({ id: tables.albumPhotos.id })
.from(tables.albumPhotos)
- .where(predicate)
+ .where(
+ siteAnd(predicate, siteEq(tables.albumPhotos.siteId, site.id)),
+ )
.get()
)
return false
- tx.delete(tables.albumPhotos).where(predicate).run()
+ tx.delete(tables.albumPhotos)
+ .where(siteAnd(predicate, siteEq(tables.albumPhotos.siteId, site.id)))
+ .run()
tx.update(tables.albums)
.set({ coverPhotoId: null, updatedAt })
.where(
- and(
- eq(tables.albums.id, id),
- eq(tables.albums.coverPhotoId, photoId),
+ siteAnd(
+ and(
+ eq(tables.albums.id, id),
+ eq(tables.albums.coverPhotoId, photoId),
+ ),
+ siteEq(tables.albums.siteId, site.id),
),
)
.run()
@@ -140,27 +209,54 @@ export function createSqliteAlbumWriteRepository(
/** Map photo writes at the existing connection boundary without changing its lifecycle. */
export function createSqlitePhotoWriteRepository(
db: AppDatabase,
+ site: SiteContext,
): PhotoWriteRepository {
+ requireSite(db, site)
return {
async get(id) {
const photo = db
.select()
.from(tables.photos)
- .where(eq(tables.photos.id, id))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, id),
+ siteEq(tables.photos.siteId, site.id),
+ ),
+ )
.get()
return photo ? toPhotoDto(photo) : null
},
async update(id, update) {
- db.update(tables.photos).set(update).where(eq(tables.photos.id, id)).run()
+ db.update(tables.photos)
+ .set(update)
+ .where(
+ siteAnd(
+ eq(tables.photos.id, id),
+ siteEq(tables.photos.siteId, site.id),
+ ),
+ )
+ .run()
const photo = db
.select()
.from(tables.photos)
- .where(eq(tables.photos.id, id))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, id),
+ siteEq(tables.photos.siteId, site.id),
+ ),
+ )
.get()
return photo ? toPhotoDto(photo) : null
},
async delete(id) {
- db.delete(tables.photos).where(eq(tables.photos.id, id)).run()
+ db.delete(tables.photos)
+ .where(
+ siteAnd(
+ eq(tables.photos.id, id),
+ siteEq(tables.photos.siteId, site.id),
+ ),
+ )
+ .run()
},
}
}
diff --git a/packages/database/src/sqlite-resources.ts b/packages/database/src/sqlite-resources.ts
index 17e6dc36..7a6bacc9 100644
--- a/packages/database/src/sqlite-resources.ts
+++ b/packages/database/src/sqlite-resources.ts
@@ -1,3 +1,6 @@
+import { requireSite } from './site-repository.ts'
+import { type SiteContext } from '@chronoframe/core'
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
import { asc, desc, eq, getTableColumns, notInArray } from 'drizzle-orm'
import type { ResourceReadRepository } from '@chronoframe/core'
import { tables, type AppDatabase } from './connection.ts'
@@ -6,7 +9,9 @@ import { toAlbumDto, toPhotoDto } from './dto.ts'
/** Adapt existing SQLite queries without changing connections, schema or lifecycle. */
export function createSqliteResourceRepository(
db: AppDatabase,
+ site: SiteContext,
): ResourceReadRepository {
+ requireSite(db, site)
const albumRecord = (row: typeof tables.albums.$inferSelect) => ({
resource: toAlbumDto(row),
passwordHash: row.passwordHash,
@@ -25,9 +30,12 @@ export function createSqliteResourceRepository(
.select()
.from(tables.photos)
.where(
- excludedIds.length
- ? notInArray(tables.photos.id, excludedIds)
- : undefined,
+ siteAnd(
+ excludedIds.length
+ ? notInArray(tables.photos.id, excludedIds)
+ : undefined,
+ siteEq(tables.photos.siteId, site.id),
+ ),
)
.orderBy(desc(tables.photos.dateTaken), asc(tables.photos.id))
.limit(page?.limit ?? -1)
@@ -39,6 +47,7 @@ export function createSqliteResourceRepository(
return db
.select()
.from(tables.albums)
+ .where(siteEq(tables.albums.siteId, site.id))
.orderBy(asc(tables.albums.position), desc(tables.albums.createdAt))
.all()
.map(albumRecord)
@@ -47,7 +56,12 @@ export function createSqliteResourceRepository(
const row = db
.select()
.from(tables.albums)
- .where(eq(tables.albums.id, id))
+ .where(
+ siteAnd(
+ eq(tables.albums.id, id),
+ siteEq(tables.albums.siteId, site.id),
+ ),
+ )
.get()
return row ? albumRecord(row) : null
},
@@ -55,7 +69,12 @@ export function createSqliteResourceRepository(
return db
.select({ id: tables.albumPhotos.photoId })
.from(tables.albumPhotos)
- .where(eq(tables.albumPhotos.albumId, id))
+ .where(
+ siteAnd(
+ eq(tables.albumPhotos.albumId, id),
+ siteEq(tables.albumPhotos.siteId, site.id),
+ ),
+ )
.orderBy(asc(tables.albumPhotos.position))
.all()
.map((row) => row.id)
@@ -68,7 +87,12 @@ export function createSqliteResourceRepository(
tables.albumPhotos,
eq(tables.photos.id, tables.albumPhotos.photoId),
)
- .where(eq(tables.albumPhotos.albumId, id))
+ .where(
+ siteAnd(
+ eq(tables.albumPhotos.albumId, id),
+ siteEq(tables.photos.siteId, site.id),
+ ),
+ )
.orderBy(asc(tables.albumPhotos.position))
.all()
.map(toPhotoDto)
@@ -82,6 +106,7 @@ export function createSqliteResourceRepository(
passwordHash: tables.albums.passwordHash,
})
.from(tables.albumPhotos)
+ .where(siteEq(tables.albumPhotos.siteId, site.id))
.innerJoin(
tables.albums,
eq(tables.albumPhotos.albumId, tables.albums.id),
diff --git a/packages/database/src/sqlite-uploads.ts b/packages/database/src/sqlite-uploads.ts
index 3cde4730..409bef68 100644
--- a/packages/database/src/sqlite-uploads.ts
+++ b/packages/database/src/sqlite-uploads.ts
@@ -1,10 +1,17 @@
+import { requireSite } from './site-repository.ts'
+import { type SiteContext } from '@chronoframe/core'
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
import { eq } from 'drizzle-orm'
import type { DuplicatePhoto } from '@chronoframe/core'
import type { Photo } from '@chronoframe/contracts/resources'
import { tables, type AppDatabase } from './connection.ts'
/** Project only fields used by authenticated duplicate checks. */
-export function createSqliteUploadRepository(db: AppDatabase) {
+export function createSqliteUploadRepository(
+ db: AppDatabase,
+ site: SiteContext,
+) {
+ requireSite(db, site)
const summary = {
id: tables.photos.id,
title: tables.photos.title,
@@ -19,7 +26,12 @@ export function createSqliteUploadRepository(db: AppDatabase) {
db
.select(summary)
.from(tables.photos)
- .where(eq(tables.photos.id, id))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, id),
+ siteEq(tables.photos.siteId, site.id),
+ ),
+ )
.get() || null
)
},
@@ -37,7 +49,12 @@ export function createSqliteUploadRepository(db: AppDatabase) {
height: tables.photos.height,
})
.from(tables.photos)
- .where(eq(tables.photos.id, id))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, id),
+ siteEq(tables.photos.siteId, site.id),
+ ),
+ )
.get() || null
)
},
diff --git a/scripts/migrate-database.ts b/scripts/migrate-database.ts
new file mode 100644
index 00000000..7355eeb7
--- /dev/null
+++ b/scripts/migrate-database.ts
@@ -0,0 +1,13 @@
+import { resolve } from 'node:path'
+import { openDatabase } from '@chronoframe/database'
+
+const connection = openDatabase({
+ filename: resolve(process.env.DATABASE_URL || './data/app.sqlite3'),
+ migrationsFolder: resolve(
+ process.env.DATABASE_MIGRATIONS || './packages/database/migrations',
+ ),
+})
+connection.close()
+console.log(
+ 'Database migration completed; pending upgrades of existing files were backed up automatically.',
+)
diff --git a/server/api/albums/[albumId]/unlock.post.ts b/server/api/albums/[albumId]/unlock.post.ts
index 42a87289..1fa74eb4 100644
--- a/server/api/albums/[albumId]/unlock.post.ts
+++ b/server/api/albums/[albumId]/unlock.post.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { eq } from 'drizzle-orm'
import { z } from 'zod'
import { ALBUM_PASSWORD_MAX_LENGTH } from '~~/shared/utils/album'
@@ -28,7 +30,12 @@ export default eventHandler(async (event) => {
const album = useDB()
.select()
.from(tables.albums)
- .where(eq(tables.albums.id, albumId))
+ .where(
+ siteAnd(
+ eq(tables.albums.id, albumId),
+ siteEq(tables.albums.siteId, DEFAULT_SITE.id),
+ ),
+ )
.get()
if (!album || album.isHidden || !album.passwordHash) {
throw createError({ statusCode: 404, statusMessage: 'Album not found' })
diff --git a/server/api/photos/[photoId]/albums.get.ts b/server/api/photos/[photoId]/albums.get.ts
index ca94cf0d..e8884eaa 100644
--- a/server/api/photos/[photoId]/albums.get.ts
+++ b/server/api/photos/[photoId]/albums.get.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { eq } from 'drizzle-orm'
import z from 'zod'
import { albumAccess } from '../../../utils/album-access'
@@ -30,7 +32,12 @@ export default eventHandler(async (event) => {
tables.albumPhotos,
eq(tables.albums.id, tables.albumPhotos.albumId),
)
- .where(eq(tables.albumPhotos.photoId, photoId))
+ .where(
+ siteAnd(
+ eq(tables.albumPhotos.photoId, photoId),
+ siteEq(tables.albums.siteId, DEFAULT_SITE.id),
+ ),
+ )
.all()
return albums.filter(canAccess).map(({ passwordHash, ...album }) => ({
diff --git a/server/api/photos/[photoId]/livephoto.get.ts b/server/api/photos/[photoId]/livephoto.get.ts
index 677cc699..8566af09 100644
--- a/server/api/photos/[photoId]/livephoto.get.ts
+++ b/server/api/photos/[photoId]/livephoto.get.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { eq } from 'drizzle-orm'
export default eventHandler(async (event) => {
@@ -19,7 +21,12 @@ export default eventHandler(async (event) => {
const photos = await db
.select()
.from(tables.photos)
- .where(eq(tables.photos.id, photoId))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, photoId),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.limit(1)
if (photos.length === 0) {
diff --git a/server/api/photos/[photoId]/reactions.ts b/server/api/photos/[photoId]/reactions.ts
index f97db333..e458636c 100644
--- a/server/api/photos/[photoId]/reactions.ts
+++ b/server/api/photos/[photoId]/reactions.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import type { H3Event } from 'h3'
import { eq, and, sql } from 'drizzle-orm'
import { assertPhotoIdAccess } from '../../../utils/album-access'
@@ -40,9 +42,12 @@ async function checkRateLimit(fingerprint: string): Promise<boolean> {
.select({ count: sql<number>`count(*)` })
.from(tables.photoReactions)
.where(
- and(
- eq(tables.photoReactions.fingerprint, fingerprint),
- sql`${tables.photoReactions.createdAt} > ${Math.floor(windowStart.getTime() / 1000)}`,
+ siteAnd(
+ and(
+ eq(tables.photoReactions.fingerprint, fingerprint),
+ sql`${tables.photoReactions.createdAt} > ${Math.floor(windowStart.getTime() / 1000)}`,
+ ),
+ siteEq(tables.photoReactions.siteId, DEFAULT_SITE.id),
),
)
.get()
@@ -73,7 +78,12 @@ export default defineEventHandler(async (event) => {
count: sql<number>`count(*)`,
})
.from(tables.photoReactions)
- .where(eq(tables.photoReactions.photoId, photoId))
+ .where(
+ siteAnd(
+ eq(tables.photoReactions.photoId, photoId),
+ siteEq(tables.photoReactions.siteId, DEFAULT_SITE.id),
+ ),
+ )
.groupBy(tables.photoReactions.reactionType)
.all()
@@ -83,9 +93,12 @@ export default defineEventHandler(async (event) => {
.select()
.from(tables.photoReactions)
.where(
- and(
- eq(tables.photoReactions.photoId, photoId),
- eq(tables.photoReactions.fingerprint, fingerprint),
+ siteAnd(
+ and(
+ eq(tables.photoReactions.photoId, photoId),
+ eq(tables.photoReactions.fingerprint, fingerprint),
+ ),
+ siteEq(tables.photoReactions.siteId, DEFAULT_SITE.id),
),
)
.get()
@@ -142,9 +155,12 @@ export default defineEventHandler(async (event) => {
.select()
.from(tables.photoReactions)
.where(
- and(
- eq(tables.photoReactions.photoId, photoId),
- eq(tables.photoReactions.fingerprint, fingerprint),
+ siteAnd(
+ and(
+ eq(tables.photoReactions.photoId, photoId),
+ eq(tables.photoReactions.fingerprint, fingerprint),
+ ),
+ siteEq(tables.photoReactions.siteId, DEFAULT_SITE.id),
),
)
.get()
@@ -157,7 +173,12 @@ export default defineEventHandler(async (event) => {
reactionType,
updatedAt: new Date(),
})
- .where(eq(tables.photoReactions.id, existingReaction.id))
+ .where(
+ siteAnd(
+ eq(tables.photoReactions.id, existingReaction.id),
+ siteEq(tables.photoReactions.siteId, DEFAULT_SITE.id),
+ ),
+ )
return {
success: true,
@@ -190,9 +211,12 @@ export default defineEventHandler(async (event) => {
.select()
.from(tables.photoReactions)
.where(
- and(
- eq(tables.photoReactions.photoId, photoId),
- eq(tables.photoReactions.fingerprint, fingerprint),
+ siteAnd(
+ and(
+ eq(tables.photoReactions.photoId, photoId),
+ eq(tables.photoReactions.fingerprint, fingerprint),
+ ),
+ siteEq(tables.photoReactions.siteId, DEFAULT_SITE.id),
),
)
.get()
@@ -206,7 +230,12 @@ export default defineEventHandler(async (event) => {
await db
.delete(tables.photoReactions)
- .where(eq(tables.photoReactions.id, existingReaction.id))
+ .where(
+ siteAnd(
+ eq(tables.photoReactions.id, existingReaction.id),
+ siteEq(tables.photoReactions.siteId, DEFAULT_SITE.id),
+ ),
+ )
return {
success: true,
diff --git a/server/api/photos/check-duplicate.post.ts b/server/api/photos/check-duplicate.post.ts
index 9d28cf6d..cf798365 100644
--- a/server/api/photos/check-duplicate.post.ts
+++ b/server/api/photos/check-duplicate.post.ts
@@ -1,3 +1,4 @@
+import { DEFAULT_SITE } from '@chronoframe/core'
import { z } from 'zod'
import { createDuplicateChecker } from '@chronoframe/core'
import { createSqliteUploadRepository } from '../../repositories/sqlite-uploads'
@@ -40,7 +41,7 @@ export default defineEventHandler(async (event) => {
const config = storageProvider.config
const check = createDuplicateChecker({
identifiers: { fromStorageKey: generateSafePhotoId },
- find: createSqliteUploadRepository(useDB()).findDetails,
+ find: createSqliteUploadRepository(useDB(), DEFAULT_SITE).findDetails,
})
const results = await check(
{ fileNames, storageKeys },
diff --git a/server/api/photos/exif/reindex.post.ts b/server/api/photos/exif/reindex.post.ts
index 10f3ac69..c68a251a 100644
--- a/server/api/photos/exif/reindex.post.ts
+++ b/server/api/photos/exif/reindex.post.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { eq, isNotNull, inArray, and } from 'drizzle-orm'
import {
extractExifData,
@@ -16,7 +18,12 @@ export default eventHandler(async (event) => {
const photo = await useDB()
.select()
.from(tables.photos)
- .where(eq(tables.photos.id, photoId))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, photoId),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.limit(1)
.then((rows) => rows[0])
@@ -59,7 +66,12 @@ export default eventHandler(async (event) => {
lastModified: new Date().toISOString(),
thumbnailKey: `${storageProvider.config?.prefix?.replace(/\/$/, '')}/thumbnails/${photoId}.webp`,
})
- .where(eq(tables.photos.id, photoId))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, photoId),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
logger.chrono.success(`Successfully reindexed EXIF for photo ${photoId}`)
@@ -82,9 +94,12 @@ export default eventHandler(async (event) => {
})
.from(tables.photos)
.where(
- and(
- isNotNull(tables.photos.storageKey),
- inArray(tables.photos.id, photoIds),
+ siteAnd(
+ and(
+ isNotNull(tables.photos.storageKey),
+ inArray(tables.photos.id, photoIds),
+ ),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
),
)
} else {
@@ -95,7 +110,12 @@ export default eventHandler(async (event) => {
storageKey: tables.photos.storageKey,
})
.from(tables.photos)
- .where(isNotNull(tables.photos.storageKey))
+ .where(
+ siteAnd(
+ isNotNull(tables.photos.storageKey),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
}
if (photos.length === 0) {
@@ -157,7 +177,12 @@ export default eventHandler(async (event) => {
lastModified: new Date().toISOString(),
thumbnailKey: `${storageProvider.config?.prefix?.replace(/\/$/, '')}/thumbnails/${photo.id}.webp`,
})
- .where(eq(tables.photos.id, photo.id))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, photo.id),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
updated++
diff --git a/server/api/photos/index.post.ts b/server/api/photos/index.post.ts
index a09efa8e..d62b1e44 100644
--- a/server/api/photos/index.post.ts
+++ b/server/api/photos/index.post.ts
@@ -1,3 +1,4 @@
+import { DEFAULT_SITE } from '@chronoframe/core'
import type {
UploadPreparationResponse,
PreparedUploadResponse,
@@ -23,7 +24,7 @@ export default eventHandler(
const providerConfig = storageProvider.config
const mime = useRuntimeConfig(event).upload.mime
const preparer = createUploadPreparer({
- repository: createSqliteUploadRepository(useDB()),
+ repository: createSqliteUploadRepository(useDB(), DEFAULT_SITE),
identifiers: { fromStorageKey: generateSafePhotoId },
// Self-hosted has no account-wide quota; the per-file policy still applies.
quota: { assertAllowed: async () => {} },
diff --git a/server/api/photos/livephoto/manage.post.ts b/server/api/photos/livephoto/manage.post.ts
index c18f8990..bf8b9210 100644
--- a/server/api/photos/livephoto/manage.post.ts
+++ b/server/api/photos/livephoto/manage.post.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import {
processSpecificLivePhotoVideo,
scanAndProcessExistingLivePhotos,
@@ -72,7 +74,12 @@ export default eventHandler(async (event) => {
const photos = await db
.select()
.from(tables.photos)
- .where(eq(tables.photos.id, photoId))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, photoId),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.limit(1)
if (photos.length === 0) {
@@ -99,7 +106,12 @@ export default eventHandler(async (event) => {
),
livePhotoVideoKey: livePhotoVideo.videoKey,
})
- .where(eq(tables.photos.id, photoId))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, photoId),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
return {
message: 'Photo updated to LivePhoto successfully',
diff --git a/server/api/photos/reactions.get.ts b/server/api/photos/reactions.get.ts
index 9bab70d5..341a6e04 100644
--- a/server/api/photos/reactions.get.ts
+++ b/server/api/photos/reactions.get.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { sql, inArray } from 'drizzle-orm'
import { filterAccessiblePhotoIds } from '../../utils/album-access'
@@ -34,7 +36,12 @@ export default defineEventHandler(async (event) => {
count: sql<number>`count(*)`,
})
.from(tables.photoReactions)
- .where(inArray(tables.photoReactions.photoId, accessibleIds))
+ .where(
+ siteAnd(
+ inArray(tables.photoReactions.photoId, accessibleIds),
+ siteEq(tables.photoReactions.siteId, DEFAULT_SITE.id),
+ ),
+ )
.groupBy(tables.photoReactions.photoId, tables.photoReactions.reactionType)
.all()
diff --git a/server/api/photos/status.get.ts b/server/api/photos/status.get.ts
index 51752eb0..6f123b4e 100644
--- a/server/api/photos/status.get.ts
+++ b/server/api/photos/status.get.ts
@@ -1,3 +1,5 @@
+import { eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { toPhotoDto } from '../../utils/dto'
import { photos } from '~~/server/database/schema'
@@ -11,6 +13,7 @@ export default eventHandler(async (event) => {
const recentPhotos = await useDB()
.select()
.from(photos)
+ .where(siteEq(photos.siteId, DEFAULT_SITE.id))
.orderBy(photos.lastModified)
.limit(10)
.all()
diff --git a/server/api/queue/recent.get.ts b/server/api/queue/recent.get.ts
index 70b682da..42d3cb68 100644
--- a/server/api/queue/recent.get.ts
+++ b/server/api/queue/recent.get.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { desc, inArray, or } from 'drizzle-orm'
import { photos, pipelineQueue } from '~~/server/database/schema'
import type { PipelineQueueItem } from '~~/server/utils/db'
@@ -47,6 +49,7 @@ export default defineEventHandler(async (event) => {
completedAt: pipelineQueue.completedAt,
})
.from(pipelineQueue)
+ .where(siteEq(pipelineQueue.siteId, DEFAULT_SITE.id))
.orderBy(desc(pipelineQueue.createdAt))
.limit(RECENT_TASK_LIMIT)
.all()
@@ -81,7 +84,12 @@ export default defineEventHandler(async (event) => {
storageKey: photos.storageKey,
})
.from(photos)
- .where(or(...photoFilters))
+ .where(
+ siteAnd(
+ or(...photoFilters),
+ siteEq(photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.all()
: []
diff --git a/server/api/queue/task/[taskId].delete.ts b/server/api/queue/task/[taskId].delete.ts
index 539ad308..06cd891a 100644
--- a/server/api/queue/task/[taskId].delete.ts
+++ b/server/api/queue/task/[taskId].delete.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { and, eq, inArray } from 'drizzle-orm'
/** 删除指定的已完成或失败任务。 */
@@ -17,9 +19,12 @@ export default defineEventHandler(async (event) => {
const deletedTask = db
.delete(tables.pipelineQueue)
.where(
- and(
- eq(tables.pipelineQueue.id, taskId),
- inArray(tables.pipelineQueue.status, ['completed', 'failed']),
+ siteAnd(
+ and(
+ eq(tables.pipelineQueue.id, taskId),
+ inArray(tables.pipelineQueue.status, ['completed', 'failed']),
+ ),
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
),
)
.returning({ id: tables.pipelineQueue.id })
@@ -29,7 +34,12 @@ export default defineEventHandler(async (event) => {
const task = db
.select({ id: tables.pipelineQueue.id })
.from(tables.pipelineQueue)
- .where(eq(tables.pipelineQueue.id, taskId))
+ .where(
+ siteAnd(
+ eq(tables.pipelineQueue.id, taskId),
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
.get()
throw createError({
diff --git a/server/api/queue/task/clear.delete.ts b/server/api/queue/task/clear.delete.ts
index 3ac51e75..c4819f49 100644
--- a/server/api/queue/task/clear.delete.ts
+++ b/server/api/queue/task/clear.delete.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { z } from 'zod'
import { or, eq, sql } from 'drizzle-orm'
@@ -72,7 +74,12 @@ export default defineEventHandler(async (event) => {
createdAt: tables.pipelineQueue.createdAt,
})
.from(tables.pipelineQueue)
- .where(whereCondition)
+ .where(
+ siteAnd(
+ whereCondition,
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
if (tasksToDelete.length === 0) {
return {
@@ -87,7 +94,14 @@ export default defineEventHandler(async (event) => {
}
// 执行删除操作
- await db.delete(tables.pipelineQueue).where(whereCondition)
+ await db
+ .delete(tables.pipelineQueue)
+ .where(
+ siteAnd(
+ whereCondition,
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
// 统计删除的任务
const breakdown = tasksToDelete.reduce(
diff --git a/server/api/queue/task/list.get.ts b/server/api/queue/task/list.get.ts
index 8293cde7..f1a95a77 100644
--- a/server/api/queue/task/list.get.ts
+++ b/server/api/queue/task/list.get.ts
@@ -1,3 +1,5 @@
+import { eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { z } from 'zod'
import { desc, sql, eq, and } from 'drizzle-orm'
@@ -41,8 +43,10 @@ export default defineEventHandler(async (event) => {
)
}
- const whereCondition =
- conditions.length > 0 ? and(...conditions) : undefined
+ const whereCondition = and(
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ...conditions,
+ )
// 构建查询
const queryBuilder = db
@@ -60,12 +64,9 @@ export default defineEventHandler(async (event) => {
completedAt: tables.pipelineQueue.completedAt,
})
.from(tables.pipelineQueue)
+ .where(whereCondition)
.orderBy(desc(tables.pipelineQueue.createdAt))
- if (whereCondition) {
- queryBuilder.where(whereCondition)
- }
-
const tasks = await queryBuilder
return {
diff --git a/server/api/queue/task/retry-batch.post.ts b/server/api/queue/task/retry-batch.post.ts
index c68f449a..db8092e5 100644
--- a/server/api/queue/task/retry-batch.post.ts
+++ b/server/api/queue/task/retry-batch.post.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { z } from 'zod'
import { eq, inArray } from 'drizzle-orm'
@@ -36,7 +38,12 @@ export default defineEventHandler(async (event) => {
const tasksToRetry = await db
.select()
.from(tables.pipelineQueue)
- .where(whereCondition)
+ .where(
+ siteAnd(
+ whereCondition,
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
if (
!session.user.isAdmin &&
@@ -76,7 +83,12 @@ export default defineEventHandler(async (event) => {
attempts: 0, // 重置尝试次数
availableAt: new Date(),
})
- .where(inArray(tables.pipelineQueue.id, failedTaskIds))
+ .where(
+ siteAnd(
+ inArray(tables.pipelineQueue.id, failedTaskIds),
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
return {
success: true,
diff --git a/server/api/queue/task/retry.post.ts b/server/api/queue/task/retry.post.ts
index 2952520a..01d44c5d 100644
--- a/server/api/queue/task/retry.post.ts
+++ b/server/api/queue/task/retry.post.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { z } from 'zod'
import { eq } from 'drizzle-orm'
@@ -21,7 +23,12 @@ export default defineEventHandler(async (event) => {
const task = await db
.select()
.from(tables.pipelineQueue)
- .where(eq(tables.pipelineQueue.id, taskId))
+ .where(
+ siteAnd(
+ eq(tables.pipelineQueue.id, taskId),
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
.get()
if (!task) {
@@ -56,7 +63,12 @@ export default defineEventHandler(async (event) => {
attempts: 0, // 重置尝试次数
availableAt: new Date(),
})
- .where(eq(tables.pipelineQueue.id, taskId))
+ .where(
+ siteAnd(
+ eq(tables.pipelineQueue.id, taskId),
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
return {
success: true,
diff --git a/server/api/system/settings/all.get.ts b/server/api/system/settings/all.get.ts
index 58d4261f..d8181fab 100644
--- a/server/api/system/settings/all.get.ts
+++ b/server/api/system/settings/all.get.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import type { PublicSettingsResponse } from '@chronoframe/contracts/settings'
import { useDB, tables, eq, or, and } from '~~/server/utils/db'
@@ -14,15 +16,18 @@ export default eventHandler(async () => {
.select()
.from(tables.settings)
.where(
- or(
- and(
- eq(tables.settings.isPublic, true),
- eq(tables.settings.isSecret, false),
- ),
- and(
- eq(tables.settings.namespace, 'system'),
- eq(tables.settings.key, 'firstLaunch'),
+ siteAnd(
+ or(
+ and(
+ eq(tables.settings.isPublic, true),
+ eq(tables.settings.isSecret, false),
+ ),
+ and(
+ eq(tables.settings.namespace, 'system'),
+ eq(tables.settings.key, 'firstLaunch'),
+ ),
),
+ siteEq(tables.settings.siteId, DEFAULT_SITE.id),
),
)
.all()
diff --git a/server/api/system/stats.get.ts b/server/api/system/stats.get.ts
index 45a0e549..9bb3aebd 100644
--- a/server/api/system/stats.get.ts
+++ b/server/api/system/stats.get.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import type {} from '../../types/worker'
import { getLocationMigrationStatus } from '../../services/pipeline-queue/location-migration'
import { settingsManager } from '~~/server/services/settings/settingsManager'
@@ -134,12 +136,14 @@ export default eventHandler(async (event) => {
>`MIN(CASE WHEN status = 'pending' THEN created_at END)`,
})
.from(tables.pipelineQueue)
+ .where(siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id))
.get()
// 获取基础统计
const totalPhotos = await useDB()
.select({ count: sql<number>`count(*)` })
.from(tables.photos)
+ .where(siteEq(tables.photos.siteId, DEFAULT_SITE.id))
.get()
// 获取今日新增照片数量
@@ -150,7 +154,12 @@ export default eventHandler(async (event) => {
const todayPhotos = await useDB()
.select({ count: sql<number>`count(*)` })
.from(tables.photos)
- .where(gte(tables.photos.dateTaken, todayISO))
+ .where(
+ siteAnd(
+ gte(tables.photos.dateTaken, todayISO),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.get()
// 获取本周新增照片数量
@@ -162,7 +171,12 @@ export default eventHandler(async (event) => {
const weekPhotos = await useDB()
.select({ count: sql<number>`count(*)` })
.from(tables.photos)
- .where(gte(tables.photos.dateTaken, weekAgoISO))
+ .where(
+ siteAnd(
+ gte(tables.photos.dateTaken, weekAgoISO),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.get()
// 获取本月新增照片数量
@@ -174,7 +188,12 @@ export default eventHandler(async (event) => {
const monthPhotos = await useDB()
.select({ count: sql<number>`count(*)` })
.from(tables.photos)
- .where(gte(tables.photos.dateTaken, monthStartISO))
+ .where(
+ siteAnd(
+ gte(tables.photos.dateTaken, monthStartISO),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.get()
// 获取存储统计(估算)
@@ -185,6 +204,7 @@ export default eventHandler(async (event) => {
maxSize: sql<number>`COALESCE(max(file_size), 0)`,
})
.from(tables.photos)
+ .where(siteEq(tables.photos.siteId, DEFAULT_SITE.id))
.get()
// 获取最近7天的上传趋势
@@ -201,7 +221,12 @@ export default eventHandler(async (event) => {
count: sql<number>`count(*)`,
})
.from(tables.photos)
- .where(gte(tables.photos.dateTaken, sevenDaysAgoISO))
+ .where(
+ siteAnd(
+ gte(tables.photos.dateTaken, sevenDaysAgoISO),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.groupBy(sql`DATE(${tables.photos.dateTaken})`)
.orderBy(sql`DATE(${tables.photos.dateTaken}) ASC`)
.all()
diff --git a/server/middleware/00.site.ts b/server/middleware/00.site.ts
new file mode 100644
index 00000000..4fe60198
--- /dev/null
+++ b/server/middleware/00.site.ts
@@ -0,0 +1,4 @@
+import { DEFAULT_SITE } from '@chronoframe/core'
+export default defineEventHandler((event) => {
+ event.context.site = DEFAULT_SITE
+})
diff --git a/server/plugins/0.db-migrate.ts b/server/plugins/0.db-migrate.ts
index c02816dd..5cf17d59 100644
--- a/server/plugins/0.db-migrate.ts
+++ b/server/plugins/0.db-migrate.ts
@@ -1,14 +1,8 @@
-import { resolve } from 'node:path'
-import { migrate } from 'drizzle-orm/better-sqlite3/migrator'
+import type {} from '../types/worker'
import { useDB, closeDB } from '../utils/db'
-
export default defineNitroPlugin((nitroApp) => {
try {
- migrate(useDB(), {
- migrationsFolder: resolve(
- process.env.DATABASE_MIGRATIONS || './server/database/migrations',
- ),
- })
+ useDB()
logger
.dynamic('db-migrate')
.info('Database migration finished successfully')
@@ -16,5 +10,8 @@ export default defineNitroPlugin((nitroApp) => {
closeDB()
throw error
}
- nitroApp.hooks.hook('close', closeDB)
+ nitroApp.hooks.hook('close', async () => {
+ await globalThis.__workerPool?.stop()
+ closeDB()
+ })
})
diff --git a/server/plugins/2.settings-manager.ts b/server/plugins/2.settings-manager.ts
index e3f1048c..840211b1 100644
--- a/server/plugins/2.settings-manager.ts
+++ b/server/plugins/2.settings-manager.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { createSettingsRuntimeEffects } from '../runtime/settings-effects'
import type { SettingValue } from '~~/shared/types/settings'
import { DEFAULT_SETTINGS } from '../services/settings/contants'
@@ -237,9 +239,12 @@ async function removeDeprecatedSettings() {
db.delete(tables.settings)
.where(
- and(
- eq(tables.settings.namespace, 'app'),
- eq(tables.settings.key, 'upload.maxFileSize'),
+ siteAnd(
+ and(
+ eq(tables.settings.namespace, 'app'),
+ eq(tables.settings.key, 'upload.maxFileSize'),
+ ),
+ siteEq(tables.settings.siteId, DEFAULT_SITE.id),
),
)
.run()
diff --git a/server/plugins/3.storage.ts b/server/plugins/3.storage.ts
index 739142e8..c417cf5e 100644
--- a/server/plugins/3.storage.ts
+++ b/server/plugins/3.storage.ts
@@ -90,7 +90,10 @@ export async function initializeStorageManagerFromActiveProvider(
}
try {
- const storageManager = new StorageManager(activeProvider.config, logger.storage)
+ const storageManager = new StorageManager(
+ activeProvider.config,
+ logger.storage,
+ )
setGlobalStorageManager(storageManager)
attachStorageManagerEvents(storageManager)
await ensureLocalStorageReady(activeProvider.config)
diff --git a/server/plugins/4.pipeline-queue.ts b/server/plugins/4.pipeline-queue.ts
index 9b2dad3b..27f5ce12 100644
--- a/server/plugins/4.pipeline-queue.ts
+++ b/server/plugins/4.pipeline-queue.ts
@@ -1,3 +1,4 @@
+import { closeDB } from '../utils/db'
import type {} from '../types/worker'
import { WorkerPool } from '../services/pipeline-queue'
import { settingsManager } from '../services/settings/settingsManager'
@@ -22,7 +23,7 @@ export default defineNitroPlugin(async (nitroApp) => {
globalThis.__workerPool = workerPool
let shutdown: Promise<void> | undefined
- const stop = () => (shutdown ||= workerPool.stop())
+ const stop = () => (shutdown ||= workerPool.stop().finally(closeDB))
nitroApp.hooks.hook('close', stop)
const exitHandler = () => {
diff --git a/server/routes/image/[...key].get.ts b/server/routes/image/[...key].get.ts
index bb6a8627..e25ea82c 100644
--- a/server/routes/image/[...key].get.ts
+++ b/server/routes/image/[...key].get.ts
@@ -1,3 +1,6 @@
+import { storageForPhoto } from '../../utils/object-storage'
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { serveLocalMedia } from '../../utils/local-media'
import { eq } from 'drizzle-orm'
import { Readable } from 'node:stream'
@@ -5,7 +8,7 @@ import { assertPhotoAccess } from '../../utils/album-access'
import { tables, useDB } from '../../utils/db'
export default eventHandler(async (event) => {
- const { storageProvider } = useStorageProvider(event)
+ let { storageProvider } = useStorageProvider(event)
const key = getRouterParam(event, 'key')
if (!key) {
@@ -31,12 +34,18 @@ export default eventHandler(async (event) => {
const photo = useDB()
.select()
.from(tables.photos)
- .where(eq(tables.photos.id, photoId))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, photoId),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.get()
if (!photo) {
throw createError({ statusCode: 404, statusMessage: 'Photo not found' })
}
const restricted = await assertPhotoAccess(event, photo.id)
+ storageProvider = await storageForPhoto(photo.id, storageProvider)
const targetUrl =
kind === 'original'
diff --git a/server/routes/thumb/[...thumbnailUrl].get.ts b/server/routes/thumb/[...thumbnailUrl].get.ts
index 36c83a6e..aefd4062 100644
--- a/server/routes/thumb/[...thumbnailUrl].get.ts
+++ b/server/routes/thumb/[...thumbnailUrl].get.ts
@@ -1,3 +1,6 @@
+import { storageForPhoto } from '../../utils/object-storage'
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { readFile } from 'node:fs/promises'
import { resolveLocalMediaPath } from '../../utils/local-media'
import { eq } from 'drizzle-orm'
@@ -6,7 +9,7 @@ import sharp from 'sharp'
import { assertPhotoAccess } from '../../utils/album-access'
export default eventHandler(async (event) => {
- const { storageProvider } = useStorageProvider(event)
+ let { storageProvider } = useStorageProvider(event)
let url = getRouterParam(event, 'thumbnailUrl')
@@ -18,7 +21,7 @@ export default eventHandler(async (event) => {
}
url = decodeURIComponent(url)
- const isAppPath = url.startsWith('/storage/') || url.startsWith('/image/')
+ let isAppPath = url.startsWith('/storage/') || url.startsWith('/image/')
let absoluteUrl: URL | undefined
if (!isAppPath) {
try {
@@ -40,26 +43,34 @@ export default eventHandler(async (event) => {
const restricted = await assertPhotoAccess(event, accessKey, !isAppPath)
if (restricted) setHeader(event, 'Cache-Control', 'private, no-store')
+ if (protectedPhotoMatch) {
+ const row = useDB()
+ .select()
+ .from(tables.photos)
+ .where(
+ siteAnd(
+ eq(tables.photos.id, accessKey),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
+ .get()
+ const kind = url.split('/').pop()
+ const resourceUrl =
+ kind === 'original'
+ ? row?.originalUrl
+ : kind === 'live'
+ ? row?.livePhotoVideoUrl
+ : row?.thumbnailUrl
+ if (!resourceUrl)
+ throw createError({ statusCode: 404, statusMessage: 'Photo not found' })
+ storageProvider = await storageForPhoto(accessKey, storageProvider)
+ url = resourceUrl
+ isAppPath = url.startsWith('/storage/') || url.startsWith('/image/')
+ }
+
let photo: Buffer
if (storageProvider.config?.provider === 'local' && isAppPath) {
let target = url
- if (protectedPhotoMatch) {
- const row = useDB()
- .select()
- .from(tables.photos)
- .where(eq(tables.photos.id, accessKey))
- .get()
- const kind = url.split('/').pop()
- const resourceUrl =
- kind === 'original'
- ? row?.originalUrl
- : kind === 'live'
- ? row?.livePhotoVideoUrl
- : row?.thumbnailUrl
- if (!resourceUrl)
- throw createError({ statusCode: 404, statusMessage: 'Photo not found' })
- target = resourceUrl
- }
if (!/^\/(?:storage|image)\//.test(target))
throw createError({ statusCode: 404, statusMessage: 'Photo not found' })
const localKey = decodeURIComponent(
diff --git a/server/services/image/processor.ts b/server/services/image/processor.ts
index 5f6f12a8..dfd92f4a 100644
--- a/server/services/image/processor.ts
+++ b/server/services/image/processor.ts
@@ -1,3 +1,4 @@
+import type { StorageProvider } from '@chronoframe/storage'
import path from 'node:path'
import { getStorageManager } from '../../plugins/3.storage'
import { logger } from '../../utils/logger'
@@ -14,12 +15,12 @@ export const {
} = createImageProcessor(logger.image)
export const preprocessImageWithJpegUpload = async (
s3key: string,
+ storageProvider: StorageProvider = getStorageManager().getProvider(),
): Promise<{
raw: Buffer
processed: Buffer
jpegKey?: string // HEIC 转换后上传的 JPEG 文件的 key
} | null> => {
- const storageProvider = getStorageManager().getProvider()
if (!storageProvider) return null
try {
diff --git a/server/services/pipeline-queue/location-migration.ts b/server/services/pipeline-queue/location-migration.ts
index f26b4b5a..eceaac90 100644
--- a/server/services/pipeline-queue/location-migration.ts
+++ b/server/services/pipeline-queue/location-migration.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { and, eq, isNull, or, sql } from 'drizzle-orm'
import type { useDB } from '../../utils/db'
import { photos, pipelineQueue } from '../../database/schema.ts'
@@ -11,9 +13,12 @@ export function enqueueLocationMigrationRequest(
.select({ id: pipelineQueue.id })
.from(pipelineQueue)
.where(
- and(
- sql`json_extract(${pipelineQueue.payload}, '$.type') = 'location-migration'`,
- sql`${pipelineQueue.status} IN ('pending', 'in-stages')`,
+ siteAnd(
+ and(
+ sql`json_extract(${pipelineQueue.payload}, '$.type') = 'location-migration'`,
+ sql`${pipelineQueue.status} IN ('pending', 'in-stages')`,
+ ),
+ siteEq(pipelineQueue.siteId, DEFAULT_SITE.id),
),
)
.get()
@@ -44,21 +49,26 @@ export function getLocationMigrationStatus(db: ReturnType<typeof useDB>) {
const { count } = db
.select({ count: sql<number>`count(*)` })
.from(photos)
- .where(legacyLocationCondition)
+ .where(
+ siteAnd(legacyLocationCondition, siteEq(photos.siteId, DEFAULT_SITE.id)),
+ )
.get()!
const active = db
.select({ id: pipelineQueue.id })
.from(pipelineQueue)
.where(
- and(
- sql`${pipelineQueue.status} IN ('pending', 'in-stages')`,
- or(
- sql`json_extract(${pipelineQueue.payload}, '$.type') = 'location-migration'`,
- and(
- sql`json_extract(${pipelineQueue.payload}, '$.type') = 'photo-reverse-geocoding'`,
- sql`json_extract(${pipelineQueue.payload}, '$.migrationOnly') = 1`,
+ siteAnd(
+ and(
+ sql`${pipelineQueue.status} IN ('pending', 'in-stages')`,
+ or(
+ sql`json_extract(${pipelineQueue.payload}, '$.type') = 'location-migration'`,
+ and(
+ sql`json_extract(${pipelineQueue.payload}, '$.type') = 'photo-reverse-geocoding'`,
+ sql`json_extract(${pipelineQueue.payload}, '$.migrationOnly') = 1`,
+ ),
),
),
+ siteEq(pipelineQueue.siteId, DEFAULT_SITE.id),
),
)
.get()
@@ -72,15 +82,23 @@ export function enqueueLocationMigration(db: ReturnType<typeof useDB>) {
const candidates = tx
.select({ id: photos.id, storageKey: photos.storageKey })
.from(photos)
- .where(legacyLocationCondition)
+ .where(
+ siteAnd(
+ legacyLocationCondition,
+ siteEq(photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.all()
const active = tx
.select({ payload: pipelineQueue.payload })
.from(pipelineQueue)
.where(
- or(
- eq(pipelineQueue.status, 'pending'),
- eq(pipelineQueue.status, 'in-stages'),
+ siteAnd(
+ or(
+ eq(pipelineQueue.status, 'pending'),
+ eq(pipelineQueue.status, 'in-stages'),
+ ),
+ siteEq(pipelineQueue.siteId, DEFAULT_SITE.id),
),
)
.all()
diff --git a/server/services/pipeline-queue/location-update.ts b/server/services/pipeline-queue/location-update.ts
index 86819cd5..356d3d8f 100644
--- a/server/services/pipeline-queue/location-update.ts
+++ b/server/services/pipeline-queue/location-update.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { and, eq, isNull } from 'drizzle-orm'
import { photos } from '../../database/schema.ts'
import type { Photo, useDB } from '../../utils/db.ts'
@@ -34,15 +36,18 @@ export function updateGeocodedPhoto(
geocoding: location.geocoding,
})
.where(
- and(
- eq(photos.id, photo.id),
- photo.latitude == null
- ? isNull(photos.latitude)
- : eq(photos.latitude, photo.latitude),
- photo.longitude == null
- ? isNull(photos.longitude)
- : eq(photos.longitude, photo.longitude),
- migrationOnly ? isNull(photos.geocoding) : undefined,
+ siteAnd(
+ and(
+ eq(photos.id, photo.id),
+ photo.latitude == null
+ ? isNull(photos.latitude)
+ : eq(photos.latitude, photo.latitude),
+ photo.longitude == null
+ ? isNull(photos.longitude)
+ : eq(photos.longitude, photo.longitude),
+ migrationOnly ? isNull(photos.geocoding) : undefined,
+ ),
+ siteEq(photos.siteId, DEFAULT_SITE.id),
),
)
.run().changes
diff --git a/server/services/pipeline-queue/manager.ts b/server/services/pipeline-queue/manager.ts
index 66a5e821..841157ac 100644
--- a/server/services/pipeline-queue/manager.ts
+++ b/server/services/pipeline-queue/manager.ts
@@ -1,3 +1,6 @@
+import { storageForReference } from '../../utils/object-storage'
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import {
enqueueLocationMigration,
enqueueLocationMigrationRequest,
@@ -134,11 +137,30 @@ export class QueueManager {
const db = useDB()
if (payload.type === 'location-migration')
return enqueueLocationMigrationRequest(db, options)
+ const active = await settingsManager.storage.getActiveProvider()
+ const photoId = 'photoId' in payload ? payload.photoId : undefined
+ const photo = photoId
+ ? db
+ .select()
+ .from(tables.photos)
+ .where(
+ and(
+ eq(tables.photos.id, photoId),
+ eq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
+ .get()
+ : undefined
+ if (photoId && !photo) throw new PermanentTaskError('Photo not found')
const result = db
.insert(tables.pipelineQueue)
.values({
payload,
...options,
+ siteId: DEFAULT_SITE.id,
+ storageConnectionId: photo?.storageConnectionId ?? active?.id ?? null,
+ storageRevision: photo?.storageRevision ?? active?.revision ?? 1,
+ sourceVersion: photo?.sourceVersion ?? 1,
})
.returning({ id: tables.pipelineQueue.id })
.get()
@@ -155,7 +177,12 @@ export class QueueManager {
const task = await db
.select()
.from(tables.pipelineQueue)
- .where(eq(tables.pipelineQueue.id, taskId))
+ .where(
+ siteAnd(
+ eq(tables.pipelineQueue.id, taskId),
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
.get()
return task
}
@@ -173,9 +200,12 @@ export class QueueManager {
.select()
.from(tables.pipelineQueue)
.where(
- and(
- eq(tables.pipelineQueue.status, 'pending'),
- lte(tables.pipelineQueue.availableAt, new Date()),
+ siteAnd(
+ and(
+ eq(tables.pipelineQueue.status, 'pending'),
+ lte(tables.pipelineQueue.availableAt, new Date()),
+ ),
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
),
)
// 优先处理高优先级和较早创建的任务
@@ -192,7 +222,12 @@ export class QueueManager {
const task = highestPriorityPendingTask
tx.update(tables.pipelineQueue)
.set({ status: 'in-stages' })
- .where(eq(tables.pipelineQueue.id, task.id))
+ .where(
+ siteAnd(
+ eq(tables.pipelineQueue.id, task.id),
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
.run()
return { ...task, status: 'in-stages' as const }
@@ -214,7 +249,12 @@ export class QueueManager {
await db
.update(tables.pipelineQueue)
.set({ statusStage: stage })
- .where(eq(tables.pipelineQueue.id, taskId))
+ .where(
+ siteAnd(
+ eq(tables.pipelineQueue.id, taskId),
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
}
/**
@@ -233,7 +273,12 @@ export class QueueManager {
completedAt: sql`(unixepoch())`,
warningCode,
})
- .where(eq(tables.pipelineQueue.id, taskId))
+ .where(
+ siteAnd(
+ eq(tables.pipelineQueue.id, taskId),
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
}
/**
@@ -250,7 +295,12 @@ export class QueueManager {
const task = await db
.select()
.from(tables.pipelineQueue)
- .where(eq(tables.pipelineQueue.id, taskId))
+ .where(
+ siteAnd(
+ eq(tables.pipelineQueue.id, taskId),
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
.get()
if (!task) return
@@ -280,7 +330,12 @@ export class QueueManager {
}
: {}),
})
- .where(eq(tables.pipelineQueue.id, taskId))
+ .where(
+ siteAnd(
+ eq(tables.pipelineQueue.id, taskId),
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
if (shouldRetry) {
this.logger.warn(
@@ -304,7 +359,10 @@ export class QueueManager {
)
}
const { storageKey } = payload
- const storageProvider = getStorageManager().getProvider()
+ const storageProvider = await storageForReference(
+ task,
+ getStorageManager().getProvider(),
+ )
const photoId = generateSafePhotoId(storageKey)
try {
@@ -329,7 +387,10 @@ export class QueueManager {
// STEP 1: 预处理 - 转换 HEIC 到 JPEG 并上传
await this.updateTaskStage(taskId, 'preprocessing')
this.logger.info(`[${taskId}:in-stage] preprocessing`)
- const imageBuffers = await preprocessImageWithJpegUpload(storageKey)
+ const imageBuffers = await preprocessImageWithJpegUpload(
+ storageKey,
+ storageProvider,
+ )
if (!imageBuffers) {
throw new Error('Preprocessing failed')
}
@@ -434,7 +495,10 @@ export class QueueManager {
this.logger.info(`[${taskId}:in-stage] live photo detection`)
let livePhotoInfo = null
if (!motionPhotoInfo?.isMotionPhoto) {
- const livePhotoVideo = await findLivePhotoVideoForImage(storageKey)
+ const livePhotoVideo = await findLivePhotoVideoForImage(
+ storageKey,
+ storageProvider,
+ )
if (livePhotoVideo) {
livePhotoInfo = {
isLivePhoto: 1,
@@ -456,7 +520,11 @@ export class QueueManager {
}
// 构建最终的 Photo 对象
- const result: Photo = {
+ const result: typeof tables.photos.$inferInsert = {
+ siteId: task.siteId,
+ storageConnectionId: task.storageConnectionId,
+ storageRevision: task.storageRevision,
+ sourceVersion: task.sourceVersion,
id: photoId,
title: photoInfo.title,
description: photoInfo.description,
@@ -562,7 +630,12 @@ export class QueueManager {
const photo = await db
.select()
.from(tables.photos)
- .where(eq(tables.photos.id, photoId))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, photoId),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.get()
if (!photo) {
@@ -624,7 +697,12 @@ export class QueueManager {
locationName: null,
geocoding: null,
})
- .where(eq(tables.photos.id, photoId))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, photoId),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
throw new PermanentTaskError(
`Missing coordinates for photo ${photoId}`,
)
@@ -672,8 +750,11 @@ export class QueueManager {
},
eraseLocation: async (task: PipelineQueueItem) => {
const db = useDB()
- const storageProvider = getStorageManager().getProvider()
const { id: taskId, payload } = task
+ const storageProvider = await storageForReference(
+ task,
+ getStorageManager().getProvider(),
+ )
if (payload.type !== 'photo-erase-location') {
throw new Error(
@@ -689,7 +770,12 @@ export class QueueManager {
const photo = await db
.select()
.from(tables.photos)
- .where(eq(tables.photos.id, payload.photoId))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, payload.photoId),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.get()
if (!photo) {
@@ -732,15 +818,7 @@ export class QueueManager {
const updatedBuffer = await readFile(tempFile)
- const prefix =
- storageProvider.config && 'prefix' in storageProvider.config
- ? storageProvider.config.prefix
- : ''
-
- await storageProvider.create(
- photo.storageKey.replace(prefix || '', ''),
- updatedBuffer,
- )
+ await storageProvider.create(photo.storageKey, updatedBuffer)
const exifData = stripLocationFromExif(
await extractExifData(updatedBuffer),
@@ -759,7 +837,12 @@ export class QueueManager {
locationName: null,
geocoding: null,
})
- .where(eq(tables.photos.id, payload.photoId))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, payload.photoId),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
this.logger.success(
`[${taskId}:location-erase] erased location info for photo ${payload.photoId}`,
@@ -770,7 +853,10 @@ export class QueueManager {
},
livePhotoDetect: async (task: PipelineQueueItem) => {
const db = useDB()
- const storageProvider = getStorageManager().getProvider()
+ const storageProvider = await storageForReference(
+ task,
+ getStorageManager().getProvider(),
+ )
const { id: taskId, payload } = task
if (payload.type !== 'live-photo-video') {
@@ -818,7 +904,12 @@ export class QueueManager {
const photos = await db
.select()
.from(tables.photos)
- .where(eq(tables.photos.storageKey, photoKey))
+ .where(
+ siteAnd(
+ eq(tables.photos.storageKey, photoKey),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.limit(1)
const matched = photos[0]
@@ -848,7 +939,12 @@ export class QueueManager {
livePhotoVideoUrl,
livePhotoVideoKey: videoKey,
})
- .where(eq(tables.photos.id, matchedPhoto.id))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, matchedPhoto.id),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
this.logger.success(
`LivePhoto detection task ${taskId} processed successfully, updated photo ${matchedPhoto.id}`,
@@ -983,6 +1079,7 @@ export class QueueManager {
count: sql<number>`COUNT(*)`,
})
.from(tables.pipelineQueue)
+ .where(siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id))
.groupBy(tables.pipelineQueue.status)
return stats.reduce(
diff --git a/server/services/pipeline-queue/worker-pool.ts b/server/services/pipeline-queue/worker-pool.ts
index 9236ff0b..ccf11124 100644
--- a/server/services/pipeline-queue/worker-pool.ts
+++ b/server/services/pipeline-queue/worker-pool.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import type { ConsolaInstance } from 'consola'
import { consola } from 'consola'
import { eq, sql } from 'drizzle-orm'
@@ -49,6 +51,7 @@ export class WorkerPool {
private statsInterval: NodeJS.Timeout | null = null
private isRunning: boolean = false
private resizing: Promise<void> = Promise.resolve()
+ private stopping: Promise<void> | null = null
constructor(config: Partial<WorkerPoolConfig>, logger?: ConsolaInstance) {
this.config = {
@@ -76,6 +79,7 @@ export class WorkerPool {
`Starting WorkerPool with ${this.config.workerCount} workers`,
)
+ this.stopping = null
// 在启动工作器之前,清理死任务
await this.cleanupDeadTasks()
@@ -107,7 +111,12 @@ export class WorkerPool {
/**
* 停止工作器池
*/
- async stop(): Promise<void> {
+ stop(): Promise<void> {
+ this.stopping ??= this.stopWorkers()
+ return this.stopping
+ }
+
+ private async stopWorkers(): Promise<void> {
if (!this.isRunning) {
this.logger.warn('WorkerPool is not running')
return
@@ -253,7 +262,12 @@ export class WorkerPool {
const deadTasks = await db
.select()
.from(tables.pipelineQueue)
- .where(eq(tables.pipelineQueue.status, 'in-stages'))
+ .where(
+ siteAnd(
+ eq(tables.pipelineQueue.status, 'in-stages'),
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
if (deadTasks.length > 0) {
this.logger.warn(
@@ -271,7 +285,12 @@ export class WorkerPool {
THEN -1 ELSE 1 END`,
statusStage: null,
})
- .where(eq(tables.pipelineQueue.status, 'in-stages'))
+ .where(
+ siteAnd(
+ eq(tables.pipelineQueue.status, 'in-stages'),
+ siteEq(tables.pipelineQueue.siteId, DEFAULT_SITE.id),
+ ),
+ )
this.logger.success(
`Successfully reset ${deadTasks.length} dead tasks to pending status with migration priorities preserved`,
diff --git a/server/services/settings/settingsManager.ts b/server/services/settings/settingsManager.ts
index f081ed2e..694a1609 100644
--- a/server/services/settings/settingsManager.ts
+++ b/server/services/settings/settingsManager.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import type {
NewStorageProviderRow as NewSettingStorageProvider,
StorageProviderRow as SettingStorageProvider,
@@ -70,7 +72,7 @@ export class SettingsManager {
namespace: SettingNamespace,
key: SettingKey<typeof namespace>,
): string {
- return `${namespace}:${key}`
+ return `site:${DEFAULT_SITE.id}:${namespace}:${key}`
}
/**
@@ -138,9 +140,12 @@ export class SettingsManager {
.select()
.from(tables.settings)
.where(
- and(
- eq(tables.settings.namespace, config.namespace),
- eq(tables.settings.key, config.key),
+ siteAnd(
+ and(
+ eq(tables.settings.namespace, config.namespace),
+ eq(tables.settings.key, config.key),
+ ),
+ siteEq(tables.settings.siteId, DEFAULT_SITE.id),
),
)
.get()
@@ -185,9 +190,12 @@ export class SettingsManager {
.select()
.from(tables.settings)
.where(
- and(
- eq(tables.settings.namespace, namespace),
- eq(tables.settings.key, key),
+ siteAnd(
+ and(
+ eq(tables.settings.namespace, namespace),
+ eq(tables.settings.key, key),
+ ),
+ siteEq(tables.settings.siteId, DEFAULT_SITE.id),
),
)
.get()
@@ -226,9 +234,12 @@ export class SettingsManager {
})
.from(tables.settings)
.where(
- and(
- eq(tables.settings.namespace, namespace),
- eq(tables.settings.key, key),
+ siteAnd(
+ and(
+ eq(tables.settings.namespace, namespace),
+ eq(tables.settings.key, key),
+ ),
+ siteEq(tables.settings.siteId, DEFAULT_SITE.id),
),
)
.get()
@@ -251,9 +262,12 @@ export class SettingsManager {
.select()
.from(tables.settings)
.where(
- and(
- eq(tables.settings.namespace, namespace),
- eq(tables.settings.key, key),
+ siteAnd(
+ and(
+ eq(tables.settings.namespace, namespace),
+ eq(tables.settings.key, key),
+ ),
+ siteEq(tables.settings.siteId, DEFAULT_SITE.id),
),
)
.get()
@@ -280,9 +294,12 @@ export class SettingsManager {
updatedBy: updatedBy ?? null,
})
.where(
- and(
- eq(tables.settings.namespace, namespace),
- eq(tables.settings.key, key),
+ siteAnd(
+ and(
+ eq(tables.settings.namespace, namespace),
+ eq(tables.settings.key, key),
+ ),
+ siteEq(tables.settings.siteId, DEFAULT_SITE.id),
),
)
.run()
@@ -300,7 +317,12 @@ export class SettingsManager {
const settings = db
.select()
.from(tables.settings)
- .where(eq(tables.settings.namespace, namespace))
+ .where(
+ siteAnd(
+ eq(tables.settings.namespace, namespace),
+ siteEq(tables.settings.siteId, DEFAULT_SITE.id),
+ ),
+ )
.all()
const result: Record<string, SettingValue> = {}
@@ -313,7 +335,11 @@ export class SettingsManager {
async getSchema(): Promise<SettingConfig[]> {
const db = useDB()
- const settings = db.select().from(tables.settings).all()
+ const settings = db
+ .select()
+ .from(tables.settings)
+ .where(siteEq(tables.settings.siteId, DEFAULT_SITE.id))
+ .all()
return settings.map((setting) => ({
namespace: setting.namespace,
@@ -339,6 +365,9 @@ export class SettingsManager {
const providers = db
.select()
.from(tables.settings_storage_providers)
+ .where(
+ siteEq(tables.settings_storage_providers.siteId, DEFAULT_SITE.id),
+ )
.all()
return providers
},
@@ -348,7 +377,12 @@ export class SettingsManager {
const provider = db
.select()
.from(tables.settings_storage_providers)
- .where(eq(tables.settings_storage_providers.id, id))
+ .where(
+ siteAnd(
+ eq(tables.settings_storage_providers.id, id),
+ siteEq(tables.settings_storage_providers.siteId, DEFAULT_SITE.id),
+ ),
+ )
.get()
return provider || null
},
@@ -408,7 +442,12 @@ export class SettingsManager {
.set({
...providerConfig,
})
- .where(eq(tables.settings_storage_providers.id, id))
+ .where(
+ siteAnd(
+ eq(tables.settings_storage_providers.id, id),
+ siteEq(tables.settings_storage_providers.siteId, DEFAULT_SITE.id),
+ ),
+ )
.run()
// Rebuild the active instance before saving completes so subsequent
@@ -426,7 +465,15 @@ export class SettingsManager {
provider: previousProvider.provider,
config: previousProvider.config,
})
- .where(eq(tables.settings_storage_providers.id, id))
+ .where(
+ siteAnd(
+ eq(tables.settings_storage_providers.id, id),
+ siteEq(
+ tables.settings_storage_providers.siteId,
+ DEFAULT_SITE.id,
+ ),
+ ),
+ )
.run()
} catch (rollbackError) {
settingsManager._logger.error(
@@ -442,7 +489,12 @@ export class SettingsManager {
async deleteProvider(id: number): Promise<void> {
const db = useDB()
db.delete(tables.settings_storage_providers)
- .where(eq(tables.settings_storage_providers.id, id))
+ .where(
+ siteAnd(
+ eq(tables.settings_storage_providers.id, id),
+ siteEq(tables.settings_storage_providers.siteId, DEFAULT_SITE.id),
+ ),
+ )
.run()
},
}
diff --git a/server/services/video/livephoto.ts b/server/services/video/livephoto.ts
index 4624c7c3..ae424db6 100644
--- a/server/services/video/livephoto.ts
+++ b/server/services/video/livephoto.ts
@@ -1,3 +1,6 @@
+import type { StorageProvider } from '@chronoframe/storage'
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { isLivePhotoVideo } from '@chronoframe/media/livephoto'
import path from 'path'
import { eq } from 'drizzle-orm'
@@ -39,7 +42,12 @@ export const processLivePhotoVideo = async (
const photos = await db
.select()
.from(tables.photos)
- .where(eq(tables.photos.storageKey, photoKey))
+ .where(
+ siteAnd(
+ eq(tables.photos.storageKey, photoKey),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.limit(1)
if (photos.length > 0) {
@@ -67,7 +75,12 @@ export const processLivePhotoVideo = async (
livePhotoVideoUrl: videoUrl,
livePhotoVideoKey: videoKey,
})
- .where(eq(tables.photos.id, matchedPhoto.id))
+ .where(
+ siteAnd(
+ eq(tables.photos.id, matchedPhoto.id),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
logger.chrono.success(
`Successfully processed LivePhoto: ${matchedPhoto.id}, video: ${videoKey}`,
@@ -84,9 +97,8 @@ export const processLivePhotoVideo = async (
*/
export const findLivePhotoVideoForImage = async (
imageKey: string,
+ storageProvider: StorageProvider = getStorageManager().getProvider(),
): Promise<{ videoKey: string; videoSize: number } | null> => {
- const storageProvider = getStorageManager().getProvider()
-
try {
// 从图片文件名提取基础名称(去除扩展名)
const imageBaseName = path.basename(imageKey, path.extname(imageKey))
diff --git a/server/services/video/test-utils.ts b/server/services/video/test-utils.ts
index 137ed67b..a8a65c13 100644
--- a/server/services/video/test-utils.ts
+++ b/server/services/video/test-utils.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { eq, and, inArray } from 'drizzle-orm'
import { findLivePhotoVideoForImage } from '../video/livephoto'
@@ -54,9 +56,12 @@ export const batchTestLivePhotoDetection = async (photoIds?: string[]) => {
.select()
.from(tables.photos)
.where(
- and(
- eq(tables.photos.isLivePhoto, 0),
- inArray(tables.photos.id, photoIds),
+ siteAnd(
+ and(
+ eq(tables.photos.isLivePhoto, 0),
+ inArray(tables.photos.id, photoIds),
+ ),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
),
)
} else {
@@ -64,7 +69,12 @@ export const batchTestLivePhotoDetection = async (photoIds?: string[]) => {
photos = await db
.select()
.from(tables.photos)
- .where(eq(tables.photos.isLivePhoto, 0))
+ .where(
+ siteAnd(
+ eq(tables.photos.isLivePhoto, 0),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
}
logger.chrono.info(
diff --git a/server/tasks/db/migrate.ts b/server/tasks/db/migrate.ts
index 521b6388..f8b386e8 100644
--- a/server/tasks/db/migrate.ts
+++ b/server/tasks/db/migrate.ts
@@ -1,29 +1,10 @@
-import { migrate } from 'drizzle-orm/better-sqlite3/migrator'
-import { fileURLToPath } from 'url'
-import { dirname, join } from 'path'
-
export default defineTask({
meta: {
name: 'db:migrate',
- description: 'Migrate the database',
+ description: 'Migrate the configured database with a pre-upgrade backup',
},
async run() {
- const log = logger.dynamic('db')
- const db = useDB()
-
- log.info('Migrating database...')
-
- const __filename = fileURLToPath(import.meta.url)
- const __dirname = dirname(__filename)
-
- migrate(db, {
- migrationsFolder: join(__dirname, '../../server/database/migrations'),
- })
-
- log.success('Database migrated successfully.')
-
- return {
- result: 'success',
- }
+ useDB()
+ return { result: 'success' }
},
})
diff --git a/server/utils/album-access.ts b/server/utils/album-access.ts
index b5b2cd26..17963577 100644
--- a/server/utils/album-access.ts
+++ b/server/utils/album-access.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import {
canReadAlbum,
photoAccessDenied,
@@ -9,7 +11,7 @@ import { eq, inArray } from 'drizzle-orm'
import type { H3Event } from 'h3'
import { tables, useDB } from './db'
-const cookieName = 'album_access'
+const cookieName = `album_access_${DEFAULT_SITE.id}`
const grantLifetimeSeconds = 7 * 24 * 60 * 60
const maxGrants = 30
type Grant = { id: number; hash: string; expiresAt: number }
@@ -47,7 +49,7 @@ export async function verifyAlbumPassword(
function signature(payload: string): string {
return createHmac('sha256', sessionSecret())
- .update('album-access-cookie\0')
+ .update(`album-access-cookie:${DEFAULT_SITE.id}\0`)
.update(payload)
.digest('base64url')
}
@@ -155,7 +157,12 @@ export async function assertPhotoAccess(
const matchedPhotos = db
.select({ id: tables.photoAccessKeys.photoId })
.from(tables.photoAccessKeys)
- .where(eq(tables.photoAccessKeys.accessKey, cleanKey))
+ .where(
+ siteAnd(
+ eq(tables.photoAccessKeys.accessKey, cleanKey),
+ siteEq(tables.photoAccessKeys.siteId, DEFAULT_SITE.id),
+ ),
+ )
.all()
if (matchedPhotos.length === 0) {
if (!admin || requireKnown) throw photoNotFound()
@@ -170,7 +177,12 @@ export async function assertPhotoAccess(
tables.albums,
eq(tables.albumPhotos.albumId, tables.albums.id),
)
- .where(eq(tables.albumPhotos.photoId, photo.id))
+ .where(
+ siteAnd(
+ eq(tables.albumPhotos.photoId, photo.id),
+ siteEq(tables.albumPhotos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.all()
if (memberships.some(({ album }) => album.isHidden || album.passwordHash)) {
restricted = true
@@ -206,7 +218,12 @@ export async function filterAccessiblePhotoIds(
const existing = db
.select({ id: tables.photos.id })
.from(tables.photos)
- .where(inArray(tables.photos.id, chunk))
+ .where(
+ siteAnd(
+ inArray(tables.photos.id, chunk),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.all()
if (existing.length === 0) continue
@@ -226,7 +243,12 @@ export async function filterAccessiblePhotoIds(
tables.albums,
eq(tables.albumPhotos.albumId, tables.albums.id),
)
- .where(inArray(tables.albumPhotos.photoId, ids))
+ .where(
+ siteAnd(
+ inArray(tables.albumPhotos.photoId, ids),
+ siteEq(tables.albumPhotos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.all()
const membershipsByPhoto = new Map<string, { album: AlbumAccessTarget }[]>()
for (const row of rows) {
diff --git a/server/utils/album-visibility.ts b/server/utils/album-visibility.ts
index a5c37d83..98c3da11 100644
--- a/server/utils/album-visibility.ts
+++ b/server/utils/album-visibility.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { asc, eq, getTableColumns, or, isNotNull, ne, and } from 'drizzle-orm'
import type { useDB } from './db'
import type * as schema from '../database/schema'
@@ -28,7 +30,12 @@ export async function fetchAlbumPhotos(
tables.albumPhotos,
eq(tables.photos.id, tables.albumPhotos.photoId),
)
- .where(eq(tables.albumPhotos.albumId, albumId))
+ .where(
+ siteAnd(
+ eq(tables.albumPhotos.albumId, albumId),
+ siteEq(tables.photos.siteId, DEFAULT_SITE.id),
+ ),
+ )
.orderBy(asc(tables.albumPhotos.position))
.all()
@@ -45,15 +52,18 @@ export async function fetchAlbumPhotos(
eq(tables.albumPhotos.albumId, tables.albums.id),
)
.where(
- includePasswordProtected
- ? eq(tables.albums.isHidden, true)
- : or(
- eq(tables.albums.isHidden, true),
- and(
- isNotNull(tables.albums.passwordHash),
- ne(tables.albums.id, albumId),
+ siteAnd(
+ includePasswordProtected
+ ? eq(tables.albums.isHidden, true)
+ : or(
+ eq(tables.albums.isHidden, true),
+ and(
+ isNotNull(tables.albums.passwordHash),
+ ne(tables.albums.id, albumId),
+ ),
),
- ),
+ siteEq(tables.albumPhotos.siteId, DEFAULT_SITE.id),
+ ),
)
.all()
).map((r: { photoId: string }) => r.photoId)
diff --git a/server/utils/db.ts b/server/utils/db.ts
index 1471d3d2..3a08a0d6 100644
--- a/server/utils/db.ts
+++ b/server/utils/db.ts
@@ -21,6 +21,9 @@ let connection: ReturnType<typeof openDatabase> | null = null
export function useDB() {
connection ??= openDatabase({
filename: resolve(process.env.DATABASE_URL || './data/app.sqlite3'),
+ migrationsFolder: resolve(
+ process.env.DATABASE_MIGRATIONS || './server/database/migrations',
+ ),
verbose:
process.env.NODE_ENV === 'development'
? logger.dynamic('db').verbose
diff --git a/server/utils/object-storage.ts b/server/utils/object-storage.ts
new file mode 100644
index 00000000..381eb00b
--- /dev/null
+++ b/server/utils/object-storage.ts
@@ -0,0 +1,43 @@
+import { DEFAULT_SITE, siteCacheKey } from '@chronoframe/core'
+import { createSiteRepository } from '@chronoframe/database'
+import { StorageManager, type StorageProvider } from '../services/storage'
+import { useDB } from './db'
+import { logger } from './logger'
+
+const versions = new Map<string, StorageProvider>()
+
+/** Resolve immutable connection revisions, rather than silently reading the currently active provider. */
+export async function storageForReference(
+ reference: { storageConnectionId: number | null; storageRevision: number },
+ fallback: StorageProvider,
+): Promise<StorageProvider> {
+ if (reference.storageConnectionId === null) return fallback // Legacy unconfigured records.
+ const key = siteCacheKey(
+ DEFAULT_SITE,
+ `${reference.storageConnectionId}:${reference.storageRevision}`,
+ )
+ const cached = versions.get(key)
+ if (cached) return cached
+ const config = await createSiteRepository(
+ useDB(),
+ DEFAULT_SITE,
+ ).storageVersion(reference.storageConnectionId, reference.storageRevision)
+ if (!config)
+ throw createError({
+ statusCode: 404,
+ statusMessage: 'Storage connection version not found',
+ })
+ const provider = new StorageManager(config, logger.storage).getProvider()
+ versions.set(key, provider)
+ return provider
+}
+
+export async function storageForPhoto(id: string, fallback: StorageProvider) {
+ const reference = await createSiteRepository(
+ useDB(),
+ DEFAULT_SITE,
+ ).photoReference(id)
+ if (!reference)
+ throw createError({ statusCode: 404, statusMessage: 'Photo not found' })
+ return storageForReference(reference, fallback)
+}
diff --git a/server/utils/photo-album.ts b/server/utils/photo-album.ts
index 83953197..85fd50ea 100644
--- a/server/utils/photo-album.ts
+++ b/server/utils/photo-album.ts
@@ -1,51 +1,18 @@
-import { and, eq } from 'drizzle-orm'
-import type { drizzle } from 'drizzle-orm/better-sqlite3'
-import * as tables from '../database/schema.ts'
-import { QueueWarningCode } from '../../shared/utils/queue-warning.ts'
-import { appendAlbumPhotos, touchAlbum } from './album-membership.ts'
-
-export type AlbumAssignmentResult =
- | 'no-album'
- | typeof QueueWarningCode.AlbumMissing
- | 'already-added'
- | 'added'
-
-export const persistPhotoWithAlbum = (
- db: ReturnType<typeof drizzle>,
+import { DEFAULT_SITE } from '@chronoframe/core'
+import {
+ createPhotoPersistenceRepository,
+ type AppDatabase,
+ type tables,
+} from '@chronoframe/database'
+export type { AlbumAssignmentResult } from '@chronoframe/database'
+/** Compatibility adapter for the embedded default Site. */
+export function persistPhotoWithAlbum(
+ db: AppDatabase,
photo: typeof tables.photos.$inferInsert,
albumId?: number,
-): AlbumAssignmentResult =>
- db.transaction((tx) => {
- tx.insert(tables.photos)
- .values(photo)
- .onConflictDoUpdate({ target: tables.photos.id, set: photo })
- .run()
-
- if (albumId === undefined) return 'no-album'
-
- const album = tx
- .select({ id: tables.albums.id })
- .from(tables.albums)
- .where(eq(tables.albums.id, albumId))
- .get()
- if (!album) return QueueWarningCode.AlbumMissing
-
- const existing = tx
- .select({ id: tables.albumPhotos.id })
- .from(tables.albumPhotos)
- .where(
- and(
- eq(tables.albumPhotos.albumId, albumId),
- eq(tables.albumPhotos.photoId, photo.id),
- ),
- )
- .get()
- if (existing) return 'already-added'
-
- if (appendAlbumPhotos(tx, albumId, [photo.id]) === 0) {
- return 'already-added'
- }
-
- touchAlbum(tx, albumId)
- return 'added'
- })
+) {
+ return createPhotoPersistenceRepository(db, DEFAULT_SITE).persist(
+ photo,
+ albumId,
+ )
+}
diff --git a/server/utils/queue-payload.ts b/server/utils/queue-payload.ts
index 9902dbbc..19217e5a 100644
--- a/server/utils/queue-payload.ts
+++ b/server/utils/queue-payload.ts
@@ -1,3 +1,5 @@
+import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { z } from 'zod'
import { eq } from 'drizzle-orm'
import * as tables from '../database/schema.ts'
@@ -44,7 +46,12 @@ export const photoTaskAlbumExists = (
const album = (db ?? useDB())
.select({ id: tables.albums.id })
.from(tables.albums)
- .where(eq(tables.albums.id, payload.albumId))
+ .where(
+ siteAnd(
+ eq(tables.albums.id, payload.albumId),
+ siteEq(tables.albums.siteId, DEFAULT_SITE.id),
+ ),
+ )
.get()
return Boolean(album)
diff --git a/server/utils/resource-reader.ts b/server/utils/resource-reader.ts
index 433aeb46..0023ebfc 100644
--- a/server/utils/resource-reader.ts
+++ b/server/utils/resource-reader.ts
@@ -1,3 +1,4 @@
+import { DEFAULT_SITE } from '@chronoframe/core'
import { createError } from 'h3'
import { createResourceReader, CoreError } from '@chronoframe/core'
import { createSqliteResourceRepository } from '../repositories/sqlite-resources'
@@ -5,7 +6,9 @@ import { useDB } from './db'
/** Assemble the current self-hosted repository at the application boundary. */
export function useResourceReader() {
- return createResourceReader(createSqliteResourceRepository(useDB()))
+ return createResourceReader(
+ createSqliteResourceRepository(useDB(), DEFAULT_SITE),
+ )
}
/** Translate only known domain failures; preserve unexpected errors for server handling. */
diff --git a/server/utils/resource-writer.ts b/server/utils/resource-writer.ts
index 681f2bf0..f706ad01 100644
--- a/server/utils/resource-writer.ts
+++ b/server/utils/resource-writer.ts
@@ -1,3 +1,6 @@
+import { persistenceErrorCode } from '@chronoframe/database'
+import { storageForPhoto } from './object-storage'
+import { DEFAULT_SITE } from '@chronoframe/core'
import type {} from '../types/worker'
import { createError, type H3Event } from 'h3'
import {
@@ -18,7 +21,7 @@ import { logger } from './logger'
/** Assemble album persistence, clock and hashing in the self-hosted application. */
export function useAlbumWriter() {
return createAlbumWriter({
- repository: createSqliteAlbumWriteRepository(useDB()),
+ repository: createSqliteAlbumWriteRepository(useDB(), DEFAULT_SITE),
clock: { now: () => new Date() },
hashPassword: hashAlbumPassword,
})
@@ -28,16 +31,18 @@ export function useAlbumWriter() {
export function usePhotoWriter(event: H3Event) {
const { storageProvider } = useStorageProvider(event)
return createPhotoWriter({
- repository: createSqlitePhotoWriteRepository(useDB()),
+ repository: createSqlitePhotoWriteRepository(useDB(), DEFAULT_SITE),
clock: { now: () => new Date() },
- storage: { forPhoto: async () => storageProvider },
- editMetadata: (photo, input) => {
+ storage: {
+ forPhoto: (photo) => storageForPhoto(photo.id, storageProvider),
+ },
+ editMetadata: async (photo, input) => {
if (!photo.storageKey)
throw new CoreError(400, 'Photo has no storage key')
return editPhotoMetadata(
{ ...photo, storageKey: photo.storageKey },
input,
- storageProvider,
+ await storageForPhoto(photo.id, storageProvider),
)
},
tasks: {
@@ -68,6 +73,11 @@ export async function mutationResponse<T>(
try {
return await operation()
} catch (error) {
+ if (persistenceErrorCode(error) === 'invalid-relation')
+ throw createError({
+ statusCode: 400,
+ statusMessage: 'Invalid resource reference',
+ })
if (error instanceof CoreError)
throw createError({
statusCode: error.statusCode,
diff --git a/server/utils/upload-album-options.ts b/server/utils/upload-album-options.ts
index 0c3c49c6..5d2d183a 100644
--- a/server/utils/upload-album-options.ts
+++ b/server/utils/upload-album-options.ts
@@ -1,3 +1,5 @@
+import { eq as siteEq } from 'drizzle-orm'
+import { DEFAULT_SITE } from '@chronoframe/core'
import { asc, count, desc, eq } from 'drizzle-orm'
import type { drizzle } from 'drizzle-orm/better-sqlite3'
import * as tables from '../database/schema.ts'
@@ -12,6 +14,7 @@ export const listUploadAlbumOptions = (db: ReturnType<typeof drizzle>) => {
photoCount: count(tables.albumPhotos.id),
})
.from(tables.albums)
+ .where(siteEq(tables.albums.siteId, DEFAULT_SITE.id))
.leftJoin(
tables.albumPhotos,
eq(tables.albumPhotos.albumId, tables.albums.id),
diff --git a/tests/core-mutations.test.ts b/tests/core-mutations.test.ts
index 2c9006c7..2334ae06 100644
--- a/tests/core-mutations.test.ts
+++ b/tests/core-mutations.test.ts
@@ -1,3 +1,4 @@
+import { DEFAULT_SITE } from '@chronoframe/core'
import assert from 'node:assert/strict'
import test from 'node:test'
import Database from 'better-sqlite3'
@@ -31,7 +32,7 @@ test('album mutations preserve ordering, password semantics, cover membership an
.values([{ id: 'a' }, { id: 'b' }])
.run()
const writer = createAlbumWriter({
- repository: createSqliteAlbumWriteRepository(db),
+ repository: createSqliteAlbumWriteRepository(db, DEFAULT_SITE),
clock: { now: () => now },
hashPassword: async (value) => `hash:${value}`,
})
@@ -147,7 +148,7 @@ test('photo mutations keep normalized EXIF and database edits aligned and tolera
})
.run()
const writer = createPhotoWriter({
- repository: createSqlitePhotoWriteRepository(db),
+ repository: createSqlitePhotoWriteRepository(db, DEFAULT_SITE),
clock: { now: () => now },
storage: {
forPhoto: async () => ({
diff --git a/tests/database-lifecycle.test.ts b/tests/database-lifecycle.test.ts
index 44333e35..a9e1389b 100644
--- a/tests/database-lifecycle.test.ts
+++ b/tests/database-lifecycle.test.ts
@@ -1,3 +1,4 @@
+import { DEFAULT_SITE } from '@chronoframe/core'
import test from 'node:test'
import assert from 'node:assert/strict'
import { mkdtemp, rm } from 'node:fs/promises'
@@ -29,7 +30,7 @@ test('database connection, repositories, rollback, backup, restart and reentrant
{ id: 'c', dateTaken: null },
])
.run()
- const reader = createSqliteResourceRepository(db)
+ const reader = createSqliteResourceRepository(db, DEFAULT_SITE)
assert.deepEqual(
(await reader.listPhotos()).map((p) => p.id),
['b', 'a', 'c'],
@@ -46,7 +47,7 @@ test('database connection, repositories, rollback, backup, restart and reentrant
reader.listPhotos([], { limit: 0, offset: 0 }),
RangeError,
)
- const writer = createSqliteAlbumWriteRepository(db)
+ const writer = createSqliteAlbumWriteRepository(db, DEFAULT_SITE)
const createdAt = new Date('2025-01-01T00:00:00Z')
const album = await writer.createFirst(
{ title: 'fixture', createdAt, updatedAt: createdAt },
diff --git a/tests/location-migration.test.ts b/tests/location-migration.test.ts
index 9b772d41..5b17a789 100644
--- a/tests/location-migration.test.ts
+++ b/tests/location-migration.test.ts
@@ -29,9 +29,12 @@ test('migration selects only old geocoded photos and deduplicates queue entries'
'utf8',
),
)
+ sqlite.exec(
+ 'ALTER TABLE photos ADD COLUMN site_id INTEGER NOT NULL DEFAULT 1; ALTER TABLE pipeline_queue ADD COLUMN site_id INTEGER NOT NULL DEFAULT 1; ALTER TABLE pipeline_queue ADD COLUMN storage_connection_id INTEGER; ALTER TABLE pipeline_queue ADD COLUMN storage_revision INTEGER NOT NULL DEFAULT 1; ALTER TABLE pipeline_queue ADD COLUMN source_version INTEGER NOT NULL DEFAULT 1;',
+ )
const db = drizzle(sqlite) as Parameters<typeof enqueueLocationMigration>[0]
const insert = sqlite.prepare(
- 'INSERT INTO photos VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
+ 'INSERT INTO photos(id,storage_key,latitude,longitude,country,city,location_name,geocoding) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
)
insert.run(
'legacy',
diff --git a/tests/queue-task-delete.test.ts b/tests/queue-task-delete.test.ts
index 96a4bb8d..4c3cc6c7 100644
--- a/tests/queue-task-delete.test.ts
+++ b/tests/queue-task-delete.test.ts
@@ -7,7 +7,7 @@ import { pipelineQueue } from '../server/database/schema.ts'
test('single task deletion only removes finished queue records', async (t) => {
const sqlite = new Database(':memory:')
sqlite.exec(
- 'CREATE TABLE pipeline_queue (id INTEGER PRIMARY KEY, status TEXT NOT NULL)',
+ 'CREATE TABLE pipeline_queue (id INTEGER PRIMARY KEY, status TEXT NOT NULL, site_id INTEGER NOT NULL DEFAULT 1)',
)
const db = drizzle(sqlite)
const globals = {
@@ -33,7 +33,7 @@ test('single task deletion only removes finished queue records', async (t) => {
const seed = (status: string) => {
sqlite.exec('DELETE FROM pipeline_queue')
sqlite
- .prepare('INSERT INTO pipeline_queue VALUES (1, ?), (2, ?)')
+ .prepare('INSERT INTO pipeline_queue (id,status) VALUES (1, ?), (2, ?)')
.run(status, 'completed')
}
const remaining = () =>
diff --git a/tests/site-isolation.test.ts b/tests/site-isolation.test.ts
new file mode 100644
index 00000000..a4fe63ed
--- /dev/null
+++ b/tests/site-isolation.test.ts
@@ -0,0 +1,186 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { eq } from 'drizzle-orm'
+import { DEFAULT_SITE, siteCacheKey } from '@chronoframe/core'
+import {
+ openDatabase,
+ tables,
+ createSiteRepository,
+ createSqliteResourceRepository,
+ createSqliteAlbumWriteRepository,
+ createSqlitePhotoWriteRepository,
+ createSqliteUploadRepository,
+} from '@chronoframe/database'
+
+test('two sites isolate resource reads, writes, settings, objects, associations and job connections', async () => {
+ const connection = openDatabase({
+ filename: ':memory:',
+ migrationsFolder: './packages/database/migrations',
+ })
+ try {
+ const { db } = connection,
+ second = { id: 2 }
+ db.insert(tables.sites)
+ .values({ id: 2, workspaceId: 1, name: 'Second' })
+ .run()
+ db.insert(tables.photos)
+ .values([
+ { id: 'first', siteId: 1, storageKey: 'same.jpg' },
+ { id: 'second', siteId: 2, storageKey: 'same.jpg' },
+ ])
+ .run()
+ const a = createSqliteResourceRepository(db, DEFAULT_SITE),
+ b = createSqliteResourceRepository(db, second)
+ assert.deepEqual(
+ (await a.listPhotos()).map((p) => p.id),
+ ['first'],
+ )
+ assert.deepEqual(
+ (await b.listPhotos()).map((p) => p.id),
+ ['second'],
+ )
+ const album = await createSqliteAlbumWriteRepository(
+ db,
+ second,
+ ).createFirst({ title: 'Second album' }, ['second'])
+ assert.equal(await a.getAlbum(album.id), null)
+ assert.deepEqual(await a.listAlbumPhotos(album.id), [])
+ assert.equal(
+ await createSqliteAlbumWriteRepository(db, DEFAULT_SITE).update(
+ album.id,
+ { title: 'stolen' },
+ ),
+ null,
+ )
+ assert.equal(
+ await createSqlitePhotoWriteRepository(db, DEFAULT_SITE).update(
+ 'second',
+ { title: 'stolen' },
+ ),
+ null,
+ )
+ await createSqlitePhotoWriteRepository(db, DEFAULT_SITE).delete('second')
+ assert.equal((await b.listPhotos()).length, 1)
+ assert.equal(
+ await createSqliteUploadRepository(db, DEFAULT_SITE).findDuplicate(
+ 'second',
+ ),
+ null,
+ )
+ await assert.rejects(
+ createSqliteAlbumWriteRepository(db, DEFAULT_SITE).createFirst(
+ { title: 'invalid' },
+ ['second'],
+ ),
+ )
+ assert.throws(() =>
+ db
+ .insert(tables.albumPhotos)
+ .values({ albumId: album.id, photoId: 'first', siteId: 2 })
+ .run(),
+ )
+ assert.throws(() =>
+ db
+ .update(tables.albums)
+ .set({ coverPhotoId: 'first' })
+ .where(eq(tables.albums.id, album.id))
+ .run(),
+ )
+ assert.throws(() =>
+ db
+ .update(tables.photos)
+ .set({ siteId: 1 })
+ .where(eq(tables.photos.id, 'second'))
+ .run(),
+ )
+ db.insert(tables.settings)
+ .values([
+ {
+ siteId: 1,
+ namespace: 'app',
+ key: 'test',
+ type: 'string',
+ value: 'a',
+ },
+ {
+ siteId: 2,
+ namespace: 'app',
+ key: 'test',
+ type: 'string',
+ value: 'b',
+ },
+ ])
+ .run()
+ assert.equal(
+ (await createSiteRepository(db, DEFAULT_SITE).settings('app'))[0]?.value,
+ 'a',
+ )
+ assert.equal(
+ (await createSiteRepository(db, second).settings('app'))[0]?.value,
+ 'b',
+ )
+ const provider = db
+ .insert(tables.settings_storage_providers)
+ .values({
+ siteId: 2,
+ name: 'fixture',
+ provider: 'local',
+ config: {
+ provider: 'local',
+ basePath: '/tmp/site-two',
+ baseUrl: '/storage',
+ prefix: '',
+ },
+ })
+ .returning()
+ .get()
+ assert.equal(
+ await createSiteRepository(db, DEFAULT_SITE).storageVersion(
+ provider.id,
+ 1,
+ ),
+ null,
+ )
+ assert.throws(() =>
+ db
+ .insert(tables.pipelineQueue)
+ .values({ siteId: 1, storageConnectionId: provider.id })
+ .run(),
+ )
+ assert.throws(() =>
+ db
+ .insert(tables.photos)
+ .values({
+ id: 'cross-storage',
+ siteId: 1,
+ storageConnectionId: provider.id,
+ })
+ .run(),
+ )
+ db.update(tables.settings_storage_providers)
+ .set({ config: { ...provider.config, basePath: '/tmp/site-two-new' } })
+ .where(eq(tables.settings_storage_providers.id, provider.id))
+ .run()
+ assert.equal(
+ (await createSiteRepository(db, second).storageVersion(provider.id, 1))
+ ?.provider,
+ 'local',
+ )
+ assert.notDeepEqual(
+ await createSiteRepository(db, second).storageVersion(provider.id, 1),
+ await createSiteRepository(db, second).storageVersion(provider.id, 2),
+ )
+ assert.equal(
+ await createSiteRepository(db, DEFAULT_SITE).photoReference('second'),
+ null,
+ )
+ assert.notEqual(
+ siteCacheKey(DEFAULT_SITE, 'resource'),
+ siteCacheKey(second, 'resource'),
+ )
+ assert.throws(() => createSqliteResourceRepository(db, undefined as never))
+ assert.throws(() => createSqliteResourceRepository(db, { id: 999 }))
+ } finally {
+ connection.close()
+ }
+})
diff --git a/tests/site-migration.test.ts b/tests/site-migration.test.ts
new file mode 100644
index 00000000..417fdc7c
--- /dev/null
+++ b/tests/site-migration.test.ts
@@ -0,0 +1,137 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { mkdtemp, readFile, writeFile, cp, readdir, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import Database from 'better-sqlite3'
+import { openDatabase } from '@chronoframe/database'
+
+/** Exercise actual pre-Site files, including WAL backup and failure rollback. */
+test('legacy ownership upgrade preserves rows, assigns memberships, backs up and rolls back failed migrations', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'chronoframe-site-upgrade-'))
+ const migrations = join(root, 'migrations'),
+ filename = join(root, 'legacy.sqlite3')
+ await cp('packages/database/migrations', migrations, { recursive: true })
+ const journal = JSON.parse(
+ await readFile(join(migrations, 'meta/_journal.json'), 'utf8'),
+ )
+ const legacy = {
+ ...journal,
+ entries: journal.entries.filter((e: { idx: number }) => e.idx < 18),
+ }
+ await writeFile(
+ join(migrations, 'meta/_journal.json'),
+ JSON.stringify(legacy),
+ )
+ let old = openDatabase({ filename, migrationsFolder: migrations })
+ old.close()
+ let raw = new Database(filename)
+ raw
+ .prepare(
+ "INSERT INTO users(name,email,created_at,is_admin) VALUES('admin','[email protected]',1700000000,1),('member','[email protected]',1700000001,0)",
+ )
+ .run()
+ raw
+ .prepare(
+ "INSERT INTO photos(id,title,storage_key) VALUES('legacy','Original','original.jpg')",
+ )
+ .run()
+ raw.prepare("INSERT INTO albums(title) VALUES('Legacy Album')").run()
+ raw
+ .prepare(
+ "INSERT INTO album_photos(album_id,photo_id,position) VALUES(1,'legacy',42)",
+ )
+ .run()
+ raw.close()
+ // Migration and its journal record must roll back together; the backup remains usable.
+ const failure = {
+ ...journal,
+ entries: [
+ ...legacy.entries,
+ {
+ idx: 18,
+ version: '6',
+ when: journal.entries.at(-1).when,
+ tag: 'failure',
+ breakpoints: true,
+ },
+ ],
+ }
+ await writeFile(
+ join(migrations, 'failure.sql'),
+ 'CREATE TABLE should_rollback(id INTEGER);\n--> statement-breakpoint\nSELECT * FROM deliberately_missing_table;',
+ )
+ await writeFile(
+ join(migrations, 'meta/_journal.json'),
+ JSON.stringify(failure),
+ )
+ assert.throws(() => openDatabase({ filename, migrationsFolder: migrations }))
+ raw = new Database(filename)
+ assert.equal(
+ raw
+ .prepare("SELECT name FROM sqlite_master WHERE name='should_rollback'")
+ .get(),
+ undefined,
+ )
+ assert.equal(
+ raw.prepare('SELECT count(*) n FROM __drizzle_migrations').get().n,
+ 18,
+ )
+ assert.equal(
+ raw.prepare("SELECT title FROM photos WHERE id='legacy'").get().title,
+ 'Original',
+ )
+ raw.close()
+ const backups = (await readdir(root)).filter((n) =>
+ n.includes('.pre-migration-'),
+ )
+ assert.equal(backups.length, 1)
+ const backup = new Database(join(root, backups[0]!))
+ assert.equal(backup.prepare('SELECT count(*) n FROM photos').get().n, 1)
+ backup.close()
+ const upgraded = openDatabase({
+ filename,
+ migrationsFolder: 'packages/database/migrations',
+ })
+ upgraded.close()
+ raw = new Database(filename)
+ assert.deepEqual(
+ raw.prepare('SELECT id,title,storage_key,site_id FROM photos').all(),
+ [
+ {
+ id: 'legacy',
+ title: 'Original',
+ storage_key: 'original.jpg',
+ site_id: 1,
+ },
+ ],
+ )
+ assert.equal(
+ raw.prepare('SELECT position FROM album_photos').get().position,
+ 42,
+ )
+ assert.deepEqual(
+ raw.prepare('SELECT user_id,role FROM memberships ORDER BY user_id').all(),
+ [
+ { user_id: 1, role: 'admin' },
+ { user_id: 2, role: 'member' },
+ ],
+ )
+ assert.deepEqual(raw.pragma('foreign_key_check'), [])
+ const count = raw
+ .prepare('SELECT count(*) n FROM __drizzle_migrations')
+ .get().n
+ raw.close()
+ const restarted = openDatabase({
+ filename,
+ migrationsFolder: 'packages/database/migrations',
+ })
+ restarted.close()
+ raw = new Database(filename)
+ assert.equal(
+ raw.prepare('SELECT count(*) n FROM __drizzle_migrations').get().n,
+ count,
+ )
+ raw.close()
+ await rm(root, { recursive: true, force: true })
+})
diff --git a/tests/sqlite-resource-read.test.ts b/tests/sqlite-resource-read.test.ts
index dfdb8293..7bc01432 100644
--- a/tests/sqlite-resource-read.test.ts
+++ b/tests/sqlite-resource-read.test.ts
@@ -1,3 +1,4 @@
+import { DEFAULT_SITE } from '@chronoframe/core'
import assert from 'node:assert/strict'
import test from 'node:test'
import Database from 'better-sqlite3'
@@ -38,7 +39,9 @@ test('SQLite reader preserves migrated data, ordering and legacy album visibilit
{ albumId: 3, photoId: 'locked', position: 0 },
])
.run()
- const reader = createResourceReader(createSqliteResourceRepository(db))
+ const reader = createResourceReader(
+ createSqliteResourceRepository(db, DEFAULT_SITE),
+ )
const anonymous = {
admin: false,
canAccess: (album: { isHidden: boolean; passwordHash: string | null }) =>
diff --git a/tests/upload-album-batch.test.ts b/tests/upload-album-batch.test.ts
index 321db5d0..059e30af 100644
--- a/tests/upload-album-batch.test.ts
+++ b/tests/upload-album-batch.test.ts
@@ -11,7 +11,9 @@ test('batch album checker queries once per distinct album ID', () => {
verbose: (query) => queries.push(query),
})
try {
- sqlite.exec('CREATE TABLE albums (id INTEGER PRIMARY KEY)')
+ sqlite.exec(
+ 'CREATE TABLE albums (id INTEGER PRIMARY KEY, site_id INTEGER NOT NULL DEFAULT 1)',
+ )
sqlite.exec('INSERT INTO albums (id) VALUES (7)')
const db = drizzle(sqlite, { schema })
const albumExists = createPhotoTaskAlbumChecker(db)
diff --git a/tests/upload-album-queue.test.ts b/tests/upload-album-queue.test.ts
index 960abe9c..2b738afa 100644
--- a/tests/upload-album-queue.test.ts
+++ b/tests/upload-album-queue.test.ts
@@ -54,7 +54,9 @@ test('photo queue payload rejects invalid albums and video album IDs', () => {
test('photo tasks only target existing albums', () => {
const sqlite = new Database(':memory:')
try {
- sqlite.exec('CREATE TABLE albums (id INTEGER PRIMARY KEY)')
+ sqlite.exec(
+ 'CREATE TABLE albums (id INTEGER PRIMARY KEY, site_id INTEGER NOT NULL DEFAULT 1)',
+ )
sqlite.exec('INSERT INTO albums (id) VALUES (7)')
const db = drizzle(sqlite, { schema })
assert.equal(