-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathr2Middleware.ts
More file actions
181 lines (156 loc) · 5.01 KB
/
r2Middleware.ts
File metadata and controls
181 lines (156 loc) · 5.01 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
169
170
171
172
173
174
175
176
177
178
179
180
181
import * as Sentry from '@sentry/cloudflare';
import { CACHE_HEADERS } from '../constants/cache';
import docsDirectory from '../constants/docsDirectory.json' assert { type: 'json' };
import type { Context } from '../context';
import type { GetFileResult } from '../providers/provider';
import { R2Provider } from '../providers/r2Provider';
import responses from '../responses';
import { hasTrailingSlash, isDirectoryPath } from '../utils/path';
import type { Middleware } from './middleware';
import latestVersions from '../constants/latestVersions.json' assert { type: 'json' };
import type { Request } from '../routes/request';
import { renderDirectoryListing } from '../utils/directoryListing';
import { parseConditionalHeaders } from '../utils/request';
import { once } from '../utils/memo';
const getProvider = once((ctx: Context) => new R2Provider({ ctx }));
export class R2Middleware implements Middleware {
async handle(request: Request, ctx: Context): Promise<Response> {
const path = getR2Path(request);
const isPathADirectory = isDirectoryPath(path);
Sentry.addBreadcrumb({
category: 'R2Middleware',
data: {
r2Path: path,
isPathADirectory,
},
});
return isPathADirectory
? handleDirectory(request, path, ctx)
: handleFile(request, path, ctx);
}
}
async function handleDirectory(
request: Request,
r2Path: string,
ctx: Context
): Promise<Response> {
if (!hasTrailingSlash(request.urlObj.pathname)) {
// We always want directory listing requests to have a trailing slash
const url = request.unsubstitutedUrl ?? request.urlObj;
return Response.redirect(`${url}/`, 301);
}
const result = await getProvider(ctx).readDirectory(r2Path);
if (result === undefined) {
return responses.directoryNotFound(request.method);
}
if (result.hasIndexHtmlFile) {
// Prioritize showing index files over directory listings
return handleFile(request, r2Path + 'index.html', ctx);
}
let responseBody;
if (request.method === 'GET') {
responseBody = renderDirectoryListing(
request.unsubstitutedUrl ?? request.urlObj,
result
);
}
return new Response(responseBody, {
headers: {
'last-modified': result.lastModified.toUTCString(),
'content-type': 'text/html',
'cache-control': CACHE_HEADERS.success,
},
});
}
function handleFile(
request: Request,
r2Path: string,
ctx: Context
): Promise<Response> {
switch (request.method) {
case 'HEAD':
return headFile(request, r2Path, ctx);
case 'GET':
return getFile(request, r2Path, ctx);
}
throw new Error('R2Middleware handleFile unsupported method');
}
async function headFile(
request: Request,
r2Path: string,
ctx: Context
): Promise<Response> {
const result = await getProvider(ctx).headFile(r2Path);
if (result === undefined) {
return responses.fileNotFound(request.method);
}
return new Response(undefined, {
status: result.httpStatusCode,
headers: result.httpHeaders,
});
}
async function getFile(
request: Request,
r2Path: string,
ctx: Context
): Promise<Response> {
const provider = getProvider(ctx);
let result: GetFileResult | undefined;
try {
result = await provider.getFile(r2Path, {
conditionalHeaders: parseConditionalHeaders(request.headers),
});
} catch (err) {
if (err instanceof Error) {
if (err.message.includes('10020')) {
// Object name not valid, url probably has some weirdness in it
return new Response(undefined, { status: 400 });
} else if (err.message.includes('10039')) {
// Range not compatible, probably out of bounds
return new Response(undefined, { status: 416 });
}
}
throw err;
}
if (result === undefined) {
return responses.fileNotFound(request.method);
}
return new Response(result.contents, {
status: result.httpStatusCode,
headers: result.httpHeaders,
});
}
function getR2Path({
urlObj,
params,
}: Pick<Request, 'urlObj' | 'params'>): string {
const { pathname } = urlObj;
const filePath = params.filePath ?? '';
if (pathname.startsWith('/dist')) {
return `nodejs/release/${filePath}`;
} else if (pathname.startsWith('/download')) {
return `nodejs/${filePath}`;
} else if (pathname.startsWith('/api')) {
return `nodejs/release/${latestVersions['latest']}/docs/api/${filePath}`;
} else if (pathname.startsWith('/docs')) {
if (params.version !== undefined) {
// /docs/vX.X.X at minimum
// Older version, docs exist in the docs folder
if (docsDirectory.includes(params.version)) {
return `nodejs/docs/${params.version}/${filePath}`;
}
return `nodejs/release/${params.version}/docs/${filePath}`;
} else {
// Just /docs
return `nodejs/docs/`;
}
} else if (
pathname.startsWith('/metrics') ||
pathname === '/node-config-schema.json' ||
pathname === '/llms.txt'
) {
// Substring to cut off the leading /
return pathname.substring(1);
}
throw new Error(`unhandled path case: ${pathname}`);
}