testflows.machine 0.1.4__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.
@@ -0,0 +1,875 @@
1
+ # Copyright 2026 Katteli Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Sessions: cloud machines that host runs, as `machine sessions`."""
15
+
16
+ from __future__ import annotations
17
+
18
+ import builtins
19
+ from typing import TYPE_CHECKING, Any, Generator, Literal, Optional, overload
20
+
21
+ from testflows.machine._core import api
22
+ from testflows.machine._core import migration as _migration
23
+ from testflows.machine._core import sessions as _sessions
24
+
25
+ from . import _args
26
+ from . import _warn
27
+ from .errors import ApiError, InvalidArgument, NotFound, _translated
28
+
29
+ if TYPE_CHECKING:
30
+ from .client import Client
31
+
32
+ #: The state of a session that was deleted.
33
+ _DELETED = "terminated"
34
+
35
+ #: MB in a GB: `create` takes storage in GB, the service in MB.
36
+ _MB_PER_GB = 1024
37
+
38
+ #: The fields a session exposes, in the order `as_json` lists them.
39
+ FIELDS: tuple[str, ...] = (
40
+ "id",
41
+ "name",
42
+ "state",
43
+ "cpus",
44
+ "mem_mb",
45
+ "storage_mb",
46
+ "instance_type",
47
+ "error",
48
+ "created_at",
49
+ "started_at",
50
+ "stopped_at",
51
+ )
52
+
53
+
54
+ class SessionClosing(UserWarning):
55
+ """A session is scheduled to stop for maintenance of its host. The
56
+ client gives it once for each notice, at the program's next call into the
57
+ session, when the program set no `on_session_closing`. Use
58
+ `warnings.simplefilter("error", SessionClosing)` to raise it instead."""
59
+
60
+
61
+ class SessionMovedBack(UserWarning):
62
+ """A run that `migrate` started at its last checkpoint, not where it was,
63
+ because the session's host was lost before the move stopped it."""
64
+
65
+
66
+ class Session:
67
+ """One session: a machine the account rents, with its own CPUs,
68
+ memory and storage, where runs execute.
69
+
70
+ Not created directly: `Client.sessions` creates, lists and shows
71
+ sessions. `client.sessions.use(session)` makes one the client's current
72
+ session, where its commands go. The attributes are what the last read
73
+ returned; `refresh` reads them again.
74
+
75
+ A session uses credits from the moment it is created until it stops. Used
76
+ in a `with` block, it is deleted when the block exits, however it exits.
77
+ Without `with`, it lives until `delete`, or until it has been idle for
78
+ its plan's idle time: no command for that long, `keep` aside.
79
+
80
+ Example:
81
+ >>> with client.sessions.create("ci-1", cpus=4) as session:
82
+ ... client.sessions.use(session)
83
+ ... run = client.create(disk="app")
84
+ """
85
+
86
+ def __init__(self, client: "Client", row: dict[str, Any]) -> None:
87
+ self._client = client
88
+ self._row = row
89
+
90
+ @property
91
+ def id(self) -> str:
92
+ """str: The session's id. A session moved with `migrate` has a new id,
93
+ which this follows, whichever client or object moved it."""
94
+ return self._client._now_id(str(self._row["session_id"]))
95
+
96
+ @property
97
+ def name(self) -> str:
98
+ """str: The session's name, unique in the account; `rename` changes
99
+ it."""
100
+ return str(self._row.get("name") or self.id)
101
+
102
+ @property
103
+ def state(self) -> str:
104
+ """str: `provisioning` while its machine is prepared, `running` once
105
+ runs can execute there, then `stopping`, and `terminated` once it is
106
+ gone; `failed` when it could not start, with `error` saying why."""
107
+ return str(self._row.get("state") or "")
108
+
109
+ @property
110
+ def cpus(self) -> Optional[int]:
111
+ """int: vCPUs reserved for the session and shared by its runs."""
112
+ return _int_or_none(self._row.get("cpus"))
113
+
114
+ @property
115
+ def mem_mb(self) -> Optional[int]:
116
+ """int: Memory reserved for the session in MB, shared by its runs."""
117
+ return _int_or_none(self._row.get("mem_mb"))
118
+
119
+ @property
120
+ def storage_mb(self) -> Optional[int]:
121
+ """int: Storage reserved for the session in MB, for the runs and disks
122
+ copied there."""
123
+ return _int_or_none(self._row.get("storage_mb"))
124
+
125
+ @property
126
+ def storage_gb(self) -> Optional[int]:
127
+ """int: The disk in GB, the unit `Sessions.create` takes; rounded
128
+ down when the service gave an uneven number of MB."""
129
+ megabytes = self.storage_mb
130
+ return None if megabytes is None else megabytes // _MB_PER_GB
131
+
132
+ @property
133
+ def instance_type(self) -> Optional[str]:
134
+ """str: The class of machine the session runs on."""
135
+ value = self._row.get("instance_type")
136
+ return None if value is None else str(value)
137
+
138
+ @property
139
+ def error(self) -> Optional[str]:
140
+ """str: Why the session failed; None unless `state` is `failed`."""
141
+ value = self._row.get("error")
142
+ return None if value is None else str(value)
143
+
144
+ @property
145
+ def created_at(self) -> Optional[str]:
146
+ """str: When the session was created, ISO 8601."""
147
+ return _str_or_none(self._row.get("created_at"))
148
+
149
+ @property
150
+ def started_at(self) -> Optional[str]:
151
+ """str: When the session first reached `running`, ISO 8601; None
152
+ before then."""
153
+ return _str_or_none(self._row.get("started_at"))
154
+
155
+ @property
156
+ def stopped_at(self) -> Optional[str]:
157
+ """str: When the session stopped, ISO 8601; None while it runs."""
158
+ return _str_or_none(self._row.get("stopped_at"))
159
+
160
+ @property
161
+ def closing_at(self) -> Optional[str]:
162
+ """str: When the session stops for maintenance of its host, ISO 8601;
163
+ None when none is scheduled. Use `migrate` before then to keep its
164
+ machines running in a new session. Read again with `refresh`."""
165
+ return _str_or_none(self._row.get("closing_at"))
166
+
167
+ @property
168
+ def closing_reason(self) -> Optional[str]:
169
+ """str: Why the session stops at `closing_at`, such as a kernel
170
+ update; None when none is scheduled."""
171
+ return _str_or_none(self._row.get("closing_reason"))
172
+
173
+ def _closing(self, by: Optional[str], reason: Optional[str]) -> None:
174
+ """Set the notice the client read, without asking the API again."""
175
+ self._row["closing_at"] = by
176
+ self._row["closing_reason"] = reason
177
+
178
+ def refresh(self) -> "Session":
179
+ """Read the session again, so its attributes are current.
180
+
181
+ Returns:
182
+ Session: This session.
183
+
184
+ Raises:
185
+ NotFound: The session no longer exists.
186
+ """
187
+ client, creds = self._client._account()
188
+ with _translated():
189
+ self._row = _sessions.get(client, creds, self.id)
190
+ return self
191
+
192
+ def wait(
193
+ self, state: str = "running", *, timeout: Optional[float] = None
194
+ ) -> "Session":
195
+ """Wait until the session is in `state`, as `machine sessions create`
196
+ waits for `running`.
197
+
198
+ A new session takes minutes to reach `running` while its machine is
199
+ prepared. Waiting for `running` ends at once when the session can no
200
+ longer get there, such as one that failed.
201
+
202
+ Example:
203
+ >>> session = client.sessions.create(cpus=4, wait=False)
204
+ >>> session.wait("running", timeout=900)
205
+
206
+ Args:
207
+ state (str, optional): The state to wait for. Defaults to
208
+ `running`.
209
+ timeout (float, optional): Seconds to wait; None waits without a
210
+ limit.
211
+
212
+ Returns:
213
+ Session: This session, read in `state`.
214
+
215
+ Raises:
216
+ NotRunning: Waiting for `running` and the session failed or
217
+ stopped; `error` says why.
218
+ Timeout: The session was not in `state` within `timeout`.
219
+ """
220
+ client, creds = self._client._account()
221
+ with _translated():
222
+ self._row = _sessions.wait_until(
223
+ client, creds, self.id, state, timeout_s=timeout
224
+ )
225
+ return self
226
+
227
+ def rename(self, new_name: str) -> "Session":
228
+ """Rename the session, as `machine sessions rename` does.
229
+
230
+ Its machine, its runs and its id are unchanged.
231
+
232
+ Args:
233
+ new_name (str): The new name: up to 64 letters, digits, dots,
234
+ dashes and underscores, starting with a letter or digit.
235
+
236
+ Returns:
237
+ Session: This session, renamed.
238
+
239
+ Raises:
240
+ InvalidArgument: `new_name` is not a valid session name.
241
+ AlreadyExists: Another session has this name.
242
+ """
243
+ _require_valid_name(new_name)
244
+ client, creds = self._client._account()
245
+ with _translated():
246
+ api.auth.authed(
247
+ creds, lambda t: client.session_rename(t, self.id, new_name)
248
+ )
249
+ self._row = {**self._row, "name": new_name}
250
+ return self
251
+
252
+ def keep(self, minutes: int) -> "Session":
253
+ """Keep the session running while it is idle, as `machine sessions keep` does.
254
+
255
+ A session is idle while it serves no command. An idle session stops
256
+ after the plan's idle time. Keep holds it for `minutes`, up to the
257
+ plan's limit. A later keep replaces the hold.
258
+
259
+ Args:
260
+ minutes (int): How long to hold the session, in minutes.
261
+
262
+ Returns:
263
+ Session: This session, kept.
264
+
265
+ Raises:
266
+ InvalidArgument: `minutes` is less than 1.
267
+ Forbidden: `minutes` is more than the plan allows.
268
+ NotFound: The session is not running.
269
+ """
270
+ if minutes < 1:
271
+ raise InvalidArgument(f"Keep for at least 1 minute, not {minutes}.")
272
+ client, creds = self._client._account()
273
+ with _translated():
274
+ self._row = _sessions.keep(client, creds, self.id, minutes)
275
+ return self
276
+
277
+ def migrate(self) -> "Session":
278
+ """Move the session to a new session with its runs, as `machine
279
+ sessions migrate` does.
280
+
281
+ A session of the same class and size is created. Each running machine
282
+ is stopped, which checkpoints it, and started in the new session at
283
+ that checkpoint, in the same state. The new session takes the name,
284
+ and the old one is deleted. A command running on a machine ends, as
285
+ `stop` ends it.
286
+
287
+ A move that fails is put back: every machine it stopped starts again
288
+ in the session, and the new session is deleted. When the session ends
289
+ during the move, the move finishes in the new session instead.
290
+
291
+ A machine the move had not stopped when the session's host was lost
292
+ starts at its last checkpoint, not where it was. Each one is reported
293
+ with a `SessionMovedBack` warning that names the run.
294
+
295
+ This object becomes the new session. When it was the client's current
296
+ session, the client uses the new one.
297
+
298
+ Example:
299
+ >>> session = client.sessions.show("ci-1")
300
+ >>> session.migrate().name
301
+ 'ci-1'
302
+
303
+ Returns:
304
+ Session: This session, moved.
305
+
306
+ Raises:
307
+ NoCapacity: No other host has room for the session now.
308
+ NotRunning: The session is not running.
309
+ Diverged: A machine started in another state in the new session.
310
+ The sessions are kept as they are, and the message says how
311
+ to go on.
312
+ Conflict: The move was refused, or failed and was put back. The
313
+ message says why.
314
+ ApiError: The service could not carry out the move.
315
+ """
316
+ client, creds = self._client._account()
317
+ old_id = self.id
318
+ with _translated():
319
+ planned = _migration.plan(client, creds, old_id)
320
+ moved = _migration.migrate(client, creds, planned)
321
+ self._row = moved.session
322
+ self._client._moved(old_id, self)
323
+ for machine in moved.went_back:
324
+ _warn.warn(
325
+ f"{machine.name} ({machine.run_id}) started at its last checkpoint."
326
+ " The session's host was lost before the move stopped it.",
327
+ SessionMovedBack,
328
+ )
329
+ return self
330
+
331
+ def delete(self, *, wait: bool = True, timeout: Optional[float] = None) -> None:
332
+ """Delete the session, as `machine sessions delete` does.
333
+
334
+ Its machines stop, their runs are published to shared storage, and
335
+ the session stops using credits. A session already gone is not an error,
336
+ so cleanup code can call this unconditionally. When it is the
337
+ client's current session, the client has none after.
338
+
339
+ Example:
340
+ >>> try:
341
+ ... run_tests(client)
342
+ ... finally:
343
+ ... session.delete()
344
+
345
+ Args:
346
+ wait (bool, optional): Return once the session is gone. Defaults
347
+ to True.
348
+ timeout (float, optional): Seconds to wait; None waits without a
349
+ limit.
350
+
351
+ Raises:
352
+ Timeout: The session was not gone within `timeout`.
353
+ """
354
+ client, creds = self._client._account()
355
+ with _translated():
356
+ _sessions.delete(client, creds, self.id)
357
+ if wait:
358
+ _sessions.wait_until_gone(client, creds, self.id, timeout_s=timeout)
359
+ api.store.clear_session(self.id)
360
+ self._client._forget(self.id)
361
+
362
+ def as_json(self) -> dict[str, Any]:
363
+ """The session's attributes as a JSON-serializable dict.
364
+
365
+ Returns:
366
+ dict[str, Any]: One key per attribute, `id` through `stopped_at`.
367
+ """
368
+ return {field: getattr(self, field) for field in FIELDS}
369
+
370
+ def __enter__(self) -> "Session":
371
+ return self
372
+
373
+ def __exit__(self, *exc: object) -> None:
374
+ self.delete()
375
+
376
+ def __eq__(self, other: object) -> bool:
377
+ return isinstance(other, Session) and other.id == self.id
378
+
379
+ def __hash__(self) -> int:
380
+ return hash(self.id)
381
+
382
+ def __repr__(self) -> str:
383
+ return f"Session(name={self.name!r}, id={self.id!r}, state={self.state!r})"
384
+
385
+
386
+ class Sessions:
387
+ """The account's sessions, as `Client.sessions`; not created directly.
388
+
389
+ Call it to list them, as `machine sessions` does. A session named by
390
+ `session` is a `Session`, or its name, id or unique id prefix; where it
391
+ may be left out, the account's only session is meant.
392
+
393
+ Example:
394
+ >>> [s.name for s in client.sessions()]
395
+ ['ci-1', 'ci-2']
396
+ >>> client.sessions.use("ci-1")
397
+ """
398
+
399
+ def __init__(self, client: "Client") -> None:
400
+ self._client = client
401
+
402
+ @overload
403
+ def __call__(
404
+ self, *, watch: Literal[False] = ..., timeout: Optional[float] = ...
405
+ ) -> builtins.list[Session]: ...
406
+
407
+ @overload
408
+ def __call__(
409
+ self, *, watch: Literal[True], timeout: Optional[float] = ...
410
+ ) -> Generator[builtins.list[Session], None, None]: ...
411
+
412
+ def __call__(
413
+ self, *, watch: bool = False, timeout: Optional[float] = None
414
+ ) -> "builtins.list[Session] | Generator[builtins.list[Session], None, None]":
415
+ """List the account's sessions, as `machine sessions` does; the
416
+ same as `list`.
417
+
418
+ Args:
419
+ watch (bool, optional): Yield the list each time it changes.
420
+ Defaults to False.
421
+ timeout (float, optional): With `watch`, end the generator after
422
+ this many seconds, without raising; None watches until the
423
+ caller leaves the loop.
424
+
425
+ Returns:
426
+ list[Session]: The sessions; with `watch`, an iterator of such
427
+ lists.
428
+ """
429
+ return _args.watched(self._rows, self._sessions, watch, timeout)
430
+
431
+ @overload
432
+ def list(
433
+ self, *, watch: Literal[False] = ..., timeout: Optional[float] = ...
434
+ ) -> builtins.list[Session]: ...
435
+
436
+ @overload
437
+ def list(
438
+ self, *, watch: Literal[True], timeout: Optional[float] = ...
439
+ ) -> Generator[builtins.list[Session], None, None]: ...
440
+
441
+ def list(
442
+ self, *, watch: bool = False, timeout: Optional[float] = None
443
+ ) -> "builtins.list[Session] | Generator[builtins.list[Session], None, None]":
444
+ """List the account's sessions, as `machine sessions list` does.
445
+
446
+ Deleted sessions are left out. With `watch`, it yields the list at
447
+ once, then again each time it changes: a session created, deleted,
448
+ or changing state. Leave the loop, or pass `timeout`, to stop.
449
+
450
+ Example:
451
+ >>> for sessions in client.sessions.list(watch=True, timeout=900):
452
+ ... if all(s.state == "running" for s in sessions):
453
+ ... break
454
+
455
+ Args:
456
+ watch (bool, optional): Yield the list each time it changes.
457
+ Defaults to False.
458
+ timeout (float, optional): With `watch`, end the generator after
459
+ this many seconds, without raising; None watches until the
460
+ caller leaves the loop.
461
+
462
+ Returns:
463
+ list[Session]: The sessions; with `watch`, an iterator of such
464
+ lists.
465
+
466
+ Raises:
467
+ NotSignedIn: There are no credentials.
468
+ """
469
+ return _args.watched(self._rows, self._sessions, watch, timeout)
470
+
471
+ def create(
472
+ self,
473
+ name: Optional[str] = None,
474
+ *,
475
+ cpus: int = 1,
476
+ mem: Optional[int] = None,
477
+ storage: Optional[int] = None,
478
+ class_: Optional[str] = None,
479
+ wait: bool = True,
480
+ timeout: Optional[float] = None,
481
+ ) -> Session:
482
+ """Create a session, as `machine sessions create` does.
483
+
484
+ The session uses credits from the moment it is created until it
485
+ stops. Create it in a `with` block to have it deleted when the
486
+ block exits, however it exits; without `with`, it lives until
487
+ `Session.delete`, or until it has been idle for its plan's idle time. Its memory and storage default to what `cpus` buys
488
+ on the account's hardware class. `use` makes it the client's current
489
+ session.
490
+
491
+ Example:
492
+ >>> with client.sessions.create("ci-1", cpus=4) as session:
493
+ ... client.sessions.use(session)
494
+ ... run = client.create(disk="app")
495
+
496
+ Args:
497
+ name (str, optional): The session's name: up to 64 letters,
498
+ digits, dots, dashes and underscores, starting with a letter
499
+ or digit. One is generated when omitted.
500
+ cpus (int, optional): vCPUs to reserve. Defaults to 1.
501
+ mem (int, optional): Memory to reserve in MB.
502
+ storage (int, optional): Disk to reserve, in GB; the session
503
+ reports it as `storage_mb`, and `storage_gb` in these terms.
504
+ class_ (str, optional): The hardware class to run on; defaults
505
+ to the plan's. The trailing underscore avoids the Python
506
+ keyword.
507
+ wait (bool, optional): Return once the session is running.
508
+ Defaults to True.
509
+ timeout (float, optional): Seconds to wait; None waits without a
510
+ limit.
511
+
512
+ Returns:
513
+ Session: The new session.
514
+
515
+ Raises:
516
+ InvalidArgument: `name` is not a valid session name.
517
+ AlreadyExists: A session has this name.
518
+ Forbidden: The account may not create sessions, such as one that
519
+ is not active or over its plan's limits, or the class is not
520
+ sold to the account's plan.
521
+ NoCapacity: No host of the class has room for the session now.
522
+ Retry later, ask for less, or pick another class.
523
+ ClassUnavailable: No machine of the class is in service. Pick
524
+ another class.
525
+ NotRunning: The session failed to start; `error` says why.
526
+ Timeout: It was not running within `timeout`.
527
+ """
528
+ if name is not None:
529
+ _require_valid_name(name)
530
+ client, creds = self._client._account()
531
+ with _translated():
532
+ row = _sessions.create(
533
+ client,
534
+ creds,
535
+ cpus,
536
+ name,
537
+ class_,
538
+ mem,
539
+ None if storage is None else storage * _MB_PER_GB,
540
+ )
541
+ session = Session(self._client, row)
542
+ if wait:
543
+ session.wait("running", timeout=timeout)
544
+ return session
545
+
546
+ def use(
547
+ self,
548
+ session: "Session | str | None" = None,
549
+ *,
550
+ wait: bool = True,
551
+ timeout: Optional[float] = None,
552
+ ) -> Session:
553
+ """Make a session the client's current session, as `machine sessions
554
+ use` does.
555
+
556
+ A session this machine already holds a tunnel to is RECHECKED, not
557
+ trusted: the tunnel outlives a daemon that has gone silent, so `use`
558
+ tests it and reconnects through a fresh tunnel when it does not
559
+ answer. Otherwise it connects, waiting while the session is still
560
+ provisioning. Only this client changes: the CLI's current session is
561
+ left as it is. A session that moved, `migrate` here or on another
562
+ computer, is followed: the session it moved to becomes current, and
563
+ every Session object of the one it left names it.
564
+
565
+ Example:
566
+ >>> session = client.sessions.use("ci-1")
567
+ >>> client.session == session
568
+ True
569
+
570
+ Args:
571
+ session (Session or str, optional): The session; defaults to the
572
+ only one.
573
+ wait (bool, optional): Wait while the session is provisioning;
574
+ False refuses a session that is not running yet. Defaults to
575
+ True.
576
+ timeout (float, optional): Seconds to wait; None waits without a
577
+ limit.
578
+
579
+ Returns:
580
+ Session: The session, now current.
581
+
582
+ Raises:
583
+ NotFound: No session matches.
584
+ InvalidArgument: The prefix matches more than one session, or
585
+ none is named and there are several.
586
+ NotRunning: The session is not running and `wait` is False, or it
587
+ failed.
588
+ ServiceUnavailable: The session does not respond.
589
+ """
590
+ known = self._moved_to(self.show(session))
591
+ with _translated():
592
+ if api.store.session_connected(known.id) and _sessions.recheck(known.id):
593
+ self._client._use(known)
594
+ return known
595
+ return self.connect(known, wait=wait, timeout=timeout)
596
+
597
+ def _moved_to(self, session: Session) -> Session:
598
+ """The session `session` moved to, after every move; itself when it did
599
+ not move."""
600
+ if not session._row.get("successor_id"):
601
+ return session
602
+ client, creds = self._client._account()
603
+ with _translated():
604
+ row = _sessions.follow(client, creds, session.id)
605
+ if row is None:
606
+ return session
607
+ moved = Session(self._client, row)
608
+ self._client._moved(session.id, moved)
609
+ return moved
610
+
611
+ def migrate(self, session: "Session | str | None" = None) -> Session:
612
+ """Move a session to a new session with its runs, as `machine sessions
613
+ migrate` does. See `Session.migrate`.
614
+
615
+ Args:
616
+ session (Session or str, optional): The session; defaults to the
617
+ only one.
618
+
619
+ Returns:
620
+ Session: The session, moved.
621
+
622
+ Raises:
623
+ NotFound: No session matches.
624
+ NoCapacity: No other host has room for the session now.
625
+ NotRunning: The session is not running.
626
+ Diverged: A machine started in another state. See `Session.migrate`.
627
+ Conflict: The move was refused, or failed and was put back.
628
+ """
629
+ target = session if isinstance(session, Session) else self.show(session)
630
+ return target.migrate()
631
+
632
+ def show(self, session: "Session | str | None" = None) -> Session:
633
+ """Read a session, as `machine sessions show` does.
634
+
635
+ Args:
636
+ session (Session or str, optional): The session; defaults to the
637
+ only one.
638
+
639
+ Returns:
640
+ Session: The session, read now.
641
+
642
+ Raises:
643
+ NotFound: No session matches; a deleted session is not found.
644
+ InvalidArgument: The prefix matches more than one session, or
645
+ none is named and there are several.
646
+ """
647
+ client, creds = self._client._account()
648
+ ref = _ref(session)
649
+ with _translated():
650
+ session_id = _sessions.resolve_ref_or_sole(self._rows(), ref)
651
+ row = _sessions.get(client, creds, session_id)
652
+ if row.get("state") == _DELETED:
653
+ raise NotFound(f"No such session: {ref!r}.")
654
+ return Session(self._client, row)
655
+
656
+ def delete(
657
+ self,
658
+ session: "Session | str | None" = None,
659
+ *,
660
+ all: bool = False,
661
+ wait: bool = True,
662
+ timeout: Optional[float] = None,
663
+ ) -> builtins.list[Session]:
664
+ """Delete a session, or every session, as `machine sessions delete`
665
+ does.
666
+
667
+ Its machines stop, their runs are published to shared storage, and
668
+ the session stops costing. Already gone is not an error. A prune is
669
+ refused while any session is live, so `all` is what
670
+ `storage.prune` needs.
671
+
672
+ Example:
673
+ >>> client.sessions.delete("ci-1")
674
+ >>> client.sessions.delete(all=True)
675
+
676
+ Args:
677
+ session (Session or str, optional): The session; defaults to the
678
+ only one.
679
+ all (bool, optional): Delete every session. Defaults to False.
680
+ wait (bool, optional): Return once the sessions are gone; with
681
+ `all` they are asked one after another and waited for after
682
+ that, so N sessions cost one wait. False returns once each
683
+ request is accepted, as `machine sessions delete -a` does.
684
+ Defaults to True.
685
+ timeout (float, optional): Seconds to wait; None waits without a
686
+ limit.
687
+
688
+ Returns:
689
+ list[Session]: The sessions deleted.
690
+
691
+ Raises:
692
+ InvalidArgument: A session is named with `all`.
693
+ NotFound: No session matches.
694
+ ApiError: With `all`, some sessions could not be deleted; the
695
+ message names the first.
696
+ """
697
+ if all:
698
+ if session is not None:
699
+ raise InvalidArgument("Name a session or pass all=True, not both.")
700
+ return self._delete_all(wait=wait, timeout=timeout)
701
+ doomed = session if isinstance(session, Session) else self.show(session)
702
+ doomed.delete(wait=wait, timeout=timeout)
703
+ return [doomed]
704
+
705
+ def rename(self, session: "Session | str", new_name: str) -> Session:
706
+ """Rename a session, as `machine sessions rename` does.
707
+
708
+ Its machine and its runs are unchanged.
709
+
710
+ Args:
711
+ session (Session or str): The session.
712
+ new_name (str): The new name: up to 64 letters, digits, dots,
713
+ dashes and underscores, starting with a letter or digit.
714
+
715
+ Returns:
716
+ Session: The session, renamed.
717
+
718
+ Raises:
719
+ InvalidArgument: `new_name` is not a valid session name.
720
+ NotFound: No session matches.
721
+ AlreadyExists: Another session has this name.
722
+ """
723
+ target = session if isinstance(session, Session) else self.show(session)
724
+ return target.rename(new_name)
725
+
726
+ def keep(self, session: "Session | str", minutes: int) -> Session:
727
+ """Keep a session running while it is idle, as `machine sessions keep` does.
728
+
729
+ Args:
730
+ session (Session or str): The session.
731
+ minutes (int): How long to hold it, in minutes, up to the plan's
732
+ limit.
733
+
734
+ Returns:
735
+ Session: The session, kept.
736
+
737
+ Raises:
738
+ InvalidArgument: `minutes` is less than 1.
739
+ Forbidden: `minutes` is more than the plan allows.
740
+ NotFound: No session matches, or it is not running.
741
+ """
742
+ target = session if isinstance(session, Session) else self.show(session)
743
+ return target.keep(minutes)
744
+
745
+ def connect(
746
+ self,
747
+ session: "Session | str | None" = None,
748
+ *,
749
+ wait: bool = True,
750
+ timeout: Optional[float] = None,
751
+ ) -> Session:
752
+ """Connect to a session and make it the client's current session, as
753
+ `machine sessions connect` does.
754
+
755
+ Opens this machine's tunnel to the session, waiting while it is
756
+ still provisioning. `use` is the everyday verb.
757
+
758
+ Args:
759
+ session (Session or str, optional): The session; defaults to the
760
+ only one.
761
+ wait (bool, optional): Wait while the session is provisioning;
762
+ False refuses a session that is not running yet. Defaults to
763
+ True.
764
+ timeout (float, optional): Seconds to wait; None waits without a
765
+ limit.
766
+
767
+ Returns:
768
+ Session: The session, now current.
769
+
770
+ Raises:
771
+ NotFound: No session matches.
772
+ NotRunning: The session is not running and `wait` is False, or it
773
+ failed.
774
+ ServiceUnavailable: The session does not respond.
775
+ """
776
+ client, creds = self._client._account()
777
+ with _translated():
778
+ row = _sessions.connect(
779
+ client, creds, _ref(session), wait=wait, timeout_s=timeout
780
+ )
781
+ made = Session(self._client, row)
782
+ self._client._use(made)
783
+ return made
784
+
785
+ def disconnect(self, session: "Session | str | None" = None) -> bool:
786
+ """Close this machine's tunnel to a session, as `machine sessions
787
+ disconnect` does.
788
+
789
+ The session keeps running. The tunnel is shared on this machine, so
790
+ the CLI and every other program lose it too; the next command that
791
+ needs it opens it again.
792
+
793
+ Args:
794
+ session (Session or str, optional): The session; defaults to the
795
+ client's current one.
796
+
797
+ Returns:
798
+ bool: True when a tunnel was closed.
799
+
800
+ Raises:
801
+ InvalidArgument: None is named and the client has no session.
802
+ NotFound: No session matches.
803
+ """
804
+ target = self._client.session if session is None else None
805
+ if session is not None:
806
+ target = session if isinstance(session, Session) else self.show(session)
807
+ if target is None:
808
+ raise InvalidArgument("No session. Name the session to disconnect.")
809
+ with _translated():
810
+ closed = _sessions.tunnel_stop(target.id)
811
+ self._client._forget(target.id)
812
+ return closed
813
+
814
+ def _list(self) -> builtins.list[Session]:
815
+ return self._sessions(self._rows())
816
+
817
+ def _sessions(self, rows: builtins.list[dict[str, Any]]) -> builtins.list[Session]:
818
+ return [Session(self._client, row) for row in rows]
819
+
820
+ def _rows(self) -> builtins.list[dict[str, Any]]:
821
+ """The account's sessions, less the deleted ones: the service's list can
822
+ trail a deletion that has already completed."""
823
+ client, creds = self._client._account()
824
+ with _translated():
825
+ rows = api.auth.authed(creds, client.session_list)
826
+ return [row for row in rows if row.get("state") != _DELETED]
827
+
828
+ def _delete_all(
829
+ self, *, wait: bool, timeout: Optional[float]
830
+ ) -> builtins.list[Session]:
831
+ """Delete every session, each in turn, reporting the first failure
832
+ after trying them all.
833
+
834
+ Asked one after another rather than waited for one after another: the
835
+ wait, when there is one, comes after every session has been told to
836
+ go, so N sessions cost one wait and not N.
837
+ """
838
+ done: builtins.list[Session] = []
839
+ errors: builtins.list[str] = []
840
+ for session in self._list():
841
+ try:
842
+ session.delete(wait=False)
843
+ done.append(session)
844
+ except Exception as exc:
845
+ errors.append(f"{session.name}: {exc}")
846
+ if errors:
847
+ raise ApiError(
848
+ f"Deleted {len(done)}, {len(errors)} failed; first {errors[0]}"
849
+ )
850
+ if wait:
851
+ for session in done:
852
+ with _translated():
853
+ client, creds = self._client._account()
854
+ _sessions.wait_until_gone(
855
+ client, creds, session.id, timeout_s=timeout
856
+ )
857
+ return done
858
+
859
+
860
+ def _ref(session: "Session | str | None") -> Optional[str]:
861
+ """What names `session` to the service: its id, or the text given."""
862
+ return session.id if isinstance(session, Session) else session
863
+
864
+
865
+ def _require_valid_name(name: str) -> None:
866
+ if not _sessions.valid_name(name):
867
+ raise InvalidArgument(f"Invalid session name {name!r}: {_sessions.NAME_RULE}.")
868
+
869
+
870
+ def _int_or_none(value: Any) -> Optional[int]:
871
+ return None if value is None else int(value)
872
+
873
+
874
+ def _str_or_none(value: Any) -> Optional[str]:
875
+ return None if value is None else str(value)