sandscale 1.0.0__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.
- sandscale/__init__.py +450 -0
- sandscale/_account.py +150 -0
- sandscale/_admin.py +349 -0
- sandscale/_api.py +291 -0
- sandscale/_api_gen.py +353 -0
- sandscale/_builtin.py +20 -0
- sandscale/_call.py +80 -0
- sandscale/_capabilities.py +177 -0
- sandscale/_code.py +340 -0
- sandscale/_compute.py +131 -0
- sandscale/_objects.py +193 -0
- sandscale/_operations_gen.py +355 -0
- sandscale/_processes.py +40 -0
- sandscale/_services.py +1104 -0
- sandscale/_transport.py +371 -0
- sandscale/_version.py +5 -0
- sandscale/admin_models.py +1663 -0
- sandscale/errors.py +394 -0
- sandscale/integrations/__init__.py +13 -0
- sandscale/integrations/langchain.py +243 -0
- sandscale/integrations/openai_agents.py +381 -0
- sandscale/models.py +566 -0
- sandscale/py.typed +0 -0
- sandscale-1.0.0.dist-info/METADATA +416 -0
- sandscale-1.0.0.dist-info/RECORD +27 -0
- sandscale-1.0.0.dist-info/WHEEL +4 -0
- sandscale-1.0.0.dist-info/licenses/LICENSE +231 -0
sandscale/__init__.py
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
# Copyright 2026 Neural Inverse
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Sandscale Python SDK.
|
|
4
|
+
|
|
5
|
+
Every call goes to Sandscale's public API (https://api.sandscale.dev by default) as the API
|
|
6
|
+
key's or the signed-in person's own identity; the server decides what is allowed, the SDK only
|
|
7
|
+
carries the answer::
|
|
8
|
+
|
|
9
|
+
from sandscale import Sandscale
|
|
10
|
+
|
|
11
|
+
with Sandscale(region="eu") as sandscale:
|
|
12
|
+
box = sandscale.sandboxes.create(template="builtin:python")
|
|
13
|
+
run = sandscale.sandboxes.run(box.id, "python -V", region=box.region, on_stdout=print)
|
|
14
|
+
sandscale.sandboxes.stop(box.id, region=box.region)
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from typing import Any, Mapping, Optional
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
|
|
23
|
+
from ._account import Account
|
|
24
|
+
from ._api import Api, ApiArgumentError, ApiFunction, ApiNamespace
|
|
25
|
+
from ._code import (
|
|
26
|
+
ApiErrorInfo,
|
|
27
|
+
CodePolicy,
|
|
28
|
+
CodePolicyService,
|
|
29
|
+
ConsoleLine,
|
|
30
|
+
PendingApproval,
|
|
31
|
+
SearchResult,
|
|
32
|
+
Task,
|
|
33
|
+
TaskError,
|
|
34
|
+
TaskFailedError,
|
|
35
|
+
Tasks,
|
|
36
|
+
TaskTimeoutError,
|
|
37
|
+
execute as _execute,
|
|
38
|
+
search as _search,
|
|
39
|
+
)
|
|
40
|
+
from ._call import call as _call, operations
|
|
41
|
+
from ._capabilities import Capabilities, capabilities as _capabilities
|
|
42
|
+
from ._builtin import BUILTIN_TEMPLATES
|
|
43
|
+
from ._admin import Policy, Snapshots, Templates, Traces, Webhooks, verify_webhook_signature
|
|
44
|
+
from ._compute import AgentCloud, LabHosts
|
|
45
|
+
from ._objects import Objects
|
|
46
|
+
from ._services import BuildHosts, Caches, ProcessInfo, ProcessLogs, ProcessStart, Sandboxes, Volumes, Workspaces
|
|
47
|
+
from ._transport import DEFAULT_BASE_URL, SANDSCALE_REGION_URLS, TokenSource, Transport
|
|
48
|
+
from ._version import VERSION
|
|
49
|
+
from .errors import (
|
|
50
|
+
AccountExistsError,
|
|
51
|
+
APIConnectionError,
|
|
52
|
+
AuthenticationError,
|
|
53
|
+
ConfigurationError,
|
|
54
|
+
ConflictError,
|
|
55
|
+
EntitlementError,
|
|
56
|
+
FairUseLimit,
|
|
57
|
+
LimitInfo,
|
|
58
|
+
PlanRefusal,
|
|
59
|
+
FreeAlreadyClaimedError,
|
|
60
|
+
FreeDailyLimitError,
|
|
61
|
+
FreeMonthlyLimitError,
|
|
62
|
+
FreeNewAccountLimitError,
|
|
63
|
+
InvalidRequestError,
|
|
64
|
+
KillSwitchError,
|
|
65
|
+
LimitExceededError,
|
|
66
|
+
NotFoundError,
|
|
67
|
+
PermissionDeniedError,
|
|
68
|
+
RateLimitError,
|
|
69
|
+
RegionError,
|
|
70
|
+
SandscaleError,
|
|
71
|
+
SandboxWakingError,
|
|
72
|
+
ServerError,
|
|
73
|
+
ServiceUnavailableError,
|
|
74
|
+
)
|
|
75
|
+
from .admin_models import (
|
|
76
|
+
CodeModeUsage,
|
|
77
|
+
DailyUsage,
|
|
78
|
+
GithubLinkStart,
|
|
79
|
+
Identity,
|
|
80
|
+
PeriodUsage,
|
|
81
|
+
RampUsage,
|
|
82
|
+
UsageLimits,
|
|
83
|
+
TraceCost,
|
|
84
|
+
NoncurrentVersionExpiration,
|
|
85
|
+
BucketUsage,
|
|
86
|
+
BucketEndpoints,
|
|
87
|
+
ApiKeyLimits,
|
|
88
|
+
AppShareResult,
|
|
89
|
+
AccessKey,
|
|
90
|
+
AgentTask,
|
|
91
|
+
ApiKey,
|
|
92
|
+
ApiKeyList,
|
|
93
|
+
BackupVerification,
|
|
94
|
+
Billing,
|
|
95
|
+
Bucket,
|
|
96
|
+
BucketList,
|
|
97
|
+
CacheEntry,
|
|
98
|
+
CacheView,
|
|
99
|
+
Checkout,
|
|
100
|
+
CreatedAccessKey,
|
|
101
|
+
CreatedApiKey,
|
|
102
|
+
CreatedWebhook,
|
|
103
|
+
CreditBalance,
|
|
104
|
+
DefaultRetention,
|
|
105
|
+
LabHost,
|
|
106
|
+
LeaseArtifact,
|
|
107
|
+
LeaseRun,
|
|
108
|
+
LifecycleRule,
|
|
109
|
+
ObjectsLimits,
|
|
110
|
+
OpenLink,
|
|
111
|
+
PlanOffer,
|
|
112
|
+
PlanState,
|
|
113
|
+
PortExposure,
|
|
114
|
+
PreviewLink,
|
|
115
|
+
RegionInfo,
|
|
116
|
+
SandboxPolicy,
|
|
117
|
+
SandboxSshCertificate,
|
|
118
|
+
SandboxSshInfo,
|
|
119
|
+
SnapshotList,
|
|
120
|
+
SnapshotUsage,
|
|
121
|
+
Template,
|
|
122
|
+
TemplateBuildStatus,
|
|
123
|
+
Trace,
|
|
124
|
+
TraceBox,
|
|
125
|
+
TraceCommand,
|
|
126
|
+
TraceEvent,
|
|
127
|
+
TraceExport,
|
|
128
|
+
TraceExportTest,
|
|
129
|
+
TraceFile,
|
|
130
|
+
TraceSpan,
|
|
131
|
+
TraceSummary,
|
|
132
|
+
Usage,
|
|
133
|
+
Webhook,
|
|
134
|
+
WebhookDelivery,
|
|
135
|
+
WorkspaceApp,
|
|
136
|
+
WorkspaceBackup,
|
|
137
|
+
)
|
|
138
|
+
from .models import (
|
|
139
|
+
DependencyCache,
|
|
140
|
+
CacheResult,
|
|
141
|
+
ActivityDay,
|
|
142
|
+
ConnectInfo,
|
|
143
|
+
FileEntry,
|
|
144
|
+
Lease,
|
|
145
|
+
LeaseConnectInfo,
|
|
146
|
+
ListResult,
|
|
147
|
+
OutputChunk,
|
|
148
|
+
Pool,
|
|
149
|
+
RegionPage,
|
|
150
|
+
RunEnd,
|
|
151
|
+
RunOutput,
|
|
152
|
+
RunResult,
|
|
153
|
+
Sandbox,
|
|
154
|
+
SandboxActivity,
|
|
155
|
+
Snapshot,
|
|
156
|
+
SSHCertificate,
|
|
157
|
+
VaultEnvRef,
|
|
158
|
+
Volume,
|
|
159
|
+
VolumeAttachment,
|
|
160
|
+
Workspace,
|
|
161
|
+
WorkspaceBuild,
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class Sandscale:
|
|
166
|
+
"""The Sandscale client.
|
|
167
|
+
|
|
168
|
+
:param api_key: a Sandscale API key (default ``$SANDSCALE_API_KEY``); give this or ``token``.
|
|
169
|
+
:param token: the person's own sign-in access token, or a function returning a current one.
|
|
170
|
+
:param base_url: default ``$SANDSCALE_BASE_URL``, else ``https://api.sandscale.dev``.
|
|
171
|
+
:param org_id: sent as ``X-Org-ID`` and used by the workspace and build host routes
|
|
172
|
+
(default ``$SANDSCALE_ORG_ID``).
|
|
173
|
+
:param region: region of every call that names none (``"us"`` or ``"eu"``).
|
|
174
|
+
:param region_urls: explicit API URL per region instead of the server's region list.
|
|
175
|
+
:param timeout: per-request timeout in seconds.
|
|
176
|
+
:param max_retries: retries of safe (GET) calls after a connection error, 429, 502, 503, 504.
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
def __init__(
|
|
180
|
+
self,
|
|
181
|
+
*,
|
|
182
|
+
api_key: Optional[str] = None,
|
|
183
|
+
token: Optional[TokenSource] = None,
|
|
184
|
+
base_url: Optional[str] = None,
|
|
185
|
+
org_id: Optional[str] = None,
|
|
186
|
+
region: Optional[str] = None,
|
|
187
|
+
region_urls: Optional[Mapping[str, str]] = None,
|
|
188
|
+
timeout: float = 60.0,
|
|
189
|
+
max_retries: int = 2,
|
|
190
|
+
http_client: Optional[httpx.Client] = None,
|
|
191
|
+
) -> None:
|
|
192
|
+
self.transport = Transport(
|
|
193
|
+
api_key=api_key,
|
|
194
|
+
token=token,
|
|
195
|
+
base_url=base_url,
|
|
196
|
+
org_id=org_id,
|
|
197
|
+
region=region,
|
|
198
|
+
region_urls=region_urls,
|
|
199
|
+
timeout=timeout,
|
|
200
|
+
max_retries=max_retries,
|
|
201
|
+
http_client=http_client,
|
|
202
|
+
)
|
|
203
|
+
self.sandboxes = Sandboxes(self.transport)
|
|
204
|
+
#: Persistent volumes; attach them with ``sandboxes.attach_volume``.
|
|
205
|
+
self.volumes = Volumes(self.transport)
|
|
206
|
+
#: Dependency caches; restore and save them with ``sandboxes.restore_cache`` and ``save_cache``.
|
|
207
|
+
self.caches = Caches(self.transport)
|
|
208
|
+
self.workspaces = Workspaces(self.transport)
|
|
209
|
+
self.build_hosts = BuildHosts(self.transport, self.workspaces)
|
|
210
|
+
self.snapshots = Snapshots(self.transport)
|
|
211
|
+
self.templates = Templates(self.transport)
|
|
212
|
+
self.policy = Policy(self.transport)
|
|
213
|
+
self.webhooks = Webhooks(self.transport)
|
|
214
|
+
self.traces = Traces(self.transport)
|
|
215
|
+
self.objects = Objects(self.transport)
|
|
216
|
+
self.lab_hosts = LabHosts(self.transport)
|
|
217
|
+
self.agent_cloud = AgentCloud(self.transport)
|
|
218
|
+
self.account = Account(self.transport)
|
|
219
|
+
#: Code mode tasks (``execute`` starts one).
|
|
220
|
+
self.tasks = Tasks(self.transport)
|
|
221
|
+
#: What a code mode script must ask a person about first.
|
|
222
|
+
self.code_policy = CodePolicyService(self.transport)
|
|
223
|
+
self._api: Optional[Api] = None
|
|
224
|
+
|
|
225
|
+
@property
|
|
226
|
+
def api(self) -> Api:
|
|
227
|
+
"""The typed Sandscale API, ``api.<namespace>.<function>(**args)``: every operation a code mode
|
|
228
|
+
script can call, called directly from Python as this client."""
|
|
229
|
+
if self._api is None:
|
|
230
|
+
self._api = Api(self.transport)
|
|
231
|
+
return self._api
|
|
232
|
+
|
|
233
|
+
def execute(
|
|
234
|
+
self,
|
|
235
|
+
code: str,
|
|
236
|
+
*,
|
|
237
|
+
wait_seconds: float = 30,
|
|
238
|
+
poll_interval: float = 1.0,
|
|
239
|
+
timeout: Optional[float] = None,
|
|
240
|
+
wait_for_approval: bool = False,
|
|
241
|
+
raise_on_failure: bool = True,
|
|
242
|
+
idempotency_key: Optional[str] = None,
|
|
243
|
+
) -> Task:
|
|
244
|
+
"""Runs a TypeScript or JavaScript script on the server against your typed API (code mode) and
|
|
245
|
+
returns its task once it succeeded or failed.
|
|
246
|
+
|
|
247
|
+
The script sees ``sandscale.<namespace>.<fn>(args)`` and ``vault.ref(...)``, may ``await`` and
|
|
248
|
+
``return``; its return value is ``task.result``. The server answers within ``wait_seconds``
|
|
249
|
+
(at most 30) or the SDK reads the task again until it ends. A task that waits on a person's
|
|
250
|
+
approval is returned in state ``awaiting_approval`` unless ``wait_for_approval``. A failed
|
|
251
|
+
task raises :class:`TaskFailedError` (``raise_on_failure=False`` returns it instead);
|
|
252
|
+
``timeout`` (seconds, default none) raises :class:`TaskTimeoutError` with the task still
|
|
253
|
+
running on the server."""
|
|
254
|
+
return _execute(
|
|
255
|
+
self.transport,
|
|
256
|
+
self.tasks,
|
|
257
|
+
code,
|
|
258
|
+
wait_seconds=wait_seconds,
|
|
259
|
+
poll_interval=poll_interval,
|
|
260
|
+
timeout=timeout,
|
|
261
|
+
wait_for_approval=wait_for_approval,
|
|
262
|
+
raise_on_failure=raise_on_failure,
|
|
263
|
+
idempotency_key=idempotency_key,
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
def search(self, code: str) -> SearchResult:
|
|
267
|
+
"""Runs a script against the typed API as data (``api.namespaces[ns].functions[fn]``,
|
|
268
|
+
``api.find("words", limit)``) and returns what it returned. A script failure raises
|
|
269
|
+
:class:`InvalidRequestError` (422) with ``details`` ``{line, column}``."""
|
|
270
|
+
return _search(self.transport, code)
|
|
271
|
+
|
|
272
|
+
def call(
|
|
273
|
+
self,
|
|
274
|
+
operation: str,
|
|
275
|
+
args: Optional[Mapping[str, Any]] = None,
|
|
276
|
+
*,
|
|
277
|
+
region: Optional[str] = None,
|
|
278
|
+
idempotency_key: Optional[str] = None,
|
|
279
|
+
) -> Any:
|
|
280
|
+
"""Runs any operation of the Sandscale API by its catalogue name (``operations()`` lists them with their
|
|
281
|
+
arguments), for what the typed methods do not cover. The server decides everything else."""
|
|
282
|
+
return _call(self.transport, operation, args, region=region, idempotency_key=idempotency_key)
|
|
283
|
+
|
|
284
|
+
def capabilities(self, *, region: Optional[str] = None) -> Capabilities:
|
|
285
|
+
"""What this account can do here now: the plan, its limits (vCPU, memory, concurrent boxes, time to
|
|
286
|
+
live, network modes), the templates that start and what is in them, the regions and the vCPU-hour
|
|
287
|
+
balance with the time it resets. The server decides every figure."""
|
|
288
|
+
return _capabilities(self.transport, region)
|
|
289
|
+
|
|
290
|
+
def close(self) -> None:
|
|
291
|
+
self.transport.close()
|
|
292
|
+
|
|
293
|
+
def __enter__(self) -> "Sandscale":
|
|
294
|
+
return self
|
|
295
|
+
|
|
296
|
+
def __exit__(self, *exc: Any) -> None:
|
|
297
|
+
self.close()
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
__all__ = [
|
|
301
|
+
"Api",
|
|
302
|
+
"ApiArgumentError",
|
|
303
|
+
"ApiErrorInfo",
|
|
304
|
+
"ApiFunction",
|
|
305
|
+
"ApiNamespace",
|
|
306
|
+
"CodePolicy",
|
|
307
|
+
"CodePolicyService",
|
|
308
|
+
"ConsoleLine",
|
|
309
|
+
"PendingApproval",
|
|
310
|
+
"SearchResult",
|
|
311
|
+
"Task",
|
|
312
|
+
"TaskError",
|
|
313
|
+
"TaskFailedError",
|
|
314
|
+
"TaskTimeoutError",
|
|
315
|
+
"Tasks",
|
|
316
|
+
"operations",
|
|
317
|
+
"AccountExistsError",
|
|
318
|
+
"Capabilities",
|
|
319
|
+
"ProcessInfo",
|
|
320
|
+
"ProcessLogs",
|
|
321
|
+
"ProcessStart",
|
|
322
|
+
"CodeModeUsage",
|
|
323
|
+
"DailyUsage",
|
|
324
|
+
"FairUseLimit",
|
|
325
|
+
"LimitInfo",
|
|
326
|
+
"PlanRefusal",
|
|
327
|
+
"FreeAlreadyClaimedError",
|
|
328
|
+
"FreeDailyLimitError",
|
|
329
|
+
"FreeMonthlyLimitError",
|
|
330
|
+
"FreeNewAccountLimitError",
|
|
331
|
+
"GithubLinkStart",
|
|
332
|
+
"Identity",
|
|
333
|
+
"PeriodUsage",
|
|
334
|
+
"RampUsage",
|
|
335
|
+
"UsageLimits",
|
|
336
|
+
"Sandscale",
|
|
337
|
+
"BUILTIN_TEMPLATES",
|
|
338
|
+
"Sandboxes",
|
|
339
|
+
"Volumes",
|
|
340
|
+
"Caches",
|
|
341
|
+
"Workspaces",
|
|
342
|
+
"BuildHosts",
|
|
343
|
+
"Transport",
|
|
344
|
+
"DEFAULT_BASE_URL",
|
|
345
|
+
"SANDSCALE_REGION_URLS",
|
|
346
|
+
"VERSION",
|
|
347
|
+
"SandscaleError",
|
|
348
|
+
"ConfigurationError",
|
|
349
|
+
"APIConnectionError",
|
|
350
|
+
"AuthenticationError",
|
|
351
|
+
"ConflictError",
|
|
352
|
+
"EntitlementError",
|
|
353
|
+
"InvalidRequestError",
|
|
354
|
+
"KillSwitchError",
|
|
355
|
+
"LimitExceededError",
|
|
356
|
+
"NotFoundError",
|
|
357
|
+
"PermissionDeniedError",
|
|
358
|
+
"RateLimitError",
|
|
359
|
+
"RegionError",
|
|
360
|
+
"ServerError",
|
|
361
|
+
"DependencyCache",
|
|
362
|
+
"CacheResult",
|
|
363
|
+
"ConnectInfo",
|
|
364
|
+
"FileEntry",
|
|
365
|
+
"Lease",
|
|
366
|
+
"LeaseConnectInfo",
|
|
367
|
+
"ListResult",
|
|
368
|
+
"OutputChunk",
|
|
369
|
+
"Pool",
|
|
370
|
+
"RegionPage",
|
|
371
|
+
"RunEnd",
|
|
372
|
+
"RunOutput",
|
|
373
|
+
"RunResult",
|
|
374
|
+
"Sandbox",
|
|
375
|
+
"Snapshot",
|
|
376
|
+
"SandboxActivity",
|
|
377
|
+
"ActivityDay",
|
|
378
|
+
"SSHCertificate",
|
|
379
|
+
"VaultEnvRef",
|
|
380
|
+
"Volume",
|
|
381
|
+
"VolumeAttachment",
|
|
382
|
+
"Workspace",
|
|
383
|
+
"WorkspaceBuild",
|
|
384
|
+
"Account",
|
|
385
|
+
"TraceCost",
|
|
386
|
+
"NoncurrentVersionExpiration",
|
|
387
|
+
"BucketUsage",
|
|
388
|
+
"BucketEndpoints",
|
|
389
|
+
"ApiKeyLimits",
|
|
390
|
+
"AppShareResult",
|
|
391
|
+
"Policy",
|
|
392
|
+
"Snapshots",
|
|
393
|
+
"Templates",
|
|
394
|
+
"Traces",
|
|
395
|
+
"Webhooks",
|
|
396
|
+
"Objects",
|
|
397
|
+
"LabHosts",
|
|
398
|
+
"AgentCloud",
|
|
399
|
+
"verify_webhook_signature",
|
|
400
|
+
"SandboxWakingError",
|
|
401
|
+
"ServiceUnavailableError",
|
|
402
|
+
"AccessKey",
|
|
403
|
+
"AgentTask",
|
|
404
|
+
"ApiKey",
|
|
405
|
+
"ApiKeyList",
|
|
406
|
+
"BackupVerification",
|
|
407
|
+
"Billing",
|
|
408
|
+
"Bucket",
|
|
409
|
+
"BucketList",
|
|
410
|
+
"CacheEntry",
|
|
411
|
+
"CacheView",
|
|
412
|
+
"Checkout",
|
|
413
|
+
"CreatedAccessKey",
|
|
414
|
+
"CreatedApiKey",
|
|
415
|
+
"CreatedWebhook",
|
|
416
|
+
"CreditBalance",
|
|
417
|
+
"DefaultRetention",
|
|
418
|
+
"LabHost",
|
|
419
|
+
"LeaseArtifact",
|
|
420
|
+
"LeaseRun",
|
|
421
|
+
"LifecycleRule",
|
|
422
|
+
"ObjectsLimits",
|
|
423
|
+
"OpenLink",
|
|
424
|
+
"PlanOffer",
|
|
425
|
+
"PlanState",
|
|
426
|
+
"PortExposure",
|
|
427
|
+
"PreviewLink",
|
|
428
|
+
"RegionInfo",
|
|
429
|
+
"SandboxPolicy",
|
|
430
|
+
"SandboxSshCertificate",
|
|
431
|
+
"SandboxSshInfo",
|
|
432
|
+
"SnapshotList",
|
|
433
|
+
"SnapshotUsage",
|
|
434
|
+
"Template",
|
|
435
|
+
"TemplateBuildStatus",
|
|
436
|
+
"Trace",
|
|
437
|
+
"TraceBox",
|
|
438
|
+
"TraceCommand",
|
|
439
|
+
"TraceEvent",
|
|
440
|
+
"TraceExport",
|
|
441
|
+
"TraceExportTest",
|
|
442
|
+
"TraceFile",
|
|
443
|
+
"TraceSpan",
|
|
444
|
+
"TraceSummary",
|
|
445
|
+
"Usage",
|
|
446
|
+
"Webhook",
|
|
447
|
+
"WebhookDelivery",
|
|
448
|
+
"WorkspaceApp",
|
|
449
|
+
"WorkspaceBackup",
|
|
450
|
+
]
|
sandscale/_account.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# Copyright 2026 Neural Inverse
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The account: Sandscale billing, usage, regions and API keys."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from typing import Any, Optional, Sequence, Union
|
|
9
|
+
|
|
10
|
+
from ._transport import Transport, seg
|
|
11
|
+
from .admin_models import ApiKey, ApiKeyLimits, ApiKeyList, Billing, Checkout, CreatedApiKey, GithubLinkStart, Identity, PlanState, RegionInfo, Usage
|
|
12
|
+
|
|
13
|
+
Raw = dict[str, Any]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _body(**fields: Any) -> Raw:
|
|
17
|
+
return {k: v for k, v in fields.items() if v is not None}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Account:
|
|
21
|
+
"""Plan, credits, usage, regions and personal API keys. The server decides every plan and
|
|
22
|
+
price; this class only calls it. Plan changes and API keys need a signed-in person's token."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, t: Transport) -> None:
|
|
25
|
+
self._t = t
|
|
26
|
+
|
|
27
|
+
def _org(self) -> str:
|
|
28
|
+
return seg(self._t.require_org())
|
|
29
|
+
|
|
30
|
+
# billing
|
|
31
|
+
def billing(self, *, region: Optional[str] = None) -> Billing:
|
|
32
|
+
"""Plan state, the offer in force, the credit balance and the price book."""
|
|
33
|
+
return Billing.from_raw(self._t.request("GET", f"/api/v1/orgs/{self._org()}/sandscale/billing", region=region))
|
|
34
|
+
|
|
35
|
+
def change_plan(
|
|
36
|
+
self,
|
|
37
|
+
*,
|
|
38
|
+
plan: str,
|
|
39
|
+
interval: Optional[str] = None,
|
|
40
|
+
seats: Optional[int] = None,
|
|
41
|
+
region: Optional[str] = None,
|
|
42
|
+
) -> PlanState:
|
|
43
|
+
"""Changes a live subscription: an upgrade or more seats is charged first and applies only when
|
|
44
|
+
the payment succeeds, a downgrade or fewer seats at the period end.
|
|
45
|
+
|
|
46
|
+
Refused 402 ``payment_declined``, ``payment_authentication_required`` or
|
|
47
|
+
``payment_method_required`` (nothing changed; the error body names ``next_step`` and, for
|
|
48
|
+
authentication, ``hosted_invoice_url``), and 409 ``charge_in_progress``,
|
|
49
|
+
``charge_not_applied`` or ``pending_change``.
|
|
50
|
+
"""
|
|
51
|
+
raw = self._t.request(
|
|
52
|
+
"POST",
|
|
53
|
+
f"/api/v1/orgs/{self._org()}/sandscale/billing/plan",
|
|
54
|
+
region=region,
|
|
55
|
+
json_body=_body(plan=plan, interval=interval, seats=seats),
|
|
56
|
+
)
|
|
57
|
+
return PlanState.from_raw(raw.get("state") if isinstance(raw.get("state"), dict) else raw)
|
|
58
|
+
|
|
59
|
+
def set_overage(self, enabled: bool, *, region: Optional[str] = None) -> PlanState:
|
|
60
|
+
"""Turns overage on or off (refused 409 ``overage_not_in_plan`` on Free)."""
|
|
61
|
+
raw = self._t.request(
|
|
62
|
+
"PUT", f"/api/v1/orgs/{self._org()}/sandscale/billing/overage", region=region, json_body={"enabled": enabled}
|
|
63
|
+
)
|
|
64
|
+
return PlanState.from_raw(raw.get("state") if isinstance(raw.get("state"), dict) else raw)
|
|
65
|
+
|
|
66
|
+
def cancel_pending_plan_change(self, *, region: Optional[str] = None) -> PlanState:
|
|
67
|
+
"""Withdraws a waiting downgrade or seat decrease."""
|
|
68
|
+
raw = self._t.request("DELETE", f"/api/v1/orgs/{self._org()}/sandscale/billing/plan/pending", region=region)
|
|
69
|
+
body: Raw = raw if isinstance(raw, dict) else {}
|
|
70
|
+
state = body.get("state")
|
|
71
|
+
return PlanState.from_raw(state if isinstance(state, dict) else body)
|
|
72
|
+
|
|
73
|
+
def checkout(
|
|
74
|
+
self,
|
|
75
|
+
*,
|
|
76
|
+
plan: str,
|
|
77
|
+
interval: str,
|
|
78
|
+
seats: Optional[int] = None,
|
|
79
|
+
region: Optional[str] = None,
|
|
80
|
+
) -> Checkout:
|
|
81
|
+
"""Starts a Checkout session for Pro or Team; open ``url`` to pay."""
|
|
82
|
+
raw = self._t.request(
|
|
83
|
+
"POST",
|
|
84
|
+
f"/api/v1/orgs/{self._org()}/sandscale/billing/checkout",
|
|
85
|
+
region=region,
|
|
86
|
+
json_body=_body(plan=plan, interval=interval, seats=seats),
|
|
87
|
+
)
|
|
88
|
+
return Checkout.from_raw(raw)
|
|
89
|
+
|
|
90
|
+
# usage and regions
|
|
91
|
+
def usage(self, *, region: Optional[str] = None) -> Usage:
|
|
92
|
+
"""The month's usage across every region."""
|
|
93
|
+
return Usage.from_raw(self._t.request("GET", "/api/v1/sandscale/usage", region=region))
|
|
94
|
+
|
|
95
|
+
def identity(self, *, region: Optional[str] = None) -> Identity:
|
|
96
|
+
"""What your login linked: a GitHub account and a verified card lift the new-account ramp."""
|
|
97
|
+
return Identity.from_raw(self._t.request("GET", "/api/v1/sandscale/identity", region=region))
|
|
98
|
+
|
|
99
|
+
def github_start(self, *, region: Optional[str] = None) -> GithubLinkStart:
|
|
100
|
+
"""Starts linking a GitHub account (a person signed in, not an API key). Send the person to
|
|
101
|
+
``authorize_url``; GitHub returns them with a code that :meth:`github_complete` finishes with ``state``.
|
|
102
|
+
A GitHub account another Sandscale login holds is refused ``account_exists``."""
|
|
103
|
+
return GithubLinkStart.from_raw(self._t.request("POST", "/api/v1/sandscale/identity/github/start", region=region))
|
|
104
|
+
|
|
105
|
+
def github_complete(self, code: str, state: str, *, region: Optional[str] = None) -> Identity:
|
|
106
|
+
"""Finishes a GitHub link with the code GitHub returned and the ``state`` :meth:`github_start` gave."""
|
|
107
|
+
return Identity.from_raw(
|
|
108
|
+
self._t.request("POST", "/api/v1/sandscale/identity/github/complete", json_body={"code": code, "state": state}, region=region)
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
def regions(self) -> list[RegionInfo]:
|
|
112
|
+
"""The regions the server lists (public)."""
|
|
113
|
+
raw = self._t.request("GET", "/api/v1/regions")
|
|
114
|
+
return [RegionInfo.from_raw(r) for r in raw.get("regions") or [] if isinstance(r, dict)]
|
|
115
|
+
|
|
116
|
+
# API keys
|
|
117
|
+
def list_api_keys(self, *, region: Optional[str] = None) -> ApiKeyList:
|
|
118
|
+
raw = self._t.request("GET", "/api/v1/account/api-keys", region=region)
|
|
119
|
+
limits = raw.get("limits") or {}
|
|
120
|
+
return ApiKeyList(
|
|
121
|
+
api_keys=[ApiKey.from_raw(k) for k in raw.get("api_keys") or []],
|
|
122
|
+
limits=ApiKeyLimits(max_days=limits.get("max_days"), max_active=limits.get("max_active")),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def create_api_key(
|
|
126
|
+
self,
|
|
127
|
+
*,
|
|
128
|
+
name: str,
|
|
129
|
+
expires_at: Union[datetime, str],
|
|
130
|
+
scopes: Optional[Sequence[str]] = None,
|
|
131
|
+
region: Optional[str] = None,
|
|
132
|
+
) -> CreatedApiKey:
|
|
133
|
+
"""Creates a personal API key. The key itself is shown once, on the returned object
|
|
134
|
+
(not in its ``repr``); store it where it belongs and never log it."""
|
|
135
|
+
when = expires_at.isoformat() if isinstance(expires_at, datetime) else expires_at
|
|
136
|
+
body = _body(name=name, scopes=list(scopes) if scopes is not None else None, expires_at=when)
|
|
137
|
+
return CreatedApiKey.from_raw(self._t.request("POST", "/api/v1/account/api-keys", region=region, json_body=body))
|
|
138
|
+
|
|
139
|
+
def rotate_api_key(self, key_id: str, *, overlap_seconds: Optional[int] = None, region: Optional[str] = None) -> CreatedApiKey:
|
|
140
|
+
"""Replaces a key; the old one keeps working for ``overlap_seconds``."""
|
|
141
|
+
raw = self._t.request(
|
|
142
|
+
"POST",
|
|
143
|
+
f"/api/v1/account/api-keys/{seg(key_id)}/rotate",
|
|
144
|
+
region=region,
|
|
145
|
+
json_body=_body(overlap_seconds=overlap_seconds),
|
|
146
|
+
)
|
|
147
|
+
return CreatedApiKey.from_raw(raw)
|
|
148
|
+
|
|
149
|
+
def delete_api_key(self, key_id: str, *, region: Optional[str] = None) -> None:
|
|
150
|
+
self._t.request("DELETE", f"/api/v1/account/api-keys/{seg(key_id)}", region=region)
|