evva-partner 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,166 @@
1
+ """EVVA Partner SDK for Python — server-side access to the EVVA Partner Integration Platform.
2
+
3
+ Start with :class:`EvvaPartnerClient` (sync) or :class:`AsyncEvvaPartnerClient` (asyncio). Events arrive
4
+ through :class:`FeedConsumer` / :class:`AsyncFeedConsumer` (durable), :class:`RealtimeClient` (low
5
+ latency) or both at once through :class:`PartnerEventStream`; webhooks are verified with
6
+ :func:`verify_webhook` and received with :class:`WebhookHandler` / :class:`AsyncWebhookHandler`
7
+ (deduplicated on ``event_id``).
8
+
9
+ Every application operation of openapi.yaml is ``client.operations.<snake_case(operationId)>`` (generated,
10
+ typed with :mod:`evva_partner.schemas`); endpoints, fields and protocol constants live in
11
+ :mod:`evva_partner.contract`.
12
+ """
13
+
14
+ from . import contract, schemas
15
+ from ._common import UploadResult
16
+ from ._generated.operations import AsyncOperations, Operations
17
+ from ._ops import bulk_item_idempotency_key
18
+ from ._version import __version__
19
+ from .async_client import AsyncEvvaPartnerClient
20
+ from .auth import (
21
+ AccessToken,
22
+ AsyncTokenManager,
23
+ ClientAuthentication,
24
+ ClientSecretBasic,
25
+ ClientSecretPost,
26
+ PrivateKeyJwt,
27
+ TokenManager,
28
+ )
29
+ from .client import EvvaPartnerClient
30
+ from .errors import (
31
+ ApiError,
32
+ ApprovalRequiredError,
33
+ AuthError,
34
+ AutomationPausedError,
35
+ BadRequestError,
36
+ ConfigurationError,
37
+ ConflictError,
38
+ ConversationAdvancedError,
39
+ CursorExpiredError,
40
+ EvvaError,
41
+ IdempotencyConflictError,
42
+ LeaseHeldError,
43
+ LeaseLostError,
44
+ NetworkError,
45
+ NotFoundError,
46
+ PermissionDeniedError,
47
+ RateLimitedError,
48
+ RealtimeError,
49
+ ServerError,
50
+ StaleFencingTokenError,
51
+ UploadError,
52
+ WebhooksMovedError,
53
+ WebhookVerificationError,
54
+ )
55
+ from .events import (
56
+ AsyncCheckpointStore,
57
+ AsyncDedupStore,
58
+ AsyncFeedConsumer,
59
+ CheckpointStore,
60
+ DedupStore,
61
+ Event,
62
+ FeedConsumer,
63
+ InMemoryCheckpointStore,
64
+ InMemoryDedupStore,
65
+ PartnerEventStream,
66
+ SQLiteStore,
67
+ parse_event,
68
+ stop_on_signals,
69
+ )
70
+ from .leases import HeldLease, lease_ttl_seconds
71
+ from .models import application_id_of, is_buyer_ref, message_status_of, status_of_event
72
+ from .pagination import AsyncOffsetPaginator, AsyncPaginator, OffsetPaginator, Page, Paginator
73
+ from .polling import PollTimeoutError, async_wait_for, wait_for
74
+ from .realtime import RealtimeClient, RealtimeEvent, Resync
75
+ from .redaction import Secret, redact_headers, redact_text
76
+ from .retry import RetryPolicy
77
+ from .webhooks import (
78
+ WEBHOOK_RESPONSE_STATUS,
79
+ AsyncWebhookHandler,
80
+ WebhookHandler,
81
+ WebhookResult,
82
+ verify_signature,
83
+ verify_webhook,
84
+ )
85
+
86
+ __all__ = [
87
+ "WEBHOOK_RESPONSE_STATUS",
88
+ "AccessToken",
89
+ "ApiError",
90
+ "ApprovalRequiredError",
91
+ "AsyncCheckpointStore",
92
+ "AsyncDedupStore",
93
+ "AsyncEvvaPartnerClient",
94
+ "AsyncFeedConsumer",
95
+ "AsyncOffsetPaginator",
96
+ "AsyncOperations",
97
+ "AsyncPaginator",
98
+ "AsyncTokenManager",
99
+ "AsyncWebhookHandler",
100
+ "AuthError",
101
+ "AutomationPausedError",
102
+ "BadRequestError",
103
+ "CheckpointStore",
104
+ "ClientAuthentication",
105
+ "ClientSecretBasic",
106
+ "ClientSecretPost",
107
+ "ConfigurationError",
108
+ "ConflictError",
109
+ "ConversationAdvancedError",
110
+ "CursorExpiredError",
111
+ "DedupStore",
112
+ "Event",
113
+ "EvvaError",
114
+ "EvvaPartnerClient",
115
+ "FeedConsumer",
116
+ "HeldLease",
117
+ "IdempotencyConflictError",
118
+ "InMemoryCheckpointStore",
119
+ "InMemoryDedupStore",
120
+ "LeaseHeldError",
121
+ "LeaseLostError",
122
+ "NetworkError",
123
+ "NotFoundError",
124
+ "OffsetPaginator",
125
+ "Operations",
126
+ "Page",
127
+ "Paginator",
128
+ "PartnerEventStream",
129
+ "PermissionDeniedError",
130
+ "PollTimeoutError",
131
+ "PrivateKeyJwt",
132
+ "RateLimitedError",
133
+ "RealtimeClient",
134
+ "RealtimeError",
135
+ "RealtimeEvent",
136
+ "Resync",
137
+ "RetryPolicy",
138
+ "SQLiteStore",
139
+ "Secret",
140
+ "ServerError",
141
+ "StaleFencingTokenError",
142
+ "TokenManager",
143
+ "UploadError",
144
+ "UploadResult",
145
+ "WebhookHandler",
146
+ "WebhookResult",
147
+ "WebhookVerificationError",
148
+ "WebhooksMovedError",
149
+ "__version__",
150
+ "application_id_of",
151
+ "async_wait_for",
152
+ "bulk_item_idempotency_key",
153
+ "contract",
154
+ "is_buyer_ref",
155
+ "lease_ttl_seconds",
156
+ "message_status_of",
157
+ "parse_event",
158
+ "redact_headers",
159
+ "redact_text",
160
+ "schemas",
161
+ "status_of_event",
162
+ "stop_on_signals",
163
+ "verify_signature",
164
+ "verify_webhook",
165
+ "wait_for",
166
+ ]
@@ -0,0 +1,155 @@
1
+ """Small pieces shared by the sync and the async client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import ipaddress
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, cast
9
+ from urllib.parse import urlsplit, urlunsplit
10
+
11
+ from . import contract
12
+ from .errors import ConfigurationError, UploadError
13
+ from .models import MediaAsset, UploadDescriptor
14
+
15
+ _LOOPBACK_NAMES = frozenset({"localhost"})
16
+
17
+
18
+ def _is_loopback(host: str | None) -> bool:
19
+ if not host:
20
+ return False
21
+ if host.lower() in _LOOPBACK_NAMES:
22
+ return True
23
+ try:
24
+ return ipaddress.ip_address(host).is_loopback
25
+ except ValueError:
26
+ return False
27
+
28
+
29
+ def normalize_base_url(base_url: str, *, allow_insecure_http: bool) -> str:
30
+ """``https://api.<domain>`` without a trailing slash. Plain HTTP only for loopback or when allowed."""
31
+ try:
32
+ parts = urlsplit(base_url)
33
+ except ValueError as exc:
34
+ raise ConfigurationError("base_url is not a valid URL") from exc
35
+ if parts.scheme not in ("https", "http") or not parts.netloc:
36
+ raise ConfigurationError("base_url must be an absolute http(s) URL such as https://api.example.com")
37
+ if parts.query or parts.fragment or parts.username or parts.password:
38
+ raise ConfigurationError("base_url must not carry credentials, a query or a fragment")
39
+ if parts.scheme == "http" and not (allow_insecure_http or _is_loopback(parts.hostname)):
40
+ raise ConfigurationError(
41
+ "refusing to send credentials over plain HTTP; use https (or a loopback host)"
42
+ )
43
+ return urlunsplit((parts.scheme, parts.netloc, parts.path.rstrip("/"), "", ""))
44
+
45
+
46
+ def realtime_url_for(base_url: str) -> str:
47
+ """``wss://<api host>/realtime`` for ``https://<api host>`` (``ws://`` for a loopback http base)."""
48
+ parts = urlsplit(base_url)
49
+ scheme = "wss" if parts.scheme == "https" else "ws"
50
+ return urlunsplit((scheme, parts.netloc, contract.REALTIME_PATH, "", ""))
51
+
52
+
53
+ def check_idempotency_key(key: str) -> str:
54
+ if not contract.IDEMPOTENCY_KEY_PATTERN.match(key):
55
+ raise ValueError("idempotency_key must be 1-128 characters of [A-Za-z0-9_-]")
56
+ return key
57
+
58
+
59
+ def derived_key(key: str, step: str) -> str:
60
+ """A deterministic per-step key derived from one logical call's key (e.g. upload finalize)."""
61
+ # Decision: one caller-visible key per logical upload; each server call in the flow gets its own key
62
+ # derived from it, so re-running the whole upload with the same key replays every step.
63
+ candidate = f"{key}-{step}"
64
+ if len(candidate) <= 128:
65
+ return candidate
66
+ return f"{hashlib.sha256(key.encode('utf-8')).hexdigest()}-{step}"
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class UploadResult:
71
+ """The finalized asset plus what the flow did."""
72
+
73
+ asset: MediaAsset
74
+ upload_session_id: str
75
+ replayed: bool
76
+ raw: dict[str, Any] = field(repr=False, default_factory=dict)
77
+
78
+
79
+ def parse_upload_created(body: Any, *, allow_insecure_http: bool) -> tuple[str, UploadDescriptor]:
80
+ if not isinstance(body, dict):
81
+ raise UploadError("upload create returned no JSON object")
82
+ session = body.get(contract.F_UPLOAD_SESSION)
83
+ descriptor = body.get(contract.F_UPLOAD)
84
+ if not isinstance(session, dict) or not isinstance(session.get("id"), str):
85
+ raise UploadError("upload create returned no uploadSession.id")
86
+ if not isinstance(descriptor, dict):
87
+ raise UploadError("upload create returned no upload descriptor")
88
+ method = descriptor.get("method")
89
+ if method == contract.UPLOAD_METHOD_MULTIPART:
90
+ multipart_layout(descriptor)
91
+ return cast("str", session["id"]), cast("UploadDescriptor", descriptor)
92
+ if method != contract.UPLOAD_METHOD_PUT:
93
+ raise UploadError(f"unsupported upload method {method!r} (expected PUT or MULTIPART)")
94
+ url = descriptor.get("url")
95
+ if not isinstance(url, str):
96
+ raise UploadError("upload descriptor has no url")
97
+ check_upload_url(url, allow_insecure_http=allow_insecure_http)
98
+ return cast("str", session["id"]), cast("UploadDescriptor", descriptor)
99
+
100
+
101
+ def check_upload_url(url: str, *, allow_insecure_http: bool) -> str:
102
+ """A presigned storage URL: https only (plain http for loopback or when allowed)."""
103
+ target = urlsplit(url)
104
+ if target.scheme != "https" and not (
105
+ target.scheme == "http" and (allow_insecure_http or _is_loopback(target.hostname))
106
+ ):
107
+ raise UploadError("refusing to upload to a non-https URL")
108
+ return url
109
+
110
+
111
+ def multipart_layout(descriptor: dict[str, Any]) -> tuple[int, int]:
112
+ """``(partSizeBytes, partCount)`` of a MULTIPART descriptor, checked."""
113
+ size, count = descriptor.get("partSizeBytes"), descriptor.get("partCount")
114
+ if not isinstance(size, int) or isinstance(size, bool) or size < 1:
115
+ raise UploadError("MULTIPART descriptor has no valid partSizeBytes")
116
+ if not isinstance(count, int) or isinstance(count, bool) or count < 1:
117
+ raise UploadError("MULTIPART descriptor has no valid partCount")
118
+ return size, count
119
+
120
+
121
+ def signed_part_urls(body: Any, *, allow_insecure_http: bool, now: float) -> dict[int, tuple[str, float]]:
122
+ """``signUploadParts`` -> ``{partNumber: (url, deadline)}`` (deadline = ``now`` + ``expiresInSec``)."""
123
+ parts = body.get("parts") if isinstance(body, dict) else None
124
+ if not isinstance(parts, list):
125
+ raise UploadError("signUploadParts returned no parts")
126
+ out: dict[int, tuple[str, float]] = {}
127
+ for part in parts:
128
+ if not isinstance(part, dict):
129
+ continue
130
+ number, url, ttl = part.get("partNumber"), part.get("url"), part.get("expiresInSec")
131
+ if isinstance(number, int) and isinstance(url, str):
132
+ check_upload_url(url, allow_insecure_http=allow_insecure_http)
133
+ out[number] = (url, now + (float(ttl) if isinstance(ttl, (int, float)) else 60.0))
134
+ return out
135
+
136
+
137
+ def put_headers(descriptor: UploadDescriptor, size_bytes: int) -> dict[str, str]:
138
+ headers = {str(k): str(v) for k, v in (descriptor.get("headers") or {}).items()}
139
+ # Drop anything that would carry our identity to the storage host, and anything we set ourselves.
140
+ for name in list(headers):
141
+ if name.lower() in ("authorization", "cookie", "content-length", "transfer-encoding", "host"):
142
+ del headers[name]
143
+ headers["Content-Length"] = str(size_bytes)
144
+ return headers
145
+
146
+
147
+ def parse_upload_finalized(body: Any, upload_session_id: str) -> UploadResult:
148
+ if not isinstance(body, dict) or not isinstance(body.get(contract.F_ASSET), dict):
149
+ raise UploadError("upload finalize returned no asset")
150
+ return UploadResult(
151
+ asset=cast("MediaAsset", body[contract.F_ASSET]),
152
+ upload_session_id=upload_session_id,
153
+ replayed=bool(body.get(contract.F_REPLAYED, False)),
154
+ raw=cast("dict[str, Any]", body),
155
+ )
@@ -0,0 +1,5 @@
1
+ """Modules generated from the Partner API OpenAPI and AsyncAPI documents.
2
+
3
+ Never edit them by hand: change the specs (or the generator) and regenerate; tests/test_openapi_conformance.py
4
+ fails while a regeneration is pending.
5
+ """