1
+ use sqlx:: SqlitePool ;
1
2
use dotenv:: dotenv;
2
3
use env_logger:: Env ;
3
- use std:: env;
4
+ use std:: { env, time :: Duration } ;
4
5
use tokio:: main;
5
6
6
7
mod config;
@@ -11,24 +12,39 @@ mod utils;
11
12
use crate :: scraper:: client:: fetch_data;
12
13
use db:: operations:: insert_data;
13
14
use sqlx:: sqlite:: SqlitePoolOptions ;
15
+ use utils:: rate_limiter:: rate_limited_operation;
14
16
15
- async fn fetch_and_insert_data ( pool : & sqlx :: SqlitePool , base_url : & str , pages : usize ) -> Result < ( ) , Box < dyn std:: error:: Error > > {
17
+ async fn fetch_and_insert_data ( pool : & SqlitePool , base_url : & str , pages : usize ) -> Result < ( ) , Box < dyn std:: error:: Error > > {
16
18
let mut tasks = vec ! [ ] ;
17
19
18
20
for page in 1 ..=pages {
19
21
let url = format ! ( "{}/page/{}" , base_url, page) ;
20
22
let pool = pool. clone ( ) ;
21
23
22
24
let task = tokio:: spawn ( async move {
23
- match fetch_data ( & url) . await {
24
- Ok ( data) => {
25
- if let Err ( err) = insert_data ( & pool, & data) . await {
26
- log:: error!( "Error inserting data from {}: {}" , url, err) ;
27
- } else {
28
- log:: info!( "Successfully inserted data from {}" , url) ;
29
- }
25
+ let result = rate_limited_operation ( || async {
26
+ match fetch_data ( & url) . await {
27
+ Ok ( data) => {
28
+ match insert_data ( & pool, & data) . await {
29
+ Ok ( _) => {
30
+ log:: info!( "Successfully inserted data from {}" , url) ;
31
+ Ok ( ( ) )
32
+ } ,
33
+ Err ( err) => {
34
+ log:: error!( "Error inserting data from {}: {}" , url, err) ;
35
+ Err ( err)
36
+ } ,
37
+ }
38
+ } ,
39
+ Err ( err) => {
40
+ log:: error!( "Error fetching data from {}: {}" , url, err) ;
41
+ Err ( sqlx:: Error :: Protocol ( err. to_string ( ) ) )
42
+ } ,
30
43
}
31
- Err ( err) => log:: error!( "Error fetching data from {}: {}" , url, err) ,
44
+ } , Duration :: from_secs ( 1 ) ) . await ;
45
+
46
+ if let Err ( err) = result {
47
+ log:: error!( "Error in rate limited operation: {}" , err) ;
32
48
}
33
49
} ) ;
34
50
0 commit comments