Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(tasks): lock mutation snapshots with field writes

Tin43e0b3795313
diff --git a/apps/api/src/task/controllers/bulk-update-tasks.ts b/apps/api/src/task/controllers/bulk-update-tasks.ts
index 7d7701b7e..0b209267a 100644
--- a/apps/api/src/task/controllers/bulk-update-tasks.ts
+++ b/apps/api/src/task/controllers/bulk-update-tasks.ts
@@ -195,19 +195,43 @@ async function bulkUpdateTasks({
}
assertValidPriority(value);
- const result = await db
- .update(taskTable)
- .set({ priority: value })
- .where(inArray(taskTable.id, foundIds));
-
- updatedCount = result.rowCount ?? foundIds.length;
-
- for (const task of tasks)
+ const before = await db.transaction(async (tx) => {
+ const locked = await tx
+ .select({
+ id: taskTable.id,
+ projectId: taskTable.projectId,
+ title: taskTable.title,
+ userId: taskTable.userId,
+ priority: taskTable.priority,
+ })
+ .from(taskTable)
+ .where(inArray(taskTable.id, foundIds))
+ .orderBy(asc(taskTable.id))
+ .for("update");
+ const originalProjects = new Map(
+ tasks.map((task) => [task.id, task.projectId]),
+ );
+ if (
+ locked.length !== foundIds.length ||
+ locked.some(
+ (task) => task.projectId !== originalProjects.get(task.id),
+ )
+ )
+ throw new HTTPException(409, {
+ message: "Tasks changed projects; retry the operation",
+ });
+ await tx
+ .update(taskTable)
+ .set({ priority: value })
+ .where(inArray(taskTable.id, foundIds));
+ return locked;
+ });
+ updatedCount = before.length;
+ for (const task of before)
await publishTaskMutation(
task,
{
...task,
- description: null,
priority: value,
},
userId,
@@ -229,17 +253,42 @@ async function bulkUpdateTasks({
where: eq(userTable.id, assigneeId),
})
: undefined;
- const result = await db
- .update(taskTable)
- .set({ userId: assigneeId })
- .where(inArray(taskTable.id, foundIds));
- updatedCount = result.rowCount ?? foundIds.length;
- for (const task of tasks)
+ const before = await db.transaction(async (tx) => {
+ const locked = await tx
+ .select({
+ id: taskTable.id,
+ projectId: taskTable.projectId,
+ title: taskTable.title,
+ userId: taskTable.userId,
+ })
+ .from(taskTable)
+ .where(inArray(taskTable.id, foundIds))
+ .orderBy(asc(taskTable.id))
+ .for("update");
+ const originalProjects = new Map(
+ tasks.map((task) => [task.id, task.projectId]),
+ );
+ if (
+ locked.length !== foundIds.length ||
+ locked.some(
+ (task) => task.projectId !== originalProjects.get(task.id),
+ )
+ )
+ throw new HTTPException(409, {
+ message: "Tasks changed projects; retry the operation",
+ });
+ await tx
+ .update(taskTable)
+ .set({ userId: assigneeId })
+ .where(inArray(taskTable.id, foundIds));
+ return locked;
+ });
+ updatedCount = before.length;
+ for (const task of before)
await publishTaskMutation(
task,
{
...task,
- description: null,
userId: assigneeId,
},
userId,
diff --git a/apps/api/src/task/controllers/update-task-assignee.ts b/apps/api/src/task/controllers/update-task-assignee.ts
index 3d2d9f20a..56fdba4cf 100644
--- a/apps/api/src/task/controllers/update-task-assignee.ts
+++ b/apps/api/src/task/controllers/update-task-assignee.ts
@@ -1,6 +1,6 @@
import { eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
-import db from "../../database";
+import { withLockedTask } from "./with-locked-task";
import { taskTable } from "../../database/schema";
import { publishTaskMutation } from "./task-mutation-effects";
import {
@@ -17,39 +17,36 @@ async function updateTaskAssignee({
userId: string | null;
currentUserId: string;
}) {
- const existingTask = await db.query.taskTable.findFirst({
- where: eq(taskTable.id, id),
- });
-
- if (!existingTask) {
- throw new HTTPException(404, {
- message: "Task not found",
- });
- }
-
- const nextAssigneeId = userId?.trim() || null;
- if (existingTask.userId === nextAssigneeId) {
- return existingTask;
- }
-
- if (nextAssigneeId) {
- await assertAssignableUser(
- nextAssigneeId,
- await getProjectWorkspaceId(existingTask.projectId),
- );
- }
-
- const [updatedTask] = await db
- .update(taskTable)
- .set({ userId: nextAssigneeId })
- .where(eq(taskTable.id, id))
- .returning();
-
- if (!updatedTask) {
- throw new HTTPException(500, {
- message: "Failed to update task assignee",
- });
- }
+ const { before: existingTask, after: updatedTask } = await withLockedTask(
+ id,
+ async (tx, existingTask) => {
+ const nextAssigneeId = userId?.trim() || null;
+ if (existingTask.userId === nextAssigneeId) {
+ return existingTask;
+ }
+
+ if (nextAssigneeId) {
+ await assertAssignableUser(
+ nextAssigneeId,
+ await getProjectWorkspaceId(existingTask.projectId),
+ );
+ }
+
+ const [updatedTask] = await tx
+ .update(taskTable)
+ .set({ userId: nextAssigneeId })
+ .where(eq(taskTable.id, id))
+ .returning();
+
+ if (!updatedTask) {
+ throw new HTTPException(500, {
+ message: "Failed to update task assignee",
+ });
+ }
+
+ return updatedTask;
+ },
+ );
await publishTaskMutation(existingTask, updatedTask, currentUserId, {
fields: ["userId"],
diff --git a/apps/api/src/task/controllers/update-task-description.ts b/apps/api/src/task/controllers/update-task-description.ts
index 810f72047..0f102f333 100644
--- a/apps/api/src/task/controllers/update-task-description.ts
+++ b/apps/api/src/task/controllers/update-task-description.ts
@@ -1,6 +1,6 @@
import { eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
-import db from "../../database";
+import { withLockedTask } from "./with-locked-task";
import { taskTable } from "../../database/schema";
import { publishTaskMutation } from "./task-mutation-effects";
@@ -13,27 +13,24 @@ async function updateTaskDescription({
description: string;
currentUserId: string;
}) {
- const existingTask = await db.query.taskTable.findFirst({
- where: eq(taskTable.id, id),
- });
-
- if (!existingTask) {
- throw new HTTPException(404, {
- message: "Task not found",
- });
- }
+ const { before: existingTask, after: updatedTask } = await withLockedTask(
+ id,
+ async (tx) => {
+ const [updatedTask] = await tx
+ .update(taskTable)
+ .set({ description })
+ .where(eq(taskTable.id, id))
+ .returning();
- const [updatedTask] = await db
- .update(taskTable)
- .set({ description })
- .where(eq(taskTable.id, id))
- .returning();
+ if (!updatedTask) {
+ throw new HTTPException(500, {
+ message: "Failed to update task description",
+ });
+ }
- if (!updatedTask) {
- throw new HTTPException(500, {
- message: "Failed to update task description",
- });
- }
+ return updatedTask;
+ },
+ );
await publishTaskMutation(existingTask, updatedTask, currentUserId, {
fields: ["description"],
diff --git a/apps/api/src/task/controllers/update-task-priority.ts b/apps/api/src/task/controllers/update-task-priority.ts
index 942e55775..9042c5abc 100644
--- a/apps/api/src/task/controllers/update-task-priority.ts
+++ b/apps/api/src/task/controllers/update-task-priority.ts
@@ -1,6 +1,6 @@
import { eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
-import db from "../../database";
+import { withLockedTask } from "./with-locked-task";
import { taskTable } from "../../database/schema";
import { publishTaskMutation } from "./task-mutation-effects";
@@ -13,27 +13,24 @@ async function updateTaskPriority({
priority: string;
currentUserId: string;
}) {
- const existingTask = await db.query.taskTable.findFirst({
- where: eq(taskTable.id, id),
- });
-
- if (!existingTask) {
- throw new HTTPException(404, {
- message: "Task not found",
- });
- }
+ const { before: existingTask, after: updatedTask } = await withLockedTask(
+ id,
+ async (tx) => {
+ const [updatedTask] = await tx
+ .update(taskTable)
+ .set({ priority })
+ .where(eq(taskTable.id, id))
+ .returning();
- const [updatedTask] = await db
- .update(taskTable)
- .set({ priority })
- .where(eq(taskTable.id, id))
- .returning();
+ if (!updatedTask) {
+ throw new HTTPException(500, {
+ message: "Failed to update task priority",
+ });
+ }
- if (!updatedTask) {
- throw new HTTPException(500, {
- message: "Failed to update task priority",
- });
- }
+ return updatedTask;
+ },
+ );
await publishTaskMutation(existingTask, updatedTask, currentUserId, {
fields: ["priority"],
diff --git a/apps/api/src/task/controllers/update-task-status.ts b/apps/api/src/task/controllers/update-task-status.ts
index 633835b07..d9dda6740 100644
--- a/apps/api/src/task/controllers/update-task-status.ts
+++ b/apps/api/src/task/controllers/update-task-status.ts
@@ -1,6 +1,6 @@
import { and, eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
-import db from "../../database";
+import { withLockedTask } from "./with-locked-task";
import { columnTable, taskTable } from "../../database/schema";
import { publishTaskMutation } from "./task-mutation-effects";
import { assertValidTaskStatus } from "../validate-task-fields";
@@ -14,36 +14,33 @@ async function updateTaskStatus({
status: string;
currentUserId: string;
}) {
- const existingTask = await db.query.taskTable.findFirst({
- where: eq(taskTable.id, id),
- });
-
- if (!existingTask) {
- throw new HTTPException(404, {
- message: "Task not found",
- });
- }
-
- await assertValidTaskStatus(status, existingTask.projectId);
-
- const column = await db.query.columnTable.findFirst({
- where: and(
- eq(columnTable.projectId, existingTask.projectId),
- eq(columnTable.slug, status),
- ),
- });
-
- const [updatedTask] = await db
- .update(taskTable)
- .set({ status, columnId: column?.id ?? null })
- .where(eq(taskTable.id, id))
- .returning();
-
- if (!updatedTask) {
- throw new HTTPException(500, {
- message: "Failed to update task status",
- });
- }
+ const { before: existingTask, after: updatedTask } = await withLockedTask(
+ id,
+ async (tx, existingTask) => {
+ await assertValidTaskStatus(status, existingTask.projectId);
+
+ const column = await tx.query.columnTable.findFirst({
+ where: and(
+ eq(columnTable.projectId, existingTask.projectId),
+ eq(columnTable.slug, status),
+ ),
+ });
+
+ const [updatedTask] = await tx
+ .update(taskTable)
+ .set({ status, columnId: column?.id ?? null })
+ .where(eq(taskTable.id, id))
+ .returning();
+
+ if (!updatedTask) {
+ throw new HTTPException(500, {
+ message: "Failed to update task status",
+ });
+ }
+
+ return updatedTask;
+ },
+ );
await publishTaskMutation(existingTask, updatedTask, currentUserId, {
fields: ["status"],
diff --git a/apps/api/src/task/controllers/with-locked-task.ts b/apps/api/src/task/controllers/with-locked-task.ts
new file mode 100644
index 000000000..c856ed405
--- /dev/null
+++ b/apps/api/src/task/controllers/with-locked-task.ts
@@ -0,0 +1,23 @@
+import { eq } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import { taskTable } from "../../database/schema";
+
+type TaskTransaction = Parameters<Parameters<typeof db.transaction>[0]>[0];
+export async function withLockedTask<T>(
+ id: string,
+ mutate: (
+ tx: TaskTransaction,
+ before: typeof taskTable.$inferSelect,
+ ) => Promise<T>,
+) {
+ return db.transaction(async (tx) => {
+ const [before] = await tx
+ .select()
+ .from(taskTable)
+ .where(eq(taskTable.id, id))
+ .for("update");
+ if (!before) throw new HTTPException(404, { message: "Task not found" });
+ return { before, after: await mutate(tx, before) };
+ });
+}
diff --git a/tests/api-integration/task-mutation-parity.test.ts b/tests/api-integration/task-mutation-parity.test.ts
index df144e3dc..cd0283b96 100644
--- a/tests/api-integration/task-mutation-parity.test.ts
+++ b/tests/api-integration/task-mutation-parity.test.ts
@@ -1,6 +1,6 @@
import updateTaskPriority from "../../apps/api/src/task/controllers/update-task-priority";
import { eq } from "drizzle-orm";
-import { beforeEach, expect, it, vi } from "vite-plus/test";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
import db, { getDatabase, schema } from "../../apps/api/src/database";
import updateTask from "../../apps/api/src/task/controllers/update-task";
import bulkUpdateTasks from "../../apps/api/src/task/controllers/bulk-update-tasks";
@@ -15,6 +15,7 @@ beforeEach(async () => {
await resetTestDatabase();
vi.clearAllMocks();
});
+afterEach(() => vi.restoreAllMocks());
it("full updates store title history, assignment events and reset reminders together", async () => {
const { user, workspace } = await createWorkspaceMember();
const { project } = await createProjectFixture({ workspaceId: workspace.id });
@@ -103,17 +104,14 @@ it("a single-field write does not attribute another concurrent field change to i
.insert(schema.taskTable)
.values({ projectId: project.id, title: "old", priority: "low" })
.returning();
- const findFirst = getDatabase().query.taskTable.findFirst.bind(
- getDatabase().query.taskTable,
- );
- vi.spyOn(getDatabase().query.taskTable, "findFirst").mockImplementationOnce(
- async (query) => {
- const before = await findFirst(query);
+ const transaction = db.transaction.bind(db);
+ vi.spyOn(getDatabase(), "transaction").mockImplementationOnce(
+ async (apply, config) => {
await db
.update(schema.taskTable)
.set({ title: "concurrent title" })
.where(eq(schema.taskTable.id, task.id));
- return before;
+ return transaction(apply, config);
},
);
await updateTaskPriority({
@@ -197,3 +195,48 @@ it("bulk assignment resolves the assignee once and bulk status refreshes each pr
publish.mock.calls.filter(([type]) => type === "task-relation.refresh"),
).toHaveLength(1);
});
+
+it.each(["single", "bulk"])(
+ "%s priority writes publish the actual overwritten priority",
+ async (mode) => {
+ const { user, workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ title: "priority race",
+ priority: "low",
+ })
+ .returning();
+ const transaction = db.transaction.bind(db);
+ vi.spyOn(getDatabase(), "transaction").mockImplementationOnce(
+ async (apply, config) => {
+ await db
+ .update(schema.taskTable)
+ .set({ priority: "high" })
+ .where(eq(schema.taskTable.id, task.id));
+ return transaction(apply, config);
+ },
+ );
+ if (mode === "single")
+ await updateTaskPriority({
+ id: task.id,
+ priority: "low",
+ currentUserId: user.id,
+ });
+ else
+ await bulkUpdateTasks({
+ taskIds: [task.id],
+ operation: "updatePriority",
+ value: "low",
+ userId: user.id,
+ });
+ expect(publish).toHaveBeenCalledWith(
+ "task.priority_changed",
+ expect.objectContaining({ oldPriority: "high", newPriority: "low" }),
+ );
+ },
+);