dagster-tableau 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
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 2023 Dagster Labs, 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.
@@ -0,0 +1,3 @@
1
+ include README.md
2
+ include LICENSE
3
+ include dagster_tableau/py.typed
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.1
2
+ Name: dagster_tableau
3
+ Version: 0.0.1
4
+ Summary: Build assets representing Tableau workbooks and sheets.
5
+ Home-page: https://github.com/dagster-io/dagster/tree/master/python_modules/libraries/dagster-tableau
6
+ Author: Dagster Labs
7
+ Author-email: hello@dagsterlabs.com
8
+ License: Apache-2.0
9
+ Classifier: Programming Language :: Python :: 3.8
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Requires-Python: >=3.8,<3.13
17
+ License-File: LICENSE
18
+ Requires-Dist: dagster==0.0.1
19
+ Requires-Dist: pyjwt[crypto]
20
+ Requires-Dist: requests
@@ -0,0 +1,4 @@
1
+ # dagster-tableau
2
+
3
+ The docs for `dagster-tableau` can be found
4
+ [here](https://docs.dagster.io/_apidocs/libraries/dagster-tableau).
@@ -0,0 +1,12 @@
1
+ from dagster._core.libraries import DagsterLibraryRegistry
2
+
3
+ from dagster_tableau.resources import (
4
+ TableauCloudWorkspace as TableauCloudWorkspace,
5
+ TableauServerWorkspace as TableauServerWorkspace,
6
+ )
7
+ from dagster_tableau.translator import DagsterTableauTranslator as DagsterTableauTranslator
8
+
9
+ # Move back to version.py and edit setup.py once we are ready to publish.
10
+ __version__ = "0.0.1"
11
+
12
+ DagsterLibraryRegistry.register("dagster-tableau", __version__)
@@ -0,0 +1 @@
1
+ partial
@@ -0,0 +1,543 @@
1
+ import datetime
2
+ import uuid
3
+ from abc import abstractmethod
4
+ from contextlib import contextmanager
5
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Type, Union, cast
6
+
7
+ import jwt
8
+ import requests
9
+ from dagster import (
10
+ AssetsDefinition,
11
+ ConfigurableResource,
12
+ Definitions,
13
+ ObserveResult,
14
+ _check as check,
15
+ external_assets_from_specs,
16
+ multi_asset,
17
+ )
18
+ from dagster._annotations import experimental
19
+ from dagster._core.definitions.cacheable_assets import (
20
+ AssetsDefinitionCacheableData,
21
+ CacheableAssetsDefinition,
22
+ )
23
+ from dagster._utils.cached_method import cached_method
24
+ from pydantic import Field, PrivateAttr
25
+
26
+ from dagster_tableau.translator import (
27
+ DagsterTableauTranslator,
28
+ TableauContentData,
29
+ TableauContentType,
30
+ TableauWorkspaceData,
31
+ )
32
+
33
+ TABLEAU_REST_API_VERSION = "3.23"
34
+
35
+
36
+ @experimental
37
+ class BaseTableauClient:
38
+ def __init__(
39
+ self,
40
+ connected_app_client_id: str,
41
+ connected_app_secret_id: str,
42
+ connected_app_secret_value: str,
43
+ username: str,
44
+ site_name: str,
45
+ ):
46
+ self.connected_app_client_id = connected_app_client_id
47
+ self.connected_app_secret_id = connected_app_secret_id
48
+ self.connected_app_secret_value = connected_app_secret_value
49
+ self.username = username
50
+ self.site_name = site_name
51
+ self._api_token = None
52
+ self._site_id = None
53
+
54
+ @property
55
+ @abstractmethod
56
+ def rest_api_base_url(self) -> str:
57
+ raise NotImplementedError()
58
+
59
+ @property
60
+ @abstractmethod
61
+ def metadata_api_base_url(self) -> str:
62
+ raise NotImplementedError()
63
+
64
+ def _fetch_json(
65
+ self,
66
+ url: str,
67
+ data: Optional[Mapping[str, object]] = None,
68
+ method: str = "GET",
69
+ with_auth_header: bool = True,
70
+ ) -> Mapping[str, object]:
71
+ """Fetch JSON data from the Tableau APIs given the URL. Raises an exception if the request fails.
72
+
73
+ Args:
74
+ url (str): The url to fetch data from.
75
+ data (Optional[Dict[str, Any]]): JSON-formatted data string to be included in the request.
76
+ method (str): The HTTP method to use for the request.
77
+ with_auth_header (bool): Whether to add X-Tableau-Auth header to the request. Enabled by default.
78
+
79
+ Returns:
80
+ Dict[str, Any]: The JSON data returned from the API.
81
+ """
82
+ response = self._make_request(
83
+ url=url, data=data, method=method, with_auth_header=with_auth_header
84
+ )
85
+ return response.json()
86
+
87
+ def _make_request(
88
+ self,
89
+ url: str,
90
+ data: Optional[Mapping[str, object]] = None,
91
+ method: str = "GET",
92
+ with_auth_header: bool = True,
93
+ ) -> requests.Response:
94
+ headers: Mapping[str, object] = {
95
+ "accept": "application/json",
96
+ "content-type": "application/json",
97
+ }
98
+ if with_auth_header:
99
+ headers = {**headers, "X-tableau-auth": self._api_token}
100
+ request_args: Dict[str, Any] = dict(
101
+ method=method,
102
+ url=url,
103
+ headers=headers,
104
+ )
105
+ if data:
106
+ request_args = {**request_args, "json": data}
107
+ response = requests.request(**request_args)
108
+ response.raise_for_status()
109
+ return response
110
+
111
+ @cached_method
112
+ def get_workbooks(self) -> Mapping[str, object]:
113
+ """Fetches a list of all Tableau workbooks in the workspace."""
114
+ endpoint = self._with_site_id("workbooks")
115
+ return self._fetch_json(url=f"{self.rest_api_base_url}/{endpoint}")
116
+
117
+ @cached_method
118
+ def get_workbook(self, workbook_id) -> Mapping[str, object]:
119
+ """Fetches information, including sheets, dashboards and data sources, for a given workbook."""
120
+ data = {"query": self.workbook_graphql_query, "variables": {"luid": workbook_id}}
121
+ return self._fetch_json(url=self.metadata_api_base_url, data=data, method="POST")
122
+
123
+ @cached_method
124
+ def get_view(
125
+ self,
126
+ view_id: str,
127
+ ) -> Mapping[str, object]:
128
+ """Fetches information for a given view."""
129
+ endpoint = self._with_site_id(f"views/{view_id}")
130
+ return self._fetch_json(url=f"{self.rest_api_base_url}/{endpoint}")
131
+
132
+ def sign_in(self) -> Mapping[str, object]:
133
+ """Sign in to the site in Tableau."""
134
+ jwt_token = jwt.encode(
135
+ {
136
+ "iss": self.connected_app_client_id,
137
+ "exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=5),
138
+ "jti": str(uuid.uuid4()),
139
+ "aud": "tableau",
140
+ "sub": self.username,
141
+ "scp": ["tableau:content:read"],
142
+ },
143
+ self.connected_app_secret_value,
144
+ algorithm="HS256",
145
+ headers={"kid": self.connected_app_secret_id, "iss": self.connected_app_client_id},
146
+ )
147
+ data = {
148
+ "credentials": {
149
+ "jwt": jwt_token,
150
+ "site": {"contentUrl": self.site_name},
151
+ }
152
+ }
153
+ response = self._fetch_json(
154
+ url=f"{self.rest_api_base_url}/auth/signin",
155
+ data=data,
156
+ method="POST",
157
+ with_auth_header=False,
158
+ )
159
+
160
+ response = cast(Dict[str, Any], response)
161
+ self._api_token = response["credentials"]["token"]
162
+ self._site_id = response["credentials"]["site"]["id"]
163
+ return response
164
+
165
+ def sign_out(self) -> None:
166
+ """Sign out from the site in Tableau."""
167
+ self._make_request(url=f"{self.rest_api_base_url}/auth/signout", method="POST")
168
+ self._api_token = None
169
+ self._site_id = None
170
+
171
+ def _with_site_id(self, endpoint: str) -> str:
172
+ return f"sites/{self._site_id}/{endpoint}"
173
+
174
+ @property
175
+ def workbook_graphql_query(self) -> str:
176
+ return """
177
+ query workbooks($luid: String!) {
178
+ workbooks(filter: {luid: $luid}) {
179
+ luid
180
+ name
181
+ createdAt
182
+ updatedAt
183
+ uri
184
+ sheets {
185
+ luid
186
+ name
187
+ createdAt
188
+ updatedAt
189
+ path
190
+ parentEmbeddedDatasources {
191
+ parentPublishedDatasources {
192
+ luid
193
+ name
194
+ }
195
+ }
196
+ }
197
+ dashboards {
198
+ luid
199
+ name
200
+ createdAt
201
+ updatedAt
202
+ path
203
+ sheets {
204
+ luid
205
+ }
206
+ }
207
+ }
208
+ }
209
+ """
210
+
211
+
212
+ @experimental
213
+ class TableauCloudClient(BaseTableauClient):
214
+ """Represents a client for Tableau Cloud and provides utilities
215
+ to interact with the Tableau API.
216
+ """
217
+
218
+ def __init__(
219
+ self,
220
+ connected_app_client_id: str,
221
+ connected_app_secret_id: str,
222
+ connected_app_secret_value: str,
223
+ username: str,
224
+ site_name: str,
225
+ pod_name: str,
226
+ ):
227
+ self.pod_name = pod_name
228
+ super().__init__(
229
+ connected_app_client_id=connected_app_client_id,
230
+ connected_app_secret_id=connected_app_secret_id,
231
+ connected_app_secret_value=connected_app_secret_value,
232
+ username=username,
233
+ site_name=site_name,
234
+ )
235
+
236
+ @property
237
+ def rest_api_base_url(self) -> str:
238
+ """REST API base URL for Tableau Cloud."""
239
+ return f"https://{self.pod_name}.online.tableau.com/api/{TABLEAU_REST_API_VERSION}"
240
+
241
+ @property
242
+ def metadata_api_base_url(self) -> str:
243
+ """Metadata API base URL for Tableau Cloud."""
244
+ return f"https://{self.pod_name}.online.tableau.com/api/metadata/graphql"
245
+
246
+
247
+ @experimental
248
+ class TableauServerClient(BaseTableauClient):
249
+ """Represents a client for Tableau Server and provides utilities
250
+ to interact with Tableau APIs.
251
+ """
252
+
253
+ def __init__(
254
+ self,
255
+ connected_app_client_id: str,
256
+ connected_app_secret_id: str,
257
+ connected_app_secret_value: str,
258
+ username: str,
259
+ site_name: str,
260
+ server_name: str,
261
+ ):
262
+ self.server_name = server_name
263
+ super().__init__(
264
+ connected_app_client_id=connected_app_client_id,
265
+ connected_app_secret_id=connected_app_secret_id,
266
+ connected_app_secret_value=connected_app_secret_value,
267
+ username=username,
268
+ site_name=site_name,
269
+ )
270
+
271
+ @property
272
+ def rest_api_base_url(self) -> str:
273
+ """REST API base URL for Tableau Server."""
274
+ return f"https://{self.server_name}/api/{TABLEAU_REST_API_VERSION}"
275
+
276
+ @property
277
+ def metadata_api_base_url(self) -> str:
278
+ """Metadata API base URL for Tableau Server."""
279
+ return f"https://{self.server_name}/api/metadata/graphql"
280
+
281
+
282
+ @experimental
283
+ class BaseTableauWorkspace(ConfigurableResource):
284
+ """Base class to represent a workspace in Tableau and provides utilities
285
+ to interact with Tableau APIs.
286
+ """
287
+
288
+ connected_app_client_id: str = Field(
289
+ ..., description="The client id of the connected app used to connect to Tableau Workspace."
290
+ )
291
+ connected_app_secret_id: str = Field(
292
+ ..., description="The secret id of the connected app used to connect to Tableau Workspace."
293
+ )
294
+ connected_app_secret_value: str = Field(
295
+ ...,
296
+ description="The secret value of the connected app used to connect to Tableau Workspace.",
297
+ )
298
+ username: str = Field(..., description="The username to authenticate to Tableau Workspace.")
299
+ site_name: str = Field(..., description="The name of the Tableau site to use.")
300
+
301
+ _client: Optional[Union[TableauCloudClient, TableauServerClient]] = PrivateAttr(default=None)
302
+
303
+ @abstractmethod
304
+ def build_client(self) -> None:
305
+ raise NotImplementedError()
306
+
307
+ @contextmanager
308
+ def get_client(self):
309
+ if not self._client:
310
+ self.build_client()
311
+ self._client.sign_in()
312
+ try:
313
+ yield self._client
314
+ finally:
315
+ self._client.sign_out()
316
+
317
+ def fetch_tableau_workspace_data(
318
+ self,
319
+ ) -> TableauWorkspaceData:
320
+ """Retrieves all Tableau content from the workspace and returns it as a TableauWorkspaceData object.
321
+ Future work will cache this data to avoid repeated calls to the Tableau API.
322
+
323
+ Returns:
324
+ TableauWorkspaceData: A snapshot of the Tableau workspace's content.
325
+ """
326
+ with self.get_client() as client:
327
+ workbooks_data = client.get_workbooks()["workbooks"]
328
+ workbook_ids = [workbook["id"] for workbook in workbooks_data["workbook"]]
329
+
330
+ workbooks_by_id = {}
331
+ sheets_by_id = {}
332
+ dashboards_by_id = {}
333
+ data_sources_by_id = {}
334
+ for workbook_id in workbook_ids:
335
+ workbook_data = client.get_workbook(workbook_id=workbook_id)["data"]["workbooks"][0]
336
+ workbooks_by_id[workbook_id] = TableauContentData(
337
+ content_type=TableauContentType.WORKBOOK, properties=workbook_data
338
+ )
339
+
340
+ for sheet_data in workbook_data["sheets"]:
341
+ sheet_id = sheet_data["luid"]
342
+ if sheet_id:
343
+ augmented_sheet_data = {**sheet_data, "workbook": {"luid": workbook_id}}
344
+ sheets_by_id[sheet_id] = TableauContentData(
345
+ content_type=TableauContentType.SHEET, properties=augmented_sheet_data
346
+ )
347
+
348
+ for embedded_data_source_data in sheet_data.get(
349
+ "parentEmbeddedDatasources", []
350
+ ):
351
+ for published_data_source_data in embedded_data_source_data.get(
352
+ "parentPublishedDatasources", []
353
+ ):
354
+ data_source_id = published_data_source_data["luid"]
355
+ if data_source_id and data_source_id not in data_sources_by_id:
356
+ data_sources_by_id[data_source_id] = TableauContentData(
357
+ content_type=TableauContentType.DATA_SOURCE,
358
+ properties=published_data_source_data,
359
+ )
360
+
361
+ for dashboard_data in workbook_data["dashboards"]:
362
+ dashboard_id = dashboard_data["luid"]
363
+ if dashboard_id:
364
+ augmented_dashboard_data = {
365
+ **dashboard_data,
366
+ "workbook": {"luid": workbook_id},
367
+ }
368
+ dashboards_by_id[dashboard_id] = TableauContentData(
369
+ content_type=TableauContentType.DASHBOARD,
370
+ properties=augmented_dashboard_data,
371
+ )
372
+
373
+ return TableauWorkspaceData.from_content_data(
374
+ self.site_name,
375
+ list(workbooks_by_id.values())
376
+ + list(sheets_by_id.values())
377
+ + list(dashboards_by_id.values())
378
+ + list(data_sources_by_id.values()),
379
+ )
380
+
381
+ def build_assets(
382
+ self,
383
+ dagster_tableau_translator: Type[DagsterTableauTranslator],
384
+ ) -> Sequence[CacheableAssetsDefinition]:
385
+ """Returns a set of CacheableAssetsDefinition which will load Tableau content from
386
+ the workspace and translates it into AssetSpecs, using the provided translator.
387
+
388
+ Args:
389
+ dagster_tableau_translator (Type[DagsterTableauTranslator]): The translator to use
390
+ to convert Tableau content into AssetSpecs. Defaults to DagsterTableauTranslator.
391
+
392
+ Returns:
393
+ Sequence[CacheableAssetsDefinition]: A list of CacheableAssetsDefinitions which
394
+ will load the Tableau content.
395
+ """
396
+ return [TableauCacheableAssetsDefinition(self, dagster_tableau_translator)]
397
+
398
+ def build_defs(
399
+ self, dagster_tableau_translator: Type[DagsterTableauTranslator] = DagsterTableauTranslator
400
+ ) -> Definitions:
401
+ """Returns a Definitions object which will load Tableau content from
402
+ the workspace and translate it into assets, using the provided translator.
403
+
404
+ Args:
405
+ dagster_tableau_translator (Type[DagsterTableauTranslator]): The translator to use
406
+ to convert Tableau content into AssetSpecs. Defaults to DagsterTableauTranslator.
407
+
408
+ Returns:
409
+ Definitions: A Definitions object which will build and return the Power BI content.
410
+ """
411
+ defs = Definitions(
412
+ assets=self.build_assets(dagster_tableau_translator=dagster_tableau_translator)
413
+ )
414
+ return defs
415
+
416
+
417
+ @experimental
418
+ class TableauCloudWorkspace(BaseTableauWorkspace):
419
+ """Represents a workspace in Tableau Cloud and provides utilities
420
+ to interact with Tableau APIs.
421
+ """
422
+
423
+ pod_name: str = Field(..., description="The pod name of the Tableau Cloud workspace.")
424
+
425
+ def build_client(self) -> None:
426
+ self._client = TableauCloudClient(
427
+ connected_app_client_id=self.connected_app_client_id,
428
+ connected_app_secret_id=self.connected_app_secret_id,
429
+ connected_app_secret_value=self.connected_app_secret_value,
430
+ username=self.username,
431
+ site_name=self.site_name,
432
+ pod_name=self.pod_name,
433
+ )
434
+
435
+
436
+ @experimental
437
+ class TableauServerWorkspace(BaseTableauWorkspace):
438
+ """Represents a workspace in Tableau Server and provides utilities
439
+ to interact with Tableau APIs.
440
+ """
441
+
442
+ server_name: str = Field(..., description="The server name of the Tableau Server workspace.")
443
+
444
+ def build_client(self) -> None:
445
+ self._client = TableauServerClient(
446
+ connected_app_client_id=self.connected_app_client_id,
447
+ connected_app_secret_id=self.connected_app_secret_id,
448
+ connected_app_secret_value=self.connected_app_secret_value,
449
+ username=self.username,
450
+ site_name=self.site_name,
451
+ server_name=self.server_name,
452
+ )
453
+
454
+
455
+ class TableauCacheableAssetsDefinition(CacheableAssetsDefinition):
456
+ def __init__(self, workspace: BaseTableauWorkspace, translator: Type[DagsterTableauTranslator]):
457
+ self._workspace = workspace
458
+ self._translator_cls = translator
459
+ super().__init__(unique_id=self._workspace.site_name)
460
+
461
+ def compute_cacheable_data(self) -> Sequence[AssetsDefinitionCacheableData]:
462
+ workspace_data: TableauWorkspaceData = self._workspace.fetch_tableau_workspace_data()
463
+ return [
464
+ AssetsDefinitionCacheableData(extra_metadata=data.to_cached_data())
465
+ for data in [
466
+ *workspace_data.workbooks_by_id.values(),
467
+ *workspace_data.sheets_by_id.values(),
468
+ *workspace_data.dashboards_by_id.values(),
469
+ *workspace_data.data_sources_by_id.values(),
470
+ ]
471
+ ]
472
+
473
+ def build_definitions(
474
+ self, data: Sequence[AssetsDefinitionCacheableData]
475
+ ) -> Sequence[AssetsDefinition]:
476
+ workspace_data = TableauWorkspaceData.from_content_data(
477
+ self._workspace.site_name,
478
+ [
479
+ TableauContentData.from_cached_data(check.not_none(entry.extra_metadata))
480
+ for entry in data
481
+ ],
482
+ )
483
+
484
+ translator = self._translator_cls(context=workspace_data)
485
+
486
+ external_assets = external_assets_from_specs(
487
+ [
488
+ translator.get_asset_spec(content)
489
+ for content in workspace_data.data_sources_by_id.values()
490
+ ]
491
+ )
492
+
493
+ tableau_assets = self._build_tableau_assets_from_workspace_data(
494
+ workspace_data=workspace_data,
495
+ translator=translator,
496
+ )
497
+
498
+ return external_assets + tableau_assets
499
+
500
+ def _build_tableau_assets_from_workspace_data(
501
+ self,
502
+ workspace_data: TableauWorkspaceData,
503
+ translator: DagsterTableauTranslator,
504
+ ) -> List[AssetsDefinition]:
505
+ @multi_asset(
506
+ name=f"tableau_sync_site_{self._workspace.site_name.replace('-', '_')}",
507
+ compute_kind="tableau",
508
+ can_subset=False,
509
+ specs=[
510
+ translator.get_asset_spec(content)
511
+ for content in [
512
+ *workspace_data.sheets_by_id.values(),
513
+ *workspace_data.dashboards_by_id.values(),
514
+ ]
515
+ ],
516
+ resource_defs={"tableau": self._workspace.get_resource_definition()},
517
+ )
518
+ def _assets(tableau: BaseTableauWorkspace):
519
+ with tableau.get_client() as client:
520
+ for view_id, view_content_data in [
521
+ *workspace_data.sheets_by_id.items(),
522
+ *workspace_data.dashboards_by_id.items(),
523
+ ]:
524
+ data = client.get_view(view_id)["view"]
525
+ if view_content_data.content_type == TableauContentType.SHEET:
526
+ asset_key = translator.get_sheet_asset_key(view_content_data)
527
+ elif view_content_data.content_type == TableauContentType.DASHBOARD:
528
+ asset_key = translator.get_dashboard_asset_key(view_content_data)
529
+ else:
530
+ check.assert_never(view_content_data.content_type)
531
+ yield ObserveResult(
532
+ asset_key=asset_key,
533
+ metadata={
534
+ "workbook_id": data["workbook"]["id"],
535
+ "owner_id": data["owner"]["id"],
536
+ "name": data["name"],
537
+ "contentUrl": data["contentUrl"],
538
+ "createdAt": data["createdAt"],
539
+ "updatedAt": data["updatedAt"],
540
+ },
541
+ )
542
+
543
+ return [_assets]
@@ -0,0 +1,173 @@
1
+ import re
2
+ from enum import Enum
3
+ from typing import Any, Mapping, Sequence
4
+
5
+ from dagster import _check as check
6
+ from dagster._core.definitions.asset_key import AssetKey
7
+ from dagster._core.definitions.asset_spec import AssetSpec
8
+ from dagster._record import record
9
+
10
+ TABLEAU_PREFIX = "tableau/"
11
+
12
+
13
+ def _clean_asset_name(name: str) -> str:
14
+ """Cleans an input to be a valid Dagster asset name."""
15
+ return re.sub(r"[^a-z0-9A-Z.]+", "_", name).lower()
16
+
17
+
18
+ class TableauContentType(Enum):
19
+ """Enum representing each object in Tableau's ontology."""
20
+
21
+ WORKBOOK = "workbook"
22
+ SHEET = "sheet"
23
+ DASHBOARD = "dashboard"
24
+ DATA_SOURCE = "data_source"
25
+
26
+
27
+ @record
28
+ class TableauContentData:
29
+ """A record representing a piece of content in Tableau.
30
+ Includes the content's type and data as returned from the API.
31
+ """
32
+
33
+ content_type: TableauContentType
34
+ properties: Mapping[str, Any]
35
+
36
+ def to_cached_data(self) -> Mapping[str, Any]:
37
+ return {"content_type": self.content_type.value, "properties": self.properties}
38
+
39
+ @classmethod
40
+ def from_cached_data(cls, data: Mapping[Any, Any]) -> "TableauContentData":
41
+ return cls(
42
+ content_type=TableauContentType(data["content_type"]),
43
+ properties=data["properties"],
44
+ )
45
+
46
+
47
+ @record
48
+ class TableauWorkspaceData:
49
+ """A record representing all content in a Tableau workspace.
50
+ Provided as context for the translator so that it can resolve dependencies between content.
51
+ """
52
+
53
+ site_name: str
54
+ workbooks_by_id: Mapping[str, TableauContentData]
55
+ sheets_by_id: Mapping[str, TableauContentData]
56
+ dashboards_by_id: Mapping[str, TableauContentData]
57
+ data_sources_by_id: Mapping[str, TableauContentData]
58
+
59
+ @classmethod
60
+ def from_content_data(
61
+ cls, site_name: str, content_data: Sequence[TableauContentData]
62
+ ) -> "TableauWorkspaceData":
63
+ return cls(
64
+ site_name=site_name,
65
+ workbooks_by_id={
66
+ workbook.properties["luid"]: workbook
67
+ for workbook in content_data
68
+ if workbook.content_type == TableauContentType.WORKBOOK
69
+ },
70
+ sheets_by_id={
71
+ sheet.properties["luid"]: sheet
72
+ for sheet in content_data
73
+ if sheet.content_type == TableauContentType.SHEET
74
+ },
75
+ dashboards_by_id={
76
+ dashboard.properties["luid"]: dashboard
77
+ for dashboard in content_data
78
+ if dashboard.content_type == TableauContentType.DASHBOARD
79
+ },
80
+ data_sources_by_id={
81
+ data_source.properties["luid"]: data_source
82
+ for data_source in content_data
83
+ if data_source.content_type == TableauContentType.DATA_SOURCE
84
+ },
85
+ )
86
+
87
+
88
+ class DagsterTableauTranslator:
89
+ """Translator class which converts raw response data from the Tableau API into AssetSpecs.
90
+ Subclass this class to implement custom logic for each type of Tableau content.
91
+ """
92
+
93
+ def __init__(self, context: TableauWorkspaceData):
94
+ self._context = context
95
+
96
+ @property
97
+ def workspace_data(self) -> TableauWorkspaceData:
98
+ return self._context
99
+
100
+ def get_asset_spec(self, data: TableauContentData) -> AssetSpec:
101
+ if data.content_type == TableauContentType.SHEET:
102
+ return self.get_sheet_spec(data)
103
+ elif data.content_type == TableauContentType.DASHBOARD:
104
+ return self.get_dashboard_spec(data)
105
+ elif data.content_type == TableauContentType.DATA_SOURCE:
106
+ return self.get_data_source_spec(data)
107
+ else:
108
+ check.assert_never(data.content_type)
109
+
110
+ def get_sheet_asset_key(self, data: TableauContentData) -> AssetKey:
111
+ workbook_id = data.properties["workbook"]["luid"]
112
+ workbook_data = self.workspace_data.workbooks_by_id[workbook_id]
113
+ return AssetKey(
114
+ [
115
+ _clean_asset_name(workbook_data.properties["name"]),
116
+ "sheet",
117
+ _clean_asset_name(data.properties["name"]),
118
+ ]
119
+ )
120
+
121
+ def get_sheet_spec(self, data: TableauContentData) -> AssetSpec:
122
+ sheet_embedded_data_sources = data.properties.get("parentEmbeddedDatasources", [])
123
+ data_source_ids = {
124
+ published_data_source["luid"]
125
+ for embedded_data_source in sheet_embedded_data_sources
126
+ for published_data_source in embedded_data_source.get("parentPublishedDatasources", [])
127
+ }
128
+
129
+ data_source_keys = [
130
+ self.get_data_source_asset_key(self.workspace_data.data_sources_by_id[data_source_id])
131
+ for data_source_id in data_source_ids
132
+ ]
133
+
134
+ return AssetSpec(
135
+ key=self.get_sheet_asset_key(data),
136
+ deps=data_source_keys if data_source_keys else None,
137
+ tags={"dagster/storage_kind": "tableau"},
138
+ )
139
+
140
+ def get_dashboard_asset_key(self, data: TableauContentData) -> AssetKey:
141
+ workbook_id = data.properties["workbook"]["luid"]
142
+ workbook_data = self.workspace_data.workbooks_by_id[workbook_id]
143
+ return AssetKey(
144
+ [
145
+ _clean_asset_name(workbook_data.properties["name"]),
146
+ "dashboard",
147
+ _clean_asset_name(data.properties["name"]),
148
+ ]
149
+ )
150
+
151
+ def get_dashboard_spec(self, data: TableauContentData) -> AssetSpec:
152
+ dashboard_upstream_sheets = data.properties.get("sheets", [])
153
+ sheet_ids = {sheet["luid"] for sheet in dashboard_upstream_sheets if sheet["luid"]}
154
+
155
+ sheet_keys = [
156
+ self.get_sheet_asset_key(self.workspace_data.sheets_by_id[sheet_id])
157
+ for sheet_id in sheet_ids
158
+ ]
159
+
160
+ return AssetSpec(
161
+ key=self.get_dashboard_asset_key(data),
162
+ deps=sheet_keys if sheet_keys else None,
163
+ tags={"dagster/storage_kind": "tableau"},
164
+ )
165
+
166
+ def get_data_source_asset_key(self, data: TableauContentData) -> AssetKey:
167
+ return AssetKey([_clean_asset_name(data.properties["name"])])
168
+
169
+ def get_data_source_spec(self, data: TableauContentData) -> AssetSpec:
170
+ return AssetSpec(
171
+ key=self.get_data_source_asset_key(data),
172
+ tags={"dagster/storage_kind": "tableau"},
173
+ )
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.1
2
+ Name: dagster_tableau
3
+ Version: 0.0.1
4
+ Summary: Build assets representing Tableau workbooks and sheets.
5
+ Home-page: https://github.com/dagster-io/dagster/tree/master/python_modules/libraries/dagster-tableau
6
+ Author: Dagster Labs
7
+ Author-email: hello@dagsterlabs.com
8
+ License: Apache-2.0
9
+ Classifier: Programming Language :: Python :: 3.8
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Requires-Python: >=3.8,<3.13
17
+ License-File: LICENSE
18
+ Requires-Dist: dagster==0.0.1
19
+ Requires-Dist: pyjwt[crypto]
20
+ Requires-Dist: requests
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ setup.cfg
5
+ setup.py
6
+ dagster_tableau/__init__.py
7
+ dagster_tableau/py.typed
8
+ dagster_tableau/resources.py
9
+ dagster_tableau/translator.py
10
+ dagster_tableau.egg-info/PKG-INFO
11
+ dagster_tableau.egg-info/SOURCES.txt
12
+ dagster_tableau.egg-info/dependency_links.txt
13
+ dagster_tableau.egg-info/not-zip-safe
14
+ dagster_tableau.egg-info/requires.txt
15
+ dagster_tableau.egg-info/top_level.txt
@@ -0,0 +1,3 @@
1
+ dagster==0.0.1
2
+ pyjwt[crypto]
3
+ requests
@@ -0,0 +1 @@
1
+ dagster_tableau
@@ -0,0 +1,14 @@
1
+ [metadata]
2
+ license_files = LICENSE
3
+
4
+ [check-manifest]
5
+ ignore =
6
+ .coveragerc
7
+ tox.ini
8
+ pytest.ini
9
+ dagster_tableau_tests/**
10
+
11
+ [egg_info]
12
+ tag_build =
13
+ tag_date = 0
14
+
@@ -0,0 +1,46 @@
1
+ from setuptools import find_packages, setup
2
+
3
+
4
+ def get_version() -> str:
5
+ return "0.0.1"
6
+ # Uncomment when ready to publish
7
+ # version: Dict[str, str] = {}
8
+ # with open(Path(__file__).parent / "dagster_tableau/version.py", encoding="utf8") as fp:
9
+ # exec(fp.read(), version)
10
+
11
+ # return version["__version__"]
12
+
13
+
14
+ ver = get_version()
15
+ # dont pin dev installs to avoid pip dep resolver issues
16
+ pin = "" if ver == "1!0+dev" else f"=={ver}"
17
+ setup(
18
+ name="dagster_tableau",
19
+ version=get_version(),
20
+ author="Dagster Labs",
21
+ author_email="hello@dagsterlabs.com",
22
+ license="Apache-2.0",
23
+ description="Build assets representing Tableau workbooks and sheets.",
24
+ url=(
25
+ "https://github.com/dagster-io/dagster/tree/master/python_modules/libraries/"
26
+ "dagster-tableau"
27
+ ),
28
+ classifiers=[
29
+ "Programming Language :: Python :: 3.8",
30
+ "Programming Language :: Python :: 3.9",
31
+ "Programming Language :: Python :: 3.10",
32
+ "Programming Language :: Python :: 3.11",
33
+ "Programming Language :: Python :: 3.12",
34
+ "License :: OSI Approved :: Apache Software License",
35
+ "Operating System :: OS Independent",
36
+ ],
37
+ packages=find_packages(exclude=["dagster_tableau_tests*"]),
38
+ install_requires=[
39
+ f"dagster{pin}",
40
+ "pyjwt[crypto]",
41
+ "requests",
42
+ ],
43
+ include_package_data=True,
44
+ python_requires=">=3.8,<3.13",
45
+ zip_safe=False,
46
+ )