Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/cli-reference/invoke-local.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ osls invoke local --function functionName

**Note:** Please refer to [this guide](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-input-format) for event data passing when your function uses the `http` event with a Lambda Proxy integration.

**Note:** This command is not supported for [web functions](../guides/web-functions.md). A web function is a plain HTTP server: start it with Node.js instead.
**Note:** This command is not supported for [web functions](../guides/web-functions.md). A web function is a plain HTTP server or a Python application: start the server with Node.js, or serve the application with an ASGI or WSGI server, instead.

## Options

Expand Down
2 changes: 1 addition & 1 deletion docs/guides/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ In-depth guides for building, testing, deploying, and operating services with os
- [AWS Lambda Events](events.md) — Wiring event sources (HTTP, schedule, queues, streams, and more) to functions.
- [IAM Permissions For Functions](iam.md) — Granting functions the permissions they need via IAM roles and policies.
- [AWS Lambda Layers](layers.md) — Publishing and consuming Lambda layers.
- [AWS Lambda Web Functions](web-functions.md) — Deploying Node.js HTTP servers that Lambda serves through their own HTTPS endpoint.
- [AWS Lambda Web Functions](web-functions.md) — Deploying Node.js HTTP servers and Python applications that Lambda serves through their own HTTPS endpoint.
- [AWS Infrastructure Resources](resources.md) — Adding raw CloudFormation resources and outputs to a service.
- [Packaging](packaging.md) — Controlling what code and dependencies are bundled into the deployment artifact.
- [Variables](variables.md) — Using `${...}` variable sources to keep configuration DRY.
Expand Down
5 changes: 3 additions & 2 deletions docs/guides/serverless.yml.md
Original file line number Diff line number Diff line change
Expand Up @@ -1466,13 +1466,14 @@ Deploy [Lambda web functions](./web-functions.md), HTTP servers with their own H
webFunctions:
# A Lambda web function
api:
# optional, the file that starts the HTTP server (default: index.js)
# optional, the file that starts the HTTP server (default: index.js),
# or the module and name of a Python application (default: main:app)
entryPoint: src/server.js
# optional, Deployed Lambda web function name (default: <service>-<stage>-<key>)
name: ${sls:stage}-webFunctionName
# optional, Description to publish to AWS
description: Description of what the web function does
# optional, nodejs24.x or nodejs26.x (default: nodejs26.x)
# optional, nodejs24.x, nodejs26.x or python3.15 (default: nodejs26.x)
runtime: nodejs26.x
# optional, request timeout in seconds, between 3 and 900 (default: 30, set by Lambda)
timeout: 30
Expand Down
62 changes: 54 additions & 8 deletions docs/guides/web-functions.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
# AWS Lambda Web Functions

[AWS Lambda Web Functions](https://docs.aws.amazon.com/lambda/latest/dg/web-functions.html) run a Node.js HTTP server on AWS Lambda. Instead of exporting a handler that receives events, your code starts a server and Lambda sends HTTPS requests to it through an endpoint with its own URL. No API Gateway, function URL or adapter is involved.
[AWS Lambda Web Functions](https://docs.aws.amazon.com/lambda/latest/dg/web-functions.html) run an HTTP server on AWS Lambda. Instead of exporting a handler that receives events, your code starts a Node.js server, or is a Python application that Lambda serves, and Lambda sends HTTPS requests to it through an endpoint with its own URL. No API Gateway, function URL or adapter is involved.

Web functions are configured under the top-level `webFunctions` property.

## Contents

- [Configuration](#configuration)
- [The server](#the-server)
- [Python applications](#python-applications)
- [Endpoint](#endpoint)
- [Multi-Region endpoints](#multi-region-endpoints)
- [Custom domains and CloudFront](#custom-domains-and-cloudfront)
Expand Down Expand Up @@ -43,7 +44,7 @@ webFunctions:
entryPoint: src/server.js # optional, the file that starts the server (default: index.js)
name: ${sls:stage}-api # optional, deployed name (default: <service>-<stage>-<key>)
description: Storefront API # optional, up to 256 characters
runtime: nodejs26.x # optional, nodejs24.x or nodejs26.x (default: nodejs26.x)
runtime: nodejs26.x # optional, nodejs24.x, nodejs26.x or python3.15 (default: nodejs26.x)
timeout: 30 # optional, in seconds, between 3 and 900 (Lambda's default: 30)
maxConcurrencyPerEnvironment: 64 # optional, between 1 and 128 (Lambda's default: 64)
environment: # optional, merged over provider.environment
Expand Down Expand Up @@ -80,7 +81,7 @@ Properties of functions such as `handler`, `events`, `memorySize`, `layers` or `

## The server

Lambda sets the `AWS_LAMBDA_HTTP_ENDPOINT` environment variable to the `host:port` the server has to listen on, and the server has to be listening there within 10 seconds of its start. When it listens somewhere else, for example on `localhost` or on `PORT`, or starts listening too late, requests to the endpoint fail with status 502.
A Node.js web function starts its own HTTP server. Lambda sets the `AWS_LAMBDA_HTTP_ENDPOINT` environment variable to the `host:port` the server has to listen on, and the server has to be listening there within 10 seconds of its start. When it listens somewhere else, for example on `localhost` or on `PORT`, or starts listening too late, requests to the endpoint fail with status 502.

```js
// index.js
Expand Down Expand Up @@ -110,6 +111,43 @@ webFunctions:

`entryPoint` is the only way to name the entry file. osls passes it to Lambda in the `AWS_LAMBDA_NODEJS_ENTRYPOINT` environment variable, and rejects that variable in `environment` and in `provider.environment`. Lambda does not read the entry file from `package.json`, and it reports a deployment as successful even when the entry file is missing. For that reason `osls package` and `osls deploy` fail when the package does not contain the entry file, also when it is a [zip you built yourself](#packaging).

## Python applications

Lambda offers the `python3.15` runtime for web functions as a public preview. It is not covered by the Lambda SLA or AWS Support, AWS recommends against using it for production workloads, and its behavior can still change.

A Python web function is an ASGI or WSGI application and not a server: Lambda runs the HTTP server and calls the application, which does not use `AWS_LAMBDA_HTTP_ENDPOINT`. Set `runtime`, because web functions do not use `provider.runtime`:

```yaml
webFunctions:
api:
runtime: python3.15
```

```python
# main.py
import json


def app(environ, start_response):
start_response('200 OK', [('Content-Type', 'application/json')])
return [json.dumps({'message': 'Hello from a web function'}).encode()]
```

Lambda imports the `main` module at the root of the package and serves its `app`. Set `entryPoint` to serve another application. It is the module and the name of the application in it, separated by a colon, with the module written without the `.py` extension:

```yaml
webFunctions:
api:
runtime: python3.15
entryPoint: src.api:application # "application" in src/api.py
```

The module can be a dotted path to a file or to a package, and the name can be a dotted path to an attribute, but not a call such as `create_app()`. Lambda detects whether the application uses ASGI or WSGI. Prefix `entryPoint` with `asgi:` or `wsgi:`, in lower case, to choose one, as in `asgi:src.api:application`.

osls passes `entryPoint` to Lambda in the `AWS_LAMBDA_PYTHON_ENTRYPOINT` environment variable, and rejects that variable in `environment` and in `provider.environment`. Lambda reports a deployment as successful even when it cannot import the application, and then answers every request with status 502. For that reason `osls package` and `osls deploy` fail when the root of the package contains neither the file nor the package of the module, which for `src.api` are `src/api.py` and `src/api/__init__.py`.

Unlike the Python runtime of functions, this runtime does not include `boto3`. See [Packaging](#packaging) for the dependencies of the application.

## Endpoint

Every web function gets one endpoint, named `main` unless `endpoint.name` says otherwise, in the region of the service. Its URL is printed at the end of `osls deploy` and by `osls info`. It is also the `<Key>WebFunctionUrl` output of the stack, which other stacks import as `sls-<service>-<stage>-<Key>WebFunctionUrl` (`sls-myService-dev-ApiWebFunctionUrl` for the `api` web function above).
Expand Down Expand Up @@ -316,6 +354,14 @@ An entry file that is an ES module needs the `package.json` with `"type": "modul

The package has to contain everything the server needs at runtime, including `node_modules`. osls does not bundle or compile code. Native modules have to be built for Linux on arm64. A package can be up to 512 MiB once unzipped.

The package of a Python web function has to contain the dependencies of the application at its root, next to the module of `entryPoint`, built for Linux on arm64 and for Python 3.15. osls does not install them. Install them into the directory of the service, or into the directory you build the zip of `package.artifact` from:

```bash
pip install --target . --platform manylinux2014_aarch64 --python-version 3.15 --only-binary=:all: -r requirements.txt
```

Exclude directories such as `.venv` and `__pycache__` with `package.patterns`: they are not needed, and a change to them gives the web function a new revision.

To deploy a zip built by another tool, set `package.artifact` of the web function to its local path, instead of `patterns`. The zip is deployed as it is and `patterns` are ignored. Packaging fails when the file is not a zip or does not contain the entry file. An artifact hosted on S3 is not supported.

```yaml
Expand Down Expand Up @@ -376,7 +422,7 @@ See [Encryption at rest for Web Functions](https://docs.aws.amazon.com/lambda/la
`environment` works like the [environment of a function](./functions.md#environment-variables) and is merged over `provider.environment`. Lambda is stricter with web functions, and osls reports each of the following when packaging:

- The following names are reserved: `AWS_ACCESS_KEY`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SECRET_KEY`, `AWS_SECURITY_TOKEN`, `AWS_SESSION_TOKEN`, `AWS_DEFAULT_REGION`, `AWS_REGION`, `AWS_LAMBDA_HTTP_ENDPOINT`, `AWS_LAMBDA_RUNTIME_API`, `AWS_LAMBDA_INITIALIZATION_TYPE`, `AWS_LAMBDA_FUNCTION_MEMORY_SIZE`, `AWS_LAMBDA_METADATA_API` and `AWS_LAMBDA_METADATA_TOKEN`.
- `AWS_LAMBDA_NODEJS_ENTRYPOINT` is set with [`entryPoint`](#the-server).
- `AWS_LAMBDA_NODEJS_ENTRYPOINT` and `AWS_LAMBDA_PYTHON_ENTRYPOINT` are set with [`entryPoint`](#the-server).
- A name has to start with a letter.
- A value cannot be an empty string or have more than 4,096 characters, and all names and values together cannot exceed 32 KB.

Expand Down Expand Up @@ -430,7 +476,7 @@ Prefer the default [deployment mode](./deploying.md#deployment-mode) where a suc
| [`osls deploy function`](../cli-reference/deploy-function.md) | Not supported, use `osls deploy` |
| [`osls rollback function`](../cli-reference/rollback-function.md) | Not supported, use `osls rollback` |
| [`osls invoke`](../cli-reference/invoke.md) | Not supported, send a request to the URL |
| [`osls invoke local`](../cli-reference/invoke-local.md) | Not supported, start the server with Node.js |
| [`osls invoke local`](../cli-reference/invoke-local.md) | Not supported, run the server or the application yourself |
| [`osls metrics`](../cli-reference/metrics.md) | Not supported, web functions are left out |

## Generated resources
Expand Down Expand Up @@ -521,12 +567,12 @@ The function arn:aws:lambda:us-east-2:123456789012:web-function/myService-dev-ap

**The deployment fails on the revision with "does not have s3:GetObject and s3:GetObjectVersion permission".** The policy of an existing deployment bucket does not let Lambda read the code, see [Existing bucket](#existing-bucket). If this was the first deployment of the service, the stack can be left in the `ROLLBACK_COMPLETE` state: run `osls remove` before deploying again.

**Every request fails with status 502 after a successful deployment.** The server did not start, or does not listen on the `host:port` of `AWS_LAMBDA_HTTP_ENDPOINT`, see [The server](#the-server). `osls logs` shows the error.
**Every request fails with status 502 after a successful deployment.** The server did not start, or does not listen on the `host:port` of `AWS_LAMBDA_HTTP_ENDPOINT`, see [The server](#the-server). `osls logs` shows the error. A Python web function answers with the header `lambda-web-error-type: Runtime.ImportCodeError` when Lambda cannot import the application, see [Python applications](#python-applications).

**Every request fails with status 409 and the header `lambda-web-error-type: Platform.RevisionNotActive`.** The zip of the revision is gone from the deployment bucket, see [Where the code is stored](#where-the-code-is-stored).

## Limitations

- Only the `nodejs24.x` and `nodejs26.x` runtimes are supported, and Lambda does not offer web functions in every region.
- Only the `nodejs24.x`, `nodejs26.x` and `python3.15` runtimes are supported, the last one as a public preview, and Lambda does not offer web functions in every region.
- One endpoint per web function. Several endpoints and shifting traffic gradually between revisions are not supported.
- No local emulation. The server is a plain Node.js HTTP server, so run it with `AWS_LAMBDA_HTTP_ENDPOINT=127.0.0.1:3000 node index.js`.
- No local emulation. The server is a plain Node.js HTTP server, so run it with `AWS_LAMBDA_HTTP_ENDPOINT=127.0.0.1:3000 node index.js`. A Python application runs under any ASGI or WSGI server.
7 changes: 6 additions & 1 deletion lib/plugins/aws/invoke-local/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,13 @@ class AwsInvokeLocal {
async extendedValidate() {
this.validate();
if (this.serverless.service.getAllWebFunctions().includes(this.options.function)) {
const { runtime } = this.serverless.service.getWebFunction(this.options.function);
throw new ServerlessError(
`Web function "${this.options.function}" cannot be invoked with "serverless invoke local". Start its server with Node.js instead.`,
`Web function "${this.options.function}" cannot be invoked with "serverless invoke local". ${
this.provider.getWebFunctionLanguage(runtime) === 'python'
? 'Serve its application with an ASGI or WSGI server instead.'
: 'Start its server with Node.js instead.'
}`,
'WEB_FUNCTION_INVOKE_LOCAL_UNSUPPORTED'
);
}
Expand Down
37 changes: 29 additions & 8 deletions lib/plugins/aws/package/compile/web-functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@ const maxNameLength = 64;
const kmsKeyArnPattern = /^arn:[^:]+:kms:[^:]*:[^:]*:key\//;

const environmentVariableNamePattern = /^[a-zA-Z][a-zA-Z0-9_]*$/;
const entryPointEnvironmentVariable = 'AWS_LAMBDA_NODEJS_ENTRYPOINT';
const entryPointEnvironmentVariables = {
nodejs: 'AWS_LAMBDA_NODEJS_ENTRYPOINT',
python: 'AWS_LAMBDA_PYTHON_ENTRYPOINT',
};
const pythonEntryPointPattern =
/^((asgi|wsgi):)?[A-Za-z_]\w*(\.[A-Za-z_]\w*)*:[A-Za-z_]\w*(\.[A-Za-z_]\w*)*$/;
const reservedEnvironmentVariables = new Set([
'AWS_ACCESS_KEY',
'AWS_ACCESS_KEY_ID',
Expand Down Expand Up @@ -121,26 +126,37 @@ class AwsCompileWebFunctions {
}
webFunctionNamesByName.set(webFunctionObject.name, webFunctionName);

const { entryPoint, kmsKeyArn } = webFunctionObject;
const { entryPoint, kmsKeyArn, runtime } = webFunctionObject;
if (entryPoint) {
const isPython = this.provider.getWebFunctionLanguage(runtime) === 'python';
let entryPointProblem;
if (typeof entryPoint !== 'string') {
entryPointProblem = 'is not a string';
} else if (isPython) {
if (!pythonEntryPointPattern.test(entryPoint)) {
entryPointProblem = /\.py(:|$)/.test(entryPoint)
? 'names a file with the ".py" extension'
: 'is not of the "module:callable" form';
}
} else if (path.posix.isAbsolute(entryPoint) || path.win32.isAbsolute(entryPoint)) {
entryPointProblem = 'is an absolute path';
} else if (entryPoint.includes('\\')) {
entryPointProblem = 'contains a backslash';
} else if (
this.provider
.getWebFunctionEntryPoint(entryPoint)
.getWebFunctionEntryPoint(entryPoint, runtime)
.split('/')
.some((segment) => segment === '.' || segment === '..')
) {
entryPointProblem = 'contains a "." or ".." segment';
}
if (entryPointProblem) {
throw new ServerlessError(
`Web function "${webFunctionName}" has an invalid "entryPoint": it ${entryPointProblem}. Set it to the path of the file relative to the root of the package, written with forward slashes and without "." or ".." segments, for example "src/server.js".`,
`Web function "${webFunctionName}" has an invalid "entryPoint": it ${entryPointProblem}. ${
isPython
? 'Set it to the module that holds the application and the name of the application in it, for example "src.api:application" for "application" in "src/api.py".'
: 'Set it to the path of the file relative to the root of the package, written with forward slashes and without "." or ".." segments, for example "src/server.js".'
}`,
'WEB_FUNCTION_INVALID_ENTRY_POINT'
);
}
Expand All @@ -157,7 +173,7 @@ class AwsCompileWebFunctions {
for (const [variableName, value] of Object.entries(
this.resolveEnvironment(webFunctionObject)
)) {
if (variableName === entryPointEnvironmentVariable) {
if (Object.values(entryPointEnvironmentVariables).includes(variableName)) {
throw new ServerlessError(
`Web function "${webFunctionName}" sets the "${variableName}" environment variable. Set "entryPoint" on the web function instead, and remove the variable from "environment" and from "provider.environment".`,
'WEB_FUNCTION_ENTRY_POINT_ENVIRONMENT_VARIABLE_DEFINED'
Expand Down Expand Up @@ -331,9 +347,14 @@ class AwsCompileWebFunctions {
}

const environment = this.resolveEnvironment(webFunctionObject);
const entryPoint = this.provider.getWebFunctionEntryPoint(webFunctionObject.entryPoint);
if (entryPoint !== this.provider.getWebFunctionEntryPoint()) {
environment[entryPointEnvironmentVariable] = entryPoint;
const { runtime } = webFunctionObject;
const entryPoint = this.provider.getWebFunctionEntryPoint(
webFunctionObject.entryPoint,
runtime
);
if (entryPoint !== this.provider.getWebFunctionEntryPoint(undefined, runtime)) {
environment[entryPointEnvironmentVariables[this.provider.getWebFunctionLanguage(runtime)]] =
entryPoint;
}
if (Object.keys(environment).length) {
serviceConfig.EnvironmentVariables = environment;
Expand Down
Loading