wrapkit 0.4.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.
wrapkit/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ """
2
+ Shared infrastructure for the data-API wrappers.
3
+
4
+ The modules, each importable on its own:
5
+
6
+ * :mod:`wrapkit.log`: package logger, CLI log handlers, secret redaction.
7
+ * :mod:`wrapkit.cache`: the ``DEFAULT_CACHE_DIR`` sentinel and an on-disk JSON
8
+ cache whose file names never contain a secret.
9
+ * :mod:`wrapkit.http`: retries with backoff and ``Retry-After``, a request-rate
10
+ throttle (sync and async), the User-Agent pattern.
11
+ * :mod:`wrapkit.frames`: the tidy output shape, polars conversion, period
12
+ start/end parsing.
13
+ * :mod:`wrapkit.incremental`: new/revised-row selection and upserts for
14
+ ``new_observations`` and ``update_csv``.
15
+ * :mod:`wrapkit.io`: write a frame to CSV, Excel, Parquet or JSON by extension.
16
+ * :mod:`wrapkit.cli`: python-fire helpers and the error-handling runner.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ __version__ = "0.4.0"
22
+
23
+ __all__ = ["__version__"]
wrapkit/cache.py ADDED
@@ -0,0 +1,271 @@
1
+ """
2
+ On-disk JSON response cache with a freshness window.
3
+
4
+ Every wrapper's ``cache_dir`` argument defaults to :data:`DEFAULT_CACHE_DIR`,
5
+ which :func:`resolve_cache_dir` turns into ``~/.cache/<package>`` when the
6
+ client is built (never at import, so a changed home directory is honoured).
7
+ ``None`` or ``""`` means no on-disk cache.
8
+
9
+ A :class:`DiskCache` stores one JSON file per request. The file name is a
10
+ SHA-256 digest of the endpoint and the sorted request parameters with the secret
11
+ ones left out, so a key never reaches a file name and two callers with
12
+ different keys share one cached answer.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import enum
18
+ import hashlib
19
+ import json
20
+ import os
21
+ import stat
22
+ import tempfile
23
+ import time
24
+ from pathlib import Path
25
+ from typing import TYPE_CHECKING, Any
26
+
27
+ if TYPE_CHECKING:
28
+ import logging
29
+ from collections.abc import Iterable, Sequence
30
+
31
+ __all__ = [
32
+ "DEFAULT_CACHE_DIR",
33
+ "CacheDir",
34
+ "DefaultCacheDir",
35
+ "DiskCache",
36
+ "cache_path",
37
+ "resolve_cache_dir",
38
+ ]
39
+
40
+
41
+ class DefaultCacheDir(enum.Enum):
42
+ """
43
+ Type of :data:`DEFAULT_CACHE_DIR`, the "use the default cache" marker.
44
+
45
+ A one-member enum rather than a ready-made path, so that the directory is
46
+ resolved when a client is constructed, not when a module is imported. Being
47
+ an enum member, it is a distinct value type checkers can narrow on, and it
48
+ can never be confused with ``None``, which means "no on-disk cache".
49
+ """
50
+
51
+ DEFAULT_CACHE_DIR = "DEFAULT_CACHE_DIR"
52
+
53
+ def __repr__(self) -> str:
54
+ """
55
+ Return the public name, so signatures read ``cache_dir=DEFAULT_CACHE_DIR``.
56
+
57
+ Returns:
58
+ str: The literal ``"DEFAULT_CACHE_DIR"``.
59
+ """
60
+ return "DEFAULT_CACHE_DIR"
61
+
62
+
63
+ #: Default value of a ``cache_dir`` argument: cache in ``~/.cache/<package>``.
64
+ DEFAULT_CACHE_DIR = DefaultCacheDir.DEFAULT_CACHE_DIR
65
+
66
+ #: What a ``cache_dir`` argument accepts.
67
+ CacheDir = str | Path | DefaultCacheDir | None
68
+
69
+
70
+ def resolve_cache_dir(value: CacheDir, package: str) -> Path | None:
71
+ """
72
+ Turn a ``cache_dir`` argument into the cache directory to use, if any.
73
+
74
+ Nothing is created here; :class:`DiskCache` creates the directory.
75
+
76
+ Args:
77
+ value (CacheDir): The value passed to a client constructor.
78
+ package (str): Directory name under ``~/.cache`` for the default.
79
+
80
+ Returns:
81
+ Path | None: ``~/.cache/<package>`` under the *current* home directory
82
+ for :data:`DEFAULT_CACHE_DIR`, ``None`` for ``None`` or any other falsy
83
+ value (caching off), otherwise the given path.
84
+ """
85
+ if isinstance(value, DefaultCacheDir):
86
+ return Path.home() / ".cache" / package
87
+ return Path(value) if value else None
88
+
89
+
90
+ def cache_path(
91
+ cache_dir: Path | None,
92
+ endpoint: str,
93
+ params: Iterable[tuple[str, Any]] | None,
94
+ *,
95
+ hidden: Iterable[str] = (),
96
+ suffix: str = ".json",
97
+ ) -> Path | None:
98
+ """
99
+ Return the cache file for a request, or ``None`` when caching is off.
100
+
101
+ Args:
102
+ cache_dir (Path | None): Cache directory, or ``None`` if caching is off.
103
+ endpoint (str): The path or URL being requested.
104
+ params (Iterable[tuple[str, Any]] | None): Request parameters as
105
+ (name, value) pairs.
106
+ hidden (Iterable[str]): Names of secret parameters, left out of the
107
+ digest so a key never influences (or reaches) the file name.
108
+ suffix (str): File-name extension.
109
+
110
+ Returns:
111
+ Path | None: The cache file path, or ``None`` if caching is disabled.
112
+ """
113
+ if not cache_dir:
114
+ return None
115
+ skip = set(hidden)
116
+ signature = sorted((str(k), str(v)) for k, v in params or () if k not in skip)
117
+ blob = json.dumps([endpoint, signature], separators=(",", ":"))
118
+ digest = hashlib.sha256(blob.encode("utf-8")).hexdigest()
119
+ return cache_dir / f"{digest}{suffix}"
120
+
121
+
122
+ class DiskCache:
123
+ """
124
+ A directory of cached JSON answers, each fresh for ``ttl_seconds``.
125
+
126
+ Only successful answers should be stored: callers :meth:`put` after their
127
+ own error checks. Reads and writes use UTF-8.
128
+ """
129
+
130
+ def __init__(
131
+ self,
132
+ directory: Path | None,
133
+ ttl_seconds: float,
134
+ *,
135
+ hidden: Iterable[str] = (),
136
+ logger: logging.Logger | None = None,
137
+ ) -> None:
138
+ """
139
+ Set up the cache and create its directory.
140
+
141
+ Args:
142
+ directory (Path | None): Cache directory, or ``None`` for a cache
143
+ that never hits and never stores.
144
+ ttl_seconds (float): How long an entry stays fresh; ``0`` (or
145
+ less) means never.
146
+ hidden (Iterable[str]): Secret parameter names left out of the key.
147
+ logger (logging.Logger | None): Receives DEBUG lines for hits and
148
+ expired entries.
149
+ """
150
+ self.directory = directory
151
+ self.ttl_seconds = ttl_seconds
152
+ self.hidden = tuple(hidden)
153
+ self.logger = logger
154
+ if directory:
155
+ directory.mkdir(parents=True, exist_ok=True)
156
+
157
+ def path(
158
+ self, endpoint: str, params: Sequence[tuple[str, Any]] | None
159
+ ) -> Path | None:
160
+ """
161
+ Return the cache file for a request (see :func:`cache_path`).
162
+
163
+ Args:
164
+ endpoint (str): The path or URL being requested.
165
+ params (Sequence[tuple[str, Any]] | None): Request parameters.
166
+
167
+ Returns:
168
+ Path | None: The cache file, or ``None`` if caching is disabled.
169
+ """
170
+ return cache_path(self.directory, endpoint, params, hidden=self.hidden)
171
+
172
+ def get(
173
+ self, endpoint: str, params: Sequence[tuple[str, Any]] | None
174
+ ) -> tuple[bool, Any]:
175
+ """
176
+ Look up a fresh cached answer.
177
+
178
+ Args:
179
+ endpoint (str): The path or URL being requested.
180
+ params (Sequence[tuple[str, Any]] | None): Request parameters.
181
+
182
+ Returns:
183
+ tuple[bool, Any]: ``(True, payload)`` on a fresh hit, otherwise
184
+ ``(False, None)``. A JSON ``null`` payload is a valid hit; a file
185
+ that cannot be decoded (say, a truncated write) is a miss, and so
186
+ is an entry that is not a regular file (a symlink, FIFO or
187
+ directory), which is never followed or opened. An entry whose file
188
+ time is ahead of the clock is expired.
189
+ """
190
+ file = self.path(endpoint, params)
191
+ if file is None:
192
+ return False, None
193
+ try:
194
+ # lstat, not stat: a symlink at the entry name is not followed.
195
+ info = file.lstat()
196
+ except OSError:
197
+ return False, None
198
+ if not stat.S_ISREG(info.st_mode):
199
+ # put only ever leaves a regular file here. Anything else was put
200
+ # there by someone else; reading it could follow a link out of the
201
+ # directory or block for good on a FIFO.
202
+ self._debug("Cache entry unreadable, ignored: %s", endpoint)
203
+ return False, None
204
+ # Whole nanoseconds: in float seconds, a file written a moment ago can
205
+ # look a hair ahead of the clock.
206
+ age_ns = time.time_ns() - info.st_mtime_ns
207
+ age = age_ns / 1e9
208
+ # Fresh only while 0 <= age < TTL. A TTL of zero (or less) always
209
+ # refetches, and a file time ahead of the clock cannot be trusted: such
210
+ # an entry would otherwise stay fresh until the clock caught up.
211
+ if age_ns < 0 or not age < self.ttl_seconds:
212
+ self._debug("Cache expired: %s (age %.0fs)", endpoint, age)
213
+ return False, None
214
+ try:
215
+ payload = json.loads(file.read_text("utf-8"))
216
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
217
+ self._debug("Cache entry unreadable, ignored: %s", endpoint)
218
+ return False, None
219
+ self._debug("Cache hit: %s (age %.0fs)", endpoint, age)
220
+ return True, payload
221
+
222
+ def put(
223
+ self, endpoint: str, params: Sequence[tuple[str, Any]] | None, payload: object
224
+ ) -> None:
225
+ """
226
+ Store an answer (a no-op when caching is off).
227
+
228
+ The answer is written to a new temp file in the cache directory, which
229
+ then replaces the entry, so a reader never sees a half-written entry
230
+ and an interrupted write leaves none. The temp file is created
231
+ exclusively, under a random name and with mode ``0o600`` on POSIX
232
+ (which the entry keeps), so it is never a file or link someone else
233
+ put there, nor the temp file of another put of the same key.
234
+
235
+ Args:
236
+ endpoint (str): The path or URL that was requested.
237
+ params (Sequence[tuple[str, Any]] | None): Request parameters.
238
+ payload (object): A JSON-serialisable answer.
239
+ """
240
+ file = self.path(endpoint, params)
241
+ if file is None:
242
+ return
243
+ # Encode first: an answer JSON cannot encode raises before any file
244
+ # exists.
245
+ text = json.dumps(payload)
246
+ # mkstemp opens with O_CREAT | O_EXCL (plus O_NOFOLLOW where the OS has
247
+ # it) and mode 0o600, drawing a new random name if one is taken.
248
+ fd, name = tempfile.mkstemp(
249
+ dir=file.parent, prefix=f"{file.name}.", suffix=".tmp"
250
+ )
251
+ temp = Path(name)
252
+ try:
253
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
254
+ stream.write(text)
255
+ # A rename replaces whatever sits at the entry name, a symlink
256
+ # included, without following it.
257
+ temp.replace(file)
258
+ except BaseException:
259
+ temp.unlink(missing_ok=True)
260
+ raise
261
+
262
+ def _debug(self, msg: str, *args: object) -> None:
263
+ """
264
+ Log at DEBUG on the configured logger, if any.
265
+
266
+ Args:
267
+ msg (str): The format string.
268
+ *args (object): Its arguments.
269
+ """
270
+ if self.logger is not None:
271
+ self.logger.debug(msg, *args)
wrapkit/cli.py ADDED
@@ -0,0 +1,258 @@
1
+ """
2
+ Helpers for the wrappers' python-fire command lines.
3
+
4
+ Fire turns a class's methods into subcommands with no hand-written parsing,
5
+ but a few of its habits need correcting in every wrapper:
6
+
7
+ * a bare boolean flag takes the next word as its value, so ``--no-cache
8
+ browse`` swallows the subcommand (:func:`bind_bool_flags`);
9
+ * arguments that look like numbers arrive as ints, so ``--start 2024`` is
10
+ ``2024`` and the code ``01`` cannot be written bare (:func:`as_text`,
11
+ :func:`literal_keeping_codes`, :func:`set_parse_fns`).
12
+
13
+ :func:`run` wraps the Fire call itself: expected errors print a short
14
+ ``Error: ...`` line and exit 1, with the traceback sent to the log. The line is
15
+ masked by the logger's :class:`~wrapkit.log.RedactFilter`, as the log is.
16
+ :func:`resolve_out` routes bare output file names into ``outputs/``.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import inspect
22
+ import re
23
+ import sys
24
+ from pathlib import Path
25
+ from typing import TYPE_CHECKING, Any
26
+
27
+ from wrapkit.log import RedactFilter
28
+
29
+ if TYPE_CHECKING:
30
+ import logging
31
+ from collections.abc import Callable, Iterable, Mapping
32
+
33
+ __all__ = [
34
+ "as_text",
35
+ "bind_bool_flags",
36
+ "literal_keeping_codes",
37
+ "resolve_out",
38
+ "run",
39
+ "set_parse_fns",
40
+ ]
41
+
42
+
43
+ def resolve_out(path: str, outputs: str | Path = "outputs") -> str:
44
+ """
45
+ Route a bare filename into the outputs folder.
46
+
47
+ A path with no directory part (``data.csv``) is written under ``outputs``
48
+ (created if needed); a path that already has a directory, relative or
49
+ absolute, is returned unchanged, ``./data.csv`` included.
50
+
51
+ Args:
52
+ path (str): The user-supplied destination.
53
+ outputs (str | Path): The folder for bare names.
54
+
55
+ Returns:
56
+ str: The path to write to.
57
+ """
58
+ candidate = Path(path)
59
+ # Path("./data.csv").parent is Path() too, so look at the text as typed.
60
+ if candidate.parent == Path() and not re.search(r"[\\/]", path):
61
+ folder = Path(outputs)
62
+ folder.mkdir(parents=True, exist_ok=True)
63
+ return str(folder / candidate.name)
64
+ return path
65
+
66
+
67
+ def as_text(value: object) -> str | None:
68
+ """
69
+ Pass a CLI value through as text.
70
+
71
+ Fire parses arguments that look like numbers, so ``--start 2024`` arrives
72
+ as the int ``2024``. Turning it back into a string keeps a ``str | None``
73
+ contract and gives the same query (and cache entry) as the library call.
74
+
75
+ Args:
76
+ value (object): The value Fire passed, or ``None``.
77
+
78
+ Returns:
79
+ str | None: ``None`` unchanged, anything else as ``str(value)``.
80
+ """
81
+ return None if value is None else str(value)
82
+
83
+
84
+ def bind_bool_flags(argv: list[str], flags: Iterable[str]) -> list[str]:
85
+ """
86
+ Pin bare boolean flags to ``True`` wherever they appear.
87
+
88
+ ``--no-cache`` (or ``--no_cache``) becomes ``--no_cache=True``, so the flag
89
+ works before or after the subcommand. Arguments after a standalone ``--``
90
+ (Fire's own flags such as ``--help``) are left alone.
91
+
92
+ Args:
93
+ argv (list[str]): The arguments, without the program name.
94
+ flags (Iterable[str]): Flag names with underscores, such as
95
+ ``"no_cache"``.
96
+
97
+ Returns:
98
+ list[str]: A new argument list.
99
+ """
100
+ spellings: dict[str, str] = {}
101
+ for flag in flags:
102
+ bound = f"--{flag}=True"
103
+ spellings[f"--{flag}"] = bound
104
+ spellings[f"--{flag.replace('_', '-')}"] = bound
105
+ out: list[str] = []
106
+ for i, arg in enumerate(argv):
107
+ if arg == "--":
108
+ return out + argv[i:]
109
+ out.append(spellings.get(arg, arg))
110
+ return out
111
+
112
+
113
+ #: A quoted string literal (group 1, left alone) or a bare word that starts with
114
+ #: a zero followed by a digit (group 2), such as the code ``01``. A word joined
115
+ #: to a ``-``, ``/`` or ``:`` is part of a date or a time (``2024-01-15``,
116
+ #: ``06/2024``, ``08:30``) and is left alone.
117
+ _LEADING_ZERO_WORD = re.compile(
118
+ r"""("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')"""
119
+ r"""|(?<![\w./-])(0\d[\w.]*)(?![\w./:-])"""
120
+ )
121
+
122
+
123
+ def literal_keeping_codes(value: str) -> object:
124
+ """
125
+ Parse a Fire argument, keeping leading-zero codes as text.
126
+
127
+ Fire reads an argument as a Python literal with bare words allowed
128
+ (``{stateid: CO}``), but ``{generatorid: 01}`` is not valid Python, so Fire
129
+ passes the whole text on as a string, and ``00`` becomes the int ``0``.
130
+ Such words are quoted first, so they arrive as ``"01"`` and ``"00"``.
131
+ Quoted values and other numbers parse as before.
132
+
133
+ Args:
134
+ value (str): The argument's raw command-line text.
135
+
136
+ Returns:
137
+ object: The parsed value.
138
+ """
139
+ from fire import parser
140
+
141
+ quoted = _LEADING_ZERO_WORD.sub(
142
+ lambda match: match.group(1) or repr(match.group(2)), value
143
+ )
144
+ return parser.DefaultParseValue(quoted)
145
+
146
+
147
+ def set_parse_fns(cli: type, parsers: Mapping[str, Callable[[str], object]]) -> None:
148
+ """
149
+ Register Fire parse functions on every command that takes those parameters.
150
+
151
+ Fire stores the setting on the method itself, so calling this again is
152
+ harmless.
153
+
154
+ Args:
155
+ cli (type): The CLI class.
156
+ parsers (Mapping[str, Callable[[str], object]]): Parameter name to
157
+ parse function.
158
+ """
159
+ from fire import decorators
160
+
161
+ for name in dir(cli):
162
+ command = getattr(cli, name)
163
+ if name.startswith("_") or not inspect.isfunction(command):
164
+ continue
165
+ params = inspect.signature(command).parameters
166
+ if chosen := {k: fn for k, fn in parsers.items() if k in params}:
167
+ decorators.SetParseFns(**chosen)(command)
168
+
169
+
170
+ def _masked(text: str, logger: logging.Logger) -> str:
171
+ """
172
+ Mask secrets in text the way ``logger``'s own filters mask its records.
173
+
174
+ Text printed outside logging never reaches a filter, so the ``redact`` of
175
+ every :class:`~wrapkit.log.RedactFilter` attached to ``logger`` itself is
176
+ applied to it, in the order the filters run on a record. Other filters are
177
+ skipped: they cannot rewrite plain text.
178
+
179
+ Args:
180
+ text (str): Text shown outside logging, such as an error message.
181
+ logger (logging.Logger): The logger whose filters apply.
182
+
183
+ Returns:
184
+ str: ``text`` with its secrets replaced by ``***``; unchanged when no
185
+ filter matches.
186
+ """
187
+ # A LoggerAdapter creates its records on the logger it wraps, so that
188
+ # logger's filters are the ones that mask them.
189
+ target = getattr(logger, "logger", logger)
190
+ for flt in getattr(target, "filters", ()):
191
+ if isinstance(flt, RedactFilter):
192
+ text = flt.redact(text)
193
+ return text
194
+
195
+
196
+ def run(
197
+ cli: type,
198
+ *,
199
+ name: str,
200
+ logger: logging.Logger,
201
+ expected: tuple[type[BaseException], ...],
202
+ argv: list[str] | None = None,
203
+ bool_flags: Iterable[str] = (),
204
+ error_prefix: str = "Error",
205
+ failure_message: str = "Command failed",
206
+ ) -> Any: # ruff: ignore[any-type] - whatever the command returns
207
+ """
208
+ Run a Fire CLI, turning expected errors into a short message and exit 1.
209
+
210
+ The two texts a user sees come from the caller, so a wrapper whose CLI
211
+ speaks another language keeps it (``error_prefix="Fehler"``).
212
+
213
+ The error's message is printed, not logged, so no logging filter sees it.
214
+ It gets the masking its DEBUG record gets instead: the ``redact`` of every
215
+ :class:`~wrapkit.log.RedactFilter` attached to ``logger`` itself. A
216
+ ``requests`` error quotes the request URL, so with the usual
217
+ ``RedactFilter(["api_key"]).install(package)`` and that package's logger
218
+ passed here, the line shows ``api_key=***``, as the log does. A filter on
219
+ a parent logger or on a handler is not used (logging does not apply a
220
+ parent logger's filters to the record either), so attach it to
221
+ ``logger``. A message with no secret is printed unchanged.
222
+
223
+ Args:
224
+ cli (type): The CLI class (Fire instantiates it with the global flags).
225
+ name (str): The program name shown in help.
226
+ logger (logging.Logger): Receives the traceback at DEBUG. The
227
+ :class:`~wrapkit.log.RedactFilter` instances attached to it also
228
+ mask the printed message.
229
+ expected (tuple[type[BaseException], ...]): Errors shown as
230
+ ``Error: <message>`` on stderr instead of a traceback, with
231
+ secrets masked as in the log.
232
+ argv (list[str] | None): Arguments without the program name;
233
+ ``sys.argv[1:]`` when ``None``.
234
+ bool_flags (Iterable[str]): Boolean flags to pin with
235
+ :func:`bind_bool_flags`.
236
+ error_prefix (str): Printed before an expected error's message, as
237
+ ``<prefix>: <message>``.
238
+ failure_message (str): The DEBUG log line that carries the traceback.
239
+
240
+ Returns:
241
+ Any: What the command returned, as ``fire.Fire`` gives it back (Fire
242
+ has already printed it).
243
+
244
+ Raises:
245
+ SystemExit: With code 1 after an expected error; Fire also raises it
246
+ for usage errors.
247
+ """
248
+ import fire
249
+
250
+ args = list(sys.argv[1:] if argv is None else argv)
251
+ try:
252
+ return fire.Fire(cli, name=name, command=bind_bool_flags(args, bool_flags))
253
+ except expected as exc:
254
+ logger.debug(failure_message, exc_info=True)
255
+ # A requests error quotes the URL, key included: mask it as the log does.
256
+ message = _masked(str(exc), logger)
257
+ print(f"{error_prefix}: {message}", file=sys.stderr) # ruff: ignore[print]
258
+ raise SystemExit(1) from exc