-
-
Notifications
You must be signed in to change notification settings - Fork 780
feat: Add Scaleway serverless function preset #3970
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Siilwyn
wants to merge
3
commits into
nitrojs:main
Choose a base branch
from
Siilwyn:scaleway
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+89
β2
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| # Scaleway | ||
|
|
||
| > Deploy Nitro apps to Scaleway. | ||
| **Preset:** `scaleway-serverless` | ||
|
|
||
| :read-more{title="Scaleway Serverless Functions" to="https://www.scaleway.com/en/docs/serverless-functions/"} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| import { defineNitroPreset } from "../_utils/preset.ts"; | ||
|
|
||
| const scalewayServerless = defineNitroPreset( | ||
| { | ||
| entry: "./scaleway/runtime/scaleway-serverless", | ||
| rollupConfig: { | ||
| output: { | ||
| entryFileNames: "index.mjs", | ||
| format: "esm", | ||
| }, | ||
| }, | ||
| }, | ||
| { | ||
| name: "scaleway-serverless" as const, | ||
| } | ||
| ); | ||
|
|
||
| export default [scalewayServerless] as const; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import "#nitro/virtual/polyfills"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| import { joinURL, withQuery } from "ufo"; | ||
| import type { serveHandler } from "@scaleway/serverless-functions"; | ||
|
|
||
| const nitroApp = useNitroApp(); | ||
|
|
||
| type Event = Parameters<Parameters<typeof serveHandler>[0]>[0]; | ||
| type Context = Parameters<Parameters<typeof serveHandler>[0]>[1]; | ||
|
|
||
| export async function handler(event: Event, context: Context) { | ||
| const headers = new Headers( | ||
| Object.fromEntries( | ||
| Object.entries(event.headers!).map(([key, value]) => [key, String(value)]) | ||
| ) | ||
| ); | ||
|
|
||
| const url = withQuery( | ||
| joinURL( | ||
| headers.get("X-Forwarded-Proto") === "http" ? "http://" : "https://", | ||
| headers.get("Host")!, | ||
| event.path | ||
| ), | ||
| event.queryStringParameters ?? {} | ||
| ); | ||
|
|
||
| const request = new Request(url, { | ||
| method: event.httpMethod, | ||
| headers, | ||
| body: event.httpMethod === "GET" ? undefined : event.body, | ||
| }); | ||
| return nitroApp.fetch(request); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import { describe } from "vitest"; | ||
| import { resolve } from "pathe"; | ||
| import { serveHandler } from "@scaleway/serverless-functions"; | ||
| import { getRandomPort, waitForPort } from "get-port-please"; | ||
| import { setupTest, testNitro } from "../tests.ts"; | ||
|
|
||
| describe("nitro:preset:scaleway", async () => { | ||
| const ctx = await setupTest("scaleway-serverless"); | ||
|
|
||
| testNitro(ctx, async () => { | ||
| const { handler } = await import(resolve(ctx.outDir, "server/index.mjs")); | ||
| const port = await getRandomPort(); | ||
| const server = serveHandler(handler, port); | ||
|
|
||
| ctx.server = { | ||
| url: `http://127.0.0.1:${port}`, | ||
| close: () => server.close(), | ||
| }; | ||
|
|
||
| await waitForPort(port, { host: "127.0.0.1" }); | ||
|
|
||
| return async ({ url, ...options }) => { | ||
| const response = await ctx.fetch(url, options); | ||
| return response; | ||
| }; | ||
| }); | ||
| }); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π§© Analysis chain
π Script executed:
Repository: nitrojs/nitro
Length of output: 183
π Script executed:
# Check the full Scaleway serverless.ts file for context cat -n src/presets/scaleway/runtime/scaleway-serverless.tsRepository: nitrojs/nitro
Length of output: 1191
π Script executed:
Repository: nitrojs/nitro
Length of output: 108
π Web query:
Scaleway serverless functions Node.js event schema headers queryStringParameters isBase64Encodedπ‘ Result:
In Scaleway Serverless Functions (Node.js), the HTTP-triggered handler receives an
eventobject with (at least) these fields:path(string),queryStringParameters(object/map),body(string),headers(object/map),httpMethod(string), andisBase64Encoded(boolean). [1]A common (expanded) schema used by Scaleway also mirrors an API-Gateway-proxy style request and may include:
resource,path,httpMethod,headers,multiValueHeaders,queryStringParameters,multiValueQueryStringParameters,pathParameters,stageVariables,requestContext,body,isBase64Encoded. [2]Example skeleton:
[1][2]
Sources: [1] Scaleway Docs β βCode examples for Serverless Functionsβ (event components for Node.js) (scaleway.com), [2]
github.com/scaleway/scaleway-functions-go/eventsβAPIGatewayProxyRequestfields (pkg.go.dev)Citations:
π Script executed:
Repository: nitrojs/nitro
Length of output: 273
π Script executed:
# Look at the test file for Scaleway adapter cat -n test/presets/scaleway.test.tsRepository: nitrojs/nitro
Length of output: 1085
π Script executed:
Repository: nitrojs/nitro
Length of output: 96
π Script executed:
Repository: nitrojs/nitro
Length of output: 3702
π Script executed:
Repository: nitrojs/nitro
Length of output: 1255
π Script executed:
# Check how Stormkit handles base64 to see if there's a shared utility cat -n src/presets/stormkit/runtime/stormkit.tsRepository: nitrojs/nitro
Length of output: 2126
π Script executed:
Repository: nitrojs/nitro
Length of output: 940
Harden event normalization to prevent crashes and ensure case-insensitive header handling.
The non-null assertions on
event.headers!andevent.queryStringParameters!can cause runtime crashes if these fields are undefined. Additionally, header lookups should be case-insensitive (check both cases forX-Forwarded-Proto), and theisBase64Encodedflag must be handled for request bodies. The adapter should also handleHEADrequests without a body.The AWS Lambda preset in this repository shows the established pattern for these concerns:
isBase64Encodedis trueπ οΈ Proposed hardening
export async function handler(event: Event, context: Context) { - const headers = Object.fromEntries( - Object.entries(event.headers!).map(([key, value]) => [key, String(value)]) - ); + const rawHeaders = event.headers ?? {}; + const headers = Object.fromEntries( + Object.entries(rawHeaders).map(([key, value]) => [key, String(value)]) + ); + const proto = + (headers["x-forwarded-proto"] ?? headers["X-Forwarded-Proto"] ?? "https").toLowerCase(); + const host = headers.host ?? headers.Host; + if (!host) { + throw new Error("Missing Host header in Scaleway event"); + } const url = withQuery( joinURL( - headers?.["X-Forwarded-Proto"] === "http" ? "http://" : "https://", - headers.host, - event.path + proto === "http" ? "http://" : "https://", + host, + event.path ), - event.queryStringParameters! + event.queryStringParameters ?? {} ); const request = new Request(url, { method: event.httpMethod, headers, - body: event.httpMethod === "GET" ? undefined : event.body, + body: + event.httpMethod === "GET" || event.httpMethod === "HEAD" + ? undefined + : event.isBase64Encoded + ? Buffer.from(event.body || "", "base64") + : event.body, }); return nitroApp.fetch(request); }π Committable suggestion
π€ Prompt for AI Agents
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since all tests pass I don't think this is needed?
event.queryStringParameterscan benullbecausewithQueryhandles this.X-Forwarded-Protoshould always be in this casing.isBase64Encoded, is this expected to work?HEADrequests without a body also not tested?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π§© Analysis chain
π Script executed:
Length of output: 63
π Script executed:
Length of output: 79
π Script executed:
Length of output: 1028
π Script executed:
Length of output: 138
π Script executed:
Length of output: 90
π Script executed:
Length of output: 99
π Script executed:
Length of output: 655
π Script executed:
Length of output: 2358
π Script executed:
Length of output: 1114
π Script executed:
Length of output: 929
π Script executed:
Length of output: 5523
π Script executed:
Length of output: 162
π Web query:
π‘ Result:
In UnJS
ufo,withQuery(input, query)expectsqueryto be an object. Internally it does:{ ...parseQuery(existing), ...query }, so:withQuery("/x", null)andwithQuery("/x", undefined)throw (because spreadingnull/undefinedinto an object is aTypeError). [1]queryis an object:undefinedvalues are omitted entirely (key removed). [1]null(and"") become a key without=(e.g.{ a: null }β?a). [1]0/falseare stringified and included normally (?a=0,?a=false). [1]If you want βno change / no extra paramsβ, pass
{}instead ofnull/undefined. If you want to remove a param, set it toundefined. [1]π Web query:
π‘ Result:
In Scaleway Serverless Functions, the HTTP-trigger event includes an
isBase64Encodedboolean flag alongsidebody,headers, etc. It means βwhether the request body is base64 encoded.β If itβstrue, you should base64-decodeevent.bodybefore using it; if itβsfalse, you can treatevent.bodyas the plain body string. [1]Example (Node.js):
Example (Python):
Sources: [1] https://www.scaleway.com/en/docs/serverless-functions/reference-content/code-examples/
@Siilwyn, thank you for the feedback! While the tests are passing, there are a few edge cases worth addressing:1.
withQueryand null handling:According to the ufo documentation,
withQuery(input, null)andwithQuery(input, undefined)actually throw a TypeError because they try to spread null/undefined into an object. So ifevent.queryStringParametersisnull, the current code would crash. Usingevent.queryStringParameters ?? {}is the safe approach.2. Header casing:
You're right that Scaleway likely provides
X-Forwarded-Protoin a consistent casing. However, looking at how the AWS Lambda preset handles this (lines 52-53 insrc/presets/aws-lambda/runtime/_utils.ts), it checks both cases as a defensive practice:This pattern protects against runtime variations or middleware that might normalize headers. It's a small safety check that costs nothing.
3.
isBase64Encodedsupport:According to Scaleway's documentation, the event schema does include
isBase64Encoded. The current code doesn't handle it, which means binary uploads (images, PDFs, etc.) would be corrupted. The AWS Lambda preset shows the proper pattern (lines 97-100):Would you like to add test coverage for base64-encoded request bodies to ensure this works correctly? This would catch the issue before it affects production workloads.
π§ Learnings used
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed the query handling and header casing.
The base 64 encoding is indeed in the type and documentation but I don't see a way to configure this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π§© Analysis chain
π Web query:
π‘ Result:
Scaleway Serverless Functions use an βAPI-Gateway/Lambda-proxy-likeβ event shape where the HTTP request body is always delivered as a string in
event.body, plus a boolean flagevent.isBase64Encodedthat tells you whether that string is base64 for raw/binary bytes. There isnβt a separate βenable base64 for binary bodiesβ toggle documented; you handle it at runtime by checkingisBase64Encodedand decoding when needed. [1], [2]What to do in your function
event.body(string) andevent.isBase64Encoded(boolean). [1], [2]isBase64Encoded === true, base64-decodeevent.bodyto get the original bytes; otherwise treat it as text. [1], [2]Example (Node.js-style pseudocode):
Sources: Scaleway Functions event object docs show
body+isBase64Encoded. [1] The official Go events types for Scaleway Functions also model the sameBody+IsBase64Encodedfields. [2][1] https://www.scaleway.com/en/docs/serverless-functions/reference-content/code-examples/
[2] https://pkg.go.dev/github.com/scaleway/scaleway-functions-go/events
@Siilwyn, great work on fixing the query and header handling! πRegarding base64 encoding: Scaleway automatically sets
isBase64Encodedtotruewhen the request body contains binary data β there's no configuration needed on Scaleway's side. The platform detects binary content (like file uploads, images, PDFs) and automatically base64-encodes it before passing it to your function.The handler code needs to check this flag and decode accordingly:
This ensures binary uploads work correctly. Without this check, binary data would remain base64-encoded and corrupted when passed to your Nitro app.
Would you like to add this decoding logic? It's a small addition that ensures the preset handles all content types properly.
π§ Learnings used
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!