Repository navigation
Expand file tree
/
Copy pathproject.py
More file actions
342 lines (250 loc) · 9.33 KB
/
Copy pathproject.py
File metadata and controls
342 lines (250 loc) · 9.33 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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Iterator, List, Literal, Optional, TypedDict, Union, overload
import gql
import graphql.language as l
from latch_sdk_gql.execute import execute
from latch_sdk_gql.utils import _GqlJsonValue, _json_value, _name_node, _parse_selection
from typing_extensions import TypeAlias
from latch.registry.table import Table
from latch.utils import NotFoundError, current_workspace
class _CatalogExperimentNode(TypedDict):
id: str
displayName: str
@dataclass
class _Cache:
display_name: Optional[str] = None
tables: Optional[List[Table]] = None
class ProjectNotFoundError(NotFoundError): ...
@dataclass(frozen=True)
class Project:
"""Registry project (folder containing :class:`tables <latch.registry.table.Table>`).
:meth:`~latch.account.Account.list_registry_projects` is the typical way to get a :class:`Project`.
"""
_cache: _Cache = field(
default_factory=lambda: _Cache(),
init=False,
repr=False,
hash=False,
compare=False,
)
id: str
"""Unique identifier."""
def load(self) -> None:
"""(Re-)populate this project instance's cache.
Future calls to most getters will return immediately without making a network request.
Always makes a network request.
"""
data = execute(
document=gql.gql("""
query ProjectQuery($id: BigInt!) {
catalogProject(id: $id) {
id
displayName
catalogExperimentsByProjectId (
condition: {
projectId: $id
removed: false
}
) {
nodes {
id
displayName
}
}
}
}
"""),
variables={"id": self.id},
)["catalogProject"]
if data is None:
raise ProjectNotFoundError(
f"project does not exist or you lack permissions: id={self.id}"
)
self._cache.display_name = data["displayName"]
self._cache.tables = []
experiments: List[_CatalogExperimentNode] = data[
"catalogExperimentsByProjectId"
]["nodes"]
for x in experiments:
cur = Table(x["id"])
cur._cache.display_name = x["displayName"]
self._cache.tables.append(cur)
# get_display_name
@overload
def get_display_name(self, *, load_if_missing: Literal[True] = True) -> str: ...
@overload
def get_display_name(self, *, load_if_missing: bool) -> Optional[str]: ...
def get_display_name(self, *, load_if_missing: bool = True) -> Optional[str]:
"""Get the display name of this project.
This is an opaque string that can contain any valid Unicode data.
Display names are *not unique* and *must never be used as identifiers*.
Use :attr:`id` instead.
Args:
load_if_missing:
If true, :meth:`load` the display name if not in cache.
If false, return `None` if not in cache.
Returns:
Display name.
"""
if self._cache.display_name is None and load_if_missing:
self.load()
return self._cache.display_name
# list_tables
@overload
def list_tables(self, *, load_if_missing: Literal[True] = True) -> List[Table]: ...
@overload
def list_tables(self, *, load_if_missing: bool) -> Optional[List[Table]]: ...
def list_tables(self, *, load_if_missing: bool = True) -> Optional[List[Table]]:
"""List Registry tables contained in this project.
Args:
load_if_missing:
If true, :meth:`load` the table list if not in cache.
If false, return `None` if not in cache.
Returns:
Tables in this project.
"""
if self._cache.tables is None and load_if_missing:
self.load()
return self._cache.tables
@contextmanager
def update(self, *, reload_on_commit: bool = True) -> Iterator["ProjectUpdate"]:
"""Start an update transaction.
The transaction will commit when the context manager closes unless an error occurs.
No changes will occur until the transaction commits.
The transaction can be cancelled by running :meth:`ProjectUpdate.clear`
before closing the context manager.
Args:
reload_on_commit:
If true, :meth:`load` this project after the transaction commits.
Returns:
Context manager for the new transaction.
"""
upd = ProjectUpdate(self)
yield upd
upd.commit()
if reload_on_commit:
self.load()
def __repr__(self):
display_name = self.get_display_name(load_if_missing=False)
if display_name is not None:
return f"Project(id={self.id}, display_name={display_name})"
return f"Project(id={self.id})"
def __str__(self):
return repr(self)
@dataclass(frozen=True)
class _ProjectTablesUpsertData:
display_name: str
@dataclass(frozen=True)
class _ProjectTablesDeleteData:
id: str
_ProjectTablesMutationData: TypeAlias = Union[
_ProjectTablesUpsertData, _ProjectTablesDeleteData
]
@dataclass(frozen=True)
class ProjectUpdate:
_table_mutations: List[_ProjectTablesMutationData] = field(
default_factory=list,
init=False,
repr=False,
hash=False,
compare=False,
)
project: Project
# upsert table
def upsert_table(self, display_name: str):
"""Creates a table.
Not idempotent. Two calls with the same args will create two tables.
Args:
display_name: The display name of the new table.
"""
self._table_mutations.append(_ProjectTablesUpsertData(display_name))
def _add_table_upserts_selection(
self, upserts: List[_ProjectTablesUpsertData], mutations: List[l.SelectionNode]
):
if len(upserts) == 0:
return
display_names: _GqlJsonValue = [x.display_name for x in upserts]
res = _parse_selection("""
catalogMultiCreateExperiments(input: {}) {
clientMutationId
}
""")
assert isinstance(res, l.FieldNode)
args = l.ArgumentNode()
args.name = _name_node("input")
args.value = _json_value({
"argProjectId": self.project.id,
"argDisplayNames": display_names,
})
res.alias = _name_node(f"upd{len(mutations)}")
res.arguments = tuple([args])
mutations.append(res)
# delete table
def delete_table(self, id: str):
"""Deletes a table.
Args:
id: The ID of the target table.
"""
self._table_mutations.append(_ProjectTablesDeleteData(id))
def _add_table_deletes_selection(
self, deletes: List[_ProjectTablesDeleteData], mutations: List[l.SelectionNode]
):
if len(deletes) == 0:
return
ids: _GqlJsonValue = [x.id for x in deletes]
res = _parse_selection("""
catalogMultiDeleteExperiments(input: {}) {
clientMutationId
}
""")
assert isinstance(res, l.FieldNode)
args = l.ArgumentNode()
args.name = _name_node("input")
args.value = _json_value({
"argIds": ids,
})
res.alias = _name_node(f"upd{len(mutations)}")
res.arguments = tuple([args])
mutations.append(res)
# transaction
def commit(self) -> None:
"""Commit this project update transaction.
May be called multiple times.
All pending updates are committed with one network request.
Atomic. The entire transaction either commits or fails with an exception.
"""
mutations: List[l.SelectionNode] = []
if len(self._table_mutations) == 0:
return
def _add_table_mutations_selection(cur):
if isinstance(cur[0], _ProjectTablesUpsertData):
self._add_table_upserts_selection(cur, mutations)
if isinstance(cur[0], _ProjectTablesDeleteData):
self._add_table_deletes_selection(cur, mutations)
cur = [self._table_mutations[0]]
for mut in self._table_mutations[1:]:
if isinstance(mut, type(cur[0])):
cur.append(mut)
continue
_add_table_mutations_selection(cur)
cur = [mut]
_add_table_mutations_selection(cur)
sel_set = l.SelectionSetNode()
sel_set.selections = tuple(mutations)
doc = l.parse("""
mutation ProjectUpdate {
placeholder
}
""")
assert len(doc.definitions) == 1
mut = doc.definitions[0]
assert isinstance(mut, l.OperationDefinitionNode)
mut.selection_set = sel_set
execute(doc)
self.clear()
def clear(self):
"""Remove pending updates.
May be called to cancel any pending updates that have not been committed.
"""
self._table_mutations.clear()