mistrive-sutra 0.2.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.
Files changed (72) hide show
  1. mistrive/sutra/__init__.py +397 -0
  2. mistrive/sutra/_calls.py +138 -0
  3. mistrive/sutra/_client.py +148 -0
  4. mistrive/sutra/_config.py +138 -0
  5. mistrive/sutra/_errors.py +510 -0
  6. mistrive/sutra/_files.py +915 -0
  7. mistrive/sutra/_gen/__init__.py +0 -0
  8. mistrive/sutra/_gen/sutra/__init__.py +0 -0
  9. mistrive/sutra/_gen/sutra/sandbox/__init__.py +0 -0
  10. mistrive/sutra/_gen/sutra/sandbox/v1/__init__.py +0 -0
  11. mistrive/sutra/_gen/sutra/sandbox/v1/file_service_pb2.py +339 -0
  12. mistrive/sutra/_gen/sutra/sandbox/v1/file_service_pb2_grpc.py +644 -0
  13. mistrive/sutra/_gen/sutra/sandbox/v1/operation_pb2.py +49 -0
  14. mistrive/sutra/_gen/sutra/sandbox/v1/operation_pb2_grpc.py +24 -0
  15. mistrive/sutra/_gen/sutra/sandbox/v1/port_service_pb2.py +118 -0
  16. mistrive/sutra/_gen/sutra/sandbox/v1/port_service_pb2_grpc.py +409 -0
  17. mistrive/sutra/_gen/sutra/sandbox/v1/process_service_pb2.py +299 -0
  18. mistrive/sutra/_gen/sutra/sandbox/v1/process_service_pb2_grpc.py +717 -0
  19. mistrive/sutra/_gen/sutra/sandbox/v1/resources_pb2.py +140 -0
  20. mistrive/sutra/_gen/sutra/sandbox/v1/resources_pb2_grpc.py +24 -0
  21. mistrive/sutra/_gen/sutra/sandbox/v1/sandbox_policy_service_pb2.py +101 -0
  22. mistrive/sutra/_gen/sutra/sandbox/v1/sandbox_policy_service_pb2_grpc.py +165 -0
  23. mistrive/sutra/_gen/sutra/sandbox/v1/sandbox_service_pb2.py +237 -0
  24. mistrive/sutra/_gen/sutra/sandbox/v1/sandbox_service_pb2_grpc.py +400 -0
  25. mistrive/sutra/_gen/sutra/sandbox/v1/snapshot_service_pb2.py +128 -0
  26. mistrive/sutra/_gen/sutra/sandbox/v1/snapshot_service_pb2_grpc.py +290 -0
  27. mistrive/sutra/_gen/sutra/sandbox/v1/ssh_access_service_pb2.py +127 -0
  28. mistrive/sutra/_gen/sutra/sandbox/v1/ssh_access_service_pb2_grpc.py +216 -0
  29. mistrive/sutra/_gen/sutra/sandbox/v1/template_service_pb2.py +84 -0
  30. mistrive/sutra/_gen/sutra/sandbox/v1/template_service_pb2_grpc.py +157 -0
  31. mistrive/sutra/_gen/sutra/sandbox/v1/volume_service_pb2.py +136 -0
  32. mistrive/sutra/_gen/sutra/sandbox/v1/volume_service_pb2_grpc.py +292 -0
  33. mistrive/sutra/_gen/sutra/workloads/__init__.py +0 -0
  34. mistrive/sutra/_gen/sutra/workloads/v1/__init__.py +0 -0
  35. mistrive/sutra/_gen/sutra/workloads/v1/agent_service_pb2.py +155 -0
  36. mistrive/sutra/_gen/sutra/workloads/v1/agent_service_pb2_grpc.py +346 -0
  37. mistrive/sutra/_gen/sutra/workloads/v1/error_reason_pb2.py +37 -0
  38. mistrive/sutra/_gen/sutra/workloads/v1/error_reason_pb2_grpc.py +24 -0
  39. mistrive/sutra/_gen/sutra/workloads/v1/invocation_service_pb2.py +122 -0
  40. mistrive/sutra/_gen/sutra/workloads/v1/invocation_service_pb2_grpc.py +254 -0
  41. mistrive/sutra/_gen/sutra/workloads/v1/operation_pb2.py +49 -0
  42. mistrive/sutra/_gen/sutra/workloads/v1/operation_pb2_grpc.py +24 -0
  43. mistrive/sutra/_gen/sutra/workloads/v1/resources_pb2.py +48 -0
  44. mistrive/sutra/_gen/sutra/workloads/v1/resources_pb2_grpc.py +24 -0
  45. mistrive/sutra/_gen/sutra/workloads/v1/revision_service_pb2.py +192 -0
  46. mistrive/sutra/_gen/sutra/workloads/v1/revision_service_pb2_grpc.py +203 -0
  47. mistrive/sutra/_gen/sutra/workloads/v1/rollout_service_pb2.py +118 -0
  48. mistrive/sutra/_gen/sutra/workloads/v1/rollout_service_pb2_grpc.py +251 -0
  49. mistrive/sutra/_gen/sutra/workloads/v1/service_service_pb2.py +173 -0
  50. mistrive/sutra/_gen/sutra/workloads/v1/service_service_pb2_grpc.py +399 -0
  51. mistrive/sutra/_gen/sutra/workloads/v1/session_service_pb2.py +141 -0
  52. mistrive/sutra/_gen/sutra/workloads/v1/session_service_pb2_grpc.py +299 -0
  53. mistrive/sutra/_invocations.py +366 -0
  54. mistrive/sutra/_operations.py +143 -0
  55. mistrive/sutra/_operations_api.py +240 -0
  56. mistrive/sutra/_pages.py +56 -0
  57. mistrive/sutra/_ports.py +399 -0
  58. mistrive/sutra/_processes.py +672 -0
  59. mistrive/sutra/_sandbox_policies.py +276 -0
  60. mistrive/sutra/_sandboxes.py +928 -0
  61. mistrive/sutra/_snapshots.py +323 -0
  62. mistrive/sutra/_ssh_access.py +287 -0
  63. mistrive/sutra/_templates.py +141 -0
  64. mistrive/sutra/_transport.py +150 -0
  65. mistrive/sutra/_values.py +119 -0
  66. mistrive/sutra/_volumes.py +357 -0
  67. mistrive/sutra/_workload_specs.py +638 -0
  68. mistrive/sutra/_workloads.py +1922 -0
  69. mistrive/sutra/py.typed +0 -0
  70. mistrive_sutra-0.2.0.dist-info/METADATA +52 -0
  71. mistrive_sutra-0.2.0.dist-info/RECORD +72 -0
  72. mistrive_sutra-0.2.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,397 @@
1
+ # OWNING_DOC: cloud/sutra/sdk/README.md
2
+ """mistrive.sutra: the Python client of the Sutra platform, sync (``Sutra``)
3
+ and asyncio (``AsyncSutra``)."""
4
+
5
+ from ._client import AsyncSutra, Sutra
6
+ from ._config import Endpoints
7
+ from ._operations_api import AsyncOperation, AsyncOperations, Operation, Operations
8
+ from ._files import (
9
+ ArchiveFormat,
10
+ AsyncFiles,
11
+ FileContentKind,
12
+ FileCopyResult,
13
+ FileCopyState,
14
+ FileInfo,
15
+ FileReplacement,
16
+ Files,
17
+ FileSearchMatch,
18
+ FileType,
19
+ FindResult,
20
+ ReadOptions,
21
+ ReadResult,
22
+ ReplaceResult,
23
+ SearchResult,
24
+ WriteOptions,
25
+ WriteResult,
26
+ )
27
+ from ._pages import AsyncPage, Page
28
+ from ._ports import AsyncPort, AsyncPorts, DnsRecord, Port, PortHost, PortHostState, Ports, PortState
29
+ from ._ssh_access import (
30
+ AsyncSshAccess,
31
+ SshAccess,
32
+ SshAccessInfo,
33
+ SshAccessState,
34
+ SshCredential,
35
+ SshPasswordMode,
36
+ SshRoute,
37
+ )
38
+ from ._processes import (
39
+ AsyncProcess,
40
+ AsyncProcesses,
41
+ CodeLanguage,
42
+ Exit,
43
+ ExitReason,
44
+ OutputChunk,
45
+ OutputPage,
46
+ OutputStream,
47
+ Process,
48
+ ProcessCode,
49
+ Processes,
50
+ ProcessInput,
51
+ ProcessKind,
52
+ ProcessResult,
53
+ ProcessState,
54
+ Signal,
55
+ )
56
+ from ._sandboxes import (
57
+ AsyncSandbox,
58
+ AsyncSandboxes,
59
+ Identity,
60
+ IdentityMode,
61
+ IntegrationRef,
62
+ Lifecycle,
63
+ LifecycleAction,
64
+ LifecycleSource,
65
+ LifecycleSources,
66
+ LifecycleUpdate,
67
+ Network,
68
+ Placement,
69
+ PortAccess,
70
+ PortProtocol,
71
+ PortSpec,
72
+ PreservedLevel,
73
+ Resources,
74
+ Sandbox,
75
+ SandboxLifecycle,
76
+ Sandboxes,
77
+ SandboxSource,
78
+ SandboxState,
79
+ SandboxStateReason,
80
+ Timeout,
81
+ )
82
+ from ._sandbox_policies import (
83
+ AsyncSandboxPolicies,
84
+ AsyncSandboxPolicy,
85
+ LifecycleLimits,
86
+ LifecycleLimitsUpdate,
87
+ SandboxPolicies,
88
+ SandboxPolicy,
89
+ )
90
+ from ._snapshots import AsyncSnapshot, AsyncSnapshots, Snapshot, Snapshots, SnapshotState
91
+ from ._templates import AsyncTemplates, Template, Templates
92
+ from ._volumes import AsyncVolume, AsyncVolumes, Volume, VolumeAccessMode, VolumeKind, Volumes, VolumeState
93
+ from ._invocations import AsyncInvocationStream, InvocationResult, InvocationStream
94
+ from ._workload_specs import (
95
+ AgentState,
96
+ Creator,
97
+ HealthCheck,
98
+ InvocationOutputChunk,
99
+ InvocationState,
100
+ ProcessSpec,
101
+ RevisionProtocol,
102
+ RevisionSource,
103
+ RevisionSpec,
104
+ RevisionState,
105
+ RevisionStateReason,
106
+ RolloutState,
107
+ RolloutStateReason,
108
+ Scaling,
109
+ ServiceState,
110
+ ServiceStateReason,
111
+ SessionSettings,
112
+ SessionState,
113
+ SessionStateReason,
114
+ SignedUri,
115
+ TrafficTarget,
116
+ VolumeMount,
117
+ )
118
+ from ._workloads import (
119
+ Agent,
120
+ Agents,
121
+ AsyncAgent,
122
+ AsyncAgents,
123
+ AsyncInvocation,
124
+ AsyncInvocations,
125
+ AsyncRevision,
126
+ AsyncRevisions,
127
+ AsyncRollout,
128
+ AsyncRollouts,
129
+ AsyncService,
130
+ AsyncServices,
131
+ AsyncSession,
132
+ AsyncSessions,
133
+ AsyncWorkloads,
134
+ Deployment,
135
+ Invocation,
136
+ Invocations,
137
+ Revision,
138
+ Revisions,
139
+ Rollout,
140
+ Rollouts,
141
+ Service,
142
+ Services,
143
+ Session,
144
+ Sessions,
145
+ Workloads,
146
+ )
147
+ from ._errors import (
148
+ ApiError,
149
+ ConfigurationError,
150
+ CredentialInvalidError,
151
+ ErrorResource,
152
+ EtagMismatchError,
153
+ ExecutableNotFoundError,
154
+ FieldInvalidError,
155
+ FieldNotSupportedError,
156
+ FieldViolation,
157
+ FilterInvalidError,
158
+ IntegrationScopeExceededError,
159
+ ListingTooLargeError,
160
+ NoCapacityError,
161
+ OperationTimeoutError,
162
+ PageTokenInvalidError,
163
+ PermissionMissingError,
164
+ ProcessStartFailedError,
165
+ QuotaExceededError,
166
+ QuotaViolation,
167
+ RateLimitedError,
168
+ RegistrationRejectedError,
169
+ RequestIdReusedError,
170
+ ResourceExistsError,
171
+ ResourceNotFoundError,
172
+ SandboxFailedError,
173
+ SandboxIdRetiredError,
174
+ VolumeIdRetiredError,
175
+ SandboxLaunchFailedError,
176
+ LifecycleLimitExceededError,
177
+ AboveOrganizationLimitError,
178
+ SandboxNotRunningError,
179
+ SandboxOwnedError,
180
+ ServiceUnavailableError,
181
+ SutraError,
182
+ AgentNotReadyError,
183
+ InvocationCancelledError,
184
+ InvocationOutputNotRetainedError,
185
+ InvocationTimeoutError,
186
+ InvokeDeniedError,
187
+ RolloutInProgressError,
188
+ SessionBusyError,
189
+ SessionIdInvalidError,
190
+ SessionLimitError,
191
+ SessionSubjectMismatchError,
192
+ TimeoutOutOfRangeError,
193
+ WorkloadNotReadyError,
194
+ )
195
+
196
+ __all__ = [
197
+ "AboveOrganizationLimitError",
198
+ "Agent",
199
+ "AgentNotReadyError",
200
+ "AgentState",
201
+ "Agents",
202
+ "ApiError",
203
+ "ArchiveFormat",
204
+ "AsyncAgent",
205
+ "AsyncAgents",
206
+ "AsyncFiles",
207
+ "AsyncInvocation",
208
+ "AsyncInvocationStream",
209
+ "AsyncInvocations",
210
+ "AsyncOperation",
211
+ "AsyncOperations",
212
+ "AsyncPage",
213
+ "AsyncPort",
214
+ "AsyncPorts",
215
+ "AsyncProcess",
216
+ "AsyncProcesses",
217
+ "AsyncRevision",
218
+ "AsyncRevisions",
219
+ "AsyncRollout",
220
+ "AsyncRollouts",
221
+ "AsyncSandbox",
222
+ "AsyncSandboxPolicies",
223
+ "AsyncSandboxPolicy",
224
+ "AsyncSandboxes",
225
+ "AsyncService",
226
+ "AsyncServices",
227
+ "AsyncSession",
228
+ "AsyncSessions",
229
+ "AsyncSnapshot",
230
+ "AsyncSnapshots",
231
+ "AsyncSshAccess",
232
+ "AsyncSutra",
233
+ "AsyncTemplates",
234
+ "AsyncVolume",
235
+ "AsyncVolumes",
236
+ "AsyncWorkloads",
237
+ "CodeLanguage",
238
+ "ConfigurationError",
239
+ "Creator",
240
+ "CredentialInvalidError",
241
+ "Deployment",
242
+ "DnsRecord",
243
+ "Endpoints",
244
+ "ErrorResource",
245
+ "EtagMismatchError",
246
+ "ExecutableNotFoundError",
247
+ "Exit",
248
+ "ExitReason",
249
+ "FieldInvalidError",
250
+ "FieldNotSupportedError",
251
+ "FieldViolation",
252
+ "FileContentKind",
253
+ "FileCopyResult",
254
+ "FileCopyState",
255
+ "FileInfo",
256
+ "FileReplacement",
257
+ "FileSearchMatch",
258
+ "FileType",
259
+ "Files",
260
+ "FilterInvalidError",
261
+ "FindResult",
262
+ "HealthCheck",
263
+ "Identity",
264
+ "IdentityMode",
265
+ "IntegrationRef",
266
+ "IntegrationScopeExceededError",
267
+ "Invocation",
268
+ "InvocationCancelledError",
269
+ "InvocationOutputChunk",
270
+ "InvocationOutputNotRetainedError",
271
+ "InvocationResult",
272
+ "InvocationState",
273
+ "InvocationStream",
274
+ "InvocationTimeoutError",
275
+ "Invocations",
276
+ "InvokeDeniedError",
277
+ "Lifecycle",
278
+ "LifecycleAction",
279
+ "LifecycleLimitExceededError",
280
+ "LifecycleLimits",
281
+ "LifecycleLimitsUpdate",
282
+ "LifecycleSource",
283
+ "LifecycleSources",
284
+ "LifecycleUpdate",
285
+ "ListingTooLargeError",
286
+ "Network",
287
+ "NoCapacityError",
288
+ "Operation",
289
+ "OperationTimeoutError",
290
+ "Operations",
291
+ "OutputChunk",
292
+ "OutputPage",
293
+ "OutputStream",
294
+ "Page",
295
+ "PageTokenInvalidError",
296
+ "PermissionMissingError",
297
+ "Placement",
298
+ "Port",
299
+ "PortAccess",
300
+ "PortHost",
301
+ "PortHostState",
302
+ "PortProtocol",
303
+ "PortSpec",
304
+ "PortState",
305
+ "Ports",
306
+ "PreservedLevel",
307
+ "Process",
308
+ "ProcessCode",
309
+ "ProcessInput",
310
+ "ProcessKind",
311
+ "ProcessResult",
312
+ "ProcessSpec",
313
+ "ProcessStartFailedError",
314
+ "ProcessState",
315
+ "Processes",
316
+ "QuotaExceededError",
317
+ "QuotaViolation",
318
+ "RateLimitedError",
319
+ "ReadOptions",
320
+ "ReadResult",
321
+ "RegistrationRejectedError",
322
+ "ReplaceResult",
323
+ "RequestIdReusedError",
324
+ "ResourceExistsError",
325
+ "ResourceNotFoundError",
326
+ "Resources",
327
+ "Revision",
328
+ "RevisionProtocol",
329
+ "RevisionSource",
330
+ "RevisionSpec",
331
+ "RevisionState",
332
+ "RevisionStateReason",
333
+ "Revisions",
334
+ "Rollout",
335
+ "RolloutInProgressError",
336
+ "RolloutState",
337
+ "RolloutStateReason",
338
+ "Rollouts",
339
+ "Sandbox",
340
+ "SandboxFailedError",
341
+ "SandboxIdRetiredError",
342
+ "SandboxLaunchFailedError",
343
+ "SandboxLifecycle",
344
+ "SandboxNotRunningError",
345
+ "SandboxOwnedError",
346
+ "SandboxPolicies",
347
+ "SandboxPolicy",
348
+ "SandboxSource",
349
+ "SandboxState",
350
+ "SandboxStateReason",
351
+ "Sandboxes",
352
+ "Scaling",
353
+ "SearchResult",
354
+ "Service",
355
+ "ServiceState",
356
+ "ServiceStateReason",
357
+ "ServiceUnavailableError",
358
+ "Services",
359
+ "Session",
360
+ "SessionBusyError",
361
+ "SessionIdInvalidError",
362
+ "SessionLimitError",
363
+ "SessionSettings",
364
+ "SessionState",
365
+ "SessionStateReason",
366
+ "SessionSubjectMismatchError",
367
+ "Sessions",
368
+ "Signal",
369
+ "SignedUri",
370
+ "Snapshot",
371
+ "SnapshotState",
372
+ "Snapshots",
373
+ "SshAccess",
374
+ "SshAccessInfo",
375
+ "SshAccessState",
376
+ "SshCredential",
377
+ "SshPasswordMode",
378
+ "SshRoute",
379
+ "Sutra",
380
+ "SutraError",
381
+ "Template",
382
+ "Templates",
383
+ "Timeout",
384
+ "TimeoutOutOfRangeError",
385
+ "TrafficTarget",
386
+ "Volume",
387
+ "VolumeAccessMode",
388
+ "VolumeIdRetiredError",
389
+ "VolumeKind",
390
+ "VolumeMount",
391
+ "VolumeState",
392
+ "Volumes",
393
+ "WorkloadNotReadyError",
394
+ "Workloads",
395
+ "WriteOptions",
396
+ "WriteResult",
397
+ ]
@@ -0,0 +1,138 @@
1
+ # OWNING_DOC: cloud/sutra/sdk/README.md
2
+ """How every call is made: gRPC errors become typed errors, a call the
3
+ service could not answer is repeated, and a mutation keeps one request id
4
+ across its repeats so the service answers a repeat from its first result
5
+ (docs/platform/sandbox-api-structure.md, sections 3.3 and 3.15)."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import random
11
+ import time
12
+ import uuid
13
+ from collections.abc import Awaitable, Callable
14
+ from dataclasses import dataclass, field
15
+ from typing import TypeVar
16
+
17
+ import grpc
18
+
19
+ from ._errors import ApiError, error_from_rpc, with_resume_fields
20
+
21
+ T = TypeVar("T")
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class RetryPolicy:
26
+ """When and how often a call that failed with ``UNAVAILABLE`` is repeated."""
27
+
28
+ #: Repeats after the first attempt.
29
+ max_retries: int = 2
30
+ #: Seconds before the first repeat; each next one waits twice as long.
31
+ initial_delay: float = 0.5
32
+ #: The longest wait between attempts, in seconds, also when the error asks for more.
33
+ max_delay: float = 8.0
34
+ #: Waits (the sync client); replaced in tests.
35
+ sleep: Callable[[float], None] = time.sleep
36
+ #: Waits (the async client); replaced in tests.
37
+ async_sleep: Callable[[float], Awaitable[None]] = asyncio.sleep
38
+ #: A number in [0, 1); replaced in tests.
39
+ random: Callable[[], float] = field(default=random.random)
40
+
41
+ def delay(self, attempt: int, error: ApiError) -> float:
42
+ backoff = self.initial_delay * 2**attempt * (0.5 + self.random() / 2)
43
+ return min(error.retry_delay if error.retry_delay is not None else backoff, self.max_delay)
44
+
45
+
46
+ DEFAULT_RETRY_POLICY = RetryPolicy()
47
+
48
+ #: The client deadline of each attempt of a call that may take long, in
49
+ #: seconds: a create, a delete (which completes within the call until
50
+ #: TODO(sandbox-delete-operation, ANC-304) makes it a pending operation) and
51
+ #: a list of operations. It is generous on purpose: a call cut off early is
52
+ #: one whose outcome the caller cannot read.
53
+ CALL_TIMEOUT = 120.0
54
+
55
+
56
+ def new_request_id() -> str:
57
+ """A new request id: a UUIDv4, as the API recommends."""
58
+ return str(uuid.uuid4())
59
+
60
+
61
+ def _typed(error: Exception) -> Exception:
62
+ return error_from_rpc(error) if isinstance(error, grpc.RpcError) else error
63
+
64
+
65
+ def _repeatable(error: Exception, attempt: int, policy: RetryPolicy) -> bool:
66
+ return isinstance(error, ApiError) and error.code == "UNAVAILABLE" and attempt < policy.max_retries
67
+
68
+
69
+ def invoke(call: Callable[[], T]) -> T:
70
+ """Calls once and turns a gRPC error into the typed error it stands for."""
71
+ try:
72
+ return call()
73
+ except grpc.RpcError as error:
74
+ raise _typed(error) from None
75
+
76
+
77
+ async def invoke_async(call: Callable[[], Awaitable[T]]) -> T:
78
+ try:
79
+ return await call()
80
+ except grpc.RpcError as error:
81
+ raise _typed(error) from None
82
+
83
+
84
+ def with_retries(call: Callable[[], T], policy: RetryPolicy = DEFAULT_RETRY_POLICY) -> T:
85
+ """Calls, and repeats the call while it fails with ``UNAVAILABLE``."""
86
+ attempt = 0
87
+ while True:
88
+ try:
89
+ return invoke(call)
90
+ except ApiError as error:
91
+ if not _repeatable(error, attempt, policy):
92
+ raise
93
+ policy.sleep(policy.delay(attempt, error))
94
+ attempt += 1
95
+
96
+
97
+ async def with_retries_async(call: Callable[[], Awaitable[T]], policy: RetryPolicy = DEFAULT_RETRY_POLICY) -> T:
98
+ attempt = 0
99
+ while True:
100
+ try:
101
+ return await invoke_async(call)
102
+ except ApiError as error:
103
+ if not _repeatable(error, attempt, policy):
104
+ raise
105
+ await policy.async_sleep(policy.delay(attempt, error))
106
+ attempt += 1
107
+
108
+
109
+ def mutate(
110
+ request_id: str | None,
111
+ call: Callable[[str], T],
112
+ policy: RetryPolicy = DEFAULT_RETRY_POLICY,
113
+ ) -> T:
114
+ """Makes a mutation with the caller's request id, or a new one, which every
115
+ repeat sends again. An error it raises carries that ``request_id``."""
116
+ rid = request_id or new_request_id()
117
+ try:
118
+ return with_retries(lambda: call(rid), policy)
119
+ except Exception as error:
120
+ resumable = with_resume_fields(error, request_id=rid)
121
+ if resumable is error:
122
+ raise
123
+ raise resumable from error
124
+
125
+
126
+ async def mutate_async(
127
+ request_id: str | None,
128
+ call: Callable[[str], Awaitable[T]],
129
+ policy: RetryPolicy = DEFAULT_RETRY_POLICY,
130
+ ) -> T:
131
+ rid = request_id or new_request_id()
132
+ try:
133
+ return await with_retries_async(lambda: call(rid), policy)
134
+ except Exception as error:
135
+ resumable = with_resume_fields(error, request_id=rid)
136
+ if resumable is error:
137
+ raise
138
+ raise resumable from error
@@ -0,0 +1,148 @@
1
+ # OWNING_DOC: cloud/sutra/sdk/README.md
2
+ """The clients, sync and async. Each holds what its arguments and the
3
+ environment resolved to, one gRPC channel per service, opened on first use,
4
+ and the service modules: ``sandboxes``, ``sandbox_policies``, ``snapshots``,
5
+ ``volumes``, ``templates``, ``operations`` and ``workloads`` so far; each surface slice adds its own (docs/platform/sandbox-api-structure.md, sections
6
+ 3.15 and 4)."""
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable, Mapping
11
+ from types import TracebackType
12
+ from typing import Generic, TypeVar
13
+
14
+ import grpc
15
+ import grpc.aio
16
+
17
+ from ._calls import DEFAULT_RETRY_POLICY, RetryPolicy
18
+ from ._config import ResolvedConfig, resolve_config
19
+ from ._operations_api import AsyncOperations, Operations
20
+ from ._sandbox_policies import AsyncSandboxPolicies, SandboxPolicies
21
+ from ._sandboxes import AsyncSandboxes, Sandboxes
22
+ from ._snapshots import AsyncSnapshots, Snapshots
23
+ from ._templates import AsyncTemplates, Templates
24
+ from ._transport import OperationsClient, open_async_channel, open_channel
25
+ from ._volumes import AsyncVolumes, Volumes
26
+ from ._workloads import AsyncWorkloads, Workloads
27
+
28
+ C = TypeVar("C", grpc.Channel, grpc.aio.Channel)
29
+
30
+
31
+ class _Context(Generic[C]):
32
+ """What a client's modules call through."""
33
+
34
+ def __init__(
35
+ self,
36
+ config: ResolvedConfig,
37
+ open_channel: Callable[[str, str], C],
38
+ retry: RetryPolicy = DEFAULT_RETRY_POLICY,
39
+ ) -> None:
40
+ self.config = config
41
+ self.retry = retry
42
+ self._open_channel = open_channel
43
+ self._channels: dict[str, C] = {}
44
+
45
+ def channel(self, service: str) -> C:
46
+ """The service's channel, carrying the credential."""
47
+ channel = self._channels.get(service)
48
+ if channel is None:
49
+ channel = self._open_channel(self.config.endpoint(service), self.config.api_key)
50
+ self._channels[service] = channel
51
+ return channel
52
+
53
+ def operations(self, service: str) -> OperationsClient:
54
+ """The ``google.longrunning.Operations`` client of the service whose operations they are."""
55
+ return OperationsClient(self.channel(service))
56
+
57
+ def take_channels(self) -> list[C]:
58
+ channels = list(self._channels.values())
59
+ self._channels.clear()
60
+ return channels
61
+
62
+
63
+ class Sutra:
64
+ """A client of the Sutra platform.
65
+
66
+ ``api_key`` defaults to SUTRA_API_KEY, ``project`` to SUTRA_PROJECT (unset
67
+ is the caller's default project) and ``api_domain`` to SUTRA_API_DOMAIN;
68
+ each service is reached at ``https://<service>.<api_domain>`` unless
69
+ ``endpoints`` (or SUTRA_<SERVICE>_ENDPOINT) gives its URL."""
70
+
71
+ def __init__(
72
+ self,
73
+ *,
74
+ api_key: str | None = None,
75
+ project: str | None = None,
76
+ api_domain: str | None = None,
77
+ endpoints: Mapping[str, str] | None = None,
78
+ ) -> None:
79
+ config = resolve_config(api_key=api_key, project=project, api_domain=api_domain, endpoints=endpoints)
80
+ self._context: _Context[grpc.Channel] = _Context(config, open_channel)
81
+ #: Long-running operations of the client's project.
82
+ self.operations = Operations(self._context)
83
+ #: Sandboxes of the client's project.
84
+ self.sandboxes = Sandboxes(self._context, self.operations)
85
+ #: The sandbox policy of the client's project, or another's: lifecycle defaults and limits.
86
+ self.sandbox_policies = SandboxPolicies(self._context)
87
+ #: Snapshots of sandboxes in the client's project.
88
+ self.snapshots = Snapshots(self._context, self.operations)
89
+ #: Volumes of the client's project.
90
+ self.volumes = Volumes(self._context, self.operations)
91
+ #: The templates sandboxes are created from: the built-in ones, and a project's.
92
+ self.templates = Templates(self._context)
93
+ #: Services and agents of the client's project, at ``workloads.<api_domain>``.
94
+ self.workloads = Workloads(self._context)
95
+
96
+ def close(self) -> None:
97
+ """Closes the client's channels. A closed client opens new ones if it is used again."""
98
+ for channel in self._context.take_channels():
99
+ channel.close()
100
+
101
+ def __enter__(self) -> Sutra:
102
+ return self
103
+
104
+ def __exit__(
105
+ self,
106
+ exc_type: type[BaseException] | None,
107
+ exc: BaseException | None,
108
+ traceback: TracebackType | None,
109
+ ) -> None:
110
+ self.close()
111
+
112
+
113
+ class AsyncSutra:
114
+ """The asyncio client of the Sutra platform, with the same surface as ``Sutra``."""
115
+
116
+ def __init__(
117
+ self,
118
+ *,
119
+ api_key: str | None = None,
120
+ project: str | None = None,
121
+ api_domain: str | None = None,
122
+ endpoints: Mapping[str, str] | None = None,
123
+ ) -> None:
124
+ config = resolve_config(api_key=api_key, project=project, api_domain=api_domain, endpoints=endpoints)
125
+ self._context: _Context[grpc.aio.Channel] = _Context(config, open_async_channel)
126
+ self.operations = AsyncOperations(self._context)
127
+ self.sandboxes = AsyncSandboxes(self._context, self.operations)
128
+ self.sandbox_policies = AsyncSandboxPolicies(self._context)
129
+ self.snapshots = AsyncSnapshots(self._context, self.operations)
130
+ self.volumes = AsyncVolumes(self._context, self.operations)
131
+ self.templates = AsyncTemplates(self._context)
132
+ self.workloads = AsyncWorkloads(self._context)
133
+
134
+ async def close(self) -> None:
135
+ """Closes the client's channels. A closed client opens new ones if it is used again."""
136
+ for channel in self._context.take_channels():
137
+ await channel.close()
138
+
139
+ async def __aenter__(self) -> AsyncSutra:
140
+ return self
141
+
142
+ async def __aexit__(
143
+ self,
144
+ exc_type: type[BaseException] | None,
145
+ exc: BaseException | None,
146
+ traceback: TracebackType | None,
147
+ ) -> None:
148
+ await self.close()