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(integrations): bound and coalesce corrective provider writes

Tin16ba4fa74876
diff --git a/apps/api/src/plugins/github/services/defer-issue-edit.ts b/apps/api/src/plugins/github/services/defer-issue-edit.ts
new file mode 100644
index 000000000..424a8cfe6
--- /dev/null
+++ b/apps/api/src/plugins/github/services/defer-issue-edit.ts
@@ -0,0 +1,57 @@
+import { issueEditScope, type IssueField } from "../utils/deferred-issue-edit";
+import { updateExternalLink } from "./link-manager";
+import { withIntegrationLink } from "./with-integration-link";
+type Integration = {
+ id: string;
+ projectId: string;
+ type: string;
+ config: string;
+};
+// Commit the intent before acknowledging a delivery which cannot wait for its writer.
+export async function deferIssueEdit(
+ link: { id: string; taskId: string },
+ integration: Integration,
+ fields: IssueField[],
+) {
+ await withIntegrationLink(
+ link,
+ integration,
+ async (tx) => {
+ await updateExternalLink(
+ link.id,
+ { deferredEdit: { fields, scope: issueEditScope(integration) } },
+ tx,
+ );
+ },
+ {
+ validate: (binding) =>
+ issueEditScope(binding) === issueEditScope(integration),
+ },
+ );
+}
+
+// Coalesce remaining local corrections by link and field without storing task text.
+export async function deferTaskSync(
+ link: { id: string; taskId: string },
+ integration: Integration,
+ fields: IssueField[],
+) {
+ await withIntegrationLink(
+ link,
+ integration,
+ async (tx) => {
+ await updateExternalLink(
+ link.id,
+ {
+ deferredEdit: {
+ fields: [],
+ repairFields: fields,
+ scope: issueEditScope(integration),
+ },
+ },
+ tx,
+ );
+ },
+ integration,
+ );
+}
diff --git a/apps/api/src/plugins/github/services/deferred-issue-edits.ts b/apps/api/src/plugins/github/services/deferred-issue-edits.ts
index 6e413ff7e..7af1c65e4 100644
--- a/apps/api/src/plugins/github/services/deferred-issue-edits.ts
+++ b/apps/api/src/plugins/github/services/deferred-issue-edits.ts
@@ -47,28 +47,7 @@ const metadataFor = (link: { id: string; metadata: string | null }) =>
source: "deferred_issue_edit",
});
-// Commit the intent before acknowledging a delivery which cannot wait for its writer.
-export async function deferIssueEdit(
- link: { id: string; taskId: string },
- integration: Integration,
- fields: IssueField[],
-) {
- await withIntegrationLink(
- link,
- integration,
- async (tx) => {
- await updateExternalLink(
- link.id,
- { deferredEdit: { fields, scope: issueEditScope(integration) } },
- tx,
- );
- },
- {
- validate: (binding) =>
- issueEditScope(binding) === issueEditScope(integration),
- },
- );
-}
+export { deferIssueEdit } from "./defer-issue-edit";
async function issueAccess(
integration: Integration,
@@ -156,9 +135,12 @@ export async function replayDeferredIssueEdits() {
await updateExternalLink(link.id, { completeDeferredEdit: job.id });
continue;
}
+ const fields = [
+ ...new Set([...job.fields, ...(job.repairFields ?? [])]),
+ ];
// An orphaned writer expires after five minutes; until then let it settle.
if (
- job.fields.some((field) =>
+ fields.some((field) =>
metadata.lastSync?.[field]?.outbound?.some(
(entry) =>
entry.pending &&
@@ -230,7 +212,7 @@ export async function replayDeferredIssueEdits() {
)
return;
if (
- job.fields.some(
+ fields.some(
(field) =>
JSON.stringify(current.lastSync?.[field]) !==
JSON.stringify(metadata.lastSync?.[field]),
@@ -250,7 +232,7 @@ export async function replayDeferredIssueEdits() {
columns: { title: true, description: true, status: true },
});
if (!task) return;
- for (const field of job.fields) {
+ for (const field of fields) {
const stamp = current.lastSync?.[field];
const uncertain = uncertainOutboundIntent(stamp, values[field]);
const local =
@@ -261,6 +243,14 @@ export async function replayDeferredIssueEdits() {
: field === "description"
? task.description || ""
: task.title;
+ if (job.repairFields?.includes(field)) {
+ repairs.push({
+ field,
+ value: local,
+ providerValue: values[field],
+ });
+ continue;
+ }
// A crashed older writer can leave the provider behind our completed
// local value. Its missing receipt does not make it a remote edit.
if (
diff --git a/apps/api/src/plugins/github/services/link-manager.ts b/apps/api/src/plugins/github/services/link-manager.ts
index 0ecebead7..41169bcdf 100644
--- a/apps/api/src/plugins/github/services/link-manager.ts
+++ b/apps/api/src/plugins/github/services/link-manager.ts
@@ -29,7 +29,11 @@ export type CreateExternalLinkParams = {
};
export type UpdateExternalLinkParams = {
- deferredEdit?: { fields: IssueField[]; scope: string };
+ deferredEdit?: {
+ fields: IssueField[];
+ repairFields?: IssueField[];
+ scope: string;
+ };
completeDeferredEdit?: string;
outbound?: {
field: "title" | "description" | "state";
@@ -162,10 +166,19 @@ export async function updateExternalLink(
if (params.completeDeferredEdit === previousJob?.id)
delete merged.deferredIssueEdit;
if (params.deferredEdit) {
- const { fields, scope } = params.deferredEdit;
+ const { fields, repairFields = [], scope } = params.deferredEdit;
+ const repairs = [
+ ...new Set([
+ ...(previousJob?.scope === scope
+ ? (previousJob.repairFields ?? [])
+ : []),
+ ...repairFields,
+ ]),
+ ];
merged.deferredIssueEdit = {
id: randomUUID(),
scope,
+ ...(repairs.length ? { repairFields: repairs } : {}),
fields: [
...new Set([
...(previousJob?.scope === scope ? previousJob.fields : []),
diff --git a/apps/api/src/plugins/github/services/sync-latest-task-value.ts b/apps/api/src/plugins/github/services/sync-latest-task-value.ts
index c504d684a..b66020fbe 100644
--- a/apps/api/src/plugins/github/services/sync-latest-task-value.ts
+++ b/apps/api/src/plugins/github/services/sync-latest-task-value.ts
@@ -1,3 +1,4 @@
+import { deferTaskSync } from "./defer-issue-edit";
import { randomUUID } from "node:crypto";
import db from "../../../database";
import { parseLinkMetadata } from "../utils/parse-link-metadata";
@@ -22,6 +23,7 @@ export async function syncLatestTaskValue(
expectedBinding?: { type?: string; config?: string },
) {
let value = initialValue;
+ let attempts = 0;
let identity = expectedBinding;
const currentBinding = async () => {
const binding = (await findExternalLinksByTask(taskId)).find(
@@ -58,6 +60,7 @@ export async function syncLatestTaskValue(
let updatedAt: string | undefined;
try {
updatedAt = await write(value);
+ attempts++;
} catch (error) {
const status =
typeof error === "object" && error && "status" in error
@@ -135,6 +138,13 @@ export async function syncLatestTaskValue(
? task.title
: task.description || "";
if (current === value) return;
+ if (attempts >= 3) {
+ if (binding.integration)
+ await deferTaskSync({ id: link.id, taskId }, binding.integration, [
+ field,
+ ]);
+ return;
+ }
value = current;
}
}
diff --git a/apps/api/src/plugins/github/utils/deferred-issue-edit.ts b/apps/api/src/plugins/github/utils/deferred-issue-edit.ts
index 4fb5a7ee7..43db72a72 100644
--- a/apps/api/src/plugins/github/utils/deferred-issue-edit.ts
+++ b/apps/api/src/plugins/github/utils/deferred-issue-edit.ts
@@ -5,6 +5,7 @@ export type IssueField = "title" | "description" | "state";
export type DeferredIssueEdit = {
id: string;
fields: IssueField[];
+ repairFields?: IssueField[];
scope: string;
};
@@ -17,7 +18,12 @@ export function parseDeferredIssueEdit(
typeof job.id !== "string" ||
typeof job.scope !== "string" ||
!Array.isArray(job.fields) ||
- !job.fields.length ||
+ (job.repairFields !== undefined &&
+ (!Array.isArray(job.repairFields) ||
+ job.repairFields.some(
+ (field) => !["title", "description", "state"].includes(field),
+ ))) ||
+ (!job.fields.length && !job.repairFields?.length) ||
job.fields.some(
(field) => !["title", "description", "state"].includes(field),
)
diff --git a/tests/api-integration/deferred-issue-edits.test.ts b/tests/api-integration/deferred-issue-edits.test.ts
index 664ba0d52..04603b234 100644
--- a/tests/api-integration/deferred-issue-edits.test.ts
+++ b/tests/api-integration/deferred-issue-edits.test.ts
@@ -6,6 +6,8 @@ import {
deferIssueEdit,
replayDeferredIssueEdits,
} from "../../apps/api/src/plugins/github/services/deferred-issue-edits";
+import { deferTaskSync } from "../../apps/api/src/plugins/github/services/defer-issue-edit";
+import { syncLatestTaskValue } from "../../apps/api/src/plugins/github/services/sync-latest-task-value";
import { updateExternalLink } from "../../apps/api/src/plugins/github/services/link-manager";
import { handleGiteaIssueEdited } from "../../apps/api/src/plugins/gitea/webhooks/issue-edited";
import { handleIssueEdited } from "../../apps/api/src/plugins/github/webhooks/issue-edited";
@@ -1027,3 +1029,143 @@ it.each(["github", "gitea"])(
expect(publishEvent).not.toHaveBeenCalled();
},
);
+
+it.each(
+ (["github", "gitea"] as const).flatMap((provider) =>
+ (["title", "description", "state"] as const).map((field) => ({
+ provider,
+ field,
+ })),
+ ),
+)(
+ "bounds sustained $provider/$field correction and durably syncs the latest task",
+ async ({ provider, field }) => {
+ const { task, integration, link } = await seed(provider);
+ await db
+ .update(schema.externalLinkTable)
+ .set({ metadata: "{}" })
+ .where(eq(schema.externalLinkTable.id, link.id));
+ const initial = field === "state" ? "open" : "A";
+ const column = field === "state" ? "status" : field;
+ const write = vi.fn(async () => {
+ if (write.mock.calls.length > 6)
+ throw new Error("unbounded repair regression");
+ await db
+ .update(schema.taskTable)
+ .set({
+ [column]:
+ field === "state"
+ ? write.mock.calls.length % 2
+ ? "done"
+ : "to-do"
+ : `edit-${write.mock.calls.length}`,
+ })
+ .where(eq(schema.taskTable.id, task.id));
+ return "2026-09-30T00:00:04Z";
+ });
+ await syncLatestTaskValue(
+ task.id,
+ integration.projectId,
+ link,
+ field,
+ initial,
+ write,
+ ).catch(() => undefined);
+ expect(write).toHaveBeenCalledTimes(3);
+ expect((await metadata(link.id)).deferredIssueEdit).toMatchObject({
+ fields: [],
+ repairFields: [field],
+ });
+ expect(JSON.stringify(await metadata(link.id))).not.toContain(
+ "test-secret-never-metadata",
+ );
+ const latest = field === "state" ? "closed" : "latest local";
+ await db
+ .update(schema.taskTable)
+ .set({ [column]: field === "state" ? "done" : latest })
+ .where(eq(schema.taskTable.id, task.id));
+ await replayDeferredIssueEdits();
+ expect(m.write).toHaveBeenCalledTimes(1);
+ expect(m.write).toHaveBeenCalledWith(
+ expect.objectContaining(
+ field === "description"
+ ? { body: expect.stringContaining(latest) }
+ : { [field]: latest },
+ ),
+ );
+ expect((await current(task.id))?.[column]).toBe(
+ field === "state" ? "done" : latest,
+ );
+ expect((await metadata(link.id)).deferredIssueEdit).toBeUndefined();
+ expect(publishEvent).not.toHaveBeenCalled();
+ },
+);
+
+it("coalesces local correction fields with inbound deliveries without importing stale values", async () => {
+ const { task, integration, link } = await seed();
+ await db
+ .update(schema.externalLinkTable)
+ .set({ metadata: "{}" })
+ .where(eq(schema.externalLinkTable.id, link.id));
+ await Promise.all([
+ deferTaskSync(link, integration, ["title"]),
+ deferTaskSync(link, integration, ["description"]),
+ deferIssueEdit(link, integration, ["state"]),
+ ]);
+ const job = (await metadata(link.id)).deferredIssueEdit;
+ expect(job.fields).toEqual(["state"]);
+ expect(job.repairFields.sort()).toEqual(["description", "title"]);
+ await replayDeferredIssueEdits();
+ expect(await current(task.id)).toMatchObject({
+ title: "B",
+ description: "old body",
+ status: "done",
+ });
+ expect(m.write).toHaveBeenCalledTimes(2);
+ expect((await metadata(link.id)).deferredIssueEdit).toBeUndefined();
+});
+it("retains failed queued corrections and retries the current task value", async () => {
+ const { task, integration, link } = await seed();
+ await db
+ .update(schema.externalLinkTable)
+ .set({ metadata: "{}" })
+ .where(eq(schema.externalLinkTable.id, link.id));
+ await deferTaskSync(link, integration, ["title"]);
+ m.write.mockRejectedValueOnce(new Error("provider unavailable"));
+ expect(await replayDeferredIssueEdits()).toEqual({ degraded: true });
+ expect((await metadata(link.id)).deferredIssueEdit.repairFields).toEqual([
+ "title",
+ ]);
+ await db
+ .update(schema.taskTable)
+ .set({ title: "latest" })
+ .where(eq(schema.taskTable.id, task.id));
+ await replayDeferredIssueEdits();
+ expect(m.write).toHaveBeenLastCalledWith(
+ expect.objectContaining({ title: "latest" }),
+ );
+ expect((await current(task.id))?.title).toBe("latest");
+ expect((await metadata(link.id)).deferredIssueEdit).toBeUndefined();
+ expect(publishEvent).not.toHaveBeenCalled();
+});
+it("preserves a newer correction queued while its worker reads the provider", async () => {
+ const { integration, link } = await seed();
+ await db
+ .update(schema.externalLinkTable)
+ .set({ metadata: "{}" })
+ .where(eq(schema.externalLinkTable.id, link.id));
+ await deferTaskSync(link, integration, ["title"]);
+ const first = (await metadata(link.id)).deferredIssueEdit.id;
+ m.read.mockImplementationOnce(async () => {
+ await deferTaskSync(link, integration, ["description"]);
+ return { title: "A", body: "remote", state: "open" };
+ });
+ await replayDeferredIssueEdits();
+ expect(m.write).not.toHaveBeenCalled();
+ const next = (await metadata(link.id)).deferredIssueEdit;
+ expect(next.id).not.toBe(first);
+ expect(next.repairFields.sort()).toEqual(["description", "title"]);
+ await replayDeferredIssueEdits();
+ expect(m.write).toHaveBeenCalledTimes(2);
+ expect((await metadata(link.id)).deferredIssueEdit).toBeUndefined();
+});