GithubHelp home page GithubHelp logo

tempbottle / deno-lambda Goto Github PK

View Code? Open in Web Editor NEW

This project forked from hayd/deno-lambda

0.0 0.0 0.0 13 MB

A deno runtime for AWS Lambda. Deploy deno via docker, SAM, serverless, or bundle it yourself.

License: MIT License

Shell 24.07% JavaScript 0.89% TypeScript 68.39% Dockerfile 6.65%

deno-lambda's Introduction

deno on AWS Lambda

A deno runtime for AWS Lambda.

Deploy deno code via SAR application (see quick start), SAM, serverless, or bundle it yourself.

ci status

Define a handler function, for example:

// hello.ts

import {
  APIGatewayProxyEventV2,
  APIGatewayProxyResultV2,
  Context,
} from "https://deno.land/x/lambda/mod.ts";

export async function handler(
  event: APIGatewayProxyEventV2,
  context: Context,
): Promise<APIGatewayProxyResultV2> {
  return {
    body: `Welcome to deno ${Deno.version.deno} ๐Ÿฆ•`,
    headers: { "content-type": "text/html;charset=utf8" },
    statusCode: 200,
  };
}

Here the handler is hello.handler but this can be configured by the Handler setting.

Configuration

The following environment variables can be set to change deno-lambda's behavior:

  • HANDLER_EXT to set supported extension of handler file e.g. js or bundle.js (default ts).
  • DENO_CONFIG so deno runs with --config=$DENO_CONFIG.
  • DENO_DIR so deno runs with DENO_DIR=$DENO_DIR deno ....
  • DENO_IMPORTMAP so deno runs with --importmap=$DENO_IMPORTMAP.
  • DENO_LOCATION so deno runs with --location=$DENO_LOCATION.
  • DENO_LOCK so deno runs with --lock=$DENO_LOCK.
  • DENO_PERMISSIONS so deno only runs with a specific list of permissions. Deno lambda requires at least --allow-env and --allow-net.
  • DENO_PREFIX prepends to console.log etc. a template literal, this can include requestId and level variables only (default ${level}\tRequestId: ${requestId}\r).
  • DENO_UNSTABLE so deno runs with the --unstable.

Further configuration TBD.

Types

deno-lambda exports Definitely Typed's aws-lambda types, listed in https://deno.land/x/lambda/mod.ts and defined in https://deno.land/x/lambda/types.d.ts.

It's good practice to reference the trigger's type in the handler, for example: APIGateway use APIGatewayProxyEventV2 and APIGatewayProxyResultV2, SQS use SQSEvent, etc.

Note: Despite there being multiple interfaces with the Context suffix, the second handler argument must be Context. These other interfaces can be accessed from the first argument (the event), for example event.requestContext of an APIGatewayProxyEventV2.

How to deploy

The recommended way to deploy is to use the SAR application and either reference the outputted LayerArn as a layer in your function.

See earlier version of quick start for a walkthrough of how to bundle yourself.

See the deno_dir-remapping section for how to include the correct DENO_DIR files to avoid any runtime compilation.

Warning

The way the lambda platform works means that promises not awaited in the handler may never be completed. This is because the underlying container can be suspended between invocations and will sometimes be shutdown afterwards.

export async function badHandler(
  event: APIGatewayProxyEventV2,
  context: Context,
): Promise<APIGatewayProxyResultV2> {
  somethingAsync(); // not awaited so may not complete
  return { statusCode: 200, body: "" };
}

export async function goodHandler(
  event: APIGatewayProxyEventV2,
  context: Context,
): Promise<APIGatewayProxyResultV2> {
  await somethingAsync();
  return { statusCode: 200, body: "" };
}

If you need to return immediately but want to invoke a longer running process you can async-invoke another lambda function (that does the await somethingAsync()).

Related projects


Bundling code

Create a zip file which contains:

  • an entry point which exports an async function (e.g. hello.ts)
  • include any other files needed to run the entry file
  • (optional but preferred) .deno_dir directory

*You can use a different directory with DENO_DIR environment variable.

Alternatively use deno bundle command and include the outputted js file, see also HANDLER_EXT.

DENO_DIR remapping

In order for compile artifacts to be recovered (and avoid runtime compilation) you must do the following directory remapping:

# Compile the handler (and cache dependencies and compile artifacts into DENO_DIR).
DENO_DIR=.deno_dir deno cache hello.ts

# This is the "remapping" step:
cp -R .deno_dir/gen/file/$PWD/ .deno_dir/LAMBDA_TASK_ROOT
# Note: We do the inverse of this operation in bootstrap.

zip lambda.zip -x '.deno_dir/gen/file/*' -r .deno_dir hello.ts  # other source files

Serverless pre-deploy remapping

In a serverless.yml this can be automatically prior to each upload using the serverless-scriptable-plugin:

plugins:
  - serverless-scriptable-plugin

custom:
  scriptHooks:
    before:package:createDeploymentArtifacts: DENO_DIR=.deno_dir deno cache api/candidate.ts && cp -R .deno_dir/gen/file/$PWD/ .deno_dir/LAMBDA_TASK_ROOT

See example-serverless/serverless.yml.

Testing locally with docker-lambda

You can execute deno-lambda locally using docker-lambda. First, unzip the deno-lambda-layer.zip layer into a directory.

Now, from the directory of your application:

# replace LAYER_DIR with the directory you unzipped the layer to e.g. $PWD/layer
# replace hello.handler with your file/handler function
# replace '{}' with the json to pass to the handler
$ docker run -it --rm -v "$PWD":/var/task:ro,delegated -v "LAYER_DIR":/opt:ro,delegated lambci/lambda:provided.al2 hello.handler '{}'
# handler response from goes to stdout

To execute multiple times AKA "stay-open" API mode:

# replace LAYER_DIR with the directory you unzipped to e.g. $PWD/layer
# replace hello.handler with your file.handler function
$ docker run -e DOCKER_LAMBDA_STAY_OPEN=1 -p 9001:9001 -it --rm -v "$PWD":/var/task:ro,delegated -v "LAYER_DIR":/opt:ro,delegated lambci/lambda:provided.al2 hello.handler
Lambda API listening on port 9001...

and in another terminal:

# replace '{}' with the json to pass to the handler
$ aws lambda invoke --endpoint http://localhost:9001 --no-sign-request --function-name deno-func --payload '{}' output.json
# output.json is populated with the handler response

For more advanced usage, e.g. including multiple layers and installing additional libraries (with yumbda), please consult the docker-lambda documentation.

Advanced logging

You can set the way console.log etc. outputs to cloudwatch logs using DENO_PREFIX. You can include the line number using ${(new Error).stack.split('\n')[4]} or the datetime using ${new Date().toISOString()} (though the datetime of every cloudwatch event is part of the event itself.

Use these as a template literal, for example:

DENO_PREFIX=${level}\t${requestId}\t${(new Error).stack.split('\n')[4]}\r

This will prefix each log with the level, the request id and the line number:

Screen Shot 2020-02-11 at 18 12 42


Many thanks to Yoshiya Hinosawa's blogpost for the initial work on this runtime.

deno-lambda's People

Contributors

alon2303 avatar brianleroux avatar dependabot[bot] avatar hayd avatar ije avatar kim-cloudconformity avatar lsagetlethias avatar lucacasonato avatar turlockmike avatar web-flow avatar wperron avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.