fix: preserve large Unicode drafts with bounded keepalive transport

This commit is contained in:
2026-10-29 23:08:09 +02:00
parent fa2ece10de
commit ed96fd10b9
7 changed files with 305 additions and 25 deletions
+38 -22
View File
@@ -150,34 +150,50 @@ export type ContextPlan = {
documents_preserved: number;
notice: string;
};
// Leave headroom below the browser's shared 64 KiB keepalive budget.
const contextKeepaliveBudget = 60000;
let contextKeepaliveBytes = 0;
export async function contextApi<T>(
url: string,
body?: unknown,
method = 'POST',
keepalive = false,
): Promise<T> {
const response = await fetch(url, {
keepalive,
method: body === undefined ? 'GET' : method,
credentials: 'same-origin',
headers: {
Accept: 'application/json',
...(body === undefined
? {}
: {
'Content-Type': 'application/json',
'X-XSRF-TOKEN': csrfToken(),
}),
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
const data = await response.json().catch(() => null);
if (!response.ok)
throw new Error(
data?.message ||
`Não foi possível recuperar ou guardar o contexto (HTTP ${response.status}).`,
);
return data as T;
const serializedBody =
body === undefined ? undefined : JSON.stringify(body);
const bytes = serializedBody
? new TextEncoder().encode(serializedBody).byteLength
: 0;
const useKeepalive =
keepalive && contextKeepaliveBytes + bytes < contextKeepaliveBudget;
if (useKeepalive) contextKeepaliveBytes += bytes;
try {
const response = await fetch(url, {
keepalive: useKeepalive,
method: body === undefined ? 'GET' : method,
credentials: 'same-origin',
headers: {
Accept: 'application/json',
...(body === undefined
? {}
: {
'Content-Type': 'application/json',
'X-XSRF-TOKEN': csrfToken(),
}),
},
...(serializedBody === undefined ? {} : { body: serializedBody }),
});
const data = await response.json().catch(() => null);
if (!response.ok)
throw new Error(
data?.message ||
`Não foi possível recuperar ou guardar o contexto (HTTP ${response.status}).`,
);
return data as T;
} finally {
if (useKeepalive) contextKeepaliveBytes -= bytes;
}
}
export const contextFieldNames: Record<string, string> = {
investment_form: 'Tipo do investimento',
+2 -3
View File
@@ -299,7 +299,7 @@ export default function ContextEditor({
draft_sequence: savedSequence,
},
'POST',
draftBody.length < 60000,
true,
),
)
.then(() => {
@@ -318,8 +318,7 @@ export default function ContextEditor({
const body = latestDraft.current;
if (
!awaitingSavedContext.current &&
body !== confirmedDraftBody.current &&
body.length < 60000
body !== confirmedDraftBody.current
)
void contextApi(
'/investimentos/' + initial.case.id + '/contexto/rascunho',