-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
168 lines (146 loc) · 4.28 KB
/
Copy pathroute.ts
File metadata and controls
168 lines (146 loc) · 4.28 KB
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
import { after } from 'next/server';
import {
createTransformError,
type TransformError,
type TransformErrorResponse,
type TransformResponse,
} from '@/lib/api';
import {
createTransformLog,
createValidationLog,
logTransformOutcome,
} from '@/lib/request-logger';
import {
type BufferedProgressEmitter,
createBufferedProgressEmitter,
createNdjsonResponse,
type FirstTransformOutcome,
NDJSON_CONTENT_TYPE,
} from '@/lib/stream';
import { transformUrl } from '@/lib/transform';
import {
type TransformRequest,
validateTransformRequest,
ValidationError,
} from '@/lib/validate';
export const maxDuration = 120;
const NDJSON_HEADERS = {
'Content-Type': NDJSON_CONTENT_TYPE,
'Cache-Control': 'no-cache',
} as const;
const MAX_REQUEST_BODY_SIZE = 4096;
const INVALID_JSON_BODY_MESSAGE = 'Invalid JSON body.';
async function readRequestBody(request: Request): Promise<unknown> {
const contentLength = Number.parseInt(
request.headers.get('Content-Length') ?? '',
10
);
if (Number.isFinite(contentLength) && contentLength > MAX_REQUEST_BODY_SIZE) {
throw new ValidationError('Request body too large.', 413);
}
const text = await request.text().catch(() => {
throw new ValidationError(INVALID_JSON_BODY_MESSAGE);
});
if (text.length > MAX_REQUEST_BODY_SIZE) {
throw new ValidationError('Request body too large.', 413);
}
try {
return JSON.parse(text) as unknown;
} catch {
throw new ValidationError(INVALID_JSON_BODY_MESSAGE);
}
}
async function parseTransformRequest(
request: Request
): Promise<TransformRequest> {
return validateTransformRequest(await readRequestBody(request));
}
function createValidationErrorResponse(error: unknown): Response {
const validationError =
error instanceof ValidationError
? error
: new ValidationError('Invalid request.');
return createErrorResponse(
createTransformError('VALIDATION_ERROR', validationError.message, {
retryable: false,
statusCode: validationError.statusCode,
})
);
}
function createErrorResponse(error: TransformError): Response {
return Response.json(
{ ok: false, error },
{ status: error.statusCode ?? 500 }
);
}
function shouldReturnImmediateErrorResponse(
initialOutcome: FirstTransformOutcome,
progressEmitter: BufferedProgressEmitter
): initialOutcome is {
type: 'response';
response: TransformErrorResponse;
} {
return (
initialOutcome.type === 'response' &&
!progressEmitter.hasProgress() &&
!initialOutcome.response.ok
);
}
function createStreamingTransformResponse(
request: Request,
responsePromise: Promise<TransformResponse>,
progressEmitter: BufferedProgressEmitter
): Response {
return createNdjsonResponse(
request,
responsePromise,
progressEmitter.attachWriter,
NDJSON_HEADERS
);
}
function scheduleTransformLog(
request: Request,
url: string,
startTime: number,
responseOrPromise: TransformResponse | Promise<TransformResponse>
): void {
after(async () => {
const response = await responseOrPromise;
logTransformOutcome(createTransformLog(request, url, startTime, response));
});
}
function scheduleValidationLog(request: Request, startTime: number): void {
after(() => logTransformOutcome(createValidationLog(request, startTime)));
}
export async function POST(request: Request): Promise<Response> {
const startTime = Date.now();
try {
const validated = await parseTransformRequest(request);
const progressEmitter = createBufferedProgressEmitter();
const responsePromise = transformUrl(
validated,
progressEmitter.emitProgress,
request.signal
);
const initialOutcome =
await progressEmitter.waitForFirstProgressOrResponse(responsePromise);
if (shouldReturnImmediateErrorResponse(initialOutcome, progressEmitter)) {
scheduleTransformLog(
request,
validated.url,
startTime,
initialOutcome.response
);
return createErrorResponse(initialOutcome.response.error);
}
scheduleTransformLog(request, validated.url, startTime, responsePromise);
return createStreamingTransformResponse(
request,
responsePromise,
progressEmitter
);
} catch (error) {
scheduleValidationLog(request, startTime);
return createValidationErrorResponse(error);
}
}