Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | 1x 1x 1x 1x 1x 1x 1x 1x 20x 18x 1x 5x 5x 2x 10x 10x 3x 9x 11x 2x 2x 2x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 3x 4x 4x 4x 1x 14x 10x 9x 9x 4x 4x 3x 3x 3x 1x 9x 9x 9x 17x 17x 17x 17x 17x 17x 17x 2x 15x 15x 14x 11x 8x 2x 6x 1x 5x 9x 9x 1x 9x 1x 1x 1x 9x 2x 2x 26x 26x 26x 26x 6x 20x 20x 20x 20x 15x 15x 5x 9x 4x 4x 2x 2x 3x 1x | import {
ServerResponse,
IncomingMessage,
createServer,
RequestListener,
} from "http";
import { URL } from "url";
import {
Endpoint,
SimpleMeta,
Transport,
TransportType,
URL_FORM_DATA_KEY,
HTTP_STATUS_CODES,
matchUrl,
ApiError,
} from "estuary-rpc";
import { readAuthentication } from "./authentication";
import {
answerError,
createErrorHandlers,
DEFAULT_BAD_REQUEST,
DEFAULT_NOT_FOUND,
DEFAULT_TOO_LARGE,
DEFAULT_UNAUTHORIZED,
errorResponse,
} from "./errors";
import { automaticMiddleware, getUrl, methodId } from "./middleware";
import { MultiPartParser } from "./multipart";
import { ApiContext, RestApiContext, ServerOpts } from "./types";
/** Default {@link ServerOpts.maxBodyBytes}: 10 MiB @group Server */
export const DEFAULT_MAX_BODY_BYTES = 10 * 1024 * 1024;
export const restResponse =
(res: ServerResponse) => (status: number, message?: string) => {
res
.writeHead(status, {
"Content-Length": Buffer.byteLength(message ?? ""),
"Content-Type": "application/json",
})
.end(message);
};
/** Options for {@link parseIncoming} @group Server */
export type ParseOpts = {
/** Largest body read, in bytes; a larger one is refused (an {@link ApiError} with 413) */
maxBodyBytes?: number;
/** Path parameters matched in the URL, added to the request */
params?: Record<string, string>;
};
const parseJson = (text: string) => {
try {
return JSON.parse(text);
} catch {
throw new ApiError(HTTP_STATUS_CODES.BAD_REQUEST, DEFAULT_BAD_REQUEST);
}
};
function queryRecord(url: URL | undefined, rawStrings?: boolean) {
const requestRecord: Record<string, unknown> = {};
for (const [key, value] of url?.searchParams ?? []) {
requestRecord[key] = rawStrings ? value : parseJson(value);
}
return requestRecord;
}
/** Adds path parameters to a request (an object, or nothing). */
function withParams<Req>(request: Req, params?: Record<string, string>): Req {
if (!params || !Object.keys(params).length) return request;
Iif (request === null || request === undefined) return params as unknown as Req;
if (typeof request === "object" && !Array.isArray(request)) {
return { ...request, ...params } as Req;
}
return request;
}
/** Reads a request's whole body, up to maxBodyBytes, as a Buffer. */
function readBody(incoming: IncomingMessage, maxBodyBytes: number) {
return new Promise<Buffer>((resolve, reject) => {
const chunks: Buffer[] = [];
let size = 0;
const onData = (chunk: Buffer) => {
size += chunk.length;
if (size > maxBodyBytes) {
incoming.off("data", onData);
incoming.resume();
reject(new ApiError(HTTP_STATUS_CODES.CONTENT_TOO_LARGE, DEFAULT_TOO_LARGE));
return;
}
chunks.push(chunk);
};
incoming.on("data", onData);
incoming.on("end", () => resolve(Buffer.concat(chunks)));
incoming.on("error", reject);
});
}
export async function parseIncoming<Req, Res>(
incoming: IncomingMessage,
transport: Transport<Req, Res>,
url?: URL,
{ maxBodyBytes = DEFAULT_MAX_BODY_BYTES, params }: ParseOpts = {}
): Promise<Req | null> {
if (
transport.transportType === TransportType.URL_FORM_DATA ||
transport.transportType === TransportType.RAW
) {
const requestRecord = queryRecord(url, transport.rawStrings);
// non-objects are encoded as _es_data=<value>
Iif (
requestRecord[URL_FORM_DATA_KEY] !== undefined &&
Object.keys(requestRecord).length === 1
) {
return requestRecord[URL_FORM_DATA_KEY] as Req;
}
// A raw transport's body is left for the endpoint to read.
return withParams(requestRecord as Req, params);
}
Iif (transport.transportType === TransportType.MULTIPART_FORM_DATA) {
const multiPart = new MultiPartParser(
incoming,
transport.persist,
transport.rawStrings
);
await new Promise<void>((resolve, reject) => {
incoming.on("data", (chunk) => multiPart.parse(chunk));
incoming.on("end", resolve);
incoming.on("error", reject);
});
const multiData = multiPart.get();
// non-objects are encoded as _es_data=<value>
Iif (multiData[URL_FORM_DATA_KEY] && Object.keys(multiData).length === 1) {
return multiData[URL_FORM_DATA_KEY] as Req;
}
return withParams(multiData as Req, params);
}
const body = await readBody(incoming, maxBodyBytes);
Iif (transport.transportType === TransportType.UNKNOWN) {
return transport.decode.req(
transport.isBinary ? new Uint8Array(body) : body.toString("utf8")
);
}
const text = body.toString("utf8");
// how to gracefully handle this if we don't know whether req is nullable?
return withParams(text === "" ? null : (parseJson(text) as Req), params);
}
/**
* The listener for one REST endpoint. Before the body is read, the call's authentication is read onto its context
* and checked by {@link ServerOpts.authenticate}, and the middlewares run; then the endpoint is called with the
* request and the context, and its response is sent as JSON (204 for none), unless it answered the call itself.
* An error thrown along the way is answered as {@link answerError} says.
* @group Server
*/
export function restEndpoint<Req, Res, Meta extends SimpleMeta>(
endpoint: Endpoint<Req, Res, ApiContext, unknown>,
meta: Meta,
serverOpts: ServerOpts<Meta>
) {
const transport = (meta.transport || {
transportType: TransportType.JSON,
}) as Transport<Req, Res>;
const where = `${meta.method} /${meta.url}`;
return async (
req: IncomingMessage,
res: ServerResponse,
params?: Record<string, string>
) => {
const respond = restResponse(res);
const answered = () => res.headersSent || res.writableEnded;
const { badRequest, internalServerError } = createErrorHandlers(respond);
const apiContext: RestApiContext = {
badRequest,
internalServerError,
respond,
req,
res,
authentication: readAuthentication(
req,
meta.authentication || serverOpts.defaultAuthentication
),
};
try {
if (
apiContext.authentication &&
serverOpts.authenticate &&
!(await serverOpts.authenticate(apiContext.authentication, apiContext))
) {
throw new ApiError(HTTP_STATUS_CODES.UNAUTHORIZED, DEFAULT_UNAUTHORIZED);
}
for (const middleware of serverOpts.middlewares ?? []) {
Iif (!(await middleware(apiContext, meta))) {
return;
}
}
const body = await parseIncoming<Req, Res>(req, transport, getUrl(req), {
maxBodyBytes: serverOpts.maxBodyBytes,
params,
});
const response = await endpoint(body as Req, apiContext);
if (answered()) {
return;
}
if (response == null) {
res.writeHead(HTTP_STATUS_CODES.NO_CONTENT).end();
} else {
respond(HTTP_STATUS_CODES.OK, JSON.stringify(response));
}
} catch (error) {
Iif (answered()) {
// Too late to say so: the reply has started.
console.error(`${where}:`, error);
res.destroy();
return;
}
if (ApiError.is(error) && error.status === HTTP_STATUS_CODES.CONTENT_TOO_LARGE) {
res.shouldKeepAlive = false;
}
answerError(respond, error, where, serverOpts.mapError);
}
};
}
/** A REST endpoint's listener, which may be passed the URL's path parameters. @group Server */
export type RestListener = (
req: IncomingMessage,
res: ServerResponse,
params?: Record<string, string>
) => void | Promise<void>;
/**
* The request listener serving REST endpoints (by {@link methodId}, with path parameters, `:name` segments,
* matched when no URL matches exactly), after the rest middleware (static files, then
* {@link ServerOpts.restMiddleware}).
* @group Server
*/
export function createRestHandler<Meta extends SimpleMeta>(
restEndpoints: { [methodId: string]: RestListener | RequestListener },
serverOpts: ServerOpts<Meta>
): RequestListener {
const restMiddleware = automaticMiddleware(serverOpts);
const patterns = Object.keys(restEndpoints)
.filter((id) => id.includes(":", id.indexOf(":") + 1))
.map((id) => {
const split = id.indexOf(":");
return { id, method: id.slice(0, split), url: id.slice(split + 1) };
});
return async (req: IncomingMessage, res: ServerResponse) => {
try {
for (const middleware of restMiddleware) {
if (!(await middleware(req, res))) {
return;
}
}
const method = req.method ?? "";
const path = getUrl(req)?.pathname?.slice(1) ?? "";
const exact = restEndpoints[methodId({ method, url: path })];
if (exact) {
await exact(req, res);
return;
}
for (const pattern of patterns) {
if (pattern.method !== method) continue;
const params = matchUrl(pattern.url, path);
if (params) {
await (restEndpoints[pattern.id] as RestListener)(req, res, params);
return;
}
}
restResponse(res)(
HTTP_STATUS_CODES.NOT_FOUND,
errorResponse(DEFAULT_NOT_FOUND)
);
} catch (error) {
if (res.headersSent) {
console.error(`${req.method} ${req.url}:`, error);
res.destroy();
} else {
answerError(restResponse(res), error, `${req.method} ${req.url}`, serverOpts.mapError);
}
}
};
}
export function createRestServer<Meta extends SimpleMeta>(
restEndpoints: { [methodId: string]: RestListener | RequestListener },
serverOpts: ServerOpts<Meta>
) {
return createServer(createRestHandler(restEndpoints, serverOpts));
}
|