qodalis-cli-server-plugin-data-explorer-redis 1.0.0b24__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,44 @@
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/
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.5
2
+ Name: qodalis-cli-server-plugin-data-explorer-redis
3
+ Version: 1.0.0b24
4
+ Summary: Redis Data Explorer provider plugin for Qodalis CLI servers
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
+ Keywords: cli,data-explorer,plugin,qodalis,redis
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: qodalis-cli-server-abstractions
21
+ Requires-Dist: redis[hiredis]>=5.0.0
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "qodalis-cli-server-plugin-data-explorer-redis"
7
+ version = "1.0.0b24"
8
+ description = "Redis Data Explorer provider plugin for Qodalis CLI servers"
9
+ readme = { text = "", content-type = "text/plain" }
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ authors = [
13
+ { name = "Nicolae Lupei", email = "nicolae.lupei@qodalis.com" },
14
+ ]
15
+ keywords = ["cli", "qodalis", "data-explorer", "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",
28
+ "redis[hiredis]>=5.0.0",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/qodalis-solutions/cli-server-python"
33
+ Repository = "https://github.com/qodalis-solutions/cli-server-python"
34
+ Issues = "https://github.com/qodalis-solutions/cli-server-python/issues"
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["qodalis_cli_data_explorer_redis"]
38
+
39
+ [tool.hatch.build.targets.sdist]
40
+ include = ["qodalis_cli_data_explorer_redis/**"]
@@ -0,0 +1,5 @@
1
+ """Qodalis CLI Data Explorer Redis plugin — Redis provider."""
2
+
3
+ from .redis_provider import RedisDataExplorerProvider
4
+
5
+ __all__ = ["RedisDataExplorerProvider"]
@@ -0,0 +1,297 @@
1
+ """Redis-backed Data Explorer provider."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Any
7
+
8
+ import redis.asyncio as aioredis
9
+
10
+ from qodalis_cli_server_abstractions import (
11
+ DataExplorerExecutionContext,
12
+ DataExplorerProviderOptions,
13
+ DataExplorerResult,
14
+ DataExplorerSchemaColumn,
15
+ DataExplorerSchemaResult,
16
+ DataExplorerSchemaTable,
17
+ IDataExplorerProvider,
18
+ )
19
+
20
+ # Commands that are safe to execute via the data explorer
21
+ _ALLOWED_COMMANDS = frozenset({
22
+ # Key inspection
23
+ "GET", "MGET", "GETRANGE", "STRLEN",
24
+ "TYPE", "TTL", "PTTL", "PERSIST",
25
+ "EXISTS", "KEYS", "SCAN",
26
+ "OBJECT", "DEBUG",
27
+ # Hash
28
+ "HGET", "HMGET", "HGETALL", "HKEYS", "HVALS", "HLEN", "HEXISTS",
29
+ # List
30
+ "LRANGE", "LLEN", "LINDEX",
31
+ # Set
32
+ "SMEMBERS", "SCARD", "SRANDMEMBER", "SISMEMBER",
33
+ # Sorted set
34
+ "ZRANGE", "ZRANGEBYSCORE", "ZRANGEBYLEX",
35
+ "ZREVRANGE", "ZREVRANGEBYSCORE",
36
+ "ZSCORE", "ZRANK", "ZREVRANK", "ZCARD", "ZCOUNT",
37
+ # Stream
38
+ "XRANGE", "XREVRANGE", "XLEN", "XREAD",
39
+ # Server info (read-only)
40
+ "INFO", "DBSIZE", "TIME", "PING", "CLIENT",
41
+ # Write commands (opt-in)
42
+ "SET", "MSET", "SETEX", "PSETEX", "SETNX",
43
+ "DEL", "UNLINK", "RENAME", "EXPIRE", "PEXPIRE", "EXPIREAT",
44
+ "HSET", "HMSET", "HDEL",
45
+ "LPUSH", "RPUSH", "LPOP", "RPOP", "LSET", "LREM",
46
+ "SADD", "SREM", "SMOVE",
47
+ "ZADD", "ZREM", "ZINCRBY",
48
+ "INCR", "DECR", "INCRBY", "DECRBY", "INCRBYFLOAT",
49
+ "APPEND",
50
+ })
51
+
52
+ # Commands whose result is a flat list of field/value pairs (alternating)
53
+ _PAIR_LIST_COMMANDS = frozenset({"HGETALL"})
54
+
55
+ # Commands that return a list of items
56
+ _LIST_COMMANDS = frozenset({
57
+ "KEYS", "HKEYS", "HVALS", "SMEMBERS", "LRANGE",
58
+ "ZRANGE", "ZREVRANGE", "ZRANGEBYSCORE", "ZREVRANGEBYSCORE",
59
+ "ZRANGEBYLEX", "MGET",
60
+ })
61
+
62
+ # Commands that return a single scalar value
63
+ _SCALAR_COMMANDS = frozenset({
64
+ "GET", "HGET", "LINDEX", "SRANDMEMBER", "ZSCORE",
65
+ "TYPE", "TTL", "PTTL", "STRLEN", "LLEN", "HLEN",
66
+ "SCARD", "ZCARD", "ZRANK", "ZREVRANK", "ZCOUNT",
67
+ "EXISTS", "HEXISTS", "SISMEMBER", "DBSIZE", "PING",
68
+ })
69
+
70
+
71
+ def _decode(value: Any) -> Any:
72
+ """Recursively decode bytes to str."""
73
+ if isinstance(value, bytes):
74
+ return value.decode("utf-8", errors="replace")
75
+ if isinstance(value, list):
76
+ return [_decode(v) for v in value]
77
+ if isinstance(value, dict):
78
+ return {_decode(k): _decode(v) for k, v in value.items()}
79
+ return value
80
+
81
+
82
+ def _normalise_result(command: str, raw: Any) -> tuple[list[str], list[list[Any]]]:
83
+ """Normalise a raw redis-py result into (columns, rows) table form."""
84
+ decoded = _decode(raw)
85
+
86
+ if command in _PAIR_LIST_COMMANDS:
87
+ # HGETALL returns a dict from redis-py (or list of pairs in older
88
+ # versions). Normalise both.
89
+ if isinstance(decoded, dict):
90
+ columns = ["field", "value"]
91
+ rows = [[k, v] for k, v in decoded.items()]
92
+ elif isinstance(decoded, list):
93
+ # alternating field / value
94
+ columns = ["field", "value"]
95
+ rows = [
96
+ [decoded[i], decoded[i + 1]]
97
+ for i in range(0, len(decoded) - 1, 2)
98
+ ]
99
+ else:
100
+ columns = ["value"]
101
+ rows = [[decoded]]
102
+ return columns, rows
103
+
104
+ if command in _LIST_COMMANDS:
105
+ if isinstance(decoded, list):
106
+ columns = ["value"]
107
+ rows = [[item] for item in decoded]
108
+ else:
109
+ columns = ["value"]
110
+ rows = [[decoded]]
111
+ return columns, rows
112
+
113
+ if command in _SCALAR_COMMANDS:
114
+ return ["value"], [[decoded]]
115
+
116
+ # Generic fallback — wrap whatever we got
117
+ if isinstance(decoded, list):
118
+ columns = ["value"]
119
+ rows = [[item] for item in decoded]
120
+ elif isinstance(decoded, dict):
121
+ columns = list(decoded.keys())
122
+ rows = [list(decoded.values())]
123
+ else:
124
+ columns = ["value"]
125
+ rows = [[decoded]]
126
+
127
+ return columns, rows
128
+
129
+
130
+ def _parse_command_args(query: str) -> list[str]:
131
+ """Split a Redis command into words; a quoted part (``"my key"``, ``'a b'``)
132
+ stays one word, without its quotes. Matches the Node and .NET providers."""
133
+ parts: list[str] = []
134
+ current = ""
135
+ quote: str | None = None
136
+ for ch in query.strip():
137
+ if quote:
138
+ if ch == quote:
139
+ quote = None
140
+ else:
141
+ current += ch
142
+ elif ch in ("'", '"'):
143
+ quote = ch
144
+ elif ch.isspace():
145
+ if current:
146
+ parts.append(current)
147
+ current = ""
148
+ else:
149
+ current += ch
150
+ if current:
151
+ parts.append(current)
152
+ return parts
153
+
154
+
155
+ class RedisDataExplorerProvider(IDataExplorerProvider):
156
+ """Executes Redis commands against a Redis server."""
157
+
158
+ def __init__(self, connection_string: str = "redis://localhost:6379") -> None:
159
+ self._connection_string = connection_string
160
+
161
+ async def execute_async(
162
+ self, context: DataExplorerExecutionContext
163
+ ) -> DataExplorerResult:
164
+ """Execute a Redis command against the server."""
165
+ start = time.monotonic()
166
+ client: aioredis.Redis | None = None
167
+ try:
168
+ parts = _parse_command_args(context.query)
169
+ if not parts:
170
+ raise ValueError("Empty query — please provide a Redis command.")
171
+
172
+ command = parts[0].upper()
173
+ args = parts[1:]
174
+
175
+ if command not in _ALLOWED_COMMANDS:
176
+ raise ValueError(
177
+ f"Command '{command}' is not permitted. "
178
+ "Only safe read/write Redis commands are allowed."
179
+ )
180
+
181
+ client = aioredis.from_url(
182
+ self._connection_string,
183
+ decode_responses=False,
184
+ )
185
+ raw = await client.execute_command(command, *args)
186
+
187
+ columns, rows = _normalise_result(command, raw)
188
+
189
+ return DataExplorerResult(
190
+ success=True,
191
+ source=context.options.name,
192
+ language=context.options.language,
193
+ default_output_format=context.options.default_output_format,
194
+ execution_time=int((time.monotonic() - start) * 1000),
195
+ columns=columns,
196
+ rows=rows,
197
+ row_count=len(rows),
198
+ truncated=False,
199
+ error=None,
200
+ )
201
+ except Exception as exc:
202
+ return DataExplorerResult(
203
+ success=False,
204
+ source=context.options.name,
205
+ language=context.options.language,
206
+ default_output_format=context.options.default_output_format,
207
+ execution_time=int((time.monotonic() - start) * 1000),
208
+ columns=None,
209
+ rows=[],
210
+ row_count=0,
211
+ truncated=False,
212
+ error=str(exc),
213
+ )
214
+ finally:
215
+ if client is not None:
216
+ await client.aclose()
217
+
218
+ async def get_schema_async(
219
+ self, options: DataExplorerProviderOptions
220
+ ) -> DataExplorerSchemaResult | None:
221
+ """Scan keys and group them by Redis type to form a schema."""
222
+ client: aioredis.Redis | None = None
223
+ try:
224
+ client = aioredis.from_url(
225
+ self._connection_string,
226
+ decode_responses=True,
227
+ )
228
+
229
+ keys: list[str] = []
230
+ cursor: int = 0
231
+ max_keys = 1000
232
+ while True:
233
+ cursor, batch = await client.scan(
234
+ cursor=cursor, count=100
235
+ )
236
+ keys.extend(batch)
237
+ if cursor == 0 or len(keys) >= max_keys:
238
+ break
239
+ keys = keys[:max_keys]
240
+
241
+ type_to_keys: dict[str, list[str]] = {}
242
+ for key in keys:
243
+ key_type: str = await client.type(key) # type: ignore[assignment]
244
+ type_to_keys.setdefault(key_type, []).append(key)
245
+
246
+ _TYPE_COLUMNS: dict[str, list[DataExplorerSchemaColumn]] = {
247
+ "string": [
248
+ DataExplorerSchemaColumn(name="key", type="string", nullable=False, primary_key=True),
249
+ DataExplorerSchemaColumn(name="value", type="string", nullable=True, primary_key=False),
250
+ ],
251
+ "hash": [
252
+ DataExplorerSchemaColumn(name="key", type="string", nullable=False, primary_key=True),
253
+ DataExplorerSchemaColumn(name="field", type="string", nullable=False, primary_key=False),
254
+ DataExplorerSchemaColumn(name="value", type="string", nullable=True, primary_key=False),
255
+ ],
256
+ "list": [
257
+ DataExplorerSchemaColumn(name="key", type="string", nullable=False, primary_key=True),
258
+ DataExplorerSchemaColumn(name="index", type="integer", nullable=False, primary_key=False),
259
+ DataExplorerSchemaColumn(name="value", type="string", nullable=True, primary_key=False),
260
+ ],
261
+ "set": [
262
+ DataExplorerSchemaColumn(name="key", type="string", nullable=False, primary_key=True),
263
+ DataExplorerSchemaColumn(name="member", type="string", nullable=True, primary_key=False),
264
+ ],
265
+ "zset": [
266
+ DataExplorerSchemaColumn(name="key", type="string", nullable=False, primary_key=True),
267
+ DataExplorerSchemaColumn(name="member", type="string", nullable=False, primary_key=False),
268
+ DataExplorerSchemaColumn(name="score", type="float", nullable=False, primary_key=False),
269
+ ],
270
+ "stream": [
271
+ DataExplorerSchemaColumn(name="key", type="string", nullable=False, primary_key=True),
272
+ DataExplorerSchemaColumn(name="id", type="string", nullable=False, primary_key=False),
273
+ DataExplorerSchemaColumn(name="fields", type="object", nullable=True, primary_key=False),
274
+ ],
275
+ }
276
+
277
+ tables: list[DataExplorerSchemaTable] = []
278
+ for redis_type, type_keys in sorted(type_to_keys.items()):
279
+ columns = _TYPE_COLUMNS.get(
280
+ redis_type,
281
+ [
282
+ DataExplorerSchemaColumn(name="key", type="string", nullable=False, primary_key=True),
283
+ DataExplorerSchemaColumn(name="value", type="string", nullable=True, primary_key=False),
284
+ ],
285
+ )
286
+ tables.append(
287
+ DataExplorerSchemaTable(
288
+ name=redis_type,
289
+ type="table",
290
+ columns=columns,
291
+ )
292
+ )
293
+
294
+ return DataExplorerSchemaResult(source=options.name, tables=tables)
295
+ finally:
296
+ if client is not None:
297
+ await client.aclose()