├── .github └── CODEOWNERS ├── .gitignore ├── CHANGELOG.md ├── License.md ├── setup.py └── tap_framework ├── __init__.py ├── client.py ├── config.py ├── schemas.py ├── state.py └── streams.py /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Owning team for this repo 2 | * @dbt-labs/tap-team 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.json 2 | !*/schemas/*.json 3 | *.sublime-* 4 | .python-version 5 | singer-check-tap-data 6 | *.pyc 7 | *.egg-info 8 | dist/ 9 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 0.1.1 (May 6, 2019) 2 | 3 | - Use `selected-by-default` metadata if `selected` is not available 4 | 5 | ## 0.1.0 (April 5, 2019) 6 | 7 | - Remove default key property `id` 8 | -------------------------------------------------------------------------------- /License.md: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from setuptools import setup, find_packages 4 | import os.path 5 | 6 | setup(name='tap-framework', 7 | version='0.2.0', 8 | description='Framework for building Singer.io taps', 9 | author='dbt Labs', 10 | url='https://getdbt.com', 11 | classifiers=['Programming Language :: Python :: 3 :: Only'], 12 | py_modules=['tap_framework'], 13 | install_requires=[ 14 | 'singer-python>=5.1.0,<5.14', 15 | 'backoff>=1.3.2,<=1.8.0', 16 | 'requests>=2.18.4,<2.29', 17 | 'requests-oauthlib>=0.8.0,<1.4', 18 | 'funcy>=1.10.1,<1.19', 19 | ], 20 | packages=['tap_framework']) 21 | -------------------------------------------------------------------------------- /tap_framework/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import json 4 | import sys 5 | 6 | import singer 7 | 8 | from tap_framework.state import save_state 9 | from tap_framework.streams import is_selected 10 | 11 | LOGGER = singer.get_logger() # noqa 12 | 13 | 14 | class Runner: 15 | 16 | def __init__(self, args, client, available_streams): 17 | self.config = args.config 18 | self.state = args.state 19 | self.catalog = args.catalog 20 | self.client = client 21 | self.available_streams = available_streams 22 | 23 | def get_streams_to_replicate(self): 24 | streams = [] 25 | 26 | if not self.catalog: 27 | return streams 28 | 29 | for stream_catalog in self.catalog.streams: 30 | if not is_selected(stream_catalog): 31 | LOGGER.info("'{}' is not marked selected, skipping." 32 | .format(stream_catalog.stream)) 33 | continue 34 | 35 | for available_stream in self.available_streams: 36 | if available_stream.matches_catalog(stream_catalog): 37 | if not available_stream.requirements_met(self.catalog): 38 | raise RuntimeError( 39 | "{} requires that that the following are " 40 | "selected: {}" 41 | .format(stream_catalog.stream, 42 | ','.join(available_stream.REQUIRES))) 43 | 44 | to_add = available_stream( 45 | self.config, self.state, stream_catalog, self.client) 46 | 47 | streams.append(to_add) 48 | 49 | return streams 50 | 51 | def do_discover(self): 52 | LOGGER.info("Starting discovery.") 53 | 54 | catalog = [] 55 | 56 | for available_stream in self.available_streams: 57 | stream = available_stream(self.config, self.state, None, None) 58 | 59 | catalog += stream.generate_catalog() 60 | 61 | json.dump({'streams': catalog}, sys.stdout, indent=4) 62 | 63 | def do_sync(self): 64 | LOGGER.info("Starting sync.") 65 | 66 | streams = self.get_streams_to_replicate() 67 | 68 | for stream in streams: 69 | try: 70 | stream.state = self.state 71 | stream.sync() 72 | self.state = stream.state 73 | except OSError as e: 74 | LOGGER.error(str(e)) 75 | exit(e.errno) 76 | 77 | except Exception as e: 78 | LOGGER.error(str(e)) 79 | LOGGER.error('Failed to sync endpoint {}, moving on!' 80 | .format(stream.TABLE)) 81 | raise e 82 | 83 | save_state(self.state) 84 | 85 | 86 | # @singer.utils.handle_top_exception(LOGGER) 87 | # def main(): 88 | # args = singer.utils.parse_args( 89 | # required_config_keys=['api_key', 'client_id']) 90 | 91 | # if args.discover: 92 | # do_discover(args) 93 | # else: 94 | # do_sync(args) 95 | 96 | 97 | # if __name__ == '__main__': 98 | # main() 99 | -------------------------------------------------------------------------------- /tap_framework/client.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import singer 3 | import time 4 | 5 | LOGGER = singer.get_logger() 6 | 7 | 8 | class BaseClient: 9 | 10 | def __init__(self, config): 11 | self.config = config 12 | 13 | def get_authorization(self): 14 | raise RuntimeError("get_authorization not implemented!") 15 | 16 | def make_request(self, url, method, base_backoff=45, 17 | params=None, body=None): 18 | auth = self.get_authorization() 19 | 20 | LOGGER.info("Making {} request to {}".format(method, url)) 21 | 22 | response = requests.request( 23 | method, 24 | url, 25 | headers={ 26 | 'Content-Type': 'application/json' 27 | }, 28 | auth=auth, 29 | params=params, 30 | json=body) 31 | 32 | if response.status_code == 429: 33 | LOGGER.info('Got a 429, sleeping for {} seconds and trying again' 34 | .format(base_backoff)) 35 | time.sleep(base_backoff) 36 | return self.make_request(url, method, base_backoff * 2, params, body) 37 | 38 | if response.status_code != 200: 39 | raise RuntimeError(response.text) 40 | 41 | return response.json() 42 | -------------------------------------------------------------------------------- /tap_framework/config.py: -------------------------------------------------------------------------------- 1 | from dateutil.parser import parse 2 | 3 | 4 | def get_config_start_date(config): 5 | return parse(config.get('start_date')) 6 | -------------------------------------------------------------------------------- /tap_framework/schemas.py: -------------------------------------------------------------------------------- 1 | import os.path 2 | import singer.utils 3 | import sys 4 | 5 | 6 | def get_abs_path(path): 7 | return os.path.join( 8 | os.path.dirname( 9 | os.path.dirname( 10 | sys.modules['__main__'].__file__)), 11 | path) 12 | 13 | 14 | def load_schema_by_name(name): 15 | return singer.utils.load_json('schemas/{}.json'.format(name)) 16 | -------------------------------------------------------------------------------- /tap_framework/state.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import json 3 | import singer 4 | 5 | from dateutil.parser import parse 6 | 7 | LOGGER = singer.get_logger() 8 | 9 | 10 | def get_last_record_value_for_table(state, table): 11 | last_value = state.get('bookmarks', {}) \ 12 | .get(table, {}) \ 13 | .get('last_record') 14 | 15 | if last_value is None: 16 | return None 17 | 18 | return parse(last_value) 19 | 20 | 21 | def incorporate(state, table, field, value): 22 | if value is None: 23 | return state 24 | 25 | if state is None: 26 | new_state = {} 27 | else: 28 | new_state = state.copy() 29 | 30 | if isinstance(value, datetime.datetime): 31 | parsed = value.strftime("%Y-%m-%d %H:%M:%S") 32 | else: 33 | parsed = parse(value).strftime("%Y-%m-%d %H:%M:%S") 34 | 35 | if 'bookmarks' not in new_state: 36 | new_state['bookmarks'] = {} 37 | 38 | if(new_state['bookmarks'].get(table, {}).get('last_record') is None or 39 | new_state['bookmarks'].get(table, {}).get('last_record') < parsed): 40 | new_state['bookmarks'][table] = { 41 | 'field': field, 42 | 'last_record': parsed, 43 | } 44 | 45 | return new_state 46 | 47 | 48 | def save_state(state): 49 | if not state: 50 | return 51 | 52 | LOGGER.info('Updating state.') 53 | 54 | singer.write_state(state) 55 | 56 | 57 | def load_state(filename): 58 | if filename is None: 59 | return {} 60 | 61 | try: 62 | with open(filename) as handle: 63 | return json.load(handle) 64 | except: 65 | LOGGER.fatal("Failed to decode state file. Is it valid json?") 66 | raise RuntimeError 67 | -------------------------------------------------------------------------------- /tap_framework/streams.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | import os.path 3 | import singer 4 | import singer.utils 5 | import singer.metrics 6 | 7 | LOGGER = singer.get_logger() 8 | 9 | 10 | def is_selected(stream_catalog): 11 | metadata = singer.metadata.to_map(stream_catalog.metadata) 12 | stream_metadata = metadata.get((), {}) 13 | 14 | inclusion = stream_metadata.get('inclusion') 15 | 16 | if stream_metadata.get('selected') is not None: 17 | selected = stream_metadata.get('selected') 18 | else: 19 | selected = stream_metadata.get('selected-by-default') 20 | 21 | if inclusion == 'unsupported': 22 | return False 23 | 24 | elif selected is not None: 25 | return selected 26 | 27 | return inclusion == 'automatic' 28 | 29 | 30 | class BaseStream: 31 | # GLOBAL PROPERTIES 32 | TABLE = None 33 | KEY_PROPERTIES = [] 34 | API_METHOD = 'GET' 35 | REQUIRES = [] 36 | 37 | def __init__(self, config, state, catalog, client): 38 | self.config = config 39 | self.state = state 40 | self.catalog = catalog 41 | self.client = client 42 | self.substreams = [] 43 | 44 | def get_class_path(self): 45 | return os.path.dirname(inspect.getfile(self.__class__)) 46 | 47 | def load_schema_by_name(self, name): 48 | return singer.utils.load_json( 49 | os.path.normpath( 50 | os.path.join( 51 | self.get_class_path(), 52 | '../schemas/{}.json'.format(name)))) 53 | 54 | def get_schema(self): 55 | return self.load_schema_by_name(self.TABLE) 56 | 57 | def get_stream_data(self, result): 58 | """ 59 | Given a result set from Campaign Monitor, return the data 60 | to be persisted for this stream. 61 | """ 62 | raise RuntimeError("get_stream_data not implemented!") 63 | 64 | def get_url(self): 65 | """ 66 | Return the URL to hit for data from this stream. 67 | """ 68 | raise RuntimeError("get_url not implemented!") 69 | 70 | @classmethod 71 | def requirements_met(cls, catalog): 72 | selected_streams = [ 73 | s.stream for s in catalog.streams if is_selected(s) 74 | ] 75 | 76 | return set(cls.REQUIRES).issubset(selected_streams) 77 | 78 | @classmethod 79 | def matches_catalog(cls, stream_catalog): 80 | return stream_catalog.stream == cls.TABLE 81 | 82 | def generate_catalog(self): 83 | schema = self.get_schema() 84 | mdata = singer.metadata.new() 85 | 86 | mdata = singer.metadata.write( 87 | mdata, 88 | (), 89 | 'inclusion', 90 | 'available' 91 | ) 92 | 93 | for field_name, field_schema in schema.get('properties').items(): 94 | inclusion = 'available' 95 | 96 | if field_name in self.KEY_PROPERTIES: 97 | inclusion = 'automatic' 98 | 99 | mdata = singer.metadata.write( 100 | mdata, 101 | ('properties', field_name), 102 | 'inclusion', 103 | inclusion 104 | ) 105 | 106 | return [{ 107 | 'tap_stream_id': self.TABLE, 108 | 'stream': self.TABLE, 109 | 'key_properties': self.KEY_PROPERTIES, 110 | 'schema': self.get_schema(), 111 | 'metadata': singer.metadata.to_list(mdata) 112 | }] 113 | 114 | def transform_record(self, record): 115 | with singer.Transformer() as tx: 116 | metadata = {} 117 | 118 | if self.catalog.metadata is not None: 119 | metadata = singer.metadata.to_map(self.catalog.metadata) 120 | 121 | return tx.transform( 122 | record, 123 | self.catalog.schema.to_dict(), 124 | metadata) 125 | 126 | def get_catalog_keys(self): 127 | return list(self.catalog.schema.properties.keys()) 128 | 129 | def write_schema(self): 130 | singer.write_schema( 131 | self.catalog.stream, 132 | self.catalog.schema.to_dict(), 133 | key_properties=self.catalog.key_properties) 134 | 135 | def sync(self): 136 | LOGGER.info('Syncing stream {} with {}' 137 | .format(self.catalog.tap_stream_id, 138 | self.__class__.__name__)) 139 | 140 | self.write_schema() 141 | 142 | return self.sync_data() 143 | 144 | def sync_data(self, substreams=None): 145 | if substreams is None: 146 | substreams = [] 147 | 148 | table = self.TABLE 149 | 150 | url = self.get_url() 151 | 152 | result = self.client.make_request(url, self.API_METHOD) 153 | 154 | data = self.get_stream_data(result) 155 | 156 | with singer.metrics.record_counter(endpoint=table) as counter: 157 | for index, obj in enumerate(data): 158 | LOGGER.debug("On {} of {}".format(index, len(data))) 159 | 160 | singer.write_records( 161 | table, 162 | [self.transform_record(obj)]) 163 | 164 | counter.increment() 165 | 166 | for substream in substreams: 167 | substream.sync_data(parent=obj) 168 | 169 | 170 | class ChildStream(BaseStream): 171 | 172 | def get_parent_id(self, parent): 173 | raise NotImplementedError('get_parent_id is not implemented!') 174 | 175 | def get_api_path_for_child(self, parent): 176 | raise NotImplementedError( 177 | 'get_api_path_for_child is not implemented!') 178 | 179 | def sync_data(self, parent=None): 180 | if parent is None: 181 | raise RuntimeError('Cannot sync a subobject of null!') 182 | 183 | table = self.TABLE 184 | url = self.get_url() 185 | 186 | result = self.client.make_request(url, self.API_METHOD) 187 | 188 | data = self.get_stream_data(result) 189 | 190 | with singer.metrics.record_counter(endpoint=table) as counter: 191 | for obj in data: 192 | singer.write_records( 193 | table, 194 | [self.transform_record( 195 | self.incorporate_parent_id(obj, parent))]) 196 | 197 | counter.increment() 198 | --------------------------------------------------------------------------------