diff --git a/CHANGELOG.md b/CHANGELOG.md index 574795a4..44442748 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,33 @@ +## Unreleased + +Added the JavaScript side of two native changes that come later. One +behavior changes now: every handler's `meta` has `ambiguousAttempts`, which +is 0 for today's events. A test that compares the whole `meta` object, and a +`Meta` built by hand, need the new field. Nothing else changes until native +code sends the new fields. + +- `Meta.ambiguousAttempts` (a number) counts the attempts of the current + generation that ended with no answer from the server after the whole + request can have reached it. The library sends the request again after + each one, so a count above 0 means the server can have more than one copy. + It reads 0 when native does not send it, which is the case for now. +- `AttemptEvent.bodySent` (`'none' | 'partial' | 'full'`, optional) says how + much of the request body had left when the attempt ended. +- `RawResponse.bodyUnknown` (`true`, optional) marks a request the server + accepted whose response body the library did not get. The outcome is + `completed`, is never sent again, and is never the `truncated` error. A + definition without a `response` parser gets it in `onSuccess`. A + definition with one gets the new optional handler + `onBodyUnknown(response, vars, meta)` instead of the parser and + `onSuccess`. A definition with a parser and `onSuccess` but no + `onBodyUnknown` gets no call: the outcome is held unacknowledged with a + warning per outcome, and is delivered when a `define()` of the key adds + the handler, or at the next launch. With neither `onSuccess` nor + `onBodyUnknown`, the outcome is acknowledged with no call. +- `createFakeNative()` can settle such an outcome + (`response: { bodyUnknown: true }`) and set `ambiguousAttempts` in the + overrides. + ## 11.3.0 Added `useRequests(filter?)` and `useRequestsWithProgress(filter?)`, React diff --git a/README.md b/README.md index 525c964f..e8802d55 100644 --- a/README.md +++ b/README.md @@ -351,6 +351,7 @@ Retry classes: | payload missing on disk | settle `error` with `errorKind: 'file'` | | `expiresAt` passed | settle `error` with `errorKind: 'expired'`; bytes kept | | response body over 1 MB with a `response` parser | `onError` with `errorKind: 'truncated'`; the entry is `completed` | +| accepted, but the response body was not received (`bodyUnknown`; not yet sent by native) | settle `completed`; never sent again. Without a `response` parser, `onSuccess` gets the response with `bodyUnknown: true`. With one, `onBodyUnknown` runs instead. See "Accepted, body unknown" below | **Transient rule counts.** The library counts the responses each rule excuses. It keeps the count by the rule's `status` and `bodyIncludes`, not by @@ -367,6 +368,59 @@ its place in the list: - A same-id `mutate()` that reopens a settled entry starts every count at 0. A same-id `mutate()` on a live entry keeps the counts. +**Accepted, body unknown.** Sometimes the library knows the server accepted +a request but did not get the response body. For example, the status line +said 201 and the connection dropped before the body arrived. The request is +done: the library does not send it again, and it is not an error. The +outcome is `completed`, and its `RawResponse` has `bodyUnknown: true` and no +`body`. This is not `bodyTruncated`, which means the body was over 1 MB. + +The app handles it in one place, typically by fetching the object from the +server: + +- A definition without a `response` parser gets it in `onSuccess`, like any + completed outcome. Check `response.bodyUnknown` there. Once native sends + the flag, an `onSuccess` that reads `response.body` without that check + throws on such a response, and a handler that throws is delivered again + at every launch. +- A definition with a parser cannot get typed data, so the parser and + `onSuccess` do not run, and `onError` is not called. `onBodyUnknown(response, + vars, meta)` runs instead. +- A definition with a parser and `onSuccess` but no `onBodyUnknown` gets no + call. The outcome is held unacknowledged, and native keeps the row. It is + delivered when a `define()` of the key adds `onBodyUnknown`, or at the + next launch, with `meta.deliveries` grown. Unlike a key with no + definition, this hold emits no `state` event: the row stays `completed` + until the outcome is acknowledged. The only signal is a warning through + `onWarning`, one per outcome, with the outcome (and its `vars`) as + `detail`, so an app should set `onWarning`. This is an exception to the + order per id in rule 5: when a same-id `mutate()` with a different body + reopens the entry while the outcome is held, the later outcome of that id + can be delivered first. +- A definition with a parser and neither `onSuccess` nor `onBodyUnknown` + asked for no result, so its outcome is acknowledged with no call and no + warning. + +```ts +const createNote = uploads.define({ + key: 'note.create', + request: (vars: NoteVars) => ({ url: notesUrl(vars), data: vars.note }), + response: (raw) => noteSchema.parse(raw), + onSuccess: (note) => { + store.dispatch(noteSaved(note)); + }, + // The server has the note, but its answer was lost. Fetch it. + onBodyUnknown: (_response, vars) => { + store.dispatch(fetchNote(vars.noteId)); + }, +}); +``` + +As with the other handlers, the outcome is acknowledged after the handler's +promise resolves, and a handler that rejects runs again at the next launch. + +Native code does not set `bodyUnknown` yet, so for now no outcome carries it. + Every attempt sends an `X-Request-Id` header, minted per attempt. `Meta.requestId` carries the last one. @@ -385,6 +439,7 @@ type Definition = response: (raw: unknown, vars: V) => T; // JSON-parsed body, or undefined when there is none onSuccess?: (data: T, vars: V, meta: Meta) => void | Promise; onError?: (error: OutcomeError, vars: V, meta: Meta) => void | Promise; + onBodyUnknown?: (response: RawResponse, vars: V, meta: Meta) => void | Promise; } | { key: string; @@ -399,7 +454,7 @@ type Definition = return type. `response` also receives the entry's `vars`, for a parser that needs the request context; a one-argument parser such as `schema.parse` is assignable as it is. Without `response`, `onSuccess` receives the `RawResponse` -(`{ status?, headers?, body?, bodyTruncated }`), and an `onSuccess` annotated +(`{ status?, headers?, body?, bodyTruncated, bodyUnknown? }`), and an `onSuccess` annotated with any other type is a compile error. `V` is any object or `null`, so a generated API request type works as it is. `mutate()` rejects vars and `data` that do not serialize: a cycle, a function, a BigInt, or a value that @@ -408,16 +463,35 @@ dropped. A `request` that declares no parameter gives `V = null`, and `mutate()` then takes no arguments. When `response` is set and the body was truncated, `onError` gets `errorKind: 'truncated'`. When `response` throws, `onError` gets `errorKind: 'unknown'` with the thrown -message; the entry still settles as completed. A key that is already defined +message; the entry still settles as completed. When `response` is set and +the server accepted the request but the body is unknown, `onBodyUnknown` +runs instead of the parser and `onSuccess` (see "Accepted, body unknown"). +Only a definition with `response` takes `onBodyUnknown`. A key that is already defined is replaced, with a warning in development. A `cancelled` outcome calls no handler. -`Meta` is `{ id, key, at, attempts, requestId?, deliveries }`; `at` is the +`Meta` is `{ id, key, at, attempts, requestId?, deliveries, ambiguousAttempts }`; `at` is the native outcome time. `attempts` counts attempts in the current generation; a same-id `mutate()` that reopens the entry starts a new one. `deliveries` counts deliveries that reached a JS listener: 1 on the first, +1 per replay. An outcome journaled while no listener exists starts at 0 and is not emitted -live, so its first delivery, at the boot replay, is 1. +live, so its first delivery, at the boot replay, is 1. `ambiguousAttempts` +counts the attempts of the current generation that ended with no answer from +the server after the whole request can have reached it. The library always +sends the request again after such an attempt, so a count above 0 means the +server can have more than one copy. Native code does not count these yet, so +for now it is 0, and an outcome journaled before the count existed reads 0. + +```ts +onSuccess: (data, vars, meta) => { + if (meta.ambiguousAttempts > 0) { + analytics.track('upload sent in doubt', { + key: meta.key, + count: meta.ambiguousAttempts, + }); + } +}, +``` ### `mutate(vars, { id? }): Promise<{ id }>` @@ -605,8 +679,10 @@ const CaptureBadge = ({ captureId }: { captureId: string }) => { - Completed rows are included. A completed row stays until its outcome is acknowledged. When its handler rejects, or its key has no definition and no `define()` of the key runs in this session (rule 5 of "Reliable - delivery"), the outcome is not acknowledged, so the row stays for the whole - session. Do not treat a completed row as work still to do. + delivery"), or its body is unknown and its definition has a parser and + `onSuccess` but no `onBodyUnknown` ("Accepted, body unknown"), the outcome + is not acknowledged, so the row stays for the whole session. Do not treat a + completed row as work still to do. - `useRequests()` re-renders when a row appears, changes state, or goes. A row's bytes are those of its last `state` event. - `useRequestsWithProgress()` also re-renders on each `progress` event of a @@ -779,7 +855,7 @@ Fires when the Android progress notification is pressed. No event data. | --- | --- | | `state` | A full `RequestRow`, one per transition, plus `reason: 'unhandled-key'` for an outcome whose key has no definition. A consumer's reducer is one upsert. | | `progress` | `{ id, bytesSent, totalBytes }`, byte-weighted across a chunked upload's parts. | -| `attempt` | One HTTP attempt: `{ id, key, requestId, attempt, url, method, partIndex?, outcome, httpCode?, responseBody? (4 KB cap), responseBodyTruncated?, responseHeaders?, errorKind?, errorMessage?, at }`. `outcome` is `completed` for an accepted response (2xx or a matching `accept` rule). Any other HTTP response is `error` with `errorKind: 'http'`; a transport failure is `error` with its own `errorKind`. Pause, cancel, and supersede emit no attempt event. Live-only; never journaled or replayed. | +| `attempt` | One HTTP attempt: `{ id, key, requestId, attempt, url, method, partIndex?, outcome, httpCode?, responseBody? (4 KB cap), responseBodyTruncated?, responseHeaders?, errorKind?, errorMessage?, bodySent?, at }`. `bodySent` is `'none'`, `'partial'` or `'full'`: how much of the request body (for a chunked upload, the part's range) had left when the attempt ended. It is absent when native does not report it; native code does not report it yet. `outcome` is `completed` for an accepted response (2xx or a matching `accept` rule). Any other HTTP response is `error` with `errorKind: 'http'`; a transport failure is `error` with its own `errorKind`. Pause, cancel, and supersede emit no attempt event. Live-only; never journaled or replayed. | Terminal outcomes do not appear here. They go to the definition's handlers. @@ -903,6 +979,18 @@ them. `seedDiagnostics()` adds records for `takeDiagnostics()`, and `seedBootSnapshot({ v9Leftovers: { unownedUploads: 2 } })` adds a boot record with those counts, the others 0 and no ids. +To test an accepted response whose body is unknown, settle it with the flag. +To test the count of attempts in doubt, pass it in the overrides; the fake +leaves it out by default, so `meta.ambiguousAttempts` is 0: + +```ts +await native.settle( + id, + { kind: 'completed', response: { status: 201, bodyUnknown: true } }, + { ambiguousAttempts: 1 }, +); +``` + An app that builds its client at module load can use the fake from the mock for every client instead. Get it with `TurboModuleRegistry.getEnforcing('RNFileUploader')`, and call diff --git a/src/NativeRNFileUploader.ts b/src/NativeRNFileUploader.ts index 50948451..a71a6e7f 100644 --- a/src/NativeRNFileUploader.ts +++ b/src/NativeRNFileUploader.ts @@ -132,7 +132,9 @@ export interface Spec extends TurboModule { // accepted response. Any other HTTP response is 'error' with errorKind // 'http'. A transport failure is 'error' with its own errorKind. Pause, // cancel, and supersede emit no attempt event. Live-only: never journaled, - // never replayed. + // never replayed. Optional bodySent: 'none' | 'partial' | 'full', how much + // of the request body (a part's range for a chunked upload) had left when + // the attempt ended. readonly onAttempt: CodegenTypes.EventEmitter; // The journaled terminal outcome, emitted after the journal write, in the // ./delivery SettledEvent shape: { eventId, id, key, vars, at, attempts, @@ -144,6 +146,14 @@ export interface Spec extends TurboModule { // layer treats it as 1. No ordering // guarantee between different ids; the JS layer orders one id's outcomes. // ./delivery routes it to the definition's handlers. + // + // Optional ambiguousAttempts: attempts of this generation that ended with + // no server answer after the whole request can have reached the server. + // Persisted with the entry; JS reads a missing value as 0. A completed + // outcome whose status was accepted but whose body was not received sets + // response.bodyUnknown to the JSON boolean true and leaves response.body + // out. JS reads any truthy value as the flag. It settles completed, is + // never sent again, and is never the truncated error. readonly onSettled: CodegenTypes.EventEmitter; readonly onNotification: CodegenTypes.EventEmitter; } diff --git a/src/__tests__/client.test.ts b/src/__tests__/client.test.ts index df173d80..1944cf0f 100644 --- a/src/__tests__/client.test.ts +++ b/src/__tests__/client.test.ts @@ -688,6 +688,7 @@ describe('end to end', () => { attempts: 1, requestId: 'r1', deliveries: 1, + ambiguousAttempts: 0, }, ); expect(native.ackEvents).toHaveBeenCalledWith(['e1']); @@ -1369,3 +1370,264 @@ describe('late definitions with onWarning and the row cache', () => { subscription.remove(); }); }); + +describe('with a fake native: attempts in doubt and an unknown body', () => { + let consoleWarn: jest.SpyInstance; + beforeEach(() => { + consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + }); + afterEach(() => consoleWarn.mockRestore()); + + it('settles an accepted response with an unknown body into onSuccess of a definition without a parser', async () => { + const fake = createFakeNative(); + const client = createUploadClient({ native: fake }); + const onSuccess = jest.fn(); + const onError = jest.fn(); + const create = client.define({ + key: 'note.create', + request: (_v: null) => ({ url: 'https://x/notes', data: {} }), + onSuccess, + onError, + }); + client.configure({}); + const { id } = await create.mutate(); + const event = await fake.settle( + id, + { kind: 'completed', response: { status: 201, bodyUnknown: true } }, + { ambiguousAttempts: 1 }, + ); + expect(onSuccess).toHaveBeenCalledWith( + { status: 201, bodyTruncated: false, bodyUnknown: true }, + null, + expect.objectContaining({ id, ambiguousAttempts: 1, deliveries: 1 }), + ); + expect(onError).not.toHaveBeenCalled(); + expect(fake.ackedEventIds).toEqual([event.eventId]); + expect(client.getRequests()).toEqual([]); + }); + + it('settles it into onBodyUnknown of a definition with a parser', async () => { + const fake = createFakeNative(); + const client = createUploadClient({ native: fake }); + const onSuccess = jest.fn(); + const onError = jest.fn(); + const onBodyUnknown = jest.fn(); + const create = client.define({ + key: 'note.create', + request: ({ n }: { n: number }) => ({ url: `https://x/${n}`, data: {} }), + response: (raw) => (raw as { id: string }).id, + onSuccess, + onError, + onBodyUnknown, + }); + client.configure({}); + const { id } = await create.mutate({ n: 1 }); + const event = await fake.settle(id, { + kind: 'completed', + response: { status: 201, bodyUnknown: true }, + }); + expect(onBodyUnknown).toHaveBeenCalledWith( + { status: 201, bodyTruncated: false, bodyUnknown: true }, + { n: 1 }, + expect.objectContaining({ id, ambiguousAttempts: 0 }), + ); + expect(onSuccess).not.toHaveBeenCalled(); + expect(onError).not.toHaveBeenCalled(); + expect(fake.ackedEventIds).toEqual([event.eventId]); + }); + + it('settles a chunked completion, which has no status, into onBodyUnknown', async () => { + const fake = createFakeNative(); + const client = createUploadClient({ native: fake }); + const onBodyUnknown = jest.fn(); + const upload = client.define({ + key: 'file.chunked', + request: (_v: null) => ({ + method: 'PUT', + file: '/f', + parts: [ + { url: 'https://s3/1', range: { start: 0, end: 5 } }, + { url: 'https://s3/2', range: { start: 5, end: 9 } }, + ], + }), + response: (raw) => raw, + onSuccess: jest.fn(), + onBodyUnknown, + }); + client.configure({}); + const { id } = await upload.mutate(); + const event = await fake.settle(id, { + kind: 'completed', + response: { bodyUnknown: true }, + }); + expect(onBodyUnknown).toHaveBeenCalledWith( + { bodyTruncated: false, bodyUnknown: true }, + null, + expect.objectContaining({ id }), + ); + expect(fake.ackedEventIds).toEqual([event.eventId]); + }); + + describe('a parser definition with onSuccess and no onBodyUnknown', () => { + const noteRequest = (_v: null) => ({ url: 'https://x/notes', data: {} }); + + const settleThree = async () => { + const fake = createFakeNative({ ackTimeoutMs: 100 }); + const client = createUploadClient({ native: fake }); + const onSuccess = jest.fn(); + const onError = jest.fn(); + const onWarning = jest.fn(); + const create = client.define({ + key: 'note.create', + request: noteRequest, + response: (raw) => raw, + onSuccess, + onError, + }); + client.configure({ onWarning }); + const ids = ['a', 'b', 'c']; + for (const id of ids) { + await create.mutate(null, { id }); + } + const settled = await Promise.allSettled( + ids.map((id) => + fake.settle(id, { + kind: 'completed', + response: { status: 201, bodyUnknown: true }, + }), + ), + ); + return { fake, client, onSuccess, onError, onWarning, ids, settled }; + }; + + it('holds every outcome unacknowledged, keeps the rows, and warns per outcome with the event', async () => { + const { fake, client, onSuccess, onError, onWarning, ids, settled } = + await settleThree(); + expect(settled.map((r) => r.status)).toEqual([ + 'rejected', + 'rejected', + 'rejected', + ]); + expect(onSuccess).not.toHaveBeenCalled(); + expect(onError).not.toHaveBeenCalled(); + expect(fake.ackedEventIds).toEqual([]); + expect(client.getRequests().map((r) => [r.id, r.state])).toEqual([ + ['a', 'completed'], + ['b', 'completed'], + ['c', 'completed'], + ]); + expect(onWarning).toHaveBeenCalledTimes(3); + ids.forEach((id, i) => { + expect(onWarning).toHaveBeenNthCalledWith( + i + 1, + `delivery: "note.create" got an accepted response whose body is unknown (id ${id}). The definition has a response parser and onSuccess but no onBodyUnknown, so no handler ran. The outcome stays unacknowledged until define() adds onBodyUnknown for the key, or until the next launch.`, + expect.objectContaining({ id, key: 'note.create', vars: null }), + ); + }); + }); + + it('delivers the held outcomes when define() adds onBodyUnknown in the same session', async () => { + const { fake, client, ids } = await settleThree(); + const onBodyUnknown = jest.fn(); + client.define({ + key: 'note.create', + request: noteRequest, + response: (raw) => raw, + onSuccess: jest.fn(), + onBodyUnknown, + }); + await flush(); + expect(onBodyUnknown.mock.calls.map(([, , meta]) => meta.id)).toEqual( + ids, + ); + expect(fake.ackedEventIds).toHaveLength(3); + expect(client.getRequests()).toEqual([]); + }); + + it('redelivers the held outcomes at the next launch, with deliveries grown', async () => { + const { fake } = await settleThree(); + // The next launch: a new client on the same native journal. + const next = createUploadClient({ native: fake }); + const onBodyUnknown = jest.fn(); + next.define({ + key: 'note.create', + request: noteRequest, + response: (raw) => raw, + onSuccess: jest.fn(), + onBodyUnknown, + }); + next.configure({}); + await flush(); + expect(onBodyUnknown).toHaveBeenCalledTimes(3); + onBodyUnknown.mock.calls.forEach(([, , meta]) => { + expect(meta.deliveries).toBe(2); + }); + expect(fake.ackedEventIds).toHaveLength(3); + }); + }); + + it('acks with no call when a parser definition has neither onSuccess nor onBodyUnknown', async () => { + const fake = createFakeNative(); + const client = createUploadClient({ native: fake }); + const onError = jest.fn(); + const onWarning = jest.fn(); + const create = client.define({ + key: 'note.create', + request: (_v: null) => ({ url: 'https://x/notes', data: {} }), + response: (raw) => raw, + onError, + }); + client.configure({ onWarning }); + const { id } = await create.mutate(); + const event = await fake.settle(id, { + kind: 'completed', + response: { bodyUnknown: true }, + }); + expect(onError).not.toHaveBeenCalled(); + expect(onWarning).not.toHaveBeenCalled(); + expect(fake.ackedEventIds).toEqual([event.eventId]); + }); + + it('runs a rejected onBodyUnknown again at the next launch, with deliveries grown', async () => { + const fake = createFakeNative({ ackTimeoutMs: 100 }); + const first = createUploadClient({ native: fake }); + const failing = jest.fn(async () => { + throw new Error('fetch failed'); + }); + const create = first.define({ + key: 'note.create', + request: (_v: null) => ({ url: 'https://x/notes', data: {} }), + response: (raw) => raw, + onBodyUnknown: failing, + }); + first.configure({ onWarning: jest.fn() }); + const { id } = await create.mutate(); + await expect( + fake.settle(id, { kind: 'completed', response: { bodyUnknown: true } }), + ).rejects.toThrow(/not acknowledged/); + expect(failing).toHaveBeenCalledTimes(1); + expect(failing.mock.calls[0]).toEqual([ + expect.anything(), + null, + expect.objectContaining({ deliveries: 1 }), + ]); + expect(fake.ackedEventIds).toEqual([]); + + const next = createUploadClient({ native: fake }); + const onBodyUnknown = jest.fn(); + next.define({ + key: 'note.create', + request: (_v: null) => ({ url: 'https://x/notes', data: {} }), + response: (raw) => raw, + onBodyUnknown, + }); + next.configure({}); + await flush(); + expect(onBodyUnknown).toHaveBeenCalledTimes(1); + expect(onBodyUnknown.mock.calls[0]?.[2]).toMatchObject({ + id, + deliveries: 2, + }); + expect(fake.ackedEventIds).toHaveLength(1); + }); +}); diff --git a/src/__tests__/delivery.test.ts b/src/__tests__/delivery.test.ts index 0e7d78ae..b065d8ec 100644 --- a/src/__tests__/delivery.test.ts +++ b/src/__tests__/delivery.test.ts @@ -643,6 +643,7 @@ describe('completed', () => { attempts: 2, requestId: 'req-9', deliveries: 1, + ambiguousAttempts: 0, }, ); }); @@ -1097,3 +1098,376 @@ describe('onAcked', () => { ); }); }); + +describe('attempts in doubt', () => { + it('passes the native ambiguousAttempts count to the handler in meta', async () => { + const onSuccess = jest.fn(); + const onError = jest.fn(); + const { start, emit } = setup({ + k: { key: 'k', request: jest.fn(), onSuccess, onError }, + }); + start(); + await flush(); + emit(completed({ eventId: 'a', ambiguousAttempts: 2 })); + emit( + completed({ + eventId: 'b', + ambiguousAttempts: 1, + kind: 'error', + error: { errorKind: 'expired', message: 'expired' }, + state: 'error', + } as Partial), + ); + await flush(); + expect(onSuccess.mock.calls[0]?.[2]).toMatchObject({ + ambiguousAttempts: 2, + }); + expect(onError.mock.calls[0]?.[2]).toMatchObject({ ambiguousAttempts: 1 }); + }); + + it('reads a missing or malformed count as 0, as from an older native build', async () => { + const onSuccess = jest.fn(); + const { start, emit } = setup({ + k: { key: 'k', request: jest.fn(), onSuccess }, + }); + start(); + await flush(); + emit(completed({ eventId: 'a' })); + emit(completed({ eventId: 'b', ambiguousAttempts: -1 })); + emit(completed({ eventId: 'c', ambiguousAttempts: 1.5 })); + emit( + completed({ + eventId: 'd', + ambiguousAttempts: '2' as unknown as number, + }), + ); + await flush(); + expect(onSuccess).toHaveBeenCalledTimes(4); + onSuccess.mock.calls.forEach(([, , meta]) => { + expect(meta.ambiguousAttempts).toBe(0); + }); + }); +}); + +describe('accepted, body unknown', () => { + const unknownBody = { status: 201, bodyTruncated: false, bodyUnknown: true }; + + it('gives a definition without a parser the flagged response in onSuccess', async () => { + const onSuccess = jest.fn(); + const onError = jest.fn(); + const { start, emit, native, warn } = setup({ + k: { key: 'k', request: jest.fn(), onSuccess, onError }, + }); + start(); + await flush(); + emit(completed({ response: unknownBody })); + await flush(); + expect(onSuccess).toHaveBeenCalledTimes(1); + expect(onSuccess).toHaveBeenCalledWith( + unknownBody, + { n: 1 }, + expect.objectContaining({ id: 'u1', deliveries: 1 }), + ); + expect(onError).not.toHaveBeenCalled(); + expect(warn).not.toHaveBeenCalled(); + expect(native.ackEvents).toHaveBeenCalledTimes(1); + expect(native.ackEvents).toHaveBeenCalledWith(['e1']); + }); + + it('calls onBodyUnknown, not the parser, onSuccess or onError, when a parser is set', async () => { + const response = jest.fn(); + const onSuccess = jest.fn(); + const onError = jest.fn(); + const onBodyUnknown = jest.fn(); + const { start, emit, native, warn } = setup({ + k: { + key: 'k', + request: jest.fn(), + response, + onSuccess, + onError, + onBodyUnknown, + }, + }); + start(); + await flush(); + emit(completed({ response: unknownBody, ambiguousAttempts: 1 })); + await flush(); + expect(response).not.toHaveBeenCalled(); + expect(onSuccess).not.toHaveBeenCalled(); + expect(onError).not.toHaveBeenCalled(); + expect(onBodyUnknown).toHaveBeenCalledTimes(1); + expect(onBodyUnknown).toHaveBeenCalledWith( + unknownBody, + { n: 1 }, + expect.objectContaining({ + id: 'u1', + key: 'k', + attempts: 2, + requestId: 'req-9', + deliveries: 1, + ambiguousAttempts: 1, + }), + ); + expect(warn).not.toHaveBeenCalled(); + expect(native.ackEvents).toHaveBeenCalledTimes(1); + expect(native.ackEvents).toHaveBeenCalledWith(['e1']); + }); + + it('never reports a flagged response as truncated, even with bodyTruncated set', async () => { + const onError = jest.fn(); + const onBodyUnknown = jest.fn(); + const { start, emit } = setup({ + k: { + key: 'k', + request: jest.fn(), + response: jest.fn(), + onError, + onBodyUnknown, + }, + }); + start(); + await flush(); + emit(completed({ response: { ...unknownBody, bodyTruncated: true } })); + await flush(); + expect(onError).not.toHaveBeenCalled(); + expect(onBodyUnknown).toHaveBeenCalledTimes(1); + }); + + it('reads a truthy flag that is not true as the flag, so the parser never runs', async () => { + const response = jest.fn(() => { + throw new Error('no body to parse'); + }); + const onSuccess = jest.fn(); + const onError = jest.fn(); + const onBodyUnknown = jest.fn(); + const { start, emit, native } = setup({ + k: { + key: 'k', + request: jest.fn(), + response, + onSuccess, + onError, + onBodyUnknown, + }, + }); + start(); + await flush(); + emit( + completed({ + response: { + status: 201, + bodyTruncated: false, + bodyUnknown: 1 as unknown as true, + }, + }), + ); + await flush(); + expect(response).not.toHaveBeenCalled(); + expect(onError).not.toHaveBeenCalled(); + expect(onSuccess).not.toHaveBeenCalled(); + expect(onBodyUnknown).toHaveBeenCalledTimes(1); + expect(native.ackEvents).toHaveBeenCalledWith(['e1']); + }); + + it('treats bodyUnknown: false as a normal response', async () => { + const onSuccess = jest.fn(); + const onBodyUnknown = jest.fn(); + const { start, emit } = setup({ + k: { + key: 'k', + request: jest.fn(), + response: (raw: unknown) => raw, + onSuccess, + onBodyUnknown, + }, + }); + start(); + await flush(); + emit( + completed({ + response: { + status: 200, + body: '{"ok":true}', + bodyTruncated: false, + bodyUnknown: false as unknown as true, + }, + }), + ); + await flush(); + expect(onBodyUnknown).not.toHaveBeenCalled(); + expect(onSuccess).toHaveBeenCalledWith( + { ok: true }, + { n: 1 }, + expect.anything(), + ); + }); + + it('does not call onBodyUnknown for a response with a body', async () => { + const onSuccess = jest.fn(); + const onBodyUnknown = jest.fn(); + const { start, emit } = setup({ + k: { + key: 'k', + request: jest.fn(), + response: (raw: unknown) => raw, + onSuccess, + onBodyUnknown, + }, + }); + start(); + await flush(); + emit(completed()); + await flush(); + expect(onBodyUnknown).not.toHaveBeenCalled(); + expect(onSuccess).toHaveBeenCalledTimes(1); + }); + + it('holds every outcome unacknowledged when a parser definition has onSuccess and no onBodyUnknown', async () => { + const response = jest.fn(); + const onSuccess = jest.fn(); + const onError = jest.fn(); + const { start, emit, native, warn, stateEvents } = setup({ + k: { key: 'k', request: jest.fn(), response, onSuccess, onError }, + }); + start(); + await flush(); + const events = [ + completed({ eventId: 'a', id: 'u1', response: unknownBody }), + completed({ eventId: 'b', id: 'u2', response: unknownBody }), + completed({ eventId: 'c', id: 'u3', response: unknownBody }), + ]; + events.forEach(emit); + await flush(); + expect(response).not.toHaveBeenCalled(); + expect(onSuccess).not.toHaveBeenCalled(); + expect(onError).not.toHaveBeenCalled(); + expect(native.ackEvents).not.toHaveBeenCalled(); + // One warning per outcome, as for a key with no definition. Each names + // its id and the handler to add, and carries the event as detail. + expect(warn).toHaveBeenCalledTimes(3); + events.forEach((event, i) => { + expect(warn).toHaveBeenNthCalledWith( + i + 1, + expect.stringContaining(`(id ${event.id})`), + event, + ); + expect(warn.mock.calls[i]?.[0]).toMatch(/no onBodyUnknown/); + }); + // The row keeps its real state: no unhandled-key row. + expect(stateEvents).toEqual([]); + }); + + it('releases held outcomes when define() adds onBodyUnknown in the same session', async () => { + const definitions: Record = { + k: { + key: 'k', + request: jest.fn(), + response: jest.fn(), + onSuccess: jest.fn(), + }, + }; + const { start, emit, native, release } = setup(definitions); + start(); + await flush(); + emit(completed({ eventId: 'a', id: 'u1', response: unknownBody })); + emit(completed({ eventId: 'b', id: 'u2', response: unknownBody })); + await flush(); + expect(native.ackEvents).not.toHaveBeenCalled(); + + const onBodyUnknown = jest.fn(); + definitions.k = { ...definitions.k!, onBodyUnknown }; + release('k'); + await flush(); + expect(onBodyUnknown).toHaveBeenCalledTimes(2); + expect(onBodyUnknown.mock.calls.map(([, , meta]) => meta.id)).toEqual([ + 'u1', + 'u2', + ]); + expect(native.ackEvents).toHaveBeenCalledWith(['a']); + expect(native.ackEvents).toHaveBeenCalledWith(['b']); + }); + + it('delivers to onBodyUnknown an outcome held for a key defined late', async () => { + const definitions: Record = {}; + const { start, emit, native, release } = setup(definitions); + start(); + await flush(); + emit(completed({ response: unknownBody })); + await flush(); + expect(native.ackEvents).not.toHaveBeenCalled(); + + const onBodyUnknown = jest.fn(); + definitions.k = { + key: 'k', + request: jest.fn(), + response: jest.fn(), + onSuccess: jest.fn(), + onBodyUnknown, + }; + release('k'); + await flush(); + expect(onBodyUnknown).toHaveBeenCalledWith( + unknownBody, + { n: 1 }, + expect.objectContaining({ id: 'u1' }), + ); + expect(native.ackEvents).toHaveBeenCalledWith(['e1']); + }); + + it('acks with no call when a parser definition has neither onSuccess nor onBodyUnknown', async () => { + const response = jest.fn(); + const onError = jest.fn(); + const { start, native, warn } = setup( + { k: { key: 'k', request: jest.fn(), response, onError } }, + [completed({ response: unknownBody, deliveries: 3 })], + ); + start(); + await flush(); + expect(response).not.toHaveBeenCalled(); + expect(onError).not.toHaveBeenCalled(); + expect(native.ackEvents).toHaveBeenCalledWith(['e1']); + expect(warn).not.toHaveBeenCalled(); + }); + + it('acks only after an async onBodyUnknown resolves', async () => { + const gate = deferred(); + const onBodyUnknown = jest.fn(() => gate.promise); + const { start, emit, native } = setup({ + k: { key: 'k', request: jest.fn(), response: jest.fn(), onBodyUnknown }, + }); + start(); + await flush(); + emit(completed({ response: unknownBody })); + await flush(); + expect(onBodyUnknown).toHaveBeenCalledTimes(1); + expect(native.ackEvents).not.toHaveBeenCalled(); + gate.resolve(); + await flush(); + expect(native.ackEvents).toHaveBeenCalledWith(['e1']); + }); + + it('keeps the outcome unacknowledged when onBodyUnknown rejects', async () => { + const failing = jest.fn(async () => { + throw new Error('fetch failed'); + }); + const { start, emit, native, warn } = setup({ + k: { + key: 'k', + request: jest.fn(), + response: jest.fn(), + onBodyUnknown: failing, + }, + }); + start(); + await flush(); + emit(completed({ response: unknownBody })); + await flush(); + expect(failing).toHaveBeenCalledTimes(1); + expect(native.ackEvents).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalledWith( + expect.stringMatching(/rejected/), + expect.any(Error), + ); + }); +}); diff --git a/src/__tests__/testing.test.ts b/src/__tests__/testing.test.ts index 8f19ca58..fc4e63dc 100644 --- a/src/__tests__/testing.test.ts +++ b/src/__tests__/testing.test.ts @@ -652,3 +652,57 @@ describe('holdNext', () => { await expect(fake.enqueue(entry({ id: 'b' }))).resolves.toBe('b'); }); }); + +describe('attempts in doubt and an unknown body', () => { + it('leaves ambiguousAttempts out by default, as native that does not count it', async () => { + const fake = createFakeNative(); + await fake.enqueue(entry()); + const event = fake.buildSettled('a', { kind: 'completed' }); + expect(event).not.toHaveProperty('ambiguousAttempts'); + }); + + it('sets ambiguousAttempts from the overrides', async () => { + const fake = createFakeNative(); + await fake.enqueue(entry()); + const event = fake.buildSettled( + 'a', + { kind: 'completed' }, + { ambiguousAttempts: 2 }, + ); + expect(event).toMatchObject({ ambiguousAttempts: 2 }); + }); + + it('builds a completed outcome whose body is unknown', async () => { + const fake = createFakeNative(); + await fake.enqueue(entry()); + const event = fake.buildSettled('a', { + kind: 'completed', + response: { status: 201, bodyUnknown: true }, + }); + expect(event).toMatchObject({ + kind: 'completed', + response: { status: 201, bodyTruncated: false, bodyUnknown: true }, + }); + expect(event.kind === 'completed' && 'body' in event.response).toBe(false); + }); + + it('passes an attempt event with bodySent through emit.attempt unchanged', () => { + const fake = createFakeNative(); + const handler = jest.fn(); + fake.onAttempt(handler); + const attempt = { + id: 'a', + key: 'item.create', + requestId: 'r1', + attempt: 1, + url: 'https://x/1', + method: 'POST' as const, + outcome: 'error' as const, + errorKind: 'network' as const, + bodySent: 'full' as const, + at: 1, + }; + fake.emit.attempt(attempt); + expect(handler).toHaveBeenCalledWith(attempt); + }); +}); diff --git a/src/__typetests__/doubt.ts b/src/__typetests__/doubt.ts new file mode 100644 index 00000000..d32f091d --- /dev/null +++ b/src/__typetests__/doubt.ts @@ -0,0 +1,185 @@ +// Type-level tests for attempts in doubt and an accepted response whose body +// is unknown. tsc compiles this file with the library (yarn typecheck); +// nothing here runs. +import type { + AttemptEvent, + DefinitionWithoutResponse, + DefinitionWithResponse, + Meta, + OutcomeError, + RawResponse, + UploadClient, +} from '../types'; +import type { FakeOutcome, SettledOverrides } from '../testing'; + +type Equal = (() => T extends A ? 1 : 2) extends () => T extends B + ? 1 + : 2 + ? true + : false; +const assertEqual = ( + _proof: Equal extends true ? true : never, +) => {}; + +const expectType = (_actual: Expected): void => {}; + +declare const client: UploadClient; + +// Meta always has the count. AttemptEvent may say how much body left. +assertEqual(true); +assertEqual( + true, +); +client.addListener('attempt', (e) => { + expectType<'none' | 'partial' | 'full' | undefined>(e.bodySent); +}); +// The flag is true or absent, and separate from bodyTruncated. +assertEqual(true); +assertEqual(true); +const flagged: RawResponse = { + status: 201, + bodyTruncated: false, + bodyUnknown: true, +}; +void flagged; +// @ts-expect-error bodyUnknown is true or absent, never false +const unflagged: RawResponse = { bodyTruncated: false, bodyUnknown: false }; +void unflagged; + +// A definition with a parser handles the case in onBodyUnknown, which gets +// the raw response, the vars and the meta. +type Dto = { id: string }; +const create = client.define({ + key: 'note.create', + request: (_vars: { noteId: string }) => ({ url: 'https://x', data: {} }), + response: (body) => body as Dto, + onSuccess: (_data) => { + assertEqual(true); + }, + onBodyUnknown: (_response, _vars, _meta) => { + assertEqual(true); + assertEqual(true); + assertEqual(true); + }, + onError: (_error) => { + assertEqual(true); + }, +}); +void create.mutate({ noteId: 'n' }); +// An async onBodyUnknown is allowed, as for the other handlers. +client.define({ + key: 'note.create.async', + request: (_vars: null) => ({ url: 'https://x', data: {} }), + response: (body) => body as Dto, + onBodyUnknown: async () => undefined, +}); +// onBodyUnknown checks the vars type. +const wrongVars: DefinitionWithResponse<{ noteId: string }, Dto> = { + key: 'note.create.wrong.vars', + request: (_vars) => ({ url: 'https://x', data: {} }), + response: (body) => body as Dto, + // @ts-expect-error the handler's vars must match the request's + onBodyUnknown: (_response: RawResponse, _vars: { other: number }) => + undefined, +}; +void wrongVars; +// define() reports the same mismatch at the call, because no overload fits. +// @ts-expect-error the handler's vars must match the request's +client.define({ + key: 'note.create.wrong.vars.call', + request: (_vars: { noteId: string }) => ({ url: 'https://x', data: {} }), + response: (body) => body as Dto, + onBodyUnknown: (_response: RawResponse, _vars: { other: number }) => + undefined, +}); +// A definition without a parser gets the flag in onSuccess, so it takes no +// onBodyUnknown. +client.define({ + key: 'note.create.raw', + request: (_vars: null) => ({ url: 'https://x', data: {} }), + onSuccess: (response) => { + expectType(response.bodyUnknown); + }, +}); +const rawWithHandler: DefinitionWithoutResponse = { + key: 'note.create.raw.handler', + request: () => ({ url: 'https://x', data: {} }), + // @ts-expect-error onBodyUnknown needs a response parser + onBodyUnknown: () => undefined, +}; +void rawWithHandler; +// @ts-expect-error onBodyUnknown needs a response parser +client.define({ + key: 'note.create.raw.handler.call', + request: (_vars: null) => ({ url: 'https://x', data: {} }), + onBodyUnknown: () => undefined, +}); +// Also when the definition is built first, where no excess-property check +// applies: the handler would never run, so it does not compile. +const builtFirst = { + key: 'note.create.raw.built', + request: (_vars: null) => ({ url: 'https://x', data: {} }), + onBodyUnknown: () => undefined, +}; +// @ts-expect-error onBodyUnknown needs a response parser +client.define(builtFirst); + +// The fake native can settle the case and set the count. +const settledUnknown: FakeOutcome = { + kind: 'completed', + response: { status: 201, bodyUnknown: true }, +}; +void settledUnknown; +const overrides: SettledOverrides = { ambiguousAttempts: 2 }; +void overrides; + +// The README examples for this feature, as written there. A Redux-style +// dispatch returns the action, so a handler must use a block body to return +// void. +type NoteVars = { noteId: string; siteId: string; note: { text: string } }; +type Note = { id: string; text: string }; +type Action = { type: string }; +declare const store: { dispatch: (action: A) => A }; +declare const notesUrl: (vars: NoteVars) => string; +declare const noteSchema: { parse: (input: unknown) => Note }; +declare const noteSaved: (note: Note) => Action; +declare const fetchNote: (noteId: string) => Action; +declare const analytics: { + track: (name: string, props: Record) => void; +}; +declare const uploads: UploadClient; + +const createNote = uploads.define({ + key: 'note.create', + request: (vars: NoteVars) => ({ url: notesUrl(vars), data: vars.note }), + response: (raw) => noteSchema.parse(raw), + onSuccess: (note) => { + store.dispatch(noteSaved(note)); + }, + // The server has the note, but its answer was lost. Fetch it. + onBodyUnknown: (_response, vars) => { + store.dispatch(fetchNote(vars.noteId)); + }, +}); +void createNote; +// The expression-body form the README used before does not compile. +uploads.define({ + key: 'note.create.expression', + request: (vars: NoteVars) => ({ url: notesUrl(vars), data: vars.note }), + response: (raw) => noteSchema.parse(raw), + // @ts-expect-error a handler returns void or a Promise, not the action + onSuccess: (note) => store.dispatch(noteSaved(note)), +}); + +uploads.define({ + key: 'note.count', + request: (_vars: null) => ({ url: 'https://x' }), + onSuccess: (data, vars, meta) => { + if (meta.ambiguousAttempts > 0) { + analytics.track('upload sent in doubt', { + key: meta.key, + count: meta.ambiguousAttempts, + }); + } + }, +}); diff --git a/src/delivery.ts b/src/delivery.ts index 54fcc986..dbf7458f 100644 --- a/src/delivery.ts +++ b/src/delivery.ts @@ -32,6 +32,12 @@ export type SettledEvent = { * not emitted live. When native omits it, the JS layer treats it as 1. */ deliveries?: number; + /** + * Attempts in this generation that ended with no server answer after the + * whole request can have reached the server. When native omits it, or it is + * not a whole number of 0 or more, the JS layer treats it as 0. + */ + ambiguousAttempts?: number; /** The entry's real state, for the unhandled-key row. */ state: RequestState; bytesSent?: number; @@ -65,8 +71,10 @@ export type Delivery = { /** Delivery for `id` waits until this promise has settled. */ trackMutate: (id: string, pending: Promise) => void; /** - * Call after `define()` registers `key`. The outcomes that reached `key` - * before it had a definition are routed again, in their original order. + * Call after `define()` registers `key`. The held outcomes of `key` are + * routed again, in their original order: those that arrived before it had + * a definition, and those whose body is unknown and that arrived while its + * definition had a parser and onSuccess but no onBodyUnknown. */ release: (key: string) => void; /** @@ -76,6 +84,13 @@ export type Delivery = { forget: (id: string) => void; }; +/** + * Native sends `bodyUnknown` as a JSON boolean. Any truthy value counts, so a + * wrong value never sends an accepted request to the parser with no body. + */ +const isBodyUnknown = (response: RawResponse | undefined): boolean => + Boolean(response?.bodyUnknown); + const errorMessage = (e: unknown): string => e instanceof Error ? e.message : String(e); @@ -86,8 +101,11 @@ const errorMessage = (e: unknown): string => * the id's in-flight mutate(), ack a cancelled outcome, look up the key, run * the handler, ack after its promise resolves. An unknown key or a rejected * handler leaves the outcome unacknowledged, so native redelivers it at the - * next launch. An outcome with an unknown key is also held, and `release()` - * routes it again when `define()` registers the key in the same session. + * next launch. Two kinds of outcome are also held, and `release()` routes + * them again when `define()` registers the key in the same session: one whose + * key has no definition, and one whose body is unknown when the definition + * has a parser and onSuccess but no onBodyUnknown. A held outcome can be + * delivered after a later outcome of its id. */ export const createDelivery = ({ native, @@ -182,6 +200,13 @@ export const createDelivery = ({ await definition.onSuccess?.(response, vars, meta); return; } + // The server accepted the request, but there is no body for the parser. + // It is not an error and never the truncated error. A definition with + // onSuccess and no onBodyUnknown never gets here: settle() holds it. + if (isBodyUnknown(response)) { + await definition.onBodyUnknown?.(response, vars, meta); + return; + } if (response.bodyTruncated) { await definition.onError?.( { @@ -213,11 +238,27 @@ export const createDelivery = ({ await definition.onSuccess?.(data, vars, meta); }; + /** + * True when a parser definition wants a success but has no handler for an + * accepted response whose body is unknown. A definition with neither + * onSuccess nor onBodyUnknown asked for nothing, so it is not held. + */ + const lacksBodyUnknownHandler = ( + event: SettledEvent, + definition: AnyDefinition, + ): boolean => + event.kind === 'completed' && + isBodyUnknown(event.response) && + definition.response !== undefined && + definition.onBodyUnknown === undefined && + definition.onSuccess !== undefined; + /** True when the handler settled, so the outcome may be acknowledged. */ const runHandler = async ( event: SettledEvent, definition: AnyDefinition, ): Promise => { + const ambiguous = event.ambiguousAttempts; const meta: Meta = { id: event.id, key: event.key, @@ -228,6 +269,12 @@ export const createDelivery = ({ typeof event.deliveries === 'number' && event.deliveries >= 1 ? event.deliveries : 1, + ambiguousAttempts: + typeof ambiguous === 'number' && + Number.isInteger(ambiguous) && + ambiguous >= 0 + ? ambiguous + : 0, }; const timer = setTimeout(() => { warn( @@ -303,6 +350,18 @@ export const createDelivery = ({ emitState(unhandledRow(event)); return; } + // Held like an outcome with no definition, so it is never acknowledged + // without a delivery. A define() of the key with onBodyUnknown releases + // it, and the next launch replays it. The row keeps its real state, so no + // unhandled-key row is emitted. + if (lacksBodyUnknownHandler(event, definition)) { + warn( + `delivery: "${event.key}" got an accepted response whose body is unknown (id ${event.id}). The definition has a response parser and onSuccess but no onBodyUnknown, so no handler ran. The outcome stays unacknowledged until define() adds onBodyUnknown for the key, or until the next launch.`, + event, + ); + hold(event); + return; + } if (await runHandler(event, definition)) { await ack(event); } diff --git a/src/testing.ts b/src/testing.ts index 4aef5f59..a5b5bca2 100644 --- a/src/testing.ts +++ b/src/testing.ts @@ -59,7 +59,9 @@ export type FakeEntry = { /** * The outcome to settle. Fields you omit get defaults: a completed response * is status 200 (none for a chunked upload) with `bodyTruncated: false`, an - * error message is the errorKind, and a cancel reason is 'user'. + * error message is the errorKind, and a cancel reason is 'user'. For an + * accepted response whose body is unknown, pass + * `{ kind: 'completed', response: { status: 201, bodyUnknown: true } }`. */ export type FakeOutcome = | { kind: 'completed'; response?: Partial } @@ -74,7 +76,10 @@ export type FakeOutcome = } | { kind: 'cancelled'; cancelReason?: CancelReason }; -/** Fields of the SettledEvent to set instead of the defaults. */ +/** + * Fields of the SettledEvent to set instead of the defaults. The fake leaves + * `ambiguousAttempts` out, as native that does not count it; set it here. + */ export type SettledOverrides = Partial< Omit >; @@ -146,9 +151,10 @@ export type FakeNative = Spec & { * and emits it on onSettled when a listener exists. Resolves with the event * after delivery acks it and the client has handled the ack, so the row * hooks no longer show a forgotten row. Rejects after `ackTimeoutMs` when no ack comes: - * the handler rejected, the key has no definition, or configure() was not - * called. To test those cases, create the fake with a short - * `ackTimeoutMs` and expect settle() to reject. + * the handler rejected, the key has no definition, the body is unknown and + * the definition has a parser and onSuccess but no onBodyUnknown, or + * configure() was not called. To test those cases, create the fake with a + * short `ackTimeoutMs` and expect settle() to reject. */ settle: ( id: string, @@ -435,7 +441,7 @@ export const createFakeNative = ( ackWaiters.delete(event.eventId); reject( new Error( - `createFakeNative: outcome ${event.eventId} ("${event.key}", id ${id}) was not acknowledged within ${ackTimeoutMs} ms. The handler rejected or has not settled, the key has no definition, or configure() was not called.`, + `createFakeNative: outcome ${event.eventId} ("${event.key}", id ${id}) was not acknowledged within ${ackTimeoutMs} ms. The handler rejected or has not settled, the key has no definition, the body is unknown and the definition has a parser and onSuccess but no onBodyUnknown, or configure() was not called.`, ), ); }, ackTimeoutMs); diff --git a/src/types.ts b/src/types.ts index 4bd96fc9..a5f4c4b6 100644 --- a/src/types.ts +++ b/src/types.ts @@ -156,6 +156,14 @@ export type RawResponse = { headers?: Record; body?: string; bodyTruncated: boolean; + /** + * `true` when the server accepted the request but the library did not get + * the response body, for example when the status line said 201 and the + * connection dropped before the body arrived. `body` is then undefined. The + * request is done and is not sent again. Absent otherwise. Not the same as + * `bodyTruncated`, which means the body was over 1 MB. + */ + bodyUnknown?: true; }; /** @@ -191,6 +199,14 @@ export type Meta = { * not emitted live, so its first delivery, at the boot replay, is 1. */ deliveries: number; + /** + * Attempts in the current generation that ended with no answer from the + * server after the whole request can have reached it. The library sent the + * request again after each one, so the server can have more than one copy. + * 0 when native does not report the count: an older native build, or an + * outcome journaled before it. + */ + ambiguousAttempts: number; }; export type Outcome = @@ -289,6 +305,12 @@ export type AttemptEvent = { responseHeaders?: Record; errorKind?: ErrorKind; errorMessage?: string; + /** + * How much of the request body had left the phone when the attempt ended. + * For a chunked upload, the body is the part's byte range. Absent when + * native does not report it. + */ + bodySent?: 'none' | 'partial' | 'full'; /** Native stamp, epoch ms. */ at: number; }; @@ -310,12 +332,31 @@ export type DefinitionWithResponse = DefinitionBase & { */ response: (raw: unknown, vars: V) => T; onSuccess?: (data: T, vars: V, meta: Meta) => void | Promise; + /** + * Called instead of the parser and `onSuccess` when the server accepted + * the request but the response body is unknown (`response.bodyUnknown`). + * The request is done; a typical handler fetches the object from the + * server. When the definition has `onSuccess` but no `onBodyUnknown`, the + * outcome is held unacknowledged with a warning, and is delivered again + * when `define()` adds this handler or at the next launch. With neither + * handler, it is acknowledged with no call. + */ + onBodyUnknown?: ( + response: RawResponse, + vars: V, + meta: Meta, + ) => void | Promise; }; -/** A definition without a parser. `onSuccess` receives the `RawResponse`. */ +/** + * A definition without a parser. `onSuccess` receives the `RawResponse`, + * also when its body is unknown (`bodyUnknown`), so it takes no + * `onBodyUnknown`. + */ export type DefinitionWithoutResponse = DefinitionBase & { response?: undefined; onSuccess?: (data: RawResponse, vars: V, meta: Meta) => void | Promise; + onBodyUnknown?: undefined; }; /**