logigate/server/utils/accounts.ts

52 lines
2.0 KiB
TypeScript

// Projects stored per account, with a revision number per project so two
// devices can't silently overwrite each other's work.
import type { Project } from '../../app/lib/logic/types'
export interface CloudMeta {
id: string
name: string
updated: number
rev: number
/** Stored size in bytes, for the per-account limit. */
size?: number
/** Share link of this project, with its edit key, so every device of the owner can update it. */
link?: { id: string; key?: string }
}
export interface AccountIndex {
projects: CloudMeta[]
/** Projects deleted on one device, so the others remove them too. */
deleted: { id: string; at: number }[]
}
export const MAX_PROJECTS = 1000
/** Total size of all projects of one account. */
export const MAX_ACCOUNT_BYTES = 100_000_000
export const accounts = () => useStorage('accounts')
export const isProjectId = (id: unknown): id is string => typeof id === 'string' && /^[A-Za-z0-9]{4,32}$/.test(id)
export async function readIndex(uid: string): Promise<AccountIndex> {
const index = await accounts().getItem<AccountIndex>(`${uid}:index`)
return { projects: index?.projects ?? [], deleted: index?.deleted ?? [] }
}
export const writeIndex = (uid: string, index: AccountIndex) => accounts().setItem(`${uid}:index`, index)
export const projectKey = (uid: string, id: string) => `${uid}:p:${id}`
export const readProject = (uid: string, id: string) => accounts().getItem<Project>(projectKey(uid, id))
// One change at a time per account, so two quick saves can't both read the
// old index and lose one of the updates.
const locks = new Map<string, Promise<unknown>>()
export function withLock<T>(uid: string, fn: () => Promise<T>): Promise<T> {
const prev = locks.get(uid) ?? Promise.resolve()
const next = prev.catch(() => {}).then(fn)
locks.set(uid, next)
next.finally(() => locks.get(uid) === next && locks.delete(uid)).catch(() => {})
return next
}
export async function deleteAccountData(uid: string) {
for (const key of await accounts().getKeys(`${uid}:`)) await accounts().removeItem(key)
}