feat: platform backbone and field capture, first part (checkpoint)
Platform backbone (plan 2026-10-13-plattform-rueckgrat), reviewed tasks: - run roles api/worker/job/all with shared startup checks (Task 1) - schema and migration for DomainEvent, deliveries, JobRun, ThrottlerHit (Task 2) - audit, notifications and domain events written in the same transaction (Task 3) - dispatcher with SKIP LOCKED claims, retries and stale release (Task 4) - worker building blocks: tick, LISTEN/NOTIFY wake-up, health (Task 5) - worker process and entry points (Task 6) - throttler counters in Postgres (Task 19) - separate keys per purpose with key ring (Task 20) - public origin page without exact location (Task 22) - shop keys split into read and write (Task 23) - Kustomize base, components, overlay encry, CI validation (Task 26) Field capture T3 (plan 2026-10-13-t3-erfassung-am-stand), reviewed tasks: - brood frames, read endpoints, apiary overview and offline pack - network basics, offline queue v3, navigation sheets, form building blocks - new inspection with last-time hints and weather, varroa per day, treatment prefill, apiary page with round - inspection photo (Task 10) is implemented, review pending Not rolled out. Remaining tasks follow in later commits. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
1 parent
10cbe9bf2d
commit
c01a38835a
340 files changed
+25695
-1808
No files matched your search
@@ -0,0 +1,104 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getConnectivity, reportRequestOutcome } from "@/lib/offline/connectivity";
|
||||
import {
|
||||
DEFAULT_TIMEOUT_MS,
|
||||
DOWNLOAD_TIMEOUT_MS,
|
||||
NON_IDEMPOTENT_WRITE_TIMEOUT_MS,
|
||||
UPLOAD_TIMEOUT_MS,
|
||||
} from "@/lib/http/fetch-with-timeout";
|
||||
import { expectTimeoutAt, stubHangingFetch } from "@/lib/http/deadline-test-helper";
|
||||
import { setAccessToken } from "./token-store";
|
||||
import { ApiError, apiFetch, apiFetchBlob, apiFetchFormData } from "./api-client";
|
||||
|
||||
vi.mock("../config/runtime-config", () => ({
|
||||
getApiUrl: vi.fn().mockResolvedValue("http://api.test"),
|
||||
}));
|
||||
|
||||
function jsonResponse(status: number, body: unknown): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
describe("api-client", () => {
|
||||
beforeEach(() => {
|
||||
setAccessToken(null);
|
||||
reportRequestOutcome("reached-server");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("ApiError carries the parsed JSON body", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockResolvedValue(jsonResponse(400, { message: "Ungültig", invalidColonyIds: ["c1"] })),
|
||||
);
|
||||
const error = await apiFetch("/x").catch((e: unknown) => e);
|
||||
expect(error).toBeInstanceOf(ApiError);
|
||||
const apiError = error as ApiError;
|
||||
expect(apiError.status).toBe(400);
|
||||
expect(apiError.message).toBe("Ungültig");
|
||||
expect((apiError.body as { invalidColonyIds: string[] }).invalidColonyIds).toEqual(["c1"]);
|
||||
});
|
||||
|
||||
it("reports network-error on a failed fetch and reached-server on any HTTP answer", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("Failed to fetch")));
|
||||
await expect(apiFetch("/x")).rejects.toBeInstanceOf(TypeError);
|
||||
expect(getConnectivity()).toBe("offline");
|
||||
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(500, { message: "boom" })));
|
||||
await expect(apiFetch("/x")).rejects.toBeInstanceOf(ApiError);
|
||||
expect(getConnectivity()).toBe("online");
|
||||
});
|
||||
|
||||
describe("timeouts", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
stubHangingFetch();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("apiFetch: GET and keyed writes 4 s, unkeyed writes 15 s", async () => {
|
||||
await expectTimeoutAt(() => apiFetch("/x"), DEFAULT_TIMEOUT_MS);
|
||||
await expectTimeoutAt(
|
||||
() => apiFetch("/x", { method: "POST", headers: { "Idempotency-Key": "k" } }),
|
||||
DEFAULT_TIMEOUT_MS,
|
||||
);
|
||||
await expectTimeoutAt(() => apiFetch("/x", { method: "POST" }), NON_IDEMPOTENT_WRITE_TIMEOUT_MS);
|
||||
});
|
||||
|
||||
it("apiFetchFormData uses 30 s by default and honours timeoutMs", async () => {
|
||||
await expectTimeoutAt(() => apiFetchFormData("/x", new FormData()), UPLOAD_TIMEOUT_MS);
|
||||
await expectTimeoutAt(
|
||||
() => apiFetchFormData("/x", new FormData(), { timeoutMs: 5_000 }),
|
||||
5_000,
|
||||
);
|
||||
});
|
||||
|
||||
it("apiFetchFormData passes options.headers through", async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, {}));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
await apiFetchFormData("/x", new FormData(), { headers: { "Idempotency-Key": "k9" } });
|
||||
const init = fetchMock.mock.calls[0][1] as RequestInit;
|
||||
expect(new Headers(init.headers).get("Idempotency-Key")).toBe("k9");
|
||||
});
|
||||
|
||||
it("apiFetchBlob uses 60 s", async () => {
|
||||
await expectTimeoutAt(() => apiFetchBlob("/x", "f.csv"), DOWNLOAD_TIMEOUT_MS);
|
||||
});
|
||||
});
|
||||
|
||||
it("apiFetchBlob builds an ApiError with the parsed body", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(403, { message: "Nein", why: 1 })));
|
||||
const error = (await apiFetchBlob("/x", "f.csv").catch((e: unknown) => e)) as ApiError;
|
||||
expect(error).toBeInstanceOf(ApiError);
|
||||
expect(error.status).toBe(403);
|
||||
expect(error.body).toEqual({ message: "Nein", why: 1 });
|
||||
});
|
||||
});
|
||||
@@ -1,27 +1,50 @@
|
||||
import { getAccessToken, setAccessToken } from './token-store';
|
||||
import { refreshRequest } from './api';
|
||||
import { getApiUrl } from '../config/runtime-config';
|
||||
import {
|
||||
DOWNLOAD_TIMEOUT_MS,
|
||||
UPLOAD_TIMEOUT_MS,
|
||||
fetchReportingOutcome,
|
||||
timeoutFor,
|
||||
} from '../http/fetch-with-timeout';
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
readonly status: number;
|
||||
readonly body: unknown;
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
constructor(status: number, message: string, body?: unknown) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.body = body;
|
||||
}
|
||||
}
|
||||
|
||||
async function rawFetch(path: string, init: RequestInit): Promise<Response> {
|
||||
async function apiErrorFrom(response: Response, fallbackMessage = 'Request failed'): Promise<ApiError> {
|
||||
const body: unknown = await response.json().catch(() => ({}));
|
||||
const message =
|
||||
typeof body === 'object' && body !== null && 'message' in body
|
||||
? String((body as { message: unknown }).message)
|
||||
: fallbackMessage;
|
||||
return new ApiError(response.status, message, body);
|
||||
}
|
||||
|
||||
async function rawFetch(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
timeoutMs?: number,
|
||||
): Promise<Response> {
|
||||
const token = getAccessToken();
|
||||
const apiUrl = await getApiUrl();
|
||||
return fetch(`${apiUrl}${path}`, {
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
...init.headers,
|
||||
};
|
||||
return fetchReportingOutcome(`${apiUrl}${path}`, {
|
||||
...init,
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
...init.headers,
|
||||
},
|
||||
headers,
|
||||
timeoutMs: timeoutMs ?? timeoutFor(init.method ?? 'GET', headers),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -36,18 +59,18 @@ function filenameFromContentDisposition(header: string | null, fallback: string)
|
||||
}
|
||||
|
||||
export async function apiFetchBlob(path: string, fallbackFilename: string): Promise<BlobDownload> {
|
||||
let response = await rawFetch(path, {});
|
||||
let response = await rawFetch(path, {}, DOWNLOAD_TIMEOUT_MS);
|
||||
|
||||
if (response.status === 401) {
|
||||
const refreshed = await refreshRequest();
|
||||
if (refreshed) {
|
||||
setAccessToken(refreshed.accessToken);
|
||||
response = await rawFetch(path, {});
|
||||
response = await rawFetch(path, {}, DOWNLOAD_TIMEOUT_MS);
|
||||
}
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ApiError(response.status, 'Export fehlgeschlagen');
|
||||
throw await apiErrorFrom(response, 'Export fehlgeschlagen');
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
@@ -58,37 +81,47 @@ export async function apiFetchBlob(path: string, fallbackFilename: string): Prom
|
||||
return { blob, filename };
|
||||
}
|
||||
|
||||
async function rawFetchFormData(path: string, formData: FormData): Promise<Response> {
|
||||
export interface FormDataOptions {
|
||||
headers?: HeadersInit;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
async function rawFetchFormData(
|
||||
path: string,
|
||||
formData: FormData,
|
||||
options: FormDataOptions,
|
||||
): Promise<Response> {
|
||||
const token = getAccessToken();
|
||||
const apiUrl = await getApiUrl();
|
||||
return fetch(`${apiUrl}${path}`, {
|
||||
return fetchReportingOutcome(`${apiUrl}${path}`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
...options.headers,
|
||||
},
|
||||
timeoutMs: options.timeoutMs ?? UPLOAD_TIMEOUT_MS,
|
||||
});
|
||||
}
|
||||
|
||||
export async function apiFetchFormData<T>(path: string, formData: FormData): Promise<T> {
|
||||
let response = await rawFetchFormData(path, formData);
|
||||
export async function apiFetchFormData<T>(
|
||||
path: string,
|
||||
formData: FormData,
|
||||
options: FormDataOptions = {},
|
||||
): Promise<T> {
|
||||
let response = await rawFetchFormData(path, formData, options);
|
||||
|
||||
if (response.status === 401) {
|
||||
const refreshed = await refreshRequest();
|
||||
if (refreshed) {
|
||||
setAccessToken(refreshed.accessToken);
|
||||
response = await rawFetchFormData(path, formData);
|
||||
response = await rawFetchFormData(path, formData, options);
|
||||
}
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const body: unknown = await response.json().catch(() => ({}));
|
||||
const message =
|
||||
typeof body === 'object' && body !== null && 'message' in body
|
||||
? String((body as { message: unknown }).message)
|
||||
: 'Request failed';
|
||||
throw new ApiError(response.status, message);
|
||||
throw await apiErrorFrom(response);
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>;
|
||||
@@ -106,12 +139,7 @@ export async function apiFetch<T>(path: string, init: RequestInit = {}): Promise
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const body: unknown = await response.json().catch(() => ({}));
|
||||
const message =
|
||||
typeof body === 'object' && body !== null && 'message' in body
|
||||
? String((body as { message: unknown }).message)
|
||||
: 'Request failed';
|
||||
throw new ApiError(response.status, message);
|
||||
throw await apiErrorFrom(response);
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { afterEach, beforeEach, describe, it, vi } from "vitest";
|
||||
import {
|
||||
DEFAULT_TIMEOUT_MS,
|
||||
NON_IDEMPOTENT_WRITE_TIMEOUT_MS,
|
||||
} from "@/lib/http/fetch-with-timeout";
|
||||
import { expectTimeoutAt, stubHangingFetch } from "@/lib/http/deadline-test-helper";
|
||||
import {
|
||||
getCurrentUserRequest,
|
||||
loginRequest,
|
||||
logoutRequest,
|
||||
refreshRequest,
|
||||
ssoCompleteRequest,
|
||||
verifyMfaRequest,
|
||||
} from "./api";
|
||||
|
||||
vi.mock("../config/runtime-config", () => ({
|
||||
getApiUrl: vi.fn().mockResolvedValue("http://api.test"),
|
||||
}));
|
||||
|
||||
describe("auth api timeouts", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
stubHangingFetch();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["login", () => loginRequest("[email protected]", "pw")],
|
||||
["MFA verify", () => verifyMfaRequest("t", "123456")],
|
||||
["refresh", () => refreshRequest()],
|
||||
["SSO complete", () => ssoCompleteRequest()],
|
||||
["logout", () => logoutRequest()],
|
||||
])("%s (one-shot / rotating) uses the long write timeout", async (_name, call) => {
|
||||
await expectTimeoutAt(call, NON_IDEMPOTENT_WRITE_TIMEOUT_MS);
|
||||
});
|
||||
|
||||
it("plain reads use the default timeout", async () => {
|
||||
await expectTimeoutAt(() => getCurrentUserRequest("tok"), DEFAULT_TIMEOUT_MS);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,9 @@
|
||||
import { getApiUrl } from '../config/runtime-config';
|
||||
import {
|
||||
DEFAULT_TIMEOUT_MS,
|
||||
NON_IDEMPOTENT_WRITE_TIMEOUT_MS,
|
||||
fetchReportingOutcome,
|
||||
} from '../http/fetch-with-timeout';
|
||||
|
||||
export interface AccessTokenResponse {
|
||||
accessToken: string;
|
||||
@@ -17,7 +22,8 @@ export function isMfaRequired(response: LoginResponse): response is MfaRequiredR
|
||||
|
||||
export async function loginRequest(email: string, password: string): Promise<LoginResponse> {
|
||||
const apiUrl = await getApiUrl();
|
||||
const response = await fetch(`${apiUrl}/auth/login`, {
|
||||
const response = await fetchReportingOutcome(`${apiUrl}/auth/login`, {
|
||||
timeoutMs: NON_IDEMPOTENT_WRITE_TIMEOUT_MS,
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -31,7 +37,8 @@ export async function loginRequest(email: string, password: string): Promise<Log
|
||||
|
||||
export async function verifyMfaRequest(mfaToken: string, code: string): Promise<AccessTokenResponse> {
|
||||
const apiUrl = await getApiUrl();
|
||||
const response = await fetch(`${apiUrl}/auth/mfa/verify`, {
|
||||
const response = await fetchReportingOutcome(`${apiUrl}/auth/mfa/verify`, {
|
||||
timeoutMs: NON_IDEMPOTENT_WRITE_TIMEOUT_MS,
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -43,6 +50,10 @@ export async function verifyMfaRequest(mfaToken: string, code: string): Promise<
|
||||
return response.json() as Promise<AccessTokenResponse>;
|
||||
}
|
||||
|
||||
// Login, MFA, refresh, SSO complete and logout are one-shot / rotating: a client
|
||||
// abort after the server processed them would burn a TOTP code or lose the
|
||||
// rotated refresh cookie, so they get the long write timeout.
|
||||
|
||||
// The refresh token is single-use and rotates on every call. If two callers
|
||||
// (e.g. React StrictMode's dev double-invoke, or two components hitting a 401
|
||||
// at once) both call refresh at the same time, the second one always fails
|
||||
@@ -53,7 +64,8 @@ let inFlightRefresh: Promise<AccessTokenResponse | null> | null = null;
|
||||
|
||||
async function performRefresh(): Promise<AccessTokenResponse | null> {
|
||||
const apiUrl = await getApiUrl();
|
||||
const response = await fetch(`${apiUrl}/auth/refresh`, {
|
||||
const response = await fetchReportingOutcome(`${apiUrl}/auth/refresh`, {
|
||||
timeoutMs: NON_IDEMPOTENT_WRITE_TIMEOUT_MS,
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
});
|
||||
@@ -75,7 +87,7 @@ export function refreshRequest(): Promise<AccessTokenResponse | null> {
|
||||
export async function ssoStatusRequest(): Promise<boolean> {
|
||||
const apiUrl = await getApiUrl();
|
||||
try {
|
||||
const response = await fetch(`${apiUrl}/auth/sso/status`);
|
||||
const response = await fetchReportingOutcome(`${apiUrl}/auth/sso/status`, { timeoutMs: DEFAULT_TIMEOUT_MS });
|
||||
if (!response.ok) {
|
||||
return false;
|
||||
}
|
||||
@@ -98,7 +110,8 @@ export async function ssoLoginUrl(): Promise<string> {
|
||||
// same challenge as a password login before tokens are issued.
|
||||
export async function ssoCompleteRequest(): Promise<LoginResponse> {
|
||||
const apiUrl = await getApiUrl();
|
||||
const response = await fetch(`${apiUrl}/auth/sso/complete`, {
|
||||
const response = await fetchReportingOutcome(`${apiUrl}/auth/sso/complete`, {
|
||||
timeoutMs: NON_IDEMPOTENT_WRITE_TIMEOUT_MS,
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
});
|
||||
@@ -110,7 +123,11 @@ export async function ssoCompleteRequest(): Promise<LoginResponse> {
|
||||
|
||||
export async function logoutRequest(): Promise<void> {
|
||||
const apiUrl = await getApiUrl();
|
||||
await fetch(`${apiUrl}/auth/logout`, { method: 'POST', credentials: 'include' });
|
||||
await fetchReportingOutcome(`${apiUrl}/auth/logout`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
timeoutMs: NON_IDEMPOTENT_WRITE_TIMEOUT_MS,
|
||||
});
|
||||
}
|
||||
|
||||
export interface CurrentUserProfile {
|
||||
@@ -126,7 +143,8 @@ export interface CurrentUserProfile {
|
||||
|
||||
export async function getCurrentUserRequest(accessToken: string): Promise<CurrentUserProfile> {
|
||||
const apiUrl = await getApiUrl();
|
||||
const response = await fetch(`${apiUrl}/auth/me`, {
|
||||
const response = await fetchReportingOutcome(`${apiUrl}/auth/me`, {
|
||||
timeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
credentials: 'include',
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user