@midwayjs/faas 3.3.6-beta.4 → 3.4.0-beta.2

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2013 - Now midwayjs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -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,5 +1,5 @@
1
1
  /// <reference types="node" />
2
- import { Context, IFaaSConfigurationOptions, Application, NextFunction } from './interface';
2
+ import { Context, IFaaSConfigurationOptions, Application, NextFunction, HandlerOptions } from './interface';
3
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';
@@ -15,6 +15,7 @@ export declare class MidwayFaaSFramework extends BaseFramework<Application, Cont
15
15
  private server;
16
16
  private respond;
17
17
  private applicationAdapter;
18
+ private webRouterService;
18
19
  protected httpMiddlewareManager: ContextMiddlewareManager<Context, unknown, unknown>;
19
20
  protected eventMiddlewareManager: ContextMiddlewareManager<Context, unknown, unknown>;
20
21
  environmentService: MidwayEnvironmentService;
@@ -24,7 +25,12 @@ export declare class MidwayFaaSFramework extends BaseFramework<Application, Cont
24
25
  applicationInitialize(options: IMidwayBootstrapOptions): Promise<void>;
25
26
  run(): Promise<void>;
26
27
  getFrameworkType(): MidwayFrameworkType;
27
- handleInvokeWrapper(handlerMapping: string): (...args: any[]) => Promise<{
28
+ /**
29
+ * @deprecated
30
+ * @param handlerMapping
31
+ */
32
+ handleInvokeWrapper(handlerMapping: string): (...args: any[]) => Promise<any>;
33
+ getTriggerFunction(handlerMapping: string): (context: any, options: HandlerOptions) => Promise<{
28
34
  result: any;
29
35
  error: Error;
30
36
  } | {
@@ -33,6 +39,7 @@ export declare class MidwayFaaSFramework extends BaseFramework<Application, Cont
33
39
  headers: any;
34
40
  body: any;
35
41
  }>;
42
+ wrapHttpRequest(req: http.IncomingMessage, res?: http.ServerResponse): Promise<unknown>;
36
43
  /**
37
44
  * @deprecated
38
45
  * @param middlewareId
@@ -48,6 +55,7 @@ export declare class MidwayFaaSFramework extends BaseFramework<Application, Cont
48
55
  useMiddleware(middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>): void;
49
56
  useEventMiddleware(middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>): void;
50
57
  getEventMiddleware(): ContextMiddlewareManager<Context, NextFunction, undefined>;
58
+ getAllHandlerNames(): string[];
51
59
  }
52
60
  export declare const createModuleServerlessFramework: (globalOption: Omit<IMidwayBootstrapOptions, 'applicationContext'> & IFaaSConfigurationOptions) => Promise<MidwayFaaSFramework>;
53
61
  //# 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() {
@@ -44,13 +43,14 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
44
43
  return !this.developmentRun;
45
44
  }
46
45
  async applicationInitialize(options) {
47
- var _a, _b;
46
+ var _a, _b, _c;
48
47
  if (!this.logger) {
49
48
  this.logger = options.logger || logger_1.loggers.getLogger('appLogger');
50
49
  }
51
- this.applicationAdapter = this.configurationOptions.applicationAdapter;
50
+ this.applicationAdapter =
51
+ this.configurationOptions.applicationAdapter || {};
52
52
  this.app =
53
- ((_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)) ||
54
54
  new serverless_http_parser_1.Application();
55
55
  this.defineApplicationProperties({
56
56
  /**
@@ -68,29 +68,53 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
68
68
  },
69
69
  getFunctionName: () => {
70
70
  var _a;
71
- 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
+ '');
72
74
  },
75
+ /**
76
+ * get function service/group in runtime
77
+ */
73
78
  getFunctionServiceName: () => {
74
79
  var _a;
75
- 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);
76
97
  },
77
- useEventMiddleware: () => { },
78
98
  });
79
99
  // hack use method
80
100
  this.app.originUse = this.app.use;
81
101
  this.app.use = this.app.useMiddleware;
82
- 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) {
83
103
  this.configurationOptions.applicationAdapter.runAppHook(this.app);
84
104
  }
85
105
  }
86
106
  async run() {
87
107
  return this.lock.sureOnce(async () => {
88
- var _a, _b;
108
+ var _a;
89
109
  // set app keys
90
110
  this.app['keys'] = (_a = this.configService.getConfiguration('keys')) !== null && _a !== void 0 ? _a : '';
91
111
  // store all http function entry
92
- const collector = new core_1.ServerlessTriggerCollector();
93
- const functionList = await collector.getFunctionList();
112
+ this.webRouterService = await this.applicationContext.getAsync(core_1.MidwayWebRouterService, [
113
+ {
114
+ includeFunctionRouter: true,
115
+ },
116
+ ]);
117
+ const functionList = await this.webRouterService.getFlattenRouterTable();
94
118
  for (const funcInfo of functionList) {
95
119
  // store handler
96
120
  this.funMappingStore.set(funcInfo.funcHandlerName, funcInfo);
@@ -103,40 +127,69 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
103
127
  }
104
128
  }
105
129
  this.respond = this.app.callback();
106
- if (this.environmentService.isDevelopmentEnvironment()) {
107
- const faasConfig = (_b = this.configService.getConfiguration('faas')) !== null && _b !== void 0 ? _b : {};
108
- this.server = await new Promise(resolve => {
109
- const server = http.createServer((req, res) => {
110
- const url = new URL(req.url, `http://${req.headers.host}`);
111
- // create event and invoke
112
- this.handleInvokeWrapper(url.pathname)(req, res, {});
113
- });
114
- if (faasConfig['port']) {
115
- server.listen(faasConfig['port']);
116
- }
117
- resolve(server);
118
- });
119
- }
120
130
  }, LOCK_KEY);
121
131
  }
122
132
  getFrameworkType() {
123
133
  return core_1.MidwayFrameworkType.FAAS;
124
134
  }
135
+ /**
136
+ * @deprecated
137
+ * @param handlerMapping
138
+ */
125
139
  handleInvokeWrapper(handlerMapping) {
126
- let funOptions = this.funMappingStore.get(handlerMapping);
140
+ const funOptions = this.funMappingStore.get(handlerMapping);
127
141
  return async (...args) => {
128
- var _a, _b;
129
142
  if (args.length === 0) {
130
143
  throw new Error('first parameter must be function context');
131
144
  }
132
- const event = args[0];
133
- const isLegacyMode = event.originContext && event.originEvent;
134
- const isHttpFunction = event.constructor.name === 'IncomingMessage' ||
135
- event.constructor.name === 'EventEmitter' ||
136
- !!(event.headers && event.get);
145
+ if (!funOptions) {
146
+ throw new Error(`function handler = ${handlerMapping} not found`);
147
+ }
148
+ const context = this.getContext(args.shift());
149
+ const isHttpFunction = !!(context.headers && context.get);
150
+ const globalMiddlewareFn = await this.applyMiddleware();
151
+ const middlewareManager = new core_1.ContextMiddlewareManager();
152
+ middlewareManager.insertLast(globalMiddlewareFn);
153
+ middlewareManager.insertLast(async (ctx, next) => {
154
+ const fn = await this.middlewareService.compose([
155
+ ...(isHttpFunction
156
+ ? this.httpMiddlewareManager
157
+ : this.eventMiddlewareManager),
158
+ ...funOptions.controllerMiddleware,
159
+ ...funOptions.middleware,
160
+ async (ctx, next) => {
161
+ if (isHttpFunction) {
162
+ args = [ctx];
163
+ }
164
+ // invoke handler
165
+ const result = await this.invokeHandler(funOptions, ctx, args, isHttpFunction);
166
+ if (isHttpFunction && result !== undefined) {
167
+ if (result === null) {
168
+ // 这样设置可以绕过 koa 的 _explicitStatus 赋值机制
169
+ ctx.response._body = null;
170
+ }
171
+ else {
172
+ ctx.body = result;
173
+ }
174
+ }
175
+ return result;
176
+ },
177
+ ], this.app);
178
+ return await fn(ctx, next);
179
+ });
180
+ const composeMiddleware = await this.middlewareService.compose(middlewareManager, this.app);
181
+ return await composeMiddleware(context);
182
+ };
183
+ }
184
+ getTriggerFunction(handlerMapping) {
185
+ let funOptions = this.funMappingStore.get(handlerMapping);
186
+ return async (context, options) => {
187
+ var _a;
188
+ const isHttpFunction = options.isHttpFunction;
137
189
  if (!funOptions && isHttpFunction) {
138
190
  for (const item of this.serverlessRoutes) {
139
- if (item.matchPattern.test(event.path)) {
191
+ if (context.method === item.funcInfo['requestMethod'].toUpperCase() &&
192
+ item.matchPattern.test(context.path)) {
140
193
  funOptions = item.funcInfo;
141
194
  break;
142
195
  }
@@ -145,19 +198,7 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
145
198
  if (!funOptions) {
146
199
  throw new Error(`function handler = ${handlerMapping} not found`);
147
200
  }
148
- let context;
149
- if (isLegacyMode) {
150
- context = this.getContext(args.shift());
151
- }
152
- else if (isHttpFunction) {
153
- const newReq = ((_a = this.applicationAdapter) === null || _a === void 0 ? void 0 : _a.runRequestHook(...args)) ||
154
- new serverless_http_parser_1.HTTPRequest(args[0], args[1]);
155
- const newRes = new serverless_http_parser_1.HTTPResponse();
156
- context = this.getContext(await this.createHttpContext(newReq, newRes));
157
- }
158
- else {
159
- context = this.getContext(await ((_b = this.applicationAdapter) === null || _b === void 0 ? void 0 : _b.runEventHook(...args)));
160
- }
201
+ context = this.getContext(context);
161
202
  const result = await (await this.applyMiddleware(async (ctx, next) => {
162
203
  const fn = await this.middlewareService.compose([
163
204
  ...(isHttpFunction
@@ -166,24 +207,34 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
166
207
  ...funOptions.controllerMiddleware,
167
208
  ...funOptions.middleware,
168
209
  async (ctx, next) => {
210
+ let args;
169
211
  if (isHttpFunction) {
170
212
  args = [ctx];
171
213
  }
214
+ else {
215
+ args = [options.originEvent, options.originContext];
216
+ }
172
217
  // invoke handler
173
218
  const result = await this.invokeHandler(funOptions, ctx, args, isHttpFunction);
174
219
  if (isHttpFunction && result !== undefined) {
175
- ctx.body = result;
220
+ if (result === null) {
221
+ // 这样设置可以绕过 koa 的 _explicitStatus 赋值机制
222
+ ctx.response._body = null;
223
+ }
224
+ else {
225
+ ctx.body = result;
226
+ }
227
+ }
228
+ // http 靠 ctx.body,否则会出现状态码不正确的问题
229
+ if (!isHttpFunction) {
230
+ return result;
176
231
  }
177
- return result;
178
232
  },
179
233
  ], this.app);
180
234
  return await fn(ctx, next);
181
235
  }))(context);
182
- if (isLegacyMode) {
183
- return result;
184
- }
185
- else if (isHttpFunction) {
186
- if (!context.response._explicitStatus) {
236
+ if (isHttpFunction) {
237
+ if (!((_a = context.response) === null || _a === void 0 ? void 0 : _a._explicitStatus)) {
187
238
  if (context.body === null || context.body === 'undefined') {
188
239
  context.body = '';
189
240
  context.type = 'text';
@@ -220,6 +271,13 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
220
271
  // set data to string
221
272
  context.body = data = data + '';
222
273
  }
274
+ // middleware return value and will be got 204 status
275
+ if (context.body === undefined &&
276
+ !context.response._explicitStatus &&
277
+ context._matchedRoute) {
278
+ // 如果进了路由,重新赋值,防止 404
279
+ context.body = undefined;
280
+ }
223
281
  return {
224
282
  isBase64Encoded: encoded,
225
283
  statusCode: context.status,
@@ -232,6 +290,11 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
232
290
  }
233
291
  };
234
292
  }
293
+ async wrapHttpRequest(req, res) {
294
+ const newReq = res ? new serverless_http_parser_1.HTTPRequest(req, res) : req;
295
+ const newRes = new serverless_http_parser_1.HTTPResponse();
296
+ return this.createHttpContext(newReq, newRes);
297
+ }
235
298
  /**
236
299
  * @deprecated
237
300
  * @param middlewareId
@@ -325,6 +388,9 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
325
388
  getEventMiddleware() {
326
389
  return this.eventMiddlewareManager;
327
390
  }
391
+ getAllHandlerNames() {
392
+ return Array.from(this.funMappingStore.keys());
393
+ }
328
394
  };
329
395
  __decorate([
330
396
  (0, decorator_1.Inject)(),
@@ -1,4 +1,4 @@
1
- import { MidwayRequestContainer, IMidwayApplication, IConfigurationOptions, IMidwayContext, NextFunction as BaseNextFunction, CommonMiddlewareUnion, ContextMiddlewareManager } 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';
@@ -12,6 +12,11 @@ export interface FaaSContext extends IMidwayContext<FaaSHTTPContext> {
12
12
  * @deprecated
13
13
  */
14
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
+ }
15
20
  export declare type IMidwayFaaSApplication = IMidwayApplication<Context, {
16
21
  getInitializeContext(): any;
17
22
  use(middleware: FaaSMiddleware): any;
@@ -30,6 +35,8 @@ export declare type IMidwayFaaSApplication = IMidwayApplication<Context, {
30
35
  getFunctionServiceName(): string;
31
36
  useEventMiddleware(middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>): void;
32
37
  getEventMiddleware: ContextMiddlewareManager<Context, NextFunction, undefined>;
38
+ getTriggerFunction(handler: string): (context: any, options: HandlerOptions) => Promise<any>;
39
+ getServerlessInstance<T>(serviceClass: T): Promise<T>;
33
40
  }> & ServerlessHttpApplication;
34
41
  export interface Application extends IMidwayFaaSApplication {
35
42
  }
@@ -44,8 +51,6 @@ export interface IFaaSConfigurationOptions extends IConfigurationOptions {
44
51
  getFunctionName(): string;
45
52
  getFunctionServiceName(): string;
46
53
  runAppHook?(app: Application): void;
47
- runEventHook?(...args: any[]): any | void;
48
- runRequestHook?(...args: any[]): any | void;
49
54
  };
50
55
  }
51
56
  /**
@@ -54,4 +59,16 @@ export interface IFaaSConfigurationOptions extends IConfigurationOptions {
54
59
  export interface IWebMiddleware {
55
60
  resolve(): FaaSMiddleware;
56
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
+ }
57
74
  //# sourceMappingURL=interface.d.ts.map
package/package.json CHANGED
@@ -1,20 +1,20 @@
1
1
  {
2
2
  "name": "@midwayjs/faas",
3
- "version": "3.3.6-beta.4",
3
+ "version": "3.4.0-beta.2",
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.2",
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.4.0-beta.2",
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",
17
- "@midwayjs/serverless-scf-starter": "^3.3.5",
14
+ "@midwayjs/decorator": "^3.4.0-beta.2",
15
+ "@midwayjs/mock": "^3.4.0-beta.2",
16
+ "@midwayjs/serverless-fc-starter": "^3.4.0-beta.2",
17
+ "@midwayjs/serverless-scf-starter": "^3.4.0-beta.2",
18
18
  "mm": "3.2.0"
19
19
  },
20
20
  "engines": {
@@ -46,5 +46,5 @@
46
46
  "url": "git@github.com:midwayjs/midway.git"
47
47
  },
48
48
  "license": "MIT",
49
- "gitHead": "a603d2348d6141f8f723901498f03a162a037708"
49
+ "gitHead": "a61721d3946b30fd4cac183265edcd99b31ac72b"
50
50
  }