Repository navigation
fix(client): retry transient Accelerate failures in RemoteExecutor #30766
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
SahinurDEV
wants to merge
2
commits into
prisma:v7
Choose a base branch
from
SahinurDEV:fix/accelerate-retry
base: v7
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
181 changes: 181 additions & 0 deletions
181
packages/client/src/runtime/core/engines/client/RemoteExecutor.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| import { PrismaClientKnownRequestError } from '@prisma/client-runtime-utils' | ||
| import { EventEmitter } from 'events' | ||
|
|
||
| import { disabledTracingHelper } from '../../tracing/TracingHelper' | ||
| import type { AccelerateExtensionFetch } from '../common/Engine' | ||
| import type { LogEmitter, LogEvent } from '../common/types/Events' | ||
| import { RemoteExecutor } from './RemoteExecutor' | ||
|
|
||
| const ACCELERATE_URL = 'prisma://accelerate.prisma-data.net/?api_key=test-api-key' | ||
|
|
||
| const connectionInfo = { provider: 'postgres', connectionInfo: { supportsRelationJoins: true } } | ||
|
|
||
| function jsonResponse(body: unknown, status = 200): Response { | ||
| return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) | ||
| } | ||
|
|
||
| function networkError(): TypeError { | ||
| return new TypeError('fetch failed', { cause: new Error('other side closed') }) | ||
| } | ||
|
|
||
| function setup(responses: Array<Response | Error>) { | ||
| const warnings: string[] = [] | ||
| const logEmitter = new EventEmitter() as unknown as LogEmitter | ||
| logEmitter.on('warn', (event: LogEvent) => warnings.push(event.message)) | ||
|
|
||
| const executor = new RemoteExecutor({ | ||
| clientVersion: '0.0.0', | ||
| accelerateUrl: ACCELERATE_URL, | ||
| logEmitter, | ||
| logLevel: 'info', | ||
| logQueries: false, | ||
| tracingHelper: disabledTracingHelper, | ||
| }) | ||
|
|
||
| const fetch = jest.fn<ReturnType<AccelerateExtensionFetch>, Parameters<AccelerateExtensionFetch>>(() => { | ||
| const next = responses.shift() | ||
| if (next === undefined) { | ||
| throw new Error('unexpected request') | ||
| } | ||
| return next instanceof Response ? Promise.resolve(next) : Promise.reject(next) | ||
| }) | ||
|
|
||
| return { executor, fetch, warnings } | ||
| } | ||
|
|
||
| function execute(executor: RemoteExecutor, fetch: AccelerateExtensionFetch) { | ||
| return executor.execute({ | ||
| plan: { type: 'value', args: 1 } as never, | ||
| placeholderValues: {}, | ||
| model: 'User', | ||
| operation: 'findMany', | ||
| transaction: undefined, | ||
| batchIndex: undefined, | ||
| customFetch: fetch, | ||
| queryInfo: { type: 'single', modelName: 'User', action: 'findMany', query: {} }, | ||
| }) | ||
| } | ||
|
|
||
| describe('RemoteExecutor retries', () => { | ||
| let globalFetch: jest.SpyInstance | ||
|
|
||
| beforeEach(() => { | ||
| globalFetch = jest.spyOn(globalThis, 'fetch') | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| globalFetch.mockRestore() | ||
| }) | ||
|
|
||
| test('retries a request whose fetch rejects with a network error', async () => { | ||
| const { executor, fetch, warnings } = setup([networkError(), networkError(), jsonResponse({ data: [] })]) | ||
|
|
||
| await expect(execute(executor, fetch)).resolves.toEqual([]) | ||
|
|
||
| expect(fetch).toHaveBeenCalledTimes(3) | ||
| expect(warnings).toEqual([ | ||
| 'Attempt 1/3 failed for POST /query: fetch failed', | ||
| expect.stringMatching(/^Retrying after \d+ms$/), | ||
| 'Attempt 2/3 failed for POST /query: fetch failed', | ||
| expect.stringMatching(/^Retrying after \d+ms$/), | ||
| ]) | ||
| }) | ||
|
|
||
| test('sends the same request again on retry', async () => { | ||
| const { executor, fetch } = setup([networkError(), jsonResponse({ data: [] })]) | ||
|
|
||
| await execute(executor, fetch) | ||
|
|
||
| const [first, second] = fetch.mock.calls | ||
| expect(second[0]).toEqual(first[0]) | ||
| expect(second[1].method).toEqual(first[1].method) | ||
| expect(second[1].body).toEqual(first[1].body) | ||
| }) | ||
|
|
||
| test.each([500, 502, 503])('retries a %d response', async (status) => { | ||
| const { executor, fetch, warnings } = setup([ | ||
| jsonResponse({ message: 'Worker exceeded resource limits' }, status), | ||
| jsonResponse({ data: [] }), | ||
| ]) | ||
|
|
||
| await expect(execute(executor, fetch)).resolves.toEqual([]) | ||
|
|
||
| expect(fetch).toHaveBeenCalledTimes(2) | ||
| expect(warnings[0]).toEqual(`Attempt 1/3 failed for POST /query: HTTP ${status}`) | ||
| }) | ||
|
|
||
| test('does not put the response body of a retried request in the logs', async () => { | ||
| const { executor, fetch, warnings } = setup([ | ||
| new Response(JSON.stringify({ message: 'internal details: secret-value' }), { | ||
| status: 503, | ||
| statusText: 'Service Unavailable', | ||
| }), | ||
| jsonResponse({ data: [] }), | ||
| ]) | ||
|
|
||
| await expect(execute(executor, fetch)).resolves.toEqual([]) | ||
|
|
||
| expect(warnings[0]).toEqual('Attempt 1/3 failed for POST /query: HTTP 503 Service Unavailable') | ||
| expect(warnings.join('\n')).not.toContain('secret-value') | ||
| }) | ||
|
|
||
| test.each([ | ||
| ['AbortError', 'This operation was aborted'], | ||
| ['TimeoutError', 'The operation was aborted due to timeout'], | ||
| ])('does not retry a request cancelled with %s', async (name, message) => { | ||
| const error = new DOMException(message, name) | ||
| const { executor, fetch, warnings } = setup([error, jsonResponse({ data: [] })]) | ||
|
|
||
| await expect(execute(executor, fetch)).rejects.toBe(error) | ||
|
|
||
| expect(fetch).toHaveBeenCalledTimes(1) | ||
| expect(warnings).toEqual([]) | ||
| }) | ||
|
|
||
| test('retries requests that use the global fetch', async () => { | ||
| const { executor } = setup([]) | ||
| globalFetch.mockRejectedValueOnce(networkError()).mockResolvedValueOnce(jsonResponse(connectionInfo)) | ||
|
|
||
| await expect(executor.getConnectionInfo()).resolves.toEqual(connectionInfo) | ||
| expect(globalFetch).toHaveBeenCalledTimes(2) | ||
| }) | ||
|
|
||
| test('rethrows the network error after the last retry', async () => { | ||
| const error = networkError() | ||
| const { executor, fetch, warnings } = setup([error, error, error, error]) | ||
|
|
||
| await expect(execute(executor, fetch)).rejects.toBe(error) | ||
|
|
||
| expect(fetch).toHaveBeenCalledTimes(4) | ||
| expect(warnings.filter((message) => message.startsWith('Attempt'))).toHaveLength(3) | ||
| }) | ||
|
|
||
| test('reports the last server error after the last retry', async () => { | ||
| const { executor, fetch } = setup([ | ||
| jsonResponse({ message: 'first' }, 503), | ||
| jsonResponse({ message: 'second' }, 503), | ||
| jsonResponse({ message: 'third' }, 503), | ||
| jsonResponse({ message: 'last' }, 503), | ||
| ]) | ||
|
|
||
| const result = execute(executor, fetch) | ||
|
|
||
| await expect(result).rejects.toBeInstanceOf(PrismaClientKnownRequestError) | ||
| await expect(result).rejects.toMatchObject({ message: 'last', code: 'P6000' }) | ||
| expect(fetch).toHaveBeenCalledTimes(4) | ||
| }) | ||
|
|
||
| test.each([ | ||
| [400, { code: 'P2002', error: 'Unique constraint failed on the fields: (`email`)' }], | ||
| [409, { code: 'P2028', error: 'Transaction already closed' }], | ||
| [422, { error: 'Query exceeded the response size limit' }], | ||
| [504, { message: 'Query timed out' }], | ||
| ])('does not retry a %d response', async (status, body) => { | ||
| const { executor, fetch, warnings } = setup([jsonResponse(body, status)]) | ||
|
|
||
| await expect(execute(executor, fetch)).rejects.toBeInstanceOf(PrismaClientKnownRequestError) | ||
|
|
||
| expect(fetch).toHaveBeenCalledTimes(1) | ||
| expect(warnings).toEqual([]) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
16 changes: 16 additions & 0 deletions
16
packages/client/src/runtime/core/engines/client/utils/backoff.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| const BACKOFF_INTERVAL_MS = 50 | ||
|
|
||
| /** | ||
| * Waits for an exponentially growing, jittered delay before retry number | ||
| * `attempt` (0-based) and resolves with the delay that was used. | ||
| * | ||
| * Same schedule as the `DataProxyEngine` of Prisma 6: roughly 50ms, 100ms, | ||
| * 200ms, ... each with up to ±50% jitter. | ||
| */ | ||
| export function backOff(attempt: number): Promise<number> { | ||
| const baseDelay = Math.pow(2, attempt) * BACKOFF_INTERVAL_MS | ||
| const jitter = Math.ceil(Math.random() * baseDelay) - Math.ceil(baseDelay / 2) | ||
| const delay = baseDelay + jitter | ||
|
|
||
| return new Promise((resolve) => setTimeout(() => resolve(delay), delay)) | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧹 Nitpick | 🔵 Trivial
Decide whether to replay non-idempotent requests after a network error.
#requestnow retries everyfetchrejection, includingPOST /transaction/startandPOST /querywith write operations. After a network error, the client cannot know whether the server processed the request. The client sends no idempotency key. A retry can duplicate a write. A retry can also start a second transaction that stays open until timeout.The PR states that this matches Prisma 6 behavior, so this is a maintainer decision. Confirm the decision is intended. Consider limiting retries of writes and
/transaction/startto failures where the request is known not to have reached the server.🤖 Prompt for AI Agents
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Agreed that this is the maintainers' call. I wrote up the trade-off in this comment: the PR currently keeps Prisma 6 behaviour (a), and I can switch to retrying only reads, commit and rollback (b) if that is preferred. I'll wait for a maintainer to decide before changing it.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@SahinurDEV Thanks for clarifying. The trade-off is documented. No change is needed before maintainers choose the retry policy. This finding remains open pending that decision.
You are interacting with an AI system.