diff --git a/docs/cli-reference/invoke-local.md b/docs/cli-reference/invoke-local.md index 20ed5bd61..79740c078 100644 --- a/docs/cli-reference/invoke-local.md +++ b/docs/cli-reference/invoke-local.md @@ -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 diff --git a/docs/guides/README.md b/docs/guides/README.md index c2f7c0f31..84ce66a6b 100644 --- a/docs/guides/README.md +++ b/docs/guides/README.md @@ -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. diff --git a/docs/guides/serverless.yml.md b/docs/guides/serverless.yml.md index d5c063166..0eb8afdbe 100644 --- a/docs/guides/serverless.yml.md +++ b/docs/guides/serverless.yml.md @@ -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: --) 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 diff --git a/docs/guides/web-functions.md b/docs/guides/web-functions.md index c24d1a662..3cb5b617c 100644 --- a/docs/guides/web-functions.md +++ b/docs/guides/web-functions.md @@ -1,6 +1,6 @@ # 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. @@ -8,6 +8,7 @@ Web functions are configured under the top-level `webFunctions` property. - [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) @@ -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: --) 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 @@ -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 @@ -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 `WebFunctionUrl` output of the stack, which other stacks import as `sls---WebFunctionUrl` (`sls-myService-dev-ApiWebFunctionUrl` for the `api` web function above). @@ -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 @@ -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. @@ -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 @@ -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. diff --git a/lib/plugins/aws/invoke-local/index.js b/lib/plugins/aws/invoke-local/index.js index 60b7ba80c..fa8c2926d 100644 --- a/lib/plugins/aws/invoke-local/index.js +++ b/lib/plugins/aws/invoke-local/index.js @@ -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' ); } diff --git a/lib/plugins/aws/package/compile/web-functions.js b/lib/plugins/aws/package/compile/web-functions.js index 451965579..6d073c3b7 100644 --- a/lib/plugins/aws/package/compile/web-functions.js +++ b/lib/plugins/aws/package/compile/web-functions.js @@ -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', @@ -121,18 +126,25 @@ 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 === '..') ) { @@ -140,7 +152,11 @@ class AwsCompileWebFunctions { } 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' ); } @@ -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' @@ -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; diff --git a/lib/plugins/aws/provider.js b/lib/plugins/aws/provider.js index 37096b231..7df3c494d 100644 --- a/lib/plugins/aws/provider.js +++ b/lib/plugins/aws/provider.js @@ -81,7 +81,7 @@ const constants = { const imageNamePattern = '^[a-z][a-z0-9-_]{1,31}$'; const defaultWebFunctionRuntime = 'nodejs26.x'; -const defaultWebFunctionEntryPoint = 'index.js'; +const defaultWebFunctionEntryPoints = { nodejs: 'index.js', python: 'main:app' }; const apiGatewayUsagePlan = { type: 'object', @@ -672,7 +672,7 @@ class AwsProvider { additionalProperties: false, required: ['securityGroupIds', 'subnetIds'], }, - awsLambdaWebFunctionRuntime: { enum: ['nodejs24.x', 'nodejs26.x'] }, + awsLambdaWebFunctionRuntime: { enum: ['nodejs24.x', 'nodejs26.x', 'python3.15'] }, awsLogicalResourceId: { type: 'string', pattern: '^[#A-Za-z0-9-_./]+[*]?$', @@ -1957,8 +1957,22 @@ class AwsProvider { return runtime || defaultWebFunctionRuntime; } - getWebFunctionEntryPoint(entryPoint) { - return (entryPoint && entryPoint.replace(/^\.\//, '')) || defaultWebFunctionEntryPoint; + getWebFunctionLanguage(runtime) { + return String(this.getWebFunctionRuntime(runtime)).startsWith('python') ? 'python' : 'nodejs'; + } + + getWebFunctionEntryPoint(entryPoint, runtime) { + if (this.getWebFunctionLanguage(runtime) === 'python') { + return entryPoint || defaultWebFunctionEntryPoints.python; + } + return (entryPoint && entryPoint.replace(/^\.\//, '')) || defaultWebFunctionEntryPoints.nodejs; + } + + getWebFunctionEntryFiles(entryPoint, runtime) { + const resolvedEntryPoint = this.getWebFunctionEntryPoint(entryPoint, runtime); + if (this.getWebFunctionLanguage(runtime) !== 'python') return [resolvedEntryPoint]; + const modulePath = resolvedEntryPoint.split(':').at(-2).replaceAll('.', '/'); + return [`${modulePath}.py`, `${modulePath}/__init__.py`]; } resolveWebFunctionEndpoint(endpoint) { diff --git a/lib/plugins/package/lib/package-service.js b/lib/plugins/package/lib/package-service.js index cf1b30e82..c3fbf3c02 100644 --- a/lib/plugins/package/lib/package-service.js +++ b/lib/plugins/package/lib/package-service.js @@ -223,9 +223,13 @@ module.exports = { const webFunctionObject = this.serverless.service.getWebFunction(webFunctionName); const webFunctionPackageConfig = webFunctionObject.package || {}; const zipFileName = `${webFunctionName}.web.zip`; - const entryPoint = this.serverless - .getProvider('aws') - .getWebFunctionEntryPoint(webFunctionObject.entryPoint); + const provider = this.serverless.getProvider('aws'); + const isPython = provider.getWebFunctionLanguage(webFunctionObject.runtime) === 'python'; + const entryFiles = provider.getWebFunctionEntryFiles( + webFunctionObject.entryPoint, + webFunctionObject.runtime + ); + const entryFilesText = entryFiles.map((entryFile) => `"${entryFile}"`).join(' or '); // a prebuilt artifact is copied, so every web function is deployed from the package path if (webFunctionPackageConfig.artifact) { @@ -258,9 +262,15 @@ module.exports = { 'INVALID_PACKAGE_ARTIFACT' ); } - if (!entryNames.includes(entryPoint)) { + if (!entryFiles.some((entryFile) => entryNames.includes(entryFile))) { throw new ServerlessError( - `Web function "${webFunctionName}" has no "${entryPoint}" file in its package artifact "${webFunctionPackageConfig.artifact}". Lambda loads this file to start the server, and without it every request fails. Set "entryPoint" to the file that starts the server, as a path relative to the root of the zip.`, + `Web function "${webFunctionName}" has no ${entryFilesText} file in its package artifact "${ + webFunctionPackageConfig.artifact + }". ${ + isPython + ? 'Lambda imports the application from this module, and without it every request fails. Set "entryPoint" to the module, without the ".py" extension, and the callable of the application, with the module at the root of the zip.' + : 'Lambda loads this file to start the server, and without it every request fails. Set "entryPoint" to the file that starts the server, as a path relative to the root of the zip.' + }`, 'WEB_FUNCTION_ENTRY_POINT_NOT_FOUND' ); } @@ -269,9 +279,13 @@ module.exports = { const filePaths = await this.resolveFilePathsWebFunction(webFunctionName); - if (!filePaths.includes(entryPoint)) { + if (!entryFiles.some((entryFile) => filePaths.includes(entryFile))) { throw new ServerlessError( - `Web function "${webFunctionName}" has no "${entryPoint}" file in its package. Lambda loads this file to start the server, and without it every request fails. Set "entryPoint" to the file that starts the server, and make sure "package.patterns" does not exclude it.`, + `Web function "${webFunctionName}" has no ${entryFilesText} file in its package. ${ + isPython + ? 'Lambda imports the application from this module, and without it every request fails. Set "entryPoint" to the module, without the ".py" extension, and the callable of the application, and make sure "package.patterns" does not exclude the module.' + : 'Lambda loads this file to start the server, and without it every request fails. Set "entryPoint" to the file that starts the server, and make sure "package.patterns" does not exclude it.' + }`, 'WEB_FUNCTION_ENTRY_POINT_NOT_FOUND' ); } diff --git a/test/fixtures/programmatic/web-function/main.py b/test/fixtures/programmatic/web-function/main.py new file mode 100644 index 000000000..c1921d223 --- /dev/null +++ b/test/fixtures/programmatic/web-function/main.py @@ -0,0 +1,6 @@ +import json + + +def app(environ, start_response): + start_response('200 OK', [('Content-Type', 'application/json')]) + return [json.dumps({'message': 'Basic'}).encode()] diff --git a/test/fixtures/programmatic/web-function/src/api.py b/test/fixtures/programmatic/web-function/src/api.py new file mode 100644 index 000000000..9b9876d38 --- /dev/null +++ b/test/fixtures/programmatic/web-function/src/api.py @@ -0,0 +1,10 @@ +import json + + +async def application(scope, receive, send): + await send({ + 'type': 'http.response.start', + 'status': 200, + 'headers': [(b'content-type', b'application/json')], + }) + await send({'type': 'http.response.body', 'body': json.dumps({'message': 'Api'}).encode()}) diff --git a/test/unit/lib/plugins/aws/package/compile/web-functions.test.js b/test/unit/lib/plugins/aws/package/compile/web-functions.test.js index 594342a20..8364cb2c2 100644 --- a/test/unit/lib/plugins/aws/package/compile/web-functions.test.js +++ b/test/unit/lib/plugins/aws/package/compile/web-functions.test.js @@ -49,6 +49,9 @@ describe('test/unit/lib/plugins/aws/package/compile/web-functions.test.js', () = perRegion: { endpoint: { type: 'PerRegion', regions: ['us-east-1', 'us-west-2'] } }, indexEntryPoint: { entryPoint: 'index.js' }, relativeEntryPoint: { entryPoint: './src/server.js' }, + python: { runtime: 'python3.15' }, + pythonEntryPoint: { runtime: 'python3.15', entryPoint: 'asgi:src.api:application' }, + pythonNameEndingInPy: { runtime: 'python3.15', entryPoint: 'main:holder.py' }, emptyEndpoint: { endpoint: { type: null, regions: null } }, roleArn: { role: roleArn }, roleLogicalId: { role: 'WebRole' }, @@ -202,6 +205,27 @@ describe('test/unit/lib/plugins/aws/package/compile/web-functions.test.js', () = ).to.deep.equal({ AWS_LAMBDA_NODEJS_ENTRYPOINT: 'src/server.js' }); }); + it('should support the `python3.15` runtime', () => { + const { Properties } = cfResources[naming.getWebFunctionRevisionLogicalId('python')]; + + expect(Properties.BuildConfig.RuntimeConfig).to.deep.equal({ Runtime: 'python3.15' }); + expect(Properties.ServiceConfig).to.not.have.property('EnvironmentVariables'); + }); + + it('should support a Python `webFunctions[].entryPoint`', () => { + expect( + cfResources[naming.getWebFunctionRevisionLogicalId('pythonEntryPoint')].Properties + .ServiceConfig.EnvironmentVariables + ).to.deep.equal({ AWS_LAMBDA_PYTHON_ENTRYPOINT: 'asgi:src.api:application' }); + }); + + it('should support a Python `webFunctions[].entryPoint` with a name that ends in `.py`', () => { + expect( + cfResources[naming.getWebFunctionRevisionLogicalId('pythonNameEndingInPy')].Properties + .ServiceConfig.EnvironmentVariables + ).to.deep.equal({ AWS_LAMBDA_PYTHON_ENTRYPOINT: 'main:holder.py' }); + }); + it('should support `webFunctions[].endpoint`', () => { const { Properties } = cfResources[naming.getWebFunctionEndpointLogicalId('configured')]; @@ -488,6 +512,41 @@ describe('test/unit/lib/plugins/aws/package/compile/web-functions.test.js', () = }); } + for (const [description, entryPoint, message] of [ + [ + 'a Python `entryPoint` that is a file', + 'src/api.py', + 'it names a file with the ".py" extension', + ], + [ + 'a Python `entryPoint` without a callable', + 'api', + 'it is not of the "module:callable" form', + ], + [ + 'a Python `entryPoint` that calls a factory', + 'api:create_app()', + 'it is not of the "module:callable" form', + ], + [ + 'a Python `entryPoint` with an upper-case prefix', + 'WSGI:api:application', + 'it is not of the "module:callable" form', + ], + ]) { + it(`should reject ${description}`, async () => { + await expect( + runServerless({ + fixture: 'web-function', + command: 'package', + configExt: { webFunctions: { basic: { runtime: 'python3.15', entryPoint } } }, + }) + ) + .to.eventually.be.rejectedWith(message) + .and.have.property('code', 'WEB_FUNCTION_INVALID_ENTRY_POINT'); + }); + } + it('should reject a `kmsKeyArn` that is the ARN of an alias', async () => { await expect( runServerless({ @@ -684,21 +743,22 @@ describe('test/unit/lib/plugins/aws/package/compile/web-functions.test.js', () = .and.have.property('code', 'WEB_FUNCTION_ENVIRONMENT_TOO_LARGE'); }); - it('should reject the environment variable that `entryPoint` sets', async () => { - await expect( - runServerless({ - fixture: 'web-function', - command: 'package', - configExt: { - webFunctions: { - basic: { environment: { AWS_LAMBDA_NODEJS_ENTRYPOINT: 'src/server.js' } }, - }, - }, - }) - ) - .to.eventually.be.rejectedWith('Set "entryPoint" on the web function instead') - .and.have.property('code', 'WEB_FUNCTION_ENTRY_POINT_ENVIRONMENT_VARIABLE_DEFINED'); - }); + for (const [variableName, value] of [ + ['AWS_LAMBDA_NODEJS_ENTRYPOINT', 'src/server.js'], + ['AWS_LAMBDA_PYTHON_ENTRYPOINT', 'src.api:application'], + ]) { + it(`should reject the \`${variableName}\` environment variable that \`entryPoint\` sets`, async () => { + await expect( + runServerless({ + fixture: 'web-function', + command: 'package', + configExt: { webFunctions: { basic: { environment: { [variableName]: value } } } }, + }) + ) + .to.eventually.be.rejectedWith('Set "entryPoint" on the web function instead') + .and.have.property('code', 'WEB_FUNCTION_ENTRY_POINT_ENVIRONMENT_VARIABLE_DEFINED'); + }); + } it('should reject `endpoint.regions` on a `HomeRegion` endpoint', async () => { await expect( diff --git a/test/unit/lib/plugins/package/lib/package-service.test.js b/test/unit/lib/plugins/package/lib/package-service.test.js index 761873170..74bbc0265 100644 --- a/test/unit/lib/plugins/package/lib/package-service.test.js +++ b/test/unit/lib/plugins/package/lib/package-service.test.js @@ -402,9 +402,15 @@ describe('test/unit/lib/plugins/package/lib/packageService.test.js', () => { ).to.deep.equal(await fsp.readFile(path.join(serviceDir, 'artifact-function.zip'))); }); - for (const [description, webFunction, entryPoint] of [ - ['`index.js`', { package: { patterns: ['!index.js'] } }, 'index.js'], - ['the `entryPoint`', { entryPoint: 'dir2/server.js' }, 'dir2/server.js'], + for (const [description, webFunction, entryFiles] of [ + ['`index.js`', { package: { patterns: ['!index.js'] } }, '"index.js"'], + ['the `entryPoint`', { entryPoint: 'dir2/server.js' }, '"dir2/server.js"'], + ['`main.py`', { runtime: 'python3.15' }, '"main.py" or "main/__init__.py"'], + [ + 'the module of the Python `entryPoint`', + { runtime: 'python3.15', entryPoint: 'dir2.api:application' }, + '"dir2/api.py" or "dir2/api/__init__.py"', + ], ]) { it(`should reject a package without ${description}`, async () => { await expect( @@ -415,7 +421,7 @@ describe('test/unit/lib/plugins/package/lib/packageService.test.js', () => { configExt: { ...configExt, webFunctions: { web: webFunction } }, }) ) - .to.eventually.be.rejectedWith(`Web function "web" has no "${entryPoint}" file`) + .to.eventually.be.rejectedWith(`Web function "web" has no ${entryFiles} file`) .and.have.property('code', 'WEB_FUNCTION_ENTRY_POINT_NOT_FOUND'); }); } @@ -497,6 +503,24 @@ describe('test/unit/lib/plugins/package/lib/packageService.test.js', () => { await runServerless({ cwd: servicePath, command: 'package', awsSdkV3StubMap }); }); + it('should support a `webFunctions[].package.artifact` with a Python package as the module', async () => { + const { servicePath } = await setupProgrammaticFixture('packaging', { + configExt: { + ...configExt, + webFunctions: { + web: { + runtime: 'python3.15', + entryPoint: 'app:application', + package: { artifact: 'python.zip' }, + }, + }, + }, + files: [{ to: 'python.zip', contents: await createZipBuffer(['app/__init__.py']) }], + }); + + await runServerless({ cwd: servicePath, command: 'package', awsSdkV3StubMap }); + }); + it('should reject a `webFunctions[].package.artifact` with a backslash in an entry name', async () => { const zip = await createZipBuffer(['dir2/index.js']); const { servicePath } = await setupProgrammaticFixture('packaging', { diff --git a/types/index.d.ts b/types/index.d.ts index e5b610778..a404ccd41 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -87,7 +87,7 @@ export type AwsLambdaRuntimeManagement = export type AwsLambdaTimeout = number; export type AwsLambdaTracing = ('Active' | 'PassThrough') | boolean; export type AwsLambdaVersioning = boolean; -export type AwsLambdaWebFunctionRuntime = 'nodejs24.x' | 'nodejs26.x'; +export type AwsLambdaWebFunctionRuntime = 'nodejs24.x' | 'nodejs26.x' | 'python3.15'; export type AwsPruneFunctionVersions = | boolean | {