snap-python 0.1.7__py3-none-any.whl → 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.
@@ -1,4 +1,3 @@
1
- import asyncio
2
1
  import logging
3
2
  from pathlib import Path
4
3
  from typing import Any
@@ -6,13 +5,14 @@ from typing import Any
6
5
  import httpx
7
6
 
8
7
  from snap_python.schemas.changes import ChangesResponse
9
- from snap_python.schemas.common import AsyncResponse, BaseErrorResult
8
+ from snap_python.schemas.common import AsyncResponse
10
9
  from snap_python.schemas.snaps import (
11
10
  AppsResponse,
11
+ InstalledSnap,
12
12
  InstalledSnapListResponse,
13
13
  SingleInstalledSnapResponse,
14
14
  )
15
- from snap_python.utils import AbstractSnapsClient, SnapdAPIError, going_to_reload_daemon
15
+ from snap_python.utils import AbstractSnapsClient, SnapdAPIError, wait_for_change
16
16
 
17
17
  logger = logging.getLogger("snap_python.components.snaps")
18
18
 
@@ -22,26 +22,77 @@ class SnapsEndpoints:
22
22
  self._client = client
23
23
  self.common_endpoint = "snaps"
24
24
 
25
- async def list_installed_snaps(self) -> InstalledSnapListResponse:
25
+ async def _wait_for_change(
26
+ self,
27
+ change_id: str,
28
+ timeout: float | None = None,
29
+ poll_interval: float = 0.5,
30
+ progress_callback=None,
31
+ ) -> ChangesResponse:
32
+ """Wait for a snapd change to reach a terminal state.
33
+
34
+ Thin wrapper around :func:`snap_python.utils.wait_for_change` bound to
35
+ this endpoint's client.
36
+
37
+ :param change_id: The change to wait for.
38
+ :type change_id: str
39
+ :param timeout: Maximum number of seconds to wait, None waits forever.
40
+ :type timeout: float, optional
41
+ :param poll_interval: Seconds between two polls.
42
+ :type poll_interval: float, optional
43
+ :param progress_callback: Optional callable receiving intermediate changes.
44
+ :type progress_callback: callable, optional
45
+
46
+ :returns: The final change response.
47
+ :rtype: ChangesResponse
48
+
49
+ :raises SnapdAPIError: If the change reports an error or times out.
50
+ """
51
+ return await wait_for_change(
52
+ self._client,
53
+ change_id,
54
+ timeout=timeout,
55
+ poll_interval=poll_interval,
56
+ progress_callback=progress_callback,
57
+ )
58
+
59
+ async def list_installed_snaps(
60
+ self,
61
+ select: str | None = None,
62
+ snaps: list[str] | None = None,
63
+ ) -> InstalledSnapListResponse:
26
64
  """
27
65
  Asynchronously retrieves a list of installed snaps.
28
66
 
67
+ :param select: Which revisions snapd should return. ``"all"`` returns
68
+ every revision in each snap's sequence, inactive ones included;
69
+ ``"enabled"`` returns only the revision snapd currently has
70
+ enabled; ``"refresh-inhibited"`` returns only snaps whose refresh
71
+ is inhibited, i.e. those carrying a ``refresh-inhibit`` field with
72
+ the time the refresh may proceed. None (default) omits the
73
+ parameter so snapd applies its own default (only the enabled
74
+ revision of every snap).
75
+ :type select: str, optional
76
+ :param snaps: Only return these snap names. None (default) returns
77
+ every installed snap. snapd receives the names as a single
78
+ comma-separated ``snaps`` query parameter.
79
+ :type snaps: list[str], optional
80
+
29
81
  :returns: The response containing the list of installed snaps.
30
82
  :rtype: InstalledSnapListResponse
31
83
 
32
- :raises httpx.HTTPStatusError: If the response status code does not indicate success.
84
+ :raises SnapdAPIError: If snapd rejects the request, for example for an
85
+ unknown ``select`` value (``kind`` is ``bad-request``).
33
86
  """
87
+ params: dict[str, Any] = {}
88
+ if select is not None:
89
+ params["select"] = select
90
+ if snaps:
91
+ params["snaps"] = ",".join(snaps)
34
92
 
35
93
  response: httpx.Response = await self._client.request(
36
- "GET", self.common_endpoint
94
+ "GET", self.common_endpoint, params=params
37
95
  )
38
-
39
- if response.status_code > 299:
40
- raise httpx.HTTPStatusError(
41
- request=response.request,
42
- response=response,
43
- message=f"Invalid status code in response: {response.status_code}",
44
- )
45
96
  return InstalledSnapListResponse.model_validate_json(response.content)
46
97
 
47
98
  async def get_snap_info(self, snap: str) -> SingleInstalledSnapResponse:
@@ -61,15 +112,47 @@ class SnapsEndpoints:
61
112
  "GET", f"{self.common_endpoint}/{snap}"
62
113
  )
63
114
  except httpx.HTTPStatusError as e:
64
- logger.debug(
65
- "Bad status code from get_snap_info on snap %s: %s",
66
- snap,
67
- e.response.status_code,
68
- )
69
- response = e.response
115
+ if e.response.status_code != httpx.codes.NOT_FOUND:
116
+ logger.debug(
117
+ "Bad status code from get_snap_info on snap %s: %s",
118
+ snap,
119
+ e.response.status_code,
120
+ )
121
+ if isinstance(e, SnapdAPIError):
122
+ # Already carries the parsed kind/value envelope.
123
+ raise
124
+ raise SnapdAPIError(
125
+ f"Failed to get info for snap {snap}: "
126
+ f"HTTP {e.response.status_code}",
127
+ response=e.response,
128
+ ) from e
129
+ logger.debug("Snap %s is not installed (HTTP 404)", snap)
130
+ return SingleInstalledSnapResponse.model_validate_json(e.response.content)
70
131
 
71
132
  return SingleInstalledSnapResponse.model_validate_json(response.content)
72
133
 
134
+ async def get_installed_snap(self, snap: str) -> InstalledSnap | None:
135
+ """
136
+ Get information about an installed snap.
137
+
138
+ :param snap: The name of the snap to inspect.
139
+ :type snap: str
140
+
141
+ :returns: The installed snap, or None if the snap is not installed.
142
+ :rtype: InstalledSnap | None
143
+
144
+ :raises SnapdAPIError: If snapd reports an unexpected error.
145
+ """
146
+ response = await self.get_snap_info(snap)
147
+ if isinstance(response.result, InstalledSnap):
148
+ return response.result
149
+ if response.status_code == httpx.codes.NOT_FOUND:
150
+ return None
151
+ raise SnapdAPIError(
152
+ f"Unexpected response while getting snap {snap}: "
153
+ f"HTTP {response.status_code}"
154
+ )
155
+
73
156
  async def is_snap_installed(self, snap: str) -> bool:
74
157
  """
75
158
  Check if a snap package is installed.
@@ -81,15 +164,195 @@ class SnapsEndpoints:
81
164
  :rtype: bool
82
165
  """
83
166
 
84
- snap_info = await self.get_snap_info(snap)
85
- if snap_info.status == "OK":
86
- return True
87
- return False
167
+ return await self.get_installed_snap(snap) is not None
168
+
169
+ @staticmethod
170
+ def _sideload_form_data(
171
+ filename: str,
172
+ channel: str | None = None,
173
+ classic: bool = False,
174
+ dangerous: bool = False,
175
+ devmode: bool = False,
176
+ jailmode: bool = False,
177
+ ) -> dict[str, str]:
178
+ """Build the multipart form snapd honors for a sideload.
179
+
180
+ The daemon's multipart handler (``sideloadOrTrySnap`` in
181
+ ``daemon/api_sideload_n_try.go``) only special-cases ``action ==
182
+ "try"``; every other action is a path install. These field names match
183
+ what snapd's own client writes (``client/snap_op.go``).
184
+
185
+ :param filename: Path to the snap file, sent as ``snap-path``.
186
+ :type filename: str
187
+ :param channel: Optional channel to send with the sideload.
188
+ :type channel: str, optional
189
+ :param classic: Whether to request classic confinement.
190
+ :type classic: bool
191
+ :param dangerous: Whether to allow unasserted snaps.
192
+ :type dangerous: bool
193
+ :param devmode: Whether to request devmode.
194
+ :type devmode: bool
195
+ :param jailmode: Whether to request jailmode.
196
+ :type jailmode: bool
197
+
198
+ :returns: Form fields to send alongside the ``snap`` file part.
199
+ :rtype: dict[str, str]
200
+ """
201
+ form_data = {"action": "install", "snap-path": filename}
202
+ if channel is not None:
203
+ form_data["channel"] = channel
204
+ for key, value in (
205
+ ("classic", classic),
206
+ ("dangerous", dangerous),
207
+ ("devmode", devmode),
208
+ ("jailmode", jailmode),
209
+ ):
210
+ if value:
211
+ form_data[key] = "true"
212
+ return form_data
213
+
214
+ @staticmethod
215
+ def _multi_snap_payload(
216
+ action: str,
217
+ snaps: list[str] | None = None,
218
+ *,
219
+ transaction: str | None = None,
220
+ validation_sets: list[str] | None = None,
221
+ quota_group: str | None = None,
222
+ ignore_running: bool = False,
223
+ purge: bool = False,
224
+ terminate: bool = False,
225
+ time: str | None = None,
226
+ hold_level: str | None = None,
227
+ ) -> dict[str, Any]:
228
+ """Build the JSON body of a multi-snap ``POST /v2/snaps`` request.
229
+
230
+ Only options snapd accepts for the multi-snap form are emitted, and
231
+ unset ones are omitted entirely. The daemon rejects the single-snap
232
+ options ``channel``, ``revision``, ``devmode``, ``jailmode``,
233
+ ``cohort-key``, ``leave-cohort``, ``prefer`` and
234
+ ``allow-unsupported-instances`` for this form ("unsupported option
235
+ provided for multi-snap operation"), so callers must use the
236
+ single-snap methods for those.
237
+
238
+ An empty ``snaps`` list is omitted from the body; snapd reads the
239
+ missing field as "all snaps" for the ``refresh``, ``hold`` and
240
+ ``unhold`` actions.
241
+
242
+ :param action: The snapd action, for example ``"install"``.
243
+ :type action: str
244
+ :param snaps: Snap names to act on. None or empty is omitted.
245
+ :type snaps: list[str], optional
246
+ :param transaction: ``"per-snap"`` or ``"all-snaps"``; snapd only
247
+ accepts it for install and refresh.
248
+ :type transaction: str, optional
249
+ :param validation_sets: Validation sets to enforce on a refresh.
250
+ :type validation_sets: list[str], optional
251
+ :param quota_group: Quota group to install into; snapd only accepts it
252
+ for install.
253
+ :type quota_group: str, optional
254
+ :param ignore_running: Whether to proceed while the snap's apps run.
255
+ :type ignore_running: bool
256
+ :param purge: Also remove the snap's data (remove only).
257
+ :type purge: bool
258
+ :param terminate: Kill the snap's processes before removal (remove
259
+ only).
260
+ :type terminate: bool
261
+ :param time: When the hold expires, ``"forever"`` or an RFC3339
262
+ timestamp (hold only).
263
+ :type time: str, optional
264
+ :param hold_level: ``"auto-refresh"`` or ``"general"`` (hold only).
265
+ :type hold_level: str, optional
266
+
267
+ :returns: JSON-serialisable request body.
268
+ :rtype: dict[str, Any]
269
+ """
270
+ payload: dict[str, Any] = {"action": action}
271
+ if snaps:
272
+ payload["snaps"] = list(snaps)
273
+ if transaction is not None:
274
+ payload["transaction"] = transaction
275
+ if validation_sets:
276
+ payload["validation-sets"] = list(validation_sets)
277
+ if quota_group is not None:
278
+ payload["quota-group"] = quota_group
279
+ if ignore_running:
280
+ payload["ignore-running"] = True
281
+ if purge:
282
+ payload["purge"] = True
283
+ if terminate:
284
+ payload["terminate"] = True
285
+ if time is not None:
286
+ payload["time"] = time
287
+ if hold_level is not None:
288
+ payload["hold-level"] = hold_level
289
+ return payload
290
+
291
+ async def _post_snap_action(
292
+ self,
293
+ snap: str,
294
+ payload: dict[str, Any],
295
+ *,
296
+ wait: bool,
297
+ timeout: float | None,
298
+ ) -> AsyncResponse | ChangesResponse:
299
+ """POST ``payload`` to ``/v2/snaps/{snap}`` and optionally wait.
300
+
301
+ :param snap: Name of the snap the action applies to.
302
+ :type snap: str
303
+ :param payload: JSON request body, including the ``action`` field.
304
+ :type payload: dict[str, Any]
305
+ :param wait: Whether to wait for the resulting change.
306
+ :type wait: bool
307
+ :param timeout: Maximum number of seconds to wait, None waits forever.
308
+ :type timeout: float, optional
309
+
310
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
311
+ :rtype: AsyncResponse | ChangesResponse
312
+
313
+ :raises SnapdAPIError: If snapd rejects the action.
314
+ """
315
+ raw_response: httpx.Response = await self._client.request(
316
+ "POST", f"{self.common_endpoint}/{snap}", json=payload
317
+ )
318
+ response = AsyncResponse.model_validate_json(raw_response.content)
319
+ if wait:
320
+ return await self._wait_for_change(response.change, timeout=timeout)
321
+ return response
322
+
323
+ async def _post_multi_snap_action(
324
+ self,
325
+ payload: dict[str, Any],
326
+ *,
327
+ wait: bool,
328
+ timeout: float | None,
329
+ ) -> AsyncResponse | ChangesResponse:
330
+ """POST ``payload`` to ``/v2/snaps`` and optionally wait.
331
+
332
+ :param payload: JSON request body, including the ``action`` field.
333
+ :type payload: dict[str, Any]
334
+ :param wait: Whether to wait for the resulting change.
335
+ :type wait: bool
336
+ :param timeout: Maximum number of seconds to wait, None waits forever.
337
+ :type timeout: float, optional
338
+
339
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
340
+ :rtype: AsyncResponse | ChangesResponse
341
+
342
+ :raises SnapdAPIError: If snapd rejects the action.
343
+ """
344
+ raw_response: httpx.Response = await self._client.request(
345
+ "POST", self.common_endpoint, json=payload
346
+ )
347
+ response = AsyncResponse.model_validate_json(raw_response.content)
348
+ if wait:
349
+ return await self._wait_for_change(response.change, timeout=timeout)
350
+ return response
88
351
 
89
352
  async def install_snap(
90
353
  self,
91
354
  snap: str,
92
- channel: str = "stable",
355
+ channel: str | None = None,
93
356
  classic: bool = False,
94
357
  dangerous: bool = False,
95
358
  devmode: bool = False,
@@ -97,15 +360,20 @@ class SnapsEndpoints:
97
360
  revision: int = None,
98
361
  filename: str = None,
99
362
  wait: bool = False,
363
+ timeout: float | None = None,
100
364
  ) -> AsyncResponse | ChangesResponse:
101
365
  """
102
366
  Install or sideload a snap.
103
367
 
104
368
  To sideload a snap, provide the filename parameter with the path to the snap file.
369
+ snapd accepts a locally injected snap whose assertion is valid without
370
+ ``dangerous``; that flag is only needed for unasserted snaps and is
371
+ passed through untouched.
105
372
 
106
373
  :param snap: Name of the snap to install.
107
374
  :type snap: str
108
- :param channel: Channel to install, defaults to "stable".
375
+ :param channel: Channel to install from. None (default) lets snapd use
376
+ its own default channel.
109
377
  :type channel: str, optional
110
378
  :param classic: Install with classic confinement, defaults to False.
111
379
  :type classic: bool, optional
@@ -121,9 +389,10 @@ class SnapsEndpoints:
121
389
  :type filename: str, optional
122
390
  :param wait: Whether to wait for snap to install. If not waiting, will return async response with change id, defaults to False.
123
391
  :type wait: bool, optional
392
+ :param timeout: Maximum number of seconds to wait for the install to finish, defaults to None (wait forever).
393
+ :type timeout: float, optional
124
394
 
125
395
  :raises FileNotFoundError: If the specified snap file does not exist.
126
- :raises ValueError: If attempting to sideload without the dangerous flag set to True.
127
396
  :raises SnapdAPIError: If there is an error during the snap install.
128
397
 
129
398
  :returns: If wait is True, will return ChangesResponse. Otherwise, will return AsyncResponse.
@@ -131,28 +400,35 @@ class SnapsEndpoints:
131
400
  """
132
401
  request_data = {
133
402
  "action": "install",
134
- "channel": channel,
135
403
  "classic": classic,
136
404
  "dangerous": dangerous,
137
405
  "devmode": devmode,
138
406
  "jailmode": jailmode,
139
407
  }
408
+ if channel is not None:
409
+ request_data["channel"] = channel
140
410
  if revision:
141
411
  request_data["revision"] = revision
142
412
  if filename:
143
413
  # sideload
144
- if not Path(filename).exists():
414
+ snap_path = Path(filename)
415
+ if not snap_path.exists():
145
416
  raise FileNotFoundError(f"File {filename} does not exist")
146
- if request_data.get("dangerous") is not True:
147
- raise ValueError(
148
- "Cannot sideload snap without dangerous flag set to True"
149
- )
150
- raw_response: httpx.Response = await self._client.request(
151
- "POST",
152
- f"{self.common_endpoint}",
153
- data=request_data,
154
- files={"snap": open(filename, "rb")},
417
+ form_data = self._sideload_form_data(
418
+ filename=str(snap_path),
419
+ channel=channel,
420
+ classic=classic,
421
+ dangerous=dangerous,
422
+ devmode=devmode,
423
+ jailmode=jailmode,
155
424
  )
425
+ with open(snap_path, "rb") as snap_file:
426
+ raw_response: httpx.Response = await self._client.request(
427
+ "POST",
428
+ f"{self.common_endpoint}",
429
+ data=form_data,
430
+ files={"snap": (snap_path.name, snap_file)},
431
+ )
156
432
  else:
157
433
  # install from default snap store
158
434
  raw_response: httpx.Response = await self._client.request(
@@ -160,24 +436,7 @@ class SnapsEndpoints:
160
436
  )
161
437
  response = AsyncResponse.model_validate_json(raw_response.content)
162
438
  if wait:
163
- changes_id = response.change
164
- previous_changes = None
165
- while True:
166
- try:
167
- changes = await self._client.get_changes_by_id(changes_id)
168
- logger.debug("Progress: %s", changes.result.overall_progress)
169
- except httpx.HTTPError:
170
- if going_to_reload_daemon(previous_changes):
171
- logger.debug("Waiting for daemon to reload")
172
- changes = previous_changes
173
-
174
- if changes.ready:
175
- break
176
- if changes.result.err:
177
- raise SnapdAPIError(f"Error in snap install: {changes.result.err}")
178
- await asyncio.sleep(0.1)
179
- previous_changes = changes
180
- return changes
439
+ return await self._wait_for_change(response.change, timeout=timeout)
181
440
  return response
182
441
 
183
442
  async def remove_snap(
@@ -186,6 +445,7 @@ class SnapsEndpoints:
186
445
  purge: bool = False,
187
446
  terminate: bool = False,
188
447
  wait: bool = False,
448
+ timeout: float | None = None,
189
449
  ) -> AsyncResponse | ChangesResponse:
190
450
  """
191
451
  Asynchronously removes a snap package.
@@ -198,6 +458,8 @@ class SnapsEndpoints:
198
458
  :type terminate: bool, optional
199
459
  :param wait: If True, waits for the removal process to complete. Defaults to False.
200
460
  :type wait: bool, optional
461
+ :param timeout: Maximum number of seconds to wait for the removal to finish, defaults to None (wait forever).
462
+ :type timeout: float, optional
201
463
 
202
464
  :returns: The response from the snapd API, either an asynchronous response or a changes response if waiting for completion.
203
465
  :rtype: AsyncResponse | ChangesResponse
@@ -216,30 +478,14 @@ class SnapsEndpoints:
216
478
  response = AsyncResponse.model_validate_json(raw_response.content)
217
479
 
218
480
  if wait:
219
- changes_id = response.change
220
- previous_changes = None
221
- while True:
222
- try:
223
- changes = await self._client.get_changes_by_id(changes_id)
224
- except httpx.HTTPError:
225
- if going_to_reload_daemon(previous_changes):
226
- logger.debug("Waiting for daemon to reload")
227
- await asyncio.sleep(0.1)
228
- continue
229
- if changes.ready:
230
- break
231
- if changes.result.err:
232
- raise SnapdAPIError(f"Error in snap remove: {changes.result.err}")
233
- await asyncio.sleep(0.1)
234
- previous_changes = changes
235
- return changes
481
+ return await self._wait_for_change(response.change, timeout=timeout)
236
482
 
237
483
  return response
238
484
 
239
485
  async def refresh_snap(
240
486
  self,
241
487
  snap: str,
242
- channel: str = "stable",
488
+ channel: str | None = None,
243
489
  classic: bool = False,
244
490
  dangerous: bool = False,
245
491
  devmode: bool = False,
@@ -248,13 +494,15 @@ class SnapsEndpoints:
248
494
  revision: int = None,
249
495
  filename: str = None,
250
496
  wait: bool = False,
497
+ timeout: float | None = None,
251
498
  ) -> AsyncResponse | ChangesResponse:
252
499
  """
253
500
  Refreshes a snap package.
254
501
 
255
502
  :param snap: The name of the snap package to refresh.
256
503
  :type snap: str
257
- :param channel: The channel to refresh the snap from. Defaults to "stable".
504
+ :param channel: Channel to refresh from. None (default) keeps the
505
+ currently tracked channel.
258
506
  :type channel: str, optional
259
507
  :param classic: Whether to use classic confinement. Defaults to False.
260
508
  :type classic: bool, optional
@@ -272,71 +520,536 @@ class SnapsEndpoints:
272
520
  :type filename: str, optional
273
521
  :param wait: Whether to wait for the refresh operation to complete. Defaults to False.
274
522
  :type wait: bool, optional
523
+ :param timeout: Maximum number of seconds to wait for the refresh to finish, defaults to None (wait forever).
524
+ :type timeout: float, optional
275
525
 
276
526
  :returns: The response from the refresh operation.
277
527
  :rtype: AsyncResponse | ChangesResponse
278
528
 
279
529
  :raises FileNotFoundError: If the specified snap file does not exist.
280
- :raises ValueError: If attempting to sideload without the dangerous flag set to True.
281
530
  :raises SnapdAPIError: If there is an error during the snap refresh.
282
531
  """
283
532
  request_data = {
284
533
  "action": "refresh",
285
- "channel": channel,
286
534
  "classic": classic,
287
535
  "dangerous": dangerous,
288
536
  "devmode": devmode,
289
537
  "ignore_validation": ignore_validation,
290
538
  "jailmode": jailmode,
291
539
  }
540
+ if channel is not None:
541
+ request_data["channel"] = channel
292
542
  if revision:
293
543
  request_data["revision"] = revision
294
544
  if filename:
295
- # sideload
296
- if not Path(filename).exists():
545
+ # Sideload. The daemon's multipart handler only treats
546
+ # action == "try" specially; every other value is a path install,
547
+ # so use "install" here instead of "refresh".
548
+ snap_path = Path(filename)
549
+ if not snap_path.exists():
297
550
  raise FileNotFoundError(f"File {filename} does not exist")
298
- if request_data.get("dangerous") is not True:
299
- raise ValueError(
300
- "Cannot sideload snap without dangerous flag set to True"
301
- )
302
- raw_response: httpx.Response = await self._client.request(
303
- "POST",
304
- f"{self.common_endpoint}",
305
- data=request_data,
306
- files={"snap": open(filename, "rb")},
551
+ form_data = self._sideload_form_data(
552
+ filename=str(snap_path),
553
+ channel=channel,
554
+ classic=classic,
555
+ dangerous=dangerous,
556
+ devmode=devmode,
557
+ jailmode=jailmode,
307
558
  )
559
+ with open(snap_path, "rb") as snap_file:
560
+ raw_response: httpx.Response = await self._client.request(
561
+ "POST",
562
+ f"{self.common_endpoint}",
563
+ data=form_data,
564
+ files={"snap": (snap_path.name, snap_file)},
565
+ )
308
566
  else:
309
- # install from default snap store
567
+ # refresh from default snap store
310
568
  raw_response: httpx.Response = await self._client.request(
311
569
  "POST", f"{self.common_endpoint}/{snap}", json=request_data
312
570
  )
313
571
  response = AsyncResponse.model_validate_json(raw_response.content)
314
572
  if wait:
315
- changes_id = response.change
316
- previous_changes = None
317
- while True:
318
- try:
319
- changes = await self._client.get_changes_by_id(changes_id)
320
- logger.debug("Progress: %s", changes.result.overall_progress)
321
- except httpx.HTTPError:
322
- if going_to_reload_daemon(previous_changes):
323
- logger.debug("Waiting for daemon to reload")
324
- await asyncio.sleep(0.1)
325
- continue
326
-
327
- if changes.ready:
328
- break
329
- if changes.result.err:
330
- raise SnapdAPIError(f"Error in snap remove: {changes.result.err}")
331
- await asyncio.sleep(0.1)
332
- previous_changes = changes
333
- return changes
573
+ return await self._wait_for_change(response.change, timeout=timeout)
334
574
  return response
335
575
 
576
+ async def install_snaps(
577
+ self,
578
+ snaps: list[str],
579
+ transaction: str | None = None,
580
+ validation_sets: list[str] | None = None,
581
+ quota_group: str | None = None,
582
+ ignore_running: bool = False,
583
+ wait: bool = False,
584
+ timeout: float | None = None,
585
+ ) -> AsyncResponse | ChangesResponse:
586
+ """
587
+ Install several snaps in a single change (JSON ``POST /v2/snaps``).
588
+
589
+ This is the only form that can put multiple snaps in one change,
590
+ group them into a transaction and assign a quota group. snapd rejects
591
+ the single-snap options (channel, revision, devmode, jailmode,
592
+ cohort-key, leave-cohort, prefer) here, so per-snap overrides require
593
+ calling :meth:`install_snap` once per snap.
594
+
595
+ :param snaps: Names of the snaps to install. Must not be empty; snapd
596
+ answers "cannot install zero snaps" otherwise.
597
+ :type snaps: list[str]
598
+ :param transaction: ``"per-snap"`` treats every snap as its own
599
+ transaction, ``"all-snaps"`` reverts everything when one snap
600
+ fails. None (default) lets snapd use its own default.
601
+ :type transaction: str, optional
602
+ :param validation_sets: Validation sets to enforce. snapd accepts the
603
+ field for install but only acts on it while refreshing; use
604
+ :meth:`refresh_snaps` to enforce them.
605
+ :type validation_sets: list[str], optional
606
+ :param quota_group: Quota group the snaps should be placed in. snapd
607
+ only accepts a quota group on install.
608
+ :type quota_group: str, optional
609
+ :param ignore_running: Install even if the snaps' applications are
610
+ running. Defaults to False.
611
+ :type ignore_running: bool
612
+ :param wait: Whether to wait for the change to reach a terminal state.
613
+ Defaults to False.
614
+ :type wait: bool
615
+ :param timeout: Maximum number of seconds to wait, defaults to None
616
+ (wait forever).
617
+ :type timeout: float, optional
618
+
619
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
620
+ :rtype: AsyncResponse | ChangesResponse
621
+
622
+ :raises SnapdAPIError: If snapd rejects the install.
623
+ """
624
+ payload = self._multi_snap_payload(
625
+ "install",
626
+ snaps,
627
+ transaction=transaction,
628
+ validation_sets=validation_sets,
629
+ quota_group=quota_group,
630
+ ignore_running=ignore_running,
631
+ )
632
+ return await self._post_multi_snap_action(payload, wait=wait, timeout=timeout)
633
+
634
+ async def refresh_snaps(
635
+ self,
636
+ snaps: list[str] | None = None,
637
+ transaction: str | None = None,
638
+ validation_sets: list[str] | None = None,
639
+ ignore_running: bool = False,
640
+ wait: bool = False,
641
+ timeout: float | None = None,
642
+ ) -> AsyncResponse | ChangesResponse:
643
+ """
644
+ Refresh several snaps, or every installed snap, in one change.
645
+
646
+ ``snaps=None`` (or an empty list) refreshes **every** installed snap:
647
+ the ``snaps`` field is omitted from the request and snapd treats that
648
+ as a full refresh, also updating the validation set assertions.
649
+ :meth:`refresh_all_snaps` is a convenience wrapper for that case.
650
+
651
+ ``validation_sets`` enforces validation sets instead of refreshing
652
+ named snaps; snapd rejects it together with a non-empty ``snaps`` list
653
+ ("snap names cannot be specified with validation sets to enforce").
654
+
655
+ :param snaps: Names of the snaps to refresh. None or empty refreshes
656
+ every installed snap.
657
+ :type snaps: list[str], optional
658
+ :param transaction: ``"per-snap"`` or ``"all-snaps"``; snapd defaults
659
+ to ``"per-snap"`` when omitted.
660
+ :type transaction: str, optional
661
+ :param validation_sets: Validation sets to enforce, for example
662
+ ``"account/name"`` or ``"account/name=42"``. Must be used without
663
+ snap names.
664
+ :type validation_sets: list[str], optional
665
+ :param ignore_running: Refresh even if the snaps' applications are
666
+ running. Defaults to False.
667
+ :type ignore_running: bool
668
+ :param wait: Whether to wait for the change to reach a terminal state.
669
+ Defaults to False.
670
+ :type wait: bool
671
+ :param timeout: Maximum number of seconds to wait, defaults to None
672
+ (wait forever).
673
+ :type timeout: float, optional
674
+
675
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
676
+ :rtype: AsyncResponse | ChangesResponse
677
+
678
+ :raises SnapdAPIError: If snapd rejects the refresh.
679
+ """
680
+ payload = self._multi_snap_payload(
681
+ "refresh",
682
+ snaps,
683
+ transaction=transaction,
684
+ validation_sets=validation_sets,
685
+ ignore_running=ignore_running,
686
+ )
687
+ return await self._post_multi_snap_action(payload, wait=wait, timeout=timeout)
688
+
689
+ async def refresh_all_snaps(
690
+ self,
691
+ transaction: str | None = None,
692
+ wait: bool = False,
693
+ timeout: float | None = None,
694
+ ) -> AsyncResponse | ChangesResponse:
695
+ """
696
+ Refresh every installed snap.
697
+
698
+ Thin wrapper around :meth:`refresh_snaps` with no snap names, which is
699
+ how snapd expresses a full refresh.
700
+
701
+ :param transaction: ``"per-snap"`` or ``"all-snaps"``. None (default)
702
+ lets snapd use ``"per-snap"``.
703
+ :type transaction: str, optional
704
+ :param wait: Whether to wait for the change to reach a terminal state.
705
+ Defaults to False.
706
+ :type wait: bool
707
+ :param timeout: Maximum number of seconds to wait, defaults to None
708
+ (wait forever).
709
+ :type timeout: float, optional
710
+
711
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
712
+ :rtype: AsyncResponse | ChangesResponse
713
+
714
+ :raises SnapdAPIError: If snapd rejects the refresh.
715
+ """
716
+ return await self.refresh_snaps(
717
+ transaction=transaction, wait=wait, timeout=timeout
718
+ )
719
+
720
+ async def remove_snaps(
721
+ self,
722
+ snaps: list[str],
723
+ purge: bool = False,
724
+ terminate: bool = False,
725
+ wait: bool = False,
726
+ timeout: float | None = None,
727
+ ) -> AsyncResponse | ChangesResponse:
728
+ """
729
+ Remove several snaps in a single change (JSON ``POST /v2/snaps``).
730
+
731
+ snapd accepts no transaction type for removal and no per-snap options;
732
+ ``purge`` and ``terminate`` apply to every listed snap.
733
+
734
+ :param snaps: Names of the snaps to remove.
735
+ :type snaps: list[str]
736
+ :param purge: Also remove the snaps' data. Defaults to False.
737
+ :type purge: bool
738
+ :param terminate: Kill the snaps' running processes before removal,
739
+ which may lose data. Defaults to False.
740
+ :type terminate: bool
741
+ :param wait: Whether to wait for the change to reach a terminal state.
742
+ Defaults to False.
743
+ :type wait: bool
744
+ :param timeout: Maximum number of seconds to wait, defaults to None
745
+ (wait forever).
746
+ :type timeout: float, optional
747
+
748
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
749
+ :rtype: AsyncResponse | ChangesResponse
750
+
751
+ :raises SnapdAPIError: If snapd rejects the removal.
752
+ """
753
+ payload = self._multi_snap_payload(
754
+ "remove", snaps, purge=purge, terminate=terminate
755
+ )
756
+ return await self._post_multi_snap_action(payload, wait=wait, timeout=timeout)
757
+
758
+ async def hold_snap(
759
+ self,
760
+ snap: str,
761
+ time: str = "forever",
762
+ hold_level: str = "general",
763
+ wait: bool = False,
764
+ timeout: float | None = None,
765
+ ) -> AsyncResponse | ChangesResponse:
766
+ """
767
+ Hold refreshes of a single snap.
768
+
769
+ :param snap: The snap whose refreshes should be held.
770
+ :type snap: str
771
+ :param time: ``"forever"`` or an RFC3339 timestamp, defaults to
772
+ ``"forever"``. snapd validates the format and answers 400 for
773
+ anything else.
774
+ :type time: str
775
+ :param hold_level: ``"general"`` (default) holds every refresh,
776
+ ``"auto-refresh"`` only holds automatic refreshes so an explicit
777
+ refresh still works. Current snapd requires this field for the
778
+ ``hold`` action and rejects any other value.
779
+ :type hold_level: str
780
+ :param wait: Whether to wait for the change to reach a terminal state.
781
+ Defaults to False.
782
+ :type wait: bool
783
+ :param timeout: Maximum number of seconds to wait, defaults to None
784
+ (wait forever).
785
+ :type timeout: float, optional
786
+
787
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
788
+ :rtype: AsyncResponse | ChangesResponse
789
+
790
+ :raises SnapdAPIError: If snapd rejects the hold, for example because
791
+ ``time`` is not ``"forever"``/RFC3339 or ``hold_level`` is
792
+ unknown.
793
+ """
794
+ payload = {
795
+ "action": "hold",
796
+ "time": time,
797
+ "hold-level": hold_level,
798
+ }
799
+ return await self._post_snap_action(snap, payload, wait=wait, timeout=timeout)
800
+
801
+ async def unhold_snap(
802
+ self,
803
+ snap: str,
804
+ wait: bool = False,
805
+ timeout: float | None = None,
806
+ ) -> AsyncResponse | ChangesResponse:
807
+ """
808
+ Release a refresh hold on a single snap.
809
+
810
+ Only the action is sent: snapd rejects both ``time`` and
811
+ ``hold-level`` for any action other than ``hold`` ("time can only be
812
+ specified for the \"hold\" action").
813
+
814
+ :param snap: The snap whose hold should be released.
815
+ :type snap: str
816
+ :param wait: Whether to wait for the change to reach a terminal state.
817
+ Defaults to False.
818
+ :type wait: bool
819
+ :param timeout: Maximum number of seconds to wait, defaults to None
820
+ (wait forever).
821
+ :type timeout: float, optional
822
+
823
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
824
+ :rtype: AsyncResponse | ChangesResponse
825
+
826
+ :raises SnapdAPIError: If snapd rejects the request.
827
+ """
828
+ return await self._post_snap_action(
829
+ snap, {"action": "unhold"}, wait=wait, timeout=timeout
830
+ )
831
+
832
+ async def hold_snaps(
833
+ self,
834
+ snaps: list[str],
835
+ time: str = "forever",
836
+ hold_level: str = "general",
837
+ wait: bool = False,
838
+ timeout: float | None = None,
839
+ ) -> AsyncResponse | ChangesResponse:
840
+ """
841
+ Hold refreshes of several snaps in one change.
842
+
843
+ :param snaps: The snaps whose refreshes should be held. Must not be
844
+ empty; an empty list is sent as a system-wide hold, for which
845
+ snapd only accepts ``hold_level="auto-refresh"``.
846
+ :type snaps: list[str]
847
+ :param time: ``"forever"`` or an RFC3339 timestamp, defaults to
848
+ ``"forever"``.
849
+ :type time: str
850
+ :param hold_level: ``"general"`` (default) or ``"auto-refresh"``.
851
+ :type hold_level: str
852
+ :param wait: Whether to wait for the change to reach a terminal state.
853
+ Defaults to False.
854
+ :type wait: bool
855
+ :param timeout: Maximum number of seconds to wait, defaults to None
856
+ (wait forever).
857
+ :type timeout: float, optional
858
+
859
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
860
+ :rtype: AsyncResponse | ChangesResponse
861
+
862
+ :raises SnapdAPIError: If snapd rejects the hold.
863
+ """
864
+ payload = self._multi_snap_payload(
865
+ "hold", snaps, time=time, hold_level=hold_level
866
+ )
867
+ return await self._post_multi_snap_action(payload, wait=wait, timeout=timeout)
868
+
869
+ async def unhold_snaps(
870
+ self,
871
+ snaps: list[str],
872
+ wait: bool = False,
873
+ timeout: float | None = None,
874
+ ) -> AsyncResponse | ChangesResponse:
875
+ """
876
+ Release refresh holds on several snaps in one change.
877
+
878
+ No ``time``/``hold-level`` is sent: snapd rejects either field for
879
+ anything but the ``hold`` action.
880
+
881
+ :param snaps: The snaps whose holds should be released. Must not be
882
+ empty; an omitted list is a system-wide unhold.
883
+ :type snaps: list[str]
884
+ :param wait: Whether to wait for the change to reach a terminal state.
885
+ Defaults to False.
886
+ :type wait: bool
887
+ :param timeout: Maximum number of seconds to wait, defaults to None
888
+ (wait forever).
889
+ :type timeout: float, optional
890
+
891
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
892
+ :rtype: AsyncResponse | ChangesResponse
893
+
894
+ :raises SnapdAPIError: If snapd rejects the request.
895
+ """
896
+ payload = self._multi_snap_payload("unhold", snaps)
897
+ return await self._post_multi_snap_action(payload, wait=wait, timeout=timeout)
898
+
899
+ async def hold_all_snaps(
900
+ self,
901
+ time: str = "forever",
902
+ hold_level: str = "auto-refresh",
903
+ wait: bool = False,
904
+ timeout: float | None = None,
905
+ ) -> AsyncResponse | ChangesResponse:
906
+ """
907
+ Hold refreshes for every installed snap.
908
+
909
+ snapd implements this as a configuration change of ``refresh.hold`` on
910
+ the ``core`` snap (``snapHoldMany`` with an empty ``snaps`` list), not
911
+ as a per-snap hold. Only ``hold_level="auto-refresh"`` is supported
912
+ for this form: snapd answers 400 with "holding general refreshes for
913
+ all snaps is not supported" for ``"general"``.
914
+
915
+ :param time: ``"forever"`` or an RFC3339 timestamp, defaults to
916
+ ``"forever"``.
917
+ :type time: str
918
+ :param hold_level: Only ``"auto-refresh"`` (the default) is accepted
919
+ by snapd for the system-wide form.
920
+ :type hold_level: str
921
+ :param wait: Whether to wait for the change to reach a terminal state.
922
+ Defaults to False.
923
+ :type wait: bool
924
+ :param timeout: Maximum number of seconds to wait, defaults to None
925
+ (wait forever).
926
+ :type timeout: float, optional
927
+
928
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
929
+ :rtype: AsyncResponse | ChangesResponse
930
+
931
+ :raises SnapdAPIError: If snapd rejects the hold.
932
+ """
933
+ payload = self._multi_snap_payload("hold", time=time, hold_level=hold_level)
934
+ return await self._post_multi_snap_action(payload, wait=wait, timeout=timeout)
935
+
936
+ async def unhold_all_snaps(
937
+ self,
938
+ wait: bool = False,
939
+ timeout: float | None = None,
940
+ ) -> AsyncResponse | ChangesResponse:
941
+ """
942
+ Release the system-wide refresh hold.
943
+
944
+ snapd implements this as a ``refresh.hold`` configuration change on
945
+ the ``core`` snap (``snapUnholdMany`` with an empty ``snaps`` list).
946
+
947
+ :param wait: Whether to wait for the change to reach a terminal state.
948
+ Defaults to False.
949
+ :type wait: bool
950
+ :param timeout: Maximum number of seconds to wait, defaults to None
951
+ (wait forever).
952
+ :type timeout: float, optional
953
+
954
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
955
+ :rtype: AsyncResponse | ChangesResponse
956
+
957
+ :raises SnapdAPIError: If snapd rejects the request.
958
+ """
959
+ payload = self._multi_snap_payload("unhold")
960
+ return await self._post_multi_snap_action(payload, wait=wait, timeout=timeout)
961
+
962
+ async def revert_snap(
963
+ self,
964
+ snap: str,
965
+ revision: int | None = None,
966
+ wait: bool = False,
967
+ timeout: float | None = None,
968
+ ) -> AsyncResponse | ChangesResponse:
969
+ """
970
+ Revert a snap to its previous revision, or to a specific one.
971
+
972
+ :param snap: The snap to revert.
973
+ :type snap: str
974
+ :param revision: Revision to revert to. None (default) rolls the snap
975
+ back one revision, like ``snap revert``; snapd accepts the
976
+ ``revision`` field for ``revert``.
977
+ :type revision: int, optional
978
+ :param wait: Whether to wait for the change to reach a terminal state.
979
+ Defaults to False.
980
+ :type wait: bool
981
+ :param timeout: Maximum number of seconds to wait, defaults to None
982
+ (wait forever).
983
+ :type timeout: float, optional
984
+
985
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
986
+ :rtype: AsyncResponse | ChangesResponse
987
+
988
+ :raises SnapdAPIError: If snapd rejects the revert, for example with
989
+ kind ``snap-change-conflict`` when another change for the snap is
990
+ in progress.
991
+ """
992
+ payload: dict[str, Any] = {"action": "revert"}
993
+ if revision is not None:
994
+ payload["revision"] = revision
995
+ return await self._post_snap_action(snap, payload, wait=wait, timeout=timeout)
996
+
997
+ async def switch_channel(
998
+ self,
999
+ snap: str,
1000
+ channel: str | None = None,
1001
+ cohort_key: str | None = None,
1002
+ leave_cohort: bool = False,
1003
+ wait: bool = False,
1004
+ timeout: float | None = None,
1005
+ ) -> AsyncResponse | ChangesResponse:
1006
+ """
1007
+ Switch the channel (and/or cohort) a snap tracks without refreshing.
1008
+
1009
+ snapd takes no ``revision`` for ``switch`` ("switch takes no
1010
+ revision") and refuses the request while another change for the snap
1011
+ is in progress, answering 409 with kind ``snap-change-conflict``.
1012
+
1013
+ :param snap: The snap to switch.
1014
+ :type snap: str
1015
+ :param channel: Channel to track, for example ``"latest/edge"``. snapd
1016
+ validates it with its channel parser. None (default) keeps the
1017
+ currently tracked channel, which is what a cohort-only switch
1018
+ needs.
1019
+ :type channel: str, optional
1020
+ :param cohort_key: Cohort to join. snapd rejects combining it with
1021
+ ``leave_cohort`` ("cannot specify both cohort-key and
1022
+ leave-cohort").
1023
+ :type cohort_key: str, optional
1024
+ :param leave_cohort: Leave the current cohort. Defaults to False.
1025
+ :type leave_cohort: bool
1026
+ :param wait: Whether to wait for the change to reach a terminal state.
1027
+ Defaults to False.
1028
+ :type wait: bool
1029
+ :param timeout: Maximum number of seconds to wait, defaults to None
1030
+ (wait forever).
1031
+ :type timeout: float, optional
1032
+
1033
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
1034
+ :rtype: AsyncResponse | ChangesResponse
1035
+
1036
+ :raises SnapdAPIError: If snapd rejects the switch, for example because
1037
+ the channel is invalid or the cohort options conflict.
1038
+ """
1039
+ payload: dict[str, Any] = {"action": "switch"}
1040
+ if channel is not None:
1041
+ payload["channel"] = channel
1042
+ if cohort_key is not None:
1043
+ payload["cohort-key"] = cohort_key
1044
+ if leave_cohort:
1045
+ payload["leave-cohort"] = True
1046
+ return await self._post_snap_action(snap, payload, wait=wait, timeout=timeout)
1047
+
336
1048
  async def disable_snap(
337
1049
  self,
338
1050
  snap: str,
339
1051
  wait: bool = False,
1052
+ timeout: float | None = None,
340
1053
  ) -> AsyncResponse | ChangesResponse:
341
1054
  """
342
1055
  Disables a snap package.
@@ -345,6 +1058,8 @@ class SnapsEndpoints:
345
1058
  :type snap: str
346
1059
  :param wait: Whether to wait for the disable operation to complete. Defaults to False.
347
1060
  :type wait: bool, optional
1061
+ :param timeout: Maximum number of seconds to wait for the disable to finish, defaults to None (wait forever).
1062
+ :type timeout: float, optional
348
1063
 
349
1064
  :returns: The response from the disable operation.
350
1065
  :rtype: AsyncResponse | ChangesResponse
@@ -361,28 +1076,7 @@ class SnapsEndpoints:
361
1076
  response = AsyncResponse.model_validate_json(raw_response.content)
362
1077
 
363
1078
  if wait:
364
- changes_id = response.change
365
- previous_changes = None
366
- while True:
367
- try:
368
- changes = await self._client.get_changes_by_id(changes_id)
369
- except httpx.HTTPError:
370
- if going_to_reload_daemon(previous_changes):
371
- logger.debug("Waiting for daemon to reload")
372
- await asyncio.sleep(0.1)
373
- continue
374
- raise
375
- if changes.ready:
376
- break
377
- if isinstance(changes.result, BaseErrorResult):
378
- raise SnapdAPIError(
379
- f"Error in snap disable: {changes.result.message}"
380
- )
381
- if changes.result.err:
382
- raise SnapdAPIError(f"Error in snap disable: {changes.result.err}")
383
- await asyncio.sleep(0.1)
384
- previous_changes = changes
385
- return changes
1079
+ return await self._wait_for_change(response.change, timeout=timeout)
386
1080
 
387
1081
  return response
388
1082
 
@@ -390,6 +1084,7 @@ class SnapsEndpoints:
390
1084
  self,
391
1085
  snap: str,
392
1086
  wait: bool = False,
1087
+ timeout: float | None = None,
393
1088
  ) -> AsyncResponse | ChangesResponse:
394
1089
  """
395
1090
  enables a snap package.
@@ -398,6 +1093,8 @@ class SnapsEndpoints:
398
1093
  :type snap: str
399
1094
  :param wait: Whether to wait for the enable operation to complete. Defaults to False.
400
1095
  :type wait: bool, optional
1096
+ :param timeout: Maximum number of seconds to wait for the enable to finish, defaults to None (wait forever).
1097
+ :type timeout: float, optional
401
1098
 
402
1099
  :returns: The response from the enable operation.
403
1100
  :rtype: AsyncResponse | ChangesResponse
@@ -414,31 +1111,52 @@ class SnapsEndpoints:
414
1111
  response = AsyncResponse.model_validate_json(raw_response.content)
415
1112
 
416
1113
  if wait:
417
- changes_id = response.change
418
- previous_changes = None
419
- while True:
420
- try:
421
- changes = await self._client.get_changes_by_id(changes_id)
422
- except httpx.HTTPError:
423
- if going_to_reload_daemon(previous_changes):
424
- logger.debug("Waiting for daemon to reload")
425
- await asyncio.sleep(0.1)
426
- continue
427
- raise
428
- if changes.ready:
429
- break
430
- if isinstance(changes.result, BaseErrorResult):
431
- raise SnapdAPIError(
432
- f"Error in snap enable: {changes.result.message}"
433
- )
434
- if changes.result.err:
435
- raise SnapdAPIError(f"Error in snap enable: {changes.result.err}")
436
- await asyncio.sleep(0.1)
437
- previous_changes = changes
438
- return changes
1114
+ return await self._wait_for_change(response.change, timeout=timeout)
439
1115
 
440
1116
  return response
441
1117
 
1118
+ async def list_apps(
1119
+ self,
1120
+ names: list[str] | None = None,
1121
+ services_only: bool = False,
1122
+ global_scope: bool | None = None,
1123
+ ) -> AppsResponse:
1124
+ """
1125
+ Retrieves applications of the installed snaps.
1126
+
1127
+ :param names: Snap names (all their apps are returned) or
1128
+ ``snap.app`` entries (that single app). snapd receives them as a
1129
+ comma-separated ``names`` query parameter. None (default) returns
1130
+ every app of the requested kind.
1131
+ :type names: list[str], optional
1132
+ :param services_only: Only return background daemons. snapd receives
1133
+ this as ``select=service``. Defaults to False.
1134
+ :type services_only: bool
1135
+ :param global_scope: For user services, report the global enable
1136
+ status instead of the status for the requesting user. None
1137
+ (default) omits the parameter; snapd always uses the global status
1138
+ for root.
1139
+ :type global_scope: bool, optional
1140
+
1141
+ :returns: The response containing the matching applications.
1142
+ :rtype: AppsResponse
1143
+
1144
+ :raises SnapdAPIError: If snapd rejects the request, for example when a
1145
+ name does not resolve to an app or the snap is not installed.
1146
+ """
1147
+ params: dict[str, Any] = {}
1148
+ if names:
1149
+ params["names"] = ",".join(names)
1150
+ if services_only:
1151
+ params["select"] = "service"
1152
+ if global_scope is not None:
1153
+ params["global"] = "true" if global_scope else "false"
1154
+
1155
+ response: httpx.Response = await self._client.request(
1156
+ "GET", "apps", params=params
1157
+ )
1158
+ return AppsResponse.model_validate_json(response.content)
1159
+
442
1160
  async def get_snap_apps(
443
1161
  self,
444
1162
  snap: str,
@@ -447,6 +1165,8 @@ class SnapsEndpoints:
447
1165
  """
448
1166
  Retrieves the applications associated with a specific snap.
449
1167
 
1168
+ Thin wrapper around :meth:`list_apps` restricted to one snap.
1169
+
450
1170
  :param snap: The name of the snap to retrieve applications for.
451
1171
  :type snap: str
452
1172
  :param services_only: Whether to retrieve only service applications.
@@ -454,15 +1174,149 @@ class SnapsEndpoints:
454
1174
 
455
1175
  :returns: The response containing the list of applications for the specified snap.
456
1176
  :rtype: AppsResponse
1177
+
1178
+ :raises SnapdAPIError: If snapd rejects the request.
457
1179
  """
1180
+ return await self.list_apps(names=[snap], services_only=services_only)
458
1181
 
459
- payload: dict[str, Any] = {"names": [snap]}
460
- if services_only:
461
- payload["select"] = "service"
1182
+ async def _post_app_action(
1183
+ self,
1184
+ action: str,
1185
+ names: list[str],
1186
+ *,
1187
+ reload: bool = False,
1188
+ wait: bool = False,
1189
+ timeout: float | None = None,
1190
+ ) -> AsyncResponse | ChangesResponse:
1191
+ """POST a service instruction to ``/v2/apps`` and optionally wait.
462
1192
 
463
- response: httpx.Response = await self._client.request(
464
- "GET", "apps", params=payload
1193
+ :param action: ``"start"``, ``"stop"`` or ``"restart"``.
1194
+ :type action: str
1195
+ :param names: Snap names or ``snap.app`` names to operate on.
1196
+ :type names: list[str]
1197
+ :param reload: For ``"restart"``, ask snapd to reload the service when
1198
+ it has a reload command instead of restarting it. Defaults to
1199
+ False.
1200
+ :type reload: bool
1201
+ :param wait: Whether to wait for the resulting change.
1202
+ :type wait: bool
1203
+ :param timeout: Maximum number of seconds to wait, None waits forever.
1204
+ :type timeout: float, optional
1205
+
1206
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
1207
+ :rtype: AsyncResponse | ChangesResponse
1208
+
1209
+ :raises SnapdAPIError: If snapd rejects the service instruction.
1210
+ """
1211
+ payload: dict[str, Any] = {"action": action, "names": names}
1212
+ if reload:
1213
+ payload["reload"] = True
1214
+ raw_response: httpx.Response = await self._client.request(
1215
+ "POST", "apps", json=payload
1216
+ )
1217
+ response = AsyncResponse.model_validate_json(raw_response.content)
1218
+ if wait:
1219
+ return await self._wait_for_change(response.change, timeout=timeout)
1220
+ return response
1221
+
1222
+ async def start_apps(
1223
+ self,
1224
+ names: list[str],
1225
+ wait: bool = False,
1226
+ timeout: float | None = None,
1227
+ ) -> AsyncResponse | ChangesResponse:
1228
+ """
1229
+ Start the services of one or more snaps.
1230
+
1231
+ ``POST /v2/apps`` with ``{"action": "start", "names": [...]}``. Each
1232
+ name may be a snap (all of its services are started) or ``snap.app``
1233
+ (only that service); snapd only operates on services and rejects an
1234
+ empty list with 400.
1235
+
1236
+ :param names: Snap names or ``snap.app`` names to start. Must not be
1237
+ empty.
1238
+ :type names: list[str]
1239
+ :param wait: Whether to wait for the change to reach a terminal state.
1240
+ Defaults to False.
1241
+ :type wait: bool
1242
+ :param timeout: Maximum number of seconds to wait, defaults to None
1243
+ (wait forever).
1244
+ :type timeout: float, optional
1245
+
1246
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
1247
+ :rtype: AsyncResponse | ChangesResponse
1248
+
1249
+ :raises SnapdAPIError: If snapd rejects the start, for example with
1250
+ kind ``snap-change-conflict`` when another change for the snap is
1251
+ in progress.
1252
+ """
1253
+ return await self._post_app_action("start", names, wait=wait, timeout=timeout)
1254
+
1255
+ async def stop_apps(
1256
+ self,
1257
+ names: list[str],
1258
+ wait: bool = False,
1259
+ timeout: float | None = None,
1260
+ ) -> AsyncResponse | ChangesResponse:
1261
+ """
1262
+ Stop the services of one or more snaps.
1263
+
1264
+ ``POST /v2/apps`` with ``{"action": "stop", "names": [...]}``. Each
1265
+ name may be a snap or ``snap.app``; snapd only operates on services
1266
+ and rejects an empty list with 400.
1267
+
1268
+ :param names: Snap names or ``snap.app`` names to stop. Must not be
1269
+ empty.
1270
+ :type names: list[str]
1271
+ :param wait: Whether to wait for the change to reach a terminal state.
1272
+ Defaults to False.
1273
+ :type wait: bool
1274
+ :param timeout: Maximum number of seconds to wait, defaults to None
1275
+ (wait forever).
1276
+ :type timeout: float, optional
1277
+
1278
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
1279
+ :rtype: AsyncResponse | ChangesResponse
1280
+
1281
+ :raises SnapdAPIError: If snapd rejects the stop.
1282
+ """
1283
+ return await self._post_app_action("stop", names, wait=wait, timeout=timeout)
1284
+
1285
+ async def restart_apps(
1286
+ self,
1287
+ names: list[str],
1288
+ reload: bool = False,
1289
+ wait: bool = False,
1290
+ timeout: float | None = None,
1291
+ ) -> AsyncResponse | ChangesResponse:
1292
+ """
1293
+ Restart the services of one or more snaps.
1294
+
1295
+ ``POST /v2/apps`` with ``{"action": "restart", "names": [...]}``.
1296
+ snapd has no separate ``reload`` action on this endpoint (its dispatch
1297
+ table is start/stop/restart); instead ``"reload": true`` asks it to run
1298
+ the service's reload command where one exists and to restart it
1299
+ otherwise.
1300
+
1301
+ :param names: Snap names or ``snap.app`` names to restart. Must not be
1302
+ empty.
1303
+ :type names: list[str]
1304
+ :param reload: Send ``"reload": true`` so snapd reloads services that
1305
+ support it and restarts the rest. Defaults to False, which sends
1306
+ a plain restart.
1307
+ :type reload: bool
1308
+ :param wait: Whether to wait for the change to reach a terminal state.
1309
+ Defaults to False.
1310
+ :type wait: bool
1311
+ :param timeout: Maximum number of seconds to wait, defaults to None
1312
+ (wait forever).
1313
+ :type timeout: float, optional
1314
+
1315
+ :returns: AsyncResponse, or ChangesResponse when ``wait`` is True.
1316
+ :rtype: AsyncResponse | ChangesResponse
1317
+
1318
+ :raises SnapdAPIError: If snapd rejects the restart.
1319
+ """
1320
+ return await self._post_app_action(
1321
+ "restart", names, reload=reload, wait=wait, timeout=timeout
465
1322
  )
466
- if response.status_code != 200:
467
- raise SnapdAPIError(f"Failed to retrieve apps for snap: {snap}")
468
- return AppsResponse.model_validate_json(response.content)