@thexjs/core 1.6.1 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +51 -1
- package/dist/index.js +125 -0
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { ComponentType, ReactNode, CSSProperties, AnchorHTMLAttributes } from 'react';
|
|
3
3
|
|
|
4
|
+
interface BackpressureOptions {
|
|
5
|
+
/** Maximum number of requests allowed to execute concurrently in this process. */
|
|
6
|
+
maxConcurrent: number;
|
|
7
|
+
/** Maximum number of additional requests allowed to wait for a slot. Default: 0. */
|
|
8
|
+
maxQueue?: number;
|
|
9
|
+
/** Retry-After value used by `withBackpressure` when the queue is full. Default: 1 second. */
|
|
10
|
+
retryAfterSeconds?: number;
|
|
11
|
+
}
|
|
12
|
+
interface BackpressureSnapshot {
|
|
13
|
+
active: number;
|
|
14
|
+
queued: number;
|
|
15
|
+
maxConcurrent: number;
|
|
16
|
+
maxQueue: number;
|
|
17
|
+
}
|
|
18
|
+
interface BackpressureLease {
|
|
19
|
+
/** Releases one active slot. Safe to call more than once. */
|
|
20
|
+
release(): void;
|
|
21
|
+
}
|
|
22
|
+
interface BackpressureController {
|
|
23
|
+
/**
|
|
24
|
+
* Waits for an execution slot. Rejects with `BackpressureSaturatedError`
|
|
25
|
+
* when the queue is full, or with the request's abort reason while queued.
|
|
26
|
+
*/
|
|
27
|
+
acquire(signal?: AbortSignal): Promise<BackpressureLease>;
|
|
28
|
+
snapshot(): BackpressureSnapshot;
|
|
29
|
+
}
|
|
30
|
+
declare class BackpressureSaturatedError extends Error {
|
|
31
|
+
readonly retryAfterSeconds: number;
|
|
32
|
+
constructor(retryAfterSeconds: number);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Creates one in-process admission controller.
|
|
36
|
+
*
|
|
37
|
+
* This is deliberately separate from rate limiting: rate limiting controls
|
|
38
|
+
* request frequency per identity/window, while this controller bounds the
|
|
39
|
+
* amount of work that may be active or waiting inside one process at a time.
|
|
40
|
+
* Queued requests are promoted FIFO as active leases are released.
|
|
41
|
+
*/
|
|
42
|
+
declare function createBackpressureController(options: BackpressureOptions): BackpressureController;
|
|
43
|
+
type BackpressureHandler<TServer = unknown> = (req: Request, server?: TServer) => Response | Promise<Response>;
|
|
44
|
+
/**
|
|
45
|
+
* Wraps a request handler with bounded per-process admission.
|
|
46
|
+
*
|
|
47
|
+
* Saturation is reported as 503 Service Unavailable (not 429): the caller is
|
|
48
|
+
* not being rate-limited; this process has no execution/queue capacity left.
|
|
49
|
+
* Requests aborted while waiting are removed from the queue and their abort
|
|
50
|
+
* reason is re-thrown without invoking the wrapped handler.
|
|
51
|
+
*/
|
|
52
|
+
declare function withBackpressure<TServer = unknown>(handler: BackpressureHandler<TServer>, options: BackpressureOptions): BackpressureHandler<TServer>;
|
|
53
|
+
|
|
4
54
|
type RouteMode = "static" | "server";
|
|
5
55
|
interface BuildOptions {
|
|
6
56
|
routesDir?: string;
|
|
@@ -955,4 +1005,4 @@ declare function resetServerFunctions(): void;
|
|
|
955
1005
|
declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
|
|
956
1006
|
declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
|
|
957
1007
|
|
|
958
|
-
export { type AuditEntry, type AuditEvent, type AuditSink, type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CounterSeries, type CreateAppOptions, type CsrfOptions, type CsrfResult, DEFAULT_HISTOGRAM_BUCKETS_MS, DEFAULT_MAX_BODY_SIZE, DefaultNotFound, EnvLeakageError, type ErrorContext, type ErrorReporter, type Frontmatter, type HealthCheck, type HealthCheckOptions, type HistogramSeries, Image, type ImageProps, type ImageProxyOptions, type InMemoryMetricsOptions, type InMemoryMetricsReporter, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, Link, type LinkProps, type LoaderArgs, type LoaderReturn, type LogFields, type Logger, type MetricLabels, type MetricsReporter, type MetricsSnapshot, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, OTEL_ERROR_STATUS_CODE, type OtelMeterLike, type OtelTracerLike, PUBLIC_ENV_PREFIX, type ProcessCrashHandlerOptions, REDACTED, type RateLimitOptions, type RateLimitResult, type RateLimitStore, type ReadinessResult, RequestBodyTooLargeError, type RevalidateOptions, type RouteEntry, type RouteMode, type RouteProps, SRCSET_WIDTHS, type SecurityHeadersOptions, type SentryLike, type TraceSpan, type TracerLike, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, createApp, createConsoleAuditSink, createHealthCheckHandler, createImageProxyHandler, createInMemoryMetrics, createOtelReporter, createOtlpMetricsReporter, createRateLimiter, createRedisRateLimitStore, createSentryReporter, dbTraceAttributes, defineConfig, enforceRequestBodySize, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getAuditSink, getErrorReporter, getServerFunctionHandler, getTracer, installProcessCrashHandlers, isSensitiveKey, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, runWithRequestSpan, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, setTracer, tracePhase, tracePhaseSync, traceRequestId, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
|
|
1008
|
+
export { type AuditEntry, type AuditEvent, type AuditSink, type BackpressureController, type BackpressureHandler, type BackpressureLease, type BackpressureOptions, BackpressureSaturatedError, type BackpressureSnapshot, type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CounterSeries, type CreateAppOptions, type CsrfOptions, type CsrfResult, DEFAULT_HISTOGRAM_BUCKETS_MS, DEFAULT_MAX_BODY_SIZE, DefaultNotFound, EnvLeakageError, type ErrorContext, type ErrorReporter, type Frontmatter, type HealthCheck, type HealthCheckOptions, type HistogramSeries, Image, type ImageProps, type ImageProxyOptions, type InMemoryMetricsOptions, type InMemoryMetricsReporter, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, Link, type LinkProps, type LoaderArgs, type LoaderReturn, type LogFields, type Logger, type MetricLabels, type MetricsReporter, type MetricsSnapshot, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, OTEL_ERROR_STATUS_CODE, type OtelMeterLike, type OtelTracerLike, PUBLIC_ENV_PREFIX, type ProcessCrashHandlerOptions, REDACTED, type RateLimitOptions, type RateLimitResult, type RateLimitStore, type ReadinessResult, RequestBodyTooLargeError, type RevalidateOptions, type RouteEntry, type RouteMode, type RouteProps, SRCSET_WIDTHS, type SecurityHeadersOptions, type SentryLike, type TraceSpan, type TracerLike, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, createApp, createBackpressureController, createConsoleAuditSink, createHealthCheckHandler, createImageProxyHandler, createInMemoryMetrics, createOtelReporter, createOtlpMetricsReporter, createRateLimiter, createRedisRateLimitStore, createSentryReporter, dbTraceAttributes, defineConfig, enforceRequestBodySize, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getAuditSink, getErrorReporter, getServerFunctionHandler, getTracer, installProcessCrashHandlers, isSensitiveKey, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, runWithRequestSpan, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, setTracer, tracePhase, tracePhaseSync, traceRequestId, verifyCsrfToken, verifyOrigin, withBackpressure, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
|
package/dist/index.js
CHANGED
|
@@ -56,6 +56,128 @@ import {
|
|
|
56
56
|
withRequestTracing
|
|
57
57
|
} from "./chunk-OIPCIXYR.js";
|
|
58
58
|
|
|
59
|
+
// src/backpressure.ts
|
|
60
|
+
var BackpressureSaturatedError = class extends Error {
|
|
61
|
+
retryAfterSeconds;
|
|
62
|
+
constructor(retryAfterSeconds) {
|
|
63
|
+
super("Backpressure queue is full");
|
|
64
|
+
this.name = "BackpressureSaturatedError";
|
|
65
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
function positiveInteger(value, name) {
|
|
69
|
+
if (!Number.isInteger(value) || value < 1) {
|
|
70
|
+
throw new TypeError(`${name} must be a positive integer`);
|
|
71
|
+
}
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
function nonNegativeInteger(value, name) {
|
|
75
|
+
if (!Number.isInteger(value) || value < 0) {
|
|
76
|
+
throw new TypeError(`${name} must be a non-negative integer`);
|
|
77
|
+
}
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
function abortReason(signal) {
|
|
81
|
+
if (signal.reason !== void 0) return signal.reason;
|
|
82
|
+
return new DOMException("The operation was aborted", "AbortError");
|
|
83
|
+
}
|
|
84
|
+
function createBackpressureController(options) {
|
|
85
|
+
const maxConcurrent = positiveInteger(options.maxConcurrent, "maxConcurrent");
|
|
86
|
+
const maxQueue = nonNegativeInteger(options.maxQueue ?? 0, "maxQueue");
|
|
87
|
+
const retryAfterSeconds = positiveInteger(options.retryAfterSeconds ?? 1, "retryAfterSeconds");
|
|
88
|
+
const queue = [];
|
|
89
|
+
let active = 0;
|
|
90
|
+
function detachAbort(waiter) {
|
|
91
|
+
if (waiter.signal && waiter.onAbort) {
|
|
92
|
+
waiter.signal.removeEventListener("abort", waiter.onAbort);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function makeLease() {
|
|
96
|
+
let released = false;
|
|
97
|
+
return {
|
|
98
|
+
release() {
|
|
99
|
+
if (released) return;
|
|
100
|
+
released = true;
|
|
101
|
+
active -= 1;
|
|
102
|
+
promote();
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
function promote() {
|
|
107
|
+
while (active < maxConcurrent && queue.length > 0) {
|
|
108
|
+
const waiter = queue.shift();
|
|
109
|
+
if (!waiter) return;
|
|
110
|
+
detachAbort(waiter);
|
|
111
|
+
if (waiter.signal?.aborted) {
|
|
112
|
+
waiter.reject(abortReason(waiter.signal));
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
active += 1;
|
|
116
|
+
waiter.resolve(makeLease());
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function acquire(signal) {
|
|
120
|
+
if (signal?.aborted) return Promise.reject(abortReason(signal));
|
|
121
|
+
if (active < maxConcurrent) {
|
|
122
|
+
active += 1;
|
|
123
|
+
return Promise.resolve(makeLease());
|
|
124
|
+
}
|
|
125
|
+
if (queue.length >= maxQueue) {
|
|
126
|
+
return Promise.reject(new BackpressureSaturatedError(retryAfterSeconds));
|
|
127
|
+
}
|
|
128
|
+
return new Promise((resolve2, reject) => {
|
|
129
|
+
const waiter = {
|
|
130
|
+
signal,
|
|
131
|
+
resolve: resolve2,
|
|
132
|
+
reject,
|
|
133
|
+
onAbort: void 0
|
|
134
|
+
};
|
|
135
|
+
if (signal) {
|
|
136
|
+
waiter.onAbort = () => {
|
|
137
|
+
const index = queue.indexOf(waiter);
|
|
138
|
+
if (index < 0) return;
|
|
139
|
+
queue.splice(index, 1);
|
|
140
|
+
detachAbort(waiter);
|
|
141
|
+
reject(abortReason(signal));
|
|
142
|
+
};
|
|
143
|
+
signal.addEventListener("abort", waiter.onAbort, { once: true });
|
|
144
|
+
}
|
|
145
|
+
queue.push(waiter);
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
acquire,
|
|
150
|
+
snapshot() {
|
|
151
|
+
return { active, queued: queue.length, maxConcurrent, maxQueue };
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
function withBackpressure(handler, options) {
|
|
156
|
+
const controller = createBackpressureController(options);
|
|
157
|
+
return async (req, server) => {
|
|
158
|
+
let lease;
|
|
159
|
+
try {
|
|
160
|
+
lease = await controller.acquire(req.signal);
|
|
161
|
+
} catch (error) {
|
|
162
|
+
if (error instanceof BackpressureSaturatedError) {
|
|
163
|
+
return new Response("Service Unavailable", {
|
|
164
|
+
status: 503,
|
|
165
|
+
headers: {
|
|
166
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
167
|
+
"Retry-After": String(error.retryAfterSeconds)
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
throw error;
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
return await handler(req, server);
|
|
175
|
+
} finally {
|
|
176
|
+
lease.release();
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
59
181
|
// src/build.ts
|
|
60
182
|
import { cpSync, existsSync, mkdirSync, writeFileSync } from "fs";
|
|
61
183
|
import { join as join2, relative as relative2 } from "path";
|
|
@@ -2850,6 +2972,7 @@ function installProcessCrashHandlers(options = {}) {
|
|
|
2850
2972
|
};
|
|
2851
2973
|
}
|
|
2852
2974
|
export {
|
|
2975
|
+
BackpressureSaturatedError,
|
|
2853
2976
|
CLIENT_NAV_SCRIPT,
|
|
2854
2977
|
DEFAULT_HISTOGRAM_BUCKETS_MS,
|
|
2855
2978
|
DEFAULT_MAX_BODY_SIZE,
|
|
@@ -2882,6 +3005,7 @@ export {
|
|
|
2882
3005
|
combineReporters,
|
|
2883
3006
|
composeMiddleware,
|
|
2884
3007
|
createApp,
|
|
3008
|
+
createBackpressureController,
|
|
2885
3009
|
createConsoleAuditSink,
|
|
2886
3010
|
createHealthCheckHandler,
|
|
2887
3011
|
createImageProxyHandler,
|
|
@@ -2941,6 +3065,7 @@ export {
|
|
|
2941
3065
|
traceRequestId,
|
|
2942
3066
|
verifyCsrfToken,
|
|
2943
3067
|
verifyOrigin,
|
|
3068
|
+
withBackpressure,
|
|
2944
3069
|
withCsrfCookie,
|
|
2945
3070
|
withRequestLogging,
|
|
2946
3071
|
withRequestMetrics,
|
package/package.json
CHANGED