├── .gitignore ├── LICENSE ├── README.md ├── config.example.yml ├── lambda ├── dynamodb │ ├── LambdaChatDynamoDBPolicy.json │ ├── code │ │ ├── LambdaChatDynamoDB.js │ │ └── README │ ├── config.yml │ └── input.json └── sns │ ├── LambdaChatPolicy.json │ ├── config.yml │ ├── dynamodb_table.json │ ├── input.json │ └── lambdachat.js ├── presentation ├── example.html ├── imgs │ ├── dynamic-dashboards.png │ ├── kinesis-pull-10.png │ ├── lambda-chat.png │ ├── push-s3-example-10.png │ └── vote-app.png ├── index.html ├── public ├── remark-latest.min.js └── remark.language.js ├── publish-presentation.sh ├── requirements.txt ├── resources.py ├── s3-website ├── public │ ├── error.html │ ├── index.html │ ├── lambda-chat.css │ └── lambda-chat.js └── update.sh └── yaml2shell.sh /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # node-waf configuration 20 | .lock-wscript 21 | 22 | # Compiled binary addons (http://nodejs.org/api/addons.html) 23 | build/Release 24 | 25 | # Dependency directory 26 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 27 | node_modules 28 | 29 | # Ignore the config file as it has secrets in it 30 | config.yml 31 | s3-website/public/config.js 32 | 33 | # Ignore compiled Python files 34 | *.pyc 35 | 36 | # Ignore Emacs backup files 37 | *~ 38 | 39 | # Ignore the data file 40 | s3-website/public/data.json 41 | -------------------------------------------------------------------------------- /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 2015 CloudNative, Inc. 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 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lambda Chat 2 | A chat application without servers - using only AWS Lambda, S3, DynamoDB and SNS 3 | 4 | 5 | ## Live Demo 6 | 7 | http://lambda-chat.s3-website-us-west-2.amazonaws.com/ 8 | 9 | Please don't send a million messages through here - it does cost us money and we will turn it off if it is abused. 10 | 11 | 12 | ## How it works 13 | 14 | 15 |
◎ ◎ 16 | ◡ 17 | 18 | │(1) 19 | │ ┏━━━━━━━━━━━━━━━━━━┓ 20 | │ ┃ ┃ 21 | │ (2) ┃ Google OAuth2 ┃ (4) 22 | │ ┌─────────────▶┃ API ┃◀────────────┐ 23 | │ │ ┃ ┃ │ 24 | │ │ ┗━━━━━━━━━━━━━━━━━━┛ │ 25 | ▼ ▼ ┏━━━━━━━━━━━━━━━━━━┓ 26 | ┏━━━━━━━━━━━━━━━━━━┓ ┃ ┃ 27 | ┃ ┃ (3) ┃ AWS STS ┃ 28 | ┌─▶┃ Website ┃◀──────────────────────────▶┃ AWS Web ID Fed ┃ 29 | │ ┃ ┃ ┃ ┃ 30 | │ ┗━━━━━━━━━━━━━━━━━━┛ ┗━━━━━━━━━━━━━━━━━━┛ 31 | │ │ 32 | │ │ ┏━━━━━━━━━━━━━━━━━━┓ 33 | │ │ ┃ ┃ 34 | │ └───────▶┃ SNS Topic ┃ 35 | │ (5) ┃ ┃ 36 | │ ┗━━━━━━━━━━━━━━━━━━┛ 37 | │ │ 38 | │ │ ┏━━━━━━━━━━━━━━━━━━┓ 39 | │ │ ┃ ┃ 40 | │ └──────▶┃ Lambda fn1 ┃ 41 | │ (6) ┃ ┃ 42 | │ ┗━━━━━━━━━━━━━━━━━━┛ 43 | │ │ 44 | │ │ ┏━━━━━━━━━━━━━━━━━━┓ 45 | │ │ ┃ ┃ 46 | │ └─────▶┃ DynamoDB Table ┃ 47 | │ (7) ┃ ┃ 48 | │ ┗━━━━━━━━━━━━━━━━━━┛ 49 | │ │ 50 | │ ┏━━━━━━━━━━━━━━━━━━┓ │ 51 | │ ┃ ┃ │ 52 | │ ┃ Lambda fn2 ┃◀─────────┘ 53 | │ ┃ ┃ (8) 54 | │ ┗━━━━━━━━━━━━━━━━━━┛ 55 | │ │ 56 | │ ┏━━━━━━━━━━━━━━━━━━┓ │ 57 | │ ┃ ┃ │ 58 | └────────────┃ S3 Object ┃◀─────────────┘ 59 | (10) ┃ ┃ (9) 60 | ┗━━━━━━━━━━━━━━━━━━┛ 61 | 62 | 63 | Created with Monodraw 64 |65 | 66 | 1. The user opens their browser and go to the website which is hosted entirely on S3 67 | 2. The user signs in with their Google account and gets back an `id_token` 68 | 3. Using AWS Web Identity Federation in the Javascript SDK, the `id_token` is sent to get temporary AWS credentials from STS. 69 | 4. STS verifies the token with Google 70 | 5. The users types in a message, hits ENTER, and the website publishes the message to an SNS Topic. 71 | 6. A Lambda function is trigged by the SNS message, which gets the contents of the message, and... 72 | 7. Stores the message in a DynamoDB table 73 | 8. The process of adding a new chat message to the DynamoDB table triggers another Lambda function. This requires the currently-in-preview DynamoDB Streams feature. This second Lambda function reads the last 20 messages from DynamoDB, and... 74 | 9. Writes them to an S3 object in JSON format 75 | 10. The website polls the S3 object every second, and updates the chat box with any new messages it finds. 76 | 77 | 78 | ## Getting Started 79 | 80 | There is a lot involved here, but we have tried to make it as easy as possible for you to follow along. 81 | 82 | ### Get the code 83 | 84 | git clone git@github.com:cloudnative/lambda-chat.git 85 | cd lambda-chat 86 | 87 | ### Config 88 | 89 | cp config.example.yml config.yml 90 | 91 | The only thing to edit at this point is the name of the S3 bucket to put the website in as bucket names are globally unique. 92 | 93 | s3_bucket: my-lambda-chat-bucket 94 | 95 | ### Google OAuth 96 | 97 | To be able to use AWS Web Identity Federation, you will need to create a new Google Project and create credentials. 98 | 99 | 1. Go to: https://console.developers.google.com/project 100 | 1. Create a new project 101 | 1. Enable **Google+ API** 102 | 1. Create OAuth 2 credentials. Leave the Javascript Origin empty for now 103 | 1. Edit `config.yml` and set `google_oauth_client_id` to your Client ID 104 | 105 | ### AWS Resources 106 | 107 | #### Prerequisites 108 | 109 | You will need Python 2.7. On OSX using brew 110 | 111 | brew install python 112 | 113 | Now we need a few Python libraries 114 | 115 | pip install -r requirements.txt 116 | 117 | #### CloudFormation 118 | 119 | There is a script called `resources.py` which will generate a CloudFormation template to bring up the AWS resources needed to run Lambda Chat. 120 | 121 | You can see the template by running 122 | 123 | ./resources.py cf 124 | 125 | If you are happy with that, the script can also launch the CloudFormation Stack. To create it in N. Virginia, run: 126 | 127 | ./resources.py launch --region=us-east-1 128 | 129 | The script returns quickly because it is now up to CloudFormation to bring up the AWS resources. Login to the AWS Web Console and go to the CloudFormation section in that region. Select the `Lambda-Chat` stack, then click on the **Events** tab to see the progress and check for errors. 130 | 131 | Once the stack is complete, run: 132 | 133 | ./resources.py output --region=us-east-1 134 | 135 | and add these values to your `config.yml` file. 136 | 137 | #### Website 138 | 139 | The files needed to run the website need to be in S3. To get them there: 140 | 141 | cd s3-website 142 | ./update.sh 143 | 144 | You can run this command as many times as you like, particularly if you are editing the files to see what is happening. 145 | 146 | The script tells you the URL of the website. Open that up in your browser. 147 | 148 | #### Lambda functions 149 | 150 | To help with the AWS Lambda side of things, we are using 151 | [kappa](https://github.com/garnaat/kappa). Kappa is a CLI tool that helps with 152 | the details of creating and managing AWS Lambda applications. You must install 153 | kappa before proceeding. You can install it from PyPI using pip: 154 | 155 | % pip install kappa 156 | 157 | or you can clone the kappa repo and install locally: 158 | 159 | % git clone git@github.com:garnaat/kappa.git 160 | % cd kappa 161 | % pip install -r requirements.txt 162 | % python setup.py install 163 | 164 | Next, you must edit the config.yml files in the lambda/sns directory and the 165 | lambda/dynamodb directories. The config.yml files have comments which direct 166 | you to the parts that need to be changed. 167 | 168 | Now create the components required for the SNS->DynamoDB Lambda function: 169 | 170 | 1. cd lambda/sns 171 | 1. run ``kappa config.yml create`` 172 | 1. run ``kappa config.yml invoke``. This will call the AWS Lambda function 173 | synchronously with test data and return the log data to the console. 174 | 1. run ``kappa config.yml add_event_sources``. This will connect the SNS topic 175 | to your AWS Lambda function. 176 | 177 | Finally, you need to create the components requried for the DynamoDB->S3 Lambda 178 | function: 179 | 180 | 1. cd lambda/dynamodb 181 | 1. run ``kappa config.yml create`` 182 | 1. run ``kappa config.yml invoke``. This will call the AWS Lambda function 183 | synchronously with test data and return the log data to the console. 184 | 1. run ``kappa config.yml add_event_sources``. This will connect the DynamoDB 185 | stream to your AWS Lambda function. 186 | 187 | 188 | ### Usage 189 | 190 | 1. Go to the URL returned by the `update.sh` script, and login with your Google account. 191 | 1. Use like any other chat application :-) 192 | 193 | 194 | ## Updating 195 | 196 | You should feel free to mess around with this and update parts of it with your own code. If you do, please [let us know](https://twitter.com/intent/tweet?text=I%20am%20having%20fun%20with%20Lambda%20Chat.%20Thanks%20@CloudNativeIO). 197 | 198 | When you are making changes to the website, you can push them to S3 by running: 199 | 200 | cd s3-website 201 | ./update.sh 202 | 203 | For modifications to the AWS Lambda functions, run: 204 | 205 | % kappa config.yml update_code 206 | 207 | in the corresponding lambda directory. 208 | 209 | 210 | ## Clean up 211 | 212 | Delete the CloudFormation stack 213 | 214 | ./resources.py delete --region=us-east-1 215 | 216 | Delete the Lambda functions 217 | 218 | % kappa config.yml delete 219 | 220 | in the corresponding lambda directory. This will delete the AWS Lambda 221 | function, remove the event source mappings, and delete the IAM role. 222 | 223 | ## Reading, resources and other stuff 224 | 225 | - [The blog post that describes why we did this](https://cloudnative.io/blog/2015/05/lambda-chat/) 226 | - [AWS Web Identity Federation playground](https://web-identity-federation-playground.s3.amazonaws.com/index.html) 227 | - [Building Dynamic Dashboards Using Lambda and DynamoDB Streams: Part 1](https://medium.com/aws-activate-startup-blog/building-dynamic-dashboards-using-lambda-and-dynamodb-streams-part-1-217e2318ae17) 228 | - [Kappa](https://github.com/garnaat/kappa) 229 | - [Troposphere](https://github.com/cloudtools/troposphere) 230 | 231 | -------------------------------------------------------------------------------- /config.example.yml: -------------------------------------------------------------------------------- 1 | # Example configuration for Lambda Chat 2 | # Copy this file to `config.yml` and then set the values appropriately 3 | 4 | # The Google OAuth Client ID 5 | # Visit: https://console.developers.google.com/project 6 | # To create a project, enable the Google+ API, and create an ID 7 | # Set the Javascript Origin to the S3 bucket URL 8 | google_oauth_client_id: TODO 9 | 10 | # The AWS region to do everything in 11 | region: us-east-1 12 | 13 | # The name of the S3 bucket to use for the website 14 | # This must be unique across all AWS accounts 15 | s3_bucket: lambda-chat 16 | 17 | # The S3 object key for the chat data 18 | data_key: data.json 19 | 20 | # The ARN of the IAM role the website will assume to be able to send messages 21 | # using SNS 22 | website_iam_role_arn: arn:aws:iam::TODO 23 | 24 | # The ARN of the SNS topic to publish chat messages to, and for Lambda to read 25 | sns_topic_arn: arn:aws:sns::TODO 26 | -------------------------------------------------------------------------------- /lambda/dynamodb/LambdaChatDynamoDBPolicy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "lambda:InvokeFunction" 8 | ], 9 | "Resource": "*" 10 | }, 11 | { 12 | "Effect": "Allow", 13 | "Action": [ 14 | "dynamodb:*", 15 | "s3:*", 16 | "logs:*" 17 | ], 18 | "Resource": "*" 19 | } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /lambda/dynamodb/code/LambdaChatDynamoDB.js: -------------------------------------------------------------------------------- 1 | console.log('Loading function'); 2 | var async = require('async'); 3 | var aws = require('aws-sdk'); 4 | var ddb = new aws.DynamoDB( 5 | {endpoint: "https://dynamodb.us-west-2.amazonaws.com/", 6 | params: {TableName: "lambdachat"}}); 7 | var s3 = new aws.S3(); 8 | // change bucket name to match your bucket name 9 | var bucket = "lambda-chat"; 10 | var keyname = "data.json"; 11 | 12 | 13 | function escapeHtml(text) { 14 | var map = { 15 | '&': '&', 16 | '<': '<', 17 | '>': '>', 18 | '"': '"', 19 | "'": ''' 20 | }; 21 | 22 | return text.replace(/[&<>"']/g, function(m) { return map[m]; }); 23 | } 24 | 25 | 26 | exports.handler = function(event, context) { 27 | console.log('Handle DynamoDB Streams event'); 28 | console.log(JSON.stringify(event, null, 2)); 29 | var new_object = event.Records[0].dynamodb; 30 | var channel = "default"; 31 | if ('channel' in new_object.NewImage) { 32 | channel = new_object.NewImage.channel.S; 33 | } 34 | console.log("channel = " + channel); 35 | 36 | 37 | async.waterfall([ 38 | function getrecords(next) { 39 | var params = { 40 | "IndexName": "channel-timestamp-index", 41 | "KeyConditions": { 42 | "channel": { 43 | "AttributeValueList": [{ 44 | "S": channel 45 | }], 46 | "ComparisonOperator": "EQ" 47 | } 48 | 49 | }, 50 | "Limit": 20, 51 | "ScanIndexForward": false 52 | } 53 | console.log("Scanning the table"); 54 | ddb.query(params, next); 55 | }, 56 | function buildjson(response, next) { 57 | console.log("Building JSON file"); 58 | console.log(JSON.stringify(response)); 59 | var messageData = { 60 | messages: [] 61 | }; 62 | 63 | for (var i = response.Items.length - 1; i >= 0; i--) { 64 | ii = response.Items[i]; 65 | var message = {}; 66 | message['id'] = ii.message_id['S']; 67 | message['name'] = escapeHtml(ii.name['S']); 68 | message['message'] = escapeHtml(ii.message['S']); 69 | message['channel'] = ii.channel['S']; 70 | messageData.messages.push(message); 71 | } 72 | next(null, JSON.stringify(messageData)); 73 | }, 74 | function savetos3(jsonstring, next) { 75 | console.log(jsonstring); 76 | s3.putObject({ 77 | Bucket: bucket, 78 | Key: keyname, 79 | Body: jsonstring 80 | }, next); 81 | } 82 | ], function (err) { 83 | if (err) { 84 | console.log('got an error'); 85 | console.log(err, err.stack); 86 | } else { 87 | console.log('Saved Data to S3'); 88 | } 89 | context.done(err, ''); 90 | }); 91 | 92 | }; 93 | -------------------------------------------------------------------------------- /lambda/dynamodb/code/README: -------------------------------------------------------------------------------- 1 | This code requires the async nodejs package. Before uploading the function you 2 | should install that package here using: 3 | 4 | % npm install async -------------------------------------------------------------------------------- /lambda/dynamodb/config.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # change profile and region to meet your needs 3 | profile: cloudnative-dev 4 | region: us-west-2 5 | resources: resources.json 6 | iam: 7 | policy: 8 | description: A policy used with the Kappa SNS->DynamoDB example 9 | name: LambdaChatDynamoDBPolicy 10 | document: LambdaChatDynamoDBPolicy.json 11 | role: 12 | name: LambdaChatDynamoDBRole 13 | lambda: 14 | name: LambdaChatDynamoDB 15 | zipfile_name: LambdaChatDynamoDB.zip 16 | description: A simple chat app with S3/SNS/DynamoDB/Lambda 17 | path: code/ 18 | handler: LambdaChatDynamoDB.handler 19 | runtime: nodejs 20 | memory_size: 128 21 | timeout: 3 22 | event_sources: 23 | - 24 | # Change this to point to your DynamoDB stream. 25 | # Note that you must be in the DynamoDB Streams preview. 26 | arn: arn:aws:dynamodb:us-west-2:860421987956:table/lambdachat/stream/2015-09-09T17:52:45.927 27 | batch_size: 1 28 | starting_position: LATEST 29 | enabled: true 30 | test_data: input.json 31 | -------------------------------------------------------------------------------- /lambda/dynamodb/input.json: -------------------------------------------------------------------------------- 1 | { 2 | "Records":[ 3 | { 4 | "EventName":"INSERT", 5 | "EventVersion":"1.0", 6 | "EventSource":"aws:dynamodb", 7 | "Dynamodb":{ 8 | "NewImage":{ 9 | "Message":{ 10 | "S":"New item!" 11 | }, 12 | "Id":{ 13 | "N":"101" 14 | } 15 | }, 16 | "SizeBytes":26, 17 | "StreamViewType":"NEW_AND_OLD_IMAGES", 18 | "SequenceNumber":"111", 19 | "Keys":{ 20 | "Id":{ 21 | "N":"101" 22 | } 23 | } 24 | }, 25 | "EventID":"1", 26 | "eventSourceARN":"arn:aws:dynamodb:us-east-1:acct-id:table/ExampleTableWithStream/stream/stream-id/", 27 | "AwsRegion":"us-east-1" 28 | }, 29 | { 30 | "EventName":"MODIFY", 31 | "EventVersion":"1.0", 32 | "EventSource":"aws:dynamodb", 33 | "Dynamodb":{ 34 | "NewImage":{ 35 | "Message":{ 36 | "S":"This item has changed" 37 | }, 38 | "Id":{ 39 | "N":"101" 40 | } 41 | }, 42 | "SizeBytes":59, 43 | "StreamViewType":"NEW_AND_OLD_IMAGES", 44 | "SequenceNumber":"222", 45 | "OldImage":{ 46 | "Message":{ 47 | "S":"New item!" 48 | }, 49 | "Id":{ 50 | "N":"101" 51 | } 52 | }, 53 | "Keys":{ 54 | "Id":{ 55 | "N":"101" 56 | } 57 | } 58 | }, 59 | "EventID":"2", 60 | "eventSourceARN":"arn:aws:dynamodb:us-east-1:acct-id:table/ExampleTableWithStream/stream/stream-id/", 61 | "AwsRegion":"us-east-1" 62 | }, 63 | { 64 | "EventName":"REMOVE", 65 | "EventVersion":"1.0", 66 | "EventSource":"aws:dynamodb", 67 | "Dynamodb":{ 68 | "SizeBytes":38, 69 | "StreamViewType":"NEW_AND_OLD_IMAGES", 70 | "SequenceNumber":"333", 71 | "OldImage":{ 72 | "Message":{ 73 | "S":"This item has changed" 74 | }, 75 | "Id":{ 76 | "N":"101" 77 | } 78 | }, 79 | "Keys":{ 80 | "Id":{ 81 | "N":"101" 82 | } 83 | } 84 | }, 85 | "EventID":"3", 86 | "eventSourceARN":"arn:aws:dynamodb:eu-west-1:acct-id:table/ExampleTableWithStream/stream/stream-id/", 87 | "AwsRegion":"eu-west-1" 88 | } 89 | ] 90 | } 91 | -------------------------------------------------------------------------------- /lambda/sns/LambdaChatPolicy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement":[ 4 | { 5 | "Sid":"Stmt1", 6 | "Effect":"Allow", 7 | "Action":["dynamodb:*"], 8 | "Resource":["arn:aws:dynamodb:us-west-2:860421987956:table/lambdachat"] 9 | }, 10 | { 11 | "Sid":"Stmt2", 12 | "Effect":"Allow", 13 | "Action":["logs:*"], 14 | "Resource":["arn:aws:logs:*:*:*"] 15 | } 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /lambda/sns/config.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # change profile and region to meet your needs 3 | profile: cloudnative-dev 4 | region: us-west-2 5 | iam: 6 | policy: 7 | description: A policy used with the Kappa SNS->DynamoDB example 8 | name: LambdaChatPolicy 9 | document: LambdaChatPolicy.json 10 | role: 11 | name: LambdaChatRole 12 | policy: LambdaChatPolicy 13 | lambda: 14 | name: LambdaChat 15 | zipfile_name: LambdaChat.zip 16 | description: A simple chat app with S3/SNS/DynamoDB/Lambda 17 | path: lambdachat.js 18 | handler: lambdachat.handler 19 | runtime: nodejs 20 | memory_size: 128 21 | timeout: 3 22 | permissions: 23 | - 24 | statement_id: sns_invoke 25 | action: lambda:invokeFunction 26 | principal: sns.amazonaws.com 27 | # change this to point to your SNS topic 28 | source_arn: arn:aws:sns:us-west-2:860421987956:lambda-chat 29 | event_sources: 30 | - 31 | # change this to point to your SNS topic 32 | arn: arn:aws:sns:us-west-2:860421987956:lambda-chat 33 | test_data: input.json 34 | -------------------------------------------------------------------------------- /lambda/sns/dynamodb_table.json: -------------------------------------------------------------------------------- 1 | { 2 | "TableName": "snslambda", 3 | "AttributeDefinitions": [ 4 | { 5 | "AttributeName": "SnsTopicArn", 6 | "AttributeType": "S" 7 | }, 8 | { 9 | "AttributeName": "SnsPublishTime", 10 | "AttributeType": "S" 11 | }, 12 | { 13 | "AttributeName": "SnsMessageId", 14 | "AttributeType": "S" 15 | } 16 | ], 17 | "KeySchema": [ 18 | { 19 | "AttributeName": "SnsTopicArn", 20 | "KeyType": "HASH" 21 | }, 22 | { 23 | "AttributeName": "SnsPublishTime", 24 | "KeyType": "RANGE" 25 | } 26 | ], 27 | "GlobalSecondaryIndexes": [ 28 | { 29 | "IndexName": "MesssageIndex", 30 | "KeySchema": [ 31 | { 32 | "AttributeName": "SnsMessageId", 33 | "KeyType": "HASH" 34 | } 35 | ], 36 | "Projection": { 37 | "ProjectionType": "ALL" 38 | }, 39 | "ProvisionedThroughput": { 40 | "ReadCapacityUnits": 5, 41 | "WriteCapacityUnits": 1 42 | } 43 | } 44 | ], 45 | "ProvisionedThroughput": { 46 | "ReadCapacityUnits": 5, 47 | "WriteCapacityUnits": 5 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /lambda/sns/input.json: -------------------------------------------------------------------------------- 1 | { 2 | "Records":[ 3 | { 4 | "EventSource":"aws:sns", 5 | "EventVersion": "1.0", 6 | "EventSubscriptionArn": "arn:aws:sns:us-east-1:123456789012:lambda_topic:0b6941c3-f04d-4d3e-a66d-b1df00e1e381", 7 | "Sns":{ 8 | "Type" : "Notification", 9 | "MessageId" : "e70fa8dd-0d77-5944-8862-e569494b48b5", 10 | "TopicArn" : "arn:aws:sns:us-east-1:658794617753:lambda-chat", 11 | "Message" : "{\"name\":\"Mitch Garnaat\",\"message\":\"just testing this out\"}", 12 | "Timestamp" : "2015-04-24T13:15:40.632Z", 13 | "Channel" : "foo", 14 | "SignatureVersion" : "1", 15 | "Signature" : "n0zU4mvKQT5vy6RbDK3BoiWQrFBirbaIGRQOVXE4Vx1XE0SrsXBo4mPm2eDMgjFboP0RJxRCvkFpN07mbnVOIoT2UWKVD2hU1vLdTlEPE4ppSSx17KzhABsOuA8XwijL3hm4cpVHmCmhNXcKekC+fGCryjf9cxr6ODm45PxxE4WLSak85uLzgWhfbAEgPqD2Q/Fa3NwJIyBkZWEdlpJCeaZb4gCzPauvcynRyzWS+e+76WpXMgInCU2y7lhtajDpHrDlZ13UvHOWAQONFRGJXsxFeP370tnzVKfdfMPNbmr4gb3dk+VP0+PsyrIakqp31cO5umUZwSeVZaXLQLewmg==", 16 | "SigningCertURL" : "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-d6d679a1d18e95c2f9ffcf11f4f9e198.pem", 17 | "UnsubscribeURL" : "https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:658794617753:lambda-chat:f1bde0aa-11eb-4417-a9cf-6a00c6aac0a7" 18 | } 19 | } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /lambda/sns/lambdachat.js: -------------------------------------------------------------------------------- 1 | console.log('Loading event'); 2 | var aws = require('aws-sdk'); 3 | var ddb = new aws.DynamoDB( 4 | {endpoint: 'https://dynamodb.us-west-2.amazonaws.com/', 5 | params: {TableName: 'lambdachat'}}); 6 | 7 | exports.handler = function(event, context) { 8 | var message_id = event.Records[0].Sns.MessageId; 9 | var timestamp = event.Records[0].Sns.Timestamp; 10 | var payload = JSON.parse(event.Records[0].Sns.Message); 11 | var channel = 'default'; 12 | if ("channel" in payload) { 13 | channel = payload.channel; 14 | } 15 | var name = payload.name; 16 | var message = payload.message; 17 | var LambdaReceiveTime = new Date().toString(); 18 | var itemParams = {Item: {message_id: {S: message_id}, 19 | timestamp: {S: timestamp}, 20 | channel: {S: channel}, 21 | name: {S: name}, 22 | message: {S: message}}}; 23 | ddb.putItem(itemParams, function(err, data) { 24 | context.done(err,''); 25 | }); 26 | }; 27 | -------------------------------------------------------------------------------- /presentation/example.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |