diff --git a/.changeset/clear-job-write-outcomes.md b/.changeset/clear-job-write-outcomes.md new file mode 100644 index 00000000..eec425a4 --- /dev/null +++ b/.changeset/clear-job-write-outcomes.md @@ -0,0 +1,5 @@ +--- +'@inkcre/core': patch +--- + +区分 Job 领取竞争、终态写入冲突和请求出错。执行结束后只尝试写入一次终态,收到数据库更新确认后才报告成功。 diff --git a/packages/core/src/job/job.ts b/packages/core/src/job/job.ts index e1e059fa..cfeeb60c 100644 --- a/packages/core/src/job/job.ts +++ b/packages/core/src/job/job.ts @@ -27,7 +27,9 @@ export class JobType extends Z.class({ static dbApi = new DBAPIClient<'job_types', JobType>('job_types', JobType) static async get(id: JobTypeRef): Promise { - return JobType.parse((await this.dbApi.from().select().eq('id', id).single()).data) + return JobType.parse( + (await this.dbApi.from().select().eq('id', id).single().throwOnError()).data + ) } static async getAll(): Promise { @@ -71,7 +73,7 @@ export class Job extends Z.class({ .order('created_at', { ascending: false }) .limit(options.limit ?? 20) if (options.status) query = query.eq('status', options.status) - return ((await query).data ?? []).map((item) => Job.parse(item)) + return ((await query.throwOnError()).data ?? []).map((item) => Job.parse(item)) } static async getBySource(source: number, limit = 20): Promise { diff --git a/packages/core/src/job/manager.ts b/packages/core/src/job/manager.ts index d86ce9b0..245e4a4f 100644 --- a/packages/core/src/job/manager.ts +++ b/packages/core/src/job/manager.ts @@ -8,7 +8,12 @@ import { type Context, } from '../obsrv/telemetry' import { z } from 'zod' -import { Job, JobStatus, JobType, type JobRef, type JobTypeRef } from './job' +import { Job, JobStatus, JobType, type JobRef, type JobStatusValue, type JobTypeRef } from './job' + +type TerminalJobStatus = Exclude< + JobStatusValue, + typeof JobStatus.PENDING | typeof JobStatus.RUNNING +> export interface JobHandler { parameters: Parameters @@ -70,6 +75,7 @@ export class JobManager { }) .select() .single() + .throwOnError() const job = Job.parse(result.data) span?.setAttribute('inkcre.job.id', job.id) emitJobEvent('job.submitted', job.id, active) @@ -94,18 +100,20 @@ export class JobManager { .eq('status', JobStatus.PENDING) .select() .maybeSingle() + .throwOnError() return result.data ? Job.parse(result.data) : null } - private static async close(job: Job, status: string): Promise { + private static async close(job: Job, status: TerminalJobStatus): Promise { const result = await Job.dbApi .update({ status, state: job.state }) .eq('id', job.id) .eq('status', JobStatus.RUNNING) .select('id') - const closed = (result.data?.length ?? 0) > 0 - if (closed) job.status = status as Job['status'] - return closed + .throwOnError() + if (!result.data?.length) + throw new Error(`Job ${job.id} no longer matches a running row while writing ${status}`) + job.status = status } static run(id: JobRef): Promise { @@ -207,26 +215,26 @@ export class JobManager { () => controller.abort(JobStatus.TIMED_OUT), claimed.timeout_seconds * 1000 ) + let status: TerminalJobStatus = JobStatus.FINISHED try { // An abort signal is only a request. Await actual handler settlement; // Promise.race would report closure while side effects were still running. await handler.handle(claimed, parameters, controller.signal) - await this.close( - claimed, - controller.signal.aborted ? String(controller.signal.reason) : JobStatus.FINISHED - ) } catch (error) { claimed.state = { ...claimed.state, error: error instanceof Error ? error.message : String(error), } - await this.close( - claimed, - controller.signal.aborted ? String(controller.signal.reason) : JobStatus.FAILED - ) + status = JobStatus.FAILED } finally { clearTimeout(timeout) } + if (controller.signal.aborted) { + status = + controller.signal.reason === JobStatus.TIMED_OUT ? JobStatus.TIMED_OUT : JobStatus.ABORTED + } + // A lost close response may follow a commit. Propagate the error without writing a second outcome. + await this.close(claimed, status) } static async checkAbortRequests(): Promise { @@ -237,6 +245,7 @@ export class JobManager { .select('id') .in('id', [...active.keys()]) .eq('abort_requested', true) + .throwOnError() for (const job of result.data ?? []) { active.get(job.id)?.controller.abort(JobStatus.ABORTED) } diff --git a/scripts/tests/job-cancellation.test.mjs b/scripts/tests/job-cancellation.test.mjs index 37ee9246..ffe3a5af 100644 --- a/scripts/tests/job-cancellation.test.mjs +++ b/scripts/tests/job-cancellation.test.mjs @@ -35,6 +35,14 @@ for (const scenario of [ handled: false, updates: ['running'], }, + { + name: 'a terminal write that matches no row does not report success', + cancelled: true, + eligible: false, + onClose: { status: 'timed_out' }, + closeConflict: true, + updates: ['running', 'aborted'], + }, ]) { void test(scenario.name, async (t) => { const prior = { ...configStore.metaConfig } @@ -59,6 +67,7 @@ for (const scenario of [ if (init.method === 'GET') return Response.json([job]) const fields = JSON.parse(init.body) if (fields.status === 'running') Object.assign(job, scenario.onClaim) + else Object.assign(job, scenario.onClose) const id = url.searchParams.get('id') const status = url.searchParams.get('status') updates.push({ method: init.method, id, status, next: fields.status }) @@ -75,7 +84,12 @@ for (const scenario of [ const handle = t.mock.fn(async () => {}) JobManager.registerHandler(job.type, { parameters: MetaConfigSchema, canHandle, handle }) try { - assert.equal(await JobManager.run(job.id), scenario.handled) + if (scenario.closeConflict) { + await assert.rejects(JobManager.run(job.id), /Job 81 no longer matches a running row/) + assert.equal(job.status, 'timed_out') + } else { + assert.equal(await JobManager.run(job.id), scenario.handled) + } assert.equal(canHandle.mock.callCount(), scenario.cancelled ? 0 : 1) assert.equal(handle.mock.callCount(), 0) assert.deepEqual( diff --git a/tests/e2e/peer-database.spec.ts b/tests/e2e/peer-database.spec.ts index 7a59ba1d..2a4f8350 100644 --- a/tests/e2e/peer-database.spec.ts +++ b/tests/e2e/peer-database.spec.ts @@ -716,6 +716,161 @@ test('disabling participation drains a dispatched claim before saving configurat } }) +test('Job execution distinguishes denied or competing claims, a conflicting close, and a lost close reply', async ({ + page, +}) => { + const authorization = `Bearer ${await token()}` + const headers = { Authorization: authorization, 'Content-Type': 'application/json' } + const type = `e2e.job-outcomes.${crypto.randomUUID()}` + const createdType = await fetch(`${postgrestUrl}job_types`, { + method: 'POST', + headers, + body: JSON.stringify({ + id: type, + description: 'Job transport outcomes', + parameters_schema: {}, + default_timeout_seconds: 3600, + }), + }) + expect(createdType.status).toBe(201) + try { + await page.goto('/sources') + await expect(page.getByRole('main')).toBeVisible() + await expect( + page.getByText( + 'Connecting this Web Peer; database pages are available, local jobs are not running yet.' + ) + ).toHaveCount(0) + + await page.evaluate(async (type) => { + type Sdk = typeof import('../../packages/core/src/index') + const globals = globalThis as typeof globalThis & { + __FEDERATION__: { + __INSTANCES__: Array<{ + options: { name: string } + loadShare(name: string): Promise<() => Sdk> + }> + } + runJobForTransportTest(id: number): Promise<{ accepted?: boolean; error?: string }> + } + const host = globals.__FEDERATION__.__INSTANCES__.find( + (instance) => instance.options.name === 'host' + )! + const { JobManager, MetaConfigSchema } = (await host.loadShare('@inkcre/core'))() + JobManager.startWorker(3_600_000) + JobManager.registerHandler(type, { + parameters: MetaConfigSchema, + canHandle: () => true, + handle: async (job) => { + job.state = { handlerCompleted: true } + }, + }) + globals.runJobForTransportTest = async (id) => { + try { + return { accepted: await JobManager.run(id) } + } catch (error) { + return { error: error instanceof Error ? error.message : String(error) } + } + } + }, type) + + for (const scenario of ['denied', 'competing', 'close-conflict', 'lost-reply'] as const) { + const created = await fetch(`${postgrestUrl}jobs`, { + method: 'POST', + headers: { ...headers, Prefer: 'return=representation' }, + body: JSON.stringify({ type, parameters: {}, timeout_seconds: 3600 }), + }) + expect(created.status).toBe(201) + const [{ id }] = (await created.json()) as Array<{ id: number }> + const jobUrl = `${postgrestUrl}jobs?id=eq.${id}` + const writes: string[] = [] + const routePattern = '**/jobs?**' + await page.route(routePattern, async (route) => { + const request = route.request() + if ( + request.method() !== 'PATCH' || + new URL(request.url()).searchParams.get('id') !== `eq.${id}` + ) { + await route.continue() + return + } + const { status } = request.postDataJSON() as { status: string } + writes.push(status) + if (scenario === 'denied') { + const response = await route.fetch({ + headers: { ...request.headers(), authorization: 'Bearer invalid-fixture' }, + }) + expect(response.status()).toBe(401) + await route.fulfill({ response }) + } else if (scenario === 'competing') { + const winner = await fetch(jobUrl, { + method: 'PATCH', + headers, + body: JSON.stringify({ status: 'running' }), + }) + expect(winner.ok).toBe(true) + await route.continue() + } else if (scenario === 'close-conflict' && status === 'finished') { + const winner = await fetch(`${jobUrl}&status=eq.running`, { + method: 'PATCH', + headers: { ...headers, Prefer: 'return=representation' }, + body: JSON.stringify({ status: 'timed_out' }), + }) + expect(winner.ok).toBe(true) + expect(await winner.json()).toMatchObject([{ status: 'timed_out' }]) + const conflict = await route.fetch() + expect(conflict.status()).toBe(200) + expect(await conflict.json()).toEqual([]) + await route.fulfill({ response: conflict }) + } else if (scenario === 'lost-reply' && status === 'finished') { + const committed = await route.fetch() + expect(committed.ok()).toBe(true) + await route.abort('failed') + } else { + await route.continue() + } + }) + try { + const result = await page.evaluate((id) => { + const globals = globalThis as typeof globalThis & { + runJobForTransportTest(id: number): Promise<{ accepted?: boolean; error?: string }> + } + return globals.runJobForTransportTest(id) + }, id) + const read = await fetch(`${jobUrl}&select=status,state`, { headers }) + expect(read.ok).toBe(true) + const persisted = await read.json() + if (scenario === 'denied') { + expect(result.error).toBeTruthy() + expect(result.accepted).toBeUndefined() + expect(writes).toEqual(['running']) + expect(persisted).toEqual([{ status: 'pending', state: {} }]) + } else if (scenario === 'competing') { + expect(result).toEqual({ accepted: false }) + expect(writes).toEqual(['running']) + expect(persisted).toEqual([{ status: 'running', state: {} }]) + } else if (scenario === 'close-conflict') { + expect(result).toEqual({ + error: `Job ${id} no longer matches a running row while writing finished`, + }) + expect(writes).toEqual(['running', 'finished']) + expect(persisted).toEqual([{ status: 'timed_out', state: {} }]) + } else { + expect(result.error).toBeTruthy() + expect(result.accepted).toBeUndefined() + expect(writes).toEqual(['running', 'finished']) + expect(persisted).toEqual([{ status: 'finished', state: { handlerCompleted: true } }]) + } + } finally { + await page.unroute(routePattern) + await fetch(jobUrl, { method: 'DELETE', headers }) + } + } + } finally { + await fetch(`${postgrestUrl}job_types?id=eq.${type}`, { method: 'DELETE', headers }) + } +}) + test('Registry confirmation selects one Peer and offline enablement preserves other native pins', async ({ page, }) => {