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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! Instruction fields of [ArgApp] and its Configuration
//!
//! # `config` Configuration
//!
//! Some fields are required, some are not Configurable, some are optional, The following fields
//! are configurable 
//!
//! ## ArgApp
//!
//! **`is_skip`**: `bool`, `true` as default, use the files stroed in `data_dir` or not, if not a new
//!
//! **`spawn_task_max`**: `usize`, `100` as default, the maximal length of spawned tasks
//!
//! **`buf_task`**: `usize`, `10000` as default, the length of `Task` collected by `parser`s, exceeding
//! which all `Task` will be stored into `data_dir/tasks/` for memory saving
//!
//! **`round_entity`**: `usize`, `10` as default, the number of entities exceed which `process_entity`
//! is called to consume them
//! session will started all older files will be truncated.
//!
//! **`data_dir`**: `string`, `data/` as default, the place to store or load files of `App` when
//! reaching` rate.cycle`
//!
//! **`nap`**: `f64`, `15.0` as default, the duration after which generated `Task` or `Profile` or recycled `Profile` become
//! availible
//!
//! **`join_gap`**: `f64`, `7.0` as default, the duration which the spawned task exceeds the executor
//! is called to forcefully join it
//!
//! **`round_req`**: `usize`, `10`, for more to see [ArgApp]
//!
//! **`round_req_min`**: `usize`, `5`, for more to see [ArgApp]
//!
//! **`round_req_max`**: `uize`, `77`, for more to see [ArgApp]
//!
//! **`round_task`**: `usize`, `10` as default, for more to see [ArgApp]
//!
//! **`round_task_min`**: `usize`, `7`, for more to see [ArgApp]
//!
//! **`round_res`**: `usize`, `10` as default, for more to see [ArgApp]
//!
//! **`round_yield_err`**: `usize`, `10` as default, the number of `Response` cannot be parsed, exceed which `process_entity`
//! is called to consume them,
//! 
//! ## ArgProfile
//! 
//! **`arg_profile.is_on`**: `bool`, `false` as defalut, enable profile customization or not, when
//! true, `ProfileInfo.req` cannot be None, 
//!
//! **`arg_profile.profile_min`**: `usize` `0` as default, the minimal length of profile( including
//! these in use or in future )
//!
//! **`arg_profile.profile_max`**: `usize` `0` as default, the minimal length of profile( including,
//! these in use or in future )
//! 
//! ## ArgRate
//! 
//! **`rate.cycle`**: `f64`, 600.0 as default, the duration after which backup files of `App`
//!
//! **`rate.load`**: `f64`, 99.0 as default, the load to be spawned in each `interval`,
//!
//! **`rate.rate_low`**: `f64`, 0.333 as dafault, a value between 0-1.0 that lower the taks to be spawned, eg. the oringnal
//! value is 12, rate_low is 0.33, the tasks to be spawned is 12.0 * 0.33 ~ 4. 
//!
//! **`rate.err`**: `usize`, the nubmer that erros of `Response` occurs, the default value is 0,
//!
//! **`rate.interval`**: `f64`, the duration of time after which updating `ArgRate` `ArgApp`, the default
//! value is 30.0,
//!
//! [ArgApp]: crate::engine::arg::ArgApp
//!
use std::io::{BufRead, BufReader};
use std::sync::{Arc, Mutex};
use crate::utils;

/// Arguments that control the `App` at runtime, including using history or not,  
/// `Task` `Profile` `Request` `Response` `Entity` consuming and generating
/// There shall be an introduction to every member(maybe coming soon).
#[derive(std::fmt::Debug)]
pub struct ArgApp {
    /// time tap added to created Tasks or Profiles
    pub nap: f64,
    /// gap to forcefully join the spawned task
    pub join_gap: f64,
    /// number that once for a concurrent future poll
    pub round_req: usize,
    /// cache request minimal length
    pub round_req_min: usize,
    /// cache request maximal length
    pub round_req_max: usize,
    /// buffer length for the created task.
    pub buf_task: usize,
    /// maximal spawned task that cached
    pub spawn_task_max: usize,
    /// construct req from task one time
    pub round_task: usize,
    /// minimal task(profile) consumed per round
    pub round_task_min: usize,
    /// consume response once upon a time
    pub round_res: usize,
    ///consume yield_err once upon a time
    pub round_yield_err: usize,
    ///consume Entity once upon a time
    pub round_entity: usize,
    /// use files in directory `data/` or not,
    /// set true as default
    pub is_skip: bool,
    /// control the task speed runtime
    pub rate: Arc<Mutex<ArgRate>>,
    /// control the profile workflow
    pub arg_profile: Option<ArgProfile>,
    /// directory that store history file
    pub data_dir: String,
}

impl ArgApp {
    /// create an instance of `ArgApp`
    pub fn new() -> Self {
        let mut arg = ArgApp {
            nap: 17.0,
            join_gap: 7.0,
            round_req: 10,
            round_req_min: 3,
            round_req_max: 70,
            buf_task: 1000,
            spawn_task_max: 100,
            round_task: 10,
            round_task_min: 7,
            round_res: 10,
            round_yield_err: 10,
            round_entity: 10,
            is_skip: true,
            rate: Arc::new(Mutex::new(ArgRate::new())),
            arg_profile: None,
            data_dir: "data/".into(),
        };
        arg.parse_config(None, false);
        arg
    }

    /// set key-value pairs in `ArgApp`
    fn set(&mut self, key: &str, value: &str, fail_safe: bool) {
        match key {
            "nap" => {
                if let Ok(v) = value.parse::<f64>() {
                    self.nap = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for nap: {}", value);
                }else {
                    panic!("update failed, invalid value for nap: {}", value);
                }
            }
            "join_gap" => {
                if let Ok(v) = value.parse::<f64>() {
                    self.join_gap = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for join_gap: {}", value);
                }else {
                    panic!("update failed, invalid value for join_gap: {}", value);
                }
                
            }
            "round_req" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.round_req = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for round_req: {}", value);
                }else {
                    panic!("update failed, invalid value for round_req: {}", value);
                }
            }
            "round_req_min" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.round_req_min = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for round_req_min: {}", value);
                }else {
                    panic!("update failed, invalid value for round_req_min: {}", value);
                }
            }
            "round_req_max" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.round_req_max = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for round_req_max: {}", value);
                }else {
                    panic!("update failed, invalid value for round_req_max: {}", value);
                }
            }
            "buf_task" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.buf_task = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for buf_task: {}", value);
                }else {
                    panic!("update failed, invalid value for buf_task: {}", value);
                }
            }
            "spawn_task_max" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.spawn_task_max = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for spawn_task_max: {}", value);
                }else {
                    panic!("update failed, invalid value for spawn_task_max: {}", value);
                }
            }
            "round_task" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.round_task = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for round_task: {}", value);
                }else {
                    panic!("update failed, invalid value for round_task: {}", value);
                }
            }
            "round_task_min" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.round_task_min = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for round_task_min: {}", value);
                }else {
                    panic!("update failed, invalid value for round_task_min: {}", value);
                }
            }
            "round_res" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.round_res = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for round_res: {}", value);
                }else {
                    panic!("update failed, invalid value for round_res: {}", value);
                }
            }
            "round_yield_err" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.round_yield_err = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for round_yield_err: {}", value);
                }else {
                    panic!("update failed, invalid value for round_yield_err: {}", value);
                }
            }
            "round_entity" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.round_entity = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for round_entity: {}", value);
                }else {
                    panic!("update failed, invalid value for round_entity: {}", value);
                }
            }
            "is_skip" => {
                if let Ok(v) = value.parse::<bool>() {
                    self.is_skip = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for is_skip: {}", value);
                }else {
                    panic!("update failed, invalid value for is_skip: {}", value);
                }
            }
            "data_dir" => {
                if let Ok(v) = value.parse::<String>() {
                    self.data_dir = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for data_dir: {}", value);
                }else {
                    panic!("update failed, invalid value for data_dir: {}", value);
                }
            }
            "rate.cycle" => {
                if let Ok(v) = value.parse::<f64>() {
                    self.rate.lock().unwrap().cycle = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for rate.cycle: {}", value);
                }else {
                    panic!("update failed, invalid value for rate.cycle: {}", value);
                }
            }
            "rate.interval" => {
                if let Ok(v) = value.parse::<f64>() {
                    self.rate.lock().unwrap().interval = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for rate.interval: {}", value);
                }else {
                    panic!("update failed, invalid value for rate.interval: {}", value);
                }
            }
            "rate.load" => {
                if let Ok(v) = value.parse::<f64>() {
                    self.rate.lock().unwrap().load = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for rate.load: {}", value);
                }else {
                    panic!("update failed, invalid value for rate.load: {}", value);
                }
            }
            "rate.remains" => {
                if let Ok(v) = value.parse::<usize>() {
                    self.rate.lock().unwrap().remains = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for rate.remains: {}", value);
                }else {
                    panic!("update failed, invalid value for rate.remains: {}", value);
                }
            }
            "rate.rate_low" => {
                if let Ok(v) = value.parse::<f64>() {
                    self.rate.lock().unwrap().rate_low = v;
                }else if fail_safe {
                    log::error!("update failed, invalid value for rate.rate_low: {}", value);
                }else {
                    panic!("update failed, invalid value for rate.rate_low: {}", value);
                }
            }
            "arg_profile.is_on" => {
                if self.arg_profile.is_some() {
                    if let Ok(v) = value.parse::<bool>() {
                        self.arg_profile.as_mut().unwrap().is_on = v;
                    }else if fail_safe {
                        log::error!("update failed, invalid value for arg_profile.is_on: {}", value);
                    }else {
                        panic!("update failed, invalid value for arg_profile.is_on: {}", value);
                    }
                } else {
                    let mut arg = ArgProfile::new();
                    if let Ok(v) = value.parse::<bool>() {
                        arg.is_on = v;
                    }else if fail_safe {
                        log::error!("update failed, invalid value for arg_profile.is_on: {}", value);
                    }else {
                        panic!("update failed, invalid value for arg_profile.is_on: {}", value);
                    }
                    self.arg_profile = Some(arg);
                }
            }
            "arg_profile.profile_min" => {
                if self.arg_profile.is_some() {
                    if let Ok(v) = value.parse::<usize>() {
                        self.arg_profile.as_mut().unwrap().profile_min = v;
                    }else if fail_safe {
                        log::error!("update failed, invalid value for arg_profile.profile_min: {}", value);
                    }else {
                        panic!("update failed, invalid value for arg_profile.profile_in: {}", value);
                    }
                } else {
                    let mut arg = ArgProfile::new();
                    if let Ok(v) = value.parse::<usize>() {
                        arg.profile_min = v;
                    }else if fail_safe {
                        log::error!("update failed, invalid value for arg_profile.profile_min: {}", value);
                    }else {
                        panic!("update failed, invalid value for arg_profile.profile_in: {}", value);
                    }
                    self.arg_profile = Some(arg);
                }
            }
            "arg_profile.profile_max" => {
                if self.arg_profile.is_some() {
                    if let Ok(v) = value.parse::<usize>() {
                        self.arg_profile.as_mut().unwrap().profile_max = v;
                    }else if fail_safe {
                        log::error!("update failed, invalid value for arg_profile.profile_max : {}", value);
                    }else {
                        panic!("update failed, invalid value for arg_profile.profile_max: {}", value);
                    }
                } else {
                    let mut arg = ArgProfile::new();
                    if let Ok(v) = value.parse::<usize>() {
                        arg.profile_max = v;
                    }else if fail_safe {
                        log::error!("update failed, invalid value for arg_profile.profile_max : {}", value);
                    }else {
                        panic!("update failed, invalid value for arg_profile.profile_max: {}", value);
                    }
                    self.arg_profile = Some(arg);
                }
            }
            _ => {
                eprintln!("Unrecognizable or unnecessary variable: {}", key);
            }
        }
    }

    /// parse the config file and update the `ArgApp`
    /// not fail safe for the first time call in `ArgApp::new`
    /// fail safe after that
    pub fn parse_config(&mut self, path: Option<&str>, fail_safe: bool) {
        let fields = [
            "arg_profile.is_on",
            "arg_profile.profile_min",
            "arg_profile.profile_max",
            "rate.cycle",
            "rate.interval",
            "rate.load",
            "rate.remains",
            "rate.rate_low",
            "data_dir",
            "is_skip",
            "nap",
            "join_gap",
            "round_req",
            "round_req_min",
            "round_req_max",
            "buf_task",
            "spawn_task_max",
            "round_task",
            "round_task_min",
            "round_res",
            "round_yield_err",
            "round_entity",
        ];
        let file = std::fs::File::open(path.unwrap_or("./config")).unwrap();
        let reader = BufReader::new(file);
        reader.lines().filter(|line| line.is_ok()).for_each(|line| {
            let pairs = line
                .unwrap()
                .split(":")
                .map(|ele| ele.to_string())
                .collect::<Vec<String>>();
            if pairs.len() == 2 {
                let key = pairs[0].trim();
                if fields.contains(&key) {
                    let value = pairs[1].trim().trim_end_matches(|c| c == ',');
                    self.set(key, value, fail_safe);
                }
            }
        });
        self.init();
        //println!("{:?}", self);
    }

    fn init(&mut self) {
        if self.arg_profile.is_some() {
            if self.arg_profile.as_ref().unwrap().profile_min
                >= self.arg_profile.as_ref().unwrap().profile_max
            {
                self.arg_profile.as_mut().unwrap().profile_max =
                    self.arg_profile.as_ref().unwrap().profile_min * 3 + 1;
            }
        }
        if self.round_req_min >= self.round_req_max {
            self.round_req_max = self.round_req_min * 3 + 1;
        }
    }
}

/// To control the workflow of engine in dealing with `Profile`
/// including using profile or not, the amount to use/generate
#[derive(std::fmt::Debug)]
pub struct ArgProfile {
    /// use profile customization or not
    pub is_on: bool,
    /// minimal cached profile number(including profiles used in `Request` that to be executed)
    pub profile_min: usize,
    /// maximal cached profile number(including profiles used in `Request` that to be executed)
    pub profile_max: usize,
}

impl ArgProfile {
    /// create an instance of `ArgProfile`
    pub fn new() -> Self {
        ArgProfile {
            is_on: false,
            profile_min: 0,
            profile_max: 0,
        }
    }
}

/// some infomation about `dyer` at rumtime where speed and error-handler based on
#[derive(std::fmt::Debug)]
pub struct ArgRate {
    /// all time the app runs
    pub uptime: f64,
    /// the time that a cycle lasts, backup application history once running out
    pub cycle: f64,
    /// time the app runs in each cycle
    pub cycle_usage: f64,
    /// a time gap when updating some infomation
    pub interval: f64,
    /// normally the speed that the app spawns tasks in the whole interval
    pub load: f64,
    /// failed tasks in each interval
    pub err: usize,
    /// remaining jobs to do in each cycle in each interval
    pub remains: usize,
    /// the rate applied to limit the requests to be spawned in low mode
    pub rate_low: f64,
    /// time anchor by which the mode is low
    pub anchor_low: f64,
    /// time anchor at which update some infomation
    pub anchor: f64,
    /// vector of gap each request takes to receive response header in each interval  
    pub stamps: Vec<f64>,
}

impl ArgRate {
    pub fn new() -> Self {
        let now = utils::now();
        ArgRate {
            uptime: 0.0,
            cycle: 600.0,
            cycle_usage: 0.0,
            load: 99.0,
            remains: 110,
            rate_low: 0.333,
            anchor_low: 0.0,
            err: 0,
            anchor: now + 30.0,
            interval: 30.0,
            stamps: Vec::new(),
        }
    }

    pub fn update(&mut self) -> bool {
        let now = utils::now();
        if now > self.anchor {
            self.cycle_usage += self.interval;
            self.anchor += self.interval;
            self.uptime += self.interval;
            if self.err > 0 {
                self.anchor_low = now + self.err as f64 * 0.333;
            }
            if now >= self.anchor_low {
                log::debug!("active period");
                self.stamps.clear();
                self.remains = self.load as usize;
            }
            return true;
        }
        false
    }

    /// backup the `Task` `Profile` `Request` for some time in case of interupt
    pub fn backup(&mut self) -> bool {
        if self.cycle_usage >= self.cycle {
            self.cycle_usage = self.cycle_usage.rem_euclid(self.cycle);
            return true;
        }
        false
    }

    /// decide the length of `Task` to be spawned
    pub fn get_len(&mut self, tm: Option<f64>) -> usize {
        let now = match tm {
            Some(now) => now,
            None => utils::now(),
        };
        let delta = self.load * (self.anchor - now) / self.interval;
        let len = if self.remains as f64 >= delta + 0.5 && delta >= 0.0 {
            self.remains as f64 - delta
        } else if (self.remains as f64) < delta + 0.5 && delta >= 0.0 {
            self.remains = delta as usize;
            0.0
        } else {
            self.remains as f64
        };
        log::trace!("remains:{}, delta: {}, len: {}", self.remains, delta, len);
        self.remains = self.remains - (len as usize) + 1;
        if len > 0.0 {
            log::trace!("only {} tasks are valid by rate control.", len);
        }
        if self.anchor_low <= now {
            len.ceil() as usize
        } else {
            (self.rate_low * len).ceil() as usize
        }
    }
}