diff --git a/src/gitlab.ts b/src/gitlab.ts index c526667..cce5a32 100644 --- a/src/gitlab.ts +++ b/src/gitlab.ts @@ -307,6 +307,14 @@ export async function tokenCheck(kind: TokenKind, projects: string[]): Promise<{ export const botCheck = (projects: string[]) => tokenCheck('bot', projects); +// GitLab computes mergeability lazily and leaves it `unchecked` until someone asks; only a +// Developer or above may ask, so this runs as the merge account. The answer usually lands a +// few seconds later, so callers read the MR again on their next pass. +export async function recheckMergeStatus(ref: MrRef): Promise { + const m = await tokenApi('merge', 'GET', `projects/${encodeURIComponent(ref.projectPath)}/merge_requests/${ref.iid}?with_merge_status_recheck=true`); + return m.detailed_merge_status ?? null; +} + // Merges exactly `sha`: GitLab refuses when the head moved, so Gas never merges an unreviewed commit. export async function mergeMr(ref: MrRef, sha: string): Promise<{ mergeSha: string | null; state: string }> { const m = await tokenApi('merge', 'PUT', `projects/${encodeURIComponent(ref.projectPath)}/merge_requests/${ref.iid}/merge`, { sha }); diff --git a/src/hub.ts b/src/hub.ts index 911d64a..bfb6b10 100644 --- a/src/hub.ts +++ b/src/hub.ts @@ -47,6 +47,7 @@ export type Ports = { listNotes(ref: MrRef, afterId: number): Promise; postNote(ref: MrRef, body: string): Promise; updateNote(ref: MrRef, noteId: number, body: string): Promise; + recheckMergeStatus(ref: MrRef): Promise; mergeMr(ref: MrRef, sha: string): Promise<{ mergeSha: string | null; state: string }>; closeMr(ref: MrRef): Promise<{ state: string }>; pipelineFor(project: string, sha: string | null, ref: string): Promise<{ id: number; status: string; webUrl: string } | null>; @@ -67,6 +68,10 @@ export type Ports = { }; const MAX_ATTEMPTS = 3; +// GitLab statuses that mean "not computed yet", not "no": Gas asks for a recheck and waits. +const PENDING_MERGE_STATUS = new Set(['unchecked', 'checking', 'preparing', 'approvals_syncing']); +const MERGE_STATUS_WAIT_MS = 2 * 60_000; +const RECHECK_EVERY_MS = 30_000; export class Hub { readonly store: Store; @@ -76,6 +81,8 @@ export class Hub { readonly workRoot: string; readonly log: (line: string) => void; private lastDeployCheck = 0; + // When each waiting Gas last asked GitLab to recompute mergeability (in memory; a restart just asks again). + private rechecked = new Map(); private notifyRetryAt = 0; constructor(store: Store, config: HubConfig, reviewer: Reviewer, ports: Ports, workRoot: string, log: (line: string) => void = () => {}) { @@ -339,10 +346,13 @@ export class Hub { const a = this.store.ajuanById(ev.ajuan_id); try { const result = ev.kind === 'gas' ? await this.gas(a, ev, now) : ev.kind === 'close' ? await this.close(a, ev) : await this.announce(a, ev); + if (result === null) continue; // still waiting on GitLab; the claimed event runs again next tick + this.rechecked.delete(ev.id); this.store.finishEvent(ev.id, result); this.log(`${a.project} !${a.iid} ${ev.kind}: ${result}`); } catch (e: any) { // Not retried: a merge that failed is for the approver to look at and Gas again. + this.rechecked.delete(ev.id); const msg = String(e?.message ?? e).slice(0, 300); this.store.finishEvent(ev.id, `failed: ${msg}`); this.log(`${a.project} !${a.iid} ${ev.kind} gagal: ${msg}`); @@ -361,7 +371,8 @@ export class Hub { } // Every check runs again against GitLab at the moment of the merge; the board's view may be old. - private async gas(a: Ajuan, ev: QueuedEvent, now: number): Promise { + // Null: GitLab has not computed mergeability yet; try again on the next tick. + private async gas(a: Ajuan, ev: QueuedEvent, now: number): Promise { const ref = this.ref(a); const m = await this.ports.gitlab.mrSummary(ref); const by = ev.payload.by as string; @@ -376,6 +387,16 @@ export class Hub { if (a.status !== 'go') return refuse(`verdict sekarang ${a.status}`); if (m.sha !== a.reviewed_sha || ev.payload.sha !== a.reviewed_sha) return refuse('ada commit baru setelah review'); if (m.pipelineStatus && m.pipelineStatus !== 'success') return refuse(`pipeline MR ${m.pipelineStatus}`); + if (m.mergeStatus && PENDING_MERGE_STATUS.has(m.mergeStatus)) { + const waited = now - ev.payload.at - this.gasConfig.graceSeconds * 1000; + if (waited >= MERGE_STATUS_WAIT_MS) return refuse(`GitLab masih ${m.mergeStatus} setelah ${MERGE_STATUS_WAIT_MS / 60_000} menit`); + if (now - (this.rechecked.get(ev.id) ?? 0) >= RECHECK_EVERY_MS) { + this.rechecked.set(ev.id, now); + await this.ports.gitlab.recheckMergeStatus(ref); + this.log(`${a.project} !${a.iid} gas: GitLab ${m.mergeStatus}, minta cek ulang`); + } + return null; + } if (m.mergeStatus && m.mergeStatus !== 'mergeable') return refuse(`GitLab bilang ${m.mergeStatus}`); if (this.gasConfig.mode !== 'live') { this.store.update(a.id, { deploy_state: 'dry' }); diff --git a/test/hub.test.ts b/test/hub.test.ts index 4e1a1f4..5f924d1 100644 --- a/test/hub.test.ts +++ b/test/hub.test.ts @@ -43,6 +43,9 @@ function world(config: Partial = {}) { changes: { mrs: [], commits: [] } as { mrs: Array<{ iid: number; title: string; author: string }>; commits: Array<{ sha: string; title: string }> }, created: [] as Array<{ name: string; sha: string; message: string }>, closed: [] as number[], + // Asks for a mergeability recheck; what GitLab answers on the next read (null: it stays as it is). + rechecks: [] as number[], + recheckTo: 'mergeable' as string | null, }; const calls = { connect: [] as Array, review: [] as Array, ask: [] as string[] }; let outcomes: Array<() => any> = []; @@ -64,6 +67,13 @@ function world(config: Partial = {}) { updateNote: async (ref, id, body) => { gl.posted.push({ iid: ref.iid, id, body, edit: true }); }, + recheckMergeStatus: async (ref) => { + gl.rechecks.push(ref.iid); + const m = gl.mrs.get(ref.iid)!; + const before = m.mergeStatus ?? 'mergeable'; + if (gl.recheckTo) m.mergeStatus = gl.recheckTo; + return before; + }, mergeMr: async (ref, sha) => { const m = gl.mrs.get(ref.iid)!; if (m.sha !== sha) throw new Error('409 SHA does not match HEAD of source branch'); @@ -411,6 +421,34 @@ test('undo inside the grace period drops the Gas; a new commit drops it too', as assert.ok(w.gl.sent.some((t) => t.includes('Gas api !20 batal: ada commit baru'))); }); +test('Gas waits while GitLab has not computed mergeability, asking it to recheck', async () => { + const { w, a } = await readyAjuan(); + w.gl.mrs.get(20)!.mergeStatus = 'unchecked'; + decide(w.store, a.id, 'gas', 'sen', { sha: 'g1' }, T0); + await w.hub.tick(T0 + 16_000); + assert.deepEqual(w.gl.rechecks, [20], 'asks GitLab once'); + assert.deepEqual(w.gl.merges, [], 'does not merge on the first pass'); + assert.equal(w.store.ajuanById(a.id).decision, 'gas', 'keeps the decision while waiting'); + assert.ok(!w.gl.sent.some((t) => t.includes('tidak dijalankan'))); + await w.hub.tick(T0 + 21_000); + assert.deepEqual(w.gl.merges, [{ iid: 20, sha: 'g1' }]); + assert.deepEqual(w.gl.rechecks, [20]); +}); + +test('Gas gives up when GitLab stays unchecked, re-asking every 30 seconds', async () => { + const { w, a } = await readyAjuan(); + w.gl.mrs.get(20)!.mergeStatus = 'unchecked'; + w.gl.recheckTo = null; + decide(w.store, a.id, 'gas', 'sen', { sha: 'g1' }, T0); + for (let t = T0 + 16_000; t < T0 + 15_000 + 120_000; t += 5_000) await w.hub.tick(t); + assert.equal(w.gl.rechecks.length, 4); + assert.equal(w.store.ajuanById(a.id).decision, 'gas'); + await w.hub.tick(T0 + 15_000 + 120_000); + assert.deepEqual(w.gl.merges, []); + assert.equal(w.store.ajuanById(a.id).decision, null); + assert.ok(w.gl.sent.some((t) => t.includes('tidak dijalankan: GitLab masih unchecked setelah 2 menit'))); +}); + test('the Hub checks GitLab again before merging, and dry mode stops before the merge', async () => { const { w, a } = await readyAjuan(); w.gl.mrs.get(20)!.mergeStatus = 'conflict';