lamindb_setup 0.77.2__py2.py3-none-any.whl → 0.77.4__py2.py3-none-any.whl
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.
- lamindb_setup/__init__.py +1 -1
- lamindb_setup/_cache.py +34 -34
- lamindb_setup/_check.py +7 -7
- lamindb_setup/_check_setup.py +79 -79
- lamindb_setup/_close.py +35 -35
- lamindb_setup/_connect_instance.py +444 -444
- lamindb_setup/_delete.py +9 -5
- lamindb_setup/_django.py +41 -41
- lamindb_setup/_entry_points.py +22 -22
- lamindb_setup/_exportdb.py +68 -68
- lamindb_setup/_importdb.py +50 -50
- lamindb_setup/_init_instance.py +374 -374
- lamindb_setup/_migrate.py +239 -239
- lamindb_setup/_register_instance.py +36 -36
- lamindb_setup/_schema.py +27 -27
- lamindb_setup/_schema_metadata.py +411 -411
- lamindb_setup/_set_managed_storage.py +55 -55
- lamindb_setup/_setup_user.py +137 -137
- lamindb_setup/_silence_loggers.py +44 -44
- lamindb_setup/core/__init__.py +21 -21
- lamindb_setup/core/_aws_credentials.py +151 -151
- lamindb_setup/core/_aws_storage.py +48 -48
- lamindb_setup/core/_deprecated.py +55 -55
- lamindb_setup/core/_docs.py +14 -14
- lamindb_setup/core/_hub_core.py +590 -590
- lamindb_setup/core/_hub_crud.py +211 -211
- lamindb_setup/core/_hub_utils.py +109 -109
- lamindb_setup/core/_private_django_api.py +88 -88
- lamindb_setup/core/_settings.py +138 -138
- lamindb_setup/core/_settings_instance.py +467 -467
- lamindb_setup/core/_settings_load.py +105 -105
- lamindb_setup/core/_settings_save.py +81 -81
- lamindb_setup/core/_settings_storage.py +405 -393
- lamindb_setup/core/_settings_store.py +75 -75
- lamindb_setup/core/_settings_user.py +53 -53
- lamindb_setup/core/_setup_bionty_sources.py +101 -101
- lamindb_setup/core/cloud_sqlite_locker.py +232 -232
- lamindb_setup/core/django.py +114 -114
- lamindb_setup/core/exceptions.py +12 -12
- lamindb_setup/core/hashing.py +114 -114
- lamindb_setup/core/types.py +19 -19
- lamindb_setup/core/upath.py +779 -779
- {lamindb_setup-0.77.2.dist-info → lamindb_setup-0.77.4.dist-info}/METADATA +1 -1
- lamindb_setup-0.77.4.dist-info/RECORD +47 -0
- {lamindb_setup-0.77.2.dist-info → lamindb_setup-0.77.4.dist-info}/WHEEL +1 -1
- lamindb_setup-0.77.2.dist-info/RECORD +0 -47
- {lamindb_setup-0.77.2.dist-info → lamindb_setup-0.77.4.dist-info}/LICENSE +0 -0
lamindb_setup/core/_hub_core.py
CHANGED
|
@@ -1,590 +1,590 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
import json
|
|
4
|
-
import os
|
|
5
|
-
import uuid
|
|
6
|
-
from importlib import metadata
|
|
7
|
-
from typing import TYPE_CHECKING, Literal
|
|
8
|
-
from uuid import UUID
|
|
9
|
-
|
|
10
|
-
from lamin_utils import logger
|
|
11
|
-
from postgrest.exceptions import APIError
|
|
12
|
-
|
|
13
|
-
from ._hub_client import (
|
|
14
|
-
call_with_fallback,
|
|
15
|
-
call_with_fallback_auth,
|
|
16
|
-
connect_hub,
|
|
17
|
-
)
|
|
18
|
-
from ._hub_crud import (
|
|
19
|
-
_delete_instance_record,
|
|
20
|
-
select_account_by_handle,
|
|
21
|
-
select_db_user_by_instance,
|
|
22
|
-
select_default_storage_by_instance_id,
|
|
23
|
-
select_instance_by_id_with_storage,
|
|
24
|
-
select_instance_by_name,
|
|
25
|
-
select_instance_by_owner_name,
|
|
26
|
-
)
|
|
27
|
-
from ._hub_crud import update_instance as _update_instance_record
|
|
28
|
-
from ._hub_utils import (
|
|
29
|
-
LaminDsn,
|
|
30
|
-
LaminDsnModel,
|
|
31
|
-
)
|
|
32
|
-
from ._settings import settings
|
|
33
|
-
from ._settings_storage import StorageSettings, base62
|
|
34
|
-
|
|
35
|
-
if TYPE_CHECKING:
|
|
36
|
-
from supabase import Client # type: ignore
|
|
37
|
-
|
|
38
|
-
from ._settings_instance import InstanceSettings
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
def delete_storage_record(
|
|
42
|
-
storage_uuid: UUID,
|
|
43
|
-
) -> None:
|
|
44
|
-
return call_with_fallback_auth(
|
|
45
|
-
_delete_storage_record,
|
|
46
|
-
storage_uuid=storage_uuid,
|
|
47
|
-
)
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
def _delete_storage_record(storage_uuid: UUID, client: Client) -> None:
|
|
51
|
-
if storage_uuid is None:
|
|
52
|
-
return None
|
|
53
|
-
response = client.table("storage").delete().eq("id", storage_uuid.hex).execute()
|
|
54
|
-
if response.data:
|
|
55
|
-
logger.important(f"deleted storage record on hub {storage_uuid.hex}")
|
|
56
|
-
else:
|
|
57
|
-
raise PermissionError(
|
|
58
|
-
f"Deleting of storage with {storage_uuid.hex} was not successful. Probably, you"
|
|
59
|
-
" don't have sufficient permissions."
|
|
60
|
-
)
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
def update_instance_record(instance_uuid: UUID, fields: dict) -> None:
|
|
64
|
-
return call_with_fallback_auth(
|
|
65
|
-
_update_instance_record, instance_id=instance_uuid.hex, instance_fields=fields
|
|
66
|
-
)
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
def get_storage_records_for_instance(
|
|
70
|
-
instance_id: UUID,
|
|
71
|
-
) -> list[dict[str, str | int]]:
|
|
72
|
-
return call_with_fallback_auth(
|
|
73
|
-
_get_storage_records_for_instance,
|
|
74
|
-
instance_id=instance_id,
|
|
75
|
-
)
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
def _get_storage_records_for_instance(
|
|
79
|
-
instance_id: UUID, client: Client
|
|
80
|
-
) -> list[dict[str, str | int]]:
|
|
81
|
-
response = (
|
|
82
|
-
client.table("storage").select("*").eq("instance_id", instance_id.hex).execute()
|
|
83
|
-
)
|
|
84
|
-
return response.data
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
def _select_storage(
|
|
88
|
-
ssettings: StorageSettings, update_uid: bool, client: Client
|
|
89
|
-
) -> bool:
|
|
90
|
-
root = ssettings.root_as_str
|
|
91
|
-
response = client.table("storage").select("*").eq("root", root).execute()
|
|
92
|
-
if not response.data:
|
|
93
|
-
return False
|
|
94
|
-
else:
|
|
95
|
-
existing_storage = response.data[0]
|
|
96
|
-
if existing_storage["instance_id"] is not None:
|
|
97
|
-
if ssettings._instance_id is not None:
|
|
98
|
-
# consider storage settings that are meant to be managed by an instance
|
|
99
|
-
if UUID(existing_storage["instance_id"]) != ssettings._instance_id:
|
|
100
|
-
# everything is alright if the instance_id matches
|
|
101
|
-
# we're probably just switching storage locations
|
|
102
|
-
# below can be turned into a warning and then delegate the error
|
|
103
|
-
# to a unique constraint violation below
|
|
104
|
-
raise ValueError(
|
|
105
|
-
f"Storage root {root} is already managed by instance {existing_storage['instance_id']}."
|
|
106
|
-
)
|
|
107
|
-
else:
|
|
108
|
-
# if the request is agnostic of the instance, that's alright,
|
|
109
|
-
# we'll update the instance_id with what's stored in the hub
|
|
110
|
-
ssettings._instance_id = UUID(existing_storage["instance_id"])
|
|
111
|
-
ssettings._uuid_ = UUID(existing_storage["id"])
|
|
112
|
-
if update_uid:
|
|
113
|
-
ssettings._uid = existing_storage["lnid"]
|
|
114
|
-
else:
|
|
115
|
-
assert ssettings._uid == existing_storage["lnid"]
|
|
116
|
-
return True
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
def init_storage(
|
|
120
|
-
ssettings: StorageSettings,
|
|
121
|
-
auto_populate_instance: bool = True,
|
|
122
|
-
) -> Literal["hub-record-retireved", "hub-record-created"]:
|
|
123
|
-
if settings.user.handle != "anonymous":
|
|
124
|
-
return call_with_fallback_auth(
|
|
125
|
-
_init_storage,
|
|
126
|
-
ssettings=ssettings,
|
|
127
|
-
auto_populate_instance=auto_populate_instance,
|
|
128
|
-
)
|
|
129
|
-
else:
|
|
130
|
-
storage_exists = call_with_fallback(
|
|
131
|
-
_select_storage, ssettings=ssettings, update_uid=True
|
|
132
|
-
)
|
|
133
|
-
if storage_exists:
|
|
134
|
-
return "hub-record-retireved"
|
|
135
|
-
else:
|
|
136
|
-
raise ValueError("Log in to create a storage location on the hub.")
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
def _init_storage(
|
|
140
|
-
ssettings: StorageSettings, auto_populate_instance: bool, client: Client
|
|
141
|
-
) -> Literal["hub-record-retireved", "hub-record-created"]:
|
|
142
|
-
from lamindb_setup import settings
|
|
143
|
-
|
|
144
|
-
# storage roots are always stored without the trailing slash in the SQL
|
|
145
|
-
# database
|
|
146
|
-
root = ssettings.root_as_str
|
|
147
|
-
if _select_storage(ssettings, update_uid=True, client=client):
|
|
148
|
-
return "hub-record-retireved"
|
|
149
|
-
if ssettings.type_is_cloud:
|
|
150
|
-
id = uuid.uuid5(uuid.NAMESPACE_URL, root)
|
|
151
|
-
else:
|
|
152
|
-
id = uuid.uuid4()
|
|
153
|
-
if (
|
|
154
|
-
ssettings._instance_id is None
|
|
155
|
-
and settings._instance_exists
|
|
156
|
-
and auto_populate_instance
|
|
157
|
-
):
|
|
158
|
-
logger.warning(
|
|
159
|
-
f"will manage storage location {ssettings.root_as_str} with instance {settings.instance.slug}"
|
|
160
|
-
)
|
|
161
|
-
ssettings._instance_id = settings.instance._id
|
|
162
|
-
instance_id_hex = (
|
|
163
|
-
ssettings._instance_id.hex
|
|
164
|
-
if (ssettings._instance_id is not None and auto_populate_instance)
|
|
165
|
-
else None
|
|
166
|
-
)
|
|
167
|
-
fields = {
|
|
168
|
-
"id": id.hex,
|
|
169
|
-
"lnid": ssettings.uid,
|
|
170
|
-
"created_by": settings.user._uuid.hex, # type: ignore
|
|
171
|
-
"root": root,
|
|
172
|
-
"region": ssettings.region,
|
|
173
|
-
"type": ssettings.type,
|
|
174
|
-
"instance_id": instance_id_hex,
|
|
175
|
-
# the empty string is important as we want the user flow to be through LaminHub
|
|
176
|
-
# if this errors with unique constraint error, the user has to update
|
|
177
|
-
# the description in LaminHub
|
|
178
|
-
"description": "",
|
|
179
|
-
}
|
|
180
|
-
# TODO: add error message for violated unique constraint
|
|
181
|
-
# on root & description
|
|
182
|
-
client.table("storage").upsert(fields).execute()
|
|
183
|
-
ssettings._uuid_ = id
|
|
184
|
-
return "hub-record-created"
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
def delete_instance(identifier: UUID | str, require_empty: bool = True) -> str | None:
|
|
188
|
-
return call_with_fallback_auth(
|
|
189
|
-
_delete_instance, identifier=identifier, require_empty=require_empty
|
|
190
|
-
)
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
def _delete_instance(
|
|
194
|
-
identifier: UUID | str, require_empty: bool, client: Client
|
|
195
|
-
) -> str | None:
|
|
196
|
-
"""Fully delete an instance in the hub.
|
|
197
|
-
|
|
198
|
-
This function deletes the relevant instance and storage records in the hub,
|
|
199
|
-
conditional on the emptiness of the storage location.
|
|
200
|
-
"""
|
|
201
|
-
from ._settings_storage import mark_storage_root
|
|
202
|
-
from .upath import check_storage_is_empty, create_path
|
|
203
|
-
|
|
204
|
-
# the "/" check is for backward compatibility with the old identifier format
|
|
205
|
-
if isinstance(identifier, UUID) or "/" not in identifier:
|
|
206
|
-
if isinstance(identifier, UUID):
|
|
207
|
-
instance_id_str = identifier.hex
|
|
208
|
-
else:
|
|
209
|
-
instance_id_str = identifier
|
|
210
|
-
instance_with_storage = select_instance_by_id_with_storage(
|
|
211
|
-
instance_id=instance_id_str, client=client
|
|
212
|
-
)
|
|
213
|
-
else:
|
|
214
|
-
owner, name = identifier.split("/")
|
|
215
|
-
instance_with_storage = select_instance_by_owner_name(
|
|
216
|
-
owner=owner, name=name, client=client
|
|
217
|
-
)
|
|
218
|
-
|
|
219
|
-
if instance_with_storage is None:
|
|
220
|
-
logger.important("not deleting instance from hub as instance not found there")
|
|
221
|
-
return "instance-not-found"
|
|
222
|
-
|
|
223
|
-
storage_records = _get_storage_records_for_instance(
|
|
224
|
-
UUID(instance_with_storage["id"]),
|
|
225
|
-
client,
|
|
226
|
-
)
|
|
227
|
-
if require_empty:
|
|
228
|
-
for storage_record in storage_records:
|
|
229
|
-
account_for_sqlite_file = (
|
|
230
|
-
instance_with_storage["db_scheme"] is None
|
|
231
|
-
and instance_with_storage["storage"]["root"] == storage_record["root"]
|
|
232
|
-
)
|
|
233
|
-
root_string = storage_record["root"]
|
|
234
|
-
# gate storage and instance deletion on empty storage location for
|
|
235
|
-
if client.auth.get_session() is not None:
|
|
236
|
-
access_token = client.auth.get_session().access_token
|
|
237
|
-
else:
|
|
238
|
-
access_token = None
|
|
239
|
-
root_path = create_path(root_string, access_token)
|
|
240
|
-
mark_storage_root(
|
|
241
|
-
root_path,
|
|
242
|
-
storage_record["lnid"], # type: ignore
|
|
243
|
-
) # address permission error
|
|
244
|
-
check_storage_is_empty(
|
|
245
|
-
root_path, account_for_sqlite_file=account_for_sqlite_file
|
|
246
|
-
)
|
|
247
|
-
_update_instance_record(instance_with_storage["id"], {"storage_id": None}, client)
|
|
248
|
-
# first delete the storage records because we will turn instance_id on
|
|
249
|
-
# storage into a FK soon
|
|
250
|
-
for storage_record in storage_records:
|
|
251
|
-
_delete_storage_record(UUID(storage_record["id"]), client) # type: ignore
|
|
252
|
-
_delete_instance_record(UUID(instance_with_storage["id"]), client)
|
|
253
|
-
return None
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
def delete_instance_record(
|
|
257
|
-
instance_id: UUID,
|
|
258
|
-
) -> None:
|
|
259
|
-
return call_with_fallback_auth(
|
|
260
|
-
_delete_instance_record,
|
|
261
|
-
instance_id=instance_id,
|
|
262
|
-
)
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
def init_instance(isettings: InstanceSettings) -> None:
|
|
266
|
-
return call_with_fallback_auth(_init_instance, isettings=isettings)
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
def _init_instance(isettings: InstanceSettings, client: Client) -> None:
|
|
270
|
-
from ._settings import settings
|
|
271
|
-
|
|
272
|
-
try:
|
|
273
|
-
lamindb_version = metadata.version("lamindb")
|
|
274
|
-
except metadata.PackageNotFoundError:
|
|
275
|
-
lamindb_version = None
|
|
276
|
-
fields = {
|
|
277
|
-
"id": isettings._id.hex,
|
|
278
|
-
"account_id": settings.user._uuid.hex, # type: ignore
|
|
279
|
-
"name": isettings.name,
|
|
280
|
-
"lnid": isettings.uid,
|
|
281
|
-
"schema_str": isettings._schema_str,
|
|
282
|
-
"lamindb_version": lamindb_version,
|
|
283
|
-
"public": False,
|
|
284
|
-
}
|
|
285
|
-
if isettings.dialect != "sqlite":
|
|
286
|
-
db_dsn = LaminDsnModel(db=isettings.db)
|
|
287
|
-
db_fields = {
|
|
288
|
-
"db_scheme": db_dsn.db.scheme,
|
|
289
|
-
"db_host": db_dsn.db.host,
|
|
290
|
-
"db_port": db_dsn.db.port,
|
|
291
|
-
"db_database": db_dsn.db.database,
|
|
292
|
-
}
|
|
293
|
-
fields.update(db_fields)
|
|
294
|
-
# I'd like the following to be an upsert, but this seems to violate RLS
|
|
295
|
-
# Similarly, if we don't specify `returning="minimal"`, we'll violate RLS
|
|
296
|
-
# we could make this idempotent by catching an error, but this seems dangerous
|
|
297
|
-
# as then init_instance is no longer idempotent
|
|
298
|
-
try:
|
|
299
|
-
client.table("instance").insert(fields, returning="minimal").execute()
|
|
300
|
-
except APIError:
|
|
301
|
-
logger.warning(
|
|
302
|
-
f"instance already existed at: https://lamin.ai/{isettings.owner}/{isettings.name}"
|
|
303
|
-
)
|
|
304
|
-
return None
|
|
305
|
-
client.table("storage").update(
|
|
306
|
-
{"instance_id": isettings._id.hex, "is_default": True}
|
|
307
|
-
).eq("id", isettings.storage._uuid.hex).execute() # type: ignore
|
|
308
|
-
logger.important(f"go to: https://lamin.ai/{isettings.owner}/{isettings.name}")
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
def connect_instance(
|
|
312
|
-
*,
|
|
313
|
-
owner: str, # account_handle
|
|
314
|
-
name: str, # instance_name
|
|
315
|
-
) -> tuple[dict, dict] | str:
|
|
316
|
-
from ._settings import settings
|
|
317
|
-
|
|
318
|
-
if settings.user.handle != "anonymous":
|
|
319
|
-
return call_with_fallback_auth(_connect_instance, owner=owner, name=name)
|
|
320
|
-
else:
|
|
321
|
-
return call_with_fallback(_connect_instance, owner=owner, name=name)
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
def _connect_instance(
|
|
325
|
-
*,
|
|
326
|
-
owner: str, # account_handle
|
|
327
|
-
name: str, # instance_name
|
|
328
|
-
client: Client,
|
|
329
|
-
) -> tuple[dict, dict] | str:
|
|
330
|
-
instance_account_storage = select_instance_by_owner_name(owner, name, client)
|
|
331
|
-
if instance_account_storage is None:
|
|
332
|
-
# try the via single requests, will take more time
|
|
333
|
-
account = select_account_by_handle(owner, client)
|
|
334
|
-
if account is None:
|
|
335
|
-
return "account-not-exists"
|
|
336
|
-
instance = select_instance_by_name(account["id"], name, client)
|
|
337
|
-
if instance is None:
|
|
338
|
-
return "instance-not-found"
|
|
339
|
-
# get default storage
|
|
340
|
-
storage = select_default_storage_by_instance_id(instance["id"], client)
|
|
341
|
-
if storage is None:
|
|
342
|
-
return "default-storage-does-not-exist-on-hub"
|
|
343
|
-
else:
|
|
344
|
-
account = instance_account_storage.pop("account")
|
|
345
|
-
storage = instance_account_storage.pop("storage")
|
|
346
|
-
instance = instance_account_storage
|
|
347
|
-
# check if is postgres instance
|
|
348
|
-
# this used to be a check for `instance["db"] is not None` in earlier versions
|
|
349
|
-
# removed this on 2022-10-25 and can remove from the hub probably for lamindb 1.0
|
|
350
|
-
if instance["db_scheme"] is not None:
|
|
351
|
-
db_user = select_db_user_by_instance(instance["id"], client)
|
|
352
|
-
if db_user is None:
|
|
353
|
-
name, password = "none", "none"
|
|
354
|
-
else:
|
|
355
|
-
name, password = db_user["db_user_name"], db_user["db_user_password"]
|
|
356
|
-
# construct dsn from instance and db_account fields
|
|
357
|
-
db_dsn = LaminDsn.build(
|
|
358
|
-
scheme=instance["db_scheme"],
|
|
359
|
-
user=name,
|
|
360
|
-
password=password,
|
|
361
|
-
host=instance["db_host"],
|
|
362
|
-
port=instance["db_port"],
|
|
363
|
-
database=instance["db_database"],
|
|
364
|
-
)
|
|
365
|
-
instance["db"] = db_dsn
|
|
366
|
-
return instance, storage # type: ignore
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
def _connect_instance_new(
|
|
370
|
-
owner: str, # account_handle
|
|
371
|
-
name: str, # instance_name
|
|
372
|
-
client: Client,
|
|
373
|
-
) -> tuple[dict, dict] | str:
|
|
374
|
-
response = client.functions.invoke(
|
|
375
|
-
"get-instance-settings", invoke_options={"body": {"owner": owner, "name": name}}
|
|
376
|
-
)
|
|
377
|
-
# no instance found, check why is that
|
|
378
|
-
if response == b"{}":
|
|
379
|
-
# try the via single requests, will take more time
|
|
380
|
-
account = select_account_by_handle(owner, client)
|
|
381
|
-
if account is None:
|
|
382
|
-
return "account-not-exists"
|
|
383
|
-
instance = select_instance_by_name(account["id"], name, client)
|
|
384
|
-
if instance is None:
|
|
385
|
-
return "instance-not-found"
|
|
386
|
-
# get default storage
|
|
387
|
-
storage = select_default_storage_by_instance_id(instance["id"], client)
|
|
388
|
-
if storage is None:
|
|
389
|
-
return "default-storage-does-not-exist-on-hub"
|
|
390
|
-
logger.warning(
|
|
391
|
-
"Could not find instance via API, but found directly querying hub."
|
|
392
|
-
)
|
|
393
|
-
else:
|
|
394
|
-
instance = json.loads(response)
|
|
395
|
-
storage = instance.pop("storage")
|
|
396
|
-
|
|
397
|
-
if instance["db_scheme"] is not None:
|
|
398
|
-
db_user_name, db_user_password = None, None
|
|
399
|
-
if "db_user_name" in instance and "db_user_password" in instance:
|
|
400
|
-
db_user_name, db_user_password = (
|
|
401
|
-
instance["db_user_name"],
|
|
402
|
-
instance["db_user_password"],
|
|
403
|
-
)
|
|
404
|
-
else:
|
|
405
|
-
db_user = select_db_user_by_instance(instance["id"], client)
|
|
406
|
-
if db_user is not None:
|
|
407
|
-
db_user_name, db_user_password = (
|
|
408
|
-
db_user["db_user_name"],
|
|
409
|
-
db_user["db_user_password"],
|
|
410
|
-
)
|
|
411
|
-
db_dsn = LaminDsn.build(
|
|
412
|
-
scheme=instance["db_scheme"],
|
|
413
|
-
user=db_user_name if db_user_name is not None else "none",
|
|
414
|
-
password=db_user_password if db_user_password is not None else "none",
|
|
415
|
-
host=instance["db_host"],
|
|
416
|
-
port=instance["db_port"],
|
|
417
|
-
database=instance["db_database"],
|
|
418
|
-
)
|
|
419
|
-
instance["db"] = db_dsn
|
|
420
|
-
return instance, storage # type: ignore
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
def connect_instance_new(
|
|
424
|
-
*,
|
|
425
|
-
owner: str, # account_handle
|
|
426
|
-
name: str, # instance_name
|
|
427
|
-
) -> tuple[dict, dict] | str:
|
|
428
|
-
from ._settings import settings
|
|
429
|
-
|
|
430
|
-
if settings.user.handle != "anonymous":
|
|
431
|
-
return call_with_fallback_auth(_connect_instance_new, owner=owner, name=name)
|
|
432
|
-
else:
|
|
433
|
-
return call_with_fallback(_connect_instance_new, owner=owner, name=name)
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
def access_aws(storage_root: str, access_token: str | None = None) -> dict[str, dict]:
|
|
437
|
-
from ._settings import settings
|
|
438
|
-
|
|
439
|
-
if settings.user.handle != "anonymous" or access_token is not None:
|
|
440
|
-
storage_root_info = call_with_fallback_auth(
|
|
441
|
-
_access_aws, storage_root=storage_root, access_token=access_token
|
|
442
|
-
)
|
|
443
|
-
return storage_root_info
|
|
444
|
-
else:
|
|
445
|
-
raise RuntimeError("Can only get access to AWS if authenticated.")
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
def _access_aws(*, storage_root: str, client: Client) -> dict[str, dict]:
|
|
449
|
-
import lamindb_setup
|
|
450
|
-
|
|
451
|
-
storage_root_info: dict[str, dict] = {"credentials": {}, "accessibility": {}}
|
|
452
|
-
response = client.functions.invoke(
|
|
453
|
-
"access-aws",
|
|
454
|
-
invoke_options={"body": {"storage_root": storage_root}},
|
|
455
|
-
)
|
|
456
|
-
if response is not None and response != b"{}":
|
|
457
|
-
data = json.loads(response)
|
|
458
|
-
|
|
459
|
-
loaded_credentials = data["Credentials"]
|
|
460
|
-
loaded_accessibility = data["StorageAccessibility"]
|
|
461
|
-
|
|
462
|
-
credentials = storage_root_info["credentials"]
|
|
463
|
-
credentials["key"] = loaded_credentials["AccessKeyId"]
|
|
464
|
-
credentials["secret"] = loaded_credentials["SecretAccessKey"]
|
|
465
|
-
credentials["token"] = loaded_credentials["SessionToken"]
|
|
466
|
-
|
|
467
|
-
accessibility = storage_root_info["accessibility"]
|
|
468
|
-
accessibility["storage_root"] = loaded_accessibility["storageRoot"]
|
|
469
|
-
accessibility["is_managed"] = loaded_accessibility["isManaged"]
|
|
470
|
-
return storage_root_info
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
def get_lamin_site_base_url():
|
|
474
|
-
if "LAMIN_ENV" in os.environ:
|
|
475
|
-
if os.environ["LAMIN_ENV"] == "local":
|
|
476
|
-
return "http://localhost:3000"
|
|
477
|
-
elif os.environ["LAMIN_ENV"] == "staging":
|
|
478
|
-
return "https://staging.lamin.ai"
|
|
479
|
-
return "https://lamin.ai"
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
def sign_up_local_hub(email) -> str | tuple[str, str, str]:
|
|
483
|
-
# raises gotrue.errors.AuthApiError: User already registered
|
|
484
|
-
password = base62(40) # generate new password
|
|
485
|
-
sign_up_kwargs = {"email": email, "password": password}
|
|
486
|
-
client = connect_hub()
|
|
487
|
-
auth_response = client.auth.sign_up(sign_up_kwargs)
|
|
488
|
-
client.auth.sign_out()
|
|
489
|
-
return (
|
|
490
|
-
password,
|
|
491
|
-
auth_response.session.user.id,
|
|
492
|
-
auth_response.session.access_token,
|
|
493
|
-
)
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
def _sign_in_hub(email: str, password: str, handle: str | None, client: Client):
|
|
497
|
-
auth = client.auth.sign_in_with_password(
|
|
498
|
-
{
|
|
499
|
-
"email": email,
|
|
500
|
-
"password": password,
|
|
501
|
-
}
|
|
502
|
-
)
|
|
503
|
-
data = client.table("account").select("*").eq("id", auth.user.id).execute().data
|
|
504
|
-
if data: # sync data from hub to local cache in case it was updated on the hub
|
|
505
|
-
user = data[0]
|
|
506
|
-
user_uuid = UUID(user["id"])
|
|
507
|
-
user_id = user["lnid"]
|
|
508
|
-
user_handle = user["handle"]
|
|
509
|
-
user_name = user["name"]
|
|
510
|
-
if handle is not None and handle != user_handle:
|
|
511
|
-
logger.warning(
|
|
512
|
-
f"using account handle {user_handle} (cached handle was {handle})"
|
|
513
|
-
)
|
|
514
|
-
else: # user did not complete signup as usermeta has no matching row
|
|
515
|
-
logger.error("complete signup on your account page.")
|
|
516
|
-
return "complete-signup"
|
|
517
|
-
return (
|
|
518
|
-
user_uuid,
|
|
519
|
-
user_id,
|
|
520
|
-
user_handle,
|
|
521
|
-
user_name,
|
|
522
|
-
auth.session.access_token,
|
|
523
|
-
)
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
def sign_in_hub(
|
|
527
|
-
email: str, password: str, handle: str | None = None
|
|
528
|
-
) -> Exception | str | tuple[UUID, str, str, str, str]:
|
|
529
|
-
try:
|
|
530
|
-
result = call_with_fallback(
|
|
531
|
-
_sign_in_hub, email=email, password=password, handle=handle
|
|
532
|
-
)
|
|
533
|
-
except Exception as exception: # this is bad, but I don't find APIError right now
|
|
534
|
-
logger.error(exception)
|
|
535
|
-
logger.error(
|
|
536
|
-
"Could not login. Probably your password is wrong or you didn't complete"
|
|
537
|
-
" signup."
|
|
538
|
-
)
|
|
539
|
-
return exception
|
|
540
|
-
return result
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
def _sign_in_hub_api_key(api_key: str, client: Client):
|
|
544
|
-
response = client.functions.invoke(
|
|
545
|
-
"create-jwt",
|
|
546
|
-
invoke_options={"body": {"api_key": api_key}},
|
|
547
|
-
)
|
|
548
|
-
access_token = json.loads(response)["accessToken"]
|
|
549
|
-
# probably need more info here to avoid additional queries
|
|
550
|
-
# like handle, uid etc
|
|
551
|
-
account_id = client.auth._decode_jwt(access_token)["sub"]
|
|
552
|
-
client.postgrest.auth(access_token)
|
|
553
|
-
# normally public.account.id is equal to auth.user.id
|
|
554
|
-
data = client.table("account").select("*").eq("id", account_id).execute().data
|
|
555
|
-
if data:
|
|
556
|
-
user = data[0]
|
|
557
|
-
user_uuid = UUID(user["id"])
|
|
558
|
-
user_id = user["lnid"]
|
|
559
|
-
user_handle = user["handle"]
|
|
560
|
-
user_name = user["name"]
|
|
561
|
-
else:
|
|
562
|
-
logger.error("Invalid API key.")
|
|
563
|
-
return "invalid-api-key"
|
|
564
|
-
return (user_uuid, user_id, user_handle, user_name, access_token)
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
def sign_in_hub_api_key(
|
|
568
|
-
api_key: str,
|
|
569
|
-
) -> Exception | str | tuple[UUID, str, str, str, str]:
|
|
570
|
-
try:
|
|
571
|
-
result = call_with_fallback(_sign_in_hub_api_key, api_key=api_key)
|
|
572
|
-
except Exception as exception:
|
|
573
|
-
logger.error(exception)
|
|
574
|
-
logger.error("Could not login. Probably your API key is wrong.")
|
|
575
|
-
return exception
|
|
576
|
-
return result
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
def _create_api_key(body: dict, client: Client) -> str:
|
|
580
|
-
response = client.functions.invoke(
|
|
581
|
-
"create-api-key",
|
|
582
|
-
invoke_options={"body": body},
|
|
583
|
-
)
|
|
584
|
-
api_key = json.loads(response)["apiKey"]
|
|
585
|
-
return api_key
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
def create_api_key(body: dict) -> str:
|
|
589
|
-
api_key = call_with_fallback_auth(_create_api_key, body=body)
|
|
590
|
-
return api_key
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import uuid
|
|
6
|
+
from importlib import metadata
|
|
7
|
+
from typing import TYPE_CHECKING, Literal
|
|
8
|
+
from uuid import UUID
|
|
9
|
+
|
|
10
|
+
from lamin_utils import logger
|
|
11
|
+
from postgrest.exceptions import APIError
|
|
12
|
+
|
|
13
|
+
from ._hub_client import (
|
|
14
|
+
call_with_fallback,
|
|
15
|
+
call_with_fallback_auth,
|
|
16
|
+
connect_hub,
|
|
17
|
+
)
|
|
18
|
+
from ._hub_crud import (
|
|
19
|
+
_delete_instance_record,
|
|
20
|
+
select_account_by_handle,
|
|
21
|
+
select_db_user_by_instance,
|
|
22
|
+
select_default_storage_by_instance_id,
|
|
23
|
+
select_instance_by_id_with_storage,
|
|
24
|
+
select_instance_by_name,
|
|
25
|
+
select_instance_by_owner_name,
|
|
26
|
+
)
|
|
27
|
+
from ._hub_crud import update_instance as _update_instance_record
|
|
28
|
+
from ._hub_utils import (
|
|
29
|
+
LaminDsn,
|
|
30
|
+
LaminDsnModel,
|
|
31
|
+
)
|
|
32
|
+
from ._settings import settings
|
|
33
|
+
from ._settings_storage import StorageSettings, base62
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING:
|
|
36
|
+
from supabase import Client # type: ignore
|
|
37
|
+
|
|
38
|
+
from ._settings_instance import InstanceSettings
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def delete_storage_record(
|
|
42
|
+
storage_uuid: UUID,
|
|
43
|
+
) -> None:
|
|
44
|
+
return call_with_fallback_auth(
|
|
45
|
+
_delete_storage_record,
|
|
46
|
+
storage_uuid=storage_uuid,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _delete_storage_record(storage_uuid: UUID, client: Client) -> None:
|
|
51
|
+
if storage_uuid is None:
|
|
52
|
+
return None
|
|
53
|
+
response = client.table("storage").delete().eq("id", storage_uuid.hex).execute()
|
|
54
|
+
if response.data:
|
|
55
|
+
logger.important(f"deleted storage record on hub {storage_uuid.hex}")
|
|
56
|
+
else:
|
|
57
|
+
raise PermissionError(
|
|
58
|
+
f"Deleting of storage with {storage_uuid.hex} was not successful. Probably, you"
|
|
59
|
+
" don't have sufficient permissions."
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def update_instance_record(instance_uuid: UUID, fields: dict) -> None:
|
|
64
|
+
return call_with_fallback_auth(
|
|
65
|
+
_update_instance_record, instance_id=instance_uuid.hex, instance_fields=fields
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def get_storage_records_for_instance(
|
|
70
|
+
instance_id: UUID,
|
|
71
|
+
) -> list[dict[str, str | int]]:
|
|
72
|
+
return call_with_fallback_auth(
|
|
73
|
+
_get_storage_records_for_instance,
|
|
74
|
+
instance_id=instance_id,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _get_storage_records_for_instance(
|
|
79
|
+
instance_id: UUID, client: Client
|
|
80
|
+
) -> list[dict[str, str | int]]:
|
|
81
|
+
response = (
|
|
82
|
+
client.table("storage").select("*").eq("instance_id", instance_id.hex).execute()
|
|
83
|
+
)
|
|
84
|
+
return response.data
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _select_storage(
|
|
88
|
+
ssettings: StorageSettings, update_uid: bool, client: Client
|
|
89
|
+
) -> bool:
|
|
90
|
+
root = ssettings.root_as_str
|
|
91
|
+
response = client.table("storage").select("*").eq("root", root).execute()
|
|
92
|
+
if not response.data:
|
|
93
|
+
return False
|
|
94
|
+
else:
|
|
95
|
+
existing_storage = response.data[0]
|
|
96
|
+
if existing_storage["instance_id"] is not None:
|
|
97
|
+
if ssettings._instance_id is not None:
|
|
98
|
+
# consider storage settings that are meant to be managed by an instance
|
|
99
|
+
if UUID(existing_storage["instance_id"]) != ssettings._instance_id:
|
|
100
|
+
# everything is alright if the instance_id matches
|
|
101
|
+
# we're probably just switching storage locations
|
|
102
|
+
# below can be turned into a warning and then delegate the error
|
|
103
|
+
# to a unique constraint violation below
|
|
104
|
+
raise ValueError(
|
|
105
|
+
f"Storage root {root} is already managed by instance {existing_storage['instance_id']}."
|
|
106
|
+
)
|
|
107
|
+
else:
|
|
108
|
+
# if the request is agnostic of the instance, that's alright,
|
|
109
|
+
# we'll update the instance_id with what's stored in the hub
|
|
110
|
+
ssettings._instance_id = UUID(existing_storage["instance_id"])
|
|
111
|
+
ssettings._uuid_ = UUID(existing_storage["id"])
|
|
112
|
+
if update_uid:
|
|
113
|
+
ssettings._uid = existing_storage["lnid"]
|
|
114
|
+
else:
|
|
115
|
+
assert ssettings._uid == existing_storage["lnid"]
|
|
116
|
+
return True
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def init_storage(
|
|
120
|
+
ssettings: StorageSettings,
|
|
121
|
+
auto_populate_instance: bool = True,
|
|
122
|
+
) -> Literal["hub-record-retireved", "hub-record-created"]:
|
|
123
|
+
if settings.user.handle != "anonymous":
|
|
124
|
+
return call_with_fallback_auth(
|
|
125
|
+
_init_storage,
|
|
126
|
+
ssettings=ssettings,
|
|
127
|
+
auto_populate_instance=auto_populate_instance,
|
|
128
|
+
)
|
|
129
|
+
else:
|
|
130
|
+
storage_exists = call_with_fallback(
|
|
131
|
+
_select_storage, ssettings=ssettings, update_uid=True
|
|
132
|
+
)
|
|
133
|
+
if storage_exists:
|
|
134
|
+
return "hub-record-retireved"
|
|
135
|
+
else:
|
|
136
|
+
raise ValueError("Log in to create a storage location on the hub.")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _init_storage(
|
|
140
|
+
ssettings: StorageSettings, auto_populate_instance: bool, client: Client
|
|
141
|
+
) -> Literal["hub-record-retireved", "hub-record-created"]:
|
|
142
|
+
from lamindb_setup import settings
|
|
143
|
+
|
|
144
|
+
# storage roots are always stored without the trailing slash in the SQL
|
|
145
|
+
# database
|
|
146
|
+
root = ssettings.root_as_str
|
|
147
|
+
if _select_storage(ssettings, update_uid=True, client=client):
|
|
148
|
+
return "hub-record-retireved"
|
|
149
|
+
if ssettings.type_is_cloud:
|
|
150
|
+
id = uuid.uuid5(uuid.NAMESPACE_URL, root)
|
|
151
|
+
else:
|
|
152
|
+
id = uuid.uuid4()
|
|
153
|
+
if (
|
|
154
|
+
ssettings._instance_id is None
|
|
155
|
+
and settings._instance_exists
|
|
156
|
+
and auto_populate_instance
|
|
157
|
+
):
|
|
158
|
+
logger.warning(
|
|
159
|
+
f"will manage storage location {ssettings.root_as_str} with instance {settings.instance.slug}"
|
|
160
|
+
)
|
|
161
|
+
ssettings._instance_id = settings.instance._id
|
|
162
|
+
instance_id_hex = (
|
|
163
|
+
ssettings._instance_id.hex
|
|
164
|
+
if (ssettings._instance_id is not None and auto_populate_instance)
|
|
165
|
+
else None
|
|
166
|
+
)
|
|
167
|
+
fields = {
|
|
168
|
+
"id": id.hex,
|
|
169
|
+
"lnid": ssettings.uid,
|
|
170
|
+
"created_by": settings.user._uuid.hex, # type: ignore
|
|
171
|
+
"root": root,
|
|
172
|
+
"region": ssettings.region,
|
|
173
|
+
"type": ssettings.type,
|
|
174
|
+
"instance_id": instance_id_hex,
|
|
175
|
+
# the empty string is important as we want the user flow to be through LaminHub
|
|
176
|
+
# if this errors with unique constraint error, the user has to update
|
|
177
|
+
# the description in LaminHub
|
|
178
|
+
"description": "",
|
|
179
|
+
}
|
|
180
|
+
# TODO: add error message for violated unique constraint
|
|
181
|
+
# on root & description
|
|
182
|
+
client.table("storage").upsert(fields).execute()
|
|
183
|
+
ssettings._uuid_ = id
|
|
184
|
+
return "hub-record-created"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def delete_instance(identifier: UUID | str, require_empty: bool = True) -> str | None:
|
|
188
|
+
return call_with_fallback_auth(
|
|
189
|
+
_delete_instance, identifier=identifier, require_empty=require_empty
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _delete_instance(
|
|
194
|
+
identifier: UUID | str, require_empty: bool, client: Client
|
|
195
|
+
) -> str | None:
|
|
196
|
+
"""Fully delete an instance in the hub.
|
|
197
|
+
|
|
198
|
+
This function deletes the relevant instance and storage records in the hub,
|
|
199
|
+
conditional on the emptiness of the storage location.
|
|
200
|
+
"""
|
|
201
|
+
from ._settings_storage import mark_storage_root
|
|
202
|
+
from .upath import check_storage_is_empty, create_path
|
|
203
|
+
|
|
204
|
+
# the "/" check is for backward compatibility with the old identifier format
|
|
205
|
+
if isinstance(identifier, UUID) or "/" not in identifier:
|
|
206
|
+
if isinstance(identifier, UUID):
|
|
207
|
+
instance_id_str = identifier.hex
|
|
208
|
+
else:
|
|
209
|
+
instance_id_str = identifier
|
|
210
|
+
instance_with_storage = select_instance_by_id_with_storage(
|
|
211
|
+
instance_id=instance_id_str, client=client
|
|
212
|
+
)
|
|
213
|
+
else:
|
|
214
|
+
owner, name = identifier.split("/")
|
|
215
|
+
instance_with_storage = select_instance_by_owner_name(
|
|
216
|
+
owner=owner, name=name, client=client
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
if instance_with_storage is None:
|
|
220
|
+
logger.important("not deleting instance from hub as instance not found there")
|
|
221
|
+
return "instance-not-found"
|
|
222
|
+
|
|
223
|
+
storage_records = _get_storage_records_for_instance(
|
|
224
|
+
UUID(instance_with_storage["id"]),
|
|
225
|
+
client,
|
|
226
|
+
)
|
|
227
|
+
if require_empty:
|
|
228
|
+
for storage_record in storage_records:
|
|
229
|
+
account_for_sqlite_file = (
|
|
230
|
+
instance_with_storage["db_scheme"] is None
|
|
231
|
+
and instance_with_storage["storage"]["root"] == storage_record["root"]
|
|
232
|
+
)
|
|
233
|
+
root_string = storage_record["root"]
|
|
234
|
+
# gate storage and instance deletion on empty storage location for
|
|
235
|
+
if client.auth.get_session() is not None:
|
|
236
|
+
access_token = client.auth.get_session().access_token
|
|
237
|
+
else:
|
|
238
|
+
access_token = None
|
|
239
|
+
root_path = create_path(root_string, access_token)
|
|
240
|
+
mark_storage_root(
|
|
241
|
+
root_path,
|
|
242
|
+
storage_record["lnid"], # type: ignore
|
|
243
|
+
) # address permission error
|
|
244
|
+
check_storage_is_empty(
|
|
245
|
+
root_path, account_for_sqlite_file=account_for_sqlite_file
|
|
246
|
+
)
|
|
247
|
+
_update_instance_record(instance_with_storage["id"], {"storage_id": None}, client)
|
|
248
|
+
# first delete the storage records because we will turn instance_id on
|
|
249
|
+
# storage into a FK soon
|
|
250
|
+
for storage_record in storage_records:
|
|
251
|
+
_delete_storage_record(UUID(storage_record["id"]), client) # type: ignore
|
|
252
|
+
_delete_instance_record(UUID(instance_with_storage["id"]), client)
|
|
253
|
+
return None
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def delete_instance_record(
|
|
257
|
+
instance_id: UUID,
|
|
258
|
+
) -> None:
|
|
259
|
+
return call_with_fallback_auth(
|
|
260
|
+
_delete_instance_record,
|
|
261
|
+
instance_id=instance_id,
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def init_instance(isettings: InstanceSettings) -> None:
|
|
266
|
+
return call_with_fallback_auth(_init_instance, isettings=isettings)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _init_instance(isettings: InstanceSettings, client: Client) -> None:
|
|
270
|
+
from ._settings import settings
|
|
271
|
+
|
|
272
|
+
try:
|
|
273
|
+
lamindb_version = metadata.version("lamindb")
|
|
274
|
+
except metadata.PackageNotFoundError:
|
|
275
|
+
lamindb_version = None
|
|
276
|
+
fields = {
|
|
277
|
+
"id": isettings._id.hex,
|
|
278
|
+
"account_id": settings.user._uuid.hex, # type: ignore
|
|
279
|
+
"name": isettings.name,
|
|
280
|
+
"lnid": isettings.uid,
|
|
281
|
+
"schema_str": isettings._schema_str,
|
|
282
|
+
"lamindb_version": lamindb_version,
|
|
283
|
+
"public": False,
|
|
284
|
+
}
|
|
285
|
+
if isettings.dialect != "sqlite":
|
|
286
|
+
db_dsn = LaminDsnModel(db=isettings.db)
|
|
287
|
+
db_fields = {
|
|
288
|
+
"db_scheme": db_dsn.db.scheme,
|
|
289
|
+
"db_host": db_dsn.db.host,
|
|
290
|
+
"db_port": db_dsn.db.port,
|
|
291
|
+
"db_database": db_dsn.db.database,
|
|
292
|
+
}
|
|
293
|
+
fields.update(db_fields)
|
|
294
|
+
# I'd like the following to be an upsert, but this seems to violate RLS
|
|
295
|
+
# Similarly, if we don't specify `returning="minimal"`, we'll violate RLS
|
|
296
|
+
# we could make this idempotent by catching an error, but this seems dangerous
|
|
297
|
+
# as then init_instance is no longer idempotent
|
|
298
|
+
try:
|
|
299
|
+
client.table("instance").insert(fields, returning="minimal").execute()
|
|
300
|
+
except APIError:
|
|
301
|
+
logger.warning(
|
|
302
|
+
f"instance already existed at: https://lamin.ai/{isettings.owner}/{isettings.name}"
|
|
303
|
+
)
|
|
304
|
+
return None
|
|
305
|
+
client.table("storage").update(
|
|
306
|
+
{"instance_id": isettings._id.hex, "is_default": True}
|
|
307
|
+
).eq("id", isettings.storage._uuid.hex).execute() # type: ignore
|
|
308
|
+
logger.important(f"go to: https://lamin.ai/{isettings.owner}/{isettings.name}")
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def connect_instance(
|
|
312
|
+
*,
|
|
313
|
+
owner: str, # account_handle
|
|
314
|
+
name: str, # instance_name
|
|
315
|
+
) -> tuple[dict, dict] | str:
|
|
316
|
+
from ._settings import settings
|
|
317
|
+
|
|
318
|
+
if settings.user.handle != "anonymous":
|
|
319
|
+
return call_with_fallback_auth(_connect_instance, owner=owner, name=name)
|
|
320
|
+
else:
|
|
321
|
+
return call_with_fallback(_connect_instance, owner=owner, name=name)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _connect_instance(
|
|
325
|
+
*,
|
|
326
|
+
owner: str, # account_handle
|
|
327
|
+
name: str, # instance_name
|
|
328
|
+
client: Client,
|
|
329
|
+
) -> tuple[dict, dict] | str:
|
|
330
|
+
instance_account_storage = select_instance_by_owner_name(owner, name, client)
|
|
331
|
+
if instance_account_storage is None:
|
|
332
|
+
# try the via single requests, will take more time
|
|
333
|
+
account = select_account_by_handle(owner, client)
|
|
334
|
+
if account is None:
|
|
335
|
+
return "account-not-exists"
|
|
336
|
+
instance = select_instance_by_name(account["id"], name, client)
|
|
337
|
+
if instance is None:
|
|
338
|
+
return "instance-not-found"
|
|
339
|
+
# get default storage
|
|
340
|
+
storage = select_default_storage_by_instance_id(instance["id"], client)
|
|
341
|
+
if storage is None:
|
|
342
|
+
return "default-storage-does-not-exist-on-hub"
|
|
343
|
+
else:
|
|
344
|
+
account = instance_account_storage.pop("account")
|
|
345
|
+
storage = instance_account_storage.pop("storage")
|
|
346
|
+
instance = instance_account_storage
|
|
347
|
+
# check if is postgres instance
|
|
348
|
+
# this used to be a check for `instance["db"] is not None` in earlier versions
|
|
349
|
+
# removed this on 2022-10-25 and can remove from the hub probably for lamindb 1.0
|
|
350
|
+
if instance["db_scheme"] is not None:
|
|
351
|
+
db_user = select_db_user_by_instance(instance["id"], client)
|
|
352
|
+
if db_user is None:
|
|
353
|
+
name, password = "none", "none"
|
|
354
|
+
else:
|
|
355
|
+
name, password = db_user["db_user_name"], db_user["db_user_password"]
|
|
356
|
+
# construct dsn from instance and db_account fields
|
|
357
|
+
db_dsn = LaminDsn.build(
|
|
358
|
+
scheme=instance["db_scheme"],
|
|
359
|
+
user=name,
|
|
360
|
+
password=password,
|
|
361
|
+
host=instance["db_host"],
|
|
362
|
+
port=instance["db_port"],
|
|
363
|
+
database=instance["db_database"],
|
|
364
|
+
)
|
|
365
|
+
instance["db"] = db_dsn
|
|
366
|
+
return instance, storage # type: ignore
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _connect_instance_new(
|
|
370
|
+
owner: str, # account_handle
|
|
371
|
+
name: str, # instance_name
|
|
372
|
+
client: Client,
|
|
373
|
+
) -> tuple[dict, dict] | str:
|
|
374
|
+
response = client.functions.invoke(
|
|
375
|
+
"get-instance-settings", invoke_options={"body": {"owner": owner, "name": name}}
|
|
376
|
+
)
|
|
377
|
+
# no instance found, check why is that
|
|
378
|
+
if response == b"{}":
|
|
379
|
+
# try the via single requests, will take more time
|
|
380
|
+
account = select_account_by_handle(owner, client)
|
|
381
|
+
if account is None:
|
|
382
|
+
return "account-not-exists"
|
|
383
|
+
instance = select_instance_by_name(account["id"], name, client)
|
|
384
|
+
if instance is None:
|
|
385
|
+
return "instance-not-found"
|
|
386
|
+
# get default storage
|
|
387
|
+
storage = select_default_storage_by_instance_id(instance["id"], client)
|
|
388
|
+
if storage is None:
|
|
389
|
+
return "default-storage-does-not-exist-on-hub"
|
|
390
|
+
logger.warning(
|
|
391
|
+
"Could not find instance via API, but found directly querying hub."
|
|
392
|
+
)
|
|
393
|
+
else:
|
|
394
|
+
instance = json.loads(response)
|
|
395
|
+
storage = instance.pop("storage")
|
|
396
|
+
|
|
397
|
+
if instance["db_scheme"] is not None:
|
|
398
|
+
db_user_name, db_user_password = None, None
|
|
399
|
+
if "db_user_name" in instance and "db_user_password" in instance:
|
|
400
|
+
db_user_name, db_user_password = (
|
|
401
|
+
instance["db_user_name"],
|
|
402
|
+
instance["db_user_password"],
|
|
403
|
+
)
|
|
404
|
+
else:
|
|
405
|
+
db_user = select_db_user_by_instance(instance["id"], client)
|
|
406
|
+
if db_user is not None:
|
|
407
|
+
db_user_name, db_user_password = (
|
|
408
|
+
db_user["db_user_name"],
|
|
409
|
+
db_user["db_user_password"],
|
|
410
|
+
)
|
|
411
|
+
db_dsn = LaminDsn.build(
|
|
412
|
+
scheme=instance["db_scheme"],
|
|
413
|
+
user=db_user_name if db_user_name is not None else "none",
|
|
414
|
+
password=db_user_password if db_user_password is not None else "none",
|
|
415
|
+
host=instance["db_host"],
|
|
416
|
+
port=instance["db_port"],
|
|
417
|
+
database=instance["db_database"],
|
|
418
|
+
)
|
|
419
|
+
instance["db"] = db_dsn
|
|
420
|
+
return instance, storage # type: ignore
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def connect_instance_new(
|
|
424
|
+
*,
|
|
425
|
+
owner: str, # account_handle
|
|
426
|
+
name: str, # instance_name
|
|
427
|
+
) -> tuple[dict, dict] | str:
|
|
428
|
+
from ._settings import settings
|
|
429
|
+
|
|
430
|
+
if settings.user.handle != "anonymous":
|
|
431
|
+
return call_with_fallback_auth(_connect_instance_new, owner=owner, name=name)
|
|
432
|
+
else:
|
|
433
|
+
return call_with_fallback(_connect_instance_new, owner=owner, name=name)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def access_aws(storage_root: str, access_token: str | None = None) -> dict[str, dict]:
|
|
437
|
+
from ._settings import settings
|
|
438
|
+
|
|
439
|
+
if settings.user.handle != "anonymous" or access_token is not None:
|
|
440
|
+
storage_root_info = call_with_fallback_auth(
|
|
441
|
+
_access_aws, storage_root=storage_root, access_token=access_token
|
|
442
|
+
)
|
|
443
|
+
return storage_root_info
|
|
444
|
+
else:
|
|
445
|
+
raise RuntimeError("Can only get access to AWS if authenticated.")
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _access_aws(*, storage_root: str, client: Client) -> dict[str, dict]:
|
|
449
|
+
import lamindb_setup
|
|
450
|
+
|
|
451
|
+
storage_root_info: dict[str, dict] = {"credentials": {}, "accessibility": {}}
|
|
452
|
+
response = client.functions.invoke(
|
|
453
|
+
"access-aws",
|
|
454
|
+
invoke_options={"body": {"storage_root": storage_root}},
|
|
455
|
+
)
|
|
456
|
+
if response is not None and response != b"{}":
|
|
457
|
+
data = json.loads(response)
|
|
458
|
+
|
|
459
|
+
loaded_credentials = data["Credentials"]
|
|
460
|
+
loaded_accessibility = data["StorageAccessibility"]
|
|
461
|
+
|
|
462
|
+
credentials = storage_root_info["credentials"]
|
|
463
|
+
credentials["key"] = loaded_credentials["AccessKeyId"]
|
|
464
|
+
credentials["secret"] = loaded_credentials["SecretAccessKey"]
|
|
465
|
+
credentials["token"] = loaded_credentials["SessionToken"]
|
|
466
|
+
|
|
467
|
+
accessibility = storage_root_info["accessibility"]
|
|
468
|
+
accessibility["storage_root"] = loaded_accessibility["storageRoot"]
|
|
469
|
+
accessibility["is_managed"] = loaded_accessibility["isManaged"]
|
|
470
|
+
return storage_root_info
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def get_lamin_site_base_url():
|
|
474
|
+
if "LAMIN_ENV" in os.environ:
|
|
475
|
+
if os.environ["LAMIN_ENV"] == "local":
|
|
476
|
+
return "http://localhost:3000"
|
|
477
|
+
elif os.environ["LAMIN_ENV"] == "staging":
|
|
478
|
+
return "https://staging.lamin.ai"
|
|
479
|
+
return "https://lamin.ai"
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def sign_up_local_hub(email) -> str | tuple[str, str, str]:
|
|
483
|
+
# raises gotrue.errors.AuthApiError: User already registered
|
|
484
|
+
password = base62(40) # generate new password
|
|
485
|
+
sign_up_kwargs = {"email": email, "password": password}
|
|
486
|
+
client = connect_hub()
|
|
487
|
+
auth_response = client.auth.sign_up(sign_up_kwargs)
|
|
488
|
+
client.auth.sign_out()
|
|
489
|
+
return (
|
|
490
|
+
password,
|
|
491
|
+
auth_response.session.user.id,
|
|
492
|
+
auth_response.session.access_token,
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _sign_in_hub(email: str, password: str, handle: str | None, client: Client):
|
|
497
|
+
auth = client.auth.sign_in_with_password(
|
|
498
|
+
{
|
|
499
|
+
"email": email,
|
|
500
|
+
"password": password,
|
|
501
|
+
}
|
|
502
|
+
)
|
|
503
|
+
data = client.table("account").select("*").eq("id", auth.user.id).execute().data
|
|
504
|
+
if data: # sync data from hub to local cache in case it was updated on the hub
|
|
505
|
+
user = data[0]
|
|
506
|
+
user_uuid = UUID(user["id"])
|
|
507
|
+
user_id = user["lnid"]
|
|
508
|
+
user_handle = user["handle"]
|
|
509
|
+
user_name = user["name"]
|
|
510
|
+
if handle is not None and handle != user_handle:
|
|
511
|
+
logger.warning(
|
|
512
|
+
f"using account handle {user_handle} (cached handle was {handle})"
|
|
513
|
+
)
|
|
514
|
+
else: # user did not complete signup as usermeta has no matching row
|
|
515
|
+
logger.error("complete signup on your account page.")
|
|
516
|
+
return "complete-signup"
|
|
517
|
+
return (
|
|
518
|
+
user_uuid,
|
|
519
|
+
user_id,
|
|
520
|
+
user_handle,
|
|
521
|
+
user_name,
|
|
522
|
+
auth.session.access_token,
|
|
523
|
+
)
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def sign_in_hub(
|
|
527
|
+
email: str, password: str, handle: str | None = None
|
|
528
|
+
) -> Exception | str | tuple[UUID, str, str, str, str]:
|
|
529
|
+
try:
|
|
530
|
+
result = call_with_fallback(
|
|
531
|
+
_sign_in_hub, email=email, password=password, handle=handle
|
|
532
|
+
)
|
|
533
|
+
except Exception as exception: # this is bad, but I don't find APIError right now
|
|
534
|
+
logger.error(exception)
|
|
535
|
+
logger.error(
|
|
536
|
+
"Could not login. Probably your password is wrong or you didn't complete"
|
|
537
|
+
" signup."
|
|
538
|
+
)
|
|
539
|
+
return exception
|
|
540
|
+
return result
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def _sign_in_hub_api_key(api_key: str, client: Client):
|
|
544
|
+
response = client.functions.invoke(
|
|
545
|
+
"create-jwt",
|
|
546
|
+
invoke_options={"body": {"api_key": api_key}},
|
|
547
|
+
)
|
|
548
|
+
access_token = json.loads(response)["accessToken"]
|
|
549
|
+
# probably need more info here to avoid additional queries
|
|
550
|
+
# like handle, uid etc
|
|
551
|
+
account_id = client.auth._decode_jwt(access_token)["sub"]
|
|
552
|
+
client.postgrest.auth(access_token)
|
|
553
|
+
# normally public.account.id is equal to auth.user.id
|
|
554
|
+
data = client.table("account").select("*").eq("id", account_id).execute().data
|
|
555
|
+
if data:
|
|
556
|
+
user = data[0]
|
|
557
|
+
user_uuid = UUID(user["id"])
|
|
558
|
+
user_id = user["lnid"]
|
|
559
|
+
user_handle = user["handle"]
|
|
560
|
+
user_name = user["name"]
|
|
561
|
+
else:
|
|
562
|
+
logger.error("Invalid API key.")
|
|
563
|
+
return "invalid-api-key"
|
|
564
|
+
return (user_uuid, user_id, user_handle, user_name, access_token)
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def sign_in_hub_api_key(
|
|
568
|
+
api_key: str,
|
|
569
|
+
) -> Exception | str | tuple[UUID, str, str, str, str]:
|
|
570
|
+
try:
|
|
571
|
+
result = call_with_fallback(_sign_in_hub_api_key, api_key=api_key)
|
|
572
|
+
except Exception as exception:
|
|
573
|
+
logger.error(exception)
|
|
574
|
+
logger.error("Could not login. Probably your API key is wrong.")
|
|
575
|
+
return exception
|
|
576
|
+
return result
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def _create_api_key(body: dict, client: Client) -> str:
|
|
580
|
+
response = client.functions.invoke(
|
|
581
|
+
"create-api-key",
|
|
582
|
+
invoke_options={"body": body},
|
|
583
|
+
)
|
|
584
|
+
api_key = json.loads(response)["apiKey"]
|
|
585
|
+
return api_key
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def create_api_key(body: dict) -> str:
|
|
589
|
+
api_key = call_with_fallback_auth(_create_api_key, body=body)
|
|
590
|
+
return api_key
|