shardcache-client-rs 0.3.2

Blocking Rust client for shardcache's native SCNP protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
#[cfg(feature = "redis")]
use std::collections::VecDeque;
use std::net::ToSocketAddrs;

use crate::commands::del::{self, Del};
use crate::commands::exists::{self, Exists};
use crate::commands::expire::{self, Expire};
use crate::commands::get::{self, Get};
use crate::commands::getex::{self, GetEx};
#[cfg(feature = "redis")]
use crate::commands::redis::{
    self, RedisCommand as OptimizedRedisCommand, RedisCommandKind, RedisCommandRouteKeys,
    RedisRespCommand, RedisResponse,
};
use crate::commands::resp::RespCommand;
use crate::commands::set::{self, Set};
use crate::commands::setex::{self, SetEx};
use crate::commands::ttl::{self, Ttl};
use crate::connection::ScnpConnection;
use crate::error::{Result, ShardCacheClientError};
#[cfg(feature = "redis")]
use crate::routing::ShardCacheRoute;
use crate::routing::{ShardCacheDirectRouter, ShardCacheRouteMode};

#[cfg(feature = "redis")]
#[derive(Debug, Clone, Copy)]
enum RedisPipelineResponse {
    Native,
    Resp,
}

/// Blocking SCNP client for the ordinary server listener.
#[derive(Debug)]
pub struct ShardCacheClient {
    conn: ScnpConnection,
    #[cfg(feature = "redis")]
    redis_pipeline_responses: VecDeque<RedisPipelineResponse>,
}

impl ShardCacheClient {
    /// Connects to a shardcache server listener that accepts generic SCNP.
    pub fn connect(addr: impl ToSocketAddrs) -> Result<Self> {
        Ok(Self {
            conn: ScnpConnection::connect(addr)?,
            #[cfg(feature = "redis")]
            redis_pipeline_responses: VecDeque::new(),
        })
    }

    /// Reads `key` into `out`, returning `true` on hit.
    pub fn get_into(&mut self, key: &[u8], out: &mut Vec<u8>) -> Result<bool> {
        self.conn.execute(Get::new(key, out))
    }

    /// Sets `key` to `value`.
    pub fn set(&mut self, key: &[u8], value: &[u8]) -> Result<()> {
        self.conn.execute(Set::new(key, value))
    }

    /// Sets `key` to `value` with a millisecond TTL.
    pub fn set_ex(&mut self, key: &[u8], value: &[u8], ttl_ms: u64) -> Result<()> {
        self.conn.execute(SetEx::new(key, value, ttl_ms))
    }

    /// Reads `key` into `out` and sets a millisecond TTL, returning `true` on hit.
    pub fn get_ex_into(&mut self, key: &[u8], ttl_ms: u64, out: &mut Vec<u8>) -> Result<bool> {
        self.conn.execute(GetEx::new(key, ttl_ms, out))
    }

    /// Deletes `key`, returning `true` when an entry was removed.
    pub fn del(&mut self, key: &[u8]) -> Result<bool> {
        self.conn.execute(Del::new(key))
    }

    /// Returns whether `key` exists.
    pub fn exists(&mut self, key: &[u8]) -> Result<bool> {
        self.conn.execute(Exists::new(key))
    }

    /// Returns Redis-compatible TTL seconds for `key`.
    pub fn ttl(&mut self, key: &[u8]) -> Result<i64> {
        self.conn.execute(Ttl::new(key))
    }

    /// Sets a millisecond TTL on `key`, returning `true` when the TTL changed.
    pub fn expire(&mut self, key: &[u8], ttl_ms: u64) -> Result<bool> {
        self.conn.execute(Expire::new(key, ttl_ms))
    }

    /// Returns the first-party Redis command namespace.
    #[cfg(feature = "redis")]
    pub fn redis(&mut self) -> crate::Redis<'_, Self> {
        crate::Redis::new(self)
    }

    /// Executes a Redis-compatible command through the compact opcode SCNP wrapper.
    #[cfg(feature = "redis")]
    pub fn redis_command(
        &mut self,
        command: RedisCommandKind,
        args: &[&[u8]],
    ) -> Result<RedisResponse> {
        self.conn.execute(OptimizedRedisCommand::new(command, args))
    }

    /// Executes a Redis-compatible command by name through native SCNP.
    ///
    /// Commands with compact opcodes use the optimized Redis wrapper. Other
    /// names use the SCNP command-name wrapper and return decoded RESP.
    #[cfg(feature = "redis")]
    pub fn redis_command_by_name(
        &mut self,
        command: &[u8],
        args: &[&[u8]],
    ) -> Result<RedisResponse> {
        match RedisCommandKind::from_name(command) {
            Some(command) => self.redis_command(command, args),
            None => self.redis_resp_command(command, args),
        }
    }

    /// Executes a Redis-compatible command through the SCNP command-name wrapper.
    ///
    /// This path is still native SCNP, but it carries the Redis command name in
    /// the body so it can cover commands that do not have a compact opcode.
    #[cfg(feature = "redis")]
    pub fn redis_resp_command(&mut self, command: &[u8], args: &[&[u8]]) -> Result<RedisResponse> {
        validate_redis_command_name(command)?;
        self.conn.execute(RedisRespCommand::new(command, args))
    }

    /// Executes a Redis-compatible command through the generic SCNP wrapper.
    ///
    /// The server returns RESP bytes as an SCNP value. `out` receives those raw
    /// bytes so callers can decode exactly the shape they requested.
    pub fn resp_command_into(&mut self, parts: &[&[u8]], out: &mut Vec<u8>) -> Result<bool> {
        self.conn.execute(RespCommand::new(parts, out))
    }

    /// Runs the global SCNP scan wrapper and returns the RESP scan reply bytes.
    pub fn scan_resp_into(&mut self, cursor: u64, count: usize, out: &mut Vec<u8>) -> Result<bool> {
        let cursor = cursor.to_string();
        let count = count.to_string();
        self.resp_command_into(
            &[b"SCNP.SCAN", cursor.as_bytes(), b"COUNT", count.as_bytes()],
            out,
        )
    }

    /// Runs a shard-local SCNP scan. Call this concurrently per shard to avoid
    /// a server-side fanout scan.
    pub fn scan_shard_resp_into(
        &mut self,
        shard_id: usize,
        cursor: u64,
        count: usize,
        out: &mut Vec<u8>,
    ) -> Result<bool> {
        let shard_id = shard_id.to_string();
        let cursor = cursor.to_string();
        let count = count.to_string();
        self.resp_command_into(
            &[
                b"SCNP.SCANSHARD",
                shard_id.as_bytes(),
                cursor.as_bytes(),
                b"COUNT",
                count.as_bytes(),
            ],
            out,
        )
    }

    /// Writes a GET request without flushing or reading its response.
    pub fn begin_pipeline_get(&mut self, key: &[u8]) -> Result<()> {
        get::write_request(&mut self.conn, None, key)
    }

    /// Writes a SET request without flushing or reading its response.
    pub fn begin_pipeline_set(&mut self, key: &[u8], value: &[u8]) -> Result<()> {
        set::write_request(&mut self.conn, None, key, value)
    }

    /// Writes a SETEX request without flushing or reading its response.
    pub fn begin_pipeline_set_ex(&mut self, key: &[u8], value: &[u8], ttl_ms: u64) -> Result<()> {
        setex::write_request(&mut self.conn, None, key, value, ttl_ms)
    }

    /// Writes a GETEX request without flushing or reading its response.
    pub fn begin_pipeline_get_ex(&mut self, key: &[u8], ttl_ms: u64) -> Result<()> {
        getex::write_request(&mut self.conn, None, key, ttl_ms)
    }

    /// Writes a DEL request without flushing or reading its response.
    pub fn begin_pipeline_del(&mut self, key: &[u8]) -> Result<()> {
        del::write_request(&mut self.conn, None, key)
    }

    /// Writes an EXISTS request without flushing or reading its response.
    pub fn begin_pipeline_exists(&mut self, key: &[u8]) -> Result<()> {
        exists::write_request(&mut self.conn, None, key)
    }

    /// Writes a TTL request without flushing or reading its response.
    pub fn begin_pipeline_ttl(&mut self, key: &[u8]) -> Result<()> {
        ttl::write_request(&mut self.conn, None, key)
    }

    /// Writes an EXPIRE request without flushing or reading its response.
    pub fn begin_pipeline_expire(&mut self, key: &[u8], ttl_ms: u64) -> Result<()> {
        expire::write_request(&mut self.conn, None, key, ttl_ms)
    }

    /// Writes a compact Redis command request without flushing or reading its response.
    #[cfg(feature = "redis")]
    pub fn begin_pipeline_redis_command(
        &mut self,
        command: RedisCommandKind,
        args: &[&[u8]],
    ) -> Result<()> {
        redis::write_request(&mut self.conn, command, None, args)?;
        self.redis_pipeline_responses
            .push_back(RedisPipelineResponse::Native);
        Ok(())
    }

    /// Writes a Redis command request by name without flushing or reading its response.
    ///
    /// Compact-opcode commands use the optimized Redis wrapper. Other command
    /// names use the SCNP command-name wrapper and decode the RESP payload when
    /// [`finish_pipeline_redis_command`](Self::finish_pipeline_redis_command)
    /// is called.
    #[cfg(feature = "redis")]
    pub fn begin_pipeline_redis_command_by_name(
        &mut self,
        command: &[u8],
        args: &[&[u8]],
    ) -> Result<()> {
        match RedisCommandKind::from_name(command) {
            Some(command) => self.begin_pipeline_redis_command(command, args),
            None => self.begin_pipeline_redis_resp_command(command, args),
        }
    }

    /// Writes a Redis command-name wrapper request without flushing or reading its response.
    #[cfg(feature = "redis")]
    pub fn begin_pipeline_redis_resp_command(
        &mut self,
        command: &[u8],
        args: &[&[u8]],
    ) -> Result<()> {
        validate_redis_command_name(command)?;
        redis::write_resp_request(&mut self.conn, command, args)?;
        self.redis_pipeline_responses
            .push_back(RedisPipelineResponse::Resp);
        Ok(())
    }

    /// Flushes all queued pipelined requests.
    pub fn flush_pipeline(&mut self) -> Result<()> {
        self.conn.flush()
    }

    /// Reads the next pipelined GET response.
    pub fn finish_pipeline_get_into(&mut self, out: &mut Vec<u8>) -> Result<bool> {
        self.conn
            .read_value(<Get as crate::commands::ScnpCommand>::NAME, out)
    }

    /// Reads the next pipelined SET response.
    pub fn finish_pipeline_set(&mut self) -> Result<()> {
        self.conn
            .expect_ok(<Set as crate::commands::ScnpCommand>::NAME)
    }

    /// Reads the next pipelined SETEX response.
    pub fn finish_pipeline_set_ex(&mut self) -> Result<()> {
        self.conn
            .expect_ok(<SetEx as crate::commands::ScnpCommand>::NAME)
    }

    /// Reads the next pipelined GETEX response.
    pub fn finish_pipeline_get_ex_into(&mut self, out: &mut Vec<u8>) -> Result<bool> {
        self.conn
            .read_value(<GetEx as crate::commands::ScnpCommand>::NAME, out)
    }

    /// Reads the next pipelined DEL response.
    pub fn finish_pipeline_del(&mut self) -> Result<bool> {
        self.conn
            .read_integer(<Del as crate::commands::ScnpCommand>::NAME)
            .map(|deleted| deleted != 0)
    }

    /// Reads the next pipelined EXISTS response.
    pub fn finish_pipeline_exists(&mut self) -> Result<bool> {
        self.conn
            .read_integer(<Exists as crate::commands::ScnpCommand>::NAME)
            .map(|exists| exists != 0)
    }

    /// Reads the next pipelined TTL response.
    pub fn finish_pipeline_ttl(&mut self) -> Result<i64> {
        self.conn
            .read_integer(<Ttl as crate::commands::ScnpCommand>::NAME)
    }

    /// Reads the next pipelined EXPIRE response.
    pub fn finish_pipeline_expire(&mut self) -> Result<bool> {
        self.conn
            .read_integer(<Expire as crate::commands::ScnpCommand>::NAME)
            .map(|changed| changed != 0)
    }

    /// Reads the next pipelined compact Redis command response.
    #[cfg(feature = "redis")]
    pub fn finish_pipeline_redis_command(&mut self) -> Result<RedisResponse> {
        match self
            .redis_pipeline_responses
            .pop_front()
            .unwrap_or(RedisPipelineResponse::Native)
        {
            RedisPipelineResponse::Native => self.conn.read_native_redis_response("REDIS"),
            RedisPipelineResponse::Resp => self.conn.read_resp_redis_response("RESP"),
        }
    }
}

impl ShardCacheDirectRouter {
    /// Connects directly to one shard-owned port.
    pub fn connect_shard(&self, shard_id: usize) -> Result<ShardCacheDirectShardClient> {
        Ok(ShardCacheDirectShardClient {
            router: *self,
            shard_id,
            conn: ScnpConnection::connect(self.shard_addr(shard_id)?)?,
        })
    }
}

/// Blocking SCNP client that automatically routes each key to its shard port.
#[derive(Debug)]
pub struct ShardCacheDirectClient {
    router: ShardCacheDirectRouter,
    conns: Vec<ScnpConnection>,
}

impl ShardCacheDirectClient {
    /// Connects to every shard-owned port starting at `addr`.
    ///
    /// `addr` must be the first direct shard port, not the fanout port.
    pub fn connect(addr: impl ToSocketAddrs, shard_count: usize) -> Result<Self> {
        let router = ShardCacheDirectRouter::new(addr, shard_count)?;
        Self::connect_with_router(router)
    }

    /// Connects to every shard-owned port using an explicit route mode.
    pub fn connect_with_route_mode(
        addr: impl ToSocketAddrs,
        shard_count: usize,
        route_mode: ShardCacheRouteMode,
    ) -> Result<Self> {
        let router = ShardCacheDirectRouter::new(addr, shard_count)?.with_route_mode(route_mode);
        Self::connect_with_router(router)
    }

    fn connect_with_router(router: ShardCacheDirectRouter) -> Result<Self> {
        let mut conns = Vec::with_capacity(router.shard_count());
        for shard_id in 0..router.shard_count() {
            conns.push(ScnpConnection::connect(router.shard_addr(shard_id)?)?);
        }
        Ok(Self { router, conns })
    }

    /// Reads `key` from its owning shard into `out`, returning `true` on hit.
    pub fn get_into(&mut self, key: &[u8], out: &mut Vec<u8>) -> Result<bool> {
        let route = self.router.route_key(key);
        self.conns[route.shard_id].execute(Get::routed(route, key, out))
    }

    /// Sets `key` on its owning shard.
    pub fn set(&mut self, key: &[u8], value: &[u8]) -> Result<()> {
        let route = self.router.route_key(key);
        self.conns[route.shard_id].execute(Set::routed(route, key, value))
    }

    /// Sets `key` on its owning shard with a millisecond TTL.
    pub fn set_ex(&mut self, key: &[u8], value: &[u8], ttl_ms: u64) -> Result<()> {
        let route = self.router.route_key(key);
        self.conns[route.shard_id].execute(SetEx::routed(route, key, value, ttl_ms))
    }

    /// Reads `key` from its owning shard into `out` and sets a millisecond TTL.
    pub fn get_ex_into(&mut self, key: &[u8], ttl_ms: u64, out: &mut Vec<u8>) -> Result<bool> {
        let route = self.router.route_key(key);
        self.conns[route.shard_id].execute(GetEx::routed(route, key, ttl_ms, out))
    }

    /// Deletes `key` from its owning shard.
    pub fn del(&mut self, key: &[u8]) -> Result<bool> {
        let route = self.router.route_key(key);
        self.conns[route.shard_id].execute(Del::routed(route, key))
    }

    /// Returns whether `key` exists on its owning shard.
    pub fn exists(&mut self, key: &[u8]) -> Result<bool> {
        let route = self.router.route_key(key);
        self.conns[route.shard_id].execute(Exists::routed(route, key))
    }

    /// Returns Redis-compatible TTL seconds for `key` on its owning shard.
    pub fn ttl(&mut self, key: &[u8]) -> Result<i64> {
        let route = self.router.route_key(key);
        self.conns[route.shard_id].execute(Ttl::routed(route, key))
    }

    /// Sets a millisecond TTL on `key` on its owning shard.
    pub fn expire(&mut self, key: &[u8], ttl_ms: u64) -> Result<bool> {
        let route = self.router.route_key(key);
        self.conns[route.shard_id].execute(Expire::routed(route, key, ttl_ms))
    }

    /// Returns the first-party Redis command namespace for direct shard routing.
    #[cfg(feature = "redis")]
    pub fn redis(&mut self) -> crate::Redis<'_, Self> {
        crate::Redis::new(self)
    }

    /// Executes a compact Redis command on the owning direct shard.
    ///
    /// Commands that require all shards are rejected; use [`ShardCacheClient`] against
    /// the fanout listener for those.
    #[cfg(feature = "redis")]
    pub fn redis_command(
        &mut self,
        command: RedisCommandKind,
        args: &[&[u8]],
    ) -> Result<RedisResponse> {
        let route = redis_direct_route(&self.router, command, args)?;
        let shard_id = route.map_or(0, |route| route.shard_id);
        self.conns[shard_id].execute(OptimizedRedisCommand::routed(command, route, args))
    }

    /// Executes a compact Redis command by name on the owning direct shard.
    #[cfg(feature = "redis")]
    pub fn redis_command_by_name(
        &mut self,
        command: &[u8],
        args: &[&[u8]],
    ) -> Result<RedisResponse> {
        self.redis_command(redis_command_kind_from_name(command)?, args)
    }

    /// Runs a shard-local SCNP scan on one direct shard connection. Callers can
    /// invoke this for different shards from different threads for parallel
    /// scans.
    pub fn scan_shard_resp_into(
        &mut self,
        shard_id: usize,
        cursor: u64,
        count: usize,
        out: &mut Vec<u8>,
    ) -> Result<bool> {
        if shard_id >= self.conns.len() {
            return Err(ShardCacheClientError::Config(format!(
                "shard {shard_id} is outside configured shard count {}",
                self.conns.len()
            )));
        }
        let shard_id_text = shard_id.to_string();
        let cursor = cursor.to_string();
        let count = count.to_string();
        self.conns[shard_id].execute(RespCommand::new(
            &[
                b"SCNP.SCANSHARD",
                shard_id_text.as_bytes(),
                cursor.as_bytes(),
                b"COUNT",
                count.as_bytes(),
            ],
            out,
        ))
    }
}

/// Blocking SCNP client pinned to one shard-owned port.
///
/// This is useful for thread-per-shard clients that pre-partition work.
#[derive(Debug)]
pub struct ShardCacheDirectShardClient {
    router: ShardCacheDirectRouter,
    shard_id: usize,
    conn: ScnpConnection,
}

impl ShardCacheDirectShardClient {
    /// Returns the shard this client is connected to.
    pub fn shard_id(&self) -> usize {
        self.shard_id
    }

    /// Reads `key` into `out`, returning `true` on hit.
    pub fn get_into(&mut self, key: &[u8], out: &mut Vec<u8>) -> Result<bool> {
        let route = self.checked_route(key)?;
        self.conn.execute(Get::routed(route, key, out))
    }

    /// Sets `key` to `value`.
    pub fn set(&mut self, key: &[u8], value: &[u8]) -> Result<()> {
        let route = self.checked_route(key)?;
        self.conn.execute(Set::routed(route, key, value))
    }

    /// Sets `key` to `value` with a millisecond TTL.
    pub fn set_ex(&mut self, key: &[u8], value: &[u8], ttl_ms: u64) -> Result<()> {
        let route = self.checked_route(key)?;
        self.conn.execute(SetEx::routed(route, key, value, ttl_ms))
    }

    /// Reads `key` into `out` and sets a millisecond TTL, returning `true` on hit.
    pub fn get_ex_into(&mut self, key: &[u8], ttl_ms: u64, out: &mut Vec<u8>) -> Result<bool> {
        let route = self.checked_route(key)?;
        self.conn.execute(GetEx::routed(route, key, ttl_ms, out))
    }

    /// Deletes `key`, returning `true` when an entry was removed.
    pub fn del(&mut self, key: &[u8]) -> Result<bool> {
        let route = self.checked_route(key)?;
        self.conn.execute(Del::routed(route, key))
    }

    /// Returns whether `key` exists.
    pub fn exists(&mut self, key: &[u8]) -> Result<bool> {
        let route = self.checked_route(key)?;
        self.conn.execute(Exists::routed(route, key))
    }

    /// Returns Redis-compatible TTL seconds for `key`.
    pub fn ttl(&mut self, key: &[u8]) -> Result<i64> {
        let route = self.checked_route(key)?;
        self.conn.execute(Ttl::routed(route, key))
    }

    /// Sets a millisecond TTL on `key`, returning `true` when the TTL changed.
    pub fn expire(&mut self, key: &[u8], ttl_ms: u64) -> Result<bool> {
        let route = self.checked_route(key)?;
        self.conn.execute(Expire::routed(route, key, ttl_ms))
    }

    /// Returns the first-party Redis command namespace for this shard.
    #[cfg(feature = "redis")]
    pub fn redis(&mut self) -> crate::Redis<'_, Self> {
        crate::Redis::new(self)
    }

    /// Executes a compact Redis command on this direct shard.
    ///
    /// Commands that require all shards are rejected; use [`ShardCacheClient`] against
    /// the fanout listener for those.
    #[cfg(feature = "redis")]
    pub fn redis_command(
        &mut self,
        command: RedisCommandKind,
        args: &[&[u8]],
    ) -> Result<RedisResponse> {
        let route = redis_direct_shard_route(&self.router, self.shard_id, command, args)?;
        self.conn
            .execute(OptimizedRedisCommand::routed(command, route, args))
    }

    /// Executes a compact Redis command by name on this direct shard.
    #[cfg(feature = "redis")]
    pub fn redis_command_by_name(
        &mut self,
        command: &[u8],
        args: &[&[u8]],
    ) -> Result<RedisResponse> {
        self.redis_command(redis_command_kind_from_name(command)?, args)
    }

    /// Runs a shard-local SCNP scan on this shard-owned connection.
    pub fn scan_resp_into(&mut self, cursor: u64, count: usize, out: &mut Vec<u8>) -> Result<bool> {
        let shard_id = self.shard_id.to_string();
        let cursor = cursor.to_string();
        let count = count.to_string();
        self.conn.execute(RespCommand::new(
            &[
                b"SCNP.SCANSHARD",
                shard_id.as_bytes(),
                cursor.as_bytes(),
                b"COUNT",
                count.as_bytes(),
            ],
            out,
        ))
    }

    /// Writes a routed GET request without flushing or reading its response.
    pub fn begin_pipeline_get(&mut self, key: &[u8]) -> Result<()> {
        let route = self.checked_route(key)?;
        get::write_request(&mut self.conn, Some(route), key)
    }

    /// Writes a routed SET request without flushing or reading its response.
    pub fn begin_pipeline_set(&mut self, key: &[u8], value: &[u8]) -> Result<()> {
        let route = self.checked_route(key)?;
        set::write_request(&mut self.conn, Some(route), key, value)
    }

    /// Writes a routed SETEX request without flushing or reading its response.
    pub fn begin_pipeline_set_ex(&mut self, key: &[u8], value: &[u8], ttl_ms: u64) -> Result<()> {
        let route = self.checked_route(key)?;
        setex::write_request(&mut self.conn, Some(route), key, value, ttl_ms)
    }

    /// Writes a routed GETEX request without flushing or reading its response.
    pub fn begin_pipeline_get_ex(&mut self, key: &[u8], ttl_ms: u64) -> Result<()> {
        let route = self.checked_route(key)?;
        getex::write_request(&mut self.conn, Some(route), key, ttl_ms)
    }

    /// Writes a routed DEL request without flushing or reading its response.
    pub fn begin_pipeline_del(&mut self, key: &[u8]) -> Result<()> {
        let route = self.checked_route(key)?;
        del::write_request(&mut self.conn, Some(route), key)
    }

    /// Writes a routed EXISTS request without flushing or reading its response.
    pub fn begin_pipeline_exists(&mut self, key: &[u8]) -> Result<()> {
        let route = self.checked_route(key)?;
        exists::write_request(&mut self.conn, Some(route), key)
    }

    /// Writes a routed TTL request without flushing or reading its response.
    pub fn begin_pipeline_ttl(&mut self, key: &[u8]) -> Result<()> {
        let route = self.checked_route(key)?;
        ttl::write_request(&mut self.conn, Some(route), key)
    }

    /// Writes a routed EXPIRE request without flushing or reading its response.
    pub fn begin_pipeline_expire(&mut self, key: &[u8], ttl_ms: u64) -> Result<()> {
        let route = self.checked_route(key)?;
        expire::write_request(&mut self.conn, Some(route), key, ttl_ms)
    }

    /// Writes a compact Redis command request without flushing or reading its response.
    #[cfg(feature = "redis")]
    pub fn begin_pipeline_redis_command(
        &mut self,
        command: RedisCommandKind,
        args: &[&[u8]],
    ) -> Result<()> {
        let route = redis_direct_shard_route(&self.router, self.shard_id, command, args)?;
        redis::write_request(&mut self.conn, command, route, args)
    }

    /// Writes a compact Redis command request by name without flushing or reading its response.
    #[cfg(feature = "redis")]
    pub fn begin_pipeline_redis_command_by_name(
        &mut self,
        command: &[u8],
        args: &[&[u8]],
    ) -> Result<()> {
        self.begin_pipeline_redis_command(redis_command_kind_from_name(command)?, args)
    }

    /// Flushes all queued pipelined requests.
    pub fn flush_pipeline(&mut self) -> Result<()> {
        self.conn.flush()
    }

    /// Reads the next pipelined GET response.
    pub fn finish_pipeline_get_into(&mut self, out: &mut Vec<u8>) -> Result<bool> {
        self.conn
            .read_value(<Get as crate::commands::ScnpCommand>::NAME, out)
    }

    /// Reads the next pipelined SET response.
    pub fn finish_pipeline_set(&mut self) -> Result<()> {
        self.conn
            .expect_ok(<Set as crate::commands::ScnpCommand>::NAME)
    }

    /// Reads the next pipelined SETEX response.
    pub fn finish_pipeline_set_ex(&mut self) -> Result<()> {
        self.conn
            .expect_ok(<SetEx as crate::commands::ScnpCommand>::NAME)
    }

    /// Reads the next pipelined GETEX response.
    pub fn finish_pipeline_get_ex_into(&mut self, out: &mut Vec<u8>) -> Result<bool> {
        self.conn
            .read_value(<GetEx as crate::commands::ScnpCommand>::NAME, out)
    }

    /// Reads the next pipelined DEL response.
    pub fn finish_pipeline_del(&mut self) -> Result<bool> {
        self.conn
            .read_integer(<Del as crate::commands::ScnpCommand>::NAME)
            .map(|deleted| deleted != 0)
    }

    /// Reads the next pipelined EXISTS response.
    pub fn finish_pipeline_exists(&mut self) -> Result<bool> {
        self.conn
            .read_integer(<Exists as crate::commands::ScnpCommand>::NAME)
            .map(|exists| exists != 0)
    }

    /// Reads the next pipelined TTL response.
    pub fn finish_pipeline_ttl(&mut self) -> Result<i64> {
        self.conn
            .read_integer(<Ttl as crate::commands::ScnpCommand>::NAME)
    }

    /// Reads the next pipelined EXPIRE response.
    pub fn finish_pipeline_expire(&mut self) -> Result<bool> {
        self.conn
            .read_integer(<Expire as crate::commands::ScnpCommand>::NAME)
            .map(|changed| changed != 0)
    }

    /// Reads the next pipelined compact Redis command response.
    #[cfg(feature = "redis")]
    pub fn finish_pipeline_redis_command(&mut self) -> Result<RedisResponse> {
        self.conn.read_native_redis_response("REDIS")
    }

    fn checked_route(&self, key: &[u8]) -> Result<crate::routing::ShardCacheRoute> {
        let route = self.router.route_key(key);
        if route.shard_id != self.shard_id {
            return Err(ShardCacheClientError::Config(format!(
                "key routes to shard {}, but client is connected to shard {}",
                route.shard_id, self.shard_id
            )));
        }
        Ok(route)
    }
}

#[cfg(feature = "redis")]
fn redis_command_kind_from_name(command: &[u8]) -> Result<RedisCommandKind> {
    RedisCommandKind::from_name(command).ok_or_else(|| {
        ShardCacheClientError::Config(format!(
            "Redis command `{}` is not available on direct SCNP shard clients; use ShardCacheClient on the fanout listener for command-name fallback",
            String::from_utf8_lossy(command)
        ))
    })
}

#[cfg(feature = "redis")]
fn validate_redis_command_name(command: &[u8]) -> Result<()> {
    if command.is_empty() {
        return Err(ShardCacheClientError::Config(
            "Redis command name cannot be empty".into(),
        ));
    }
    if command.iter().any(|byte| byte.is_ascii_whitespace()) {
        return Err(ShardCacheClientError::Config(format!(
            "Redis command name cannot contain whitespace: `{}`",
            String::from_utf8_lossy(command)
        )));
    }
    Ok(())
}

#[cfg(feature = "redis")]
fn redis_direct_route(
    router: &ShardCacheDirectRouter,
    command: RedisCommandKind,
    args: &[&[u8]],
) -> Result<Option<ShardCacheRoute>> {
    let keys = match command.route_keys(args) {
        RedisCommandRouteKeys::None => return Ok(None),
        RedisCommandRouteKeys::AllShards => {
            return Err(ShardCacheClientError::Config(format!(
                "{} requires all shards; use ShardCacheClient on the fanout listener",
                command.name()
            )));
        }
        RedisCommandRouteKeys::Keys(keys) if keys.is_empty() => return Ok(None),
        RedisCommandRouteKeys::Keys(keys) => keys,
    };

    let first_route = router.route_key(keys[0]);
    for key in keys.iter().skip(1) {
        let route = router.route_key(key);
        if route.shard_id != first_route.shard_id {
            return Err(ShardCacheClientError::Config(format!(
                "{} keys span multiple direct shards",
                command.name()
            )));
        }
    }
    Ok(Some(first_route))
}

#[cfg(feature = "redis")]
fn redis_direct_shard_route(
    router: &ShardCacheDirectRouter,
    shard_id: usize,
    command: RedisCommandKind,
    args: &[&[u8]],
) -> Result<Option<ShardCacheRoute>> {
    let route = redis_direct_route(router, command, args)?;
    if let Some(route) = route
        && route.shard_id != shard_id
    {
        return Err(ShardCacheClientError::Config(format!(
            "{} routes to shard {}, but client is connected to shard {}",
            command.name(),
            route.shard_id,
            shard_id
        )));
    }
    Ok(route)
}