mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-25 15:17:23 +00:00
* refactor(util): shared helpers for hosts, timeouts, chunking, paging, shutdown flush and codes Adds normalizeHost/getPuterHostedDomains, withTimeout, chunk, nowSeconds, isMissingTable, clampLimit/parsePageQuery/pageEnvelope, finalFlush, parseRetryAfterMs/doublingBackoffMs, randomCode, sweepInBatches, hashPassword/generateEmailConfirmCode, requestIp and isTemporaryAccount, and removes util exports nothing called. * refactor(clients,core): drop unread alarm state and dead shutdown paths, share host helpers DynamoDB batches still throttled after the retries answer 503 db_unavailable. * refactor(stores): one cache read per miss, tombstones on every write, batch methods for callers above The multi-check permission cache is read with pipelined GETs. claimOwnership, replaceDataUrlIcon and setLabel tombstone their keys. updateMetadata merges in one statement. App stats reject an unknown period and cap grouped answers. * refactor(services): fewer serial round trips in permission, share, metering and events paths checkMany no longer caches a check that threw. Account deletion revokes its sessions first. OIDC email_verified strings are read as booleans. Events limits, FS service types and the events worker deployer live under services. * refactor(drivers): one teardown path for workers, shared credit hold and provider helpers A URL input and a generated-media download have a deadline and a size cap. Azure chat clients take the shared client options. xAI and Mistral chat send tools through toolsToWire and honor apiBaseUrl. * refactor(controllers): shared download, paging and second-factor helpers, store methods for raw SQL /batch answers a non-HTTP op error generically and logs it. /fs/search returns the client entry shape. The unused /puterai/video/proxy route is removed. * refactor: thumbnails accept raster types only, boot failure exits, docs for new limits * fix: sessions stay listed after a rename, token grants follow the whole revoke cascade, app delete in one transaction - listSessions asks the primary about rows marked as changed, so a renamed session stays on the list under its new label. - The revoke cascade reports the access tokens it revoked, and their grants are dropped at any depth. The read before each revoke is gone. - App delete records the deletion, clears filetype associations and deletes the row in one transaction. - A local worker deploy waits for the runtime to start, so a script it cannot load fails the deploy. - Speechify plain text: an & that starts no XML entity and a < that starts no complete tag are escaped. - The events forward queue's byte bound counts UTF-8 bytes. - Without a dedicated store, thumbnails stay in the default bucket. - AppStore.invalidateWrittenByUid for writers that hold the uid. - subdomainFromHost takes the configured domain list; the sorting wrapper only tests called is removed. - Changelog and alarm docs match the code. * fix: cache pipelines fall back to single commands across shards, TURN records metered one by one, allowance baseline kept - execTogether runs single-key cache commands in one round trip and, on a cluster that cannot route them in one pipeline, sends each on its own. The row cache, tombstone reads and writes, the FS entry backfill, the permission check cache and the revoked-session cache write use it. - TURN usage ingestion makes one metering call per user with each record as its own usage, so one malformed record does not affect the others. - The allowance settlement keeps the baseline fold for month records without allowanceUsed. - Speechify plain text keeps a self-closing tag without attributes. * fix(localworker): a deploy waits for the runtime to start and a failed cold start answers 502 A script the runtime cannot load fails the deploy. What was serving before goes back in place, and a first request for such a worker answers 502. * fix(subdomains): the sites rooted under a folder are read in name order, a page at a time subdomainsRootedUnder takes the name to start past, so a caller pages through every match instead of stopping at one query's limit.
218 lines
7.5 KiB
TypeScript
218 lines
7.5 KiB
TypeScript
/*
|
|
* Copyright (C) 2024-present Puter Technologies Inc.
|
|
*
|
|
* This file is part of Puter.
|
|
*
|
|
* Puter is free software: you can redistribute it and/or modify
|
|
* it under the terms of the GNU Affero General Public License as published
|
|
* by the Free Software Foundation, either version 3 of the License, or
|
|
* (at your option) any later version.
|
|
*
|
|
* This program is distributed in the hope that it will be useful,
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
* GNU Affero General Public License for more details.
|
|
*
|
|
* You should have received a copy of the GNU Affero General Public License
|
|
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
*/
|
|
|
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
import type { Request } from 'express';
|
|
import type { Actor } from './actor';
|
|
|
|
/**
|
|
* Per-request context with both typed well-known fields AND an open-ended
|
|
* key-value map for ad-hoc data. Common fields (`actor`, `req`) are typed for
|
|
* autocomplete / safety, while the generic `get`/`set` bag lets any code stash
|
|
* per-request values without threading them through function arguments.
|
|
*
|
|
* Backed by Node's `AsyncLocalStorage`, so the context propagates through
|
|
* async/await, timers, and microtasks automatically. The middleware
|
|
* (`createRequestContextMiddleware`) wraps each incoming request in a fresh
|
|
* context after the auth probe has populated `req.actor`.
|
|
*
|
|
* Usage:
|
|
*
|
|
* ```ts
|
|
* // read typed field
|
|
* const actor = Context.get('actor');
|
|
*
|
|
* // read the express request from anywhere
|
|
* const req = Context.get('req');
|
|
*
|
|
* // stash / read ad-hoc values
|
|
* Context.set('myService.txId', txId);
|
|
* const txId = Context.get('myService.txId');
|
|
* ```
|
|
*/
|
|
|
|
// -- Well-known typed keys -------------------------------------------
|
|
|
|
export interface KnownContextFields {
|
|
/** The authenticated actor, if one was resolved by the auth probe. */
|
|
actor: Actor | undefined;
|
|
/** The express request object for this request. */
|
|
req: Request;
|
|
/** A unique id for this request — useful for structured logging / tracing. */
|
|
requestId: string;
|
|
/**
|
|
* The driver name the caller addressed (set by DriverController for
|
|
* `/drivers/call` dispatch); drivers read it to pick a provider.
|
|
*/
|
|
driverName: string;
|
|
/**
|
|
* Aborts when the client disconnects before the response has finished (set
|
|
* by DriverController). Some drivers (Gemini, Replicate) stop early on it.
|
|
* Async video and image jobs keep polling and are metered after a
|
|
* disconnect, since the provider bills them either way.
|
|
*/
|
|
abortSignal: AbortSignal;
|
|
/**
|
|
* Keeps the request's concurrency slot until `work` settles, for work that
|
|
* outlives the response. Set by DriverController for a capped method and by
|
|
* the route concurrency gate.
|
|
*/
|
|
keepConcurrencySlot: (work: Promise<unknown>) => void;
|
|
/**
|
|
* Aborts the chat driver's upstream request. A client disconnect doesn't
|
|
* fire it: the upstream bills a request it has accepted either way, so the
|
|
* driver lets it finish and meters what it reports.
|
|
*/
|
|
upstreamSignal: AbortSignal;
|
|
/**
|
|
* When true, `ChatCompletionDriver.complete` treats a request-level
|
|
* upstream 4xx as final instead of falling back to another provider — set
|
|
* by the Anthropic route, which needs the vendor's own error rather than a
|
|
* different provider's translation of it.
|
|
*/
|
|
strictUpstreamErrors: boolean;
|
|
/**
|
|
* Set while Puter files something into an account for it (mail delivery),
|
|
* so filesystem events never report that write as the request actor's own.
|
|
*/
|
|
platformWrite: boolean;
|
|
}
|
|
|
|
// Every key of `KnownContextFields`, checked both ways by the compiler, so
|
|
// `get` and `set` can never disagree about where a known key lives.
|
|
const KNOWN_KEY_FLAGS: Record<keyof KnownContextFields, true> = {
|
|
actor: true,
|
|
req: true,
|
|
requestId: true,
|
|
driverName: true,
|
|
abortSignal: true,
|
|
keepConcurrencySlot: true,
|
|
upstreamSignal: true,
|
|
strictUpstreamErrors: true,
|
|
platformWrite: true,
|
|
};
|
|
const KNOWN_KEYS: ReadonlySet<string> = new Set(Object.keys(KNOWN_KEY_FLAGS));
|
|
|
|
// -- Context store ---------------------------------------------------
|
|
|
|
interface ContextStore {
|
|
known: Partial<KnownContextFields>;
|
|
extra: Map<string, unknown>;
|
|
}
|
|
|
|
const als = new AsyncLocalStorage<ContextStore>();
|
|
|
|
const storeValue = (store: ContextStore, key: string, value: unknown) => {
|
|
if (KNOWN_KEYS.has(key)) {
|
|
(store.known as Record<string, unknown>)[key] = value;
|
|
} else {
|
|
store.extra.set(key, value);
|
|
}
|
|
};
|
|
|
|
// -- Public API ------------------------------------------------------
|
|
|
|
/**
|
|
* Static-style context accessor.
|
|
*
|
|
* Well-known keys (`KnownContextFields`) return typed values. Any other string
|
|
* key hits the generic map and returns `unknown`.
|
|
*/
|
|
export class Context {
|
|
/**
|
|
* Get a value from the current request context.
|
|
*
|
|
* Well-known keys return typed values; arbitrary string keys return
|
|
* `unknown`. Returns `undefined` when called outside a request scope or
|
|
* when the key hasn't been set.
|
|
*/
|
|
static get<K extends keyof KnownContextFields>(
|
|
key: K,
|
|
): KnownContextFields[K] | undefined;
|
|
static get(key: string): unknown;
|
|
static get(key: string): unknown {
|
|
const store = als.getStore();
|
|
if (!store) return undefined;
|
|
if (KNOWN_KEYS.has(key)) {
|
|
return (store.known as Record<string, unknown>)[key];
|
|
}
|
|
return store.extra.get(key);
|
|
}
|
|
|
|
/**
|
|
* Set a value on the current request context.
|
|
*
|
|
* Well-known keys are type-checked; arbitrary keys accept `unknown`.
|
|
*/
|
|
static set<K extends keyof KnownContextFields>(
|
|
key: K,
|
|
value: KnownContextFields[K],
|
|
): void;
|
|
static set(key: string, value: unknown): void;
|
|
static set(key: string, value: unknown): void {
|
|
const store = als.getStore();
|
|
if (!store) {
|
|
throw new Error(
|
|
`Context.set('${key}', ...) called outside a request scope`,
|
|
);
|
|
}
|
|
storeValue(store, key, value);
|
|
}
|
|
|
|
/**
|
|
* Returns the full context store, or `undefined` when called outside a
|
|
* request scope. Prefer `.get(key)` for individual lookups.
|
|
*/
|
|
static current(): ContextStore | undefined {
|
|
return als.getStore();
|
|
}
|
|
}
|
|
|
|
// -- Internal: used by the request-context middleware -----------------
|
|
|
|
/**
|
|
* Run `fn` in a scope that starts as a copy of the current one, so what it
|
|
* writes is invisible both to the caller and to anything running beside it.
|
|
* Cuts both ways: nothing the callee stores survives the scope.
|
|
*/
|
|
export const runInDerivedContext = <T>(fn: () => T): T => {
|
|
const parent = als.getStore();
|
|
const store: ContextStore = {
|
|
known: { ...(parent?.known ?? {}) },
|
|
extra: new Map(parent?.extra ?? []),
|
|
};
|
|
return als.run(store, fn);
|
|
};
|
|
|
|
/**
|
|
* Run `fn` inside a new context scope. Used by the request-context middleware
|
|
* to wrap the remainder of the middleware/handler chain.
|
|
*/
|
|
export const runWithContext = <T>(
|
|
initial: Partial<KnownContextFields>,
|
|
fn: () => T,
|
|
): T => {
|
|
const store: ContextStore = { known: {}, extra: new Map() };
|
|
// Routed like `set`, so an untyped caller's extra key stays readable.
|
|
for (const [key, value] of Object.entries(initial)) {
|
|
storeValue(store, key, value);
|
|
}
|
|
return als.run(store, fn);
|
|
};
|