dokuments 3.2.0__tar.gz → 3.2.1__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: dokuments
3
- Version: 3.2.0
3
+ Version: 3.2.1
4
4
  Summary: The python client for dokuments, the arkitekt document service
5
5
  Author-email: jhnnsrs <jhnnsrs@gmail.com>
6
6
  Requires-Python: >=3.11
@@ -69,7 +69,9 @@ from arkitekt import easy
69
69
  from dokuments import dokuments_service
70
70
 
71
71
  with easy("my-script", dokuments_service) as dokuments:
72
- file = dokuments.from_file_like(file="scan.pdf") # a path, a Path or a binary file object
72
+ file = dokuments.from_file_like(
73
+ file="scan.pdf"
74
+ ) # a path, a Path or a binary file object
73
75
  document = dokuments.create_document(title="My scan", file=file.id)
74
76
  print(document.id, file.store.download()) # the bytes, through a scoped read grant
75
77
  ```
@@ -54,7 +54,9 @@ from arkitekt import easy
54
54
  from dokuments import dokuments_service
55
55
 
56
56
  with easy("my-script", dokuments_service) as dokuments:
57
- file = dokuments.from_file_like(file="scan.pdf") # a path, a Path or a binary file object
57
+ file = dokuments.from_file_like(
58
+ file="scan.pdf"
59
+ ) # a path, a Path or a binary file object
58
60
  document = dokuments.create_document(title="My scan", file=file.id)
59
61
  print(document.id, file.store.download()) # the bytes, through a scoped read grant
60
62
  ```
@@ -1,6 +1,5 @@
1
- from .dokuments import Dokuments
2
-
3
1
  # The service is declared with arkitekt-spec, a core dependency: it is always there.
4
2
  from .arkitekt import dokuments as dokuments_service
3
+ from .dokuments import Dokuments
5
4
 
6
5
  __all__ = ["Dokuments", "dokuments_service"]
@@ -0,0 +1 @@
1
+ {"version": "6.4.3"}
@@ -8,9 +8,11 @@ ask for the ``Dokuments`` it returns. An app takes all of it in with
8
8
  import os
9
9
  from typing import Annotated
10
10
 
11
+ from arkitekt_spec.declare.app import AppRegistry
12
+ from arkitekt_spec.declare.tested import tested_against
13
+ from arkitekt_spec.declare.widgets import SearchWidget
11
14
  from fakts import Alias, Require, TokenLoader
12
15
  from fakts.contrib.rath.auth import FaktsAuthLink
13
- from graphql import OperationType
14
16
  from rath.links.aiohttp import AIOHttpLink
15
17
  from rath.links.compose import compose
16
18
  from rath.links.dictinglink import DictingLink
@@ -18,15 +20,12 @@ from rath.links.file import FileExtraction
18
20
  from rath.links.graphql_ws import GraphQLWSLink
19
21
  from rath.links.split import SplitLink
20
22
 
21
- from arkitekt_spec.declare.app import AppRegistry
22
- from arkitekt_spec.declare.tested import tested_against
23
- from arkitekt_spec.declare.widgets import SearchWidget
24
-
25
23
  from dokuments.api.schema import File, SearchFilesQuery
26
24
  from dokuments.datalayer import DataLayer
27
25
  from dokuments.dokuments import Dokuments
28
26
  from dokuments.links.upload import UploadLink
29
27
  from dokuments.rath import DokumentsRath
28
+ from graphql import OperationType
30
29
 
31
30
 
32
31
  def build_relative_path(*path: str) -> str:
@@ -49,7 +48,9 @@ TESTED = tested_against("dokuments")
49
48
  def dokuments(
50
49
  dokuments: Annotated[
51
50
  Alias,
52
- Require("live.arkitekt.dokuments", "Where the user's documents live", version=TESTED),
51
+ Require(
52
+ "live.arkitekt.dokuments", "Where the user's documents live", version=TESTED
53
+ ),
53
54
  ],
54
55
  datalayer: Annotated[
55
56
  Alias,
@@ -82,8 +83,16 @@ def dokuments(
82
83
  UploadLink(datalayer=store),
83
84
  FaktsAuthLink(token_loader=tokens),
84
85
  SplitLink(
85
- left=AIOHttpLink(endpoint_url=dokuments.to_http_path("graphql"), proxy=dokuments.proxy, ssl_context=dokuments.ssl_context()),
86
- right=GraphQLWSLink(ws_endpoint_url=dokuments.to_ws_path("graphql"), proxy=dokuments.proxy, ssl_context=dokuments.ssl_context()),
86
+ left=AIOHttpLink(
87
+ endpoint_url=dokuments.to_http_path("graphql"),
88
+ proxy=dokuments.proxy,
89
+ ssl_context=dokuments.ssl_context(),
90
+ ),
91
+ right=GraphQLWSLink(
92
+ ws_endpoint_url=dokuments.to_ws_path("graphql"),
93
+ proxy=dokuments.proxy,
94
+ ssl_context=dokuments.ssl_context(),
95
+ ),
87
96
  split=lambda o: o.node.operation != OperationType.SUBSCRIPTION,
88
97
  ),
89
98
  ),
@@ -34,15 +34,17 @@ Example:
34
34
  import contextvars
35
35
  import ssl
36
36
  from types import TracebackType
37
+ from typing import TypeVar
37
38
 
38
39
  from fakts import Alias
39
40
  from koil.composition import KoiledModel
40
41
 
41
-
42
42
  current_dokuments_datalayer: contextvars.ContextVar["DataLayer | None"] = (
43
43
  contextvars.ContextVar("current_dokuments_datalayer", default=None)
44
44
  )
45
45
 
46
+ DataLayerT = TypeVar("DataLayerT", bound="DataLayer")
47
+
46
48
 
47
49
  class DataLayer(KoiledModel):
48
50
  """Implements a S3 DataLayer
@@ -74,8 +76,11 @@ class DataLayer(KoiledModel):
74
76
  pinned, the public roots otherwise."""
75
77
  from arkitekt_spec.declare import tls
76
78
 
77
- return tls.pinned_context(self.certificates) if self.certificates else tls.default_context()
78
-
79
+ return (
80
+ tls.pinned_context(self.certificates)
81
+ if self.certificates
82
+ else tls.default_context()
83
+ )
79
84
 
80
85
  @classmethod
81
86
  def from_alias(cls, alias: "Alias") -> "DataLayer":
@@ -93,10 +98,10 @@ class DataLayer(KoiledModel):
93
98
  certificates=list(alias.certificates) if alias.is_pinned() else [],
94
99
  )
95
100
 
96
- async def get_endpoint_url(self):
101
+ async def get_endpoint_url(self) -> str:
97
102
  return self.endpoint_url
98
103
 
99
- async def __aenter__(self):
104
+ async def __aenter__(self: DataLayerT) -> DataLayerT:
100
105
  current_dokuments_datalayer.set(self)
101
106
  return self
102
107
 
@@ -27,11 +27,15 @@ class Dokuments(Composition, DokumentsApi):
27
27
  datalayer: DataLayer
28
28
 
29
29
  @staticmethod
30
- def _serialize(operation: type[TOperation], variables: dict[str, Any]) -> dict[str, Any]:
30
+ def _serialize(
31
+ operation: type[TOperation], variables: dict[str, Any]
32
+ ) -> dict[str, Any]:
31
33
  # dokuments sends every argument, set or not (no exclude_unset), as it always has.
32
34
  return operation.Arguments(**variables).model_dump(by_alias=True)
33
35
 
34
- def execute(self, operation: type[TOperation], variables: dict[str, Any]) -> TOperation:
36
+ def execute(
37
+ self, operation: type[TOperation], variables: dict[str, Any]
38
+ ) -> TOperation:
35
39
  """Executes a query or mutation in a blocking way."""
36
40
  return unkoil(self.aexecute, operation, variables)
37
41
 
@@ -39,7 +43,9 @@ class Dokuments(Composition, DokumentsApi):
39
43
  self, operation: type[TOperation], variables: dict[str, Any]
40
44
  ) -> TOperation:
41
45
  """Executes a query or mutation in a non-blocking way."""
42
- x = await self.rath.aquery(operation.Meta.document, self._serialize(operation, variables))
46
+ x = await self.rath.aquery(
47
+ operation.Meta.document, self._serialize(operation, variables)
48
+ )
43
49
  return operation.model_validate(
44
50
  x.data, context=origin_context(client=self, rath=self.rath)
45
51
  )
@@ -1,5 +1,6 @@
1
1
  """Download a stored file with a scoped read grant (``requestMediaAccess``); there are no presigned URLs."""
2
2
 
3
+ import asyncio
3
4
  import os
4
5
  from typing import TYPE_CHECKING
5
6
 
@@ -26,9 +27,14 @@ async def adownload_file(dokuments: "Dokuments", store_id: str, file_name: str)
26
27
  if parent:
27
28
  os.makedirs(parent, exist_ok=True)
28
29
  response = await obstore.get_async(store, grant.key)
29
- with open(file_name, "wb") as file:
30
+ # Opening, writing and closing block: each runs on a worker thread, so a
31
+ # large download does not stall the event loop.
32
+ file = await asyncio.to_thread(open, file_name, "wb")
33
+ try:
30
34
  async for chunk in response.stream():
31
- file.write(chunk)
35
+ await asyncio.to_thread(file.write, chunk)
36
+ finally:
37
+ await asyncio.to_thread(file.close)
32
38
  return file_name
33
39
 
34
40
 
@@ -1,25 +1,30 @@
1
1
  import asyncio
2
2
  import io
3
+ from collections.abc import Awaitable, Callable
4
+ from concurrent.futures import ThreadPoolExecutor
5
+ from functools import partial
6
+ from typing import TYPE_CHECKING, Any, TypeVar
3
7
 
4
-
5
- from dokuments.scalars import FileLike
6
- from rath.links.parsing import ParsingLink
7
- from rath.operation import Operation, opify
8
- from typing import Any
9
8
  from mikro.io.upload import aupload_bigfile
10
9
  from pydantic import Field
11
- from concurrent.futures import ThreadPoolExecutor
12
- from functools import partial
10
+ from rath.links.parsing import ParsingLink
11
+ from rath.operation import Operation, opify
12
+
13
13
  from dokuments.datalayer import DataLayer
14
- from typing import TYPE_CHECKING
14
+ from dokuments.scalars import FileLike
15
15
 
16
16
  if TYPE_CHECKING:
17
17
  from dokuments.datalayer import DataLayer
18
18
 
19
19
 
20
+ T = TypeVar("T")
21
+
22
+
20
23
  async def apply_recursive(
21
- func, obj, typeguard: type[Any] | tuple[type[Any], ...]
22
- ) -> Any: # type: ignore
24
+ func: Callable[[T], Awaitable[object]],
25
+ obj: object,
26
+ typeguard: type[T] | tuple[type[T], ...],
27
+ ) -> object:
23
28
  """
24
29
  Recursively applies an asynchronous function to elements in a nested structure.
25
30
 
@@ -34,23 +39,23 @@ async def apply_recursive(
34
39
  if isinstance(
35
40
  obj, dict
36
41
  ): # If obj is a dictionary, recursively apply to each key-value pair
37
- return {k: await apply_recursive(func, v, typeguard) for k, v in obj.items()} # type: ignore
42
+ return {k: await apply_recursive(func, v, typeguard) for k, v in obj.items()}
38
43
  elif isinstance(obj, list): # If obj is a list, recursively apply to each element
39
44
  return await asyncio.gather(
40
45
  *[apply_recursive(func, elem, typeguard) for elem in obj]
41
- ) # type: ignore
46
+ )
42
47
  elif isinstance(
43
48
  obj, tuple
44
49
  ): # If obj is a tuple, recursively apply to each element and convert back to tuple
45
50
  return tuple(
46
51
  await asyncio.gather(
47
52
  *[apply_recursive(func, elem, typeguard) for elem in obj]
48
- ) # type: ignore
53
+ )
49
54
  )
50
55
  elif isinstance(obj, typeguard):
51
- return await func(obj) # type: ignore
56
+ return await func(obj)
52
57
  else: # If obj is not a dict, list, tuple, or matching the typeguard, return it as is
53
- return obj # type: ignore
58
+ return obj
54
59
 
55
60
 
56
61
  def _size_of(file: FileLike) -> int:
@@ -87,14 +92,16 @@ class UploadLink(ParsingLink):
87
92
  executor: ThreadPoolExecutor = Field(
88
93
  default_factory=lambda: ThreadPoolExecutor(max_workers=4), exclude=True
89
94
  )
90
- _executor_session: Any = None
95
+ _executor_session: ThreadPoolExecutor | None = None
91
96
 
92
97
  async def __aenter__(self) -> "UploadLink":
93
98
  """Enter the context manager for the UploadLink"""
94
99
  self._executor_session = self.executor.__enter__()
95
100
  return self
96
101
 
97
- async def _aexecute(self, document: str, variables: dict[str, Any]) -> Any:
102
+ async def _aexecute(
103
+ self, document: str, variables: dict[str, Any]
104
+ ) -> dict[str, Any]:
98
105
  if not self.next:
99
106
  raise ValueError("No next link found. Please set the next link.")
100
107
  async for result in self.next.aexecute(opify(document, variables=variables)):
@@ -114,13 +121,23 @@ class UploadLink(ParsingLink):
114
121
  size = _size_of(file)
115
122
  granted = await self._aexecute(
116
123
  RequestMediaUploadMutation.Meta.document,
117
- {"input": RequestMediaUploadInput(originalFileName=file.file_name, fileSize=size, contentType=file.mime_type).model_dump(by_alias=True, exclude_none=True)},
124
+ {
125
+ "input": RequestMediaUploadInput(
126
+ originalFileName=file.file_name,
127
+ fileSize=size,
128
+ contentType=file.mime_type,
129
+ ).model_dump(by_alias=True, exclude_none=True)
130
+ },
118
131
  )
119
132
  credentials = RequestMediaUploadMutation(**granted).request_media_upload
120
133
  store = await aupload_bigfile(file, credentials, datalayer)
121
134
  await self._aexecute(
122
135
  FinishMediaUploadMutation.Meta.document,
123
- {"input": FinishMediaUploadInput(storeId=store, valid=True).model_dump(by_alias=True, exclude_none=True)},
136
+ {
137
+ "input": FinishMediaUploadInput(storeId=store, valid=True).model_dump(
138
+ by_alias=True, exclude_none=True
139
+ )
140
+ },
124
141
  )
125
142
  return store
126
143
 
@@ -138,11 +155,14 @@ class UploadLink(ParsingLink):
138
155
 
139
156
  datalayer = operation.context.kwargs.get("datalayer", self.datalayer)
140
157
 
141
- operation.variables = await apply_recursive(
158
+ variables = await apply_recursive(
142
159
  partial(self.aupload_bigfile, datalayer),
143
160
  operation.variables,
144
161
  FileLike,
145
162
  )
163
+ # A dict in is a dict out: only the FileLike leaves are replaced.
164
+ assert isinstance(variables, dict)
165
+ operation.variables = variables
146
166
 
147
167
  return operation
148
168
 
@@ -1,10 +1,11 @@
1
- import os
1
+ import io
2
2
  import mimetypes
3
+ import os
3
4
  from pathlib import Path
4
- from typing import IO, Any, TypeAlias
5
- import io
6
- from pydantic_core import core_schema, CoreSchema
5
+ from typing import IO, TypeAlias
6
+
7
7
  from pydantic import GetCoreSchemaHandler
8
+ from pydantic_core import CoreSchema, core_schema
8
9
 
9
10
  FileCoercible: TypeAlias = str | bytes | Path | io.BufferedReader
10
11
 
@@ -20,15 +21,15 @@ class FileLike:
20
21
  self.file_name = os.path.basename(name)
21
22
  self.mime_type = mimetypes.guess_type(self.file_name)[0]
22
23
 
23
- def __get__(self, instance, owner) -> "FileLike": ... # noqa: ANN001, D105 # type: ignore
24
+ def __get__(self, instance: object, owner: type | None) -> "FileLike": ... # type: ignore
24
25
 
25
- def __set__(self, instance, value: FileCoercible) -> None: ... # noqa: ANN001, D105 # type: ignore
26
+ def __set__(self, instance: object, value: FileCoercible) -> None: ... # type: ignore
26
27
 
27
28
  @classmethod
28
29
  def __get_pydantic_core_schema__(
29
30
  cls,
30
- source_type: Any, # noqa: ANN401
31
- handler: GetCoreSchemaHandler, # noqa: ANN401
31
+ source_type: object,
32
+ handler: GetCoreSchemaHandler,
32
33
  ) -> CoreSchema:
33
34
  """Get the pydantic core schema for the validator function"""
34
35
  return core_schema.no_info_after_validator_function(
@@ -1,7 +1,8 @@
1
1
  from typing import Any
2
+
2
3
  from pydantic import BaseModel
3
4
  from rath.origin import ContextBound, get_origin
4
- from rath.turms.utils import NotQueriedError, get_attributes_or_error
5
+ from rath.turms.utils import get_attributes_or_error
5
6
 
6
7
 
7
8
  class HasDownloadAccessor(ContextBound, BaseModel):
@@ -18,13 +19,14 @@ class HasDownloadAccessor(ContextBound, BaseModel):
18
19
  Returns:
19
20
  str: The path to the downloaded file
20
21
  """
21
- from dokuments.io.download import download_file
22
-
23
22
  from dokuments.dokuments import Dokuments
23
+ from dokuments.io.download import download_file
24
24
 
25
25
  origin = get_origin(self)
26
26
  client = origin.client if origin is not None else None
27
27
  if not isinstance(client, Dokuments):
28
- raise ValueError("This store was not fetched through a Dokuments client, so there is none to ask for a read grant.")
28
+ raise ValueError(
29
+ "This store was not fetched through a Dokuments client, so there is none to ask for a read grant."
30
+ )
29
31
  store_id, key = get_attributes_or_error(self, "id", "key")
30
32
  return download_file(client, store_id, file_name or key.rsplit("/", 1)[-1])
@@ -19,24 +19,19 @@ dependencies = [
19
19
  ]
20
20
 
21
21
 
22
- [tool.uv]
23
- dev-dependencies = [
22
+ [dependency-groups]
23
+ dev = [
24
24
  "dokker>=2.8",
25
25
  "pytest>=8.3.5",
26
26
  "pytest-asyncio>=0.26.0",
27
27
  "pytest-aiohttp>=1.0.5,<2",
28
28
  "pytest-cov>=5.0.0,<6",
29
29
  "python-semantic-release>=9.21.1",
30
- "ruff>0.11",
30
+ "ruff==0.17.6",
31
31
  "turms>=3.0",
32
- "basedpyright>=1.21",
32
+ "basedpyright==1.40.2",
33
33
  ]
34
34
 
35
- [tool.basedpyright]
36
- include = ["dokuments"]
37
- exclude = ["**/__pycache__", "tests"]
38
- typeCheckingMode = "standard"
39
-
40
35
  # `_tested.json` is written by the integration tests (the server version they ran against)
41
36
  # and is not in git: named as an artifact, on both, it is shipped all the same.
42
37
  [tool.hatch.build.targets.sdist]
@@ -47,13 +42,6 @@ artifacts = ["dokuments/_tested.json"]
47
42
  include = ["dokuments"]
48
43
  artifacts = ["dokuments/_tested.json"]
49
44
 
50
-
51
- [tool.ruff.lint]
52
- extend-select = ["UP"]
53
- extend-ignore = ["UP037", "UP038", "UP042"]
54
-
55
- [tool.ruff.lint.per-file-ignores]
56
- "dokuments/api/schema.py" = ["UP035"]
57
45
  [build-system]
58
46
  requires = ["hatchling", "hatch-vcs"]
59
47
  build-backend = "hatchling.build"
@@ -1 +0,0 @@
1
- {"version": "6.3.0"}
File without changes
File without changes
File without changes