Skip to content
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

feat: switch to Azure Functions v4 #177

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Changelog

## [Unreleased]

### Features

* **Breaking:** switch to Azure Functions v4:
* the function path has changed from `/api/__render` to `/api/sk_render` (v4 does not allow routes starting with underscores)
* see also [Migrate to version 4 of the Node.js programming model for Azure Functions](https://learn.microsoft.com/en-us/azure/azure-functions/functions-node-upgrade-v4) from the Azure docs



### [0.20.1](https://www.github.com/geoffrich/svelte-adapter-azure-swa/compare/v0.20.0...v0.20.1) (2024-07-13)


Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ custom/
└── index.js
```

Also note that the adapter reserves the folder prefix `sk_render` and API route prefix `__render` for Azure functions generated by the adapter. So, if you use a custom API directory, you cannot have any other folder starting with `sk_render` or functions available at the `__render` route, since these will conflict with the adapter's Azure functions.
Also note that the adapter reserves the folder prefix `sk_render` and API route prefix `sk_render` for Azure functions generated by the adapter. So, if you use a custom API directory, you cannot have any other folder starting with `sk_render` or functions available at the `sk_render` route, since these will conflict with the adapter's Azure functions.

### staticDir

Expand Down
16 changes: 0 additions & 16 deletions demo/func/HelloWorld/function.json

This file was deleted.

35 changes: 22 additions & 13 deletions demo/func/HelloWorld/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');

const name = req.query.name || (req.body && req.body.name);
const responseMessage = name
? 'Hello, ' + name + '. This HTTP triggered function executed successfully.'
: 'This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.';

context.res = {
// status: 200, /* Defaults to 200 */
body: responseMessage
};
};
const { app } = require('@azure/functions');

app.http('httpTrigger1', {
methods: ['GET', 'POST'],
handler: async (req, context) => {
context.log('JavaScript HTTP trigger function processed a request.');

let name;
if (req.query.has('name')) {
name = req.query.get('name')
} else {
let body = await req.json();
name = body.name;
}

const responseMessage = name
? 'Hello, ' + name + '. This HTTP triggered function executed successfully.'
: 'This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.';

return { body: responseMessage };
}
});
2 changes: 1 addition & 1 deletion demo/func/host.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[2.*, 3.0.0)"
"version": "[4.0.0, 5.0.0)"
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a external Azure function in this folder that also needs to be converted to the v4 model

}
}
2 changes: 1 addition & 1 deletion files/api/host.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[2.*, 3.0.0)"
"version": "[4.0.0, 5.0.0)"
}
}
7 changes: 6 additions & 1 deletion files/api/package.json
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
{}
{
"main": "sk_render/index.js",
"dependencies": {
"@azure/functions": "^4"
}
}
137 changes: 70 additions & 67 deletions files/entry.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
getClientPrincipalFromHeaders,
splitCookiesFromHeaders
} from './headers';
import { app } from '@azure/functions';

// replaced at build time
// @ts-expect-error
Expand All @@ -17,99 +18,101 @@ const server = new Server(manifest);
const initialized = server.init({ env: process.env });

/**
* @typedef {import('@azure/functions').AzureFunction} AzureFunction
* @typedef {import('@azure/functions').Context} Context
* @typedef {import('@azure/functions').InvocationContext} InvocationContext
* @typedef {import('@azure/functions').HttpRequest} HttpRequest
* @typedef {import('@azure/functions').HttpResponse} HttpResponse
*/

/**
* @param {Context} context
*/
export async function index(context) {
const request = toRequest(context);

if (debug) {
context.log(
'Starting request',
context?.req?.method,
context?.req?.headers?.['x-ms-original-url']
);
context.log(`Original request: ${JSON.stringify(context)}`);
context.log(`Request: ${JSON.stringify(request)}`);
}

const ipAddress = getClientIPFromHeaders(request.headers);
const clientPrincipal = getClientPrincipalFromHeaders(request.headers);

await initialized;
const rendered = await server.respond(request, {
getClientAddress() {
return ipAddress;
},
platform: {
clientPrincipal,
context
app.http('sk_render', {
methods: ['HEAD', 'GET', 'POST', 'DELETE', 'PUT', 'OPTIONS'],
/**
*
* @param {HttpRequest} httpRequest
* @param {InvocationContext} context
*/
handler: async (httpRequest, context) => {
if (debug) {
context.log(
'Starting request',
httpRequest.method,
httpRequest.headers.get('x-ms-original-url')
);
context.log(`Request: ${JSON.stringify(httpRequest)}`);
}
});

const response = await toResponse(rendered);
const request = toRequest(httpRequest);

const ipAddress = getClientIPFromHeaders(request.headers);
const clientPrincipal = getClientPrincipalFromHeaders(request.headers);

await initialized;
const rendered = await server.respond(request, {
getClientAddress() {
return ipAddress;
},
platform: {
user: httpRequest.user,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clientPrincipal,
context
}
});

if (debug) {
context.log(`SK headers: ${JSON.stringify(Object.fromEntries(rendered.headers.entries()))}`);
context.log(`Response: ${JSON.stringify(rendered)}`);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not continue to log the response here?

}

if (debug) {
context.log(`SK headers: ${JSON.stringify(Object.fromEntries(rendered.headers.entries()))}`);
context.log(`Response: ${JSON.stringify(response)}`);
return toResponse(rendered);
}

context.res = response;
}
});

/**
* @param {Context} context
* @param {HttpRequest} httpRequest
* @returns {Request}
* */
function toRequest(context) {
const { method, headers, rawBody, body } = context.req;
// because we proxy all requests to the render function, the original URL in the request is /api/__render
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we keep the comment?

// this header contains the URL the user requested
const originalUrl = headers['x-ms-original-url'];
*/
function toRequest(httpRequest) {
const originalUrl = httpRequest.headers.get('x-ms-original-url');

// SWA strips content-type headers from empty POST requests, but SK form actions require the header
// https://github.com/geoffrich/svelte-adapter-azure-swa/issues/178
if (method === 'POST' && !body && !headers['content-type']) {
headers['content-type'] = 'application/x-www-form-urlencoded';
if (
httpRequest.method === 'POST' &&
!httpRequest.body &&
!httpRequest.headers.get('content-type')
) {
httpRequest.headers.set('content-type', 'application/x-www-form-urlencoded');
}

/** @type {RequestInit} */
const init = {
method,
headers: new Headers(headers)
};

if (method !== 'GET' && method !== 'HEAD') {
init.body = Buffer.isBuffer(body)
? body
: typeof rawBody === 'string'
? Buffer.from(rawBody, 'utf-8')
: rawBody;
}
Comment on lines -87 to -93
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this logic isn't needed any more under the v4 model?

/** @type {Record<string, string>} */
const headers = {};
httpRequest.headers.forEach((value, key) => {
if (key !== 'x-ms-original-url') {
headers[key] = value;
}
});

return new Request(originalUrl, init);
return new Request(originalUrl, {
method: httpRequest.method,
headers: new Headers(headers),
// @ts-ignore
body: httpRequest.body,
duplex: 'half'
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why set this property?

});
}

/**
* @param {Response} rendered
* @returns {Promise<Record<string, any>>}
* @returns {Promise<HttpResponse>}
*/
async function toResponse(rendered) {
const { status } = rendered;
const resBody = new Uint8Array(await rendered.arrayBuffer());

const { headers, cookies } = splitCookiesFromHeaders(rendered.headers);

return {
status,
body: resBody,
status: rendered.status,
// @ts-ignore
body: rendered.body,
headers,
cookies,
isRaw: true
enableContentNegotiation: false
};
}
13 changes: 9 additions & 4 deletions files/headers.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,35 @@
import * as set_cookie_parser from 'set-cookie-parser';

/**
* @typedef {import('@azure/functions').Cookie} Cookie
*/

/**
* Splits 'set-cookie' headers into individual cookies
* @param {Headers} headers
* @returns {{
* headers: Record<string, string>,
* cookies: set_cookie_parser.Cookie[]
* headers: Headers,
* cookies: Cookie[]
* }}
*/
export function splitCookiesFromHeaders(headers) {
/** @type {Record<string, string>} */
const resHeaders = {};

/** @type {set_cookie_parser.Cookie[]} */
/** @type {Cookie[]} */
const resCookies = [];

headers.forEach((value, key) => {
if (key === 'set-cookie') {
const cookieStrings = set_cookie_parser.splitCookiesString(value);
// @ts-ignore
resCookies.push(...set_cookie_parser.parse(cookieStrings));
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like this is due to a type mismatch on the sameSite property - are we sure the sameSite property returned by set_cookie_parser matches what Azure expects?

Type 'string' is not assignable to type '"Strict" | "Lax" | "None"'

} else {
resHeaders[key] = value;
}
});

return { headers: resHeaders, cookies: resCookies };
return { headers: new Headers(resHeaders), cookies: resCookies };
}

/**
Expand Down
7 changes: 5 additions & 2 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Adapter } from '@sveltejs/kit';
import { ClientPrincipal, CustomStaticWebAppConfig } from './types/swa';
import { Context } from '@azure/functions';
import { HttpRequestUser, InvocationContext } from '@azure/functions';
import esbuild from 'esbuild';

export * from './types/swa';
Expand Down Expand Up @@ -37,8 +37,11 @@ declare global {
*
* @see The {@link https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node#context-object Azure function documentation}
*/
context: InvocationContext;

user: HttpRequestUser;

clientPrincipal?: ClientPrincipal;
context: Context;
}
}
}
27 changes: 6 additions & 21 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,7 @@ import esbuild from 'esbuild';
* @typedef {import('esbuild').BuildOptions} BuildOptions
*/

const ssrFunctionRoute = '/api/__render';

const functionJson = `
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"route": "__render"
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
`;
const ssrFunctionRoute = '/api/sk_render';
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


/**
* Validate the static web app configuration does not override the minimum config for the adapter to work correctly.
Expand Down Expand Up @@ -123,6 +104,11 @@ If you want to suppress this error, set allowReservedSwaRoutes to true in your a
})};\n`
);

// add @azure/functions to esbuildOptions.external if not already set - this is needed by the Azure Functiions v4 runtime
if (!esbuildOptions.external?.includes('@azure/functions')) {
esbuildOptions.external = [...(esbuildOptions.external || []), '@azure/functions'];
}

/** @type {BuildOptions} */
const default_options = {
entryPoints: [entry],
Expand All @@ -137,7 +123,6 @@ If you want to suppress this error, set allowReservedSwaRoutes to true in your a
};

await esbuild.build(default_options);
writeFileSync(join(functionDir, 'function.json'), functionJson);

builder.log.minor('Copying assets...');
builder.writeClient(staticDir);
Expand Down
Loading