market2nats 0.1.0

WebSocket market data → NATS JetStream relay
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
use serde::Deserialize;

/// Top-level application configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AppConfig {
    /// Service-level settings.
    pub service: ServiceConfig,
    /// Wire serialization settings for messages published to NATS.
    #[serde(default)]
    pub serialization: SerializationSettings,
    /// NATS connection and JetStream settings.
    pub nats: NatsConfig,
    /// Venue definitions.
    pub venues: Vec<VenueConfig>,
}

/// Wire serialization settings for NATS-published messages.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SerializationSettings {
    /// Wire format: `"json"` (default) or `"protobuf"`.
    #[serde(default = "default_serialization_format")]
    pub format: String,
}

impl Default for SerializationSettings {
    #[inline]
    fn default() -> Self {
        Self {
            format: default_serialization_format(),
        }
    }
}

#[inline]
fn default_serialization_format() -> String {
    "json".to_owned()
}

/// Service-level settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServiceConfig {
    /// Service name for logging and identification.
    pub name: String,
    /// Log level (tracing EnvFilter compatible).
    #[serde(default = "default_log_level")]
    pub log_level: String,
    /// Log format: "json" or "pretty".
    #[serde(default = "default_log_format")]
    pub log_format: String,
    /// Graceful shutdown timeout in milliseconds.
    #[serde(default = "default_shutdown_timeout")]
    pub shutdown_timeout_ms: u64,
}

/// NATS connection and JetStream configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NatsConfig {
    /// NATS server URLs.
    pub urls: Vec<String>,
    /// Connection timeout in milliseconds.
    #[serde(default = "default_connect_timeout")]
    pub connect_timeout_ms: u64,
    /// Buffer size during reconnection (bytes).
    #[serde(default = "default_reconnect_buffer")]
    pub reconnect_buffer_size: usize,
    /// Maximum reconnection attempts (-1 = unlimited).
    #[serde(default = "default_max_reconnects")]
    pub max_reconnects: i64,
    /// Ping interval in seconds.
    #[serde(default = "default_ping_interval")]
    pub ping_interval_secs: u64,
    /// Authentication method: "none", "token", "userpass", "nkey", "credentials".
    #[serde(default = "default_auth")]
    pub auth: String,
    /// Token for token-based auth (supports `${ENV_VAR}` substitution).
    pub token: Option<String>,
    /// Username for user/password auth (supports `${ENV_VAR}` substitution).
    pub username: Option<String>,
    /// Password for user/password auth (supports `${ENV_VAR}` substitution).
    pub password: Option<String>,
    /// Path to credentials file.
    pub credentials_path: Option<String>,
    /// NKey seed (supports `${ENV_VAR}` substitution).
    pub nkey_seed: Option<String>,
    /// TLS configuration.
    #[serde(default)]
    pub tls: NatsTlsConfig,
    /// JetStream stream definitions.
    #[serde(default)]
    pub streams: Vec<StreamConfig>,
    /// JetStream consumer definitions.
    #[serde(default)]
    pub consumers: Vec<ConsumerConfig>,
}

/// NATS TLS configuration.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NatsTlsConfig {
    /// Whether TLS is enabled.
    #[serde(default)]
    pub enabled: bool,
    /// Path to CA certificate.
    pub ca_path: Option<String>,
    /// Path to client certificate.
    pub cert_path: Option<String>,
    /// Path to client private key.
    pub key_path: Option<String>,
}

/// JetStream stream configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StreamConfig {
    /// Stream name.
    pub name: String,
    /// Subject patterns this stream captures.
    pub subjects: Vec<String>,
    /// Storage type: "file" or "memory".
    #[serde(default = "default_storage")]
    pub storage: String,
    /// Retention policy: "limits", "interest", or "workqueue".
    #[serde(default = "default_retention")]
    pub retention: String,
    /// Maximum age of messages in seconds (0 = no limit).
    #[serde(default)]
    pub max_age_secs: u64,
    /// Maximum total bytes (0 = no limit).
    #[serde(default)]
    pub max_bytes: i64,
    /// Maximum number of messages (0 = no limit).
    #[serde(default)]
    pub max_msgs: i64,
    /// Maximum message size in bytes.
    #[serde(default = "default_max_msg_size")]
    pub max_msg_size: i32,
    /// Discard policy: "old" or "new".
    #[serde(default = "default_discard")]
    pub discard: String,
    /// Number of replicas.
    #[serde(default = "default_num_replicas")]
    pub num_replicas: usize,
    /// Deduplication window in seconds.
    #[serde(default = "default_duplicate_window")]
    pub duplicate_window_secs: u64,
}

/// JetStream consumer configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConsumerConfig {
    /// Name of the stream this consumer belongs to.
    pub stream: String,
    /// Consumer name.
    pub name: String,
    /// Whether the consumer is durable.
    #[serde(default = "default_true")]
    pub durable: bool,
    /// Ack policy: "none", "all", or "explicit".
    #[serde(default = "default_ack_policy")]
    pub ack_policy: String,
    /// Ack wait timeout in seconds.
    #[serde(default = "default_ack_wait")]
    pub ack_wait_secs: u64,
    /// Maximum delivery attempts.
    #[serde(default = "default_max_deliver")]
    pub max_deliver: i64,
    /// Optional subject filter.
    pub filter_subject: Option<String>,
    /// Deliver policy: "all", "last", "new", or "by_start_time".
    #[serde(default = "default_deliver_policy")]
    pub deliver_policy: String,
    /// Start time for "by_start_time" deliver policy (RFC 3339).
    pub start_time: Option<String>,
    /// Maximum outstanding unacknowledged messages.
    #[serde(default)]
    pub max_ack_pending: i64,
    /// Inactive threshold in seconds before auto-delete (0 = never).
    #[serde(default)]
    pub inactive_threshold_secs: u64,
}

/// Configuration for a trading venue.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VenueConfig {
    /// Unique venue identifier (e.g., "binance").
    pub id: String,
    /// Adapter type: "binance", "generic_ws", etc.
    pub adapter: String,
    /// Whether this venue is enabled.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// WebSocket connection settings.
    pub connection: ConnectionConfig,
    /// Circuit breaker settings.
    #[serde(default)]
    pub circuit_breaker: Option<CircuitBreakerConfig>,
    /// Generic WebSocket adapter configuration (only for adapter = "generic_ws").
    pub generic_ws: Option<GenericWsConfig>,
    /// Subscriptions for this venue.
    pub subscriptions: Vec<SubscriptionConfig>,
}

/// WebSocket connection settings for a venue.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConnectionConfig {
    /// WebSocket URL.
    pub ws_url: String,
    /// Initial reconnect delay in milliseconds.
    #[serde(default = "default_reconnect_delay")]
    pub reconnect_delay_ms: u64,
    /// Maximum reconnect delay in milliseconds.
    #[serde(default = "default_max_reconnect_delay")]
    pub max_reconnect_delay_ms: u64,
    /// Maximum reconnect attempts (0 = unlimited).
    #[serde(default)]
    pub max_reconnect_attempts: u64,
    /// Ping interval in seconds.
    #[serde(default = "default_ws_ping_interval")]
    pub ping_interval_secs: u64,
    /// Pong timeout in seconds.
    #[serde(default = "default_pong_timeout")]
    pub pong_timeout_secs: u64,
}

/// Circuit breaker configuration for a venue.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CircuitBreakerConfig {
    /// Consecutive failures before opening the circuit.
    #[serde(default = "default_failure_threshold")]
    pub failure_threshold: u32,
    /// Seconds before trying half-open probe.
    #[serde(default = "default_reset_timeout")]
    pub reset_timeout_secs: u64,
    /// Probe requests allowed in half-open state.
    #[serde(default = "default_half_open_max")]
    pub half_open_max_requests: u32,
}

/// Configuration for the generic WebSocket adapter.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GenericWsConfig {
    /// Template for per-stream subscribe messages.
    ///
    /// Supported placeholders vary by `subscribe_mode`:
    /// - `"per_pair"` (default): `${channel}`, `${instrument}`.
    /// - `"per_channel"`: `${channel}`, `${instruments}` (JSON array of instrument strings).
    ///
    /// Not used in `"products_channels"` mode (use `batch_subscribe_template` instead).
    pub subscribe_template: Option<String>,
    /// Template for batch subscribe.
    ///
    /// Supported placeholders vary by `subscribe_mode`:
    /// - `"per_pair"` (default): `${params}` (JSON array of stream names built from
    ///   `stream_format`). Example: `{"method":"SUBSCRIBE","params":${params},"id":1}`
    /// - `"products_channels"`: `${instruments}` (JSON array of unique instrument strings)
    ///   and `${channels}` (JSON array of unique channel strings).
    pub batch_subscribe_template: Option<String>,
    /// Format for individual stream names in batch mode. Default: `${instrument}@${channel}`.
    #[serde(default = "default_stream_format")]
    pub stream_format: String,
    /// Map from MarketDataType subject strings to venue-specific channel names.
    pub channel_map: std::collections::HashMap<String, String>,
    /// Message format: "json" or "binary".
    #[serde(default = "default_message_format")]
    pub message_format: String,
    /// Subscribe mode: `"per_pair"` (default) sends one frame per (instrument, channel) pair.
    /// `"per_channel"` groups by channel and sends one frame per channel with `${instruments}`
    /// rendered as a JSON array of instrument strings.
    /// `"products_channels"` collects unique instruments and channels into separate arrays,
    /// rendering `${instruments}` and `${channels}` in a single frame.
    #[serde(default = "default_subscribe_mode")]
    pub subscribe_mode: String,
    /// Args format for batch subscribe: `"string"` (default) serializes stream names as a
    /// JSON array of strings. `"object"` parses each stream name as a JSON value and
    /// serializes the array without double-escaping.
    #[serde(default = "default_args_format")]
    pub args_format: String,
    /// Per-channel suffix appended to stream names after rendering `stream_format`.
    /// Keys are canonical data-type strings (e.g. `"trade"`, `"l2_orderbook"`), values
    /// are literal suffixes (e.g. `".raw"`, `".none.20.100ms"`).
    #[serde(default)]
    pub channel_suffix: std::collections::HashMap<String, String>,
}

/// Subscription configuration for a venue instrument.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SubscriptionConfig {
    /// Venue-local instrument identifier.
    pub instrument: String,
    /// Canonical symbol for NATS subject naming.
    pub canonical_symbol: String,
    /// Data types to subscribe to.
    pub data_types: Vec<String>,
}

// ── Default value functions ─────────────────────────────────────────────

#[inline]
fn default_log_level() -> String {
    "info".to_owned()
}

#[inline]
fn default_log_format() -> String {
    "json".to_owned()
}

#[inline]
fn default_shutdown_timeout() -> u64 {
    5000
}

#[inline]
fn default_connect_timeout() -> u64 {
    5000
}

#[inline]
fn default_reconnect_buffer() -> usize {
    8_388_608 // 8 MB
}

#[inline]
fn default_max_reconnects() -> i64 {
    -1
}

#[inline]
fn default_ping_interval() -> u64 {
    20
}

#[inline]
fn default_auth() -> String {
    "none".to_owned()
}

#[inline]
fn default_storage() -> String {
    "file".to_owned()
}

#[inline]
fn default_retention() -> String {
    "limits".to_owned()
}

#[inline]
fn default_max_msg_size() -> i32 {
    65_536 // 64 KB
}

#[inline]
fn default_discard() -> String {
    "old".to_owned()
}

#[inline]
fn default_num_replicas() -> usize {
    1
}

#[inline]
fn default_duplicate_window() -> u64 {
    120
}

#[inline]
fn default_true() -> bool {
    true
}

#[inline]
fn default_ack_policy() -> String {
    "explicit".to_owned()
}

#[inline]
fn default_ack_wait() -> u64 {
    30
}

#[inline]
fn default_max_deliver() -> i64 {
    5
}

#[inline]
fn default_deliver_policy() -> String {
    "all".to_owned()
}

#[inline]
fn default_reconnect_delay() -> u64 {
    1000
}

#[inline]
fn default_max_reconnect_delay() -> u64 {
    60_000
}

#[inline]
fn default_ws_ping_interval() -> u64 {
    30
}

#[inline]
fn default_pong_timeout() -> u64 {
    10
}

#[inline]
fn default_failure_threshold() -> u32 {
    5
}

#[inline]
fn default_reset_timeout() -> u64 {
    60
}

#[inline]
fn default_half_open_max() -> u32 {
    2
}

#[inline]
fn default_message_format() -> String {
    "json".to_owned()
}

#[inline]
fn default_stream_format() -> String {
    "${instrument}@${channel}".to_owned()
}

#[inline]
fn default_subscribe_mode() -> String {
    "per_pair".to_owned()
}

#[inline]
fn default_args_format() -> String {
    "string".to_owned()
}