Skip to main content

Function

The cloud.Function resource represents a serverless function for performing short, stateless tasks. Functions are typically used to run business logic in response to events, such as a file being uploaded to a bucket, a message being pushed to a queue, or a timer expiring.

When a function is invoked on a cloud provider, it is typically executed in a container/host which is provisioned on demand.

Functions may be invoked more than once, and some cloud providers may automatically retry failed invocations. For performance reasons, most cloud providers impose a timeout on functions, after which the function is automatically terminated.

Usage

A function can be invoked in two ways:

  • invoke() - Executes the function with a payload and waits for the result.
  • invokeAsync() - Kicks off the execution of the function with a payload and returns immediately while the function is running.
bring cloud;
bring util;

// defining a cloud.Function resource
let countWords = new cloud.Function(inflight (s: str): str => {
return "${s.split(" ").length}";
}) as "countWords";

let longTask = new cloud.Function(inflight () => {
util.sleep(30s);
log("done!");
});

new cloud.Function(inflight () => {
let sentence = "I am a sentence with 7 words";
// invoking cloud.Function from inflight context
let wordsCount = countWords.invoke(sentence);
log("'${sentence}' has ${wordsCount} words");

longTask.invokeAsync("");
log("task started");
}) as "Invoke Me";

Function container reuse

Most cloud providers will opportunistically reuse the function's container in additional invocations. It is possible to leverage this behavior to cache objects across function executions using inflight new and inflight fields.

The following example reads the bigdata.json file once and reuses it every time query() is called.

bring cloud;

let big = new cloud.Bucket();

big.addObject("bigdata.json", Json.stringify({
"my-key": "my-value"
}));

class MyDatabase {
inflight bigdata: Json;
inflight new() {
// download big data once
this.bigdata = big.getJson("bigdata.json");
}

pub inflight query(key: str): Json {
return this.bigdata.get(key);
}
}

let db = new MyDatabase();

new cloud.Function(inflight () => {
log(Json.stringify(db.query("my-key")));
});

Target-specific details

Simulator (sim)

The sim implementation of cloud.Function runs the inflight code as a JavaScript function.

AWS (tf-aws and awscdk)

The AWS implementation of cloud.Function uses AWS Lambda.

To add extra IAM permissions to the function, you can use the aws.Function class as shown below.

bring aws;
bring cloud;

let f = new cloud.Function(inflight () => {
log("Hello world!");
});
if let lambdaFn = aws.Function.from(f) {
lambdaFn.addPolicyStatements(
aws.PolicyStatement {
actions: ["ses:sendEmail"],
effect: aws.Effect.ALLOW,
resources: ["*"],
},
);
}

Azure (tf-azure)

The Azure implementation of cloud.Function uses Azure Functions.

🚧 invoke API is not supported yet (tracking issue: #1371)

GCP (tf-gcp)

🚧 Not supported yet (tracking issue: #614)

API Reference

Function

A function.

Initializers

bring cloud;

new cloud.Function(handler: IFunctionHandler, props?: FunctionProps);
NameTypeDescription
handlerIFunctionHandlerNo description.
propsFunctionPropsNo description.

handlerRequired

propsOptional

Methods

Preflight Methods
NameDescription
addEnvironmentAdd an environment variable to the function.
Inflight Methods
NameDescription
invokeInvokes the function with a payload and waits for the result.
invokeAsyncKicks off the execution of the function with a payload and returns immediately while the function is running.

addEnvironment
addEnvironment(name: str, value: str): void

Add an environment variable to the function.

nameRequired
  • Type: str

valueRequired
  • Type: str

invoke
inflight invoke(payload?: str): str

Invokes the function with a payload and waits for the result.

payloadOptional
  • Type: str

payload to pass to the function.

If not defined, an empty string will be passed.


invokeAsync
inflight invokeAsync(payload?: str): void

Kicks off the execution of the function with a payload and returns immediately while the function is running.

payloadOptional
  • Type: str

payload to pass to the function.

If not defined, an empty string will be passed.


Static Functions

NameDescription
onLiftTypeA hook called by the Wing compiler once for each inflight host that needs to use this type inflight.

onLiftType
bring cloud;

cloud.Function.onLiftType(host: IInflightHost, ops: MutArray<str>);

A hook called by the Wing compiler once for each inflight host that needs to use this type inflight.

The list of requested inflight methods needed by the inflight host are given by ops.

This method is commonly used for adding permissions, environment variables, or other capabilities to the inflight host.

hostRequired

opsRequired
  • Type: MutArray<str>

Properties

NameTypeDescription
nodeconstructs.NodeThe tree node.
envMutMap<str>Returns the set of environment variables for this function.

nodeRequired
node: Node;
  • Type: constructs.Node

The tree node.


envRequired
env: MutMap<str>;
  • Type: MutMap<str>

Returns the set of environment variables for this function.


Structs

FunctionProps

Options for Function.

Initializer

bring cloud;

let FunctionProps = cloud.FunctionProps{ ... };

Properties

NameTypeDescription
envMutMap<str>Environment variables to pass to the function.
logRetentionDaysnumSpecifies the number of days that function logs will be kept.
memorynumThe amount of memory to allocate to the function, in MB.
timeoutdurationThe maximum amount of time the function can run.

envOptional
env: MutMap<str>;
  • Type: MutMap<str>
  • Default: No environment variables.

Environment variables to pass to the function.


logRetentionDaysOptional
logRetentionDays: num;
  • Type: num
  • Default: 30

Specifies the number of days that function logs will be kept.

Setting negative value means logs will not expire.


memoryOptional
memory: num;
  • Type: num
  • Default: 1024

The amount of memory to allocate to the function, in MB.


timeoutOptional
timeout: duration;

The maximum amount of time the function can run.


Protocols

IFunctionHandler

Inflight client: @winglang/sdk.cloud.IFunctionHandlerClient

A resource with an inflight "handle" method that can be used to create a cloud.Function.

IFunctionHandlerClient

Inflight client for IFunctionHandler.

Methods

NameDescription
handleEntrypoint function that will be called when the cloud function is invoked.

handle
inflight handle(event?: str): str

Entrypoint function that will be called when the cloud function is invoked.

eventOptional
  • Type: str