mocra 0.3.0

A distributed, event-driven crawling and data collection framework
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
#![allow(unused)]
use crate::common::model::entity::*;
use crate::errors::OrmError;
use crate::errors::Result;
use crate::utils::txn::begin_read;
use sea_orm::{
    ColumnTrait, ConnectionTrait, DatabaseConnection, DbBackend, EntityTrait, QueryFilter,
    Statement, TryGetable, Value,
};
use std::collections::HashMap;
use std::sync::Arc;

/// Read-focused repository for loading task-related entities from database.
pub struct TaskRepository {
    db: Arc<DatabaseConnection>,
}

impl TaskRepository {
    /// Creates repository from SeaORM database connection.
    pub fn new(db: DatabaseConnection) -> Self {
        Self { db: Arc::new(db) }
    }

    /// Loads enabled account by account name.
    pub async fn load_account(&self, account_name: &str) -> Result<AccountModel> {
        let txn = begin_read(&self.db)
            .await
            .map_err(|e| OrmError::ConnectionError(e.to_string().into()))?;

        if self.db.get_database_backend() == DbBackend::Sqlite {
            let account_escaped = account_name.replace('\'', "''");
            let sql = format!(
                "select id from base.account where name = '{account_escaped}' and enabled = true limit 1"
            );
            let row = txn
                .query_one(Statement::from_string(DbBackend::Sqlite, sql))
                .await
                .map_err(|e| {
                    OrmError::QueryExecutionError(
                        format!("load_account(sqlite raw) failed: {e}").into(),
                    )
                })?
                .ok_or_else(|| OrmError::NotFound)?;

            let id: i32 = row.try_get("", "id").map_err(|e| {
                OrmError::QueryExecutionError(
                    format!("load_account(sqlite id decode) failed: {e}").into(),
                )
            })?;
            let now = chrono::Utc::now().naive_utc();
            let account = AccountModel {
                id,
                name: account_name.to_string(),
                modules: vec![],
                enabled: true,
                config: serde_json::json!({}),
                priority: 1,
                created_at: now,
                updated_at: now,
            };
            return Ok(account);
        }

        let account = AccountEntity::find()
            .filter(AccountColumn::Name.eq(account_name))
            .filter(AccountColumn::Enabled.eq(true))
            .one(&txn)
            .await
            .map_err(|e| {
                OrmError::QueryExecutionError(format!("load_account(filter) failed: {e}").into())
            })?
            .ok_or_else(|| OrmError::NotFound)?;

        Ok(account)
    }

    /// Loads enabled platform by platform name.
    pub async fn load_platform(&self, platform_name: &str) -> Result<PlatformModel> {
        let txn = begin_read(&self.db)
            .await
            .map_err(|e| OrmError::ConnectionError(e.to_string().into()))?;

        if self.db.get_database_backend() == DbBackend::Sqlite {
            let platform_escaped = platform_name.replace('\'', "''");
            let sql = format!(
                "select id from base.platform where name = '{platform_escaped}' and enabled = true limit 1"
            );
            let row = txn
                .query_one(Statement::from_string(DbBackend::Sqlite, sql))
                .await
                .map_err(|e| {
                    OrmError::QueryExecutionError(
                        format!("load_platform(sqlite raw) failed: {e}").into(),
                    )
                })?
                .ok_or_else(|| OrmError::NotFound)?;

            let id: i32 = row.try_get("", "id").map_err(|e| {
                OrmError::QueryExecutionError(
                    format!("load_platform(sqlite id decode) failed: {e}").into(),
                )
            })?;
            let now = chrono::Utc::now().naive_utc();
            let platform = PlatformModel {
                id,
                name: platform_name.to_string(),
                description: None,
                base_url: None,
                enabled: true,
                config: serde_json::json!({}),
                created_at: now,
                updated_at: now,
            };
            return Ok(platform);
        }

        let platform = PlatformEntity::find()
            .filter(PlatformColumn::Name.eq(platform_name))
            .filter(PlatformColumn::Enabled.eq(true))
            .one(&txn)
            .await
            .map_err(|e| {
                OrmError::QueryExecutionError(format!("load_platform(filter) failed: {e}").into())
            })?
            .ok_or_else(|| OrmError::NotFound)?;

        Ok(platform)
    }

    /// Loads enabled account-platform relation.
    pub async fn load_account_platform_relation(
        &self,
        account_id: i32,
        platform_id: i32,
    ) -> Result<RelAccountPlatformModel> {
        let txn = begin_read(&self.db)
            .await
            .map_err(|e| OrmError::ConnectionError(e.to_string().into()))?;

        let relation = RelAccountPlatformEntity::find()
            .filter(RelAccountPlatformColumn::AccountId.eq(account_id))
            .filter(RelAccountPlatformColumn::PlatformId.eq(platform_id))
            .filter(RelAccountPlatformColumn::Enabled.eq(true))
            .one(&txn)
            .await
            .map_err(|e| OrmError::QueryExecutionError(e.to_string().into()))?
            .ok_or_else(|| OrmError::NotFound)?;

        Ok(relation)
    }

    /// Loads all enabled modules bound to account-platform pair.
    pub async fn load_modules_by_account_platform(
        &self,
        platform_name: &str,
        account_name: &str,
    ) -> Result<Vec<ModuleModel>> {
        let txn = begin_read(&self.db)
            .await
            .map_err(|e| OrmError::ConnectionError(e.to_string().into()))?;

        let db_backend = self.db.get_database_backend();
        if db_backend == DbBackend::Sqlite {
            let platform_escaped = platform_name.replace('\'', "''");
            let account_escaped = account_name.replace('\'', "''");
            let sql = format!(
                r#"
        select a.* from base.module as a
        left join base.rel_module_platform rmp on a.id = rmp.module_id
        left join base.rel_module_account rma on a.id = rma.module_id
        left join base.rel_account_platform rap on rma.account_id = rap.account_id and rmp.platform_id = rap.platform_id
        left join base.platform as p on rmp.platform_id = p.id
        left join base.account as acc on rma.account_id = acc.id
        where a.enabled = true
        and rmp.enabled = true
        and rma.enabled = true
        and rap.enabled = true
        and p.enabled = true
        and acc.enabled = true
        and p.name = '{platform_escaped}'
        and acc.name = '{account_escaped}'"#
            );

            let modules = ModuleEntity::find()
                .from_raw_sql(Statement::from_string(db_backend, sql))
                .all(&txn)
                .await
                .map_err(|e| {
                    OrmError::QueryExecutionError(
                        format!("load_modules_by_account_platform(sqlite raw) failed: {e}").into(),
                    )
                })?;
            return Ok(modules);
        }

        let module_sql = if db_backend == DbBackend::Sqlite {
            r#"
        select a.* from base.module as a
        left join base.rel_module_platform rmp on a.id = rmp.module_id
        left join base.rel_module_account rma on a.id = rma.module_id
        left join base.rel_account_platform rap on rma.account_id = rap.account_id and rmp.platform_id = rap.platform_id
        left join base.platform as p on rmp.platform_id = p.id
        left join base.account as acc on rma.account_id = acc.id
        where a.enabled = true
        and rmp.enabled = true
        and rma.enabled = true
        and rap.enabled = true
        and p.enabled = true
        and acc.enabled = true
        and p.name = ?
        and acc.name = ?"#
        } else {
            r#"
        select a.* from base.module as a
        left join base.rel_module_platform rmp on a.id = rmp.module_id
        left join base.rel_module_account rma on a.id = rma.module_id
        left join base.rel_account_platform rap on rma.account_id = rap.account_id and rmp.platform_id = rap.platform_id
        left join base.platform as p on rmp.platform_id = p.id
        left join base.account as acc on rma.account_id = acc.id
        where a.enabled = true
        and rmp.enabled = true
        and rma.enabled = true
        and rap.enabled = true
        and p.enabled = true
        and acc.enabled = true
        and p.name = $1
        and acc.name = $2"#
        };

        let modules = ModuleEntity::find()
            .from_raw_sql(Statement::from_sql_and_values(
                db_backend,
                module_sql,
                vec![
                    Value::from(platform_name.to_string()),
                    Value::from(account_name.to_string()),
                ],
            ))
            .all(&txn)
            .await
            .map_err(|e| OrmError::QueryExecutionError(e.to_string().into()))?;

        Ok(modules)
    }

    /// Loads selected modules by names under account-platform scope.
    pub async fn load_module_by_account_platform_module(
        &self,
        platform_name: &str,
        account_name: &str,
        module_name: &[String],
    ) -> Result<Vec<ModuleModel>> {
        let txn = begin_read(&self.db)
            .await
            .map_err(|e| OrmError::ConnectionError(e.to_string().into()))?;

        let db_backend = self.db.get_database_backend();
        if db_backend == DbBackend::Sqlite {
            let platform_escaped = platform_name.replace('\'', "''");
            let account_escaped = account_name.replace('\'', "''");
            let module_list = module_name
                .iter()
                .map(|name| format!("'{}'", name.replace('\'', "''")))
                .collect::<Vec<_>>()
                .join(", ");

            let sql = format!(
                r#"
        select a.* from base.module as a
        left join base.rel_module_platform rmp on a.id = rmp.module_id
        left join base.rel_module_account rma on a.id = rma.module_id
        left join base.rel_account_platform rap on rma.account_id = rap.account_id and rmp.platform_id = rap.platform_id
        left join base.platform as p on rmp.platform_id = p.id
        left join base.account as acc on rma.account_id = acc.id
        where a.enabled = true
        and rmp.enabled = true
        and rma.enabled = true
        and rap.enabled = true
        and p.enabled = true
        and acc.enabled = true
        and a.name IN ({module_list})
        and p.name = '{platform_escaped}'
        and acc.name = '{account_escaped}'"#
            );

            let module = ModuleEntity::find()
                .from_raw_sql(Statement::from_string(db_backend, sql))
                .all(&txn)
                .await
                .map_err(|e| OrmError::QueryExecutionError(e.to_string().into()))?;
            return Ok(module);
        }

        // Build dynamic placeholders for IN clause.
        let placeholders: Vec<String> = if db_backend == DbBackend::Sqlite {
            (0..module_name.len()).map(|_| "?".to_string()).collect()
        } else {
            (1..=module_name.len()).map(|i| format!("${i}")).collect()
        };
        let in_clause = placeholders.join(", ");

        let module_sql = if db_backend == DbBackend::Sqlite {
            format!(
                r#"  
        select a.* from base.module as a  
        left join base.rel_module_platform rmp on a.id = rmp.module_id  
        left join base.rel_module_account rma on a.id = rma.module_id  
        left join base.rel_account_platform rap on rma.account_id = rap.account_id and rmp.platform_id = rap.platform_id  
        left join base.platform as p on rmp.platform_id = p.id  
        left join base.account as acc on rma.account_id = acc.id  
        where a.enabled = true  
        and rmp.enabled = true  
        and rma.enabled = true  
        and rap.enabled = true  
        and p.enabled = true  
        and acc.enabled = true  
        and a.name IN ({})  
        and p.name = ?  
        and acc.name = ?"#,
                in_clause,
            )
        } else {
            format!(
                r#"  
        select a.* from base.module as a  
        left join base.rel_module_platform rmp on a.id = rmp.module_id  
        left join base.rel_module_account rma on a.id = rma.module_id  
        left join base.rel_account_platform rap on rma.account_id = rap.account_id and rmp.platform_id = rap.platform_id  
        left join base.platform as p on rmp.platform_id = p.id  
        left join base.account as acc on rma.account_id = acc.id  
        where a.enabled = true  
        and rmp.enabled = true  
        and rma.enabled = true  
        and rap.enabled = true  
        and p.enabled = true  
        and acc.enabled = true  
        and a.name IN ({})  
        and p.name = ${}  
        and acc.name = ${}"#,
                in_clause,
                module_name.len() + 1,
                module_name.len() + 2
            )
        };

        // Build SQL bind values in placeholder order.
        let mut values: Vec<Value> = module_name
            .iter()
            .map(|name| Value::from(name.clone()))
            .collect();
        values.push(Value::from(platform_name.to_string()));
        values.push(Value::from(account_name.to_string()));

        let module = ModuleEntity::find()
            .from_raw_sql(Statement::from_sql_and_values(
                db_backend, module_sql, values,
            ))
            .all(&txn)
            .await
            .map_err(|e| OrmError::QueryExecutionError(e.to_string().into()))?;

        Ok(module)
    }

    /// Batch loads module-platform relations keyed by module_id.
    pub async fn load_module_platform_relations(
        &self,
        module_ids: &[i32],
        platform_id: i32,
    ) -> Result<HashMap<i32, RelModulePlatformModel>> {
        let txn = begin_read(&self.db)
            .await
            .map_err(|e| OrmError::ConnectionError(e.to_string().into()))?;

        let relations = RelModulePlatformEntity::find()
            .filter(RelModulePlatformColumn::ModuleId.is_in(module_ids.iter().copied()))
            .filter(RelModulePlatformColumn::PlatformId.eq(platform_id))
            .filter(RelModulePlatformColumn::Enabled.eq(true))
            .all(&txn)
            .await
            .map_err(|e| OrmError::QueryExecutionError(e.to_string().into()))?;

        let mut map = HashMap::new();
        for relation in relations {
            map.insert(relation.module_id, relation);
        }

        Ok(map)
    }

    /// Batch loads module-account relations keyed by module_id.
    pub async fn load_module_account_relations(
        &self,
        module_ids: &[i32],
        account_id: i32,
    ) -> Result<HashMap<i32, RelModuleAccountModel>> {
        let txn = begin_read(&self.db)
            .await
            .map_err(|e| OrmError::ConnectionError(e.to_string().into()))?;

        let relations = RelModuleAccountEntity::find()
            .filter(RelModuleAccountColumn::ModuleId.is_in(module_ids.iter().copied()))
            .filter(RelModuleAccountColumn::AccountId.eq(account_id))
            .filter(RelModuleAccountColumn::Enabled.eq(true))
            .all(&txn)
            .await
            .map_err(|e| OrmError::QueryExecutionError(e.to_string().into()))?;

        let mut map = HashMap::new();
        for relation in relations {
            map.insert(relation.module_id, relation);
        }

        Ok(map)
    }

    /// Loads module-platform relation for one module.
    pub async fn load_module_platform_relation(
        &self,
        module_id: i32,
        platform_id: i32,
    ) -> Result<RelModulePlatformModel> {
        let txn = begin_read(&self.db)
            .await
            .map_err(|e| OrmError::ConnectionError(e.to_string().into()))?;

        let relation = RelModulePlatformEntity::find()
            .filter(RelModulePlatformColumn::ModuleId.eq(module_id))
            .filter(RelModulePlatformColumn::PlatformId.eq(platform_id))
            .filter(RelModulePlatformColumn::Enabled.eq(true))
            .one(&txn)
            .await
            .map_err(|e| OrmError::QueryExecutionError(e.to_string().into()))?
            .ok_or_else(|| OrmError::NotFound)?;

        Ok(relation)
    }

    /// Loads module-account relation for one module.
    pub async fn load_module_account_relation(
        &self,
        module_id: i32,
        account_id: i32,
    ) -> Result<RelModuleAccountModel> {
        let txn = begin_read(&self.db)
            .await
            .map_err(|e| OrmError::ConnectionError(e.to_string().into()))?;

        let relation = RelModuleAccountEntity::find()
            .filter(RelModuleAccountColumn::ModuleId.eq(module_id))
            .filter(RelModuleAccountColumn::AccountId.eq(account_id))
            .filter(RelModuleAccountColumn::Enabled.eq(true))
            .one(&txn)
            .await
            .map_err(|e| OrmError::QueryExecutionError(e.to_string().into()))?
            .ok_or_else(|| OrmError::NotFound)?;

        Ok(relation)
    }

    /// Batch loads module-data-middleware relations grouped by module id.
    pub async fn load_module_data_middleware_relations(
        &self,
        module_ids: &[i32],
    ) -> Result<HashMap<i32, Vec<RelModuleDataMiddlewareModel>>> {
        let txn = begin_read(&self.db)
            .await
            .map_err(|e| OrmError::ConnectionError(e.to_string().into()))?;

        let relations = RelModuleDataMiddlewareEntity::find()
            .filter(RelModuleDataMiddlewareColumn::ModuleId.is_in(module_ids.iter().copied()))
            .filter(RelModuleDataMiddlewareColumn::Enabled.eq(true))
            .all(&txn)
            .await
            .map_err(|e| OrmError::QueryExecutionError(e.to_string().into()))?;

        let mut grouped = HashMap::new();
        for relation in relations {
            grouped
                .entry(relation.module_id)
                .or_insert_with(Vec::new)
                .push(relation);
        }

        Ok(grouped)
    }

    /// Batch loads module-download-middleware relations grouped by module id.
    pub async fn load_module_download_middleware_relations(
        &self,
        module_ids: &[i32],
    ) -> Result<HashMap<i32, Vec<RelModuleDownloadMiddlewareModel>>> {
        let txn = begin_read(&self.db)
            .await
            .map_err(|e| OrmError::ConnectionError(e.to_string().into()))?;

        let relations = RelModuleDownloadMiddlewareEntity::find()
            .filter(RelModuleDownloadMiddlewareColumn::ModuleId.is_in(module_ids.iter().copied()))
            .filter(RelModuleDownloadMiddlewareColumn::Enabled.eq(true))
            .all(&txn)
            .await
            .map_err(|e| OrmError::QueryExecutionError(e.to_string().into()))?;

        let mut grouped = HashMap::new();
        for relation in relations {
            grouped
                .entry(relation.module_id)
                .or_insert_with(Vec::new)
                .push(relation);
        }

        Ok(grouped)
    }

    /// Batch loads enabled data middlewares by ids.
    pub async fn load_data_middlewares(
        &self,
        middleware_ids: &[i32],
    ) -> Result<Vec<DataMiddlewareModel>> {
        let txn = begin_read(&self.db)
            .await
            .map_err(|e| OrmError::ConnectionError(e.to_string().into()))?;

        let middlewares = DataMiddlewareEntity::find()
            .filter(DataMiddlewareColumn::Id.is_in(middleware_ids.iter().copied()))
            .filter(DataMiddlewareColumn::Enabled.eq(true))
            .all(&txn)
            .await
            .map_err(|e| OrmError::QueryExecutionError(e.to_string().into()))?;

        Ok(middlewares)
    }

    /// Batch loads enabled download middlewares by ids.
    pub async fn load_download_middlewares(
        &self,
        middleware_ids: &[i32],
    ) -> Result<Vec<DownloadMiddlewareModel>> {
        let txn = begin_read(&self.db)
            .await
            .map_err(|e| OrmError::ConnectionError(e.to_string().into()))?;

        let middlewares = DownloadMiddlewareEntity::find()
            .filter(DownloadMiddlewareColumn::Id.is_in(middleware_ids.iter().copied()))
            .filter(DownloadMiddlewareColumn::Enabled.eq(true))
            .all(&txn)
            .await
            .map_err(|e| OrmError::QueryExecutionError(e.to_string().into()))?;

        Ok(middlewares)
    }
}