sfdctrust 0.1.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.
@@ -0,0 +1,326 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ :Module: sfdctrust._transport
4
+ :Synopsis: Internal HTTP transport and shared request policies for My Trust Center
5
+ :Created By: Jeff Shurtliff
6
+ :Last Modified: Jeff Shurtliff (via GPT-6.1 Sol)
7
+ :Modified Date: 04 Nov 2026
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import math
14
+ import random
15
+ import re
16
+ import time
17
+ from collections.abc import Callable, Mapping
18
+ from contextlib import suppress
19
+ from datetime import UTC, datetime
20
+ from email.utils import parsedate_to_datetime
21
+ from typing import Any, NoReturn, Self
22
+ from urllib.parse import unquote
23
+
24
+ import httpx
25
+
26
+ from ._auth import PATAuth
27
+ from ._constants import DEFAULT_BASE_URL, PACKAGE_NAME
28
+ from ._exceptions import (
29
+ APIStatusError,
30
+ AuthenticationError,
31
+ ConfigurationError,
32
+ MalformedResponseError,
33
+ NetworkError,
34
+ NotFoundError,
35
+ RateLimitError,
36
+ RequestTimeoutError,
37
+ TrustCenterError,
38
+ )
39
+ from ._version import __version__
40
+
41
+ _BASE = httpx.URL(DEFAULT_BASE_URL)
42
+ _REFRESH_URL = _BASE.copy_with(path=f'{_BASE.path}/pats/refresh')
43
+ _MAX_JITTER = 0.25
44
+ _MAX_RETRY_AFTER = 30
45
+ # HTTP-date allows IMF-fixdate and the two obsolete HTTP date formats.
46
+ _DAY = r'(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)'
47
+ _LONG_DAY = r'(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)'
48
+ _CLOCK = r'[0-9]{2}:[0-9]{2}:[0-9]{2}'
49
+ _HTTP_DATE = re.compile(
50
+ rf'{_DAY}, [0-9]{{2}} [A-Z][a-z]{{2}} [0-9]{{4}} {_CLOCK} GMT'
51
+ rf'|{_LONG_DAY}, [0-9]{{2}}-[A-Z][a-z]{{2}}-(?P<short_year>[0-9]{{2}}) {_CLOCK} GMT'
52
+ rf'|{_DAY} [A-Z][a-z]{{2}} (?: [0-9]|[0-9]{{2}}) {_CLOCK} [0-9]{{4}}'
53
+ )
54
+ _RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
55
+ _STATUS_ERRORS = {401: AuthenticationError, 404: NotFoundError, 429: RateLimitError}
56
+
57
+
58
+ def _destination(path: str) -> httpx.URL:
59
+ """Resolve a path under the API base, rejecting ambiguous path syntax."""
60
+ relative = path.removeprefix('/')
61
+ if not relative or '//' in path or ':' in relative.split('/', 1)[0]:
62
+ raise ConfigurationError('An API-relative path is required.')
63
+
64
+ segments = [unquote(segment) for segment in relative.split('/')]
65
+ for segment in segments:
66
+ if (
67
+ segment in {'.', '..'}
68
+ or any(char in '/\\%?#;' for char in segment)
69
+ or any(ord(char) < 0x20 or ord(char) == 0x7F for char in segment)
70
+ ):
71
+ raise ConfigurationError('The API path contains an unsafe segment.')
72
+
73
+ if '/'.join(segments).rstrip('/').lower() == 'pats/refresh':
74
+ raise ConfigurationError('PAT refresh requires the dedicated transport path.')
75
+
76
+ try:
77
+ url = _BASE.copy_with(path=f'{_BASE.path}/{relative}')
78
+ except (httpx.InvalidURL, ValueError):
79
+ pass
80
+ else:
81
+ if (
82
+ (url.scheme, url.host, url.port) == (_BASE.scheme, _BASE.host, _BASE.port)
83
+ and url.path.startswith(f'{_BASE.path}/')
84
+ and not (url.userinfo or url.query or url.fragment)
85
+ ):
86
+ return url
87
+ raise ConfigurationError('The request destination must be under the My Trust Center API base.')
88
+
89
+
90
+ def _can_retry(method: str, path: str) -> bool:
91
+ if method == 'POST':
92
+ return path == '/events/search'
93
+ if method != 'GET':
94
+ return False
95
+ if path in {'/tenants', '/status'}:
96
+ return True
97
+ collection, _, identifier = path[1:].partition('/')
98
+ return collection in {'tenants', 'events'} and bool(identifier) and '/' not in identifier
99
+
100
+
101
+ def _retry_after(value: str | None) -> float | None:
102
+ if value is None:
103
+ return None
104
+ value = value.strip(' \t')
105
+ if value.isascii() and value.isdecimal():
106
+ digits = value.lstrip('0')
107
+ # Avoid converting an unbounded integer from an untrusted header.
108
+ return _MAX_RETRY_AFTER if len(digits) > 2 else min(_MAX_RETRY_AFTER, int(digits or '0'))
109
+ match = _HTTP_DATE.fullmatch(value)
110
+ if match is None:
111
+ return None
112
+ try:
113
+ now = time.time()
114
+ if match['short_year'] is not None:
115
+ # RFC 9110 interprets a two-digit year relative to the current date.
116
+ current = datetime.fromtimestamp(now, UTC)
117
+ upper_year = current.year + 50
118
+ year = upper_year - (upper_year - int(match['short_year'])) % 100
119
+ start, end = match.span('short_year')
120
+ date = parsedate_to_datetime(f'{value[:start]}{year:04d}{value[end:]}')
121
+ if year == upper_year and date.timetuple()[1:6] > current.timetuple()[1:6]:
122
+ date = date.replace(year=year - 100)
123
+ else:
124
+ date = parsedate_to_datetime(value)
125
+ if date.tzinfo is None:
126
+ date = date.replace(tzinfo=UTC)
127
+ return min(_MAX_RETRY_AFTER, max(0.0, date.timestamp() - now))
128
+ except (ValueError, OverflowError, OSError):
129
+ return None
130
+
131
+
132
+ def _reject_json_constant(_: str) -> NoReturn:
133
+ raise ValueError('Nonstandard JSON constant.')
134
+
135
+
136
+ def _refresh_fields(pairs: list[tuple[str, object]]) -> dict[str, object]:
137
+ """Invalidate duplicate fields without discarding an unambiguous secret."""
138
+ fields: dict[str, object] = {}
139
+ for key, value in pairs:
140
+ fields[key] = None if key in fields else value
141
+ return fields
142
+
143
+
144
+ _QueryParams = httpx.QueryParams | Mapping[str, str | int | float | bool | None]
145
+ _READ_EXCEPTIONS = (ValueError, RecursionError, httpx.RequestError)
146
+
147
+
148
+ def _validate_max_retries(max_retries: int) -> int:
149
+ if not isinstance(max_retries, int) or isinstance(max_retries, bool) or not 0 <= max_retries <= 5:
150
+ raise ConfigurationError('max_retries must be an integer from 0 through 5.')
151
+ return max_retries
152
+
153
+
154
+ def _request_timeout(timeout: httpx.Timeout | None) -> httpx.Timeout:
155
+ result = httpx.Timeout(30.0, connect=5.0, pool=5.0) if timeout is None else httpx.Timeout(timeout)
156
+ if any(value is None or not math.isfinite(value) or value <= 0 for value in result.as_dict().values()):
157
+ raise ConfigurationError('HTTP timeouts must be finite and positive.')
158
+ return result
159
+
160
+
161
+ def _pool_limits() -> httpx.Limits:
162
+ return httpx.Limits(max_connections=20, max_keepalive_connections=10)
163
+
164
+
165
+ def _build_request(
166
+ method: str, url: httpx.URL, timeout: httpx.Timeout, *, params: _QueryParams | None = None, json_body: Any = None
167
+ ) -> httpx.Request:
168
+ return httpx.Request(
169
+ method,
170
+ url,
171
+ params=params,
172
+ json=json_body,
173
+ headers={'Accept': 'application/json', 'User-Agent': f'{PACKAGE_NAME}/{__version__}'},
174
+ extensions={'timeout': timeout.as_dict()},
175
+ )
176
+
177
+
178
+ def _status_failure(response: httpx.Response) -> tuple[TrustCenterError, bool, str | None]:
179
+ status = response.status_code
180
+ if status in _STATUS_ERRORS:
181
+ error: TrustCenterError = _STATUS_ERRORS[status]()
182
+ elif response.is_error:
183
+ error = APIStatusError(status)
184
+ else:
185
+ error = TrustCenterError('My Trust Center API returned an unexpected HTTP status.')
186
+ retry_after = response.headers.get('Retry-After') if status in {429, 503} else None
187
+ return error, status in _RETRY_STATUSES, retry_after
188
+
189
+
190
+ def _read_failure(exc: Exception) -> tuple[TrustCenterError, bool]:
191
+ if isinstance(exc, httpx.TimeoutException):
192
+ return RequestTimeoutError('My Trust Center request timed out.'), True
193
+ if isinstance(exc, (ValueError, RecursionError, httpx.DecodingError)):
194
+ return MalformedResponseError('My Trust Center returned an invalid JSON response.'), False
195
+ return NetworkError('My Trust Center request could not complete.'), isinstance(exc, httpx.ConnectError)
196
+
197
+
198
+ def _retry_delay(attempt: int, retry_after: str | None) -> float:
199
+ delay = _retry_after(retry_after)
200
+ if delay is None:
201
+ jitter = random.uniform(0, _MAX_JITTER) # nosec B311
202
+ delay = 0.5 * 2**attempt + jitter
203
+ return delay
204
+
205
+
206
+ def _decode_json(content: bytes) -> Any:
207
+ return json.loads(content.decode('utf-8'), parse_constant=_reject_json_constant)
208
+
209
+
210
+ def _refresh_body(days: int | None) -> dict[str, int] | None:
211
+ return None if days is None else {'expiresInDays': days}
212
+
213
+
214
+ def _decode_refresh(content: bytes) -> dict[str, object] | None:
215
+ payload = json.loads(
216
+ content.decode('utf-8'),
217
+ parse_constant=_reject_json_constant,
218
+ # Refresh fields are strings. Invalid numeric metadata must not lose the secret.
219
+ parse_int=lambda _: None,
220
+ parse_float=lambda _: None,
221
+ object_pairs_hook=_refresh_fields,
222
+ )
223
+ return payload if isinstance(payload, dict) else None
224
+
225
+
226
+ class _Transport:
227
+ """Send synchronous requests using one SDK-owned or trusted injected client.
228
+
229
+ The timeout applies to each attempt, including on injected clients. The
230
+ owned client verifies TLS, ignores environment proxies and CA overrides,
231
+ and uses a pool of 20 connections with up to 10 kept idle. An injected
232
+ client controls its own TLS, proxy, pool, hooks, and transport behavior.
233
+ """
234
+
235
+ def __init__(
236
+ self,
237
+ auth: PATAuth | Callable[[], PATAuth],
238
+ *,
239
+ client: httpx.Client | None = None,
240
+ timeout: httpx.Timeout | None = None,
241
+ max_retries: int = 2,
242
+ ) -> None:
243
+ self._max_retries = _validate_max_retries(max_retries)
244
+ self._auth = auth
245
+ self._timeout = _request_timeout(timeout)
246
+ self._owns_client = client is None
247
+ self._client = httpx.Client(trust_env=False, limits=_pool_limits()) if client is None else client
248
+
249
+ def close(self) -> None:
250
+ """Close the SDK-owned client."""
251
+ if self._owns_client:
252
+ self._client.close()
253
+
254
+ def __enter__(self) -> Self:
255
+ return self
256
+
257
+ def __exit__(self, *_: object) -> None:
258
+ self.close()
259
+
260
+ def _send(self, request: httpx.Request, auth: PATAuth) -> httpx.Response:
261
+ return self._client.send(request, auth=auth, follow_redirects=False, stream=True)
262
+
263
+ def refresh_once(self, auth: PATAuth, days: int | None) -> tuple[int | None, dict[str, object] | None]:
264
+ """Use the fixed refresh destination exactly once, decoding only success."""
265
+ body = _refresh_body(days)
266
+ return self._send_pat_operation('POST', _REFRESH_URL, auth, json_body=body)
267
+
268
+ def probe_once(self, auth: PATAuth) -> int | None:
269
+ """Check the old PAT with one status-only tenants request."""
270
+ status, _ = self._send_pat_operation('GET', _destination('/tenants'), auth)
271
+ return status
272
+
273
+ def _send_pat_operation(
274
+ self, method: str, url: httpx.URL, auth: PATAuth, *, json_body: dict[str, int] | None = None
275
+ ) -> tuple[int | None, dict[str, object] | None]:
276
+ status = None
277
+ try:
278
+ response = self._send(_build_request(method, url, self._timeout, json_body=json_body), auth)
279
+ except Exception:
280
+ # Hooks and custom transports can raise arbitrary exceptions containing secrets.
281
+ return None, None
282
+ try:
283
+ status = response.status_code
284
+ if method == 'POST' and response.is_success:
285
+ return status, _decode_refresh(response.read())
286
+ except Exception:
287
+ return status, None
288
+ finally:
289
+ # A failed close cannot invalidate an already received replacement or status.
290
+ with suppress(Exception):
291
+ response.close()
292
+ return status, None
293
+
294
+ def request(
295
+ self,
296
+ method: str,
297
+ path: str,
298
+ *,
299
+ params: _QueryParams | None = None,
300
+ json_body: Any = None,
301
+ ) -> Any:
302
+ """Send an API-relative request and return its decoded JSON."""
303
+ url = _destination(path)
304
+ method = method.upper()
305
+ retryable = _can_retry(method, url.path.removeprefix(_BASE.path))
306
+
307
+ for attempt in range(self._max_retries + 1):
308
+ request = _build_request(method, url, self._timeout, params=params, json_body=json_body)
309
+ auth = self._auth if isinstance(self._auth, PATAuth) else self._auth()
310
+ try:
311
+ response = self._send(request, auth)
312
+ try:
313
+ if response.is_success:
314
+ return _decode_json(response.read())
315
+ error, transient, retry_after = _status_failure(response)
316
+ finally:
317
+ response.close()
318
+ except _READ_EXCEPTIONS as exc:
319
+ error, transient = _read_failure(exc)
320
+ retry_after = None
321
+
322
+ if not retryable or not transient or attempt == self._max_retries:
323
+ raise error
324
+ time.sleep(_retry_delay(attempt, retry_after))
325
+
326
+ raise AssertionError('Unreachable retry state.')
sfdctrust/_version.py ADDED
@@ -0,0 +1,84 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ :Module: sfdctrust._version
4
+ :Synopsis: Utilities for working with the package version
5
+ :Created By: Jeff Shurtliff
6
+ :Last Modified: Jeff Shurtliff (via GPT-6)
7
+ :Modified Date: 01 Nov 2026
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import tomllib
14
+ from importlib.metadata import PackageNotFoundError, version
15
+ from pathlib import Path
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ def get_full_version() -> str:
21
+ """Returns the current full version of the ``sfdctrust`` package.
22
+
23
+ The package version is retrieved from the installed package metadata, which is
24
+ populated from the ``version`` field in ``pyproject.toml``.
25
+
26
+ :returns: The current package version as a string
27
+ :rtype: str
28
+ """
29
+ try:
30
+ return version('sfdctrust')
31
+ except PackageNotFoundError:
32
+ # This can happen if the package is not installed in the environment
33
+ # (e.g. running from a source checkout without an editable install)
34
+ logger.debug('Package is not installed and version will be retrieved from pyproject.toml file')
35
+ return get_version_from_pyproject()
36
+
37
+
38
+ def get_major_minor_version(full_version: str | None = None) -> str:
39
+ """Returns the current major.minor (i.e., X.Y) version of the package.
40
+
41
+ :param full_version: The full package version (e.g. X.Y.Z)
42
+ :type full_version: str, optional
43
+ :returns: The current package version (X.Y) as a string
44
+ :rtype: str
45
+ """
46
+ if not full_version:
47
+ full_version = get_full_version()
48
+ parts = full_version.split('.')
49
+ if len(parts) >= 2:
50
+ return '.'.join(parts[:2])
51
+ return full_version
52
+
53
+
54
+ def get_version_from_pyproject(pyproject_path: str | None = None) -> str:
55
+ """Retrieves the current version from the pyproject.toml file.
56
+
57
+ :param pyproject_path: The path to the pyproject.toml file
58
+ :type pyproject_path: str, optional
59
+ :returns: The current package version as a string
60
+ :rtype: str
61
+ """
62
+ path = Path(pyproject_path) if pyproject_path else Path(__file__).resolve().parents[2] / 'pyproject.toml'
63
+
64
+ # tomllib.loads() expects a string, while Path.read_bytes() returns bytes
65
+ # Prefer tomllib.load() with a binary file handle to avoid encoding pitfalls
66
+ with path.open('rb') as fp:
67
+ data = tomllib.load(fp)
68
+
69
+ # PEP 621
70
+ project_version = data.get('project', {}).get('version')
71
+ if project_version:
72
+ return str(project_version)
73
+
74
+ # Poetry legacy layout
75
+ project_version = data.get('tool', {}).get('poetry', {}).get('version')
76
+ if project_version:
77
+ return str(project_version)
78
+
79
+ logger.warning("sfdctrust version could not be retrieved; falling back to '0.0.0' as version")
80
+ return '0.0.0'
81
+
82
+
83
+ # Define __version__ for backward compatibility and to utilize as needed
84
+ __version__ = get_full_version()
@@ -0,0 +1,8 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ :Module: sfdctrust.integrations
4
+ :Synopsis:
5
+ :Created By: Jeff Shurtliff
6
+ :Last Modified: Jeff Shurtliff
7
+ :Modified Date: 01 Nov 2026
8
+ """
@@ -0,0 +1,8 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ :Module: sfdctrust.models
4
+ :Synopsis:
5
+ :Created By: Jeff Shurtliff
6
+ :Last Modified: Jeff Shurtliff
7
+ :Modified Date: 01 Nov 2026
8
+ """
@@ -0,0 +1,39 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ :Module: sfdctrust.models._wire
4
+ :Synopsis: Shared response validation
5
+ :Created By: Jeff Shurtliff
6
+ :Last Modified: Jeff Shurtliff (via GPT-6.1 Sol)
7
+ :Modified Date: 03 Nov 2026
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from datetime import datetime
14
+ from typing import Annotated
15
+
16
+ from pydantic import BaseModel, BeforeValidator, ConfigDict
17
+
18
+ _TIMESTAMP = re.compile(
19
+ r'[0-9]{4}-[0-9]{2}-[0-9]{2}[Tt][0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]+)?(?:[Zz]|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])'
20
+ )
21
+
22
+
23
+ def _parse_timestamp(value: object) -> datetime:
24
+ if not isinstance(value, str) or not _TIMESTAMP.fullmatch(value):
25
+ raise ValueError('Expected a full ISO 8601 timestamp with an explicit offset.')
26
+ return datetime.fromisoformat(value.upper())
27
+
28
+
29
+ _Timestamp = Annotated[datetime, BeforeValidator(_parse_timestamp)]
30
+
31
+
32
+ def _reject_null(value: object) -> object:
33
+ if value is None:
34
+ raise ValueError('This field may be omitted but cannot be null.')
35
+ return value
36
+
37
+
38
+ class _WireModel(BaseModel):
39
+ model_config = ConfigDict(strict=True, extra='allow')
@@ -0,0 +1,228 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ :Module: sfdctrust.models.events
4
+ :Synopsis: Typed event search, detail, and timeline models
5
+ :Created By: Jeff Shurtliff
6
+ :Last Modified: Jeff Shurtliff (via GPT-6.1 Sol)
7
+ :Modified Date: 03 Nov 2026
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Annotated, Any, Literal, Self
13
+
14
+ from pydantic import Discriminator, Field, InstanceOf, Tag, ValidationInfo, field_validator, model_validator
15
+
16
+ from ._wire import _reject_null, _Timestamp, _WireModel
17
+
18
+ __all__ = [
19
+ 'EventType',
20
+ 'EventSearchScope',
21
+ 'EventSearchResponse',
22
+ 'EventSearchResult',
23
+ 'EventDetail',
24
+ 'EventSummary',
25
+ 'SubEventScope',
26
+ 'PatchEventData',
27
+ 'IncidentEventData',
28
+ 'MaintenanceEventData',
29
+ 'InformationalMessageEventData',
30
+ 'TimelineItem',
31
+ 'PatchTimelineItem',
32
+ 'IncidentTimelineItem',
33
+ 'MaintenanceTimelineItem',
34
+ 'InformationalMessageTimelineItem',
35
+ 'PatchNote',
36
+ ]
37
+
38
+ EventType = Literal['patch', 'incident', 'maintenance', 'informationalMessage']
39
+
40
+
41
+ class EventSearchScope(_WireModel, extra='forbid', frozen=True):
42
+ """One tenant to search, identified by its opaque, case-sensitive ID."""
43
+
44
+ id: str = Field(min_length=1)
45
+ type: Literal['tenant'] = 'tenant'
46
+
47
+
48
+ class SubEventScope(_WireModel):
49
+ """Tenant membership keyed by opaque tenant IDs."""
50
+
51
+ tenants: dict[str, dict[str, Any]]
52
+
53
+
54
+ class PatchEventData(_WireModel):
55
+ release_id: str = Field(alias='releaseId')
56
+ release_name: str = Field(alias='releaseName')
57
+ release_version: str = Field(alias='releaseVersion')
58
+ planned_start_time: _Timestamp | None = Field(alias='plannedStartTime')
59
+ planned_end_time: _Timestamp | None = Field(alias='plannedEndTime')
60
+
61
+
62
+ class IncidentEventData(_WireModel):
63
+ additional_information: str | None = Field(alias='additionalInformation')
64
+ rca_link: str | None = Field(alias='rcaLink')
65
+ rca_created_at: _Timestamp | None = Field(alias='rcaCreatedAt')
66
+
67
+
68
+ class MaintenanceEventData(_WireModel):
69
+ planned_start_time: _Timestamp | None = Field(alias='plannedStartTime')
70
+ planned_end_time: _Timestamp | None = Field(alias='plannedEndTime')
71
+ additional_information: str | None = Field(alias='additionalInformation')
72
+
73
+
74
+ class InformationalMessageEventData(_WireModel):
75
+ informational_message_type: str | None = Field(alias='informationalMessageType')
76
+
77
+
78
+ _EVENT_DATA = {
79
+ 'patch': PatchEventData,
80
+ 'incident': IncidentEventData,
81
+ 'maintenance': MaintenanceEventData,
82
+ 'informationalMessage': InformationalMessageEventData,
83
+ }
84
+
85
+
86
+ class _TimelineEntry(_WireModel):
87
+ sub_event_id: str = Field(alias='subEventId')
88
+ sub_event_type: str = Field(alias='subEventType')
89
+ scope: SubEventScope
90
+ created_at: _Timestamp = Field(alias='createdAt')
91
+ message: str | None = None
92
+ updated_at: _Timestamp | None = Field(default=None, alias='updatedAt')
93
+
94
+
95
+ class PatchNote(_WireModel):
96
+ related_item: str | None = Field(default=None, alias='relatedItem')
97
+ description: str | None = None
98
+
99
+ _nonnull = field_validator('related_item', 'description', mode='before')(_reject_null)
100
+
101
+
102
+ class PatchTimelineItem(_TimelineEntry):
103
+ publication_date: _Timestamp | None = Field(default=None, alias='publicationDate')
104
+ planned_start_time: _Timestamp | None = Field(default=None, alias='plannedStartTime')
105
+ planned_end_time: _Timestamp | None = Field(default=None, alias='plannedEndTime')
106
+ contents: list[PatchNote] | None = None
107
+
108
+ _nonnull = field_validator('contents', mode='before')(_reject_null)
109
+
110
+
111
+ class IncidentTimelineItem(_TimelineEntry):
112
+ pass
113
+
114
+
115
+ class MaintenanceTimelineItem(_TimelineEntry):
116
+ planned_start_time: _Timestamp | None = Field(default=None, alias='plannedStartTime')
117
+ planned_end_time: _Timestamp | None = Field(default=None, alias='plannedEndTime')
118
+
119
+
120
+ class InformationalMessageTimelineItem(_TimelineEntry):
121
+ pass
122
+
123
+
124
+ _TIMELINE_TYPES = {
125
+ 'patch_release_scheduled': 'patch',
126
+ 'patch_release_started': 'patch',
127
+ 'patch_release_ended': 'patch',
128
+ 'patch_release_notes': 'patch',
129
+ 'incident_started': 'incident',
130
+ 'incident_update': 'incident',
131
+ 'incident_resolved': 'incident',
132
+ 'maintenance_scheduled': 'maintenance',
133
+ 'maintenance_update': 'maintenance',
134
+ 'maintenance_started': 'maintenance',
135
+ 'maintenance_completed': 'maintenance',
136
+ 'maintenance_canceled': 'maintenance',
137
+ 'im_created': 'informationalMessage',
138
+ 'im_update_added': 'informationalMessage',
139
+ }
140
+
141
+
142
+ def _timeline_tag(value: object) -> str:
143
+ subtype = value.get('subEventType') if isinstance(value, dict) else getattr(value, 'sub_event_type', None)
144
+ return _TIMELINE_TYPES.get(subtype, 'unknown') if isinstance(subtype, str) else 'unknown'
145
+
146
+
147
+ TimelineItem = Annotated[
148
+ Annotated[PatchTimelineItem, Tag('patch')]
149
+ | Annotated[IncidentTimelineItem, Tag('incident')]
150
+ | Annotated[MaintenanceTimelineItem, Tag('maintenance')]
151
+ | Annotated[InformationalMessageTimelineItem, Tag('informationalMessage')]
152
+ | Annotated[_TimelineEntry, Tag('unknown')],
153
+ Discriminator(_timeline_tag),
154
+ ]
155
+
156
+
157
+ class _Event(_WireModel):
158
+ event_id: str = Field(alias='eventId')
159
+ event_type: str = Field(alias='eventType')
160
+ status: str
161
+ products: list[str]
162
+ services: list[str]
163
+ created_at: _Timestamp = Field(alias='createdAt')
164
+ title: str | None = None
165
+ description: str | None = None
166
+ start_time: _Timestamp | None = Field(default=None, alias='startTime')
167
+ end_time: _Timestamp | None = Field(default=None, alias='endTime')
168
+ duration: str | None = None
169
+ display_duration: str | None = Field(default=None, alias='displayDuration')
170
+ data: (
171
+ InstanceOf[PatchEventData]
172
+ | InstanceOf[IncidentEventData]
173
+ | InstanceOf[MaintenanceEventData]
174
+ | InstanceOf[InformationalMessageEventData]
175
+ | dict[str, Any]
176
+ | None
177
+ ) = None
178
+
179
+ @field_validator('data', mode='before')
180
+ @classmethod
181
+ def _parse_data(cls, value: object, info: ValidationInfo) -> object:
182
+ _reject_null(value)
183
+ model = _EVENT_DATA.get(info.data.get('event_type'))
184
+ return model.model_validate(value) if model is not None else value
185
+
186
+
187
+ class EventSummary(_Event):
188
+ """A scoped event in a status snapshot or tenant history."""
189
+
190
+ scope: SubEventScope
191
+
192
+ @model_validator(mode='after')
193
+ def _exclude_timeline(self) -> Self:
194
+ if self.model_extra and 'timeline' in self.model_extra:
195
+ raise ValueError('Event summaries do not include a timeline.')
196
+ return self
197
+
198
+
199
+ class EventSearchResult(EventSummary):
200
+ """A scoped search result with lifecycle values for the matched tenant."""
201
+
202
+
203
+ class EventDetail(_Event):
204
+ """An event and its optional tenant-scoped timeline."""
205
+
206
+ timeline: list[TimelineItem] | None = None
207
+
208
+ _nonnull = field_validator('timeline', mode='before')(_reject_null)
209
+
210
+ @model_validator(mode='after')
211
+ def _check_detail_shape(self) -> Self:
212
+ if self.model_extra and 'scope' in self.model_extra:
213
+ raise ValueError('Event detail does not include a top-level scope.')
214
+ if self.event_type in _EVENT_DATA:
215
+ for entry in self.timeline or ():
216
+ category = _TIMELINE_TYPES.get(entry.sub_event_type)
217
+ if category is not None and category != self.event_type:
218
+ raise ValueError('Timeline type does not match the parent event type.')
219
+ return self
220
+
221
+
222
+ class EventSearchResponse(_WireModel):
223
+ """One page of search results and its optional continuation token."""
224
+
225
+ events: list[EventSearchResult] = Field(max_length=200)
226
+ next_page_token: str | None = Field(default=None, alias='nextPageToken')
227
+
228
+ _nonnull = field_validator('next_page_token', mode='before')(_reject_null)