Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/_parsers/helpers.py: 13%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

928 statements  

1import datetime 

2import math 

3 

4from redis.utils import str_if_bytes 

5 

6 

7def timestamp_to_datetime(response): 

8 "Converts a unix timestamp to a Python datetime object" 

9 if not response: 

10 return None 

11 try: 

12 response = int(response) 

13 except ValueError: 

14 return None 

15 return datetime.datetime.fromtimestamp(response) 

16 

17 

18def parse_debug_object(response): 

19 "Parse the results of Redis's DEBUG OBJECT command into a Python dict" 

20 # The 'type' of the object is the first item in the response, but isn't 

21 # prefixed with a name 

22 response = str_if_bytes(response) 

23 response = "type:" + response 

24 response = dict(kv.split(":") for kv in response.split()) 

25 

26 # parse some expected int values from the string response 

27 # note: this cmd isn't spec'd so these may not appear in all redis versions 

28 int_fields = ("refcount", "serializedlength", "lru", "lru_seconds_idle") 

29 for field in int_fields: 

30 if field in response: 

31 response[field] = int(response[field]) 

32 

33 return response 

34 

35 

36def decode_info(response, encoder): 

37 """Decode a raw INFO reply, replacing any bytes the encoder can't decode""" 

38 try: 

39 return encoder.decode(response) 

40 except UnicodeDecodeError: 

41 return response.decode(encoder.encoding, errors="replace") 

42 

43 

44def parse_info(response, **options): 

45 """Parse the result of Redis's INFO command into a Python dict""" 

46 info = {} 

47 response = str_if_bytes(response) 

48 

49 def get_value(value): 

50 if "," not in value and "=" not in value: 

51 try: 

52 if "." in value: 

53 return float(value) 

54 else: 

55 return int(value) 

56 except ValueError: 

57 return value 

58 elif "=" not in value: 

59 return [get_value(v) for v in value.split(",") if v] 

60 else: 

61 sub_dict = {} 

62 for item in value.split(","): 

63 if not item: 

64 continue 

65 if "=" in item: 

66 k, v = item.rsplit("=", 1) 

67 sub_dict[k] = get_value(v) 

68 else: 

69 sub_dict[item] = True 

70 return sub_dict 

71 

72 for line in response.splitlines(): 

73 if line and not line.startswith("#"): 

74 if line.find(":") != -1: 

75 # Split, the info fields keys and values. 

76 # Note that the value may contain ':'. but the 'host:' 

77 # pseudo-command is the only case where the key contains ':' 

78 key, value = line.split(":", 1) 

79 if key == "cmdstat_host": 

80 key, value = line.rsplit(":", 1) 

81 

82 if key == "module": 

83 # Hardcode a list for key 'modules' since there could be 

84 # multiple lines that started with 'module' 

85 info.setdefault("modules", []).append(get_value(value)) 

86 else: 

87 info[key] = get_value(value) 

88 else: 

89 # if the line isn't splittable, append it to the "__raw__" key 

90 info.setdefault("__raw__", []).append(line) 

91 

92 return info 

93 

94 

95def parse_memory_stats(response, **kwargs): 

96 """Parse the results of MEMORY STATS""" 

97 stats = pairs_to_dict(response, decode_keys=True, decode_string_values=True) 

98 for key, value in stats.items(): 

99 if key.startswith("db.") and isinstance(value, list): 

100 stats[key] = pairs_to_dict( 

101 value, decode_keys=True, decode_string_values=True 

102 ) 

103 return stats 

104 

105 

106def parse_memory_stats_unified(response, **kwargs): 

107 """Parse MEMORY STATS for unified RESP2 output. 

108 

109 Unified responses decode structural keys and use native numeric values. 

110 The RESP2 reply holds the ratios and percentages, such as 

111 ``fragmentation``, as bulk strings, while RESP3 sends doubles. Convert 

112 them to ``float`` so both wires give the same values; the integer 

113 replies, and any string that isn't a number, are left as they are. 

114 """ 

115 stats = pairs_to_dict(response, decode_keys=True) 

116 for key, value in stats.items(): 

117 if key.startswith("db.") and isinstance(value, list): 

118 stats[key] = pairs_to_dict(value, decode_keys=True) 

119 elif isinstance(value, (bytes, str)): 

120 try: 

121 stats[key] = float(value) 

122 except ValueError: 

123 pass 

124 return stats 

125 

126 

127def parse_memory_stats_resp3(response, **kwargs): 

128 """Parse the results of MEMORY STATS on RESP3 wire. 

129 

130 Each entry arrives as a top-level ``dict`` instead of a flat list of 

131 pairs; decode the keys to ``str`` and recurse into the per-database 

132 ``db.*`` sub-dicts so the Python shape matches what 

133 :func:`parse_memory_stats` produces from RESP2 wire. 

134 """ 

135 stats = {str_if_bytes(key): value for key, value in response.items()} 

136 for key, value in stats.items(): 

137 if key.startswith("db.") and isinstance(value, dict): 

138 stats[key] = {str_if_bytes(k): v for k, v in value.items()} 

139 return stats 

140 

141 

142def parse_list_of_dicts_resp3(response, **kwargs): 

143 """Parse list-of-maps responses on RESP3 wire (e.g. ``XINFO`` family). 

144 

145 Each list entry arrives as a ``dict`` with bytes keys; decode the 

146 keys to ``str`` so the Python shape matches what 

147 :func:`parse_list_of_dicts` produces from RESP2 wire. 

148 """ 

149 return [{str_if_bytes(key): value for key, value in x.items()} for x in response] 

150 

151 

152SENTINEL_STATE_TYPES = { 

153 "can-failover-its-master": int, 

154 "config-epoch": int, 

155 "down-after-milliseconds": int, 

156 "failover-timeout": int, 

157 "info-refresh": int, 

158 "last-hello-message": int, 

159 "last-ok-ping-reply": int, 

160 "last-ping-reply": int, 

161 "last-ping-sent": int, 

162 "master-link-down-time": int, 

163 "master-port": int, 

164 "num-other-sentinels": int, 

165 "num-slaves": int, 

166 "o-down-time": int, 

167 "pending-commands": int, 

168 "parallel-syncs": int, 

169 "port": int, 

170 "quorum": int, 

171 "role-reported-time": int, 

172 "s-down-time": int, 

173 "slave-priority": int, 

174 "slave-repl-offset": int, 

175 "voted-leader-epoch": int, 

176} 

177 

178 

179_SENTINEL_DERIVED_BOOLEANS = ( 

180 ("is_master", "master"), 

181 ("is_slave", "slave"), 

182 ("is_sdown", "s_down"), 

183 ("is_odown", "o_down"), 

184 ("is_sentinel", "sentinel"), 

185 ("is_disconnected", "disconnected"), 

186 ("is_master_down", "master_down"), 

187) 

188 

189 

190def _add_derived_sentinel_booleans(result, flags): 

191 """Set ``is_master`` / ``is_slave`` / ``is_sdown`` / ``is_odown`` / 

192 ``is_sentinel`` / ``is_disconnected`` / ``is_master_down`` on 

193 ``result`` based on membership in the ``flags`` set. 

194 """ 

195 for name, flag in _SENTINEL_DERIVED_BOOLEANS: 

196 result[name] = flag in flags 

197 

198 

199def parse_sentinel_state(item): 

200 result = pairs_to_dict_typed(item, SENTINEL_STATE_TYPES) 

201 flags = set(result["flags"].split(",")) 

202 _add_derived_sentinel_booleans(result, flags) 

203 return result 

204 

205 

206def parse_sentinel_master(response, **options): 

207 return parse_sentinel_state(map(str_if_bytes, response)) 

208 

209 

210def parse_sentinel_state_resp3(response, **options): 

211 result = {} 

212 for key in response: 

213 str_key = str_if_bytes(key) 

214 try: 

215 value = SENTINEL_STATE_TYPES[str_key](str_if_bytes(response[key])) 

216 result[str_key] = value 

217 except Exception: 

218 result[str_key] = str_if_bytes(response[key]) 

219 flags = set(result["flags"].split(",")) 

220 result["flags"] = flags 

221 _add_derived_sentinel_booleans(result, flags) 

222 return result 

223 

224 

225def parse_sentinel_masters(response, **options): 

226 result = {} 

227 for item in response: 

228 state = parse_sentinel_state(map(str_if_bytes, item)) 

229 result[state["name"]] = state 

230 return result 

231 

232 

233def parse_sentinel_masters_resp3(response, **options): 

234 result = {} 

235 for master in response: 

236 state = parse_sentinel_state_resp3(master) 

237 result[state["name"]] = state 

238 return result 

239 

240 

241def parse_sentinel_slaves_and_sentinels(response, **options): 

242 return [parse_sentinel_state(map(str_if_bytes, item)) for item in response] 

243 

244 

245def parse_sentinel_slaves_and_sentinels_resp3(response, **options): 

246 return [parse_sentinel_state_resp3(item, **options) for item in response] 

247 

248 

249def _flatten_resp3_state_pairs(state): 

250 """Yield key/value pairs from a RESP3 sentinel-state map as a flat 

251 iterable suitable for ``parse_sentinel_state``. 

252 """ 

253 for key, value in state.items(): 

254 yield key 

255 yield value 

256 

257 

258def parse_sentinel_master_resp3_to_resp2_legacy(response, **options): 

259 return parse_sentinel_state(map(str_if_bytes, _flatten_resp3_state_pairs(response))) 

260 

261 

262def parse_sentinel_masters_resp3_to_resp2_legacy(response, **options): 

263 result = {} 

264 for master in response: 

265 state = parse_sentinel_state( 

266 map(str_if_bytes, _flatten_resp3_state_pairs(master)) 

267 ) 

268 result[state["name"]] = state 

269 return result 

270 

271 

272def parse_sentinel_slaves_and_sentinels_resp3_to_resp2_legacy(response, **options): 

273 return [ 

274 parse_sentinel_state(map(str_if_bytes, _flatten_resp3_state_pairs(item))) 

275 for item in response 

276 ] 

277 

278 

279def parse_sentinel_master_unified(response, **options): 

280 state = parse_sentinel_state(map(str_if_bytes, response)) 

281 state["flags"] = set(state["flags"].split(",")) 

282 return state 

283 

284 

285def parse_sentinel_masters_unified(response, **options): 

286 result = {} 

287 for item in response: 

288 state = parse_sentinel_state(map(str_if_bytes, item)) 

289 state["flags"] = set(state["flags"].split(",")) 

290 result[state["name"]] = state 

291 return result 

292 

293 

294def parse_sentinel_slaves_and_sentinels_unified(response, **options): 

295 out = [] 

296 for item in response: 

297 state = parse_sentinel_state(map(str_if_bytes, item)) 

298 state["flags"] = set(state["flags"].split(",")) 

299 out.append(state) 

300 return out 

301 

302 

303def parse_sentinel_master_unified_resp3(response, **options): 

304 state = parse_sentinel_state_resp3(response, **options) 

305 _add_derived_sentinel_booleans(state, state["flags"]) 

306 return state 

307 

308 

309def parse_sentinel_masters_unified_resp3(response, **options): 

310 result = {} 

311 for master in response: 

312 state = parse_sentinel_state_resp3(master) 

313 _add_derived_sentinel_booleans(state, state["flags"]) 

314 result[state["name"]] = state 

315 return result 

316 

317 

318def parse_sentinel_slaves_and_sentinels_unified_resp3(response, **options): 

319 out = [] 

320 for item in response: 

321 state = parse_sentinel_state_resp3(item, **options) 

322 _add_derived_sentinel_booleans(state, state["flags"]) 

323 out.append(state) 

324 return out 

325 

326 

327def parse_sentinel_get_master(response, **options): 

328 return response and (response[0], int(response[1])) or None 

329 

330 

331def pairs_to_dict(response, decode_keys=False, decode_string_values=False): 

332 """Create a dict given a list of key/value pairs""" 

333 if response is None: 

334 return {} 

335 if decode_keys or decode_string_values: 

336 # the iter form is faster, but I don't know how to make that work 

337 # with a str_if_bytes() map 

338 keys = response[::2] 

339 if decode_keys: 

340 keys = map(str_if_bytes, keys) 

341 values = response[1::2] 

342 if decode_string_values: 

343 values = map(str_if_bytes, values) 

344 return dict(zip(keys, values)) 

345 else: 

346 it = iter(response) 

347 return dict(zip(it, it)) 

348 

349 

350def pairs_to_dict_typed(response, type_info): 

351 it = iter(response) 

352 result = {} 

353 for key, value in zip(it, it): 

354 if key in type_info: 

355 try: 

356 value = type_info[key](value) 

357 except Exception: 

358 # if for some reason the value can't be coerced, just use 

359 # the string value 

360 pass 

361 result[key] = value 

362 return result 

363 

364 

365def _wrap_score_cast_func(score_cast_func): 

366 """Wrap score_cast_func to handle scientific notation in RESP2 byte strings. 

367 

368 Redis returns scores as byte strings in RESP2, and large numbers may use 

369 scientific notation (e.g., b'1.7732526297292595e+18'). Python's int() cannot 

370 parse scientific notation directly. Rather than unconditionally routing 

371 through float() (which would change the input type for every custom 

372 callable), we try the original function first and only fall back to 

373 converting through float() on ValueError. 

374 """ 

375 if score_cast_func is float: 

376 return score_cast_func 

377 

378 def _safe_cast(x): 

379 try: 

380 return score_cast_func(x) 

381 except (ValueError, TypeError): 

382 return score_cast_func(float(x)) 

383 

384 return _safe_cast 

385 

386 

387def zset_score_pairs(response, **options): 

388 """ 

389 If ``withscores`` is specified in the options, return the response as 

390 a list of (value, score) pairs 

391 """ 

392 if not response or not options.get("withscores"): 

393 return response 

394 score_cast_func = _wrap_score_cast_func(options.get("score_cast_func", float)) 

395 it = iter(response) 

396 return list(zip(it, map(score_cast_func, it))) 

397 

398 

399def zpop_score_pairs(response, **options): 

400 """RESP2-wire ZPOPMAX/ZPOPMIN -> legacy ``list[(member, score), ...]``. 

401 

402 ZPOPMAX/ZPOPMIN always include scores, so this parser intentionally 

403 does not depend on a ``withscores`` option. 

404 """ 

405 if not response: 

406 return response 

407 score_cast_func = _wrap_score_cast_func(options.get("score_cast_func", float)) 

408 it = iter(response) 

409 return list(zip(it, map(score_cast_func, it))) 

410 

411 

412def zset_score_for_rank(response, **options): 

413 """ 

414 If ``withscores`` is specified in the options, return the response as 

415 a [value, score] pair 

416 """ 

417 if not response or not options.get("withscore"): 

418 return response 

419 score_cast_func = _wrap_score_cast_func(options.get("score_cast_func", float)) 

420 return [response[0], score_cast_func(response[1])] 

421 

422 

423def zset_score_pairs_resp3(response, **options): 

424 """ 

425 If ``withscores`` is specified in the options, return the response as 

426 a list of [value, score] pairs 

427 """ 

428 if not response or not options.get("withscores"): 

429 return response 

430 score_cast_func = options.get("score_cast_func", float) 

431 return [[name, score_cast_func(val)] for name, val in response] 

432 

433 

434def zset_score_for_rank_resp3(response, **options): 

435 """ 

436 If ``withscores`` is specified in the options, return the response as 

437 a [value, score] pair 

438 """ 

439 if not response or not options.get("withscore"): 

440 return response 

441 score_cast_func = options.get("score_cast_func", float) 

442 return [response[0], score_cast_func(response[1])] 

443 

444 

445def _score_to_resp2_bytes(value): 

446 """Re-encode a score back to the bytes form Redis returns on the RESP2 

447 wire so that custom ``score_cast_func`` callables observe the same 

448 input type they would receive on a RESP2 connection when the wire 

449 protocol is RESP3 but legacy response shapes are requested. 

450 """ 

451 if isinstance(value, bytes): 

452 return value 

453 if isinstance(value, str): 

454 return value.encode() 

455 if isinstance(value, bool): 

456 return b"1" if value else b"0" 

457 return _redis_double_to_string(float(value)).encode() 

458 

459 

460def _score_to_resp2_reply(value, decode): 

461 """Like ``_score_to_resp2_bytes`` but returns ``str`` when the client 

462 decodes responses, as the RESP2 parser does with ``decode_responses=True``. 

463 """ 

464 if not decode: 

465 return _score_to_resp2_bytes(value) 

466 if isinstance(value, str): 

467 return value 

468 if isinstance(value, bytes): 

469 return value.decode() 

470 if isinstance(value, bool): 

471 return "1" if value else "0" 

472 return _redis_double_to_string(float(value)) 

473 

474 

475def _redis_double_to_string(value): 

476 """Format a double the way Redis does in replies (``d2string``). 

477 

478 Redis writes integral values in the 64-bit range as plain integers and 

479 everything else with the shortest round-trip digits (``fpconv_dtoa``), 

480 e.g. ``0.1`` and not ``0.10000000000000001``. 

481 """ 

482 if math.isinf(value): 

483 return "inf" if value > 0 else "-inf" 

484 if value == 0: 

485 return "-0" if math.copysign(1.0, value) < 0 else "0" 

486 if -(2**62) <= value <= 2**62 and value.is_integer(): 

487 return str(int(value)) 

488 # repr() gives the shortest digits that round-trip; lay them out with 

489 # the same rules as fpconv's emit_digits(). 

490 text = repr(value) 

491 sign = "" 

492 if text[0] == "-": 

493 sign, text = "-", text[1:] 

494 mantissa, _, exponent = text.partition("e") 

495 int_part, _, frac = mantissa.partition(".") 

496 if not exponent: 

497 # repr() is plain decimal; Redis prints it the same way unless it 

498 # has 7+ fractional digits and a decimal exponent of 4 or more. 

499 if int_part != "0": 

500 exp = len(int_part) - 1 

501 else: 

502 exp = len(frac) - len(frac.lstrip("0")) + 1 

503 if len(frac) < 7 or exp < 4: 

504 return sign + text 

505 digits = (int_part + frac).lstrip("0") 

506 k = int(exponent or 0) - len(frac) 

507 stripped = digits.rstrip("0") 

508 k += len(digits) - len(stripped) 

509 digits = stripped 

510 ndigits = len(digits) 

511 exp = abs(k + ndigits - 1) 

512 if k >= 0 and exp < ndigits + 7: 

513 out = digits + "0" * k 

514 elif k < 0 and (k > -7 or exp < 4): 

515 offset = ndigits + k 

516 if offset <= 0: 

517 out = "0." + "0" * -offset + digits 

518 else: 

519 out = digits[:offset] + "." + digits[offset:] 

520 else: 

521 out = digits[0] + ("." + digits[1:] if ndigits > 1 else "") 

522 out += f"e{'-' if k + ndigits - 1 < 0 else '+'}{exp}" 

523 return sign + out 

524 

525 

526def zset_score_pairs_resp3_to_resp2_legacy(response, **options): 

527 """Convert RESP3 nested ``[[member, score], ...]`` to today's RESP2 

528 ``list[(member, score)]`` shape: tuples instead of lists, scores 

529 re-encoded to bytes (``str`` when the client decodes responses) before 

530 being passed to ``score_cast_func`` so the cast receives the same input 

531 as on a RESP2 connection. 

532 """ 

533 if not response or not options.get("withscores"): 

534 return response 

535 score_cast_func = options.get("score_cast_func", float) 

536 if score_cast_func is float: 

537 return [(member, float(score)) for member, score in response] 

538 score_cast_func = _wrap_score_cast_func(score_cast_func) 

539 # Members are str exactly when the client decodes responses. 

540 decode = isinstance(response[0][0], str) 

541 return [ 

542 (member, score_cast_func(_score_to_resp2_reply(score, decode))) 

543 for member, score in response 

544 ] 

545 

546 

547def zset_score_pairs_resp3_to_resp2_legacy_flat(response, **options): 

548 """Convert RESP3 nested ``[[member, score], ...]`` to the flat raw RESP2 

549 wire shape ``[member, score_bytes, ...]`` used by ZDIFF in v8.0.0b1 

550 (scores are ``str`` when the client decodes responses). 

551 

552 ZDIFF historically did not propagate ``withscores`` to the response 

553 callback, so the legacy RESP2 callback was a no-op and the raw flat 

554 wire response was returned to the user. This helper reproduces that 

555 shape on RESP3 wires so ``legacy_responses=True`` keeps emitting the 

556 same Python value regardless of the underlying protocol. 

557 """ 

558 if not response or not options.get("withscores"): 

559 return response 

560 decode = isinstance(response[0][0], str) 

561 flat = [] 

562 for member, score in response: 

563 flat.append(member) 

564 flat.append(_score_to_resp2_reply(score, decode)) 

565 return flat 

566 

567 

568def zset_score_for_rank_resp3_to_resp2_legacy(response, **options): 

569 """RESP3-wire ZRANK/ZREVRANK WITHSCORE → legacy RESP2 ``[rank, score]``. 

570 

571 The shape ``[rank, score]`` is identical between RESP2 and RESP3; only 

572 the score is re-encoded to bytes (``str`` when ``decode_responses`` is 

573 passed as true) before being passed to ``score_cast_func`` so the cast 

574 observes the same input type it would on a RESP2 connection. 

575 """ 

576 if not response or not options.get("withscore"): 

577 return response 

578 score_cast_func = options.get("score_cast_func", float) 

579 if score_cast_func is float: 

580 return [response[0], float(response[1])] 

581 score_cast_func = _wrap_score_cast_func(score_cast_func) 

582 # The reply has no member to tell whether the client decodes responses, 

583 # so ZRANK/ZREVRANK pass ``decode_responses`` in the options. 

584 decode = options.get("decode_responses", False) 

585 return [response[0], score_cast_func(_score_to_resp2_reply(response[1], decode))] 

586 

587 

588def zset_score_pairs_unified(response, **options): 

589 """RESP2-wire WITHSCORES → unified ``list[[member, score], ...]``. 

590 

591 Normalises RESP2 byte-string scores through ``float`` before applying 

592 ``score_cast_func`` so the cast receives the same input type as on a 

593 RESP3 connection. 

594 """ 

595 if not response or not options.get("withscores"): 

596 return response 

597 score_cast_func = _wrap_score_cast_func(options.get("score_cast_func", float)) 

598 it = iter(response) 

599 return [[val, score_cast_func(float(score))] for val, score in zip(it, it)] 

600 

601 

602def zset_score_for_rank_unified(response, **options): 

603 """RESP2-wire ZRANK/ZREVRANK WITHSCORE → unified ``[rank, score]``. 

604 

605 Normalises the RESP2 byte-string score through ``float`` before 

606 applying ``score_cast_func`` so the cast receives the same input type 

607 as on a RESP3 connection. 

608 """ 

609 if not response or not options.get("withscore"): 

610 return response 

611 score_cast_func = _wrap_score_cast_func(options.get("score_cast_func", float)) 

612 return [response[0], score_cast_func(float(response[1]))] 

613 

614 

615def zpop_score_pairs_unified(response, **options): 

616 """RESP2-wire ZPOPMAX/ZPOPMIN → unified ``list[[member, score], ...]``. 

617 

618 ZPOPMAX/ZPOPMIN always include scores; no ``withscores`` gate is 

619 required. Scores are normalised through ``float`` before applying 

620 ``score_cast_func`` for parity with RESP3. 

621 """ 

622 if not response: 

623 return response 

624 score_cast_func = _wrap_score_cast_func(options.get("score_cast_func", float)) 

625 it = iter(response) 

626 return [[val, score_cast_func(float(score))] for val, score in zip(it, it)] 

627 

628 

629def zpop_score_pairs_resp3_unified(response, **options): 

630 """RESP3-wire ZPOPMAX/ZPOPMIN → unified ``list[[member, score], ...]``. 

631 

632 Without ``count`` RESP3 returns a flat ``[member, score]``; with 

633 ``count`` it returns a nested ``[[member, score], ...]``. Both shapes 

634 are normalised to a nested list with ``score_cast_func`` applied. 

635 """ 

636 if not response: 

637 return response 

638 score_cast_func = options.get("score_cast_func", float) 

639 if isinstance(response[0], list): 

640 return [[name, score_cast_func(val)] for name, val in response] 

641 return [[response[0], score_cast_func(response[1])]] 

642 

643 

644def zpop_score_pairs_resp3_to_resp2_legacy(response, **options): 

645 """RESP3-wire ZPOPMAX/ZPOPMIN → legacy RESP2 ``list[(member, score), ...]``. 

646 

647 Both RESP3 shapes (flat without ``count``; nested with ``count``) are 

648 converted to a list of tuples. Scores are re-encoded to bytes (``str`` 

649 when the client decodes responses) before being passed to 

650 ``score_cast_func`` so the cast observes the same input type it would 

651 on a RESP2 connection. 

652 """ 

653 if not response: 

654 return response 

655 score_cast_func = options.get("score_cast_func", float) 

656 if score_cast_func is float: 

657 if isinstance(response[0], list): 

658 return [(member, float(score)) for member, score in response] 

659 return [(response[0], float(response[1]))] 

660 score_cast_func = _wrap_score_cast_func(score_cast_func) 

661 if isinstance(response[0], list): 

662 decode = isinstance(response[0][0], str) 

663 return [ 

664 (member, score_cast_func(_score_to_resp2_reply(score, decode))) 

665 for member, score in response 

666 ] 

667 decode = isinstance(response[0], str) 

668 return [(response[0], score_cast_func(_score_to_resp2_reply(response[1], decode)))] 

669 

670 

671def bzpop_score_unified(response, **options): 

672 """BZPOPMAX/BZPOPMIN → unified ``[key, member, score]``. 

673 

674 Works for both RESP2 (bytes score) and RESP3 (float score) wire shapes. 

675 """ 

676 if not response: 

677 return None 

678 return [response[0], response[1], float(response[2])] 

679 

680 

681def bzpop_score_resp3_to_resp2_legacy(response, **options): 

682 """RESP3-wire BZPOPMAX/BZPOPMIN → legacy RESP2 ``(key, member, score)``. 

683 

684 Matches the v8.0.0b1 RESP2-wire callback shape (tuple, ``float`` score). 

685 """ 

686 if not response: 

687 return None 

688 return (response[0], response[1], float(response[2])) 

689 

690 

691def zmpop_resp3_to_resp2_legacy(response, **options): 

692 """RESP3-wire ZMPOP/BZMPOP → legacy RESP2 ``[name, [[member, b"score"], ...]]``. 

693 

694 Re-encodes RESP3 native float scores back to the bytes form Redis 

695 returns on the RESP2 wire (``str`` when the client decodes responses) 

696 so callers observe today's RESP2 raw shape. 

697 """ 

698 if not response: 

699 return response 

700 decode = isinstance(response[0], str) 

701 return [ 

702 response[0], 

703 [ 

704 [member, _score_to_resp2_reply(score, decode)] 

705 for member, score in response[1] 

706 ], 

707 ] 

708 

709 

710def zmpop_unified(response, **options): 

711 """ZMPOP/BZMPOP → unified ``[name, [[member, float_score], ...]]``. 

712 

713 Used for the ``legacy_responses=False`` overlay on RESP2 wire to mirror 

714 RESP3's native float-score shape. 

715 """ 

716 if not response: 

717 return response 

718 return [ 

719 response[0], 

720 [[member, float(score)] for member, score in response[1]], 

721 ] 

722 

723 

724def parse_zmove(response, **options): 

725 """RESP2-wire ZMOVE/BZMOVE/ZMOVEMEMBER -> ``list[[member, float_score], ...]``. 

726 

727 The reply is a nested array of pairs on both wires; only the RESP2 bytes 

728 scores need converting to match RESP3's native float scores. The null 

729 reply (nothing moved) stays ``None``. The pairs are fresh lists built by 

730 the parser, so the scores are converted in place. 

731 """ 

732 if response is None: 

733 return None 

734 for pair in response: 

735 pair[1] = float(pair[1]) 

736 return response 

737 

738 

739def hrandfield_unified(response, **options): 

740 """RESP2-wire HRANDFIELD WITHVALUES → unified ``list[[field, value], ...]``. 

741 

742 Plain (no-values) responses — flat list of fields — pass through. 

743 The ``withvalues`` option (forwarded by the command method) selects the 

744 pairing branch so the no-values flat result is never misread. 

745 """ 

746 if not response or not options.get("withvalues"): 

747 return response 

748 if isinstance(response[0], list): 

749 return response 

750 it = iter(response) 

751 return [[field, value] for field, value in zip(it, it)] 

752 

753 

754def hrandfield_resp3_to_resp2_legacy(response, **options): 

755 """RESP3-wire HRANDFIELD WITHVALUES → legacy RESP2 flat ``[field, value, ...]``. 

756 

757 Plain (no-values) responses — flat list of fields — pass through. 

758 """ 

759 if not response or not options.get("withvalues"): 

760 return response 

761 if not isinstance(response[0], list): 

762 return response 

763 flat = [] 

764 for field, value in response: 

765 flat.append(field) 

766 flat.append(value) 

767 return flat 

768 

769 

770def parse_geopos_unified(response, **options): 

771 """GEOPOS → unified ``list[list[float, float] | None]``. 

772 

773 Used for the ``legacy_responses=False`` overlay on RESP2 wire to mirror 

774 RESP3's native ``list[list]`` shape. 

775 """ 

776 return [[float(ll[0]), float(ll[1])] if ll is not None else None for ll in response] 

777 

778 

779def parse_geopos_resp3_to_resp2_legacy(response, **options): 

780 """RESP3-wire GEOPOS → legacy RESP2 ``list[tuple(float, float) | None]``. 

781 

782 Matches today's RESP2-wire callback shape (tuple coordinates). 

783 """ 

784 return [(float(ll[0]), float(ll[1])) if ll is not None else None for ll in response] 

785 

786 

787def parse_lcs_idx_unified(response, **options): 

788 """LCS with IDX → unified ``dict``. 

789 

790 Used for the ``legacy_responses=False`` overlay on RESP2 wire to mirror 

791 RESP3's native ``dict`` shape. Non-IDX responses (``bytes`` / ``int``) 

792 pass through unchanged. 

793 """ 

794 if isinstance(response, list): 

795 it = iter(response) 

796 return {str_if_bytes(key): value for key, value in zip(it, it)} 

797 if isinstance(response, dict): 

798 return {str_if_bytes(key): value for key, value in response.items()} 

799 return response 

800 

801 

802def parse_lcs_idx_resp3_to_resp2_legacy(response, **options): 

803 """RESP3-wire LCS with IDX → legacy RESP2 flat list shape. 

804 

805 Reproduces today's RESP2 raw output (``[b"matches", [...], b"len", n]``). 

806 Non-IDX responses pass through unchanged. 

807 """ 

808 if not isinstance(response, dict): 

809 return response 

810 out: list = [] 

811 for key, value in response.items(): 

812 out.append(key) 

813 out.append(value) 

814 return out 

815 

816 

817def parse_client_trackinginfo_unified(response, **options): 

818 """CLIENT TRACKINGINFO → unified ``dict[str, Any]``. 

819 

820 Accepts either RESP2's flat ``[label, value, ...]`` list or RESP3's 

821 native ``dict`` and returns a ``dict`` with ``str`` keys. 

822 """ 

823 if isinstance(response, dict): 

824 data = {str_if_bytes(key): value for key, value in response.items()} 

825 else: 

826 data = { 

827 str_if_bytes(key): value 

828 for key, value in zip(response[::2], response[1::2]) 

829 } 

830 if "flags" in data: 

831 data["flags"] = [str_if_bytes(flag) for flag in data["flags"]] 

832 if "prefixes" in data: 

833 data["prefixes"] = [str_if_bytes(prefix) for prefix in data["prefixes"]] 

834 return data 

835 

836 

837def parse_client_trackinginfo_resp3_to_resp2_legacy(response, **options): 

838 """RESP3-wire CLIENT TRACKINGINFO → legacy RESP2 flat ``list``. 

839 

840 Mirrors today's RESP2-wire callback (``list(map(str_if_bytes, r))``): 

841 labels are decoded to ``str`` while values are preserved as-is. 

842 """ 

843 if not isinstance(response, dict): 

844 return list(map(str_if_bytes, response)) 

845 out: list = [] 

846 for key, value in response.items(): 

847 out.append(str_if_bytes(key)) 

848 out.append(value) 

849 return out 

850 

851 

852def sort_return_tuples(response, **options): 

853 """ 

854 If ``groups`` is specified, return the response as a list of 

855 n-element tuples with n being the value found in options['groups'] 

856 """ 

857 if not response or not options.get("groups"): 

858 return response 

859 n = options["groups"] 

860 return list(zip(*[response[i::n] for i in range(n)])) 

861 

862 

863def parse_stream_list(response, **options): 

864 if response is None: 

865 return None 

866 data = [] 

867 for r in response: 

868 if r is not None: 

869 if "claim_min_idle_time" in options: 

870 data.append((r[0], pairs_to_dict(r[1]), *r[2:])) 

871 else: 

872 data.append((r[0], pairs_to_dict(r[1]))) 

873 else: 

874 data.append((None, None)) 

875 return data 

876 

877 

878def pairs_to_dict_with_str_keys(response): 

879 return pairs_to_dict(response, decode_keys=True) 

880 

881 

882def parse_list_of_dicts(response): 

883 return list(map(pairs_to_dict_with_str_keys, response)) 

884 

885 

886def parse_xclaim(response, **options): 

887 if options.get("parse_justid", False): 

888 return response 

889 return parse_stream_list(response) 

890 

891 

892def parse_xautoclaim(response, **options): 

893 if options.get("parse_justid", False): 

894 return response[1] 

895 response[1] = parse_stream_list(response[1]) 

896 return response 

897 

898 

899def parse_arinfo(response, **options): 

900 if isinstance(response, list): 

901 return pairs_to_dict(response, decode_keys=True) 

902 return {str_if_bytes(k): v for k, v in response.items()} 

903 

904 

905def parse_xinfo_stream(response, **options): 

906 if isinstance(response, list): 

907 data = pairs_to_dict(response, decode_keys=True) 

908 else: 

909 data = {str_if_bytes(k): v for k, v in response.items()} 

910 if not options.get("full", False): 

911 first = data.get("first-entry") 

912 if first is not None and first[0] is not None: 

913 data["first-entry"] = (first[0], pairs_to_dict(first[1])) 

914 last = data["last-entry"] 

915 if last is not None and last[0] is not None: 

916 data["last-entry"] = (last[0], pairs_to_dict(last[1])) 

917 else: 

918 data["entries"] = {_id: pairs_to_dict(entry) for _id, entry in data["entries"]} 

919 if len(data["groups"]) > 0 and isinstance(data["groups"][0], list): 

920 data["groups"] = [ 

921 pairs_to_dict(group, decode_keys=True) for group in data["groups"] 

922 ] 

923 for g in data["groups"]: 

924 if g["consumers"] and g["consumers"][0] is not None: 

925 g["consumers"] = [ 

926 pairs_to_dict(c, decode_keys=True) for c in g["consumers"] 

927 ] 

928 else: 

929 data["groups"] = [ 

930 {str_if_bytes(k): v for k, v in group.items()} 

931 for group in data["groups"] 

932 ] 

933 for g in data["groups"]: 

934 if g["consumers"] and g["consumers"][0] is not None: 

935 g["consumers"] = [ 

936 {str_if_bytes(k): v for k, v in c.items()} 

937 for c in g["consumers"] 

938 ] 

939 return data 

940 

941 

942def parse_xread(response, **options): 

943 if response is None: 

944 return [] 

945 return [[r[0], parse_stream_list(r[1], **options)] for r in response] 

946 

947 

948def parse_xread_resp3(response, **options): 

949 if response is None: 

950 return {} 

951 return { 

952 key: [parse_stream_list(value, **options)] for key, value in response.items() 

953 } 

954 

955 

956def parse_xread_unified(response, **options): 

957 """XREAD/XREADGROUP → unified ``dict[stream, list[tuple[id, dict]]]``. 

958 

959 Accepts either RESP2 (``list[[stream, entries]]``) or RESP3 

960 (``dict[stream, entries]``) wire shape. Empty result is ``{}``. 

961 """ 

962 if not response: 

963 return {} 

964 if isinstance(response, dict): 

965 return { 

966 key: parse_stream_list(value, **options) for key, value in response.items() 

967 } 

968 return { 

969 stream: parse_stream_list(entries, **options) for stream, entries in response 

970 } 

971 

972 

973def parse_xread_resp3_to_resp2_legacy(response, **options): 

974 """RESP3-wire XREAD/XREADGROUP → legacy RESP2 ``list[[stream, entries]]``. 

975 

976 Empty result ``{}`` is converted to ``[]`` to match today's RESP2 shape. 

977 """ 

978 if not response: 

979 return [] 

980 return [ 

981 [key, parse_stream_list(value, **options)] for key, value in response.items() 

982 ] 

983 

984 

985def parse_xpending(response, **options): 

986 if options.get("parse_detail", False): 

987 return parse_xpending_range(response) 

988 consumers = [{"name": n, "pending": int(p)} for n, p in response[3] or []] 

989 return { 

990 "pending": response[0], 

991 "min": response[1], 

992 "max": response[2], 

993 "consumers": consumers, 

994 } 

995 

996 

997def parse_xpending_range(response): 

998 k = ("message_id", "consumer", "time_since_delivered", "times_delivered") 

999 return [dict(zip(k, r)) for r in response] 

1000 

1001 

1002def float_or_none(response): 

1003 if response is None: 

1004 return None 

1005 return float(response) 

1006 

1007 

1008def bool_ok(response, **options): 

1009 return str_if_bytes(response) == "OK" 

1010 

1011 

1012def parse_zadd(response, **options): 

1013 if response is None: 

1014 return None 

1015 if options.get("as_score"): 

1016 return float(response) 

1017 return int(response) 

1018 

1019 

1020def _parse_client_info_fields(value): 

1021 """Tokenize a single ``key=value`` client-info blob into a dict. 

1022 

1023 The server emits this space-separated format for each client in 

1024 ``CLIENT INFO`` and ``CLIENT LIST``, and inside ``ACL LOG`` entries. 

1025 Two quirks have to be preserved: a value may contain ``=`` (a client 

1026 name set to ``foo=bar``), so only the first ``=`` splits key from value; 

1027 and a value may contain spaces (a Unix-socket ``addr``/``laddr`` path 

1028 such as ``/tmp/redis sock/redis.sock``), so a token with no ``=`` is 

1029 reattached to the previous value. ``last_key is None`` guards the leading 

1030 and empty/whitespace-only cases, which yield an empty dict rather than 

1031 raising. 

1032 """ 

1033 fields = {} 

1034 last_key = None 

1035 for token in value.split(" "): 

1036 if "=" in token: 

1037 key, val = token.split("=", 1) 

1038 fields[key] = val 

1039 last_key = key 

1040 elif last_key is not None: 

1041 # A token without ``=`` continues the previous value, since a 

1042 # Unix-socket path may contain spaces. Empty tokens (from two or 

1043 # more consecutive spaces in the path) are reattached the same 

1044 # way, so a run of spaces round-trips verbatim instead of being 

1045 # collapsed. Tokens before the first ``key=`` (``last_key is 

1046 # None``, i.e. a leading space or an empty/whitespace-only blob) 

1047 # are dropped, yielding an empty dict rather than raising. 

1048 fields[last_key] += " " + token 

1049 return fields 

1050 

1051 

1052def parse_client_list(response, **options): 

1053 clients = _client_list_iter(response) 

1054 if options.pop("as_iter", False): 

1055 return clients 

1056 return list(clients) 

1057 

1058 

1059def _client_list_iter(response): 

1060 """ 

1061 Yield one CLIENT LIST record at a time instead of building the full 

1062 ``list[dict]`` up front, so a caller processing records one at a time 

1063 doesn't need all of them held in memory simultaneously. The full reply 

1064 is still buffered off the socket before this runs - that part is 

1065 unavoidable given how RESP bulk-string framing (and hiredis) works - 

1066 so this only trims the per-record dict/string overhead, not the raw 

1067 reply size. 

1068 

1069 Line boundaries are scanned for lazily (rather than via ``splitlines()``) 

1070 so the generator never materializes a list of all lines either - that 

1071 list would otherwise be held for the generator's whole lifetime, right 

1072 alongside the decoded reply, defeating the point of iterating. 

1073 """ 

1074 text = str_if_bytes(response) 

1075 # With decode_responses=False, str_if_bytes decodes a full copy of the 

1076 # reply. response is a parameter of this generator, so it stays alive 

1077 # in this frame for as long as the generator does; drop it once decoded 

1078 # so the original buffer doesn't sit alongside the decoded one for the 

1079 # whole iteration. 

1080 response = None 

1081 end = len(text) 

1082 start = 0 

1083 while start < end: 

1084 newline = text.find("\n", start) 

1085 if newline == -1: 

1086 newline = end 

1087 client_dict = _parse_client_info_fields(text[start:newline]) 

1088 start = newline + 1 

1089 if client_dict: 

1090 yield client_dict 

1091 

1092 

1093def parse_config_get(response, **options): 

1094 response = [str_if_bytes(i) if i is not None else None for i in response] 

1095 return response and pairs_to_dict(response) or {} 

1096 

1097 

1098def parse_config_get_resp3_to_resp2_legacy(response, **options): 

1099 """RESP3-wire CONFIG GET → today's RESP2 ``dict[str, str]`` shape. 

1100 

1101 On RESP3 the server returns a map; convert both keys and values via 

1102 ``str_if_bytes`` so callers using ``r.config_get()["timeout"]`` 

1103 keep working when the wire is RESP3 with ``legacy_responses=True``. 

1104 """ 

1105 if not response: 

1106 return {} 

1107 return { 

1108 str_if_bytes(key) if key is not None else None: ( 

1109 str_if_bytes(value) if value is not None else None 

1110 ) 

1111 for key, value in response.items() 

1112 } 

1113 

1114 

1115def parse_scan(response, **options): 

1116 cursor, r = response 

1117 return int(cursor), r 

1118 

1119 

1120def parse_hscan(response, **options): 

1121 cursor, r = response 

1122 no_values = options.get("no_values", False) 

1123 if no_values: 

1124 payload = r or [] 

1125 else: 

1126 payload = r and pairs_to_dict(r) or {} 

1127 return int(cursor), payload 

1128 

1129 

1130def parse_zscan(response, **options): 

1131 score_cast_func = _wrap_score_cast_func(options.get("score_cast_func", float)) 

1132 cursor, r = response 

1133 it = iter(r) 

1134 return int(cursor), list(zip(it, map(score_cast_func, it))) 

1135 

1136 

1137def parse_zscan_unified(response, **options): 

1138 score_cast_func = _wrap_score_cast_func(options.get("score_cast_func", float)) 

1139 cursor, r = response 

1140 it = iter(r) 

1141 return int(cursor), [ 

1142 [value, score_cast_func(float(score))] for value, score in zip(it, it) 

1143 ] 

1144 

1145 

1146def parse_zmscore(response, **options): 

1147 # zmscore: list of scores (double precision floating point number) or nil 

1148 return [float(score) if score is not None else None for score in response] 

1149 

1150 

1151def parse_increx_unified(response, **options): 

1152 """RESP2-wire INCREX -> unified ``[value, increment]``. 

1153 

1154 With ``BYFLOAT`` the RESP2 reply holds both numbers as bulk strings, 

1155 while RESP3 sends doubles. Convert the strings to ``float`` so both 

1156 wires give the same values; the integer replies of the default and 

1157 ``BYINT`` forms are left as they are. 

1158 """ 

1159 return [float(x) if isinstance(x, (bytes, str)) else x for x in response] 

1160 

1161 

1162def parse_slowlog_get(response, **options): 

1163 space = " " if options.get("decode_responses", False) else b" " 

1164 

1165 def parse_item(item): 

1166 result = {"id": item[0], "start_time": int(item[1]), "duration": int(item[2])} 

1167 # Redis Enterprise injects another entry at index [3], which has 

1168 # the complexity info (i.e. the value N in case the command has 

1169 # an O(N) complexity) instead of the command. 

1170 if isinstance(item[3], list): 

1171 result["command"] = space.join(item[3]) 

1172 

1173 # These fields are optional, depends on environment. 

1174 if len(item) >= 6: 

1175 result["client_address"] = item[4] 

1176 result["client_name"] = item[5] 

1177 else: 

1178 result["complexity"] = item[3] 

1179 result["command"] = space.join(item[4]) 

1180 

1181 # These fields are optional, depends on environment. 

1182 if len(item) >= 7: 

1183 result["client_address"] = item[5] 

1184 result["client_name"] = item[6] 

1185 

1186 return result 

1187 

1188 return [parse_item(item) for item in response] 

1189 

1190 

1191def parse_stralgo(response, **options): 

1192 """ 

1193 Parse the response from `STRALGO` command. 

1194 Without modifiers the returned value is string. 

1195 When LEN is given the command returns the length of the result 

1196 (i.e integer). 

1197 When IDX is given the command returns a dictionary with the LCS 

1198 length and all the ranges in both the strings, start and end 

1199 offset for each string, where there are matches. 

1200 When WITHMATCHLEN is given, each array representing a match will 

1201 also have the length of the match at the beginning of the array. 

1202 """ 

1203 if options.get("len", False): 

1204 return int(response) 

1205 if options.get("idx", False): 

1206 if options.get("withmatchlen", False): 

1207 matches = [ 

1208 [(int(match[-1]))] + list(map(tuple, match[:-1])) 

1209 for match in response[1] 

1210 ] 

1211 else: 

1212 matches = [list(map(tuple, match)) for match in response[1]] 

1213 return { 

1214 str_if_bytes(response[0]): matches, 

1215 str_if_bytes(response[2]): int(response[3]), 

1216 } 

1217 return str_if_bytes(response) 

1218 

1219 

1220def parse_stralgo_unified(response, **options): 

1221 """ 

1222 Parse STRALGO into the approved unified shape. 

1223 

1224 The legacy parser returns tuple ranges for IDX responses. Unified 

1225 responses use list ranges so RESP2 and RESP3 produce the same value. 

1226 """ 

1227 if options.get("len", False): 

1228 return int(response) 

1229 if options.get("idx", False): 

1230 if options.get("withmatchlen", False): 

1231 matches = [ 

1232 [int(match[-1])] + [list(m) for m in match[:-1]] 

1233 for match in response[1] 

1234 ] 

1235 else: 

1236 matches = [[list(m) for m in match] for match in response[1]] 

1237 return { 

1238 str_if_bytes(response[0]): matches, 

1239 str_if_bytes(response[2]): int(response[3]), 

1240 } 

1241 return str_if_bytes(response) 

1242 

1243 

1244def parse_stralgo_resp3_unified(response, **options): 

1245 """Parse RESP3 STRALGO into the same value as ``parse_stralgo_unified``.""" 

1246 if options.get("len", False): 

1247 return int(response) 

1248 if options.get("idx", False): 

1249 if not isinstance(response, dict): 

1250 return str_if_bytes(response) 

1251 raw_matches = response.get("matches", response.get(b"matches", [])) 

1252 raw_len = response.get("len", response.get(b"len", 0)) 

1253 if options.get("withmatchlen", False): 

1254 matches = [ 

1255 [int(match[-1])] + [list(m) for m in match[:-1]] 

1256 for match in raw_matches 

1257 ] 

1258 else: 

1259 matches = [[list(m) for m in match] for match in raw_matches] 

1260 return {"matches": matches, "len": int(raw_len)} 

1261 return str_if_bytes(response) 

1262 

1263 

1264def parse_cluster_info(response, **options): 

1265 response = str_if_bytes(response) 

1266 return dict(line.split(":") for line in response.splitlines() if line) 

1267 

1268 

1269def _parse_node_line(line): 

1270 line_items = line.split(" ") 

1271 node_id, addr, flags, master_id, ping, pong, epoch, connected = line.split(" ")[:8] 

1272 ip = addr.split("@")[0] 

1273 hostname = addr.split("@")[1].split(",")[1] if "@" in addr and "," in addr else "" 

1274 node_dict = { 

1275 "node_id": node_id, 

1276 "hostname": hostname, 

1277 "flags": flags, 

1278 "master_id": master_id, 

1279 "last_ping_sent": ping, 

1280 "last_pong_rcvd": pong, 

1281 "epoch": epoch, 

1282 "slots": [], 

1283 "migrations": [], 

1284 "connected": True if connected == "connected" else False, 

1285 } 

1286 if len(line_items) >= 9: 

1287 slots, migrations = _parse_slots(line_items[8:]) 

1288 node_dict["slots"], node_dict["migrations"] = slots, migrations 

1289 return ip, node_dict 

1290 

1291 

1292def _parse_slots(slot_ranges): 

1293 slots, migrations = [], [] 

1294 for s_range in slot_ranges: 

1295 if "->-" in s_range: 

1296 slot_id, dst_node_id = s_range[1:-1].split("->-", 1) 

1297 migrations.append( 

1298 {"slot": slot_id, "node_id": dst_node_id, "state": "migrating"} 

1299 ) 

1300 elif "-<-" in s_range: 

1301 slot_id, src_node_id = s_range[1:-1].split("-<-", 1) 

1302 migrations.append( 

1303 {"slot": slot_id, "node_id": src_node_id, "state": "importing"} 

1304 ) 

1305 else: 

1306 s_range = [sl for sl in s_range.split("-")] 

1307 slots.append(s_range) 

1308 

1309 return slots, migrations 

1310 

1311 

1312def parse_cluster_nodes(response, **options): 

1313 """ 

1314 @see: https://redis.io/commands/cluster-nodes # string / bytes 

1315 @see: https://redis.io/commands/cluster-replicas # list of string / bytes 

1316 """ 

1317 if isinstance(response, (str, bytes)): 

1318 response = response.splitlines() 

1319 return dict(_parse_node_line(str_if_bytes(node)) for node in response) 

1320 

1321 

1322def parse_geosearch_generic(response, **options): 

1323 """ 

1324 Parse the response of 'GEOSEARCH', GEORADIUS' and 'GEORADIUSBYMEMBER' 

1325 commands according to 'withdist', 'withhash' and 'withcoord' labels. 

1326 """ 

1327 try: 

1328 if options["store"] or options["store_dist"]: 

1329 # `store` and `store_dist` can't be combined 

1330 # with other command arguments. 

1331 # relevant to 'GEORADIUS' and 'GEORADIUSBYMEMBER' 

1332 return response 

1333 except KeyError: # it means the command was sent via execute_command 

1334 return response 

1335 

1336 if not isinstance(response, list): 

1337 response_list = [response] 

1338 else: 

1339 response_list = response 

1340 

1341 if not options["withdist"] and not options["withcoord"] and not options["withhash"]: 

1342 # just a bunch of places 

1343 return response_list 

1344 

1345 cast = { 

1346 "withdist": float, 

1347 "withcoord": lambda ll: (float(ll[0]), float(ll[1])), 

1348 "withhash": int, 

1349 } 

1350 

1351 # zip all output results with each casting function to get 

1352 # the properly native Python value. 

1353 f = [lambda x: x] 

1354 f += [cast[o] for o in ["withdist", "withhash", "withcoord"] if options[o]] 

1355 return [list(map(lambda fv: fv[0](fv[1]), zip(f, r))) for r in response_list] 

1356 

1357 

1358def parse_geosearch_generic_unified(response, **options): 

1359 """ 

1360 Parse GEOSEARCH/GEORADIUS responses using tuple coordinates. 

1361 """ 

1362 try: 

1363 if options["store"] or options["store_dist"]: 

1364 return response 

1365 except KeyError: 

1366 return response 

1367 

1368 response_list = response if isinstance(response, list) else [response] 

1369 

1370 if not options["withdist"] and not options["withcoord"] and not options["withhash"]: 

1371 return response_list 

1372 

1373 cast = { 

1374 "withdist": float, 

1375 "withcoord": lambda ll: (float(ll[0]), float(ll[1])), 

1376 "withhash": int, 

1377 } 

1378 funcs = [lambda x: x] 

1379 funcs += [cast[o] for o in ["withdist", "withhash", "withcoord"] if options[o]] 

1380 return [list(map(lambda fv: fv[0](fv[1]), zip(funcs, r))) for r in response_list] 

1381 

1382 

1383def parse_command(response, **options): 

1384 commands = {} 

1385 for command in response: 

1386 cmd_dict = {} 

1387 cmd_name = str_if_bytes(command[0]) 

1388 cmd_dict["name"] = cmd_name 

1389 cmd_dict["arity"] = int(command[1]) 

1390 cmd_dict["flags"] = [str_if_bytes(flag) for flag in command[2]] 

1391 cmd_dict["first_key_pos"] = command[3] 

1392 cmd_dict["last_key_pos"] = command[4] 

1393 cmd_dict["step_count"] = command[5] 

1394 if len(command) > 6: 

1395 cmd_dict["acl_categories"] = [ 

1396 str_if_bytes(category) for category in command[6] 

1397 ] 

1398 if len(command) > 7: 

1399 cmd_dict["tips"] = command[7] 

1400 cmd_dict["key_specifications"] = command[8] 

1401 cmd_dict["subcommands"] = command[9] 

1402 commands[cmd_name] = cmd_dict 

1403 return commands 

1404 

1405 

1406def parse_command_unified(response, **options): 

1407 commands = {} 

1408 for command in response: 

1409 cmd_dict = {} 

1410 cmd_name = str_if_bytes(command[0]) 

1411 cmd_dict["name"] = cmd_name 

1412 cmd_dict["arity"] = int(command[1]) 

1413 cmd_dict["flags"] = {str_if_bytes(flag) for flag in command[2]} 

1414 cmd_dict["first_key_pos"] = command[3] 

1415 cmd_dict["last_key_pos"] = command[4] 

1416 cmd_dict["step_count"] = command[5] 

1417 if len(command) > 6: 

1418 cmd_dict["acl_categories"] = {str_if_bytes(c) for c in command[6]} 

1419 if len(command) > 7: 

1420 cmd_dict["tips"] = command[7] 

1421 cmd_dict["key_specifications"] = command[8] 

1422 cmd_dict["subcommands"] = command[9] 

1423 commands[cmd_name] = cmd_dict 

1424 return commands 

1425 

1426 

1427def parse_command_resp3(response, **options): 

1428 commands = {} 

1429 for command in response: 

1430 cmd_dict = {} 

1431 cmd_name = str_if_bytes(command[0]) 

1432 cmd_dict["name"] = cmd_name 

1433 cmd_dict["arity"] = command[1] 

1434 cmd_dict["flags"] = {str_if_bytes(flag) for flag in command[2]} 

1435 cmd_dict["first_key_pos"] = command[3] 

1436 cmd_dict["last_key_pos"] = command[4] 

1437 cmd_dict["step_count"] = command[5] 

1438 cmd_dict["acl_categories"] = command[6] 

1439 if len(command) > 7: 

1440 cmd_dict["tips"] = command[7] 

1441 cmd_dict["key_specifications"] = command[8] 

1442 cmd_dict["subcommands"] = command[9] 

1443 

1444 commands[cmd_name] = cmd_dict 

1445 return commands 

1446 

1447 

1448def parse_pubsub_numsub(response, **options): 

1449 return list(zip(response[0::2], response[1::2])) 

1450 

1451 

1452def parse_client_kill(response, **options): 

1453 if isinstance(response, int): 

1454 return response 

1455 return str_if_bytes(response) == "OK" 

1456 

1457 

1458def parse_acl_getuser(response, **options): 

1459 if response is None: 

1460 return None 

1461 if isinstance(response, list): 

1462 data = pairs_to_dict(response, decode_keys=True) 

1463 else: 

1464 data = {str_if_bytes(key): value for key, value in response.items()} 

1465 

1466 # convert everything but user-defined data in 'keys' to native strings 

1467 data["flags"] = list(map(str_if_bytes, data["flags"])) 

1468 data["passwords"] = list(map(str_if_bytes, data["passwords"])) 

1469 data["commands"] = str_if_bytes(data["commands"]) 

1470 if isinstance(data["keys"], str) or isinstance(data["keys"], bytes): 

1471 data["keys"] = list(str_if_bytes(data["keys"]).split(" ")) 

1472 if data["keys"] == [""]: 

1473 data["keys"] = [] 

1474 if "channels" in data: 

1475 if isinstance(data["channels"], str) or isinstance(data["channels"], bytes): 

1476 data["channels"] = list(str_if_bytes(data["channels"]).split(" ")) 

1477 if data["channels"] == [""]: 

1478 data["channels"] = [] 

1479 if "selectors" in data: 

1480 if data["selectors"] != [] and isinstance(data["selectors"][0], list): 

1481 data["selectors"] = [ 

1482 list(map(str_if_bytes, selector)) for selector in data["selectors"] 

1483 ] 

1484 elif data["selectors"] != []: 

1485 data["selectors"] = [ 

1486 {str_if_bytes(k): str_if_bytes(v) for k, v in selector.items()} 

1487 for selector in data["selectors"] 

1488 ] 

1489 

1490 # split 'commands' into separate 'categories' and 'commands' lists 

1491 commands, categories = [], [] 

1492 for command in data["commands"].split(" "): 

1493 categories.append(command) if "@" in command else commands.append(command) 

1494 

1495 data["commands"] = commands 

1496 data["categories"] = categories 

1497 data["enabled"] = "on" in data["flags"] 

1498 return data 

1499 

1500 

1501def parse_acl_log(response, **options): 

1502 if response is None: 

1503 return None 

1504 if isinstance(response, list): 

1505 data = [] 

1506 for log in response: 

1507 log_data = pairs_to_dict(log, True, True) 

1508 client_info = log_data.get("client-info", "") 

1509 log_data["client-info"] = parse_client_info(client_info) 

1510 

1511 # float() is lossy comparing to the "double" in C 

1512 log_data["age-seconds"] = float(log_data["age-seconds"]) 

1513 data.append(log_data) 

1514 else: 

1515 data = bool_ok(response) 

1516 return data 

1517 

1518 

1519def parse_acl_log_resp3_to_resp2_legacy(response, **options): 

1520 """RESP3-wire ACL LOG → today's RESP2 parsed shape. 

1521 

1522 Each log entry arrives as a ``dict`` on RESP3 wire instead of a flat 

1523 list of pairs; convert ``client-info`` from a string blob into the 

1524 parsed ``dict`` and ``age-seconds`` to ``float`` so the Python shape 

1525 matches what :func:`parse_acl_log` produces from RESP2 wire. 

1526 

1527 Also used as the unified callback (Set D): the legacy and unified 

1528 shapes coincide for ACL LOG. 

1529 """ 

1530 if response is None: 

1531 return None 

1532 if not isinstance(response, list): 

1533 return bool_ok(response) 

1534 data = [] 

1535 for log in response: 

1536 if isinstance(log, dict): 

1537 log_data = {str_if_bytes(k): str_if_bytes(v) for k, v in log.items()} 

1538 else: 

1539 log_data = pairs_to_dict(log, True, True) 

1540 client_info = log_data.get("client-info", "") 

1541 log_data["client-info"] = parse_client_info(client_info) 

1542 log_data["age-seconds"] = float(log_data["age-seconds"]) 

1543 data.append(log_data) 

1544 return data 

1545 

1546 

1547def parse_acl_log_resp3_unified(response, **options): 

1548 """Parse RESP3 ACL LOG into the approved unified shape.""" 

1549 if response is None: 

1550 return None 

1551 if not isinstance(response, list): 

1552 return bool_ok(response) 

1553 data = [] 

1554 for entry in response: 

1555 if isinstance(entry, dict): 

1556 log_data = {str_if_bytes(k): v for k, v in entry.items()} 

1557 else: 

1558 log_data = pairs_to_dict(entry, True, True) 

1559 if "age-seconds" in log_data: 

1560 log_data["age-seconds"] = float(log_data["age-seconds"]) 

1561 if "client-info" in log_data: 

1562 log_data["client-info"] = parse_client_info(log_data["client-info"]) 

1563 for key, value in list(log_data.items()): 

1564 if key not in ("age-seconds", "client-info"): 

1565 log_data[key] = str_if_bytes(value) 

1566 data.append(log_data) 

1567 return data 

1568 

1569 

1570def parse_acl_getuser_unified(response, **options): 

1571 """ACL GETUSER → unified shape with selectors as ``list[dict]``. 

1572 

1573 On RESP2 wire each selector arrives as a flat ``[k, v, k, v, …]`` 

1574 list; pair them into dicts to match the RESP3 wire shape. 

1575 """ 

1576 data = parse_acl_getuser(response, **options) 

1577 if data is None: 

1578 return data 

1579 selectors = data.get("selectors") 

1580 if selectors and isinstance(selectors[0], list): 

1581 data["selectors"] = [ 

1582 dict(zip(selector[0::2], selector[1::2])) for selector in selectors 

1583 ] 

1584 return data 

1585 

1586 

1587def parse_acl_getuser_resp3_to_resp2_legacy(response, **options): 

1588 """RESP3-wire ACL GETUSER → today's RESP2 selectors as flat lists. 

1589 

1590 Each selector arrives as a ``dict`` on RESP3 wire; flatten back to 

1591 the interleaved ``[k, v, k, v, …]`` form produced by RESP2 wire. 

1592 """ 

1593 data = parse_acl_getuser(response, **options) 

1594 if data is None: 

1595 return data 

1596 selectors = data.get("selectors") 

1597 if selectors and isinstance(selectors[0], dict): 

1598 data["selectors"] = [ 

1599 [item for kv in selector.items() for item in kv] for selector in selectors 

1600 ] 

1601 return data 

1602 

1603 

1604def parse_client_info(value): 

1605 """ 

1606 Parsing client-info in ACL Log in following format. 

1607 "key1=value1 key2=value2 key3=value3" 

1608 """ 

1609 client_info = _parse_client_info_fields(str_if_bytes(value).strip()) 

1610 

1611 # Those fields are defined as int in networking.c 

1612 for int_key in { 

1613 "id", 

1614 "age", 

1615 "idle", 

1616 "db", 

1617 "sub", 

1618 "psub", 

1619 "multi", 

1620 "qbuf", 

1621 "qbuf-free", 

1622 "obl", 

1623 "argv-mem", 

1624 "oll", 

1625 "omem", 

1626 "tot-mem", 

1627 }: 

1628 if int_key in client_info: 

1629 client_info[int_key] = int(client_info[int_key]) 

1630 return client_info 

1631 

1632 

1633def parse_set_result(response, **options): 

1634 """ 

1635 Handle SET result since GET argument is available since Redis 6.2. 

1636 Parsing SET result into: 

1637 - BOOL 

1638 - String when GET argument is used 

1639 """ 

1640 if options.get("get"): 

1641 # Redis will return a getCommand result. 

1642 # See `setGenericCommand` in t_string.c 

1643 return response 

1644 return response and str_if_bytes(response) == "OK" 

1645 

1646 

1647def parse_function_list_unified(response, **options): 

1648 """FUNCTION LIST → unified ``list[dict]`` with bytes keys. 

1649 

1650 Accepts either RESP2 wire (``list[list]`` of flat ``[k, v, k, v, …]`` 

1651 pairs, with the nested ``b"functions"`` value also a flat list of 

1652 flat lists) or RESP3 wire (``list[dict]`` already in nested-map 

1653 form). Both are normalised to ``list[dict]``. 

1654 """ 

1655 if response is None: 

1656 return None 

1657 result = [] 

1658 for lib in response: 

1659 if isinstance(lib, dict): 

1660 result.append(lib) 

1661 continue 

1662 lib_dict = pairs_to_dict(lib) 

1663 func_key = b"functions" if b"functions" in lib_dict else "functions" 

1664 if func_key in lib_dict: 

1665 functions = lib_dict[func_key] 

1666 lib_dict[func_key] = [ 

1667 func if isinstance(func, dict) else pairs_to_dict(func) 

1668 for func in functions 

1669 ] 

1670 result.append(lib_dict) 

1671 return result 

1672 

1673 

1674def parse_function_list_resp3_to_resp2_legacy(response, **options): 

1675 """RESP3-wire FUNCTION LIST → today's RESP2 ``list[list]`` shape. 

1676 

1677 Each library and each nested function arrives as a ``dict``; flatten 

1678 them back to interleaved ``[k, v, k, v, …]`` lists so the Python 

1679 shape matches what RESP2 wire produces natively. 

1680 """ 

1681 if response is None: 

1682 return None 

1683 result = [] 

1684 for lib in response: 

1685 if not isinstance(lib, dict): 

1686 result.append(lib) 

1687 continue 

1688 flat = [] 

1689 for key, value in lib.items(): 

1690 flat.append(key) 

1691 if key == b"functions" or key == "functions": 

1692 flat.append( 

1693 [ 

1694 [item for kv in func.items() for item in kv] 

1695 if isinstance(func, dict) 

1696 else func 

1697 for func in value 

1698 ] 

1699 ) 

1700 else: 

1701 flat.append(value) 

1702 result.append(flat) 

1703 return result 

1704 

1705 

1706def parse_function_stats_unified(response, **options): 

1707 """FUNCTION STATS → unified nested ``dict`` with bytes keys. 

1708 

1709 Accepts either RESP2 wire (a flat ``[k, v, k, v, …]`` list whose 

1710 ``running_script`` value is a flat list or ``None`` and whose 

1711 ``engines`` value pairs each engine name with a flat list of its 

1712 stats) or RESP3 wire (nested maps). Both are normalised to nested 

1713 dicts. 

1714 """ 

1715 if response is None or isinstance(response, dict): 

1716 return response 

1717 stats = {} 

1718 it = iter(response) 

1719 for key, value in zip(it, it): 

1720 if isinstance(value, list): 

1721 name = str_if_bytes(key) 

1722 if name == "running_script": 

1723 value = pairs_to_dict(value) 

1724 elif name == "engines": 

1725 engines = iter(value) 

1726 value = { 

1727 engine: pairs_to_dict(engine_stats) 

1728 for engine, engine_stats in zip(engines, engines) 

1729 } 

1730 stats[key] = value 

1731 return stats 

1732 

1733 

1734def parse_function_stats_resp3_to_resp2_legacy(response, **options): 

1735 """RESP3-wire FUNCTION STATS → today's RESP2 flat ``list`` shape. 

1736 

1737 The reply, the running script and the stats of each engine each arrive 

1738 as a ``dict``; flatten them back to interleaved ``[k, v, k, v, …]`` 

1739 lists so the Python shape matches what RESP2 wire produces natively. 

1740 """ 

1741 if not isinstance(response, dict): 

1742 return response 

1743 flat = [] 

1744 for key, value in response.items(): 

1745 if isinstance(value, dict): 

1746 if str_if_bytes(key) == "engines": 

1747 engines = [] 

1748 for engine, engine_stats in value.items(): 

1749 if isinstance(engine_stats, dict): 

1750 engine_stats = [ 

1751 item for kv in engine_stats.items() for item in kv 

1752 ] 

1753 engines.append(engine) 

1754 engines.append(engine_stats) 

1755 value = engines 

1756 else: 

1757 value = [item for kv in value.items() for item in kv] 

1758 flat.append(key) 

1759 flat.append(value) 

1760 return flat 

1761 

1762 

1763def parse_cluster_links_unified(response, **options): 

1764 """CLUSTER LINKS → unified ``list[dict]`` with string keys. 

1765 

1766 Accepts either RESP2 wire (``list[list]`` of flat pairs) or RESP3 

1767 wire (``list[dict]``). Both are normalised to ``list[dict]``. 

1768 """ 

1769 if response is None: 

1770 return None 

1771 return [ 

1772 {str_if_bytes(k): v for k, v in item.items()} 

1773 if isinstance(item, dict) 

1774 else pairs_to_dict(item, decode_keys=True) 

1775 for item in response 

1776 ] 

1777 

1778 

1779def parse_cluster_links_resp3_to_resp2_legacy(response, **options): 

1780 """RESP3-wire CLUSTER LINKS → today's RESP2 ``list[list]`` shape. 

1781 

1782 Each link arrives as a ``dict`` with bytes keys; flatten back to 

1783 interleaved ``[k, v, k, v, …]`` lists so the Python shape matches 

1784 what RESP2 wire produces natively. 

1785 """ 

1786 if response is None: 

1787 return None 

1788 return [ 

1789 [item for kv in link.items() for item in kv] if isinstance(link, dict) else link 

1790 for link in response 

1791 ] 

1792 

1793 

1794def string_keys_to_dict(key_string, callback): 

1795 return dict.fromkeys(key_string.split(), callback) 

1796 

1797 

1798# The command-to-callback mapping dictionaries (``_RedisCallbacks``, 

1799# ``_RedisCallbacksRESP2``, ``_RedisCallbacksRESP3``, …) and the 

1800# ``get_response_callbacks`` selector live in 

1801# ``redis/_parsers/response_callbacks.py``. They are re-exported below for 

1802# backward compatibility so existing imports of the form 

1803# ``from redis._parsers.helpers import _RedisCallbacks`` keep working. The 

1804# import is placed at module bottom to avoid a circular import (the 

1805# response_callbacks module imports parser helpers defined above). 

1806# isort: off 

1807from .response_callbacks import ( # noqa: E402, F401 

1808 _RedisCallbacks, 

1809 _RedisCallbacksRESP2, 

1810 _RedisCallbacksRESP2Unified, 

1811 _RedisCallbacksRESP3, 

1812 _RedisCallbacksRESP3Unified, 

1813 _RedisCallbacksRESP3toRESP2Legacy, 

1814 get_response_callbacks, 

1815) 

1816# isort: on