siftplane 0.1.0b1__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.
- siftplane/__init__.py +13 -0
- siftplane/_operations.py +263 -0
- siftplane/_transport.py +355 -0
- siftplane/client.py +527 -0
- siftplane/errors.py +42 -0
- siftplane/models.py +73 -0
- siftplane/py.typed +0 -0
- siftplane/webhooks.py +99 -0
- siftplane-0.1.0b1.dist-info/LICENSE +202 -0
- siftplane-0.1.0b1.dist-info/METADATA +221 -0
- siftplane-0.1.0b1.dist-info/RECORD +13 -0
- siftplane-0.1.0b1.dist-info/WHEEL +5 -0
- siftplane-0.1.0b1.dist-info/top_level.txt +1 -0
siftplane/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Siftplane document SDK for the 2026-10-24 API contract."""
|
|
2
|
+
from .client import Client, PreparedClassify, PreparedEvaluation, PreparedExtract, PreparedParse
|
|
3
|
+
from .models import ClassifyDecision, ClassifyResult, ClassifyRun, Binary, Processor, ProcessorVersion, EvaluationItem, EvaluationReport, EvaluationRun, EvaluationSet, Event, ExtractRecord, ExtractResult, ExtractRun, File, Page, ParseRun, Resource, Result, WebhookDelivery, WebhookEndpoint, WebhookSubscription
|
|
4
|
+
from .errors import APIError, AuthenticationError, Cancelled, ClientClosed, Conflict, DeadlineExceeded, Expired, LimitExceeded, NotFound, PermissionDenied, ProtocolError, RateLimited, ServiceUnavailable, SiftplaneError, TransportError, UnsupportedVersion, ValidationError
|
|
5
|
+
from .webhooks import WebhookVerificationError, verify_webhook
|
|
6
|
+
|
|
7
|
+
__all__ = ["Client", "PreparedParse", "Resource", "File", "ParseRun", "Result", "Event", "Page", "Binary",
|
|
8
|
+
"PreparedClassify", "ClassifyRun", "ClassifyResult", "ClassifyDecision",
|
|
9
|
+
"PreparedExtract", "ExtractRun", "ExtractResult", "ExtractRecord", "PreparedEvaluation", "Processor", "ProcessorVersion", "EvaluationSet", "EvaluationItem", "EvaluationRun", "EvaluationReport",
|
|
10
|
+
"WebhookEndpoint", "WebhookSubscription", "WebhookDelivery", "verify_webhook", "WebhookVerificationError",
|
|
11
|
+
"SiftplaneError", "APIError", "AuthenticationError", "PermissionDenied", "Conflict", "NotFound", "Expired",
|
|
12
|
+
"RateLimited", "ServiceUnavailable", "TransportError", "DeadlineExceeded", "Cancelled", "ClientClosed",
|
|
13
|
+
"LimitExceeded", "ProtocolError", "UnsupportedVersion", "ValidationError"]
|
siftplane/_operations.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""Generated by generate_operations.py; do not edit operation metadata."""
|
|
2
|
+
API_VERSION = '2026-10-24'
|
|
3
|
+
OPENAPI_SHA256 = '0b81f8587910f00455fdd5ff043f4a8a53d4a7bf416515611bd6265f34845342'
|
|
4
|
+
OPERATIONS = {'archiveProcessor': {'method': 'POST',
|
|
5
|
+
'path': '/v1/idp/processors/{processor_id}/archive',
|
|
6
|
+
'success_statuses': [200]},
|
|
7
|
+
'cancelClassifyRun': {'method': 'POST',
|
|
8
|
+
'path': '/v1/idp/classify-runs/{run_id}/cancel',
|
|
9
|
+
'success_statuses': [200, 202]},
|
|
10
|
+
'cancelEvaluationRun': {'method': 'POST',
|
|
11
|
+
'path': '/v1/idp/evaluation-runs/{run_id}/cancel',
|
|
12
|
+
'success_statuses': [202]},
|
|
13
|
+
'cancelExtractRun': {'method': 'POST',
|
|
14
|
+
'path': '/v1/idp/extract-runs/{run_id}/cancel',
|
|
15
|
+
'success_statuses': [200, 202]},
|
|
16
|
+
'cancelParseRun': {'method': 'POST',
|
|
17
|
+
'path': '/v1/idp/parse-runs/{run_id}/cancel',
|
|
18
|
+
'success_statuses': [200, 202]},
|
|
19
|
+
'createClassifyRun': {'method': 'POST',
|
|
20
|
+
'path': '/v1/idp/classify-runs',
|
|
21
|
+
'success_statuses': [200, 202]},
|
|
22
|
+
'createEvaluationItem': {'method': 'POST',
|
|
23
|
+
'path': '/v1/idp/evaluation-sets/{set_id}/items',
|
|
24
|
+
'success_statuses': [201]},
|
|
25
|
+
'createEvaluationRun': {'method': 'POST',
|
|
26
|
+
'path': '/v1/idp/evaluation-runs',
|
|
27
|
+
'success_statuses': [200, 202]},
|
|
28
|
+
'createEvaluationSet': {'method': 'POST',
|
|
29
|
+
'path': '/v1/idp/evaluation-sets',
|
|
30
|
+
'success_statuses': [201]},
|
|
31
|
+
'createEvaluationSetVersion': {'method': 'POST',
|
|
32
|
+
'path': '/v1/idp/evaluation-sets/{set_id}/versions',
|
|
33
|
+
'success_statuses': [201]},
|
|
34
|
+
'createExtractRun': {'method': 'POST',
|
|
35
|
+
'path': '/v1/idp/extract-runs',
|
|
36
|
+
'success_statuses': [200, 202]},
|
|
37
|
+
'createParseRun': {'method': 'POST', 'path': '/v1/idp/parse-runs', 'success_statuses': [200, 202]},
|
|
38
|
+
'createProcessor': {'method': 'POST', 'path': '/v1/idp/processors', 'success_statuses': [201]},
|
|
39
|
+
'createProcessorVersion': {'method': 'POST',
|
|
40
|
+
'path': '/v1/idp/processors/{processor_id}/versions',
|
|
41
|
+
'success_statuses': [201]},
|
|
42
|
+
'createWebhookEndpoint': {'method': 'POST',
|
|
43
|
+
'path': '/v1/idp/webhook-endpoints',
|
|
44
|
+
'success_statuses': [201]},
|
|
45
|
+
'createWebhookSubscription': {'method': 'POST',
|
|
46
|
+
'path': '/v1/idp/webhook-subscriptions',
|
|
47
|
+
'success_statuses': [201]},
|
|
48
|
+
'deleteClassifyRun': {'method': 'DELETE',
|
|
49
|
+
'path': '/v1/idp/classify-runs/{run_id}',
|
|
50
|
+
'success_statuses': [200]},
|
|
51
|
+
'deleteEvaluationItem': {'method': 'DELETE',
|
|
52
|
+
'path': '/v1/idp/evaluation-sets/{set_id}/items/{item_id}',
|
|
53
|
+
'success_statuses': [200]},
|
|
54
|
+
'deleteEvaluationRun': {'method': 'DELETE',
|
|
55
|
+
'path': '/v1/idp/evaluation-runs/{run_id}',
|
|
56
|
+
'success_statuses': [200]},
|
|
57
|
+
'deleteExtractRun': {'method': 'DELETE',
|
|
58
|
+
'path': '/v1/idp/extract-runs/{run_id}',
|
|
59
|
+
'success_statuses': [200]},
|
|
60
|
+
'deleteFile': {'method': 'DELETE',
|
|
61
|
+
'path': '/v1/idp/files/{file_id}',
|
|
62
|
+
'success_statuses': [200, 202]},
|
|
63
|
+
'deleteParseRun': {'method': 'DELETE',
|
|
64
|
+
'path': '/v1/idp/parse-runs/{run_id}',
|
|
65
|
+
'success_statuses': [200]},
|
|
66
|
+
'deleteWebhookEndpoint': {'method': 'DELETE',
|
|
67
|
+
'path': '/v1/idp/webhook-endpoints/{endpoint_id}',
|
|
68
|
+
'success_statuses': [200]},
|
|
69
|
+
'deleteWebhookSubscription': {'method': 'DELETE',
|
|
70
|
+
'path': '/v1/idp/webhook-subscriptions/{subscription_id}',
|
|
71
|
+
'success_statuses': [200]},
|
|
72
|
+
'downloadArtifact': {'method': 'GET',
|
|
73
|
+
'path': '/v1/idp/results/{result_id}/artifacts/{artifact_id}',
|
|
74
|
+
'success_statuses': [200]},
|
|
75
|
+
'downloadFile': {'method': 'GET',
|
|
76
|
+
'path': '/v1/idp/files/{file_id}/content',
|
|
77
|
+
'success_statuses': [200]},
|
|
78
|
+
'getCapabilities': {'method': 'GET', 'path': '/v1/idp/capabilities', 'success_statuses': [200]},
|
|
79
|
+
'getClassifyDecision': {'method': 'GET',
|
|
80
|
+
'path': '/v1/idp/classify-results/{result_id}/decision',
|
|
81
|
+
'success_statuses': [200]},
|
|
82
|
+
'getClassifyResult': {'method': 'GET',
|
|
83
|
+
'path': '/v1/idp/classify-results/{result_id}',
|
|
84
|
+
'success_statuses': [200]},
|
|
85
|
+
'getClassifyRun': {'method': 'GET',
|
|
86
|
+
'path': '/v1/idp/classify-runs/{run_id}',
|
|
87
|
+
'success_statuses': [200]},
|
|
88
|
+
'getClassifyRunConfiguration': {'method': 'GET',
|
|
89
|
+
'path': '/v1/idp/classify-runs/{run_id}/configuration',
|
|
90
|
+
'success_statuses': [200]},
|
|
91
|
+
'getClassifyRunRequest': {'method': 'GET',
|
|
92
|
+
'path': '/v1/idp/classify-run-requests',
|
|
93
|
+
'success_statuses': [200]},
|
|
94
|
+
'getEvaluationItem': {'method': 'GET',
|
|
95
|
+
'path': '/v1/idp/evaluation-sets/{set_id}/items/{item_id}',
|
|
96
|
+
'success_statuses': [200]},
|
|
97
|
+
'getEvaluationReport': {'method': 'GET',
|
|
98
|
+
'path': '/v1/idp/evaluation-reports/{report_id}',
|
|
99
|
+
'success_statuses': [200]},
|
|
100
|
+
'getEvaluationRun': {'method': 'GET',
|
|
101
|
+
'path': '/v1/idp/evaluation-runs/{run_id}',
|
|
102
|
+
'success_statuses': [200]},
|
|
103
|
+
'getEvaluationRunRequest': {'method': 'GET',
|
|
104
|
+
'path': '/v1/idp/evaluation-run-requests',
|
|
105
|
+
'success_statuses': [200]},
|
|
106
|
+
'getEvaluationSet': {'method': 'GET',
|
|
107
|
+
'path': '/v1/idp/evaluation-sets/{set_id}',
|
|
108
|
+
'success_statuses': [200]},
|
|
109
|
+
'getEvaluationSetVersion': {'method': 'GET',
|
|
110
|
+
'path': '/v1/idp/evaluation-sets/{set_id}/versions/{set_version_id}',
|
|
111
|
+
'success_statuses': [200]},
|
|
112
|
+
'getEvaluationVersionItem': {'method': 'GET',
|
|
113
|
+
'path': '/v1/idp/evaluation-sets/{set_id}/versions/{set_version_id}/items/{item_id}',
|
|
114
|
+
'success_statuses': [200]},
|
|
115
|
+
'getEvent': {'method': 'GET', 'path': '/v1/idp/events/{event_id}', 'success_statuses': [200]},
|
|
116
|
+
'getExtractRecord': {'method': 'GET',
|
|
117
|
+
'path': '/v1/idp/extract-results/{result_id}/record',
|
|
118
|
+
'success_statuses': [200]},
|
|
119
|
+
'getExtractResult': {'method': 'GET',
|
|
120
|
+
'path': '/v1/idp/extract-results/{result_id}',
|
|
121
|
+
'success_statuses': [200]},
|
|
122
|
+
'getExtractRun': {'method': 'GET',
|
|
123
|
+
'path': '/v1/idp/extract-runs/{run_id}',
|
|
124
|
+
'success_statuses': [200]},
|
|
125
|
+
'getExtractRunConfiguration': {'method': 'GET',
|
|
126
|
+
'path': '/v1/idp/extract-runs/{run_id}/configuration',
|
|
127
|
+
'success_statuses': [200]},
|
|
128
|
+
'getExtractRunRequest': {'method': 'GET',
|
|
129
|
+
'path': '/v1/idp/extract-run-requests',
|
|
130
|
+
'success_statuses': [200]},
|
|
131
|
+
'getFile': {'method': 'GET', 'path': '/v1/idp/files/{file_id}', 'success_statuses': [200]},
|
|
132
|
+
'getParseRun': {'method': 'GET', 'path': '/v1/idp/parse-runs/{run_id}', 'success_statuses': [200]},
|
|
133
|
+
'getParseRunRequest': {'method': 'GET',
|
|
134
|
+
'path': '/v1/idp/parse-run-requests',
|
|
135
|
+
'success_statuses': [200]},
|
|
136
|
+
'getProcessor': {'method': 'GET',
|
|
137
|
+
'path': '/v1/idp/processors/{processor_id}',
|
|
138
|
+
'success_statuses': [200]},
|
|
139
|
+
'getProcessorVersion': {'method': 'GET',
|
|
140
|
+
'path': '/v1/idp/processors/{processor_id}/versions/{processor_version_id}',
|
|
141
|
+
'success_statuses': [200]},
|
|
142
|
+
'getResult': {'method': 'GET', 'path': '/v1/idp/results/{result_id}', 'success_statuses': [200]},
|
|
143
|
+
'getResultChunks': {'method': 'GET',
|
|
144
|
+
'path': '/v1/idp/results/{result_id}/chunks',
|
|
145
|
+
'success_statuses': [200]},
|
|
146
|
+
'getResultContent': {'method': 'GET',
|
|
147
|
+
'path': '/v1/idp/results/{result_id}/content',
|
|
148
|
+
'success_statuses': [200]},
|
|
149
|
+
'getResultFeatures': {'method': 'GET',
|
|
150
|
+
'path': '/v1/idp/results/{result_id}/features',
|
|
151
|
+
'success_statuses': [200]},
|
|
152
|
+
'getWebhookDelivery': {'method': 'GET',
|
|
153
|
+
'path': '/v1/idp/webhook-deliveries/{delivery_id}',
|
|
154
|
+
'success_statuses': [200]},
|
|
155
|
+
'getWebhookEndpoint': {'method': 'GET',
|
|
156
|
+
'path': '/v1/idp/webhook-endpoints/{endpoint_id}',
|
|
157
|
+
'success_statuses': [200]},
|
|
158
|
+
'getWebhookSubscription': {'method': 'GET',
|
|
159
|
+
'path': '/v1/idp/webhook-subscriptions/{subscription_id}',
|
|
160
|
+
'success_statuses': [200]},
|
|
161
|
+
'listClassifyRuns': {'method': 'GET', 'path': '/v1/idp/classify-runs', 'success_statuses': [200]},
|
|
162
|
+
'listEvaluationItems': {'method': 'GET',
|
|
163
|
+
'path': '/v1/idp/evaluation-sets/{set_id}/items',
|
|
164
|
+
'success_statuses': [200]},
|
|
165
|
+
'listEvaluationReportItems': {'method': 'GET',
|
|
166
|
+
'path': '/v1/idp/evaluation-reports/{report_id}/items',
|
|
167
|
+
'success_statuses': [200]},
|
|
168
|
+
'listEvaluationRuns': {'method': 'GET',
|
|
169
|
+
'path': '/v1/idp/evaluation-runs',
|
|
170
|
+
'success_statuses': [200]},
|
|
171
|
+
'listEvaluationSetVersions': {'method': 'GET',
|
|
172
|
+
'path': '/v1/idp/evaluation-sets/{set_id}/versions',
|
|
173
|
+
'success_statuses': [200]},
|
|
174
|
+
'listEvaluationSets': {'method': 'GET',
|
|
175
|
+
'path': '/v1/idp/evaluation-sets',
|
|
176
|
+
'success_statuses': [200]},
|
|
177
|
+
'listEvaluationVersionItems': {'method': 'GET',
|
|
178
|
+
'path': '/v1/idp/evaluation-sets/{set_id}/versions/{set_version_id}/items',
|
|
179
|
+
'success_statuses': [200]},
|
|
180
|
+
'listEvents': {'method': 'GET', 'path': '/v1/idp/events', 'success_statuses': [200]},
|
|
181
|
+
'listExtractRuns': {'method': 'GET', 'path': '/v1/idp/extract-runs', 'success_statuses': [200]},
|
|
182
|
+
'listFiles': {'method': 'GET', 'path': '/v1/idp/files', 'success_statuses': [200]},
|
|
183
|
+
'listParseRuns': {'method': 'GET', 'path': '/v1/idp/parse-runs', 'success_statuses': [200]},
|
|
184
|
+
'listProcessorVersions': {'method': 'GET',
|
|
185
|
+
'path': '/v1/idp/processors/{processor_id}/versions',
|
|
186
|
+
'success_statuses': [200]},
|
|
187
|
+
'listProcessors': {'method': 'GET', 'path': '/v1/idp/processors', 'success_statuses': [200]},
|
|
188
|
+
'listWebhookAttempts': {'method': 'GET',
|
|
189
|
+
'path': '/v1/idp/webhook-deliveries/{delivery_id}/attempts',
|
|
190
|
+
'success_statuses': [200]},
|
|
191
|
+
'listWebhookDeliveries': {'method': 'GET',
|
|
192
|
+
'path': '/v1/idp/webhook-deliveries',
|
|
193
|
+
'success_statuses': [200]},
|
|
194
|
+
'listWebhookEndpoints': {'method': 'GET',
|
|
195
|
+
'path': '/v1/idp/webhook-endpoints',
|
|
196
|
+
'success_statuses': [200]},
|
|
197
|
+
'listWebhookSubscriptions': {'method': 'GET',
|
|
198
|
+
'path': '/v1/idp/webhook-subscriptions',
|
|
199
|
+
'success_statuses': [200]},
|
|
200
|
+
'promoteProcessorVersion': {'method': 'POST',
|
|
201
|
+
'path': '/v1/idp/processors/{processor_id}/promote',
|
|
202
|
+
'success_statuses': [200]},
|
|
203
|
+
'replayWebhookDelivery': {'method': 'POST',
|
|
204
|
+
'path': '/v1/idp/webhook-deliveries/{delivery_id}/replay',
|
|
205
|
+
'success_statuses': [202]},
|
|
206
|
+
'rotateWebhookSecret': {'method': 'POST',
|
|
207
|
+
'path': '/v1/idp/webhook-endpoints/{endpoint_id}/rotate-secret',
|
|
208
|
+
'success_statuses': [200]},
|
|
209
|
+
'testWebhookEndpoint': {'method': 'POST',
|
|
210
|
+
'path': '/v1/idp/webhook-endpoints/{endpoint_id}/test',
|
|
211
|
+
'success_statuses': [202]},
|
|
212
|
+
'updateEvaluationItem': {'method': 'PATCH',
|
|
213
|
+
'path': '/v1/idp/evaluation-sets/{set_id}/items/{item_id}',
|
|
214
|
+
'success_statuses': [200]},
|
|
215
|
+
'updateEvaluationSet': {'method': 'PATCH',
|
|
216
|
+
'path': '/v1/idp/evaluation-sets/{set_id}',
|
|
217
|
+
'success_statuses': [200]},
|
|
218
|
+
'updateProcessor': {'method': 'PATCH',
|
|
219
|
+
'path': '/v1/idp/processors/{processor_id}',
|
|
220
|
+
'success_statuses': [200]},
|
|
221
|
+
'updateWebhookEndpoint': {'method': 'PATCH',
|
|
222
|
+
'path': '/v1/idp/webhook-endpoints/{endpoint_id}',
|
|
223
|
+
'success_statuses': [200]},
|
|
224
|
+
'updateWebhookSubscription': {'method': 'PATCH',
|
|
225
|
+
'path': '/v1/idp/webhook-subscriptions/{subscription_id}',
|
|
226
|
+
'success_statuses': [200]},
|
|
227
|
+
'uploadFile': {'method': 'POST', 'path': '/v1/idp/files', 'success_statuses': [201]}}
|
|
228
|
+
KNOWN_ERROR_CODES = frozenset(['allowance_exceeded',
|
|
229
|
+
'allocation_unavailable',
|
|
230
|
+
'semantic_allowance_exceeded',
|
|
231
|
+
'semantic_authority_unavailable',
|
|
232
|
+
'unauthenticated',
|
|
233
|
+
'forbidden',
|
|
234
|
+
'policy_stale',
|
|
235
|
+
'invalid_request',
|
|
236
|
+
'missing_api_version',
|
|
237
|
+
'unsupported_api_version',
|
|
238
|
+
'method_not_allowed',
|
|
239
|
+
'payload_too_large',
|
|
240
|
+
'unsupported_media_type',
|
|
241
|
+
'unsupported_profile',
|
|
242
|
+
'not_implemented',
|
|
243
|
+
'unavailable',
|
|
244
|
+
'deadline_exceeded',
|
|
245
|
+
'rate_limited',
|
|
246
|
+
'internal',
|
|
247
|
+
'cancelled',
|
|
248
|
+
'not_found',
|
|
249
|
+
'idempotency_conflict',
|
|
250
|
+
'resource_conflict',
|
|
251
|
+
'result_expired',
|
|
252
|
+
'file_expired',
|
|
253
|
+
'table_structure_unresolved',
|
|
254
|
+
'table_spans_flattened',
|
|
255
|
+
'parser_feature_incomplete',
|
|
256
|
+
'parser_feature_limit',
|
|
257
|
+
'extraction_incomplete',
|
|
258
|
+
'extraction_invalid_output',
|
|
259
|
+
'extraction_source_failed',
|
|
260
|
+
'classification_source_failed',
|
|
261
|
+
'classification_invalid_output',
|
|
262
|
+
'classification_input_limit',
|
|
263
|
+
'classification_uncertain'])
|
siftplane/_transport.py
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
"""HTTP/1.1 with a monotonic deadline across DNS, TLS, headers and body.
|
|
2
|
+
|
|
3
|
+
No process-global signals, subprocesses, proxies or unbounded request threads.
|
|
4
|
+
DNS cannot be interrupted portably; at most eight daemon resolver calls may remain
|
|
5
|
+
after callers time out. Waiting callers cannot create more resolver work.
|
|
6
|
+
"""
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
import errno
|
|
9
|
+
import http.client
|
|
10
|
+
import ipaddress
|
|
11
|
+
import queue
|
|
12
|
+
import re
|
|
13
|
+
import selectors
|
|
14
|
+
import socket
|
|
15
|
+
import ssl
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
18
|
+
from urllib.parse import urlsplit
|
|
19
|
+
|
|
20
|
+
from .errors import Cancelled, ClientClosed, DeadlineExceeded, LimitExceeded, ProtocolError, TransportError, ValidationError
|
|
21
|
+
|
|
22
|
+
_DNS_SLOTS = threading.BoundedSemaphore(8)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Budget:
|
|
26
|
+
def __init__(self, deadline, cancel=None, closed=None):
|
|
27
|
+
self.deadline, self.cancel, self.closed = deadline, cancel, closed
|
|
28
|
+
|
|
29
|
+
def remaining(self):
|
|
30
|
+
if self.closed is not None and self.closed.is_set():
|
|
31
|
+
raise ClientClosed("Client is closed")
|
|
32
|
+
if self.cancel is not None and self.cancel.is_set():
|
|
33
|
+
raise Cancelled("Local operation was cancelled; accepted work is unchanged")
|
|
34
|
+
remaining = self.deadline - time.monotonic()
|
|
35
|
+
if remaining <= 0:
|
|
36
|
+
raise DeadlineExceeded("Operation deadline exceeded; accepted work may continue")
|
|
37
|
+
return remaining
|
|
38
|
+
|
|
39
|
+
def sleep(self, seconds):
|
|
40
|
+
end = min(self.deadline, time.monotonic() + seconds)
|
|
41
|
+
while time.monotonic() < end:
|
|
42
|
+
duration = min(0.05, end - time.monotonic(), self.remaining())
|
|
43
|
+
if self.cancel is not None:
|
|
44
|
+
self.cancel.wait(max(0, duration))
|
|
45
|
+
else:
|
|
46
|
+
time.sleep(max(0, duration))
|
|
47
|
+
self.remaining()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _wait(sock, event, budget):
|
|
51
|
+
with selectors.DefaultSelector() as selector:
|
|
52
|
+
selector.register(sock, event)
|
|
53
|
+
while not selector.select(min(0.05, budget.remaining())):
|
|
54
|
+
pass
|
|
55
|
+
budget.remaining()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _addresses(host, port, budget):
|
|
59
|
+
try:
|
|
60
|
+
ip = ipaddress.ip_address(host)
|
|
61
|
+
return [(socket.AF_INET6 if ip.version == 6 else socket.AF_INET, socket.SOCK_STREAM, 0, "", (host, port))]
|
|
62
|
+
except ValueError:
|
|
63
|
+
pass
|
|
64
|
+
while not _DNS_SLOTS.acquire(timeout=min(0.05, budget.remaining())):
|
|
65
|
+
pass
|
|
66
|
+
result = queue.Queue(maxsize=1)
|
|
67
|
+
def resolve():
|
|
68
|
+
try:
|
|
69
|
+
addresses = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
|
|
70
|
+
result.put(addresses[:16])
|
|
71
|
+
except (OSError, ValueError):
|
|
72
|
+
result.put(None)
|
|
73
|
+
finally:
|
|
74
|
+
_DNS_SLOTS.release()
|
|
75
|
+
try:
|
|
76
|
+
threading.Thread(target=resolve, name="siftplane-dns", daemon=True).start()
|
|
77
|
+
except RuntimeError:
|
|
78
|
+
_DNS_SLOTS.release()
|
|
79
|
+
raise TransportError("Document endpoint resolver is unavailable") from None
|
|
80
|
+
while True:
|
|
81
|
+
try:
|
|
82
|
+
addresses = result.get(timeout=min(0.05, budget.remaining()))
|
|
83
|
+
budget.remaining()
|
|
84
|
+
if not addresses:
|
|
85
|
+
raise TransportError("Document endpoint could not be resolved")
|
|
86
|
+
return addresses
|
|
87
|
+
except queue.Empty:
|
|
88
|
+
pass
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class _SocketFile:
|
|
92
|
+
def __init__(self, sock, budget, header_limit):
|
|
93
|
+
self.sock, self.budget = sock, budget
|
|
94
|
+
self.buffer = bytearray()
|
|
95
|
+
self.closed = False
|
|
96
|
+
self.in_headers = True
|
|
97
|
+
self.line_bytes = 0
|
|
98
|
+
self.header_limit = header_limit
|
|
99
|
+
|
|
100
|
+
def _receive(self):
|
|
101
|
+
while True:
|
|
102
|
+
self.budget.remaining()
|
|
103
|
+
try:
|
|
104
|
+
return self.sock.recv(65536)
|
|
105
|
+
except (ssl.SSLWantReadError, BlockingIOError):
|
|
106
|
+
_wait(self.sock, selectors.EVENT_READ, self.budget)
|
|
107
|
+
except ssl.SSLWantWriteError:
|
|
108
|
+
_wait(self.sock, selectors.EVENT_WRITE, self.budget)
|
|
109
|
+
|
|
110
|
+
def read(self, size=-1):
|
|
111
|
+
if size < 0:
|
|
112
|
+
raise ProtocolError("Unbounded transport read is disabled")
|
|
113
|
+
self.budget.remaining()
|
|
114
|
+
while len(self.buffer) < size:
|
|
115
|
+
data = self._receive()
|
|
116
|
+
if not data:
|
|
117
|
+
break
|
|
118
|
+
self.buffer.extend(data)
|
|
119
|
+
out = bytes(self.buffer[:size])
|
|
120
|
+
del self.buffer[:size]
|
|
121
|
+
return out
|
|
122
|
+
|
|
123
|
+
def readinto(self, target):
|
|
124
|
+
body = self.read(len(target))
|
|
125
|
+
target[:len(body)] = body
|
|
126
|
+
return len(body)
|
|
127
|
+
|
|
128
|
+
def readline(self, limit=-1):
|
|
129
|
+
self.budget.remaining()
|
|
130
|
+
limit = min(65536, limit if limit >= 0 else 65536)
|
|
131
|
+
while True:
|
|
132
|
+
position = self.buffer.find(b"\n", 0, limit)
|
|
133
|
+
if position >= 0 or len(self.buffer) >= limit:
|
|
134
|
+
size = position + 1 if position >= 0 else limit
|
|
135
|
+
break
|
|
136
|
+
data = self._receive()
|
|
137
|
+
if not data:
|
|
138
|
+
size = len(self.buffer)
|
|
139
|
+
break
|
|
140
|
+
self.buffer.extend(data)
|
|
141
|
+
line = bytes(self.buffer[:size])
|
|
142
|
+
del self.buffer[:size]
|
|
143
|
+
self.line_bytes += len(line)
|
|
144
|
+
if self.line_bytes > (self.header_limit if self.in_headers else 262144):
|
|
145
|
+
raise LimitExceeded("Response framing exceeds the SDK limit")
|
|
146
|
+
if self.in_headers and line.startswith((b" ", b"\t")):
|
|
147
|
+
raise ProtocolError("Folded HTTP response headers are unsupported")
|
|
148
|
+
return line
|
|
149
|
+
|
|
150
|
+
def close(self):
|
|
151
|
+
self.closed = True
|
|
152
|
+
|
|
153
|
+
def flush(self):
|
|
154
|
+
# HTTPResponse.close delegates to IOBase.flush even for a read-only file.
|
|
155
|
+
pass
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class _ResponseSocket:
|
|
159
|
+
def __init__(self, stream): self.stream = stream
|
|
160
|
+
def makefile(self, _mode): return self.stream
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@dataclass
|
|
164
|
+
class HTTPResult:
|
|
165
|
+
status: int
|
|
166
|
+
headers: dict = field(repr=False)
|
|
167
|
+
body: bytes = field(repr=False)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class Transport:
|
|
171
|
+
def __init__(self, base_url, bearer, *, allow_loopback_http=False, ssl_context=None, max_concurrency=8):
|
|
172
|
+
if not isinstance(base_url, str) or any(ord(c) < 32 or ord(c) == 127 for c in base_url):
|
|
173
|
+
raise ValidationError("Invalid document endpoint origin")
|
|
174
|
+
try:
|
|
175
|
+
origin = urlsplit(base_url)
|
|
176
|
+
if origin.username is not None or origin.password is not None or origin.path not in ("", "/") or origin.query or origin.fragment or not origin.hostname:
|
|
177
|
+
raise ValueError()
|
|
178
|
+
self.host = origin.hostname.encode("idna").decode("ascii")
|
|
179
|
+
self.port = origin.port or (443 if origin.scheme == "https" else 80)
|
|
180
|
+
self.tls = origin.scheme == "https"
|
|
181
|
+
loopback = self.host == "localhost"
|
|
182
|
+
try: loopback = loopback or ipaddress.ip_address(self.host).is_loopback
|
|
183
|
+
except ValueError: pass
|
|
184
|
+
if not self.tls and not (origin.scheme == "http" and allow_loopback_http and loopback):
|
|
185
|
+
raise ValueError()
|
|
186
|
+
if not 1 <= self.port <= 65535 or len(self.host) > 253:
|
|
187
|
+
raise ValueError()
|
|
188
|
+
except (ValueError, UnicodeError):
|
|
189
|
+
invalid_origin = True
|
|
190
|
+
else:
|
|
191
|
+
invalid_origin = False
|
|
192
|
+
if invalid_origin:
|
|
193
|
+
raise ValidationError("HTTPS origin required; loopback HTTP needs an explicit test option")
|
|
194
|
+
if not isinstance(bearer, str) or not 1 <= len(bearer) <= 8192 or not all(33 <= ord(c) <= 126 for c in bearer):
|
|
195
|
+
raise ValidationError("Invalid bearer credential")
|
|
196
|
+
if type(max_concurrency) is not int or not 1 <= max_concurrency <= 32:
|
|
197
|
+
raise ValidationError("Concurrency must be between 1 and 32")
|
|
198
|
+
self._bearer = bearer
|
|
199
|
+
self._context = ssl_context or ssl.create_default_context()
|
|
200
|
+
if self._context.verify_mode != ssl.CERT_REQUIRED or not self._context.check_hostname:
|
|
201
|
+
raise ValidationError("TLS certificate and hostname verification are required")
|
|
202
|
+
self._context.set_alpn_protocols(["http/1.1"])
|
|
203
|
+
self._slots = threading.BoundedSemaphore(max_concurrency)
|
|
204
|
+
self.closed = threading.Event()
|
|
205
|
+
self._lock = threading.Lock()
|
|
206
|
+
self._sockets = set()
|
|
207
|
+
authority = f"[{self.host}]" if ":" in self.host else self.host
|
|
208
|
+
if self.port != (443 if self.tls else 80):
|
|
209
|
+
authority += ":" + str(self.port)
|
|
210
|
+
self.origin = ("https://" if self.tls else "http://") + authority
|
|
211
|
+
|
|
212
|
+
def close(self):
|
|
213
|
+
self.closed.set()
|
|
214
|
+
with self._lock:
|
|
215
|
+
sockets = list(self._sockets)
|
|
216
|
+
for sock in sockets:
|
|
217
|
+
try: sock.close()
|
|
218
|
+
except OSError: pass
|
|
219
|
+
|
|
220
|
+
def _register(self, sock):
|
|
221
|
+
with self._lock:
|
|
222
|
+
self._sockets.add(sock)
|
|
223
|
+
|
|
224
|
+
def _discard(self, sock):
|
|
225
|
+
with self._lock:
|
|
226
|
+
self._sockets.discard(sock)
|
|
227
|
+
try: sock.close()
|
|
228
|
+
except OSError: pass
|
|
229
|
+
|
|
230
|
+
def _connect(self, budget):
|
|
231
|
+
for family, kind, protocol, _canonname, address in _addresses(self.host, self.port, budget):
|
|
232
|
+
budget.remaining()
|
|
233
|
+
if family not in (socket.AF_INET, socket.AF_INET6):
|
|
234
|
+
continue
|
|
235
|
+
if not self.tls and not ipaddress.ip_address(address[0]).is_loopback:
|
|
236
|
+
raise TransportError("HTTP test origin resolved outside loopback")
|
|
237
|
+
sock = socket.socket(family, kind, protocol)
|
|
238
|
+
self._register(sock)
|
|
239
|
+
try:
|
|
240
|
+
sock.setblocking(False)
|
|
241
|
+
result = sock.connect_ex(address)
|
|
242
|
+
if result not in (0, errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY):
|
|
243
|
+
raise OSError()
|
|
244
|
+
if result:
|
|
245
|
+
_wait(sock, selectors.EVENT_WRITE, budget)
|
|
246
|
+
if sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR):
|
|
247
|
+
raise OSError()
|
|
248
|
+
if self.tls:
|
|
249
|
+
original = sock
|
|
250
|
+
sock = self._context.wrap_socket(sock, server_hostname=self.host, do_handshake_on_connect=False)
|
|
251
|
+
with self._lock:
|
|
252
|
+
self._sockets.discard(original)
|
|
253
|
+
self._sockets.add(sock)
|
|
254
|
+
while True:
|
|
255
|
+
budget.remaining()
|
|
256
|
+
try:
|
|
257
|
+
sock.do_handshake()
|
|
258
|
+
break
|
|
259
|
+
except ssl.SSLWantReadError:
|
|
260
|
+
_wait(sock, selectors.EVENT_READ, budget)
|
|
261
|
+
except ssl.SSLWantWriteError:
|
|
262
|
+
_wait(sock, selectors.EVENT_WRITE, budget)
|
|
263
|
+
if sock.selected_alpn_protocol() not in (None, "http/1.1"):
|
|
264
|
+
raise ProtocolError("Unsupported negotiated HTTP protocol")
|
|
265
|
+
return sock
|
|
266
|
+
except (OSError, ssl.SSLError):
|
|
267
|
+
self._discard(sock)
|
|
268
|
+
budget.remaining()
|
|
269
|
+
except BaseException:
|
|
270
|
+
self._discard(sock)
|
|
271
|
+
raise
|
|
272
|
+
raise TransportError("Document endpoint connection failed")
|
|
273
|
+
|
|
274
|
+
@staticmethod
|
|
275
|
+
def _send(sock, data, budget):
|
|
276
|
+
view = memoryview(data)
|
|
277
|
+
while view:
|
|
278
|
+
budget.remaining()
|
|
279
|
+
try:
|
|
280
|
+
sent = sock.send(view[:65536])
|
|
281
|
+
if sent <= 0: raise OSError()
|
|
282
|
+
view = view[sent:]
|
|
283
|
+
except (ssl.SSLWantWriteError, BlockingIOError):
|
|
284
|
+
_wait(sock, selectors.EVENT_WRITE, budget)
|
|
285
|
+
except ssl.SSLWantReadError:
|
|
286
|
+
_wait(sock, selectors.EVENT_READ, budget)
|
|
287
|
+
|
|
288
|
+
def request(self, method, path, headers, body, budget, maximum):
|
|
289
|
+
while not self._slots.acquire(timeout=min(0.05, budget.remaining())):
|
|
290
|
+
pass
|
|
291
|
+
sock = None
|
|
292
|
+
try:
|
|
293
|
+
sock = self._connect(budget)
|
|
294
|
+
host = f"[{self.host}]" if ":" in self.host else self.host
|
|
295
|
+
if self.port != (443 if self.tls else 80): host += ":" + str(self.port)
|
|
296
|
+
values = {"Host": host, "Authorization": "Bearer " + self._bearer,
|
|
297
|
+
"Connection": "close", "Accept-Encoding": "identity", "User-Agent": "siftplane-python/0.1.0",
|
|
298
|
+
"Content-Length": str(len(body) if body is not None else 0)}
|
|
299
|
+
values.update(headers)
|
|
300
|
+
if any(not re.fullmatch(r"[A-Za-z0-9-]+", key) or not isinstance(value, str) or not all(32 <= ord(c) <= 126 for c in value) for key, value in values.items()):
|
|
301
|
+
raise ValidationError("Invalid request header")
|
|
302
|
+
request = (method + " " + path + " HTTP/1.1\r\n" + "".join(key + ": " + value + "\r\n" for key, value in values.items()) + "\r\n").encode("ascii")
|
|
303
|
+
if len(request) > 16384:
|
|
304
|
+
raise LimitExceeded("Request headers exceed the SDK limit")
|
|
305
|
+
self._send(sock, request, budget)
|
|
306
|
+
if body: self._send(sock, body, budget)
|
|
307
|
+
stream = _SocketFile(sock, budget, 32768)
|
|
308
|
+
response = http.client.HTTPResponse(_ResponseSocket(stream), method=method)
|
|
309
|
+
try:
|
|
310
|
+
response.begin()
|
|
311
|
+
if response.status >= 400:
|
|
312
|
+
maximum = min(maximum, 65536)
|
|
313
|
+
for name in ("Content-Length", "Transfer-Encoding", "Siftplane-API-Version", "X-Request-ID"):
|
|
314
|
+
if len(response.headers.get_all(name, [])) > 1:
|
|
315
|
+
raise ProtocolError("Ambiguous HTTP response headers")
|
|
316
|
+
transfer = response.getheader("Transfer-Encoding")
|
|
317
|
+
length = response.getheader("Content-Length")
|
|
318
|
+
if transfer and (transfer.lower() != "chunked" or length is not None):
|
|
319
|
+
raise ProtocolError("Unsupported or ambiguous response framing")
|
|
320
|
+
if length is not None:
|
|
321
|
+
if not re.fullmatch(r"[0-9]{1,20}", length):
|
|
322
|
+
raise ProtocolError("Invalid response length")
|
|
323
|
+
if int(length) > maximum:
|
|
324
|
+
raise LimitExceeded("Response exceeds the SDK byte limit")
|
|
325
|
+
if response.getheader("Content-Encoding", "identity").lower() != "identity":
|
|
326
|
+
raise ProtocolError("Unexpected response content encoding")
|
|
327
|
+
if 300 <= response.status < 400:
|
|
328
|
+
raise ProtocolError("Redirects are disabled")
|
|
329
|
+
if not 200 <= response.status <= 599:
|
|
330
|
+
raise ProtocolError("Unexpected HTTP response status")
|
|
331
|
+
stream.in_headers = False
|
|
332
|
+
stream.line_bytes = 0
|
|
333
|
+
chunks, size = [], 0
|
|
334
|
+
while True:
|
|
335
|
+
budget.remaining()
|
|
336
|
+
chunk = response.read(min(65536, maximum + 1 - size))
|
|
337
|
+
if not chunk: break
|
|
338
|
+
size += len(chunk)
|
|
339
|
+
if size > maximum:
|
|
340
|
+
raise LimitExceeded("Response exceeds the SDK byte limit")
|
|
341
|
+
chunks.append(chunk)
|
|
342
|
+
if length is not None and size != int(length):
|
|
343
|
+
raise ProtocolError("Incomplete HTTP response")
|
|
344
|
+
return HTTPResult(response.status, {key.lower(): value for key, value in response.getheaders()}, b"".join(chunks))
|
|
345
|
+
finally:
|
|
346
|
+
response.close()
|
|
347
|
+
except (OSError, ssl.SSLError, http.client.HTTPException, UnicodeError, ValueError):
|
|
348
|
+
pass
|
|
349
|
+
finally:
|
|
350
|
+
if sock is not None: self._discard(sock)
|
|
351
|
+
self._slots.release()
|
|
352
|
+
# HTTP parser exceptions may retain raw status/body bytes. Do not chain
|
|
353
|
+
# them into the public, sanitized transport exception.
|
|
354
|
+
budget.remaining()
|
|
355
|
+
raise TransportError("Document endpoint request failed; accepted work may continue")
|