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: extract core mutations settings and upload use cases

HoshinoSuzumiBot41b3bcc5436e
diff --git a/app/pages/dashboard/photos.vue b/app/pages/dashboard/photos.vue
index ec691571..8d399db5 100644
--- a/app/pages/dashboard/photos.vue
+++ b/app/pages/dashboard/photos.vue
@@ -1,5 +1,6 @@
<script lang="ts" setup>
import type { FormSubmitEvent, TableColumn } from '@nuxt/ui'
+import type { UploadPreparationResponse } from '@chronoframe/contracts/upload'
import type { Album, Photo } from '@chronoframe/contracts/resources'
import type { UploadingFile } from '~~/shared/types/uploading-file'
import {
@@ -288,15 +289,18 @@ const uploadImage = async (
try {
// 第一步:获取预签名 URL
uploadingFile.status = UploadQueueStatus.Preparing
- const signedUrlResponse = await $fetch('/api/photos', {
- method: 'POST',
- body: {
- fileName: file.name,
- contentType: file.type,
- fileSize: file.size,
- chunked: true,
+ const signedUrlResponse = await $fetch<UploadPreparationResponse>(
+ '/api/photos',
+ {
+ method: 'POST',
+ body: {
+ fileName: file.name,
+ contentType: file.type,
+ fileSize: file.size,
+ chunked: true,
+ },
},
- })
+ )
uploadingFile.signedUrlResponse = signedUrlResponse
diff --git a/packages/contracts/src/upload.ts b/packages/contracts/src/upload.ts
index d8147aba..c87090cd 100644
--- a/packages/contracts/src/upload.ts
+++ b/packages/contracts/src/upload.ts
@@ -1,3 +1,5 @@
+import type { Photo } from './resources.ts'
+
export interface UploadPart {
partNumber: number
etag: string
@@ -29,3 +31,39 @@ export type UploadPlan =
}
export const UPLOAD_CHUNK_SIZE = 8 * 1024 * 1024
+
+/** Public duplicate summary returned by upload preparation, without internal columns. */
+export type UploadDuplicateSummary = Pick<
+ Photo,
+ 'id' | 'title' | 'storageKey' | 'originalUrl' | 'thumbnailUrl' | 'dateTaken'
+>
+
+export interface PreparedUploadResponse {
+ skipped?: false
+ signedUrl: string
+ upload: UploadPlan
+ fileKey: string
+ expiresIn: number
+ duplicate?: boolean
+ existingPhoto?: UploadDuplicateSummary
+ warningInfo?: {
+ title: string
+ message: string
+ warning: string
+ info: string
+ }
+}
+
+export interface SkippedUploadResponse {
+ skipped: true
+ duplicate: true
+ existingPhoto: UploadDuplicateSummary
+ fileKey: string
+ title: string
+ message: string
+ info: string
+}
+
+export type UploadPreparationResponse =
+ | PreparedUploadResponse
+ | SkippedUploadResponse
diff --git a/packages/core/README.md b/packages/core/README.md
index ed164621..5819bc93 100644
--- a/packages/core/README.md
+++ b/packages/core/README.md
@@ -10,6 +10,19 @@ not expose protected membership. Authorized protected album details replace raw
storage references with access-controlled media URLs. Password hashes remain in
internal access records and never appear in response resources.
-This first P2 batch covers reads only. Writes, settings, Site scoping, database
-migration, and job lifecycle remain in later batches. Do not use this interface
+The first P2 batch introduced reads; the second adds the primary write and
+settings use cases described below. Site scoping, database package migration,
+and durable job lifecycle remain in later batches. Do not use this interface
for multi-site data until a required Site context is introduced.
+
+The second P2 batch adds album and photo mutations, settings validation and
+connection resolution, upload preparation and completion, and protected-access
+policy. Application adapters supply the clock, identifier generation, quota,
+password hashing, object I/O, native EXIF editing, and task dispatch. SQLite
+adapters keep multi-row album changes transactional. HTTP validation, translated
+messages, signed cookies, upload transport, and runtime effects remain in Nuxt.
+
+Photo object edits and database updates retain the existing cross-system
+consistency boundary; source-version fencing and durable task recovery belong
+to the later jobs batch. Self-hosted account-wide quota remains unlimited while
+per-file limits continue to apply.
diff --git a/packages/core/src/access.ts b/packages/core/src/access.ts
new file mode 100644
index 00000000..c3590782
--- /dev/null
+++ b/packages/core/src/access.ts
@@ -0,0 +1,31 @@
+export interface AlbumAccessTarget {
+ id: number
+ isHidden: boolean
+ passwordHash: string | null
+}
+
+/** Hidden albums require a session; public protected albums require a current password grant. */
+export function canReadAlbum(
+ album: AlbumAccessTarget,
+ authenticated: boolean,
+ hasGrant: (album: AlbumAccessTarget) => boolean,
+): boolean {
+ return (
+ authenticated ||
+ (!album.isHidden && (!album.passwordHash || hasGrant(album)))
+ )
+}
+
+/** A hidden membership wins; otherwise one valid protected membership permits media access. */
+export function photoAccessDenied(
+ authenticated: boolean,
+ memberships: { album: AlbumAccessTarget }[],
+ canAccess: (album: AlbumAccessTarget) => boolean,
+): boolean {
+ if (authenticated) return false
+ return (
+ memberships.some(({ album }) => album.isHidden) ||
+ (memberships.some(({ album }) => album.passwordHash) &&
+ !memberships.some(({ album }) => album.passwordHash && canAccess(album)))
+ )
+}
diff --git a/packages/core/src/errors.ts b/packages/core/src/errors.ts
new file mode 100644
index 00000000..225b8227
--- /dev/null
+++ b/packages/core/src/errors.ts
@@ -0,0 +1,19 @@
+/** Transport-neutral domain failure; the application supplies HTTP mapping and translations. */
+export class CoreError extends Error {
+ readonly statusCode: number
+ readonly code?: string
+ constructor(statusCode: number, message: string, code?: string) {
+ super(message)
+ this.name = 'CoreError'
+ this.statusCode = statusCode
+ this.code = code
+ }
+}
+
+/** Retain the read-specific error identity for existing consumers. */
+export class ResourceReadError extends CoreError {
+ constructor(statusCode: 401 | 403 | 404, message: string) {
+ super(statusCode, message)
+ this.name = 'ResourceReadError'
+ }
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 875c312a..c09962a1 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -32,15 +32,8 @@ export interface ReadAccess {
}): boolean
}
-/** Transport-neutral failure translated to HTTP by the application adapter. */
-export class ResourceReadError extends Error {
- readonly statusCode: 401 | 403 | 404
- constructor(statusCode: 401 | 403 | 404, message: string) {
- super(message)
- this.statusCode = statusCode
- this.name = 'ResourceReadError'
- }
-}
+export { CoreError, ResourceReadError } from './errors.ts'
+import { ResourceReadError } from './errors.ts'
/** Read use cases own visibility rules; repositories own query and ordering details. */
export function createResourceReader(repository: ResourceReadRepository) {
@@ -142,3 +135,9 @@ export function createResourceReader(repository: ResourceReadRepository) {
},
}
}
+
+export * from './mutations.ts'
+export * from './settings.ts'
+export * from './uploads.ts'
+export * from './access.ts'
+export * from './upload-preparation.ts'
diff --git a/packages/core/src/mutations.ts b/packages/core/src/mutations.ts
new file mode 100644
index 00000000..9776c43c
--- /dev/null
+++ b/packages/core/src/mutations.ts
@@ -0,0 +1,295 @@
+import { hasValidCoordinates } from '@chronoframe/contracts/location'
+import type { Album, Photo } from '@chronoframe/contracts/resources'
+import { CoreError } from './errors.ts'
+
+export interface MutationAccess {
+ authenticated: boolean
+}
+export interface Clock {
+ now(): Date
+}
+
+export interface AlbumInput {
+ title?: string
+ description?: string
+ coverPhotoId?: string
+ photoIds?: string[]
+ isHidden?: boolean
+ password?: string
+}
+export interface AlbumWriteData {
+ title?: string
+ description?: string | null
+ coverPhotoId?: string | null
+ isHidden?: boolean
+ passwordHash?: string | null
+ updatedAt?: Date
+}
+
+/** Each multi-row operation is atomic in the concrete database adapter. */
+export interface AlbumWriteRepository {
+ exists(id: number): Promise<boolean>
+ createFirst(
+ data: AlbumWriteData & { title: string },
+ photoIds: string[],
+ ): Promise<Album>
+ update(
+ id: number,
+ data: AlbumWriteData,
+ photoIds?: string[],
+ ): Promise<Album | null>
+ delete(id: number): Promise<boolean>
+ reorder(ids: number[]): Promise<void>
+ removePhoto(id: number, photoId: string, updatedAt: Date): Promise<boolean>
+}
+
+function authorize(access: MutationAccess) {
+ if (!access.authenticated) throw new CoreError(401, 'Unauthorized')
+}
+
+function albumPhotoIds(input: AlbumInput): string[] {
+ const ids = new Set(input.photoIds || [])
+ if (input.coverPhotoId) ids.add(input.coverPhotoId)
+ return [...ids]
+}
+
+/** Own album write policy while delegating atomic persistence and password hashing. */
+export function createAlbumWriter(deps: {
+ repository: AlbumWriteRepository
+ clock: Clock
+ hashPassword(password: string): Promise<string>
+}) {
+ return {
+ async create(
+ input: AlbumInput & { title: string },
+ access: MutationAccess,
+ ) {
+ authorize(access)
+ return deps.repository.createFirst(
+ {
+ title: input.title,
+ description: input.description || null,
+ coverPhotoId: input.coverPhotoId || null,
+ isHidden: input.isHidden || false,
+ passwordHash: input.password
+ ? await deps.hashPassword(input.password)
+ : null,
+ },
+ albumPhotoIds(input),
+ )
+ },
+ async update(id: number, input: AlbumInput, access: MutationAccess) {
+ authorize(access)
+ if (!(await deps.repository.exists(id)))
+ throw new CoreError(404, 'Album not found')
+ const data: AlbumWriteData = { updatedAt: deps.clock.now() }
+ if (input.title !== undefined) data.title = input.title
+ if (input.description !== undefined)
+ data.description = input.description || null
+ if (input.coverPhotoId !== undefined)
+ data.coverPhotoId = input.coverPhotoId || null
+ if (input.isHidden !== undefined) data.isHidden = input.isHidden
+ if (input.password !== undefined)
+ data.passwordHash = input.password
+ ? await deps.hashPassword(input.password)
+ : null
+ const album = await deps.repository.update(
+ id,
+ data,
+ input.photoIds === undefined ? undefined : albumPhotoIds(input),
+ )
+ if (!album) throw new CoreError(404, 'Album not found')
+ return album
+ },
+ async delete(id: number, access: MutationAccess) {
+ authorize(access)
+ if (!(await deps.repository.delete(id)))
+ throw new CoreError(404, 'Album not found')
+ return { success: true }
+ },
+ async reorder(ids: number[], access: MutationAccess) {
+ authorize(access)
+ await deps.repository.reorder(ids)
+ return { success: true }
+ },
+ async removePhoto(id: number, photoId: string, access: MutationAccess) {
+ authorize(access)
+ if (!(await deps.repository.removePhoto(id, photoId, deps.clock.now())))
+ throw new CoreError(404, 'Photo not found in album')
+ return { success: true }
+ },
+ }
+}
+
+export interface PhotoMetadataInput {
+ title?: string
+ description?: string
+ tags?: string[]
+ location?: { latitude: number; longitude: number } | null
+ rating?: number | null
+}
+export type PhotoUpdate = Partial<
+ Pick<
+ Photo,
+ | 'title'
+ | 'description'
+ | 'tags'
+ | 'exif'
+ | 'fileSize'
+ | 'lastModified'
+ | 'latitude'
+ | 'longitude'
+ | 'country'
+ | 'city'
+ | 'locationName'
+ | 'geocoding'
+ >
+>
+export interface PhotoWriteRepository {
+ get(id: string): Promise<Photo | null>
+ update(id: string, update: PhotoUpdate): Promise<Photo | null>
+ delete(id: string): Promise<void>
+}
+export interface PhotoObjectStorage {
+ delete(key: string): Promise<void>
+}
+export interface StorageResolver {
+ forPhoto(photo: Photo): Promise<PhotoObjectStorage>
+}
+export interface PhotoTaskDispatcher {
+ reverseGeocode(
+ id: string,
+ coordinates: { latitude: number; longitude: number },
+ ): Promise<void>
+}
+
+/** Normalize editable text and tags before updating either EXIF or the database. */
+export function normalizePhotoMetadata(
+ input: PhotoMetadataInput,
+): PhotoMetadataInput {
+ const normalized = { ...input }
+ if (input.title !== undefined) normalized.title = input.title.trim()
+ if (input.description !== undefined)
+ normalized.description = input.description.trim()
+ if (input.tags !== undefined) {
+ const seen = new Set<string>()
+ normalized.tags = input.tags
+ .map((tag) => tag.trim())
+ .filter((tag) => {
+ const key = tag.toLowerCase()
+ if (!tag || seen.has(key)) return false
+ seen.add(key)
+ return true
+ })
+ }
+ return normalized
+}
+
+/** Coordinate metadata edits and best-effort file cleanup without runtime globals. */
+export function createPhotoWriter(deps: {
+ repository: PhotoWriteRepository
+ storage: StorageResolver
+ clock: Clock
+ editMetadata(
+ photo: Photo,
+ input: PhotoMetadataInput,
+ ): Promise<Pick<Photo, 'exif' | 'fileSize'>>
+ tasks: PhotoTaskDispatcher
+ warn(error: unknown, operation: string): void
+}) {
+ return {
+ async update(id: string, raw: PhotoMetadataInput, access: MutationAccess) {
+ authorize(access)
+ if (Object.values(raw).every((value) => value === undefined))
+ throw new CoreError(
+ 400,
+ 'No changes provided',
+ 'dashboard.photos.messages.noChangesProvided',
+ )
+ if (
+ raw.location &&
+ !hasValidCoordinates(raw.location.latitude, raw.location.longitude)
+ )
+ throw new CoreError(400, 'Invalid coordinates')
+ const photo = await deps.repository.get(id)
+ if (!photo)
+ throw new CoreError(
+ 404,
+ 'Photo not found',
+ 'dashboard.photos.messages.photoNotFound',
+ )
+ if (!photo.storageKey)
+ throw new CoreError(
+ 400,
+ 'Photo has no storage key',
+ 'dashboard.photos.messages.noStorageKey',
+ )
+ const input = normalizePhotoMetadata(raw)
+ const edited = await deps.editMetadata(photo, input)
+ const update: PhotoUpdate = {
+ exif: edited.exif,
+ fileSize: edited.fileSize,
+ lastModified: deps.clock.now().toISOString(),
+ }
+ if (input.title !== undefined) update.title = input.title || null
+ if (input.description !== undefined)
+ update.description = input.description || null
+ if (input.tags !== undefined) update.tags = input.tags
+ if (input.location !== undefined) {
+ Object.assign(update, {
+ latitude: input.location?.latitude ?? null,
+ longitude: input.location?.longitude ?? null,
+ country: null,
+ city: null,
+ locationName: null,
+ geocoding: null,
+ })
+ }
+ let updated: Photo | null
+ try {
+ updated = await deps.repository.update(id, update)
+ } catch (error) {
+ deps.warn(error, 'update-photo-record')
+ throw new CoreError(
+ 500,
+ 'Failed to update photo metadata',
+ 'dashboard.photos.messages.metadataUpdateFailed',
+ )
+ }
+ if (input.location) {
+ try {
+ await deps.tasks.reverseGeocode(id, input.location)
+ } catch (error) {
+ deps.warn(error, 'reverse-geocoding')
+ }
+ }
+ return { success: true, photo: updated || undefined }
+ },
+ async delete(id: string, access: MutationAccess) {
+ authorize(access)
+ const photo = await deps.repository.get(id)
+ if (!photo) throw new CoreError(404, 'Photo not found')
+ const keys = [
+ photo.storageKey,
+ photo.thumbnailKey,
+ photo.livePhotoVideoKey,
+ ]
+ const match =
+ photo.storageKey && /\.(heic|heif|hif)$/i.exec(photo.storageKey)
+ if (match)
+ keys.push(photo.storageKey!.slice(0, -match[0].length) + '.jpeg')
+ const storage = await deps.storage.forPhoto(photo)
+ for (const key of new Set(
+ keys.filter((key): key is string => Boolean(key)),
+ )) {
+ try {
+ await storage.delete(key)
+ } catch (error) {
+ deps.warn(error, 'delete-photo-object')
+ }
+ }
+ await deps.repository.delete(id)
+ return { statusCode: 200, statusMessage: 'Photo deleted successfully' }
+ },
+ }
+}
diff --git a/packages/core/src/settings.ts b/packages/core/src/settings.ts
new file mode 100644
index 00000000..9b2a3812
--- /dev/null
+++ b/packages/core/src/settings.ts
@@ -0,0 +1,71 @@
+import type { SettingValue } from '@chronoframe/contracts/settings'
+
+export const DEFAULT_QUEUE_WORKER_COUNT = 5
+
+/** Validate configured embedded concurrency before persistence or worker startup. */
+export function validateQueueWorkerCount(
+ value: unknown,
+): asserts value is number {
+ if (
+ typeof value !== 'number' ||
+ !Number.isInteger(value) ||
+ value < 1 ||
+ value > 8
+ ) {
+ throw new Error('Queue concurrency must be an integer between 1 and 8')
+ }
+}
+
+/** Validate domain rules without owning persistence, caches or runtime effects. */
+export function validateSettingWrite(input: {
+ namespace: string
+ key: string
+ value: SettingValue
+ readonly: boolean
+ enumValues: string[] | null
+ sudo: boolean
+}): void {
+ const { namespace, key, value, enumValues, sudo } = input
+ if (input.readonly && !sudo)
+ throw new Error(`Setting ${namespace}:${key} is readonly`)
+ if (
+ enumValues?.length &&
+ (value === null || !enumValues.includes(String(value)))
+ ) {
+ throw new Error(
+ `Invalid value for setting ${namespace}:${key}. Allowed values: ${enumValues.join(', ')}`,
+ )
+ }
+ if (namespace === 'location' && key === 'fallbackOrder') {
+ const levels = [
+ 'country',
+ 'region',
+ 'subregion',
+ 'city',
+ 'district',
+ 'locality',
+ 'neighborhood',
+ ]
+ if (
+ typeof value !== 'string' ||
+ value.split(',').some((level) => !levels.includes(level.trim()))
+ ) {
+ throw new Error('Invalid location fallback order')
+ }
+ }
+ if (namespace === 'system' && key === 'queue.workerCount')
+ validateQueueWorkerCount(value)
+}
+
+/** Resolve the configured connection through an injected persistence boundary. */
+export function createStorageResolver<T>(repository: {
+ getSelectedId(): Promise<number | null | undefined>
+ find(id: number): Promise<T | null>
+}) {
+ return {
+ async resolve(): Promise<T | null> {
+ const id = await repository.getSelectedId()
+ return id ? repository.find(id) : null
+ },
+ }
+}
diff --git a/packages/core/src/upload-preparation.ts b/packages/core/src/upload-preparation.ts
new file mode 100644
index 00000000..cfec99dd
--- /dev/null
+++ b/packages/core/src/upload-preparation.ts
@@ -0,0 +1,186 @@
+import type {
+ UploadPlan,
+ UploadDuplicateSummary,
+} from '@chronoframe/contracts/upload'
+import { CoreError } from './errors.ts'
+
+export type DuplicatePhoto = UploadDuplicateSummary
+export interface UploadQuota {
+ assertAllowed(owner: string, size: number | undefined): Promise<void>
+}
+export interface PhotoIdentifiers {
+ fromStorageKey(key: string): string
+}
+export interface UploadPreparationRepository {
+ findDuplicate(id: string): Promise<DuplicatePhoto | null>
+}
+export interface UploadPreparationInput {
+ fileName: string
+ contentType?: string
+ fileSize?: number
+ chunked?: boolean
+ skipDuplicateCheck?: boolean
+}
+export interface UploadPolicy {
+ prefix?: string
+ maxBytes: number
+ mimeWhitelistEnabled: boolean
+ mimeWhitelist: string[]
+ duplicateCheckEnabled: boolean
+ duplicateMode: 'warn' | 'block' | 'skip'
+}
+
+/** Carry only the declared duplicate summary for transport-specific warning rendering. */
+export class DuplicateUploadError extends CoreError {
+ readonly existingPhoto: DuplicatePhoto
+ constructor(photo: DuplicatePhoto) {
+ super(409, 'Duplicate upload blocked', 'upload.duplicate.block.title')
+ this.existingPhoto = photo
+ }
+}
+
+const imageExtensions = new Set([
+ '.avif',
+ '.bmp',
+ '.gif',
+ '.heic',
+ '.heif',
+ '.jpeg',
+ '.jpg',
+ '.png',
+ '.tif',
+ '.tiff',
+ '.webp',
+])
+const extension = (name: string) =>
+ name.slice(name.lastIndexOf('.')).toLowerCase()
+
+/** Enforce upload policy and duplicate decisions before creating provider upload sessions. */
+export function createUploadPreparer(deps: {
+ repository: UploadPreparationRepository
+ identifiers: PhotoIdentifiers
+ quota: UploadQuota
+ prepare(
+ owner: string,
+ key: string,
+ size: number | undefined,
+ contentType: string,
+ chunked: boolean,
+ ): Promise<UploadPlan>
+}) {
+ return async (
+ owner: string,
+ input: UploadPreparationInput,
+ policy: UploadPolicy,
+ ) => {
+ if (!input.fileName || typeof input.fileName !== 'string')
+ throw new CoreError(
+ 400,
+ 'File name is required',
+ 'upload.error.required.title',
+ )
+ const { fileName, fileSize, chunked, contentType } = input
+ if (chunked || fileSize !== undefined) {
+ if (!Number.isSafeInteger(fileSize) || fileSize! <= 0)
+ throw new CoreError(400, 'Invalid file size')
+ if (fileSize! > policy.maxBytes)
+ throw new CoreError(
+ 413,
+ 'File is too large',
+ 'upload.error.tooLarge.title',
+ )
+ if (
+ policy.mimeWhitelistEnabled &&
+ policy.mimeWhitelist.length &&
+ !policy.mimeWhitelist.includes(
+ contentType || 'application/octet-stream',
+ )
+ )
+ throw new CoreError(
+ 415,
+ 'Invalid content type',
+ 'upload.error.invalidType.title',
+ )
+ if (/[\\/]/.test(fileName) || fileName === '.' || fileName === '..')
+ throw new CoreError(400, 'Invalid file name')
+ }
+ await deps.quota.assertAllowed(owner, fileSize)
+ const fileKey = buildUploadObjectKey(policy.prefix, fileName)
+ let existingPhoto: DuplicatePhoto | null = null
+ if (policy.duplicateCheckEnabled && !input.skipDuplicateCheck) {
+ existingPhoto = await deps.repository.findDuplicate(
+ deps.identifiers.fromStorageKey(fileKey),
+ )
+ const video =
+ contentType?.toLowerCase().startsWith('video/') ||
+ ['.mov', '.mp4'].includes(extension(fileName))
+ if (
+ existingPhoto &&
+ video &&
+ existingPhoto.storageKey &&
+ imageExtensions.has(extension(existingPhoto.storageKey))
+ )
+ existingPhoto = null
+ if (existingPhoto && policy.duplicateMode === 'block')
+ throw new DuplicateUploadError(existingPhoto)
+ if (existingPhoto && policy.duplicateMode === 'skip')
+ return { skipped: true as const, existingPhoto, fileKey }
+ }
+ const upload = await deps.prepare(
+ owner,
+ fileKey,
+ fileSize,
+ contentType || 'application/octet-stream',
+ Boolean(chunked),
+ )
+ return { skipped: false as const, existingPhoto, fileKey, upload }
+ }
+}
+
+/** Preserve configured object-key prefixes without quadratic trailing-slash trimming. */
+export function buildUploadObjectKey(
+ prefix: string | undefined,
+ fileName: string,
+): string {
+ const value = prefix || ''
+ let end = value.length
+ while (end > 0 && value[end - 1] === '/') end--
+ return `${value.slice(0, end)}/${fileName}`
+}
+
+/** Reuse upload key and identifier rules for authenticated preflight checks. */
+export function createDuplicateChecker<T extends DuplicatePhoto>(deps: {
+ identifiers: PhotoIdentifiers
+ find(id: string): Promise<T | null>
+}) {
+ return async (
+ input: { fileNames?: string[]; storageKeys?: string[] },
+ prefix?: string,
+ ) => {
+ const results: Array<{
+ fileName?: string
+ storageKey: string
+ photoId: string
+ exists: boolean
+ photo: T | null
+ }> = []
+ for (const fileName of input.fileNames || []) {
+ const storageKey = buildUploadObjectKey(prefix, fileName)
+ const photoId = deps.identifiers.fromStorageKey(storageKey)
+ const photo = await deps.find(photoId)
+ results.push({
+ fileName,
+ storageKey,
+ photoId,
+ exists: Boolean(photo),
+ photo,
+ })
+ }
+ for (const storageKey of input.storageKeys || []) {
+ const photoId = deps.identifiers.fromStorageKey(storageKey)
+ const photo = await deps.find(photoId)
+ results.push({ storageKey, photoId, exists: Boolean(photo), photo })
+ }
+ return results
+ }
+}
diff --git a/packages/core/src/uploads.ts b/packages/core/src/uploads.ts
new file mode 100644
index 00000000..c5446bb2
--- /dev/null
+++ b/packages/core/src/uploads.ts
@@ -0,0 +1,121 @@
+import type { UploadPart } from '@chronoframe/contracts/upload'
+import { CoreError } from './errors.ts'
+
+export interface MultipartSession {
+ owner: string
+ key: string
+ busy: boolean
+ cancelled: boolean
+ completed: boolean
+ touched: number
+ setup: {
+ partUrls: readonly string[]
+ complete(parts: UploadPart[]): Promise<void>
+ }
+}
+export interface MultipartSessionRepository {
+ get(id: string): MultipartSession | undefined
+ abort(id: string): Promise<void>
+}
+
+/** Complete a user-owned multipart session once, reserving it before reading request data. */
+export function createMultipartCompleter(deps: {
+ sessions: MultipartSessionRepository
+ now(): number
+ event(
+ name: string,
+ details: Record<string, string | number | boolean | undefined>,
+ error?: unknown,
+ ): void
+}) {
+ return async (
+ id: string,
+ owner: string,
+ readParts: () => Promise<unknown>,
+ ) => {
+ const session = deps.sessions.get(id)
+ if (!session || session.owner !== owner)
+ throw new CoreError(404, 'Upload session not found')
+ if (session.cancelled) throw new CoreError(410, 'Upload cancelled')
+ if (session.busy) throw new CoreError(409, 'Upload is busy')
+ if (session.completed) {
+ deps.event('multipart.complete.repeated', {
+ sessionId: id,
+ key: session.key,
+ })
+ return { ok: true, key: session.key }
+ }
+ session.busy = true
+ session.touched = deps.now()
+ const startedAt = deps.now()
+ deps.event('multipart.complete.started', {
+ sessionId: id,
+ key: session.key,
+ partCount: session.setup.partUrls.length,
+ })
+ try {
+ const raw = await readParts()
+ if (
+ !Array.isArray(raw) ||
+ raw.length !== session.setup.partUrls.length ||
+ raw.some(
+ (part, index) =>
+ !part ||
+ part.partNumber !== index + 1 ||
+ typeof part.etag !== 'string' ||
+ !part.etag ||
+ part.etag.length > 256,
+ )
+ ) {
+ throw new CoreError(400, 'Invalid multipart completion data')
+ }
+ if (session.cancelled) throw new CoreError(410, 'Upload cancelled')
+ await session.setup.complete(raw)
+ session.completed = true
+ deps.event('multipart.complete.succeeded', {
+ sessionId: id,
+ key: session.key,
+ partCount: raw.length,
+ durationMs: deps.now() - startedAt,
+ })
+ return { ok: true, key: session.key }
+ } catch (error) {
+ deps.event(
+ 'multipart.complete.failed',
+ { sessionId: id, key: session.key, durationMs: deps.now() - startedAt },
+ error,
+ )
+ throw error
+ } finally {
+ session.busy = false
+ session.touched = deps.now()
+ if (session.cancelled) await deps.sessions.abort(id)
+ }
+ }
+}
+
+/** Validate Local chunk completeness before publishing through caller-owned file I/O. */
+export async function completeLocalUpload(input: {
+ completed: boolean
+ cancelled: boolean
+ key: string
+ size: number
+ partSize: number
+ receivedParts: number
+ fileSize(): Promise<number>
+ publish(): Promise<void>
+ cleanup(): Promise<void>
+ markCompleted(): void
+}) {
+ if (input.cancelled) throw new CoreError(410, 'Upload cancelled')
+ if (input.completed) return { ok: true, key: input.key }
+ if (
+ input.receivedParts !== Math.ceil(input.size / input.partSize) ||
+ (await input.fileSize()) !== input.size
+ )
+ throw new CoreError(400, 'Upload is incomplete')
+ await input.publish()
+ input.markCompleted()
+ await input.cleanup().catch(() => {})
+ return { ok: true, key: input.key }
+}
diff --git a/server/api/albums/[albumId]/index.delete.ts b/server/api/albums/[albumId]/index.delete.ts
index ab105a02..99657f46 100644
--- a/server/api/albums/[albumId]/index.delete.ts
+++ b/server/api/albums/[albumId]/index.delete.ts
@@ -1,9 +1,12 @@
-import { z } from 'zod'
import { requireAdminSession } from '../../../utils/require-admin.ts'
+import { z } from 'zod'
+import {
+ useAlbumWriter,
+ mutationResponse,
+} from '../../../utils/resource-writer'
export default eventHandler(async (event) => {
await requireAdminSession(event)
-
const { albumId } = await getValidatedRouterParams(
event,
z.object({
@@ -14,32 +17,7 @@ export default eventHandler(async (event) => {
}).parse,
)
- const db = useDB()
-
- // 检查相簌是否存在
- const album = await db
- .select()
- .from(tables.albums)
- .where(eq(tables.albums.id, albumId))
- .get()
-
- if (!album) {
- throw createError({
- statusCode: 404,
- statusMessage: 'Album not found',
- })
- }
-
- // 使用事务删除相簌及其关联的照片关系
- db.transaction((tx) => {
- // 删除相簌-照片关系
- tx.delete(tables.albumPhotos)
- .where(eq(tables.albumPhotos.albumId, albumId))
- .run()
-
- // 删除相簌
- tx.delete(tables.albums).where(eq(tables.albums.id, albumId)).run()
- })
-
- return { success: true }
+ return mutationResponse(() =>
+ useAlbumWriter().delete(albumId, { authenticated: true }),
+ )
})
diff --git a/server/api/albums/[albumId]/index.put.ts b/server/api/albums/[albumId]/index.put.ts
index 82e08e61..52ed29c5 100644
--- a/server/api/albums/[albumId]/index.put.ts
+++ b/server/api/albums/[albumId]/index.put.ts
@@ -1,16 +1,16 @@
-import { toAlbumDto } from '../../../utils/dto'
+import { requireAdminSession } from '../../../utils/require-admin.ts'
import { z } from 'zod'
import {
ALBUM_PASSWORD_MAX_LENGTH,
ALBUM_PASSWORD_MIN_LENGTH,
} from '~~/shared/utils/album'
-import { hashAlbumPassword } from '../../../utils/album-access'
-import { appendAlbumPhotos } from '../../../utils/album-membership.ts'
-import { requireAdminSession } from '../../../utils/require-admin.ts'
+import {
+ useAlbumWriter,
+ mutationResponse,
+} from '../../../utils/resource-writer'
export default eventHandler(async (event) => {
await requireAdminSession(event)
-
const { albumId } = await getValidatedRouterParams(
event,
z.object({
@@ -41,87 +41,7 @@ export default eventHandler(async (event) => {
}).parse,
)
- const db = useDB()
-
- // 检查相簿是否存在
- const album = await db
- .select()
- .from(tables.albums)
- .where(eq(tables.albums.id, albumId))
- .get()
-
- if (!album) {
- throw createError({
- statusCode: 404,
- statusMessage: 'Album not found',
- })
- }
-
- const passwordHash =
- body.password !== undefined
- ? body.password
- ? await hashAlbumPassword(body.password)
- : null
- : undefined
-
- // 使用事务更新相簿
- const updatedAlbum = db.transaction((tx) => {
- // 更新基本信息
- const updateData: Record<string, any> = {
- updatedAt: new Date(),
- }
-
- if (body.title !== undefined) {
- updateData.title = body.title
- }
-
- if (body.description !== undefined) {
- updateData.description = body.description || null
- }
-
- if (body.coverPhotoId !== undefined) {
- updateData.coverPhotoId = body.coverPhotoId || null
- }
- if (body.isHidden !== undefined) {
- updateData.isHidden = body.isHidden
- }
- if (passwordHash !== undefined) {
- updateData.passwordHash = passwordHash
- }
-
- tx.update(tables.albums)
- .set(updateData)
- .where(eq(tables.albums.id, albumId))
- .run()
-
- // 如果提供了新的照片列表,替换现有照片
- if (body.photoIds !== undefined) {
- // 删除现有的相簌-照片关系
- tx.delete(tables.albumPhotos)
- .where(eq(tables.albumPhotos.albumId, albumId))
- .run()
-
- // 添加新的相簌-照片关系
- const photoIds = new Set(body.photoIds)
-
- // 确保 coverPhotoId 在列表中
- if (body.coverPhotoId) {
- photoIds.add(body.coverPhotoId)
- }
-
- if (photoIds.size > 0) {
- appendAlbumPhotos(tx, albumId, [...photoIds])
- }
- }
-
- return tx
- .select()
- .from(tables.albums)
- .where(eq(tables.albums.id, albumId))
- .get()
- })
-
- if (!updatedAlbum)
- throw createError({ statusCode: 404, statusMessage: 'Album not found' })
- return toAlbumDto(updatedAlbum)
+ return mutationResponse(() =>
+ useAlbumWriter().update(albumId, body, { authenticated: true }),
+ )
})
diff --git a/server/api/albums/[albumId]/photos/[photoId].delete.ts b/server/api/albums/[albumId]/photos/[photoId].delete.ts
index f1269d6b..b33152c2 100644
--- a/server/api/albums/[albumId]/photos/[photoId].delete.ts
+++ b/server/api/albums/[albumId]/photos/[photoId].delete.ts
@@ -1,10 +1,12 @@
-import { z } from 'zod'
-import { and } from 'drizzle-orm'
import { requireAdminSession } from '../../../../utils/require-admin.ts'
+import { z } from 'zod'
+import {
+ useAlbumWriter,
+ mutationResponse,
+} from '../../../../utils/resource-writer'
export default eventHandler(async (event) => {
await requireAdminSession(event)
-
const { albumId } = await getValidatedRouterParams(
event,
z.object({
@@ -22,53 +24,7 @@ export default eventHandler(async (event) => {
}).parse,
)
- const db = useDB()
-
- // 检查相簌-照片关系是否存在
- const relation = await db
- .select()
- .from(tables.albumPhotos)
- .where(
- and(
- eq(tables.albumPhotos.albumId, albumId),
- eq(tables.albumPhotos.photoId, photoId),
- ),
- )
- .get()
-
- if (!relation) {
- throw createError({
- statusCode: 404,
- statusMessage: 'Photo not found in album',
- })
- }
-
- // 使用事务删除照片关系,如果该照片是封面则更新为 null
- db.transaction((tx) => {
- // 删除相簌-照片关系
- tx.delete(tables.albumPhotos)
- .where(
- and(
- eq(tables.albumPhotos.albumId, albumId),
- eq(tables.albumPhotos.photoId, photoId),
- ),
- )
- .run()
-
- // 如果该照片是封面,清除封面
- const album = tx
- .select()
- .from(tables.albums)
- .where(eq(tables.albums.id, albumId))
- .get()
-
- if (album && album.coverPhotoId === photoId) {
- tx.update(tables.albums)
- .set({ coverPhotoId: null, updatedAt: new Date() })
- .where(eq(tables.albums.id, albumId))
- .run()
- }
- })
-
- return { success: true }
+ return mutationResponse(() =>
+ useAlbumWriter().removePhoto(albumId, photoId, { authenticated: true }),
+ )
})
diff --git a/server/api/albums/index.post.ts b/server/api/albums/index.post.ts
index c03096b1..83a24cb6 100644
--- a/server/api/albums/index.post.ts
+++ b/server/api/albums/index.post.ts
@@ -1,17 +1,13 @@
-import { toAlbumDto } from '../../utils/dto'
-import { min } from 'drizzle-orm'
+import { requireAdminSession } from '../../utils/require-admin.ts'
import z from 'zod'
import {
ALBUM_PASSWORD_MAX_LENGTH,
ALBUM_PASSWORD_MIN_LENGTH,
} from '~~/shared/utils/album'
-import { hashAlbumPassword } from '../../utils/album-access'
-import { appendAlbumPhotos } from '../../utils/album-membership.ts'
-import { requireAdminSession } from '../../utils/require-admin.ts'
+import { useAlbumWriter, mutationResponse } from '../../utils/resource-writer'
export default eventHandler(async (event) => {
await requireAdminSession(event)
-
const body = await readValidatedBody(
event,
z.object({
@@ -28,47 +24,7 @@ export default eventHandler(async (event) => {
}).parse,
)
- const db = useDB()
-
- const passwordHash = body.password
- ? await hashAlbumPassword(body.password)
- : null
-
- const album = db.transaction((tx) => {
- // Place new album first (min position minus one gap), preserving the
- // default "newest first" order
- const minRow = tx
- .select({ min: min(tables.albums.position) })
- .from(tables.albums)
- .get()
- const position = (minRow?.min ?? 1000) - 1000
-
- const newAlbum = tx
- .insert(tables.albums)
- .values({
- title: body.title,
- description: body.description || null,
- coverPhotoId: body.coverPhotoId || null,
- isHidden: body.isHidden || false,
- passwordHash,
- position,
- })
- .returning()
- .get()
-
- const albumId = newAlbum.id
- const photoIds = new Set(body.photoIds || [])
-
- if (body.coverPhotoId) {
- photoIds.add(body.coverPhotoId)
- }
-
- if (photoIds.size > 0) {
- appendAlbumPhotos(tx, albumId, [...photoIds])
- }
-
- return toAlbumDto(newAlbum)
- })
-
- return album
+ return mutationResponse(() =>
+ useAlbumWriter().create(body, { authenticated: true }),
+ )
})
diff --git a/server/api/albums/reorder.put.ts b/server/api/albums/reorder.put.ts
index 91281fe5..a62bd8d0 100644
--- a/server/api/albums/reorder.put.ts
+++ b/server/api/albums/reorder.put.ts
@@ -1,9 +1,9 @@
-import z from 'zod'
import { requireAdminSession } from '../../utils/require-admin.ts'
+import { z } from 'zod'
+import { useAlbumWriter, mutationResponse } from '../../utils/resource-writer'
export default eventHandler(async (event) => {
await requireAdminSession(event)
-
const { albumIds } = await readValidatedBody(
event,
z.object({
@@ -11,17 +11,7 @@ export default eventHandler(async (event) => {
}).parse,
)
- const db = useDB()
-
- // Reassign position by incoming order (gap of 1000 to ease future inserts)
- db.transaction((tx) => {
- albumIds.forEach((id, index) => {
- tx.update(tables.albums)
- .set({ position: index * 1000 })
- .where(eq(tables.albums.id, id))
- .run()
- })
- })
-
- return { success: true }
+ return mutationResponse(() =>
+ useAlbumWriter().reorder(albumIds, { authenticated: true }),
+ )
})
diff --git a/server/api/photos/[photoId]/index.delete.ts b/server/api/photos/[photoId]/index.delete.ts
index c4859d42..a13660c1 100644
--- a/server/api/photos/[photoId]/index.delete.ts
+++ b/server/api/photos/[photoId]/index.delete.ts
@@ -1,75 +1,17 @@
-const HEIC_EXTENSIONS = ['.heic', '.heif', '.hif']
+import {
+ usePhotoWriter,
+ mutationResponse,
+} from '../../../utils/resource-writer'
export default eventHandler(async (event) => {
await requireUserSession(event)
- const { storageProvider } = useStorageProvider(event)
const photoId = getRouterParam(event, 'photoId')
-
- if (!photoId) {
- return createError({
+ if (!photoId)
+ throw createError({
statusCode: 400,
statusMessage: 'Photo ID is required',
})
- }
-
- const photo = await useDB()
- .select()
- .from(tables.photos)
- .where(eq(tables.photos.id, photoId))
- .get()
-
- if (!photo) {
- return createError({
- statusCode: 404,
- statusMessage: 'Photo not found',
- })
- }
-
- logger.image.info(`Deleting photo ${photo.title || photo.id || photoId}`)
-
- if (photo.storageKey) {
- logger.image.info(`Deleting photo files for ${photoId} from storage`)
- try {
- await storageProvider.delete(photo.storageKey)
- const lowerStorageKey = photo.storageKey.toLowerCase()
- const heicExtension = HEIC_EXTENSIONS.find((ext) =>
- lowerStorageKey.endsWith(ext),
- )
- if (heicExtension) {
- const jpegKey =
- photo.storageKey.slice(
- 0,
- photo.storageKey.length - heicExtension.length,
- ) + '.jpeg'
-
- if (jpegKey !== photo.storageKey) {
- logger.image.info(
- `Deleting converted JPEG for HEIC photo ${photoId}: ${jpegKey}`,
- )
- try {
- await storageProvider.delete(jpegKey)
- } catch {
- // ignore error when deleting converted JPEG
- }
- }
- }
- if (photo.thumbnailKey) {
- await storageProvider.delete(photo.thumbnailKey)
- }
- if (photo.livePhotoVideoKey) {
- await storageProvider.delete(photo.livePhotoVideoKey)
- }
- } catch {
- // ignore error
- }
- }
-
- useDB().delete(tables.photos).where(eq(tables.photos.id, photoId)).run()
-
- logger.image.success(`Photo ${photoId} deleted`)
-
- return {
- statusCode: 200,
- statusMessage: 'Photo deleted successfully',
- }
+ return mutationResponse(() =>
+ usePhotoWriter(event).delete(photoId, { authenticated: true }),
+ )
})
diff --git a/server/api/photos/[photoId]/index.put.ts b/server/api/photos/[photoId]/index.put.ts
index 9a30aafb..d17eec15 100644
--- a/server/api/photos/[photoId]/index.put.ts
+++ b/server/api/photos/[photoId]/index.put.ts
@@ -1,16 +1,9 @@
-import type {} from '../../../types/worker'
-import { toPhotoDto } from '../../../utils/dto'
-import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import path from 'node:path'
import { z } from 'zod'
-import { exiftool } from 'exiftool-vendored'
-import { eq } from 'drizzle-orm'
import { hasValidCoordinates } from '../../../../shared/utils/location'
-
-import { extractExifData } from '~~/server/services/image/exif'
-import { tables, useDB } from '~~/server/utils/db'
-import { useStorageProvider } from '~~/server/utils/useStorageProvider'
+import {
+ usePhotoWriter,
+ mutationResponse,
+} from '../../../utils/resource-writer'
const paramsSchema = z.object({
photoId: z.string().min(1),
@@ -39,246 +32,14 @@ const bodySchema = z.object({
rating: z.union([z.number().int().min(0).max(5), z.null()]).optional(),
})
-const normalizeTags = (tags: string[] | undefined) => {
- if (!tags) return undefined
- const seen = new Set<string>()
- const normalized: string[] = []
- for (const rawTag of tags) {
- const trimmed = rawTag.trim()
- if (!trimmed) continue
- const key = trimmed.toLowerCase()
- if (seen.has(key)) continue
- seen.add(key)
- normalized.push(trimmed)
- }
- return normalized
-}
-
export default eventHandler(async (event) => {
await requireUserSession(event)
-
const t = await useTranslation(event)
const { photoId } = paramsSchema.parse(event.context.params ?? {})
const payload = bodySchema.parse(await readBody(event))
-
- if (
- payload.title === undefined &&
- payload.description === undefined &&
- payload.tags === undefined &&
- payload.location === undefined &&
- payload.rating === undefined
- ) {
- throw createError({
- statusCode: 400,
- statusMessage: t('dashboard.photos.messages.noChangesProvided'),
- })
- }
-
- const db = useDB()
- const photo = await db
- .select()
- .from(tables.photos)
- .where(eq(tables.photos.id, photoId))
- .get()
-
- if (!photo) {
- throw createError({
- statusCode: 404,
- statusMessage: t('dashboard.photos.messages.photoNotFound'),
- })
- }
-
- if (!photo.storageKey) {
- throw createError({
- statusCode: 400,
- statusMessage: t('dashboard.photos.messages.noStorageKey'),
- })
- }
-
- const { storageProvider } = useStorageProvider(event)
- const originalBuffer = await storageProvider.get(photo.storageKey)
-
- if (!originalBuffer) {
- throw createError({
- statusCode: 404,
- statusMessage: t('dashboard.photos.messages.photoFileMissing'),
- })
- }
-
- const normalizedTitle =
- payload.title !== undefined ? payload.title.trim() : undefined
- const normalizedDescription =
- payload.description !== undefined ? payload.description.trim() : undefined
- const normalizedTags = normalizeTags(payload.tags)
- let pendingReverseGeocode: {
- latitude: number
- longitude: number
- } | null = null
-
- const exifUpdates: Record<string, any> = {}
-
- if (normalizedTitle !== undefined) {
- const titleValue = normalizedTitle.length > 0 ? normalizedTitle : null
- exifUpdates.Title = titleValue
- exifUpdates.XPTitle = titleValue
- }
-
- if (normalizedDescription !== undefined) {
- const descriptionValue =
- normalizedDescription.length > 0 ? normalizedDescription : null
- exifUpdates.Description = descriptionValue
- exifUpdates.ImageDescription = descriptionValue
- exifUpdates.CaptionAbstract = descriptionValue
- exifUpdates.XPComment = descriptionValue
- exifUpdates.UserComment = descriptionValue
- }
-
- if (normalizedTags !== undefined) {
- const tagsValue = normalizedTags.length > 0 ? normalizedTags : null
- exifUpdates.Subject = tagsValue
- exifUpdates.Keywords = tagsValue
- exifUpdates.XPKeywords =
- normalizedTags.length > 0 ? normalizedTags.join('; ') : null
- }
-
- if (payload.location !== undefined) {
- if (payload.location) {
- const { latitude, longitude } = payload.location
- const latAbs = Math.abs(latitude)
- const lonAbs = Math.abs(longitude)
- exifUpdates.GPSLatitude = latAbs
- exifUpdates.GPSLatitudeRef = latitude >= 0 ? 'N' : 'S'
- exifUpdates.GPSLongitude = lonAbs
- exifUpdates.GPSLongitudeRef = longitude >= 0 ? 'E' : 'W'
- exifUpdates.GPSPosition = `${latitude} ${longitude}`
- } else {
- exifUpdates.GPSLatitude = null
- exifUpdates.GPSLatitudeRef = null
- exifUpdates.GPSLongitude = null
- exifUpdates.GPSLongitudeRef = null
- exifUpdates.GPSPosition = null
- }
- }
-
- if (payload.rating !== undefined) {
- exifUpdates.Rating = payload.rating !== null ? payload.rating : null
- }
-
- const tempRoot = tmpdir()
- await mkdir(tempRoot, { recursive: true })
- const tempDir = await mkdtemp(path.join(tempRoot, 'cframe-edit-'))
- const ext = path.extname(photo.storageKey) || '.jpg'
- const tempFile = path.join(tempDir, `edited${ext}`)
-
- try {
- await writeFile(tempFile, originalBuffer)
-
- if (Object.keys(exifUpdates).length > 0) {
- await exiftool.write(tempFile, exifUpdates, ['-overwrite_original'])
- }
-
- const updatedBuffer = await readFile(tempFile)
- const prefix =
- storageProvider.config && 'prefix' in storageProvider.config
- ? storageProvider.config.prefix
- : ''
- await storageProvider.create(
- photo.storageKey.replace(prefix || '', ''),
- updatedBuffer,
- )
-
- const exifData = await extractExifData(updatedBuffer)
-
- const updateData: Record<string, any> = {
- exif: exifData,
- fileSize: updatedBuffer.length,
- lastModified: new Date().toISOString(),
- }
-
- if (normalizedTitle !== undefined) {
- updateData.title = normalizedTitle || null
- }
-
- if (normalizedDescription !== undefined) {
- updateData.description = normalizedDescription || null
- }
-
- if (normalizedTags !== undefined) {
- updateData.tags = normalizedTags
- }
-
- if (payload.location !== undefined) {
- if (payload.location) {
- updateData.latitude = payload.location.latitude
- updateData.longitude = payload.location.longitude
- updateData.country = null
- updateData.city = null
- updateData.locationName = null
- updateData.geocoding = null
- pendingReverseGeocode = {
- latitude: payload.location.latitude,
- longitude: payload.location.longitude,
- }
- } else {
- updateData.latitude = null
- updateData.longitude = null
- updateData.country = null
- updateData.city = null
- updateData.locationName = null
- updateData.geocoding = null
- }
- }
-
- await db
- .update(tables.photos)
- .set(updateData)
- .where(eq(tables.photos.id, photoId))
-
- const updatedPhoto = await db
- .select()
- .from(tables.photos)
- .where(eq(tables.photos.id, photoId))
- .get()
-
- if (pendingReverseGeocode) {
- const workerPool = globalThis.__workerPool
- if (workerPool) {
- try {
- await workerPool.addTask(
- {
- type: 'photo-reverse-geocoding',
- photoId,
- latitude: pendingReverseGeocode.latitude,
- longitude: pendingReverseGeocode.longitude,
- },
- {
- priority: 1,
- },
- )
- } catch (taskError) {
- logger.location.warn(
- `Failed to enqueue reverse geocoding for photo ${photoId}:`,
- taskError,
- )
- }
- } else {
- logger.location.warn(
- `Worker pool not initialized, skipping reverse geocoding enqueue for photo ${photoId}`,
- )
- }
- }
-
- return {
- success: true,
- photo: updatedPhoto ? toPhotoDto(updatedPhoto) : undefined,
- }
- } catch (error) {
- logger.image.error('Failed to update photo metadata', error)
- throw createError({
- statusCode: 500,
- statusMessage: t('dashboard.photos.messages.metadataUpdateFailed'),
- })
- } finally {
- await rm(tempDir, { recursive: true, force: true })
- }
+ return mutationResponse(
+ () =>
+ usePhotoWriter(event).update(photoId, payload, { authenticated: true }),
+ (key) => t(key),
+ )
})
diff --git a/server/api/photos/check-duplicate.post.ts b/server/api/photos/check-duplicate.post.ts
index 16e4d6da..9d28cf6d 100644
--- a/server/api/photos/check-duplicate.post.ts
+++ b/server/api/photos/check-duplicate.post.ts
@@ -1,5 +1,8 @@
import { z } from 'zod'
-import { eq } from 'drizzle-orm'
+import { createDuplicateChecker } from '@chronoframe/core'
+import { createSqliteUploadRepository } from '../../repositories/sqlite-uploads'
+import { useDB } from '../../utils/db'
+import { useStorageProvider } from '../../utils/useStorageProvider'
import { generateSafePhotoId } from '~~/server/utils/file-utils'
/**
@@ -33,73 +36,16 @@ export default defineEventHandler(async (event) => {
})
}
- const db = useDB()
- const results = []
-
- // 检查文件名
- if (fileNames && fileNames.length > 0) {
- for (const fileName of fileNames) {
- // 生成 photoId(与上传时的逻辑相同)
- const { storageProvider } = useStorageProvider(event)
- const storageKey = `${(storageProvider.config?.prefix || '').replace(/\/+$/, '')}/${fileName}`
- const photoId = generateSafePhotoId(storageKey)
-
- // 查询数据库
- const existingPhoto = await db
- .select({
- id: tables.photos.id,
- title: tables.photos.title,
- storageKey: tables.photos.storageKey,
- originalUrl: tables.photos.originalUrl,
- thumbnailUrl: tables.photos.thumbnailUrl,
- dateTaken: tables.photos.dateTaken,
- fileSize: tables.photos.fileSize,
- width: tables.photos.width,
- height: tables.photos.height,
- })
- .from(tables.photos)
- .where(eq(tables.photos.id, photoId))
- .get()
-
- results.push({
- fileName,
- storageKey,
- photoId,
- exists: !!existingPhoto,
- photo: existingPhoto || null,
- })
- }
- }
-
- // 检查 storageKey
- if (storageKeys && storageKeys.length > 0) {
- for (const storageKey of storageKeys) {
- const photoId = generateSafePhotoId(storageKey)
-
- const existingPhoto = await db
- .select({
- id: tables.photos.id,
- title: tables.photos.title,
- storageKey: tables.photos.storageKey,
- originalUrl: tables.photos.originalUrl,
- thumbnailUrl: tables.photos.thumbnailUrl,
- dateTaken: tables.photos.dateTaken,
- fileSize: tables.photos.fileSize,
- width: tables.photos.width,
- height: tables.photos.height,
- })
- .from(tables.photos)
- .where(eq(tables.photos.id, photoId))
- .get()
-
- results.push({
- storageKey,
- photoId,
- exists: !!existingPhoto,
- photo: existingPhoto || null,
- })
- }
- }
+ const { storageProvider } = useStorageProvider(event)
+ const config = storageProvider.config
+ const check = createDuplicateChecker({
+ identifiers: { fromStorageKey: generateSafePhotoId },
+ find: createSqliteUploadRepository(useDB()).findDetails,
+ })
+ const results = await check(
+ { fileNames, storageKeys },
+ config && 'prefix' in config ? config.prefix : '',
+ )
const duplicatesFound = results.filter((r) => r.exists).length
diff --git a/server/api/photos/chunks/[id].ts b/server/api/photos/chunks/[id].ts
index 9ba70da0..80501ac3 100644
--- a/server/api/photos/chunks/[id].ts
+++ b/server/api/photos/chunks/[id].ts
@@ -1,3 +1,5 @@
+import { completeLocalUpload } from '@chronoframe/core'
+import { mutationResponse } from '../../../utils/resource-writer'
import { open, stat, rm } from 'node:fs/promises'
import { UPLOAD_CHUNK_SIZE } from '../../../../shared/utils/upload'
import { logUpload } from '../../../utils/upload-log'
@@ -47,28 +49,31 @@ export default eventHandler(async (event) => {
receivedParts: upload.hashes.size,
size: upload.size,
})
- if (
- upload.hashes.size !== Math.ceil(upload.size / UPLOAD_CHUNK_SIZE) ||
- (await stat(upload.filePath)).size !== upload.size
- ) {
- throw createError({
- statusCode: 400,
- statusMessage: 'Upload is incomplete',
- })
- }
- await upload.provider.createFromFile(
- upload.key,
- upload.filePath,
- upload.contentType,
+ await mutationResponse(() =>
+ completeLocalUpload({
+ completed: upload.completed,
+ cancelled: upload.cancelled,
+ key: upload.key,
+ size: upload.size,
+ partSize: UPLOAD_CHUNK_SIZE,
+ receivedParts: upload.hashes.size,
+ fileSize: async () => (await stat(upload.filePath)).size,
+ publish: () =>
+ upload.provider
+ .createFromFile(upload.key, upload.filePath, upload.contentType)
+ .then(() => {}),
+ markCompleted: () => {
+ upload.completed = true
+ },
+ cleanup: () => rm(upload.filePath, { force: true }),
+ }),
)
- upload.completed = true
logUpload('local.complete.succeeded', {
sessionId: id,
key: upload.key,
size: upload.size,
durationMs: Date.now() - startedAt,
})
- await rm(upload.filePath, { force: true }).catch(() => {})
return { ok: true, key: upload.key }
}
if (event.method !== 'PUT') throw createError({ statusCode: 405 })
diff --git a/server/api/photos/index.post.ts b/server/api/photos/index.post.ts
index 71d8db3f..a09efa8e 100644
--- a/server/api/photos/index.post.ts
+++ b/server/api/photos/index.post.ts
@@ -1,220 +1,127 @@
-import path from 'path'
-import { useStorageProvider } from '~~/server/utils/useStorageProvider'
-import { eq } from 'drizzle-orm'
-import { generateSafePhotoId } from '~~/server/utils/file-utils'
-import { settingsManager } from '~~/server/services/settings/settingsManager'
-import { prepareUpload } from '~~/server/utils/direct-upload'
-
-const VIDEO_EXTENSIONS = new Set(['.mov', '.mp4'])
-
-const IMAGE_EXTENSIONS = new Set([
- '.avif',
- '.bmp',
- '.gif',
- '.heic',
- '.heif',
- '.jpeg',
- '.jpg',
- '.png',
- '.tif',
- '.tiff',
- '.webp',
-])
-
-const isVideoFile = (
- fileName: string,
- contentType?: string | null,
-): boolean => {
- if (contentType?.toLowerCase().startsWith('video/')) {
- return true
- }
-
- const ext = path.extname(fileName).toLowerCase()
- return ext !== '' && VIDEO_EXTENSIONS.has(ext)
-}
-
-const isLikelyImageKey = (storageKey?: string | null): boolean => {
- if (!storageKey) {
- return false
- }
-
- const ext = path.extname(storageKey).toLowerCase()
- return ext !== '' && IMAGE_EXTENSIONS.has(ext)
-}
-
-export default eventHandler(async (event) => {
- const session = await requireUserSession(event)
- const { storageProvider } = useStorageProvider(event)
- const t = await useTranslation(event)
-
- const body = await readBody(event)
- const { fileName, contentType, skipDuplicateCheck, fileSize, chunked } = body
- const isVideoUpload = fileName ? isVideoFile(fileName, contentType) : false
-
- if (!fileName) {
- throw createError({
- statusCode: 400,
- statusMessage: t('upload.error.required.title'),
- })
- }
-
- if (chunked || fileSize !== undefined) {
- const maxMB =
- (await settingsManager.get<number>('system', 'upload.maxFileSize')) ?? 256
- if (!Number.isSafeInteger(fileSize) || fileSize <= 0)
- throw createError({ statusCode: 400, statusMessage: 'Invalid file size' })
- if (fileSize > maxMB * 1024 * 1024)
- throw createError({
- statusCode: 413,
- statusMessage: t('upload.error.tooLarge.title'),
- })
- const mime = useRuntimeConfig(event).upload.mime
- const allowed = mime.whitelist
- .split(',')
- .map((type: string) => type.trim())
- .filter(Boolean)
- if (
- mime.whitelistEnabled &&
- allowed.length &&
- !allowed.includes(contentType || 'application/octet-stream')
- ) {
- throw createError({
- statusCode: 415,
- statusMessage: t('upload.error.invalidType.title'),
- })
- }
- if (
- typeof fileName !== 'string' ||
- /[\\/]/.test(fileName) ||
- fileName === '.' ||
- fileName === '..'
- ) {
- throw createError({ statusCode: 400, statusMessage: 'Invalid file name' })
- }
- }
-
- try {
+import type {
+ UploadPreparationResponse,
+ PreparedUploadResponse,
+} from '@chronoframe/contracts/upload'
+import {
+ createUploadPreparer,
+ DuplicateUploadError,
+ CoreError,
+} from '@chronoframe/core'
+import { useStorageProvider } from '../../utils/useStorageProvider'
+import { generateSafePhotoId } from '../../utils/file-utils'
+import { settingsManager } from '../../services/settings/settingsManager'
+import { prepareUpload } from '../../utils/direct-upload'
+import { useDB } from '../../utils/db'
+import { createSqliteUploadRepository } from '../../repositories/sqlite-uploads'
+
+export default eventHandler(
+ async (event): Promise<UploadPreparationResponse> => {
+ const session = await requireUserSession(event)
+ const { storageProvider } = useStorageProvider(event)
+ const t = await useTranslation(event)
+ const body = (await readBody(event)) || {}
const providerConfig = storageProvider.config
- const prefix =
- providerConfig && 'prefix' in providerConfig ? providerConfig.prefix : ''
- const objectKey = `${(prefix || '').replace(/\/+$/, '')}/${fileName}`
-
- // 重复文件检测
- const duplicateCheckEnabled =
- ((await settingsManager.get<boolean>(
- 'system',
- 'upload.duplicateCheck.enabled',
- )) ??
- true) &&
- !skipDuplicateCheck
- let existingPhoto = null
-
- if (duplicateCheckEnabled) {
- const photoId = generateSafePhotoId(objectKey)
- const db = useDB()
-
- existingPhoto = await db
- .select({
- id: tables.photos.id,
- title: tables.photos.title,
- storageKey: tables.photos.storageKey,
- originalUrl: tables.photos.originalUrl,
- thumbnailUrl: tables.photos.thumbnailUrl,
- dateTaken: tables.photos.dateTaken,
- })
- .from(tables.photos)
- .where(eq(tables.photos.id, photoId))
- .get()
-
- if (
- existingPhoto &&
- isVideoUpload &&
- isLikelyImageKey(existingPhoto.storageKey)
- ) {
- existingPhoto = null
- }
-
- if (existingPhoto) {
- const checkMode =
+ const mime = useRuntimeConfig(event).upload.mime
+ const preparer = createUploadPreparer({
+ repository: createSqliteUploadRepository(useDB()),
+ identifiers: { fromStorageKey: generateSafePhotoId },
+ // Self-hosted has no account-wide quota; the per-file policy still applies.
+ quota: { assertAllowed: async () => {} },
+ prepare: (owner, key, size, contentType, chunked) =>
+ prepareUpload(owner, key, size, contentType, storageProvider, chunked),
+ })
+ try {
+ const result = await preparer(String(session.user.id), body, {
+ prefix:
+ providerConfig && 'prefix' in providerConfig
+ ? providerConfig.prefix
+ : '',
+ maxBytes:
+ ((await settingsManager.get<number>(
+ 'system',
+ 'upload.maxFileSize',
+ )) ?? 256) *
+ 1024 *
+ 1024,
+ mimeWhitelistEnabled: mime.whitelistEnabled,
+ mimeWhitelist: mime.whitelist
+ .split(',')
+ .map((type: string) => type.trim())
+ .filter(Boolean),
+ duplicateCheckEnabled:
+ (await settingsManager.get<boolean>(
+ 'system',
+ 'upload.duplicateCheck.enabled',
+ )) ?? true,
+ duplicateMode:
(await settingsManager.get<'warn' | 'block' | 'skip'>(
'system',
'upload.duplicateCheck.mode',
- )) ?? 'skip'
-
- if (checkMode === 'block') {
- // 阻止模式:直接拒绝上传
- throw createError({
- statusCode: 409,
- statusMessage: t('upload.duplicate.block.title'),
- data: {
- duplicate: true,
- existingPhoto,
- title: t('upload.duplicate.block.title'),
- message: t('upload.duplicate.block.message', { fileName }),
- },
- })
- } else if (checkMode === 'skip') {
- // 跳过模式:返回现有照片信息,不上传
- return {
- skipped: true,
- duplicate: true,
- existingPhoto,
- fileKey: objectKey,
- title: t('upload.duplicate.skip.title'),
- message: t('upload.duplicate.skip.message', { fileName }),
- info: t('upload.duplicate.skip.info', {
- dateTaken:
- existingPhoto.dateTaken || t('common.unknown', 'unknown date'),
- }),
- }
+ )) ?? 'skip',
+ })
+ const fileName = body.fileName
+ if (result.skipped) {
+ return {
+ skipped: true,
+ duplicate: true,
+ existingPhoto: result.existingPhoto,
+ fileKey: result.fileKey,
+ title: t('upload.duplicate.skip.title'),
+ message: t('upload.duplicate.skip.message', { fileName }),
+ info: t('upload.duplicate.skip.info', {
+ dateTaken:
+ result.existingPhoto.dateTaken ||
+ t('common.unknown', 'unknown date'),
+ }),
}
- // 'warn' 模式:继续上传但返回警告信息
}
- }
-
- // Let the provider choose direct upload before considering a local receiver.
- {
- const upload = await prepareUpload(
- String(session.user.id),
- objectKey,
- fileSize,
- contentType || 'application/octet-stream',
- storageProvider,
- Boolean(chunked),
- )
-
- const response: any = {
- signedUrl: upload.url,
- upload,
- fileKey: objectKey,
+ const response: PreparedUploadResponse = {
+ signedUrl: result.upload.url,
+ upload: result.upload,
+ fileKey: result.fileKey,
expiresIn: 3600,
}
-
- if (existingPhoto) {
+ if (result.existingPhoto) {
response.duplicate = true
- response.existingPhoto = existingPhoto
+ response.existingPhoto = result.existingPhoto
response.warningInfo = {
title: t('upload.duplicate.warn.title'),
message: t('upload.duplicate.warn.message', { fileName }),
warning: t('upload.duplicate.warn.warning'),
info: t('upload.duplicate.warn.info', {
- title: existingPhoto.title || fileName,
+ title: result.existingPhoto.title || fileName,
dateTaken:
- existingPhoto.dateTaken || t('common.unknown', 'unknown date'),
+ result.existingPhoto.dateTaken ||
+ t('common.unknown', 'unknown date'),
}),
}
}
-
return response
+ } catch (error) {
+ if (error instanceof DuplicateUploadError)
+ throw createError({
+ statusCode: 409,
+ statusMessage: t('upload.duplicate.block.title'),
+ data: {
+ duplicate: true,
+ existingPhoto: error.existingPhoto,
+ title: t('upload.duplicate.block.title'),
+ message: t('upload.duplicate.block.message', {
+ fileName: body.fileName,
+ }),
+ },
+ })
+ if (error instanceof CoreError)
+ throw createError({
+ statusCode: error.statusCode,
+ statusMessage: error.code ? t(error.code) : error.message,
+ })
+ if ((error as { statusCode?: number }).statusCode) throw error
+ logger.chrono.error('Failed to prepare upload:', error)
+ throw createError({
+ statusCode: 500,
+ statusMessage: 'Failed to prepare upload',
+ })
}
- } catch (error) {
- if ((error as any).statusCode) {
- throw error
- }
- logger.chrono.error('Failed to prepare upload:', error)
- throw createError({
- statusCode: 500,
- statusMessage: 'Failed to prepare upload',
- })
- }
-})
+ },
+)
diff --git a/server/api/photos/multipart/[id].ts b/server/api/photos/multipart/[id].ts
index aee16759..d7692628 100644
--- a/server/api/photos/multipart/[id].ts
+++ b/server/api/photos/multipart/[id].ts
@@ -1,5 +1,6 @@
import { directUploads, abortDirectUpload } from '~~/server/utils/direct-upload'
-import type { UploadPart } from '~~/shared/types/upload'
+import { createMultipartCompleter } from '@chronoframe/core'
+import { mutationResponse } from '../../../utils/resource-writer'
import { logUpload } from '../../../utils/upload-log'
export default eventHandler(async (event) => {
@@ -21,65 +22,19 @@ export default eventHandler(async (event) => {
return { ok: true }
}
if (event.method !== 'POST') throw createError({ statusCode: 405 })
- if (session.cancelled)
- throw createError({ statusCode: 410, statusMessage: 'Upload cancelled' })
- if (session.busy)
- throw createError({ statusCode: 409, statusMessage: 'Upload is busy' })
- if (session.completed) {
- logUpload('multipart.complete.repeated', {
- sessionId: id,
- key: session.key,
- })
- return { ok: true, key: session.key }
- }
- session.busy = true
- session.touched = Date.now()
- const startedAt = Date.now()
- logUpload('multipart.complete.started', {
- sessionId: id,
- key: session.key,
- partCount: session.setup.partUrls.length,
+ const complete = createMultipartCompleter({
+ sessions: {
+ get: (key) => directUploads.get(key),
+ abort: abortDirectUpload,
+ },
+ now: Date.now,
+ event: (name, details, error) => logUpload(name, details, error),
})
- try {
- const body = (await readBody(event)) as { parts?: UploadPart[] }
- const parts = body?.parts
- if (
- !Array.isArray(parts) ||
- parts.length !== session.setup.partUrls.length ||
- parts.some(
- (part, index) =>
- !part ||
- part.partNumber !== index + 1 ||
- typeof part.etag !== 'string' ||
- !part.etag ||
- part.etag.length > 256,
- )
- )
- throw createError({
- statusCode: 400,
- statusMessage: 'Invalid multipart completion data',
- })
- if (session.cancelled)
- throw createError({ statusCode: 410, statusMessage: 'Upload cancelled' })
- await session.setup.complete(parts)
- session.completed = true
- logUpload('multipart.complete.succeeded', {
- sessionId: id,
- key: session.key,
- partCount: parts.length,
- durationMs: Date.now() - startedAt,
- })
- return { ok: true, key: session.key }
- } catch (error) {
- logUpload(
- 'multipart.complete.failed',
- { sessionId: id, key: session.key, durationMs: Date.now() - startedAt },
- error,
- )
- throw error
- } finally {
- session.busy = false
- session.touched = Date.now()
- if (session.cancelled) await abortDirectUpload(id)
- }
+ return mutationResponse(() =>
+ complete(
+ id,
+ String(user.user.id),
+ async () => (await readBody(event))?.parts,
+ ),
+ )
})
diff --git a/server/plugins/2.settings-manager.ts b/server/plugins/2.settings-manager.ts
index cd3bdf2d..e3f1048c 100644
--- a/server/plugins/2.settings-manager.ts
+++ b/server/plugins/2.settings-manager.ts
@@ -1,3 +1,4 @@
+import { createSettingsRuntimeEffects } from '../runtime/settings-effects'
import type { SettingValue } from '~~/shared/types/settings'
import { DEFAULT_SETTINGS } from '../services/settings/contants'
import type { SettingNamespace } from '../services/settings/contants'
@@ -6,6 +7,9 @@ import { and, eq, tables, useDB } from '../utils/db'
export default defineNitroPlugin(async (_nitroApp) => {
const _settingsManager = settingsManager
+ _settingsManager.setRuntimeEffects(
+ createSettingsRuntimeEffects(_settingsManager),
+ )
// Mark initialization phase to prevent storage provider switch triggers
// until storage manager is properly initialized in plugin 2_storage.ts
@@ -84,7 +88,9 @@ async function migrateRuntimeConfigToSettings() {
}
// Migrate auth settings (GitHub OAuth) from explicit env only
- const githubOauthEnabled = getExplicitEnv('NUXT_PUBLIC_OAUTH_GITHUB_ENABLED')
+ const githubOauthEnabled = getExplicitEnv(
+ 'NUXT_PUBLIC_OAUTH_GITHUB_ENABLED',
+ )
if (githubOauthEnabled === 'true') {
await migrateSetting('system', 'auth.github.enabled', true, _logger)
}
@@ -124,7 +130,8 @@ async function migrateRuntimeConfigToSettings() {
} else {
try {
// Check if a provider of the same type already exists
- const existingProviders = await settingsManager.storage.getProviders()
+ const existingProviders =
+ await settingsManager.storage.getProviders()
const sameTypeProviderExists = existingProviders.some(
(provider) => provider.provider === storageProvider,
)
@@ -298,9 +305,9 @@ function isRuntimeProviderConfigUsable(config: any): boolean {
case 's3':
return Boolean(
config.endpoint &&
- config.bucket &&
- config.accessKeyId &&
- config.secretAccessKey,
+ config.bucket &&
+ config.accessKeyId &&
+ config.secretAccessKey,
)
case 'local':
return Boolean(config.basePath)
diff --git a/server/repositories/sqlite-mutations.ts b/server/repositories/sqlite-mutations.ts
new file mode 100644
index 00000000..c065970f
--- /dev/null
+++ b/server/repositories/sqlite-mutations.ts
@@ -0,0 +1,166 @@
+import { and, eq, min } from 'drizzle-orm'
+import type {
+ AlbumWriteRepository,
+ PhotoWriteRepository,
+} from '@chronoframe/core'
+import { tables, type useDB } from '../utils/db.ts'
+import { toAlbumDto, toPhotoDto } from '../utils/dto.ts'
+
+/** Keep album row and membership changes inside synchronous SQLite transactions. */
+export function createSqliteAlbumWriteRepository(
+ db: ReturnType<typeof useDB>,
+): AlbumWriteRepository {
+ return {
+ async exists(id) {
+ return Boolean(
+ db
+ .select({ id: tables.albums.id })
+ .from(tables.albums)
+ .where(eq(tables.albums.id, id))
+ .get(),
+ )
+ },
+ async createFirst(data, photoIds) {
+ return db.transaction((tx) => {
+ const row = tx
+ .select({ min: min(tables.albums.position) })
+ .from(tables.albums)
+ .get()
+ const album = tx
+ .insert(tables.albums)
+ .values({ ...data, position: (row?.min ?? 1000) - 1000 })
+ .returning()
+ .get()
+ photoIds.forEach((photoId, index) =>
+ tx
+ .insert(tables.albumPhotos)
+ .values({
+ albumId: album.id,
+ photoId,
+ position: 1000000 + (index + 1) * 10,
+ })
+ .onConflictDoNothing()
+ .run(),
+ )
+ return toAlbumDto(album)
+ })
+ },
+ async update(id, data, photoIds) {
+ return db.transaction((tx) => {
+ const exists = tx
+ .select({ id: tables.albums.id })
+ .from(tables.albums)
+ .where(eq(tables.albums.id, id))
+ .get()
+ if (!exists) return null
+ tx.update(tables.albums).set(data).where(eq(tables.albums.id, id)).run()
+ if (photoIds !== undefined) {
+ tx.delete(tables.albumPhotos)
+ .where(eq(tables.albumPhotos.albumId, id))
+ .run()
+ photoIds.forEach((photoId, index) =>
+ tx
+ .insert(tables.albumPhotos)
+ .values({
+ albumId: id,
+ photoId,
+ position: 1000000 + (index + 1) * 10,
+ })
+ .onConflictDoNothing()
+ .run(),
+ )
+ }
+ return toAlbumDto(
+ tx
+ .select()
+ .from(tables.albums)
+ .where(eq(tables.albums.id, id))
+ .get()!,
+ )
+ })
+ },
+ async delete(id) {
+ return db.transaction((tx) => {
+ if (
+ !tx
+ .select({ id: tables.albums.id })
+ .from(tables.albums)
+ .where(eq(tables.albums.id, id))
+ .get()
+ )
+ return false
+ tx.delete(tables.albumPhotos)
+ .where(eq(tables.albumPhotos.albumId, id))
+ .run()
+ tx.delete(tables.albums).where(eq(tables.albums.id, id)).run()
+ return true
+ })
+ },
+ async reorder(ids) {
+ db.transaction((tx) => {
+ ids.forEach((id, index) =>
+ tx
+ .update(tables.albums)
+ .set({ position: index * 1000 })
+ .where(eq(tables.albums.id, id))
+ .run(),
+ )
+ })
+ },
+ async removePhoto(id, photoId, updatedAt) {
+ return db.transaction((tx) => {
+ const predicate = and(
+ eq(tables.albumPhotos.albumId, id),
+ eq(tables.albumPhotos.photoId, photoId),
+ )
+ if (
+ !tx
+ .select({ id: tables.albumPhotos.id })
+ .from(tables.albumPhotos)
+ .where(predicate)
+ .get()
+ )
+ return false
+ tx.delete(tables.albumPhotos).where(predicate).run()
+ tx.update(tables.albums)
+ .set({ coverPhotoId: null, updatedAt })
+ .where(
+ and(
+ eq(tables.albums.id, id),
+ eq(tables.albums.coverPhotoId, photoId),
+ ),
+ )
+ .run()
+ return true
+ })
+ },
+ }
+}
+
+/** Map photo writes at the existing connection boundary without changing its lifecycle. */
+export function createSqlitePhotoWriteRepository(
+ db: ReturnType<typeof useDB>,
+): PhotoWriteRepository {
+ return {
+ async get(id) {
+ const photo = db
+ .select()
+ .from(tables.photos)
+ .where(eq(tables.photos.id, id))
+ .get()
+ return photo ? toPhotoDto(photo) : null
+ },
+ async update(id, update) {
+ db.update(tables.photos).set(update).where(eq(tables.photos.id, id)).run()
+ const photo = db
+ .select()
+ .from(tables.photos)
+ .where(eq(tables.photos.id, id))
+ .get()
+ return photo ? toPhotoDto(photo) : null
+ },
+ async delete(id) {
+ db.delete(tables.photos).where(eq(tables.photos.id, id)).run()
+ },
+ }
+}
diff --git a/server/repositories/sqlite-uploads.ts b/server/repositories/sqlite-uploads.ts
new file mode 100644
index 00000000..080c31aa
--- /dev/null
+++ b/server/repositories/sqlite-uploads.ts
@@ -0,0 +1,45 @@
+import { eq } from 'drizzle-orm'
+import type { DuplicatePhoto } from '@chronoframe/core'
+import type { Photo } from '@chronoframe/contracts/resources'
+import { tables, type useDB } from '../utils/db.ts'
+
+/** Project only fields used by authenticated duplicate checks. */
+export function createSqliteUploadRepository(db: ReturnType<typeof useDB>) {
+ const summary = {
+ id: tables.photos.id,
+ title: tables.photos.title,
+ storageKey: tables.photos.storageKey,
+ originalUrl: tables.photos.originalUrl,
+ thumbnailUrl: tables.photos.thumbnailUrl,
+ dateTaken: tables.photos.dateTaken,
+ }
+ return {
+ async findDuplicate(id: string): Promise<DuplicatePhoto | null> {
+ return (
+ db
+ .select(summary)
+ .from(tables.photos)
+ .where(eq(tables.photos.id, id))
+ .get() || null
+ )
+ },
+ async findDetails(
+ id: string,
+ ): Promise<
+ (DuplicatePhoto & Pick<Photo, 'fileSize' | 'width' | 'height'>) | null
+ > {
+ return (
+ db
+ .select({
+ ...summary,
+ fileSize: tables.photos.fileSize,
+ width: tables.photos.width,
+ height: tables.photos.height,
+ })
+ .from(tables.photos)
+ .where(eq(tables.photos.id, id))
+ .get() || null
+ )
+ },
+ }
+}
diff --git a/server/runtime/settings-effects.ts b/server/runtime/settings-effects.ts
new file mode 100644
index 00000000..e643ae80
--- /dev/null
+++ b/server/runtime/settings-effects.ts
@@ -0,0 +1,91 @@
+import type {} from '../types/worker'
+import type {
+ SettingsManager,
+ SettingsRuntimeEffects,
+} from '../services/settings/settingsManager'
+import { logger } from '../utils/logger'
+
+/** Assemble post-persistence effects in the self-hosted application, not the settings service. */
+export function createSettingsRuntimeEffects(
+ settings: SettingsManager,
+): SettingsRuntimeEffects {
+ const runtimeLogger = logger.dynamic('settings-runtime')
+ async function reloadStorageProvider(providerId: number): Promise<void> {
+ try {
+ // Dynamically import to avoid circular dependency issues
+ const { getGlobalStorageManager, setGlobalStorageManager } =
+ await import('../services/storage/events')
+ const { StorageManager } = await import('../services/storage')
+ const loggerModule = await import('../utils/logger')
+
+ const newProvider = await settings.storage.getProviderById(providerId)
+ if (!newProvider) {
+ throw new Error(`Provider with ID ${providerId} not found`)
+ }
+
+ let storageManager = getGlobalStorageManager()
+ if (!storageManager) {
+ runtimeLogger.info(
+ `Storage manager not initialized, bootstrapping with provider: ${newProvider.name} (ID: ${providerId})`,
+ )
+ try {
+ storageManager = new StorageManager(
+ newProvider.config,
+ loggerModule.logger.dynamic('storage'),
+ )
+ if (newProvider.config.provider === 'local') {
+ const fs = await import('node:fs/promises')
+ await fs.mkdir(newProvider.config.basePath, { recursive: true })
+ }
+
+ setGlobalStorageManager(storageManager)
+ runtimeLogger.info('Storage manager bootstrap completed')
+ return
+ } catch (bootstrapError) {
+ runtimeLogger.error(
+ 'Failed to bootstrap storage manager with new provider:',
+ bootstrapError,
+ )
+ throw bootstrapError
+ }
+ }
+
+ runtimeLogger.info(
+ `Triggering storage provider switch to: ${newProvider.name} (ID: ${providerId})`,
+ )
+
+ await storageManager.registerProvider(
+ newProvider.config,
+ loggerModule.logger.dynamic('storage'),
+ )
+ } catch (error) {
+ runtimeLogger.error('Failed to switch storage provider:', error)
+ throw error
+ }
+ }
+ return {
+ reloadStorageProvider,
+ settingChanged({ namespace, key, value }) {
+ if (namespace === 'system' && key === 'queue.workerCount') {
+ void globalThis.__workerPool
+ ?.setWorkerCount(value as number)
+ .catch((error) => {
+ runtimeLogger.error(
+ 'Failed to apply queue concurrency setting:',
+ error,
+ )
+ })
+ }
+ if (namespace === 'storage' && key === 'provider') {
+ setImmediate(() => {
+ reloadStorageProvider(value as number).catch((error) =>
+ runtimeLogger.error(
+ 'Failed to trigger storage provider switch:',
+ error,
+ ),
+ )
+ })
+ }
+ },
+ }
+}
diff --git a/server/services/resources/photo-metadata.ts b/server/services/resources/photo-metadata.ts
new file mode 100644
index 00000000..a21e2fae
--- /dev/null
+++ b/server/services/resources/photo-metadata.ts
@@ -0,0 +1,107 @@
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { exiftool } from 'exiftool-vendored'
+import type { Photo } from '@chronoframe/contracts/resources'
+import { CoreError, type PhotoMetadataInput } from '@chronoframe/core'
+import type { StorageProvider } from '../storage/interfaces'
+import { extractExifData } from '../image/exif'
+import { logger } from '../../utils/logger'
+
+/** Keep temporary files, EXIF tooling and object I/O in the application adapter. */
+export async function editPhotoMetadata(
+ photo: Photo & { storageKey: string },
+ payload: PhotoMetadataInput,
+ storageProvider: StorageProvider,
+) {
+ const originalBuffer = await storageProvider.get(photo.storageKey)
+ if (!originalBuffer)
+ throw new CoreError(
+ 404,
+ 'Photo file missing',
+ 'dashboard.photos.messages.photoFileMissing',
+ )
+ const normalizedTitle = payload.title
+ const normalizedDescription = payload.description
+ const normalizedTags = payload.tags
+ const exifUpdates: Record<string, any> = {}
+
+ if (normalizedTitle !== undefined) {
+ const titleValue = normalizedTitle.length > 0 ? normalizedTitle : null
+ exifUpdates.Title = titleValue
+ exifUpdates.XPTitle = titleValue
+ }
+
+ if (normalizedDescription !== undefined) {
+ const descriptionValue =
+ normalizedDescription.length > 0 ? normalizedDescription : null
+ exifUpdates.Description = descriptionValue
+ exifUpdates.ImageDescription = descriptionValue
+ exifUpdates.CaptionAbstract = descriptionValue
+ exifUpdates.XPComment = descriptionValue
+ exifUpdates.UserComment = descriptionValue
+ }
+
+ if (normalizedTags !== undefined) {
+ const tagsValue = normalizedTags.length > 0 ? normalizedTags : null
+ exifUpdates.Subject = tagsValue
+ exifUpdates.Keywords = tagsValue
+ exifUpdates.XPKeywords =
+ normalizedTags.length > 0 ? normalizedTags.join('; ') : null
+ }
+
+ if (payload.location !== undefined) {
+ if (payload.location) {
+ const { latitude, longitude } = payload.location
+ const latAbs = Math.abs(latitude)
+ const lonAbs = Math.abs(longitude)
+ exifUpdates.GPSLatitude = latAbs
+ exifUpdates.GPSLatitudeRef = latitude >= 0 ? 'N' : 'S'
+ exifUpdates.GPSLongitude = lonAbs
+ exifUpdates.GPSLongitudeRef = longitude >= 0 ? 'E' : 'W'
+ exifUpdates.GPSPosition = `${latitude} ${longitude}`
+ } else {
+ exifUpdates.GPSLatitude = null
+ exifUpdates.GPSLatitudeRef = null
+ exifUpdates.GPSLongitude = null
+ exifUpdates.GPSLongitudeRef = null
+ exifUpdates.GPSPosition = null
+ }
+ }
+
+ if (payload.rating !== undefined) {
+ exifUpdates.Rating = payload.rating !== null ? payload.rating : null
+ }
+
+ const tempRoot = tmpdir()
+ await mkdir(tempRoot, { recursive: true })
+ const tempDir = await mkdtemp(path.join(tempRoot, 'cframe-edit-'))
+ const ext = path.extname(photo.storageKey) || '.jpg'
+ const tempFile = path.join(tempDir, `edited${ext}`)
+
+ try {
+ await writeFile(tempFile, originalBuffer)
+
+ if (Object.keys(exifUpdates).length > 0) {
+ await exiftool.write(tempFile, exifUpdates, ['-overwrite_original'])
+ }
+
+ const updatedBuffer = await readFile(tempFile)
+ // Stored keys already identify the full object; each provider handles its
+ // own prefix normalization. Removing a substring can overwrite another key.
+ await storageProvider.create(photo.storageKey, updatedBuffer)
+
+ const exifData = await extractExifData(updatedBuffer)
+
+ return { exif: exifData, fileSize: updatedBuffer.length }
+ } catch (error) {
+ logger.image.error('Failed to update photo metadata', error)
+ throw new CoreError(
+ 500,
+ 'Failed to update photo metadata',
+ 'dashboard.photos.messages.metadataUpdateFailed',
+ )
+ } finally {
+ await rm(tempDir, { recursive: true, force: true })
+ }
+}
diff --git a/server/services/settings/settingsManager.ts b/server/services/settings/settingsManager.ts
index 27501754..f081ed2e 100644
--- a/server/services/settings/settingsManager.ts
+++ b/server/services/settings/settingsManager.ts
@@ -1,4 +1,3 @@
-import type {} from '../../types/worker'
import type {
NewStorageProviderRow as NewSettingStorageProvider,
StorageProviderRow as SettingStorageProvider,
@@ -9,9 +8,25 @@ import type {
SettingValue,
} from '~~/shared/types/settings'
import type { SettingKey, SettingNamespace } from './contants'
-import { validateQueueWorkerCount } from '~~/shared/utils/queue-config'
+import { validateSettingWrite, createStorageResolver } from '@chronoframe/core'
+
+export interface SettingsRuntimeEffects {
+ settingChanged(change: {
+ namespace: string
+ key: string
+ value: SettingValue
+ }): void
+ reloadStorageProvider(id: number): Promise<void>
+}
export class SettingsManager {
+ private runtimeEffects?: SettingsRuntimeEffects
+
+ /** Attach application-owned effects; persistence itself does not own workers or storage instances. */
+ setRuntimeEffects(effects: SettingsRuntimeEffects): void {
+ this.runtimeEffects = effects
+ }
+
private static instance: SettingsManager
protected settingsCache: Map<string, SettingValue> = new Map()
protected _logger = logger.dynamic('settings-mgr')
@@ -43,27 +58,6 @@ export class SettingsManager {
return this.isInitializing
}
- /**
- * Validate setting value against enum if defined
- * @param value Setting value
- * @param enumValues Enum values if defined
- * @returns true if valid, false if not valid
- */
- private validateEnum(
- value: SettingValue,
- enumValues: string[] | null,
- ): boolean {
- // Allow null values if no enum is defined
- if (value === null) {
- return !enumValues || enumValues.length === 0
- }
-
- if (!enumValues || enumValues.length === 0) {
- return true
- }
- return enumValues.includes(String(value))
- }
-
/**
* Generate cache key for a setting
* @param namespace
@@ -269,43 +263,15 @@ export class SettingsManager {
throw new Error(`Setting ${namespace}:${key} does not exist`)
}
- if (existing.isReadonly && !sudo) {
- this._logger.warn(
- `Attempt to modify readonly setting ${namespace}:${key}`,
- )
- throw new Error(`Setting ${namespace}:${key} is readonly`)
- }
-
- if (!this.validateEnum(value, existing.enum)) {
- this._logger.warn(
- `Invalid value for enum setting ${namespace}:${key}. Value: ${value}, allowed: ${existing.enum?.join(', ')}`,
- )
- throw new Error(
- `Invalid value for setting ${namespace}:${key}. Allowed values: ${existing.enum?.join(', ')}`,
- )
- }
-
- if (namespace === 'location' && key === 'fallbackOrder') {
- const levels = [
- 'country',
- 'region',
- 'subregion',
- 'city',
- 'district',
- 'locality',
- 'neighborhood',
- ]
- if (
- typeof value !== 'string' ||
- value.split(',').some((level) => !levels.includes(level.trim()))
- ) {
- throw new Error('Invalid location fallback order')
- }
- }
+ validateSettingWrite({
+ namespace,
+ key,
+ value,
+ readonly: Boolean(existing.isReadonly),
+ enumValues: existing.enum,
+ sudo,
+ })
const serializedValue = this.serialize(value)
- if (namespace === 'system' && key === 'queue.workerCount') {
- validateQueueWorkerCount(value)
- }
db.update(tables.settings)
.set({
@@ -323,94 +289,8 @@ export class SettingsManager {
this._logger.info(`Setting ${namespace}:${key} updated`)
this.settingsCache.set(cacheKey, value)
- if (
- namespace === 'system' &&
- key === 'queue.workerCount' &&
- !this.isInitializing
- ) {
- void globalThis.__workerPool
- ?.setWorkerCount(value as number)
- .catch((error) => {
- this._logger.error(
- 'Failed to apply queue concurrency setting:',
- error,
- )
- })
- }
-
- // Trigger storage provider switch if storage:provider is being changed
- // Skip during initialization as storage manager is not yet initialized
- if (namespace === 'storage' && key === 'provider' && !this.isInitializing) {
- // Use setImmediate to avoid blocking and handle async operation
- setImmediate(() => {
- this.triggerStorageProviderSwitch(value as number).catch((error) => {
- this._logger.error(
- 'Failed to trigger storage provider switch:',
- error,
- )
- })
- })
- }
- }
-
- /**
- * Trigger storage provider switch
- * @param providerId Provider ID to switch to
- */
- private async triggerStorageProviderSwitch(
- providerId: number,
- ): Promise<void> {
- try {
- // Dynamically import to avoid circular dependency issues
- const { getGlobalStorageManager, setGlobalStorageManager } =
- await import('~~/server/services/storage/events')
- const { StorageManager } = await import('~~/server/services/storage')
- const loggerModule = await import('~~/server/utils/logger')
-
- const newProvider = await this.storage.getProviderById(providerId)
- if (!newProvider) {
- throw new Error(`Provider with ID ${providerId} not found`)
- }
-
- let storageManager = getGlobalStorageManager()
- if (!storageManager) {
- this._logger.info(
- `Storage manager not initialized, bootstrapping with provider: ${newProvider.name} (ID: ${providerId})`,
- )
- try {
- storageManager = new StorageManager(
- newProvider.config,
- loggerModule.logger.dynamic('storage'),
- )
- if (newProvider.config.provider === 'local') {
- const fs = await import('node:fs/promises')
- await fs.mkdir(newProvider.config.basePath, { recursive: true })
- }
-
- setGlobalStorageManager(storageManager)
- this._logger.info('Storage manager bootstrap completed')
- return
- } catch (bootstrapError) {
- this._logger.error(
- 'Failed to bootstrap storage manager with new provider:',
- bootstrapError,
- )
- throw bootstrapError
- }
- }
-
- this._logger.info(
- `Triggering storage provider switch to: ${newProvider.name} (ID: ${providerId})`,
- )
-
- await storageManager.registerProvider(
- newProvider.config,
- loggerModule.logger.dynamic('storage'),
- )
- } catch (error) {
- this._logger.error('Failed to switch storage provider:', error)
- throw error
- }
+ if (!this.isInitializing)
+ this.runtimeEffects?.settingChanged({ namespace, key, value })
}
async getNamespace(
@@ -474,14 +354,10 @@ export class SettingsManager {
},
async getActiveProvider(): Promise<SettingStorageProvider | null> {
- const providerId = await settingsManager.get<number>(
- 'storage',
- 'provider',
- )
- if (!providerId) {
- return null
- }
- return this.getProviderById(providerId)
+ return createStorageResolver({
+ getSelectedId: () => settingsManager.get<number>('storage', 'provider'),
+ find: (id) => this.getProviderById(id),
+ }).resolve()
},
async addProvider(
@@ -539,7 +415,7 @@ export class SettingsManager {
// requests use the updated configuration, including client credentials.
if (previousProvider) {
try {
- await settingsManager.triggerStorageProviderSwitch(id)
+ await settingsManager.runtimeEffects?.reloadStorageProvider(id)
} catch (error) {
// Provider construction leaves the existing instance untouched on
// failure; restore its persisted configuration to match.
diff --git a/server/utils/album-access.ts b/server/utils/album-access.ts
index b2853113..b5b2cd26 100644
--- a/server/utils/album-access.ts
+++ b/server/utils/album-access.ts
@@ -1,3 +1,8 @@
+import {
+ canReadAlbum,
+ photoAccessDenied,
+ type AlbumAccessTarget,
+} from '@chronoframe/core'
import { createHmac, randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
import { promisify } from 'node:util'
import { eq, inArray } from 'drizzle-orm'
@@ -108,42 +113,22 @@ export function grantAlbumAccess(
})
}
-type AlbumAccessTarget = {
- id: number
- isHidden: boolean
- passwordHash: string | null
-}
-
function photoNotFound() {
return createError({ statusCode: 404, statusMessage: 'Photo not found' })
}
-function photoAccessDenied(
- admin: boolean,
- memberships: { album: AlbumAccessTarget }[],
- canAccess: (album: AlbumAccessTarget) => boolean,
-): boolean {
- if (admin) return false
- return (
- memberships.some(({ album }) => album.isHidden) ||
- (memberships.some(({ album }) => album.passwordHash) &&
- !memberships.some(({ album }) => album.passwordHash && canAccess(album)))
- )
-}
-
export async function albumAccess(event: H3Event) {
const session = await getUserSession(event)
const admin = Boolean(session.user)
const grants = readGrants(event)
const canAccess = (album: AlbumAccessTarget) =>
- admin ||
- (!album.isHidden &&
- (!album.passwordHash ||
- grants.some(
- (grant) =>
- grant.id === album.id &&
- grant.hash === passwordVersion(album.passwordHash!),
- )))
+ canReadAlbum(album, admin, (target) =>
+ grants.some(
+ (grant) =>
+ grant.id === target.id &&
+ grant.hash === passwordVersion(target.passwordHash!),
+ ),
+ )
return { admin, canAccess }
}
diff --git a/server/utils/direct-upload.ts b/server/utils/direct-upload.ts
index 5e74ea7d..c73b1bc4 100644
--- a/server/utils/direct-upload.ts
+++ b/server/utils/direct-upload.ts
@@ -37,7 +37,7 @@ export async function abortDirectUpload(id: string) {
export async function prepareUpload(
owner: string,
key: string,
- size: number,
+ size: number | undefined,
contentType: string,
provider: StorageProvider,
chunked: boolean,
@@ -49,7 +49,12 @@ export async function prepareUpload(
size,
chunked,
})
- if (provider.prepareDirectUpload && Number.isSafeInteger(size) && size > 0) {
+ if (
+ provider.prepareDirectUpload &&
+ typeof size === 'number' &&
+ Number.isSafeInteger(size) &&
+ size > 0
+ ) {
const setup = await provider.prepareDirectUpload(key, size, contentType)
if (setup?.mode === 'single' || setup?.mode === 'range') {
logUpload('prepare.direct', {
@@ -101,6 +106,7 @@ export async function prepareUpload(
}
}
if (chunked && provider.config?.provider === 'local') {
+ if (typeof size !== 'number') throw new Error('Invalid file size')
return {
mode: 'chunks',
url: await createChunkUpload(owner, key, size, contentType, provider),
diff --git a/server/utils/resource-reader.ts b/server/utils/resource-reader.ts
index b8b5013a..433aeb46 100644
--- a/server/utils/resource-reader.ts
+++ b/server/utils/resource-reader.ts
@@ -1,5 +1,5 @@
import { createError } from 'h3'
-import { createResourceReader, ResourceReadError } from '@chronoframe/core'
+import { createResourceReader, CoreError } from '@chronoframe/core'
import { createSqliteResourceRepository } from '../repositories/sqlite-resources'
import { useDB } from './db'
@@ -15,7 +15,7 @@ export async function resourceReadResponse<T>(
try {
return await operation()
} catch (error) {
- if (error instanceof ResourceReadError)
+ if (error instanceof CoreError)
throw createError({
statusCode: error.statusCode,
statusMessage: error.message,
diff --git a/server/utils/resource-writer.ts b/server/utils/resource-writer.ts
new file mode 100644
index 00000000..681f2bf0
--- /dev/null
+++ b/server/utils/resource-writer.ts
@@ -0,0 +1,79 @@
+import type {} from '../types/worker'
+import { createError, type H3Event } from 'h3'
+import {
+ CoreError,
+ createAlbumWriter,
+ createPhotoWriter,
+} from '@chronoframe/core'
+import {
+ createSqliteAlbumWriteRepository,
+ createSqlitePhotoWriteRepository,
+} from '../repositories/sqlite-mutations'
+import { editPhotoMetadata } from '../services/resources/photo-metadata'
+import { hashAlbumPassword } from './album-access'
+import { useDB } from './db'
+import { useStorageProvider } from './useStorageProvider'
+import { logger } from './logger'
+
+/** Assemble album persistence, clock and hashing in the self-hosted application. */
+export function useAlbumWriter() {
+ return createAlbumWriter({
+ repository: createSqliteAlbumWriteRepository(useDB()),
+ clock: { now: () => new Date() },
+ hashPassword: hashAlbumPassword,
+ })
+}
+
+/** Supply object I/O, native metadata editing and background dispatch to core. */
+export function usePhotoWriter(event: H3Event) {
+ const { storageProvider } = useStorageProvider(event)
+ return createPhotoWriter({
+ repository: createSqlitePhotoWriteRepository(useDB()),
+ clock: { now: () => new Date() },
+ storage: { forPhoto: async () => storageProvider },
+ editMetadata: (photo, input) => {
+ if (!photo.storageKey)
+ throw new CoreError(400, 'Photo has no storage key')
+ return editPhotoMetadata(
+ { ...photo, storageKey: photo.storageKey },
+ input,
+ storageProvider,
+ )
+ },
+ tasks: {
+ async reverseGeocode(photoId, coordinates) {
+ if (!globalThis.__workerPool) {
+ logger.location.warn(
+ `Worker pool not initialized, skipping reverse geocoding enqueue for photo ${photoId}`,
+ )
+ return
+ }
+ await globalThis.__workerPool.addTask(
+ { type: 'photo-reverse-geocoding', photoId, ...coordinates },
+ { priority: 1 },
+ )
+ },
+ },
+ warn(error, operation) {
+ logger.image.warn(`Photo operation failed: ${operation}`, error)
+ },
+ })
+}
+
+/** Map domain failures to stable HTTP responses with request-local translations. */
+export async function mutationResponse<T>(
+ operation: () => Promise<T>,
+ translate?: (key: string) => string,
+): Promise<T> {
+ try {
+ return await operation()
+ } catch (error) {
+ if (error instanceof CoreError)
+ throw createError({
+ statusCode: error.statusCode,
+ statusMessage:
+ error.code && translate ? translate(error.code) : error.message,
+ })
+ throw error
+ }
+}
diff --git a/shared/types/uploading-file.ts b/shared/types/uploading-file.ts
index e579b0b9..0a6b626e 100644
--- a/shared/types/uploading-file.ts
+++ b/shared/types/uploading-file.ts
@@ -1,3 +1,4 @@
+import type { UploadPreparationResponse } from '@chronoframe/contracts/upload'
import type { UploadQueueStatus } from '~~/shared/utils/upload-status'
export interface UploadingFile {
@@ -10,7 +11,7 @@ export interface UploadingFile {
error?: string
warning?: string
taskId?: number
- signedUrlResponse?: { signedUrl: string; fileKey: string; expiresIn: number }
+ signedUrlResponse?: UploadPreparationResponse
uploadProgress?: {
loaded: number
total: number
diff --git a/shared/utils/queue-config.ts b/shared/utils/queue-config.ts
index f42aa0fe..50afd9cc 100644
--- a/shared/utils/queue-config.ts
+++ b/shared/utils/queue-config.ts
@@ -1,14 +1,4 @@
-export const DEFAULT_QUEUE_WORKER_COUNT = 5
-
-export function validateQueueWorkerCount(
- value: unknown,
-): asserts value is number {
- if (
- typeof value !== 'number' ||
- !Number.isInteger(value) ||
- value < 1 ||
- value > 8
- ) {
- throw new Error('Queue concurrency must be an integer between 1 and 8')
- }
-}
+export {
+ DEFAULT_QUEUE_WORKER_COUNT,
+ validateQueueWorkerCount,
+} from '@chronoframe/core'
diff --git a/tests/core-mutations.test.ts b/tests/core-mutations.test.ts
new file mode 100644
index 00000000..2c9006c7
--- /dev/null
+++ b/tests/core-mutations.test.ts
@@ -0,0 +1,209 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import Database from 'better-sqlite3'
+import { drizzle } from 'drizzle-orm/better-sqlite3'
+import { migrate } from 'drizzle-orm/better-sqlite3/migrator'
+import { eq } from 'drizzle-orm'
+import {
+ CoreError,
+ createAlbumWriter,
+ createPhotoWriter,
+} from '@chronoframe/core'
+import * as schema from '../server/database/schema.ts'
+import {
+ createSqliteAlbumWriteRepository,
+ createSqlitePhotoWriteRepository,
+} from '../server/repositories/sqlite-mutations.ts'
+
+const now = new Date('2026-10-20T08:00:00Z')
+const access = { authenticated: true }
+const setup = () => {
+ const sqlite = new Database(':memory:')
+ const db = drizzle(sqlite, { schema })
+ migrate(db, { migrationsFolder: './server/database/migrations' })
+ return { sqlite, db }
+}
+
+test('album mutations preserve ordering, password semantics, cover membership and transaction rollback', async () => {
+ const { sqlite, db } = setup()
+ try {
+ db.insert(schema.photos)
+ .values([{ id: 'a' }, { id: 'b' }])
+ .run()
+ const writer = createAlbumWriter({
+ repository: createSqliteAlbumWriteRepository(db),
+ clock: { now: () => now },
+ hashPassword: async (value) => `hash:${value}`,
+ })
+ await assert.rejects(
+ writer.create({ title: 'Denied' }, { authenticated: false }),
+ (error: unknown) =>
+ error instanceof CoreError && error.statusCode === 401,
+ )
+ const album = await writer.create(
+ {
+ title: 'First',
+ photoIds: ['a', 'a'],
+ coverPhotoId: 'b',
+ password: 'secret',
+ },
+ access,
+ )
+ assert.equal(album.hasPassword, true)
+ assert.equal('passwordHash' in album, false)
+ assert.deepEqual(
+ db
+ .select()
+ .from(schema.albumPhotos)
+ .all()
+ .map((row) => row.photoId),
+ ['a', 'b'],
+ )
+ const second = await writer.create({ title: 'Second' }, access)
+ assert.ok(second.position < album.position)
+ await writer.update(album.id, { title: 'Changed' }, access)
+ assert.equal(
+ db
+ .select()
+ .from(schema.albums)
+ .where(eq(schema.albums.id, album.id))
+ .get()!.passwordHash,
+ 'hash:secret',
+ )
+ const cleared = await writer.update(
+ album.id,
+ { password: '', photoIds: ['b'] },
+ access,
+ )
+ assert.equal(cleared.hasPassword, false)
+ await assert.rejects(
+ writer.update(
+ album.id,
+ { title: 'Must roll back', photoIds: ['missing-photo'] },
+ access,
+ ),
+ )
+ assert.equal(
+ db
+ .select()
+ .from(schema.albums)
+ .where(eq(schema.albums.id, album.id))
+ .get()!.title,
+ 'Changed',
+ )
+ assert.deepEqual(
+ db
+ .select()
+ .from(schema.albumPhotos)
+ .all()
+ .map((row) => row.photoId),
+ ['b'],
+ )
+ await writer.removePhoto(album.id, 'b', access)
+ assert.equal(
+ db
+ .select()
+ .from(schema.albums)
+ .where(eq(schema.albums.id, album.id))
+ .get()!.coverPhotoId,
+ null,
+ )
+ await writer.reorder([album.id, second.id], access)
+ assert.equal(
+ db
+ .select()
+ .from(schema.albums)
+ .where(eq(schema.albums.id, second.id))
+ .get()!.position,
+ 1000,
+ )
+ await writer.delete(album.id, access)
+ assert.equal(db.select().from(schema.photos).all().length, 2)
+ await assert.rejects(
+ writer.delete(album.id, access),
+ (error: unknown) =>
+ error instanceof CoreError && error.statusCode === 404,
+ )
+ } finally {
+ sqlite.close()
+ }
+})
+
+test('photo mutations keep normalized EXIF and database edits aligned and tolerate queue or cleanup failures', async () => {
+ const { sqlite, db } = setup()
+ const deleted: string[] = []
+ const edits: unknown[] = []
+ const warnings: string[] = []
+ try {
+ db.insert(schema.photos)
+ .values({
+ id: 'p',
+ storageKey: 'p.HEIC',
+ thumbnailKey: 'p.webp',
+ livePhotoVideoKey: 'p.mp4',
+ title: 'Original',
+ latitude: 31,
+ longitude: 121,
+ })
+ .run()
+ const writer = createPhotoWriter({
+ repository: createSqlitePhotoWriteRepository(db),
+ clock: { now: () => now },
+ storage: {
+ forPhoto: async () => ({
+ async delete(key) {
+ deleted.push(key)
+ if (key === 'p.HEIC') throw new Error('storage failure')
+ },
+ }),
+ },
+ editMetadata: async (_photo, input) => {
+ edits.push(input)
+ return { exif: null, fileSize: 100 }
+ },
+ tasks: {
+ reverseGeocode: async () => {
+ throw new Error('queue failure')
+ },
+ },
+ warn: (_error, operation) => warnings.push(operation),
+ })
+ await assert.rejects(
+ writer.update('p', {}, access),
+ (error: unknown) =>
+ error instanceof CoreError && error.statusCode === 400,
+ )
+ const updated = await writer.update(
+ 'p',
+ {
+ title: ' New ',
+ tags: [' Tag ', 'tag', '', 'Other'],
+ location: { latitude: 32, longitude: 120 },
+ },
+ access,
+ )
+ assert.equal(updated.photo!.title, 'New')
+ assert.deepEqual(updated.photo!.tags, ['Tag', 'Other'])
+ assert.equal(updated.photo!.lastModified, now.toISOString())
+ assert.equal(updated.photo!.geocoding, null)
+ assert.deepEqual(edits[0], {
+ title: 'New',
+ tags: ['Tag', 'Other'],
+ location: { latitude: 32, longitude: 120 },
+ })
+ assert.deepEqual(warnings, ['reverse-geocoding'])
+ const erased = await writer.update(
+ 'p',
+ { title: ' ', location: null },
+ access,
+ )
+ assert.equal(erased.photo!.title, null)
+ assert.equal(erased.photo!.latitude, null)
+ await writer.delete('p', access)
+ assert.deepEqual(deleted, ['p.HEIC', 'p.webp', 'p.mp4', 'p.jpeg'])
+ assert.equal(db.select().from(schema.photos).get(), undefined)
+ assert.ok(warnings.includes('delete-photo-object'))
+ } finally {
+ sqlite.close()
+ }
+})
diff --git a/tests/core-settings.test.ts b/tests/core-settings.test.ts
new file mode 100644
index 00000000..0b510fd2
--- /dev/null
+++ b/tests/core-settings.test.ts
@@ -0,0 +1,67 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { createStorageResolver, validateSettingWrite } from '@chronoframe/core'
+
+test('settings rules reject invalid values before persistence and preserve privileged writes', () => {
+ const input = {
+ namespace: 'app',
+ key: 'title',
+ value: 'Gallery',
+ readonly: true,
+ enumValues: null,
+ sudo: false,
+ }
+ assert.throws(() => validateSettingWrite(input), /readonly/)
+ validateSettingWrite({ ...input, sudo: true })
+ assert.throws(
+ () =>
+ validateSettingWrite({
+ ...input,
+ readonly: false,
+ enumValues: ['Other'],
+ }),
+ /Allowed values/,
+ )
+ assert.throws(
+ () =>
+ validateSettingWrite({
+ ...input,
+ readonly: false,
+ namespace: 'system',
+ key: 'queue.workerCount',
+ value: 0,
+ }),
+ /between 1 and 8/,
+ )
+ assert.throws(
+ () =>
+ validateSettingWrite({
+ ...input,
+ readonly: false,
+ namespace: 'location',
+ key: 'fallbackOrder',
+ value: 'city,unknown',
+ }),
+ /fallback/,
+ )
+ validateSettingWrite({
+ ...input,
+ readonly: false,
+ namespace: 'location',
+ key: 'fallbackOrder',
+ value: 'city, country',
+ })
+})
+
+test('storage selection reads the current connection rather than caching a provider instance', async () => {
+ let selected: number | null = null
+ const resolver = createStorageResolver({
+ getSelectedId: async () => selected,
+ find: async (id) => (id === 1 ? { id, provider: 'local' } : null),
+ })
+ assert.equal(await resolver.resolve(), null)
+ selected = 1
+ assert.deepEqual(await resolver.resolve(), { id: 1, provider: 'local' })
+ selected = 2
+ assert.equal(await resolver.resolve(), null)
+})
diff --git a/tests/core-upload-completion.test.ts b/tests/core-upload-completion.test.ts
new file mode 100644
index 00000000..9403af67
--- /dev/null
+++ b/tests/core-upload-completion.test.ts
@@ -0,0 +1,158 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import {
+ CoreError,
+ createMultipartCompleter,
+ completeLocalUpload,
+ type MultipartSession,
+} from '@chronoframe/core'
+
+const code = (status: number) => (error: unknown) =>
+ error instanceof CoreError && error.statusCode === status
+const parts = [
+ { partNumber: 1, etag: 'one' },
+ { partNumber: 2, etag: 'two' },
+]
+
+test('multipart completion enforces ownership, ordered parts and a single reserved completion', async () => {
+ let completed = 0
+ const session: MultipartSession = {
+ owner: 'owner',
+ key: 'p.jpg',
+ busy: false,
+ cancelled: false,
+ completed: false,
+ touched: 0,
+ setup: {
+ partUrls: ['one', 'two'],
+ complete: async () => {
+ completed++
+ },
+ },
+ }
+ const complete = createMultipartCompleter({
+ sessions: { get: () => session, abort: async () => {} },
+ now: () => 1000,
+ event() {},
+ })
+ await assert.rejects(
+ complete('id', 'stranger', async () => parts),
+ code(404),
+ )
+ for (const invalid of [
+ undefined,
+ [],
+ parts.slice(0, 1),
+ [parts[0], parts[0]],
+ [...parts].reverse(),
+ [{ partNumber: 1, etag: '' }, parts[1]],
+ ]) {
+ await assert.rejects(
+ complete('id', 'owner', async () => invalid),
+ code(400),
+ )
+ assert.equal(session.busy, false)
+ }
+ let release!: (value: unknown) => void
+ const inFlight = complete(
+ 'id',
+ 'owner',
+ () =>
+ new Promise((resolve) => {
+ release = resolve
+ }),
+ )
+ assert.equal(session.busy, true)
+ await assert.rejects(
+ complete('id', 'owner', async () => parts),
+ code(409),
+ )
+ release(parts)
+ assert.deepEqual(await inFlight, { ok: true, key: 'p.jpg' })
+ await complete('id', 'owner', async () => {
+ throw new Error('must not read repeated body')
+ })
+ assert.equal(completed, 1)
+})
+
+test('cancellation while reading completion data aborts without publishing', async () => {
+ let aborted = 0
+ let published = 0
+ const session: MultipartSession = {
+ owner: 'owner',
+ key: 'p',
+ busy: false,
+ cancelled: false,
+ completed: false,
+ touched: 0,
+ setup: {
+ partUrls: ['one', 'two'],
+ complete: async () => {
+ published++
+ },
+ },
+ }
+ const complete = createMultipartCompleter({
+ sessions: {
+ get: () => session,
+ abort: async () => {
+ aborted++
+ },
+ },
+ now: Date.now,
+ event() {},
+ })
+ await assert.rejects(
+ complete('id', 'owner', async () => {
+ session.cancelled = true
+ return parts
+ }),
+ code(410),
+ )
+ assert.equal(published, 0)
+ assert.equal(aborted, 1)
+ assert.equal(session.busy, false)
+})
+
+test('Local completion validates byte count, only marks successful publication, and tolerates cleanup failure', async () => {
+ let published = 0
+ let marked = false
+ const input = {
+ completed: false,
+ cancelled: false,
+ key: 'p',
+ size: 9,
+ partSize: 5,
+ receivedParts: 2,
+ fileSize: async () => 9,
+ publish: async () => {
+ published++
+ },
+ markCompleted: () => {
+ marked = true
+ },
+ cleanup: async () => {
+ throw new Error('cleanup failure')
+ },
+ }
+ await assert.rejects(
+ completeLocalUpload({ ...input, receivedParts: 1 }),
+ code(400),
+ )
+ await assert.rejects(
+ completeLocalUpload({ ...input, fileSize: async () => 8 }),
+ code(400),
+ )
+ await assert.rejects(
+ completeLocalUpload({
+ ...input,
+ publish: async () => {
+ throw new Error('write failure')
+ },
+ }),
+ )
+ assert.equal(marked, false)
+ await completeLocalUpload(input)
+ assert.equal(marked, true)
+ assert.equal(published, 1)
+})
diff --git a/tests/core-upload-preparation.test.ts b/tests/core-upload-preparation.test.ts
new file mode 100644
index 00000000..ffe97f4a
--- /dev/null
+++ b/tests/core-upload-preparation.test.ts
@@ -0,0 +1,174 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import {
+ CoreError,
+ DuplicateUploadError,
+ createUploadPreparer,
+ canReadAlbum,
+ photoAccessDenied,
+ type UploadPolicy,
+} from '@chronoframe/core'
+
+const policy: UploadPolicy = {
+ prefix: 'photos///',
+ maxBytes: 10,
+ mimeWhitelistEnabled: true,
+ mimeWhitelist: ['image/jpeg'],
+ duplicateCheckEnabled: true,
+ duplicateMode: 'skip',
+}
+const duplicate = {
+ id: 'photo',
+ title: null,
+ storageKey: 'photos/p.jpg',
+ originalUrl: '/image',
+ thumbnailUrl: '/thumb',
+ dateTaken: null,
+}
+
+test('upload preparation rejects invalid size, MIME, names and quota before creating sessions', async () => {
+ let prepared = 0
+ const prepare = createUploadPreparer({
+ repository: { findDuplicate: async () => null },
+ identifiers: { fromStorageKey: () => 'photo' },
+ quota: { assertAllowed: async () => {} },
+ prepare: async () => {
+ prepared++
+ return { mode: 'single', url: '/upload' }
+ },
+ })
+ for (const input of [
+ { fileName: 'p.jpg', fileSize: 0 },
+ { fileName: 'p.jpg', fileSize: 11 },
+ { fileName: 'p.jpg', fileSize: 2, contentType: 'text/plain' },
+ { fileName: '../p.jpg', fileSize: 2, contentType: 'image/jpeg' },
+ ]) {
+ await assert.rejects(
+ prepare('owner', input, policy),
+ (error: unknown) => error instanceof CoreError,
+ )
+ }
+ assert.equal(prepared, 0)
+ const blocked = createUploadPreparer({
+ repository: { findDuplicate: async () => null },
+ identifiers: { fromStorageKey: () => 'photo' },
+ quota: {
+ assertAllowed: async () => {
+ throw new CoreError(403, 'Quota exhausted')
+ },
+ },
+ prepare: async () => {
+ throw new Error('must not prepare')
+ },
+ })
+ await assert.rejects(
+ blocked('owner', { fileName: 'p.jpg' }, policy),
+ /Quota exhausted/,
+ )
+})
+
+test('duplicate skip, block and warning preserve keys and avoid unwanted provider calls', async () => {
+ const prepared: string[] = []
+ const prepare = createUploadPreparer({
+ repository: { findDuplicate: async () => duplicate },
+ identifiers: { fromStorageKey: () => 'photo' },
+ quota: { assertAllowed: async () => {} },
+ prepare: async (_owner, key) => {
+ prepared.push(key)
+ return { mode: 'single', url: '/upload' }
+ },
+ })
+ const skipped = await prepare('owner', { fileName: 'p.jpg' }, policy)
+ assert.equal(skipped.skipped, true)
+ assert.equal(skipped.fileKey, 'photos/p.jpg')
+ assert.deepEqual(prepared, [])
+ await assert.rejects(
+ prepare(
+ 'owner',
+ { fileName: 'p.jpg' },
+ { ...policy, duplicateMode: 'block' },
+ ),
+ (error: unknown) =>
+ error instanceof DuplicateUploadError &&
+ error.existingPhoto.id === 'photo',
+ )
+ const warning = await prepare(
+ 'owner',
+ { fileName: 'p.jpg' },
+ { ...policy, duplicateMode: 'warn' },
+ )
+ assert.equal(warning.skipped, false)
+ assert.equal(warning.existingPhoto!.id, 'photo')
+ const ignored = await prepare(
+ 'owner',
+ { fileName: 'p.jpg', skipDuplicateCheck: true },
+ policy,
+ )
+ assert.equal(ignored.existingPhoto, null)
+ const video = await prepare('owner', { fileName: 'p.mov' }, policy)
+ assert.equal(video.skipped, false)
+ assert.equal(video.existingPhoto, null)
+})
+
+test('protected access requires current grants and hidden membership wins', () => {
+ const publicAlbum = { id: 1, isHidden: false, passwordHash: null }
+ const protectedAlbum = { id: 2, isHidden: false, passwordHash: 'hash' }
+ const hiddenAlbum = { id: 3, isHidden: true, passwordHash: null }
+ assert.equal(
+ canReadAlbum(publicAlbum, false, () => false),
+ true,
+ )
+ assert.equal(
+ canReadAlbum(protectedAlbum, false, () => false),
+ false,
+ )
+ assert.equal(
+ canReadAlbum(protectedAlbum, false, () => true),
+ true,
+ )
+ assert.equal(
+ canReadAlbum(hiddenAlbum, false, () => true),
+ false,
+ )
+ assert.equal(
+ photoAccessDenied(
+ false,
+ [{ album: protectedAlbum }, { album: hiddenAlbum }],
+ () => true,
+ ),
+ true,
+ )
+ assert.equal(
+ photoAccessDenied(false, [{ album: protectedAlbum }], () => true),
+ false,
+ )
+ assert.equal(
+ photoAccessDenied(true, [{ album: hiddenAlbum }], () => false),
+ false,
+ )
+})
+
+test('batch preflight shares upload key and identifier rules without altering explicit storage keys', async () => {
+ const { createDuplicateChecker } = await import('@chronoframe/core')
+ const keys: string[] = []
+ const check = createDuplicateChecker({
+ identifiers: {
+ fromStorageKey(key) {
+ keys.push(key)
+ return 'photo'
+ },
+ },
+ find: async () => duplicate,
+ })
+ const results = await check(
+ { fileNames: ['p.jpg'], storageKeys: ['original/key.jpg'] },
+ 'photos///',
+ )
+ assert.deepEqual(keys, ['photos/p.jpg', 'original/key.jpg'])
+ assert.deepEqual(
+ results.map((row) => row.exists),
+ [true, true],
+ )
+ assert.equal(results[0]!.fileName, 'p.jpg')
+ assert.equal('fileName' in results[1]!, false)
+})
diff --git a/tests/settings-effects-boundary.test.ts b/tests/settings-effects-boundary.test.ts
new file mode 100644
index 00000000..efc14158
--- /dev/null
+++ b/tests/settings-effects-boundary.test.ts
@@ -0,0 +1,106 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import Database from 'better-sqlite3'
+import { drizzle } from 'drizzle-orm/better-sqlite3'
+import { migrate } from 'drizzle-orm/better-sqlite3/migrator'
+import { and, eq } from 'drizzle-orm'
+import * as tables from '../server/database/schema.ts'
+
+test('settings emit effects only after persistence and restore an active config after reload failure', async () => {
+ const sqlite = new Database(':memory:')
+ const db = drizzle(sqlite, { schema: tables })
+ migrate(db, { migrationsFolder: './server/database/migrations' })
+ const fakeLogger = { info() {}, warn() {}, error() {}, debug() {} }
+ const globals = globalThis as unknown as Record<string, unknown>
+ const overrides = {
+ logger: { dynamic: () => fakeLogger },
+ useDB: () => db,
+ tables,
+ and,
+ eq,
+ }
+ const previous = Object.fromEntries(
+ Object.keys(overrides).map((key) => [key, globals[key]]),
+ )
+ Object.assign(globals, overrides)
+ try {
+ const { settingsManager } =
+ await import('../server/services/settings/settingsManager.ts')
+ db.insert(tables.settings)
+ .values([
+ {
+ namespace: 'system',
+ key: 'queue.workerCount',
+ type: 'number',
+ value: '5',
+ },
+ { namespace: 'storage', key: 'provider', type: 'number', value: '1' },
+ ])
+ .run()
+ db.insert(tables.settings_storage_providers)
+ .values({
+ id: 1,
+ name: 'Original',
+ provider: 'local',
+ config: { provider: 'local', basePath: '/tmp/original' },
+ })
+ .run()
+ const effects: string[] = []
+ settingsManager.setRuntimeEffects({
+ settingChanged(change) {
+ const row = db
+ .select()
+ .from(tables.settings)
+ .where(
+ and(
+ eq(tables.settings.namespace, change.namespace),
+ eq(tables.settings.key, change.key),
+ ),
+ )
+ .get()!
+ assert.equal(row.value, String(change.value))
+ effects.push(change.key)
+ },
+ async reloadStorageProvider(id) {
+ assert.equal(id, 1)
+ assert.equal(
+ (await settingsManager.storage.getProviderById(id))!.name,
+ 'Broken',
+ )
+ throw new Error('construction failed')
+ },
+ })
+ settingsManager.setInitializingFlag(true)
+ await settingsManager.set('system', 'queue.workerCount', 2)
+ assert.deepEqual(effects, [])
+ settingsManager.setInitializingFlag(false)
+ await settingsManager.set('system', 'queue.workerCount', 3)
+ assert.deepEqual(effects, ['queue.workerCount'])
+ await assert.rejects(
+ settingsManager.set('system', 'queue.workerCount', 99),
+ /between 1 and 8/,
+ )
+ assert.equal(await settingsManager.get('system', 'queue.workerCount'), 3)
+ await assert.rejects(
+ settingsManager.storage.updateProvider(1, {
+ name: 'Broken',
+ config: { provider: 'local', basePath: '/tmp/broken' },
+ }),
+ /construction failed/,
+ )
+ assert.equal(
+ (await settingsManager.storage.getActiveProvider())!.name,
+ 'Original',
+ )
+ assert.deepEqual(
+ (await settingsManager.storage.getActiveProvider())!.config,
+ { provider: 'local', basePath: '/tmp/original' },
+ )
+ } finally {
+ for (const [key, value] of Object.entries(previous)) {
+ if (value === undefined) delete globals[key]
+ else globals[key] = value
+ }
+ sqlite.close()
+ }
+})