qodalis-cli-server-plugin-config-redis 1.0.0b32__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.
@@ -0,0 +1,50 @@
1
+ # Byte-compiled / optimized
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # Distribution / packaging
7
+ *.egg-info/
8
+ dist/
9
+ build/
10
+ .eggs/
11
+ *.egg
12
+
13
+ # Virtual environments
14
+ .venv/
15
+ venv/
16
+ env/
17
+
18
+ # Environment variables
19
+ .env
20
+
21
+ # Testing
22
+ .pytest_cache/
23
+ .coverage
24
+ htmlcov/
25
+ TestResults/
26
+
27
+ # Type checking / linting
28
+ .mypy_cache/
29
+ .ruff_cache/
30
+
31
+ # C extensions
32
+ *.so
33
+
34
+ # IDEs and editors
35
+ .idea/
36
+ .vscode/*
37
+ !.vscode/settings.json
38
+ !.vscode/launch.json
39
+ !.vscode/extensions.json
40
+
41
+ # System files
42
+ .DS_Store
43
+ Thumbs.db
44
+ node_modules/
45
+
46
+ # Portal site copied into the package at build time (scripts/copy_portal.py)
47
+ plugins/portal/qodalis_cli_portal/site/
48
+
49
+ # Dashboard plugins installed from the marketplace (admin plugin, default dir)
50
+ qcli-data/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-2026 Qodalis Solutions
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.5
2
+ Name: qodalis-cli-server-plugin-config-redis
3
+ Version: 1.0.0b32
4
+ Summary: Redis config store for Qodalis CLI servers: writable settings of the config providers kept in Redis
5
+ Project-URL: Homepage, https://github.com/qodalis-solutions/cli-server-python
6
+ Project-URL: Repository, https://github.com/qodalis-solutions/cli-server-python
7
+ Project-URL: Issues, https://github.com/qodalis-solutions/cli-server-python/issues
8
+ Author-email: Nicolae Lupei <nicolae.lupei@qodalis.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: cli,config,plugin,qodalis,redis
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: qodalis-cli-server-abstractions>=1.0.0b31
22
+ Requires-Dist: redis>=5
23
+ Provides-Extra: test
24
+ Requires-Dist: httpx>=0.24; extra == 'test'
25
+ Requires-Dist: pytest-asyncio>=0.21; extra == 'test'
26
+ Requires-Dist: pytest>=7.0; extra == 'test'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # qodalis-cli-server-plugin-config-redis
30
+
31
+ A Redis store for the [config providers](../../README.md#config-providers) of
32
+ [Qodalis CLI Server (Python)](https://github.com/qodalis-solutions/cli-server-python): the writable settings of one
33
+ provider, several or all of them, kept in Redis and shared by every server using the same Redis (the Node and .NET
34
+ servers included: same keys, same hashes, same write script).
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install qodalis-cli-server-plugin-config-redis
40
+ ```
41
+
42
+ It uses [redis-py](https://github.com/redis/redis-py) (`redis>=5`, installed with it).
43
+
44
+ ## Quick Start
45
+
46
+ Every provider can have its own store. Keep `jobs` in Redis and the rest in the app's settings file:
47
+
48
+ ```python
49
+ import os
50
+
51
+ from qodalis_cli import CliServerOptions, create_cli_server
52
+ from qodalis_cli.create_cli_server import CliServerConfigOptions
53
+ from qodalis_cli_server_abstractions.config import JsonFileConfigStore
54
+ from qodalis_cli_config_redis import CliRedisConfigStore
55
+
56
+ redis_store = CliRedisConfigStore(url=os.environ["REDIS_URL"]) # redis://[:password@]host:6379/0
57
+
58
+ server = create_cli_server(CliServerOptions(
59
+ config=CliServerConfigOptions(
60
+ store=JsonFileConfigStore("config/app.json", section="qcli"), # the default store
61
+ stores={"jobs": redis_store}, # per provider id
62
+ ),
63
+ ))
64
+ ```
65
+
66
+ The stored settings are applied when the app starts (or by `await server.config.ready()`).
67
+
68
+ Other ways to give a provider this store:
69
+
70
+ ```python
71
+ builder.set_config_store(redis_store) # the default store: every provider without its own
72
+ builder.set_config_store(redis_store, "users") # one provider, by id (wins over the provider's own)
73
+ CliJobsBuilder().set_config_store(redis_store) # the jobs plugin's provider (also users, portal, admin)
74
+ CliStoredConfigProvider(id="billing", title="Billing", store=redis_store, sections=[...])
75
+ ```
76
+
77
+ One store may serve several providers: their data never mixes (one key per provider and section).
78
+
79
+ ## Options
80
+
81
+ | Option | Default | Description |
82
+ |---|---|---|
83
+ | `url` | | A Redis URL (`redis://`, `rediss://` for TLS); the store creates its client (connecting on the first command) and `close()` ends it |
84
+ | `client` | | A `redis.asyncio` client of your app (or any object with async `hgetall` and `eval`); the store never closes it. `client` or `url` is required |
85
+ | `key_prefix` | `qcli:config:` | Prepended to every key |
86
+ | `ttl_seconds` | none | Expire a section this many seconds after its last change; without it sections are kept until deleted |
87
+ | `max_retries` | `10` | How often a write without an expected version is retried when another write came first |
88
+
89
+ ## How It Works
90
+
91
+ - **One hash per provider section**: `qcli:config:<provider>:<section>` with the fields `values` (the settings
92
+ changed from their defaults, as JSON), `version` (grows by one on every write) and `updatedAt` (ISO 8601).
93
+ - **Atomic, versioned writes**: a write reads the section, applies the changes (`None` removes a key) and stores them
94
+ with a Lua script (`REDIS_CONFIG_WRITE_SCRIPT`) that first checks the version is still the one read. A change made
95
+ with an expected version (the dashboard, `config set --expected-version`, `PATCH` with `version`) that is stale, or
96
+ that loses the race to another server, is refused with `CliConfigConflictError` (HTTP 409 with the current version);
97
+ one without is retried on the new values, so concurrent writers never lose a change.
98
+ - **Source** `database`, **persistent**: the settings survive server restarts (as long as Redis keeps its data).
99
+ - **`describe()`**: `{"kind": "redis", "title": "Redis", "detail": "cache:6379/0, prefix qcli:config", "persistent": true}`
100
+ (host, port, database and key prefix; never the user or password), shown as the provider's `store` by
101
+ `GET /api/v1/qcli/config` and by `config list`:
102
+
103
+ ```text
104
+ jobs Jobs · Redis (cache:6379/0, prefix qcli:config)
105
+ ```
106
+
107
+ Secrets are stored as given: protect the Redis (password, TLS, network) like the rest of the server's data.
108
+
109
+ ## Tests
110
+
111
+ ```bash
112
+ pip install -e plugins/config-redis/
113
+ pytest plugins/config-redis/tests/
114
+ ```
115
+
116
+ The store runs the same contract as the in-memory, JSON file and database stores on a fake Redis (fakeredis when
117
+ installed, else a small in-test fake running the write script's logic). Set `QCLI_TEST_REDIS`
118
+ (`redis://localhost:6379/15`) to run it against a real Redis too, keys under a temporary prefix removed afterwards.
119
+
120
+ ## Terminal commands
121
+
122
+ None of its own: the settings are read and changed with the server's [`config` command](../../README.md#permissions-audit-events-mcp-terminal)
123
+ (`config list`, `config get`, `config set`, `config reset`).
124
+
125
+ ## Install from the dashboard
126
+
127
+ Installable at runtime from the server marketplace (the dashboard's Plugins → Marketplace, or
128
+ `admin plugins install config-redis`; it loads at the next start), or in code through the same entry, its options the
129
+ defaults of the settings below (a saved setting overrides them):
130
+
131
+ ```python
132
+ from qodalis_cli_config_redis import plugin as config_redis
133
+
134
+ builder.add_plugin(config_redis, {...})
135
+ ```
136
+
137
+ Entry point `config-redis = "qodalis_cli_config_redis.plugin:create_plugin"` (group `qodalis_cli.plugins`), load order 20. Its settings
138
+ (provider `config-redis`, section `settings`; `config set config-redis.settings.<key> <value>`, then a restart):
139
+
140
+ | Setting | Type | Default | |
141
+ |---|---|---|---|
142
+ | `url` | secret (required) | | redis://[:password@]host:6379/0 (rediss:// for TLS); kept as a secret, never returned |
143
+ | `keyPrefix` | string | `"qcli:config:"` | Prepended to every key: <prefix><provider>:<section> |
144
+ | `ttlSeconds` | number | `0` | A section expires this long after its last change; 0: never |
145
+
146
+ ## License
147
+
148
+ MIT
@@ -0,0 +1,120 @@
1
+ # qodalis-cli-server-plugin-config-redis
2
+
3
+ A Redis store for the [config providers](../../README.md#config-providers) of
4
+ [Qodalis CLI Server (Python)](https://github.com/qodalis-solutions/cli-server-python): the writable settings of one
5
+ provider, several or all of them, kept in Redis and shared by every server using the same Redis (the Node and .NET
6
+ servers included: same keys, same hashes, same write script).
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pip install qodalis-cli-server-plugin-config-redis
12
+ ```
13
+
14
+ It uses [redis-py](https://github.com/redis/redis-py) (`redis>=5`, installed with it).
15
+
16
+ ## Quick Start
17
+
18
+ Every provider can have its own store. Keep `jobs` in Redis and the rest in the app's settings file:
19
+
20
+ ```python
21
+ import os
22
+
23
+ from qodalis_cli import CliServerOptions, create_cli_server
24
+ from qodalis_cli.create_cli_server import CliServerConfigOptions
25
+ from qodalis_cli_server_abstractions.config import JsonFileConfigStore
26
+ from qodalis_cli_config_redis import CliRedisConfigStore
27
+
28
+ redis_store = CliRedisConfigStore(url=os.environ["REDIS_URL"]) # redis://[:password@]host:6379/0
29
+
30
+ server = create_cli_server(CliServerOptions(
31
+ config=CliServerConfigOptions(
32
+ store=JsonFileConfigStore("config/app.json", section="qcli"), # the default store
33
+ stores={"jobs": redis_store}, # per provider id
34
+ ),
35
+ ))
36
+ ```
37
+
38
+ The stored settings are applied when the app starts (or by `await server.config.ready()`).
39
+
40
+ Other ways to give a provider this store:
41
+
42
+ ```python
43
+ builder.set_config_store(redis_store) # the default store: every provider without its own
44
+ builder.set_config_store(redis_store, "users") # one provider, by id (wins over the provider's own)
45
+ CliJobsBuilder().set_config_store(redis_store) # the jobs plugin's provider (also users, portal, admin)
46
+ CliStoredConfigProvider(id="billing", title="Billing", store=redis_store, sections=[...])
47
+ ```
48
+
49
+ One store may serve several providers: their data never mixes (one key per provider and section).
50
+
51
+ ## Options
52
+
53
+ | Option | Default | Description |
54
+ |---|---|---|
55
+ | `url` | | A Redis URL (`redis://`, `rediss://` for TLS); the store creates its client (connecting on the first command) and `close()` ends it |
56
+ | `client` | | A `redis.asyncio` client of your app (or any object with async `hgetall` and `eval`); the store never closes it. `client` or `url` is required |
57
+ | `key_prefix` | `qcli:config:` | Prepended to every key |
58
+ | `ttl_seconds` | none | Expire a section this many seconds after its last change; without it sections are kept until deleted |
59
+ | `max_retries` | `10` | How often a write without an expected version is retried when another write came first |
60
+
61
+ ## How It Works
62
+
63
+ - **One hash per provider section**: `qcli:config:<provider>:<section>` with the fields `values` (the settings
64
+ changed from their defaults, as JSON), `version` (grows by one on every write) and `updatedAt` (ISO 8601).
65
+ - **Atomic, versioned writes**: a write reads the section, applies the changes (`None` removes a key) and stores them
66
+ with a Lua script (`REDIS_CONFIG_WRITE_SCRIPT`) that first checks the version is still the one read. A change made
67
+ with an expected version (the dashboard, `config set --expected-version`, `PATCH` with `version`) that is stale, or
68
+ that loses the race to another server, is refused with `CliConfigConflictError` (HTTP 409 with the current version);
69
+ one without is retried on the new values, so concurrent writers never lose a change.
70
+ - **Source** `database`, **persistent**: the settings survive server restarts (as long as Redis keeps its data).
71
+ - **`describe()`**: `{"kind": "redis", "title": "Redis", "detail": "cache:6379/0, prefix qcli:config", "persistent": true}`
72
+ (host, port, database and key prefix; never the user or password), shown as the provider's `store` by
73
+ `GET /api/v1/qcli/config` and by `config list`:
74
+
75
+ ```text
76
+ jobs Jobs · Redis (cache:6379/0, prefix qcli:config)
77
+ ```
78
+
79
+ Secrets are stored as given: protect the Redis (password, TLS, network) like the rest of the server's data.
80
+
81
+ ## Tests
82
+
83
+ ```bash
84
+ pip install -e plugins/config-redis/
85
+ pytest plugins/config-redis/tests/
86
+ ```
87
+
88
+ The store runs the same contract as the in-memory, JSON file and database stores on a fake Redis (fakeredis when
89
+ installed, else a small in-test fake running the write script's logic). Set `QCLI_TEST_REDIS`
90
+ (`redis://localhost:6379/15`) to run it against a real Redis too, keys under a temporary prefix removed afterwards.
91
+
92
+ ## Terminal commands
93
+
94
+ None of its own: the settings are read and changed with the server's [`config` command](../../README.md#permissions-audit-events-mcp-terminal)
95
+ (`config list`, `config get`, `config set`, `config reset`).
96
+
97
+ ## Install from the dashboard
98
+
99
+ Installable at runtime from the server marketplace (the dashboard's Plugins → Marketplace, or
100
+ `admin plugins install config-redis`; it loads at the next start), or in code through the same entry, its options the
101
+ defaults of the settings below (a saved setting overrides them):
102
+
103
+ ```python
104
+ from qodalis_cli_config_redis import plugin as config_redis
105
+
106
+ builder.add_plugin(config_redis, {...})
107
+ ```
108
+
109
+ Entry point `config-redis = "qodalis_cli_config_redis.plugin:create_plugin"` (group `qodalis_cli.plugins`), load order 20. Its settings
110
+ (provider `config-redis`, section `settings`; `config set config-redis.settings.<key> <value>`, then a restart):
111
+
112
+ | Setting | Type | Default | |
113
+ |---|---|---|---|
114
+ | `url` | secret (required) | | redis://[:password@]host:6379/0 (rediss:// for TLS); kept as a secret, never returned |
115
+ | `keyPrefix` | string | `"qcli:config:"` | Prepended to every key: <prefix><provider>:<section> |
116
+ | `ttlSeconds` | number | `0` | A section expires this long after its last change; 0: never |
117
+
118
+ ## License
119
+
120
+ MIT
@@ -0,0 +1,49 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "qodalis-cli-server-plugin-config-redis"
7
+ version = "1.0.0b32"
8
+ description = "Redis config store for Qodalis CLI servers: writable settings of the config providers kept in Redis"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ authors = [
13
+ { name = "Nicolae Lupei", email = "nicolae.lupei@qodalis.com" },
14
+ ]
15
+ keywords = ["cli", "qodalis", "config", "redis", "plugin"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ ]
26
+ dependencies = [
27
+ "qodalis-cli-server-abstractions>=1.0.0b31",
28
+ "redis>=5",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ test = ["pytest>=7.0", "pytest-asyncio>=0.21", "httpx>=0.24"]
33
+
34
+ [project.entry-points."qodalis_cli.plugins"]
35
+ config-redis = "qodalis_cli_config_redis.plugin:create_plugin"
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/qodalis-solutions/cli-server-python"
39
+ Repository = "https://github.com/qodalis-solutions/cli-server-python"
40
+ Issues = "https://github.com/qodalis-solutions/cli-server-python/issues"
41
+
42
+ [tool.hatch.build.targets.wheel]
43
+ packages = ["qodalis_cli_config_redis"]
44
+
45
+ [tool.hatch.build.targets.sdist]
46
+ include = ["qodalis_cli_config_redis/**", "README.md", "LICENSE"]
47
+
48
+ [tool.pytest.ini_options]
49
+ asyncio_mode = "auto"
@@ -0,0 +1,12 @@
1
+ """Qodalis CLI config-redis plugin: writable config settings kept in Redis."""
2
+
3
+ #: The package's icon on the admin dashboard's plugins page (``CliInstalledPlugin.icon``).
4
+ __plugin_icon__ = "🔴"
5
+
6
+ from .redis_config_store import (
7
+ DEFAULT_REDIS_CONFIG_KEY_PREFIX,
8
+ REDIS_CONFIG_WRITE_SCRIPT,
9
+ CliRedisConfigStore,
10
+ )
11
+
12
+ __all__ = ["CliRedisConfigStore", "DEFAULT_REDIS_CONFIG_KEY_PREFIX", "REDIS_CONFIG_WRITE_SCRIPT"]
@@ -0,0 +1,57 @@
1
+ """The config-redis plugin's entry point (``qodalis_cli.plugins``, ``builder.add_plugin``): Redis becomes the server's
2
+ default config store (``CLI_PLUGIN_LOAD_ORDER.CONFIG_STORE``): the settings of the providers registered before it
3
+ move to Redis, those registered after it start there. Its own settings (the URL a secret) are kept in
4
+ ``<data dir>/plugin-settings.json``, never in Redis itself. Without a URL (or a ``client`` in code) it needs
5
+ configuration and the settings stay where they were."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from typing import Any
11
+
12
+ from qodalis_cli_server_abstractions import CLI_PLUGIN_LOAD_ORDER, CliPluginEntryInfo
13
+ from qodalis_cli_server_abstractions.config import CliConfigSettingDefinition, CliConfigValidation, JsonFileConfigStore
14
+
15
+ from .redis_config_store import DEFAULT_REDIS_CONFIG_KEY_PREFIX, CliRedisConfigStore
16
+
17
+ #: The plugin, for ``builder.add_plugin`` (the marketplace's record says it for an installed copy).
18
+ plugin = CliPluginEntryInfo(id="config-redis", package="qodalis-cli-server-plugin-config-redis", title="Config on Redis", icon="🟥")
19
+
20
+ #: Before the providers resolve their store.
21
+ order = CLI_PLUGIN_LOAD_ORDER.CONFIG_STORE
22
+
23
+
24
+ def settings() -> list[CliConfigSettingDefinition]:
25
+ """Its settings (code options of the same keys are their defaults; ``client``, a redis.asyncio client, from code)."""
26
+ restart = {"requires_restart": True}
27
+ return [
28
+ CliConfigSettingDefinition(key="url", label="Redis URL",
29
+ description="redis://[:password@]host:6379/0 (rediss:// for TLS); kept as a secret, never returned",
30
+ type="secret", required=True, **restart),
31
+ CliConfigSettingDefinition(key="keyPrefix", label="Key prefix", description="Prepended to every key: <prefix><provider>:<section>",
32
+ type="string", default=DEFAULT_REDIS_CONFIG_KEY_PREFIX, validation=CliConfigValidation(max=200), **restart),
33
+ CliConfigSettingDefinition(key="ttlSeconds", label="Expiry (seconds)", description="A section expires this long after its last change; 0: never",
34
+ type="number", default=0, validation=CliConfigValidation(min=0), **restart),
35
+ ]
36
+
37
+
38
+ async def create_plugin(context: Any) -> Any:
39
+ provider = await context.settings(
40
+ title="Config on Redis", description="Redis as the server's config store", settings=settings(),
41
+ # Not in Redis: the URL must be read before Redis can be
42
+ store=context.settings_file or JsonFileConfigStore(os.path.join(context.server_data_dir, "plugin-settings.json")),
43
+ )
44
+ client = context.options.get("client")
45
+ url = str(provider.value("settings", "url") or "").strip()
46
+ if client is None and not url:
47
+ return context.needs_configuration(provider.missing_required())
48
+ ttl = provider.value("settings", "ttlSeconds")
49
+ store = CliRedisConfigStore(
50
+ client=client, url=None if client is not None else url,
51
+ key_prefix=str(provider.value("settings", "keyPrefix") or DEFAULT_REDIS_CONFIG_KEY_PREFIX),
52
+ ttl_seconds=int(ttl) if isinstance(ttl, (int, float)) and ttl > 0 else None,
53
+ )
54
+ context.builder.replace_config_store(store)
55
+ if context.restart is not None and hasattr(context.restart, "on_shutdown"):
56
+ context.restart.on_shutdown("config-redis store", store.close)
57
+ return None
@@ -0,0 +1,195 @@
1
+ """Writable config settings kept in Redis: one hash per provider section."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import json
7
+ from datetime import datetime, timezone
8
+ from typing import Any, Mapping, Optional
9
+
10
+ from qodalis_cli_server_abstractions.config import (
11
+ CliConfigConflictError,
12
+ CliConfigStoreDescription,
13
+ CliConfigStoredSection,
14
+ CliConfigValue,
15
+ ICliConfigStore,
16
+ apply_cli_config_changes,
17
+ )
18
+
19
+ #: The key prefix when none is given: ``qcli:config:<provider>:<section>``.
20
+ DEFAULT_REDIS_CONFIG_KEY_PREFIX = "qcli:config:"
21
+
22
+ #: The atomic write: sets the section's values and the next version only when
23
+ #: the stored version is still the one the change was computed from
24
+ #: (``ARGV[1]``); answers ``{1, newVersion}``, or ``{0, currentVersion}`` when
25
+ #: another write came first. ``ARGV[2]`` the values as JSON, ``ARGV[3]`` the
26
+ #: time (ISO 8601), ``ARGV[4]`` the TTL in seconds (0: none). The same script
27
+ #: as the Node and .NET servers', so they can share one Redis.
28
+ REDIS_CONFIG_WRITE_SCRIPT = """
29
+ local current = tonumber(redis.call('HGET', KEYS[1], 'version') or '0') or 0
30
+ if current ~= tonumber(ARGV[1]) then
31
+ return {0, current}
32
+ end
33
+ local nextVersion = current + 1
34
+ redis.call('HSET', KEYS[1], 'version', nextVersion, 'values', ARGV[2], 'updatedAt', ARGV[3])
35
+ local ttl = tonumber(ARGV[4]) or 0
36
+ if ttl > 0 then
37
+ redis.call('EXPIRE', KEYS[1], ttl)
38
+ end
39
+ return {1, nextVersion}
40
+ """
41
+
42
+
43
+ def _text(value: Any) -> str:
44
+ return value.decode("utf-8") if isinstance(value, (bytes, bytearray)) else str(value)
45
+
46
+
47
+ def _parse_hash(raw: Optional[Mapping[Any, Any]]) -> CliConfigStoredSection:
48
+ """A section from its hash: ``({}, 0)`` when missing; unreadable values read as empty."""
49
+ if not raw:
50
+ return CliConfigStoredSection()
51
+ fields = {_text(k): _text(v) for k, v in raw.items()}
52
+ values: dict[str, CliConfigValue] = {}
53
+ try:
54
+ parsed = json.loads(fields.get("values", "{}"))
55
+ if isinstance(parsed, dict):
56
+ values = parsed
57
+ except ValueError:
58
+ values = {}
59
+ try:
60
+ version = int(fields.get("version", ""))
61
+ except ValueError:
62
+ version = 0
63
+ return CliConfigStoredSection(values, version if version >= 0 else 0)
64
+
65
+
66
+ class CliRedisConfigStore(ICliConfigStore):
67
+ """Keeps writable config settings in Redis (source ``database``): one hash
68
+ per provider section (``qcli:config:<provider>:<section>``) with the
69
+ fields ``values`` (JSON), ``version`` and ``updatedAt``. A write reads
70
+ the section, applies the changes and stores them with a Lua script that
71
+ checks the version first (:data:`REDIS_CONFIG_WRITE_SCRIPT`), so servers
72
+ sharing the Redis never lose a change: a stale expected version is
73
+ refused (:class:`CliConfigConflictError`), a write without one is retried.
74
+
75
+ Use it for every provider, or for some only, next to other stores::
76
+
77
+ redis_store = CliRedisConfigStore(url=os.environ["REDIS_URL"])
78
+ create_cli_server(CliServerOptions(config=CliServerConfigOptions(
79
+ store=JsonFileConfigStore("config.json"), stores={"jobs": redis_store},
80
+ )))
81
+
82
+ ``client``: a connected ``redis.asyncio`` client shared with the app (the
83
+ store never closes it); or ``url`` (``redis://[:password@]host:6379/0``,
84
+ ``rediss://`` for TLS): the store creates its client and :meth:`close`
85
+ ends it. ``key_prefix`` is prepended to every key (default
86
+ ``qcli:config:``); ``ttl_seconds`` expires a section that long after its
87
+ last change (default none); ``max_retries``: how often a write without an
88
+ expected version is retried when another write came first (default 10)."""
89
+
90
+ source = "database"
91
+
92
+ def __init__(
93
+ self,
94
+ client: Any = None,
95
+ url: Optional[str] = None,
96
+ key_prefix: Optional[str] = None,
97
+ ttl_seconds: Optional[int] = None,
98
+ max_retries: int = 10,
99
+ ) -> None:
100
+ if client is not None:
101
+ self.client = client
102
+ self._owns_client = False
103
+ elif url:
104
+ import redis.asyncio as aioredis
105
+
106
+ # Connects on the first command
107
+ self.client = aioredis.Redis.from_url(url)
108
+ self._owns_client = True
109
+ else:
110
+ raise ValueError("CliRedisConfigStore needs a client or a url")
111
+ self.key_prefix = DEFAULT_REDIS_CONFIG_KEY_PREFIX if key_prefix is None else key_prefix
112
+ if ttl_seconds is not None and (
113
+ not isinstance(ttl_seconds, int) or isinstance(ttl_seconds, bool) or ttl_seconds < 0
114
+ ):
115
+ raise ValueError("ttl_seconds must be a whole number of seconds")
116
+ self.ttl_seconds = ttl_seconds or 0
117
+ self.max_retries = max(0, max_retries)
118
+
119
+ def _connection(self) -> dict[str, Any]:
120
+ """Where the client connects (its pool's connection arguments); never shown whole."""
121
+ pool = getattr(self.client, "connection_pool", None)
122
+ kwargs = getattr(pool, "connection_kwargs", None)
123
+ if isinstance(kwargs, Mapping):
124
+ return dict(kwargs)
125
+ options = getattr(self.client, "options", None)
126
+ return dict(options) if isinstance(options, Mapping) else {}
127
+
128
+ def describe(self) -> CliConfigStoreDescription:
129
+ """``cache:6379/0, prefix qcli:config``: host, port, database and key
130
+ prefix; never the password or user."""
131
+ o = self._connection()
132
+ where = o.get("path") or f"{o.get('host') or 'localhost'}:{o.get('port') or 6379}"
133
+ prefix = self.key_prefix.rstrip(":")
134
+ detail = f"{where}/{o.get('db') or 0}{f', prefix {prefix}' if prefix else ''}"
135
+ return CliConfigStoreDescription(kind="redis", title="Redis", detail=detail, persistent=True)
136
+
137
+ def key_of(self, provider: str, section: str) -> str:
138
+ """The section's key: ``<prefix><provider>:<section>``."""
139
+ return f"{self.key_prefix}{provider}:{section}"
140
+
141
+ async def read(self, provider: str, section: str) -> CliConfigStoredSection:
142
+ return _parse_hash(await self.client.hgetall(self.key_of(provider, section)))
143
+
144
+ async def write(
145
+ self,
146
+ provider: str,
147
+ section: str,
148
+ changes: Mapping[str, Optional[CliConfigValue]],
149
+ expected_version: Optional[int] = None,
150
+ ) -> CliConfigStoredSection:
151
+ key = self.key_of(provider, section)
152
+ attempt = 0
153
+ while True:
154
+ current = await self.read(provider, section)
155
+ if expected_version is not None and expected_version != current.version:
156
+ raise CliConfigConflictError(str(current.version))
157
+ values = apply_cli_config_changes(current.values, changes)
158
+ reply = await self.client.eval(
159
+ REDIS_CONFIG_WRITE_SCRIPT,
160
+ 1,
161
+ key,
162
+ current.version,
163
+ json.dumps(values, ensure_ascii=False),
164
+ datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
165
+ self.ttl_seconds,
166
+ )
167
+ ok, version = _reply(reply)
168
+ if ok == 1:
169
+ return CliConfigStoredSection(copy.deepcopy(values), version)
170
+ if ok != 0:
171
+ raise RuntimeError(f"unexpected reply from Redis: {reply!r}")
172
+ # Another write came first
173
+ if expected_version is not None:
174
+ raise CliConfigConflictError(str(version))
175
+ if attempt >= self.max_retries:
176
+ raise RuntimeError(f"config section {provider}.{section}: too many concurrent writes")
177
+ attempt += 1
178
+
179
+ async def close(self) -> None:
180
+ """Ends the client the store created from ``url``; a client given to it is left open."""
181
+ if not self._owns_client:
182
+ return
183
+ close = getattr(self.client, "aclose", None) or getattr(self.client, "close", None)
184
+ if close is not None:
185
+ await close()
186
+
187
+
188
+ def _reply(reply: Any) -> tuple[Optional[int], Optional[int]]:
189
+ """The script's ``{ok, version}``; ``(None, None)`` for anything else."""
190
+ if not isinstance(reply, (list, tuple)) or len(reply) != 2:
191
+ return None, None
192
+ try:
193
+ return int(reply[0]), int(reply[1])
194
+ except (TypeError, ValueError):
195
+ return None, None