developer guide · api gateway is an api hosting service that helps enterprises to build, manage,...

87
FunctionGraph Developer Guide Issue 04 Date 2018-08-29 HUAWEI TECHNOLOGIES CO., LTD.

Upload: others

Post on 30-May-2020

26 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

FunctionGraph

Developer Guide

Issue 04

Date 2018-08-29

HUAWEI TECHNOLOGIES CO., LTD.

Page 2: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Copyright © Huawei Technologies Co., Ltd. 2018. All rights reserved.No part of this document may be reproduced or transmitted in any form or by any means without prior writtenconsent of Huawei Technologies Co., Ltd. Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.All other trademarks and trade names mentioned in this document are the property of their respectiveholders. NoticeThe purchased products, services and features are stipulated by the contract made between Huawei and thecustomer. All or part of the products, services and features described in this document may not be within thepurchase scope or the usage scope. Unless otherwise specified in the contract, all statements, information,and recommendations in this document are provided "AS IS" without warranties, guarantees orrepresentations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in thepreparation of this document to ensure accuracy of the contents, but all statements, information, andrecommendations in this document do not constitute a warranty of any kind, express or implied.

Huawei Technologies Co., Ltd.Address: Huawei Industrial Base

Bantian, LonggangShenzhen 518129People's Republic of China

Website: http://e.huawei.com

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. i

Page 3: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Contents

1 Overview......................................................................................................................................... 11.1 Introduction to Function Development...........................................................................................................................11.2 Supported Event Sources................................................................................................................................................41.3 Basic Concepts............................................................................................................................................................... 81.4 Function Project Packaging Rules................................................................................................................................ 11

2 Developing Functions.................................................................................................................152.1 Developing Functions in Node.js................................................................................................................................. 152.2 Developing Functions in Python.................................................................................................................................. 212.3 Developing Functions in Java.......................................................................................................................................262.4 Developing Functions in Go.........................................................................................................................................41

3 Creating Workflows....................................................................................................................483.1 Introduction.................................................................................................................................................................. 483.2 Creating a Workflow to Invoke a Function.................................................................................................................. 483.3 Creating a Workflow to Handle Error Conditions........................................................................................................503.4 Creating a Workflow with Multiple State Choices.......................................................................................................51

4 Workflow Definition.................................................................................................................. 554.1 Workflow Structure...................................................................................................................................................... 554.2 Event Definition........................................................................................................................................................... 564.3 State Types and Field Description................................................................................................................................ 574.4 Input and Output...........................................................................................................................................................644.5 State Definition Examples............................................................................................................................................ 754.6 Definition Restrictions..................................................................................................................................................78

FunctionGraphDeveloper Guide Contents

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. ii

Page 4: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

1 Overview

FunctionGraph is a serverless service that coordinates the components of distributedapplications and microservices by using visual workflows. You can build applications fromcomponents that each executes a discrete function, or moves to a next step based on the inputparameter, or waits for a period before proceeding to the next step. FunctionGraph provides asimple workflow language and visual console, which help you quickly build and modifyworkflows to implement your service process.

You just define a service workflow and submit the workflow definitions to FunctionGraph.You do not need to care about running environment configurations, scalability, and reliabilityof the workflow, because all of them will be ensured by FunctionGraph.

FunctionGraph scales workflow instances in seconds based on the number of requests. Theinstances end immediately after the requests are processed. Therefore, you do not need toreserve resources, and pay only for the workflow instances you consume. FunctionGraphensures that instances are always available as the number of requests increases. It tracks therunning status of each step and provides exception handling mechanisms such as retry andpath selection in the event of errors. It also records the workflow execution logs, which youcan query to trace the execution process.

1.1 Introduction to Function Development

Supported RuntimesFunctionGraph supports Python, Node.js, Java, and Go, as shown in Table 1-1.

Table 1-1 Runtime description

Runtime SupportedVersion

SDK DownloadLink

RuntimeDownload Link

Node.js 6.10 and 8.10 - -

FunctionGraphDeveloper Guide 1 Overview

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 1

Page 5: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Runtime SupportedVersion

SDK DownloadLink

RuntimeDownload Link

Python 2.7 and 3.6 - Python 2.7Python 3.6NOTE

The Python SDKshave integrated withcommon third-partySDKs listed in Table1-3.

Java 8.0 Java SDKNOTE

The Java SDK hasintegrated with theOBS SDK.

-

Go 1.8 Go SDK -

Third-Party Components Integrated with the Node.js SDK

Table 1-2 Third-party components integrated with the Node.js SDK

Name Usage Version

q Asynchronous methodencapsulation

1.5.1

co Asynchronous processcontrol

4.6.0

lodash Common tool and methodlibrary

4.17.10

esdk-obs-nodejs OBS sdk 2.1.5

Non-Standard Libraries Integrated with the Python SDKs

Table 1-3 Non-standard libraries integrated with the Python SDKs

Library Usage Version

dateutil Date and time processing 2.6.0

requests HTTP library 2.7.0

httplib2 HTTP client 0.10.3

numpy Mathematical computation 1.13.1

FunctionGraphDeveloper Guide 1 Overview

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 2

Page 6: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Library Usage Version

redis Redis client 2.10.5

obsclient OBS client -

Download Links of the Sample Deployment Packages

Table 1-4 lists the links for downloading the sample deployment packages used in thisdocument. You can download the deployment packages to a local path and upload them whencreating functions.

Table 1-4 Download links of the sample deployment packages

Function Deployment Package

Node.js function fss_examples_nodejs6.10.zip

Python function fss_examples_python2.7.zip

Java function fss_example_java8.jar

Go function fss_examples_go1.8.zip

Download Links of CLI

FunctionGraph provides the command line interface (CLI) for you to manage functions,triggers, and aliases, and invoke functions. CLI can run on a 64-bit Linux operating system(OS) or 64-bit Windows OS. Table 1-5 provides the download links and MD5 verificationcodes of CLI for the two OSs.

Table 1-5 Download links of CLI

OS Download Link MD5 Verification Code

Linux CLI for Linux a634e80617897ac7e07d8737d21081be

Windows CLI for Windows 2615ee8aa4f794bf08e56b75b54a4b6f

Mac CLI for macOS 84b4a51d58b707887440c683c715993f

HSS

Huawei Serverless Sandbox (HSS) is used to test your functions locally, verify HuaweiServerless Application Model (HSAM) templates, and generate valid sample payloads fordifferent event sources. Table 1-6 provides the download link and MD5 verification code ofHSS.

FunctionGraphDeveloper Guide 1 Overview

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 3

Page 7: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Table 1-6 Download link of HSS

OS Download Link MD5 Verification Code

Linux HSS for Linux 67ddeb07a299a03828a165562be46465

Mac HSS for macOS 3b11c385051088a3861025194955cd5f

1.2 Supported Event SourcesThis section describes the Huawei cloud services that you can configure as event sources foryour FunctionGraph function. After you preconfigure the event source mapping, these eventsources automatically invoke the function when detecting events.

SMN

Simple Message Notification (SMN) sends messages to email addresses, phone numbers, orHTTP/HTTPS URLs. After you create a function with an SMN trigger, messages published toa specified topic are passed as a parameter (SMN example event) to invoke the function.Then, the function processes the event, for example, publishing the message to other SMNtopics or sending it to other Huawei cloud services. For details, see Using an SMN Trigger.

DMS

Distributed Message Service (DMS) is a message queuing service that enablescommunication between distributed applications. After you create a function with a DMStrigger, messages automatically polled from a specified queue are passed as a parameter(DMS example event) to invoke the function. For details, see Using a DMS Trigger.

API Gateway

API Gateway is an API hosting service that helps enterprises to build, manage, and deployAPIs at any scale. With API Gateway, your function can be invoked through HTTPS by usinga custom REST API with a specified backend. You can map each API operation (such as,GET and PUT) to a specific function. API Gateway invokes the relevant function when anHTTPS request (API Gateway example event) is sent to the API backend. For details, seeUsing an APIG Trigger.

OBS

Object Storage Service (OBS) is a stable, secure, efficient, and easy-to-use cloud storageservice. You can create a function to process OBS bucket events, for example, object creationor deletion events. When an image is uploaded to the specified bucket, OBS invokes thefunction to read the image and create a thumbnail. For details, see Using an OBS Trigger.

DIS

Data Ingestion Service (DIS) ingests large amounts of data in real time. You can create afunction to automatically poll a DIS stream and process all new data records, such as, website

FunctionGraphDeveloper Guide 1 Overview

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 4

Page 8: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

click streams, financial transactions, social media streams, IT logs, and location-trackingevents (DIS example event). For details, see Using a DIS Stream.

TimerYou can schedule a timer (timer example event) to invoke your code based on a fixed rate ofminutes, hours, or days or a cron expression. For details, see Using a Timer Trigger.

LTSLog Tank Service (LTS) collects and stores logs, allowing you to query them in real time.After you create a function with an LTS trigger, subscribed logs collected by LTS are passedas a parameter (LTS example event) to invoke the function. Then, the function processes oranalyzes the logs, or loads the logs to other systems. For details, see Using an LTS Trigger.

CTSCloud Trace Service (CTS) collects operation records of subscribed cloud resources. Afteryou create a function with a CTS trigger, collected operation records of specified cloudservices are passed as a parameter (CTS example event) to invoke the function. Then, thefunction analyzes and processes key information in the operation records, automaticallyrecovers business modules such as the system or network, or reports alarms to servicepersonnel by SMS message or email. For details, see Using a CTS Trigger.

Example Eventsl SMN example event

In the following example, the function name is test and the topic name isserverless_Test. subject is the message header, and message is the message body.{ "record": [{ "event_version": "1.0", "smn": { "message_attributes": null, "subject": "This is the message title of smn trigger", "message_id": "a5dbd701d70d4ac2a153e7dd6dd9b601", "topic_urn": "urn:smn:cn-north-1:bb8695913bb74682b9ca82a8803b60d8:serverless_Test", "type": "notification", "message": "This is the message body of smn trigger", "timestamp": "2017-11-15T04:02:24Z" }, "event_source": "smn", "event_subscription_urn": "urn:fss:cn-north-1:bb8695913bb74682b9ca82a8803b60d8:function:default:obsTrigger-Test1:latest" }], "functionname": "test", "requestId": "7c307f6a-cf68-4e65-8be0-4c77405a1b2c", "timestamp": "Wed Nov 15 2017 12:00:00 GMT+0800 (CST)"}

l DMS example eventIn the following example, the function name is test. Messages is the message body,which includes Body and Attributes. The event also includes a queue ID and consumergroup ID.

FunctionGraphDeveloper Guide 1 Overview

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 5

Page 9: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

{ "Tag": "latest", "QueueID": "48d11a53-e498-4964-84a2-aaa56442d5ca", "ConsumerGroupID": "g-61d9d290-7dae-4144-9ce7-00b9f159cdbe", "Messages": [{ "Body": "This is dms trigger body", "Attributes": { "dmstrigger": "dmstrigger", "dmstrigger2": "dmstrigger" } }], "functionname": "test", "requestId": "57453335-ccf7-4d43-8639-79d108158749", "timestamp": "Wed Nov 15 2017 14:26:10 GMT+0800 (CST)"}

l API Gateway example eventThe following is an API Gateway example event.{ "httpMethod": "GET", //Request method "path": "/test/hello", //Request path "pathParameters": { //Path parameters "proxy": "hello" }, "queryStringParameters": { //Query parameters "name": "me" }, "headers": { //Request headers "x-stage": "RELEASE", "Host": "3f96e175-d5e4-4d4b-ae7e-f6d264e63b23-apigw.cn-north-1.huaweicloud.com", "User-Agent": "lua-resty-http/0.10 (Lua) ngx_lua/10008", ... }, "body": "...", //Request body "isBase64Encoded":false/true, //Indicates whether the request body is encoded using Base64. "requestContext": { "stage": "test", //Environment alias "requestId": "dd4337362c02c7d77299e78781beb4b1", "apiId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9" },}The function returns characters strings by using the following structure.{ "isBase64Encoded": true|false, "statusCode": httpStatusCode, "headers": {"headerName":"headerValue",...}, "body": "..."}

l DIS example eventIn the following example, the stream name is dis-swtest. This example shows the formatof a request received by a function that can be invoked by the DIS trigger.{ "ShardID": "shardId-0000000000", "Message": { "next_partition_cursor": "eyJnZXRJdGVyYXRvclBhcmFtIjp7InN0cmVhbS1uYW1lIjoiZGlzLXN3dGVzdCIsInBhcnRpdGlvbi1pZCI6InNoYXJkSWQtMDAwMDAwMDAwMCIsImN1cnNvci10eXBlIjoiVFJJT

FunctionGraphDeveloper Guide 1 Overview

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 6

Page 10: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

V9IT1JJWk9OIiwic3RhcnRpbmctc2VxdWVuY2UtbnVtYmVyIjoiNCJ9LCJnZW5lcmF0ZVRpbWVzdGFtcCI6MTUwOTYwNjM5MjE5MX0", "records": [{ "partition_key": "shardId_0000000000", "data": "PEJ1ZmZlcj48L0J1ZmZlcj4=", "sequence_number": "0" }, { "partition_key": "shardId_0000000000", "data": "PEJ1ZmZlcj48L0J1ZmZlcj4=", "sequence_number": "1" }, { "partition_key": "shardId_0000000000", "data": "PEJ1ZmZlcj48L0J1ZmZlcj4=", "sequence_number": "2" }, { "partition_key": "shardId_0000000000", "data": "PEJ1ZmZlcj48L0J1ZmZlcj4=", "sequence_number": "3" }], "millis_behind_latest": "" }, "Tag": "latest", "StreamName": "dis-swtest"}

l Timer example event{ "version": "v1.0", "time": "2006-01-02T15:04:05-07:00", // Local date and time "trigger_type": "TIMER", // Trigger type "trigger_name": "Trigger name", "user_event": "User-defined event" //Event configured when you create the timer trigger}

l LTS example event{ "lts": { "data": "eyJsb2dzIjpbIntcIm1lc3NhZ2VcIjpcIjIwMTgtMDYtMjYvMTg6NDA6NTMgW0lORl0gW2NvbmZpZy5nbzo3Ml0gU3VjY2Vzc2Z1bGx5IGxvYWRlZCBnZW5lcmFsIGNvbmZpZ3VyYXRpb24gZmlsZVxcclxcblwiLFwidGltZVwiOjE1MzAwMDk2NTMwNTksXCJob3N0X25hbWVcIjpcImVjcy10ZXN0YWdlbnQubm92YWxvY2FsXCIsXCJpcFwiOlwiMTkyLjE2OC4xLjk4XCIsXCJwYXRoXCI6XCIvdXNyL2xvY2FsL3RlbGVzY29wZS9sb2cvY29tbW9uLmxvZ1wiLFwibG9nX3VpZFwiOlwiNjYzZDY5MzAtNzkyZC0xMWU4LThiMDgtMjg2ZWQ0ODhjZTcwXCIsXCJsaW5lX25vXCI6NjE1fSIsIntcIm1lc3NhZ2VcIjpcIjIwMTgtMDYtMjYvMTg6NDA6NTMgW1dSTl0gW2NvbmZpZy5nbzo4Ml0gVGhlIHByb2plY3RJZCBvciBpbnN0YW5jZUlkIG9mIGNvbmZpZy5qc29uIGlzIG5vdCBjb25zaXN0ZW50IHdpdGggbWV0YWRhdGEsIHVzZSBtZXRhZGF0YS5cXG5cIixcInRpbWVcIjoxNTMwMDA5NjUzMDU5LFwiaG9zdF9uYW1lXCI6XCJlY3MtdGVzdGFnZW50Lm5vdmFsb2NhbFwiLFwiaXBcIjpcIjE5Mi4xNjguMS45OFwiLFwicGF0aFwiOlwiL3Vzci9sb2NhbC90ZWxlc2NvcGUvbG9nL2NvbW1vbi5sb2dcIixcImxvZ191aWRcIjpcIjY2M2Q2OTMwLTc5MmQtMTFlOC04YjA5LTI4NmVkNDg4Y2U3MFwiLFwibGluZV9ub1wiOjYxNn0iLCJ7XCJtZXNzYWdlXCI6XCIgSW4gY29uZi5qc29uLCBwcm9qZWN0SWQgaXMgW10sIGluc3RhbmNlSWQgaXMgW10uIE1ldGFEYXRhIGlzIHs0NTQzMjkzYS01YjJjLTQ0YzQtYjdhMC1kZTIxOGY3ZjJmYTYgNjI4MGUxNzBiZDkzNGY2MGE0ZDg1MWNmNWNhMDUxMjkgIH1cXHJcXG5cIixcInRpbWVcIjoxNTMwMDA5NjUzMDU5LFwiaG9zdF9uYW1lXCI6XCJlY3MtdGVzdGFnZW50Lm5vdmFsb2NhbFwiLFwiaXBcIjpcIjE5Mi4xNjguMS45OFwiLFwicGF0aFwiOlwiL3Vzci9sb2NhbC90ZWxlc2NvcGUvbG9nL2NvbW1vbi5sb2dcIixcImxvZ191aWRcIjpcIjY2M2Q2OTMwLTc5MmQtMTFlOC04YjBhLTI4NmVkNDg4Y2U3MFwiLFwibGluZV9ub1wiOjYxN30iXSwib3duZXIiOiI2MjgwZTE3MGJkOTM0ZjYw

FunctionGraphDeveloper Guide 1 Overview

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 7

Page 11: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

YTRkODUxY2Y1Y2EwNTEyOSIsImxvZ19ncm91cF9pZCI6Ijk3YTlkMjg0LTQ0NDgtMTFlOC04ZmE0LTI4NmVkNDg4Y2U3MCIsImxvZ190b3BpY19pZCI6IjFhOTY3NWE3LTc4NGQtMTFlOC05ZjcwLTI4NmVkNDg4Y2U3MCJ9" }}

l CTS example event{ "cts": { "time": "2018/06/26 08:54:07 GMT+08:00", //Timestamp of the sender "user": { //Information of the user that initiates the request "name": "userName", "id": "5b726c4fbfd84821ba866bafaaf56aax", "domain": { "name": "domainName", "id": "b2b3853af40448fcb9e40dxj89505ba" } }, "request": {}, //Content of the trace request "response": {}, //Content of the trace response "code": 204, //Trace response codes, such as, 200,400 "service_type": "FunctionGraph", //Name of the sender in abbreviated form, such as, VPC and ECS "resource_type": "graph", //Resource type of the sender, such as VM and VPN "resource_name": "workflow-2be1", //Resource name, for example, name of a VM on ECS "resource_id": "urn:fgs:cn-north-1:2d1d891d93054bbaa69b9e866c0971ac:graph:workflow-2be1", //Resource ID, for example, ID of a VM on ECS "trace_name": "deleteGraph", //Trace name, such as startServer and shutDown "trace_type": "ConsoleAction", //Type of the trace source, such as ApiCall "record_time": "2018/06/26 08:54:07 GMT+08:00", //Time when CTS receives the trace "trace_id": "69be64a7-0233-11e8-82e4-e5d37911193e", //Trace ID "trace_status": "normal" }}

1.3 Basic Concepts

WorkflowA workflow defines the logical steps and their sequence to achieve a goal. FunctionGraphenables you to orchestrate a series of components in sequential, parallel, or branching mode,as shown in Figure 1-1.

FunctionGraphDeveloper Guide 1 Overview

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 8

Page 12: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 1-1 Different workflow types

In the three workflow types, each box represents a step. Each step can perform a simpleoperation such as filtering parameters or invoking a function. For details about the step types,see State Types and Field Description.

InstanceAn instance is generated while a workflow is executed. A workflow is a static service processdefined in JSON format. For details about JSON-based workflow definition, see WorkflowDefinition. A workflow can be started repeatedly to generate multiple instances.

Workflow TriggerA workflow trigger is a set of rules defined to trigger a workflow. Once the rules are satisfied,the workflow runs immediately to generate instances. Currently, a workflow can be triggeredby two cloud service triggers: OBS and SMN triggers.

When an event that satisfies the rules occurs, an event message is sent to FunctionGraph tostart a new workflow instance or to drive an existing instance to run continuously.

The following is a process of triggering a workflow by a PUT event on OBS. The process isillustrated in Figure 1-2.

1. A user uploads a file to a specified bucket, which then generates a PUT event.2. The PUT event is captured by OBS and then sent to FunctionGraph through a message.3. FunctionGraph starts the relevant workflow instance based on the event message.

FunctionGraphDeveloper Guide 1 Overview

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 9

Page 13: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 1-2 Process of triggering a workflow by OBS

Function

A function can be invoked by a workflow to execute a specified task. In an EVENT orOPERATION state, you can specify the URNs of existing functions that will be invoked andthe function invocation mode. For details, see Input and Output and State DefinitionExamples.

Timer

A timer is defined to start the instances of a workflow based on the scheduled time.

A timer is a fixed rate or cron expression, which you can choose to execute a workflow basedon service requirements.

l Fixed rate: Triggers a workflow based on a fixed rate of minutes, hours, or days.

l Cron expression: Triggers a workflow based on a more complex rule. For example,executes the workflow on the last day every week or on March 5, 20XX. For detailsabout cron expressions, see Cron Expression for a Workflow Timer.

Develop a workflow execution plan in the following procedure:

1. Create a workflow.

2. Create a timer with the required schedule for the workflow.

3. Enable the timer. FunctionGraph executes the workflow based on the schedule.

FunctionGraphDeveloper Guide 1 Overview

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 10

Page 14: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

1.4 Function Project Packaging Rules

Packaging RulesIn addition to inline code editing, you can create a function by directly uploading a ZIP file orJAR file, or uploading a ZIP file from OBS. Table 1-7 lists the rules for packaging a functionproject.

Table 1-7 Function project packaging rules

Runtime JAR File ZIP File ZIP File on OBS

Node.js Not supported. l If the functionproject files aresaved under the ~/Code/ directory,select and packageall files under thisdirectory to ensurethat the functionhandler is under theroot directory afterthe ZIP file isdecompressed.

l If the functionproject uses third-party dependencies,package them into aZIP file, and importthe file on thefunction code page.Alternatively,package the third-party dependenciesand the functionproject files together.

Compress theproject files into aZIP file andupload it to anOBS bucket.

FunctionGraphDeveloper Guide 1 Overview

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 11

Page 15: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Runtime JAR File ZIP File ZIP File on OBS

Python 2.7 Not supported. l If the functionproject files aresaved under the ~/Code/ directory,select and packageall files under thisdirectory to ensurethat the functionhandler is under theroot directory afterthe ZIP file isdecompressed.

l If the functionproject uses third-party dependencies,package them into aZIP file, and importthe file on thefunction code page.Alternatively,package the third-party dependenciesand the functionproject files together.

Compress theproject files into aZIP file andupload it to anOBS bucket.

Python 3.3 Not supported. l If the functionproject files aresaved under the ~/Code/ directory,select and packageall files under thisdirectory to ensurethat the functionhandler is under theroot directory afterthe ZIP file isdecompressed.

l If the functionproject uses third-party dependencies,package them into aZIP file, and importthe file on thefunction code page.Alternatively,package the third-party dependenciesand the functionproject files together.

Compress theproject files into aZIP file andupload it to anOBS bucket.

FunctionGraphDeveloper Guide 1 Overview

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 12

Page 16: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Runtime JAR File ZIP File ZIP File on OBS

Java 8 If the function doesnot reference third-party components,compile only thefunction project intoa JAR file.

If the functionreferences third-partycomponents, compilethe function project intoa JAR file, andcompress all third-partycomponents and thefunction JAR file into aZIP file.

Compress theproject files into aZIP file andupload it to anOBS bucket.

Go 1.8 Not supported. Zip the compiled file,and ensure that thename of the dynamiclibrary file is consistentwith the plugin name ofthe handler. Forexample, if the name ofthe dynamic library fileis testplugin.so, set thehandler totestplugin.Handler.Handler is the functionname.

Compress theproject file into aZIP file andupload it to anOBS bucket.

ZIP Project Package Examplel Example directory of a Nods.js project package

Example.zip Example project package|--- lib Service file directory|--- node_modules NPM third-party component directory|--- index.js .js handler file (mandatory)|--- package.json NPM project management file

l Example directory of a Python project packageExample.zip Example project package|--- com Service file directory|--- PLI Third-party dependency PLI directory|--- index.py .py handler file (mandatory)|--- watermark.py .py file for image watermarking|--- watermark.png Watermarked image

l Example directory of a Java project packageExample.zip Example project package|--- DISTest.jar Service function JAR file|--- commons-lang-2.6.jar Third-party dependency JAR file|--- commons-beanutils-1.9.1.jar Third-party dependency JAR file|--- commons-collections-3.2.1.jar Third-party dependency JAR file|--- commons-logging-1.1.1.jar Third-party dependency JAR file

FunctionGraphDeveloper Guide 1 Overview

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 13

Page 17: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

|--- ezmorph-1.0.6.jar Third-party dependency JAR file|--- json-lib-2.4.jar Third-party dependency JAR file

l Example directory of a Go project packageExample.zip Example project package|--- testplugin.so Service function package

FunctionGraphDeveloper Guide 1 Overview

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 14

Page 18: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

2 Developing Functions

2.1 Developing Functions in Node.js

Function Syntaxl Node.js 6.10

Use the following syntax when creating a handler function in Node.js 6.10:export.handler = function(event, context, callback)– handler: name of the function that FunctionGraph invokes to execute your code.

The name must be consistent with that you define when creating a function.– event: event parameter defined for the function. The parameter is in JSON format.– context: runtime information provided for executing the function. For details, see

the description of SDK APIs.– callback: used to return the defined err and message information to the frontend.

The general syntax is callback(err, message). You can define the err or messagecontent, for example, a character string.

– Function handler: index.handler.The function handler is in the format of [file name].[function name]. For example, ifyou set the handler to index.handler in your function, as shown in Figure 2-1,FunctionGraph will load the handler function defined in the index.js file.

Figure 2-1 Handler of a Node.js function

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 15

Page 19: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

l Node.js 8.10

Node.js 8.10 is compatible with the APIs of Node.js 6.10, and supports an async handler.

exports.handler = async (event, context, callback[optional]) => { return data;}

Responses are output through return.

SDK APIs

Table 2-1 lists the context methods provided by FunctionGraph.

Table 2-1 Context method description

Method Name Description

getRequestID() Obtains a request ID.

getRemainingTimeInMilliSeconds () Obtains the running time left of a function.

getAccessKey() Obtains an access key ID (AK). An agencyis required when you use this method.

getSecretKey() Obtains a secret access key (SK). Anagency is required when you use thismethod.

getUserData(string key) Uses keys to obtain the values passed byenvironment variables.

getFunctionName() Obtains the name of a function.

getRunningTimeInSeconds () Obtains the timeout of a function.

getVersion() Obtains the version of a function.

getMemorySize() Obtains the memory occupied by a function.

getCPUNumber() Obtains the number of CPUs occupied by afunction.

getProjectID() Obtains a project ID.

getPackage() Obtains a function group.

getToken() Obtains a token. An agency is requiredwhen you use this method.

getLogger() Obtains the logger method provided by thecontext and returns a log output class. Logsare output in the format of "time-request ID-content" by using the info method. Forexample, a logg object is obtained throughlogg = context.getLogger(), and logs areoutput by calling the info method inlogg.info("hello").

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 16

Page 20: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

WARNINGResults returned by using the getToken(), getAccessKey(), and getSecretKey() methodscontain sensitive information. When using these methods, exercise caution to avoid disclosingsensitive user information.

Developing a Node.js FunctionPerform the following steps to develop a Node.js function:

Step 1 Create a function project.

1. Write code for printing text helloworld.Open the text editor, develop a helloworld function, and save the code file ashelloworld.js. The code is as follows:var return_helloworld = function() { console.log('helloworld');};

module.exports = { print: return_helloworld};

2. Define a FunctionGraph function.Open the text editor, define a function, and save the function file as index.js under thesame directory as the helloworld.js file. The function code is as follows:var h = require('./helloworld.js');

exports.handler = function (event, context, callback) { h.print(); callback(null, JSON.stringify(event));}

NOTE

1. If the first parameter returned by callback is not null, the function execution fails and the HTTPerror message defined in the second parameter is returned.

2. FunctionGraph can return only the following types of values:

null: The HTTP response body is empty.

[]byte: The content in this byte array is the body of an HTTP response.

string: The content in this string is the body of an HTTP response.

Other: FunctionGraph returns a value as an object for JSON encoding, and uses the encoded objectas the body of an HTTP response. The Content-Type header of the HTTP response is set toapplication/json.

Step 2 Package the project files.

After creating the function project, you will have the following directory. Select all files underthe directory and package them into the fss_examples_nodejs6.10.zip file, as shown inFigure 2-2.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 17

Page 21: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-2 Packaging the project files

NOTICEIn this example, the function project files are saved under the ~/Code/ directory. Select andpackage all files under the directory to ensure that the index.js file, the handler of yourFunctionGraph function, is under the root directory when the ZIP file is decompressed.

Step 3 Create a FunctionGraph function and upload the code package.

Log in to the FunctionGraph console, create a Node.js function, and upload thefss_examples_nodejs6.10.zip file, as shown in Figure 2-3.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 18

Page 22: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-3 Uploading the code package

NOTE

1. The index of the handler must be consistent with the file name of your function, because the namewill help to locate the function file.

2. The handler is a function name, which must be consistent with that defined in the index.js file.

3. After you upload the fss_examples_nodejs6.10.zip file to OBS, when the function is triggered,FunctionGraph decompresses the file to locate the function file through index and locate thefunction in the index.js file through handler, and then executes the function.

Step 4 Test the function.

1. Create a test event.On the function details page that is displayed, choose Select test event > Configure testevent. Configure the test event information, as shown in Figure 2-4, and then clickSave.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 19

Page 23: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-4 Configuring a test event

2. On the function details page, select the configured test event, and click Test.

Step 5 View the function test result.

The function test result consists of three parts: function output (returned by callback),summary, and logs (output by using the console.log or getLogger() method), as shown inFigure 2-5.

Figure 2-5 Test result

----End

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 20

Page 24: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

2.2 Developing Functions in Python

Function Syntax

FunctionGraph supports Python 2.7 and Python 3.6.

The following is the syntax for creating a handler function in Python:

def handler (event, context)

l handler: name of the function that FunctionGraph invokes to execute your code. Thename must be consistent with that you define when creating a function.

l event: event parameter defined for the function. The parameter is in JSON format.l context: runtime information provided for executing the function. For details, see the

description of SDK APIs.

SDK APIs

Table 2-2 lists the context methods provided by FunctionGraph.

Table 2-2 Context method description

Method Name Description

getRequestID() Obtains a request ID.

getRemainingTimeInMilliSeconds () Obtains the running time left of a function.

getAccessKey() Obtains an AK. An agency is required whenyou use this method.

getSecretKey() Obtains an SK. An agency is required whenyou use this method.

getUserData(string key) Uses keys to obtain the values passed byenvironment variables.

getFunctionName() Obtains the name of a function.

getRunningTimeInSeconds () Obtains the timeout of a function.

getVersion() Obtains the version of a function.

getMemorySize() Obtains the memory occupied by a function.

getCPUNumber() Obtains the number of CPUs occupied by afunction.

getProjectID() Obtains a project ID.

getPackage() Obtains a function group.

getToken() Obtains a token. An agency is requiredwhen you use this method.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 21

Page 25: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Method Name Description

getLogger() Obtains the logger method provided by thecontext and returns a log output class. Logsare output in the format of "time-request ID-content" by using the info method. Forexample, a logg object is obtained throughlogg = context.getLogger(), and logs areoutput by calling the info method inlogg.info("hello").

WARNINGResults returned by using the getToken(), getAccessKey(), and getSecretKey() methodscontain sensitive information. When using these methods, exercise caution to avoid disclosingsensitive user information.

Developing a Python Function

Perform the following steps to develop a Python function:

Step 1 Create a function project.

1. Write code for printing text helloworld.

Open the text editor, develop a helloworld function, and save the code file ashelloworld.py. The code is as follows:def printhello(): print 'Hello world!'

2. Define a FunctionGraph function.

Open the text editor, define a function, and save the function file as index.py under thesame directory as the helloworld.py file. The function code is as follows:import jsonimport helloworld

def handler (event, context): output =json.dumps(event) helloworld.printhello() return output

NOTE

FunctionGraph can return only the following types of values:

l None: The HTTP response body is empty.

l string: The content in this string is the body of an HTTP response.

l Other: FunctionGraph returns a value as an object for JSON encoding, and uses the encoded objectas the body of an HTTP response. The Content-Type header of the HTTP response is set toapplication/json.

Step 2 Package the project files.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 22

Page 26: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

After creating the function project, you will have the following directory. Select all files underthe directory and package them into the fss_examples_python2.7.zip file, as shown in Figure2-6.

Figure 2-6 Packaging the project files

NOTICEIn this example, the function project files are saved under the ~/Code/ directory. Select andpackage all files under the directory to ensure that the index.py file, the handler of yourFunctionGraph function, is under the root directory when the ZIP file is decompressed.

Step 3 Create a FunctionGraph function and upload the code package.

Log in to the FunctionGraph console, create a Python function, and upload thefss_examples_python2.7.zip file according to Figure 2-7.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 23

Page 27: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-7 Uploading the code package

NOTE

1. The index of the handler must be consistent with the file name of your function, because the namewill help to locate the function file.

2. The handler is a function name, which must be consistent with that defined in the index.py file.

3. After you upload the fss_examples_python2.7.zip file to OBS, when the function is triggered,FunctionGraph decompresses the file to locate the function file through index and locate thefunction in the index.py file through handler, and then executes the function.

Step 4 Test the function.

1. Create a test event.On the function details page that is displayed, choose Select test event > Configure testevent. Configure the test event information, as shown in Figure 2-8, and then clickSave.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 24

Page 28: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-8 Configuring a test event

2. On the function details page, select the configured test event, and click Test.

Step 5 View the function test result.

The function test result consists of three parts: function output (returned by callback),summary, and logs (output by using the console.log or getLogger() method), as shown inFigure 2-9.

Figure 2-9 Test result

----End

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 25

Page 29: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

2.3 Developing Functions in Java

Function Syntax

Use the following syntax when creating a handler function in Java:

Scope Return parameter Function name (User-defined parameter, Context)

l Scope: It must be defined as public for the function that FunctionGraph invokes toexecute your code.

l Return parameter: user-defined output, which is converted into a character string andreturned as an HTTP response. The HTTP response is a JSON string.

l Function name: user-defined function name.l User-defined parameter: FunctionGraph supports only one user-defined parameter. For

complex parameters, you are advised to define them as an object and provide datathrough JSON strings. When invoking a function, FunctionGraph parses the JSONstrings as an object.

l Context: runtime information provided for executing the function. For details, see thedescription of SDK APIs.

When creating a function in Java, define a handler in the format of [package name].[filename].[function name].

SDK APIs

The Java SDK provides multiple event and context APIs and a logging API.

l Event APIsEvent structure definition is added to the Java SDK, facilitating development of code thatuses triggers. Currently, DMS, DIS, SMN, LTS, APIG, , and timer triggers aresupported.

a. APIG trigger

Table 2-3 APIGTriggerEvent methods

Method Name Description

isBase64Encoded() Checks whether the body of an eventhas been encoded using Base64.

getHttpMethod() Obtains the HTTP request method.

getPath() Obtains the HTTP request path.

getBody() Obtains the HTTP request body.

getPathParamters() Obtains all path parameters.

getRequestContext() Obtains API Gateway configurations(returned as an APIGRequestContextobject).

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 26

Page 30: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Method Name Description

getHeaders() Obtains the HTTP request header.

getQueryStringParameters() Obtains query parameters.

Table 2-4 APIGRequestContext methods

Method Name Description

getApiId() Obtains an API ID.

getRequestId() Obtains the request ID of an APIrequest.

getStage() Obtains the name of the environmentin which an API has been published.

Table 2-5 APIGTriggerResponse methods

Method Name Description

setBody(String body) Sets the message body.

setHeaders(Map<String,String>headers)

Sets the HTTP response header thatwill be returned.

setStatusCode(int statusCode) Sets the HTTP status codes.

setBase64Encoded(booleanisBase64Encoded)

Configures Base64 encoding of theresponse body.

b. DIS trigger

Table 2-6 DISTriggerEvent methods

Method Name Description

getShardID() Obtains a partition ID.

getMessage() Obtains the DIS message body(DISMessage structure).

getTag() Obtains the function version.

getStreamName() Obtains the channel name.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 27

Page 31: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Table 2-7 DISMessage methods

Method Name Description

getNextPatitionCursor() Obtains the next partition cursor.

getRecords() Obtains message records (DISRecordstructure).

getMillisBehindLatest() Reserved. (Currently, 0 is returned.)

Table 2-8 DISRecord methods

Method Name Description

getPartitionKey() Obtains a data partition.

getData() Obtains data.

getRawData() Obtains UTF-8 data strings afterBase64 decoding.

getSequenceNumber() Obtains a sequence number (ID of eachrecord).

c. DMS trigger

Table 2-9 DMSTriggerEvent methods

Method Name Description

getQueueId() Obtains a queue ID.

getRegion() Obtains a region name.

getEventType() Obtains the event type, and returnsMessageCreated.

getConsumerGroupId() Obtains a consumer group ID.

getMessages() Obtains DMS messages(DMSMessage structure).

Table 2-10 DMSMessage methods

Method Name Description

getBody() Obtains a message body.

getAttributes() Obtains the message attribute set.

d. SMN trigger

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 28

Page 32: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Table 2-11 SMNTriggerEvent method

Method Name Description

getRecord() Obtains message records(SMNRecord structure).

Table 2-12 SMNRecord methods

Method Name Description

getEventVersion() Obtains an event version. The currentversion is 1.0.

getEventSubscriptionUrn() Obtains a subscription URN.

getEventSource() Obtains an event source.

getSmn() Obtains a message body (SMNBodystructure).

Table 2-13 SMNBody methods

Method Name Description

getTopicUrn() Obtains a topic URN.

getTimeStamp() Obtains the timestamp of a message.

getMessageAtrributes() Obtains the message attribute set.

getMessage() Obtains the message body.

getType() Obtains the message type.

getMessageId() Obtains the message ID.

getSubject() Obtains the message topic.

e. Timer trigger

Table 2-14 TimerTriggerEvent methods

Method Name Description

getVersion() Obtains a version. The current versionis v1.0.

getTime() Obtains the current date and time.

getTriggerType() Obtains the trigger type (Timer).

getTriggerName() Obtains the trigger name.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 29

Page 33: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Method Name Description

getUserEvent() Obtains the additional information ofthe trigger.

f. LTS trigger

Table 2-15 LTSTriggerEvent method

Method Name Description

getLts() Obtains LTS messages (LTSBodystructure).

Table 2-16 LTSBody methods

Method Name Description

getData() Obtains the original LTS message.

getRawData() Obtains the UTF-8 message afterBase64 decoding.

NOTE

1. When using an APIG trigger, set the first parameter of the handler function (for example,handler) as follows: handler(APIGTriggerEvent event, Context context)

2. The six types of TriggerEvent methods have corresponding set methods, which howeverare not recommended in general cases.Both DIS and LTS triggers have getRawData()methods, but do not have setRawData() methods.

l Context APIs

The context APIs are used to obtain the context, such as tenant AK/SK, current requestID, allocated memory space, and number of CPUs, required for executing a function.

Table 2-17 lists the context APIs provided by FunctionGraph.

Table 2-17 Context method description

Method Name Description

getRequestID( ) Obtains a request ID.

getRemainingTimeInMilligetRunningTi-meInSecondsSeconds ( )

Obtains the running time left of afunction.

getAccessKey( ) Obtains an AK. An agency is requiredwhen you use this method.

getSecretKey( ) Obtains an SK. An agency is requiredwhen you use this method.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 30

Page 34: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Method Name Description

getUserData(string key) Uses keys to obtain the values passed byenvironment variables.

getFunctionName( ) Obtains the name of a function.

getRunningTimeInSeconds ( ) Obtains the timeout of a function.

getVersion( ) Obtains the version of a function.

getMemorySize( ) Obtains the memory occupied by afunction.

getCPUNumber( ) Obtains the number of CPUs occupied bya function.

getProjectID( ) Obtains a project ID.

getPackage( ) Obtains a function group.

getToken( ) Obtains a token. An agency is requiredwhen you use this method.

getLogger( ) Obtains the logger method provided bythe context. (By default, information suchas the time and request ID is output.)

WARNINGResults returned by using the getToken(), getAccessKey(), and getSecretKey() methodscontain sensitive information. When using these methods, exercise caution to avoiddisclosing sensitive user information.

l Logging APITable 2-18 lists the logging API provided in the Java SDK.

Table 2-18 Logging API description

Method Name Description

RuntimeLogger() Records user input logs. It containsmethod log(String string).

Developing a Java FunctionPerform the following procedure to develop a demo Java function:

Step 1 Create a function project.

1. Configure Eclipse and create a Java project named FuncDemo, as shown in Figure 2-10and Figure 2-11.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 31

Page 35: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-10 Configuring Eclipse

Figure 2-11 Creating a project

2. Download the SDK, and decompress it, as shown in Figure 2-12.Download the Java SDK to a local development environment, and decompress the SDKpackage to resolve the SDK dependency problem.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 32

Page 36: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-12 Downloading and decompressing the SDK

3. Configure the dependency.Configure the SDK dependency (RunTime-1.0.0.jar) for the demo project, as shown inFigure 2-13, Figure 2-14, and Figure 2-15.

Figure 2-13 Adding a dependency

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 33

Page 37: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-14 Selecting the JAR file

Figure 2-15 Configuring the dependency

Step 2 Create a function.

1. Create a package named demo, as shown in Figure 2-16.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 34

Page 38: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-16 Creating package demo

2. Create a class named MyTest under package demo, as shown in Figure 2-17.

Figure 2-17 Creating a class

3. Define function myHandler to be run on FunctionGraph, as shown in Figure 2-18.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 35

Page 39: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-18 Defining a function

Step 3 Package the project files.

Package the project files into a JAR file named FuncDemo.jar, as shown in Figure 2-19,Figure 2-20, and Figure 2-21.

Figure 2-19 Packaging the project files

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 36

Page 40: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-20 Selecting a file type

Figure 2-21 Selecting project files to be exported

Step 4 Create a function and upload the code package.

Log in to the FunctionGraph console, create a Java function, and upload the code package, asshown in Figure 2-22.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 37

Page 41: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-22 Creating a function

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 38

Page 42: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

NOTE

l In demo.MyTest.myHandler, demo is a package name, MyTest is a file name, and myHandler is afunction name.

l Set the function handler to demo.MyTest.myHandler. When creating the demo function, upload theJAR file compiled in the previous step. If the function uses third-party components, package thethird-party components and the JAR file into a ZIP file, as shown in Figure 2-23. (In a WindowsOS, select all JAR files and right-click to create a ZIP file.)

Figure 2-23 Creating a ZIP file

Step 5 Test the function.

1. Create a test event.On the function details page that is displayed, choose Select test event > Configure testevent. Configure the test event information, as shown in Figure 2-24, and then clickSave.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 39

Page 43: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-24 Configuring a test event

2. On the function details page, select the configured test event, and click Test.

Step 6 View the function test result.

The function test result consists of three parts: function output (returned by callback),summary, and logs (output by using the console.log or getLogger() method), as shown inFigure 2-25.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 40

Page 44: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-25 Test result

----End

2.4 Developing Functions in Go

Function Syntax

FunctionGraph supports only Go 1.8.3 currently.

The following is the syntax for creating a handler function in Go:

func Handler (payload []byte, ctx context.RuntimeContext)

l Handler: name of the function that FunctionGraph invokes to execute your code. Thename must be consistent with that you define when creating a function, and must startwith an uppercase letter.

l payload: event parameter defined for the function. The parameter is in JSON format.l ctx: runtime information provided for executing the function. For details, see the

description of SDK APIs.

SDK APIsl Context APIs

The Go SDK provides multiple context APIs and a logging API. The download link ofthe Go SDK is provided in Table 1-1. Table 2-19 lists the context APIs provided byFunctionGraph.

Table 2-19 Context method description

Method Name Description

GetRequestID() string Obtains a request ID.

GetRemainingTimeInMilliSeconds() Obtains the running time left of afunction.

GetAccessKey() string Obtains an AK. An agency is requiredwhen you use this method.

GetSecretKey() string Obtains an SK. An agency is requiredwhen you use this method.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 41

Page 45: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Method Name Description

GetUserData(key string) string Uses keys to obtain the values passed byenvironment variables.

GetFunctionName() string Obtains the name of a function.

GetRunningTimeInSeconds() int Obtains the timeout of a function.

GetVersion() string Obtains the version of a function.

GetMemorySize() int Obtains the memory occupied by afunction.

GetCPUNumber() int Obtains the number of CPUs occupied bya function.

GetProjectID() string Obtains a project ID.

GetPackage() string Obtains a function group.

GetToken() string Obtains a token. An agency is requiredwhen you use this method.

GetLogger() context.RuntimeLogger Obtains the logger method provided bythe context. (By default, information suchas the time and request ID is output.)

WARNINGResults returned by using the GetToken(), GetAccessKey(), and GetSecretKey()methods contain sensitive information. When using these methods, exercise caution toavoid disclosing sensitive user information.

l Logging API

Table 2-20 lists the logging API provided in the Go SDK.

Table 2-20 Logging API description

Method Name Description

RuntimeLogger() l Records user input logs. It containsmethod Logf(format string,args ...interface{}).

l This method outputs logs in theformat of "time-request ID-output",for example,2017-10-25T09:10:03.328Z473d369d-101a-445e-a7a8-315cca788f86 test log output.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 42

Page 46: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Developing a Go FunctionPerform the following steps to develop a Go function:

Step 1 Create a Go project.

1. Log in to a Linux server on which the Go 1.8.3 SDK and a running environment havebeen installed. (Currently, Ubuntu 14.04, Ubuntu 16.04, SUSE 11.3, SUSE 12.0, andSUSE 12.1 are supported.) Then create the /home/fssgo/src/go-runtime directory, anddecompress the Go SDK under this directory. The directories before and afterdecompression are as follows:$ mkdir -p /home/fssgo/src/go-runtime$ unzip fss-go-sdk.zip -d /home/fssgo/src/go-runtime

2. Create a function file under the /home/fssgo/src/go-runtime directory and implementthe following interface:func Handler(payload []byte, ctx context.RuntimeContext) (interface{}, error)In this interface, payload is the body of a client request, and ctx is the runtime contextobject provided for executing a function. For more information about the methods, seethe SDK APIs. The following uses test.go as an example.package main

import ( "fmt" "encoding/json" "go-runtime/go-api/context")

type Greeting struct { Name string `json:"name"`}

// Handler functionfunc Handler(payload []byte, ctx context.RuntimeContext) (interface{}, error) { logger := ctx.GetLogger()

var greeting Greeting err := json.Unmarshal(payload, &greeting) if err != nil { return "", fmt.Errorf("invalid request payload") }

logger.Logf("hello %s.", greeting.Name)

logger.Logf("RequestId: %s", ctx.GetRequestID()) logger.Logf("FunctionName: %s", ctx.GetFunctionName()) logger.Logf("Version: %s", ctx.GetVersion()) return fmt.Sprintf("hello %s", greeting.Name), nil}

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 43

Page 47: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

NOTICE1. If the error parameter returned by a function is not nil, the function execution fails.2. If the error parameter returned by a function is nil, FunctionGraph supports only the

following types of values:nil: The HTTP response body is empty.[]byte: The content in this byte array is the body of an HTTP response.string: The content in this string is the body of an HTTP response.Other: FunctionGraph returns a value as an object for JSON encoding, and uses theencoded object as the body of an HTTP response. The Content-Type header of theHTTP response is set to application/json.

Step 2 Compile and package the function code.

After completing the function code, compile and package it by performing the followingsteps:

1. Set environment variables GOROOT and GOPATH.$ export GOROOT=/usr/local/go (This statement assumes that the Go SDK hasbeen installed under the /usr/local/go directory.)$ export PATH=$GOROOT/bin:$PATH$ export GOPATH=/home/fssgo

2. Compile the function code.$ cd /home/fssgo/src/go-runtime$ go build --buildmode=plugin -o testplugin.so test.goAfter compilation, a file named testplugin.so is generated under the current directory.

3. Package the file.$ zip fss_examples_go1.8.zip testplugin.soAfter the command is executed, a file named fss_examples_go1.8.zip is generated underthe current directory.

Step 3 Create a function.

Log in to the FunctionGraph console, create a Go function, and upload thefss_examples_go1.8.zip file according to Figure 2-26.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 44

Page 48: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-26 Uploading the code package

NOTE

If you edit code in Go, zip the compiled file, and ensure that the name of the dynamic library file isconsistent with the plugin name of the handler. For example, if the name of the dynamic library file istestplugin.so, set the handler to testplugin.Handler. The handler must be consistent with that defined inStep 1.

Step 4 Test the function.

1. Create a test event.On the function details page that is displayed, choose Select test event > Configure testevent. Configure the test event information, as shown in Figure 2-27, and then clickSave.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 45

Page 49: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-27 Configuring a test event

2. On the function details page, select the configured test event, and click Test.

Step 5 View the function test result.

The function test result consists of three parts: function output (returned by callback),summary, and logs (output by using the console.log or getLogger() method), as shown inFigure 2-28.

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 46

Page 50: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 2-28 Test result

----End

FunctionGraphDeveloper Guide 2 Developing Functions

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 47

Page 51: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

3 Creating Workflows

3.1 IntroductionFunctionGraph is a serverless service that allows you to write JSON-based workflow files tobuild applications. If your workflow invokes functions, you need to develop functionsadditionally. This chapter provides a few examples to demonstrate how to create workflowson FunctionGraph.

3.2 Creating a Workflow to Invoke a FunctionThis example demonstrates how to create a workflow with a function. The function performsan addition operation based on the specified input of the workflow, and then returns anexecution result.

Creating a Function

The function code used in this example is as follows:

# -*- coding:utf-8 -*-import jsondef handler (event, context): result = event['key1'] + event['key2'] return str(result)

Creating a Workflow

The following is the code in the JSON definition file of the workflow. The states field definesthe workflow states. The definition file contains the following parameters:

1. taskState: name of the first state.

2. type: type of the first state, which is set to OPERATION to orchestrate a function.

3. start: This parameter is set to true, indicating that the state is the first state of theworkflow.

4. action-mode: mode to invoke multiple functions. The value of this parameter can beSEQUENTIAL or PARALLEL.

FunctionGraphDeveloper Guide 3 Creating Workflows

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 48

Page 52: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

5. actions: an array that contains one or more actions, which each invokes a function. Thefollowing example uses only one action.

6. action-name: name of an action.

7. function: function to be invoked by an action.

8. invocation-mode: mode in which a function will be invoked. The value of thisparameter can be SYNC or ASYNC.

9. next-state: This parameter is set to end, indicating that the workflow will transition tothe End state after executing the current state. The End state is of the END type, whichmarks the end of a workflow.

{ "states": { "taskState": { "type": "OPERATION", "start": true, "action-mode":"SEQUENTIAL", "actions": [ { "action-name": "action1", "function": "urn:fss:cn-north-1:d9afa2ccdc76425a8aae58303019a34d:function:default:math_caculation", "invocation-mode": "SYNC" } ], "next-state": "end" }, "end": { "type": "END" } }}

Running the Workflow

Test the workflow by specifying the following input:

{"key1":1, "key2":2}

Start the workflow. FunctionGraph invokes a function based on the input and function URN.The function calculates key1 + key2 and returns the result 3. Figure 3-1 shows the test resultof the workflow.

Figure 3-1 Test result of the workflow

FunctionGraphDeveloper Guide 3 Creating Workflows

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 49

Page 53: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

3.3 Creating a Workflow to Handle Error ConditionsThis example demonstrates how to create a workflow that invokes a function to perform anaction and handles error conditions based on the function output. If an error occurs when theworkflow invokes the function, the workflow matches the error with the corresponding stateand then runs this state.

Creating a FunctionThe function code used in this example is as follows:

# -*- coding:utf-8 -*-import jsondef handler (event, context): if not isinstance(event['key1'],int) or not isinstance(event['key2'],int): return "ERROR:must be int!" result = event['key1'] + event['key2'] return str(result)

Creating a WorkflowThe following is the code in the JSON definition file of the workflow. The states field definesthe workflow states. For descriptions about parameters in the definition file, see Creating aWorkflow. The results field contains the following parameters:

1. results: an array that contains one or more results, which are processed one by one.2. match: error type to be matched. For more information, see Definition Restrictions.3. retry-interval: interval between retries performed in case of an action failure.4. max-retry: maximum number of times that an action retries in case of a failure.5. next-state: name of the state to which the workflow will transition when the threshold

specified in max-retry is reached.{ "states": { "taskState": { "type": "OPERATION", "start": true, "action-mode":"SEQUENTIAL", "actions": [ { "action-name": "action1", "function": "urn:fss:cn-north-1:d9afa2ccdc76425a8aae58303019a34d:function:default:math_caculation", "invocation-mode": "SYNC", "results": [ { "match": "MatchAny", "retry-interval": 1, "max-retry": 3, "next-state": "noopnode" } ] } ],

FunctionGraphDeveloper Guide 3 Creating Workflows

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 50

Page 54: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

"next-state": "end" }, "noopnode": { "type": "NOOP", "next-state": "end" }, "end": { "type": "END" } }}

Running the Workflow

Test the workflow by specifying the following input:

{"key1":1, "key2":2}

Start the workflow. FunctionGraph invokes a function based on the input and function URN.An error will occur during the function execution. Figure 3-2 shows the test result of theworkflow.

Figure 3-2 Test result of the workflow

3.4 Creating a Workflow with Multiple State ChoicesThis example demonstrates how to create a workflow with multiple state choices. Theworkflow transitions to a state that matches the input parameter.

Creating a Function

The function code used in this example is as follows:

# -*- coding:utf-8 -*-import jsondef handler (event, context): if not isinstance(event['key1'],int) or not isinstance(event['key2'],int): return "ERROR:must be int!" result = event['key1'] + event['key2'] ret=dict() ret["f"] = str(result) return str(ret)

FunctionGraphDeveloper Guide 3 Creating Workflows

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 51

Page 55: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Creating a Workflow

The following is the code in the JSON definition file of the workflow. The states field definesthe workflow states. For descriptions about parameters in the definition file, see Creating aWorkflow and Creating a Workflow to Handle Error Conditions. The switch fieldcontains the following parameters:

1. type: This parameter is set to SWITCH, indicating that the state is of the SWITCH type.2. choices: an array that contains all branches of the state.3. path: filters the input of the SWITCH state. For more information, see SWITCH.4. value: a string type value used to compare with the value filtered by path.5. next-state: name of the state to which the workflow will transition if the value filtered

by path is equal to the value specified in value.6. default: state to which the workflow will transition if none of the choices is matched.{ "states": { "taskState": { "type": "OPERATION", "start": true, "action-mode":"SEQUENTIAL", "actions": [ { "action-name": "action1", "function": "urn:fss:cn-north-1:d9afa2ccdc76425a8aae58303019a34d:function:default:math_caculation", "invocation-mode": "SYNC", "results": [ { "match": "MatchAny", "retry-interval": 1, "max-retry": 3, "next-state": "noopnode" } ] } ], "next-state": "switch" }, "noopnode": { "type": "NOOP", "next-state": "end" }, "switch": { "type": "SWITCH", "choices": [ { "path": "$.f", "value": "1", "next-state": "path1" }, { "path": "$.f", "value": "2", "next-state": "path2" } ],

FunctionGraphDeveloper Guide 3 Creating Workflows

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 52

Page 56: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

"default": "default" }, "default": { "type": "NOOP", "next-state": "end" }, "path1": { "type": "NOOP", "next-state": "end" }, "path2": { "type": "NOOP", "next-state": "end" }, "end": { "type": "END" } }}

Running the WorkflowTest the workflow after specifying an input. FunctionGraph invokes a function based on theinput and function URN.

1. Test parameter 1{"key1":0, "key2":1}Figure 3-3 shows the test result of the workflow.

Figure 3-3 Test result of the workflow

2. Test parameter 2{"key1":0, "key2":2}Figure 3-4 shows the test result of the workflow.

FunctionGraphDeveloper Guide 3 Creating Workflows

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 53

Page 57: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 3-4 Test result of the workflow

3. Test parameter 3{"key1":0, "key2":3}Figure 3-5 shows the test result of the workflow.

Figure 3-5 Test result of the workflow

FunctionGraphDeveloper Guide 3 Creating Workflows

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 54

Page 58: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

4 Workflow Definition

4.1 Workflow StructureWorkflows are defined using JSON text. The following is an example HelloWorld workflow:

{ "states": { "helloWorldState": { "type": "NOOP", "start": true, "next-state": "end" }, "end": { "type": "END" } }}

The preceding code defines a workflow with the helloWorldState and end states, which aredefined in the states field. Transition between the two states is implemented through the next-state field in the helloWorldState state. The following figure shows the graphicalrepresentation of this workflow on the FunctionGraph console.

Figure 4-1 Graphical representation of the HelloWorld workflow

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 55

Page 59: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

In addition to the states field, a workflow definition generally has an event-defs field, whichdefines the trigger used in the workflow. Table 4-1 describes these two fields.

Table 4-1 Workflow structure description

Field Mandatory

Description Example

event-defs No Event definition, which isrequired if the workflowcontains an EVENT state.The value of this parameteris a JSON object thatdefines a series of events.For more information, seeEvent Definition. Anevent name is a string of1–80 characters. Onlyletters, digits, hyphens (-),and underscores (_) areallowed.

"event-defs": { "event1": {... }, "event2": {... }, ... }

states Yes State definition. The valueof this parameter is a JSONobject that defines a seriesof states. A state name is astring of 1–80 characters.Only letters, digits,hyphens (-), andunderscores (_) areallowed.

"states":{ "State1" : { },

"State2" : { }, ...}

4.2 Event DefinitionAn event definition includes three fields, which are described in Table 4-2.

Table 4-2 Event definition

Field Mandatory Description Example

payload-filter-request

No Path to filter eventparameters. Formore information,see Input andOutput. The valueof this parameter is astring. The defaultvalue is $.

$.workItem

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 56

Page 60: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Field Mandatory Description Example

payload-filter-response

No Path to filter eventresults. For moreinformation, seeInput and Output.The value of thisparameter is a string.The default value is$.

$

source Yes Uniqueidentification of anevent, which is astring. The value ofthis parameter mustbe a valid eventURN.

urn:serverless:southChina:7aad83af3e8d42e99ac194e8419e2c9b:event:Worker_WorkRequest_WorkReq-test_1502865866

The following is an example event definition:

"event1": { "payload-filter-request" : "$.workItem", "source": "urn:serverless:southChina:7aad83af3e8d42e99ac194e8419e2c9b:event:Worker_WorkRequest_WorkReq-test_1502865866", "payload-filter-response" : "$" }

4.3 State Types and Field DescriptionFunctionGraph provides six states, which are described in Table 4-3.

Table 4-3 State description

State Description

NOOP Simply passes the input without performing any action.

DELAY Waits for a period time before proceeding to the nextstate.

SWITCH Runs a next state based on the matched value.

OPERATION Performs one or more actions, that is, serverless functions,before proceeding to the next state.

EVENT Performs required actions when the trigger generates anevent.

END Ends the execution of an instance.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 57

Page 61: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

All states have the four fields described in Table 4-4.

Table 4-4 State field description

Field Mandatory Description

start No Marks the start of a workflow. Aworkflow must have one state whosestart parameter is true.

type Yes Type of a state, which is a characterstring and must be one of the six statetypes.

payload-filter-in No Path to filter the parameter input fromthe previous state. The value of thisparameter must be a valid JsonPathexpression. For more information, seePayload Filters.

payload-filter-out No Path to filter the output of a state to thenext state. The value of this parametermust be a valid JsonPath expression.For more information, see PayloadFilters.

NOTE

END states do not have the payload-filter-in and payload-filter-out fields.

NOOP

A NOOP state simply passes the input without performing any action. It is used along withparameter filtering mechanisms in workflow debugging scenarios to build requiredparameters. Table 4-5 describes the field in a NOOP state.

Table 4-5 NOOP state field description

Field Mandatory Description

next-state Yes Name of a next state, whichis a character string andmust be included in theworkflow definition.

SWITCH

A SWITCH state implements a branching logic. Specifically, a SWITCH state compares theoutput of the previous state with a preset value, and then selects a correct branch based on thecomparison result. Table 4-6 describes the fields in a SWITCH state.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 58

Page 62: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Table 4-6 SWITCH state field description

Field Mandatory Description

default Yes Name of the state totransition to if none of thechoices is matched. Thevalue of this parameter is acharacter string and must beincluded in the workflowdefinition.

choices Yes The value of this parameteris a JSON array of choices.Each choice is a JSONobject, which must includethe three parametersdescribed in Table 4-7.

Table 4-7 Description of the choices array

Parameter Description

path A character string in JsonPath. Thisparameter obtains a value from the output ofthe previous state, and then compares thevalue with a preset value. The value of thisparameter cannot be null.

value A user-defined character string. The valueof this parameter cannot be null.

next-state Name of the state to transition to if a choiceis matched.

The following is an example choices array:

"choices" :[ { "path" :"$.f", "value" :"1", "next-state" :"flv2avi" } ]

In this example, a value is obtained from the output of the previous state by using the $.f path,and then compared with the value 1. If the two values are the same, the flv2avi state is run.

DELAYA DELAY state delays the workflow from continuing for a specified period of time. The statecan be used to wait for the result of a function that is executed asynchronously. Table 4-8describes the fields in a DELAY state.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 59

Page 63: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Table 4-8 DELAY state field description

Field Mandatory Description

time-delay Yes Time (s) to wait forexecuting the next step,which must be an integerwithin 0 and 86,400.

next-state Yes Name of a next state, whichis a character string andmust be included in theworkflow definition.

OPERATION

An OPERATION state executes a specified function to achieve the expected result. Thefollowing is an example OPERATION state:

"taskState": { "type": "OPERATION", "action-mode": "SEQUENTIAL", "actions": [ { "action-name": "action1", "function": "urn:cff:cn_north_1:57f8fd63abc847ac8b52960d11185a15:function:default:FormationIdentificationdemo1234:latest", "invocation-mode": "SYNC", "results": [ { "match": "MatchAny", "retry-interval": 1, "max-retry": 3, "next-state": "next1" } ] }, { "action-name": "action2", "function": "urn:cff:cn_north_1:57f8fd63abc847ac8b52960d11185a15:function:default:FormationIdentificationdemo123:latest", "invocation-mode": "SYNC" } ], "next-state": "next1" }

In the preceding OPERATION state, the body of the state is defined in the actions field. Theactions field is an array that contains two actions. Each action invokes a function specified ina function field. The action-mode field, which is in the same level as the actions array,specifies the sequential or parallel mode to execute multiple actions. Each action has a resultsfield, which selects a branch based on the exception that occurs during function invocation.

An OPERATION state performs a series of tasks. Table 4-9 describes the fields in the state.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 60

Page 64: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Table 4-9 OPERATION state field description

Field Mandatory Description

action-mode No Mode to execute actions,which can be PARALLELor SEQUENTIAL. Thedefault value isSEQUENTIAL.

actions Yes A JSON array of actiondefinitions, which mustcontain one or more actions.For more information, seeTable 4-10.

next-state Yes Name of a next state, whichis a character string andmust be included in theworkflow definition.

Action Definition

Table 4-10 describes the fields in an action.

Table 4-10 Action field description

Field Mandatory Description

action-name Yes Name of an action, which isa unique string of 1–80characters. Only letters,digits, hyphens (-), andunderscores (_) are allowed.

function Yes Used to specify aFunctionGraph function.

invocation-mode No The value of this parametermust be SYNC or ASYNC.The default value is SYNC.

results No Retry mechanism to beimplemented when an actionfails. The value of thisparameter is a JSON arrayof result definitions. Thesize of the results field mustbe greater than or equal to 0.For more information, seeTable 4-11.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 61

Page 65: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Field Mandatory Description

timeout No Maximum executionduration (s) of an action,which is an integer within 0and 300. If the value is 0, notimeout is set for the action.

payload-filter No Path to filter input results.For more information, seeInput and Output.

Result Definition

Table 4-11 describes the fields in a result.

Table 4-11 Result field description

Field Mandatory Description

match Yes A non-empty string thatmatches an error type.MatchAny means matchingany errors.In addition, the followingsystem errors can bematched:States.ActionFailed:Function execution error orinternal error.States.PermissionError:Accessed denied.States.ParameterError:Function parameter error.States.NotFound: Nofunction found.States.TooManyRequests:Too many requests.States.FunctionStageUna-vailable: FunctionGraph isunavailable.States.FunctionStageOtherErrors: Other error codesare returned.

retry-interval No Interval (s) between retries,which must be an integergreater than or equal to 0.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 62

Page 66: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Field Mandatory Description

max-retry No Maximum number of timesthat an action will retry incase of a failure, which mustbe an integer greater than orequal to 0. The default valueis 3. If the value is 0, theaction will not retry in caseof a failure.

next-state Yes Name of a next state, whichis a character string andmust be included in theworkflow definition.

NOTE

Multiple functions can be invoked in three combination modes: asynchronous+parallel, synchronous+parallel, and synchronous+sequential.

EVENTAn EVENT state waits for events to occur, and executes a specified function immediately toimplement a predefined logic once receiving the triggering message of an event. Table 4-12describes the fields in an EVENT state.

Table 4-12 EVENT state field description

Field Mandatory Description

events Yes A JSON array that definesevent messages. Eachmember of the array is anevent message object.

event-timeout No Maximum executionduration (s) of an EVENTstate, which must be aninteger between 0 and86,400. If the value is 0, notimeout is set for the state.

Table 4-13 describes the fields in an event.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 63

Page 67: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Table 4-13 Event field description

Field Mandatory Description

event-expression Yes Name of an event, which isa character string and mustbe included in the eventdefinition.

action-mode No Mode to execute an action,which can be PARALLELor SEQUENTIAL. Thedefault value isSEQUENTIAL.

actions No A JSON array of actiondefinitions, which mustcontain 0 or more actions.For more information, seePayload Filters.

next-state Yes Name of a next state, whichis a character string andmust be included in theworkflow definition.

NOTE

Multiple functions can be invoked in three combination modes: asynchronous+parallel, synchronous+parallel, and synchronous+sequential.

END

An END state marks the end of a workflow and does not have any field. A workflow cancontain only one END state. For example:

"end1": { "type": "END" }

4.4 Input and Output

Payload Filters

FunctionGraph supports the input of JSON data and processes the data for different purposesby using the payload filters listed in Table 4-14.

Table 4-14 Data filters

Path Type Payload Filters Included

InputPath payload-filter-in (Table 4-4).

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 64

Page 68: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Path Type Payload Filters Included

ResultPath payload-filter-request (Table 4-2), payload-filter (OPERATION), and payload-filter-response (Table 4-2).

OutputPath payload-filter-out (Table 4-4).

The paths have the following rules:

l A path starts with a dollar ($) sign. It can access elements of an input by using periods(.), such as, $.x.y.

l You can define InputPath and OutputPath in JsonPath. For more information, seehttps://github.com/json-path/JsonPath.

l ResultPath supports only $.x instead of $.['x'].

InputPath

1. You can choose to pass only part of input to a task.2. If InputPath is not set, the default value $ is used, which means passing the entire input

to a task.3. If InputPath is null, the input is discarded, and the task receives an empty object {}.4. If the path does not match any item in the input, an error indicating invalid path is

reported.

ResultPath

ResultPath supports only the $.x.y format, which represents a reference path.

ResultPath puts an execution result in the result, and then OutputPath takes part of theresult to send as the output. ResultPath may add the execution result to the result, oroverwrite part or all of the result.

1. If ResultPath matches an item in the result, it overwrites the item with the input. Then,the entire modified result is used as the state output.

2. If ResultPath does not match any item in the result, another item is added to the result.The added item contains the input. Then, the expanded result is used as the state output.

3. If ResultPath is set to the default value $, the result is directly used as the state output.4. If ResultPath is null, the execution result is discarded, and the input is directly used as

the state output.

OutputPath

1. If OutputPath matches an item of the input, only the input item is used as the stateoutput.

2. If OutputPath does not match any item in the input, an error indicating invalid pathoccurs.

3. If OutputPath is set to the default value $, it matches the entire input, which will thenbe passed to the next state.

4. If OutputPath is null, an empty JSON object {} is passed to the next state.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 65

Page 69: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Example input and outputThe following is a typical workflow definition, which uses the five payload filters ofFunctionGraph:

{ "event-defs": { "event1": { "payload-filter-request": "$", "payload-filter-response": "$", "source": "urn:fgs:cn-north-1:d442abb5ca1f42038cc42f710df474b1:trigger:Worker_WorkRequest_WorkRequestada13521-3e05-4f75-50d1-09b5fb110481_1512455691" } }, "states": { "eventState": { "type": "EVENT", "start": true, "payload-filter-in": "$", "payload-filter-out": "$", "events": [{ "event-expression": "event1", "action-mode": "SEQUENTIAL", "actions": [{ "action-name": "action1", "function": "urn:fss:cn-north-1:d442abb5ca1f42038cc42f710df474b1:function:default:demo", "invocation-mode": "SYNC", "payload-filter": "$" }, { "action-name": "action2", "function": "urn:fss:cn-north-1:d442abb5ca1f42038cc42f710df474b1:function:default:demo", "invocation-mode": "SYNC", "payload-filter": "$" }], "next-state": "end" }] }, "end": { "type": "END" } }}

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 66

Page 70: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Figure 4-2 Data filtering of a typical workflow

payload-filter-in: Filters the data passed to a state.

payload-filter-out: Filters the data output from a state.

payload-filter: Filters the data passed to a state as well as the execution result of an action.

payload-filter-request: Filters the data input from an event source.

payload-filter-response: Filters the data returned to an event source.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 67

Page 71: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

The workflow has the following data relationships:

J2=payload-filter-in(J1)

J4=payload-filter-request(J2, J3)

J6=payload-filter(J2, J5)

J8=payload-filter(J2, J7)

J9=payload-filter-response(J2, J8)

J10=payload-filter-out(J8)

Examples of payload-filter-in and payload-filter-out

The following examples are based on payload-filter-in, of which the input and outputbehavior also applies to those of payload-filter-out.

Example 1:

input:

{ "foo" : "foo", "bar" : 10, "baz" : true}

Path Result

payload-filter-in:"$" { "foo": "foo", "bar": 10, "baz": true}

payload-filter-in:null {}

Example 2:

input: { "key": { "key1": 1 }, "input": "2"}

Path Result

payload-filter-in:"$.key" { "key1": 1}

payload-filter-in:"$.foo1" An error indicating invalid path occurs.

Examples of payload-filter-request, payload-filter-response, and payload-filter

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 68

Page 72: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

The following examples are based on payload-filter-request, of which the input and outputbehavior also applies to those of payload-filter-response and payload-filter.

Example 1:

input:{ "foo": "foo", "bar": 10, "baz": true}result:{ "result": "12345"}

Path Result

Adds the input to the result:payload-filter-request: "$.x.y"

{ "result": "12345", "x": { "y": { "foo": "foo", "bar": 10, "baz": true } }}

Overwrites the result with the input:payload-filter-request:"$.result"

{ "result": { "foo": "foo", "bar": 10, "baz": true }}

Example 2:

input: { "foo": "foo", "bar": 10, "baz": true}result: { "input": 1}

Path Result

payload-filter-request:"$[1]"

[ { "key": 1 }, { "input": "1234567" }]

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 69

Page 73: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Path Result

payload-filter-request:"$[0]"

[ { "input": "1234567" }]

Example 3:

input: { "foo": "foo", "bar": 10, "baz": true}result: { "input": 1}

Path Result

payload-filter-request: "$" { "input": 1}

payload-filter-request:null { "foo": "foo", "bar": 10, "baz": true}

payload-filter-request:"$.foo1.key" { "input": 1, "foo1": { "key": { "foo": "foo", "bar": 10, "baz": true } }}

Example 4:

input: { "foo": "foo", "bar": 10, "baz": true}result: null

Path Result

payload-filter-request:"$.foo" Error

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 70

Page 74: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Example 5:

input: { "key": { "key1": "1" }, "input": "2"}result: { "input": 1}

Path Result

payload-filter-request:"$.key" { "input": 1, "key": { "key": { "key1": "1" }, "input": "2" }}

Example 6:

input: { "key": { "key1": "1" }, "input": "2"}result: "2"

Path Result

payload-filter-request:"$.key1" Error

Example 7:

input: { "foo": "foo", "bar": 10, "baz": true}result: { "result": "12345"}

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 71

Page 75: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Path Result

payload-filter-request:"$.x.y.z" { "result": "12345", "x": { "y": { "z": { "foo": "foo", "bar": 10, "baz": true } } }}

Example 8:

input: { "result": "12345"}result: { "key": { "foo": 1 }}

Path Result

payload-filter-request:"$.key.foo" { "key": { "foo": { "result": "12345" } }}

Example 9:

input: { "result": "1234567"}result: [{ "key": 1}]

Path Result

payload-filter-request:"$[0]" [{ "input": "1234567"}]

payload-filter-request:"$[1]" [{ "key": 1}, { "input": "1234567"}]

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 72

Page 76: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Path Result

payload-filter-request"$[1][0][0]" [{ "key": 1 }, [ [{ "input": "1234567" }] ]]

Example 10:

input: { "input": "1234567"}result: { "key": 1}

Path Result

payload-filter-request:"$.a[0]" { "key": 1, "a": [{ "input": "1234567" }]}

payload-filter-request:"$.b[1]" Error

payload-filter-request:"$.a[0][0]" { "key": 1, "a": [ [{ "input": "1234567" }] ]}

Example 11:

input: { "input": "1234567"}result: [{ "key": 1}]

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 73

Page 77: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Path Result

payload-filter-request:"$[1].x" [{ "key": 1}, { "x": { "input": "1234567" }}]

payload-filter-request:"$.x[0]" Error

Filtering Rules for Event Messages

Table 4-15 Filtering rules for event messages

EventMessage Mode

ActionsInvolved

Action Mode Filtering Rule

Synchronous

No - The input (filtered by payload-filter-in) of theprevious step and external EventPush input arefiltered by payload-filter-request to use as both theinput of the next state and the EventPush output.

Synchronous

Yes Synchronousand sequential/parallel

The path rules are followed.

Synchronous

Yes Asynchronousand parallel

The result combined with the input of the previousstate is used as the input of the next state. The result{} is returned for event message triggering.

Asynchronous

No - The input of the previous step and the externalEventPush input are filtered by payload-filter-request to use as the input of the next state. Theresult {} is returned for event message triggering.

Asynchronous

Yes Synchronousand sequential/parallel

Internal state transitions follow the path rules. Theresult {} is returned for event message triggering.

Asynchronous

Yes Asynchronousand parallel

The result combined with the input of the previousstate is used as the input of the next state. The result{} is returned for event message triggering.

In an EVENT state, payload-filter-response is located after payload-filter, because multipleactions may be involved.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 74

Page 78: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

4.5 State Definition Examples

DELAY

The following is the definition of an example DELAY state:

{ "states": { "hello": { "type": "DELAY", "start": true, "time-delay": 2, "next-state": "next1" }, "next1": { "type": "NOOP", "next-state": "end1" }, "end1": { "type": "END" } }}

SWITCH

The following is the definition of an example SWITCH state:

{ "states": { "hello": { "type": "SWITCH", "start": true, "choices": [ { "path": "$.f", "value": "1", "next-state": "next1" }, { "path": "$.f", "value": "2", "next-state": "next2" } ], "default": "next1" }, "next1": { "type": "NOOP", "next-state": "end1" }, "next2": { "type": "NOOP", "next-state": "end1" }, "end1": { "type": "END" }

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 75

Page 79: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

}}

OPERATION

The following is the definition of an example OPERATION state:

{ "states": { "hello": { "type": "NOOP", "start": true, "next-state": "taskState" }, "taskState": { "type": "OPERATION", "action-mode": "SEQUENTIAL", "actions": [ { "action-name": "action1", "function": "urn:cff:cn_north_1:57f8fd63abc847ac8b52960d11185a15:function:default:FormationIdentificationliufen1234:latest", "invocation-mode": "SYNC", "results": [ { "match": "MatchAny", "retry-interval": 1, "max-retry": 3, "next-state": "next1" } ] }, { "action-name": "action2", "function": "urn:cff:cn_north_1:57f8fd63abc847ac8b52960d11185a15:function:default:FormationIdentificationliufen123:latest", "invocation-mode": "SYNC" } ], "next-state": "next1" }, "next1": { "type": "NOOP", "next-state": "end1" }, "end1": { "type": "END" } }}

EVENT

The following is the definition of an example EVENT state:

{ "event-defs": { "event1": { "payload-filter-request": "$.workItem",

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 76

Page 80: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

"source": "urn:serverless:southChina:7aad83af3e8d42e99ac194e8419e2c9b:event:Worker_WorkRequest_WorkReq-test_1502865866", "payload-filter-response": "$" }, "event2": { "payload-filter-request": "$", "source": "urn:serverless:region:proj0622:event:Worker_Heartbeat_0e96cdf5a72", "payload-filter-response": "$" }, "event3": { "payload-filter-request": "$", "source": "urn:serverless:region:proj0622:event:Worker_WorkSuccess_d0e96cdf5a73", "payload-filter-response": "$" }, "event4": { "payload-filter-request": "$", "source": "urn:serverless:region:proj0622:event:Worker_WorkFailure_0e96cdf5a74", "payload-filter-response": "$" } }, "states": { "eventState": { "payload-filter-in": "$", "payload-filter-out": "$", "type": "EVENT", "start": true, "events": [ { "event-expression": "event1", "action-mode": "SEQUENTIAL", "next-state": "eventState" }, { "event-expression": "event2", "action-mode": "SEQUENTIAL", "next-state": "eventState" }, { "event-expression": "event3", "action-mode": "SEQUENTIAL", "next-state": "next1" }, { "event-expression": "event4", "action-mode": "SEQUENTIAL", "next-state": "next1" } ] }, "next1": { "type": "NOOP", "next-state": "end1" }, "end1": { "type": "END" } }}

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 77

Page 81: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

4.6 Definition RestrictionsTable 4-16 lists the restrictions on workflow definition.

Table 4-16 Workflow definition restrictions

Type Field Restriction

Event definition event-defs l This field is optional,and is required onlywhen an EVENT stateexists.

l An event definition mustcontain source, whichindicates a unique eventURN.

l An event name is a stringof 1–80 characters.Only letters, digits,hyphens (-), andunderscores (_) areallowed.

l A workflow can have amaximum of 50 events.

State definition - l Must contain type,which can be EVENT,NOOP, DELAY,SWITCH,OPERATION, or END.

l A state name is a stringof 1–80 characters.Only letters, digits,hyphens (-), andunderscores (_) areallowed.

State type NOOP l Must contain next-state,which specifies the nameof a state that is includedin the workflowdefinition.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 78

Page 82: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Type Field Restriction

DELAY l Must have the time-delay attribute. Thevalue of this attributemust be an integergreater than 0. Themaximum value is86400.

l Must contain next-state,which specifies the nameof a state that is includedin the workflowdefinition.

SWITCH l Must contain default,which specifies the nameof a state that is includedin the workflowdefinition.

l Must contain choiceswhose size is greaterthan 0. next-state inchoices must specify thename of a state that isincluded in the workflowdefinition.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 79

Page 83: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Type Field Restriction

OPERATION l action-mode is optional.It can be set toPARALLEL orSEQUENTIAL. Thedefault value isSEQUENTIAL.

l Must contain actionswhose size is greaterthan 0.

l Must contain action-name, which specifies aunique action name. Anaction name is a string of1–80 characters. Onlyletters, digits, hyphens(-), and underscores (_)are allowed.

l Must contain function.Only letters, digits,hyphens (-), underscores(_), colons (:), andexclamation marks (!)are allowed.

l invocation-mode isoptional. It can be set toSYNC or ASYNC. Thedefault value is SYNC.

l results is optional withsize greater than or equalto 0. Each member ofresults must containnext-state and match.next-state must specifythe name of a state that isincluded in the workflowdefinition. match mustbe a non-empty string. Inaddition, retry-intervalis optional with sizegreater than or equal to0. max-retry is optionaland can be an integerwithin 0 and 10. Thedefault value is 3.

l next-state is requiredand must specify thename of a state that is

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 80

Page 84: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Type Field Restriction

included in the workflowdefinition.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 81

Page 85: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Type Field Restriction

EVENT l Must contain eventswhose size is greaterthan 0.

l Each event in eventsmust contain event-expression, whichspecifies the name of anevent that is included inthe event definition. Theevent name must beunique in a workflow.

l action-mode is optional.It can be set toPARALLEL orSEQUENTIAL. Thedefault value isSEQUENTIAL.

l actions is optional withsize less than 10.

l Must contain action-name, which specifies aunique action name. Anaction name is a string of1–80 characters. Onlyletters, digits, hyphens(-), and underscores (_)are allowed.

l Must contain function.Only letters, digits,hyphens (-), underscores(_), colons (:), andexclamation marks (!)are allowed.

l invocation-mode isoptional. It can be SYNCor ASYNC. The defaultvalue is SYNC.

l results is optional withsize greater than or equalto 0. Each member ofresults must containnext-state and match.next-state must specifythe name of a state that isincluded in the workflowdefinition. match mustbe a non-empty string. Inaddition, retry-interval

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 82

Page 86: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Type Field Restriction

is optional with sizegreater than or equal to0. max-retry is optionaland can be an integerwithin 0 and 10. Thedefault value is 3.

l next-state is requiredand must specify thename of a state that isincluded in the workflowdefinition.

Others - l Must contain only onestate whose startparameter is true.

l Must contain only oneEND state.

l Must contain states.

EVENT l If action-mode is set toSEQUENTIAL,invocation-mode mustbe set to SYNC for allactions.

l Under the same event-expression, the values ofinvocation-mode mustbe consistent for allactions.

OPERATION l If action-mode is set toSEQUENTIAL,invocation-mode mustbe set to SYNC for allactions.

l The values ofinvocation-mode mustbe consistent for allactions.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 83

Page 87: Developer Guide · API Gateway is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With API Gateway, your function can be invoked through

Type Field Restriction

- l payload-filter-request,payload-filter-response,and payload-filter areoptional. They can benull, or specify a singleitem, that is, as a definitepath. The threeparameters can be set inthe format of $.x insteadof $.['x'] to specify anitem in an object.

- l Only next-state of anEVENT state or that inresults of a state can bethe state itself. next-stateof a SWITCH, DELAY,or NOOP state or of anOPERATION statecannot be the state itself.

- l A workflow definitioncan contain only onecommon eventStatefield, and the eventsarray can have only oneevent member. One ormore worker events areallowed, but cannotcoexist with a commonevent.

FunctionGraphDeveloper Guide 4 Workflow Definition

Issue 04 (2018-08-29) Copyright © Huawei Technologies Co., Ltd. 84