mq-rest-admin 1.2.2

Rust wrapper for the IBM MQ administrative REST API
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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
//! Synchronous start/stop/restart wrappers for MQ objects.

use std::collections::HashMap;
use std::thread;
use std::time::{Duration, Instant};

use serde_json::Value;

use crate::error::{MqRestError, Result};
use crate::session::MqRestSession;

/// Configuration for synchronous polling operations.
#[derive(Debug, Clone, Copy)]
pub struct SyncConfig {
    /// Maximum wall-clock seconds to wait for the target state.
    pub timeout_seconds: f64,
    /// Seconds to sleep between status polls.
    pub poll_interval_seconds: f64,
}

impl SyncConfig {
    /// Create a new `SyncConfig` with validated parameters.
    ///
    /// # Errors
    ///
    /// Returns [`MqRestError::InvalidConfig`] if either value is not positive.
    pub fn new(timeout_seconds: f64, poll_interval_seconds: f64) -> Result<Self> {
        check_positive("timeout_seconds", timeout_seconds)?;
        check_positive("poll_interval_seconds", poll_interval_seconds)?;
        Ok(Self {
            timeout_seconds,
            poll_interval_seconds,
        })
    }
}

impl Default for SyncConfig {
    fn default() -> Self {
        Self {
            timeout_seconds: 30.0,
            poll_interval_seconds: 1.0,
        }
    }
}

/// Operation performed by a synchronous wrapper.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyncOperation {
    /// The object was started and confirmed running.
    Started,
    /// The object was stopped and confirmed stopped.
    Stopped,
    /// The object was stopped then started.
    Restarted,
}

/// Result of a synchronous start/stop/restart operation.
#[derive(Debug, Clone)]
pub struct SyncResult {
    /// The operation that was performed.
    pub operation: SyncOperation,
    /// Total number of status polls issued.
    pub polls: u32,
    /// Total wall-clock seconds from command to target state confirmation.
    pub elapsed_seconds: f64,
}

struct ObjectTypeConfig {
    start_qualifier: &'static str,
    stop_qualifier: &'static str,
    status_qualifier: &'static str,
    status_keys: &'static [&'static str],
    empty_means_stopped: bool,
}

const CHANNEL_CONFIG: ObjectTypeConfig = ObjectTypeConfig {
    start_qualifier: "CHANNEL",
    stop_qualifier: "CHANNEL",
    status_qualifier: "CHSTATUS",
    status_keys: &["channel_status", "STATUS"],
    empty_means_stopped: true,
};

const LISTENER_CONFIG: ObjectTypeConfig = ObjectTypeConfig {
    start_qualifier: "LISTENER",
    stop_qualifier: "LISTENER",
    status_qualifier: "LSSTATUS",
    status_keys: &["status", "STATUS"],
    empty_means_stopped: false,
};

const SERVICE_CONFIG: ObjectTypeConfig = ObjectTypeConfig {
    start_qualifier: "SERVICE",
    stop_qualifier: "SERVICE",
    status_qualifier: "SVSTATUS",
    status_keys: &["status", "STATUS"],
    empty_means_stopped: false,
};

const RUNNING_VALUES: &[&str] = &["RUNNING", "running"];
const STOPPED_VALUES: &[&str] = &["STOPPED", "stopped"];

impl MqRestSession {
    // ---- Channel ----

    /// Start a channel and wait until it is running.
    ///
    /// # Errors
    ///
    /// Returns an error if the START command fails or the channel does not
    /// reach RUNNING within the timeout.
    pub fn start_channel_sync(
        &mut self,
        name: &str,
        config: Option<SyncConfig>,
    ) -> Result<SyncResult> {
        start_and_poll(self, name, &CHANNEL_CONFIG, config)
    }

    /// Stop a channel and wait until it is stopped.
    ///
    /// # Errors
    ///
    /// Returns an error if the STOP command fails or the channel does not
    /// reach STOPPED within the timeout.
    pub fn stop_channel_sync(
        &mut self,
        name: &str,
        config: Option<SyncConfig>,
    ) -> Result<SyncResult> {
        stop_and_poll(self, name, &CHANNEL_CONFIG, config)
    }

    /// Stop then start a channel, waiting for each phase.
    ///
    /// # Errors
    ///
    /// Returns an error if either the stop or start phase fails or times out.
    pub fn restart_channel(
        &mut self,
        name: &str,
        config: Option<SyncConfig>,
    ) -> Result<SyncResult> {
        restart(self, name, &CHANNEL_CONFIG, config)
    }

    // ---- Listener ----

    /// Start a listener and wait until it is running.
    ///
    /// # Errors
    ///
    /// Returns an error if the START command fails or the listener does not
    /// reach RUNNING within the timeout.
    pub fn start_listener_sync(
        &mut self,
        name: &str,
        config: Option<SyncConfig>,
    ) -> Result<SyncResult> {
        start_and_poll(self, name, &LISTENER_CONFIG, config)
    }

    /// Stop a listener and wait until it is stopped.
    ///
    /// # Errors
    ///
    /// Returns an error if the STOP command fails or the listener does not
    /// reach STOPPED within the timeout.
    pub fn stop_listener_sync(
        &mut self,
        name: &str,
        config: Option<SyncConfig>,
    ) -> Result<SyncResult> {
        stop_and_poll(self, name, &LISTENER_CONFIG, config)
    }

    /// Stop then start a listener, waiting for each phase.
    ///
    /// # Errors
    ///
    /// Returns an error if either the stop or start phase fails or times out.
    pub fn restart_listener(
        &mut self,
        name: &str,
        config: Option<SyncConfig>,
    ) -> Result<SyncResult> {
        restart(self, name, &LISTENER_CONFIG, config)
    }

    // ---- Service ----

    /// Start a service and wait until it is running.
    ///
    /// # Errors
    ///
    /// Returns an error if the START command fails or the service does not
    /// reach RUNNING within the timeout.
    pub fn start_service_sync(
        &mut self,
        name: &str,
        config: Option<SyncConfig>,
    ) -> Result<SyncResult> {
        start_and_poll(self, name, &SERVICE_CONFIG, config)
    }

    /// Stop a service and wait until it is stopped.
    ///
    /// # Errors
    ///
    /// Returns an error if the STOP command fails or the service does not
    /// reach STOPPED within the timeout.
    pub fn stop_service_sync(
        &mut self,
        name: &str,
        config: Option<SyncConfig>,
    ) -> Result<SyncResult> {
        stop_and_poll(self, name, &SERVICE_CONFIG, config)
    }

    /// Stop then start a service, waiting for each phase.
    ///
    /// # Errors
    ///
    /// Returns an error if either the stop or start phase fails or times out.
    pub fn restart_service(
        &mut self,
        name: &str,
        config: Option<SyncConfig>,
    ) -> Result<SyncResult> {
        restart(self, name, &SERVICE_CONFIG, config)
    }
}

fn start_and_poll(
    session: &mut MqRestSession,
    name: &str,
    obj_config: &ObjectTypeConfig,
    config: Option<SyncConfig>,
) -> Result<SyncResult> {
    let sync_config = config.unwrap_or_default();
    session.mqsc_command(
        "START",
        obj_config.start_qualifier,
        Some(name),
        None,
        None,
        None,
    )?;
    let mut polls = 0u32;
    let start_time = Instant::now();
    loop {
        thread::sleep(Duration::from_secs_f64(sync_config.poll_interval_seconds));
        let all_params: &[&str] = &["all"];
        let status_rows = session.mqsc_command(
            "DISPLAY",
            obj_config.status_qualifier,
            Some(name),
            None,
            Some(all_params),
            None,
        )?;
        polls += 1;
        if has_status(&status_rows, obj_config.status_keys, RUNNING_VALUES) {
            let elapsed = start_time.elapsed().as_secs_f64();
            return Ok(SyncResult {
                operation: SyncOperation::Started,
                polls,
                elapsed_seconds: elapsed,
            });
        }
        let elapsed = start_time.elapsed().as_secs_f64();
        if elapsed >= sync_config.timeout_seconds {
            return Err(MqRestError::Timeout {
                name: name.into(),
                operation: "start".into(),
                elapsed,
                message: format!(
                    "{} '{}' did not reach RUNNING within {}s",
                    obj_config.start_qualifier, name, sync_config.timeout_seconds
                ),
            });
        }
    }
}

fn stop_and_poll(
    session: &mut MqRestSession,
    name: &str,
    obj_config: &ObjectTypeConfig,
    config: Option<SyncConfig>,
) -> Result<SyncResult> {
    let sync_config = config.unwrap_or_default();
    session.mqsc_command(
        "STOP",
        obj_config.stop_qualifier,
        Some(name),
        None,
        None,
        None,
    )?;
    let mut polls = 0u32;
    let start_time = Instant::now();
    loop {
        thread::sleep(Duration::from_secs_f64(sync_config.poll_interval_seconds));
        let all_params: &[&str] = &["all"];
        let status_rows = session.mqsc_command(
            "DISPLAY",
            obj_config.status_qualifier,
            Some(name),
            None,
            Some(all_params),
            None,
        )?;
        polls += 1;
        if obj_config.empty_means_stopped && status_rows.is_empty() {
            let elapsed = start_time.elapsed().as_secs_f64();
            return Ok(SyncResult {
                operation: SyncOperation::Stopped,
                polls,
                elapsed_seconds: elapsed,
            });
        }
        if has_status(&status_rows, obj_config.status_keys, STOPPED_VALUES) {
            let elapsed = start_time.elapsed().as_secs_f64();
            return Ok(SyncResult {
                operation: SyncOperation::Stopped,
                polls,
                elapsed_seconds: elapsed,
            });
        }
        let elapsed = start_time.elapsed().as_secs_f64();
        if elapsed >= sync_config.timeout_seconds {
            return Err(MqRestError::Timeout {
                name: name.into(),
                operation: "stop".into(),
                elapsed,
                message: format!(
                    "{} '{}' did not reach STOPPED within {}s",
                    obj_config.stop_qualifier, name, sync_config.timeout_seconds
                ),
            });
        }
    }
}

fn restart(
    session: &mut MqRestSession,
    name: &str,
    obj_config: &ObjectTypeConfig,
    config: Option<SyncConfig>,
) -> Result<SyncResult> {
    let stop_result = stop_and_poll(session, name, obj_config, config)?;
    let start_result = start_and_poll(session, name, obj_config, config)?;
    Ok(SyncResult {
        operation: SyncOperation::Restarted,
        polls: stop_result.polls + start_result.polls,
        elapsed_seconds: stop_result.elapsed_seconds + start_result.elapsed_seconds,
    })
}

fn check_positive(field: &str, value: f64) -> Result<()> {
    if value > 0.0 {
        return Ok(());
    }
    Err(MqRestError::InvalidConfig {
        message: format!("{field} must be positive, got {value}"),
    })
}

fn has_status(
    rows: &[HashMap<String, Value>],
    status_keys: &[&str],
    target_values: &[&str],
) -> bool {
    for row in rows {
        for key in status_keys {
            if let Some(Value::String(value)) = row.get(*key)
                && target_values.contains(&value.as_str())
            {
                return true;
            }
        }
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helpers::{
        MockTransport, empty_success_response, mock_session, success_response,
    };
    use serde_json::json;

    fn fast_config() -> SyncConfig {
        SyncConfig {
            timeout_seconds: 0.5,
            poll_interval_seconds: 0.01,
        }
    }

    fn status_response(key: &str, value: &str) -> crate::transport::TransportResponse {
        let mut params = HashMap::new();
        params.insert(key.into(), json!(value));
        success_response(vec![params])
    }

    // ---- SyncConfig::default ----

    #[test]
    fn sync_config_default_values() {
        let config = SyncConfig::default();
        assert!((config.timeout_seconds - 30.0).abs() < f64::EPSILON);
        assert!((config.poll_interval_seconds - 1.0).abs() < f64::EPSILON);
    }

    // ---- has_status ----

    #[test]
    fn has_status_match_first_key() {
        let mut row = HashMap::new();
        row.insert("channel_status".into(), json!("RUNNING"));
        assert!(has_status(
            &[row],
            &["channel_status", "STATUS"],
            &["RUNNING"]
        ));
    }

    #[test]
    fn has_status_match_second_key() {
        let mut row = HashMap::new();
        row.insert("STATUS".into(), json!("STOPPED"));
        assert!(has_status(
            &[row],
            &["channel_status", "STATUS"],
            &["STOPPED"]
        ));
    }

    #[test]
    fn has_status_no_match() {
        let mut row = HashMap::new();
        row.insert("STATUS".into(), json!("STARTING"));
        assert!(!has_status(
            &[row],
            &["channel_status", "STATUS"],
            &["RUNNING"]
        ));
    }

    #[test]
    fn has_status_empty_rows() {
        assert!(!has_status(&[], &["STATUS"], &["RUNNING"]));
    }

    #[test]
    fn has_status_non_string_value() {
        let mut row = HashMap::new();
        row.insert("STATUS".into(), json!(42));
        assert!(!has_status(&[row], &["STATUS"], &["RUNNING"]));
    }

    // ---- start_channel_sync ----

    #[test]
    fn start_channel_sync_first_poll_running() {
        let transport = MockTransport::new(vec![
            empty_success_response(),
            status_response("channel_status", "RUNNING"),
        ]);
        let mut session = mock_session(transport);
        let result = session
            .start_channel_sync("MY.CH", Some(fast_config()))
            .unwrap();
        assert_eq!(result.operation, SyncOperation::Started);
        assert!(result.polls >= 1);
    }

    #[test]
    fn start_channel_sync_timeout() {
        let transport = MockTransport::new(vec![
            empty_success_response(),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
            status_response("channel_status", "STARTING"),
        ]);
        let mut session = mock_session(transport);
        let result = session.start_channel_sync("MY.CH", Some(fast_config()));
        assert!(format!("{:?}", result.unwrap_err()).starts_with("Timeout"));
    }

    // ---- stop_channel_sync ----

    #[test]
    fn stop_channel_sync_returns_stopped_via_status() {
        let transport = MockTransport::new(vec![
            empty_success_response(),
            status_response("STATUS", "STOPPED"),
        ]);
        let mut session = mock_session(transport);
        let result = session
            .stop_channel_sync("MY.CH", Some(fast_config()))
            .unwrap();
        assert_eq!(result.operation, SyncOperation::Stopped);
    }

    #[test]
    fn stop_channel_sync_empty_means_stopped() {
        let transport =
            MockTransport::new(vec![empty_success_response(), empty_success_response()]);
        let mut session = mock_session(transport);
        let result = session
            .stop_channel_sync("MY.CH", Some(fast_config()))
            .unwrap();
        assert_eq!(result.operation, SyncOperation::Stopped);
    }

    // ---- stop_listener_sync ----

    #[test]
    fn stop_listener_sync_empty_rows_not_stopped() {
        // Listeners have empty_means_stopped=false, so empty rows mean timeout
        let mut responses = vec![empty_success_response()]; // STOP command
        for _ in 0..60 {
            responses.push(empty_success_response()); // poll returns empty
        }
        let transport = MockTransport::new(responses);
        let mut session = mock_session(transport);
        let result = session.stop_listener_sync("MY.LIS", Some(fast_config()));
        assert!(format!("{:?}", result.unwrap_err()).starts_with("Timeout"));
    }

    #[test]
    fn stop_listener_sync_stopped_status() {
        let transport = MockTransport::new(vec![
            empty_success_response(),
            status_response("status", "STOPPED"),
        ]);
        let mut session = mock_session(transport);
        let result = session
            .stop_listener_sync("MY.LIS", Some(fast_config()))
            .unwrap();
        assert_eq!(result.operation, SyncOperation::Stopped);
    }

    // ---- restart_channel ----

    #[test]
    fn restart_channel_both_phases_succeed() {
        let transport = MockTransport::new(vec![
            empty_success_response(),                     // STOP
            empty_success_response(),                     // poll → empty (stopped for channel)
            empty_success_response(),                     // START
            status_response("channel_status", "RUNNING"), // poll → RUNNING
        ]);
        let mut session = mock_session(transport);
        let result = session
            .restart_channel("MY.CH", Some(fast_config()))
            .unwrap();
        assert_eq!(result.operation, SyncOperation::Restarted);
        assert!(result.polls >= 2);
    }

    #[test]
    fn restart_channel_stop_phase_fails() {
        let transport = MockTransport::new(vec![]);
        let mut session = mock_session(transport);
        let result = session.restart_channel("MY.CH", Some(fast_config()));
        assert!(result.is_err());
    }

    #[test]
    fn restart_channel_start_phase_fails() {
        let transport = MockTransport::new(vec![
            empty_success_response(), // STOP
            empty_success_response(), // poll → empty (stopped for channel)
                                      // START fails - no response
        ]);
        let mut session = mock_session(transport);
        let result = session.restart_channel("MY.CH", Some(fast_config()));
        assert!(result.is_err());
    }

    // ---- Macro-generated per-method tests ----

    macro_rules! test_start_sync {
        ($method:ident) => {
            paste::paste! {
                #[test]
                fn [<test_ $method _ok>]() {
                    let transport = MockTransport::new(vec![
                        empty_success_response(),
                        status_response("status", "RUNNING"),
                    ]);
                    let mut session = mock_session(transport);
                    let result = session.$method("OBJ", Some(fast_config())).unwrap();
                    assert_eq!(result.operation, SyncOperation::Started);
                }
            }
        };
    }

    macro_rules! test_stop_sync {
        ($method:ident) => {
            paste::paste! {
                #[test]
                fn [<test_ $method _ok>]() {
                    let transport = MockTransport::new(vec![
                        empty_success_response(),
                        status_response("status", "STOPPED"),
                    ]);
                    let mut session = mock_session(transport);
                    let result = session.$method("OBJ", Some(fast_config())).unwrap();
                    assert_eq!(result.operation, SyncOperation::Stopped);
                }
            }
        };
    }

    macro_rules! test_restart {
        ($method:ident) => {
            paste::paste! {
                #[test]
                fn [<test_ $method _ok>]() {
                    let transport = MockTransport::new(vec![
                        empty_success_response(),
                        status_response("status", "STOPPED"),
                        empty_success_response(),
                        status_response("status", "RUNNING"),
                    ]);
                    let mut session = mock_session(transport);
                    let result = session.$method("OBJ", Some(fast_config())).unwrap();
                    assert_eq!(result.operation, SyncOperation::Restarted);
                }
            }
        };
    }

    macro_rules! test_start_sync_channel {
        ($method:ident) => {
            paste::paste! {
                #[test]
                fn [<test_ $method _ok>]() {
                    let transport = MockTransport::new(vec![
                        empty_success_response(),
                        status_response("channel_status", "RUNNING"),
                    ]);
                    let mut session = mock_session(transport);
                    let result = session.$method("OBJ", Some(fast_config())).unwrap();
                    assert_eq!(result.operation, SyncOperation::Started);
                }
            }
        };
    }

    macro_rules! test_stop_sync_channel {
        ($method:ident) => {
            paste::paste! {
                #[test]
                fn [<test_ $method _ok>]() {
                    let transport = MockTransport::new(vec![
                        empty_success_response(),
                        status_response("channel_status", "STOPPED"),
                    ]);
                    let mut session = mock_session(transport);
                    let result = session.$method("OBJ", Some(fast_config())).unwrap();
                    assert_eq!(result.operation, SyncOperation::Stopped);
                }
            }
        };
    }

    macro_rules! test_restart_channel {
        ($method:ident) => {
            paste::paste! {
                #[test]
                fn [<test_ $method _ok>]() {
                    let transport = MockTransport::new(vec![
                        empty_success_response(),
                        status_response("channel_status", "STOPPED"),
                        empty_success_response(),
                        status_response("channel_status", "RUNNING"),
                    ]);
                    let mut session = mock_session(transport);
                    let result = session.$method("OBJ", Some(fast_config())).unwrap();
                    assert_eq!(result.operation, SyncOperation::Restarted);
                }
            }
        };
    }

    test_start_sync_channel!(start_channel_sync);
    test_start_sync!(start_listener_sync);
    test_start_sync!(start_service_sync);

    test_stop_sync_channel!(stop_channel_sync);
    test_stop_sync!(stop_listener_sync);
    test_stop_sync!(stop_service_sync);

    test_restart_channel!(restart_channel);
    test_restart!(restart_listener);
    test_restart!(restart_service);

    #[test]
    fn start_channel_sync_start_command_fails() {
        let transport = MockTransport::new(vec![]);
        let mut session = mock_session(transport);
        let result = session.start_channel_sync("MY.CH", Some(fast_config()));
        assert!(result.is_err());
    }

    #[test]
    fn start_channel_sync_poll_fails() {
        // START succeeds but poll DISPLAY fails
        let transport = MockTransport::new(vec![
            empty_success_response(), // START ok
                                      // poll fails - no response
        ]);
        let mut session = mock_session(transport);
        let result = session.start_channel_sync("MY.CH", Some(fast_config()));
        assert!(result.is_err());
    }

    #[test]
    fn stop_channel_sync_stop_command_fails() {
        let transport = MockTransport::new(vec![]);
        let mut session = mock_session(transport);
        let result = session.stop_channel_sync("MY.CH", Some(fast_config()));
        assert!(result.is_err());
    }

    #[test]
    fn stop_channel_sync_poll_fails() {
        let transport = MockTransport::new(vec![
            empty_success_response(), // STOP ok
                                      // poll fails - no response
        ]);
        let mut session = mock_session(transport);
        let result = session.stop_channel_sync("MY.CH", Some(fast_config()));
        assert!(result.is_err());
    }

    // ---- SyncConfig validation ----

    #[test]
    fn sync_config_new_valid() {
        let config = SyncConfig::new(10.0, 0.5).unwrap();
        assert!((config.timeout_seconds - 10.0).abs() < f64::EPSILON);
        assert!((config.poll_interval_seconds - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn sync_config_new_zero_timeout_rejected() {
        let err = SyncConfig::new(0.0, 1.0).unwrap_err();
        assert!(
            format!("{err}").contains("timeout_seconds must be positive"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn sync_config_new_negative_timeout_rejected() {
        let err = SyncConfig::new(-1.0, 1.0).unwrap_err();
        assert!(
            format!("{err}").contains("timeout_seconds must be positive"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn sync_config_new_zero_poll_interval_rejected() {
        let err = SyncConfig::new(30.0, 0.0).unwrap_err();
        assert!(
            format!("{err}").contains("poll_interval_seconds must be positive"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn sync_config_new_negative_poll_interval_rejected() {
        let err = SyncConfig::new(30.0, -1.0).unwrap_err();
        assert!(
            format!("{err}").contains("poll_interval_seconds must be positive"),
            "unexpected error: {err}"
        );
    }
}