kiteticker-async-manager 0.4.0

High-performance async WebSocket client for Kite Connect API with multi-connection support, dynamic subscription management, and optimized data processing.
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
use crate::manager::{ChannelId, ConnectionStats, KiteManagerConfig};
use crate::models::{Mode, TickerMessage};
use crate::ticker::KiteTickerAsync;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{mpsc, RwLock};
use tokio::task::JoinHandle;
use tokio::time::timeout;

/// Represents a single WebSocket connection with its metadata
#[derive(Debug)]
pub struct ManagedConnection {
  pub id: ChannelId,
  pub ticker: Option<KiteTickerAsync>,
  pub subscriber: Option<crate::ticker::KiteTickerSubscriber>,
  pub subscribed_symbols: HashMap<u32, Mode>,
  pub stats: Arc<RwLock<ConnectionStats>>,
  pub is_healthy: Arc<AtomicBool>,
  pub last_ping: Arc<AtomicU64>, // Unix timestamp
  pub task_handle: Option<JoinHandle<()>>,
  // Background watcher to update last_ping on any inbound frame (including heartbeats)
  pub heartbeat_handle: Option<JoinHandle<()>>,
  pub message_sender: mpsc::UnboundedSender<TickerMessage>,
  // Store credentials for dynamic operations
  api_key: String,
  access_token: String,
  pub(crate) cmd_tx:
    Option<mpsc::UnboundedSender<tokio_tungstenite::tungstenite::Message>>,
  // Liveness threshold for heartbeats/frames
  heartbeat_liveness_threshold: Duration,
}

impl ManagedConnection {
  pub fn new(
    id: ChannelId,
    message_sender: mpsc::UnboundedSender<TickerMessage>,
  ) -> Self {
    let stats = ConnectionStats {
      connection_id: id.to_index(),
      ..Default::default()
    };

    Self {
      id,
      ticker: None,
      subscriber: None,
      subscribed_symbols: HashMap::new(),
      stats: Arc::new(RwLock::new(stats)),
      is_healthy: Arc::new(AtomicBool::new(false)),
      last_ping: Arc::new(AtomicU64::new(0)),
      task_handle: None,
      heartbeat_handle: None,
      message_sender,
      api_key: String::new(),
      access_token: String::new(),
      cmd_tx: None,
      heartbeat_liveness_threshold: Duration::from_secs(10),
    }
  }

  /// Connect to WebSocket and start message processing
  pub async fn connect(
    &mut self,
    api_key: &str,
    access_token: &str,
    config: &KiteManagerConfig,
  ) -> Result<(), String> {
    // Store credentials for dynamic operations
    self.api_key = api_key.to_string();
    self.access_token = access_token.to_string();

    // Connect to WebSocket
    let ticker = timeout(
      config.connection_timeout,
      KiteTickerAsync::connect(api_key, access_token),
    )
    .await
    .map_err(|_| "Connection timeout".to_string())?
    .map_err(|e| format!("Connection failed: {}", e))?;

    self.cmd_tx = ticker.command_sender();
    // Initialize last_ping to now and start heartbeat watcher
    let now_sec = std::time::SystemTime::now()
      .duration_since(std::time::UNIX_EPOCH)
      .unwrap_or_default()
      .as_secs();
    self.last_ping.store(now_sec, Ordering::Relaxed);
    self.ticker = Some(ticker);
    self.start_heartbeat_watcher();
    // Set configured liveness threshold
    self.heartbeat_liveness_threshold = config.heartbeat_liveness_threshold;
    self.is_healthy.store(true, Ordering::Relaxed);

    // Update stats
    {
      let mut stats = self.stats.write().await;
      stats.is_connected = true;
      stats.connection_uptime = Duration::ZERO;
    }

    Ok(())
  }

  /// Start a background watcher that listens to raw frames and updates `last_ping`.
  fn start_heartbeat_watcher(&mut self) {
    // Drop existing watcher if any
    if let Some(h) = self.heartbeat_handle.take() {
      h.abort();
    }
    let Some(ticker) = self.ticker.as_ref() else {
      return;
    };
    let mut rx = ticker.subscribe_raw_frames();
    let last_ping = Arc::clone(&self.last_ping);
    let id = self.id;
    let handle = tokio::spawn(async move {
      loop {
        match rx.recv().await {
          Ok(_frame) => {
            let now = std::time::SystemTime::now()
              .duration_since(std::time::UNIX_EPOCH)
              .unwrap_or_default()
              .as_secs();
            last_ping.store(now, Ordering::Relaxed);
          }
          Err(tokio::sync::broadcast::error::RecvError::Closed) => {
            log::debug!(
              "Heartbeat watcher closed for connection {}",
              id.to_index()
            );
            break;
          }
          Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
            // If lagging, just continue; we'll get a fresher frame soon
            continue;
          }
        }
      }
    });
    self.heartbeat_handle = Some(handle);
  }

  /// Connect with explicit raw_only flag
  pub async fn connect_with_raw(
    &mut self,
    api_key: &str,
    access_token: &str,
    config: &KiteManagerConfig,
    raw_only: bool,
  ) -> Result<(), String> {
    self.api_key = api_key.to_string();
    self.access_token = access_token.to_string();
    let ticker = tokio::time::timeout(
      config.connection_timeout,
      crate::ticker::KiteTickerAsync::connect_with_options(
        api_key,
        access_token,
        raw_only,
      ),
    )
    .await
    .map_err(|_| "Connection timeout".to_string())?
    .map_err(|e| format!("Connection failed: {}", e))?;

    self.cmd_tx = ticker.command_sender();
    // Initialize last_ping to now and start heartbeat watcher
    let now_sec = std::time::SystemTime::now()
      .duration_since(std::time::UNIX_EPOCH)
      .unwrap_or_default()
      .as_secs();
    self
      .last_ping
      .store(now_sec, std::sync::atomic::Ordering::Relaxed);
    self.ticker = Some(ticker);
    self.start_heartbeat_watcher();
    self
      .is_healthy
      .store(true, std::sync::atomic::Ordering::Relaxed);
    // Set configured liveness threshold
    self.heartbeat_liveness_threshold = config.heartbeat_liveness_threshold;
    {
      let mut stats = self.stats.write().await;
      stats.is_connected = true;
      stats.connection_uptime = Duration::ZERO;
    }
    Ok(())
  }

  /// Subscribe to symbols on this connection
  pub async fn subscribe_symbols(
    &mut self,
    symbols: &[u32],
    mode: Mode,
  ) -> Result<(), String> {
    if let Some(ticker) = self.ticker.as_mut() {
      // Use the existing ticker directly
      let subscriber = ticker.subscribe(symbols, Some(mode)).await?;
      // Track symbols
      for &symbol in symbols {
        self.subscribed_symbols.insert(symbol, mode);
      }
      self.subscriber = Some(subscriber);

      // Update stats
      {
        let mut stats = self.stats.write().await;
        stats.symbol_count = self.subscribed_symbols.len();
      }

      Ok(())
    } else {
      Err("Connection not established".to_string())
    }
  }

  /// Dynamically add new symbols to existing subscription
  pub async fn add_symbols(
    &mut self,
    symbols: &[u32],
    mode: Mode,
  ) -> Result<(), String> {
    if self.subscriber.is_some() {
      // Filter to truly new symbols
      let new: Vec<u32> = symbols
        .iter()
        .copied()
        .filter(|s| !self.subscribed_symbols.contains_key(s))
        .collect();
      if new.is_empty() {
        return Ok(());
      }
      if let Some(tx) = &self.cmd_tx {
        // send subscribe + mode
        let sub = crate::models::Request::subscribe(&new).to_string();
        let mode_msg = crate::models::Request::mode(mode, &new).to_string();
        let _ =
          tx.send(tokio_tungstenite::tungstenite::Message::Text(sub.into()));
        let _ = tx.send(tokio_tungstenite::tungstenite::Message::Text(
          mode_msg.into(),
        ));
      }
      for &s in &new {
        self.subscribed_symbols.insert(s, mode);
      }
      let mut stats = self.stats.write().await;
      stats.symbol_count = self.subscribed_symbols.len();
      log::info!(
        "Incrementally subscribed {} symbols on connection {}",
        new.len(),
        self.id.to_index()
      );
      Ok(())
    } else {
      self.subscribe_symbols(symbols, mode).await
    }
  }

  /// Dynamically remove symbols from existing subscription
  pub async fn remove_symbols(
    &mut self,
    symbols: &[u32],
  ) -> Result<(), String> {
    if self.subscriber.is_some() {
      // Only symbols currently subscribed
      let existing: Vec<u32> = symbols
        .iter()
        .copied()
        .filter(|s| self.subscribed_symbols.contains_key(s))
        .collect();
      if existing.is_empty() {
        return Ok(());
      }
      if let Some(tx) = &self.cmd_tx {
        let unsub = crate::models::Request::unsubscribe(&existing).to_string();
        let _ =
          tx.send(tokio_tungstenite::tungstenite::Message::Text(unsub.into()));
      }
      for s in &existing {
        self.subscribed_symbols.remove(s);
      }
      let mut stats = self.stats.write().await;
      stats.symbol_count = self.subscribed_symbols.len();
      log::info!(
        "Incrementally unsubscribed {} symbols on connection {}",
        existing.len(),
        self.id.to_index()
      );
      Ok(())
    } else {
      Err("No active subscription to remove symbols from".to_string())
    }
  }

  /// Start message processing for the subscriber
  pub async fn start_message_processing(&mut self) -> Result<(), String> {
    if let Some(subscriber) = self.subscriber.take() {
      let message_sender = self.message_sender.clone();
      let stats = Arc::clone(&self.stats);
      let is_healthy = Arc::clone(&self.is_healthy);
      let last_ping = Arc::clone(&self.last_ping);
      let connection_id = self.id;
      let threshold = self.heartbeat_liveness_threshold;

      let handle = tokio::spawn(async move {
        Self::message_processing_loop(
          subscriber,
          message_sender,
          stats,
          is_healthy,
          connection_id,
          last_ping,
          threshold,
        )
        .await;
      });

      self.task_handle = Some(handle);
      Ok(())
    } else {
      Err("No subscriber available for message processing".to_string())
    }
  }

  /// Message processing loop for this connection
  async fn message_processing_loop(
    mut subscriber: crate::ticker::KiteTickerSubscriber,
    message_sender: mpsc::UnboundedSender<TickerMessage>,
    stats: Arc<RwLock<ConnectionStats>>,
    is_healthy: Arc<AtomicBool>,
    connection_id: ChannelId,
    last_ping: Arc<AtomicU64>,
    heartbeat_threshold: Duration,
  ) {
    let mut last_message_time = Instant::now();
    let mut last_stats_flush = Instant::now();
    let mut pending_messages: u64 = 0;

    log::info!(
      "Starting message processing loop for connection {}",
      connection_id.to_index()
    );

    loop {
      match timeout(Duration::from_secs(30), subscriber.next_message()).await {
        Ok(Ok(Some(message))) => {
          last_message_time = Instant::now();

          // Debug: Print incoming message
          if log::log_enabled!(log::Level::Debug) {
            match &message {
              TickerMessage::Ticks(ticks) => {
                log::debug!(
                  "Connection {}: Received {} ticks",
                  connection_id.to_index(),
                  ticks.len()
                );
                for (i, tick) in ticks.iter().take(3).enumerate() {
                  log::debug!(
                    "  Tick {}: Symbol {}, Mode {:?}, LTP {:?}",
                    i + 1,
                    tick.instrument_token,
                    tick.content.mode,
                    tick.content.last_price
                  );
                }
              }
              TickerMessage::Error(err) => {
                log::debug!(
                  "Connection {}: Received error message: {}",
                  connection_id.to_index(),
                  err
                );
              }
              _ => {
                log::debug!(
                  "Connection {}: Received other message: {:?}",
                  connection_id.to_index(),
                  message
                );
              }
            }
          }

          // Update stats
          pending_messages += 1;
          if last_stats_flush.elapsed() >= Duration::from_millis(1000) {
            let mut stats = stats.write().await;
            stats.messages_received += pending_messages;
            stats.last_message_time = Some(last_message_time);
            pending_messages = 0;
            last_stats_flush = Instant::now();
          }

          // Forward message to parser (non-blocking)
          if message_sender.send(message).is_err() {
            log::warn!(
              "Connection {}: Parser channel full, dropping message",
              connection_id.to_index()
            );

            // Update error stats
            let mut stats = stats.write().await;
            stats.errors_count += 1;
          }
        }
        Ok(Ok(None)) => {
          log::info!("Connection {} closed", connection_id.to_index());
          is_healthy.store(false, Ordering::Relaxed);
          break;
        }
        Ok(Err(e)) => {
          log::error!("Connection {} error: {}", connection_id.to_index(), e);

          // Update error stats
          if last_stats_flush.elapsed() >= Duration::from_millis(250) {
            let mut stats = stats.write().await;
            stats.errors_count += 1;
            last_stats_flush = Instant::now();
          }

          // Continue trying to receive messages
        }
        Err(_) => {
          // Timeout waiting for parsed messages; consult heartbeat/frames
          let now_sec = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
          let last = last_ping.load(Ordering::Relaxed);
          // If we've seen any frame within threshold, consider connection alive
          if last > 0
            && now_sec.saturating_sub(last) <= heartbeat_threshold.as_secs()
          {
            continue;
          }
          // Fallback to parsed message timer if heartbeat missed
          if last_message_time.elapsed() > heartbeat_threshold {
            log::warn!(
              "Connection {} timeout - no frames/heartbeats within {:?}",
              connection_id.to_index(),
              heartbeat_threshold,
            );
            is_healthy.store(false, Ordering::Relaxed);
            break;
          }
        }
      }
    }

    // Update connection status
    {
      let mut stats = stats.write().await;
      stats.is_connected = false;
    }
    is_healthy.store(false, Ordering::Relaxed);
  }

  /// Check if connection can accept more symbols
  pub fn can_accept_symbols(
    &self,
    count: usize,
    max_per_connection: usize,
  ) -> bool {
    self.subscribed_symbols.len() + count <= max_per_connection
  }

  /// Get current symbol count
  pub fn symbol_count(&self) -> usize {
    self.subscribed_symbols.len()
  }

  /// Check if connection is healthy
  pub fn is_healthy(&self) -> bool {
    self.is_healthy.load(Ordering::Relaxed)
  }
}