File size: 5,838 Bytes
e81f4e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import { contextFileThreshold } from "../../completion/context-files";
import { elapsedMs, logStage, nowMs } from "../../shared/logging";
import type { UnknownRecord } from "../../shared/types";
import { readJsonRequest, requestContentLength } from "./json";
import type { ReadJsonRequestOptions } from "./json";

const LARGE_CONTEXT_INLINE_UNSUPPORTED = "large_context_inline_unsupported";

type RouteJsonConfig = {
	current_input_file_enabled?: unknown;
	current_input_file_min_bytes?: unknown;
	generic_file_upload_max_bytes?: unknown;
	request_body_max_bytes?: unknown;
	supports_authenticated_session?: unknown;
	cookie?: unknown;
	log_requests?: unknown;
};

const JSON_ATTACHMENT_OVERHEAD_BYTES = 1024 * 1024;

export type RouteJsonPostResult =
	| {
			value: UnknownRecord;
			error?: undefined;
			status?: undefined;
			code?: undefined;
	  }
	| { error: string; status: number; code?: string; value?: undefined };

export async function readRouteJsonPost(
	request: Request,
	cfg: RouteJsonConfig,
	path: string,
): Promise<RouteJsonPostResult> {
	const rejection = oversizedInlineBodyRejection(request, cfg, path);
	if (rejection) return rejection;
	const parsed = await readJsonForRoute(request, cfg, path);
	if (parsed.error !== undefined) {
		const errorResult: Extract<RouteJsonPostResult, { error: string }> = {
			error: parsed.error,
			status: parsed.status || 400,
		};
		if (parsed.code) errorResult.code = parsed.code;
		return errorResult;
	}
	return { value: parsed.value };
}

export function googleJsonError(
	message: string,
	code?: string,
): { error: { message: string; code?: string } } {
	const error: { message: string; code?: string } = { message };
	if (code) error.code = code;
	return { error };
}

function oversizedInlineBodyRejection(
	request: Request,
	cfg: RouteJsonConfig,
	path: string,
): { message: string; error: string; status: number; code: string } | null {
	const unavailable = inlineContextUnavailableReason(cfg);
	if (!unavailable) return null;
	const contentLength = requestContentLength(request);
	if (contentLength == null) return null;
	const threshold = contextFileThreshold(cfg);
	const bodyLimit = inlineContextBodyReadLimit(cfg, threshold);
	const requestBodyLimit = positiveIntegerOrNull(cfg.request_body_max_bytes);
	if (requestBodyLimit != null && requestBodyLimit < bodyLimit) return null;
	if (contentLength <= bodyLimit) return null;
	logStage(cfg, "request_json_reject", {
		path,
		status: 413,
		code: LARGE_CONTEXT_INLINE_UNSUPPORTED,
		bodyBytes: contentLength,
		threshold,
		bodyLimit,
	});
	const message = `request body is too large to parse without Gemini text attachments (${contentLength} bytes > ${bodyLimit}; inline prompt threshold ${threshold}) and ${unavailable}; configure GEMINI_COOKIE with CURRENT_INPUT_FILE_ENABLED=true so this worker can use text attachments, or reduce the request size`;
	return {
		status: 413,
		code: LARGE_CONTEXT_INLINE_UNSUPPORTED,
		message,
		error: message,
	};
}

async function readJsonForRoute(
	request: Request,
	cfg: RouteJsonConfig,
	path: string,
) {
	const options = oversizedInlineBodyReadOptions(cfg);
	const start = cfg.log_requests ? nowMs() : 0;
	const parsed = await readJsonRequest(request, options);
	if (cfg.log_requests) {
		logStage(cfg, "request_json", {
			path,
			ms: elapsedMs(start),
			status: parsed.error !== undefined ? parsed.status : 200,
			code: parsed.code,
			bodyBytes: parsed.bytes ?? requestContentLength(request) ?? "unknown",
			bodyLimit: options?.maxBodyBytes,
		});
	}
	return parsed;
}

function oversizedInlineBodyReadOptions(
	cfg: RouteJsonConfig,
): ReadJsonRequestOptions | undefined {
	const requestBodyLimit = positiveIntegerOrNull(cfg.request_body_max_bytes);
	const unavailable = inlineContextUnavailableReason(cfg);
	if (!unavailable) return requestBodyReadOptions(requestBodyLimit);
	const threshold = contextFileThreshold(cfg);
	const bodyLimit = inlineContextBodyReadLimit(cfg, threshold);
	if (requestBodyLimit != null && requestBodyLimit < bodyLimit)
		return requestBodyReadOptions(requestBodyLimit);
	return {
		maxBodyBytes: bodyLimit,
		oversizedError: {
			status: 413,
			code: LARGE_CONTEXT_INLINE_UNSUPPORTED,
			message: `request body is too large to parse without Gemini text attachments (at least ${bodyLimit + 1} UTF-8 bytes > ${bodyLimit}; inline prompt threshold ${threshold}) and ${unavailable}; configure GEMINI_COOKIE with CURRENT_INPUT_FILE_ENABLED=true so this worker can use text attachments, or reduce the request size`,
		},
	};
}

function requestBodyReadOptions(
	requestBodyLimit: number | null,
): ReadJsonRequestOptions | undefined {
	if (requestBodyLimit == null) return undefined;
	return {
		maxBodyBytes: requestBodyLimit,
		oversizedError: {
			status: 413,
			code: "request_body_too_large",
			message: `request body exceeds configured JSON limit (${requestBodyLimit} bytes)`,
		},
	};
}

function positiveIntegerOrNull(value: unknown): number | null {
	const numberValue = Number(value);
	if (!Number.isSafeInteger(numberValue) || numberValue <= 0) return null;
	return numberValue;
}

export function inlineContextBodyReadLimit(
	cfg: RouteJsonConfig,
	threshold: number = contextFileThreshold(cfg),
): number {
	const attachmentMaxBytes = Number(cfg.generic_file_upload_max_bytes);
	if (!Number.isFinite(attachmentMaxBytes) || attachmentMaxBytes <= 0)
		return threshold;
	const encodedAttachmentBytes = Math.ceil(
		(Math.floor(attachmentMaxBytes) * 4) / 3,
	);
	return threshold + encodedAttachmentBytes + JSON_ATTACHMENT_OVERHEAD_BYTES;
}

function inlineContextUnavailableReason(cfg: RouteJsonConfig): string {
	if (!cfg.current_input_file_enabled)
		return "CURRENT_INPUT_FILE_ENABLED is disabled";
	if (!(cfg.supports_authenticated_session ?? !!cfg.cookie))
		return "GEMINI_COOKIE is not configured";
	return "";
}