├── .gitignore ├── LICENSE ├── README.md ├── Serverless_Websocket_Flow.png ├── Webchat.gif ├── dynamodb.yml ├── s3.yml ├── src ├── lib │ └── scan_table.py ├── requirements.txt └── websocket │ ├── connect.py │ ├── disconnect.py │ ├── list_users.py │ ├── message.py │ └── register.py ├── webchat ├── .gitignore ├── README.md ├── package-lock.json ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt └── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── WebChat.js │ ├── config.js │ ├── github.png │ ├── index.css │ ├── index.js │ ├── logo.png │ ├── reportWebVitals.js │ ├── senior.png │ └── setupTests.js ├── websocket.yml └── websocket_route.yml /.gitignore: -------------------------------------------------------------------------------- 1 | **/node_modules 2 | **/.aws-sam/ 3 | **/*.toml 4 | **/.eslintcache -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Serverless Websocket - Webchat Sample 2 | 3 | Este projeto é um exemplo de um chat web, utilizando um Websocket Serverless construído em arquitetura AWS. Além disso, uma pequena página web foi desenvolvida para funcionar como um chat web, desenvolvida em ReactJS. 4 | 5 | O projeto pode ser executado no nível gratuito da sua conta da AWS para testes. Ao final dos testes, lembre-se de executar a etapa para interromper a execução. 6 | 7 | ## Arquitetura 8 | 9 | A arquitetura utiliza os serviços: 10 | 11 | - AWS S3 12 | - Armazenamento dos templates do AWS SAM/CloudFormation 13 | - AWS DynamoDB 14 | - Registro dos usuários conectados ao Websocket 15 | - AWS API Gateway (Websocket) 16 | - Websocket Serverless para comunicação do webchat 17 | - AWS Lambda Function 18 | - Funções Lambda para registro de usuários no DynamoDB, troca de mensagens entre os usuários conectados, listar usuarios e remover usuários desconectados do DynamoDB 19 | 20 | A arquitetura foi toda provisionada utilizando templates AWS SAM e CloudFormation, portanto, permite a replicação de forma fácil para outras contas na AWS. 21 | 22 | A imagem abaixo demonstra o fluxo do processo. 23 | 24 | ![Flow](./Serverless_Websocket_Flow.png) 25 | 26 | ## Aplicação 27 | 28 | A aplicação foi desenvolvida com o framework ReactJS de forma simples, focando em demonstrar o uso da arquitetura do Websocket Serverless. 29 | 30 | O projeto está localizado na pasta `./webchat`. 31 | 32 | Ao acessar a aplicação, o usuário deve informar um nome de usuário e acessar o chat. 33 | As mensagens recebidas e enviadas serão listadas na parte principal da tela. Logo abaixo um campo para digitação de texto e um botão para envio estão disponibilizados. 34 | 35 | ![Webchat](./Webchat.gif) 36 | 37 | ## Execução 38 | 39 | Faça clone deste repositório para sua máquina local. 40 | 41 | Para execução do projeto, é necessário subir a arquitetura na AWS, conforme os passos a seguir. Além disso, são necessários os requisitos: 42 | 43 | ### Pré-requisitos 44 | 45 | - AWS SAM 46 | - Acessar a [documentação](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) e instalar o cliente (CLI) 47 | - NodeJS 48 | - Instalar (caso ainda não tenha) o aplicativo NodeJS mais recente, disponível em https://nodejs.org. 49 | 50 | ### Arquitetura 51 | 52 | Para reproduzir este projeto precisamos subir a arquitetura na AWS. Os templates são descritos abaixo e devem ser carregados em ordem. 53 | 54 | Para subir a arquitetura, vamos utilizar o serviço [AWS SAM](https://aws.amazon.com/pt/serverless/sam/). Instalar conforme pré-requisito. 55 | 56 | Abra o terminal/console no diretório do repositório clonado. 57 | 58 | 1. **AWS S3** 59 | 60 | O primeiro passo é criar um bucket no serviço [AWS S3](https://docs.aws.amazon.com/pt_br/AmazonS3/latest/dev/Welcome.html). Este bucket será utilizado para armazenar os templates e arquivos locais que são utilizados pelos próximos templates. Como utilizados o conceito de "Nested Stack", precisamos que o template aninhado esteja disponível em um bucket S3. 61 | 62 | Execute o comando: `sam deploy --guided -t s3.yml` 63 | 64 | Serão solicitadas algumas informações e por fim o nome do bucket criado será apresentado no console. **Guarde esta informação!** 65 | 66 | 2. **AWS DynamoDB** 67 | 68 | O AWS DynamoDB é utilizado para armazenar as conexões ativas no websocket. Sempre que um usuário é conectado, um registro é inserido em uma tabela do DynamoDB. Assim que o usuário é desconectado este registro é excluído. 69 | 70 | Execute o comando: `sam deploy --guided -t dynamodb.yml` 71 | 72 | Uma das informações solicitadas será o nome da stack (pilha) que será criada. **Guarde esta informação, pois será utilizada futuramente!** 73 | 74 | 3. **AWS API Gateway e AWS Lambda Functions** 75 | 76 | Nesta etapa, o mesmo template é utilizado para criar a API Websocket e também para criar as funções Lambda que são responsáveis pelas interações com o websocket. 77 | 78 | Aqui precisamos de dois comandos para execução e vamos utilizar as informações que guardamos anteriormente. 79 | 80 | Primeiro comando: `sam package -t websocket.yml --s3-bucket "Informe o nome do bucket S3 aqui" --output-template-file websocket_package.yml` 81 | 82 | Após a execução deste comando, será criado o arquivo `websocket_package.yml`. Este arquivo possui o mesmo conteúdo que o original `websocket.yml`, porém, substitui os arquivos locais por arquivos armazenados no bucket S3 informado. Além disso, este é o arquivo utilizado para subir a arquitetura desta etapa. 83 | 84 | Segundo comando: `sam deploy --guided -t websocket_package.yml --capabilities CAPABILITY_AUTO_EXPAND CAPABILITY_IAM` 85 | 86 | Depois da execução do segundo comando, uma das informações solicitadas será o nome da stack responsável pela tabela DynamoDB (WebSocketTableStackName). Este parâmetro deve ser preenchido com a segunda informação que foi guardada, no passo do AWS DynamoDB. 87 | 88 | Ao final do processo, será apresentado o endereço do Websocket, algo parecido com `wss://WEBSOCKET.execute-api.REGIAO.amazonaws.com/Prod`. **Guarde esta informação, será usada posteriormente**. 89 | 90 | ### Aplicação 91 | 92 | Abra o arquivo `config.js` que está em `webchat/src/` com o editor de sua preferência e altere o valor da variável `websocketAddress` informando o endereço de websocket obtido no passo anterior. 93 | 94 | Abra o terminal/console e vá até o local onde repositório foi clonado e acesse a pasta `webchat`. 95 | 96 | No terminal, execute o comando: `npm start`. 97 | 98 | ## Interrompendo a execução 99 | 100 | Caso você queira interromper a execução dos serviços na sua conta da AWS para evitar possíveis custos no futuro, siga este passo a passo. 101 | 102 | 1. Acesse sua conta da AWS 103 | 2. No console da AWS, procure pelo serviço AWS CloudFormation 104 | 3. Serão listadas todas as stacks (pilhas) que estão em execução em sua conta. (Fique atento a região AWS selecionada). 105 | 4. Em ordem, exclua as stacks: AWS Websocket e Lambda Functions, DynamoDB e S3. 106 | 107 | **Obs.:** Algumas stacks estarão marcadas como "NESTED", estas stacks não precisam ser excluídas manualmente, serão excluídas quando solicitar a exclusão da stack principal. 108 | -------------------------------------------------------------------------------- /Serverless_Websocket_Flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SeniorSA/serverless-websocket/6ab45f3319965ef54fa8f3b022ab4a39f846c410/Serverless_Websocket_Flow.png -------------------------------------------------------------------------------- /Webchat.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SeniorSA/serverless-websocket/6ab45f3319965ef54fa8f3b022ab4a39f846c410/Webchat.gif -------------------------------------------------------------------------------- /dynamodb.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: >- 3 | AWS Serverless Websocket Sample - DynamoDB Stack 4 | 5 | Transform: 6 | - AWS::Serverless-2016-10-31 7 | 8 | Resources: 9 | 10 | # Table responsible for keep connected users 11 | WebSocketConnectionsTable: 12 | Type: AWS::DynamoDB::Table 13 | Properties: 14 | # On Demand Mode - Scale according requests 15 | BillingMode: PAY_PER_REQUEST 16 | # Defines table attributes and types 17 | AttributeDefinitions: 18 | - AttributeName: connectionId 19 | AttributeType: S 20 | - AttributeName: userName 21 | AttributeType: S 22 | # Defines main index (DynamoDB allows only query records by an index) 23 | KeySchema: 24 | - AttributeName: connectionId 25 | KeyType: HASH 26 | # Defines a second index 27 | GlobalSecondaryIndexes: 28 | - IndexName: user-index 29 | KeySchema: 30 | - AttributeName: userName 31 | KeyType: HASH 32 | # Defines that this index can be query all table attributes 33 | Projection: 34 | ProjectionType: ALL 35 | 36 | Outputs: 37 | WebSocketConnectionsTableName: 38 | Description: DynamoDB Table name for WebSocket ConnectionsIds 39 | Value: 40 | Ref: WebSocketConnectionsTable 41 | Export: 42 | Name: !Sub ${AWS::StackName}:WebSocketConnectionsTableName 43 | -------------------------------------------------------------------------------- /s3.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: AWS Serverless Websocket Sample - Websocket Stack 3 | 4 | Transform: 5 | - AWS::Serverless-2016-10-31 6 | 7 | 8 | Resources: 9 | # Creates S3 Bucket for store SAM/CloudFormation templates 10 | WebsocketTemplateBucket: 11 | Type: AWS::S3::Bucket 12 | 13 | Outputs: 14 | WebsocketTemplateBucketARN: 15 | Description: S3 Bucket ARN 16 | Value: 17 | Fn::GetAtt: 18 | - WebsocketTemplateBucket 19 | - Arn 20 | Export: 21 | Name: !Sub ${AWS::StackName}:WebsocketTemplateBucketARN 22 | WebsocketTemplateBucketName: 23 | Description: S3 Bucket Name 24 | Value: 25 | Ref: WebsocketTemplateBucket 26 | Export: 27 | Name: !Sub ${AWS::StackName}:WebsocketTemplateBucketName -------------------------------------------------------------------------------- /src/lib/scan_table.py: -------------------------------------------------------------------------------- 1 | import json 2 | import boto3 3 | 4 | def scan(table_name): 5 | dynamodb = boto3.resource('dynamodb') 6 | connections = dynamodb.Table(table_name) 7 | done = False 8 | start_key = None 9 | scan_kwargs = {} 10 | connections_list = [] 11 | 12 | while not done: 13 | if start_key: 14 | scan_kwargs['ExclusiveStartKey'] = start_key 15 | response = connections.scan(**scan_kwargs) 16 | connections_list += response.get('Items', []) 17 | start_key = response.get('LastEvaluatedKey', None) 18 | done = start_key is None 19 | 20 | return connections_list -------------------------------------------------------------------------------- /src/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3==1.16.0 -------------------------------------------------------------------------------- /src/websocket/connect.py: -------------------------------------------------------------------------------- 1 | import json 2 | import boto3 3 | import os 4 | 5 | def handler(event, context): 6 | client = boto3.client('dynamodb') 7 | # Register in DynamoDB table when a new user connects. 8 | client.put_item( 9 | TableName=os.getenv('TABLE_NAME'), 10 | Item={ 11 | 'connectionId': { 12 | 'S': event['requestContext'].get('connectionId') 13 | }, 14 | 'userName': { 15 | 'S': 'undefined' 16 | }}) 17 | return { 18 | 'statusCode': 200, 19 | 'body': json.dumps('Connected to the server!') 20 | } -------------------------------------------------------------------------------- /src/websocket/disconnect.py: -------------------------------------------------------------------------------- 1 | import json 2 | import boto3 3 | import os 4 | from lib.scan_table import scan 5 | 6 | def handler(event, context): 7 | # Get the connection Id from request when a user disconnects 8 | connectionId=event['requestContext'].get('connectionId') 9 | client = boto3.client('dynamodb') 10 | 11 | # Get data user from DynamoDB 12 | item = client.get_item( 13 | TableName=os.getenv('TABLE_NAME'), 14 | Key={'connectionId': {'S': connectionId}} 15 | ) 16 | 17 | userName = item.get('Item').get('userName').get('S') 18 | 19 | # Deletes the user disconnected from DynamoDB 20 | client.delete_item(TableName=os.getenv('TABLE_NAME'), Key={"connectionId": {"S": event['requestContext'].get('connectionId')}}) 21 | 22 | # Get all users connected 23 | connections_list = scan(os.getenv('TABLE_NAME')) 24 | 25 | endpoint_api = os.getenv('WEBSOCKET_ADDRESS') 26 | apigateway_client = boto3.client('apigatewaymanagementapi', endpoint_url=endpoint_api) 27 | 28 | # Send a message to all users notifying the user disconnected 29 | for connection in connections_list: 30 | apigateway_client.post_to_connection(ConnectionId=connection['connectionId'], Data=json.dumps({'action': 'userExit', 'userName': userName, 'connectionId': connectionId})) 31 | 32 | return { 33 | 'statusCode': 200, 34 | 'body': json.dumps('Disconnected from the server!') 35 | } -------------------------------------------------------------------------------- /src/websocket/list_users.py: -------------------------------------------------------------------------------- 1 | import json 2 | import boto3 3 | import os 4 | from lib.scan_table import scan 5 | 6 | def handler(event, context): 7 | # Get the connection Id from the user 8 | connectionId=event['requestContext'].get('connectionId') 9 | 10 | # Get the list of users connected 11 | connections_list = scan(os.getenv('TABLE_NAME')) 12 | 13 | # Filter the users connected, removing the requester 14 | connections_filtered = list(filter(lambda item: (item['connectionId'] != connectionId), connections_list)) 15 | 16 | users_list = list(map(lambda item: ({'userName': item['userName'], 'connectionId': item['connectionId']}), connections_filtered)) 17 | 18 | output = {'action': 'list', 'users': users_list} 19 | 20 | # Returns the users connected 21 | return { 22 | 'statusCode': 200, 23 | 'body': json.dumps(output) 24 | } 25 | -------------------------------------------------------------------------------- /src/websocket/message.py: -------------------------------------------------------------------------------- 1 | import json 2 | import boto3 3 | import os 4 | 5 | def handler(event, context): 6 | body = json.loads(event['body']) 7 | 8 | receivers = body.get('receivers', None) 9 | message = body.get('message', None) 10 | sender = body.get('sender', None) 11 | if receivers and message and sender: 12 | 13 | endpoint_api = os.getenv('WEBSOCKET_ADDRESS') 14 | apigateway_client = boto3.client('apigatewaymanagementapi', endpoint_url=endpoint_api) 15 | 16 | # Send the "message" from "sender" to all users in variable "receivers" 17 | for receiver in receivers: 18 | apigateway_client.post_to_connection(ConnectionId=receiver['connectionId'], Data=json.dumps({'action': 'message', 'sender': sender, 'receiver': receiver, 'message': message})) 19 | 20 | return { 21 | 'statusCode': 200, 22 | 'body': json.dumps('Message sent successfully') 23 | } 24 | return { 25 | 'statusCode': 400, 26 | 'body': json.dumps('Receiver, sender and message are mandatory fields') 27 | } -------------------------------------------------------------------------------- /src/websocket/register.py: -------------------------------------------------------------------------------- 1 | import json 2 | import boto3 3 | import os 4 | from lib.scan_table import scan 5 | 6 | def handler(event, context): 7 | #Get the connection Id 8 | connectionId=event['requestContext'].get('connectionId') 9 | 10 | body = json.loads(event['body']) 11 | 12 | if 'userName' in body: 13 | userName = body['userName'] 14 | client = boto3.client('dynamodb') 15 | # Updates the user record setting the userName in DynamoDB Table 16 | client.update_item( 17 | TableName=os.getenv('TABLE_NAME'), 18 | Key={'connectionId': {'S': connectionId}}, 19 | UpdateExpression='SET userName = :userName', 20 | ExpressionAttributeValues={ 21 | ':userName': { 22 | 'S': userName 23 | } 24 | }) 25 | 26 | endpoint_api = os.getenv('WEBSOCKET_ADDRESS') 27 | apigateway_client = boto3.client('apigatewaymanagementapi', endpoint_url=endpoint_api) 28 | 29 | connections_list = scan(os.getenv('TABLE_NAME')) 30 | 31 | # Notify all users connected that a new user is connected 32 | for connection in connections_list: 33 | if (connection['connectionId'] != connectionId): 34 | apigateway_client.post_to_connection(ConnectionId=connection['connectionId'], Data=json.dumps({'action': 'newUser', 'userName': userName, 'connectionId': connectionId})) 35 | 36 | return { 37 | 'statusCode': 200, 38 | 'body': json.dumps('Successfully registered') 39 | } 40 | return { 41 | 'statusCode': 400, 42 | 'body': json.dumps('User name not found') 43 | } -------------------------------------------------------------------------------- /webchat/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /webchat/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 13 | 14 | The page will reload if you make edits.\ 15 | You will also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 35 | 36 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 39 | 40 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | 48 | ### Code Splitting 49 | 50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) 51 | 52 | ### Analyzing the Bundle Size 53 | 54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) 55 | 56 | ### Making a Progressive Web App 57 | 58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) 59 | 60 | ### Advanced Configuration 61 | 62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) 63 | 64 | ### Deployment 65 | 66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) 67 | 68 | ### `npm run build` fails to minify 69 | 70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) 71 | -------------------------------------------------------------------------------- /webchat/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "webchat", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@material-ui/core": "^4.11.2", 7 | "@testing-library/jest-dom": "^5.11.6", 8 | "@testing-library/react": "^11.2.2", 9 | "@testing-library/user-event": "^12.5.0", 10 | "react": "^17.0.1", 11 | "react-dom": "^17.0.1", 12 | "react-scripts": "4.0.1", 13 | "web-vitals": "^0.2.4", 14 | "websocket": "^1.0.32" 15 | }, 16 | "scripts": { 17 | "start": "react-scripts start", 18 | "build": "react-scripts build", 19 | "test": "react-scripts test", 20 | "eject": "react-scripts eject" 21 | }, 22 | "eslintConfig": { 23 | "extends": [ 24 | "react-app", 25 | "react-app/jest" 26 | ] 27 | }, 28 | "browserslist": { 29 | "production": [ 30 | ">0.2%", 31 | "not dead", 32 | "not op_mini all" 33 | ], 34 | "development": [ 35 | "last 1 chrome version", 36 | "last 1 firefox version", 37 | "last 1 safari version" 38 | ] 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /webchat/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SeniorSA/serverless-websocket/6ab45f3319965ef54fa8f3b022ab4a39f846c410/webchat/public/favicon.ico -------------------------------------------------------------------------------- /webchat/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /webchat/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SeniorSA/serverless-websocket/6ab45f3319965ef54fa8f3b022ab4a39f846c410/webchat/public/logo192.png -------------------------------------------------------------------------------- /webchat/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SeniorSA/serverless-websocket/6ab45f3319965ef54fa8f3b022ab4a39f846c410/webchat/public/logo512.png -------------------------------------------------------------------------------- /webchat/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /webchat/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /webchat/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 20vmin; 7 | pointer-events: none; 8 | } 9 | 10 | .icons { 11 | height: 5vmin; 12 | pointer-events: none; 13 | padding: 0 15px 0 15px 14 | } 15 | 16 | .App-header { 17 | min-height: 100vh; 18 | display: flex; 19 | flex-direction: column; 20 | align-items: center; 21 | justify-content: center; 22 | font-size: calc(20px + 2vmin); 23 | } 24 | 25 | .App-link { 26 | color: #61dafb; 27 | } 28 | 29 | @keyframes App-logo-spin { 30 | from { 31 | transform: rotate(0deg); 32 | } 33 | to { 34 | transform: rotate(360deg); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /webchat/src/App.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import logo from './logo.png'; 3 | import senior from './senior.png' 4 | import github from './github.png'; 5 | import './App.css'; 6 | import { TextField, Button, Container, Grid } from '@material-ui/core'; 7 | import WebChat from "./WebChat"; 8 | 9 | class App extends React.Component { 10 | 11 | constructor(props) { 12 | super(props); 13 | this.state = { 14 | userName: "", 15 | login: false 16 | }; 17 | } 18 | 19 | login() { 20 | this.setState(state => ({userName: state.userName, login: true})); 21 | } 22 | 23 | renderChat() { 24 | return 27 | } 28 | 29 | updateValue(event) { 30 | this.setState(state => ({ 31 | userName: event.target.value, login: state.login 32 | })); 33 | } 34 | 35 | renderInitialPage() { 36 | return ( 37 |
38 |
39 | logo 40 |

41 | Serverless Webchat 42 |

43 | 44 | 45 | 46 | this.updateValue(evt)} id="userName" label="Apelido" > 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 |
58 |
59 | ); 60 | } 61 | 62 | render() { 63 | if (this.state.login) { 64 | return this.renderChat(); 65 | } else { 66 | return this.renderInitialPage(); 67 | } 68 | } 69 | 70 | } 71 | 72 | export default App; 73 | -------------------------------------------------------------------------------- /webchat/src/App.test.js: -------------------------------------------------------------------------------- 1 | import { render, screen } from '@testing-library/react'; 2 | import App from './App'; 3 | 4 | test('renders learn react link', () => { 5 | render(); 6 | const linkElement = screen.getByText(/learn react/i); 7 | expect(linkElement).toBeInTheDocument(); 8 | }); 9 | -------------------------------------------------------------------------------- /webchat/src/WebChat.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { w3cwebsocket as W3CWebSocket } from 'websocket'; 3 | import { Container, Grid, Typography, TextField, Button } from '@material-ui/core'; 4 | import { config } from './config'; 5 | 6 | let client = null; 7 | 8 | class WebChat extends React.Component { 9 | 10 | constructor(props) { 11 | super(props); 12 | this.state = { 13 | message: "", 14 | messages: "" 15 | } 16 | this.usersList = []; 17 | this.actions = { 18 | message: this.onMessage.bind(this), 19 | newUser: this.onNewUser.bind(this), 20 | userExit: this.onUserExit.bind(this), 21 | list: this.onList.bind(this) 22 | }; 23 | } 24 | 25 | connect() { 26 | client = new W3CWebSocket(config.websocketAddress); 27 | client.onopen = () => { 28 | console.log('Connected to Websocket'); 29 | client.send(JSON.stringify({action: 'register', userName: this.props.userName})); 30 | client.send(JSON.stringify({action: 'list'})); 31 | }; 32 | client.onmessage = (message) => { 33 | const data = JSON.parse(message.data); 34 | if (data.action) { 35 | this.actions[data.action](data); 36 | } 37 | }; 38 | client.onclose = (() => this.connect()); 39 | } 40 | 41 | onMessage(data) { 42 | this.setState(state => { 43 | let messages = ""; 44 | if (!state.messages) { 45 | messages = `${data.sender}: ${data.message}`; 46 | } else { 47 | messages = state.messages + `\n${data.sender}: ${data.message}`; 48 | } 49 | return {message: state.message, messages: messages}; 50 | }); 51 | } 52 | 53 | sendMessage(text) { 54 | if(text){ 55 | this.setState(state => { 56 | let messages = ""; 57 | if (!state.messages) { 58 | messages = `Você: ${text}`; 59 | } else { 60 | messages = state.messages + `\nVocê: ${text}`; 61 | } 62 | return {message: "", messages: messages}; 63 | }); 64 | client.send(JSON.stringify({ 65 | action: 'message', 66 | sender: this.props.userName, 67 | receivers: this.usersList, 68 | message: text 69 | })); 70 | } 71 | } 72 | 73 | onNewUser(data) { 74 | if (this.usersList) { 75 | this.usersList.push({'userName': data.userName, 'connectionId': data.connectionId}); 76 | } 77 | } 78 | 79 | handleKeyPress = (event) => { 80 | if(event.key === 'Enter') { 81 | this.sendMessage(this.state.message) 82 | } 83 | } 84 | 85 | onUserExit(data) { 86 | if (this.usersList) { 87 | this.usersList = this.usersList.filter(item => data.userName !== item.userName); 88 | } 89 | } 90 | 91 | onList(data) { 92 | this.usersList = data.users; 93 | } 94 | 95 | componentDidMount() { 96 | this.connect(); 97 | } 98 | 99 | onWriteMessage(event) { 100 | this.setState(state => ({message: event.target.value, messages: state.messages})); 101 | } 102 | 103 | render() { 104 | return ( 105 | 106 | 107 | 108 | 109 | Você está online como {this.props.userName} 110 | 111 | 112 | 113 | 114 | 115 | 116 | this.onWriteMessage(event)} onKeyPress={this.handleKeyPress} 117 | id="text" placeholder="Digite sua mensagem aqui..." variant="outlined"> 118 | 119 | 120 | 121 | 122 | 123 | 124 | ); 125 | } 126 | 127 | } 128 | 129 | export default WebChat; -------------------------------------------------------------------------------- /webchat/src/config.js: -------------------------------------------------------------------------------- 1 | export const config = { 2 | websocketAddress: 'wss://{WEBSOCKET}.execute-api.{REGIAO}.amazonaws.com/Prod', 3 | } 4 | -------------------------------------------------------------------------------- /webchat/src/github.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SeniorSA/serverless-websocket/6ab45f3319965ef54fa8f3b022ab4a39f846c410/webchat/src/github.png -------------------------------------------------------------------------------- /webchat/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /webchat/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import reportWebVitals from './reportWebVitals'; 6 | 7 | ReactDOM.render( 8 | 9 | 10 | , 11 | document.getElementById('root') 12 | ); 13 | 14 | // If you want to start measuring performance in your app, pass a function 15 | // to log results (for example: reportWebVitals(console.log)) 16 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 17 | reportWebVitals(); 18 | -------------------------------------------------------------------------------- /webchat/src/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SeniorSA/serverless-websocket/6ab45f3319965ef54fa8f3b022ab4a39f846c410/webchat/src/logo.png -------------------------------------------------------------------------------- /webchat/src/reportWebVitals.js: -------------------------------------------------------------------------------- 1 | const reportWebVitals = onPerfEntry => { 2 | if (onPerfEntry && onPerfEntry instanceof Function) { 3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 4 | getCLS(onPerfEntry); 5 | getFID(onPerfEntry); 6 | getFCP(onPerfEntry); 7 | getLCP(onPerfEntry); 8 | getTTFB(onPerfEntry); 9 | }); 10 | } 11 | }; 12 | 13 | export default reportWebVitals; 14 | -------------------------------------------------------------------------------- /webchat/src/senior.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SeniorSA/serverless-websocket/6ab45f3319965ef54fa8f3b022ab4a39f846c410/webchat/src/senior.png -------------------------------------------------------------------------------- /webchat/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /websocket.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: AWS Serverless Websocket Sample - Websocket Stack 3 | 4 | Transform: 5 | - AWS::Serverless-2016-10-31 6 | 7 | Parameters: 8 | # Parameter for receive SAM/CloudFormation stack name for DynamoDB (created with dynamodb.yml file) 9 | WebSocketTableStackName: 10 | Type: String 11 | Description: Stack name from stack responsible for DynamoDB Table for Connection Ids 12 | 13 | Resources: 14 | # Defines API Gateway Websocket 15 | WebsocketAPI: 16 | Type: AWS::ApiGatewayV2::Api 17 | Properties: 18 | Name: !Sub ${AWS::StackName}-WebSocketAPI 19 | ProtocolType: WEBSOCKET 20 | RouteSelectionExpression: "$request.body.action" 21 | Version: 1.0.0 22 | 23 | # Defines the deploy of API 24 | WebsocketAPIDeployment: 25 | Type: AWS::ApiGatewayV2::Deployment 26 | DependsOn: 27 | - ConnectRoute 28 | - DisconnectRoute 29 | - RegisterRoute 30 | - ListUsersRoute 31 | - MessageRoute 32 | Properties: 33 | ApiId: !Ref WebsocketAPI 34 | 35 | # Defines the stage "Prod" for deploy 36 | WebsocketAPIStage: 37 | Type: AWS::ApiGatewayV2::Stage 38 | Properties: 39 | ApiId: !Ref WebsocketAPI 40 | AutoDeploy: True 41 | StageName: Prod 42 | 43 | # The next resources uses CloudFormation Nested Stack to reuse template's code 44 | # The file websocket_route.yml contains the definitions of resources 45 | 46 | # Defines the route for connection - When a new client connects to Websocket 47 | ConnectRoute: 48 | Type: AWS::CloudFormation::Stack 49 | Properties: 50 | Parameters: 51 | ApiId: !Ref WebsocketAPI 52 | RouteKey: $connect 53 | OperationName: ConnectRoute 54 | IntegrationType: AWS_PROXY 55 | FunctionArn: !Sub ${WebSocketConnectFunction.Arn} 56 | TemplateURL: ./websocket_route.yml 57 | 58 | # Defines the route for disconnection - When any client disconnects from Websocket 59 | DisconnectRoute: 60 | Type: AWS::CloudFormation::Stack 61 | Properties: 62 | Parameters: 63 | ApiId: !Ref WebsocketAPI 64 | RouteKey: $disconnect 65 | OperationName: DisconnectRoute 66 | IntegrationType: AWS_PROXY 67 | FunctionArn: !Sub ${WebSocketDisconnectFunction.Arn} 68 | TemplateURL: ./websocket_route.yml 69 | 70 | # Defines the route for register - When any client connects, need to set an username 71 | RegisterRoute: 72 | Type: AWS::CloudFormation::Stack 73 | Properties: 74 | Parameters: 75 | ApiId: !Ref WebsocketAPI 76 | RouteKey: register 77 | OperationName: RegisterRoute 78 | IntegrationType: AWS_PROXY 79 | FunctionArn: !Sub ${WebSocketRegisterFunction.Arn} 80 | TemplateURL: ./websocket_route.yml 81 | 82 | # Defines the route for messages - When a client send a message to others 83 | MessageRoute: 84 | Type: AWS::CloudFormation::Stack 85 | Properties: 86 | Parameters: 87 | ApiId: !Ref WebsocketAPI 88 | RouteKey: message 89 | OperationName: MessageRoute 90 | IntegrationType: AWS_PROXY 91 | FunctionArn: !Sub ${WebSocketMessageFunction.Arn} 92 | TemplateURL: ./websocket_route.yml 93 | 94 | # Defines the route for list users - When a client request the list of users connected 95 | ListUsersRoute: 96 | Type: AWS::CloudFormation::Stack 97 | Properties: 98 | Parameters: 99 | ApiId: !Ref WebsocketAPI 100 | RouteKey: list 101 | OperationName: ListUsersRoute 102 | IntegrationType: AWS_PROXY 103 | FunctionArn: !Sub ${WebSocketListUsersFunction.Arn} 104 | TemplateURL: ./websocket_route.yml 105 | 106 | # Defines the default route - When a packet doesn't not match another route 107 | DefaultRoute: 108 | Type: AWS::CloudFormation::Stack 109 | Properties: 110 | Parameters: 111 | ApiId: !Ref WebsocketAPI 112 | RouteKey: $default 113 | OperationName: DefaultRoute 114 | IntegrationType: MOCK 115 | FunctionArn: "" 116 | TemplateURL: './websocket_route.yml' 117 | 118 | # Defines the connect function - Related to Connect Route 119 | WebSocketConnectFunction: 120 | Type: AWS::Serverless::Function 121 | Properties: 122 | CodeUri: src/ 123 | Handler: websocket/connect.handler 124 | Runtime: python3.8 125 | MemorySize: 128 126 | Timeout: 100 127 | Description: Executes when a new client is connected to WebSocket - Responsible for save Connection ID 128 | Policies: 129 | # Permission to access DynamoDB Table 130 | - DynamoDBCrudPolicy: 131 | TableName: 132 | Fn::ImportValue: !Sub ${WebSocketTableStackName}:WebSocketConnectionsTableName 133 | Environment: 134 | Variables: 135 | TABLE_NAME: 136 | Fn::ImportValue: !Sub ${WebSocketTableStackName}:WebSocketConnectionsTableName 137 | 138 | # Defines permission to Websocket API invoke the Lambda Function 139 | OnConnectPermission: 140 | Type: AWS::Lambda::Permission 141 | DependsOn: 142 | - WebsocketAPI 143 | Properties: 144 | Action: lambda:InvokeFunction 145 | FunctionName: !Ref WebSocketConnectFunction 146 | Principal: apigateway.amazonaws.com 147 | 148 | # Defines the disconnect function - Related to Disconnect Route 149 | WebSocketDisconnectFunction: 150 | Type: AWS::Serverless::Function 151 | Properties: 152 | CodeUri: src/ 153 | Handler: websocket/disconnect.handler 154 | Runtime: python3.8 155 | MemorySize: 128 156 | Timeout: 100 157 | Description: Executes when a new client is disconnected from WebSocket - Responsible for delete Connection ID 158 | Policies: 159 | # Defines permission to invoke Websocket API from Lambda Function 160 | - AmazonAPIGatewayInvokeFullAccess 161 | - DynamoDBCrudPolicy: 162 | TableName: 163 | Fn::ImportValue: !Sub ${WebSocketTableStackName}:WebSocketConnectionsTableName 164 | Environment: 165 | Variables: 166 | TABLE_NAME: 167 | Fn::ImportValue: !Sub ${WebSocketTableStackName}:WebSocketConnectionsTableName 168 | WEBSOCKET_ADDRESS: 169 | Fn::Join: 170 | - '' 171 | - - 'https://' 172 | - !Ref WebsocketAPI 173 | - '.execute-api.' 174 | - !Ref 'AWS::Region' 175 | - '.amazonaws.com/' 176 | - !Ref 'WebsocketAPIStage' 177 | Layers: 178 | - !Ref Libs 179 | 180 | OnDisconnectPermission: 181 | Type: AWS::Lambda::Permission 182 | DependsOn: 183 | - WebsocketAPI 184 | Properties: 185 | Action: lambda:InvokeFunction 186 | FunctionName: !Ref WebSocketDisconnectFunction 187 | Principal: apigateway.amazonaws.com 188 | 189 | WebSocketRegisterFunction: 190 | Type: AWS::Serverless::Function 191 | Properties: 192 | CodeUri: src/ 193 | Handler: websocket/register.handler 194 | Runtime: python3.8 195 | MemorySize: 128 196 | Timeout: 100 197 | Description: Executes when a client sents a message to route "register" 198 | Policies: 199 | - AmazonAPIGatewayInvokeFullAccess 200 | - DynamoDBCrudPolicy: 201 | TableName: 202 | Fn::ImportValue: !Sub ${WebSocketTableStackName}:WebSocketConnectionsTableName 203 | Environment: 204 | Variables: 205 | TABLE_NAME: 206 | Fn::ImportValue: !Sub ${WebSocketTableStackName}:WebSocketConnectionsTableName 207 | WEBSOCKET_ADDRESS: 208 | Fn::Join: 209 | - '' 210 | - - 'https://' 211 | - !Ref WebsocketAPI 212 | - '.execute-api.' 213 | - !Ref 'AWS::Region' 214 | - '.amazonaws.com/' 215 | - !Ref 'WebsocketAPIStage' 216 | Layers: 217 | - !Ref Libs 218 | 219 | RegisterPermission: 220 | Type: AWS::Lambda::Permission 221 | DependsOn: 222 | - WebsocketAPI 223 | Properties: 224 | Action: lambda:InvokeFunction 225 | FunctionName: !Ref WebSocketRegisterFunction 226 | Principal: apigateway.amazonaws.com 227 | 228 | WebSocketMessageFunction: 229 | Type: AWS::Serverless::Function 230 | Properties: 231 | CodeUri: src/ 232 | Handler: websocket/message.handler 233 | Runtime: python3.8 234 | MemorySize: 128 235 | Timeout: 100 236 | Description: Executes when a client sents a message to route "message" 237 | Policies: 238 | - AmazonAPIGatewayInvokeFullAccess 239 | - DynamoDBCrudPolicy: 240 | TableName: 241 | Fn::ImportValue: !Sub ${WebSocketTableStackName}:WebSocketConnectionsTableName 242 | Environment: 243 | Variables: 244 | TABLE_NAME: 245 | Fn::ImportValue: !Sub ${WebSocketTableStackName}:WebSocketConnectionsTableName 246 | WEBSOCKET_ADDRESS: 247 | Fn::Join: 248 | - '' 249 | - - 'https://' 250 | - !Ref WebsocketAPI 251 | - '.execute-api.' 252 | - !Ref 'AWS::Region' 253 | - '.amazonaws.com/' 254 | - !Ref 'WebsocketAPIStage' 255 | 256 | MessagePermission: 257 | Type: AWS::Lambda::Permission 258 | DependsOn: 259 | - WebsocketAPI 260 | Properties: 261 | Action: lambda:InvokeFunction 262 | FunctionName: !Ref WebSocketMessageFunction 263 | Principal: apigateway.amazonaws.com 264 | 265 | WebSocketListUsersFunction: 266 | Type: AWS::Serverless::Function 267 | Properties: 268 | CodeUri: src/ 269 | Handler: websocket/list_users.handler 270 | Runtime: python3.8 271 | MemorySize: 128 272 | Timeout: 100 273 | Description: Executes when a client sents a message to route "list" 274 | Policies: 275 | - AmazonAPIGatewayInvokeFullAccess 276 | - DynamoDBCrudPolicy: 277 | TableName: 278 | Fn::ImportValue: !Sub ${WebSocketTableStackName}:WebSocketConnectionsTableName 279 | Environment: 280 | Variables: 281 | TABLE_NAME: 282 | Fn::ImportValue: !Sub ${WebSocketTableStackName}:WebSocketConnectionsTableName 283 | WEBSOCKET_ADDRESS: 284 | Fn::Join: 285 | - '' 286 | - - 'https://' 287 | - !Ref WebsocketAPI 288 | - '.execute-api.' 289 | - !Ref 'AWS::Region' 290 | - '.amazonaws.com/' 291 | - !Ref 'WebsocketAPIStage' 292 | Layers: 293 | - !Ref Libs 294 | 295 | ListUsersPermission: 296 | Type: AWS::Lambda::Permission 297 | DependsOn: 298 | - WebsocketAPI 299 | Properties: 300 | Action: lambda:InvokeFunction 301 | FunctionName: !Ref WebSocketListUsersFunction 302 | Principal: apigateway.amazonaws.com 303 | 304 | # Defines the Layer to use the file scan_table.py as common code to all functions 305 | Libs: 306 | Type: AWS::Serverless::LayerVersion 307 | Properties: 308 | LayerName: scan-dynamodb-table 309 | Description: Dependency for scan a dynamodb table. 310 | ContentUri: src/lib/. 311 | CompatibleRuntimes: 312 | - python3.8 313 | 314 | Outputs: 315 | WebsocketAPIConnectionsAddress: 316 | Description: Endpoint API 317 | Value: 318 | Fn::Join: 319 | - '' 320 | - - 'wss://' 321 | - !Ref WebsocketAPI 322 | - '.execute-api.' 323 | - !Ref 'AWS::Region' 324 | - '.amazonaws.com/' 325 | - !Ref 'WebsocketAPIStage' 326 | Export: 327 | Name: !Sub ${AWS::StackName}:endpoint 328 | 329 | WebsocketAPIStage: 330 | Description: Stage API 331 | Value: !Ref WebsocketAPIStage 332 | Export: 333 | Name: !Sub ${AWS::StackName}:stage -------------------------------------------------------------------------------- /websocket_route.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: AWS Serverless Websocket Routes Sample - Websocket Stack 3 | 4 | Transform: 5 | - AWS::Serverless-2016-10-31 6 | 7 | Parameters: 8 | ApiId: 9 | Type: String 10 | Description: Api Id for routes 11 | RouteKey: 12 | Type: String 13 | Description: Route key name 14 | OperationName: 15 | Type: String 16 | Description: Operation name for route 17 | IntegrationType: 18 | Type: String 19 | Description: Integration type for Route Integration 20 | FunctionArn: 21 | Type: String 22 | Description: Lambda Function Arn for Integration 23 | 24 | Conditions: 25 | NeedIntegrationUri: !Equals [!Ref IntegrationType, "AWS_PROXY"] 26 | 27 | Resources: 28 | Route: 29 | Type: AWS::ApiGatewayV2::Route 30 | Properties: 31 | ApiKeyRequired: False 32 | ApiId: !Ref ApiId 33 | RouteKey: !Ref RouteKey 34 | OperationName: !Ref OperationName 35 | Target: !Join 36 | - '/' 37 | - - 'integrations' 38 | - !Ref Integration 39 | 40 | Integration: 41 | Type: AWS::ApiGatewayV2::Integration 42 | Properties: 43 | ApiId: !Ref ApiId 44 | IntegrationType: !Ref IntegrationType 45 | IntegrationUri: 46 | Fn::If: 47 | ["NeedIntegrationUri", !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${FunctionArn}/invocations", !Ref "AWS::NoValue"] 48 | 49 | IntegrationResponse: 50 | Type: AWS::ApiGatewayV2::IntegrationResponse 51 | Properties: 52 | ApiId: !Ref ApiId 53 | ContentHandlingStrategy: CONVERT_TO_TEXT 54 | IntegrationId: !Ref Integration 55 | IntegrationResponseKey: /200/ 56 | 57 | RouteResponse: 58 | Type: AWS::ApiGatewayV2::RouteResponse 59 | Properties: 60 | ApiId: !Ref ApiId 61 | RouteId: !Ref Route 62 | # Currently only $default RouteResponseKey is supported (02/Dec/2020) 63 | # https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-route-response.html 64 | RouteResponseKey: $default 65 | --------------------------------------------------------------------------------