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.
@@ -2,9 +2,10 @@ import functools
2
2
  import uuid
3
3
  from typing import Optional
4
4
 
5
- import retry
5
+ import httpx
6
6
  from httpx import AsyncClient, Response
7
7
 
8
+ from snap_python.schemas.common import VALID_SNAP_ARCHITECTURES
8
9
  from snap_python.schemas.store.categories import (
9
10
  VALID_CATEGORY_FIELDS,
10
11
  CategoryResponse,
@@ -28,6 +29,7 @@ from snap_python.schemas.store.track import (
28
29
  TrackRiskMap,
29
30
  channel_map_to_current_track_map,
30
31
  )
32
+ from snap_python.utils import async_retry
31
33
 
32
34
 
33
35
  class StoreEndpoints:
@@ -50,6 +52,10 @@ class StoreEndpoints:
50
52
  if headers is not None:
51
53
  self.store_client.headers.update(headers)
52
54
 
55
+ async def close(self) -> None:
56
+ """Close the underlying store HTTP client."""
57
+ await self.store_client.aclose()
58
+
53
59
  async def get_snap_details(self, snap_name: str, fields: list[str] | None = None):
54
60
  """
55
61
  Get details of a snap.
@@ -59,7 +65,9 @@ class StoreEndpoints:
59
65
  :param fields: The fields to include in the response.
60
66
  :type fields: list[str], optional
61
67
 
62
- :returns: The snap details.
68
+ :returns: The raw store JSON payload for the snap. Note that, unlike the
69
+ sibling methods of this class, the result is not validated into a
70
+ pydantic model.
63
71
  :rtype: dict
64
72
 
65
73
  :raises ValueError: If invalid fields are provided.
@@ -79,8 +87,16 @@ class StoreEndpoints:
79
87
  return response.json()
80
88
 
81
89
  async def get_snap_name_from_snap_id(self, snap_id: str) -> str | None:
90
+ """Resolve a snap name from its snap id using the configured store.
91
+
92
+ :param snap_id: The snap id to resolve.
93
+ :type snap_id: str
94
+
95
+ :returns: The snap name, or None if the store did not return one.
96
+ :rtype: str | None
97
+ """
82
98
  response = await self.store_client.get(
83
- f"https://api.snapcraft.io/v2/assertions/snap-declaration/16/{snap_id}"
99
+ f"{self.base_url}/assertions/snap-declaration/16/{snap_id}"
84
100
  )
85
101
  response.raise_for_status()
86
102
  response_json = response.json()
@@ -113,6 +129,8 @@ class StoreEndpoints:
113
129
  # get snap name from id, then proceed as usual
114
130
  if snap_id is not None:
115
131
  snap_name = await self.get_snap_name_from_snap_id(snap_id)
132
+ if not snap_name:
133
+ raise ValueError(f"Could not resolve a snap name for snap id {snap_id}")
116
134
 
117
135
  query = {}
118
136
  if fields is not None:
@@ -196,9 +214,9 @@ class StoreEndpoints:
196
214
  common_id: str | None = None,
197
215
  category: str | None = None,
198
216
  channel: str | None = None,
199
- confiement: str | None = None,
200
- featured: bool = False,
201
- private: bool = False,
217
+ confinement: str | None = None,
218
+ featured: bool | None = None,
219
+ private: bool | None = None,
202
220
  publisher: str | None = None,
203
221
  headers: dict[str, str] | None = None,
204
222
  ) -> SearchResponse:
@@ -209,21 +227,25 @@ class StoreEndpoints:
209
227
  :type query: str, optional
210
228
  :param fields: The fields to include in the response.
211
229
  :type fields: list[str], optional
212
- :param name_startswith: Filter snaps by name prefix.
230
+ :param name_startswith: Filter snaps by name prefix. Sent on the wire
231
+ as ``name-startswith``, as required by the store API.
213
232
  :type name_startswith: str, optional
214
233
  :param architecture: Filter snaps by architecture.
215
234
  :type architecture: str, optional
216
- :param common_id: Filter snaps by common ID.
235
+ :param common_id: Filter snaps by common ID. Sent on the wire as
236
+ ``common-id``, as required by the store API.
217
237
  :type common_id: str, optional
218
238
  :param category: Filter snaps by category.
219
239
  :type category: str, optional
220
240
  :param channel: Filter snaps by channel.
221
241
  :type channel: str, optional
222
- :param confiement: Filter snaps by confinement.
223
- :type confiement: str, optional
224
- :param featured: Filter snaps by featured status.
242
+ :param confinement: Filter snaps by confinement.
243
+ :type confinement: str, optional
244
+ :param featured: Filter snaps by featured status. Omitted from the
245
+ request when None.
225
246
  :type featured: bool, optional
226
- :param private: Filter snaps by private status.
247
+ :param private: Filter snaps by private status. Omitted from the
248
+ request when None.
227
249
  :type private: bool, optional
228
250
  :param publisher: Filter snaps by publisher.
229
251
  :type publisher: str, optional
@@ -236,14 +258,16 @@ class StoreEndpoints:
236
258
  :raises ValueError: If invalid fields are provided.
237
259
  """
238
260
  route = "/snaps/find"
261
+ # The store API uses hyphenated wire names; the Python keyword
262
+ # arguments stay snake_case for API stability.
239
263
  query_dict: dict = {
240
264
  "q": query,
241
- "name_startswith": name_startswith,
265
+ "name-startswith": name_startswith,
242
266
  "architecture": architecture,
243
- "common_id": common_id,
267
+ "common-id": common_id,
244
268
  "category": category,
245
269
  "channel": channel,
246
- "confinement": confiement,
270
+ "confinement": confinement,
247
271
  "featured": featured,
248
272
  "private": private,
249
273
  "publisher": publisher,
@@ -275,7 +299,7 @@ class StoreEndpoints:
275
299
  response.raise_for_status()
276
300
  return SearchResponse.model_validate_json(response.content)
277
301
 
278
- @retry.retry(Exception, tries=3, delay=2, backoff=2)
302
+ @async_retry(httpx.HTTPError, tries=3, delay=2, backoff=2)
279
303
  async def retry_get_snap_info(self, snap_name: str, fields: list[str]):
280
304
  """
281
305
  Retry getting snap information.
@@ -319,15 +343,7 @@ class StoreEndpoints:
319
343
  # use the old "/api/v1/snaps/names" to get all snaps for a given architecture
320
344
 
321
345
  # ensure valid arch
322
- if arch not in [
323
- "amd64",
324
- "arm64",
325
- "armhf",
326
- "i386",
327
- "ppc64el",
328
- "s390x",
329
- "riscv64",
330
- ]:
346
+ if arch not in VALID_SNAP_ARCHITECTURES:
331
347
  raise ValueError(f"Invalid architecture: {arch}")
332
348
 
333
349
  route = "/api/v1/snaps/names"
@@ -413,7 +429,7 @@ class StoreEndpoints:
413
429
  raise ValueError(
414
430
  f"Invalid fields. Allowed fields: {VALID_SNAP_REFRESH_FIELDS}"
415
431
  )
416
- payload["fields"] = fields
432
+ payload["fields"] = fields
417
433
 
418
434
  response = await self.snap_refresh(
419
435
  snap_name=snap_name,
@@ -479,7 +495,7 @@ class StoreEndpoints:
479
495
  raise ValueError(
480
496
  f"Invalid fields. Allowed fields: {VALID_SNAP_REFRESH_FIELDS}"
481
497
  )
482
- payload["fields"] = fields
498
+ payload["fields"] = fields
483
499
 
484
500
  response = await self.snap_refresh(
485
501
  snap_name=snap_name,
@@ -20,6 +20,7 @@ class Task(BaseModel):
20
20
  summary: str
21
21
  status: str
22
22
  progress: ProgressInfo
23
+ log: list[str] | None = None
23
24
  spawn_time: AwareDatetime = Field(
24
25
  validation_alias=AliasChoices("spawn-time", "spawn_time"),
25
26
  serialization_alias="spawn-time",
@@ -37,7 +38,9 @@ class ChangesResult(BaseModel):
37
38
  kind: str
38
39
  summary: str
39
40
  status: str
40
- tasks: list[Task]
41
+ # snapd tags tasks with ``omitempty``, and taskless changes exist: a
42
+ # repeated connect, or any change whose tasks have not been built yet.
43
+ tasks: list[Task] = Field(default_factory=list)
41
44
  ready: bool
42
45
  spawn_time: AwareDatetime = Field(
43
46
  validation_alias=AliasChoices("spawn-time", "spawn_time"),
@@ -70,3 +73,20 @@ class ChangesResponse(BaseResponse):
70
73
  if isinstance(self.result, BaseErrorResult):
71
74
  return True
72
75
  return self.result.ready
76
+
77
+
78
+ class ChangesListResponse(BaseResponse):
79
+ """Response of ``GET /v2/changes``.
80
+
81
+ snapd always returns a JSON array, empty rather than ``null`` when no
82
+ change matches, so :attr:`changes` is never ``None``.
83
+ """
84
+
85
+ result: list[ChangesResult] | BaseErrorResult
86
+ maintenance: MaintenanceInfo | None = None
87
+
88
+ @property
89
+ def changes(self) -> list[ChangesResult]:
90
+ if isinstance(self.result, BaseErrorResult):
91
+ return []
92
+ return self.result
@@ -1,11 +1,31 @@
1
1
  from enum import Enum
2
- from typing import Literal, Optional
2
+ from typing import Any, Literal, Optional
3
3
 
4
- from pydantic import AliasChoices, BaseModel, ConfigDict, Field
4
+ from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_validator
5
+
6
+ VALID_SNAP_ARCHITECTURES = [
7
+ "amd64",
8
+ "arm64",
9
+ "armhf",
10
+ "i386",
11
+ "powerpc",
12
+ "ppc64el",
13
+ "riscv64",
14
+ "s390x",
15
+ ]
5
16
 
6
17
 
7
18
  class BaseErrorResult(BaseModel):
19
+ """Error result returned by snapd.
20
+
21
+ snapd uses ``kind`` for both ``base`` and ``error`` statuses; ``value``
22
+ carries the kind-specific payload (a snap name, a validation set, ...).
23
+ Both are optional because not every endpoint populates them.
24
+ """
25
+
8
26
  message: str
27
+ kind: Optional[str] = None
28
+ value: Any = None
9
29
 
10
30
 
11
31
  class BaseResponse(BaseModel):
@@ -17,12 +37,21 @@ class BaseResponse(BaseModel):
17
37
  status: str
18
38
 
19
39
 
20
- class SnapBaseVersion(Enum):
40
+ class SnapBaseVersion(str, Enum):
41
+ """Known snap base versions.
42
+
43
+ The store types ``base`` as an arbitrary string and new bases keep
44
+ appearing (``core26`` was added after this enum was written), so models
45
+ store the raw string and never reject an unknown base. This enum is kept
46
+ as a convenience for callers.
47
+ """
48
+
21
49
  core16 = "core16"
22
50
  core18 = "core18"
23
51
  core20 = "core20"
24
52
  core22 = "core22"
25
53
  core24 = "core24"
54
+ core26 = "core26"
26
55
  bare = "bare"
27
56
 
28
57
 
@@ -73,7 +102,7 @@ class Download(BaseModel):
73
102
  class Revision(BaseModel):
74
103
  model_config = ConfigDict(exclude_unset=True)
75
104
 
76
- base: Optional[SnapBaseVersion] = None
105
+ base: Optional[str] = None
77
106
  channel: Optional[str] = None
78
107
  common_ids: Optional[list[str]] = Field(
79
108
  None, validation_alias=AliasChoices("common-ids", "common_ids")
@@ -84,6 +113,14 @@ class Revision(BaseModel):
84
113
  type: Optional[str] = None
85
114
  version: Optional[str] = None
86
115
 
116
+ @field_validator("base", mode="before")
117
+ @classmethod
118
+ def _base_as_string(cls, value):
119
+ """Accept any base string, including ones unknown to this library."""
120
+ if isinstance(value, SnapBaseVersion):
121
+ return value.value
122
+ return value
123
+
87
124
 
88
125
  class Publisher(BaseModel):
89
126
  model_config = ConfigDict(exclude_unset=True)
@@ -0,0 +1,251 @@
1
+ """Models for ``/v2/interfaces`` and ``/v2/connections``.
2
+
3
+ snapd speaks two very different shapes for interfaces, discriminated on the
4
+ JSON type of the envelope ``result``:
5
+
6
+ * :class:`Interface` — a JSON array, returned by ``GET /v2/interfaces`` as
7
+ soon as a non-empty ``select`` parameter is sent (the "modern" handler).
8
+ * :class:`LegacyConnections` — a JSON object, returned by
9
+ ``GET /v2/interfaces`` when ``select`` is absent (the "legacy" handler).
10
+
11
+ :class:`Connections` is the object returned by ``GET /v2/connections``.
12
+ ``plugs`` and ``slots`` entries in both connection shapes carry ``interface``,
13
+ ``apps`` and ``connections``, which modern interface entries never do.
14
+ """
15
+
16
+ from typing import Any
17
+
18
+ from pydantic import AliasChoices, BaseModel, Field
19
+
20
+ from snap_python.schemas.common import BaseErrorResult, BaseResponse
21
+
22
+
23
+ class PlugRef(BaseModel):
24
+ """Reference to a plug: ``{"snap": "foo", "plug": "network"}``."""
25
+
26
+ snap: str
27
+ plug: str
28
+
29
+
30
+ class SlotRef(BaseModel):
31
+ """Reference to a slot: ``{"snap": "core", "slot": "network"}``."""
32
+
33
+ snap: str
34
+ slot: str
35
+
36
+
37
+ class Connection(BaseModel):
38
+ """One established or undesired connection between a plug and a slot."""
39
+
40
+ slot: SlotRef
41
+ plug: PlugRef
42
+ interface: str
43
+ #: ``manual`` and ``gadget`` are tagged ``omitempty`` in snapd, so a
44
+ #: missing key means False.
45
+ manual: bool = False
46
+ gadget: bool = False
47
+ slot_attrs: dict[str, Any] | None = Field(
48
+ validation_alias=AliasChoices("slot-attrs", "slot_attrs"),
49
+ serialization_alias="slot-attrs",
50
+ default=None,
51
+ )
52
+ plug_attrs: dict[str, Any] | None = Field(
53
+ validation_alias=AliasChoices("plug-attrs", "plug_attrs"),
54
+ serialization_alias="plug-attrs",
55
+ default=None,
56
+ )
57
+
58
+
59
+ class Plug(BaseModel):
60
+ """A plug as returned by ``/v2/connections`` and legacy ``/v2/interfaces``.
61
+
62
+ :attr:`connections` lists the slots this plug is connected to.
63
+ """
64
+
65
+ snap: str
66
+ plug: str
67
+ interface: str | None = None
68
+ attrs: dict[str, Any] | None = None
69
+ apps: list[str] | None = None
70
+ label: str | None = None
71
+ connections: list[SlotRef] | None = None
72
+
73
+
74
+ class Slot(BaseModel):
75
+ """A slot as returned by ``/v2/connections`` and legacy ``/v2/interfaces``.
76
+
77
+ :attr:`connections` lists the plugs connected to this slot.
78
+ """
79
+
80
+ snap: str
81
+ slot: str
82
+ interface: str | None = None
83
+ attrs: dict[str, Any] | None = None
84
+ apps: list[str] | None = None
85
+ label: str | None = None
86
+ connections: list[PlugRef] | None = None
87
+
88
+
89
+ class Connections(BaseModel):
90
+ """Result object of ``GET /v2/connections``."""
91
+
92
+ established: list[Connection] = Field(default_factory=list)
93
+ undesired: list[Connection] | None = None
94
+ plugs: list[Plug] = Field(default_factory=list)
95
+ slots: list[Slot] = Field(default_factory=list)
96
+
97
+
98
+ class ConnectionsResponse(BaseResponse):
99
+ """Envelope of ``GET /v2/connections``."""
100
+
101
+ result: Connections | BaseErrorResult
102
+
103
+ @property
104
+ def connections(self) -> Connections | None:
105
+ """The connection information, or ``None`` for an error result."""
106
+ if isinstance(self.result, BaseErrorResult):
107
+ return None
108
+ return self.result
109
+
110
+
111
+ class InterfacePlug(BaseModel):
112
+ """A plug inside a modern ``/v2/interfaces`` entry.
113
+
114
+ snapd only fills ``snap``, ``plug``, ``attrs`` and ``label`` here;
115
+ ``interface``, ``apps`` and ``connections`` are never set.
116
+ """
117
+
118
+ snap: str
119
+ plug: str
120
+ attrs: dict[str, Any] | None = None
121
+ label: str | None = None
122
+
123
+
124
+ class InterfaceSlot(BaseModel):
125
+ """A slot inside a modern ``/v2/interfaces`` entry.
126
+
127
+ snapd only fills ``snap``, ``slot``, ``attrs`` and ``label`` here.
128
+ """
129
+
130
+ snap: str
131
+ slot: str
132
+ attrs: dict[str, Any] | None = None
133
+ label: str | None = None
134
+
135
+
136
+ class Interface(BaseModel):
137
+ """One entry of the modern ``GET /v2/interfaces`` array.
138
+
139
+ ``doc-url`` is only sent with ``doc=true``; ``plugs``/``slots`` are only
140
+ sent, and only present when non-empty, with ``plugs=true``/``slots=true``.
141
+ """
142
+
143
+ name: str
144
+ summary: str | None = None
145
+ doc_url: str | None = Field(
146
+ validation_alias=AliasChoices("doc-url", "doc_url"),
147
+ serialization_alias="doc-url",
148
+ default=None,
149
+ )
150
+ plugs: list[InterfacePlug] | None = None
151
+ slots: list[InterfaceSlot] | None = None
152
+
153
+
154
+ class LegacyConnections(BaseModel):
155
+ """Legacy ``GET /v2/interfaces`` result: ``{"plugs": [...], "slots": [...]}``.
156
+
157
+ Both keys are ``omitempty``; there is no ``established`` key.
158
+ """
159
+
160
+ plugs: list[Plug] | None = None
161
+ slots: list[Slot] | None = None
162
+
163
+
164
+ class InterfaceSummary(BaseModel):
165
+ """Shape-independent view of one interface.
166
+
167
+ Built from either response shape by
168
+ :attr:`InterfacesResponse.interfaces`. Only references are exposed:
169
+ ``attrs``/``apps``/``label`` stay available on the raw models.
170
+ """
171
+
172
+ name: str
173
+ summary: str | None = None
174
+ doc_url: str | None = None
175
+ plugs: list[PlugRef] = Field(default_factory=list)
176
+ slots: list[SlotRef] = Field(default_factory=list)
177
+
178
+
179
+ class InterfacesResponse(BaseResponse):
180
+ """Envelope of ``GET /v2/interfaces``, accepting both response shapes.
181
+
182
+ Use :attr:`legacy` to tell which shape snapd answered with and
183
+ :attr:`interfaces` for a normalised view.
184
+ """
185
+
186
+ result: list[Interface] | LegacyConnections | BaseErrorResult
187
+
188
+ @property
189
+ def legacy(self) -> bool:
190
+ """True when snapd answered with the legacy object shape."""
191
+ return isinstance(self.result, LegacyConnections)
192
+
193
+ @property
194
+ def interfaces(self) -> list[InterfaceSummary]:
195
+ """Normalised, name-sorted view of either response shape."""
196
+ if isinstance(self.result, BaseErrorResult):
197
+ return []
198
+ if isinstance(self.result, list):
199
+ return [
200
+ InterfaceSummary(
201
+ name=interface.name,
202
+ summary=interface.summary,
203
+ doc_url=interface.doc_url,
204
+ plugs=[
205
+ PlugRef(snap=plug.snap, plug=plug.plug)
206
+ for plug in interface.plugs or []
207
+ ],
208
+ slots=[
209
+ SlotRef(snap=slot.snap, slot=slot.slot)
210
+ for slot in interface.slots or []
211
+ ],
212
+ )
213
+ for interface in self.result
214
+ ]
215
+
216
+ summaries: dict[str, InterfaceSummary] = {}
217
+ for plug in self.result.plugs or []:
218
+ # Legacy entries should always carry the interface name; use an
219
+ # empty name rather than dropping information when they do not.
220
+ summary = summaries.setdefault(
221
+ plug.interface or "",
222
+ InterfaceSummary(name=plug.interface or ""),
223
+ )
224
+ summary.plugs.append(PlugRef(snap=plug.snap, plug=plug.plug))
225
+ for slot in self.result.slots or []:
226
+ summary = summaries.setdefault(
227
+ slot.interface or "",
228
+ InterfaceSummary(name=slot.interface or ""),
229
+ )
230
+ summary.slots.append(SlotRef(snap=slot.snap, slot=slot.slot))
231
+ return [summaries[name] for name in sorted(summaries)]
232
+
233
+
234
+ class InterfaceActionPlug(BaseModel):
235
+ """Plug item accepted by ``POST /v2/interfaces``.
236
+
237
+ snapd reads only ``snap`` and ``plug``; every other field is ignored.
238
+ """
239
+
240
+ snap: str
241
+ plug: str
242
+
243
+
244
+ class InterfaceActionSlot(BaseModel):
245
+ """Slot item accepted by ``POST /v2/interfaces``.
246
+
247
+ snapd reads only ``snap`` and ``slot``; every other field is ignored.
248
+ """
249
+
250
+ snap: str
251
+ slot: str
@@ -0,0 +1,17 @@
1
+ """Models for the RFC 7464 JSON-seq stream served by ``GET /v2/logs``."""
2
+
3
+ from pydantic import BaseModel
4
+
5
+
6
+ class LogEntry(BaseModel):
7
+ """One record of the ``application/json-seq`` log stream.
8
+
9
+ Mirrors snapd's ``client.Log``: ``timestamp`` is RFC 3339 to microsecond
10
+ precision, and ``pid`` is a **string** (it is taken verbatim from journald).
11
+ All four keys are always present.
12
+ """
13
+
14
+ timestamp: str
15
+ message: str
16
+ sid: str
17
+ pid: str