matroskin 0.1.0

whatsminer api client lib
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
//! State types, session ownership, and lifecycle projections for the WhatsMiner actor.
//!
//! # Architecture
//!
//! - `ActorState`: Private finite state machine owned by the actor loop.
//! - `Session`: Non-`Clone`, non-`Copy` owner of the live transport, salt, and permissions.
//! - [`ActorStatus`]: Public lightweight projection for immediate-mode observation via watch channel.
//! - [`ReconnectReason`] / [`CloseReason`]: Typed causes for state transitions.
//! - [`ReconnectPolicy`]: Deterministic backoff strategy.
//! - `PendingPlan`: Bounded lifecycle intent plan with reduction rules.

use std::collections::VecDeque;
use std::fmt;
use std::time::Duration;

use tokio::net::TcpStream;
use tokio_util::codec::Framed;

use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::{actor::codec::WhatsMinerCodec, permission::Permission};

/// Protected session salt with guaranteed zeroize-on-drop.
///
/// Owns the device session salt received during the handshake.
/// Never leaves the actor task, is omitted from public status,
/// and is redacted from all formatted debug and display representations.
#[derive(PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
pub(crate) struct Salt(String);

impl Salt {
    pub(crate) fn new(salt: impl Into<String>) -> Self {
        Self(salt.into())
    }

    pub(crate) fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for Salt {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[REDACTED]")
    }
}

impl fmt::Display for Salt {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[REDACTED]")
    }
}

/// Connection session to a WhatsMiner device.
///
/// Owns the active [`Framed`] TCP transport, session salt, and account
/// permissions. `Session` is non-`Clone` and non-`Copy`, and is moved by value
/// across FSM states.
pub(crate) struct Session {
    pub(crate) transport: Framed<TcpStream, WhatsMinerCodec>,
    pub(crate) salt: Salt,
    pub(crate) permissions: Permission,
}

impl fmt::Debug for Session {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Session")
            .field("salt", &self.salt)
            .field("permissions", &self.permissions)
            .finish_non_exhaustive()
    }
}

/// Private finite state machine representing the lifecycle of an actor connection.
///
/// Transitions transfer ownership of [`Session`] across states without cloning.
pub(crate) enum ActorState {
    Created,
    Connecting,
    Connected(Session),
    Downloading(Session),
    Uploading(Session),
    Reconnecting {
        attempt: usize,
        reason: ReconnectReason,
    },
    Disconnecting(Session),
    Closed {
        reason: CloseReason,
    },
}

impl fmt::Debug for ActorState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Created => write!(f, "Created"),
            Self::Connecting => write!(f, "Connecting"),
            Self::Connected(s) => f.debug_tuple("Connected").field(s).finish(),
            Self::Downloading(s) => f.debug_tuple("Downloading").field(s).finish(),
            Self::Uploading(s) => f.debug_tuple("Uploading").field(s).finish(),
            Self::Reconnecting { attempt, reason } => f
                .debug_struct("Reconnecting")
                .field("attempt", attempt)
                .field("reason", reason)
                .finish(),
            Self::Disconnecting(s) => f.debug_tuple("Disconnecting").field(s).finish(),
            Self::Closed { reason } => f.debug_struct("Closed").field("reason", reason).finish(),
        }
    }
}

impl ActorState {
    /// Project the internal state into the public lightweight [`ActorStatus`].
    pub(crate) fn status(&self) -> ActorStatus {
        match self {
            Self::Created => ActorStatus::Created,
            Self::Connecting => ActorStatus::Connecting,
            Self::Connected(session) => ActorStatus::Connected {
                permissions: session.permissions,
            },
            Self::Downloading(session) => ActorStatus::Downloading {
                permissions: session.permissions,
            },
            Self::Uploading(session) => ActorStatus::Uploading {
                permissions: session.permissions,
            },
            Self::Reconnecting { attempt, reason } => ActorStatus::Reconnecting {
                attempt: *attempt,
                reason: reason.clone(),
            },
            Self::Disconnecting(session) => ActorStatus::Disconnecting {
                permissions: session.permissions,
            },
            Self::Closed { reason } => ActorStatus::Closed {
                reason: reason.clone(),
            },
        }
    }
}

/// Public projection of the actor's lifecycle state for observation and UI.
///
/// Contains the current lifecycle step, and exposes permissions only in states
/// where a valid session exists (`Connected`, `Downloading`, `Uploading`,
/// `Disconnecting`). Secrets such as transport and session salt are never exposed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ActorStatus {
    Created,
    Connecting,
    Connected {
        permissions: Permission,
    },
    Downloading {
        permissions: Permission,
    },
    Uploading {
        permissions: Permission,
    },
    Reconnecting {
        attempt: usize,
        reason: ReconnectReason,
    },
    Disconnecting {
        permissions: Permission,
    },
    Closed {
        reason: CloseReason,
    },
}

impl ActorStatus {
    /// Return the account permissions if the actor has a valid session.
    pub fn permissions(&self) -> Option<Permission> {
        match self {
            Self::Connected { permissions }
            | Self::Downloading { permissions }
            | Self::Uploading { permissions }
            | Self::Disconnecting { permissions } => Some(*permissions),
            _ => None,
        }
    }

    /// Whether the actor is currently in the `Connected` state.
    pub fn is_connected(&self) -> bool {
        matches!(self, Self::Connected { .. })
    }

    /// Whether the actor is in the terminal `Closed` state.
    pub fn is_closed(&self) -> bool {
        matches!(self, Self::Closed { .. })
    }
}

impl fmt::Display for ActorStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Created => write!(f, "created"),
            Self::Connecting => write!(f, "connecting"),
            Self::Connected { permissions } => write!(f, "connected ({permissions:?})"),
            Self::Downloading { .. } => write!(f, "downloading"),
            Self::Uploading { .. } => write!(f, "uploading"),
            Self::Reconnecting { attempt, reason } => {
                write!(f, "reconnecting (attempt {attempt}: {reason})")
            }
            Self::Disconnecting { .. } => write!(f, "disconnecting"),
            Self::Closed { reason } => write!(f, "closed ({reason})"),
        }
    }
}

/// Reason why an actor entered the `Reconnecting` state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReconnectReason {
    /// Device is rebooting after a successful firmware update.
    FirmwareUpdate,
    /// An I/O error occurred on the TCP socket.
    Io(String),
    /// Protocol framing or decoding error.
    ProtocolError(String),
    /// Connection or command timed out.
    Timeout,
    /// Remote end closed the TCP connection.
    ConnectionClosed,
}

impl From<&crate::error::Error> for ReconnectReason {
    fn from(value: &crate::error::Error) -> Self {
        match value {
            crate::error::Error::Timeout => ReconnectReason::Timeout,
            crate::error::Error::ConnectionClosed => ReconnectReason::ConnectionClosed,
            crate::error::Error::Io(error) => ReconnectReason::Io(error.to_string()),
            _ => ReconnectReason::ProtocolError(value.to_string()),
        }
    }
}

impl fmt::Display for ReconnectReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::FirmwareUpdate => write!(f, "firmware update"),
            Self::Io(err) => write!(f, "I/O error: {err}"),
            Self::ProtocolError(err) => write!(f, "protocol error: {err}"),
            Self::Timeout => write!(f, "timeout"),
            Self::ConnectionClosed => write!(f, "connection closed"),
        }
    }
}

/// Reason why an actor entered the `Closed` state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CloseReason {
    /// Explicitly requested via [`Actor::shutdown`](crate::actor::Actor::shutdown).
    Shutdown,
    /// Maximum reconnect attempts exceeded under policy.
    ReconnectFailed { attempts: usize },
    /// Connection was closed and automatic reconnect is disabled.
    Disconnected,
}

impl fmt::Display for CloseReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Shutdown => write!(f, "shutdown requested"),
            Self::ReconnectFailed { attempts } => {
                write!(f, "reconnection failed after {attempts} attempts")
            }
            Self::Disconnected => write!(f, "disconnected"),
        }
    }
}

/// Deterministic reconnect policy for automatic recovery.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum ReconnectPolicy {
    /// Auto-reconnect disabled. Upon connection loss the actor transitions to `Closed`.
    #[default]
    None,
    /// Fixed delay between attempts.
    Fixed(Duration),
    /// Fixed delay with a maximum number of attempts.
    FixedWithLimit(Duration, usize),
    /// Exponential backoff delay: `initial * factor^(attempt - 1)` (without random jitter).
    Exponent(Duration, f64),
    /// Exponential backoff delay with a maximum number of attempts.
    ExponentWithLimit(Duration, f64, usize),
}

impl ReconnectPolicy {
    /// Delay for a 1-based retry, excluding the initial connection attempt.
    /// Invalid exponential factors disable recovery; arithmetic overflow saturates.
    pub fn delay_for_attempt(&self, attempt: usize) -> Option<Duration> {
        if attempt == 0 {
            return None;
        }
        let (initial, factor) = match *self {
            Self::None => return None,
            Self::Fixed(delay) => return Some(delay),
            Self::FixedWithLimit(delay, limit) => return (attempt <= limit).then_some(delay),
            Self::Exponent(initial, factor) => (initial, factor),
            Self::ExponentWithLimit(initial, factor, limit) => {
                if attempt > limit {
                    return None;
                }
                (initial, factor)
            }
        };
        if !factor.is_finite() || factor < 0.0 {
            return None;
        }
        if attempt == 1 || initial.is_zero() {
            return Some(initial);
        }
        let seconds = initial.as_secs_f64() * factor.powf((attempt - 1) as f64);
        Some(Duration::try_from_secs_f64(seconds).unwrap_or(Duration::MAX))
    }
}

/// Intent to alter the actor connection lifecycle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LifecycleIntent {
    Connect,
    Shutdown,
}

/// Bounded plan of pending lifecycle intents (capacity 4).
///
/// Reduces adjacent duplicate intents and cancels unstarted opposite intents.
#[derive(Debug, Default)]
pub(crate) struct PendingPlan {
    intents: VecDeque<LifecycleIntent>,
}

impl PendingPlan {
    pub(crate) const CAPACITY: usize = 4;

    /// Enqueue a lifecycle intent, applying deduplication and reduction rules.
    pub(crate) fn push(&mut self, intent: LifecycleIntent, current_state: &ActorState) {
        // 1. Deduplicate adjacent identical intents
        if self.intents.back() == Some(&intent) {
            return;
        }

        // 2. Redundant Connect:
        // In Connecting, Connected, or Reconnecting without a pending Shutdown,
        // a new Connect intent is redundant and cannot reset backoff or resurrect after exhaustion.
        if intent == LifecycleIntent::Connect
            && self.intents.back() != Some(&LifecycleIntent::Shutdown)
            && matches!(
                current_state,
                ActorState::Connecting
                    | ActorState::Connected(_)
                    | ActorState::Downloading(_)
                    | ActorState::Uploading(_)
                    | ActorState::Reconnecting { .. }
            )
        {
            return;
        }

        // 3. Cancellation of not-yet-started opposite intents:
        // If Shutdown arrives and Connect is pending while we are in Created or Closed,
        // the unstarted Connect is cancelled.
        if intent == LifecycleIntent::Shutdown
            && self.intents.back() == Some(&LifecycleIntent::Connect)
            && matches!(
                current_state,
                ActorState::Created | ActorState::Closed { .. }
            )
        {
            self.intents.pop_back();
            return;
        }

        assert!(
            self.intents.len() < Self::CAPACITY,
            "lifecycle plan capacity exceeded"
        );

        self.intents.push_back(intent);
    }

    /// Drain all available lifecycle intents from the receiver into the plan.
    pub(crate) fn drain_from_receiver(
        &mut self,
        rx: &mut tokio::sync::mpsc::Receiver<LifecycleIntent>,
        current_state: &ActorState,
    ) {
        for _ in 0..Self::CAPACITY.saturating_sub(self.intents.len()) {
            match rx.try_recv() {
                Ok(intent) => self.push(intent, current_state),
                Err(_) => break,
            }
        }
    }
    /// Pop the next pending lifecycle intent.
    pub(crate) fn pop(&mut self) -> Option<LifecycleIntent> {
        self.intents.pop_front()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn salt_redacted_and_as_str() {
        let salt = Salt::new("secret_salt_123");
        assert_eq!(salt.as_str(), "secret_salt_123");
        assert_eq!(format!("{salt:?}"), "[REDACTED]");
        assert_eq!(format!("{salt}"), "[REDACTED]");
    }

    #[test]
    fn reconnect_delays_preserve_growth_and_retry_limit() {
        let policy = ReconnectPolicy::ExponentWithLimit(Duration::from_millis(10), 2.0, 3);
        assert_eq!(policy.delay_for_attempt(1), Some(Duration::from_millis(10)));
        assert_eq!(policy.delay_for_attempt(3), Some(Duration::from_millis(40)));
        assert_eq!(policy.delay_for_attempt(4), None);
        let unbounded = ReconnectPolicy::Exponent(Duration::from_secs(1), 2.0);
        assert_eq!(unbounded.delay_for_attempt(usize::MAX), Some(Duration::MAX));
        assert_eq!(
            ReconnectPolicy::Exponent(Duration::ZERO, 2.0).delay_for_attempt(usize::MAX),
            Some(Duration::ZERO)
        );
        assert_eq!(
            ReconnectPolicy::Exponent(Duration::from_secs(1), f64::NAN).delay_for_attempt(2),
            None
        );
    }

    #[test]
    fn pending_plan_reduction_and_cancellation() {
        let mut plan = PendingPlan::default();
        let created = ActorState::Created;

        // 1. Connect followed by Shutdown in Created cancels Connect
        plan.push(LifecycleIntent::Connect, &created);
        assert_eq!(plan.intents.len(), 1);
        plan.push(LifecycleIntent::Shutdown, &created);
        assert_eq!(plan.intents.len(), 0);

        // 2. Adjacent duplicates no-op
        plan.push(LifecycleIntent::Connect, &created);
        plan.push(LifecycleIntent::Connect, &created);
        assert_eq!(plan.intents.len(), 1);
        assert_eq!(plan.pop(), Some(LifecycleIntent::Connect));

        // 3. Redundant Connect in Connecting/Reconnecting is dropped
        let connecting = ActorState::Connecting;
        plan.push(LifecycleIntent::Connect, &connecting);
        assert_eq!(plan.pop(), None);

        let reconnecting = ActorState::Reconnecting {
            attempt: 1,
            reason: ReconnectReason::Timeout,
        };
        plan.push(LifecycleIntent::Connect, &reconnecting);
        assert_eq!(plan.pop(), None);

        // 4. Shutdown then Connect survives (e.g. shutdown(); connect();)
        plan.push(LifecycleIntent::Shutdown, &connecting);
        plan.push(LifecycleIntent::Connect, &connecting);
        assert_eq!(plan.pop(), Some(LifecycleIntent::Shutdown));
        assert_eq!(plan.pop(), Some(LifecycleIntent::Connect));
    }
}