Skip to content

Instantly share code, notes, and snippets.

@dsschneidermann
Created October 31, 2020 05:18
Show Gist options
  • Save dsschneidermann/a9314afee146feaffbeada42829e2e73 to your computer and use it in GitHub Desktop.
Save dsschneidermann/a9314afee146feaffbeada42829e2e73 to your computer and use it in GitHub Desktop.
const fs = require("fs");
const https = require("https");
const path = require("path");
const uuid = require("uuid/v4");
const libaccount = require("@zeit/cosmosdb-server/lib/account/index.js");
const libroutes = require("@zeit/cosmosdb-server/lib/routes.js");
const options = {
cert: fs.readFileSync("/app/certs/cosmosdb-sim-cert.crt"),
key: fs.readFileSync("/app/certs/cosmosdb-sim-cert.key"),
minVersion: "TLSv1",
rejectUnauthorized: false,
requestCert: false
};
exports.default = (opts) => {
const account = new libaccount.default();
return https.createServer({ ...options, ...opts }, (req, res) => {
const requestStart = Date.now();
let requestBody = [];
let requestErrorMessage = null;
let body = null; // response body
const log = (request, response, errorMessage) => {
const { rawHeaders, httpVersion, method, socket, url } = request;
const { remoteAddress, remoteFamily } = socket;
const { statusCode, statusMessage } = response;
const headers = response.getHeaders();
console.log(
JSON.stringify({
// timestamp: Date.now(),
// processingTime: Date.now() - requestStart,
method,
url,
docdbHeaders: rawHeaders.filter(
(h, i) => h.startsWith('x-ms-documentdb') || (i > 0 && rawHeaders[i-1].startsWith('x-ms-documentdb'))
),
// httpVersion,
// requestBody,
// requestHeaders: rawHeaders,
// remoteAddress,
// remoteFamily,
response: {
statusCode,
statusMessage,
headers,
body
},
errorMessage
})
);
};
const getChunk = chunk => requestBody.push(chunk);
const assembleRequestBody = () => {
requestBody = Buffer.concat(requestBody).toString();
};
const getError = error => {
requestErrorMessage = error.message;
};
req.on("data", getChunk);
req.on("end", assembleRequestBody);
req.on("error", getError);
const logClose = () => {
removeHandlers();
log(req, res, "Client aborted.");
};
const logError = error => {
removeHandlers();
log(req, res, error.message);
};
const logFinish = () => {
removeHandlers();
log(req, res, requestErrorMessage);
};
res.on("close", logClose);
res.on("error", logError);
res.on("finish", logFinish);
const removeHandlers = () => {
req.off("data", getChunk);
req.off("end", assembleRequestBody);
req.off("error", getError);
res.off("close", logClose);
res.off("error", logError);
res.off("finish", logFinish);
};
const route = libroutes.default(req);
(async () => {
if (route) {
const [params, handler] = route;
try {
body = await handler(account, req, res, params);
}
catch (err) {
// eslint-disable-next-line no-console
console.error(err);
body = { message: err.message };
res.statusCode = 500;
}
if (res.statusCode > 399 && !body.message) {
body.message = "";
}
}
else {
res.statusCode = 400;
body = { message: "no route" };
}
if (body && body._etag) {
res.setHeader("etag", body._etag);
}
res.setHeader("content-type", "application/json");
res.setHeader("content-location", `https://${req.headers.host}${req.url}`);
res.setHeader("connection", "close");
res.setHeader("x-ms-activity-id", uuid());
res.setHeader("x-ms-request-charge", "1");
if (req.headers["x-ms-documentdb-populatequerymetrics"]) {
res.setHeader("x-ms-documentdb-query-metrics", "totalExecutionTimeInMs=0.00;queryCompileTimeInMs=0.00;queryLogicalPlanBuildTimeInMs=0.00;queryPhysicalPlanBuildTimeInMs=0.00;queryOptimizationTimeInMs=0.00;VMExecutionTimeInMs=0.00;indexLookupTimeInMs=0.00;documentLoadTimeInMs=0.00;systemFunctionExecuteTimeInMs=0.00;userFunctionExecuteTimeInMs=0.00;retrievedDocumentCount=0;retrievedDocumentSize=0;outputDocumentCount=1;outputDocumentSize=0;writeOutputTimeInMs=0.00;indexUtilizationRatio=0.00");
}
if (req.headers["a-im"] && res.statusCode === 200) {
if (req.headers["if-none-match"]) {
res.statusCode = 304;
}
res.setHeader("etag", "1");
}
res.end(JSON.stringify(body));
})().catch(err => {
// eslint-disable-next-line no-console
console.error(err);
if (!res.finished) {
res.statusCode = 500;
res.end("");
}
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment