⚡ 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: recover GitLab issue updates and preserve priority labels
Tin9ac1cf5a2b47
diff --git a/apps/api/src/plugins/gitlab/utils/gitlab-api.ts b/apps/api/src/plugins/gitlab/utils/gitlab-api.tsindex 162dbb45f..8c6540d41 100644--- a/apps/api/src/plugins/gitlab/utils/gitlab-api.ts+++ b/apps/api/src/plugins/gitlab/utils/gitlab-api.ts@@ -1,3 +1,4 @@+import { setTimeout as delay } from "node:timers/promises";import * as Sentry from "@sentry/node";import { assertPublicDestination } from "../../../utils/assert-public-destination";import type { GitlabConfig, GitlabTokenType } from "../config";@@ -86,6 +87,18 @@ export class GitlabApiError extends Error {}}+function isResourceLock(error: unknown): boolean {+ if (!(error instanceof GitlabApiError) || error.status !== 409) return false;+ try {+ return (+ JSON.parse(error.body ?? "null")?.message ===+ "409 Conflict: Resource lock"+ );+ } catch {+ return false;+ }+}+function authHeaders(token: string, tokenType: GitlabTokenType): HeadersInit {return {...(tokenType === "bearer"@@ -259,13 +272,24 @@ export function createGitlabClient(iid: number,body: Record<string, unknown>,): Promise<GitlabIssue> {- return required(- await call<GitlabIssue>(`${project(projectPath)}/issues/${iid}`, {- method: "PUT",- body: JSON.stringify(body),- }),- "update issue",- );+ for (let attempt = 0; ; attempt += 1) {+ try {+ return required(+ await call<GitlabIssue>(`${project(projectPath)}/issues/${iid}`, {+ method: "PUT",+ body: JSON.stringify(body),+ }),+ "update issue",+ );+ } catch (error) {+ // Concurrent edits can briefly lock an issue. Retry only this rejected+ // update, not creates or ambiguous failures that may have succeeded.+ if (attempt >= 3 || !isResourceLock(error)) {+ throw error;+ }+ await delay(250 * 2 ** attempt);+ }+ }},async getIssue(projectPath: string, iid: number): Promise<GitlabIssue> {diff --git a/apps/api/src/plugins/gitlab/utils/labels.ts b/apps/api/src/plugins/gitlab/utils/labels.tsindex c8b18cf77..84fc1138c 100644--- a/apps/api/src/plugins/gitlab/utils/labels.ts+++ b/apps/api/src/plugins/gitlab/utils/labels.ts@@ -57,7 +57,9 @@ export async function updateIssueLabelsGitlab(changes: { add?: string[]; remove?: string[] },) {const add = changes.add ?? [];- const remove = changes.remove ?? [];+ // GitLab removes a label when it appears in both lists. Reapplying a+ // priority or status must leave its label present.+ const remove = (changes.remove ?? []).filter((label) => !add.includes(label));if (add.length === 0 && remove.length === 0) return;diff --git a/apps/api/src/task/controllers/update-task.ts b/apps/api/src/task/controllers/update-task.tsindex 5920a2717..a3faec9c3 100644--- a/apps/api/src/task/controllers/update-task.ts+++ b/apps/api/src/task/controllers/update-task.ts@@ -30,6 +30,8 @@ async function updateTask(const [existingTask] = await db.select({id: taskTable.id,+ title: taskTable.title,+ priority: taskTable.priority,description:description === undefined ? sql<null>`null` : taskTable.description,status: taskTable.status,@@ -114,6 +116,40 @@ async function updateTask(});}+ if (existingTask.title !== title) {+ await publishEvent("task.title_changed", {+ taskId: updatedTask.id,+ projectId: updatedTask.projectId,+ userId: currentUserId,+ oldTitle: existingTask.title,+ newTitle: title,+ type: "title_changed",+ });+ }++ if (description !== undefined && existingTask.description !== description) {+ await publishEvent("task.description_changed", {+ taskId: updatedTask.id,+ projectId: updatedTask.projectId,+ userId: currentUserId,+ oldDescription: existingTask.description,+ newDescription: description,+ type: "description_changed",+ });+ }++ if (existingTask.priority !== priority) {+ await publishEvent("task.priority_changed", {+ taskId: updatedTask.id,+ projectId: updatedTask.projectId,+ userId: currentUserId,+ oldPriority: existingTask.priority,+ newPriority: priority,+ title: updatedTask.title,+ type: "priority_changed",+ });+ }+await publishEvent("task.updated", {taskId: updatedTask.id,projectId: updatedTask.projectId,diff --git a/tests/api-integration/task-update-events.test.ts b/tests/api-integration/task-update-events.test.tsnew file mode 100644index 000000000..e030c80ee--- /dev/null+++ b/tests/api-integration/task-update-events.test.ts@@ -0,0 +1,137 @@+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { publishEvent } from "../../apps/api/src/events";+import { createApp } from "../../apps/api/src/index";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++vi.mock("../../apps/api/src/events", async (original) => ({+ ...(await original<object>()),+ publishEvent: vi.fn(async () => undefined),+}));+beforeEach(async () => {+ await resetTestDatabase();+ vi.clearAllMocks();+});+async function setup() {+ const member = await createWorkspaceMember();+ const { project, columns } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ mockAuthenticatedSession(member.user);+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ columnId: columns.todo.id,+ title: "Original",+ description: "Old body",+ priority: "medium",+ status: "to-do",+ number: 1,+ position: 1,+ })+ .returning();+ const { app } = createApp();+ const update = (values: Record<string, unknown>) =>+ app.request(`/api/task/${task.id}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ title: task.title,+ status: task.status,+ priority: task.priority,+ projectId: project.id,+ position: task.position,+ ...values,+ }),+ });+ return { task, update, project, user: member.user };+}++describe("general task update integration events", () => {+ it("publishes changed fields with full descriptions and preserves the realtime refresh", async () => {+ const { task, update, project, user } = await setup();+ const description = "New body ".repeat(2000);+ const response = await update({+ title: "Updated",+ description,+ priority: "high",+ status: "done",+ });+ expect(response.status).toBe(200);+ const common = { taskId: task.id, projectId: project.id, userId: user.id };+ expect(publishEvent).toHaveBeenCalledWith(+ "task.title_changed",+ expect.objectContaining({+ ...common,+ oldTitle: "Original",+ newTitle: "Updated",+ }),+ );+ expect(publishEvent).toHaveBeenCalledWith(+ "task.description_changed",+ expect.objectContaining({+ ...common,+ oldDescription: "Old body",+ newDescription: description,+ }),+ );+ expect(publishEvent).toHaveBeenCalledWith(+ "task.priority_changed",+ expect.objectContaining({+ ...common,+ oldPriority: "medium",+ newPriority: "high",+ }),+ );+ expect(publishEvent).toHaveBeenCalledWith(+ "task.status_changed",+ expect.objectContaining({+ ...common,+ oldStatus: "to-do",+ newStatus: "done",+ }),+ );+ expect(publishEvent).toHaveBeenCalledWith(+ "task.updated",+ expect.objectContaining(common),+ );+ expect(+ await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, task.id),+ }),+ ).toMatchObject({ title: "Updated", description, priority: "high" });+ });+ it.each([{}, { description: "Old body" }])(+ "does not emit field changes for omitted or unchanged fields: %j",+ async (values) => {+ const { update } = await setup();+ expect((await update(values)).status).toBe(200);+ expect(vi.mocked(publishEvent).mock.calls.map(([name]) => name)).toEqual([+ "task.updated",+ ]);+ },+ );+ it("emits an explicit description clear", async () => {+ const { update } = await setup();+ expect((await update({ description: "" })).status).toBe(200);+ expect(publishEvent).toHaveBeenCalledWith(+ "task.description_changed",+ expect.objectContaining({+ oldDescription: "Old body",+ newDescription: "",+ }),+ );+ });+ it("does not publish changes for rejected updates", async () => {+ const { update } = await setup();+ expect((await update({ title: "Invalid", position: -1 })).status).toBe(400);+ expect(publishEvent).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/plugins/gitlab/utils/issue-updates.test.ts b/tests/api/plugins/gitlab/utils/issue-updates.test.tsnew file mode 100644index 000000000..6d2ca8b2c--- /dev/null+++ b/tests/api/plugins/gitlab/utils/issue-updates.test.ts@@ -0,0 +1,121 @@+import { setTimeout as delay } from "node:timers/promises";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createGitlabClient } from "../../../../../apps/api/src/plugins/gitlab/utils/gitlab-api";+import { updateIssueLabelsGitlab } from "../../../../../apps/api/src/plugins/gitlab/utils/labels";++vi.mock("node:timers/promises", () => ({ setTimeout: vi.fn(async () => {}) }));+vi.mock("../../../../../apps/api/src/utils/assert-public-destination", () => ({+ assertPublicDestination: vi.fn(async () => {}),+}));+const config = {+ baseUrl: "https://gitlab.example",+ accessToken: "test-token",+ projectPath: "group/nested/project",+};+const client = createGitlabClient(config);+const fetchMock = vi.fn<typeof fetch>();+const lock = () =>+ new Response(+ JSON.stringify({ message: "409 Conflict: Resource lock" }, null, 2),+ { status: 409 },+ );+const issue = { iid: 1, title: "Updated" };+beforeEach(() => {+ vi.clearAllMocks();+ fetchMock.mockReset();+ vi.stubGlobal("fetch", fetchMock);+});+afterEach(() => vi.unstubAllGlobals());++describe("GitLab issue update recovery", () => {+ it("retries a temporary resource lock with the same update and backoff", async () => {+ fetchMock+ .mockResolvedValueOnce(lock())+ .mockResolvedValueOnce(lock())+ .mockResolvedValueOnce(Response.json(issue));+ await expect(+ client.updateIssue(config.projectPath, 1, { description: "New body" }),+ ).resolves.toEqual(issue);+ expect(fetchMock).toHaveBeenCalledTimes(3);+ for (const [url, init] of fetchMock.mock.calls) {+ expect(url).toBe(+ "https://gitlab.example/api/v4/projects/group%2Fnested%2Fproject/issues/1",+ );+ expect(init).toMatchObject({+ method: "PUT",+ body: JSON.stringify({ description: "New body" }),+ redirect: "manual",+ });+ }+ expect(vi.mocked(delay).mock.calls.map(([ms]) => ms)).toEqual([250, 500]);+ });+ it("bounds retries and surfaces a persistent lock", async () => {+ fetchMock.mockImplementation(async () => lock());+ await expect(+ client.updateIssue(config.projectPath, 1, { title: "New" }),+ ).rejects.toMatchObject({ status: 409 });+ expect(fetchMock).toHaveBeenCalledTimes(4);+ expect(vi.mocked(delay).mock.calls.map(([ms]) => ms)).toEqual([+ 250, 500, 1000,+ ]);+ });+ it.each([+ [409, '{"message":"Other conflict"}'],+ [409, "invalid json"],+ [401, '{"message":"Unauthorized"}'],+ [500, '{"message":"409 Conflict: Resource lock"}'],+ ])("does not retry other failures (%s, %s)", async (status, body) => {+ fetchMock.mockResolvedValue(new Response(body, { status }));+ await expect(+ client.updateIssue(config.projectPath, 1, { title: "New" }),+ ).rejects.toMatchObject({ status });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(delay).not.toHaveBeenCalled();+ });+ it("does not replay issue or comment creation", async () => {+ fetchMock.mockImplementation(async () => lock());+ await expect(+ client.createIssue(config.projectPath, { title: "New" }),+ ).rejects.toMatchObject({ status: 409 });+ await expect(+ client.createIssueNote(config.projectPath, 1, "Comment"),+ ).rejects.toMatchObject({ status: 409 });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(delay).not.toHaveBeenCalled();+ });+ it("does not replay an ambiguous network failure", async () => {+ fetchMock.mockRejectedValue(new TypeError("fetch failed"));+ await expect(+ client.updateIssue(config.projectPath, 1, { title: "New" }),+ ).rejects.toThrow("fetch failed");+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});++describe("GitLab label reapplication", () => {+ it.each(["priority:medium", "status:to-do"])(+ "preserves %s when it is added and removed together",+ async (name) => {+ fetchMock+ .mockResolvedValueOnce(Response.json([{ id: 1, name }]))+ .mockResolvedValueOnce(Response.json(issue));+ await updateIssueLabelsGitlab(config, 1, { add: [name], remove: [name] });+ expect(JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body))).toEqual({+ add_labels: name,+ });+ },+ );+ it("still removes a replaced label", async () => {+ fetchMock+ .mockResolvedValueOnce(Response.json([{ id: 1, name: "priority:high" }]))+ .mockResolvedValueOnce(Response.json(issue));+ await updateIssueLabelsGitlab(config, 1, {+ add: ["priority:high"],+ remove: ["priority:medium"],+ });+ expect(JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body))).toEqual({+ add_labels: "priority:high",+ remove_labels: "priority:medium",+ });+ });+});