Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,73 @@
import type { MiddlewareHandler } from "hono";
import { apiError, type ApiErrorEnv } from "./error-envelope.js";
export const DEFAULT_JSON_BODY_LIMIT_BYTES = 1_048_576;
export const DEFAULT_UPLOAD_BODY_LIMIT_BYTES = 10_485_760;
export const BODY_LIMIT_HEADER = "x-api-body-limit";
const WRITE_METHODS = new Set(["POST", "PUT", "PATCH"]);
type BodyLimitRule = {
limitBytes: number;
pathPrefix?: string;
};
type BodyLimitMiddlewareOptions = {
jsonLimitBytes?: number;
uploadLimitBytes?: number;
uploadPathPrefix?: string;
};
export function createBodyLimitMiddleware(options: BodyLimitMiddlewareOptions = {}): MiddlewareHandler<ApiErrorEnv> {
const jsonLimitBytes = options.jsonLimitBytes ?? DEFAULT_JSON_BODY_LIMIT_BYTES;
const uploadLimitBytes = options.uploadLimitBytes ?? DEFAULT_UPLOAD_BODY_LIMIT_BYTES;
const uploadPathPrefix = options.uploadPathPrefix ?? "/v1/ai/upload";
return async (c, next) => {
const method = c.req.method.toUpperCase();
if (!WRITE_METHODS.has(method)) {
await next();
return;
}
const rule = getBodyLimitRule(c.req.path, { jsonLimitBytes, uploadLimitBytes, uploadPathPrefix });
const contentLength = parseContentLength(c.req.header("content-length"));
c.header(BODY_LIMIT_HEADER, String(rule.limitBytes));
if (contentLength === null && requestHasBody(c.req.raw)) {
return apiError(c, 411, "content_length_required", "Write requests with a body require a valid Content-Length header.");
}
if (contentLength !== null && contentLength > rule.limitBytes) {
return apiError(c, 413, "body_too_large", "Request body is too large.");
}
await next();
};
}
function getBodyLimitRule(path: string, options: Required<BodyLimitMiddlewareOptions>): BodyLimitRule {
if (path === options.uploadPathPrefix || path.startsWith(`${options.uploadPathPrefix}/`)) {
return { limitBytes: options.uploadLimitBytes, pathPrefix: options.uploadPathPrefix };
}
return { limitBytes: options.jsonLimitBytes };
}
function parseContentLength(value: string | undefined): number | null {
if (!value) {
return null;
}
const normalized = value.trim();
if (!/^\d+$/.test(normalized)) {
return null;
}
const parsed = Number(normalized);
return Number.isSafeInteger(parsed) ? parsed : null;
}
function requestHasBody(request: Request) {
return request.body !== null;
}