@midwayjs/faas 3.3.6-beta.3 → 3.4.0-beta.1

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.
@@ -1,7 +1,7 @@
1
1
  export declare const midwayLogger: {
2
2
  default: {
3
- disableFile: boolean;
4
- disableError: boolean;
3
+ enableFile: boolean;
4
+ enableError: boolean;
5
5
  printFormat: (info: any) => string;
6
6
  };
7
7
  };
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.midwayLogger = void 0;
4
4
  exports.midwayLogger = {
5
5
  default: {
6
- disableFile: true,
7
- disableError: true,
6
+ enableFile: false,
7
+ enableError: false,
8
8
  printFormat: (info) => {
9
9
  var _a, _b, _c, _d, _e, _f;
10
10
  const requestId = (_f = (_c = (_b = (_a = info.ctx) === null || _a === void 0 ? void 0 : _a['originContext']) === null || _b === void 0 ? void 0 : _b['requestId']) !== null && _c !== void 0 ? _c : (_e = (_d = info.ctx) === null || _d === void 0 ? void 0 : _d['originContext']) === null || _e === void 0 ? void 0 : _e['request_id']) !== null && _f !== void 0 ? _f : '';
@@ -1,34 +1,49 @@
1
1
  /// <reference types="node" />
2
- import { FaaSContext, IFaaSConfigurationOptions, IMidwayFaaSApplication } from './interface';
3
- import { BaseFramework, ContextMiddlewareManager, FunctionMiddleware, IMidwayBootstrapOptions, MidwayEnvironmentService, MidwayFrameworkType, MidwayMiddlewareService, RouterInfo } from '@midwayjs/core';
2
+ import { Context, IFaaSConfigurationOptions, Application, NextFunction, HandlerOptions } from './interface';
3
+ import { BaseFramework, CommonMiddlewareUnion, ContextMiddlewareManager, FunctionMiddleware, IMidwayBootstrapOptions, MidwayEnvironmentService, MidwayFrameworkType, MidwayMiddlewareService, RouterInfo } from '@midwayjs/core';
4
4
  import { LoggerOptions } from '@midwayjs/logger';
5
5
  import * as http from 'http';
6
- export declare class MidwayFaaSFramework extends BaseFramework<IMidwayFaaSApplication, FaaSContext, IFaaSConfigurationOptions> {
6
+ export declare class MidwayFaaSFramework extends BaseFramework<Application, Context, IFaaSConfigurationOptions> {
7
7
  protected defaultHandlerMethod: string;
8
8
  protected funMappingStore: Map<string, RouterInfo>;
9
9
  protected logger: any;
10
10
  private lock;
11
- app: IMidwayFaaSApplication;
11
+ app: Application;
12
12
  private isReplaceLogger;
13
13
  private developmentRun;
14
14
  private serverlessRoutes;
15
15
  private server;
16
16
  private respond;
17
17
  private applicationAdapter;
18
- protected eventMiddlewareManager: ContextMiddlewareManager<FaaSContext, unknown, unknown>;
18
+ protected httpMiddlewareManager: ContextMiddlewareManager<Context, unknown, unknown>;
19
+ protected eventMiddlewareManager: ContextMiddlewareManager<Context, unknown, unknown>;
19
20
  environmentService: MidwayEnvironmentService;
20
- middlewareService: MidwayMiddlewareService<FaaSContext, any>;
21
+ middlewareService: MidwayMiddlewareService<Context, any>;
21
22
  configure(options: IFaaSConfigurationOptions): any;
22
23
  isEnable(): boolean;
23
24
  applicationInitialize(options: IMidwayBootstrapOptions): Promise<void>;
24
25
  run(): Promise<void>;
25
26
  getFrameworkType(): MidwayFrameworkType;
27
+ /**
28
+ * @deprecated
29
+ * @param handlerMapping
30
+ */
26
31
  handleInvokeWrapper(handlerMapping: string): (...args: any[]) => Promise<any>;
32
+ getTriggerFunction(handlerMapping: string): (context: any, options: HandlerOptions) => Promise<{
33
+ result: any;
34
+ error: Error;
35
+ } | {
36
+ isBase64Encoded: boolean;
37
+ statusCode: any;
38
+ headers: any;
39
+ body: any;
40
+ }>;
41
+ wrapHttpRequest(req: http.IncomingMessage, res?: http.ServerResponse): Promise<unknown>;
27
42
  /**
28
43
  * @deprecated
29
44
  * @param middlewareId
30
45
  */
31
- generateMiddleware(middlewareId: string): Promise<FunctionMiddleware<FaaSContext, any>>;
46
+ generateMiddleware(middlewareId: string): Promise<FunctionMiddleware<Context, any>>;
32
47
  getContext(context?: any): any;
33
48
  private invokeHandler;
34
49
  protected getFunctionHandler(ctx: any, args: any, target: any, method: any): string;
@@ -36,6 +51,10 @@ export declare class MidwayFaaSFramework extends BaseFramework<IMidwayFaaSApplic
36
51
  getFrameworkName(): string;
37
52
  getServer(): http.Server;
38
53
  protected createHttpContext(req: any, res: any): Promise<unknown>;
54
+ useMiddleware(middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>): void;
55
+ useEventMiddleware(middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>): void;
56
+ getEventMiddleware(): ContextMiddlewareManager<Context, NextFunction, undefined>;
57
+ getAllHandlerNames(): string[];
39
58
  }
40
59
  export declare const createModuleServerlessFramework: (globalOption: Omit<IMidwayBootstrapOptions, 'applicationContext'> & IFaaSConfigurationOptions) => Promise<MidwayFaaSFramework>;
41
60
  //# sourceMappingURL=framework.d.ts.map
package/dist/framework.js CHANGED
@@ -15,7 +15,6 @@ const decorator_1 = require("@midwayjs/decorator");
15
15
  const simple_lock_1 = require("@midwayjs/simple-lock");
16
16
  const logger_1 = require("@midwayjs/logger");
17
17
  const serverless_http_parser_1 = require("@midwayjs/serverless-http-parser");
18
- const http = require("http");
19
18
  const LOCK_KEY = '_faas_starter_start_key';
20
19
  let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework {
21
20
  constructor() {
@@ -26,6 +25,7 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
26
25
  this.isReplaceLogger = process.env['MIDWAY_SERVERLESS_REPLACE_LOGGER'] === 'true';
27
26
  this.developmentRun = false;
28
27
  this.serverlessRoutes = [];
28
+ this.httpMiddlewareManager = this.createMiddlewareManager();
29
29
  this.eventMiddlewareManager = this.createMiddlewareManager();
30
30
  }
31
31
  configure(options) {
@@ -43,13 +43,14 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
43
43
  return !this.developmentRun;
44
44
  }
45
45
  async applicationInitialize(options) {
46
- var _a, _b;
46
+ var _a, _b, _c;
47
47
  if (!this.logger) {
48
48
  this.logger = options.logger || logger_1.loggers.getLogger('appLogger');
49
49
  }
50
- this.applicationAdapter = this.configurationOptions.applicationAdapter;
50
+ this.applicationAdapter =
51
+ this.configurationOptions.applicationAdapter || {};
51
52
  this.app =
52
- ((_a = this.applicationAdapter) === null || _a === void 0 ? void 0 : _a.getApplication()) ||
53
+ ((_b = (_a = this.applicationAdapter).getApplication) === null || _b === void 0 ? void 0 : _b.call(_a)) ||
53
54
  new serverless_http_parser_1.Application();
54
55
  this.defineApplicationProperties({
55
56
  /**
@@ -67,24 +68,44 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
67
68
  },
68
69
  getFunctionName: () => {
69
70
  var _a;
70
- return (_a = this.configurationOptions.applicationAdapter) === null || _a === void 0 ? void 0 : _a.getFunctionName();
71
+ return (process.env.MIDWAY_SERVERLESS_FUNCTION_NAME ||
72
+ ((_a = this.configurationOptions.applicationAdapter) === null || _a === void 0 ? void 0 : _a.getFunctionName()) ||
73
+ '');
71
74
  },
75
+ /**
76
+ * get function service/group in runtime
77
+ */
72
78
  getFunctionServiceName: () => {
73
79
  var _a;
74
- return (_a = this.configurationOptions.applicationAdapter) === null || _a === void 0 ? void 0 : _a.getFunctionServiceName();
80
+ return (process.env.MIDWAY_SERVERLESS_SERVICE_NAME ||
81
+ ((_a = this.configurationOptions.applicationAdapter) === null || _a === void 0 ? void 0 : _a.getFunctionServiceName()) ||
82
+ '');
83
+ },
84
+ useEventMiddleware: middleware => {
85
+ return this.useEventMiddleware(middleware);
86
+ },
87
+ getEventMiddleware: () => {
88
+ return this.getEventMiddleware();
89
+ },
90
+ getServerlessInstance: (serviceClass) => {
91
+ return this.app
92
+ .createAnonymousContext()
93
+ .requestContext.getAsync(serviceClass);
94
+ },
95
+ getTriggerFunction: (handlerMapping) => {
96
+ return this.getTriggerFunction(handlerMapping);
75
97
  },
76
- useEventMiddleware: () => { },
77
98
  });
78
99
  // hack use method
79
100
  this.app.originUse = this.app.use;
80
101
  this.app.use = this.app.useMiddleware;
81
- if ((_b = this.configurationOptions.applicationAdapter) === null || _b === void 0 ? void 0 : _b.runAppHook) {
102
+ if ((_c = this.configurationOptions.applicationAdapter) === null || _c === void 0 ? void 0 : _c.runAppHook) {
82
103
  this.configurationOptions.applicationAdapter.runAppHook(this.app);
83
104
  }
84
105
  }
85
106
  async run() {
86
107
  return this.lock.sureOnce(async () => {
87
- var _a, _b;
108
+ var _a;
88
109
  // set app keys
89
110
  this.app['keys'] = (_a = this.configService.getConfiguration('keys')) !== null && _a !== void 0 ? _a : '';
90
111
  // store all http function entry
@@ -102,66 +123,34 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
102
123
  }
103
124
  }
104
125
  this.respond = this.app.callback();
105
- if (this.environmentService.isDevelopmentEnvironment()) {
106
- const faasConfig = (_b = this.configService.getConfiguration('faas')) !== null && _b !== void 0 ? _b : {};
107
- this.server = await new Promise(resolve => {
108
- const server = http.createServer((req, res) => {
109
- const url = new URL(req.url, `http://${req.headers.host}`);
110
- // create event and invoke
111
- this.handleInvokeWrapper(url.pathname)(req, res, {});
112
- });
113
- if (faasConfig['port']) {
114
- server.listen(faasConfig['port']);
115
- }
116
- resolve(server);
117
- });
118
- }
119
126
  }, LOCK_KEY);
120
127
  }
121
128
  getFrameworkType() {
122
129
  return core_1.MidwayFrameworkType.FAAS;
123
130
  }
131
+ /**
132
+ * @deprecated
133
+ * @param handlerMapping
134
+ */
124
135
  handleInvokeWrapper(handlerMapping) {
125
- let funOptions = this.funMappingStore.get(handlerMapping);
136
+ const funOptions = this.funMappingStore.get(handlerMapping);
126
137
  return async (...args) => {
127
- var _a, _b;
128
138
  if (args.length === 0) {
129
139
  throw new Error('first parameter must be function context');
130
140
  }
131
- const event = args[0];
132
- const isLegacyMode = event.originContext && event.originEvent;
133
- const isHttpFunction = event.constructor.name === 'IncomingMessage' ||
134
- event.constructor.name === 'EventEmitter' ||
135
- !!(event.headers && event.get);
136
- if (!funOptions && isHttpFunction) {
137
- for (const item of this.serverlessRoutes) {
138
- if (item.matchPattern.test(event.path)) {
139
- funOptions = item.funcInfo;
140
- break;
141
- }
142
- }
143
- }
144
141
  if (!funOptions) {
145
142
  throw new Error(`function handler = ${handlerMapping} not found`);
146
143
  }
147
- let context;
148
- if (isLegacyMode) {
149
- context = this.getContext(args.shift());
150
- }
151
- else if (isHttpFunction) {
152
- const newReq = ((_a = this.applicationAdapter) === null || _a === void 0 ? void 0 : _a.runRequestHook(...args)) ||
153
- new serverless_http_parser_1.HTTPRequest(args[0], args[1]);
154
- const newRes = new serverless_http_parser_1.HTTPResponse();
155
- context = this.getContext(await this.createHttpContext(newReq, newRes));
156
- }
157
- else {
158
- context = this.getContext(await ((_b = this.applicationAdapter) === null || _b === void 0 ? void 0 : _b.runEventHook(...args)));
159
- }
144
+ const context = this.getContext(args.shift());
145
+ const isHttpFunction = !!(context.headers && context.get);
160
146
  const globalMiddlewareFn = await this.applyMiddleware();
161
147
  const middlewareManager = new core_1.ContextMiddlewareManager();
162
148
  middlewareManager.insertLast(globalMiddlewareFn);
163
149
  middlewareManager.insertLast(async (ctx, next) => {
164
150
  const fn = await this.middlewareService.compose([
151
+ ...(isHttpFunction
152
+ ? this.httpMiddlewareManager
153
+ : this.eventMiddlewareManager),
165
154
  ...funOptions.controllerMiddleware,
166
155
  ...funOptions.middleware,
167
156
  async (ctx, next) => {
@@ -179,12 +168,54 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
179
168
  return await fn(ctx, next);
180
169
  });
181
170
  const composeMiddleware = await this.middlewareService.compose(middlewareManager, this.app);
182
- const result = await composeMiddleware(context);
183
- if (isLegacyMode) {
184
- return result;
171
+ return await composeMiddleware(context);
172
+ };
173
+ }
174
+ getTriggerFunction(handlerMapping) {
175
+ let funOptions = this.funMappingStore.get(handlerMapping);
176
+ return async (context, options) => {
177
+ var _a;
178
+ const isHttpFunction = options.isHttpFunction;
179
+ if (!funOptions && isHttpFunction) {
180
+ for (const item of this.serverlessRoutes) {
181
+ if (context.method === item.funcInfo['requestMethod'].toUpperCase() &&
182
+ item.matchPattern.test(context.path)) {
183
+ funOptions = item.funcInfo;
184
+ break;
185
+ }
186
+ }
185
187
  }
186
- else if (isHttpFunction) {
187
- if (!context.response._explicitStatus) {
188
+ if (!funOptions) {
189
+ throw new Error(`function handler = ${handlerMapping} not found`);
190
+ }
191
+ context = this.getContext(context);
192
+ const result = await (await this.applyMiddleware(async (ctx, next) => {
193
+ const fn = await this.middlewareService.compose([
194
+ ...(isHttpFunction
195
+ ? this.httpMiddlewareManager
196
+ : this.eventMiddlewareManager),
197
+ ...funOptions.controllerMiddleware,
198
+ ...funOptions.middleware,
199
+ async (ctx, next) => {
200
+ let args;
201
+ if (isHttpFunction) {
202
+ args = [ctx];
203
+ }
204
+ else {
205
+ args = [options.originEvent, options.originContext];
206
+ }
207
+ // invoke handler
208
+ const result = await this.invokeHandler(funOptions, ctx, args, isHttpFunction);
209
+ if (isHttpFunction && result !== undefined) {
210
+ ctx.body = result;
211
+ }
212
+ return result;
213
+ },
214
+ ], this.app);
215
+ return await fn(ctx, next);
216
+ }))(context);
217
+ if (isHttpFunction) {
218
+ if (!((_a = context.response) === null || _a === void 0 ? void 0 : _a._explicitStatus)) {
188
219
  if (context.body === null || context.body === 'undefined') {
189
220
  context.body = '';
190
221
  context.type = 'text';
@@ -233,6 +264,11 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
233
264
  }
234
265
  };
235
266
  }
267
+ async wrapHttpRequest(req, res) {
268
+ const newReq = res ? new serverless_http_parser_1.HTTPRequest(req, res) : req;
269
+ const newRes = new serverless_http_parser_1.HTTPResponse();
270
+ return this.createHttpContext(newReq, newRes);
271
+ }
236
272
  /**
237
273
  * @deprecated
238
274
  * @param middlewareId
@@ -317,6 +353,18 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
317
353
  this.respond(req, res, resolve);
318
354
  });
319
355
  }
356
+ useMiddleware(middleware) {
357
+ this.httpMiddlewareManager.insertLast(middleware);
358
+ }
359
+ useEventMiddleware(middleware) {
360
+ this.eventMiddlewareManager.insertLast(middleware);
361
+ }
362
+ getEventMiddleware() {
363
+ return this.eventMiddlewareManager;
364
+ }
365
+ getAllHandlerNames() {
366
+ return Array.from(this.funMappingStore.keys());
367
+ }
320
368
  };
321
369
  __decorate([
322
370
  (0, decorator_1.Inject)(),
@@ -1,4 +1,4 @@
1
- import { MidwayRequestContainer, IMidwayApplication, IConfigurationOptions, IMidwayContext, NextFunction as BaseNextFunction } from '@midwayjs/core';
1
+ import { MidwayRequestContainer, IMidwayApplication, IConfigurationOptions, IMidwayContext, NextFunction as BaseNextFunction, CommonMiddlewareUnion, ContextMiddlewareManager, IMidwayBootstrapOptions } from '@midwayjs/core';
2
2
  import { FaaSHTTPContext } from '@midwayjs/faas-typings';
3
3
  import { ILogger } from '@midwayjs/logger';
4
4
  import { Application as ServerlessHttpApplication } from '@midwayjs/serverless-http-parser';
@@ -11,8 +11,13 @@ export interface FaaSContext extends IMidwayContext<FaaSHTTPContext> {
11
11
  /**
12
12
  * @deprecated
13
13
  */
14
- export declare type FaaSMiddleware = ((context: FaaSContext, next: () => Promise<any>) => any) | string;
15
- export declare type IMidwayFaaSApplication = IMidwayApplication<FaaSContext, {
14
+ export declare type FaaSMiddleware = ((context: Context, next: () => Promise<any>) => any) | string;
15
+ export interface HandlerOptions {
16
+ isHttpFunction: boolean;
17
+ originEvent: any;
18
+ originContext: any;
19
+ }
20
+ export declare type IMidwayFaaSApplication = IMidwayApplication<Context, {
16
21
  getInitializeContext(): any;
17
22
  use(middleware: FaaSMiddleware): any;
18
23
  /**
@@ -28,7 +33,10 @@ export declare type IMidwayFaaSApplication = IMidwayApplication<FaaSContext, {
28
33
  * Get function service name in serverless environment
29
34
  */
30
35
  getFunctionServiceName(): string;
31
- useEventMiddleware(): void;
36
+ useEventMiddleware(middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>): void;
37
+ getEventMiddleware: ContextMiddlewareManager<Context, NextFunction, undefined>;
38
+ getTriggerFunction(handler: string): (context: any, options: HandlerOptions) => Promise<any>;
39
+ getServerlessInstance<T>(serviceClass: T): Promise<T>;
32
40
  }> & ServerlessHttpApplication;
33
41
  export interface Application extends IMidwayFaaSApplication {
34
42
  }
@@ -39,12 +47,10 @@ export interface IFaaSConfigurationOptions extends IConfigurationOptions {
39
47
  config?: object;
40
48
  initializeContext?: object;
41
49
  applicationAdapter?: {
42
- getApplication(): IMidwayFaaSApplication;
50
+ getApplication(): Application;
43
51
  getFunctionName(): string;
44
52
  getFunctionServiceName(): string;
45
- runAppHook?(app: IMidwayFaaSApplication): void;
46
- runEventHook?(...args: any[]): any | void;
47
- runRequestHook?(...args: any[]): any | void;
53
+ runAppHook?(app: Application): void;
48
54
  };
49
55
  }
50
56
  /**
@@ -53,4 +59,16 @@ export interface IFaaSConfigurationOptions extends IConfigurationOptions {
53
59
  export interface IWebMiddleware {
54
60
  resolve(): FaaSMiddleware;
55
61
  }
62
+ export interface ServerlessStarterOptions extends IMidwayBootstrapOptions {
63
+ initializeMethodName?: string;
64
+ createAdapter?: () => Promise<{
65
+ close(): any;
66
+ createAppHook(app?: any): any;
67
+ }>;
68
+ performance?: {
69
+ mark(label: string): any;
70
+ end(): any;
71
+ };
72
+ exportAllHandler?: boolean;
73
+ }
56
74
  //# sourceMappingURL=interface.d.ts.map
package/package.json CHANGED
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "name": "@midwayjs/faas",
3
- "version": "3.3.6-beta.3",
3
+ "version": "3.4.0-beta.1",
4
4
  "main": "dist/index",
5
5
  "typings": "index.d.ts",
6
6
  "dependencies": {
7
- "@midwayjs/core": "^3.3.5",
7
+ "@midwayjs/core": "^3.4.0-beta.1",
8
8
  "@midwayjs/faas-typings": "^3.3.5",
9
9
  "@midwayjs/logger": "^2.15.0",
10
- "@midwayjs/simple-lock": "^1.1.4",
11
- "@midwayjs/serverless-http-parser": "^3.3.5"
10
+ "@midwayjs/serverless-http-parser": "^3.3.5",
11
+ "@midwayjs/simple-lock": "^1.1.4"
12
12
  },
13
13
  "devDependencies": {
14
- "@midwayjs/decorator": "^3.3.4",
15
- "@midwayjs/mock": "^3.3.5",
16
- "@midwayjs/serverless-fc-starter": "^3.3.5",
14
+ "@midwayjs/decorator": "^3.4.0-beta.1",
15
+ "@midwayjs/mock": "^3.4.0-beta.1",
16
+ "@midwayjs/serverless-fc-starter": "^3.4.0-beta.1",
17
17
  "@midwayjs/serverless-scf-starter": "^3.3.5",
18
18
  "mm": "3.2.0"
19
19
  },