Compare commits

...

27 Commits

Author SHA1 Message Date
wss-git 53524ca5a0 build: 0.0.22 2021-12-31 09:59:32 +08:00
千风 545b575b2e fix: fix async invoke withour stateul invoke id error 2021-12-31 09:57:48 +08:00
heimanba 25e6625cb2
Merge pull request #20 from devsapp/wss/dev
Wss/dev
2021-12-23 14:28:12 +08:00
wss-git 645a184c06 version: 0.0.21 2021-12-23 14:24:49 +08:00
wss-git 7486b7ee59 build: dev 2021-12-23 14:11:01 +08:00
wss-git e930d19e57 Merge branch 'master' of https://github.com/devsapp/fc-remote-invoke into wss/dev 2021-12-23 14:10:20 +08:00
wss-git 0bc9d61b5f
Merge pull request #19 from devsapp/fix#fc-460
fix: invoke function carry X-Fc-Invocation-Code-Version:Latest
2021-12-23 14:09:43 +08:00
wss-git 0b9712838c build: ncc transfrom esbuild 2021-12-23 14:07:27 +08:00
wss-git 24e0676581 fix: invoke function carry X-Fc-Invocation-Code-Version:Latest 2021-12-20 14:52:19 +08:00
wss-git f0468eddf3
Merge pull request #18 from devsapp/support/event-stdin
support/event-stdin
2021-12-13 15:19:03 +08:00
wss-git 93d6d628c2 support/event-stdin 2021-12-13 15:14:44 +08:00
wss-git 978e57fef7
Merge pull request #16 from devsapp/support-stateful-async-invocation-id
feat: add --stateful-async-invocation-id args
2021-11-16 13:29:42 +08:00
wss-git bf6593e33c build 0.0.20 2021-11-16 11:33:38 +08:00
wss-git 2c0a0b628d
Merge pull request #17 from devsapp/fix#fc-419
fix: show resp code
2021-11-16 11:25:30 +08:00
wss-git c1a2067fb0 style: ignore src dir 2021-11-15 11:23:50 +08:00
wss-git f8c5754072 fix: show resp code 2021-11-15 11:01:30 +08:00
千风 9c10415e0f feat: add --stateful-async-invocation-id args 2021-10-19 21:14:49 +08:00
千风 9c111e5b06 version 0.0.19 2021-10-19 16:00:26 +08:00
wss-git f7670a02aa fix: get client error 2021-10-19 15:56:19 +08:00
wss-git 724001f038
Merge pull request #13 from devsapp/dev
build: 0.0.18
2021-10-18 16:48:23 +08:00
wss-git 3f41b8c50a build: 0.0.18 2021-10-18 16:47:31 +08:00
wss-git ec36588ae7
Merge pull request #12 from devsapp/fc-325
Fc 325
2021-10-17 14:10:44 +08:00
wss-git 9121a9107e fix: handler http header to body 2021-10-17 14:10:24 +08:00
wss-git 2c3bcc6164 build: run build 2021-10-08 16:08:18 +08:00
wss-git 921e32f5db fix: http error log not fount 2021-08-23 17:59:37 +08:00
千风 9875ef92ab feat: version 0.0.17 2021-08-12 17:33:13 +08:00
千风 f3a244a6e1 build: update build process
move build to github action;add .signore;add -e option to ncc to make @serverless-devs/core out of
ncc compile
2021-08-12 17:33:13 +08:00
25 changed files with 193 additions and 265 deletions

View File

@ -21,9 +21,9 @@ jobs:
python -m pip install --upgrade pip
pip install setuptools wheel twine
pip install requests
# - name: NPM install
# run: |
# npm install --production
- name: Build
run: |
npm run build
- name: Add publish file
run: |
wget https://serverless-registry.oss-cn-hangzhou.aliyuncs.com/publish-file/python3/hub-publish.py

View File

@ -1,8 +1,7 @@
node_modules
.s
tsconfig.json
LICENSE
package-lok.json
package-lock.json
.prettierrc.js
.gitignore
@ -15,3 +14,4 @@ package-lok.json
README.md
./example
./.signore
./src

26
Makefile Normal file
View File

@ -0,0 +1,26 @@
.PHONY: push
CURRENT_BRANCH_NAME := $(shell git symbolic-ref --short HEAD)
add:
git add .
commit: add
git-cz
rebase-main: commit
git pull --rebase origin master
push:
git push --force-with-lease origin $(CURRENT_BRANCH_NAME)
release-dev: push
-gh release delete dev -y
-git tag -d dev
-git push origin :refs/tags/dev
gh release create dev --notes "dev release" --target dev --title "Release dev"
roll-back-dev:
git reset --soft HEAD~1
git restore --staged publish.yaml
git restore publish.yaml

View File

@ -23,9 +23,9 @@ services:
````
$ s exec -- invoke --invocation-type sync --event ${payload}
$ s exec -- invoke --invocation-type async --event-file ${path}
$ s exec -- invoke --event-stdin
$ s invoke --invocation-type sync --event ${payload}
$ s invoke --invocation-type async --event-file ${path}
$ s invoke --event-stdin
````
## CLI 用法

51
dist/index.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,11 +1,16 @@
{
"body": 123,
"method": "POST",
"headers": {
"key": "value"
"key": "value",
"Content-Type": "application/json"
},
"queries": {
"key": "value"
},
"path": "string"
"body": {
"abc": "body",
"tmpNasZipPath": "/tmpNasZipPath",
"body": "body"
},
"path": "download"
}

44
lib/common/help.d.ts vendored
View File

@ -1,44 +0,0 @@
declare const _default: ({
header: string;
content: string;
optionList?: undefined;
} | {
header: string;
optionList: ({
name: string;
description: string;
type: StringConstructor;
alias?: undefined;
} | {
name: string;
description: string;
alias: string;
type: StringConstructor;
} | {
name: string;
description: string;
type: BooleanConstructor;
alias?: undefined;
})[];
content?: undefined;
} | {
header: string;
optionList: {
name: string;
description: string;
alias: string;
type: BooleanConstructor;
}[];
content?: undefined;
} | {
header: string;
content: string[];
optionList?: undefined;
} | {
header: string;
content: {
example: string;
}[];
optionList?: undefined;
})[];
export default _default;

View File

@ -1,10 +0,0 @@
export default class ComponentLogger {
static CONTENT: string;
static setContent(content: any): void;
static log(m: any, color?: 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'whiteBright' | 'gray'): void;
static info(m: any): void;
static debug(m: any): void;
static error(m: any): void;
static warning(m: any): void;
static success(m: any): void;
}

View File

@ -1,4 +0,0 @@
export default class StdoutFormatter {
static stdoutFormatter: any;
static initStdout(): Promise<void>;
}

11
lib/index.d.ts vendored
View File

@ -1,11 +0,0 @@
import { InputProps } from './interface/entity';
export default class FcRemoteInvoke {
/**
* event
* @param inputs
* @returns
*/
invoke(inputs: InputProps): Promise<any>;
private report;
private handlerInputs;
}

File diff suppressed because one or more lines are too long

View File

@ -1,34 +0,0 @@
export interface ICredentials {
AccountID?: string;
AccessKeyID?: string;
AccessKeySecret?: string;
SecurityToken?: string;
}
export interface InputProps {
props?: IProperties;
credentials: ICredentials;
appName: string;
project: {
component: string;
access: string;
projectName: string;
};
command: string;
args: string;
path: {
configPath: string;
};
}
export interface IProperties {
region: string;
serviceName: string;
functionName: string;
qualifier?: string;
domainName?: string;
}
export declare function isProperties(args: any): args is IProperties;
export interface IEventPayload {
event?: string;
eventFile?: string;
eventStdin?: boolean;
}

5
lib/lib/client.d.ts vendored
View File

@ -1,5 +0,0 @@
import { ICredentials } from '../interface/entity';
export default class Client {
static buildFcClient(region: string, credentials: ICredentials): Promise<any>;
private static getFcEndpoint;
}

4
lib/lib/event.d.ts vendored
View File

@ -1,4 +0,0 @@
export default class File {
static getEvent(eventFile: any): Promise<unknown>;
static eventPriority(eventPriority: any): Promise<any>;
}

View File

@ -1,39 +0,0 @@
import { IProperties, IEventPayload } from '../interface/entity';
export default class RemoteInvoke {
fcClient: any;
accountId: string;
constructor(fcClient: any, accountId: string);
invoke(props: IProperties, eventPayload: IEventPayload, { invocationType }: {
invocationType: any;
}): Promise<void>;
requestDomain(url: string, event: string): Promise<void>;
getHttpTrigger(serviceName: any, functionName: any): Promise<any>;
eventInvoke({ serviceName, functionName, event, qualifier, invocationType }: {
serviceName: any;
functionName: any;
event: any;
qualifier?: string;
invocationType: any;
}): Promise<void>;
httpInvoke({ region, serviceName, functionName, event, qualifier }: {
region: any;
serviceName: any;
functionName: any;
event: any;
qualifier: any;
}): Promise<void>;
/**
* @param event: { body, headers, method, queries, path }
* path /proxy/serviceName/functionName/path ,
*/
request(event: any): Promise<void>;
handlerHttpParmase(event: any): {
headers: any;
queries: any;
method: any;
path: any;
body: any;
};
private showLog;
private getJsonEvent;
}

5
lib/lib/stdin.d.ts vendored
View File

@ -1,5 +0,0 @@
/// <reference types="node" />
export declare function getStdin(): Promise<string>;
export declare namespace getStdin {
var buffer: () => Promise<Buffer>;
}

View File

@ -1,6 +1,6 @@
{
"name": "fc-remote-invoke",
"version": "0.0.16",
"version": "0.0.22",
"description": "This is a component demo for Serverless Devs Tool ",
"keywords": [
"Serverless",
@ -13,7 +13,7 @@
"author": "Serverless-Devs",
"contributors": [],
"license": "MIT",
"main": "./lib/index.js",
"main": "./dist/index.js",
"publishConfig": {
"access": "public"
},
@ -24,15 +24,17 @@
"scripts": {
"start": "npm run watch",
"watch": "tsc -w",
"prebuild": "rm -rf node_modules && rm -rf package-lock.json && npm i && rimraf lib",
"build": "ncc build src/index.ts -m -o lib"
"prebuild": "rm -rf node_modules && rm -rf package-lock.json && npm i && rimraf dist",
"esbuild": "esbuild src/index.ts --bundle --log-level=error --minify --platform=node --format=cjs --target=node10.4 --external:@serverless-devs/core --outfile=dist/index.js",
"build": "npm run esbuild"
},
"dependencies": {
"@alicloud/fc2": "^2.2.2",
"@serverless-devs/core": "^0.0.*",
"@serverless-devs/core": "latest",
"form-data": "^4.0.0",
"fs-extra": "^10.0.0",
"got": "^11.8.2",
"lodash": "^4.17.21",
"qs": "^6.10.1",
"readline": "^1.3.0"
},
"autoInstall": false,
@ -45,6 +47,6 @@
"ts-node": "^8.10.2",
"typedoc": "^0.20.35",
"typescript": "^3.9.7",
"@vercel/ncc": "^0.24.0"
"esbuild": "^0.14.0"
}
}

View File

@ -2,7 +2,7 @@ Type: Component
Name: fc-remote-invoke
Provider:
- 其它
Version: 0.0.16
Version: 0.0.22
Description: 初始化component模板
HomePage: https://www.serverless-devs.com
Tags: #标签详情

View File

@ -75,9 +75,9 @@ export default [
content: [
'$ s invoke',
'$ s <ProjectName> invoke',
'$ s exec -- invoke --invocation-type sync --event <payload>',
'$ s exec -- invoke --event-file <file-path>',
'$ s exec -- invoke --event-stdin',
'$ s invoke --invocation-type sync --event <payload>',
'$ s invoke --event-file <file-path>',
'$ s invoke --event-stdin',
],
},
{

View File

@ -5,7 +5,6 @@ import HELP from './common/help';
import { InputProps, isProperties, IProperties } from './interface/entity';
// import StdoutFormatter from './common/stdout-formatter';
import RemoteInvoke from './lib/remote-invoke';
import Client from './lib/client';
export default class FcRemoteInvoke {
/**
@ -20,6 +19,7 @@ export default class FcRemoteInvoke {
credentials,
isHelp,
invocationType,
statefulAsyncInvocationId,
} = await this.handlerInputs(inputs);
await this.report('fc-remote-invoke', 'invoke', credentials?.AccountID);
@ -30,10 +30,11 @@ export default class FcRemoteInvoke {
let fcClient;
if (!props.domainName) {
fcClient = await Client.buildFcClient(props.region, credentials);
const fcCommon = await core.loadComponent('devsapp/fc-common');
fcClient = await fcCommon.makeFcClient({ ...inputs, props: { region: props.region }});
}
const remoteInvoke = new RemoteInvoke(fcClient, credentials.AccountID);
await remoteInvoke.invoke(props, eventPayload, { invocationType });
await remoteInvoke.invoke(props, eventPayload, { invocationType, statefulAsyncInvocationId });
}
private async report(componentName: string, command: string, accountID: string): Promise<void> {
@ -50,11 +51,12 @@ export default class FcRemoteInvoke {
const parsedArgs: {[key: string]: any} = core.commandParse({ ...inputs, args }, {
boolean: ['help', 'event-stdin'],
string: ['invocation-type', 'event', 'event-file', 'region', 'domain-name','service-name', 'function-name', 'qualifier'],
string: ['invocation-type', 'event', 'event-file', 'region', 'domain-name','service-name', 'function-name', 'qualifier', 'stateful-async-invocation-id'],
alias: {
'help': 'h',
'event': 'e',
'event-file': 'f',
'event-stdin': 's',
}
});
@ -73,6 +75,7 @@ export default class FcRemoteInvoke {
'event-stdin': eventStdin,
'invocation-type': invocationType = 'sync',
'domain-name': domainName,
'stateful-async-invocation-id': statefulAsyncInvocationId,
} = argsData;
const eventPayload = { event, eventFile, eventStdin };
// @ts-ignore: 判断三个值有几个真
@ -111,6 +114,7 @@ export default class FcRemoteInvoke {
eventPayload,
isHelp: false,
invocationType: _.upperFirst(invocationType),
statefulAsyncInvocationId,
};
}

View File

@ -1,24 +0,0 @@
import FC from '@alicloud/fc2';
import * as core from '@serverless-devs/core';
import { ICredentials } from '../interface/entity';
export default class Client {
static async buildFcClient(region: string, credentials: ICredentials) {
return new FC(credentials.AccountID, {
accessKeyID: credentials.AccessKeyID,
accessKeySecret: credentials.AccessKeySecret,
securityToken: credentials.SecurityToken,
region,
endpoint: await this.getFcEndpoint(),
timeout: 6000000,
})
}
private static async getFcEndpoint(): Promise<string | undefined> {
const fcDefault = await core.loadComponent('devsapp/fc-default');
const fcEndpoint: string = await fcDefault.get({ args: 'fc-endpoint' });
if (!fcEndpoint) { return undefined; }
const enableFcEndpoint: any = await fcDefault.get({ args: 'enable-fc-endpoint' });
return (enableFcEndpoint === true || enableFcEndpoint === 'true') ? fcEndpoint : undefined;
}
}

View File

@ -16,9 +16,10 @@ export default class File {
let input;
if (eventFile === '-') { // read from stdin
logger.log('Reading event data from stdin, which can be ended with Enter then Ctrl+D')
logger.log('Reading event data from stdin, which can be ended with Enter then Ctrl+D');
input = process.stdin;
} else {
logger.log('Reading event file content:');
input = fs.createReadStream(eventFile, {
encoding: 'utf-8'
})
@ -32,7 +33,10 @@ export default class File {
rl.on('line', (line) => {
event += line
})
rl.on('close', () => resolve(event))
rl.on('close', () => {
logger.log('');
resolve(event)
})
rl.on('SIGINT', () => reject(new Error('^C')))
})

34
src/lib/handler-body.ts Normal file
View File

@ -0,0 +1,34 @@
import _ from 'lodash';
import qs from 'qs';
import FormData from 'form-data';
export default function handlerBody(contentType: string, body: any) {
if (contentType.includes('text/') || contentType.includes('application/json') || contentType.includes('application/xml')) {
if (_.isString(body)) return body;
try {
return JSON.stringify(body);
} catch (_ex) {
return body.toString();
}
}
if (contentType.includes('application/x-www-form-urlencoded')) {
return qs.stringify(body, { indices: false });
}
if (contentType.includes('multipart/form-data')) {
const form = new FormData();
try {
const newBody = _.isObject(body) ? body : JSON.parse(body);
for (const [key, value] of Object.entries(newBody)) {
form.append(key, value);
}
return form;
} catch (_ex) {
throw new Error(`Handler body error: The request header is ${contentType}, but the request body is not an object`);
}
}
return body;
}

View File

@ -13,7 +13,7 @@ export default class RemoteInvoke {
this.accountId = accountId;
}
async invoke (props: IProperties, eventPayload: IEventPayload, { invocationType }) {
async invoke (props: IProperties, eventPayload: IEventPayload, { invocationType, statefulAsyncInvocationId }) {
const event = await Event.eventPriority(eventPayload);
logger.debug(`event: ${event}`);
@ -32,12 +32,13 @@ export default class RemoteInvoke {
const payload: any = { event, serviceName, functionName, qualifier };
if (_.isEmpty(httpTriggers)) {
payload.invocationType = invocationType;
payload.statefulAsyncInvocationId = statefulAsyncInvocationId;
payload.event = event;
await this.eventInvoke(payload);
} else {
payload.region = region;
payload.event = this.getJsonEvent(event);
await this.httpInvoke(payload);
}
}
@ -48,9 +49,9 @@ export default class RemoteInvoke {
payload.headers = {};
}
payload.headers['X-Fc-Log-Type'] = 'Tail';
const { body, headers } = await got(url, payload);
this.showLog(headers['x-fc-log-result']);
logger.log('\nFC Invoke Result:', 'green');
console.log(body);
@ -74,13 +75,15 @@ export default class RemoteInvoke {
functionName,
event,
qualifier = 'LATEST',
invocationType
invocationType,
statefulAsyncInvocationId
}) {
if (invocationType === 'Sync') {
const rs = await this.fcClient.invokeFunction(serviceName, functionName, event, {
'X-Fc-Log-Type': 'Tail',
'X-Fc-Invocation-Type': invocationType
'X-Fc-Invocation-Code-Version': 'Latest',
'X-Fc-Invocation-Type': invocationType,
}, qualifier);
this.showLog(rs.headers['x-fc-log-result']);
@ -88,8 +91,11 @@ export default class RemoteInvoke {
console.log(rs.data);
console.log('\n');
} else {
logger.debug(`Stateful async invocation id: ${statefulAsyncInvocationId}`);
const { headers } = await this.fcClient.invokeFunction(serviceName, functionName, event, {
'X-Fc-Invocation-Type': invocationType
'X-Fc-Invocation-Code-Version': 'Latest',
'X-Fc-Invocation-Type': invocationType,
'X-Fc-Stateful-Async-Invocation-Id': statefulAsyncInvocationId || "",
}, qualifier);
const rId = headers['x-fc-request-id'];
@ -101,7 +107,7 @@ export default class RemoteInvoke {
const q = qualifier ? `.${qualifier}` : '';
event.path = `/proxy/${serviceName}${q}/${functionName}/${event.path || ''}`;
logger.log(`https://${this.accountId}.${region}.fc.aliyuncs.com/2016-08-15/proxy/${serviceName}${q}/${functionName}/`);
logger.log(`Request url: https://${this.accountId}.${region}.fc.aliyuncs.com/2016-08-15/proxy/${serviceName}${q}/${functionName}/`);
await this.request(event)
}
@ -109,8 +115,14 @@ export default class RemoteInvoke {
* @param event: { body, headers, method, queries, path }
* path /proxy/serviceName/functionName/path ,
*/
async request (event) {
const { headers, queries, method, path: p, body } = this.handlerHttpParmase(event);
async request(event) {
const { headers = {}, queries, method = 'GET', path: p, body } = event;
if (!headers['X-Fc-Log-Type']) {
headers['X-Fc-Log-Type'] = 'Tail';
}
if (!headers['X-Fc-Invocation-Code-Version']) {
headers['X-Fc-Invocation-Code-Version'] = 'Latest';
}
let resp;
try {
@ -118,18 +130,17 @@ export default class RemoteInvoke {
logger.debug(`method is ${mt}.`);
logger.debug(`start invoke.`);
if (mt === 'GET') {
resp = await this.fcClient.get(p, queries, headers);
resp = await this.fcClient.costom_request('GET', p, queries, null, headers);
} else if (mt === 'POST') {
resp = await this.fcClient.post(p, body, headers, queries);
resp = await this.fcClient.costom_request('POST', p, queries, body, headers);
} else if (mt === 'PUT') {
resp = await this.fcClient.put(p, body, headers);
resp = await this.fcClient.costom_request('PUT', p, null, body, headers);
} else if (mt === 'DELETE') {
resp = await this.fcClient.request('DELETE', p, queries, null, headers);
/* else if (method.toLocaleUpperCase() === 'PATCH') {
resp = await this.fcClient.request('PATCH', p, queries, body, headers);
resp = await this.fcClient.costom_request('DELETE', p, queries, null, headers);
} else if (method.toLocaleUpperCase() === 'PATCH') {
resp = await this.fcClient.costom_request('PATCH', p, queries, body, headers);
} else if (method.toLocaleUpperCase() === 'HEAD') {
resp = await this.fcClient.request('HEAD', p, queries, body, headers);
} */
resp = await this.fcClient.costom_request('HEAD', p, queries, body, headers);
} else {
logger.error(`Does not support ${method} requests temporarily.`);
}
@ -142,47 +153,19 @@ export default class RemoteInvoke {
}
logger.debug(`end invoke.`);
if (resp) {
if (resp?.err) {
this.showLog(resp.headers['x-fc-log-result']);
logger.log('\nFC Invoke Result:', 'green');
logger.log(`\nFC Invoke Result[Code: ${resp.code}]:`, 'red');
console.log(resp.data);
console.log('\n');
}
}
} else {
if (resp) {
this.showLog(resp.headers['x-fc-log-result']);
handlerHttpParmase (event) {
const { body = '', headers = {}, method = 'GET', queries = '', path: p = '' } = event;
let postBody;
if (body) {
let buff = null;
if (Buffer.isBuffer(body)) {
buff = body;
headers['content-type'] = 'application/octet-stream';
} else if (typeof body === 'string') {
buff = Buffer.from(body, 'utf8');
headers['content-type'] = 'application/octet-stream';
} else if (typeof body.pipe === 'function') {
buff = body;
headers['content-type'] = 'application/octet-stream';
} else {
buff = Buffer.from(JSON.stringify(body), 'utf8');
headers['content-type'] = 'application/json';
logger.log(`\nFC Invoke Result[Code: ${resp.code}]:`, 'green');
console.log(resp.data);
console.log('\n');
}
postBody = buff;
}
if (!headers['X-Fc-Log-Type']) {
headers['X-Fc-Log-Type'] = 'Tail';
}
return {
headers,
queries,
method,
path: p,
body: postBody
}
}
@ -203,4 +186,4 @@ export default class RemoteInvoke {
throw new Error('handler event error. Example: https://github.com/devsapp/fc-remote-invoke/blob/master/example/http.json');
}
}
}
}

View File

@ -24,7 +24,7 @@
"./node_modules/@types"
],
"rootDir": "src",
"outDir": "lib"
"outDir": "dist"
},
"exclude": [
"**/node_modules/**",