mocra-core 0.4.0

The mocra crawler framework runtime: errors, cache, utilities, domain models, downloader, data-plane queue, coordination, scheduler and engine.
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
use crate::common::policy::PolicyConfig;
use mocra_proxy::ProxyConfig;
use serde::{Deserialize, Serialize};
use std::fmt;

/// API Configuration
#[derive(Serialize, Deserialize, Clone)]
pub struct Api {
    /// Port number for the API server
    pub port: u16,
    /// Optional API key for authentication
    pub api_key: Option<String>,
    /// Optional Rate Limit (requests per second)
    pub rate_limit: Option<f64>,
}

impl fmt::Debug for Api {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Api")
            .field("port", &self.port)
            .field("api_key", &self.api_key.as_ref().map(|_| "***REDACTED***"))
            .field("rate_limit", &self.rate_limit)
            .finish()
    }
}

/// Redis Configuration
#[derive(Serialize, Deserialize, Clone)]
pub struct RedisConfig {
    /// Redis server hostname
    pub redis_host: String,
    /// Redis server port
    pub redis_port: u16,
    /// Redis database index
    pub redis_db: u16,
    /// Optional Redis username
    pub redis_username: Option<String>,
    /// Optional Redis password
    pub redis_password: Option<String>,
    /// Connection pool size
    pub pool_size: Option<usize>,
    /// Number of shards for stream operations
    pub shards: Option<usize>,
    /// Enable TLS for connection
    pub tls: Option<bool>,
    /// Minimum idle time in milliseconds for claiming stuck messages (default: 600000)
    pub claim_min_idle: Option<u64>,
    /// Number of messages to claim at once (default: 10)
    pub claim_count: Option<usize>,
    /// Interval in milliseconds for claiming stuck messages check (default: 60000)
    pub claim_interval: Option<u64>,
    /// Number of listener tasks for sharded multiplexing (default: 4)
    pub listener_count: Option<usize>,
}

impl fmt::Debug for RedisConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RedisConfig")
            .field("redis_host", &self.redis_host)
            .field("redis_port", &self.redis_port)
            .field("redis_db", &self.redis_db)
            .field("redis_username", &self.redis_username)
            .field(
                "redis_password",
                &self.redis_password.as_ref().map(|_| "***REDACTED***"),
            )
            .field("pool_size", &self.pool_size)
            .field("shards", &self.shards)
            .field("tls", &self.tls)
            .finish()
    }
}

/// Database Configuration
#[derive(Serialize, Deserialize, Clone)]
pub struct DatabaseConfig {
    /// Connection URL
    pub url: Option<String>,
    /// Database schema
    pub database_schema: Option<String>,
    /// Connection pool size
    pub pool_size: Option<u32>,
    /// Enable TLS (sslmode=require)
    pub tls: Option<bool>,
}

impl fmt::Debug for DatabaseConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DatabaseConfig")
            .field("url", &self.url.as_ref().map(|_| "***REDACTED***"))
            .field("database_schema", &self.database_schema)
            .field("pool_size", &self.pool_size)
            .field("tls", &self.tls)
            .finish()
    }
}

/// Downloader Configuration
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DownloadConfig {
    /// Downloader expiration time in seconds
    pub downloader_expire: u64,
    /// Request timeout in seconds
    pub timeout: u32,
    /// Rate limit in requests per second
    pub rate_limit: f32,
    /// Enable session cache/sync behavior
    pub enable_session: bool,
    /// Enable distributed locking
    pub enable_locker: bool,
    /// Enable rate limiting
    pub enable_rate_limit: bool,
    /// Cache TTL in seconds
    pub cache_ttl: u64,
    /// WebSocket timeout in seconds
    pub wss_timeout: u32,
    /// Connection pool size for HTTP client (default: 200)
    pub pool_size: Option<usize>,
    /// Maximum response size in bytes (default: 10MB)
    pub max_response_size: Option<usize>,
}

/// Synchronization Configuration
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SyncConfig {
    /// Redis configuration for synchronization
    pub redis: Option<RedisConfig>,
    /// Kafka configuration for synchronization
    pub kafka: Option<KafkaConfig>,
    /// Allow rollback to older versions (default: true)
    #[serde(default = "default_sync_allow_rollback")]
    pub allow_rollback: bool,
    /// Enable versioned envelope for sync payloads (default: false)
    #[serde(default = "default_sync_envelope_enabled")]
    pub envelope_enabled: bool,
}

fn default_sync_allow_rollback() -> bool {
    true
}

fn default_sync_envelope_enabled() -> bool {
    false
}

impl Default for SyncConfig {
    fn default() -> Self {
        Self {
            redis: None,
            kafka: None,
            allow_rollback: true,
            envelope_enabled: false,
        }
    }
}

/// Cache Configuration
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CacheConfig {
    /// Default TTL for cache items
    pub ttl: u64,
    /// Redis configuration for cache storage
    pub redis: Option<RedisConfig>,
    /// Compression threshold in bytes (payloads larger than this will be compressed)
    pub compression_threshold: Option<usize>,
    /// Enable L1 local cache layer (default: false)
    pub enable_l1: Option<bool>,
    /// L1 cache TTL in seconds (default: 30)
    pub l1_ttl_secs: Option<u64>,
    /// L1 cache max entries before eviction (default: 10000)
    pub l1_max_entries: Option<usize>,
}

/// Crawler Configuration
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CrawlerConfig {
    /// Maximum retries for failed requests
    pub request_max_retries: usize,
    /// Maximum allowed errors per task
    pub task_max_errors: usize,
    /// Maximum allowed errors per module
    pub module_max_errors: usize,
    /// TTL for module locks
    pub module_locker_ttl: u64,
    /// Optional node ID (useful for stable node identity across restarts)
    pub node_id: Option<String>,
    /// Concurrency for task processor (JS execution)
    pub task_concurrency: Option<usize>,
    /// Concurrency for request publishing
    pub publish_concurrency: Option<usize>,
    /// Concurrency for parser task processor
    pub parser_concurrency: Option<usize>,
    /// Concurrency for error task processor
    pub error_task_concurrency: Option<usize>,
    /// Delay in milliseconds before retrying when backpressure is detected
    pub backpressure_retry_delay_ms: Option<u64>,
    /// Request deduplication TTL in seconds (default: 3600)
    pub dedup_ttl_secs: Option<u64>,
    /// Idle stop timeout in seconds (stop engine if local queues have no data for this duration)
    pub idle_stop_secs: Option<u64>,
}

/// Scheduler Configuration
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SchedulerConfig {
    /// Maximum tolerance in seconds for missed cron jobs (default: 300)
    pub misfire_tolerance_secs: Option<i64>,
    /// Max concurrency for processing scheduled contexts (default: 100)
    pub concurrency: Option<usize>,
    /// Refresh interval in seconds for scheduler cache (default: 60)
    pub refresh_interval_secs: Option<u64>,
    /// Max allowed staleness in seconds before forcing refresh (default: 120)
    pub max_staleness_secs: Option<u64>,
}

/// Kafka Configuration
#[derive(Serialize, Deserialize, Clone)]
pub struct KafkaConfig {
    /// Comma-separated list of brokers
    pub brokers: String,
    /// SASL username
    pub username: Option<String>,
    /// SASL password
    pub password: Option<String>,
    /// Enable TLS
    pub tls: Option<bool>,
}

impl fmt::Debug for KafkaConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("KafkaConfig")
            .field("brokers", &self.brokers)
            .field("username", &self.username)
            .field(
                "password",
                &self.password.as_ref().map(|_| "***REDACTED***"),
            )
            .field("tls", &self.tls)
            .finish()
    }
}

/// NATS (JetStream) Configuration
#[derive(Serialize, Deserialize, Clone)]
pub struct NatsConfig {
    /// 服务器地址(如 `nats://127.0.0.1:4222`;逗号分隔多个)。
    pub url: String,
    /// 可选用户名。
    pub username: Option<String>,
    /// 可选密码。
    pub password: Option<String>,
    /// 可选 token 认证。
    pub token: Option<String>,
}

impl fmt::Debug for NatsConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NatsConfig")
            .field("url", &self.url)
            .field("username", &self.username)
            .field(
                "password",
                &self.password.as_ref().map(|_| "***REDACTED***"),
            )
            .field("token", &self.token.as_ref().map(|_| "***REDACTED***"))
            .finish()
    }
}

/// Blob Storage Configuration
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BlobStorageConfig {
    /// Local file system path for blob storage
    pub path: Option<String>,
}

/// Channel (Queue) Configuration
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ChannelConfig {
    /// Blob storage configuration
    pub blob_storage: Option<BlobStorageConfig>,
    /// Redis configuration for queue
    pub redis: Option<RedisConfig>,
    /// Kafka configuration for queue
    pub kafka: Option<KafkaConfig>,
    /// NATS (JetStream) configuration for queue
    #[serde(default)]
    pub nats: Option<NatsConfig>,
    /// Compensator Redis configuration (for dead letter or retry)
    pub compensator: Option<RedisConfig>,
    /// Minimum ID time (snowflake/uuid related)
    pub minid_time: u64,
    /// Channel capacity
    pub capacity: usize,
    /// Queue codec: json | msgpack
    pub queue_codec: Option<String>,
    /// Concurrency limit for batch flushing (default: 10)
    pub batch_concurrency: Option<usize>,
    /// Compression threshold in bytes (payloads larger than this will be compressed)
    pub compression_threshold: Option<usize>,
    /// Max retries for NACK before sending to DLQ (default: 0)
    pub nack_max_retries: Option<u32>,
    /// Backoff in milliseconds before retrying NACK (default: 0)
    pub nack_backoff_ms: Option<u64>,
}

use super::logger_config::LoggerConfig;

/// Event Bus Configuration
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EventBusConfig {
    /// Channel capacity for events (default: 1024)
    pub capacity: usize,
    /// Concurrency limit for event handlers (default: 64)
    pub concurrency: usize,
}

/// Main Configuration
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Config {
    /// Application instance name
    pub name: String,
    /// Database configuration
    pub db: DatabaseConfig,
    /// Download configuration
    pub download_config: DownloadConfig,
    /// Cache configuration
    pub cache: CacheConfig,
    /// Crawler behavior configuration
    pub crawler: CrawlerConfig,
    /// Scheduler configuration
    pub scheduler: Option<SchedulerConfig>,
    /// Synchronization configuration
    pub sync: Option<SyncConfig>,
    /// Cookie storage configuration
    pub cookie: Option<RedisConfig>,
    /// Message channel configuration
    pub channel_config: ChannelConfig,
    /// Proxy configuration
    pub proxy: Option<ProxyConfig>,
    /// API server configuration
    pub api: Option<Api>,
    /// Event Bus configuration
    pub event_bus: Option<EventBusConfig>,
    /// Logger configuration
    pub logger: Option<LoggerConfig>,
    /// Policy configuration (override default error strategies)
    pub policy: Option<PolicyConfig>,
}
impl Config {
    /// Whether current config should run in single-node mode.
    ///
    /// Rule: if cache.redis is configured, runtime is distributed;
    /// otherwise it is single-node mode.
    pub fn is_single_node_mode(&self) -> bool {
        self.cache.redis.is_none()
    }

    /// Loads configuration from a TOML file
    pub fn load(path: &str) -> Result<Self, String> {
        // Read `config.toml` file content.
        let config_str = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
        let config: Config = toml::from_str(&config_str).map_err(|e| e.to_string())?;
        Ok(config)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[allow(unused_imports)]
    use std::io::Write;
    #[allow(unused_imports)]
    use tempfile::NamedTempFile;

    #[test]
    fn test_config_deserialization() {
        let toml_str = r#"
            name = "test_app"
            
            [db]
            url = "postgres://user:password@localhost:5432/db"
            database_schema = "public"
            
            [download_config]
            downloader_expire = 3600
            timeout = 30
            rate_limit = 10.0
            enable_session = true
            enable_locker = false
            enable_rate_limit = true
            cache_ttl = 600
            wss_timeout = 60
            
            [cache]
            ttl = 3600
            
            [crawler]
            request_max_retries = 3
            task_max_errors = 5
            module_max_errors = 10
            module_locker_ttl = 60
            
            [channel_config]
            minid_time = 0
            capacity = 1000
        "#;

        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.name, "test_app");
        assert_eq!(
            config.db.url.as_deref(),
            Some("postgres://user:password@localhost:5432/db")
        );
        assert_eq!(config.crawler.request_max_retries, 3);
        assert!(config.proxy.is_none());
    }
}