DB에 동시적으로 접근하더라도 데이터 무결성이 깨지지 않도록 DB 접근 코드 수정

This commit is contained in:
static
2025-01-11 03:55:19 +09:00
parent 045eb69487
commit 0bdf990dae
12 changed files with 486 additions and 438 deletions

View File

@@ -1,5 +1,6 @@
import { and, eq, isNull } from "drizzle-orm";
import db from "./drizzle";
import { IntegrityError } from "./error";
import { directory, file, mek } from "./schema";
type DirectoryId = "root" | number;
@@ -27,40 +28,42 @@ export interface NewFileParams {
encNameIv: string;
}
export const registerNewDirectory = async (params: NewDirectoryParams) => {
return await db.transaction(async (tx) => {
const meks = await tx
.select()
.from(mek)
.where(and(eq(mek.userId, params.userId), eq(mek.state, "active")));
if (meks[0]?.version !== params.mekVersion) {
throw new Error("Invalid MEK version");
}
export const registerDirectory = async (params: NewDirectoryParams) => {
await db.transaction(
async (tx) => {
const meks = await tx
.select({ version: mek.version })
.from(mek)
.where(and(eq(mek.userId, params.userId), eq(mek.state, "active")))
.limit(1);
if (meks[0]?.version !== params.mekVersion) {
throw new IntegrityError("Inactive MEK version");
}
const now = new Date();
await tx.insert(directory).values({
createdAt: now,
parentId: params.parentId === "root" ? null : params.parentId,
userId: params.userId,
mekVersion: params.mekVersion,
encDek: params.encDek,
dekVersion: params.dekVersion,
encName: { ciphertext: params.encName, iv: params.encNameIv },
});
});
await tx.insert(directory).values({
createdAt: new Date(),
parentId: params.parentId === "root" ? null : params.parentId,
userId: params.userId,
mekVersion: params.mekVersion,
encDek: params.encDek,
dekVersion: params.dekVersion,
encName: { ciphertext: params.encName, iv: params.encNameIv },
});
},
{ behavior: "exclusive" },
);
};
export const getAllDirectoriesByParent = async (userId: number, directoryId: DirectoryId) => {
export const getAllDirectoriesByParent = async (userId: number, parentId: DirectoryId) => {
return await db
.select()
.from(directory)
.where(
and(
eq(directory.userId, userId),
directoryId === "root" ? isNull(directory.parentId) : eq(directory.parentId, directoryId),
parentId === "root" ? isNull(directory.parentId) : eq(directory.parentId, parentId),
),
)
.execute();
);
};
export const getDirectory = async (userId: number, directoryId: number) => {
@@ -68,7 +71,7 @@ export const getDirectory = async (userId: number, directoryId: number) => {
.select()
.from(directory)
.where(and(eq(directory.userId, userId), eq(directory.id, directoryId)))
.execute();
.limit(1);
return res[0] ?? null;
};
@@ -79,72 +82,87 @@ export const setDirectoryEncName = async (
encName: string,
encNameIv: string,
) => {
const res = await db
.update(directory)
.set({ encName: { ciphertext: encName, iv: encNameIv } })
.where(
and(
eq(directory.userId, userId),
eq(directory.id, directoryId),
eq(directory.dekVersion, dekVersion),
),
)
.execute();
return res.changes > 0;
await db.transaction(
async (tx) => {
const directories = await tx
.select({ version: directory.dekVersion })
.from(directory)
.where(and(eq(directory.userId, userId), eq(directory.id, directoryId)))
.limit(1);
if (!directories[0]) {
throw new IntegrityError("Directory not found");
} else if (directories[0].version.getTime() !== dekVersion.getTime()) {
throw new IntegrityError("Invalid DEK version");
}
await tx
.update(directory)
.set({ encName: { ciphertext: encName, iv: encNameIv } })
.where(and(eq(directory.userId, userId), eq(directory.id, directoryId)));
},
{ behavior: "exclusive" },
);
};
export const unregisterDirectory = async (userId: number, directoryId: number) => {
return await db.transaction(async (tx) => {
const getFilePaths = async (parentId: number) => {
const files = await tx
.select({ path: file.path })
.from(file)
.where(and(eq(file.userId, userId), eq(file.parentId, parentId)));
return files.map(({ path }) => path);
};
const unregisterSubDirectoriesRecursively = async (directoryId: number): Promise<string[]> => {
const subDirectories = await tx
.select({ id: directory.id })
.from(directory)
.where(and(eq(directory.userId, userId), eq(directory.parentId, directoryId)));
const subDirectoryFilePaths = await Promise.all(
subDirectories.map(async ({ id }) => await unregisterSubDirectoriesRecursively(id)),
);
const filePaths = await getFilePaths(directoryId);
return await db.transaction(
async (tx) => {
const unregisterFiles = async (parentId: number) => {
const files = await tx
.delete(file)
.where(and(eq(file.userId, userId), eq(file.parentId, parentId)))
.returning({ path: file.path });
return files.map(({ path }) => path);
};
const unregisterDirectoryRecursively = async (directoryId: number): Promise<string[]> => {
const filePaths = await unregisterFiles(directoryId);
const subDirectories = await tx
.select({ id: directory.id })
.from(directory)
.where(and(eq(directory.userId, userId), eq(directory.parentId, directoryId)));
const subDirectoryFilePaths = await Promise.all(
subDirectories.map(async ({ id }) => await unregisterDirectoryRecursively(id)),
);
await tx.delete(file).where(eq(file.parentId, directoryId));
await tx.delete(directory).where(eq(directory.id, directoryId));
return filePaths.concat(...subDirectoryFilePaths);
};
return await unregisterSubDirectoriesRecursively(directoryId);
});
const deleteRes = await tx.delete(directory).where(eq(directory.id, directoryId));
if (deleteRes.changes === 0) {
throw new IntegrityError("Directory not found");
}
return filePaths.concat(...subDirectoryFilePaths);
};
return await unregisterDirectoryRecursively(directoryId);
},
{ behavior: "exclusive" },
);
};
export const registerNewFile = async (params: NewFileParams) => {
await db.transaction(async (tx) => {
const meks = await tx
.select()
.from(mek)
.where(and(eq(mek.userId, params.userId), eq(mek.state, "active")));
if (meks[0]?.version !== params.mekVersion) {
throw new Error("Invalid MEK version");
}
export const registerFile = async (params: NewFileParams) => {
await db.transaction(
async (tx) => {
const meks = await tx
.select({ version: mek.version })
.from(mek)
.where(and(eq(mek.userId, params.userId), eq(mek.state, "active")))
.limit(1);
if (meks[0]?.version !== params.mekVersion) {
throw new IntegrityError("Inactive MEK version");
}
const now = new Date();
await tx.insert(file).values({
path: params.path,
parentId: params.parentId === "root" ? null : params.parentId,
createdAt: now,
userId: params.userId,
mekVersion: params.mekVersion,
contentType: params.contentType,
encDek: params.encDek,
dekVersion: params.dekVersion,
encContentIv: params.encContentIv,
encName: { ciphertext: params.encName, iv: params.encNameIv },
});
});
await tx.insert(file).values({
path: params.path,
parentId: params.parentId === "root" ? null : params.parentId,
createdAt: new Date(),
userId: params.userId,
mekVersion: params.mekVersion,
contentType: params.contentType,
encDek: params.encDek,
dekVersion: params.dekVersion,
encContentIv: params.encContentIv,
encName: { ciphertext: params.encName, iv: params.encNameIv },
});
},
{ behavior: "exclusive" },
);
};
export const getAllFilesByParent = async (userId: number, parentId: DirectoryId) => {
@@ -156,8 +174,7 @@ export const getAllFilesByParent = async (userId: number, parentId: DirectoryId)
eq(file.userId, userId),
parentId === "root" ? isNull(file.parentId) : eq(file.parentId, parentId),
),
)
.execute();
);
};
export const getFile = async (userId: number, fileId: number) => {
@@ -165,7 +182,7 @@ export const getFile = async (userId: number, fileId: number) => {
.select()
.from(file)
.where(and(eq(file.userId, userId), eq(file.id, fileId)))
.execute();
.limit(1);
return res[0] ?? null;
};
@@ -176,19 +193,35 @@ export const setFileEncName = async (
encName: string,
encNameIv: string,
) => {
const res = await db
.update(file)
.set({ encName: { ciphertext: encName, iv: encNameIv } })
.where(and(eq(file.userId, userId), eq(file.id, fileId), eq(file.dekVersion, dekVersion)))
.execute();
return res.changes > 0;
await db.transaction(
async (tx) => {
const files = await tx
.select({ version: file.dekVersion })
.from(file)
.where(and(eq(file.userId, userId), eq(file.id, fileId)))
.limit(1);
if (!files[0]) {
throw new IntegrityError("File not found");
} else if (files[0].version.getTime() !== dekVersion.getTime()) {
throw new IntegrityError("Invalid DEK version");
}
await tx
.update(file)
.set({ encName: { ciphertext: encName, iv: encNameIv } })
.where(and(eq(file.userId, userId), eq(file.id, fileId)));
},
{ behavior: "exclusive" },
);
};
export const unregisterFile = async (userId: number, fileId: number) => {
const res = await db
const files = await db
.delete(file)
.where(and(eq(file.userId, userId), eq(file.id, fileId)))
.returning({ path: file.path })
.execute();
return res[0]?.path ?? null;
.returning({ path: file.path });
if (!files[0]) {
throw new IntegrityError("File not found");
}
return files[0].path;
};