@bitblit/ratchet-epsilon-common
Version:
Tiny adapter to simplify building API gateway Lambda APIS
116 lines • 5.54 kB
JavaScript
import { EventUtil } from "./http/event-util.js";
import fetch from "cross-fetch";
import { LocalServer } from "./local-server.js";
import { Logger } from "@bitblit/ratchet-common/logger/logger";
import { StringRatchet } from "@bitblit/ratchet-common/lang/string-ratchet";
import { LoggerLevelName } from "@bitblit/ratchet-common/logger/logger-level-name";
import { CliRatchet } from "@bitblit/ratchet-node-only/cli/cli-ratchet";
import { LocalServerHttpMethodHandling } from "./config/local-server/local-server-http-method-handling.js";
import { LocalServerEventLoggingStyle } from "./config/local-server/local-server-event-logging-style.js";
export class LocalContainerServer {
containerUrl;
server;
aborted = false;
options;
constructor(containerUrl = 'http://localhost:9000/2015-03-31/functions/function/invocations', inOpts) {
this.containerUrl = containerUrl;
this.options = {
port: inOpts?.port ?? 8889,
https: inOpts?.https ?? false,
methodHandling: inOpts?.methodHandling ?? LocalServerHttpMethodHandling.Uppercase,
eventLoggingLevel: inOpts?.eventLoggingLevel ?? LoggerLevelName.debug,
eventLoggingStyle: inOpts?.eventLoggingStyle ?? LocalServerEventLoggingStyle.Summary,
graphQLIntrospectionEventLogLevel: inOpts?.graphQLIntrospectionEventLogLevel ?? LoggerLevelName.silly
};
}
async runServer() {
return new Promise((res, rej) => {
try {
Logger.info('Starting Epsilon container-wrapper server on port %d calling to %s', this.options.port, this.containerUrl);
this.server = LocalServer.createNodeServer(this.options, this.requestHandler.bind(this));
Logger.info('Epsilon server is listening');
process.on('SIGINT', () => {
Logger.info('Caught SIGINT - shutting down test server...');
this.aborted = true;
res(true);
});
}
catch (err) {
Logger.error('Local server failed : %s', err, err);
rej(err);
}
});
}
async requestHandler(request, response) {
const context = {
awsRequestId: 'LOCAL-' + StringRatchet.createType4Guid(),
getRemainingTimeInMillis() {
return 300000;
},
};
const evt = await LocalServer.messageToApiGatewayEvent(request, context, this.options);
const logEventLevel = EventUtil.eventIsAGraphQLIntrospection(evt) ? LoggerLevelName.silly : LoggerLevelName.info;
Logger.logByLevel(logEventLevel, 'Processing event: %j', evt);
const respBodyText = null;
let result;
if (evt.path == '/epsilon-poison-pill') {
this.aborted = true;
return true;
}
else if (evt.path.startsWith('/epsilon-background-launcher')) {
Logger.info('Showing background launcher page');
response.end(LocalServer.buildBackgroundTriggerFormHtml());
return true;
}
else if (evt.path.startsWith('/epsilon-background-trigger')) {
Logger.info('Running background trigger');
try {
const bgEntry = LocalServer.parseEpsilonBackgroundTriggerAsTask(evt);
const snsEvent = LocalServer.createBackgroundSNSEvent(bgEntry);
const postResp = await fetch(this.containerUrl, { method: 'POST', body: JSON.stringify(snsEvent) });
let postProxy = await postResp.json();
if (!LocalServer.isProxyResult(postProxy)) {
Logger.error('Upstream returned something not a proxy result - forcing');
postProxy = {
statusCode: 500,
body: JSON.stringify({ 'failure': 'Upstream did not return a proxyResult', contents: postProxy })
};
}
const written = await LocalServer.writeProxyResultToServerResponse(postProxy, response, evt, this.options);
return written;
}
catch (err) {
response.end(`<html><body>BG TRIGGER FAILED : Error : ${err}</body></html>`);
return true;
}
}
else {
try {
const postResp = await fetch(this.containerUrl, { method: 'POST', body: JSON.stringify(evt) });
const postProxy = await postResp.json();
const written = await LocalServer.writeProxyResultToServerResponse(postProxy, response, evt, this.options);
return written;
}
catch (err) {
Logger.error('Failed: %s : Body was %s Response was : %j', err, respBodyText, result, err);
return '{"bad":true}';
}
}
}
static async runFromCliArgs(_args) {
try {
Logger.setLevel(LoggerLevelName.debug);
Logger.debug('Running local container server : %j', process?.argv);
const _postArgs = CliRatchet.argsAfterCommand(['run-local-container-server']);
const testServer = new LocalContainerServer();
await testServer.runServer();
Logger.info('Got res server');
process.exit(0);
}
catch (err) {
Logger.error('Error : %s', err);
process.exit(1);
}
}
}
//# sourceMappingURL=local-container-server.js.map