Giter Club home page Giter Club logo

serverless-websockets-plugin's Introduction

Serverless Websockets Plugin

Deprecation Notice

This repo is now deprecated, and we are no longer maintaining it. v1.38.0 of the framework now includes built-in support for websockets. Please check the docs for more info

1. Installation

Install the plugin by adding it to your service dependencies:

npm i serverless-websockets-plugin --save

Note: Because this plugin uses the new ApiGatewayV2 service in the AWS SDK, it requires v1.35.0+ of the Serverless Framework.

2. Usage

Load the serverless-websockets-plugin, then optionally provide a new API name and Route Selection Expression, and finally define your WebSockets events and their route keys:

service: serverless-websockets-service

# Load the plugin
plugins:
  - serverless-websockets-plugin

provider:
  name: aws
  runtime: nodejs8.10
  
  # Optional
  websocketApiName: foobar
  websocketApiRouteSelectionExpression: $request.body.action

functions:
  connectionManagement:
    handler: handler.connectionManagement
    events:
      - websocket:
          routeKey: $connect
      - websocket:
          routeKey: $disconnect
  defaultMessage:
    handler: handler.default
    events:
      - websocket:
          routeKey: $default
  chatMessage:
    handler: handler.chat
    events:
      - websocket:
          routeKey: message
  twoWayMessage:
    handler: handler.twoWay
    events:
      - websocket:
          routeKey: twoway
          # The property below will enable an integration response in the API Gateway.
          # See https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-route-response.html
          routeResponseSelectionExpression: $default

serverless-websockets-plugin's People

Contributors

agutoli avatar alexdebrie avatar ashishtilara avatar braindx avatar brianneisler avatar chrillo avatar coldfire87 avatar dbramwell avatar eahefnawy avatar guerrerocarlos avatar khornberg avatar popenkomaksim avatar shortjared avatar skithy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

serverless-websockets-plugin's Issues

Custom domain support

With the current setup the ApiGatewayManagementApi endpoint is derived from the requestContext.domainName , this works fine as long as one is using the AWS supplied URLS. If one is to use a custom domain like realtime.domain.com the endpoint would be set to https://realtime.domain.com/stage which (probably for signature reasons) causes 403 errors when using the @connections endpoint.

I solved this problem by deriving the correct domain from the supplied apiId property

Unable to fetch logs

I have following function in my serverless.yml

functions:
  connections:
    handler: handler.connections
    events:
      - websocket:
          routeKey: $connect
      - websocket:
          routeKey: $disconnect

But can't fetch logs with sls logs -f connections

Gives error:

  Serverless Error ---------------------------------------
 
  1 validation error detected: Value '[]' at 'logStreamNames' failed to satisfy constraint: Member must have length greater than or equal to 1

Using serverless 1.35.1. Should the logs even work with websocket functions or should I maybe call it somehow differently?

Can't update the route expression

Anyone else having trouble changing the route expression path? Even when i try to change manually in the console, and the gui shows the updated route expression, routes are still based on request.body.action

Deployment/Removal error: that.sdk[service] is not a constructor

I get the following error when trying to deploy/remove a stack with the websockets plugin. I haven't tried to do any functionality yet, I just want to see it deployed.

Serverless: Stack removal finished...
  Type Error ---------------------------------------------
  that.sdk[service] is not a constructor
     For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.
service: skippy-websockets

plugins:
  - serverless-websockets-plugin

provider:
  name: aws
  runtime: nodejs8.10
  region: eu-west-1

functions:
  connectionHandler:
    handler: handler.hello
    events:
      - websocket:
          routeKey: $connect
      - websocket:
          routeKey: $disconnect

  defaultHandler:
    handler: handler.hello
    events:
      - websocket:
          routeKey: $default

  actionHandler:
    handler: handler.hello
    events:
      - websocket:
          routeKey: myAction
'use strict';

module.exports.hello = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Go Serverless v1.0! Your function executed successfully!',
      input: event,
    }),
  };

  // Use this code if you don't use the http event with the LAMBDA-PROXY integration
  // return { message: 'Go Serverless v1.0! Your function executed successfully!', event };
};

Support for multi service deployments

I’d like to deploy API Gateway websocket endpoints to 1 single websocket API but from multiple services (or serverless.yml files). Right now I see the plugin deletes the endpoints and creates new on every deployment. Will this be possible when CF is supported?

For example in 1 serverless.yml i’d like to specify a sendMessage endpoint.. for my chat service and the other connect/disconnect endpoints in another serverless.yml service.

Thanks!

Add support for un-versioned functions

I tried to use serverless-websockets-plugin but on sls deploy I have this error:

TypeError: Cannot read property 'OutputValue' of undefined
    at /home/caiiiycuk/aws/gpx-play-java-stack/payments/node_modules/serverless-websockets-plugin/dist/index.js:159:23
    at Array.map (native)
    at ServerlessWebsocketsPlugin._callee2$ (/home/caiiiycuk/aws/gpx-play-java-stack/payments/node_modules/serverless-websockets-plugin/dist/index.js:148:63)
    at tryCatch (/home/caiiiycuk/aws/gpx-play-java-stack/payments/node_modules/regenerator-runtime/runtime.js:62:40)
    at Generator.invoke [as _invoke] (/home/caiiiycuk/aws/gpx-play-java-stack/payments/node_modules/regenerator-runtime/runtime.js:288:22)
    at Generator.prototype.(anonymous function) [as next] (/home/caiiiycuk/aws/gpx-play-java-stack/payments/node_modules/regenerator-runtime/runtime.js:114:21)
    at asyncGeneratorStep (/home/caiiiycuk/aws/gpx-play-java-stack/payments/node_modules/serverless-websockets-plugin/dist/index.js:3:103)
    at _next (/home/caiiiycuk/aws/gpx-play-java-stack/payments/node_modules/serverless-websockets-plugin/dist/index.js:5:194)
    at <anonymous>
From previous event:
    at PluginManager.invoke (/home/caiiiycuk/.nvm/versions/node/v8.0.0/lib/node_modules/serverless/lib/classes/PluginManager.js:391:22)
    at PluginManager.run (/home/caiiiycuk/.nvm/versions/node/v8.0.0/lib/node_modules/serverless/lib/classes/PluginManager.js:422:17)
    at variables.populateService.then.then (/home/caiiiycuk/.nvm/versions/node/v8.0.0/lib/node_modules/serverless/lib/Serverless.js:111:33)
    at runCallback (timers.js:800:20)
    at tryOnImmediate (timers.js:762:5)
    at processImmediate [as _immediateCallback] (timers.js:733:5)
From previous event:
    at Serverless.run (/home/caiiiycuk/.nvm/versions/node/v8.0.0/lib/node_modules/serverless/lib/Serverless.js:98:6)
    at serverless.init.then (/home/caiiiycuk/.nvm/versions/node/v8.0.0/lib/node_modules/serverless/bin/serverless:43:28)
    at <anonymous>
 
  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Issues:        forum.serverless.com
 
  Your Environment Information -----------------------------
     OS:                     linux
     Node Version:           8.0.0
     Serverless Version:     1.36.3

Looks like this problem is not critical because stack is deployed, but I didn't tried if ws actually works.
My serverless.yaml:

service: payments

plugins:
  - serverless-websockets-plugin

custom:
  defaults: ${file(../config/aws/defaults.yaml)}

provider:
  name: aws
  runtime: ${self:custom.defaults.runtime}
  timeout: ${self:custom.defaults.timeout}
  memory: ${self:custom.defaults.memory}
  versionFunctions: ${self:custom.defaults.versionFunctions}
  deploymentPrefix: ${self:custom.defaults.deploymentPrefix}
  stackTags: ${self:custom.defaults.stackTags}
  websocketApiName: ws
  websocketApiRouteSelectionExpression: $request.body.action

package:
  artifact: build/libs/bundle.jar

functions:
  Products:
    handler: com.gateway.ProductsPost
    events:
      - http:
          path: products
          method: post
  Charge:
    handler: com.gateway.ChargePost
    events:
      - http:
          path: charge
          method: post

  WSConnection:
    handler: com.gateway.ws.Connection
    events:
      - websocket:
          routeKey: $connect
      - websocket:
          routeKey: $disconnect

  WSDefault:
    handler: com.gateway.ws.Default
    events:
      - websocket:
          routeKey: $default

resources:
  Description: payments backend

Service information (after stack is updated):

Service Information
service: payments
stage: dev
region: us-east-1
stack: payments-dev
api keys:
  None
endpoints:
  POST - https://rx2132wumf.execute-api.us-east-1.amazonaws.com/dev/products
  POST - https://rx2132wumf.execute-api.us-east-1.amazonaws.com/dev/charge
functions:
  Products: payments-dev-Products
  Charge: payments-dev-Charge
  WSConnection: payments-dev-WSConnection
  WSDefault: payments-dev-WSDefault
layers:
  None

Stack Outputs
ServiceEndpoint: https://rx2132wumf.execute-api.us-east-1.amazonaws.com/dev
ServerlessDeploymentBucketName: payments-dev-serverlessdeploymentbucket-1vg9uf12cemw1

Issue with the example sls project: 502 error

Hey!

I installed the example code in a fresh environment, however I'm getting an error while attempting to connect with the following command:
wscat -c wss://*******884.execute-api.us-east-1.amazonaws.com/dev

I receive the following error in response:
error: Unexpected server response: 502

Upon attempting to check the logs for the connectionManager I received the following error:

$ sls logs -f connectionManager
 
  Serverless Error ---------------------------------------
 
  1 validation error detected: Value '[]' at 'logStreamNames' failed to satisfy constraint: Member must have length greater than or equal to 1
 
  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Issues:        forum.serverless.com
 
  Your Environment Information -----------------------------
     OS:                     darwin
     Node Version:           8.5.0
     Serverless Version:     1.35.1

Am I doing something wrong or is this indicative of a bug?

Unresolved resource dependencies [ApiGatewayRestApi] in the Resources block of the template

I am trying to export the "ApiGatewayRestApi" into the ENV param:
provider:
environment:
GW_URL:
Fn::Join:
- ""
- - "https://"
- Ref: "ApiGatewayRestApi"
- ".execute-api.${self:custom.region}.amazonaws.com/${self:custom.stage}"
it's return a error
Unresolved resource dependencies [ApiGatewayRestApi] in the Resources block of the template
it's work fine in regular Serverless project
see reference
https://serverless.com/framework/docs/providers/aws/guide/resources/
http://www.goingserverless.com/blog/api-gateway-url

can you help
Thanks

Custom authorizer support?

Awesome work on this plugin. :)

Just wondering though whether this plugin supports custom authorizers for WS?

Add ability to use "response"

Two-way communication is possible so long as the route has an Integration Response

Since implementation is LAMBDA_PROXY, the integration response does nothing but pass on the response to the socket (its body becomes the socket's body)
image

Could this be a feature of this plugin, to add a "twoWay: true" option on the routes?

Explanation on API config

So I'm trying to understand well how everything works to start coding my own service using web sockets.

First of all, is this line required, or is it a typo?

Then, what is the goal of the API gateway config stored in the DynamoDB table? I understood that it won't be required anymore with CloudFormation support, but still, I don't get it.
Basically, we store the domain name (corresponding to API id + API region) and the stage. The stage and API region could be passed as environment variables, but we would still miss the API id that can only be fetched during runtime. But if we are able to retrieve it in the event (see here), why do we need to store it in DynamoDB?
Could I replace this by a manually added env variable containing the AP id, or is the API id changing on every deploy?

Thanks for the great plugin, I hope CloudFormation support is coming soon :)

[Edit] Or maybe the API config is stored in order to use it also when the lambda event is DynamoDB stream and we don't have the websocket information?

Publish to NPM

Could you please publish the current version to NPM?

It took me a few hours to find out that the "routeResponseSelectionExpression" feature does not work with the version that's currently on npm.

Thanks!

CloudFormation Support

As of 2/8/2019, CloudFormation now supports ApiGatewayV2. Is the plan to modify the plugin to support CloudFormation or to just do a new implementation inside of the core framework?

Add minimum supported serverless version in readme

Went through a lot of trouble debugging an issue (same as in #10) that prevented me from deploying / removing stack formations with this plugin. Updating serverless to 1.35 fixed the problem.

It'd be great to have the minimum required serverless version on the readme! Even better, if that could be included in the error message.

Add support for AWS_IAM type authorizers

Would like to be able to use syntax like:

functions:                                                                                           
  # manage connection and disconnection of clients                                                   
  connectionManager:                                                                                 
    handler: sockets.connectionManager                                                               
    events:                                                                                          
      - websocket:                                                                                   
          authorizer: aws_iam                                                                        
          routeKey: $connect

I would then manage the IAM policy separately with the following permissions (as recommended by AWS)

  statement {                                                                                         
    actions = [ "execute-api:Invoke" ]                                                                
    resources = [                                                                                     
      "arn:aws:execute-api:${REGION}:${ACCOUNT_ID}:${API_ID}/${STAGE}/*"  
    ]                                                                                                 
    effect = "Allow"                                                                                 
  } 

Maximum number of Integrations for this API has been reached.

After a fair few deployments (50 or so?) I get the following:

Serverless: Recoverable error occurred (Maximum number of Integrations for this API has been reached.  Please contact AWS if you need additional Integrations.), sleeping for 5 seconds. Try 1 of 4

I've tried removing all past versions of my lamba functions, but feel like there must be some underlying 'links' still floating around in the API Gateway. Is there something i'm missing? I see this comment which seems to imply that this issue shouldn't exist

This repo is now deprecated

Hey all, we just added support for websockets in framework core via CF (v1.38 just released). So we are now deprecating this repo.

We will be adding authorizer support and other websocket features in upcoming releases.

Thanks all for the feedback! Please provide any further feedback in the framework repo.

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.