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(import): address code review findings

Andrej3769f9f1dc51
diff --git a/apps/api/package.json b/apps/api/package.json
index ac00e06b8..2b58404b3 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -34,6 +34,8 @@
"@hono/node-ws": "^1.3.1",
"@hono/zod-openapi": "^1.6.3",
"@kaneo/email": "workspace:*",
+ "@kaneo/importers": "workspace:*",
+ "@kaneo/mcp": "workspace:*",
"@kaneo/permissions": "workspace:*",
"@modelcontextprotocol/sdk": "^1.31.0",
"@modelcontextprotocol/server": "2.2.0",
@@ -53,10 +55,9 @@
"ioredis": "^6.0.0",
"octokit": "^5.0.5",
"pg": "^8.23.1",
+ "undici": "^7.30.0",
"valibot": "^1.5.0",
- "zod": "^4.6.5",
- "@kaneo/mcp": "workspace:*",
- "@kaneo/importers": "workspace:*"
+ "zod": "^4.6.5"
},
"devDependencies": {
"@types/node": "^26.6.2",
@@ -65,7 +66,7 @@
"esbuild": "0.28.2",
"tsx": "^4.23.15",
"typescript": "^7.0.2",
- "vitest": "catalog:",
- "vite-plus": "catalog:"
+ "vite-plus": "catalog:",
+ "vitest": "catalog:"
}
}
diff --git a/apps/api/src/import/active-imports.test.ts b/apps/api/src/import/active-imports.test.ts
new file mode 100644
index 000000000..b2dc8f20f
--- /dev/null
+++ b/apps/api/src/import/active-imports.test.ts
@@ -0,0 +1,87 @@
+import { HTTPException } from "hono/http-exception";
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+type Registry = typeof import("./active-imports");
+
+let registry: Registry;
+
+function reserve() {
+ const slot = registry.reserveImportSlot();
+ if (!slot) throw new Error("expected a free slot");
+ return slot;
+}
+
+async function hasSettled(promise: Promise<unknown>) {
+ let settled = false;
+ void promise.then(() => {
+ settled = true;
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ return settled;
+}
+
+describe("active imports", () => {
+ beforeEach(async () => {
+ vi.resetModules();
+ registry = await import("./active-imports");
+ });
+
+ it("reserves up to the server limit", () => {
+ const first = reserve();
+ for (let count = 1; count < registry.MAX_ACTIVE_IMPORTS; count++) {
+ reserve();
+ }
+
+ expect(registry.reserveImportSlot()).toBeNull();
+
+ registry.releaseImportSlot(first);
+ expect(registry.reserveImportSlot()).not.toBeNull();
+ });
+
+ it("settles a reservation once its job is attached", async () => {
+ const slot = reserve();
+
+ expect(await hasSettled(slot.settled)).toBe(false);
+
+ registry.trackImportJob(slot, "run-1", new Promise(() => {}), () => []);
+
+ expect(await hasSettled(slot.settled)).toBe(true);
+ expect(registry.activeImportSlots()).toEqual([slot]);
+ });
+
+ it("settles a reservation that is released without a job", async () => {
+ const slot = reserve();
+
+ registry.releaseImportSlot(slot);
+
+ expect(await hasSettled(slot.settled)).toBe(true);
+ expect(registry.activeImportSlots()).toEqual([]);
+ });
+
+ it("frees the slot when the job finishes", async () => {
+ const slot = reserve();
+
+ registry.trackImportJob(slot, "run-1", Promise.resolve(), () => []);
+ await registry.waitForActiveImports();
+
+ expect(registry.activeImportSlots()).toEqual([]);
+ });
+
+ it("refuses new reservations once the server is shutting down", () => {
+ registry.stopAcceptingImports();
+
+ let refused: unknown;
+ try {
+ registry.reserveImportSlot();
+ } catch (error) {
+ refused = error;
+ }
+
+ expect(refused).toBeInstanceOf(HTTPException);
+ expect(refused).toMatchObject({
+ status: 503,
+ message: "Kaneo is restarting. Start the import again in a minute.",
+ });
+ expect(registry.activeImportSlots()).toEqual([]);
+ });
+});
diff --git a/apps/api/src/import/active-imports.ts b/apps/api/src/import/active-imports.ts
index 204993e45..884bb0727 100644
--- a/apps/api/src/import/active-imports.ts
+++ b/apps/api/src/import/active-imports.ts
@@ -1,29 +1,44 @@
+import { HTTPException } from "hono/http-exception";
import type { ImportRunProject } from "./import-run-project";
export const MAX_ACTIVE_IMPORTS = 2;
+export const RESTARTING_MESSAGE =
+ "Kaneo is restarting. Start the import again in a minute.";
+
export type ImportSlot = {
controller: AbortController;
runId: string | null;
job: Promise<void> | null;
projects: () => ImportRunProject[];
+ settled: Promise<void>;
};
-const slots = new Set<ImportSlot>();
+const slots = new Map<ImportSlot, () => void>();
+let shuttingDown = false;
export function reserveImportSlot(): ImportSlot | null {
+ if (shuttingDown) {
+ throw new HTTPException(503, { message: RESTARTING_MESSAGE });
+ }
if (slots.size >= MAX_ACTIVE_IMPORTS) return null;
+
+ let settle: () => void = () => {};
const slot: ImportSlot = {
controller: new AbortController(),
runId: null,
job: null,
projects: () => [],
+ settled: new Promise<void>((resolve) => {
+ settle = resolve;
+ }),
};
- slots.add(slot);
+ slots.set(slot, settle);
return slot;
}
export function releaseImportSlot(slot: ImportSlot) {
+ slots.get(slot)?.();
slots.delete(slot);
}
@@ -36,10 +51,15 @@ export function trackImportJob(
slot.runId = runId;
slot.projects = projects;
slot.job = job.finally(() => releaseImportSlot(slot));
+ slots.get(slot)?.();
+}
+
+export function stopAcceptingImports() {
+ shuttingDown = true;
}
export function activeImportSlots(): ImportSlot[] {
- return [...slots];
+ return [...slots.keys()];
}
export async function waitForActiveImports() {
diff --git a/apps/api/src/import/blocked-destination-error.ts b/apps/api/src/import/blocked-destination-error.ts
new file mode 100644
index 000000000..71272bebd
--- /dev/null
+++ b/apps/api/src/import/blocked-destination-error.ts
@@ -0,0 +1,21 @@
+export const BLOCKED_DESTINATION_CODE = "EIMPORTDESTINATION";
+
+const MAX_CAUSE_DEPTH = 5;
+
+export function blockedDestinationError() {
+ return Object.assign(
+ new Error("Import destination resolves to a non-routable address"),
+ { code: BLOCKED_DESTINATION_CODE },
+ );
+}
+
+export function isBlockedDestinationError(error: unknown) {
+ let current = error;
+ for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {
+ if ((current as { code?: unknown }).code === BLOCKED_DESTINATION_CODE) {
+ return true;
+ }
+ current = (current as { cause?: unknown }).cause;
+ }
+ return false;
+}
diff --git a/apps/api/src/import/controllers/get-import-run.ts b/apps/api/src/import/controllers/get-import-run.ts
index 1ab33e806..1bfd692fd 100644
--- a/apps/api/src/import/controllers/get-import-run.ts
+++ b/apps/api/src/import/controllers/get-import-run.ts
@@ -2,6 +2,7 @@ import { and, eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { importRunTable } from "../../database/schema";
+import { markStaleRuns } from "../runs/mark-stale-runs";
import { toImportRunResponse } from "../runs/to-import-run-response";
async function getImportRun(workspaceId: string, runId: string) {
@@ -20,7 +21,10 @@ async function getImportRun(workspaceId: string, runId: string) {
throw new HTTPException(404, { message: "Import not found" });
}
- return { run: toImportRunResponse(row) };
+ const now = new Date();
+ await markStaleRuns([row], now);
+
+ return { run: toImportRunResponse(row, now) };
}
export default getImportRun;
diff --git a/apps/api/src/import/destination-fetch.ts b/apps/api/src/import/destination-fetch.ts
new file mode 100644
index 000000000..56bee62c0
--- /dev/null
+++ b/apps/api/src/import/destination-fetch.ts
@@ -0,0 +1,13 @@
+import type { FetchLike } from "@kaneo/importers";
+import { Agent, fetch, type RequestInit as UndiciRequestInit } from "undici";
+import { createDestinationLookup } from "./destination-lookup";
+
+const agent = new Agent({ connect: { lookup: createDestinationLookup() } });
+
+export const destinationFetch: FetchLike = async (input, init) => {
+ const response = await fetch(input, {
+ ...(init as UndiciRequestInit),
+ dispatcher: agent,
+ });
+ return response as unknown as Response;
+};
diff --git a/apps/api/src/import/destination-lookup.test.ts b/apps/api/src/import/destination-lookup.test.ts
new file mode 100644
index 000000000..398458937
--- /dev/null
+++ b/apps/api/src/import/destination-lookup.test.ts
@@ -0,0 +1,116 @@
+import type { LookupAddress } from "node:dns";
+import type { LookupFunction } from "node:net";
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vite-plus/test";
+import { BLOCKED_DESTINATION_CODE } from "./blocked-destination-error";
+import { createDestinationLookup, type ResolveAll } from "./destination-lookup";
+
+const PUBLIC_V4 = { address: "93.184.216.34", family: 4 };
+const PUBLIC_V6 = { address: "2606:2800:220:1:248:1893:25c8:1946", family: 6 };
+const PRIVATE_V4 = { address: "10.0.0.5", family: 4 };
+
+function resolver(addresses: LookupAddress[]) {
+ return vi.fn<ResolveAll>((_hostname, _options, callback) => {
+ callback(null, addresses);
+ });
+}
+
+function lookupAll(lookup: LookupFunction, hostname: string) {
+ return new Promise<unknown>((resolve, reject) => {
+ lookup(hostname, { all: true }, (error, addresses) =>
+ error ? reject(error) : resolve(addresses),
+ );
+ });
+}
+
+function lookupOne(lookup: LookupFunction, hostname: string) {
+ return new Promise<unknown>((resolve, reject) => {
+ lookup(hostname, { family: 0 }, (error, address, family) =>
+ error ? reject(error) : resolve({ address, family }),
+ );
+ });
+}
+
+describe("createDestinationLookup", () => {
+ beforeEach(() => {
+ vi.stubEnv("KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS", "");
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("resolves every address in resolver order", async () => {
+ const resolve = resolver([PUBLIC_V4]);
+ const lookup = createDestinationLookup(resolve);
+
+ await lookupOne(lookup, "planka.example.com");
+
+ expect(resolve).toHaveBeenCalledWith(
+ "planka.example.com",
+ expect.objectContaining({ all: true, verbatim: true }),
+ expect.any(Function),
+ );
+ });
+
+ it("passes public addresses through in both callback forms", async () => {
+ const lookup = createDestinationLookup(resolver([PUBLIC_V6, PUBLIC_V4]));
+
+ await expect(lookupAll(lookup, "planka.example.com")).resolves.toEqual([
+ PUBLIC_V6,
+ PUBLIC_V4,
+ ]);
+ await expect(lookupOne(lookup, "planka.example.com")).resolves.toEqual(
+ PUBLIC_V6,
+ );
+ });
+
+ it("refuses a host that resolves to a private address", async () => {
+ const lookup = createDestinationLookup(resolver([PRIVATE_V4]));
+
+ await expect(lookupAll(lookup, "rebind.example.com")).rejects.toMatchObject(
+ { code: BLOCKED_DESTINATION_CODE },
+ );
+ await expect(lookupOne(lookup, "rebind.example.com")).rejects.toMatchObject(
+ { code: BLOCKED_DESTINATION_CODE },
+ );
+ });
+
+ it("refuses a host when any of its addresses is private", async () => {
+ const lookup = createDestinationLookup(
+ resolver([PUBLIC_V4, { address: "::ffff:127.0.0.1", family: 6 }]),
+ );
+
+ await expect(lookupOne(lookup, "mixed.example.com")).rejects.toMatchObject({
+ code: BLOCKED_DESTINATION_CODE,
+ });
+ });
+
+ it("lets private addresses through when the instance opts in", async () => {
+ vi.stubEnv("KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS", "true");
+ const lookup = createDestinationLookup(resolver([PRIVATE_V4]));
+
+ await expect(lookupOne(lookup, "planka.internal")).resolves.toEqual(
+ PRIVATE_V4,
+ );
+ });
+
+ it("passes resolver failures through", async () => {
+ const failure = Object.assign(new Error("getaddrinfo ENOTFOUND"), {
+ code: "ENOTFOUND",
+ });
+ const lookup = createDestinationLookup((_hostname, _options, callback) =>
+ callback(failure, []),
+ );
+
+ await expect(lookupAll(lookup, "missing.example.com")).rejects.toBe(
+ failure,
+ );
+ });
+});
diff --git a/apps/api/src/import/destination-lookup.ts b/apps/api/src/import/destination-lookup.ts
new file mode 100644
index 000000000..cc2f4aca5
--- /dev/null
+++ b/apps/api/src/import/destination-lookup.ts
@@ -0,0 +1,51 @@
+import dns, { type LookupAddress, type LookupAllOptions } from "node:dns";
+import type { LookupFunction } from "node:net";
+import {
+ isDisallowedAddress,
+ privateDestinationsAllowed,
+} from "../utils/assert-public-destination";
+import { blockedDestinationError } from "./blocked-destination-error";
+
+export type ResolveAll = (
+ hostname: string,
+ options: LookupAllOptions,
+ callback: (
+ error: NodeJS.ErrnoException | null,
+ addresses: LookupAddress[],
+ ) => void,
+) => void;
+
+function notFound(hostname: string) {
+ return Object.assign(new Error(`getaddrinfo ENOTFOUND ${hostname}`), {
+ code: "ENOTFOUND",
+ hostname,
+ });
+}
+
+export function createDestinationLookup(
+ resolve: ResolveAll = dns.lookup,
+): LookupFunction {
+ return (hostname, options, callback) => {
+ resolve(
+ hostname,
+ {
+ family: options.family,
+ hints: options.hints,
+ all: true,
+ verbatim: true,
+ },
+ (error, addresses) => {
+ if (error) return callback(error, []);
+ const blocked =
+ !privateDestinationsAllowed() &&
+ addresses.some(({ address }) => isDisallowedAddress(address));
+ if (blocked) return callback(blockedDestinationError(), []);
+
+ const [first] = addresses;
+ if (!first) return callback(notFound(hostname), []);
+ if (options.all) return callback(null, addresses);
+ callback(null, first.address, first.family);
+ },
+ );
+ };
+}
diff --git a/apps/api/src/import/guarded-fetch.test.ts b/apps/api/src/import/guarded-fetch.test.ts
index 4fa48292d..226e5ba80 100644
--- a/apps/api/src/import/guarded-fetch.test.ts
+++ b/apps/api/src/import/guarded-fetch.test.ts
@@ -6,6 +6,7 @@ import {
it,
vi,
} from "vite-plus/test";
+import { blockedDestinationError } from "./blocked-destination-error";
import { createGuardedFetch, MAX_IMPORT_REDIRECTS } from "./guarded-fetch";
const PUBLIC = "http://93.184.216.34";
@@ -145,6 +146,23 @@ describe("createGuardedFetch", () => {
expect(cancelled.failure()).toBeNull();
});
+ it("reports a host that resolves to a private address at connect time as a destination problem", async () => {
+ const baseFetch = vi.fn(async () => {
+ throw new TypeError("fetch failed", {
+ cause: blockedDestinationError(),
+ });
+ });
+ const guard = createGuardedFetch("PLANKA", { baseFetch });
+
+ await expect(guard.fetch(`${PUBLIC}/api`)).rejects.toThrow(
+ "PLANKA destination resolves to a non-routable address",
+ );
+ expect(guard.failure()).toEqual({
+ kind: "destination",
+ message: "PLANKA destination resolves to a non-routable address",
+ });
+ });
+
it("rejects malformed URLs as a destination problem", async () => {
const guard = createGuardedFetch("PLANKA", {
baseFetch: vi.fn(async () => new Response("ok")),
diff --git a/apps/api/src/import/guarded-fetch.ts b/apps/api/src/import/guarded-fetch.ts
index 10d4b790c..458488175 100644
--- a/apps/api/src/import/guarded-fetch.ts
+++ b/apps/api/src/import/guarded-fetch.ts
@@ -1,6 +1,11 @@
import type { FetchLike } from "@kaneo/importers";
-import { assertPublicDestination } from "../utils/assert-public-destination";
+import {
+ assertPublicDestination,
+ nonRoutableDestinationMessage,
+} from "../utils/assert-public-destination";
import { withoutOutboundTelemetry } from "../utils/sensitive-outbound";
+import { isBlockedDestinationError } from "./blocked-destination-error";
+import { destinationFetch } from "./destination-fetch";
export const MAX_IMPORT_REDIRECTS = 3;
@@ -77,10 +82,7 @@ function redirectInit(
export function createGuardedFetch(
label: string,
- {
- cancelSignal,
- baseFetch = (input, init) => fetch(input, init),
- }: GuardOptions = {},
+ { cancelSignal, baseFetch = destinationFetch }: GuardOptions = {},
): GuardedFetch {
let failure: GuardFailure | null = null;
let lastHost: string | null = null;
@@ -129,6 +131,10 @@ export function createGuardedFetch(
baseFetch(url.href, { ...request, redirect: "manual" }),
);
} catch (error) {
+ if (isBlockedDestinationError(error)) {
+ const message = nonRoutableDestinationMessage(label);
+ fail({ kind: "destination", message }, message);
+ }
if (!cancelSignal?.aborted) {
failure = { kind: "unreachable", host: url.host };
}
diff --git a/apps/api/src/import/index.ts b/apps/api/src/import/index.ts
index a202d3ca7..9fa0f2210 100644
--- a/apps/api/src/import/index.ts
+++ b/apps/api/src/import/index.ts
@@ -107,6 +107,7 @@ const startImportRunRoute = createRoute({
502: errorResponse(
"The source could not be reached or answered with an error",
),
+ 503: errorResponse("The server is restarting and not starting new imports"),
},
});
diff --git a/apps/api/src/import/run-import-job.ts b/apps/api/src/import/run-import-job.ts
index 7a4fdc31a..50560a33d 100644
--- a/apps/api/src/import/run-import-job.ts
+++ b/apps/api/src/import/run-import-job.ts
@@ -146,7 +146,7 @@ export async function runImportJob(job: ImportJob): Promise<void> {
if (error) {
job.state.projects = failUnfinishedProjects(job.state.projects, error);
}
- await store.save({
+ await store.finish({
status: error ? "failed" : "completed",
error,
message: null,
diff --git a/apps/api/src/import/runs/import-run-store.test.ts b/apps/api/src/import/runs/import-run-store.test.ts
new file mode 100644
index 000000000..1480d60ce
--- /dev/null
+++ b/apps/api/src/import/runs/import-run-store.test.ts
@@ -0,0 +1,99 @@
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vite-plus/test";
+import { createImportRunStore } from "./import-run-store";
+import type { RunChanges } from "./update-running-run";
+
+const RESULT: RunChanges = {
+ status: "completed",
+ error: null,
+ message: null,
+ finishedAt: new Date("2026-10-01T10:00:00.000Z"),
+};
+
+function databaseDown() {
+ return Object.assign(new Error("connection terminated"), {
+ code: "57P01",
+ });
+}
+
+describe("createImportRunStore", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it("keeps going when a progress write fails", async () => {
+ const writeRun = vi
+ .fn<(runId: string, changes: RunChanges) => Promise<boolean>>()
+ .mockRejectedValueOnce(databaseDown())
+ .mockResolvedValue(true);
+ const store = createImportRunStore("run-1", { writeRun });
+
+ await store.save({ message: "Reading cards" });
+ await store.save({ message: "Saving" });
+
+ expect(writeRun).toHaveBeenCalledTimes(2);
+ expect(store.isDetached()).toBe(false);
+ });
+
+ it("retries the final status with a short backoff", async () => {
+ const writeRun = vi
+ .fn<(runId: string, changes: RunChanges) => Promise<boolean>>()
+ .mockRejectedValueOnce(databaseDown())
+ .mockRejectedValueOnce(databaseDown())
+ .mockResolvedValue(true);
+ const store = createImportRunStore("run-1", { writeRun });
+
+ const finished = store.finish(RESULT);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(writeRun).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(500);
+ expect(writeRun).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(2_000);
+ await finished;
+
+ expect(writeRun).toHaveBeenCalledTimes(3);
+ expect(writeRun).toHaveBeenLastCalledWith("run-1", RESULT);
+ expect(console.error).not.toHaveBeenCalled();
+ });
+
+ it("logs the final failure without the error message", async () => {
+ const writeRun = vi.fn(async () => {
+ throw databaseDown();
+ });
+ const store = createImportRunStore("run-1", { writeRun });
+
+ const finished = store.finish(RESULT);
+ await vi.advanceTimersByTimeAsync(2_500);
+ await finished;
+
+ expect(writeRun).toHaveBeenCalledTimes(3);
+ expect(console.error).toHaveBeenCalledTimes(1);
+ expect(console.error).toHaveBeenCalledWith(
+ "Failed to save the import result",
+ { runId: "run-1", error: "Error", code: "57P01", constraint: undefined },
+ );
+ });
+
+ it("stops writing once the run was settled elsewhere", async () => {
+ const writeRun = vi.fn(async () => false);
+ const store = createImportRunStore("run-1", { writeRun });
+
+ await store.save({ message: "Reading cards" });
+ await store.finish(RESULT);
+
+ expect(writeRun).toHaveBeenCalledTimes(1);
+ expect(store.isDetached()).toBe(true);
+ });
+});
diff --git a/apps/api/src/import/runs/import-run-store.ts b/apps/api/src/import/runs/import-run-store.ts
index 19a636349..bbc6fcb3b 100644
--- a/apps/api/src/import/runs/import-run-store.ts
+++ b/apps/api/src/import/runs/import-run-store.ts
@@ -1,49 +1,70 @@
-import { and, eq } from "drizzle-orm";
-import db from "../../database";
-import { importRunTable } from "../../database/schema";
import { logImportError } from "../log-import-error";
+import { type RunChanges, updateRunningRun } from "./update-running-run";
-type RunChanges = Partial<
- Pick<
- typeof importRunTable.$inferInsert,
- "status" | "message" | "projects" | "error" | "finishedAt"
- >
->;
+export const FINAL_WRITE_DELAYS_MS = [0, 500, 2_000] as const;
export type ImportRunStore = {
save(changes: RunChanges): Promise<void>;
+ finish(changes: RunChanges): Promise<void>;
isDetached(): boolean;
flush(): Promise<void>;
};
-export function createImportRunStore(runId: string): ImportRunStore {
+type ImportRunStoreOptions = {
+ writeRun?: typeof updateRunningRun;
+ finalWriteDelaysMs?: readonly number[];
+};
+
+function wait(ms: number) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+export function createImportRunStore(
+ runId: string,
+ {
+ writeRun = updateRunningRun,
+ finalWriteDelaysMs = FINAL_WRITE_DELAYS_MS,
+ }: ImportRunStoreOptions = {},
+): ImportRunStore {
let chain = Promise.resolve();
let detached = false;
async function write(changes: RunChanges) {
+ if (!(await writeRun(runId, changes))) detached = true;
+ }
+
+ async function saveProgress(changes: RunChanges) {
if (detached) return;
try {
- const updated = await db
- .update(importRunTable)
- .set({ ...changes, heartbeatAt: new Date() })
- .where(
- and(
- eq(importRunTable.id, runId),
- eq(importRunTable.status, "running"),
- ),
- )
- .returning({ id: importRunTable.id });
- if (updated.length === 0) detached = true;
+ await write(changes);
} catch (error) {
logImportError("Failed to save import progress", runId, error);
}
}
+ async function saveResult(changes: RunChanges) {
+ let lastError: unknown;
+ for (const delay of finalWriteDelaysMs) {
+ if (detached) return;
+ if (delay > 0) await wait(delay);
+ try {
+ await write(changes);
+ return;
+ } catch (error) {
+ lastError = error;
+ }
+ }
+ logImportError("Failed to save the import result", runId, lastError);
+ }
+
+ function enqueue(task: () => Promise<void>) {
+ chain = chain.then(task);
+ return chain;
+ }
+
return {
- save(changes) {
- chain = chain.then(() => write(changes));
- return chain;
- },
+ save: (changes) => enqueue(() => saveProgress(changes)),
+ finish: (changes) => enqueue(() => saveResult(changes)),
isDetached: () => detached,
flush: () => chain,
};
diff --git a/apps/api/src/import/runs/stop-active-imports.test.ts b/apps/api/src/import/runs/stop-active-imports.test.ts
new file mode 100644
index 000000000..aa1b4753e
--- /dev/null
+++ b/apps/api/src/import/runs/stop-active-imports.test.ts
@@ -0,0 +1,106 @@
+import { HTTPException } from "hono/http-exception";
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import { pendingRunProject } from "../import-run-project";
+
+const mocks = vi.hoisted(() => ({
+ set: vi.fn(),
+ where: vi.fn(async () => undefined),
+}));
+
+vi.mock("../../database", () => ({
+ default: {
+ update: () => ({
+ set: (values: unknown) => {
+ mocks.set(values);
+ return { where: mocks.where };
+ },
+ }),
+ },
+}));
+
+type Registry = typeof import("../active-imports");
+type Stopper = typeof import("./stop-active-imports");
+
+let registry: Registry;
+let stopper: Stopper;
+
+function reserve() {
+ const slot = registry.reserveImportSlot();
+ if (!slot) throw new Error("expected a free slot");
+ return slot;
+}
+
+function untilAborted(signal: AbortSignal) {
+ return new Promise<void>((resolve) => {
+ signal.addEventListener("abort", () => resolve());
+ });
+}
+
+describe("stopActiveImports", () => {
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ vi.resetModules();
+ registry = await import("../active-imports");
+ stopper = await import("./stop-active-imports");
+ });
+
+ it("refuses new imports even when nothing is running", async () => {
+ await stopper.stopActiveImports(10);
+
+ expect(() => registry.reserveImportSlot()).toThrow(HTTPException);
+ expect(mocks.set).not.toHaveBeenCalled();
+ });
+
+ it("waits for a start request that is still connecting, then stops its job", async () => {
+ const slot = reserve();
+ const stopping = stopper.stopActiveImports(1_000);
+ expect(() => registry.reserveImportSlot()).toThrow(HTTPException);
+
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ expect(slot.controller.signal.aborted).toBe(false);
+
+ registry.trackImportJob(
+ slot,
+ "run-1",
+ untilAborted(slot.controller.signal),
+ () => [],
+ );
+ await stopping;
+
+ expect(slot.controller.signal.aborted).toBe(true);
+ expect(registry.activeImportSlots()).toEqual([]);
+ expect(mocks.set).not.toHaveBeenCalled();
+ });
+
+ it("marks a run stopped when its job does not finish in time", async () => {
+ const slot = reserve();
+ registry.trackImportJob(slot, "run-1", new Promise(() => {}), () => [
+ { ...pendingRunProject("a", "Alpha"), status: "running" },
+ ]);
+
+ await stopper.stopActiveImports(10);
+
+ expect(slot.controller.signal.aborted).toBe(true);
+ expect(mocks.set).toHaveBeenCalledWith(
+ expect.objectContaining({
+ status: "failed",
+ error: stopper.RESTART_ERROR,
+ projects: [
+ expect.objectContaining({
+ status: "failed",
+ error: stopper.RESTART_ERROR,
+ }),
+ ],
+ }),
+ );
+ });
+
+ it("stops waiting for a reservation after the grace period", async () => {
+ const slot = reserve();
+
+ await stopper.stopActiveImports(10);
+
+ expect(slot.controller.signal.aborted).toBe(true);
+ expect(mocks.set).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/api/src/import/runs/stop-active-imports.ts b/apps/api/src/import/runs/stop-active-imports.ts
index 284bcd70a..8b0b82102 100644
--- a/apps/api/src/import/runs/stop-active-imports.ts
+++ b/apps/api/src/import/runs/stop-active-imports.ts
@@ -1,7 +1,7 @@
import { and, eq } from "drizzle-orm";
import db from "../../database";
import { importRunTable } from "../../database/schema";
-import { activeImportSlots } from "../active-imports";
+import { activeImportSlots, stopAcceptingImports } from "../active-imports";
import {
failUnfinishedProjects,
type ImportRunProject,
@@ -31,19 +31,30 @@ async function markStopped(runId: string, projects: ImportRunProject[]) {
}
}
-export async function stopActiveImports(graceMs = SHUTDOWN_GRACE_MS) {
- const slots = activeImportSlots();
- if (slots.length === 0) return;
+function settledBefore(deadline: Promise<void>, promises: unknown[]) {
+ return Promise.race([Promise.allSettled(promises), deadline]);
+}
- for (const slot of slots) slot.controller.abort(new Error(RESTART_ERROR));
+export async function stopActiveImports(graceMs = SHUTDOWN_GRACE_MS) {
+ stopAcceptingImports();
+ if (activeImportSlots().length === 0) return;
let timer: ReturnType<typeof setTimeout> | undefined;
- await Promise.race([
- Promise.allSettled(slots.map((slot) => slot.job)),
- new Promise((resolve) => {
- timer = setTimeout(resolve, graceMs);
- }),
- ]);
+ const deadline = new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, graceMs);
+ });
+
+ await settledBefore(
+ deadline,
+ activeImportSlots().map((slot) => slot.settled),
+ );
+
+ const slots = activeImportSlots();
+ for (const slot of slots) slot.controller.abort(new Error(RESTART_ERROR));
+ await settledBefore(
+ deadline,
+ slots.map((slot) => slot.job),
+ );
clearTimeout(timer);
await Promise.all(
diff --git a/apps/api/src/import/runs/update-running-run.ts b/apps/api/src/import/runs/update-running-run.ts
new file mode 100644
index 000000000..c86295031
--- /dev/null
+++ b/apps/api/src/import/runs/update-running-run.ts
@@ -0,0 +1,24 @@
+import { and, eq } from "drizzle-orm";
+import db from "../../database";
+import { importRunTable } from "../../database/schema";
+
+export type RunChanges = Partial<
+ Pick<
+ typeof importRunTable.$inferInsert,
+ "status" | "message" | "projects" | "error" | "finishedAt"
+ >
+>;
+
+export async function updateRunningRun(
+ runId: string,
+ changes: RunChanges,
+): Promise<boolean> {
+ const updated = await db
+ .update(importRunTable)
+ .set({ ...changes, heartbeatAt: new Date() })
+ .where(
+ and(eq(importRunTable.id, runId), eq(importRunTable.status, "running")),
+ )
+ .returning({ id: importRunTable.id });
+ return updated.length > 0;
+}
diff --git a/apps/api/src/import/write-imported-project.ts b/apps/api/src/import/write-imported-project.ts
index c53f5b849..526b8aaf4 100644
--- a/apps/api/src/import/write-imported-project.ts
+++ b/apps/api/src/import/write-imported-project.ts
@@ -1,7 +1,4 @@
import type { ImportedProject, ImportSourceId } from "@kaneo/importers";
-import { eq } from "drizzle-orm";
-import db from "../database";
-import { projectTable } from "../database/schema";
import { publishEvent } from "../events";
import type { ImportCounts } from "./import-run-project";
import { createImportProject } from "./writer/create-import-project";
@@ -29,43 +26,28 @@ export async function writeImportedProject({
project,
includeComments,
}: WriteImportedProjectInput): Promise<WrittenImportProject> {
- const name = project.name.trim() || "Untitled project";
- const created = await createImportProject(
- workspaceId,
- name,
- userId,
- project.key,
- );
-
- let content: Awaited<ReturnType<typeof writeProjectContent>>;
- try {
- content = await db.transaction((tx) =>
- writeProjectContent(tx, {
+ const written = await createImportProject(
+ {
+ workspaceId,
+ name: project.name.trim() || "Untitled project",
+ userId,
+ preferredKey: project.key,
+ },
+ async (tx, created) => ({
+ projectId: created.id,
+ projectSlug: created.slug,
+ ...(await writeProjectContent(tx, {
projectId: created.id,
workspaceId,
userId,
source,
project,
includeComments,
- }),
- );
- } catch (error) {
- await db
- .delete(projectTable)
- .where(eq(projectTable.id, created.id))
- .catch(() => {
- console.error("Failed to remove a partially imported project", {
- projectId: created.id,
- });
- });
- throw error;
- }
+ })),
+ }),
+ );
- await publishEvent("project.updated", { projectId: created.id });
+ await publishEvent("project.updated", { projectId: written.projectId });
- return {
- projectId: created.id,
- projectSlug: created.slug,
- ...content,
- };
+ return written;
}
diff --git a/apps/api/src/import/writer/create-import-project.test.ts b/apps/api/src/import/writer/create-import-project.test.ts
new file mode 100644
index 000000000..0b2c81fc3
--- /dev/null
+++ b/apps/api/src/import/writer/create-import-project.test.ts
@@ -0,0 +1,99 @@
+import { HTTPException } from "hono/http-exception";
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import { createImportProject } from "./create-import-project";
+
+const mocks = vi.hoisted(() => ({
+ insertProject: vi.fn(),
+ transactions: [] as { id: number; outcome: "committed" | "rolled back" }[],
+}));
+
+vi.mock("../../database", () => ({
+ default: {
+ select: () => ({ from: () => ({ where: async () => [] }) }),
+ transaction: async (work: (tx: unknown) => Promise<unknown>) => {
+ const tx = { id: mocks.transactions.length + 1 };
+ try {
+ const result = await work(tx);
+ mocks.transactions.push({ ...tx, outcome: "committed" });
+ return result;
+ } catch (error) {
+ mocks.transactions.push({ ...tx, outcome: "rolled back" });
+ throw error;
+ }
+ },
+ },
+}));
+
+vi.mock("../../project/controllers/insert-project", () => ({
+ insertProject: mocks.insertProject,
+}));
+
+const input = {
+ workspaceId: "workspace-1",
+ name: "Website",
+ userId: "user-1",
+ preferredKey: "WEB",
+};
+
+describe("createImportProject", () => {
+ beforeEach(() => {
+ mocks.insertProject.mockReset();
+ 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");
+
+ 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, {
+ workspaceId: "workspace-1",
+ name: "Website",
+ icon: "Layout",
+ 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
+ .mockRejectedValueOnce(new HTTPException(409, { message: "taken" }))
+ .mockImplementation(async (_tx, project) => ({
+ id: "project-1",
+ slug: project.slug,
+ }));
+ const fill = vi.fn(async () => "filled");
+
+ await createImportProject(input, fill);
+
+ expect(
+ mocks.insertProject.mock.calls.map(([, project]) => project.slug),
+ ).toEqual(["WEB", "WEB-2"]);
+ expect(fill).toHaveBeenCalledTimes(1);
+ expect(fill).toHaveBeenCalledWith({ id: 2 }, expect.anything());
+ 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" });
+ const failure = new Error("could not write tasks");
+
+ await expect(
+ createImportProject(input, async () => {
+ throw failure;
+ }),
+ ).rejects.toBe(failure);
+
+ 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.ts
index e299e14ae..b5d1f29dd 100644
--- a/apps/api/src/import/writer/create-import-project.ts
+++ b/apps/api/src/import/writer/create-import-project.ts
@@ -1,26 +1,44 @@
import { eq } from "drizzle-orm";
import db from "../../database";
import { projectTable } from "../../database/schema";
-import createProject from "../../project/controllers/create-project";
+import { insertProject } from "../../project/controllers/insert-project";
import { createWithUniqueKey } from "./create-with-unique-key";
-export async function createImportProject(
- workspaceId: string,
- name: string,
- userId: string,
- preferredKey?: string,
-) {
+type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];
+
+type CreatedProject = NonNullable<Awaited<ReturnType<typeof insertProject>>>;
+
+export type ImportProjectInput = {
+ workspaceId: string;
+ name: string;
+ userId: string;
+ preferredKey?: string;
+};
+
+export async function createImportProject<T>(
+ { workspaceId, name, userId, preferredKey }: ImportProjectInput,
+ fill: (tx: Transaction, project: CreatedProject) => Promise<T>,
+): Promise<T> {
const existing = await db
.select({ slug: projectTable.slug })
.from(projectTable)
.where(eq(projectTable.workspaceId, workspaceId));
- const project = await createWithUniqueKey(
+ return createWithUniqueKey(
name,
existing.map((row) => row.slug),
- (key) => createProject(workspaceId, name, "Layout", key, userId),
+ (slug) =>
+ db.transaction(async (tx) => {
+ const project = await insertProject(tx, {
+ workspaceId,
+ name,
+ icon: "Layout",
+ slug,
+ userId,
+ });
+ if (!project) throw new Error("Failed to create the imported project");
+ return fill(tx, project);
+ }),
{ preferredKey },
);
- if (!project) throw new Error("Failed to create the imported project");
- return project;
}
diff --git a/apps/api/src/import/writer/write-import-comments.test.ts b/apps/api/src/import/writer/write-import-comments.test.ts
new file mode 100644
index 000000000..3e7f3f172
--- /dev/null
+++ b/apps/api/src/import/writer/write-import-comments.test.ts
@@ -0,0 +1,53 @@
+import type { ImportedComment } from "@kaneo/importers";
+import { describe, expect, it } from "vite-plus/test";
+import { writeImportComments } from "./write-import-comments";
+
+type Transaction = Parameters<typeof writeImportComments>[0];
+
+const now = new Date("2026-10-11T12:00:00.000Z");
+
+async function authorNames(comments: ImportedComment[]) {
+ const rows: { externalUserName: string }[] = [];
+ const tx = {
+ insert: () => ({
+ values: async (batch: typeof rows) => {
+ rows.push(...batch);
+ },
+ }),
+ } as unknown as Transaction;
+
+ await writeImportComments(tx, {
+ tasks: [{ id: "task-1", comments }],
+ importedBy: "user-1",
+ source: "planka",
+ now,
+ });
+
+ return rows.map((row) => row.externalUserName);
+}
+
+describe("writeImportComments", () => {
+ it("names the author by name, then email, then as unknown", async () => {
+ await expect(
+ authorNames([
+ { author: { name: " Ana ", email: "[email protected]" }, body: "One" },
+ { author: { name: " ", email: " [email protected] " }, body: "Two" },
+ { author: { email: " " }, body: "Three" },
+ { author: {}, body: "Four" },
+ ]),
+ ).resolves.toEqual([
+ "Ana",
+ "Unknown user",
+ "Unknown user",
+ ]);
+ });
+
+ it("keeps author names within the stored length", async () => {
+ const [name] = await authorNames([
+ { author: { email: `${"a".repeat(200)}@example.com` }, body: "Long" },
+ ]);
+
+ expect(name).toHaveLength(120);
+ });
+});
diff --git a/apps/api/src/import/writer/write-import-comments.ts b/apps/api/src/import/writer/write-import-comments.ts
index 6630180ec..f7c9d7461 100644
--- a/apps/api/src/import/writer/write-import-comments.ts
+++ b/apps/api/src/import/writer/write-import-comments.ts
@@ -32,10 +32,11 @@ export async function writeImportComments(
type: "comment",
userId: importedBy,
content: comment.body,
- externalUserName: (comment.author.name?.trim() || "Unknown user").slice(
- 0,
- MAX_EXTERNAL_NAME_LENGTH,
- ),
+ externalUserName: (
+ comment.author.name?.trim() ||
+ comment.author.email?.trim() ||
+ "Unknown user"
+ ).slice(0, MAX_EXTERNAL_NAME_LENGTH),
externalSource: source,
createdAt: parseImportDate(comment.createdAt) ?? now,
})),
diff --git a/apps/api/src/project/controllers/create-project.ts b/apps/api/src/project/controllers/create-project.ts
index 6df868d99..68d422ebd 100644
--- a/apps/api/src/project/controllers/create-project.ts
+++ b/apps/api/src/project/controllers/create-project.ts
@@ -1,16 +1,5 @@
-import { eq, max, sql } from "drizzle-orm";
-import { HTTPException } from "hono/http-exception";
import 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";
-
-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 },
- { name: "In Review", slug: "in-review", position: 2, isFinal: false },
- { name: "Done", slug: "done", position: 3, isFinal: true },
-] as const;
+import { insertProject } from "./insert-project";
async function createProject(
workspaceId: string,
@@ -19,59 +8,9 @@ async function createProject(
slug: string,
userId: string,
) {
- return db.transaction(async (tx) => {
- // Serialize ordering writes per workspace: without this, two concurrent
- // 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),
- });
- }
-
- // 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 [createdProject] = await tx
- .insert(projectTable)
- .values({
- workspaceId,
- name,
- icon,
- slug,
- position: maxPosition === null ? 0 : maxPosition + 1,
- })
- .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 grantProjectToRestrictedMember(tx, {
- workspaceId,
- userId,
- projectId: createdProject.id,
- });
- }
-
- return createdProject;
- });
+ return db.transaction((tx) =>
+ insertProject(tx, { workspaceId, name, icon, slug, userId }),
+ );
}
export default createProject;
diff --git a/apps/api/src/project/controllers/insert-project.ts b/apps/api/src/project/controllers/insert-project.ts
new file mode 100644
index 000000000..fe8065954
--- /dev/null
+++ b/apps/api/src/project/controllers/insert-project.ts
@@ -0,0 +1,80 @@
+import { eq, max, sql } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+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";
+
+type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];
+
+export type NewProject = {
+ workspaceId: string;
+ name: string;
+ icon: 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 },
+ { name: "In Review", slug: "in-review", position: 2, isFinal: false },
+ { name: "Done", slug: "done", position: 3, isFinal: true },
+] as const;
+
+export async function insertProject(
+ tx: Transaction,
+ { workspaceId, name, icon, slug, userId }: NewProject,
+) {
+ // Serialize ordering writes per workspace: without this, two concurrent
+ // 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),
+ });
+ }
+
+ // 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 [createdProject] = await tx
+ .insert(projectTable)
+ .values({
+ workspaceId,
+ name,
+ icon,
+ slug,
+ position: maxPosition === null ? 0 : maxPosition + 1,
+ })
+ .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 grantProjectToRestrictedMember(tx, {
+ workspaceId,
+ userId,
+ projectId: createdProject.id,
+ });
+ }
+
+ return createdProject;
+}
diff --git a/apps/api/src/utils/assert-public-destination.ts b/apps/api/src/utils/assert-public-destination.ts
index ceb1b88ba..89efaa0b9 100644
--- a/apps/api/src/utils/assert-public-destination.ts
+++ b/apps/api/src/utils/assert-public-destination.ts
@@ -85,6 +85,10 @@ export function privateDestinationsAllowed(): boolean {
);
}
+export function nonRoutableDestinationMessage(label: string): string {
+ return `${label} destination resolves to a non-routable address`;
+}
+
export async function assertPublicDestination(
destinationUrl: string,
label: string,
@@ -100,7 +104,7 @@ export async function assertPublicDestination(
}
if (isDisallowedAddress(url.hostname)) {
- throw new Error(`${label} destination resolves to a non-routable address`);
+ throw new Error(nonRoutableDestinationMessage(label));
}
const addresses = await lookup(url.hostname, { all: true, verbatim: true });
@@ -109,6 +113,6 @@ export async function assertPublicDestination(
}
if (addresses.some((entry) => isDisallowedAddress(entry.address))) {
- throw new Error(`${label} destination resolves to a non-routable address`);
+ throw new Error(nonRoutableDestinationMessage(label));
}
}
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index 9c4a080ba..6d5b0092f 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -22888,6 +22888,16 @@
}
}
}
+ },
+ "503": {
+ "description": "The server is restarting and not starting new imports",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
}
}
}
diff --git a/packages/importers/src/kaneo/read-project.ts b/packages/importers/src/kaneo/read-project.ts
index 2f129639c..271200b74 100644
--- a/packages/importers/src/kaneo/read-project.ts
+++ b/packages/importers/src/kaneo/read-project.ts
@@ -6,7 +6,11 @@ import { collectLabels, mapColumns, mapRelations, mapTask } from "./mapping.js";
import { readOptional } from "./optional.js";
import { readBoard } from "./read-board.js";
import { readTaskDetails } from "./read-task-details.js";
-import { buildWarnings, MEMBERS_UNAVAILABLE_WARNING } from "./warnings.js";
+import {
+ buildWarnings,
+ CUSTOM_FIELDS_UNREADABLE_WARNING,
+ MEMBERS_UNAVAILABLE_WARNING,
+} from "./warnings.js";
export async function readKaneoProject(
client: KaneoClient,
@@ -30,7 +34,8 @@ export async function readKaneoProject(
: [],
);
- const customFieldNames = await readCustomFieldNames(client, projectId);
+ const customFields = await readCustomFieldNames(client, projectId);
+ if (customFields.unreadable) warnings.push(CUSTOM_FIELDS_UNREADABLE_WARNING);
const description = project.descriptionDeferred
? await client.getProjectDescription(projectId)
: project.description;
@@ -61,7 +66,7 @@ export async function readKaneoProject(
tasks: ordered,
imported: importedTasks,
members,
- customFieldNames,
+ customFieldNames: customFields.names,
relationsOutsideProject: outsideProject,
}),
);
@@ -82,12 +87,17 @@ export async function readKaneoProject(
async function readCustomFieldNames(
client: KaneoClient,
projectId: string,
-): Promise<string[]> {
+): Promise<{ names: string[]; unreadable: boolean }> {
try {
const fields = await client.listCustomFields(projectId);
- return fields.map((field) => field.name.trim()).filter(Boolean);
+ return {
+ names: fields.map((field) => field.name.trim()).filter(Boolean),
+ unreadable: false,
+ };
} catch (error) {
- if (error instanceof SourceHttpError && error.status < 500) return [];
+ if (!(error instanceof SourceHttpError)) throw error;
+ if (error.status === 404) return { names: [], unreadable: false };
+ if (error.status === 403) return { names: [], unreadable: true };
throw error;
}
}
diff --git a/packages/importers/src/kaneo/source.test.ts b/packages/importers/src/kaneo/source.test.ts
index 185d6670c..c067fbf38 100644
--- a/packages/importers/src/kaneo/source.test.ts
+++ b/packages/importers/src/kaneo/source.test.ts
@@ -519,6 +519,61 @@ describe("readProject", () => {
).toHaveLength(1);
});
+ it("leaves custom fields out quietly when the instance has none", async () => {
+ const fake = fakeFetch({
+ ...routes(),
+ "/api/custom-field/project/p1": fail(404, "Not found"),
+ });
+ const source = await connectKaneo(
+ { url: BASE, apiKey: API_KEY },
+ { fetch: fake.fetch },
+ );
+
+ const project = await source.readProject("p1", { includeComments: false });
+
+ expect(
+ project.warnings.filter((warning) => warning.includes("Custom fields")),
+ ).toEqual([]);
+ });
+
+ it("continues with a warning when the API key may not read custom fields", async () => {
+ const fake = fakeFetch({
+ ...routes(),
+ "/api/custom-field/project/p1": fail(403, "Forbidden"),
+ });
+ const source = await connectKaneo(
+ { url: BASE, apiKey: API_KEY },
+ { fetch: fake.fetch },
+ );
+
+ const project = await source.readProject("p1", { includeComments: false });
+
+ expect(project.tasks).toHaveLength(5);
+ expect(
+ project.warnings.filter((warning) => warning.includes("Custom fields")),
+ ).toEqual([
+ "Custom fields could not be read with this API key, so they are not listed here.",
+ ]);
+ });
+
+ it.each([401, 400, 500])(
+ "stops when reading custom fields fails with HTTP %i",
+ async (status) => {
+ const fake = fakeFetch({
+ ...routes(),
+ "/api/custom-field/project/p1": fail(status, "Nope"),
+ });
+ const source = await connectKaneo(
+ { url: BASE, apiKey: API_KEY },
+ { fetch: fake.fetch },
+ );
+
+ await expect(
+ source.readProject("p1", { includeComments: false }),
+ ).rejects.toMatchObject({ name: "SourceHttpError", status });
+ },
+ );
+
it("skips tasks deleted while reading", async () => {
const fake = fakeFetch({
...routes(),
diff --git a/packages/importers/src/kaneo/warnings.ts b/packages/importers/src/kaneo/warnings.ts
index 728add630..06fee1bfb 100644
--- a/packages/importers/src/kaneo/warnings.ts
+++ b/packages/importers/src/kaneo/warnings.ts
@@ -17,6 +17,8 @@ export const RELATIONS_UNAVAILABLE_WARNING =
"This Kaneo version does not expose task links, so they are not copied.";
export const COMMENTS_UNAVAILABLE_WARNING =
"This Kaneo version does not expose comments, so they are not copied.";
+export const CUSTOM_FIELDS_UNREADABLE_WARNING =
+ "Custom fields could not be read with this API key, so they are not listed here.";
export function buildWarnings(facts: WarningFacts): string[] {
const warnings: string[] = [];
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 16eeaa0ef..6457156a3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -196,6 +196,9 @@ importers:
pg:
specifier: ^8.23.1
version: 8.23.1
+ undici:
+ specifier: '>=7.29.0 <8'
+ version: 7.30.0
valibot:
specifier: '>=1.4.2'
version: 1.4.2([email protected])
@@ -9435,8 +9438,8 @@ packages:
resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==}
- resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==}
+ resolution: {integrity: sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==}
engines: {node: '>=20.18.1'}
@@ -9931,7 +9934,7 @@ snapshots:
'@actions/[email protected]':
dependencies:
tunnel: 0.0.6
- undici: 7.29.0
+ undici: 7.30.0
'@actions/[email protected]': {}
@@ -10687,7 +10690,7 @@ snapshots:
'@effect/platform-node-shared': 4.0.2([email protected])
effect: 4.0.2
redis: 6.3.0(@opentelemetry/[email protected])
- undici: 7.29.0
+ undici: 7.30.0
transitivePeerDependencies:
- bufferutil
- utf-8-validate
@@ -12880,7 +12883,7 @@ snapshots:
p-filter: 4.1.0
semantic-release: 25.0.9([email protected])
tinyglobby: 0.2.17
- undici: 7.29.0
+ undici: 7.30.0
url-join: 5.0.0
transitivePeerDependencies:
- kerberos
@@ -16050,7 +16053,7 @@ snapshots:
parse5: 8.0.1
saxes: 6.0.0
tough-cookie: 6.0.2
- undici: 7.29.0
+ undici: 7.30.0
w3c-xmlserializer: 6.0.0
webidl-conversions: 8.0.1
whatwg-mimetype: 5.0.0
@@ -17954,7 +17957,7 @@ snapshots:
stringify-object: 5.0.0
ts-morph: 26.0.0
tsconfig-paths: 4.2.0
- undici: 7.29.0
+ undici: 7.30.0
validate-npm-package-name: 7.0.2
zod: 3.25.76
zod-to-json-schema: 3.25.2([email protected])
@@ -18509,7 +18512,7 @@ snapshots:
diff --git a/tests/api-integration/helpers/fixtures.ts b/tests/api-integration/helpers/fixtures.ts
index 95f9c7f5b..faef5d3bd 100644
--- a/tests/api-integration/helpers/fixtures.ts
+++ b/tests/api-integration/helpers/fixtures.ts
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import db, { schema } from "../../../apps/api/src/database";
-import { DEFAULT_PROJECT_COLUMNS } from "../../../apps/api/src/project/controllers/create-project";
+import { DEFAULT_PROJECT_COLUMNS } from "../../../apps/api/src/project/controllers/insert-project";
export type SeededMemberContext = {
user: typeof schema.userTable.$inferSelect;
diff --git a/tests/api-integration/import.test.ts b/tests/api-integration/import.test.ts
index 160786567..b25219b18 100644
--- a/tests/api-integration/import.test.ts
+++ b/tests/api-integration/import.test.ts
@@ -8,6 +8,7 @@ import type {
} from "../../packages/importers/dist/index.js";
import db, { schema } from "../../apps/api/src/database";
import { waitForActiveImports } from "../../apps/api/src/import/active-imports";
+import { writeImportRelations } from "../../apps/api/src/import/writer/write-import-relations";
import { createApp } from "../../apps/api/src/index";
import { mockAuthenticatedSession } from "./helpers/auth";
import { resetTestDatabase } from "./helpers/database";
@@ -25,6 +26,20 @@ vi.mock("../../packages/importers/dist/index.js", async (original) => ({
connectSource: importers.connectSource,
}));
+vi.mock(
+ "../../apps/api/src/import/writer/write-import-relations",
+ async (original) => {
+ const actual =
+ await original<
+ typeof import("../../apps/api/src/import/writer/write-import-relations")
+ >();
+ return {
+ ...actual,
+ writeImportRelations: vi.fn(actual.writeImportRelations),
+ };
+ },
+);
+
const SECRET = "planka-secret-key-0123456789";
const connection = {
@@ -625,6 +640,51 @@ describe("API integration: import from other tools", () => {
expect(JSON.parse(listedText).runs).toHaveLength(1);
});
+ it("leaves no project behind when saving its content fails", async () => {
+ const admin = await createAdmin();
+ const workspaceId = admin.workspace.id;
+ importers.connectSource.mockResolvedValue(
+ fakeSource(async () => plankaProject("")),
+ );
+ vi.mocked(writeImportRelations).mockRejectedValueOnce(
+ new Error("relations failed"),
+ );
+ const logged = vi.spyOn(console, "error").mockImplementation(() => {});
+ mockAuthenticatedSession(admin.user);
+
+ try {
+ const started = await post("/runs", {
+ workspaceId,
+ connection,
+ projectIds: ["p1"],
+ });
+ expect(started.status).toBe(202);
+ const { run } = (await started.json()) as { run: { id: string } };
+ await waitForActiveImports();
+
+ const polled = await get(`/runs/${workspaceId}/${run.id}`);
+ const { run: finished } = (await polled.json()) as {
+ run: { projects: Record<string, unknown>[] };
+ };
+ expect(finished.projects).toEqual([
+ expect.objectContaining({
+ status: "failed",
+ projectId: null,
+ error: "Kaneo could not save this project.",
+ }),
+ ]);
+ expect(writeImportRelations).toHaveBeenCalled();
+
+ const projects = await db
+ .select({ id: schema.projectTable.id })
+ .from(schema.projectTable)
+ .where(eq(schema.projectTable.workspaceId, workspaceId));
+ expect(projects).toEqual([]);
+ } finally {
+ logged.mockRestore();
+ }
+ });
+
it("keeps the source key and task numbers", async () => {
const admin = await createAdmin();
const workspaceId = admin.workspace.id;