interject 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.
- interject/__init__.py +116 -0
- interject/_client.py +350 -0
- interject/_config.py +32 -0
- interject/_duration.py +29 -0
- interject/_http.py +103 -0
- interject/_keys.py +39 -0
- interject/errors.py +45 -0
- interject/py.typed +0 -0
- interject-0.1.0.dist-info/METADATA +119 -0
- interject-0.1.0.dist-info/RECORD +12 -0
- interject-0.1.0.dist-info/WHEEL +4 -0
- interject-0.1.0.dist-info/licenses/LICENSE +202 -0
interject/__init__.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""interject — a durable ``ask()`` primitive.
|
|
2
|
+
|
|
3
|
+
Stop a program, ask a human, resume days later on another machine:
|
|
4
|
+
|
|
5
|
+
>>> from interject import ask
|
|
6
|
+
>>> vehicle = ask("Is this a car?", options=["car", "moto"], id="vehicle_type")
|
|
7
|
+
|
|
8
|
+
and the outbound half of the same idea, where silence is the event:
|
|
9
|
+
|
|
10
|
+
>>> from interject import heartbeat
|
|
11
|
+
>>> heartbeat("nightly.etl", expect_every="26h")
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from ._client import DEFAULT_PRIORITY, DEFAULT_WAIT, KINDS, ON_TIMEOUT, Client
|
|
18
|
+
from ._duration import Duration
|
|
19
|
+
from ._keys import context_digest, question_key
|
|
20
|
+
from .errors import (
|
|
21
|
+
Expired,
|
|
22
|
+
InterjectError,
|
|
23
|
+
ProtocolError,
|
|
24
|
+
Suspended,
|
|
25
|
+
Unauthorized,
|
|
26
|
+
Unreachable,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"DEFAULT_PRIORITY",
|
|
31
|
+
"DEFAULT_WAIT",
|
|
32
|
+
"KINDS",
|
|
33
|
+
"ON_TIMEOUT",
|
|
34
|
+
"Client",
|
|
35
|
+
"Duration",
|
|
36
|
+
"Expired",
|
|
37
|
+
"InterjectError",
|
|
38
|
+
"ProtocolError",
|
|
39
|
+
"Suspended",
|
|
40
|
+
"Unauthorized",
|
|
41
|
+
"Unreachable",
|
|
42
|
+
"__version__",
|
|
43
|
+
"answer",
|
|
44
|
+
"ask",
|
|
45
|
+
"context_digest",
|
|
46
|
+
"heartbeat",
|
|
47
|
+
"inbox",
|
|
48
|
+
"key_for",
|
|
49
|
+
"peek",
|
|
50
|
+
"peek_answer",
|
|
51
|
+
"question_key",
|
|
52
|
+
"release",
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
__version__ = "0.1.0"
|
|
56
|
+
|
|
57
|
+
_default_client: Client | None = None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _client() -> Client:
|
|
61
|
+
"""The process-wide client, configured from the environment on first use."""
|
|
62
|
+
global _default_client
|
|
63
|
+
if _default_client is None:
|
|
64
|
+
_default_client = Client()
|
|
65
|
+
return _default_client
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def ask(prompt: str, **kwargs: Any) -> Any:
|
|
69
|
+
"""Ask a human using the process-wide client. See :meth:`Client.ask`."""
|
|
70
|
+
kwargs.setdefault("_stacklevel", 3)
|
|
71
|
+
return _client().ask(prompt, **kwargs)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def answer(key: str, value: Any, **kwargs: Any) -> Any:
|
|
75
|
+
"""Answer a question using the process-wide client. See :meth:`Client.answer`."""
|
|
76
|
+
return _client().answer(key, value, **kwargs)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def inbox(**kwargs: Any) -> Any:
|
|
80
|
+
"""Open questions, grouped by batch. See :meth:`Client.inbox`."""
|
|
81
|
+
return _client().inbox(**kwargs)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def claim(key: str, ttl_seconds: int | None = None) -> Any:
|
|
85
|
+
"""Hold a question while you work on it. See :meth:`Client.claim`."""
|
|
86
|
+
return _client().claim(key, ttl_seconds)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def release(key: str) -> Any:
|
|
90
|
+
"""Give up a claim. See :meth:`Client.release`."""
|
|
91
|
+
return _client().release(key)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def assign(key: str, to: str | None) -> Any:
|
|
95
|
+
"""Route a question to one person. See :meth:`Client.assign`."""
|
|
96
|
+
return _client().assign(key, to)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def key_for(id: str, context: Any = None) -> str:
|
|
100
|
+
"""The key the process-wide client would use. See :meth:`Client.key_for`."""
|
|
101
|
+
return _client().key_for(id, context)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def peek(key: str) -> Any:
|
|
105
|
+
"""Look at a question without creating one. See :meth:`Client.peek`."""
|
|
106
|
+
return _client().peek(key)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def peek_answer(key: str, default: Any = None) -> Any:
|
|
110
|
+
"""The stored answer for ``key``, or ``default``. See :meth:`Client.peek_answer`."""
|
|
111
|
+
return _client().peek_answer(key, default)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def heartbeat(name: str, **kwargs: Any) -> None:
|
|
115
|
+
"""Report a live signal using the process-wide client. See :meth:`Client.heartbeat`."""
|
|
116
|
+
return _client().heartbeat(name, **kwargs)
|
interject/_client.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
"""The ``ask()`` primitive and its outbound twin, ``heartbeat()``."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from collections.abc import Mapping, Sequence
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from ._config import Config
|
|
10
|
+
from ._duration import Duration, seconds
|
|
11
|
+
from ._http import Transport
|
|
12
|
+
from ._keys import question_key
|
|
13
|
+
from .errors import Expired, ProtocolError, Suspended
|
|
14
|
+
|
|
15
|
+
_UNSET = object()
|
|
16
|
+
|
|
17
|
+
#: Question kinds the protocol defines. See docs/PROTOCOL.md.
|
|
18
|
+
KINDS = ("choice", "multi", "text", "number", "approve", "rank", "label")
|
|
19
|
+
|
|
20
|
+
#: What to do when ``wait`` elapses with the question still open. See DESIGN.md D3.
|
|
21
|
+
ON_TIMEOUT = ("suspend", "block", "default")
|
|
22
|
+
|
|
23
|
+
DEFAULT_WAIT = 30
|
|
24
|
+
DEFAULT_PRIORITY = 5
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Client:
|
|
28
|
+
"""A connection to one project on one daemon.
|
|
29
|
+
|
|
30
|
+
Usually you want the module-level :func:`ask` and :func:`heartbeat`, which
|
|
31
|
+
share a process-wide client configured from the environment. Construct this
|
|
32
|
+
directly to talk to more than one project or daemon from one process.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
url: str | None = None,
|
|
38
|
+
token: str | None = None,
|
|
39
|
+
project: str | None = None,
|
|
40
|
+
identity: str | None = None,
|
|
41
|
+
) -> None:
|
|
42
|
+
self._config = Config(url=url, token=token, project=project, identity=identity)
|
|
43
|
+
self._transport = Transport(self._config)
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def project(self) -> str:
|
|
47
|
+
return self._config.project
|
|
48
|
+
|
|
49
|
+
def ask(
|
|
50
|
+
self,
|
|
51
|
+
prompt: str,
|
|
52
|
+
*,
|
|
53
|
+
options: Sequence[Any] | None = None,
|
|
54
|
+
kind: str | None = None,
|
|
55
|
+
context: Mapping[str, Any] | None = None,
|
|
56
|
+
context_ref: str | None = None,
|
|
57
|
+
id: str | None = None,
|
|
58
|
+
ttl: Duration = None,
|
|
59
|
+
default: Any = _UNSET,
|
|
60
|
+
on_timeout: str = "suspend",
|
|
61
|
+
suggest: Mapping[str, Any] | None = None,
|
|
62
|
+
wait: Duration = DEFAULT_WAIT,
|
|
63
|
+
priority: int = DEFAULT_PRIORITY,
|
|
64
|
+
batch_key: str | None = None,
|
|
65
|
+
origin: Mapping[str, Any] | None = None,
|
|
66
|
+
assign_to: str | None = None,
|
|
67
|
+
_stacklevel: int = 2,
|
|
68
|
+
) -> Any:
|
|
69
|
+
"""Ask a human, and return their answer.
|
|
70
|
+
|
|
71
|
+
The question is content-addressed (DESIGN.md D2), so calling this again
|
|
72
|
+
with the same ``id`` and ``context`` returns the stored answer instead of
|
|
73
|
+
asking twice — which is what makes a crashed or restarted program resume
|
|
74
|
+
where it left off.
|
|
75
|
+
|
|
76
|
+
Raises :class:`~interject.errors.Suspended` when ``wait`` elapses with
|
|
77
|
+
the question still open and ``on_timeout`` is ``"suspend"`` (the
|
|
78
|
+
default). Let it propagate and exit; the next run will pick up the
|
|
79
|
+
answer.
|
|
80
|
+
"""
|
|
81
|
+
if on_timeout not in ON_TIMEOUT:
|
|
82
|
+
raise ValueError(f"on_timeout must be one of {ON_TIMEOUT}, got {on_timeout!r}")
|
|
83
|
+
if kind is None:
|
|
84
|
+
kind = _infer_kind(options, default)
|
|
85
|
+
if kind not in KINDS:
|
|
86
|
+
raise ValueError(f"kind must be one of {KINDS}, got {kind!r}")
|
|
87
|
+
if on_timeout == "default" and default is _UNSET:
|
|
88
|
+
raise ValueError('on_timeout="default" requires a default= value')
|
|
89
|
+
if kind in ("choice", "multi", "rank") and not options:
|
|
90
|
+
raise ValueError(f"kind={kind!r} requires options=")
|
|
91
|
+
|
|
92
|
+
question_id = id or _derive_id(_stacklevel)
|
|
93
|
+
key = question_key(self._config.project, question_id, context)
|
|
94
|
+
wait_seconds = seconds(wait) or 0
|
|
95
|
+
|
|
96
|
+
body: dict[str, Any] = {
|
|
97
|
+
"key": key,
|
|
98
|
+
"id": question_id,
|
|
99
|
+
"prompt": prompt,
|
|
100
|
+
"kind": kind,
|
|
101
|
+
"options": list(options) if options is not None else None,
|
|
102
|
+
"context": dict(context) if context is not None else None,
|
|
103
|
+
"context_ref": context_ref,
|
|
104
|
+
"suggest": dict(suggest) if suggest is not None else None,
|
|
105
|
+
"ttl_seconds": seconds(ttl),
|
|
106
|
+
"on_timeout": on_timeout,
|
|
107
|
+
"priority": priority,
|
|
108
|
+
"batch_key": batch_key or question_id,
|
|
109
|
+
"origin": dict(origin) if origin is not None else _derive_origin(_stacklevel),
|
|
110
|
+
"assign_to": assign_to,
|
|
111
|
+
}
|
|
112
|
+
if default is not _UNSET:
|
|
113
|
+
body["default"] = default
|
|
114
|
+
|
|
115
|
+
status, payload = self._transport.request(
|
|
116
|
+
"POST", "/v0/questions", body, timeout=_timeout_for(0)
|
|
117
|
+
)
|
|
118
|
+
if status >= 400:
|
|
119
|
+
raise ProtocolError(_error_message(payload, status, "registering question"))
|
|
120
|
+
|
|
121
|
+
resolved = self._resolve(payload, key, question_id, default)
|
|
122
|
+
if resolved is not _UNSET:
|
|
123
|
+
return resolved
|
|
124
|
+
|
|
125
|
+
# Not answered yet. Long-poll, then apply the timeout policy.
|
|
126
|
+
while True:
|
|
127
|
+
status, payload = self._transport.request(
|
|
128
|
+
"GET",
|
|
129
|
+
f"/v0/questions/{key}?wait={wait_seconds}",
|
|
130
|
+
timeout=_timeout_for(wait_seconds),
|
|
131
|
+
)
|
|
132
|
+
if status >= 400:
|
|
133
|
+
raise ProtocolError(_error_message(payload, status, "polling question"))
|
|
134
|
+
|
|
135
|
+
resolved = self._resolve(payload, key, question_id, default)
|
|
136
|
+
if resolved is not _UNSET:
|
|
137
|
+
return resolved
|
|
138
|
+
|
|
139
|
+
if on_timeout == "block":
|
|
140
|
+
continue
|
|
141
|
+
if on_timeout == "default":
|
|
142
|
+
# Record the default so a later replay returns the same value.
|
|
143
|
+
self._transport.request(
|
|
144
|
+
"POST",
|
|
145
|
+
"/v0/answers",
|
|
146
|
+
{"key": key, "value": default, "source": "default"},
|
|
147
|
+
timeout=_timeout_for(0),
|
|
148
|
+
)
|
|
149
|
+
return default
|
|
150
|
+
raise Suspended(key, question_id)
|
|
151
|
+
|
|
152
|
+
def key_for(self, id: str, context: Mapping[str, Any] | None = None) -> str:
|
|
153
|
+
"""The question key this client would use for ``id`` and ``context``."""
|
|
154
|
+
return question_key(self._config.project, id, context)
|
|
155
|
+
|
|
156
|
+
def peek(self, key: str) -> dict[str, Any] | None:
|
|
157
|
+
"""Look at a question without creating one.
|
|
158
|
+
|
|
159
|
+
Returns the snapshot, or ``None`` if no question with that key exists.
|
|
160
|
+
:meth:`ask` deliberately registers as it checks, which makes it the wrong
|
|
161
|
+
tool for "has this been answered yet?" over a large backlog — this is that
|
|
162
|
+
tool.
|
|
163
|
+
"""
|
|
164
|
+
status, payload = self._transport.request(
|
|
165
|
+
"GET", f"/v0/questions/{key}?wait=0", timeout=_timeout_for(0)
|
|
166
|
+
)
|
|
167
|
+
if status == 404:
|
|
168
|
+
return None
|
|
169
|
+
if status >= 400:
|
|
170
|
+
raise ProtocolError(_error_message(payload, status, "peeking at a question"))
|
|
171
|
+
return dict(payload)
|
|
172
|
+
|
|
173
|
+
def peek_answer(self, key: str, default: Any = _UNSET) -> Any:
|
|
174
|
+
"""The answer for ``key``, or ``default`` if it is unknown or unanswered."""
|
|
175
|
+
snapshot = self.peek(key)
|
|
176
|
+
if snapshot is None or snapshot.get("state") != "answered":
|
|
177
|
+
if default is _UNSET:
|
|
178
|
+
return None
|
|
179
|
+
return default
|
|
180
|
+
answer = snapshot.get("answer") or {}
|
|
181
|
+
return answer.get("value")
|
|
182
|
+
|
|
183
|
+
def answer(
|
|
184
|
+
self,
|
|
185
|
+
key: str,
|
|
186
|
+
value: Any,
|
|
187
|
+
answered_by: str | None = None,
|
|
188
|
+
source: str | None = None,
|
|
189
|
+
) -> dict[str, Any]:
|
|
190
|
+
"""Answer a question on a human's behalf.
|
|
191
|
+
|
|
192
|
+
The answering side of the protocol, for building a surface in Python.
|
|
193
|
+
Pipelines call :meth:`ask`; inboxes call this.
|
|
194
|
+
"""
|
|
195
|
+
body: dict[str, Any] = {"key": key, "value": value}
|
|
196
|
+
if answered_by is not None:
|
|
197
|
+
body["answered_by"] = answered_by
|
|
198
|
+
if source is not None:
|
|
199
|
+
body["source"] = source
|
|
200
|
+
status, payload = self._transport.request(
|
|
201
|
+
"POST", "/v0/answers", body, timeout=_timeout_for(0)
|
|
202
|
+
)
|
|
203
|
+
if status >= 400:
|
|
204
|
+
raise ProtocolError(_error_message(payload, status, "answering a question"))
|
|
205
|
+
return dict(payload)
|
|
206
|
+
|
|
207
|
+
def inbox(
|
|
208
|
+
self,
|
|
209
|
+
limit: int = 50,
|
|
210
|
+
batch_key: str | None = None,
|
|
211
|
+
for_identity: str | None = None,
|
|
212
|
+
all_of_them: bool = False,
|
|
213
|
+
) -> dict[str, Any]:
|
|
214
|
+
"""Open questions, grouped by batch.
|
|
215
|
+
|
|
216
|
+
By default this is *your* inbox: questions assigned to someone else, and
|
|
217
|
+
questions another person currently holds a claim on, are left out.
|
|
218
|
+
``all_of_them`` lifts both filters.
|
|
219
|
+
"""
|
|
220
|
+
path = f"/v0/inbox?limit={limit}"
|
|
221
|
+
if batch_key is not None:
|
|
222
|
+
path += f"&batch_key={batch_key}"
|
|
223
|
+
if for_identity is not None:
|
|
224
|
+
path += f"&for={for_identity}"
|
|
225
|
+
if all_of_them:
|
|
226
|
+
path += "&all=true"
|
|
227
|
+
status, payload = self._transport.request("GET", path, timeout=_timeout_for(0))
|
|
228
|
+
if status >= 400:
|
|
229
|
+
raise ProtocolError(_error_message(payload, status, "reading the inbox"))
|
|
230
|
+
return dict(payload)
|
|
231
|
+
|
|
232
|
+
def claim(self, key: str, ttl_seconds: int | None = None) -> dict[str, Any]:
|
|
233
|
+
"""Take an advisory hold on a question while you work on it.
|
|
234
|
+
|
|
235
|
+
Advisory: it stops two people duplicating effort, but answering is still
|
|
236
|
+
governed by answers being write-once. Claims expire, so wandering off
|
|
237
|
+
mid-question does not hide it from everyone else for long.
|
|
238
|
+
"""
|
|
239
|
+
status, payload = self._transport.request(
|
|
240
|
+
"POST",
|
|
241
|
+
f"/v0/questions/{key}/claim",
|
|
242
|
+
{"ttl_seconds": ttl_seconds},
|
|
243
|
+
timeout=_timeout_for(0),
|
|
244
|
+
)
|
|
245
|
+
if status >= 400:
|
|
246
|
+
raise ProtocolError(_error_message(payload, status, "claiming a question"))
|
|
247
|
+
return dict(payload)
|
|
248
|
+
|
|
249
|
+
def release(self, key: str) -> bool:
|
|
250
|
+
"""Give up a claim, so the question reappears for everyone at once."""
|
|
251
|
+
status, payload = self._transport.request(
|
|
252
|
+
"POST", f"/v0/questions/{key}/release", {}, timeout=_timeout_for(0)
|
|
253
|
+
)
|
|
254
|
+
if status >= 400:
|
|
255
|
+
raise ProtocolError(_error_message(payload, status, "releasing a claim"))
|
|
256
|
+
return bool(payload.get("released"))
|
|
257
|
+
|
|
258
|
+
def assign(self, key: str, to: str | None) -> None:
|
|
259
|
+
"""Route a question to one person, or back to the pool with ``None``."""
|
|
260
|
+
status, payload = self._transport.request(
|
|
261
|
+
"POST", f"/v0/questions/{key}/assign", {"to": to}, timeout=_timeout_for(0)
|
|
262
|
+
)
|
|
263
|
+
if status >= 400:
|
|
264
|
+
raise ProtocolError(_error_message(payload, status, "assigning a question"))
|
|
265
|
+
|
|
266
|
+
def heartbeat(self, name: str, *, expect_every: Duration = None, expect_by: str | None = None) -> None:
|
|
267
|
+
"""Declare that a named signal is alive, and when it is next due.
|
|
268
|
+
|
|
269
|
+
Silence past the deadline is itself an event — the outbound half of the
|
|
270
|
+
same idea as :meth:`ask`. Exactly one of ``expect_every`` or
|
|
271
|
+
``expect_by`` should be given.
|
|
272
|
+
"""
|
|
273
|
+
if (expect_every is None) == (expect_by is None):
|
|
274
|
+
raise ValueError("pass exactly one of expect_every= or expect_by=")
|
|
275
|
+
body: dict[str, Any] = {"name": name}
|
|
276
|
+
if expect_every is not None:
|
|
277
|
+
body["expect_every_seconds"] = seconds(expect_every)
|
|
278
|
+
else:
|
|
279
|
+
body["expect_by"] = expect_by
|
|
280
|
+
status, payload = self._transport.request(
|
|
281
|
+
"POST", "/v0/signals/heartbeat", body, timeout=_timeout_for(0)
|
|
282
|
+
)
|
|
283
|
+
if status >= 400:
|
|
284
|
+
raise ProtocolError(_error_message(payload, status, "sending heartbeat"))
|
|
285
|
+
|
|
286
|
+
def _resolve(
|
|
287
|
+
self, payload: Mapping[str, Any], key: str, question_id: str, default: Any
|
|
288
|
+
) -> Any:
|
|
289
|
+
"""Turn a protocol response into an answer, or ``_UNSET`` if still open."""
|
|
290
|
+
state = payload.get("state")
|
|
291
|
+
if state == "answered":
|
|
292
|
+
answer = payload.get("answer")
|
|
293
|
+
if not isinstance(answer, dict) or "value" not in answer:
|
|
294
|
+
raise ProtocolError("daemon reported 'answered' without an answer value")
|
|
295
|
+
return answer["value"]
|
|
296
|
+
if state == "expired":
|
|
297
|
+
if default is not _UNSET:
|
|
298
|
+
return default
|
|
299
|
+
raise Expired(key, question_id)
|
|
300
|
+
if state != "open":
|
|
301
|
+
raise ProtocolError(f"daemon reported unknown state {state!r}")
|
|
302
|
+
return _UNSET
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _timeout_for(wait_seconds: int) -> float:
|
|
306
|
+
"""Read timeout: always longer than the long-poll the daemon will hold."""
|
|
307
|
+
return float(wait_seconds) + 15.0
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _infer_kind(options: Sequence[Any] | None, default: Any) -> str:
|
|
311
|
+
if options:
|
|
312
|
+
return "choice"
|
|
313
|
+
if isinstance(default, bool):
|
|
314
|
+
return "approve"
|
|
315
|
+
return "text"
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _derive_id(stacklevel: int) -> str:
|
|
319
|
+
"""Fall back to ``file:function:line`` when no explicit ``id=`` was given.
|
|
320
|
+
|
|
321
|
+
This is deliberately fragile in a documented way: editing the file moves the
|
|
322
|
+
line number, which changes the question key and re-asks the question. Pass
|
|
323
|
+
an explicit ``id=`` for anything long-lived (DESIGN.md D2).
|
|
324
|
+
"""
|
|
325
|
+
try:
|
|
326
|
+
frame = sys._getframe(stacklevel)
|
|
327
|
+
except ValueError: # pragma: no cover - shallower stack than expected
|
|
328
|
+
return "anonymous"
|
|
329
|
+
return f"{os.path.basename(frame.f_code.co_filename)}:{frame.f_code.co_name}:{frame.f_lineno}"
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _derive_origin(stacklevel: int) -> dict[str, Any]:
|
|
333
|
+
try:
|
|
334
|
+
frame = sys._getframe(stacklevel)
|
|
335
|
+
site = f"{frame.f_code.co_filename}:{frame.f_lineno}"
|
|
336
|
+
except ValueError: # pragma: no cover
|
|
337
|
+
site = None
|
|
338
|
+
origin: dict[str, Any] = {"site": site}
|
|
339
|
+
for field, variable in (("repo", "INTERJECT_REPO"), ("job", "INTERJECT_JOB"), ("run", "INTERJECT_RUN")):
|
|
340
|
+
value = os.environ.get(variable)
|
|
341
|
+
if value:
|
|
342
|
+
origin[field] = value
|
|
343
|
+
return origin
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _error_message(payload: Mapping[str, Any], status: int, doing: str) -> str:
|
|
347
|
+
error = payload.get("error")
|
|
348
|
+
if isinstance(error, dict) and error.get("message"):
|
|
349
|
+
return "{} failed ({}): {}".format(doing, status, error["message"])
|
|
350
|
+
return f"{doing} failed with status {status}"
|
interject/_config.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Client configuration, read from the environment."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
DEFAULT_URL = "http://127.0.0.1:8787"
|
|
7
|
+
DEFAULT_PROJECT = "default"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Config:
|
|
11
|
+
"""Where the daemon is and who we are to it."""
|
|
12
|
+
|
|
13
|
+
__slots__ = ("identity", "project", "token", "url")
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
url: str | None = None,
|
|
18
|
+
token: str | None = None,
|
|
19
|
+
project: str | None = None,
|
|
20
|
+
identity: str | None = None,
|
|
21
|
+
) -> None:
|
|
22
|
+
self.url = (url or os.environ.get("INTERJECT_URL") or DEFAULT_URL).rstrip("/")
|
|
23
|
+
self.token = token if token is not None else os.environ.get("INTERJECT_TOKEN")
|
|
24
|
+
self.project = project or os.environ.get("INTERJECT_PROJECT") or DEFAULT_PROJECT
|
|
25
|
+
#: Who this client acts as, for routing. A token's own label wins
|
|
26
|
+
#: server-side, so this only matters on daemons without tokens.
|
|
27
|
+
self.identity = identity or os.environ.get("INTERJECT_IDENTITY")
|
|
28
|
+
|
|
29
|
+
def __repr__(self) -> str: # pragma: no cover - debugging aid
|
|
30
|
+
return "Config(url={!r}, project={!r}, token={})".format(
|
|
31
|
+
self.url, self.project, "set" if self.token else "unset"
|
|
32
|
+
)
|
interject/_duration.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Human-friendly durations: ``"48h"``, ``"15m"``, ``90``, ``2.5``."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from typing import Union
|
|
6
|
+
|
|
7
|
+
Duration = Union[str, int, float, None]
|
|
8
|
+
|
|
9
|
+
_UNITS = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
|
|
10
|
+
_PATTERN = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([smhdw])?\s*$", re.IGNORECASE)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def seconds(value: Duration) -> int | None:
|
|
14
|
+
"""Return whole seconds, or ``None`` when ``value`` is ``None``."""
|
|
15
|
+
if value is None:
|
|
16
|
+
return None
|
|
17
|
+
if isinstance(value, bool): # bool is an int subclass; reject it explicitly
|
|
18
|
+
raise TypeError("duration must be a number or a string like '15m', not a bool")
|
|
19
|
+
if isinstance(value, (int, float)):
|
|
20
|
+
if value < 0:
|
|
21
|
+
raise ValueError("duration must not be negative")
|
|
22
|
+
return int(value)
|
|
23
|
+
match = _PATTERN.match(value)
|
|
24
|
+
if not match:
|
|
25
|
+
raise ValueError(
|
|
26
|
+
f"could not parse duration {value!r}; use seconds or a suffix of s/m/h/d/w"
|
|
27
|
+
)
|
|
28
|
+
magnitude, unit = match.groups()
|
|
29
|
+
return int(float(magnitude) * _UNITS[(unit or "s").lower()])
|
interject/_http.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Minimal JSON-over-HTTP transport. Standard library only, on purpose.
|
|
2
|
+
|
|
3
|
+
The client has no third-party dependencies so that adding ``interject`` to an
|
|
4
|
+
existing pipeline can never create a version conflict. See DESIGN.md D1.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import time
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.request
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from ._config import Config
|
|
15
|
+
from .errors import ProtocolError, Unauthorized, Unreachable
|
|
16
|
+
|
|
17
|
+
_RETRY_BACKOFF = (0.2, 0.6, 1.8)
|
|
18
|
+
_USER_AGENT = "interject-python/0.0.1"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Transport:
|
|
22
|
+
"""Speaks ``docs/PROTOCOL.md`` over HTTP/1.1."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, config: Config) -> None:
|
|
25
|
+
self._config = config
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def config(self) -> Config:
|
|
29
|
+
return self._config
|
|
30
|
+
|
|
31
|
+
def _headers(self) -> dict[str, str]:
|
|
32
|
+
headers = {
|
|
33
|
+
"Content-Type": "application/json",
|
|
34
|
+
"Accept": "application/json",
|
|
35
|
+
"User-Agent": _USER_AGENT,
|
|
36
|
+
"X-Interject-Project": self._config.project,
|
|
37
|
+
}
|
|
38
|
+
if self._config.token:
|
|
39
|
+
headers["Authorization"] = f"Bearer {self._config.token}"
|
|
40
|
+
if self._config.identity:
|
|
41
|
+
headers["X-Interject-Identity"] = self._config.identity
|
|
42
|
+
return headers
|
|
43
|
+
|
|
44
|
+
def request(
|
|
45
|
+
self,
|
|
46
|
+
method: str,
|
|
47
|
+
path: str,
|
|
48
|
+
body: dict[str, Any] | None = None,
|
|
49
|
+
timeout: float = 35.0,
|
|
50
|
+
) -> tuple[int, dict[str, Any]]:
|
|
51
|
+
"""Perform one request, retrying transport errors and 5xx responses.
|
|
52
|
+
|
|
53
|
+
4xx responses are returned to the caller rather than raised, because
|
|
54
|
+
several of them (``404`` on an unknown key, ``409`` on an already
|
|
55
|
+
answered question) are ordinary control flow for this protocol.
|
|
56
|
+
"""
|
|
57
|
+
url = f"{self._config.url}{path}"
|
|
58
|
+
payload = None if body is None else json.dumps(body).encode("utf-8")
|
|
59
|
+
last_error: BaseException | None = None
|
|
60
|
+
|
|
61
|
+
for attempt in range(len(_RETRY_BACKOFF) + 1):
|
|
62
|
+
request = urllib.request.Request(url, data=payload, method=method)
|
|
63
|
+
for name, value in self._headers().items():
|
|
64
|
+
request.add_header(name, value)
|
|
65
|
+
try:
|
|
66
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
67
|
+
return response.status, _decode(response.read())
|
|
68
|
+
except urllib.error.HTTPError as error:
|
|
69
|
+
raw = error.read()
|
|
70
|
+
if error.code == 401 or error.code == 403:
|
|
71
|
+
raise Unauthorized(_message(raw, "daemon rejected the project token"))
|
|
72
|
+
if error.code < 500:
|
|
73
|
+
return error.code, _decode(raw, allow_empty=True)
|
|
74
|
+
last_error = error
|
|
75
|
+
except (urllib.error.URLError, OSError) as error:
|
|
76
|
+
last_error = error
|
|
77
|
+
|
|
78
|
+
if attempt < len(_RETRY_BACKOFF):
|
|
79
|
+
time.sleep(_RETRY_BACKOFF[attempt])
|
|
80
|
+
|
|
81
|
+
raise Unreachable(
|
|
82
|
+
f"could not reach interjectd at {self._config.url} ({last_error})"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _decode(raw: bytes, allow_empty: bool = False) -> dict[str, Any]:
|
|
87
|
+
if not raw and allow_empty:
|
|
88
|
+
return {}
|
|
89
|
+
try:
|
|
90
|
+
decoded = json.loads(raw.decode("utf-8"))
|
|
91
|
+
except (ValueError, UnicodeDecodeError) as error:
|
|
92
|
+
raise ProtocolError(f"daemon returned a body that is not JSON: {error}")
|
|
93
|
+
if not isinstance(decoded, dict):
|
|
94
|
+
raise ProtocolError(f"daemon returned {type(decoded).__name__}, expected a JSON object")
|
|
95
|
+
return decoded
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _message(raw: bytes, fallback: str) -> str:
|
|
99
|
+
try:
|
|
100
|
+
payload = json.loads(raw.decode("utf-8"))
|
|
101
|
+
return str(payload["error"]["message"])
|
|
102
|
+
except Exception: # noqa: BLE001 - never let error-body parsing mask the real error
|
|
103
|
+
return fallback
|
interject/_keys.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Question identity.
|
|
2
|
+
|
|
3
|
+
Every client MUST compute keys exactly as specified in ``docs/PROTOCOL.md``,
|
|
4
|
+
because the key is the mechanism behind crash-replay, deduplication and
|
|
5
|
+
coalescing alike. See DESIGN.md D2.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
_NUL = "\x00"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def canon(context: Mapping[str, Any] | None) -> bytes:
|
|
18
|
+
"""Canonical JSON encoding of a question's context.
|
|
19
|
+
|
|
20
|
+
Sorted keys, no insignificant whitespace, non-ASCII preserved, UTF-8. A
|
|
21
|
+
missing context is treated as ``{}`` so that omitting it and passing an
|
|
22
|
+
empty mapping produce the same key.
|
|
23
|
+
"""
|
|
24
|
+
return json.dumps(
|
|
25
|
+
{} if context is None else dict(context),
|
|
26
|
+
sort_keys=True,
|
|
27
|
+
separators=(",", ":"),
|
|
28
|
+
ensure_ascii=False,
|
|
29
|
+
).encode("utf-8")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def context_digest(context: Mapping[str, Any] | None) -> str:
|
|
33
|
+
return hashlib.sha256(canon(context)).hexdigest()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def question_key(project: str, question_id: str, context: Mapping[str, Any] | None) -> str:
|
|
37
|
+
"""``sha256(project \\x00 question_id \\x00 context_digest)``, lowercase hex."""
|
|
38
|
+
material = _NUL.join((project, question_id, context_digest(context)))
|
|
39
|
+
return hashlib.sha256(material.encode("utf-8")).hexdigest()
|
interject/errors.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Exceptions raised by the interject client."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class InterjectError(Exception):
|
|
5
|
+
"""Base class for every error this library raises."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Suspended(InterjectError):
|
|
9
|
+
"""A question is still open and ``on_timeout="suspend"`` was in effect.
|
|
10
|
+
|
|
11
|
+
The caller is expected to let this propagate and exit cleanly. When the
|
|
12
|
+
program runs again it recomputes the same question key and, if the question
|
|
13
|
+
has been answered by then, :func:`interject.ask` returns immediately
|
|
14
|
+
instead of raising.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, key: str, question_id: str) -> None:
|
|
18
|
+
super().__init__(
|
|
19
|
+
f"question {question_id!r} is still open (key {key[:12]}); exit and retry later"
|
|
20
|
+
)
|
|
21
|
+
self.key = key
|
|
22
|
+
self.question_id = question_id
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Expired(InterjectError):
|
|
26
|
+
"""The question's TTL elapsed and no default was declared."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, key: str, question_id: str) -> None:
|
|
29
|
+
super().__init__(
|
|
30
|
+
f"question {question_id!r} expired with no default (key {key[:12]})"
|
|
31
|
+
)
|
|
32
|
+
self.key = key
|
|
33
|
+
self.question_id = question_id
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Unauthorized(InterjectError):
|
|
37
|
+
"""The daemon rejected the project token."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ProtocolError(InterjectError):
|
|
41
|
+
"""The daemon returned a response this client could not understand."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Unreachable(InterjectError):
|
|
45
|
+
"""The daemon could not be reached."""
|
interject/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: interject
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A durable ask() primitive: stop, ask a human, resume.
|
|
5
|
+
Project-URL: Homepage, https://github.com/TheJohnMatti/interject
|
|
6
|
+
Project-URL: Repository, https://github.com/TheJohnMatti/interject
|
|
7
|
+
Project-URL: Issues, https://github.com/TheJohnMatti/interject/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/TheJohnMatti/interject/releases
|
|
9
|
+
Author: John Matti
|
|
10
|
+
License: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: approval,durable,human-in-the-loop,pipeline,workflow
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
23
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
24
|
+
Classifier: Typing :: Typed
|
|
25
|
+
Requires-Python: >=3.9
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: mypy; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest-cov; extra == 'dev'
|
|
29
|
+
Requires-Dist: pytest-xdist; extra == 'dev'
|
|
30
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
31
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# interject
|
|
35
|
+
|
|
36
|
+
**A durable `ask()` primitive.** A program can stop, ask a human, and resume —
|
|
37
|
+
days later, on another machine, in one tap.
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from interject import ask
|
|
41
|
+
|
|
42
|
+
vehicle = ask(
|
|
43
|
+
"Is this a car?",
|
|
44
|
+
options=["car", "motorcycle", "boat", "trailer"],
|
|
45
|
+
id="vehicle_type",
|
|
46
|
+
context={"title": listing.title, "price": listing.price},
|
|
47
|
+
suggest={"value": "motorcycle", "confidence": 0.94},
|
|
48
|
+
)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
That call registers a question, lets everything not downstream of it keep
|
|
52
|
+
running, reaches you wherever you are, and returns the answer **to this line of
|
|
53
|
+
this program** — even if the process exited and was restarted two days later on
|
|
54
|
+
different hardware. It may also never reach you at all, if the triage layer is
|
|
55
|
+
confident enough. That is the point.
|
|
56
|
+
|
|
57
|
+
## Why
|
|
58
|
+
|
|
59
|
+
Modern pipelines are mostly autonomous with a handful of points where human
|
|
60
|
+
judgment is irreducible. Today each of those is a bespoke JSON file nobody is
|
|
61
|
+
watching, a blocking `input()` at a terminal nobody is sitting at, or a hard
|
|
62
|
+
stop.
|
|
63
|
+
|
|
64
|
+
## How it behaves
|
|
65
|
+
|
|
66
|
+
**It does not block.** By default `ask` long-polls briefly and then raises
|
|
67
|
+
`Suspended`, so the caller exits cleanly. The next run recomputes the same
|
|
68
|
+
content-addressed key and gets the stored answer immediately:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
import interject
|
|
72
|
+
|
|
73
|
+
try:
|
|
74
|
+
kind = interject.ask("Is this a car?", options=["car", "moto"],
|
|
75
|
+
id="vehicle_type", context=listing, wait=0)
|
|
76
|
+
except interject.Suspended:
|
|
77
|
+
return # somebody will answer; the next run picks it up
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Pass `on_timeout="block"` for an interactive script, or `on_timeout="default"`
|
|
81
|
+
with a `default=` for best-effort enrichment.
|
|
82
|
+
|
|
83
|
+
**Scanning a backlog does not create a backlog of questions.** `ask` registers as
|
|
84
|
+
it checks, so use `peek` to look without creating:
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
key = interject.key_for("vehicle_type", listing)
|
|
88
|
+
if interject.peek_answer(key) is None:
|
|
89
|
+
... # not answered yet
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
**Silence is the other half.** A job can declare what it owes you, and going
|
|
93
|
+
quiet becomes an event:
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
interject.heartbeat("nightly.etl", expect_every="26h")
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Installation
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
pip install interject
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
No dependencies, Python 3.9+. It talks to an `interjectd` daemon over HTTP —
|
|
106
|
+
see the [repository](https://github.com/TheJohnMatti/interject) for running one,
|
|
107
|
+
for the one-tap phone inbox, and for the triage layer that makes it ask less
|
|
108
|
+
over time.
|
|
109
|
+
|
|
110
|
+
## Configuration
|
|
111
|
+
|
|
112
|
+
| variable | default | meaning |
|
|
113
|
+
|---|---|---|
|
|
114
|
+
| `INTERJECT_URL` | `http://127.0.0.1:8787` | daemon base URL |
|
|
115
|
+
| `INTERJECT_TOKEN` | *(none)* | project or device token |
|
|
116
|
+
| `INTERJECT_PROJECT` | `default` | project name, for daemons without tokens |
|
|
117
|
+
| `INTERJECT_IDENTITY` | *(none)* | who you answer as, for routing |
|
|
118
|
+
|
|
119
|
+
Licensed under Apache-2.0.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
interject/__init__.py,sha256=Rk30rqi-G8OHQoPRyC6HIwiHtikov0PZRNSS0ua5vAE,3140
|
|
2
|
+
interject/_client.py,sha256=L0QxBsCZvF9GL9Li9rgcXSHsUu1xJO-LBEIW-whiOyQ,13815
|
|
3
|
+
interject/_config.py,sha256=Wrkg10iXDjNg4C4Tg0F_D6CFJnOB1u79JKsUuK25PJ8,1175
|
|
4
|
+
interject/_duration.py,sha256=W0v3ApYqUCf0CFZ-igbMLL_ArIRAkNEKIdMZwzij9eg,1082
|
|
5
|
+
interject/_http.py,sha256=03ob-bpNqrA98adZ4dNTlf6tD68-Nv6sLkvCg8OO8nM,3731
|
|
6
|
+
interject/_keys.py,sha256=fCEOcv_BSue6pPge9jbi8LeI0LYw3gTLxn7FWcIYPhE,1276
|
|
7
|
+
interject/errors.py,sha256=cRoYlmlnuG97p_laf5Xt_0LHQyBmqEldueDYxqUbFV4,1387
|
|
8
|
+
interject/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
interject-0.1.0.dist-info/METADATA,sha256=7sqdBF5x5CDUUetR81iwLRaEVWHq2UF9AqOXge6n70U,4136
|
|
10
|
+
interject-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
11
|
+
interject-0.1.0.dist-info/licenses/LICENSE,sha256=yVuuHRzgI17MzTVgt3LsHvuX80innw--CmNPDCzO_iw,11358
|
|
12
|
+
interject-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|