@bitblit/ratchet-epsilon-common 6.0.146-alpha → 6.0.147-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/package.json +10 -9
  2. package/src/background/background-dynamo-log-table-handler.ts +44 -0
  3. package/src/background/background-entry.ts +4 -0
  4. package/src/background/background-execution-event-type.ts +9 -0
  5. package/src/background/background-execution-event.ts +9 -0
  6. package/src/background/background-execution-listener.ts +6 -0
  7. package/src/background/background-handler.ts +352 -0
  8. package/src/background/background-http-adapter-handler.ts +166 -0
  9. package/src/background/background-meta-response-internal.ts +5 -0
  10. package/src/background/background-process-handling.ts +6 -0
  11. package/src/background/background-process-log-table-entry.ts +11 -0
  12. package/src/background/background-queue-response-internal.ts +9 -0
  13. package/src/background/background-validator.ts +105 -0
  14. package/src/background/epsilon-background-process-error.ts +110 -0
  15. package/src/background/internal-background-entry.ts +10 -0
  16. package/src/background/manager/abstract-background-manager.ts +120 -0
  17. package/src/background/manager/aws-large-payload-s3-sqs-sns-background-manager.ts +87 -0
  18. package/src/background/manager/aws-sqs-sns-background-manager.ts +201 -0
  19. package/src/background/manager/background-manager-like.ts +44 -0
  20. package/src/background/manager/background-manager.spec.ts +89 -0
  21. package/src/background/manager/single-thread-local-background-manager.ts +58 -0
  22. package/src/background/s3-background-transaction-logger.ts +65 -0
  23. package/src/build/ratchet-epsilon-common-info.ts +19 -0
  24. package/src/built-in/background/echo-processor.ts +17 -0
  25. package/src/built-in/background/log-and-enqueue-echo-processor.ts +14 -0
  26. package/src/built-in/background/log-message-background-error-processor.ts +10 -0
  27. package/src/built-in/background/no-op-processor.ts +12 -0
  28. package/src/built-in/background/retry-processor.ts +51 -0
  29. package/src/built-in/background/sample-delay-processor.ts +15 -0
  30. package/src/built-in/background/sample-input-validated-processor-data.ts +4 -0
  31. package/src/built-in/background/sample-input-validated-processor.ts +14 -0
  32. package/src/built-in/built-in-trace-id-generators.ts +22 -0
  33. package/src/built-in/daemon/daemon-authorizer-function.ts +4 -0
  34. package/src/built-in/daemon/daemon-config.ts +9 -0
  35. package/src/built-in/daemon/daemon-group-selection-function.ts +3 -0
  36. package/src/built-in/daemon/daemon-handler.ts +87 -0
  37. package/src/built-in/daemon/daemon-process-state-list.ts +9 -0
  38. package/src/built-in/http/apollo/apollo-util.ts +43 -0
  39. package/src/built-in/http/apollo/default-epsilon-apollo-context.ts +11 -0
  40. package/src/built-in/http/apollo/epsilon-apollo-context-builder-options.ts +5 -0
  41. package/src/built-in/http/apollo/epsilon-lambda-apollo-context-function-argument.ts +6 -0
  42. package/src/built-in/http/apollo/epsilon-lambda-apollo-options.ts +11 -0
  43. package/src/built-in/http/apollo-filter.ts +151 -0
  44. package/src/built-in/http/built-in-auth-filters.ts +73 -0
  45. package/src/built-in/http/built-in-authorizers.ts +22 -0
  46. package/src/built-in/http/built-in-filters.spec.ts +26 -0
  47. package/src/built-in/http/built-in-filters.ts +300 -0
  48. package/src/built-in/http/built-in-handlers.ts +85 -0
  49. package/src/built-in/http/log-level-manipulation-filter.ts +26 -0
  50. package/src/built-in/http/run-handler-as-filter.spec.ts +67 -0
  51. package/src/built-in/http/run-handler-as-filter.ts +102 -0
  52. package/src/cli/ratchet-cli-handler.ts +23 -0
  53. package/src/cli/run-background-process-from-command-line.ts +32 -0
  54. package/src/config/background/background-aws-config.ts +8 -0
  55. package/src/config/background/background-config.ts +15 -0
  56. package/src/config/background/background-error-processor.ts +5 -0
  57. package/src/config/background/background-processor.ts +14 -0
  58. package/src/config/background/background-transaction-log.ts +9 -0
  59. package/src/config/background/background-transaction-logger.ts +6 -0
  60. package/src/config/cron/abstract-cron-entry.ts +17 -0
  61. package/src/config/cron/cron-background-entry.ts +17 -0
  62. package/src/config/cron/cron-config.ts +10 -0
  63. package/src/config/dynamo-db-config.ts +6 -0
  64. package/src/config/epsilon-config.ts +30 -0
  65. package/src/config/epsilon-lambda-event-handler.ts +12 -0
  66. package/src/config/epsilon-logger-config.ts +23 -0
  67. package/src/config/espilon-server-mode.ts +10 -0
  68. package/src/config/generic-aws-event-handler-function.ts +1 -0
  69. package/src/config/http/authorizer-function.ts +9 -0
  70. package/src/config/http/epsilon-authorization-context.ts +5 -0
  71. package/src/config/http/epsilon-cors-approach.ts +7 -0
  72. package/src/config/http/extended-api-gateway-event.ts +8 -0
  73. package/src/config/http/filter-chain-context.ts +15 -0
  74. package/src/config/http/filter-function.ts +3 -0
  75. package/src/config/http/handler-function.ts +4 -0
  76. package/src/config/http/http-config.ts +27 -0
  77. package/src/config/http/http-processing-config.ts +23 -0
  78. package/src/config/http/mapped-http-processing-config.ts +12 -0
  79. package/src/config/http/null-returned-object-handling.ts +7 -0
  80. package/src/config/inter-api/inter-api-aws-config.ts +5 -0
  81. package/src/config/inter-api/inter-api-config.ts +7 -0
  82. package/src/config/inter-api/inter-api-process-mapping.ts +11 -0
  83. package/src/config/local-server/local-server-event-logging-style.ts +8 -0
  84. package/src/config/local-server/local-server-http-method-handling.ts +7 -0
  85. package/src/config/local-server/local-server-options.ts +12 -0
  86. package/src/config/logging-trace-id-generator.ts +3 -0
  87. package/src/config/no-handlers-found-error.ts +6 -0
  88. package/src/config/open-api/open-api-document-components.ts +4 -0
  89. package/src/config/open-api/open-api-document.ts +7 -0
  90. package/src/config/s3-config.ts +8 -0
  91. package/src/config/sns-config.ts +7 -0
  92. package/src/config/sqs-config.ts +7 -0
  93. package/src/epsilon-build-properties.ts +21 -0
  94. package/src/epsilon-constants.ts +62 -0
  95. package/src/epsilon-global-handler.ts +238 -0
  96. package/src/epsilon-instance.ts +20 -0
  97. package/src/epsilon-logging-extension-processor.ts +19 -0
  98. package/src/http/auth/api-gateway-adapter-authentication-handler.ts +95 -0
  99. package/src/http/auth/auth0-web-token-manipulator.ts +69 -0
  100. package/src/http/auth/basic-auth-token.ts +7 -0
  101. package/src/http/auth/google-web-token-manipulator.spec.ts +15 -0
  102. package/src/http/auth/google-web-token-manipulator.ts +80 -0
  103. package/src/http/auth/jwt-ratchet-local-web-token-manipulator.ts +37 -0
  104. package/src/http/auth/local-web-token-manipulator.spec.ts +34 -0
  105. package/src/http/auth/local-web-token-manipulator.ts +114 -0
  106. package/src/http/auth/web-token-manipulator.ts +9 -0
  107. package/src/http/error/bad-gateway.ts +11 -0
  108. package/src/http/error/bad-request-error.ts +11 -0
  109. package/src/http/error/conflict-error.ts +12 -0
  110. package/src/http/error/forbidden-error.ts +12 -0
  111. package/src/http/error/gateway-timeout.ts +12 -0
  112. package/src/http/error/method-not-allowed-error.ts +12 -0
  113. package/src/http/error/misconfigured-error.ts +12 -0
  114. package/src/http/error/not-found-error.ts +12 -0
  115. package/src/http/error/not-implemented.ts +12 -0
  116. package/src/http/error/request-timeout-error.ts +12 -0
  117. package/src/http/error/service-unavailable.ts +12 -0
  118. package/src/http/error/too-many-requests-error.ts +12 -0
  119. package/src/http/error/unauthorized-error.ts +12 -0
  120. package/src/http/event-util.spec.ts +190 -0
  121. package/src/http/event-util.ts +272 -0
  122. package/src/http/response-util.spec.ts +117 -0
  123. package/src/http/response-util.ts +164 -0
  124. package/src/http/route/epsilon-router.ts +9 -0
  125. package/src/http/route/extended-auth-response-context.ts +7 -0
  126. package/src/http/route/route-and-parse.ts +8 -0
  127. package/src/http/route/route-mapping.ts +21 -0
  128. package/src/http/route/route-validator-config.ts +5 -0
  129. package/src/http/route/router-util.spec.ts +33 -0
  130. package/src/http/route/router-util.ts +314 -0
  131. package/src/http/web-handler.spec.ts +99 -0
  132. package/src/http/web-handler.ts +157 -0
  133. package/src/http/web-v2-handler.ts +34 -0
  134. package/src/inter-api/inter-api-entry.ts +8 -0
  135. package/src/inter-api/inter-api-util.spec.ts +77 -0
  136. package/src/inter-api/inter-api-util.ts +71 -0
  137. package/src/inter-api-manager.ts +75 -0
  138. package/src/lambda-event-handler/cron-epsilon-lambda-event-handler.spec.ts +130 -0
  139. package/src/lambda-event-handler/cron-epsilon-lambda-event-handler.ts +132 -0
  140. package/src/lambda-event-handler/dynamo-epsilon-lambda-event-handler.ts +42 -0
  141. package/src/lambda-event-handler/generic-sns-epsilon-lambda-event-handler.ts +38 -0
  142. package/src/lambda-event-handler/generic-sqs-epsilon-lambda-event-handler.ts +43 -0
  143. package/src/lambda-event-handler/inter-api-epsilon-lambda-event-handler.ts +33 -0
  144. package/src/lambda-event-handler/s3-epsilon-lambda-event-handler.ts +50 -0
  145. package/src/local-container-server.ts +128 -0
  146. package/src/local-server.spec.ts +16 -0
  147. package/src/local-server.ts +426 -0
  148. package/src/open-api-util/open-api-doc-modifications.ts +9 -0
  149. package/src/open-api-util/open-api-doc-modifier.spec.ts +22 -0
  150. package/src/open-api-util/open-api-doc-modifier.ts +90 -0
  151. package/src/open-api-util/yaml-combiner.spec.ts +26 -0
  152. package/src/open-api-util/yaml-combiner.ts +35 -0
  153. package/src/sample/sample-server-components-with-apollo.ts +87 -0
  154. package/src/sample/sample-server-components.ts +183 -0
  155. package/src/sample/sample-server-static-files.ts +614 -0
  156. package/src/sample/test-error-server.ts +140 -0
  157. package/src/util/aws-util.ts +89 -0
  158. package/src/util/context-global-data.ts +13 -0
  159. package/src/util/context-util.ts +156 -0
  160. package/src/util/cron-util.spec.ts +190 -0
  161. package/src/util/cron-util.ts +86 -0
  162. package/src/util/epsilon-config-parser.ts +90 -0
  163. package/src/util/epsilon-server-util.spec.ts +18 -0
  164. package/src/util/epsilon-server-util.ts +16 -0
@@ -0,0 +1,90 @@
1
+ import yaml from 'js-yaml';
2
+ import { OpenApiDocModifications } from './open-api-doc-modifications.js';
3
+ import { Logger } from '@bitblit/ratchet-common/logger/logger';
4
+
5
+ /**
6
+ * Monitoring endpoints
7
+ */
8
+ export class OpenApiDocModifier {
9
+ constructor(private options: OpenApiDocModifications) {}
10
+
11
+ public modifyOpenApiDoc(yamlString: string): string {
12
+ let rval: string;
13
+ if (!!yamlString && !!this.options) {
14
+ try {
15
+ const openApi: any = yaml.load(yamlString);
16
+ const removeTags: string[] = this.options.removeTags ? this.options.removeTags.map((t) => t.toLowerCase()) : [];
17
+
18
+ // Apply new server path
19
+ if (this.options.newServerPath) {
20
+ openApi['servers'] = [{ url: this.options.newServerPath }];
21
+ }
22
+
23
+ if (!!this.options.removeTags && openApi['tags']) {
24
+ if (openApi['tags']) {
25
+ openApi['tags'] = openApi.tags.filter((f) => {
26
+ const n: string = !!f && !!f['name'] ? f['name'].toLowerCase() : '';
27
+ const i: number = removeTags.indexOf(n);
28
+ return i === -1;
29
+ });
30
+ }
31
+ }
32
+
33
+ if (openApi['paths']) {
34
+ let newPaths: any = {};
35
+ Object.keys(openApi['paths']).forEach((p) => {
36
+ const path: any = openApi['paths'][p];
37
+ Object.keys(path).forEach((verb) => {
38
+ const entry: any = path[verb];
39
+ entry.tags = entry.tags ? entry.tags.filter((t) => removeTags.lastIndexOf(t.toLowerCase()) == -1) : entry.tags;
40
+ const matcher: string = verb.toLowerCase() + ' ' + p.toLowerCase();
41
+ if (this.matchNone(matcher, this.options.removeEndpoints)) {
42
+ newPaths[p] = newPaths[p] || {};
43
+ newPaths[p][verb] = entry;
44
+ }
45
+ });
46
+ });
47
+
48
+ if (this.options.sortEndpoints) {
49
+ const keys: string[] = Object.keys(newPaths).sort();
50
+ const newPaths2: any = {};
51
+ keys.forEach((k) => {
52
+ newPaths2[k] = newPaths[k];
53
+ });
54
+ newPaths = newPaths2;
55
+ }
56
+ openApi['paths'] = newPaths;
57
+ }
58
+
59
+ // Sort the schemas and remove any that are marked for removal
60
+ let remSchemas: string[] = this.options.removeSchemas || [];
61
+ remSchemas = remSchemas.map((s) => s.toLowerCase());
62
+ if (openApi['components'] && openApi['components']['schemas']) {
63
+ const keys: string[] = Object.keys(openApi['components']['schemas']).sort();
64
+ const newComp: any = {};
65
+ keys.forEach((k) => {
66
+ if (remSchemas.indexOf(k.toLowerCase()) === -1) {
67
+ newComp[k] = openApi['components']['schemas'][k];
68
+ }
69
+ });
70
+ openApi['components']['schemas'] = newComp;
71
+ }
72
+
73
+ rval = yaml.dump(openApi);
74
+ } catch (err) {
75
+ Logger.error('Error processing yaml: %s', err, err);
76
+ }
77
+ }
78
+ return rval;
79
+ }
80
+
81
+ private matchNone(input: string, regex: RegExp[]): boolean {
82
+ let rval: boolean = true;
83
+ if (!!input && !!regex) {
84
+ regex.forEach((r) => {
85
+ rval = rval && !r.test(input);
86
+ });
87
+ }
88
+ return rval;
89
+ }
90
+ }
@@ -0,0 +1,26 @@
1
+ import { Logger } from '@bitblit/ratchet-common/logger/logger';
2
+ import path from 'path';
3
+ import { YamlCombiner } from './yaml-combiner.js';
4
+ import { EsmRatchet } from '@bitblit/ratchet-common/lang/esm-ratchet';
5
+ import { describe, expect, test } from 'vitest';
6
+
7
+ describe('#yamlCombiner', function () {
8
+ test('should combine yamls', async () => {
9
+ const files: string[] = [
10
+ path.join(EsmRatchet.fetchDirName(import.meta.url), '../../../../test-data/epsilon/sample-yaml/test1.yaml'),
11
+ path.join(EsmRatchet.fetchDirName(import.meta.url), '../../../../test-data/epsilon/sample-yaml/test2.yaml'),
12
+ ];
13
+ const root: string[] = ['components', 'schemas'];
14
+
15
+ const result: string = YamlCombiner.combine(files, root);
16
+
17
+ expect(result).toBeTruthy();
18
+ expect(result.indexOf('Object1')).toBeGreaterThan(0);
19
+ expect(result.indexOf('Object2')).toBeGreaterThan(0);
20
+ expect(result.indexOf('Object3')).toBeGreaterThan(0);
21
+ expect(result.indexOf('Object4')).toBeGreaterThan(0);
22
+ expect(result.indexOf('components')).toEqual(0);
23
+ expect(result.indexOf('schemas')).toBeGreaterThan(0);
24
+ Logger.info('G: \n\n%s', result);
25
+ }, 30000);
26
+ });
@@ -0,0 +1,35 @@
1
+ /*
2
+ Functions to combine a set of yaml files
3
+ */
4
+
5
+ import fs from 'fs';
6
+ import { RequireRatchet } from '@bitblit/ratchet-common/lang/require-ratchet';
7
+ import yaml from 'js-yaml';
8
+ import { Logger } from '@bitblit/ratchet-common/logger/logger';
9
+
10
+ export class YamlCombiner {
11
+ public static combine(files: string[], inRootPath: string[] = []): string {
12
+ RequireRatchet.notNullOrUndefined(files, 'Files argument');
13
+ RequireRatchet.true(files.length > 0, 'Files argument larger than 0');
14
+ RequireRatchet.notNullOrUndefined(inRootPath, 'Root path argument');
15
+ Logger.info('Processing %d files into output', files.length);
16
+
17
+ let allElements: any = {};
18
+ for (const fName of files) {
19
+ //for (let i = 0; i < files.length; i++) {
20
+ const fileContents: string = fs.readFileSync(fName).toString();
21
+ const openApi: any = yaml.load(fileContents);
22
+ allElements = Object.assign(allElements, openApi);
23
+ }
24
+ const rootPath: string[] = Object.assign([], inRootPath);
25
+ while (rootPath.length > 0) {
26
+ const next: any = {};
27
+ next[rootPath[rootPath.length - 1]] = allElements;
28
+ rootPath.splice(rootPath.length - 1, 1);
29
+ allElements = next;
30
+ }
31
+
32
+ const rval: string = yaml.dump(allElements);
33
+ return rval;
34
+ }
35
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * This is an example of how to setup a local server for testing. Replace the createRouterConfig function
3
+ * with your own.
4
+ *
5
+ * This is split from sample-server-components so that not everyone needs to include
6
+ * apollo-server if they aren't gonna do graphql
7
+ */
8
+
9
+ import { Logger } from '@bitblit/ratchet-common/logger/logger';
10
+ import { PromiseRatchet } from '@bitblit/ratchet-common/lang/promise-ratchet';
11
+ import { ApolloServer } from '@apollo/server';
12
+ import { gql } from 'graphql-tag';
13
+ import { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin/landingPage/default';
14
+ import { EpsilonConfig } from '../config/epsilon-config.js';
15
+ import { ApolloFilter } from '../built-in/http/apollo-filter.js';
16
+ import { SampleServerStaticFiles } from './sample-server-static-files.js';
17
+ import { ApolloUtil } from '../built-in/http/apollo/apollo-util.js';
18
+ import { SampleServerComponents } from './sample-server-components';
19
+ import { EpsilonCorsApproach } from '../config/http/epsilon-cors-approach.js';
20
+
21
+ export class SampleServerComponentsWithApollo {
22
+ // Prevent instantiation
23
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
24
+ private constructor() {}
25
+
26
+ public static async createSampleApollo(): Promise<ApolloServer> {
27
+ const gqlString: string = SampleServerStaticFiles.SAMPLE_SERVER_GRAPHQL;
28
+ Logger.silly('Creating apollo from : %s', gqlString);
29
+ const typeDefs = gql(gqlString);
30
+
31
+ // Provide resolver functions for your schema fields
32
+ const resolvers = {
33
+ RootQueryType: {
34
+ serverMeta: async (_root) => {
35
+ return { version: 'A1', serverTime: new Date().toISOString() };
36
+ },
37
+ forceTimeout: async (_root) => {
38
+ // This will be longer than the max timeout
39
+ await PromiseRatchet.wait(1000 * 60 * 30);
40
+ return { placeholder: 'A1' };
41
+ },
42
+ },
43
+ };
44
+
45
+ const server: ApolloServer = new ApolloServer({
46
+ introspection: true,
47
+ typeDefs,
48
+ resolvers,
49
+ plugins: [
50
+ /*
51
+ // Install a landing page plugin based on NODE_ENV
52
+ process.env.NODE_ENV === 'production'
53
+ ? ApolloServerPluginLandingPageProductionDefault({
54
+ graphRef: 'my-graph-id@my-graph-variant',
55
+ footer: false,
56
+ })
57
+ : ApolloServerPluginLandingPageLocalDefault({ footer: false }),
58
+
59
+ */
60
+ ApolloServerPluginLandingPageLocalDefault({ footer: false }),
61
+ ],
62
+ });
63
+ // Need the server started before we start processing...
64
+ await server.start();
65
+
66
+ return server;
67
+ }
68
+
69
+ // Functions below here are for using as samples
70
+ public static async createSampleEpsilonConfig(label: string): Promise<EpsilonConfig> {
71
+ const cfg: EpsilonConfig = await SampleServerComponents.createSampleEpsilonConfig(label);
72
+
73
+ ApolloFilter.addApolloFilterToList(
74
+ cfg.httpConfig.defaultMetaHandling.preFilters,
75
+ new RegExp('.*graphql.*'),
76
+ await SampleServerComponentsWithApollo.createSampleApollo(),
77
+ {
78
+ context: (arg) =>
79
+ ApolloUtil.defaultEpsilonApolloContext(arg, { jwtRatchet: SampleServerComponents.createSampleTokenManipulator().jwtRatchet }),
80
+ timeoutMS: 5_000,
81
+ corsMethod: EpsilonCorsApproach.All,
82
+ },
83
+ );
84
+
85
+ return cfg;
86
+ }
87
+ }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * This is an example of how to setup a local server for testing. Replace the createRouterConfig function
3
+ * with your own.
4
+ */
5
+
6
+ import { ErrorRatchet } from '@bitblit/ratchet-common/lang/error-ratchet';
7
+ import { StringRatchet } from '@bitblit/ratchet-common/lang/string-ratchet';
8
+ import { LoggerLevelName } from '@bitblit/ratchet-common/logger/logger-level-name';
9
+ import { NumberRatchet } from '@bitblit/ratchet-common/lang/number-ratchet';
10
+ import { JwtTokenBase } from '@bitblit/ratchet-common/jwt/jwt-token-base';
11
+ import { BooleanRatchet } from '@bitblit/ratchet-common/lang/boolean-ratchet';
12
+ import { EpsilonGlobalHandler } from '../epsilon-global-handler.js';
13
+ import { AuthorizerFunction } from '../config/http/authorizer-function.js';
14
+ import { HandlerFunction } from '../config/http/handler-function.js';
15
+ import { BuiltInHandlers } from '../built-in/http/built-in-handlers.js';
16
+ import { HttpConfig } from '../config/http/http-config.js';
17
+ import { LocalWebTokenManipulator } from '../http/auth/local-web-token-manipulator.js';
18
+ import { BackgroundConfig } from '../config/background/background-config.js';
19
+ import { EchoProcessor } from '../built-in/background/echo-processor.js';
20
+ import { NoOpProcessor } from '../built-in/background/no-op-processor.js';
21
+ import { SampleDelayProcessor } from '../built-in/background/sample-delay-processor.js';
22
+ import { LogAndEnqueueEchoProcessor } from '../built-in/background/log-and-enqueue-echo-processor.js';
23
+ import { EpsilonConfig } from '../config/epsilon-config.js';
24
+ import { EpsilonInstance } from '../epsilon-instance.js';
25
+ import { EpsilonConfigParser } from '../util/epsilon-config-parser.js';
26
+ import { RouterUtil } from '../http/route/router-util.js';
27
+ import { SampleInputValidatedProcessor } from '../built-in/background/sample-input-validated-processor.js';
28
+ import { HttpProcessingConfig } from '../config/http/http-processing-config.js';
29
+ import { BuiltInAuthorizers } from '../built-in/http/built-in-authorizers.js';
30
+ import { SampleInputValidatedProcessorData } from '../built-in/background/sample-input-validated-processor-data.js';
31
+ import { BuiltInFilters } from '../built-in/http/built-in-filters.js';
32
+ import { LogMessageBackgroundErrorProcessor } from '../built-in/background/log-message-background-error-processor.js';
33
+ import { SingleThreadLocalBackgroundManager } from '../background/manager/single-thread-local-background-manager.js';
34
+ import { BackgroundManagerLike } from '../background/manager/background-manager-like.js';
35
+ import { SampleServerStaticFiles } from './sample-server-static-files.js';
36
+
37
+ export class SampleServerComponents {
38
+ // Prevent instantiation
39
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
40
+ private constructor() {}
41
+
42
+ public static createSampleTokenManipulator(): LocalWebTokenManipulator<JwtTokenBase> {
43
+ const tokenManipulator: LocalWebTokenManipulator<JwtTokenBase> = new LocalWebTokenManipulator(['abcd1234'], 'sample.erigir.com')
44
+ .withParseFailureLogLevel(LoggerLevelName.debug)
45
+ .withExtraDecryptionKeys(['abcdefabcdef'])
46
+ .withOldKeyUseLogLevel(LoggerLevelName.info);
47
+ return tokenManipulator;
48
+ }
49
+
50
+ // Functions below here are for using as samples
51
+ public static async createSampleEpsilonConfig(label: string): Promise<EpsilonConfig> {
52
+ const yamlString: string = SampleServerStaticFiles.SAMPLE_OPEN_API_DOC;
53
+ const authorizers: Map<string, AuthorizerFunction> = new Map<string, AuthorizerFunction>();
54
+ authorizers.set('SampleAuthorizer', (token, evt) => BuiltInAuthorizers.simpleLoggedInAuth(token, evt));
55
+ authorizers.set('LogAuthorizer', (token, evt) => BuiltInAuthorizers.simpleNoAuthenticationLogAccess(token, evt));
56
+
57
+ const handlers: Map<string, HandlerFunction<any>> = new Map<string, HandlerFunction<any>>();
58
+ handlers.set('get /', (event, context) => BuiltInHandlers.sample(event, null, context));
59
+ handlers.set('get /meta/server', (event) => BuiltInHandlers.sample(event));
60
+ handlers.set('get /meta/user', (event) => BuiltInHandlers.sample(event));
61
+ handlers.set('get /meta/item/{itemId}', (event) => BuiltInHandlers.sample(event));
62
+ handlers.set('post /secure/access-token', (event) => BuiltInHandlers.sample(event));
63
+ handlers.set('get /multi/fixed', (event) => BuiltInHandlers.sample(event, 'fixed'));
64
+ handlers.set('get /multi/{v}', (event) => BuiltInHandlers.sample(event, 'variable'));
65
+ handlers.set('get /event', (event) => {
66
+ return Promise.resolve({
67
+ statusCode: 200,
68
+ headers: { 'Content-Type': 'application/json' },
69
+ body: JSON.stringify(event, null, 2),
70
+ });
71
+ });
72
+ handlers.set('get /err/{code}', (event) => {
73
+ const err: Error = ErrorRatchet.fErr('Fake Err : %j', event);
74
+ err['statusCode'] = NumberRatchet.safeNumber(event.pathParameters['code']);
75
+ throw err;
76
+ });
77
+ handlers.set('get /meta/sample-item', async (event) => {
78
+ const numberToUse: number = NumberRatchet.safeNumber(event.queryStringParameters['num']) || 5;
79
+ const rval: SampleInputValidatedProcessorData = {
80
+ numberParam: numberToUse,
81
+ nameParam: 'Test-String',
82
+ };
83
+ return rval;
84
+ });
85
+ handlers.set('post /meta/sample-item', async (event) => {
86
+ const parsed: SampleInputValidatedProcessorData = event.parsedBody;
87
+ const forceFail: boolean = BooleanRatchet.parseBool(StringRatchet.trimToNull(event.queryStringParameters['forceFail'])) === true;
88
+ if (forceFail) {
89
+ parsed['numberParam'] = 'test' as unknown as number; // Should cause a failure outbound
90
+ }
91
+
92
+ return parsed;
93
+ });
94
+
95
+ const meta: HttpProcessingConfig = RouterUtil.defaultHttpMetaProcessingConfigWithAuthenticationHeaderParsing(
96
+ SampleServerComponents.createSampleTokenManipulator(),
97
+ );
98
+ meta.timeoutMS = 10_000;
99
+ meta.errorFilters.push((fCtx) => BuiltInFilters.secureOutboundServerErrorForProduction(fCtx, 'Clean Internal Server Error', 500));
100
+
101
+ const preFiltersAllowingNull: HttpProcessingConfig = Object.assign({}, meta);
102
+ // TODO: This approach is pretty fragile...
103
+ preFiltersAllowingNull.preFilters = Object.assign([], preFiltersAllowingNull.preFilters);
104
+ preFiltersAllowingNull.preFilters.splice(8, 1);
105
+
106
+ const cfg: HttpConfig = {
107
+ defaultMetaHandling: meta,
108
+ handlers: handlers,
109
+ authorizers: authorizers,
110
+ overrideMetaHandling: [
111
+ {
112
+ pathRegex: '/background',
113
+ methods: null,
114
+ config: Object.assign({}, meta, { overrideAuthorizerName: 'LogAuthorizer' }),
115
+ },
116
+ {
117
+ pathRegex: '/meta/server', // Allow null params ONLY on this route
118
+ methods: ['GET'],
119
+ config: preFiltersAllowingNull,
120
+ },
121
+ ],
122
+ prefixesToStripBeforeRouteMatch: ['v0'],
123
+ filterHandledRouteMatches: ['options .*'],
124
+ };
125
+
126
+ const background: BackgroundConfig = {
127
+ //aws: {
128
+ // queueUrl: 'FAKE-LOCAL',
129
+ // notificationArn: 'FAKE-LOCAL',
130
+ //},
131
+ httpMetaEndpoint: '/background/meta',
132
+ httpSubmissionPath: '/background',
133
+ implyTypeFromPathSuffix: false,
134
+ processors: [
135
+ new EchoProcessor(),
136
+ new NoOpProcessor(),
137
+ new SampleDelayProcessor(),
138
+ new SampleInputValidatedProcessor(),
139
+ new LogAndEnqueueEchoProcessor(),
140
+ ],
141
+ errorProcessor: new LogMessageBackgroundErrorProcessor(),
142
+ };
143
+
144
+ const epsilonConfig: EpsilonConfig = {
145
+ label: label,
146
+ openApiYamlString: yamlString,
147
+ httpConfig: cfg,
148
+ backgroundConfig: background,
149
+ };
150
+ return epsilonConfig;
151
+ }
152
+
153
+ public static async createSampleEpsilonGlobalHandler(label: string): Promise<EpsilonGlobalHandler> {
154
+ const epsilonConfig: EpsilonConfig = await SampleServerComponents.createSampleEpsilonConfig(label);
155
+ const backgroundManager: SingleThreadLocalBackgroundManager = new SingleThreadLocalBackgroundManager();
156
+ const epsilonInstance: EpsilonInstance = EpsilonConfigParser.epsilonConfigToEpsilonInstance(epsilonConfig, backgroundManager);
157
+ const rval: EpsilonGlobalHandler = new EpsilonGlobalHandler(epsilonInstance);
158
+ return rval;
159
+ }
160
+
161
+ public static async createSampleBatchOnlyEpsilonGlobalHandler(label: string): Promise<EpsilonGlobalHandler> {
162
+ const epsilonConfig: EpsilonConfig = await SampleServerComponents.createSampleEpsilonConfig(label);
163
+ epsilonConfig.httpConfig.handlers = new Map<string, HandlerFunction<any>>(); // Unused
164
+
165
+ const byPassCfg: HttpProcessingConfig = Object.assign({}, epsilonConfig.httpConfig.defaultMetaHandling);
166
+ byPassCfg.preFilters = byPassCfg.preFilters.concat([
167
+ (fCtx) => BuiltInFilters.autoRespond(fCtx, { message: 'Background Processing Only' }),
168
+ ]);
169
+ epsilonConfig.httpConfig.overrideMetaHandling = [
170
+ {
171
+ pathRegex: '.*background.*',
172
+ invertPathMatching: true,
173
+ config: byPassCfg,
174
+ },
175
+ ];
176
+ epsilonConfig.httpConfig.filterHandledRouteMatches = ['.*']; // Only want the batch handling
177
+
178
+ const backgroundManager: BackgroundManagerLike = new SingleThreadLocalBackgroundManager();
179
+ const epsilonInstance: EpsilonInstance = EpsilonConfigParser.epsilonConfigToEpsilonInstance(epsilonConfig, backgroundManager);
180
+ const rval: EpsilonGlobalHandler = new EpsilonGlobalHandler(epsilonInstance);
181
+ return rval;
182
+ }
183
+ }