Why utils, fetch, hooks, and observer belong in your frontend and your backend.
LogosDX · Press Space to start, S for speaker notes, ? for the key list
try/catch around every await, with the error swallowed in half of themFrontend and backend drift apart because nothing makes them share.
utils | Error tuples, retry, timeout, circuit breaker, rate limit, memoize, batch |
|---|---|
fetch | HTTP client where timeouts, retries, dedupe, cache, and rate limits are config |
hooks | Named extension points that can change arguments, short-circuit, or abort |
observer | Typed events, regex subscriptions, async iteration, queues |
Zero external dependencies. TypeScript first. Tree-shakable. No Node-only or browser-only globals.
utils: failure is a valueimport { attempt } from '@logosdx/utils';
const [order, err] = await attempt(
() => loadOrder(orderId)
);
if (err) return respond(503, 'Order store unavailable');
if (!order) return respond(404, 'Order not found');
try/catch, no invisible error pathconst charge = makeRetryable(gateway.charge.bind(gateway), {
retries: 3,
delay: 200,
jitterFactor: 0.25
});
const guarded = circuitBreaker(charge, {
maxFailures: 5,
resetAfter: 10_000
});
const charged = withTimeout(guarded, {
timeout: 5_000
});
gateway.charge stands in for any flaky dependency.
| In the browser | On the server | |
|---|---|---|
attempt | Form submit, route loader | Request handler, background job |
retry | A flaky save on mobile | Calls to a partner API |
withTimeout | Search as you type | Database or gateway call |
memoize | Expensive derived data | Per-process lookup cache |
batch | Uploading many files | 1,000 records, 50 at a time |
rateLimit | Button mashing | An outbound API budget |
batch for a data import already knows
how to throttle a bulk upload.
fetch: a client that expects troubleconst [res, err] = await attempt(
() => api.get<Order>('/orders/42')
);
if (err) return showOffline();
if (!res.ok) return showError(res.status);
render(res.data);
err: no response exists (timeout, abort, connection lost)!res.ok: the server said no, and status, headers, and data are all still thereres.data: success, typedok narrowing data, and an error that says whether
it was a timeout, an abort, or a lost connection.
const api = new FetchEngine({
baseUrl: 'https://api.example.com',
totalTimeout: 5_000,
retry: { maxAttempts: 3, baseDelay: 150 },
dedupePolicy: true,
cachePolicy: {
ttl: 30_000,
staleIn: 10_000
},
rateLimitPolicy: {
maxCalls: 60,
windowMs: 60_000,
waitForToken: true,
serializer: () => 'partner'
}
});
serializer says otherwise, which is why the partner
budget here uses one. rules on each policy give one route its own budget without
a second client. Per-call escape hatches exist, such as retry: false.
hooks: extension points you nameinterface OrderLifecycle {
beforeSubmit(order: Order): Promise<Order>;
}
const hooks = new HookEngine<OrderLifecycle>()
.register('beforeSubmit');
hooks.add('beforeSubmit', (order, ctx) => {
if (!order.items.length) ctx.fail('Cart is empty');
});
await hooks.run('beforeSubmit', order);
ctxadd() returns a cleanup functionctx.args(...) | Replace the arguments for the callbacks after this one |
|---|---|
return ctx.returns(value) | Stop the chain and answer with a value (a cache hit) |
ctx.fail(...) | Abort with an error (a validation failure) |
priority, once, times | Order and lifetime of each callback |
Retry, dedupe, cache, and rate limit are plugins installed on the engine's own HookEngine.
const cleanup = api.use(auditPlugin);
// later
cleanup();
You extend fetch the same way the library does.
retryPlugin, dedupePlugin, cachePlugin,
rateLimitPlugin, and cookiePlugin exist as standalone factories.
auditPlugin here is yours: something cross-cutting that should not live in every caller.
observer: events with types and limitsinterface Events {
'order:created': { id: string; total: number };
'order:failed': { id: string; reason: string };
}
const bus = new ObserverEngine<Events>();
bus.on('order:created', ({ id }) => announce(id));
bus.on(/^order:/, ({ event }) => audit(event));
bus.emit('order:created', { id: 'o_42', total: 1999 });
on() with a callback returns a cleanup, and every form takes an AbortSignalbus.queue('order:created', processOrder, {
name: 'fulfillment',
concurrency: 4,
taskTimeoutMs: 30_000
});
// the producer does not change
bus.emit('order:created', order);
for awaitfor await (const { id } of bus.on('order:created')) {
await saveToDatabase(id);
}
Events that arrive while you await are buffered in order, so none are dropped.
BROWSER SERVER
hooks.run('beforeSubmit')
api.post('/orders') ───────▶ route handler
retry attempt(loadCart)
bus.emit('order:created')
render(res.data) ◀─────── res.ok / !res.ok
queue, concurrency 4
fetch → payment API
rateLimit + circuitBreaker
// shared/order-rules.ts, imported by the app and the API
export function addOrderRules(hooks: HookEngine<OrderLifecycle>) {
return hooks.add('beforeSubmit', (order, ctx) => {
if (!order.items.length) ctx.fail('Cart is empty');
});
}
pnpm add @logosdx/utils @logosdx/fetch @logosdx/hooks @logosdx/observer
Wrap one fetch call in attempt, in the frontend and in the backend. Add a policy when the first failure teaches you to.