├── docs └── implementations │ ├── vercel.md │ ├── lagon.md │ ├── netlify.md │ ├── aws.md │ ├── openshift-serverless-functions.md │ ├── cloudflare.md │ └── azion-edge-functions.md ├── README.md └── LICENSE /docs/implementations/vercel.md: -------------------------------------------------------------------------------- 1 | ## Vercel Edge Functions 2 | 3 | Using an [example from Vercel](https://vercel.com/docs/concepts/functions/edge-functions): 4 | 5 | ```js 6 | 7 | export const config = { runtime: 'edge' }; 8 | 9 | export default (request) => { 10 | return new Response(`Hello, from ${request.url}`); 11 | }; 12 | ``` 13 | 14 | ### Related Links 15 | 16 | * https://github.com/wintercg/admin/issues/44#issuecomment-1386274222 17 | 18 | * https://vercel.com/docs/concepts/functions/edge-functions 19 | -------------------------------------------------------------------------------- /docs/implementations/lagon.md: -------------------------------------------------------------------------------- 1 | ## Lagon 2 | 3 | To add another example, the syntax for [Lagon](https://lagon.app/) is similar to [Vercel](./vercel.md), except that the function is a named export: 4 | 5 | ```js 6 | export function handler(request) { 7 | return new Response("Hello World"); 8 | } 9 | ``` 10 | 11 | Logging is the same (using `console.log` / `console.debug` / `console.warn` / `console.error`). I believe this syntax is already used by most (if not all) of the runtimes out there. 12 | 13 | ### Related Links 14 | 15 | * https://github.com/wintercg/admin/issues/44#issuecomment-1386620726 16 | 17 | * https://lagon.app/ 18 | 19 | -------------------------------------------------------------------------------- /docs/implementations/netlify.md: -------------------------------------------------------------------------------- 1 | ## Netlify Edge Functions 2 | 3 | The syntax for [Netlify Edge Functions](https://docs.netlify.com/edge-functions/overview/) is very similar to [Vercel](./vercel.md) and [Lagon](./lagon.md), and both of those examples would work unchanged on Netlify. 4 | 5 | This is the standard signature for Netlify: 6 | 7 | ```ts 8 | export default async function handler(request: Request, context: Context) { 9 | return new Response("Hello world") 10 | } 11 | ``` 12 | 13 | The `Request` and `Response` are standard Deno objects. The `Context` object is optional, and provides things like `geo` and `ip`, as well as a `next()` function (which itself returns a `Response`). We've tried to keep everything as standard as possible, putting any non-standard fields on the context object instead of adding anything to the request or response. `console` works as expected. 14 | 15 | Netlify also supports an optional `config` export similar to Vercel but in our case it's currently just used for mapping the function to paths. 16 | 17 | We're open to adding more fields to `Request` if they are standardised but would suggest that we avoid using these objects for non-standard extensions if possible. 18 | 19 | 20 | ### Related Links 21 | 22 | * https://github.com/wintercg/admin/issues/44#issuecomment-1386751428 23 | 24 | * https://docs.netlify.com/edge-functions/overview/ 25 | -------------------------------------------------------------------------------- /docs/implementations/aws.md: -------------------------------------------------------------------------------- 1 | ## AWS Lamda Functions input/output model: 2 | 3 | From: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html function signatures are: 4 | 5 | * async function(event, context) or 6 | * function (event, context, callback) 7 | 8 | Parameters are: 9 | 10 | * event - The invoker passes this information as a JSON-formatted string when it calls [Invoke](https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html), and the runtime converts it to an object. 11 | * The second argument is the [context object](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html), which contains information about the invocation, function, and execution environment. In the preceding example, the function gets the name of the [log stream](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-logging.html) from the context object and returns it to the invoker. 12 | * The third argument, callback, is a function that you can call in [non-async handlers](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html#nodejs-handler-sync) to send a response. The callback function takes two arguments: an Error and a response. When you call it, Lambda waits for the event loop to be empty and then returns the response or error to the invoker. The response object must be compatible with JSON.stringify. 13 | 14 | For asynchronous function handlers, you return a response, error, or promise to the runtime instead of using callback. 15 | 16 | Response is object must be compatible with JSON.stringify as JSON is returned 17 | 18 | ## Logging 19 | Logging uses console.log, err 20 | 21 | ## Error handling 22 | https://docs.aws.amazon.com/lambda/latest/dg/nodejs-exceptions.html still returns JSON 23 | 24 | 25 | ### Related Links 26 | 27 | * https://github.com/wintercg/admin/issues/44#issuecomment-1396204170 28 | 29 | * https://aws.amazon.com/lambda/#:~:text=AWS%20Lambda%20is%20a%20serverless,pay%20for%20what%20you%20use. 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JavaScript Serverless Functions Standardization 2 | 3 | ## Problem 4 | Today every competing JavaScript functions API is different enough that we end up with lower developer productivity and vendor lock-in. Lower developer productivity because developers have to learn multiple ways to write the JavaScript function code and may have to write more complex code to avoid vendor lock-in. Organizations wanting to leverage multiple functions providers or move from one provider to another incur significant additional cost. 5 | 6 | ## Goal 7 | Goal is to define a JavaScript functions API that avoids vendor lock-in and facilitates developer productivity while being general enough to allow different implementations and optimizations behind the scenes. 8 | 9 | Things we should try to standardize 10 | * function sig (including parameters and what’s available on them) 11 | * how functions get events(CloudEvents)? 12 | * key supporting apis like 13 | * log method signature 14 | * exporting the function 15 | * how to report an error 16 | 17 | Things we should not try to standardize 18 | * JS framework for invoking the functions 19 | * http framework that is used(Fastify, Express, etc…) 20 | * underlying buildpack/image that ends up running 21 | * accessing platform specific APIs offered by the vendor platforms(ex: google apis) 22 | * output format/how you view logs 23 | * how you monitor functions 24 | 25 | ## Scenarios 26 | 27 | Scenario 1: Writing a HelloWorld function in one vendors platform and moving to other vendors platforms 28 | Shouldn’t have to change the code 29 | Build steps and or configuration may have to change 30 | 31 | Scenario 2: Writing in one vendor and moving to another (ex using Google Cloud Functions and move to Cloudflare workers) 32 | If code does not use vendor specific APIs you should not have to change the code. 33 | If code uses vendor specific APIs, you may need to change the code if you also need to use a different vendor for those calls. 34 | Build steps and or configuration may have to change 35 | 36 | 37 | ## Implementations 38 | 39 | * [AWS Lambda](./docs/implementations/aws.md) 40 | * [Cloudflare Workers](./docs/implementations/cloudflare.md) 41 | * [Lagon](./docs/implementations/lagon.md) 42 | * [Netlify Edge Functions](./docs/implementations/netlify.md) 43 | * [Openshift Serverless Functions](./docs/implementations/openshift-serverless-functions.md) 44 | * [Vercel Edge Functions](./docs/implementations/vercel.md) 45 | 46 | ## Contributors 47 | 48 | * https://github.com/Ethan-Arrowood 49 | * https://github.com/jasnell 50 | * https://github.com/styfle 51 | * https://github.com/QuiiBz 52 | * https://github.com/ascorbic 53 | * https://github.com/lholmquist 54 | * https://github.com/kentonv 55 | * https://github.com/mhdawson 56 | -------------------------------------------------------------------------------- /docs/implementations/openshift-serverless-functions.md: -------------------------------------------------------------------------------- 1 | ## Openshift Serverless Functions 2 | 3 | Here is the current syntax for an [Openshift Serverless Function](https://docs.openshift.com/container-platform/4.12/serverless/functions/serverless-functions-getting-started.html) for a "normal" function 4 | 5 | ```js 6 | /** 7 | * Your HTTP handling function, invoked with each request. This is an example 8 | * function that echoes its input to the caller, and returns an error if 9 | * the incoming request is something other than an HTTP POST or GET. 10 | * 11 | * In can be invoked with 'func invoke' 12 | * It can be tested with 'npm test' 13 | * 14 | * @param {Context} context a context object. 15 | * @param {object} context.body the request body if any 16 | * @param {object} context.query the query string deserialized as an object, if any 17 | * @param {object} context.log logging object with methods for 'info', 'warn', 'error', etc. 18 | * @param {object} context.headers the HTTP request headers 19 | * @param {string} context.method the HTTP request method 20 | * @param {string} context.httpVersion the HTTP protocol version 21 | * See: https://github.com/knative-sandbox/kn-plugin-func/blob/main/docs/guides/nodejs.md#the-context-object 22 | */ 23 | const handle = async (context) => { 24 | // YOUR CODE HERE 25 | context.log.info(JSON.stringify(context, null, 2)); 26 | 27 | // If the request is an HTTP POST, the context will contain the request body 28 | if (context.method === 'POST') { 29 | return { 30 | body: context.body, 31 | } 32 | // If the request is an HTTP GET, the context will include a query string, if it exists 33 | } else if (context.method === 'GET') { 34 | return { 35 | query: context.query, 36 | } 37 | } else { 38 | return { statusCode: 405, statusMessage: 'Method not allowed' }; 39 | } 40 | } 41 | 42 | // Export the function 43 | module.exports = { handle }; 44 | ``` 45 | The only parameter here is the context object, which provides a few pieces of information 46 | 47 | 48 | If you need a function that can also handle [CloudEvents](https://cloudevents.io/), then an extra `event` param is used: 49 | 50 | ```js 51 | const { CloudEvent, HTTP } = require('cloudevents'); 52 | 53 | /** 54 | * Your CloudEvent handling function, invoked with each request. 55 | * This example function logs its input, and responds with a CloudEvent 56 | * which echoes the incoming event data 57 | * 58 | * It can be invoked with 'func invoke' 59 | * It can be tested with 'npm test' 60 | * 61 | * @param {Context} context a context object. 62 | * @param {object} context.body the request body if any 63 | * @param {object} context.query the query string deserialzed as an object, if any 64 | * @param {object} context.log logging object with methods for 'info', 'warn', 'error', etc. 65 | * @param {object} context.headers the HTTP request headers 66 | * @param {string} context.method the HTTP request method 67 | * @param {string} context.httpVersion the HTTP protocol version 68 | * See: https://github.com/knative-sandbox/kn-plugin-func/blob/main/docs/guides/nodejs.md#the-context-object 69 | * @param {CloudEvent} event the CloudEvent 70 | */ 71 | const handle = async (context, event) => { 72 | // YOUR CODE HERE 73 | context.log.info("context"); 74 | context.log.info(JSON.stringify(context, null, 2)); 75 | 76 | context.log.info("event"); 77 | context.log.info(JSON.stringify(event, null, 2)); 78 | 79 | return HTTP.binary(new CloudEvent({ 80 | source: 'event.handler', 81 | type: 'echo', 82 | data: event 83 | })); 84 | }; 85 | 86 | module.exports = { handle }; 87 | ``` 88 | 89 | ### Related Links 90 | 91 | * https://github.com/wintercg/admin/issues/44#issuecomment-1387160922 92 | 93 | * https://docs.openshift.com/container-platform/4.12/serverless/functions/serverless-functions-getting-started.html 94 | 95 | -------------------------------------------------------------------------------- /docs/implementations/cloudflare.md: -------------------------------------------------------------------------------- 1 | ## Cloudflare Workers/workerd 2 | 3 | For [workerd/cloudflare workers](https://developers.cloudflare.com/workers/), we have two API models (one legacy and one preferred that we're actively moving to): 4 | 5 | Legacy (service worker style): 6 | 7 | ```js 8 | // global addEventListener 9 | addEventListener('fetch', (event) ={ 10 | // request is a property on event (e.g. request.event), as is `waitUntil` 11 | // bindings (additional resources/capabilities configured for the worker) are injected as globals 12 | event.respondWith(new Response("Hello World")); 13 | }); 14 | ``` 15 | 16 | New (ESM worker style): 17 | 18 | ```js 19 | export default { 20 | async fetch(request, env, context) => { 21 | // bindings are available through `env`, `waitUntil` is available on `context` 22 | return new Response("Hello World"); 23 | } 24 | } 25 | ``` 26 | 27 | We use `console.log(...)` for all logging. We do have a more structured logging API configurable through bindings but it's more specific purpose for metrics. 28 | 29 | Error reporting is pretty straightforward. There's really nothing fancy. We throw synchronous errors and report unhandled promise rejections to the `'unhandedrejection'` event handler using the global `addEventListener` with either worker model. 30 | 31 | Overall, our strong preference is to stick with the ESM worker style as experience has shown us time and again that the service worker model is pretty limited. 32 | 33 | The `Request` and `Response` objects here are the standard fetch APIs. In the service worker model, we use the standard `FetchEvent`. For the ESM worker model, `env` and `context` are platform-defined, non-standard APIs, although `context` mimics the `FetchEvent` API. 34 | 35 | I guess there are a few main ways Cloudflare's interface is unusual here. Let me try to explain our reasoning. 36 | 37 | # `env` 38 | Cloudflare's `env` contains "environment variables", which we also often call "bindings". But our design here is quite different from "environment variables" in most systems. Cloudflare's bindings implement a capability-based security model for configuring Workers. This is a central design feature of the whole Workers platform. 39 | 40 | Importantly, unlike most systems, environment variables are not just strings; they may be arbitrary objects representing external resources. For example, if the worker is configured to use a Workers KV namespace for storage, then the binding's type will be `KvNamespace`, which has methods `get(key)`, `put(key, value)`, and `delete(key)`. Another example of a complex binding is a "service binding", which points to another Worker. A service binding has a method `fetch()`, which behaves like the global fetch, except all requests passed to it are delivered to the target worker. (In the future, service bindings could have other methods representing other event types that Workers can listen for.) 41 | 42 | So for example, if I want to load the key "foo" from my KV namespace, I might write: 43 | 44 | ```js 45 | let value = await env.MY_KV.get("foo"); 46 | ``` 47 | 48 | We expect to add more kinds of bindings over time, which could have arbitrary APIs. Obviously those APIs aren't going to be standardized here. But, I think the concept of `env` could be. 49 | 50 | ### Why not have `env` be just strings? 51 | Most systems that have environment variables only support strings, and if the environment variable is meant to refer to an external resource, it must contain some sort of URL or other identifier for that resource. For example, you could imagine KV namespaces being accessed like: 52 | 53 | ```js 54 | let ns = KvNamespace.get(env.KV_NAME); 55 | let value = await ns.get("foo"); 56 | ``` 57 | 58 | However, this opens a can of worms. 59 | 60 | First, there is security: What limitations exist on `KvNamespace.get()`? Can the Worker pass in any old namespace name it wants? Does every Worker then have access to every KV namespace on the account? Do we need to implement a permissions model, whereby people can restrict which namespaces each Worker can access? Will any users actually configure these permissions or will they mostly just leave it unrestricted? 61 | 62 | Second, there is the problem that this model seems to allow people to hard-code namespace names, without an environment variable at all. But when people do that, it creates a lot of problems. What if you want to have staging vs. production version of your Worker which use different namespaces? How do developers test the Worker against a test namespace? You really want to _force_ people to use environment variables for this because it sets them up for success. 63 | 64 | Third, this model allows the system to _know_ which Workers are attached to which resources. You can answer the question, "What Workers are using this KV namespace?" If the user tries to delete a namespace that is in use, we can stop them. Relatedly, we can make sure that the user cannot typo a namespace name – when they configure the binding, we only let them select from valid namespaces. 65 | 66 | By having the environment variable actually be _the object_ and not just an identifier for it, we nicely solve all these problems. Plus, the application code ends up shorter. 67 | 68 | ### Why not make `env` globally available? 69 | A more common way to expose environment variables is via a global API, e.g. `process.env` in Node. 70 | 71 | The problem with this approach is that is is not _composable_. Composability means: I should be able to take two Workers and combine them into a single Worker, without changing either workers' code, just placing a new wrapper around them. For example, say I have one worker that serves static assets and another that serves my API, and for whatever reason I decide I'd rather combine them into a single worker that covers both. I should be able to write something like: 72 | 73 | ```js 74 | import assets from "static-assets.js"; 75 | import api from "api.js"; 76 | 77 | export default { 78 | async fetch(req, env, ctx) { 79 | let url = new URL(req.url); 80 | if (url.pathname.startsWith("/api/")) { 81 | return api.fetch(req, env, ctx); 82 | } else { 83 | return assets.fetch(req, env, ctx); 84 | } 85 | } 86 | } 87 | ``` 88 | 89 | Simple enough! But what if the two workers were designed to expect different bindings, and the names conflict between them. For example, say that each sub-worker requires a KV namespace with the binding name `KV`, but these refer to different KV namespaces. No problem! I can just remap them when calling the sub-workers: 90 | 91 | ```js 92 | if (url.pathname.startsWith("/api/")) { 93 | return api.fetch(req, {KV: env.ASSETS_KV}, ctx); 94 | } else { 95 | return assets.fetch(req, {KV: env.API_KV}, ctx); 96 | } 97 | ``` 98 | 99 | But if `env` were some sort of global, this would be impossible! 100 | 101 | Arguably, an alternative way to enable composability would be to wrap the entire module in a function that takes the environment as a parameter. But, I felt that passing it as a parameter to the event handler was "less weird". 102 | 103 | # Exporting functions vs. objects 104 | Many other designs work by exporting a top-level function, like Vercel's: 105 | 106 | ``` 107 | export default (request) ={ ... } 108 | ``` 109 | 110 | But Workers prefers to export an object with a `fetch` method: 111 | 112 | ```js 113 | export default { 114 | async fetch(req, env, ctx) { ... } 115 | } 116 | ``` 117 | 118 | Why? 119 | 120 | In Workers, we support event types other than HTTP. For example, Cron Triggers deliver events on a schedule. Scheduled events use a different function name: 121 | 122 | ```js 123 | export default { 124 | async scheduled(controller, env) { ... } 125 | } 126 | ``` 127 | 128 | We also support queue and pubsub events, and imagine adding support in the future for things like raw TCP sockets, email, and so on. A single worker can potentially support multiple event types. 129 | 130 | By wrapping the exports in an object, it becomes much easier to programmatically discover what event types a worker supports. A function is just a function, there's not much you can say about it. But an object has named properties which can be enumerated, telling us exactly what the worker supports. When you upload a Worker to Cloudflare, we actually execute the Worker's global scope once in order to discover what handler it exports, so that our UI can guide the user in configuring it correctly for those events. 131 | 132 | ### Why not use the export name for that? Why wrap in an object? 133 | You could argue we should just use export names instead: 134 | 135 | ``` 136 | export async function fetch(req, env, ctx) {...}; 137 | ``` 138 | 139 | The function is exported with the name `fetch`, therefore it is an HTTP handler. 140 | 141 | The problem with this is that it necessarily means a Worker can only have _one_ HTTP handler. We actually foresee the need for multiple "named entrypoints". That is, in the future, we plan to support this: 142 | 143 | ``` 144 | export default { 145 | async fetch (req, env, ctx) { … } 146 | } 147 | 148 | export let adminInterface = { 149 | async fetch (req, env, ctx) { … } 150 | } 151 | ``` 152 | 153 | Here, we have a worker that exports two different HTTP handlers. The default one probably serves an application's main web interface. The `adminInterface` export is an alternate entrypoint which serves the admin interface. This alternate entrypoint could be configured to sit behind an authorization layer like Cloudflare Access. This way, the application itself need not worry about authorizing requests and can just focus on its business logic. 154 | 155 | # What is `context`? 156 | It looks like several designs feature a "context" object, but the purpose of the object differs. 157 | 158 | In Workers' case, the purpose of the context object is to provide control over the execution environment of the specific event. The most important method it provides is `waitUntil()`, which has similar meaning to the Service Workers standard `ExtendableEvent.waitUntil()`: it allows execution to continue for some time after the event is "done", in order to perform asynchronous tasks like submitting logs to a logging service. 159 | 160 | All event types feature the same context type. This makes it not a great place to put metadata about the request, since metadata probably differs for different event types. For example, the client IP address (for HTTP requests) is not placed in `context`. Instead, we have a non-standard field `request.cf` which contains such metadata. (I am not extremely happy about `request.cf`, but repeated attempts to design something better have always led to dead ends so far.) 161 | 162 | ### Why not put `env` inside `context`? 163 | We could, but this poses some challenges to composability. In order for an application to pass a rewritten environment to a sub-worker, it would need to build a new context object. Applications cannot construct the `ExecutionContext` type directly. They could create an alternate type that emulates its API and forwards calls to the original context, but that seems tedious. I suppose we could provide an API to construct `ExecutionContext` based on an original context with an alternate `env`. But it seemed cleaner to just keep these sepanate. `env` contains things defined by the application, `context` contains things that come from the platform. 164 | 165 | 166 | 167 | 168 | 169 | ### Related Links 170 | 171 | * https://github.com/wintercg/admin/issues/44#issuecomment-1386249383 172 | * https://github.com/wintercg/admin/issues/44#issuecomment-1387268875 173 | 174 | * https://developers.cloudflare.com/workers/ 175 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /docs/implementations/azion-edge-functions.md: -------------------------------------------------------------------------------- 1 | 2 | # **Azion - Edge Functions - Functions API Specification** 3 | 4 | ## **1. Introduction** 5 | 6 | Azion’s Runtime enables developers to build serverless applications on the edge by leveraging JavaScript functions and interacting with Azion’s extensive edge computing platform. This document outlines the standard API for writing JavaScript serverless functions on Azion, emphasizing interoperability, flexibility, and scalability while avoiding vendor lock-in. 7 | 8 | --- 9 | 10 | ## **2. Function Signature** 11 | 12 | Azion’s Edge Functions support two function signature styles—an event-driven model and an ECMAScript module (ESM) style**, similar to other serverless platforms. These signatures ensure compatibility with various use cases while giving developers flexibility in handling events. 13 | 14 | ### **2.1 Event-Driven Model** 15 | 16 | In the event-driven model, edge functions respond to incoming events such as HTTP requests or firewall events, allowing them to execute logic based on specific triggers. In Azion, two key types of events are commonly used: 17 | 18 | Fetch Event: This event is used to handle incoming HTTP requests and runs within the Edge Application product. 19 | Firewall Event: This event is used for security checks and runs within the Edge Firewall product, allowing the function to intercept and handle requests based on security policies. 20 | 21 | #### **2.1.1 Fetch Event** 22 | 23 | The Fetch Event API allows edge functions to process incoming HTTP requests, access the request metadata, and generate responses. This model runs on the Edge Application product, and it's typically used for dynamic content generation, caching, or modifying responses based on user requests. 24 | 25 | ```javascript 26 | addEventListener('fetch', event => { 27 | event.respondWith(handleRequest(event.request)); 28 | }); 29 | 30 | async function handleRequest(request) { 31 | return new Response('Hello from Azion!'); 32 | } 33 | ``` 34 | 35 | 36 | #### **2.1.2 Firewall Event** 37 | 38 | The Firewall Event API allows edge functions to execute security logic when a request passes through the Edge Firewall. This event provides access to important metadata, such as the remote IP address, and integrates with security tools like Azion's network lists. The function can take security actions such as denying requests based on conditions like IP address matching. 39 | 40 | 41 | 42 | ```javascript 43 | addEventListener("firewall", (event) => { 44 | 45 | let ip = event.request.metadata["remote_addr"] // Accessing the remote address 46 | 47 | try { 48 | let found = Azion.networkList.contains(String(networkListId), ip); // Checking if the ip is in the list 49 | if (found) { 50 | event.deny(); // If it's in the list, deny the request 51 | } 52 | } catch (err) { 53 | event.console.error(`Error: `, err.stack); 54 | } 55 | }); 56 | ``` 57 | 58 | ### **2.2 ECMAScript Module Style** 59 | 60 | This model allows functions to be exported as modules, enabling flexibility for developers who prefer this structure. The request, environment, and context objects are passed in, allowing the use of environment variables, background tasks, and bindings. 61 | 62 | ```javascript 63 | export default async function main(event) { 64 | return handleRequest(event?.request, event?.args); 65 | } 66 | 67 | async function handleRequest(request, args) { 68 | return new Response('Hello from Azion!'); 69 | 70 | return handle(request, { args }); 71 | } 72 | ``` 73 | *Atention: The ECMAScript Module style is only supported by the Azion CLI during build time. This method allows you to export functions as modules, which will then be processed and deployed via the CLI. If you are not using the Azion CLI for build and deployment, this style may not be compatible with your runtime environment.* 74 | 75 | --- 76 | 77 | ## **3. Event Handling** 78 | 79 | Azion edge functions are primarily designed to handle HTTP requests via the Fetch Event API. However, they can also interact with other types of events, such as WebSockets or custom event triggers. 80 | 81 | ### **3.1 HTTP Request Handling** 82 | Azion functions use the Fetch API to handle incoming HTTP requests. Functions can parse headers, access the request body, and return structured responses. 83 | 84 | ```javascript 85 | async function handleRequest(request) { 86 | const { headers } = request; 87 | const userAgent = headers.get('User-Agent') || 'Unknown'; 88 | return new Response('User Agent: ' + userAgent); 89 | } 90 | ``` 91 | 92 | --- 93 | 94 | ## **4. Environment Variables** 95 | 96 | Azion functions can interact with environment variables to manage configurations, credentials, and other operational data. The `env` object exposes these variables within functions, ensuring secure access to sensitive information without hardcoding. 97 | 98 | ### **4.1 Accessing Environment Variables** 99 | ```javascript 100 | const apiToken = Azion.env.get('API_SERVICE_TOKEN'); 101 | ``` 102 | 103 | 104 | ### **4.2 Support Process.env API** 105 | ```javascript 106 | process.env.VAR_NAME 107 | ``` 108 | 109 | 110 | Environment variables can store data such as: 111 | - API keys 112 | - Secrets 113 | - Configuration options 114 | 115 | --- 116 | 117 | ## **5. Logging and Debugging** 118 | 119 | Azion provides built-in logging through `console.log`, enabling developers to track execution flows, errors, and other events. Structured logs can also be set up using bindings, which provide additional control over log data. 120 | 121 | ### **5.1 Basic Logging** 122 | ```javascript 123 | console.log('Handling request at the edge...'); 124 | console.error('Error processing request:', error); 125 | ``` 126 | 127 | --- 128 | 129 | ## **6. Error Handling and Reporting** 130 | 131 | Error handling in Azion functions follows JavaScript’s standard `try...catch` mechanism. All unhandled exceptions are automatically logged and reported to Azion's monitoring services. 132 | 133 | ### **6.1 Example of Error Handling** 134 | ```javascript 135 | try { 136 | // Main logic 137 | } catch (error) { 138 | console.error('An unexpected error occurred:', error); 139 | } 140 | ``` 141 | 142 | Azion also supports structured error reporting through GraphQL. Access the Documentation [here](https://www.azion.com/en/documentation/devtools/graphql-api/queries/). 143 | 144 | --- 145 | 146 | ## **7. Edge Storage and SQL API** 147 | 148 | Azion provides APIs for interacting with persistent storage and executing SQL queries directly from Edge Functions. 149 | 150 | ### **7.1 Edge Storage API** 151 | The Azion Edge Storage API allows functions to interact with buckets, storing and retrieving data at the edge. 152 | 153 | ```javascript 154 | async Storage.put(key, value, options) 155 | ``` 156 | 157 | 158 | 159 | ```js 160 | import Storage from "azion:storage"; 161 | 162 | async function handleRequest(event) { 163 | try{ 164 | const bucket = "mybucket"; 165 | const storage = new Storage(bucket); 166 | const key = "test"; 167 | const data = JSON.stringify({ 168 | name:"John", 169 | address:"Abbey Road" 170 | }); 171 | const buffer = new TextEncoder().encode(data); 172 | await storage.put(key, buffer); 173 | return new Response("OK"); 174 | }catch(error){ 175 | return new Response(error, {status:500}); 176 | } 177 | } 178 | 179 | addEventListener("fetch", (event) => { 180 | event.respondWith(handleRequest(event)); 181 | }); 182 | 183 | ``` 184 | 185 | #### **7.1.1 Parameters** 186 | 187 | 188 | | Parameter | Type | Description | 189 | | - | - | - | 190 | | `key` | string | Identifier that allows the search for an object in the storage | 191 | | `value` | ArrayBuffer ou ReadableStream | Content of the object being stored. In case `value` implements a [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream), the Stream APIs can be used, and the option `content-lenght` is required | 192 | | `options` | object | The `options` attributes are described in the table below | 193 | 194 | 195 | ### **7.2 Edge SQL API** 196 | Azion Edge Functions can also execute SQL queries on the Azion Edge SQL API, which provides an interface for interacting with a database. 197 | 198 | ```javascript 199 | import { Database } from "azion:sql"; 200 | 201 | async function db_query() { 202 | let connection = await Database.open("mydatabase"); 203 | let rows = await connection.query("select * from users"); 204 | let column_count = rows.columnCount(); 205 | let column_names = []; 206 | for (let i = 0; i < column_count; i++) { 207 | column_names.push(rows.columnName(i)); 208 | } 209 | let response_lines = []; 210 | response_lines.push(column_names.join("|")); 211 | let row = await rows.next(); 212 | while (row) { 213 | let row_items = []; 214 | for (let i = 0; i < column_count; i++) { 215 | row_items.push(row.getString(i)); 216 | } 217 | response_lines.push(row_items.join("|")); 218 | row = await rows.next(); 219 | } 220 | const response_text = response_lines.join("\n"); 221 | return response_text; 222 | } 223 | 224 | async function handle_request(request) { 225 | if (request.method != "GET") { 226 | return new Response("Method not allowed", { status: 405 }); 227 | } 228 | try { 229 | return new Response(await db_query()); 230 | } catch (e) { 231 | console.log(e.message, e.stack); 232 | return new Response(e.message, { status: 500 }); 233 | } 234 | } 235 | 236 | addEventListener("fetch", (event) => 237 | event.respondWith(handle_request(event.request)) 238 | ); 239 | ``` 240 | 241 | --- 242 | 243 | ## **8. Network and Metadata API** 244 | 245 | Azion functions provide access to network-specific and metadata information, such as GeoIP data, client IP addresses, and TLS details, enhancing security and performance. 246 | 247 | ### **8.1 Network List API** 248 | The `Azion.networkList.contains` interface allows functions to check if an IP address belongs to a specified network list. 249 | 250 | ```javascript 251 | if (Azion.networkList.contains('192.168.1.1')) { 252 | return new Response('IP is within the network'); 253 | } 254 | ``` 255 | 256 | ### **8.2 Metadata API** 257 | Edge Functions can access request metadata, such as GeoIP, TLS certificates, and client information. 258 | 259 | ```javascript 260 | let ip = event.request.metadata["remote_addr"] // Accessing the remote address 261 | ``` 262 | 263 | | Name | Description | 264 | |----------------------------------|----------------------------------------------------------------| 265 | | geoip_asn | Autonomous system number | 266 | | geoip_city | City code | 267 | | geoip_city_continent_code | City continent code information | 268 | | geoip_city_country_code | City country code | 269 | | geoip_city_country_name | City country name | 270 | | geoip_continent_code | Continent code | 271 | | geoip_country_code | Country code | 272 | | geoip_country_name | Country name | 273 | | geoip_region | Region code | 274 | | geoip_region_name | Region name | 275 | | remote_addr | Remote (client) IP address | 276 | | remote_port | Remote (client) TCP port | 277 | | remote_user | User informed in the URL. Example: user in http://user@site.com/| 278 | | server_protocol | Protocol being used in the request. Example: HTTP/1.1 | 279 | | ssl_cipher | TLS cipher used | 280 | | ssl_protocol | TLS protocol used | 281 | --- 282 | 283 | Access the full list of metadata APIs in the [official documentation](https://www.azion.com/en/documentation/products/edge-application/edge-functions/runtime/api-reference/metadata/). 284 | 285 | ## **9. Conclusion** 286 | 287 | The Functions API is extensible, allowing for integration with various JavaScript frameworks and custom workflows while providing powerful tools like Edge Storage, Edge SQL, and Metadata APIs and others DevTools. 288 | 289 | ## **10. References** 290 | 291 | [API Reference](https://www.azion.com/en/documentation/products/edge-application/edge-functions/runtime/api-reference/). 292 | 293 | [Environment Variables](https://www.azion.com/en/documentation/products/edge-application/edge-functions/runtime/api-reference/environment-variables/) 294 | 295 | [Network List](https://www.azion.com/en/documentation/products/edge-application/edge-functions/runtime/api-reference/network-list/) 296 | 297 | [Edge Storage](https://www.azion.com/en/documentation/runtime/api-reference/storage/) 298 | 299 | [Edge SQL](https://www.azion.com/en/documentation/runtime/api-reference/edge-sql/) 300 | 301 | [Metadata](https://www.azion.com/en/documentation/products/edge-application/edge-functions/runtime/api-reference/metadata/) 302 | 303 | [Edge Functions For Edge Application](https://www.azion.com/en/documentation/products/edge-application/edge-functions/) 304 | 305 | [Edge Functions For Edge Firewall](https://www.azion.com/en/documentation/products/secure/edge-firewall/edge-functions/) 306 | 307 | --------------------------------------------------------------------------------