Aller au contenu principal
Version: 3.0.0

Aliyun FC

Alibaba Cloud Serverless is one of the first teams in China to provide Serverless computing services. Relying on Alibaba Cloud's powerful cloud infrastructure service capabilities, Alibaba Cloud continues to achieve technological breakthroughs. At present, Taobao, Alipay, DingTalk, Gaud and other enterprises have applied Serverless to the production business. Serverless products on the cloud have successfully landed in tens of thousands of enterprises such as pumpkin movies, Netease Cloud Music, iQiyi sports and Lilith.

Alibaba Cloud Serverless includes many products, such as Function Compute FC and Lightweight Application Engine SAE. This article mainly uses its Function Compute part.

The following are common methods for using and testing function triggers.

Trigger code

Publish functions that do not contain triggers. This is the simplest type. You can manually trigger parameters directly through event or bind other triggers on the platform.

Bind the event trigger by @ServerlessTrigger the decorator directly in the code.

import { Provide, Inject, ServerlessTrigger, ServerlessTriggerType } from '@midwayjs/decorator';
import { Context, FC } from '@midwayjs/faas';

export class HelloAliyunService {
ctx: Context;

async handleEvent(event: any) {
return event;

Local development

HTTP triggers and API Gateway types can be developed locally by using local npm run dev and similar development methods to traditional applications. Other types of triggers cannot be developed locally by using dev. They can only be tested and executed by running npm run test.

Local test

Create a function app by createFunctionApp, obtain a class instance by getServerlessInstance, and then directly call the method of the instance to pass in parameters for testing.

describe('test/hello_aliyun.test.ts', () => {
let app: Application;
let instance: HelloAliyunService;

beforeAll(async () => {
// create app
app = await createFunctionApp<Framework>(join(__dirname, '../'), {
initContext: createInitializeContext()
instance = await app.getServerlessInstance<HelloAliyunService>(HelloAliyunService);

afterAll(async () => {
await close(app);

it('should get result from event trigger', async () => {
expect(await instance.handleEvent('hello world')).toEqual('hello world');

publish to alibaba cloud

Ensure aliyun at the provider paragraph of f.yml in the project root directory.

name: midway-faas-examples

name: aliyun

Deploy the function. You can directly use the release command to package and deploy the function. The Deploy command is automatically packaged and released by calling the official deployment tool of Alibaba Cloud.

$ npm run deploy

If you enter the wrong information, you can re-execute the npx midway-bin deploy -- resetConfig modification.

For the first time, Alibaba Cloud deployment needs to configure accountId, accountKey, and accountSecret.

For related configuration, please refer to the picture below:

Click Security Settings.

Click the AccessKey page of Alibaba Cloud.

Here is an example of an http trigger.

After the release, Alibaba Cloud will output a temporarily available domain name and open the browser to access it.

After the release is completed, the platform status is as follows.

release effect, each configured function will be published as a function on the platform, and the http trigger will be automatically configured.

Frequently Asked Questions

1. Custom domain name

You need to apply for a domain name in advance. If you are in China, you need to file it, otherwise you cannot bind it.

The first step is to turn off the function of the default automatically generated domain name

name: midway-faas-examples

name: aliyun

customDomain: false

The second step is to add domain name resolution to the gateway corresponding to your function.

Bind a custom domain name on the function page and add a route

After the binding is completed, you can use the domain name to access.

2. Some restrictions on http headers

Request Headers does not support customization starting with x-fc-and customization of the following fields:

  • accept-encoding
  • connection
  • keep-alive
  • proxy-authorization
  • te
  • trailer
  • transfer-encoding

Response Headers does not support customization starting with x-fc- and customization of the following fields:

  • connection
  • content-length
  • content-encoding
  • date
  • keep-alive
  • proxy-authenticate
  • server
  • trailer
  • transfer-encoding
  • upgrade

Request restrictions. If the following limit is exceeded, the 400 status code and InvalidArgument error code will be returned.

  • Headers Size: The total size of all Key and Value in the Headers must not exceed 4KB.
  • Path size: Including all Query Params, the total size of Path must not exceed 4KB.
  • Body size: The total size of HTTP Body must not exceed 6MB.

Response restrictions. If the following limit is exceeded, the 502 status code and BadResponse error code will be returned.

  • Headers Size: The total size of all Key and Value in the Headers must not exceed 4KB.

3. The size of the release package

In order to improve the startup speed, the Alibaba Cloud FC container limits the size of the compressed package to 50M. Please simplify your back-end code dependencies as much as possible.

Generally speaking, the default scaffold (eggjs) of midway is built at about 9M, and other frameworks will be smaller. Please try to delete the package-lock.json before trying.

4. Container time zone problem

Most Docker images are based on Alpine,Ubuntu,Debian,CentOS and other basic images. Basically, UTC time is used, and the default time zone is zero time zone.

The default time zone of Alibaba Cloud container environment is GMT +0000. When you use the new Date() and other frontend users to obtain the time zone, the time zone may not be processed by domestic users, and the difference will be 8 hours.

Domestic users may be accustomed to GMT +0800 by default. Can be adjusted by environment variables (configured on platform or f.yml).

process.env.TZ = 'Asia/Shanghai';
name: aliyun
runtime: nodejs12
TZ: 'Asia/Shanghai'

Note that the scheduled task is triggered by the gateway and will not be affected by the function time zone configured here.

5. Revised AccessKey

Sometimes, we fill in a wrong AccessKey or other regional options on the first release. We provide a modifiable parameter to clean up the last error on the release.

midway-bin deploy --resetConfig

Enter default when prompted Please create alias for key pair. If not, please enter to skip, otherwise the current AccessKey will not be used. If you only want to adjust specific fields, you can enter the ~/.s/access.yaml file, modify and save directly.

6. CLI Releases Red Tips

After the HTTP trigger is published, the following red prompt will appear. This is a prompt because if the domain name is not configured, Alibaba Cloud will add the Content-Disposition: attachment the header to the response by default, and the browser opening address will change to attachment download. You can test the results by binding a custom domain name or a local curl.

7. Specify accessKey at the time of release, etc.

export REGION=cn-beijing
export ACCOUNT_ID=xxx
export ACCESS_KEY_ID=xxx

currently, alibaba cloud releases using funcraft tools. you can use the funcraft environment variables, load the startup command line, or use the yml variable filling method.

8. Release Timeout

Sometimes the package is relatively large, and the upload of midway-bin deploy may encounter the problem of timeout, which is controlled internally by the funcraft tool.

Solution: Configure timeout in ~/.fcli/config.yaml in s (seconds).

Generally speaking, the default scaffold (eggjs) of midway is built at about 9M, and other frameworks will be smaller. Please try to delete the package-lock.json before trying.

If there is no effect, if the package is too large, you can modify the deployment time of the fun tool in ~/.fcli/config.yaml, and add the timeout field to it.

Examples are as follows:

endpoint: ***************
api_version: '2016-08-15'
access_key_id: ***************
access_key_secret: * * * * * * * * * * * * * * *
security_token: ''
debug: false
timeout: 50 ## deployment timeout, unit is s
retries: 3