mnemo-client 1.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,64 @@
1
+ # Copyright (c) 2026, PANAXON.AI, LLC. All rights reserved.
2
+ # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ # Multi-Dimensional Neural Elastic Memory Organization (MNEMO) - Python client.
17
+ #
18
+ # Inventor: Edward Suryadi
19
+ # Assignee: PANAXON.AI, LLC
20
+ #
21
+ # Author: edward.suryadi
22
+ # Since: Oct-2026
23
+
24
+ """Python client for the MNEMO API, the multi-tenant AI memory service from Panaxon AI.
25
+
26
+ Every client works the same way: a builder collects the parameters, ``build()`` gives you a client, and
27
+ ``execute()`` makes the call and returns the result.
28
+ """
29
+
30
+ from .chat import MnemoChatClient
31
+ from .client import MnemoClient, MnemoClientBuilder
32
+ from .exception import MnemoClientException, MnemoError
33
+ from .factory import MnemoClientFactory
34
+ from .model import (
35
+ Attachment,
36
+ ChatMessageResponse,
37
+ RagQueryResponse,
38
+ ResponseTiming,
39
+ SettingsResponse,
40
+ TokenUsage,
41
+ )
42
+ from .network import MnemoNetworkClient
43
+ from .rag import MnemoRAGClient
44
+ from .settings import MnemoSettingsClient
45
+
46
+ __version__ = "1.1.0"
47
+
48
+ __all__ = [
49
+ "Attachment",
50
+ "ChatMessageResponse",
51
+ "MnemoChatClient",
52
+ "MnemoClient",
53
+ "MnemoClientBuilder",
54
+ "MnemoClientException",
55
+ "MnemoClientFactory",
56
+ "MnemoError",
57
+ "MnemoNetworkClient",
58
+ "MnemoRAGClient",
59
+ "MnemoSettingsClient",
60
+ "RagQueryResponse",
61
+ "ResponseTiming",
62
+ "SettingsResponse",
63
+ "TokenUsage",
64
+ ]
@@ -0,0 +1,271 @@
1
+ # Copyright (c) 2026, PANAXON.AI, LLC. All rights reserved.
2
+ # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ # Multi-Dimensional Neural Elastic Memory Organization (MNEMO) - Python client.
17
+ #
18
+ # Inventor: Edward Suryadi
19
+ # Assignee: PANAXON.AI, LLC
20
+ #
21
+ # Author: edward.suryadi
22
+ # Since: Oct-2026
23
+
24
+ """The plumbing shared by every client implementation (not part of the public API)."""
25
+
26
+ from __future__ import annotations
27
+
28
+ import http.client
29
+ import json
30
+ import base64
31
+ import re
32
+ import time
33
+ import urllib.error
34
+ import urllib.request
35
+ from typing import Any, Callable, Dict, List, NamedTuple, Optional, TypeVar
36
+ from urllib.parse import quote, urlencode
37
+
38
+ from .client import MnemoClient, MnemoClientBuilder
39
+ from .exception import MnemoClientException, MnemoError
40
+
41
+ TOKEN_HEADER = "X-Mnemo-Api-Token"
42
+ TOKEN_REFRESH_MARGIN = 60.0
43
+ """Seconds before a client-credentials token expires at which it is replaced."""
44
+
45
+ T = TypeVar("T")
46
+
47
+
48
+ class SseEvent(NamedTuple):
49
+ """One server-sent event: its name (``message`` when none was given) and its data."""
50
+
51
+ name: str
52
+ data: str
53
+
54
+
55
+ class AbstractMnemoClient(MnemoClient):
56
+ """Validates the builder settings, calls the MNEMO REST API through ``urllib`` and translates HTTP failures
57
+ into :class:`MnemoClientException`. Nothing is kept between calls, so instances hold no connections and are
58
+ thread-safe.
59
+ """
60
+
61
+ def __init__(self, builder: MnemoClientBuilder) -> None:
62
+ self._settings = builder
63
+
64
+ def _with_target(self, call: Callable[[str], T]) -> T:
65
+ """Runs ``call`` with the service base URL after validating the builder settings."""
66
+ settings = self._settings
67
+ has_client = not (_is_blank(settings._client_id) and _is_blank(settings._client_secret))
68
+ if has_client and not _is_blank(settings._api_key):
69
+ raise _invalid("set either api_key or client_credentials, not both")
70
+ if has_client and (_is_blank(settings._client_id) or _is_blank(settings._client_secret)):
71
+ raise _invalid("client_credentials needs both a client id and a client secret")
72
+ if not has_client and _is_blank(settings._api_key):
73
+ raise MnemoClientException(MnemoError(MnemoError.Code.MISSING_API_KEY))
74
+ if _is_blank(settings._base_url):
75
+ raise _invalid("base_url is required")
76
+ timeout = settings._timeout
77
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not timeout >= 0:
78
+ raise _invalid("timeout must be zero or positive")
79
+ return call(str(settings._base_url).rstrip("/"))
80
+
81
+ def _send(self, method: str, url: str, body: Optional[Dict[str, Any]] = None,
82
+ convert: Optional[Callable[[Any], Any]] = None, expect_body: bool = True) -> Any:
83
+ """Sends one request and parses the JSON reply, passed through ``convert`` when given.
84
+
85
+ Returns ``None`` when ``expect_body`` is false, for a 204, or for an empty body.
86
+ """
87
+ text = self._request(method, url, "application/json", body)
88
+ if not expect_body or not text:
89
+ return None
90
+ parsed = _parse_json(text)
91
+ if convert is None:
92
+ return parsed
93
+ try:
94
+ return convert(parsed)
95
+ except (AttributeError, TypeError, ValueError) as e:
96
+ raise MnemoClientException(MnemoError(MnemoError.Code.SERIALIZATION_ERROR)) from e
97
+
98
+ def _send_event_stream(self, method: str, url: str, body: Dict[str, Any]) -> List[SseEvent]:
99
+ """Sends one request that answers with a server-sent event stream and reads the stream to its end.
100
+
101
+ The stream is finite for the calls that use this (it ends after a final event), so it is read whole.
102
+ """
103
+ return parse_events(self._request(method, url, "text/event-stream", body))
104
+
105
+ def _request(self, method: str, url: str, accept: str, body: Optional[Dict[str, Any]]) -> str:
106
+ if self._uses_client_credentials():
107
+ try:
108
+ return self._perform(method, url, accept, body, self._access_token(False))
109
+ except MnemoClientException as e:
110
+ if e.http_status != 401:
111
+ raise
112
+ # the cached token was revoked or its client was rotated: fetch a new one and try once more
113
+ return self._perform(method, url, accept, body, self._access_token(True))
114
+ return self._perform(method, url, accept, body, None)
115
+
116
+ def _perform(self, method: str, url: str, accept: str, body: Optional[Dict[str, Any]],
117
+ bearer: Optional[str]) -> str:
118
+ headers = {"Accept": accept}
119
+ if bearer is None:
120
+ headers[TOKEN_HEADER] = str(self._settings._api_key)
121
+ else:
122
+ headers["Authorization"] = "Bearer " + bearer
123
+ data = None
124
+ if body is not None:
125
+ headers["Content-Type"] = "application/json"
126
+ data = json.dumps(body).encode("utf-8")
127
+ return self._open(urllib.request.Request(url, data=data, headers=headers, method=method))
128
+
129
+ def _open(self, request: urllib.request.Request) -> str:
130
+ timeout = self._settings._timeout or None
131
+ try:
132
+ with urllib.request.urlopen(request, timeout=timeout) as response:
133
+ if response.status == 204:
134
+ return ""
135
+ return response.read().decode("utf-8")
136
+ except urllib.error.HTTPError as e:
137
+ raise _failure(e.code, _read_error_body(e)) from None
138
+ except (urllib.error.URLError, http.client.HTTPException, OSError) as e:
139
+ raise MnemoClientException(MnemoError(MnemoError.Code.IO_ERROR)) from e
140
+
141
+ def _uses_client_credentials(self) -> bool:
142
+ return not _is_blank(self._settings._client_id)
143
+
144
+ def _access_token(self, replace: bool) -> str:
145
+ """Returns the cached bearer token, fetching one first when there is none, it is about to expire, or
146
+ ``replace`` is set. The token and its lock live on the builder, which every call of this client shares."""
147
+ settings = self._settings
148
+ with settings._token_lock:
149
+ cached = settings._token
150
+ if not replace and cached is not None and cached[1] - time.monotonic() > TOKEN_REFRESH_MARGIN:
151
+ return cached[0]
152
+ settings._token = self._fetch_token()
153
+ return settings._token[0]
154
+
155
+ def _fetch_token(self) -> Tuple[str, float]:
156
+ settings = self._settings
157
+ credentials = quote(str(settings._client_id), safe="") + ":" + quote(str(settings._client_secret), safe="")
158
+ request = urllib.request.Request(
159
+ str(settings._base_url).rstrip("/") + "/oauth/token",
160
+ data=urlencode({"grant_type": "client_credentials"}).encode("ascii"),
161
+ headers={"Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded",
162
+ "Authorization": "Basic " + base64.b64encode(credentials.encode("utf-8")).decode("ascii")},
163
+ method="POST")
164
+ parsed = _parse_json(self._open(request))
165
+ try:
166
+ return str(parsed["access_token"]), time.monotonic() + float(parsed["expires_in"])
167
+ except (KeyError, TypeError, ValueError) as e:
168
+ raise MnemoClientException(MnemoError(MnemoError.Code.SERIALIZATION_ERROR)) from e
169
+
170
+ def _tenant_id(self) -> Optional[str]:
171
+ return self._settings._tenant_id
172
+
173
+
174
+ def parse_events(text: str) -> List[SseEvent]:
175
+ events: List[SseEvent] = []
176
+ name: Optional[str] = None
177
+ data: List[str] = []
178
+ is_open = False
179
+ for line in re.split(r"\r?\n", text):
180
+ if not line:
181
+ if is_open:
182
+ events.append(SseEvent(name or "message", "\n".join(data)))
183
+ name, data, is_open = None, [], False
184
+ elif not line.startswith(":"):
185
+ field, colon, value = line.partition(":")
186
+ if colon and value.startswith(" "):
187
+ value = value[1:]
188
+ if field == "event":
189
+ name = value
190
+ is_open = True
191
+ elif field == "data":
192
+ data.append(value)
193
+ is_open = True
194
+ if is_open:
195
+ events.append(SseEvent(name or "message", "\n".join(data)))
196
+ return events
197
+
198
+
199
+ def _parse_json(text: str) -> Any:
200
+ try:
201
+ return json.loads(text)
202
+ except ValueError as e:
203
+ raise MnemoClientException(MnemoError(MnemoError.Code.SERIALIZATION_ERROR)) from e
204
+
205
+
206
+ def _read_error_body(error: urllib.error.HTTPError) -> str:
207
+ try:
208
+ return error.read().decode("utf-8", errors="replace")
209
+ except (OSError, http.client.HTTPException):
210
+ return ""
211
+ finally:
212
+ error.close()
213
+
214
+
215
+ def _failure(status: int, text: str) -> MnemoClientException:
216
+ if status == 401:
217
+ code = MnemoError.Code.UNAUTHORIZED
218
+ elif status == 403:
219
+ code = MnemoError.Code.FORBIDDEN
220
+ elif status == 404:
221
+ code = MnemoError.Code.NOT_FOUND
222
+ elif status == 429:
223
+ code = MnemoError.Code.RATE_LIMITED
224
+ elif status >= 500:
225
+ code = MnemoError.Code.SERVER_ERROR
226
+ else:
227
+ code = MnemoError.Code.INVALID_REQUEST
228
+ detail = None
229
+ try:
230
+ error = json.loads(text).get("error")
231
+ detail = None if error is None else str(error)
232
+ except (ValueError, AttributeError):
233
+ pass # the body was not the usual {"error": "..."} JSON; fall back to the code's default message
234
+ return MnemoClientException(MnemoError(code, detail), status)
235
+
236
+
237
+ def _is_blank(value: Optional[str]) -> bool:
238
+ return value is None or not str(value).strip()
239
+
240
+
241
+ def _require(value: Optional[str], name: str) -> str:
242
+ if _is_blank(value):
243
+ raise _invalid(f"{name} is required")
244
+ return str(value)
245
+
246
+
247
+ def _invalid(message: str) -> MnemoClientException:
248
+ return MnemoClientException(MnemoError(MnemoError.Code.INVALID_REQUEST, message))
249
+
250
+
251
+ def _body(**values: Any) -> Dict[str, Any]:
252
+ """Builds a body dict that skips ``None`` values, so only the parameters the caller set are sent."""
253
+ return {key: value for key, value in values.items() if value is not None}
254
+
255
+
256
+ def _query_value(value: Any) -> str:
257
+ # str(True) is "True"; the service expects JSON-style booleans
258
+ if isinstance(value, bool):
259
+ return "true" if value else "false"
260
+ return quote(str(value), safe="")
261
+
262
+
263
+ def _query(url: str, **params: Any) -> str:
264
+ """Appends the query parameters whose value is not ``None``, in the order given."""
265
+ parts = [f"{quote(key, safe='')}={_query_value(value)}" for key, value in params.items() if value is not None]
266
+ return url if not parts else f"{url}?{'&'.join(parts)}"
267
+
268
+
269
+ def _path(base: str, template: str, **values: str) -> str:
270
+ """Resolves the ``{name}`` placeholders of a path template, encoding each value as one path segment."""
271
+ return base + "/" + re.sub(r"\{(\w+)}", lambda m: quote(values[m.group(1)], safe=""), template)
@@ -0,0 +1,144 @@
1
+ # Copyright (c) 2026, PANAXON.AI, LLC. All rights reserved.
2
+ # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ # Multi-Dimensional Neural Elastic Memory Organization (MNEMO) - Python client.
17
+ #
18
+ # Inventor: Edward Suryadi
19
+ # Assignee: PANAXON.AI, LLC
20
+ #
21
+ # Author: edward.suryadi
22
+ # Since: Oct-2026
23
+
24
+ """The implementation of :class:`~mnemo_client.MnemoChatClient` (not part of the public API)."""
25
+
26
+ from __future__ import annotations
27
+
28
+ from typing import Any, Callable, Dict, List, Optional
29
+
30
+ from ._abstract import AbstractMnemoClient, _body, _invalid, _parse_json, _path, _query, _require
31
+ from .chat import MnemoChatClient
32
+ from .exception import MnemoClientException, MnemoError
33
+ from .model import ChatMessageResponse
34
+
35
+ Op = MnemoChatClient.Operation
36
+
37
+
38
+ class MnemoChatClientImpl(AbstractMnemoClient, MnemoChatClient):
39
+ """Implements :class:`MnemoChatClient`: one private method per operation."""
40
+
41
+ def __init__(self, builder: MnemoChatClient.Builder) -> None:
42
+ super().__init__(builder)
43
+ self._builder = builder
44
+
45
+ def execute(self) -> Any:
46
+ """Dispatches to the method that implements the operation chosen on the builder."""
47
+ operation = self._builder._operation
48
+ if operation is None:
49
+ raise _invalid("operation is required")
50
+ dispatch: Dict[MnemoChatClient.Operation, Callable[[str], Any]] = {
51
+ Op.INIT_SESSION: self._init_session,
52
+ Op.CHAT: self._chat,
53
+ Op.LIST_SESSIONS: self._list_sessions,
54
+ Op.GET_HISTORY: self._get_history,
55
+ Op.RENAME_SESSION: self._rename_session,
56
+ Op.CLOSE_SESSION: self._close_session,
57
+ Op.LIST_SUBJECTS: self._list_subjects,
58
+ Op.DELETE_SUBJECT: self._delete_subject,
59
+ Op.UPDATE_SUBJECT_DESCRIPTION: self._update_subject_description,
60
+ Op.GET_PLAN: self._get_plan,
61
+ Op.HEALTH: self._health,
62
+ }
63
+ if operation not in dispatch:
64
+ raise _invalid(f"unknown operation {operation}")
65
+ return self._with_target(dispatch[operation])
66
+
67
+ def _init_session(self, base: str) -> Dict[str, Any]:
68
+ b = self._builder
69
+ events = self._send_event_stream("POST", _path(base, "mnemo/init/stream"),
70
+ _body(tenantId=_require(self._tenant_id(), "tenant_id"),
71
+ sessionId=_require(b._session_id, "session_id"),
72
+ sessionName=b._session_name))
73
+ stages: List[Dict[str, Any]] = []
74
+ complete: Optional[Dict[str, Any]] = None
75
+ for event in events:
76
+ if event.name == "init-stage":
77
+ stages.append(_parse_json(event.data))
78
+ elif event.name == "complete":
79
+ complete = _parse_json(event.data)
80
+ elif event.name == "error":
81
+ parsed = _parse_json(event.data)
82
+ error = parsed.get("error") if isinstance(parsed, dict) else None
83
+ raise MnemoClientException(MnemoError(MnemoError.Code.INIT_FAILED,
84
+ event.data if error is None else str(error)))
85
+ if complete is None:
86
+ raise MnemoClientException(MnemoError(MnemoError.Code.INIT_FAILED,
87
+ "The service ended the stream before initialization completed"))
88
+ return {**complete, "ready": True, "stages": stages}
89
+
90
+ def _chat(self, base: str) -> ChatMessageResponse:
91
+ b = self._builder
92
+ return self._send("POST", _path(base, "mnemo/chat"),
93
+ _body(tenantId=_require(self._tenant_id(), "tenant_id"),
94
+ sessionId=_require(b._session_id, "session_id"),
95
+ message=_require(b._message, "message")),
96
+ convert=ChatMessageResponse.from_dict)
97
+
98
+ def _list_sessions(self, base: str) -> Dict[str, Any]:
99
+ b = self._builder
100
+ return self._send("GET", _query(_path(base, "mnemo/sessions"),
101
+ tenantId=_require(self._tenant_id(), "tenant_id"), q=b._query,
102
+ page=b._page, size=b._size))
103
+
104
+ def _get_history(self, base: str) -> Dict[str, Any]:
105
+ b = self._builder
106
+ return self._send("GET", _query(_path(base, "mnemo/sessions/{id}/history",
107
+ id=_require(b._session_id, "session_id")),
108
+ tenantId=_require(self._tenant_id(), "tenant_id"), before=b._before,
109
+ size=b._size))
110
+
111
+ def _rename_session(self, base: str) -> Dict[str, Any]:
112
+ b = self._builder
113
+ return self._send("PATCH", _path(base, "mnemo/sessions/{id}/name", id=_require(b._session_id, "session_id")),
114
+ _body(tenantId=_require(self._tenant_id(), "tenant_id"),
115
+ sessionName=_require(b._session_name, "session_name")))
116
+
117
+ def _close_session(self, base: str) -> None:
118
+ b = self._builder
119
+ return self._send("DELETE", _query(_path(base, "mnemo/sessions/{id}", id=_require(b._session_id, "session_id")),
120
+ tenantId=_require(self._tenant_id(), "tenant_id"),
121
+ permanent=bool(b._permanent)),
122
+ expect_body=False)
123
+
124
+ def _list_subjects(self, base: str) -> List[Dict[str, Any]]:
125
+ return self._send("GET", _query(_path(base, "mnemo/subjects"),
126
+ tenantId=_require(self._tenant_id(), "tenant_id")))
127
+
128
+ def _delete_subject(self, base: str) -> None:
129
+ return self._send("DELETE", _query(_path(base, "mnemo/subject/{name}",
130
+ name=_require(self._builder._subject_name, "subject_name")),
131
+ tenantId=_require(self._tenant_id(), "tenant_id")),
132
+ expect_body=False)
133
+
134
+ def _update_subject_description(self, base: str) -> Dict[str, Any]:
135
+ return self._send("PATCH", _path(base, "mnemo/subject/{name}/description",
136
+ name=_require(self._builder._subject_name, "subject_name")),
137
+ _body(tenantId=_require(self._tenant_id(), "tenant_id"),
138
+ description=self._builder._description))
139
+
140
+ def _get_plan(self, base: str) -> Dict[str, Any]:
141
+ return self._send("GET", _query(_path(base, "mnemo/plan"), tenantId=_require(self._tenant_id(), "tenant_id")))
142
+
143
+ def _health(self, base: str) -> Dict[str, Any]:
144
+ return self._send("GET", _path(base, "mnemo/health"))
@@ -0,0 +1,162 @@
1
+ # Copyright (c) 2026, PANAXON.AI, LLC. All rights reserved.
2
+ # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ # Multi-Dimensional Neural Elastic Memory Organization (MNEMO) - Python client.
17
+ #
18
+ # Inventor: Edward Suryadi
19
+ # Assignee: PANAXON.AI, LLC
20
+ #
21
+ # Author: edward.suryadi
22
+ # Since: Oct-2026
23
+
24
+ """The implementation of :class:`~mnemo_client.MnemoNetworkClient` (not part of the public API)."""
25
+
26
+ from __future__ import annotations
27
+
28
+ from typing import Any, Callable, Dict
29
+
30
+ from ._abstract import AbstractMnemoClient, _body, _invalid, _path, _query, _require
31
+ from .network import MnemoNetworkClient
32
+
33
+ Op = MnemoNetworkClient.Operation
34
+
35
+
36
+ class MnemoNetworkClientImpl(AbstractMnemoClient, MnemoNetworkClient):
37
+ """Implements :class:`MnemoNetworkClient`: one private method per operation."""
38
+
39
+ def __init__(self, builder: MnemoNetworkClient.Builder) -> None:
40
+ super().__init__(builder)
41
+ self._builder = builder
42
+
43
+ def execute(self) -> Any:
44
+ """Dispatches to the method that implements the operation chosen on the builder."""
45
+ operation = self._builder._operation
46
+ if operation is None:
47
+ raise _invalid("operation is required")
48
+ dispatch: Dict[MnemoNetworkClient.Operation, Callable[[str], Any]] = {
49
+ Op.LIST_PRIVATE_GRANTS: self._list_private_grants,
50
+ Op.GRANT_PRIVATE: self._grant_private,
51
+ Op.REVOKE_PRIVATE: self._revoke_private,
52
+ Op.LIST_INBOUND_GRANTS: self._list_inbound_grants,
53
+ Op.ACCEPT_INBOUND_GRANT: self._accept_inbound_grant,
54
+ Op.REMOVE_INBOUND_GRANT: self._remove_inbound_grant,
55
+ Op.PUBLISH: self._publish,
56
+ Op.UNPUBLISH: self._unpublish,
57
+ Op.BROWSE_PUBLIC_REGISTRY: self._browse_public_registry,
58
+ Op.SUBSCRIBE: self._subscribe,
59
+ Op.UNSUBSCRIBE: self._unsubscribe,
60
+ Op.LIST_SUBSCRIPTIONS: self._list_subscriptions,
61
+ Op.SEARCH_TENANTS: self._search_tenants,
62
+ Op.REQUEST_AFFILIATION: self._request_affiliation,
63
+ Op.APPROVE_AFFILIATION: self._approve_affiliation,
64
+ Op.REJECT_AFFILIATION: self._reject_affiliation,
65
+ Op.LIST_OUTGOING_AFFILIATIONS: self._list_outgoing_affiliations,
66
+ Op.LIST_INCOMING_AFFILIATIONS: self._list_incoming_affiliations,
67
+ }
68
+ if operation not in dispatch:
69
+ raise _invalid(f"unknown operation {operation}")
70
+ return self._with_target(dispatch[operation])
71
+
72
+ def _list_private_grants(self, base: str) -> Dict[str, Any]:
73
+ return self._send("GET", _query(_path(base, "mnemo/network/sharing/private"), ownerTenantId=self._tenant()))
74
+
75
+ def _grant_private(self, base: str) -> Any:
76
+ return self._send("POST", _path(base, "mnemo/network/sharing/private"),
77
+ _body(ownerTenantId=self._tenant(), subject=self._subject(),
78
+ targetTenantId=self._counterpart(), description=self._builder._description))
79
+
80
+ def _revoke_private(self, base: str) -> None:
81
+ return self._send("DELETE", _query(self._subject_path(base, "sharing/private/{subject}"),
82
+ ownerTenantId=self._tenant(), targetTenantId=self._counterpart()),
83
+ expect_body=False)
84
+
85
+ def _list_inbound_grants(self, base: str) -> Dict[str, Any]:
86
+ return self._send("GET", _query(_path(base, "mnemo/network/sharing/private/inbound"),
87
+ borrowerTenantId=self._tenant()))
88
+
89
+ def _accept_inbound_grant(self, base: str) -> Any:
90
+ return self._send("POST", _query(self._subject_path(base, "sharing/private/inbound/{subject}/accept"),
91
+ borrowerTenantId=self._tenant(), ownerTenantId=self._counterpart()))
92
+
93
+ def _remove_inbound_grant(self, base: str) -> None:
94
+ return self._send("DELETE", _query(self._subject_path(base, "sharing/private/inbound/{subject}"),
95
+ borrowerTenantId=self._tenant(), ownerTenantId=self._counterpart()),
96
+ expect_body=False)
97
+
98
+ def _publish(self, base: str) -> Any:
99
+ return self._send("POST", _query(self._subject_path(base, "sharing/public/{subject}"),
100
+ ownerTenantId=self._tenant()),
101
+ _body(description=self._builder._description,
102
+ affiliatedOnly=self._builder._affiliated_only))
103
+
104
+ def _unpublish(self, base: str) -> None:
105
+ return self._send("DELETE", _query(self._subject_path(base, "sharing/public/{subject}"),
106
+ ownerTenantId=self._tenant()),
107
+ expect_body=False)
108
+
109
+ def _browse_public_registry(self, base: str) -> Dict[str, Any]:
110
+ b = self._builder
111
+ return self._send("GET", _query(_path(base, "mnemo/network/sharing/public/registry"),
112
+ subject=b._subject, ownerTenantId=b._counterpart_tenant_id,
113
+ callerTenantId=self._tenant_id(), page=b._page, size=b._size))
114
+
115
+ def _subscribe(self, base: str) -> Any:
116
+ return self._send("POST", _path(base, "mnemo/network/sharing/subscriptions"),
117
+ _body(subscriberTenantId=self._tenant(), ownerTenantId=self._counterpart(),
118
+ subject=self._subject()))
119
+
120
+ def _unsubscribe(self, base: str) -> None:
121
+ return self._send("DELETE", _query(_path(base, "mnemo/network/sharing/subscriptions/{owner}/{subject}",
122
+ owner=self._counterpart(), subject=self._subject()),
123
+ subscriberTenantId=self._tenant()),
124
+ expect_body=False)
125
+
126
+ def _list_subscriptions(self, base: str) -> Dict[str, Any]:
127
+ return self._send("GET", _query(_path(base, "mnemo/network/sharing/subscriptions"), tenantId=self._tenant()))
128
+
129
+ def _search_tenants(self, base: str) -> Dict[str, Any]:
130
+ b = self._builder
131
+ return self._send("GET", _query(_path(base, "mnemo/network/tenants/search"),
132
+ q=_require(b._query, "query"), page=b._page, size=b._size))
133
+
134
+ def _request_affiliation(self, base: str) -> Any:
135
+ return self._send("POST", _path(base, "mnemo/network/affiliates/requests"),
136
+ _body(requesterTenantId=self._tenant(), targetTenantId=self._counterpart()))
137
+
138
+ def _approve_affiliation(self, base: str) -> Any:
139
+ return self._send("POST", _query(_path(base, "mnemo/network/affiliates/requests/{requester}/approve",
140
+ requester=self._counterpart()), targetTenantId=self._tenant()))
141
+
142
+ def _reject_affiliation(self, base: str) -> Any:
143
+ return self._send("POST", _query(_path(base, "mnemo/network/affiliates/requests/{requester}/reject",
144
+ requester=self._counterpart()), targetTenantId=self._tenant()))
145
+
146
+ def _list_outgoing_affiliations(self, base: str) -> Dict[str, Any]:
147
+ return self._send("GET", _query(_path(base, "mnemo/network/affiliates/outgoing"), tenantId=self._tenant()))
148
+
149
+ def _list_incoming_affiliations(self, base: str) -> Dict[str, Any]:
150
+ return self._send("GET", _query(_path(base, "mnemo/network/affiliates/incoming"), tenantId=self._tenant()))
151
+
152
+ def _tenant(self) -> str:
153
+ return _require(self._tenant_id(), "tenant_id")
154
+
155
+ def _counterpart(self) -> str:
156
+ return _require(self._builder._counterpart_tenant_id, "counterpart_tenant_id")
157
+
158
+ def _subject(self) -> str:
159
+ return _require(self._builder._subject, "subject")
160
+
161
+ def _subject_path(self, base: str, template: str) -> str:
162
+ return _path(base, "mnemo/network/" + template, subject=self._subject())