himring 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.
- himring/__init__.py +87 -0
- himring/_async_client.py +163 -0
- himring/_async_transfers.py +339 -0
- himring/_calls.py +122 -0
- himring/_download.py +130 -0
- himring/_errors.py +81 -0
- himring/_file_content.py +5 -0
- himring/_file_kinds.py +23 -0
- himring/_generated/__init__.py +0 -0
- himring/_generated/async_methods.py +4829 -0
- himring/_generated/operations.py +4096 -0
- himring/_generated/sync_methods.py +4820 -0
- himring/_generated/types.py +14097 -0
- himring/_omitted.py +17 -0
- himring/_operation_description.py +30 -0
- himring/_request_parts.py +220 -0
- himring/_responses.py +199 -0
- himring/_settings.py +112 -0
- himring/_sync_client.py +161 -0
- himring/_sync_transfers.py +307 -0
- himring/_upload_integrity.py +25 -0
- himring/_upload_plan.py +341 -0
- himring/_webhooks.py +162 -0
- himring/py.typed +0 -0
- himring/types.py +2 -0
- himring-0.1.0.dist-info/METADATA +113 -0
- himring-0.1.0.dist-info/RECORD +29 -0
- himring-0.1.0.dist-info/WHEEL +4 -0
- himring-0.1.0.dist-info/licenses/LICENSE +21 -0
himring/__init__.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
from himring._async_client import AsyncHimring
|
|
2
|
+
from himring._download import AsyncDownload, Download
|
|
3
|
+
from himring._errors import (
|
|
4
|
+
HimringApiError,
|
|
5
|
+
HimringApiErrorKind,
|
|
6
|
+
HimringApiIssue,
|
|
7
|
+
HimringMissingPermission,
|
|
8
|
+
documented_status_of,
|
|
9
|
+
is_refusal,
|
|
10
|
+
)
|
|
11
|
+
from himring._file_content import FileContent
|
|
12
|
+
from himring._file_kinds import READABLE_FILE_EXTENSIONS, file_extension_of, file_kind_of
|
|
13
|
+
from himring._generated.operations import (
|
|
14
|
+
ERROR_MESSAGES,
|
|
15
|
+
ERROR_STATUSES,
|
|
16
|
+
FILE_KIND_LIST,
|
|
17
|
+
FILE_KINDS,
|
|
18
|
+
OPERATIONS,
|
|
19
|
+
SPEC_API_URL,
|
|
20
|
+
FileKind,
|
|
21
|
+
)
|
|
22
|
+
from himring._omitted import OMITTED, Omitted
|
|
23
|
+
from himring._operation_description import OperationDescription, ResponseDescription
|
|
24
|
+
from himring._responses import safe_download_name
|
|
25
|
+
from himring._settings import (
|
|
26
|
+
DEFAULT_HIMRING_API_URL,
|
|
27
|
+
DEFAULT_TIMEOUT_SECONDS,
|
|
28
|
+
DEFAULT_UPLOAD_IDLE_TIMEOUT_SECONDS,
|
|
29
|
+
)
|
|
30
|
+
from himring._sync_client import Himring
|
|
31
|
+
from himring._upload_plan import AddedFile, FileOutcome, UploadContent, UploadSource
|
|
32
|
+
from himring._webhooks import (
|
|
33
|
+
DEFAULT_MEMORY_WEBHOOK_TOLERANCE_SECONDS,
|
|
34
|
+
MEMORY_WEBHOOK_EVENT_ID_HEADER,
|
|
35
|
+
MEMORY_WEBHOOK_REJECTIONS,
|
|
36
|
+
MEMORY_WEBHOOK_SIGNATURE_HEADER,
|
|
37
|
+
MemoryWebhookEvent,
|
|
38
|
+
MemoryWebhookRejected,
|
|
39
|
+
MemoryWebhookRejection,
|
|
40
|
+
verify_memory_webhook,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
__version__ = "0.1.0"
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"DEFAULT_HIMRING_API_URL",
|
|
47
|
+
"DEFAULT_MEMORY_WEBHOOK_TOLERANCE_SECONDS",
|
|
48
|
+
"DEFAULT_TIMEOUT_SECONDS",
|
|
49
|
+
"DEFAULT_UPLOAD_IDLE_TIMEOUT_SECONDS",
|
|
50
|
+
"ERROR_MESSAGES",
|
|
51
|
+
"ERROR_STATUSES",
|
|
52
|
+
"FILE_KINDS",
|
|
53
|
+
"FILE_KIND_LIST",
|
|
54
|
+
"MEMORY_WEBHOOK_EVENT_ID_HEADER",
|
|
55
|
+
"MEMORY_WEBHOOK_REJECTIONS",
|
|
56
|
+
"MEMORY_WEBHOOK_SIGNATURE_HEADER",
|
|
57
|
+
"OMITTED",
|
|
58
|
+
"OPERATIONS",
|
|
59
|
+
"READABLE_FILE_EXTENSIONS",
|
|
60
|
+
"SPEC_API_URL",
|
|
61
|
+
"AddedFile",
|
|
62
|
+
"AsyncDownload",
|
|
63
|
+
"AsyncHimring",
|
|
64
|
+
"Download",
|
|
65
|
+
"FileContent",
|
|
66
|
+
"FileKind",
|
|
67
|
+
"FileOutcome",
|
|
68
|
+
"Himring",
|
|
69
|
+
"HimringApiError",
|
|
70
|
+
"HimringApiErrorKind",
|
|
71
|
+
"HimringApiIssue",
|
|
72
|
+
"HimringMissingPermission",
|
|
73
|
+
"MemoryWebhookEvent",
|
|
74
|
+
"MemoryWebhookRejected",
|
|
75
|
+
"MemoryWebhookRejection",
|
|
76
|
+
"Omitted",
|
|
77
|
+
"OperationDescription",
|
|
78
|
+
"ResponseDescription",
|
|
79
|
+
"UploadContent",
|
|
80
|
+
"UploadSource",
|
|
81
|
+
"documented_status_of",
|
|
82
|
+
"file_extension_of",
|
|
83
|
+
"file_kind_of",
|
|
84
|
+
"is_refusal",
|
|
85
|
+
"safe_download_name",
|
|
86
|
+
"verify_memory_webhook",
|
|
87
|
+
]
|
himring/_async_client.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Mapping
|
|
4
|
+
from types import TracebackType
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from himring._async_transfers import AsyncFileTransfers
|
|
10
|
+
from himring._calls import (
|
|
11
|
+
PreparedCall,
|
|
12
|
+
download_details_of,
|
|
13
|
+
passed_deadline,
|
|
14
|
+
prepare_call,
|
|
15
|
+
transport_failure,
|
|
16
|
+
)
|
|
17
|
+
from himring._download import AsyncDownload
|
|
18
|
+
from himring._generated.async_methods import AsyncOperationMethods
|
|
19
|
+
from himring._request_parts import async_file_chunks
|
|
20
|
+
from himring._responses import json_of, refusal_of
|
|
21
|
+
from himring._settings import DEFAULT_HIMRING_API_URL, ClientSettings, settings_of
|
|
22
|
+
from himring._upload_plan import AddedFile, UploadContent
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class AsyncHimring(AsyncOperationMethods):
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
*,
|
|
29
|
+
api_key: str | None = None,
|
|
30
|
+
session_token: str | None = None,
|
|
31
|
+
base_url: str = DEFAULT_HIMRING_API_URL,
|
|
32
|
+
timeout_seconds: float | None = None,
|
|
33
|
+
upload_idle_timeout_seconds: float | None = None,
|
|
34
|
+
headers: Mapping[str, str] | None = None,
|
|
35
|
+
http_client: httpx.AsyncClient | None = None,
|
|
36
|
+
) -> None:
|
|
37
|
+
self._settings: ClientSettings = settings_of(
|
|
38
|
+
api_key=api_key,
|
|
39
|
+
session_token=session_token,
|
|
40
|
+
base_url=base_url,
|
|
41
|
+
timeout_seconds=timeout_seconds,
|
|
42
|
+
upload_idle_timeout_seconds=upload_idle_timeout_seconds,
|
|
43
|
+
headers=headers,
|
|
44
|
+
)
|
|
45
|
+
self._owns_http = http_client is None
|
|
46
|
+
self._http = (
|
|
47
|
+
http_client if http_client is not None else httpx.AsyncClient(follow_redirects=False)
|
|
48
|
+
)
|
|
49
|
+
self._transfers = AsyncFileTransfers(self, self._http, self._settings)
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def base_url(self) -> str:
|
|
53
|
+
return str(self._settings.base_url)
|
|
54
|
+
|
|
55
|
+
async def aclose(self) -> None:
|
|
56
|
+
if self._owns_http:
|
|
57
|
+
await self._http.aclose()
|
|
58
|
+
|
|
59
|
+
async def __aenter__(self) -> AsyncHimring:
|
|
60
|
+
return self
|
|
61
|
+
|
|
62
|
+
async def __aexit__(
|
|
63
|
+
self,
|
|
64
|
+
kind: type[BaseException] | None,
|
|
65
|
+
error: BaseException | None,
|
|
66
|
+
trace: TracebackType | None,
|
|
67
|
+
) -> None:
|
|
68
|
+
await self.aclose()
|
|
69
|
+
|
|
70
|
+
async def invoke(
|
|
71
|
+
self,
|
|
72
|
+
operation_id: str,
|
|
73
|
+
fields: Mapping[str, object] | None = None,
|
|
74
|
+
*,
|
|
75
|
+
timeout_seconds: float | None = None,
|
|
76
|
+
) -> object:
|
|
77
|
+
prepared = prepare_call(self._settings, operation_id, fields, timeout_seconds)
|
|
78
|
+
response = await self._send(prepared)
|
|
79
|
+
if prepared.operation.response.kind == "download" and response.is_success:
|
|
80
|
+
return AsyncDownload(response, download_details_of(response, prepared), "the API")
|
|
81
|
+
body = await self._read(response, prepared)
|
|
82
|
+
if not response.is_success:
|
|
83
|
+
raise refusal_of(response, body, prepared.operation.path)
|
|
84
|
+
return json_of(response, body, prepared.operation.path)
|
|
85
|
+
|
|
86
|
+
async def _call_operation(
|
|
87
|
+
self, operation_id: str, fields: Mapping[str, object], timeout_seconds: float | None
|
|
88
|
+
) -> object:
|
|
89
|
+
return await self.invoke(operation_id, fields, timeout_seconds=timeout_seconds)
|
|
90
|
+
|
|
91
|
+
async def add_file(
|
|
92
|
+
self,
|
|
93
|
+
*,
|
|
94
|
+
project_id: str,
|
|
95
|
+
knowledge_base_id: str,
|
|
96
|
+
path: str,
|
|
97
|
+
content: UploadContent,
|
|
98
|
+
address: str | None = None,
|
|
99
|
+
content_sha256: str | None = None,
|
|
100
|
+
metadata: Mapping[str, str] | None = None,
|
|
101
|
+
on_progress: Callable[[int], object] | None = None,
|
|
102
|
+
) -> AddedFile:
|
|
103
|
+
return await self._transfers.add_file(
|
|
104
|
+
project_id=project_id,
|
|
105
|
+
knowledge_base_id=knowledge_base_id,
|
|
106
|
+
path=path,
|
|
107
|
+
content=content,
|
|
108
|
+
address=address,
|
|
109
|
+
content_sha256=content_sha256,
|
|
110
|
+
metadata=metadata,
|
|
111
|
+
on_progress=on_progress,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
async def download_file(
|
|
115
|
+
self,
|
|
116
|
+
*,
|
|
117
|
+
project_id: str,
|
|
118
|
+
knowledge_base_id: str,
|
|
119
|
+
file_id: str,
|
|
120
|
+
version: int,
|
|
121
|
+
rendition: Literal["pdf"] | None = None,
|
|
122
|
+
range: str | None = None,
|
|
123
|
+
) -> AsyncDownload:
|
|
124
|
+
return await self._transfers.download_file(
|
|
125
|
+
project_id=project_id,
|
|
126
|
+
knowledge_base_id=knowledge_base_id,
|
|
127
|
+
file_id=file_id,
|
|
128
|
+
version=version,
|
|
129
|
+
rendition=rendition,
|
|
130
|
+
byte_range=range,
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
async def _send(self, prepared: PreparedCall) -> httpx.Response:
|
|
134
|
+
file_body = prepared.parts.file_body
|
|
135
|
+
content = (
|
|
136
|
+
async_file_chunks(file_body) if file_body is not None else prepared.parts.json_body
|
|
137
|
+
)
|
|
138
|
+
request = self._http.build_request(
|
|
139
|
+
prepared.operation.method,
|
|
140
|
+
prepared.url,
|
|
141
|
+
params=list(prepared.parts.query) or None,
|
|
142
|
+
content=content,
|
|
143
|
+
headers=prepared.headers,
|
|
144
|
+
timeout=prepared.timeout,
|
|
145
|
+
)
|
|
146
|
+
try:
|
|
147
|
+
return await self._http.send(request, stream=True, follow_redirects=False)
|
|
148
|
+
except httpx.HTTPError as error:
|
|
149
|
+
raise transport_failure(error, self._settings, prepared) from error
|
|
150
|
+
|
|
151
|
+
async def _read(self, response: httpx.Response, prepared: PreparedCall) -> bytes:
|
|
152
|
+
chunks: list[bytes] = []
|
|
153
|
+
try:
|
|
154
|
+
async for chunk in response.aiter_bytes():
|
|
155
|
+
chunks.append(chunk)
|
|
156
|
+
late = passed_deadline(prepared, self._settings)
|
|
157
|
+
if late is not None:
|
|
158
|
+
raise late
|
|
159
|
+
except httpx.HTTPError as error:
|
|
160
|
+
raise transport_failure(error, self._settings, prepared) from error
|
|
161
|
+
finally:
|
|
162
|
+
await response.aclose()
|
|
163
|
+
return b"".join(chunks)
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import hashlib
|
|
5
|
+
import inspect
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from himring._download import AsyncDownload
|
|
13
|
+
from himring._errors import HimringApiError, is_refusal
|
|
14
|
+
from himring._generated.async_methods import AsyncOperationMethods
|
|
15
|
+
from himring._generated.types import CreateUploadOutput
|
|
16
|
+
from himring._settings import ClientSettings
|
|
17
|
+
from himring._upload_integrity import checked_record, checked_signed_part
|
|
18
|
+
from himring._upload_plan import (
|
|
19
|
+
CHECK_POLL_FIRST_SECONDS,
|
|
20
|
+
CHECK_POLL_MAXIMUM_SECONDS,
|
|
21
|
+
HTTP_OK,
|
|
22
|
+
HTTP_PARTIAL_CONTENT,
|
|
23
|
+
PARTS_IN_FLIGHT,
|
|
24
|
+
RESIGNED_STATUSES,
|
|
25
|
+
SEND_ATTEMPTS,
|
|
26
|
+
STREAM_CHUNK_BYTES,
|
|
27
|
+
AddedFile,
|
|
28
|
+
LockedSource,
|
|
29
|
+
SignedPart,
|
|
30
|
+
UploadContent,
|
|
31
|
+
UploadRecord,
|
|
32
|
+
added_file_of,
|
|
33
|
+
checked_layout,
|
|
34
|
+
checked_sha256,
|
|
35
|
+
content_sha256_of,
|
|
36
|
+
give_up_at,
|
|
37
|
+
is_success,
|
|
38
|
+
left_open_error,
|
|
39
|
+
link_download_details,
|
|
40
|
+
part_of,
|
|
41
|
+
part_size_of,
|
|
42
|
+
range_headers_of,
|
|
43
|
+
send_timeout_seconds,
|
|
44
|
+
should_cancel,
|
|
45
|
+
slow_storage_error,
|
|
46
|
+
still_checking_error,
|
|
47
|
+
storage_download_refusal,
|
|
48
|
+
storage_failure,
|
|
49
|
+
storage_refusal,
|
|
50
|
+
storage_url_of,
|
|
51
|
+
timeout_extensions,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
ProgressCallback = Callable[[int], object]
|
|
55
|
+
PartBody = Callable[[], "bytes | AsyncIterator[bytes]"]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def _reported(on_progress: ProgressCallback | None, sent: int) -> None:
|
|
59
|
+
if on_progress is None:
|
|
60
|
+
return
|
|
61
|
+
result = on_progress(sent)
|
|
62
|
+
if inspect.isawaitable(result):
|
|
63
|
+
await result
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
async def _chunks_of(source: LockedSource, start: int, end: int) -> AsyncIterator[bytes]:
|
|
67
|
+
for offset in range(start, end, STREAM_CHUNK_BYTES):
|
|
68
|
+
yield await asyncio.to_thread(source.read, offset, min(end, offset + STREAM_CHUNK_BYTES))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
async def _part_of(source: LockedSource, start: int, end: int) -> tuple[bytes, str]:
|
|
72
|
+
def read() -> tuple[bytes, str]:
|
|
73
|
+
data = source.read(start, end)
|
|
74
|
+
return data, hashlib.sha256(data).hexdigest()
|
|
75
|
+
|
|
76
|
+
return await asyncio.to_thread(read)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class AsyncFileTransfers:
|
|
80
|
+
def __init__(
|
|
81
|
+
self, client: AsyncOperationMethods, http: httpx.AsyncClient, settings: ClientSettings
|
|
82
|
+
) -> None:
|
|
83
|
+
self._client = client
|
|
84
|
+
self._http = http
|
|
85
|
+
self._settings = settings
|
|
86
|
+
|
|
87
|
+
async def add_file(
|
|
88
|
+
self,
|
|
89
|
+
*,
|
|
90
|
+
project_id: str,
|
|
91
|
+
knowledge_base_id: str,
|
|
92
|
+
path: str,
|
|
93
|
+
content: UploadContent,
|
|
94
|
+
address: str | None,
|
|
95
|
+
content_sha256: str | None,
|
|
96
|
+
metadata: Mapping[str, str] | None,
|
|
97
|
+
on_progress: ProgressCallback | None,
|
|
98
|
+
) -> AddedFile:
|
|
99
|
+
source = LockedSource(content)
|
|
100
|
+
sha256 = checked_sha256(content_sha256) or await asyncio.to_thread(
|
|
101
|
+
content_sha256_of, source
|
|
102
|
+
)
|
|
103
|
+
created = await self._client.create_upload(
|
|
104
|
+
project_id=project_id,
|
|
105
|
+
knowledge_base_id=knowledge_base_id,
|
|
106
|
+
path=path,
|
|
107
|
+
address=address,
|
|
108
|
+
size_bytes=source.size_bytes,
|
|
109
|
+
content_sha256=sha256,
|
|
110
|
+
metadata=metadata,
|
|
111
|
+
)
|
|
112
|
+
upload = created["upload"]
|
|
113
|
+
if upload["state"] != "open":
|
|
114
|
+
return added_file_of(checked_record(upload, source.size_bytes, sha256))
|
|
115
|
+
ids = _UploadIds(self._client, project_id, knowledge_base_id, upload["id"])
|
|
116
|
+
try:
|
|
117
|
+
checked_record(upload, source.size_bytes, sha256)
|
|
118
|
+
part_bytes, part_count = checked_layout(upload, source.size_bytes)
|
|
119
|
+
settled = await self._sent_and_settled(
|
|
120
|
+
ids, created, source, part_bytes, part_count, on_progress
|
|
121
|
+
)
|
|
122
|
+
return added_file_of(checked_record(settled, source.size_bytes, sha256))
|
|
123
|
+
except BaseException as error:
|
|
124
|
+
if should_cancel(error):
|
|
125
|
+
await ids.cancel_quietly()
|
|
126
|
+
raise
|
|
127
|
+
|
|
128
|
+
async def download_file(
|
|
129
|
+
self,
|
|
130
|
+
*,
|
|
131
|
+
project_id: str,
|
|
132
|
+
knowledge_base_id: str,
|
|
133
|
+
file_id: str,
|
|
134
|
+
version: int,
|
|
135
|
+
rendition: Literal["pdf"] | None,
|
|
136
|
+
byte_range: str | None,
|
|
137
|
+
) -> AsyncDownload:
|
|
138
|
+
headers = range_headers_of(byte_range)
|
|
139
|
+
link = await self._client.get_download_link(
|
|
140
|
+
project_id=project_id,
|
|
141
|
+
knowledge_base_id=knowledge_base_id,
|
|
142
|
+
file_id=file_id,
|
|
143
|
+
version=str(version),
|
|
144
|
+
rendition=rendition,
|
|
145
|
+
disposition="attachment",
|
|
146
|
+
)
|
|
147
|
+
url = storage_url_of(link["url"])
|
|
148
|
+
extensions = timeout_extensions(self._settings.timeout_seconds)
|
|
149
|
+
request = httpx.Request("GET", url, headers=headers, extensions=extensions)
|
|
150
|
+
try:
|
|
151
|
+
response = await self._http.send(
|
|
152
|
+
request, stream=True, follow_redirects=False, auth=None
|
|
153
|
+
)
|
|
154
|
+
except httpx.HTTPError as error:
|
|
155
|
+
raise storage_failure(error, "download the file") from error
|
|
156
|
+
if response.status_code not in (HTTP_OK, HTTP_PARTIAL_CONTENT):
|
|
157
|
+
await response.aclose()
|
|
158
|
+
raise storage_download_refusal(response.status_code)
|
|
159
|
+
return AsyncDownload(response, link_download_details(response, link), "storage")
|
|
160
|
+
|
|
161
|
+
async def _sent_and_settled(
|
|
162
|
+
self,
|
|
163
|
+
ids: _UploadIds,
|
|
164
|
+
created: CreateUploadOutput,
|
|
165
|
+
source: LockedSource,
|
|
166
|
+
part_bytes: int,
|
|
167
|
+
part_count: int,
|
|
168
|
+
on_progress: ProgressCallback | None,
|
|
169
|
+
) -> UploadRecord:
|
|
170
|
+
upload = created["upload"]
|
|
171
|
+
try:
|
|
172
|
+
if upload["method"] == "single":
|
|
173
|
+
first = created["parts"][0] if created["parts"] else None
|
|
174
|
+
await self._send_single(ids, upload["content_sha256"], first, source, on_progress)
|
|
175
|
+
else:
|
|
176
|
+
await self._send_multipart(ids, source, part_bytes, part_count, on_progress)
|
|
177
|
+
except HimringApiError as error:
|
|
178
|
+
if not is_refusal(error, "upload_closed"):
|
|
179
|
+
raise
|
|
180
|
+
return await self._settled(ids, await ids.read())
|
|
181
|
+
return await self._settled(ids, await ids.complete())
|
|
182
|
+
|
|
183
|
+
async def _send_single(
|
|
184
|
+
self,
|
|
185
|
+
ids: _UploadIds,
|
|
186
|
+
sha256: str,
|
|
187
|
+
first: SignedPart | None,
|
|
188
|
+
source: LockedSource,
|
|
189
|
+
on_progress: ProgressCallback | None,
|
|
190
|
+
) -> None:
|
|
191
|
+
async def resign() -> SignedPart:
|
|
192
|
+
return checked_signed_part(await ids.sign(1, sha256), 1, source.size_bytes)
|
|
193
|
+
|
|
194
|
+
signed = (
|
|
195
|
+
checked_signed_part(first, 1, source.size_bytes)
|
|
196
|
+
if first is not None
|
|
197
|
+
else await resign()
|
|
198
|
+
)
|
|
199
|
+
sent = await self._send_part(
|
|
200
|
+
signed, resign, lambda: _chunks_of(source, 0, source.size_bytes)
|
|
201
|
+
)
|
|
202
|
+
await _reported(on_progress, sent)
|
|
203
|
+
|
|
204
|
+
async def _send_multipart(
|
|
205
|
+
self,
|
|
206
|
+
ids: _UploadIds,
|
|
207
|
+
source: LockedSource,
|
|
208
|
+
part_bytes: int,
|
|
209
|
+
part_count: int,
|
|
210
|
+
on_progress: ProgressCallback | None,
|
|
211
|
+
) -> None:
|
|
212
|
+
next_part = 1
|
|
213
|
+
|
|
214
|
+
async def lane() -> None:
|
|
215
|
+
nonlocal next_part
|
|
216
|
+
while next_part <= part_count:
|
|
217
|
+
part_number = next_part
|
|
218
|
+
next_part += 1
|
|
219
|
+
start = (part_number - 1) * part_bytes
|
|
220
|
+
data, sha256 = await _part_of(
|
|
221
|
+
source, start, min(source.size_bytes, start + part_bytes)
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
async def resign(
|
|
225
|
+
number: int = part_number, digest: str = sha256, size: int = len(data)
|
|
226
|
+
) -> SignedPart:
|
|
227
|
+
return checked_signed_part(await ids.sign(number, digest), number, size)
|
|
228
|
+
|
|
229
|
+
sent = await self._send_part(await resign(), resign, lambda chunk=data: chunk)
|
|
230
|
+
await _reported(on_progress, sent)
|
|
231
|
+
|
|
232
|
+
lanes = [asyncio.ensure_future(lane()) for _ in range(min(PARTS_IN_FLIGHT, part_count))]
|
|
233
|
+
if not lanes:
|
|
234
|
+
return
|
|
235
|
+
try:
|
|
236
|
+
done, _ = await asyncio.wait(lanes, return_when=asyncio.FIRST_EXCEPTION)
|
|
237
|
+
for finished in done:
|
|
238
|
+
finished.result()
|
|
239
|
+
finally:
|
|
240
|
+
for running in lanes:
|
|
241
|
+
running.cancel()
|
|
242
|
+
await asyncio.gather(*lanes, return_exceptions=True)
|
|
243
|
+
|
|
244
|
+
async def _send_part(
|
|
245
|
+
self, first: SignedPart, resign: Callable[[], Awaitable[SignedPart]], body: PartBody
|
|
246
|
+
) -> int:
|
|
247
|
+
signed = first
|
|
248
|
+
attempt = 1
|
|
249
|
+
while True:
|
|
250
|
+
size = part_size_of(signed)
|
|
251
|
+
try:
|
|
252
|
+
status = await self._put(signed, body(), size)
|
|
253
|
+
except HimringApiError:
|
|
254
|
+
if attempt >= SEND_ATTEMPTS:
|
|
255
|
+
raise
|
|
256
|
+
attempt += 1
|
|
257
|
+
signed = await resign()
|
|
258
|
+
continue
|
|
259
|
+
if is_success(status):
|
|
260
|
+
return size
|
|
261
|
+
if attempt >= SEND_ATTEMPTS or status not in RESIGNED_STATUSES:
|
|
262
|
+
raise storage_refusal(status, int(signed["part_number"]))
|
|
263
|
+
attempt += 1
|
|
264
|
+
signed = await resign()
|
|
265
|
+
|
|
266
|
+
async def _put(self, signed: SignedPart, body: bytes | AsyncIterator[bytes], size: int) -> int:
|
|
267
|
+
url = storage_url_of(signed["url"])
|
|
268
|
+
timeout = send_timeout_seconds(self._settings.upload_idle_timeout_seconds, size)
|
|
269
|
+
headers = {**signed["headers"], "content-length": str(size)}
|
|
270
|
+
request = httpx.Request(
|
|
271
|
+
"PUT", url, headers=headers, content=body, extensions=timeout_extensions(timeout)
|
|
272
|
+
)
|
|
273
|
+
try:
|
|
274
|
+
response = await self._http.send(
|
|
275
|
+
request, stream=True, follow_redirects=False, auth=None
|
|
276
|
+
)
|
|
277
|
+
except httpx.TimeoutException as error:
|
|
278
|
+
raise slow_storage_error(timeout, size) from error
|
|
279
|
+
except httpx.HTTPError as error:
|
|
280
|
+
raise storage_failure(error, "send the file") from error
|
|
281
|
+
await response.aclose()
|
|
282
|
+
return response.status_code
|
|
283
|
+
|
|
284
|
+
async def _settled(self, ids: _UploadIds, upload: UploadRecord) -> UploadRecord:
|
|
285
|
+
current = upload
|
|
286
|
+
wait_seconds = CHECK_POLL_FIRST_SECONDS
|
|
287
|
+
limit = give_up_at(upload)
|
|
288
|
+
while current["state"] == "checking":
|
|
289
|
+
if time.time() > limit:
|
|
290
|
+
raise still_checking_error(upload["id"])
|
|
291
|
+
await asyncio.sleep(wait_seconds)
|
|
292
|
+
wait_seconds = min(CHECK_POLL_MAXIMUM_SECONDS, wait_seconds * 2)
|
|
293
|
+
current = await ids.read()
|
|
294
|
+
if current["state"] == "open":
|
|
295
|
+
raise left_open_error(upload["id"])
|
|
296
|
+
return current
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class _UploadIds:
|
|
300
|
+
def __init__(
|
|
301
|
+
self, client: AsyncOperationMethods, project_id: str, knowledge_base_id: str, upload_id: str
|
|
302
|
+
) -> None:
|
|
303
|
+
self._client = client
|
|
304
|
+
self.project_id = project_id
|
|
305
|
+
self.knowledge_base_id = knowledge_base_id
|
|
306
|
+
self.upload_id = upload_id
|
|
307
|
+
|
|
308
|
+
async def sign(self, part_number: int, sha256: str) -> SignedPart:
|
|
309
|
+
signed = await self._client.sign_upload_parts(
|
|
310
|
+
project_id=self.project_id,
|
|
311
|
+
knowledge_base_id=self.knowledge_base_id,
|
|
312
|
+
upload_id=self.upload_id,
|
|
313
|
+
parts=[{"part_number": part_number, "sha256": sha256}],
|
|
314
|
+
)
|
|
315
|
+
return part_of(signed, part_number)
|
|
316
|
+
|
|
317
|
+
async def read(self) -> UploadRecord:
|
|
318
|
+
return await self._client.get_upload(
|
|
319
|
+
project_id=self.project_id,
|
|
320
|
+
knowledge_base_id=self.knowledge_base_id,
|
|
321
|
+
upload_id=self.upload_id,
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
async def complete(self) -> UploadRecord:
|
|
325
|
+
return await self._client.complete_upload(
|
|
326
|
+
project_id=self.project_id,
|
|
327
|
+
knowledge_base_id=self.knowledge_base_id,
|
|
328
|
+
upload_id=self.upload_id,
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
async def cancel_quietly(self) -> None:
|
|
332
|
+
try:
|
|
333
|
+
await self._client.cancel_upload(
|
|
334
|
+
project_id=self.project_id,
|
|
335
|
+
knowledge_base_id=self.knowledge_base_id,
|
|
336
|
+
upload_id=self.upload_id,
|
|
337
|
+
)
|
|
338
|
+
except Exception:
|
|
339
|
+
return
|