⚡ 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(api): keep deferred label adds and share the delivery deadline
Tin1ab360b91912
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts b/apps/api/src/plugins/gitea/webhooks/issue-labeled.tsindex 33722a796..ed6e17832 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts@@ -1,5 +1,8 @@import { resumeLabelChanges } from "../../sync/resume-label-changes";-import { syncLabelFieldsFromIssue } from "../../sync/sync-label-fields-from-issue";+import {+ labelReadDeadline,+ syncLabelFieldsFromIssue,+} from "../../sync/sync-label-fields-from-issue";import { acceptsIssue, readSyncRules } from "../../sync/rules";import { handleGiteaIssueOpened } from "./issue-opened";import { withIntegrationLink } from "../../github/services/with-integration-link";@@ -144,6 +147,7 @@ export async function handleGiteaIssueLabeled(repository.name,integrationId,);+ const deadline = labelReadDeadline();for (const integration of integrations) {try {@@ -174,7 +178,13 @@ export async function handleGiteaIssueLabeled(const fieldEvent = !addedLabel || isSystemLabelName(addedLabel.name);// label_updated has no single label, so it always reads the issue.// Status and priority never come from this payload's label snapshot.- if (fieldEvent) await syncLabelFieldsFromIssue(integration, existingLink);+ if (fieldEvent)+ await syncLabelFieldsFromIssue(+ integration,+ existingLink,+ undefined,+ deadline,+ );await withIntegrationLink(existingLink,diff --git a/apps/api/src/plugins/github/webhooks/issue-labeled.ts b/apps/api/src/plugins/github/webhooks/issue-labeled.tsindex 2bcf2c1d8..aef5eea50 100644--- a/apps/api/src/plugins/github/webhooks/issue-labeled.ts+++ b/apps/api/src/plugins/github/webhooks/issue-labeled.ts@@ -1,5 +1,8 @@import { resumeLabelChanges } from "../../sync/resume-label-changes";-import { syncLabelFieldsFromIssue } from "../../sync/sync-label-fields-from-issue";+import {+ labelReadDeadline,+ syncLabelFieldsFromIssue,+} from "../../sync/sync-label-fields-from-issue";import { acceptsIssue, readSyncRules } from "../../sync/rules";import { handleIssueOpened } from "./issue-opened";import { withIntegrationLink } from "../services/with-integration-link";@@ -32,6 +35,7 @@ export async function handleIssueLabeled(payload: IssueLabeledPayload) {const { issue, label: addedLabel } = payload;const integrations = await findAllIntegrationsByRepo(payload);+ const deadline = labelReadDeadline();for (const integration of integrations) {const existingLink = await findExternalLink(@@ -69,6 +73,7 @@ export async function handleIssueLabeled(payload: IssueLabeledPayload) {integration,existingLink,payload.action === "labeled" ? addedLabel?.name : null,+ deadline,);await withIntegrationLink(diff --git a/apps/api/src/plugins/sync/replay-deferred-label-fields.ts b/apps/api/src/plugins/sync/replay-deferred-label-fields.tsindex 26d52c09c..681199697 100644--- a/apps/api/src/plugins/sync/replay-deferred-label-fields.ts+++ b/apps/api/src/plugins/sync/replay-deferred-label-fields.ts@@ -31,11 +31,13 @@ async function replayClaimedLabelFields() {orderBy: asc(externalLinkTable.id),limit: BATCH,});- // A short batch reached the end; the next run starts from the first link.- if (links.length < BATCH) cursor = undefined;+ let finished = true;for (const link of links) {- if (Date.now() >= deadline) break;- if (links.length === BATCH) cursor = link.id;+ if (Date.now() >= deadline) {+ finished = false;+ break;+ }+ cursor = link.id;const integration = link.integration;try {if (@@ -59,5 +61,7 @@ async function replayClaimedLabelFields() {console.error("Deferred issue label replay failed", { linkId: link.id });}}+ // Only a completed final batch starts the next run from the first link.+ if (finished && links.length < BATCH) cursor = undefined;return { degraded };}diff --git a/apps/api/src/plugins/sync/sync-label-fields-from-issue.ts b/apps/api/src/plugins/sync/sync-label-fields-from-issue.tsindex 9832e1f4a..77eb39b35 100644--- a/apps/api/src/plugins/sync/sync-label-fields-from-issue.ts+++ b/apps/api/src/plugins/sync/sync-label-fields-from-issue.ts@@ -29,7 +29,15 @@ type Link = { id: string; taskId: string; externalId: string };type Metadata = {syncFieldLabels?: unknown;syncLabelFieldsDeferred?: unknown;+ syncLabelFieldsAdded?: unknown;};+const names = (value: unknown) =>+ Array.isArray(value)+ ? value.filter((name): name is string => typeof name === "string")+ : [];++/** The delivery-wide deadline shared by every integration a webhook reaches. */+export const labelReadDeadline = () => Date.now() + BUDGET_MS;const metadataOf = (link: { id: string; metadata: string | null }) =>parseLinkMetadata<Metadata>(link.metadata, {@@ -42,7 +50,7 @@ async function applyLabelFields(link: Link,labels: string[],deferred: unknown,- added: string | undefined,+ added: string[],) {await withIntegrationLink(link,@@ -56,14 +64,17 @@ async function applyLabelFields(const metadata = metadataOf(link);// Links from before this record only trust the label the event added.const known = Array.isArray(metadata.syncFieldLabels)- ? metadata.syncFieldLabels.filter((name) => typeof name === "string")- : labels.filter((name) => isFieldLabel(name) && name !== added);+ ? names(metadata.syncFieldLabels)+ : labels.filter((name) => isFieldLabel(name) && !added.includes(name));const { status, priority } = changedLabelFields(labels, known, task);await updateExternalLink(link.id,{metadata: {syncFieldLabels: labels.filter(isFieldLabel),+ ...(metadata.syncLabelFieldsAdded+ ? { syncLabelFieldsAdded: null }+ : {}),// A delivery deferred after this read began still needs its own....(deferred && metadata.syncLabelFieldsDeferred === deferred? { syncLabelFieldsDeferred: null }@@ -122,7 +133,15 @@ async function readAndApply(});if (!stored) return "done";const metadata = metadataOf(stored);- if (added === null && !Array.isArray(metadata.syncFieldLabels))+ const pending = [+ ...(added ? [added] : []),+ ...names(metadata.syncLabelFieldsAdded),+ ];+ if (+ added === null &&+ !pending.length &&+ !Array.isArray(metadata.syncFieldLabels)+ )return "done";const deferred = metadata.syncLabelFieldsDeferred;let labels: string[];@@ -142,13 +161,7 @@ async function readAndApply(});return "done";}- await applyLabelFields(- integration,- link,- labels,- deferred,- added ?? undefined,- );+ await applyLabelFields(integration, link, labels, deferred, pending);return "done";},{ maxWaitMs: LEASE_WAIT_MS },@@ -168,14 +181,19 @@ async function readAndApply(** Links from before `syncFieldLabels` existed have no record of the labels* Kaneo accounted for. They apply only `added`, the field label a webhook- * reports as added; `null` marks a removal, which leaves them untouched.- * Without either, the first read only records the labels.+ * reports as added, kept with a deferral until replay; `null` marks a+ * removal, which leaves them untouched. Without either, the first read only+ * records the labels. Pass one `deadline` for every integration a delivery+ * reaches.*/export async function syncLabelFieldsFromIssue(integration: Integration,link: Link,added?: string | null,+ deadline = labelReadDeadline(),) {+ const remaining = deadline - Date.now();+ if (remaining <= 0) return defer(integration, link, added);let timedOut = false;let timer: NodeJS.Timeout | undefined;const work = readAndApply(integration, link, added);@@ -191,14 +209,40 @@ export async function syncLabelFieldsFromIssue(timer = setTimeout(() => {timedOut = true;resolve("defer");- }, BUDGET_MS);+ }, remaining);});try {if ((await Promise.race([work, budget])) === "done") return;} finally {clearTimeout(timer);}- await updateExternalLink(link.id, {- metadata: { syncLabelFieldsDeferred: randomUUID() },+ await defer(integration, link, added);+}++// The row lock keeps concurrent deferrals from dropping each other's label.+async function defer(+ integration: Integration,+ link: Link,+ added: string | null | undefined,+) {+ await withIntegrationLink(link, integration, async (tx, _effects, link) => {+ const metadata = metadataOf(link);+ await updateExternalLink(+ link.id,+ {+ metadata: {+ syncLabelFieldsDeferred: randomUUID(),+ // Replay of a link without a record trusts only these labels.+ ...(added && !Array.isArray(metadata.syncFieldLabels)+ ? {+ syncLabelFieldsAdded: [+ ...new Set([...names(metadata.syncLabelFieldsAdded), added]),+ ],+ }+ : {}),+ },+ },+ tx,+ );});}diff --git a/tests/api-integration/integration-label-echo-loop.test.ts b/tests/api-integration/integration-label-echo-loop.test.tsindex 160fcfeea..67fd2b160 100644--- a/tests/api-integration/integration-label-echo-loop.test.ts+++ b/tests/api-integration/integration-label-echo-loop.test.ts@@ -486,7 +486,7 @@ it("gitea still syncs ordinary labels when the issue cannot be read", async () =expect((await f.metadataOf()).syncLabelFieldsDeferred).toBeUndefined();});-it("replay stops at its deadline and resumes on the next run", async () => {+it("replay moves past a link that keeps failing at its deadline", async () => {const first = await setup("gitea");const second = await setup("gitea");const [earlier, later] = [first, second].sort((a, b) =>@@ -502,19 +502,68 @@ it("replay stops at its deadline and resumes on the next run", async () => {}),}).where(eq(schema.externalLinkTable.id, f.link.id));+ const token = async (f: typeof earlier) =>+ (await f!.metadataOf()).syncLabelFieldsDeferred;vi.useFakeTimers({ toFake: ["Date"] });try {- // The first read runs past the run's deadline.+ // Every read fails transiently and runs past the run's deadline.mocks.onRead = () => {- mocks.onRead = undefined;vi.setSystemTime(Date.now() + 46_000);+ throw Object.assign(new Error("unavailable"), { status: 503 });};await replayDeferredLabelFields();- expect((await earlier!.metadataOf()).syncLabelFieldsDeferred).toBeNull();- expect((await later!.metadataOf()).syncLabelFieldsDeferred).toBe("queued");+ expect(await token(earlier)).not.toBe("queued");+ expect(await token(later)).toBe("queued");await replayDeferredLabelFields();- expect((await later!.metadataOf()).syncLabelFieldsDeferred).toBeNull();+ expect(await token(later)).not.toBe("queued");} finally {vi.useRealTimers();}});++it("github replays the event's label for a deferred link without a record", async () => {+ const f = await setup("github", {});+ const lease = `sync-field-labels:${f.link.id}`;+ await db.insert(schema.jobLeaseTable).values({+ name: lease,+ owner: "slow-reader",+ expiresAt: new Date(Date.now() + 60_000),+ });+ change("labeled", "status:in-review");+ await f.receive(mocks.deliveries.shift()!);+ expect(await f.metadataOf()).toMatchObject({+ syncLabelFieldsAdded: ["status:in-review"],+ });++ await db+ .delete(schema.jobLeaseTable)+ .where(eq(schema.jobLeaseTable.name, lease));+ await replayDeferredLabelFields();+ expect(await f.status()).toBe("in-review");+ // Only the event's label applied; the leftover old label is recorded.+ expect(await f.metadataOf()).toMatchObject({+ syncFieldLabels: ["status:to-do", "status:in-review"],+ syncLabelFieldsAdded: null,+ syncLabelFieldsDeferred: null,+ });+}, 15_000);++it("github shares one delivery budget across integrations", async () => {+ const first = await setup("github");+ const second = await setup("github");+ let release!: () => void;+ mocks.readGate = new Promise((resolve) => {+ release = resolve;+ });+ change("labeled", "status:in-review");+ const started = Date.now();+ await first.receive(mocks.deliveries.shift()!);+ expect(Date.now() - started).toBeLessThan(9_500);+ for (const f of [first, second])+ expect((await f.metadataOf()).syncLabelFieldsDeferred).toEqual(+ expect.any(String),+ );+ // Let the stalled read finish before the next test resets the database.+ release();+ await vi.waitFor(async () => expect(await first.status()).toBe("in-review"));+}, 25_000);