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
use std::cmp::Ordering;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::RwLock;
use std::time::Duration;
use std::{cmp, sync::atomic::AtomicU32, time::Instant};

use async_trait::async_trait;
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
use rspack_collections::IdentifierMap;
use rspack_core::{
  ApplyContext, BoxModule, Compilation, CompilationAfterOptimizeModules,
  CompilationAfterProcessAssets, CompilationBuildModule, CompilationChunkIds,
  CompilationFinishModules, CompilationModuleIds, CompilationOptimizeChunkModules,
  CompilationOptimizeChunks, CompilationOptimizeDependencies, CompilationOptimizeModules,
  CompilationOptimizeTree, CompilationParams, CompilationProcessAssets, CompilationSeal,
  CompilationSucceedModule, CompilerAfterEmit, CompilerCompilation, CompilerEmit,
  CompilerFinishMake, CompilerMake, CompilerOptions, CompilerThisCompilation, ModuleIdentifier,
  Plugin, PluginContext,
};
use rspack_error::Result;
use rspack_hook::{plugin, plugin_hook};

#[derive(Debug, Clone, Default)]
pub struct ProgressPluginOptions {
  // the prefix name of progress bar
  pub prefix: String,
  // tells ProgressPlugin to collect profile data for progress steps.
  pub profile: bool,
  // the template of progress bar, see [`indicatif::ProgressStyle::with_template`]
  pub template: String,
  // the tick string sequence for spinners, see [`indicatif::ProgressStyle::tick_strings`]
  pub tick_strings: Option<Vec<String>>,
  // the progress characters, see [`indicatif::ProgressStyle::progress_chars`]
  pub progress_chars: String,
}

#[derive(Debug)]
pub struct ProgressPluginStateInfo {
  pub value: String,
  pub time: Instant,
  pub duration: Option<Duration>,
}

#[plugin]
#[derive(Debug)]
pub struct ProgressPlugin {
  pub options: ProgressPluginOptions,
  pub progress_bar: ProgressBar,
  pub modules_count: AtomicU32,
  pub modules_done: AtomicU32,
  pub active_modules: RwLock<IdentifierMap<Instant>>,
  pub last_modules_count: RwLock<Option<u32>>,
  pub last_active_module: RwLock<Option<ModuleIdentifier>>,
  pub last_state_info: RwLock<Vec<ProgressPluginStateInfo>>,
}

impl ProgressPlugin {
  pub fn new(options: ProgressPluginOptions) -> Self {
    // default interval is 20, means draw every 1000/20 = 50ms, use 100 to draw every 1000/100 = 10ms
    let progress_bar =
      ProgressBar::with_draw_target(Some(100), ProgressDrawTarget::stdout_with_hz(100));
    let mut progress_bar_style = ProgressStyle::with_template(&options.template)
      .expect("TODO:")
      .progress_chars(&options.progress_chars);
    if let Some(tick_strings) = &options.tick_strings {
      progress_bar_style = progress_bar_style.tick_strings(
        tick_strings
          .iter()
          .map(|s| s.as_str())
          .collect::<Vec<_>>()
          .as_slice(),
      );
    }
    progress_bar.set_style(progress_bar_style);

    Self::new_inner(
      options,
      progress_bar,
      AtomicU32::new(0),
      AtomicU32::new(0),
      Default::default(),
      Default::default(),
      Default::default(),
      Default::default(),
    )
  }

  fn update(&self) {
    let modules_done = self.modules_done.load(Relaxed);
    let percent_by_module = (modules_done as f32)
      / (cmp::max(
        self.last_modules_count.read().expect("TODO:").unwrap_or(1),
        self.modules_count.load(Relaxed),
      ) as f32);

    let mut items = vec![];
    let last_active_module = self.last_active_module.read().expect("TODO:");

    if let Some(last_active_module) = *last_active_module {
      items.push(last_active_module.to_string());
      let duration = self
        .active_modules
        .read()
        .expect("TODO:")
        .get(&last_active_module)
        .map(|time| Instant::now() - *time);
      self.handler(
        0.1 + percent_by_module * 0.55,
        String::from("building"),
        items,
        duration,
      );
    }
  }

  pub fn handler(
    &self,
    percent: f32,
    msg: String,
    state_items: Vec<String>,
    time: Option<Duration>,
  ) {
    if self.options.profile {
      self.default_handler(percent, msg, state_items, time);
    } else {
      self.progress_bar_handler(percent, msg, state_items);
    }
  }

  fn default_handler(&self, _: f32, msg: String, items: Vec<String>, duration: Option<Duration>) {
    let full_state = [vec![msg.clone()], items.clone()].concat();
    let now = Instant::now();
    {
      let mut last_state_info = self.last_state_info.write().expect("TODO:");
      let len = full_state.len().max(last_state_info.len());
      let original_last_state_info_len = last_state_info.len();
      for i in (0..len).rev() {
        if i + 1 > original_last_state_info_len {
          last_state_info.insert(
            original_last_state_info_len,
            ProgressPluginStateInfo {
              value: full_state[i].clone(),
              time: now,
              duration: None,
            },
          )
        } else if i + 1 > full_state.len() || !last_state_info[i].value.eq(&full_state[i]) {
          let diff = match last_state_info[i].duration {
            Some(duration) => duration,
            _ => now - last_state_info[i].time,
          }
          .as_millis();
          let report_state = if i > 0 {
            last_state_info[i - 1].value.clone() + " > " + last_state_info[i].value.clone().as_str()
          } else {
            last_state_info[i].value.clone()
          };

          if diff > 5 {
            // TODO: color map
            let mut color = "\x1b[32m";
            if diff > 10000 {
              color = "\x1b[31m"
            } else if diff > 1000 {
              color = "\x1b[33m"
            }
            println!(
              "{}{} {} ms {}\x1B[0m",
              color,
              " | ".repeat(i),
              diff,
              report_state
            );
          }
          match (i + 1).cmp(&full_state.len()) {
            Ordering::Greater => last_state_info.truncate(i),
            Ordering::Equal => {
              last_state_info[i] = ProgressPluginStateInfo {
                value: full_state[i].clone(),
                time: now,
                duration,
              }
            }
            Ordering::Less => {
              last_state_info[i] = ProgressPluginStateInfo {
                value: full_state[i].clone(),
                time: now,
                duration: None,
              };
            }
          }
        }
      }
    }
  }

  fn progress_bar_handler(&self, percent: f32, msg: String, state_items: Vec<String>) {
    self
      .progress_bar
      .set_message(msg + " " + state_items.join(" ").as_str());
    self.progress_bar.set_position((percent * 100.0) as u64);
  }

  fn sealing_hooks_report(&self, name: &str, index: i32) {
    let number_of_sealing_hooks = 38;
    self.handler(
      0.7 + 0.25 * (index / number_of_sealing_hooks) as f32,
      "sealing".to_string(),
      vec![name.to_string()],
      None,
    );
  }
}

#[plugin_hook(CompilerThisCompilation for ProgressPlugin)]
async fn this_compilation(
  &self,
  _compilation: &mut Compilation,
  _params: &mut CompilationParams,
) -> Result<()> {
  self.handler(
    0.08,
    "setup".to_string(),
    vec!["compilation".to_string()],
    None,
  );
  Ok(())
}

#[plugin_hook(CompilerCompilation for ProgressPlugin)]
async fn compilation(
  &self,
  _compilation: &mut Compilation,
  _params: &mut CompilationParams,
) -> Result<()> {
  self.handler(
    0.09,
    "setup".to_string(),
    vec!["compilation".to_string()],
    None,
  );
  Ok(())
}

#[plugin_hook(CompilerMake for ProgressPlugin)]
async fn make(&self, _compilation: &mut Compilation) -> Result<()> {
  if !self.options.profile {
    self.progress_bar.reset();
    self.progress_bar.set_prefix(self.options.prefix.clone());
  }
  self.handler(0.01, String::from("make"), vec![], None);
  self.modules_count.store(0, Relaxed);
  self.modules_done.store(0, Relaxed);
  Ok(())
}

#[plugin_hook(CompilationBuildModule for ProgressPlugin)]
async fn build_module(&self, module: &mut BoxModule) -> Result<()> {
  self
    .active_modules
    .write()
    .expect("TODO:")
    .insert(module.identifier(), Instant::now());
  self.modules_count.fetch_add(1, Relaxed);
  self
    .last_active_module
    .write()
    .expect("TODO:")
    .replace(module.identifier());
  if !self.options.profile {
    self.update();
  }
  Ok(())
}

#[plugin_hook(CompilationSucceedModule for ProgressPlugin)]
async fn succeed_module(&self, module: &mut BoxModule) -> Result<()> {
  self.modules_done.fetch_add(1, Relaxed);
  self
    .last_active_module
    .write()
    .expect("TODO:")
    .replace(module.identifier());

  // only profile mode should update at succeed module
  if self.options.profile {
    self.update();
  }
  let mut last_active_module = Default::default();
  {
    let mut active_modules = self.active_modules.write().expect("TODO:");
    active_modules.remove(&module.identifier());

    // get the last active module
    if !self.options.profile {
      active_modules.iter().for_each(|(module, _)| {
        last_active_module = *module;
      });
    }
  }
  if !self.options.profile {
    self
      .last_active_module
      .write()
      .expect("TODO:")
      .replace(last_active_module);
    if !last_active_module.is_empty() {
      self.update();
    }
  }
  Ok(())
}

#[plugin_hook(CompilerFinishMake for ProgressPlugin)]
async fn finish_make(&self, _compilation: &mut Compilation) -> Result<()> {
  self.handler(
    0.69,
    "building".to_string(),
    vec!["finish make".to_string()],
    None,
  );
  Ok(())
}

#[plugin_hook(CompilationSeal for ProgressPlugin)]
async fn seal(&self, _compilation: &mut Compilation) -> Result<()> {
  self.sealing_hooks_report("plugins", 1);
  Ok(())
}

#[plugin_hook(CompilationOptimizeDependencies for ProgressPlugin)]
fn optimize_dependencies(&self, _compilation: &mut Compilation) -> Result<Option<bool>> {
  self.sealing_hooks_report("dependencies", 2);
  Ok(None)
}

#[plugin_hook(CompilationFinishModules for ProgressPlugin)]
async fn finish_modules(&self, _compilation: &mut Compilation) -> Result<()> {
  self.sealing_hooks_report("finish modules", 0);
  Ok(())
}

#[plugin_hook(CompilationOptimizeModules for ProgressPlugin)]
async fn optimize_modules(&self, _compilation: &mut Compilation) -> Result<Option<bool>> {
  self.sealing_hooks_report("module optimization", 7);
  Ok(None)
}

#[plugin_hook(CompilationAfterOptimizeModules for ProgressPlugin)]
async fn after_optimize_modules(&self, _compilation: &mut Compilation) -> Result<()> {
  self.sealing_hooks_report("after module optimization", 8);
  Ok(())
}

#[plugin_hook(CompilationOptimizeChunks for ProgressPlugin)]
fn optimize_chunks(&self, _compilation: &mut Compilation) -> Result<Option<bool>> {
  self.sealing_hooks_report("chunk optimization", 9);
  Ok(None)
}

#[plugin_hook(CompilationOptimizeTree for ProgressPlugin)]
async fn optimize_tree(&self, _compilation: &mut Compilation) -> Result<()> {
  self.sealing_hooks_report("module and chunk tree optimization", 11);
  Ok(())
}

#[plugin_hook(CompilationOptimizeChunkModules for ProgressPlugin)]
async fn optimize_chunk_modules(&self, _compilation: &mut Compilation) -> Result<Option<bool>> {
  self.sealing_hooks_report("chunk modules optimization", 13);
  Ok(None)
}

#[plugin_hook(CompilationModuleIds for ProgressPlugin)]
fn module_ids(&self, _modules: &mut Compilation) -> Result<()> {
  self.sealing_hooks_report("module ids", 16);
  Ok(())
}

#[plugin_hook(CompilationChunkIds for ProgressPlugin)]
fn chunk_ids(&self, _compilation: &mut Compilation) -> Result<()> {
  self.sealing_hooks_report("chunk ids", 21);
  Ok(())
}

#[plugin_hook(CompilationProcessAssets for ProgressPlugin, stage = Compilation::PROCESS_ASSETS_STAGE_ADDITIONAL)]
async fn process_assets(&self, _compilation: &mut Compilation) -> Result<()> {
  self.sealing_hooks_report("asset processing", 35);
  Ok(())
}

#[plugin_hook(CompilationAfterProcessAssets for ProgressPlugin)]
async fn after_process_assets(&self, _compilation: &mut Compilation) -> Result<()> {
  self.sealing_hooks_report("after asset optimization", 36);
  Ok(())
}

#[plugin_hook(CompilerEmit for ProgressPlugin)]
async fn emit(&self, _compilation: &mut Compilation) -> Result<()> {
  self.handler(0.98, "emitting".to_string(), vec!["emit".to_string()], None);
  Ok(())
}

#[plugin_hook(CompilerAfterEmit for ProgressPlugin)]
async fn after_emit(&self, _compilation: &mut Compilation) -> Result<()> {
  self.handler(
    1.0,
    "emitting".to_string(),
    vec!["after emit".to_string()],
    None,
  );
  Ok(())
}

#[async_trait]
impl Plugin for ProgressPlugin {
  fn name(&self) -> &'static str {
    "progress"
  }

  fn apply(
    &self,
    ctx: PluginContext<&mut ApplyContext>,
    _options: &mut CompilerOptions,
  ) -> Result<()> {
    ctx
      .context
      .compiler_hooks
      .this_compilation
      .tap(this_compilation::new(self));
    ctx
      .context
      .compiler_hooks
      .compilation
      .tap(compilation::new(self));
    ctx.context.compiler_hooks.make.tap(make::new(self));
    ctx
      .context
      .compilation_hooks
      .build_module
      .tap(build_module::new(self));
    ctx
      .context
      .compilation_hooks
      .succeed_module
      .tap(succeed_module::new(self));
    ctx
      .context
      .compiler_hooks
      .finish_make
      .tap(finish_make::new(self));
    ctx
      .context
      .compilation_hooks
      .finish_modules
      .tap(finish_modules::new(self));
    ctx.context.compilation_hooks.seal.tap(seal::new(self));
    ctx
      .context
      .compilation_hooks
      .optimize_dependencies
      .tap(optimize_dependencies::new(self));
    ctx
      .context
      .compilation_hooks
      .optimize_modules
      .tap(optimize_modules::new(self));
    ctx
      .context
      .compilation_hooks
      .after_optimize_modules
      .tap(after_optimize_modules::new(self));
    ctx
      .context
      .compilation_hooks
      .optimize_chunks
      .tap(optimize_chunks::new(self));
    ctx
      .context
      .compilation_hooks
      .optimize_tree
      .tap(optimize_tree::new(self));
    ctx
      .context
      .compilation_hooks
      .optimize_chunk_modules
      .tap(optimize_chunk_modules::new(self));
    ctx
      .context
      .compilation_hooks
      .module_ids
      .tap(module_ids::new(self));
    ctx
      .context
      .compilation_hooks
      .chunk_ids
      .tap(chunk_ids::new(self));
    ctx
      .context
      .compilation_hooks
      .process_assets
      .tap(process_assets::new(self));
    ctx
      .context
      .compilation_hooks
      .after_process_assets
      .tap(after_process_assets::new(self));
    ctx.context.compiler_hooks.emit.tap(emit::new(self));
    ctx
      .context
      .compiler_hooks
      .after_emit
      .tap(after_emit::new(self));
    Ok(())
  }
}