-
Notifications
You must be signed in to change notification settings - Fork 221
Expand file tree
/
Copy pathprotocol.py
More file actions
320 lines (276 loc) · 10.4 KB
/
protocol.py
File metadata and controls
320 lines (276 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#
# Copyright (C) 2021 The Delta Lake Project Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from dataclasses import dataclass, field
from json import loads
from pathlib import Path
from typing import ClassVar, Dict, IO, Optional, Sequence, Union
import fsspec
@dataclass(frozen=True)
class DeltaSharingProfile:
CURRENT: ClassVar[int] = 2
share_credentials_version: int
endpoint: str
bearer_token: Optional[str] = None
expiration_time: Optional[str] = None
type: Optional[str] = None
token_endpoint: Optional[str] = None
client_id: Optional[str] = None
client_secret: Optional[str] = None
username: Optional[str] = None
password: Optional[str] = None
scope: Optional[str] = None
def __post_init__(self):
if self.share_credentials_version > DeltaSharingProfile.CURRENT:
raise ValueError(
"'shareCredentialsVersion' in the profile is "
f"{self.share_credentials_version} which is too new. "
f"The current release supports version {DeltaSharingProfile.CURRENT} and below. "
"Please upgrade to a newer release."
)
@staticmethod
def read_from_file(profile: Union[str, IO, Path]) -> "DeltaSharingProfile":
if isinstance(profile, str):
infile = fsspec.open(profile).open()
elif isinstance(profile, Path):
infile = fsspec.open(profile.as_uri()).open()
else:
infile = profile
try:
return DeltaSharingProfile.from_json(infile.read())
finally:
infile.close()
@staticmethod
def from_json(json) -> "DeltaSharingProfile":
if isinstance(json, (str, bytes, bytearray)):
json = loads(json)
share_credentials_version = int(json["shareCredentialsVersion"])
endpoint = json["endpoint"]
if endpoint is not None and endpoint.endswith("/"):
endpoint = endpoint[:-1]
if share_credentials_version == 1:
return DeltaSharingProfile(
share_credentials_version=share_credentials_version,
endpoint=endpoint,
bearer_token=json["bearerToken"],
expiration_time=json.get("expirationTime"),
)
elif share_credentials_version == 2:
type = json["type"]
if type == "oauth_client_credentials":
token_endpoint = json["tokenEndpoint"]
if token_endpoint is not None and token_endpoint.endswith("/"):
token_endpoint = token_endpoint[:-1]
return DeltaSharingProfile(
share_credentials_version=share_credentials_version,
type=type,
endpoint=endpoint,
token_endpoint=token_endpoint,
client_id=json["clientId"],
client_secret=json["clientSecret"],
scope=json.get("scope"),
)
elif type == "bearer_token":
return DeltaSharingProfile(
share_credentials_version=share_credentials_version,
type=type,
endpoint=endpoint,
bearer_token=json["bearerToken"],
expiration_time=json.get("expirationTime")
)
elif type == "oidc_managed_identity":
return DeltaSharingProfile(
share_credentials_version=share_credentials_version,
type=type,
endpoint=endpoint
)
elif type == "basic":
return DeltaSharingProfile(
share_credentials_version=share_credentials_version,
type=type,
endpoint=endpoint,
username=json["username"],
password=json["password"],
)
else:
raise ValueError(
f"The current release does not supports {type} type. "
"Please check type.")
else:
raise ValueError(
"'shareCredentialsVersion' in the profile is "
f"{share_credentials_version} which is too new. "
f"The current release supports version {DeltaSharingProfile.CURRENT} and below. "
"Please upgrade to a newer release."
)
@dataclass(frozen=True)
class Share:
name: str
@staticmethod
def from_json(json) -> "Share":
if isinstance(json, (str, bytes, bytearray)):
json = loads(json)
return Share(name=json["name"])
@dataclass(frozen=True)
class Schema:
name: str
share: str
@staticmethod
def from_json(json) -> "Schema":
if isinstance(json, (str, bytes, bytearray)):
json = loads(json)
return Schema(name=json["name"], share=json["share"])
@dataclass(frozen=True)
class Table:
name: str
share: str
schema: str
@staticmethod
def from_json(json) -> "Table":
if isinstance(json, (str, bytes, bytearray)):
json = loads(json)
return Table(name=json["name"], share=json["share"],
schema=json["schema"])
@dataclass(frozen=True)
class Protocol:
CURRENT: ClassVar[int] = 1
min_reader_version: int
def __post_init__(self):
if self.min_reader_version > Protocol.CURRENT:
raise ValueError(
f"The table requires a newer version {self.min_reader_version} to read. "
f"But the current release supports version {Protocol.CURRENT} and below. "
f"Please upgrade to a newer release."
)
@staticmethod
def from_json(json) -> "Protocol":
if isinstance(json, (str, bytes, bytearray)):
json = loads(json)
return Protocol(min_reader_version=int(json["minReaderVersion"]))
@dataclass(frozen=True)
class Format:
provider: str = "parquet"
options: Dict[str, str] = field(default_factory=dict)
@staticmethod
def from_json(json) -> "Format":
if isinstance(json, (str, bytes, bytearray)):
json = loads(json)
return Format(provider=json.get("provider", "parquet"), options=json.get("options", {}))
@dataclass(frozen=True)
class Metadata:
id: Optional[str] = None
name: Optional[str] = None
description: Optional[str] = None
format: Format = field(default_factory=Format)
schema_string: Optional[str] = None
configuration: Dict[str, str] = field(default_factory=dict)
partition_columns: Sequence[str] = field(default_factory=list)
version: Optional[int] = None
size: Optional[int] = None
num_files: Optional[int] = None
@staticmethod
def from_json(json) -> "Metadata":
if isinstance(json, (str, bytes, bytearray)):
json = loads(json)
if "configuration" in json:
configuration = json["configuration"]
else:
configuration = {}
return Metadata(
id=json["id"],
name=json.get("name", None),
description=json.get("description", None),
format=Format.from_json(json["format"]),
schema_string=json["schemaString"],
configuration=configuration,
partition_columns=json["partitionColumns"],
version=json.get("version", None),
size=json.get("size", None),
num_files=json.get("numFiles", None)
)
@dataclass(frozen=True)
class FileAction:
url: str
id: str
partition_values: Dict[str, str]
size: int
timestamp: Optional[int] = None
version: Optional[int] = None
def get_change_type_col_value(self) -> str:
raise ValueError(f"_change_type not supported for {self.url}")
@staticmethod
def from_json(action_json) -> "FileAction":
if "add" in action_json:
return AddFile.from_json(action_json["add"])
elif "cdf" in action_json:
return AddCdcFile.from_json(action_json["cdf"])
elif "remove" in action_json:
return RemoveFile.from_json(action_json["remove"])
else:
return None
@dataclass(frozen=True)
class AddFile(FileAction):
stats: Optional[str] = None
@staticmethod
def from_json(json) -> "AddFile":
if isinstance(json, (str, bytes, bytearray)):
json = loads(json)
return AddFile(
url=json["url"],
id=json["id"],
partition_values=json["partitionValues"],
size=int(json["size"]),
stats=json.get("stats", None),
timestamp=json.get("timestamp", None),
version=json.get("version", None),
)
def get_change_type_col_value(self) -> str:
return "insert"
@dataclass(frozen=True)
class AddCdcFile(FileAction):
@staticmethod
def from_json(json) -> "AddCdcFile":
if isinstance(json, (str, bytes, bytearray)):
json = loads(json)
return AddCdcFile(
url=json["url"],
id=json["id"],
partition_values=json["partitionValues"],
size=int(json["size"]),
timestamp=json["timestamp"],
version=json["version"],
)
@dataclass(frozen=True)
class RemoveFile(FileAction):
@staticmethod
def from_json(json) -> "RemoveFile":
if isinstance(json, (str, bytes, bytearray)):
json = loads(json)
return RemoveFile(
url=json["url"],
id=json["id"],
partition_values=json["partitionValues"],
size=int(json["size"]),
timestamp=json.get("timestamp", None),
version=json.get("version", None),
)
def get_change_type_col_value(self) -> str:
return "delete"
@dataclass(frozen=True)
class CdfOptions:
starting_version: Optional[int] = None
ending_version: Optional[int] = None
starting_timestamp: Optional[str] = None
ending_timestamp: Optional[str] = None