Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/_parsers/commands.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

357 statements  

1from typing import ( 

2 TYPE_CHECKING, 

3 Any, 

4 Callable, 

5 Dict, 

6 Iterator, 

7 List, 

8 Optional, 

9 Set, 

10 Tuple, 

11 TypeVar, 

12 Union, 

13) 

14 

15from redis.commands.metadata import ( 

16 CommandMetadata, 

17 CommandMetadataRecordsCache, 

18 CommandPolicies, 

19 PolicyRecords, 

20 RequestPolicy, 

21 ResponsePolicy, 

22) 

23from redis.exceptions import ( 

24 DataError, 

25 IncorrectPolicyType, 

26 RedisError, 

27 ResponseError, 

28) 

29from redis.utils import deprecated_function, str_if_bytes 

30 

31if TYPE_CHECKING: 

32 from redis._parsers.encoders import Encoder 

33 from redis.asyncio.cluster import ClusterNode 

34 

35# The record type ``_build_command_records`` builds per command: policies or full metadata. 

36# Constrained to the two, rather than left open, so a ``to_record`` that builds anything else 

37# is a type error at the call site. 

38_RecordT = TypeVar("_RecordT", CommandPolicies, CommandMetadata) 

39 

40# Re-exported for backwards compatibility: these types used to be defined here and are 

41# now owned by ``redis.commands.metadata``. Import them from their new home instead. 

42__all__ = [ 

43 "AbstractCommandsParser", 

44 "AsyncCommandsParser", 

45 "CommandPolicies", 

46 "CommandsParser", 

47 "PolicyRecords", 

48 "RequestPolicy", 

49 "ResponsePolicy", 

50] 

51 

52 

53class AbstractCommandsParser: 

54 def _get_pubsub_keys(self, *args): 

55 """ 

56 Get the keys from pubsub command. 

57 Although PubSub commands have predetermined key locations, they are not 

58 supported in the 'COMMAND's output, so the key positions are hardcoded 

59 in this method 

60 """ 

61 if len(args) < 2: 

62 # The command has no keys in it 

63 return None 

64 args = [str_if_bytes(arg) for arg in args] 

65 command = args[0].upper() 

66 keys = None 

67 if command == "PUBSUB": 

68 # the second argument is a part of the command name, e.g. 

69 # ['PUBSUB', 'NUMSUB', 'foo']. 

70 pubsub_type = args[1].upper() 

71 if pubsub_type in ["CHANNELS", "NUMSUB", "SHARDCHANNELS", "SHARDNUMSUB"]: 

72 keys = args[2:] 

73 elif command in ["SUBSCRIBE", "PSUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE"]: 

74 # format example: 

75 # SUBSCRIBE channel [channel ...] 

76 keys = list(args[1:]) 

77 elif command in ["PUBLISH", "SPUBLISH"]: 

78 # format example: 

79 # PUBLISH channel message 

80 keys = [args[1]] 

81 return keys 

82 

83 def parse_subcommand(self, command, **options): 

84 return _parse_subcommand(command) 

85 

86 def _get_keys_from_specs(self, cmd_name, args): 

87 """ 

88 Find the keys of a movablekeys command from the key specs compiled in 

89 initialize(), the way the server does, which saves the COMMAND GETKEYS 

90 round trip. Returns None when the server has to be asked. 

91 """ 

92 compiled = self._movablekeys_specs.get(cmd_name) 

93 if compiled is None: 

94 return None 

95 arity, specs = compiled 

96 argc = len(args) 

97 # COMMAND GETKEYS rejects a wrong argument count before reading specs. 

98 if argc < abs(arity) or (arity > 0 and argc != arity): 

99 return None 

100 keys = [] 

101 for find_type, first, a, b, step in specs: 

102 if find_type == "range": 

103 lastkey, limit = a, b 

104 if lastkey >= 0: 

105 last = first + lastkey 

106 elif not limit: 

107 last = argc + lastkey 

108 else: 

109 last = first + (argc - first) // limit + lastkey 

110 else: 

111 keynumidx, firstkey = a, b 

112 if first + keynumidx >= argc: 

113 return None 

114 numkeys = _parse_numkeys(args[first + keynumidx], self._encoder) 

115 if numkeys is None or numkeys < 0: 

116 return None 

117 first += firstkey 

118 last = first + (numkeys - 1) * step 

119 if last < first: 

120 # No keys, as for the server; a negative slice end would wrap. 

121 continue 

122 if last >= argc: 

123 return None 

124 keys.extend(args[first : last + 1 : step]) 

125 return keys 

126 

127 

128def _parse_numkeys(value, encoder): 

129 """ 

130 The key count as the server reads it, or None for a value it rejects. 

131 Checks the bytes the client sends: int() also accepts "+2", " 2", "02", 

132 "2_0" and 2.5, and a str is sent in the client's encoding. 

133 """ 

134 try: 

135 raw = encoder.encode(value) 

136 except DataError: 

137 return None 

138 if not isinstance(raw, (bytes, bytearray)) or not raw.isdigit(): 

139 return None 

140 if len(raw) > 1 and raw.startswith(b"0"): 

141 return None 

142 # More digits than a signed 64-bit count; int() would also refuse 4300+. 

143 if len(raw) > 19: 

144 return None 

145 return int(raw) 

146 

147 

148def _compile_movablekeys_specs(commands): 

149 """ 

150 Compile every movablekeys command into an ``(arity, specs)`` pair that 

151 _get_keys_from_specs evaluates, or None where COMMAND GETKEYS has to be 

152 asked: no specs, a spec flagged incomplete or variable_flags (the server 

153 then ignores the specs too), or a search the client does not implement. 

154 """ 

155 compiled = {} 

156 for name, command in commands.items(): 

157 if "movablekeys" in command["flags"]: 

158 specs = _compile_key_specs(command.get("key_specifications")) 

159 if specs is not None: 

160 specs = (int(command["arity"]), specs) 

161 compiled[name] = specs 

162 return compiled 

163 

164 

165def _compile_key_specs(specs): 

166 if not specs: 

167 return None 

168 compiled = [] 

169 for spec in specs: 

170 flags = _key_spec_flags(spec) 

171 if "incomplete" in flags or "variable_flags" in flags: 

172 return None 

173 if "not_key" in flags: 

174 continue 

175 spec = _spec_dict(spec) 

176 begin = _spec_dict(spec.get("begin_search", ())) 

177 find = _spec_dict(spec.get("find_keys", ())) 

178 if str_if_bytes(begin.get("type")) != "index": 

179 return None 

180 first = _spec_dict(begin["spec"])["index"] 

181 find_type = str_if_bytes(find.get("type")) 

182 find_spec = _spec_dict(find.get("spec", ())) 

183 step = find_spec.get("keystep", 0) 

184 if first < 1 or step < 1: 

185 return None 

186 if find_type == "range": 

187 compiled.append( 

188 (find_type, first, find_spec["lastkey"], find_spec["limit"], step) 

189 ) 

190 elif find_type == "keynum": 

191 compiled.append( 

192 ( 

193 find_type, 

194 first, 

195 find_spec["keynumidx"], 

196 find_spec["firstkey"], 

197 step, 

198 ) 

199 ) 

200 else: 

201 return None 

202 return tuple(compiled) 

203 

204 

205def _spec_dict(spec): 

206 # RESP2 sends a key spec as a flat [name, value, ...] list, RESP3 as a map. 

207 if isinstance(spec, dict): 

208 return {str_if_bytes(k): v for k, v in spec.items()} 

209 return {str_if_bytes(k): v for k, v in zip(spec[::2], spec[1::2])} 

210 

211 

212class CommandsParser(AbstractCommandsParser): 

213 """ 

214 Parses Redis commands to get command keys. 

215 COMMAND output is used to determine key locations. 

216 Commands that do not have a predefined key location are flagged with 

217 'movablekeys'. Their keys are read from the command's key specs, and 

218 'COMMAND GETKEYS' is asked only when the specs are not enough. 

219 """ 

220 

221 def __init__(self, redis_connection): 

222 self.commands = {} 

223 self._movablekeys_specs = {} 

224 self._encoder = None 

225 self.redis_connection = redis_connection 

226 self.initialize(self.redis_connection) 

227 

228 def initialize(self, r): 

229 commands = r.command() 

230 uppercase_commands = [] 

231 for cmd in commands: 

232 if any(x.isupper() for x in cmd): 

233 uppercase_commands.append(cmd) 

234 for cmd in uppercase_commands: 

235 commands[cmd.lower()] = commands.pop(cmd) 

236 self.commands = commands 

237 self._movablekeys_specs = _compile_movablekeys_specs(commands) 

238 self._encoder = r.get_encoder() 

239 

240 # As soon as this PR is merged into Redis, we should reimplement 

241 # our logic to use COMMAND INFO changes to determine the key positions 

242 # https://github.com/redis/redis/pull/8324 

243 def get_keys(self, redis_conn, *args): 

244 """ 

245 Get the keys from the passed command. 

246 

247 NOTE: Due to a bug in redis<7.0, this function does not work properly 

248 for EVAL or EVALSHA when the `numkeys` arg is 0. 

249 - issue: https://github.com/redis/redis/issues/9493 

250 - fix: https://github.com/redis/redis/pull/9733 

251 

252 So, don't use this function with EVAL or EVALSHA. 

253 """ 

254 if len(args) < 2: 

255 # The command has no keys in it 

256 return None 

257 

258 cmd_name = args[0].lower() 

259 if cmd_name not in self.commands: 

260 # try to split the command name and to take only the main command, 

261 # e.g. 'memory' for 'memory usage' 

262 cmd_name_split = cmd_name.split() 

263 cmd_name = cmd_name_split[0] 

264 if cmd_name in self.commands: 

265 # save the split command to args 

266 args = cmd_name_split + list(args[1:]) 

267 else: 

268 # We'll try to reinitialize the commands cache, if the engine 

269 # version has changed, the commands may not be current 

270 self.initialize(redis_conn) 

271 if cmd_name not in self.commands: 

272 raise RedisError( 

273 f"{cmd_name.upper()} command doesn't exist in Redis commands" 

274 ) 

275 

276 command = self.commands.get(cmd_name) 

277 if "movablekeys" in command["flags"]: 

278 keys = self._get_keys_from_specs(cmd_name, args) 

279 if keys is None: 

280 keys = self._get_moveable_keys(redis_conn, *args) 

281 elif "pubsub" in command["flags"] or command["name"] == "pubsub": 

282 keys = self._get_pubsub_keys(*args) 

283 else: 

284 if ( 

285 command["step_count"] == 0 

286 and command["first_key_pos"] == 0 

287 and command["last_key_pos"] == 0 

288 ): 

289 is_subcmd = False 

290 if "subcommands" in command: 

291 subcmd_name = f"{cmd_name}|{args[1].lower()}" 

292 for subcmd in command["subcommands"]: 

293 if str_if_bytes(subcmd[0]) == subcmd_name: 

294 command = self.parse_subcommand(subcmd) 

295 

296 if command["first_key_pos"] > 0: 

297 is_subcmd = True 

298 

299 # The command doesn't have keys in it 

300 if not is_subcmd: 

301 return None 

302 last_key_pos = command["last_key_pos"] 

303 if last_key_pos < 0: 

304 last_key_pos = len(args) - abs(last_key_pos) 

305 keys_pos = list( 

306 range(command["first_key_pos"], last_key_pos + 1, command["step_count"]) 

307 ) 

308 keys = [args[pos] for pos in keys_pos] 

309 

310 return keys 

311 

312 def _get_moveable_keys(self, redis_conn, *args): 

313 """ 

314 NOTE: Due to a bug in redis<7.0, this function does not work properly 

315 for EVAL or EVALSHA when the `numkeys` arg is 0. 

316 - issue: https://github.com/redis/redis/issues/9493 

317 - fix: https://github.com/redis/redis/pull/9733 

318 

319 So, don't use this function with EVAL or EVALSHA. 

320 """ 

321 # The command name should be split into separate arguments, 

322 # e.g. 'MEMORY USAGE' will be split into ['MEMORY', 'USAGE'] 

323 pieces = args[0].split() + list(args[1:]) 

324 try: 

325 keys = redis_conn.execute_command("COMMAND GETKEYS", *pieces) 

326 except ResponseError as e: 

327 message = e.__str__() 

328 if ( 

329 "Invalid arguments" in message 

330 or "The command has no key arguments" in message 

331 ): 

332 return None 

333 else: 

334 raise e 

335 return keys 

336 

337 @deprecated_function( 

338 version="8.2.0", 

339 reason="Use get_commands_metadata_cache() instead.", 

340 ) 

341 def get_command_policies(self) -> PolicyRecords: 

342 """ 

343 Retrieve and process the command policies for all commands and subcommands. 

344 

345 DEPRECATED: use :meth:`get_commands_metadata_cache` instead. Nothing in this library calls this 

346 method any more, and it will be removed in a future release. A metadata resolver keeps a 

347 compatibility shim for an object that serves only this method, because it was the whole 

348 contract in 7.1.0; that shim is not an invitation to write one. To decide routing 

349 yourself, implement the public ``PolicyResolver`` ABC instead. 

350 

351 This method traverses through commands and subcommands, extracting policy details 

352 from associated data structures and constructing a dictionary of commands with their 

353 associated policies. It supports nested data structures and handles both main commands 

354 and their subcommands. 

355 

356 This is the routing view of :meth:`get_commands_metadata_cache`: the same traversal of the 

357 same reply, keyed the same way, projected down to the two policies the cluster client 

358 routes by. A caller that also needs the client-side-caching metadata asks for the 

359 metadata records instead. 

360 

361 Returns: 

362 PolicyRecords: A collection of commands and subcommands associated with their 

363 respective policies. 

364 

365 Raises: 

366 IncorrectPolicyType: If an invalid policy type is encountered during policy extraction. 

367 """ 

368 return _build_policy_records(self.commands) 

369 

370 def get_commands_metadata_cache(self) -> CommandMetadataRecordsCache: 

371 """ 

372 Retrieve and process the metadata records cache for all commands and subcommands. 

373 

374 This method normalizes the command flags, command tips and key metadata of the 

375 ``COMMAND`` output into metadata records, keyed the same way as the policy records 

376 that the deprecated ``get_command_policies`` returns. The routing policies each 

377 record carries are the ones that method resolves, so both views of the same reply 

378 stay in step. 

379 

380 Returns: 

381 CommandMetadataRecordsCache: A collection of commands and subcommands 

382 associated with their respective metadata. 

383 

384 Raises: 

385 IncorrectPolicyType: If an invalid policy type is encountered during policy extraction. 

386 """ 

387 return _build_commands_metadata_cache(self.commands) 

388 

389 

390class AsyncCommandsParser(AbstractCommandsParser): 

391 """ 

392 Parses Redis commands to get command keys. 

393 

394 COMMAND output is used to determine key locations. 

395 Commands that do not have a predefined key location are flagged with 'movablekeys'. 

396 Their keys are read from the command's key specs, and 'COMMAND GETKEYS' is asked 

397 only when the specs are not enough. 

398 

399 NOTE: Due to a bug in redis<7.0, this does not work properly 

400 for EVAL or EVALSHA when the `numkeys` arg is 0. 

401 - issue: https://github.com/redis/redis/issues/9493 

402 - fix: https://github.com/redis/redis/pull/9733 

403 

404 So, don't use this with EVAL or EVALSHA. 

405 """ 

406 

407 __slots__ = ("commands", "node", "_movablekeys_specs") 

408 

409 def __init__(self) -> None: 

410 self.commands: Dict[str, Union[int, Dict[str, Any]]] = {} 

411 self._movablekeys_specs: Dict[str, Optional[Tuple]] = {} 

412 self._encoder: Optional["Encoder"] = None 

413 

414 async def initialize(self, node: Optional["ClusterNode"] = None) -> None: 

415 if node: 

416 self.node = node 

417 

418 commands = await self.node.execute_command("COMMAND") 

419 self.commands = {cmd.lower(): command for cmd, command in commands.items()} 

420 self._movablekeys_specs = _compile_movablekeys_specs(self.commands) 

421 self._encoder = self.node.get_encoder() 

422 

423 # As soon as this PR is merged into Redis, we should reimplement 

424 # our logic to use COMMAND INFO changes to determine the key positions 

425 # https://github.com/redis/redis/pull/8324 

426 async def get_keys(self, *args: Any) -> Optional[Tuple[str, ...]]: 

427 """ 

428 Get the keys from the passed command. 

429 

430 NOTE: Due to a bug in redis<7.0, this function does not work properly 

431 for EVAL or EVALSHA when the `numkeys` arg is 0. 

432 - issue: https://github.com/redis/redis/issues/9493 

433 - fix: https://github.com/redis/redis/pull/9733 

434 

435 So, don't use this function with EVAL or EVALSHA. 

436 """ 

437 if len(args) < 2: 

438 # The command has no keys in it 

439 return None 

440 

441 cmd_name = args[0].lower() 

442 if cmd_name not in self.commands: 

443 # try to split the command name and to take only the main command, 

444 # e.g. 'memory' for 'memory usage' 

445 cmd_name_split = cmd_name.split() 

446 cmd_name = cmd_name_split[0] 

447 if cmd_name in self.commands: 

448 # save the split command to args 

449 args = cmd_name_split + list(args[1:]) 

450 else: 

451 # We'll try to reinitialize the commands cache, if the engine 

452 # version has changed, the commands may not be current 

453 await self.initialize() 

454 if cmd_name not in self.commands: 

455 raise RedisError( 

456 f"{cmd_name.upper()} command doesn't exist in Redis commands" 

457 ) 

458 

459 command = self.commands.get(cmd_name) 

460 if "movablekeys" in command["flags"]: 

461 keys = self._get_keys_from_specs(cmd_name, args) 

462 if keys is None: 

463 keys = await self._get_moveable_keys(*args) 

464 elif "pubsub" in command["flags"] or command["name"] == "pubsub": 

465 keys = self._get_pubsub_keys(*args) 

466 else: 

467 if ( 

468 command["step_count"] == 0 

469 and command["first_key_pos"] == 0 

470 and command["last_key_pos"] == 0 

471 ): 

472 is_subcmd = False 

473 if "subcommands" in command: 

474 subcmd_name = f"{cmd_name}|{args[1].lower()}" 

475 for subcmd in command["subcommands"]: 

476 if str_if_bytes(subcmd[0]) == subcmd_name: 

477 command = self.parse_subcommand(subcmd) 

478 

479 if command["first_key_pos"] > 0: 

480 is_subcmd = True 

481 

482 # The command doesn't have keys in it 

483 if not is_subcmd: 

484 return None 

485 last_key_pos = command["last_key_pos"] 

486 if last_key_pos < 0: 

487 last_key_pos = len(args) - abs(last_key_pos) 

488 keys_pos = list( 

489 range(command["first_key_pos"], last_key_pos + 1, command["step_count"]) 

490 ) 

491 keys = [args[pos] for pos in keys_pos] 

492 

493 return keys 

494 

495 async def _get_moveable_keys(self, *args: Any) -> Optional[Tuple[str, ...]]: 

496 try: 

497 keys = await self.node.execute_command("COMMAND GETKEYS", *args) 

498 except ResponseError as e: 

499 message = e.__str__() 

500 if ( 

501 "Invalid arguments" in message 

502 or "The command has no key arguments" in message 

503 ): 

504 return None 

505 else: 

506 raise e 

507 return keys 

508 

509 @deprecated_function( 

510 version="8.2.0", 

511 reason="Use get_commands_metadata_cache() instead.", 

512 ) 

513 async def get_command_policies(self) -> PolicyRecords: 

514 """ 

515 Retrieve and process the command policies for all commands and subcommands. 

516 

517 DEPRECATED: use :meth:`get_commands_metadata_cache` instead. Nothing in this library calls this 

518 method any more, and it will be removed in a future release. A metadata resolver keeps a 

519 compatibility shim for an object that serves only this method, because it was the whole 

520 contract in 7.1.0; that shim is not an invitation to write one. To decide routing 

521 yourself, implement the public ``PolicyResolver`` ABC instead. 

522 

523 This method traverses through commands and subcommands, extracting policy details 

524 from associated data structures and constructing a dictionary of commands with their 

525 associated policies. It supports nested data structures and handles both main commands 

526 and their subcommands. 

527 

528 This is the routing view of :meth:`get_commands_metadata_cache`: the same traversal of the 

529 same reply, keyed the same way, projected down to the two policies the cluster client 

530 routes by. A caller that also needs the client-side-caching metadata asks for the 

531 metadata records instead. 

532 

533 Returns: 

534 PolicyRecords: A collection of commands and subcommands associated with their 

535 respective policies. 

536 

537 Raises: 

538 IncorrectPolicyType: If an invalid policy type is encountered during policy extraction. 

539 """ 

540 return _build_policy_records(self.commands) 

541 

542 async def get_commands_metadata_cache(self) -> CommandMetadataRecordsCache: 

543 """ 

544 Retrieve and process the metadata records cache for all commands and subcommands. 

545 

546 This method normalizes the command flags, command tips and key metadata of the 

547 ``COMMAND`` output into metadata records, keyed the same way as the policy records 

548 that the deprecated ``get_command_policies`` returns. The routing policies each 

549 record carries are the ones that method resolves, so both views of the same reply 

550 stay in step. 

551 

552 Returns: 

553 CommandMetadataRecordsCache: A collection of commands and subcommands 

554 associated with their respective metadata. 

555 

556 Raises: 

557 IncorrectPolicyType: If an invalid policy type is encountered during policy extraction. 

558 """ 

559 return _build_commands_metadata_cache(self.commands) 

560 

561 

562# ============================================================================= 

563# Private helpers 

564# ============================================================================= 

565def _parse_subcommand(command: Any) -> Dict[str, Any]: 

566 """ 

567 Parse a single entry of a command's ``subcommands`` field into a details dict 

568 with the same shape as a top-level ``COMMAND`` entry. 

569 """ 

570 cmd_dict = {} 

571 cmd_name = str_if_bytes(command[0]) 

572 cmd_dict["name"] = cmd_name 

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

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

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

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

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

578 if len(command) > 7: 

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

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

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

582 return cmd_dict 

583 

584 

585def _is_keyless_command( 

586 commands: Dict[str, Any], 

587 command_name: str, 

588 subcommand_name: Optional[str] = None, 

589) -> bool: 

590 """ 

591 Determines whether a given command or subcommand is considered "keyless". 

592 

593 A keyless command does not operate on specific keys, which is determined based 

594 on the first key position in the command or subcommand details. If the command 

595 or subcommand's first key position is zero or negative, it is treated as keyless - 

596 unless it is flagged ``movablekeys`` and its key specs report a key argument. A 

597 ``movablekeys`` command reports ``first_key_pos == 0`` because its keys are found by 

598 scanning the arguments, so only the key specs say that it takes keys at all. 

599 

600 Parameters: 

601 commands: Dict[str, Any] 

602 The parsed ``COMMAND`` output to look the command up in. 

603 command_name: str 

604 The name of the command to check. 

605 subcommand_name: Optional[str], default=None 

606 The name of the subcommand to check, if applicable. If not provided, 

607 the check is performed only on the command. 

608 

609 Returns: 

610 bool 

611 True if the specified command or subcommand is considered keyless, 

612 False otherwise. 

613 

614 Raises: 

615 ValueError 

616 If the specified subcommand is not found within the command or the 

617 specified command does not exist in the available commands. 

618 """ 

619 if subcommand_name: 

620 for subcommand in commands.get(command_name)["subcommands"]: 

621 if str_if_bytes(subcommand[0]) == subcommand_name: 

622 return _is_keyless(_parse_subcommand(subcommand)) 

623 raise ValueError( 

624 f"Subcommand {subcommand_name} not found in command {command_name}" 

625 ) 

626 else: 

627 command_details = commands.get(command_name, None) 

628 if command_details is not None: 

629 return _is_keyless(command_details) 

630 

631 raise ValueError(f"Command {command_name} not found in commands") 

632 

633 

634def _is_keyless(details: Dict[str, Any]) -> bool: 

635 """ 

636 The keyless test of :func:`_is_keyless_command`, for one command's parsed details. 

637 

638 ``first_key_pos`` alone decides a command that reports it, so a command whose key specs 

639 are all ``not_key`` - SPUBLISH's shard channel - keeps routing by that argument's slot. 

640 """ 

641 if details["first_key_pos"] > 0: 

642 return False 

643 

644 return not ("movablekeys" in details["flags"] and _has_key_argument(details)) 

645 

646 

647# Slots of the two-element buffer ``_apply_policy_tips`` writes into. A list rather than a 

648# record, so one buffer can be reused for every command of a ``COMMAND`` reply instead of a 

649# policy object being allocated per command and thrown away. 

650_REQUEST_POLICY = 0 

651_RESPONSE_POLICY = 1 

652 

653 

654def _walk_tips(data: Any) -> Iterator[str]: 

655 """ 

656 Recursively yield every tip string of a ``COMMAND`` reply fragment, decoding bytes. 

657 

658 The one traversal both tip readers share, so the routing view and the metadata view 

659 cannot disagree about which structures a tip may be nested inside. That matters because a 

660 metadata record is the superset of a policy record: it carries the two routing policies 

661 plus the cacheability markers, so it has to read at least everything the policy view 

662 reads off the same field. 

663 

664 A ``COMMAND`` reply reports a command's ``tips`` as a flat array, but the fragments 

665 :func:`_apply_policy_tips` is handed for a container subcommand are whole reply entries, 

666 whose nested arrays and maps have to be walked. Anything that is neither a string, an 

667 array nor a map carries no tip and is skipped. 

668 

669 Args: 

670 data: The fragment to walk (can be list, dict, str, bytes, etc.) 

671 

672 Yields: 

673 Each tip string found, in reply order, so that a caller keeping only one value per 

674 slot ends up with the last one the reply carried. 

675 """ 

676 if isinstance(data, (str, bytes)): 

677 # Decode bytes to string if needed 

678 yield str_if_bytes(data) 

679 

680 elif isinstance(data, list): 

681 # For lists, recursively process each element 

682 for item in data: 

683 yield from _walk_tips(item) 

684 

685 elif isinstance(data, dict): 

686 # For dictionaries, recursively process each value 

687 for value in data.values(): 

688 yield from _walk_tips(value) 

689 

690 

691def _apply_policy_tips(policy_pair: List[Any], data: Any) -> None: 

692 """ 

693 Extract policies from nested data structures. 

694 

695 Args: 

696 policy_pair: The ``[request_policy, response_policy]`` buffer to update in place. 

697 The last policy tip found for a slot wins. 

698 data: The data structure to search, walked by :func:`_walk_tips`. 

699 

700 Raises: 

701 IncorrectPolicyType: If an invalid policy type is encountered. 

702 """ 

703 for policy in _walk_tips(data): 

704 # Check if this is a policy string 

705 if policy.startswith("request_policy"): 

706 policy_type = policy.split(":")[1] 

707 

708 try: 

709 policy_pair[_REQUEST_POLICY] = RequestPolicy(policy_type) 

710 except ValueError: 

711 raise IncorrectPolicyType( 

712 f"Incorrect request policy type: {policy_type}" 

713 ) 

714 

715 elif policy.startswith("response_policy"): 

716 policy_type = policy.split(":")[1] 

717 

718 try: 

719 policy_pair[_RESPONSE_POLICY] = ResponsePolicy(policy_type) 

720 except ValueError: 

721 raise IncorrectPolicyType( 

722 f"Incorrect response policy type: {policy_type}" 

723 ) 

724 

725 

726def _build_command_records( 

727 commands: Dict[str, Any], 

728 to_record: Callable[[Dict[str, Any], RequestPolicy, ResponsePolicy], _RecordT], 

729) -> Dict[str, Dict[str, _RecordT]]: 

730 """ 

731 Traverse a parsed ``COMMAND`` reply, resolving the policies of every command, and build 

732 one record per command with ``to_record``. 

733 

734 ``to_record`` is called once per command and once per container subcommand, with the 

735 command's details and its resolved policies. Policies start at the keyed or keyless 

736 defaults, chosen by whether the command takes keys, and are then overwritten by the 

737 ``request_policy`` and ``response_policy`` command tips. 

738 

739 This is the single traversal behind both the policy records and the metadata records, so 

740 the two are keyed identically by construction and the tips of a reply are walked once no 

741 matter which view a caller asks for. The policies are handed over as plain enum members, 

742 so the caller that wants a ``CommandPolicies`` record builds one and the caller that 

743 wants a ``CommandMetadata`` record is not charged for one it would discard. 

744 

745 Args: 

746 commands: The parsed ``COMMAND`` output to traverse. 

747 to_record: Builds the record for one command from its details and policies. 

748 

749 Returns: 

750 The records of every command and subcommand, keyed by module name, then by command 

751 name. 

752 

753 Raises: 

754 IncorrectPolicyType: If an invalid policy type is encountered during policy extraction. 

755 """ 

756 command_records: Dict[str, Dict[str, _RecordT]] = {} 

757 # Reused by every command below: the policies are read out of it before the next command 

758 # resets it, so no per-command buffer is allocated. 

759 policy_pair: List[Any] = [ 

760 RequestPolicy.DEFAULT_KEYLESS, 

761 ResponsePolicy.DEFAULT_KEYLESS, 

762 ] 

763 

764 for command, details in commands.items(): 

765 # Check whether the command has keys 

766 is_keyless = _is_keyless_command(commands, command) 

767 

768 if is_keyless: 

769 policy_pair[_REQUEST_POLICY] = RequestPolicy.DEFAULT_KEYLESS 

770 policy_pair[_RESPONSE_POLICY] = ResponsePolicy.DEFAULT_KEYLESS 

771 else: 

772 policy_pair[_REQUEST_POLICY] = RequestPolicy.DEFAULT_KEYED 

773 policy_pair[_RESPONSE_POLICY] = ResponsePolicy.DEFAULT_KEYED 

774 

775 module_name, command_name = _split_module_and_command(command) 

776 module_records = command_records.setdefault(module_name, {}) 

777 

778 tips = details.get("tips") 

779 subcommands = details.get("subcommands") 

780 

781 # Process tips for the main command 

782 if tips: 

783 _apply_policy_tips(policy_pair, tips) 

784 

785 module_records[command_name] = to_record( 

786 details, policy_pair[_REQUEST_POLICY], policy_pair[_RESPONSE_POLICY] 

787 ) 

788 

789 # Process subcommands 

790 if subcommands: 

791 for subcommand_details in subcommands: 

792 # Get the subcommand name (first element) 

793 subcmd_name = subcommand_details[0] 

794 if isinstance(subcmd_name, bytes): 

795 subcmd_name = subcmd_name.decode() 

796 

797 # Check whether the subcommand has keys 

798 is_keyless = _is_keyless_command(commands, command, subcmd_name) 

799 

800 if is_keyless: 

801 policy_pair[_REQUEST_POLICY] = RequestPolicy.DEFAULT_KEYLESS 

802 policy_pair[_RESPONSE_POLICY] = ResponsePolicy.DEFAULT_KEYLESS 

803 else: 

804 policy_pair[_REQUEST_POLICY] = RequestPolicy.DEFAULT_KEYED 

805 policy_pair[_RESPONSE_POLICY] = ResponsePolicy.DEFAULT_KEYED 

806 

807 # Container subcommands are keyed by their space-joined name, e.g. 

808 # ``memory usage``, which is the form ``execute_command`` receives. 

809 subcmd_name = subcmd_name.replace("|", " ") 

810 

811 # Recursively extract policies from the rest of the subcommand details 

812 for subcommand_detail in subcommand_details[1:]: 

813 _apply_policy_tips(policy_pair, subcommand_detail) 

814 

815 module_records[subcmd_name] = to_record( 

816 _parse_subcommand(subcommand_details), 

817 policy_pair[_REQUEST_POLICY], 

818 policy_pair[_RESPONSE_POLICY], 

819 ) 

820 

821 return command_records 

822 

823 

824def _to_command_policies( 

825 details: Dict[str, Any], 

826 request_policy: RequestPolicy, 

827 response_policy: ResponsePolicy, 

828) -> CommandPolicies: 

829 """Build the policy record for a single entry of a ``COMMAND`` reply.""" 

830 return CommandPolicies( 

831 request_policy=request_policy, response_policy=response_policy 

832 ) 

833 

834 

835def _build_policy_records(commands: Dict[str, Any]) -> PolicyRecords: 

836 """ 

837 Retrieve and process the command policies for all commands and subcommands. 

838 

839 This function traverses through commands and subcommands, extracting policy details 

840 from associated data structures and constructing a dictionary of commands with their 

841 associated policies. It supports nested data structures and handles both main commands 

842 and their subcommands. 

843 

844 Args: 

845 commands: The parsed ``COMMAND`` output to build the policy records from. 

846 

847 Returns: 

848 PolicyRecords: A collection of commands and subcommands associated with their 

849 respective policies. 

850 

851 Raises: 

852 IncorrectPolicyType: If an invalid policy type is encountered during policy extraction. 

853 """ 

854 return _build_command_records(commands, _to_command_policies) 

855 

856 

857def _split_module_and_command(command: str) -> Tuple[str, str]: 

858 """ 

859 Split a name from a ``COMMAND`` reply into the ``(module, command)`` pair the record 

860 tables are keyed by. Non-module commands live under ``"core"``. 

861 """ 

862 split_name = command.split(".") 

863 

864 if len(split_name) > 1: 

865 return split_name[0], split_name[1] 

866 

867 return "core", split_name[0] 

868 

869 

870def _key_spec_flags(key_spec: Any) -> Set[str]: 

871 """ 

872 The flags of a single key specification. 

873 

874 RESP3 reports a key spec as a map and RESP2 as a flat ``[name, value, ...]`` sequence, 

875 so both shapes are read here. 

876 """ 

877 if isinstance(key_spec, dict): 

878 flags = key_spec.get(b"flags") or key_spec.get("flags") or () 

879 else: 

880 flags = () 

881 for index in range(0, len(key_spec) - 1, 2): 

882 if str_if_bytes(key_spec[index]) == "flags": 

883 flags = key_spec[index + 1] 

884 break 

885 

886 return {str_if_bytes(flag) for flag in flags} 

887 

888 

889def _has_key_argument(details: Dict[str, Any]) -> bool: 

890 """ 

891 Whether the command accepts at least one Redis key name argument. 

892 

893 Key specs decide it whenever the server reports them, including for ``movablekeys`` 

894 commands, whose keys are not discoverable from the legacy positions at all. A spec 

895 flagged ``not_key`` describes an argument that is not a key name, such as a shard 

896 pubsub channel, so a command whose every spec is ``not_key`` takes no keys. 

897 

898 Only a server that reports no key specs falls back to the legacy positions. 

899 ``last_key_pos`` is never consulted: it is ``-1`` for variadic commands whose key 

900 arguments run to the end of the argument list, and must not disqualify one. 

901 """ 

902 key_specs = details.get("key_specifications") 

903 

904 if key_specs: 

905 return any("not_key" not in _key_spec_flags(spec) for spec in key_specs) 

906 

907 return details.get("first_key_pos", 0) > 0 and details.get("step_count", 0) > 0 

908 

909 

910def _to_command_metadata( 

911 details: Dict[str, Any], 

912 request_policy: RequestPolicy, 

913 response_policy: ResponsePolicy, 

914) -> CommandMetadata: 

915 """ 

916 Build the metadata record for a single entry of a ``COMMAND`` reply. 

917 

918 ``details`` is either a top-level entry or a ``_parse_subcommand`` result. The routing 

919 policies are passed in rather than derived again, so a record always carries the same 

920 policies ``_build_policy_records`` resolves for the command. 

921 """ 

922 flags = {str_if_bytes(flag) for flag in details.get("flags") or ()} 

923 # Walked rather than read as a flat sequence, through the same traversal the routing view 

924 # resolves its tips with: a metadata record is the superset of a policy record, so it must 

925 # not read less of the field than the policy view does. 

926 tips = set(_walk_tips(details.get("tips"))) 

927 

928 return CommandMetadata( 

929 request_policy=request_policy, 

930 response_policy=response_policy, 

931 is_readonly="readonly" in flags, 

932 is_blocking="blocking" in flags, 

933 has_key_argument=_has_key_argument(details), 

934 # Matched exactly: ``nondeterministic_output_order`` is a different tip, denoting 

935 # only that element order varies. 

936 has_nondeterministic_output="nondeterministic_output" in tips, 

937 is_script_runner="script_runner" in flags, 

938 is_dont_cache="dont_cache" in tips, 

939 # An empty tips list is a real answer; a missing tips key means the server is too 

940 # old to report tips at all, which makes the negative markers undetectable. 

941 has_complete_metadata="flags" in details and "tips" in details, 

942 ) 

943 

944 

945def _build_commands_metadata_cache( 

946 commands: Dict[str, Any], 

947) -> CommandMetadataRecordsCache: 

948 """ 

949 Retrieve and process the metadata records cache for all commands and subcommands. 

950 

951 This function traverses through commands and subcommands, normalizing the command 

952 flags, command tips and key metadata of each into a metadata record. It shares its 

953 traversal with ``_build_policy_records``, so records are keyed the same way and carry 

954 the same policies, and a metadata resolver and a policy resolver agree on the same reply. 

955 

956 Args: 

957 commands: The parsed ``COMMAND`` output to build the metadata records from. 

958 

959 Returns: 

960 CommandMetadataRecordsCache: A collection of commands and subcommands associated 

961 with their respective metadata. 

962 

963 Raises: 

964 IncorrectPolicyType: If an invalid policy type is encountered during policy extraction. 

965 """ 

966 return _build_command_records(commands, _to_command_metadata)