├── LICENSE ├── README.md ├── lambdas ├── list-sources │ └── index.py ├── process-channel │ └── index.py └── process-item │ └── index.py └── template.yaml /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 | > This project has been deprecated in favor of [web-feed-aws-events](https://github.com/craigbailey-dev/web-feed-aws-events). It will still be available in the AWS Serverless Application Repository, but will no longer receive any updates. 2 | 3 | # rss-events 4 | 5 | RSS is a popular web syndication format that allows users to view updates to a site. This is a highly configurable serverless solution that behaves like a news aggregator for RSS, wherein multiple RSS sources are read at given internval, and events for newly discovered items in the RSS channel are sent to an EventBridge event bus. 6 | 7 | ## Architecture 8 | 9 | ### Resources 10 | 11 | - **Sources Table** - DynamoDB table that holds all sources of RSS feeds 12 | - **Items Table** - DynamoDB table that record all RSS channel items for which events have been sent 13 | - **Channel Queue** - SQS queue that dispatches a message for each RSS feed 14 | - **Items Queue** - SQS queue that dispatches a message for each new channel item in an RSS feed 15 | - **Event Bus** - EventBridge event bus that receives events for every new channel item 16 | - **List Sources Function** - Lambda function that lists all sources of RSS feeds for processing 17 | - **Process Sources Function** - Lambda function that checks the RSS feed for new content 18 | - **Process Items Function** - Lambda function that sends an event to the event bus for each new channel item 19 | 20 | 21 | ![enter image description here](https://d50daux61fgb.cloudfront.net/rss-events/solution-architecture.png) 22 | 23 | 24 | ### Table Schema 25 | 26 | #### Sources Table 27 | 28 | | Attribute | Type | Description | 29 | | ------------------- |:--------------------| :----------------------------------------------------------------------------------------------| 30 | | source | String | An HTTP/S URL for the RSS feed | 31 | | httpHeaderOverrides | Map | A map of HTTP headers to set when making a
request to retrieve RSS content from the source | 32 | 33 | #### Items Table 34 | 35 | | Attribute | Type | Description | 36 | | ---------------|:--------------------| :----------------------------------------------------------------------------------------------| 37 | | source | String | The URL of the RSS feed | 38 | | guid | String | The uinique ID of the channel item | 39 | 40 | 41 | ## Event Format 42 | 43 | The event body adheres to the standard CloudWatch event format, and describes all properties of the channel and the specific item in the channel. All properties correspond to the RSS 2.0 specification found [here]([https://cyber.harvard.edu/rss/rss.html](https://cyber.harvard.edu/rss/rss.html)). 44 | 45 | - **source** *(string)* - The URL used to derive to content of the RSS feed 46 | - **detail** *(object)* 47 | - **channel** *(object)* - Holds all properties of the channel 48 | - **title** *(string)* - The name of the channel 49 | - **link** *(string)* - The URL to the HTML website corresponding to the channel 50 | - **description** *(string)* - Phrase or sentence describing the channel 51 | - **categories** *(array<string>)* - An array of categories that the channel belongs to 52 | - **language** *(string)* - The language the channel is written in 53 | - **copyright** *(string)* - Copyright notice for content in the channel 54 | - **managingEditor** *(string)* - Email address for person responsible for editorial content 55 | - **webMaster** *(string)* - Email address for person responsible for technical issues relating to channel 56 | - **pubDate** *(string)* - The publication date for the content in the channel 57 | - **lastBuildDate** *(string)* - The last time the content of the channel changed 58 | - **generator** *(string)* - A string indicating the program used to generate the channel 59 | - **docs** *(string)* - A URL that points to the documentation for the format used in the RSS file 60 | - **cloud** *(object)* - Allows processes to register with a cloud to be notified of updates to the channel, implementing a lightweight publish-subscribe protocol for RSS feeds 61 | - **ttl** *(number)* - Number of minutes that indicates how long a channel can be cached before refreshing from the source 62 | - **image** *(object)* - Specifies a GIF, JPEG or PNG image that can be displayed with the channel 63 | - **url** *(string)* - The URL of a GIF, JPEG or PNG image that represents the channel 64 | - **title** *(string)* - Describes the image, it's used in the ALT attribute of the HTML <img> tag when the channel is rendered in HTML 65 | - **link** *(string)* -The URL of the site, when the channel is rendered, the image is a link to the site 66 | - **width** *(number)* - Width of the image 67 | - **height** *(number)* - Height of the image 68 | - **rating** *(string)* - The [PICS](http://www.w3.org/PICS/) rating for the channel 69 | - **textInput** *(object)* - Specifies a text input box that can be displayed with the channel 70 | - **title** *(string)* - The label of the Submit button in the text input area 71 | - **description** *(string)* - Explains the text input area 72 | - **name** *(string)* - The name of the text object in the text input area 73 | - **link** *(string)* - The URL of the CGI script that processes text input request 74 | - **skipHours** *(array<number>)* - A hint for aggregators telling them which hours they can skip, which takes the form of an array that contains up to 24 numbers, between 0 and 23, that specify a time in GMT 75 | - **skipDays** *(array<string>)*- A hint for aggregators telling them which days they can skip, which takes the form of an array that contains up to seven strings, with possible values of: 76 | - *Monday* 77 | - *Tuesday* 78 | - *Wednesday* 79 | - *Thursday* 80 | - *Friday* 81 | - *Saturday* 82 | - *Sunday* 83 | - **item** *(object)*- Holds all properties of an item in the channel 84 | - **title** *(string)* - The title of the item 85 | - **link** *(string)* - The URL of the item 86 | - **description** *(string)* - The item synopsis 87 | - **author** *(string)* - Email address of the author of the item 88 | - **categories** *(array<string>)* - An array of categories that the item belongs to 89 | - **comments** *(string)* - URL of a page for comments relating to the item 90 | - **enclosure** *(object)* - Describes a media object that is attached to the item 91 | - **url** *(string)* - Where the enclosure is located 92 | - **length** *(number)* - How big the media object is 93 | - **type** *(string)* - The MIME type of the media object 94 | - **guid** *(string)* - A string that uniquely identifies the item 95 | - **pubDate** *(string)* - Indicates when the item was published 96 | - **source** *(string)* - The RSS channel that the item came from 97 | 98 | 99 | 100 | *Example*: 101 | 102 | ```json 103 | { 104 | "version": "0", 105 | "id": "7bb52df8-ae60-d674-6f5e-f6cc2ad055c9", 106 | "detail-type": "New RSS Item", 107 | "source": "https://www.nasa.gov/rss/dyn/breaking_news.rss", 108 | "account": "106110356429", 109 | "time": "2020-03-07T06:08:01Z", 110 | "region": "us-east-1", 111 | "resources": [], 112 | "detail": { 113 | "item": { 114 | "title": "SpaceX Dragon Heads to Space Station with NASA Science, Cargo", 115 | "link": "http://www.nasa.gov/press-release/spacex-dragon-heads-to-space-station-with-nasa-science-cargo-1", 116 | "description": "A SpaceX Dragon cargo spacecraft is on its way to the International Space Station after launching at 11:50 p.m. EST Friday. Dragon will deliver more than 4,300 pounds of NASA cargo and science investigations, including a new science facility scheduled to be installed to the outside of the station during a spacewalk this spring.", 117 | "enclosure": { 118 | "url": "http://www.nasa.gov/sites/default/files/styles/1x1_cardfeed/public/thumbnails/image/spx_launch_0.png?itok=jlsrAtrt", 119 | "length": "953717", 120 | "type": "image/png" 121 | }, 122 | "guid": "http://www.nasa.gov/press-release/spacex-dragon-heads-to-space-station-with-nasa-science-cargo-1", 123 | "pubDate": "Fri, 06 Mar 2020 23:59 EST", 124 | "source": { 125 | "url": "http://www.nasa.gov/rss/dyn/breaking_news.rss", 126 | "name": "NASA Breaking News" 127 | } 128 | }, 129 | "channel": { 130 | "title": "NASA Breaking News", 131 | "description": "A RSS news feed containing the latest NASA news articles and press releases.", 132 | "link": "http://www.nasa.gov/", 133 | "language": "en-us", 134 | "managingEditor": "jim.wilson@nasa.gov", 135 | "webMaster": "brian.dunbar@nasa.gov", 136 | "docs": "http://blogs.harvard.edu/tech/rss" 137 | } 138 | } 139 | } -------------------------------------------------------------------------------- /lambdas/list-sources/index.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import json 3 | import os 4 | import traceback 5 | 6 | # AWS SDK CLIENTS 7 | dynamo_client = boto3.client('dynamodb') 8 | sqs_client = boto3.client('sqs') 9 | 10 | # Function handler 11 | def handler(event, context): 12 | next_scan_key = "?" 13 | while next_scan_key: 14 | # Scan sources table 15 | scan_request = { 16 | "TableName" : os.environ["DYNAMO_TABLE"] 17 | } 18 | if next_scan_key != "?": 19 | scan_request["ExclusiveStartKey"] = next_scan_key 20 | scan_response = dynamo_client.scan(**scan_request) 21 | if scan_response["Count"] != 0: 22 | # For each source found in table, send message to queue for processing 23 | for item in scan_response["Items"]: 24 | try: 25 | message = { 26 | "source": item["source"]["S"] 27 | } 28 | if item.get("httpHeaderOverrides"): 29 | message["headers"] = { key: value["S"] for key, value in item["httpHeaderOverrides"]["M"].items() } 30 | sqs_client.send_message( 31 | QueueUrl=os.environ["QUEUE_URL"], 32 | MessageBody=json.dumps(message) 33 | ) 34 | except: 35 | traceback.print_exc() 36 | next_scan_key = scan_response["LastEvaluatedKey"] if "LastEvaluatedKey" in scan_response else None 37 | -------------------------------------------------------------------------------- /lambdas/process-channel/index.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import os 3 | import json 4 | import urllib 5 | import urllib.request 6 | import xml.etree.ElementTree as ET 7 | from datetime import datetime 8 | import hashlib 9 | import time 10 | import traceback 11 | 12 | # AWS SDK CLIENTS 13 | sqs_client = boto3.client("sqs") 14 | dynamo_client = boto3.client('dynamodb') 15 | 16 | # Parse XML content of RSS feed 17 | def parse_rss(text): 18 | root = ET.fromstring(text) 19 | channel_properties = {} 20 | items = [] 21 | # Parse all elements in channel 22 | for element in root.findall('./channel/'): 23 | if element.tag == "item": 24 | item = {} 25 | for item_element in element: 26 | # Only extract supported item elements 27 | if item_element.tag == "category": 28 | item.setdefault("categories", []) 29 | item["categories"].append(item_element.text) 30 | elif item_element.tag == "title": 31 | item["title"] = item_element.text 32 | elif item_element.tag == "link": 33 | item["link"] = item_element.text 34 | elif item_element.tag == "description": 35 | item["description"] = item_element.text 36 | elif item_element.tag == "author": 37 | item["author"] = item_element.text 38 | elif item_element.tag == "comments": 39 | item["comments"] = item_element.text 40 | elif item_element.tag == "guid": 41 | item["guid"] = item_element.text 42 | elif item_element.tag == "pubDate": 43 | item["pubDate"] = item_element.text 44 | elif item_element.tag == "enclosure": 45 | item["enclosure"] = item_element.attrib 46 | elif item_element.tag == "source": 47 | item["source"] = item_element.attrib 48 | item["source"]["name"] = item_element.text 49 | items.append(item) 50 | # Only extract supported channel elements 51 | elif element.tag == "category": 52 | channel_properties.setdefault("categories", []) 53 | channel_properties["categories"].append(element.text) 54 | elif element.tag == "title": 55 | channel_properties["title"] = element.text 56 | elif element.tag == "link": 57 | channel_properties["link"] = element.text 58 | elif element.tag == "description": 59 | channel_properties["description"] = element.text 60 | elif element.tag == "language": 61 | channel_properties["language"] = element.text 62 | elif element.tag == "copyright": 63 | channel_properties["copyright"] = element.text 64 | elif element.tag == "managingEditor": 65 | channel_properties["managingEditor"] = element.text 66 | elif element.tag == "webMaster": 67 | channel_properties["webMaster"] = element.text 68 | elif element.tag == "pubDate": 69 | channel_properties["pubDate"] = element.text 70 | elif element.tag == "lastBuildDate": 71 | channel_properties["lastBuildDate"] = element.text 72 | elif element.tag == "generator": 73 | channel_properties["generator"] = element.text 74 | elif element.tag == "docs": 75 | channel_properties["docs"] = element.text 76 | elif element.tag == "cloud": 77 | channel_properties["cloud"] = element.attrib 78 | elif element.tag == "ttl": 79 | channel_properties["ttl"] = int(element.text) 80 | elif element.tag == "image": 81 | channel_properties["image"] = {} 82 | for image_element in element: 83 | if image_element.tag == "url": 84 | channel_properties["image"]["url"] = image_element.text 85 | if image_element.tag == "title": 86 | channel_properties["image"]["title"] = image_element.text 87 | if image_element.tag == "link": 88 | channel_properties["image"]["link"] = image_element.text 89 | if image_element.tag == "width": 90 | channel_properties["image"]["width"] = int(image_element.text) 91 | if image_element.tag == "height": 92 | channel_properties["image"]["height"] = int(image_element.text) 93 | if image_element.tag == "description": 94 | channel_properties["image"]["description"] = image_element.text 95 | elif element.tag == "rating": 96 | channel_properties["rating"] = element.text 97 | elif element.tag == "textInput": 98 | channel_properties["textInput"] = {} 99 | for text_input_element in element: 100 | if text_input_element.tag == "name": 101 | channel_properties["textInput"]["name"] = text_input_element.text 102 | if text_input_element.tag == "title": 103 | channel_properties["textInput"]["title"] = text_input_element.text 104 | if text_input_element.tag == "link": 105 | channel_properties["textInput"]["link"] = text_input_element.text 106 | if text_input_element.tag == "description": 107 | channel_properties["textInput"]["description"] = text_input_element.text 108 | elif element.tag == "skipHours": 109 | channel_properties["skipHours"] = [int(hour.text) for hour in root.findall('./channel/skipHours/hour')] 110 | elif element.tag == "skipDays": 111 | channel_properties["skipDays"] = [day.text for day in root.findall('./channel/skipDays/day')] 112 | # Return channel element values and channel items 113 | return channel_properties, items 114 | 115 | 116 | # List the guids of all channel items from this source that have already been sent 117 | def list_guids(source): 118 | guids = set() 119 | next_key = "?" 120 | while next_key: 121 | query_request = { 122 | "TableName" : os.environ["DYNAMO_TABLE"], 123 | "ExpressionAttributeNames" : { 124 | "#S" : "source", 125 | "#G" : "guid" 126 | }, 127 | "ExpressionAttributeValues" : { 128 | ":source" : { 129 | "S" : source 130 | } 131 | }, 132 | "KeyConditionExpression" : "#S = :source", 133 | "ProjectionExpression" : "#G" 134 | } 135 | if next_key != "?": 136 | query_request["ExclusiveStartKey"] = next_key 137 | query_response = dynamo_client.query(**query_request) 138 | if query_response["Count"] > 0: 139 | guids = guids.union([item["guid"]["S"] for item in query_response["Items"]]) 140 | next_key = query_response["LastEvaluatedKey"] if "LastEvaluatedKey" in query_response else None 141 | return guids 142 | 143 | 144 | # Delete channel items that are no longer visible in the channel 145 | def delete_old_items(source, old_item_guids): 146 | for i in range(0, len(old_item_guids), 25): 147 | time_wait = 0.05 148 | batch = old_item_guids[i:i+25] 149 | unprocessed_items = { 150 | os.environ["DYNAMO_TABLE"]: [ 151 | { 152 | "DeleteRequest": { 153 | "Key": { 154 | "source": { 155 | "S": source 156 | }, 157 | "guid": { 158 | "S": item 159 | }, 160 | } 161 | } 162 | } 163 | for item in batch 164 | ] 165 | } 166 | while unprocessed_items and len(unprocessed_items) > 0 and time_wait < 1: 167 | delete_response = dynamo_client.batch_write_item(RequestItems=unprocessed_items) 168 | unprocessed_items = delete_response.get("UnprocessedItems") 169 | time.sleep(time_wait) 170 | time_wait = time_wait * 2 171 | 172 | 173 | # Send new channel items to another queue to be processed 174 | def send_queue_messages(source, channel_attributes, new_items): 175 | for item in new_items: 176 | try: 177 | # Create hash of message to prevent deduplication 178 | message_hash = hashlib.md5("{}{}".format(source, item["guid"]).encode("utf-8")).hexdigest() 179 | sqs_client.send_message( 180 | QueueUrl=os.environ["ITEM_QUEUE_URL"], 181 | MessageBody=json.dumps({ 182 | "source": source, 183 | "channel": channel_attributes, 184 | "item": item 185 | }), 186 | MessageDeduplicationId=message_hash, 187 | MessageGroupId=message_hash 188 | ) 189 | except: 190 | print("Error sending queue message for item") 191 | print("Item:", item) 192 | traceback.print_exc() 193 | 194 | 195 | # Function handler 196 | def handler(event, context): 197 | for record in event['Records']: 198 | try: 199 | sqs_message = json.loads(record["body"]) 200 | source = sqs_message["source"] 201 | request_headers = sqs_message.get("headers") 202 | # Make HTTP request to get RSS feed content 203 | request = urllib.request.Request(source) 204 | if request_headers: 205 | for header, value in request_headers.items(): 206 | request.add_header(header, value) 207 | response = urllib.request.urlopen(request) 208 | # Extract channel attributes and channel items 209 | channel_attributes, items = parse_rss(response.read().decode("utf-8")) 210 | # Obtain guids of current channel items and already-processed channel items 211 | item_guids = set([item["guid"] for item in items]) 212 | stored_guids = list_guids(source) 213 | new_item_guids = item_guids.difference(stored_guids) 214 | old_item_guids = list(stored_guids.difference(item_guids)) 215 | new_items = [item for item in items if item["guid"] in new_item_guids] 216 | # Process new items, delete old items 217 | send_queue_messages(source, channel_attributes, new_items) 218 | delete_old_items(source, old_item_guids) 219 | except: 220 | print("Error processing source") 221 | traceback.print_exc() 222 | finally: 223 | # Always delete message from queue, even in an error. 224 | # Parsing this RSS source can be tried again later 225 | sqs_client.delete_message( 226 | QueueUrl=os.environ["CHANNEL_QUEUE_URL"], 227 | ReceiptHandle=record["receiptHandle"] 228 | ) -------------------------------------------------------------------------------- /lambdas/process-item/index.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import os 3 | import json 4 | import traceback 5 | 6 | # AWS SDK CLIENTS 7 | sqs_client = boto3.client("sqs") 8 | dynamo_client = boto3.client('dynamodb') 9 | event_client = boto3.client('events') 10 | 11 | # Function handler 12 | def handler(event, context): 13 | for record in event['Records']: 14 | body = json.loads(record["body"]) 15 | # Form body of detail for event 16 | entry = { 17 | "item": body["item"], 18 | "channel": body["channel"] 19 | } 20 | # Send event to event bus 21 | put_events_response = event_client.put_events( 22 | Entries=[ 23 | { 24 | "Source": body["source"], 25 | "Detail": json.dumps(entry), 26 | "EventBusName": os.environ["EVENT_BUS_NAME"], 27 | "DetailType": "New RSS Item" 28 | } 29 | ] 30 | ) 31 | print(put_events_response) 32 | # Record that this item has been processed by creating a row 33 | # in the DynamoDB table 34 | dynamo_client.put_item( 35 | TableName=os.environ["DYNAMO_TABLE"], 36 | Item={ 37 | "source": { 38 | "S": body["source"] 39 | }, 40 | "guid": { 41 | "S": body["item"]["guid"] 42 | } 43 | } 44 | ) 45 | # Delete this message if it is processed successully 46 | sqs_client.delete_message( 47 | QueueUrl=os.environ["ITEM_QUEUE_URL"], 48 | ReceiptHandle=record["receiptHandle"] 49 | ) -------------------------------------------------------------------------------- /template.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Transform: 3 | - AWS::Serverless-2016-10-31 4 | 5 | Parameters: 6 | ScheduleExpression: 7 | Type: String 8 | Description: The CloudWatch cron or rate expression to determine how often each RSS feed is checked for new content 9 | Default: 'rate(1 hour)' 10 | EventBusName: 11 | Description: Name of event bus to which RSS notifications are sent 12 | Type: String 13 | Default: 'rss' 14 | ChannelQueueVisibilityTimeout: 15 | Description: The amount of seconds to wait until a message is made visible again for the channel SQS queue 16 | Type: Number 17 | Default: 90 18 | MinValue: 65 19 | ItemQueueVisibilityTimeout: 20 | Description: The amount of seconds to wait until a message is made visible again for the item SQS queue 21 | Type: Number 22 | Default: 30 23 | MinValue: 20 24 | ChannelQueueRetention: 25 | Description: The amount of seconds to retain a message in the channel SQS queue 26 | Type: Number 27 | Default: 300 28 | ItemQueueRetention: 29 | Description: The amount of seconds to retain a message in the item SQS queue 30 | Type: Number 31 | Default: 300 32 | 33 | Outputs: 34 | SourcesTableName: 35 | Description: Name of RSS source table 36 | Value: !Ref SourcesTable 37 | SourcesTableArn: 38 | Description: ARN of RSS source table 39 | Value: !GetAtt SourcesTable.Arn 40 | ItemsTableName: 41 | Description: Name of channel item table 42 | Value: !Ref ItemsTable 43 | ItemsTableArn: 44 | Description: ARN of channel item table 45 | Value: !GetAtt ItemsTable.Arn 46 | EventBusName: 47 | Description: Name of event bus 48 | Value: !Ref EventBus 49 | EventBusArn: 50 | Description: ARN of event bus 51 | Value: !GetAtt EventBus.Arn 52 | 53 | Resources: 54 | 55 | ## EVENT BUSES ## 56 | 57 | 58 | # The EventBridge event bus to which RSS notifications are sent 59 | EventBus: 60 | Type: AWS::Events::EventBus 61 | Properties: 62 | Name: !Ref EventBusName 63 | 64 | ## DYNAMO TABLES ## 65 | 66 | 67 | # Holds all sources of RSS feeds 68 | SourcesTable: 69 | Type: AWS::Serverless::SimpleTable 70 | Properties: 71 | PrimaryKey: 72 | # 'source' is the URL of the RSS feed 73 | Name: source 74 | Type: String 75 | 76 | # Holds all processed channel items for each source 77 | ItemsTable: 78 | Type: AWS::DynamoDB::Table 79 | Properties: 80 | AttributeDefinitions: 81 | - 82 | # 'source' is the URL of the RSS feed 83 | AttributeName: source 84 | AttributeType: S 85 | - 86 | # 'guid' is the guid of the channel item 87 | AttributeName: guid 88 | AttributeType: S 89 | BillingMode: PAY_PER_REQUEST 90 | KeySchema: 91 | - 92 | AttributeName: source 93 | KeyType: HASH 94 | - 95 | AttributeName: guid 96 | KeyType: RANGE 97 | 98 | 99 | ## SQS QUEUES ## 100 | 101 | 102 | # Standard queue for processing each RSS source 103 | ChannelQueue: 104 | Type: AWS::SQS::Queue 105 | Properties: 106 | VisibilityTimeout: !Ref ChannelQueueVisibilityTimeout 107 | MessageRetentionPeriod: !Ref ChannelQueueRetention 108 | 109 | # FIFO queue for processing channel items 110 | ItemQueue: 111 | Type: AWS::SQS::Queue 112 | Properties: 113 | FifoQueue: true 114 | VisibilityTimeout: !Ref ItemQueueVisibilityTimeout 115 | ContentBasedDeduplication: true 116 | MessageRetentionPeriod: !Ref ItemQueueRetention 117 | 118 | 119 | ## LAMBDA FUNCTIONS ## 120 | 121 | 122 | # Runs on a schedule. Reads all sources from the sources DynamoDB table, 123 | # and sends a message to the channel SQS queue for each source. 124 | ListSourcesFunction: 125 | Type: AWS::Serverless::Function 126 | Properties: 127 | Handler: index.handler 128 | Runtime: python3.12 129 | CodeUri: lambdas/list-sources 130 | Timeout: 30 131 | Policies: 132 | - DynamoDBReadPolicy: 133 | TableName: !Ref SourcesTable 134 | - SQSSendMessagePolicy: 135 | QueueName: !GetAtt ChannelQueue.QueueName 136 | Environment: 137 | Variables: 138 | DYNAMO_TABLE: !Ref SourcesTable 139 | QUEUE_URL: !Ref ChannelQueue 140 | Events: 141 | ScheduleEvent: 142 | Type: Schedule 143 | Properties: 144 | Schedule: !Ref ScheduleExpression 145 | Enabled: True 146 | 147 | # Processes messages from the channel SQS queue. Reads the content of 148 | # the RSS feed, and extracts channel properties and items. New channel 149 | # items are sent to the item SQS queue for processing, and old channel items 150 | # are removed from the items DynamoDB table. 151 | ProcessChannelFunction: 152 | Type: AWS::Serverless::Function 153 | Properties: 154 | Handler: index.handler 155 | Runtime: python3.12 156 | CodeUri: lambdas/process-channel 157 | Timeout: 60 158 | Policies: 159 | - DynamoDBReadPolicy: 160 | TableName: !Ref ItemsTable 161 | - SQSPollerPolicy: 162 | QueueName: !GetAtt ChannelQueue.QueueName 163 | - SQSSendMessagePolicy: 164 | QueueName: !GetAtt ItemQueue.QueueName 165 | Environment: 166 | Variables: 167 | DYNAMO_TABLE: !Ref ItemsTable 168 | CHANNEL_QUEUE_URL: !Ref ChannelQueue 169 | ITEM_QUEUE_URL: !Ref ItemQueue 170 | Events: 171 | SQSEvent: 172 | Type: SQS 173 | Properties: 174 | Queue: !GetAtt ChannelQueue.Arn 175 | Enabled: True 176 | 177 | # Processes messages from the item SQS queue. Sends an event to the event bus 178 | # and inserts a row into the item DynamoDB table. 179 | ProcessItemFunction: 180 | Type: AWS::Serverless::Function 181 | Properties: 182 | Handler: index.handler 183 | Runtime: python3.12 184 | CodeUri: lambdas/process-item 185 | Timeout: 15 186 | Policies: 187 | - DynamoDBCrudPolicy: 188 | TableName: !Ref ItemsTable 189 | - SQSPollerPolicy: 190 | QueueName: !GetAtt ItemQueue.QueueName 191 | - EventBridgePutEventsPolicy: 192 | EventBusName: !Ref EventBus 193 | Environment: 194 | Variables: 195 | DYNAMO_TABLE: !Ref ItemsTable 196 | ITEM_QUEUE_URL: !Ref ItemQueue 197 | EVENT_BUS_NAME: !Ref EventBus 198 | Events: 199 | SQSEvent: 200 | Type: SQS 201 | Properties: 202 | Queue: !GetAtt ItemQueue.Arn 203 | Enabled: True --------------------------------------------------------------------------------