You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

226 lines
6.2 KiB
TypeScript

import crypto from 'crypto'
2 years ago
import { readFile, writeFile, access, constants } from 'fs/promises'
import { Database, DatabaseConnection } from '../../shared/database'
2 years ago
import { MetadataProps as MetaProps, Problem, ProblemId, Solution, SolutionId, User, UserId, UserRole } from '../../shared/model'
function once<T extends (...args: any) => any>(fn: T, message: string): T {
let flag = false
return ((...args: any) => {
if (flag) {
throw new Error(message ?? `cannot run more than once`)
}
flag = true
return fn(...args)
}) as T
}
type Lock = () => void
type Mutex = {
lock(): Promise<Lock>
}
function createMutex(): Mutex {
let locked = false
const waiters: ((fn: () => void) => void)[] = []
const unlock = () => {
if (waiters.length > 0) {
console.log(`[Database/Mutex] Passing lock to next in queue (of size ${waiters.length})`)
2 years ago
const resolve = waiters.shift()!!
resolve(once(unlock, `lock already released`))
} else {
locked = false
console.log(`[Database/Mutex] Releasing the lock`)
}
}
const lock = (): Promise<Lock> => {
if (locked) {
console.log(`[Database/Mutex] Putting into queue`)
return new Promise(resolve => {
waiters.push(resolve)
})
} else {
console.log(`[Database/Mutex] Acquiring the lock`)
locked = true
return Promise.resolve(once(unlock, `lock already released`))
}
}
return { lock }
}
type DatabaseInternal = {
path: string
initialValue: Database
mu: Mutex
}
export function createDatabaseWrapper(db: DatabaseInternal): DatabaseConnection {
return {
getProblem(id: string): Promise<Problem | null> {
return getProblem(db, id)
},
}
}
export function createDatabase(path: string, initialValue: Database) {
return {
path,
initialValue,
mu: createMutex(),
}
2 years ago
}
async function withDatabase<R>({ path, initialValue, mu }: DatabaseInternal, fn: (db: Database) => R | Promise<R>): Promise<R> {
const unlock: Lock = await mu.lock()
2 years ago
try {
await access(path, constants.R_OK)
} catch (e) {
console.log(`[Database] Creating empty database into "${path}"`)
await writeFile(path, JSON.stringify(initialValue, null, 4))
2 years ago
}
console.log(`[Database] Loading database from "${path}"`)
2 years ago
const state = JSON.parse(await readFile(path, 'utf-8'))
const result = await fn(state)
console.log(`[Database] Saving database to "${path}"`)
await writeFile(path, JSON.stringify(state, null, 4))
2 years ago
unlock()
2 years ago
return result
2 years ago
}
//
// Users
//
export const getUsers = (db: DatabaseInternal) =>
withDatabase(db, state => {
return Object.values(state.users)
})
2 years ago
export const getUser: (db: DatabaseInternal, id: string) => Promise<User | null> = (db, id) =>
2 years ago
withDatabase(db, state => {
return state.users[id] ?? null
})
export const createUser: (db: DatabaseInternal, user: User) => Promise<void> = (db, user) =>
withDatabase(db, state => {
state.users[user.id] = user
})
//
// Problems
//
export const createProblem = (db: DatabaseInternal, { title, content, createdBy }: Omit<Problem, MetaProps>): Promise<ProblemId> =>
withDatabase(db, state => {
const id = crypto.randomBytes(4).toString('hex') as ProblemId
state.problems[id] = {
id,
createdAt: new Date().toJSON(),
deleted: false,
title,
content,
createdBy,
}
return id
})
export const getProblem = (db: DatabaseInternal, id: string): Promise<Problem | null> =>
withDatabase(db, state => {
const problem = (state.problems[id] ?? null) as Problem | null
return problem && !problem.deleted ? problem : null
2 years ago
})
export const getProblems = (db: DatabaseInternal): Promise<Problem[]> =>
2 years ago
withDatabase(db, state => {
return Object.values(state.problems).filter(p => !p.deleted)
})
export const updateProblem = (db: DatabaseInternal, id: ProblemId, problem: Partial<Omit<Problem, MetaProps>>): Promise<Problem> =>
withDatabase(db, state => {
state.problems[id] = {
...state.problems[id],
...problem,
}
return state.problems[id]
})
export const deleteProblem = (db: DatabaseInternal, id: ProblemId): Promise<void> =>
withDatabase(db, state => {
state.problems[id].deleted = true
})
//
// Solutions
//
export const createSolution = (
db: DatabaseInternal,
2 years ago
{ sentBy, forProblem, content }: Omit<Solution, MetaProps | 'status' | 'visible'>
): Promise<SolutionId> =>
withDatabase(db, state => {
2 years ago
const id = crypto.randomBytes(10).toString('hex') as SolutionId
state.solutions[id] = {
id,
2 years ago
createdAt: new Date().toISOString(),
deleted: false,
2 years ago
sentBy,
forProblem,
content,
status: 'pending',
2 years ago
visible: false,
2 years ago
}
return id
2 years ago
})
export const getSolution = (db: DatabaseInternal, id: SolutionId): Promise<Solution | null> =>
withDatabase(db, state => {
const solution = (state.solutions[id] ?? null) as Solution | null
return solution && !solution.deleted ? solution : null
})
export const getSolutions = (db: DatabaseInternal) =>
withDatabase(db, state => {
return Object.values(state.solutions).filter(s => !s.deleted)
})
export const getVisibleSolutions = (db: DatabaseInternal): Promise<Solution[]> =>
withDatabase(db, state => {
return Object.values(state.solutions)
.filter(s => !s.deleted)
.filter(s => s.visible)
})
export const updateSolution = (db: DatabaseInternal, id: SolutionId, solution: Partial<Omit<Solution, MetaProps>>): Promise<Solution> =>
withDatabase(db, state => {
2 years ago
state.solutions[id] = {
...state.solutions[id],
...solution,
}
return state.solutions[id]
})
export const deleteSolution = (db: DatabaseInternal, id: SolutionId): Promise<void> =>
2 years ago
withDatabase(db, state => {
state.solutions[id].deleted = true
2 years ago
})