⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(import): hold the project lock only at commit
Andreja0e53ce41b5a
diff --git a/apps/api/src/import/runs/mark-stale-runs.test.ts b/apps/api/src/import/runs/mark-stale-runs.test.tsnew file mode 100644index 000000000..0da92ed1f--- /dev/null+++ b/apps/api/src/import/runs/mark-stale-runs.test.ts@@ -0,0 +1,78 @@+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { pendingRunProject } from "../import-run-project";+import { markStaleRuns } from "./mark-stale-runs";+import type { ImportRunRow } from "./to-import-run-response";++const mocks = vi.hoisted(() => ({+ updates: [] as string[],+ failFor: new Set<string>(),+ logImportError: vi.fn(),+}));++vi.mock("../../database", () => ({+ default: {+ update: () => ({+ set: (values: { status?: string }) => ({+ where: async () => {+ const id = mocks.updates.length === 0 ? "first" : "next";+ mocks.updates.push(values.status ?? "");+ if (mocks.failFor.has(id)) throw new Error("connection reset");+ },+ }),+ }),+ },+}));++vi.mock("../log-import-error", () => ({+ logImportError: mocks.logImportError,+}));++const now = new Date("2026-10-01T10:10:00.000Z");++function row(overrides: Partial<ImportRunRow> = {}): ImportRunRow {+ return {+ id: "run-1",+ workspaceId: "workspace-1",+ userId: "user-1",+ source: "planka",+ status: "running",+ includeComments: true,+ message: null,+ projects: [pendingRunProject("a", "Alpha")],+ error: null,+ heartbeatAt: new Date("2026-10-01T10:00:00.000Z"),+ createdAt: new Date("2026-10-01T09:59:00.000Z"),+ finishedAt: null,+ ...overrides,+ };+}++describe("markStaleRuns", () => {+ beforeEach(() => {+ mocks.updates = [];+ mocks.failFor = new Set();+ mocks.logImportError.mockReset();+ });++ it("marks stale running runs as failed and skips fresh ones", async () => {+ await markStaleRuns(+ [row(), row({ id: "run-2", heartbeatAt: new Date(now) })],+ now,+ );++ expect(mocks.updates).toEqual(["failed"]);+ expect(mocks.logImportError).not.toHaveBeenCalled();+ });++ it("logs a failed repair instead of throwing", async () => {+ mocks.failFor.add("first");++ await expect(markStaleRuns([row()], now)).resolves.toBeUndefined();++ expect(mocks.logImportError).toHaveBeenCalledWith(+ "Failed to mark a stale import run",+ "run-1",+ expect.any(Error),+ );+ });+});diff --git a/apps/api/src/import/runs/mark-stale-runs.ts b/apps/api/src/import/runs/mark-stale-runs.tsindex 2ba8cca30..c7e2248b3 100644--- a/apps/api/src/import/runs/mark-stale-runs.ts+++ b/apps/api/src/import/runs/mark-stale-runs.ts@@ -1,6 +1,7 @@import { and, eq, lt } from "drizzle-orm";import db from "../../database";import { importRunTable } from "../../database/schema";+import { logImportError } from "../log-import-error";import {type ImportRunRow,interruptedRun,@@ -10,20 +11,29 @@ import {export async function markStaleRuns(rows: readonly ImportRunRow[], now: Date) {const cutoff = new Date(now.getTime() - STALE_RUN_MS);- await Promise.all(- rows- .filter((row) => isStaleRun(row, now))- .map((row) =>- db- .update(importRunTable)- .set(interruptedRun(row))- .where(- and(- eq(importRunTable.id, row.id),- eq(importRunTable.status, "running"),- lt(importRunTable.heartbeatAt, cutoff),- ),+ const stale = rows.filter((row) => isStaleRun(row, now));+ const results = await Promise.allSettled(+ stale.map((row) =>+ db+ .update(importRunTable)+ .set(interruptedRun(row))+ .where(+ and(+ eq(importRunTable.id, row.id),+ eq(importRunTable.status, "running"),+ lt(importRunTable.heartbeatAt, cutoff),),- ),+ ),+ ),);+ results.forEach((result, index) => {+ const row = stale[index];+ if (result.status === "rejected" && row) {+ logImportError(+ "Failed to mark a stale import run",+ row.id,+ result.reason,+ );+ }+ });}diff --git a/apps/api/src/import/writer/create-import-project.test.ts b/apps/api/src/import/writer/create-import-project.test.tsindex 0b2c81fc3..c8dd1caf6 100644--- a/apps/api/src/import/writer/create-import-project.test.ts+++ b/apps/api/src/import/writer/create-import-project.test.ts@@ -3,7 +3,9 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test";import { createImportProject } from "./create-import-project";const mocks = vi.hoisted(() => ({- insertProject: vi.fn(),+ insertUnplacedProject: vi.fn(),+ placeProject: vi.fn(),+ steps: [] as string[],transactions: [] as { id: number; outcome: "committed" | "rolled back" }[],}));@@ -25,7 +27,8 @@ vi.mock("../../database", () => ({}));vi.mock("../../project/controllers/insert-project", () => ({- insertProject: mocks.insertProject,+ insertUnplacedProject: mocks.insertUnplacedProject,+ placeProject: mocks.placeProject,}));const input = {@@ -35,57 +38,72 @@ const input = {preferredKey: "WEB",};+function insertsProjects() {+ mocks.insertUnplacedProject.mockImplementation(async (_tx, project) => {+ mocks.steps.push(`insert ${project.slug}`);+ return { id: `project-${project.slug}`, slug: project.slug };+ });+}+describe("createImportProject", () => {beforeEach(() => {- mocks.insertProject.mockReset();+ mocks.insertUnplacedProject.mockReset();+ mocks.placeProject.mockReset();+ mocks.steps = [];mocks.transactions = [];});- it("creates the project and fills it in the same transaction", async () => {- mocks.insertProject.mockImplementation(async (_tx, project) => ({- id: "project-1",- slug: project.slug,- }));- const fill = vi.fn(async () => "filled");+ it("inserts, fills, then places the project in one transaction", async () => {+ insertsProjects();+ mocks.placeProject.mockImplementation(async () => {+ mocks.steps.push("place");+ });+ const fill = vi.fn(async () => {+ mocks.steps.push("fill");+ return "filled";+ });await expect(createImportProject(input, fill)).resolves.toBe("filled");- const [tx] = mocks.insertProject.mock.calls[0] ?? [];- expect(fill).toHaveBeenCalledWith(tx, { id: "project-1", slug: "WEB" });- expect(mocks.insertProject).toHaveBeenCalledWith(tx, {+ expect(mocks.steps).toEqual(["insert WEB", "fill", "place"]);+ const [tx] = mocks.insertUnplacedProject.mock.calls[0] ?? [];+ expect(mocks.insertUnplacedProject).toHaveBeenCalledWith(tx, {workspaceId: "workspace-1",name: "Website",icon: "Layout",slug: "WEB",+ });+ expect(fill).toHaveBeenCalledWith(tx, { id: "project-WEB", slug: "WEB" });+ expect(mocks.placeProject).toHaveBeenCalledWith(tx, {+ workspaceId: "workspace-1",+ projectId: "project-WEB",+ slug: "WEB",userId: "user-1",});expect(mocks.transactions).toEqual([{ id: 1, outcome: "committed" }]);});- it("retries the whole transaction with the next key when the key was taken", async () => {- mocks.insertProject+ it("retries the whole transaction with the next key when placing finds the key taken", async () => {+ insertsProjects();+ mocks.placeProject.mockRejectedValueOnce(new HTTPException(409, { message: "taken" }))- .mockImplementation(async (_tx, project) => ({- id: "project-1",- slug: project.slug,- }));+ .mockResolvedValue(undefined);const fill = vi.fn(async () => "filled");await createImportProject(input, fill);expect(- mocks.insertProject.mock.calls.map(([, project]) => project.slug),+ mocks.insertUnplacedProject.mock.calls.map(([, project]) => project.slug),).toEqual(["WEB", "WEB-2"]);- expect(fill).toHaveBeenCalledTimes(1);- expect(fill).toHaveBeenCalledWith({ id: 2 }, expect.anything());+ expect(fill).toHaveBeenCalledTimes(2);expect(mocks.transactions).toEqual([{ id: 1, outcome: "rolled back" },{ id: 2, outcome: "committed" },]);});- it("rolls the project back when filling it fails", async () => {- mocks.insertProject.mockResolvedValue({ id: "project-1", slug: "WEB" });+ it("rolls the project back and never places it when filling fails", async () => {+ insertsProjects();const failure = new Error("could not write tasks");await expect(@@ -94,6 +112,7 @@ describe("createImportProject", () => {}),).rejects.toBe(failure);+ expect(mocks.placeProject).not.toHaveBeenCalled();expect(mocks.transactions).toEqual([{ id: 1, outcome: "rolled back" }]);});});diff --git a/apps/api/src/import/writer/create-import-project.ts b/apps/api/src/import/writer/create-import-project.tsindex b5d1f29dd..b34921b6b 100644--- a/apps/api/src/import/writer/create-import-project.ts+++ b/apps/api/src/import/writer/create-import-project.ts@@ -1,12 +1,17 @@import { eq } from "drizzle-orm";import db from "../../database";import { projectTable } from "../../database/schema";-import { insertProject } from "../../project/controllers/insert-project";+import {+ insertUnplacedProject,+ placeProject,+} from "../../project/controllers/insert-project";import { createWithUniqueKey } from "./create-with-unique-key";type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];-type CreatedProject = NonNullable<Awaited<ReturnType<typeof insertProject>>>;+type CreatedProject = NonNullable<+ Awaited<ReturnType<typeof insertUnplacedProject>>+>;export type ImportProjectInput = {workspaceId: string;@@ -29,15 +34,21 @@ export async function createImportProject<T>(existing.map((row) => row.slug),(slug) =>db.transaction(async (tx) => {- const project = await insertProject(tx, {+ const project = await insertUnplacedProject(tx, {workspaceId,name,icon: "Layout",slug,- userId,});if (!project) throw new Error("Failed to create the imported project");- return fill(tx, project);+ const result = await fill(tx, project);+ await placeProject(tx, {+ workspaceId,+ projectId: project.id,+ slug,+ userId,+ });+ return result;}),{ preferredKey },);diff --git a/apps/api/src/project/controllers/insert-project.ts b/apps/api/src/project/controllers/insert-project.tsindex fe8065954..3e4cfc5d7 100644--- a/apps/api/src/project/controllers/insert-project.ts+++ b/apps/api/src/project/controllers/insert-project.ts@@ -1,9 +1,12 @@-import { eq, max, sql } from "drizzle-orm";-import { HTTPException } from "hono/http-exception";+import { eq } from "drizzle-orm";import type db from "../../database";import { columnTable, projectTable } from "../../database/schema";import { grantProjectToRestrictedMember } from "../../project-access/grant-project-to-restricted-member";-import { findProjectKeyConflict, projectKeyTakenMessage } from "../project-key";+import {+ assertProjectKeyAvailable,+ lockProjectOrdering,+ nextProjectPosition,+} from "./project-placement";type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];@@ -15,6 +18,13 @@ export type NewProject = {userId: string;};+export type ProjectPlacement = {+ workspaceId: string;+ projectId: string;+ slug: string;+ userId: string;+};+export const DEFAULT_PROJECT_COLUMNS = [{ name: "To Do", slug: "to-do", position: 0, isFinal: false },{ name: "In Progress", slug: "in-progress", position: 1, isFinal: false },@@ -22,6 +32,18 @@ export const DEFAULT_PROJECT_COLUMNS = [{ name: "Done", slug: "done", position: 3, isFinal: true },] as const;+async function seedDefaultColumns(tx: Transaction, projectId: string) {+ for (const col of DEFAULT_PROJECT_COLUMNS) {+ await tx.insert(columnTable).values({+ projectId,+ name: col.name,+ slug: col.slug,+ position: col.position,+ isFinal: col.isFinal,+ });+ }+}+export async function insertProject(tx: Transaction,{ workspaceId, name, icon, slug, userId }: NewProject,@@ -30,45 +52,19 @@ export async function insertProject(// creates can read the same max(position) and land on the same slot, and a// create can interleave with a reorder's renumber. `reorderProjects` takes// the same lock with the same key.- await tx.execute(- sql`SELECT pg_advisory_xact_lock(1524, hashtext(${workspaceId}))`,- );-- const keyConflict = await findProjectKeyConflict(tx, workspaceId, slug);- if (keyConflict) {- throw new HTTPException(409, {- message: projectKeyTakenMessage(slug, keyConflict.name),- });- }+ await lockProjectOrdering(tx, workspaceId);+ await assertProjectKeyAvailable(tx, workspaceId, slug);// New projects go to the bottom of the workspace's ordering.- const [{ maxPosition } = { maxPosition: null }] = await tx- .select({ maxPosition: max(projectTable.position) })- .from(projectTable)- .where(eq(projectTable.workspaceId, workspaceId));+ const position = await nextProjectPosition(tx, workspaceId);const [createdProject] = await tx.insert(projectTable)- .values({- workspaceId,- name,- icon,- slug,- position: maxPosition === null ? 0 : maxPosition + 1,- })+ .values({ workspaceId, name, icon, slug, position }).returning();if (createdProject) {- for (const col of DEFAULT_PROJECT_COLUMNS) {- await tx.insert(columnTable).values({- projectId: createdProject.id,- name: col.name,- slug: col.slug,- position: col.position,- isFinal: col.isFinal,- });- }-+ await seedDefaultColumns(tx, createdProject.id);await grantProjectToRestrictedMember(tx, {workspaceId,userId,@@ -78,3 +74,32 @@ export async function insertProject(return createdProject;}++export async function insertUnplacedProject(+ tx: Transaction,+ { workspaceId, name, icon, slug }: Omit<NewProject, "userId">,+) {+ const [createdProject] = await tx+ .insert(projectTable)+ .values({ workspaceId, name, icon, slug, position: 0 })+ .returning();++ if (createdProject) await seedDefaultColumns(tx, createdProject.id);+ return createdProject;+}++export async function placeProject(+ tx: Transaction,+ { workspaceId, projectId, slug, userId }: ProjectPlacement,+) {+ await lockProjectOrdering(tx, workspaceId);+ await assertProjectKeyAvailable(tx, workspaceId, slug, projectId);+ const position = await nextProjectPosition(tx, workspaceId, projectId);++ await tx+ .update(projectTable)+ .set({ position })+ .where(eq(projectTable.id, projectId));++ await grantProjectToRestrictedMember(tx, { workspaceId, userId, projectId });+}diff --git a/apps/api/src/project/controllers/project-placement.ts b/apps/api/src/project/controllers/project-placement.tsnew file mode 100644index 000000000..083616406--- /dev/null+++ b/apps/api/src/project/controllers/project-placement.ts@@ -0,0 +1,49 @@+import { and, eq, max, ne, sql } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import type db from "../../database";+import { projectTable } from "../../database/schema";+import { findProjectKeyConflict, projectKeyTakenMessage } from "../project-key";++type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];++export async function lockProjectOrdering(+ tx: Transaction,+ workspaceId: string,+) {+ await tx.execute(+ sql`SELECT pg_advisory_xact_lock(1524, hashtext(${workspaceId}))`,+ );+}++export async function assertProjectKeyAvailable(+ tx: Transaction,+ workspaceId: string,+ slug: string,+ excludeProjectId?: string,+) {+ const keyConflict = await findProjectKeyConflict(tx, workspaceId, slug, {+ excludeProjectId,+ });+ if (keyConflict) {+ throw new HTTPException(409, {+ message: projectKeyTakenMessage(slug, keyConflict.name),+ });+ }+}++export async function nextProjectPosition(+ tx: Transaction,+ workspaceId: string,+ excludeProjectId?: string,+) {+ const [{ maxPosition } = { maxPosition: null }] = await tx+ .select({ maxPosition: max(projectTable.position) })+ .from(projectTable)+ .where(+ and(+ eq(projectTable.workspaceId, workspaceId),+ excludeProjectId ? ne(projectTable.id, excludeProjectId) : undefined,+ ),+ );+ return maxPosition === null ? 0 : maxPosition + 1;+}