localmem-memory 0.1.0__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.
- localmem_memory-0.1.0/LICENSE +202 -0
- localmem_memory-0.1.0/NOTICE +5 -0
- localmem_memory-0.1.0/PKG-INFO +33 -0
- localmem_memory-0.1.0/README.md +20 -0
- localmem_memory-0.1.0/localmem_memory/__init__.py +6 -0
- localmem_memory-0.1.0/localmem_memory/cli.py +155 -0
- localmem_memory-0.1.0/localmem_memory/client.py +251 -0
- localmem_memory-0.1.0/localmem_memory.egg-info/PKG-INFO +33 -0
- localmem_memory-0.1.0/localmem_memory.egg-info/SOURCES.txt +13 -0
- localmem_memory-0.1.0/localmem_memory.egg-info/dependency_links.txt +1 -0
- localmem_memory-0.1.0/localmem_memory.egg-info/entry_points.txt +2 -0
- localmem_memory-0.1.0/localmem_memory.egg-info/top_level.txt +1 -0
- localmem_memory-0.1.0/pyproject.toml +22 -0
- localmem_memory-0.1.0/setup.cfg +4 -0
- localmem_memory-0.1.0/tests/test_sdk.py +144 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: localmem-memory
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The localmem Memory API: memory of each of your customers, with the source and date of every fact. `localmem-memory login` pairs a terminal with a project.
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://localmem.org/docs/memory-api/sdks
|
|
7
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
8
|
+
Requires-Python: >=3.9
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
License-File: NOTICE
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# localmem-memory
|
|
15
|
+
|
|
16
|
+
The localmem Memory API from Python: memory of each of your customers, with
|
|
17
|
+
the source and date of every fact. Standard library only. Server-side only.
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
pip install localmem-memory
|
|
21
|
+
localmem-memory login # pair this terminal: approve the code in the browser
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from localmem_memory import Memory
|
|
26
|
+
|
|
27
|
+
lm = Memory() # reads LOCALMEM_PROJECT, LOCALMEM_KEY_ID, LOCALMEM_KEY_SECRET
|
|
28
|
+
tenant = lm.customers.create("cust-42")["tenant"]
|
|
29
|
+
lm.documents.send(tenant, "Ada Byron joined Acme on 3 March.")
|
|
30
|
+
print(lm.recall(tenant, "Ada Byron")["facts"])
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Docs: https://localmem.org/docs/memory-api/sdks · Support: support@localmem.org
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# localmem-memory
|
|
2
|
+
|
|
3
|
+
The localmem Memory API from Python: memory of each of your customers, with
|
|
4
|
+
the source and date of every fact. Standard library only. Server-side only.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
pip install localmem-memory
|
|
8
|
+
localmem-memory login # pair this terminal: approve the code in the browser
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from localmem_memory import Memory
|
|
13
|
+
|
|
14
|
+
lm = Memory() # reads LOCALMEM_PROJECT, LOCALMEM_KEY_ID, LOCALMEM_KEY_SECRET
|
|
15
|
+
tenant = lm.customers.create("cust-42")["tenant"]
|
|
16
|
+
lm.documents.send(tenant, "Ada Byron joined Acme on 3 March.")
|
|
17
|
+
print(lm.recall(tenant, "Ada Byron")["facts"])
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Docs: https://localmem.org/docs/memory-api/sdks · Support: support@localmem.org
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""``localmem-memory login`` (specs/037 R53): pairs this terminal with a
|
|
2
|
+
project, as ``npx @localmem/memory login`` does. It asks for a pairing,
|
|
3
|
+
prints the code, opens the approval page, and polls with its device secret
|
|
4
|
+
until the key is handed to it once; then writes the three variables into
|
|
5
|
+
.env (or --env-file) and keeps that file out of git. The secret is never
|
|
6
|
+
printed.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import socket
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import time
|
|
19
|
+
import urllib.error
|
|
20
|
+
import urllib.request
|
|
21
|
+
import webbrowser
|
|
22
|
+
from typing import Callable, Dict, Tuple
|
|
23
|
+
|
|
24
|
+
from .client import DEFAULT_API
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def post(url: str, body: dict) -> Tuple[int, dict]:
|
|
28
|
+
req = urllib.request.Request(
|
|
29
|
+
url, data=json.dumps(body).encode(), method="POST", headers={"content-type": "application/json"}
|
|
30
|
+
)
|
|
31
|
+
try:
|
|
32
|
+
with urllib.request.urlopen(req, timeout=30) as r:
|
|
33
|
+
status, raw = r.status, r.read()
|
|
34
|
+
except urllib.error.HTTPError as e:
|
|
35
|
+
status, raw = e.code, e.read()
|
|
36
|
+
try:
|
|
37
|
+
return status, json.loads(raw) if raw else {}
|
|
38
|
+
except ValueError:
|
|
39
|
+
return status, {"message": raw[:200].decode(errors="replace")}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _read(path: str) -> str:
|
|
43
|
+
if not os.path.exists(path):
|
|
44
|
+
return ""
|
|
45
|
+
with open(path, encoding="utf8") as f:
|
|
46
|
+
return f.read()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def with_vars(text: str, values: Dict[str, str]) -> str:
|
|
50
|
+
"""``text`` with each of ``values`` set: an existing line replaced, a new one appended."""
|
|
51
|
+
lines = text.rstrip("\n").split("\n") if text else []
|
|
52
|
+
for k, v in values.items():
|
|
53
|
+
pattern = re.compile(rf"^\s*(export\s+)?{re.escape(k)}\s*=")
|
|
54
|
+
at = next((i for i, l in enumerate(lines) if pattern.match(l)), None)
|
|
55
|
+
if at is None:
|
|
56
|
+
lines.append(f"{k}={v}")
|
|
57
|
+
else:
|
|
58
|
+
lines[at] = f"{k}={v}"
|
|
59
|
+
return "\n".join(lines) + "\n"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def keep_out_of_git(path: str) -> str:
|
|
63
|
+
"""Nothing when git already ignores ``path``, else its name added to the .gitignore beside it."""
|
|
64
|
+
folder, name = os.path.split(os.path.abspath(path))
|
|
65
|
+
try:
|
|
66
|
+
checked = subprocess.run(["git", "check-ignore", "-q", name], cwd=folder, capture_output=True).returncode
|
|
67
|
+
except OSError:
|
|
68
|
+
checked = 128
|
|
69
|
+
if checked == 0:
|
|
70
|
+
return f"{name} is already ignored by git."
|
|
71
|
+
ignore = os.path.join(folder, ".gitignore")
|
|
72
|
+
have = _read(ignore)
|
|
73
|
+
if checked != 1 and any(l.strip() in (name, f"/{name}") for l in have.split("\n")):
|
|
74
|
+
return f"{name} is already in .gitignore."
|
|
75
|
+
with open(ignore, "a", encoding="utf8") as f:
|
|
76
|
+
f.write(("\n" if have and not have.endswith("\n") else "") + name + "\n")
|
|
77
|
+
return f"Added {name} to .gitignore, so the secret is never committed."
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def login(
|
|
81
|
+
api: str,
|
|
82
|
+
env_file: str,
|
|
83
|
+
device: str,
|
|
84
|
+
browser: bool,
|
|
85
|
+
log: Callable[[str], None] = print,
|
|
86
|
+
send: Callable[[str, dict], Tuple[int, dict]] = post,
|
|
87
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
88
|
+
open_url: Callable[[str], object] = webbrowser.open,
|
|
89
|
+
) -> int:
|
|
90
|
+
status, opened = send(f"{api}/v1/pair", {"device": device})
|
|
91
|
+
if status != 201:
|
|
92
|
+
log(f"Could not start pairing: {opened.get('message') or f'localmem answered {status}'}")
|
|
93
|
+
return 1
|
|
94
|
+
until = time.monotonic() + float(opened.get("expires_in", 600))
|
|
95
|
+
log(f"Your code: {opened['code']}")
|
|
96
|
+
log(f"Approve it at {opened['url']}")
|
|
97
|
+
if browser:
|
|
98
|
+
try:
|
|
99
|
+
open_url(opened["url"])
|
|
100
|
+
except Exception:
|
|
101
|
+
pass # The link is printed; opening it is a courtesy.
|
|
102
|
+
log("Waiting for approval…")
|
|
103
|
+
while True:
|
|
104
|
+
sleep(float(opened.get("interval", 3)))
|
|
105
|
+
if time.monotonic() > until:
|
|
106
|
+
log("The code expired before it was approved. Run `localmem-memory login` again.")
|
|
107
|
+
return 1
|
|
108
|
+
try:
|
|
109
|
+
status, said = send(f"{api}/v1/pair/{opened['pairing']}/token", {"device_secret": opened["device_secret"]})
|
|
110
|
+
except OSError:
|
|
111
|
+
continue
|
|
112
|
+
if status == 202 or status == 429 or status >= 500:
|
|
113
|
+
continue
|
|
114
|
+
if status != 200:
|
|
115
|
+
log(said.get("message") or "This pairing has ended. Run `localmem-memory login` again.")
|
|
116
|
+
return 1
|
|
117
|
+
values = {
|
|
118
|
+
"LOCALMEM_PROJECT": said["project"],
|
|
119
|
+
"LOCALMEM_KEY_ID": said["key_id"],
|
|
120
|
+
"LOCALMEM_KEY_SECRET": said["secret"],
|
|
121
|
+
}
|
|
122
|
+
if api != DEFAULT_API:
|
|
123
|
+
values["LOCALMEM_API_URL"] = api
|
|
124
|
+
existed = os.path.exists(env_file)
|
|
125
|
+
text = _read(env_file)
|
|
126
|
+
with open(env_file, "w", encoding="utf8") as f:
|
|
127
|
+
f.write(with_vars(text, values))
|
|
128
|
+
if not existed:
|
|
129
|
+
os.chmod(env_file, 0o600)
|
|
130
|
+
log(f"Paired with project {said['project']}: a test key, {said['key_id']}.")
|
|
131
|
+
log(f"Wrote {', '.join(values)} to {env_file}. The secret is not shown here.")
|
|
132
|
+
log(keep_out_of_git(env_file))
|
|
133
|
+
return 0
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def main(argv=None) -> int:
|
|
137
|
+
p = argparse.ArgumentParser(
|
|
138
|
+
prog="localmem-memory",
|
|
139
|
+
description="Pairs this terminal with a localmem project: approve the code it prints in the browser, and a test key is written to your .env file.",
|
|
140
|
+
)
|
|
141
|
+
sub = p.add_subparsers(dest="command")
|
|
142
|
+
l = sub.add_parser("login", help="pair this terminal with a project")
|
|
143
|
+
l.add_argument("--env-file", default=".env")
|
|
144
|
+
l.add_argument("--device", default=(socket.gethostname() or "a terminal")[:60])
|
|
145
|
+
l.add_argument("--api", default=os.environ.get("LOCALMEM_API_URL", DEFAULT_API))
|
|
146
|
+
l.add_argument("--no-browser", action="store_true")
|
|
147
|
+
a = p.parse_args(argv)
|
|
148
|
+
if a.command != "login":
|
|
149
|
+
p.print_help()
|
|
150
|
+
return 0 if a.command is None else 2
|
|
151
|
+
return login(a.api.rstrip("/"), a.env_file, a.device, not a.no_browser)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
if __name__ == "__main__":
|
|
155
|
+
sys.exit(main())
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""The localmem Memory API from Python (specs/037 R55).
|
|
2
|
+
|
|
3
|
+
Reads LOCALMEM_PROJECT, LOCALMEM_KEY_ID and LOCALMEM_KEY_SECRET (written by
|
|
4
|
+
``localmem-memory login``), signs every request as the gateway checks it
|
|
5
|
+
(033 R2), sends an Idempotency-Key with every document and retries it on a
|
|
6
|
+
timeout or a 5xx, honours Retry-After, and raises LocalmemError with the
|
|
7
|
+
gateway's ``{ error, message }``. Standard library only. Server-side only:
|
|
8
|
+
the secret must never reach a browser.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import hmac
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import random
|
|
18
|
+
import time
|
|
19
|
+
import urllib.error
|
|
20
|
+
import urllib.parse
|
|
21
|
+
import urllib.request
|
|
22
|
+
import uuid
|
|
23
|
+
from typing import Any, Callable, Dict, Optional
|
|
24
|
+
|
|
25
|
+
DEFAULT_API = "https://api.localmem.org"
|
|
26
|
+
# The longest Retry-After waited for; past it the error is raised at once.
|
|
27
|
+
MAX_WAIT_SECONDS = 60
|
|
28
|
+
|
|
29
|
+
Json = Dict[str, Any]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class LocalmemError(Exception):
|
|
33
|
+
"""An answer that is not a success: the gateway's code and its words."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, status: int, body: Json, request_id: Optional[str], retry_after: Optional[int]):
|
|
36
|
+
self.status = status
|
|
37
|
+
self.error = body.get("error") if isinstance(body.get("error"), str) else f"http_{status}"
|
|
38
|
+
self.message = body.get("message") if isinstance(body.get("message"), str) else f"localmem answered {status}"
|
|
39
|
+
self.request_id = request_id
|
|
40
|
+
self.retry_after = retry_after
|
|
41
|
+
self.body = body
|
|
42
|
+
super().__init__(self.message)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def sign(secret: str, timestamp: str, method: str, path: str, body: bytes) -> str:
|
|
46
|
+
"""The hex HMAC-SHA256 the gateway checks: ``timestamp.METHOD.path.body``, the path without its query."""
|
|
47
|
+
bare = path.split("?", 1)[0]
|
|
48
|
+
signed = f"{timestamp}.{method}.{bare}.".encode() + body
|
|
49
|
+
return hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _env(name: str) -> Optional[str]:
|
|
53
|
+
v = os.environ.get(name, "").strip()
|
|
54
|
+
return v or None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _backoff(attempt: int) -> float:
|
|
58
|
+
"""0.5 s, 1 s, 2 s ... with jitter, at most 8 s."""
|
|
59
|
+
return min(8.0, 0.5 * 2**attempt) * (0.5 + random.random() / 2)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Transport:
|
|
63
|
+
"""One HTTP exchange: (status, headers, body bytes). Raises OSError on no answer."""
|
|
64
|
+
|
|
65
|
+
def __call__(self, method: str, url: str, headers: Dict[str, str], body: Optional[bytes], timeout: float):
|
|
66
|
+
req = urllib.request.Request(url, data=body, method=method, headers=headers)
|
|
67
|
+
try:
|
|
68
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
69
|
+
return r.status, dict(r.headers), r.read()
|
|
70
|
+
except urllib.error.HTTPError as e:
|
|
71
|
+
return e.code, dict(e.headers or {}), e.read()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class _Customers:
|
|
75
|
+
def __init__(self, m: "Memory"):
|
|
76
|
+
self._m = m
|
|
77
|
+
|
|
78
|
+
def create(self, external_ref: str, phi: Optional[bool] = None) -> Json:
|
|
79
|
+
"""Made once per ``external_ref``: the same one again answers the same customer."""
|
|
80
|
+
body: Json = {"external_ref": external_ref}
|
|
81
|
+
if phi is not None:
|
|
82
|
+
body["phi"] = phi
|
|
83
|
+
return self._m._call("POST", "/v1/partner/tenants", body=body)
|
|
84
|
+
|
|
85
|
+
def list(self) -> Json:
|
|
86
|
+
return self._m._call("GET", "/v1/partner/tenants")
|
|
87
|
+
|
|
88
|
+
def get(self, tenant: str) -> Json:
|
|
89
|
+
return self._m._call("GET", f"/v1/partner/tenants/{urllib.parse.quote(tenant, safe='')}")
|
|
90
|
+
|
|
91
|
+
def delete(self, tenant: str) -> Json:
|
|
92
|
+
"""Access stops at once; see the data contract for what follows."""
|
|
93
|
+
return self._m._call("DELETE", f"/v1/partner/tenants/{urllib.parse.quote(tenant, safe='')}")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class _Documents:
|
|
97
|
+
def __init__(self, m: "Memory"):
|
|
98
|
+
self._m = m
|
|
99
|
+
|
|
100
|
+
def send(self, tenant: str, text: str, *, idempotency_key: Optional[str] = None, **fields: Any) -> Json:
|
|
101
|
+
"""Sends a document (``title``, ``as_of``, ``tags``, ``external_ref`` as keywords),
|
|
102
|
+
with an Idempotency-Key so a retry never reads it twice. Answers the written
|
|
103
|
+
facts, or ``{ status, follow }`` when it is read in the background: pass its
|
|
104
|
+
``document_id`` to :meth:`wait`."""
|
|
105
|
+
return self._m._call(
|
|
106
|
+
"POST",
|
|
107
|
+
"/v1/memory/documents",
|
|
108
|
+
body={"text": text, **fields},
|
|
109
|
+
tenant=tenant,
|
|
110
|
+
headers={"Idempotency-Key": idempotency_key or str(uuid.uuid4())},
|
|
111
|
+
repeatable=True,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
def get(self, tenant: str, document_id: str) -> Json:
|
|
115
|
+
return self._m._call(
|
|
116
|
+
"GET", f"/v1/memory/documents/{urllib.parse.quote(document_id, safe='')}", tenant=tenant
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
def wait(self, tenant: str, document_id: str, timeout: float = 600, every: float = 5) -> Json:
|
|
120
|
+
"""Polls a background document until it is written or failed."""
|
|
121
|
+
until = time.monotonic() + timeout
|
|
122
|
+
while True:
|
|
123
|
+
d = self.get(tenant, document_id)
|
|
124
|
+
if d.get("status") in ("written", "failed") or time.monotonic() > until:
|
|
125
|
+
return d
|
|
126
|
+
self._m._sleep(every)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class Memory:
|
|
130
|
+
"""A project's key, signing each request."""
|
|
131
|
+
|
|
132
|
+
def __init__(
|
|
133
|
+
self,
|
|
134
|
+
project: Optional[str] = None,
|
|
135
|
+
key_id: Optional[str] = None,
|
|
136
|
+
secret: Optional[str] = None,
|
|
137
|
+
base_url: Optional[str] = None,
|
|
138
|
+
timeout: float = 120,
|
|
139
|
+
max_retries: int = 3,
|
|
140
|
+
transport: Optional[Callable[..., Any]] = None,
|
|
141
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
142
|
+
):
|
|
143
|
+
project = project or _env("LOCALMEM_PROJECT")
|
|
144
|
+
key_id = key_id or _env("LOCALMEM_KEY_ID")
|
|
145
|
+
secret = secret or _env("LOCALMEM_KEY_SECRET")
|
|
146
|
+
missing = [n for n, v in (("LOCALMEM_PROJECT", project), ("LOCALMEM_KEY_ID", key_id), ("LOCALMEM_KEY_SECRET", secret)) if not v]
|
|
147
|
+
if missing:
|
|
148
|
+
raise ValueError(f"Set {', '.join(missing)}: run `localmem-memory login`, or pass them to Memory().")
|
|
149
|
+
self.project, self.key_id, self._secret = project, key_id, secret
|
|
150
|
+
self.base_url = (base_url or _env("LOCALMEM_API_URL") or DEFAULT_API).rstrip("/")
|
|
151
|
+
self._timeout, self._max_retries = timeout, max_retries
|
|
152
|
+
self._transport = transport or Transport()
|
|
153
|
+
self._sleep = sleep
|
|
154
|
+
self.customers = _Customers(self)
|
|
155
|
+
self.documents = _Documents(self)
|
|
156
|
+
|
|
157
|
+
def facts(self, tenant: str, **body: Any) -> Json:
|
|
158
|
+
"""Facts you extracted yourself: nothing goes to a model."""
|
|
159
|
+
return self._memory("facts", tenant, body)
|
|
160
|
+
|
|
161
|
+
def write(self, tenant: str, content: str, **body: Any) -> Json:
|
|
162
|
+
return self._memory("write", tenant, {"content": content, **body})
|
|
163
|
+
|
|
164
|
+
def search(self, tenant: str, query: str, **body: Any) -> Json:
|
|
165
|
+
return self._memory("search", tenant, {"query": query, **body})
|
|
166
|
+
|
|
167
|
+
def recall(self, tenant: str, entity: str, **body: Any) -> Json:
|
|
168
|
+
"""What is known about ``entity``, now or at ``at_time``."""
|
|
169
|
+
return self._memory("recall", tenant, {"entity": entity, **body})
|
|
170
|
+
|
|
171
|
+
def get(self, tenant: str, event_id: str) -> Json:
|
|
172
|
+
return self._memory("get", tenant, {"event_id": event_id})
|
|
173
|
+
|
|
174
|
+
def profile(self, tenant: str, **body: Any) -> Json:
|
|
175
|
+
return self._memory("profile", tenant, body)
|
|
176
|
+
|
|
177
|
+
def forget(self, tenant: str, target_id: str) -> Json:
|
|
178
|
+
"""Hides it from answers from now on; it does not destroy it."""
|
|
179
|
+
return self._memory("forget", tenant, {"target_id": target_id})
|
|
180
|
+
|
|
181
|
+
def usage(self, from_: Optional[str] = None, to: Optional[str] = None) -> Json:
|
|
182
|
+
"""One entry per customer and day, both dates included (YYYY-MM-DD)."""
|
|
183
|
+
q = urllib.parse.urlencode({k: v for k, v in (("from", from_), ("to", to)) if v})
|
|
184
|
+
return self._call("GET", f"/v1/partner/usage{'?' + q if q else ''}")
|
|
185
|
+
|
|
186
|
+
def _memory(self, route: str, tenant: str, body: Json) -> Json:
|
|
187
|
+
return self._call("POST", f"/v1/memory/{route}", body=body, tenant=tenant)
|
|
188
|
+
|
|
189
|
+
def _call(
|
|
190
|
+
self,
|
|
191
|
+
method: str,
|
|
192
|
+
path: str,
|
|
193
|
+
body: Optional[Json] = None,
|
|
194
|
+
tenant: Optional[str] = None,
|
|
195
|
+
headers: Optional[Dict[str, str]] = None,
|
|
196
|
+
repeatable: Optional[bool] = None,
|
|
197
|
+
) -> Json:
|
|
198
|
+
raw = b"" if body is None else json.dumps(body, separators=(",", ":")).encode()
|
|
199
|
+
repeatable = method == "GET" if repeatable is None else repeatable
|
|
200
|
+
attempt = 0
|
|
201
|
+
while True:
|
|
202
|
+
ts = str(int(time.time()))
|
|
203
|
+
h = {
|
|
204
|
+
"x-partner-id": self.project,
|
|
205
|
+
"x-localmem-key": self.key_id,
|
|
206
|
+
"x-localmem-timestamp": ts,
|
|
207
|
+
"x-localmem-signature": sign(self._secret, ts, method, path, raw),
|
|
208
|
+
"user-agent": "localmem-memory-python",
|
|
209
|
+
}
|
|
210
|
+
if raw:
|
|
211
|
+
h["content-type"] = "application/json"
|
|
212
|
+
if tenant:
|
|
213
|
+
h["x-tenant-id"] = tenant
|
|
214
|
+
h.update(headers or {})
|
|
215
|
+
try:
|
|
216
|
+
status, got, data = self._transport(method, self.base_url + path, h, raw if body is not None else None, self._timeout)
|
|
217
|
+
except OSError:
|
|
218
|
+
# No answer: sent again only when that cannot do it twice.
|
|
219
|
+
if repeatable and attempt < self._max_retries:
|
|
220
|
+
self._sleep(_backoff(attempt))
|
|
221
|
+
attempt += 1
|
|
222
|
+
continue
|
|
223
|
+
raise
|
|
224
|
+
try:
|
|
225
|
+
answer = json.loads(data) if data else {}
|
|
226
|
+
except ValueError:
|
|
227
|
+
answer = {"error": "not_json", "message": data[:200].decode(errors="replace")}
|
|
228
|
+
if 200 <= status < 300:
|
|
229
|
+
return answer
|
|
230
|
+
lower = {k.lower(): v for k, v in got.items()}
|
|
231
|
+
after = lower.get("retry-after")
|
|
232
|
+
retry_after = int(after) if after and after.isdigit() else None
|
|
233
|
+
err = LocalmemError(status, answer, lower.get("x-request-id"), retry_after)
|
|
234
|
+
if attempt < self._max_retries:
|
|
235
|
+
# A 429, and a 503 server_busy, were refused before any work,
|
|
236
|
+
# so any request may go again when the wait is short; a monthly
|
|
237
|
+
# limit's wait is days, so raised. Any other 503 (a timeout)
|
|
238
|
+
# may have done the work: only a repeatable request goes again.
|
|
239
|
+
not_done = status == 429 or (status == 503 and answer.get("error") == "server_busy")
|
|
240
|
+
if (not_done or (status == 503 and repeatable)) and (retry_after or 1) <= MAX_WAIT_SECONDS:
|
|
241
|
+
self._sleep(retry_after if retry_after is not None else _backoff(attempt))
|
|
242
|
+
attempt += 1
|
|
243
|
+
continue
|
|
244
|
+
# A document whose first send is still being read: its answer
|
|
245
|
+
# comes to the same Idempotency-Key shortly.
|
|
246
|
+
in_use = status == 409 and answer.get("error") == "idempotency_key_in_use"
|
|
247
|
+
if (status >= 500 or in_use) and repeatable:
|
|
248
|
+
self._sleep(_backoff(attempt))
|
|
249
|
+
attempt += 1
|
|
250
|
+
continue
|
|
251
|
+
raise err
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: localmem-memory
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The localmem Memory API: memory of each of your customers, with the source and date of every fact. `localmem-memory login` pairs a terminal with a project.
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://localmem.org/docs/memory-api/sdks
|
|
7
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
8
|
+
Requires-Python: >=3.9
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
License-File: NOTICE
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# localmem-memory
|
|
15
|
+
|
|
16
|
+
The localmem Memory API from Python: memory of each of your customers, with
|
|
17
|
+
the source and date of every fact. Standard library only. Server-side only.
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
pip install localmem-memory
|
|
21
|
+
localmem-memory login # pair this terminal: approve the code in the browser
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from localmem_memory import Memory
|
|
26
|
+
|
|
27
|
+
lm = Memory() # reads LOCALMEM_PROJECT, LOCALMEM_KEY_ID, LOCALMEM_KEY_SECRET
|
|
28
|
+
tenant = lm.customers.create("cust-42")["tenant"]
|
|
29
|
+
lm.documents.send(tenant, "Ada Byron joined Acme on 3 March.")
|
|
30
|
+
print(lm.recall(tenant, "Ada Byron")["facts"])
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Docs: https://localmem.org/docs/memory-api/sdks · Support: support@localmem.org
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
NOTICE
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
localmem_memory/__init__.py
|
|
6
|
+
localmem_memory/cli.py
|
|
7
|
+
localmem_memory/client.py
|
|
8
|
+
localmem_memory.egg-info/PKG-INFO
|
|
9
|
+
localmem_memory.egg-info/SOURCES.txt
|
|
10
|
+
localmem_memory.egg-info/dependency_links.txt
|
|
11
|
+
localmem_memory.egg-info/entry_points.txt
|
|
12
|
+
localmem_memory.egg-info/top_level.txt
|
|
13
|
+
tests/test_sdk.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
localmem_memory
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "localmem-memory"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "The localmem Memory API: memory of each of your customers, with the source and date of every fact. `localmem-memory login` pairs a terminal with a project."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "Apache-2.0" }
|
|
12
|
+
classifiers = ["License :: OSI Approved :: Apache Software License"]
|
|
13
|
+
dependencies = []
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://localmem.org/docs/memory-api/sdks"
|
|
17
|
+
|
|
18
|
+
[project.scripts]
|
|
19
|
+
localmem-memory = "localmem_memory.cli:main"
|
|
20
|
+
|
|
21
|
+
[tool.setuptools]
|
|
22
|
+
packages = ["localmem_memory"]
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""specs/037 R53, R55: the Python SDK and its login, against a fake gateway."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import hmac
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
8
|
+
import unittest
|
|
9
|
+
|
|
10
|
+
from localmem_memory import LocalmemError, Memory, sign
|
|
11
|
+
from localmem_memory.cli import login, with_vars
|
|
12
|
+
|
|
13
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
14
|
+
VECTOR = json.load(open(os.path.join(HERE, "..", "..", "signing-vector.json")))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Fake:
|
|
18
|
+
"""Answers from ``answers`` in turn, recording each request."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, answers):
|
|
21
|
+
self.answers, self.seen = list(answers), []
|
|
22
|
+
|
|
23
|
+
def __call__(self, method, url, headers, body, timeout):
|
|
24
|
+
self.seen.append({"method": method, "url": url, "headers": dict(headers), "body": body})
|
|
25
|
+
a = self.answers.pop(0)
|
|
26
|
+
if isinstance(a, Exception):
|
|
27
|
+
raise a
|
|
28
|
+
status, payload, headers = (a + ({},))[:3]
|
|
29
|
+
return status, headers, json.dumps(payload).encode()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def memory(fake, **kw):
|
|
33
|
+
return Memory(project="p-1a2b3c4d", key_id="key_abc", secret="s3cret", base_url="https://api.test/",
|
|
34
|
+
transport=fake, sleep=kw.pop("sleep", lambda s: None), **kw)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Sdk(unittest.TestCase):
|
|
38
|
+
def test_signs_the_shared_vector_exactly_as_the_gateway_checks_it(self):
|
|
39
|
+
v = VECTOR
|
|
40
|
+
self.assertEqual(sign(v["secret"], v["timestamp"], v["method"], v["path"], v["body"].encode()), v["signature"])
|
|
41
|
+
|
|
42
|
+
def test_says_which_variables_are_missing(self):
|
|
43
|
+
saved = dict(os.environ)
|
|
44
|
+
for k in ("LOCALMEM_PROJECT", "LOCALMEM_KEY_ID", "LOCALMEM_KEY_SECRET"):
|
|
45
|
+
os.environ.pop(k, None)
|
|
46
|
+
try:
|
|
47
|
+
with self.assertRaisesRegex(ValueError, "LOCALMEM_PROJECT, LOCALMEM_KEY_ID, LOCALMEM_KEY_SECRET.*login"):
|
|
48
|
+
Memory()
|
|
49
|
+
finally:
|
|
50
|
+
os.environ.update(saved)
|
|
51
|
+
|
|
52
|
+
def test_each_request_is_signed_for_its_method_path_and_exact_body(self):
|
|
53
|
+
f = Fake([(201, {"tenant": "t1"}), (200, {"facts": []})])
|
|
54
|
+
lm = memory(f)
|
|
55
|
+
lm.recall(lm.customers.create("cust-42")["tenant"], "Ada", at_time="2026-11-05T12:00:00Z")
|
|
56
|
+
made, recalled = f.seen
|
|
57
|
+
h = made["headers"]
|
|
58
|
+
want = hmac.new(b"s3cret", f"{h['x-localmem-timestamp']}.POST./v1/partner/tenants.".encode() + made["body"], hashlib.sha256).hexdigest()
|
|
59
|
+
self.assertEqual(made["url"], "https://api.test/v1/partner/tenants")
|
|
60
|
+
self.assertEqual((h["x-partner-id"], h["x-localmem-key"], h["x-localmem-signature"]), ("p-1a2b3c4d", "key_abc", want))
|
|
61
|
+
self.assertEqual(recalled["headers"]["x-tenant-id"], "t1")
|
|
62
|
+
self.assertEqual(json.loads(recalled["body"]), {"entity": "Ada", "at_time": "2026-11-05T12:00:00Z"})
|
|
63
|
+
|
|
64
|
+
def test_a_document_is_retried_with_the_same_idempotency_key(self):
|
|
65
|
+
f = Fake([OSError("reset"), (502, {"error": "extraction_failed"}), (200, {"status": "written", "facts_written": 3})])
|
|
66
|
+
self.assertEqual(memory(f).documents.send("t1", "Ada moved to Leeds.")["facts_written"], 3)
|
|
67
|
+
keys = {s["headers"]["Idempotency-Key"] for s in f.seen}
|
|
68
|
+
self.assertEqual((len(f.seen), len(keys)), (3, 1))
|
|
69
|
+
|
|
70
|
+
def test_a_write_is_not_sent_twice_after_a_5xx_but_waits_out_a_short_429(self):
|
|
71
|
+
f = Fake([(502, {"error": "internal", "message": "boom"})])
|
|
72
|
+
with self.assertRaises(LocalmemError) as e:
|
|
73
|
+
memory(f).write("t1", "x")
|
|
74
|
+
self.assertEqual((e.exception.status, len(f.seen)), (502, 1))
|
|
75
|
+
waits = []
|
|
76
|
+
f = Fake([(429, {"error": "rate_limited"}, {"Retry-After": "2"}), (200, {"event_id": "e1"})])
|
|
77
|
+
self.assertEqual(memory(f, sleep=waits.append).write("t1", "x")["event_id"], "e1")
|
|
78
|
+
self.assertEqual(waits, [2])
|
|
79
|
+
|
|
80
|
+
def test_server_busy_goes_again_a_timeout_does_not_and_a_document_waits_out_a_key_in_use(self):
|
|
81
|
+
f = Fake([(503, {"error": "server_busy"}), (200, {"event_id": "e1"})])
|
|
82
|
+
self.assertEqual(memory(f).write("t1", "x")["event_id"], "e1")
|
|
83
|
+
f = Fake([(503, {"error": "timeout"})])
|
|
84
|
+
with self.assertRaises(LocalmemError):
|
|
85
|
+
memory(f).write("t1", "x")
|
|
86
|
+
self.assertEqual(len(f.seen), 1)
|
|
87
|
+
f = Fake([(409, {"error": "idempotency_key_in_use"}), (200, {"status": "written"})])
|
|
88
|
+
self.assertEqual(memory(f).documents.send("t1", "x")["status"], "written")
|
|
89
|
+
|
|
90
|
+
def test_a_monthly_limit_is_raised_at_once_with_the_gateways_words(self):
|
|
91
|
+
body = {"error": "monthly_limit", "message": "This project's account has read 500 of 500 documents this month.", "resets_at": "2026-12-01T00:00:00Z"}
|
|
92
|
+
f = Fake([(429, body, {"Retry-After": "2160000", "X-Request-Id": "r1"})])
|
|
93
|
+
with self.assertRaises(LocalmemError) as e:
|
|
94
|
+
memory(f).documents.send("t1", "x")
|
|
95
|
+
err = e.exception
|
|
96
|
+
self.assertEqual((err.error, err.message, err.retry_after, err.request_id), ("monthly_limit", body["message"], 2160000, "r1"))
|
|
97
|
+
self.assertEqual((err.body["resets_at"], len(f.seen)), (body["resets_at"], 1))
|
|
98
|
+
|
|
99
|
+
def test_usage_sends_its_range_as_a_query_the_signature_leaves_out(self):
|
|
100
|
+
f = Fake([(200, {"usage": []})])
|
|
101
|
+
memory(f).usage("2026-11-01", "2026-11-05")
|
|
102
|
+
s = f.seen[0]
|
|
103
|
+
self.assertEqual(s["url"], "https://api.test/v1/partner/usage?from=2026-11-01&to=2026-11-05")
|
|
104
|
+
self.assertEqual(s["headers"]["x-localmem-signature"], sign("s3cret", s["headers"]["x-localmem-timestamp"], "GET", "/v1/partner/usage", b""))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class Login(unittest.TestCase):
|
|
108
|
+
def test_pairs_writes_the_three_variables_and_keeps_the_file_out_of_git(self):
|
|
109
|
+
d = tempfile.mkdtemp()
|
|
110
|
+
env = os.path.join(d, ".env")
|
|
111
|
+
open(env, "w").write("OTHER=1\nLOCALMEM_KEY_ID=old\n")
|
|
112
|
+
answers = [
|
|
113
|
+
(201, {"pairing": "pair_1", "device_secret": "ds", "code": "WDJB-MJHT", "url": "https://app.test/pair?code=WDJB-MJHT", "expires_in": 600, "interval": 3}),
|
|
114
|
+
(202, {"status": "pending"}),
|
|
115
|
+
(200, {"project": "p-1a2b3c4d", "key_id": "key_new", "secret": "lm_test_SECRET", "mode": "test"}),
|
|
116
|
+
]
|
|
117
|
+
sent, lines, opened = [], [], []
|
|
118
|
+
|
|
119
|
+
def send(url, body):
|
|
120
|
+
sent.append((url, body))
|
|
121
|
+
return answers.pop(0)
|
|
122
|
+
|
|
123
|
+
code = login("https://api.localmem.org", env, "ci", True, log=lines.append, send=send, sleep=lambda s: None, open_url=opened.append)
|
|
124
|
+
self.assertEqual(code, 0)
|
|
125
|
+
self.assertEqual(sent[0], ("https://api.localmem.org/v1/pair", {"device": "ci"}))
|
|
126
|
+
self.assertEqual(sent[1][1], {"device_secret": "ds"})
|
|
127
|
+
self.assertEqual(opened, ["https://app.test/pair?code=WDJB-MJHT"])
|
|
128
|
+
self.assertEqual(open(env).read(), "OTHER=1\nLOCALMEM_KEY_ID=key_new\nLOCALMEM_PROJECT=p-1a2b3c4d\nLOCALMEM_KEY_SECRET=lm_test_SECRET\n")
|
|
129
|
+
self.assertIn(".env\n", open(os.path.join(d, ".gitignore")).read())
|
|
130
|
+
self.assertNotIn("lm_test_SECRET", "\n".join(lines))
|
|
131
|
+
|
|
132
|
+
def test_says_so_when_the_pairing_ends(self):
|
|
133
|
+
answers = [(201, {"pairing": "p", "device_secret": "d", "code": "C", "url": "u"}), (410, {"message": "This pairing has ended."})]
|
|
134
|
+
lines = []
|
|
135
|
+
env = os.path.join(tempfile.mkdtemp(), ".env")
|
|
136
|
+
self.assertEqual(login("https://x", env, "ci", False, log=lines.append, send=lambda u, b: answers.pop(0), sleep=lambda s: None), 1)
|
|
137
|
+
self.assertEqual(lines[-1], "This pairing has ended.")
|
|
138
|
+
|
|
139
|
+
def test_with_vars_replaces_an_exported_line(self):
|
|
140
|
+
self.assertEqual(with_vars("export LOCALMEM_PROJECT=old", {"LOCALMEM_PROJECT": "p", "B": "2"}), "LOCALMEM_PROJECT=p\nB=2\n")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
if __name__ == "__main__":
|
|
144
|
+
unittest.main()
|