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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
use std::{
    cell::RefCell,
    fs::{create_dir_all, write},
    mem::forget,
    path::{Path, PathBuf},
    process::Command,
    sync::Arc,
    time::{Duration, Instant},
};

use anyhow::{Context, Result};
use next_api::{
    project::{DefineEnv, DraftModeOptions, ProjectContainer, ProjectOptions, WatchOptions},
    register,
    route::endpoint_write_to_disk,
};
use serde_json::json;
use tempfile::TempDir;
use tokio::runtime::Runtime;
use turbo_rcstr::RcStr;
use turbo_tasks::{
    TransientInstance, TurboTasks, TurboTasksApi, Vc, backend::Backend, trace::TraceRawVcs,
};
use turbo_tasks_backend::noop_backing_storage;

pub struct HmrBenchmark {
    test_app: TestApp,
    project_container: Vc<ProjectContainer>,
}

#[derive(Debug)]
pub struct TestApp {
    _path: PathBuf,
    /// Prevent temp directory from being dropped
    _dir: TempDir,
    modules: Vec<(PathBuf, usize)>,
}

impl TestApp {
    pub fn path(&self) -> &Path {
        &self._path
    }

    pub fn modules(&self) -> &[(PathBuf, usize)] {
        &self.modules
    }
}

fn create_test_app(module_count: usize) -> Result<TestApp> {
    let temp_dir = tempfile::tempdir().context("Failed to create temp directory")?;
    let base_path = temp_dir.path().to_path_buf();

    // Create basic Next.js structure
    let pages_dir = base_path.join("pages");
    let app_dir = base_path.join("app");
    let src_dir = base_path.join("src");

    create_dir_all(&pages_dir)?;
    create_dir_all(&app_dir)?;
    create_dir_all(&src_dir)?;

    let mut modules = Vec::new();

    // Create index page
    let index_content = r#"import React from 'react';

export default function Home() {
    return <div>Hello World</div>;
}
"#;
    let index_path = pages_dir.join("index.js");
    write(&index_path, index_content)?;
    modules.push((index_path, 0));

    // Create app layout
    let layout_content = r#"export default function RootLayout({ children }) {
    return (
        <html>
            <body>{children}</body>
        </html>
    );
}
"#;
    let layout_path = app_dir.join("layout.js");
    write(&layout_path, layout_content)?;
    modules.push((layout_path, 0));

    // Create app page
    let app_page_content = r#"export default function Page() {
    return <div>App Router Page</div>;
}
"#;
    let app_page_path = app_dir.join("page.js");
    write(&app_page_path, app_page_content)?;
    modules.push((app_page_path, 0));

    // Create additional modules based on module_count
    for i in 3..module_count {
        let component_content = format!(
            r#"import React from 'react';

export default function Component{i}() {{
    return <div>Component {i}</div>;
}}
"#
        );

        let component_path = src_dir.join(format!("component{i}.js"));
        write(&component_path, component_content)?;
        modules.push((component_path, 1));
    }

    // Create package.json
    let package_json = r#"{
    "name": "hmr-test-app",
    "version": "1.0.0",
    "dependencies": {
        "react": "^19.0.0",
        "react-dom": "^19.0.0",
        "next": "^15.0.0"
    }
}
"#;
    write(base_path.join("package.json"), package_json)?;

    // Create next.config.js
    let next_config = "module.exports = {}";
    write(base_path.join("next.config.js"), next_config)?;

    // Run `npm install`
    let output = Command::new("npm")
        .current_dir(&base_path)
        .args(["install"])
        .output()?;

    if !output.status.success() {
        return Err(anyhow::anyhow!("Failed to run `npm install`"));
    }

    Ok(TestApp {
        _path: base_path,
        _dir: temp_dir,
        modules,
    })
}

fn load_next_config() -> RcStr {
    serde_json::to_string(&json!({
        "sassOptions": {

        },
    }))
    .unwrap()
    .into()
}

fn runtime() -> Runtime {
    thread_local! {
        static LAST_SWC_ATOM_GC_TIME: RefCell<Option<Instant>> = const { RefCell::new(None) };
    }

    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .on_thread_stop(|| {
            turbo_tasks_malloc::TurboMalloc::thread_stop();
        })
        .on_thread_park(|| {
            LAST_SWC_ATOM_GC_TIME.with_borrow_mut(|cell| {
                if cell.is_none_or(|t| t.elapsed() > Duration::from_secs(2)) {
                    swc_core::ecma::atoms::hstr::global_atom_store_gc();
                    *cell = Some(Instant::now());
                }
            });
        })
        .build()
        .context("Failed to build tokio runtime")
        .unwrap()
}

impl HmrBenchmark {
    pub async fn new(module_count: usize) -> Result<Self> {
        let test_app = create_test_app(module_count)?;

        let project_container = {
            let container = ProjectContainer::new(RcStr::from("hmr-benchmark"), true)
                .to_resolved()
                .await?;

            let project_path = test_app.path().to_string_lossy().to_string();
            let root_path = test_app.path().to_string_lossy().to_string();

            let options = ProjectOptions {
                root_path: RcStr::from(root_path),
                project_path: RcStr::from(project_path.clone()),
                next_config: load_next_config(),
                js_config: RcStr::from("{}"),
                env: vec![],
                define_env: DefineEnv {
                    client: vec![],
                    edge: vec![],
                    nodejs: vec![],
                },
                watch: WatchOptions {
                    enable: true,
                    poll_interval: None,
                },
                dev: true,
                encryption_key: RcStr::from("test-key"),
                build_id: RcStr::from("development"),
                preview_props: DraftModeOptions {
                    preview_mode_id: RcStr::from("development"),
                    preview_mode_encryption_key: RcStr::from("test-key"),
                    preview_mode_signing_key: RcStr::from("test-key"),
                },
                browserslist_query: RcStr::from("last 2 versions"),
                no_mangling: false,
                current_node_js_version: RcStr::from("18.0.0"),
            };

            container.initialize(options).await?;
            Ok::<_, anyhow::Error>(container)
        }?;

        Ok(Self {
            test_app,
            project_container: *project_container,
        })
    }

    /// Simulate file changes for HMR testing
    pub fn make_file_change(&self, file_path: &Path, change_id: usize) -> Result<()> {
        let mut content =
            std::fs::read_to_string(file_path).context("Failed to read file content")?;

        // Add a comment with a unique identifier to trigger HMR
        let change_marker = format!("// HMR_CHANGE_{change_id}\n");
        content.push_str(&change_marker);

        std::fs::write(file_path, content).context("Failed to write modified content")?;

        Ok(())
    }

    /// Benchmark HMR update detection and processing
    pub async fn benchmark_hmr_update(&self, num_updates: usize) -> Result<Duration> {
        // Get entrypoints to trigger initial compilation
        let entrypoints = self.project_container.entrypoints();
        let initial_result = entrypoints.await?;

        // Check if we have routes available
        if initial_result.routes.is_empty() {
            return Err(anyhow::anyhow!("No routes found in entrypoints"));
        }

        // Get HMR identifiers
        let hmr_identifiers = self.project_container.hmr_identifiers();
        let identifiers = hmr_identifiers.await?;

        if identifiers.is_empty() {
            return Err(anyhow::anyhow!("No HMR identifiers found"));
        }

        // Get project to access HMR methods
        let project = self.project_container.project();

        // Create multiple sessions to simulate real HMR usage
        let mut update_durations = Vec::new();

        for i in 0..num_updates {
            let update_start = Instant::now();

            // Use different identifiers for each update
            let identifier = &identifiers[i % identifiers.len()];

            // Get version state for this update
            let session = TransientInstance::new(());
            let version_state = project.hmr_version_state(identifier.clone(), session);

            // Pick a module file to change
            let module_index = i % self.test_app.modules().len();
            let (module_path, _) = &self.test_app.modules()[module_index];

            // Make a file change
            self.make_file_change(module_path, i)?;

            // Wait for HMR update and measure time
            let _update_result = project
                .hmr_update(identifier.clone(), version_state)
                .await?;

            update_durations.push(update_start.elapsed());
        }

        Ok(update_durations.iter().sum::<Duration>())
    }

    /// Benchmark HMR subscription and event handling
    pub async fn benchmark_hmr_subscription(&self) -> Result<Duration> {
        let start_time = Instant::now();

        // Get entrypoints first
        let entrypoints = self.project_container.entrypoints();
        let _initial_result = entrypoints.await?;

        // Get HMR identifiers
        let hmr_identifiers = self.project_container.hmr_identifiers();
        let identifiers = hmr_identifiers.await?;

        if identifiers.is_empty() {
            return Err(anyhow::anyhow!("No HMR identifiers found"));
        }

        let project = self.project_container.project();

        // Test subscription to multiple identifiers
        let mut version_states = Vec::new();
        for identifier in identifiers.iter().take(5) {
            // Test with first 5 identifiers
            let session = TransientInstance::new(());
            let version_state = project.hmr_version_state(identifier.clone(), session);
            version_states.push((identifier.clone(), version_state));
        }

        // Simulate multiple rapid updates
        for (i, (identifier, version_state)) in version_states.iter().enumerate() {
            // Make a file change
            if let Some((module_path, _)) = self.test_app.modules().get(i) {
                self.make_file_change(module_path, i * 100)?;

                // Check for update
                let _update_result = project
                    .hmr_update(identifier.clone(), *version_state)
                    .await?;
            }
        }

        Ok(start_time.elapsed())
    }

    /// Benchmark initial project setup and entrypoint detection
    pub async fn benchmark_initial_compilation(&self) -> Result<Duration> {
        let start_time = Instant::now();

        let entrypoints = self.project_container.entrypoints();
        let result = entrypoints.await?;

        for route in result.routes.values() {
            match route {
                next_api::route::Route::Page {
                    html_endpoint,
                    data_endpoint,
                } => {
                    let _ = endpoint_write_to_disk(**html_endpoint).await?;
                    let _ = endpoint_write_to_disk(**data_endpoint).await?;
                }
                next_api::route::Route::PageApi { endpoint } => {
                    let _ = endpoint_write_to_disk(**endpoint).await?;
                }
                next_api::route::Route::AppPage(app_page_routes) => {
                    for route in app_page_routes.iter() {
                        let _ = endpoint_write_to_disk(*route.html_endpoint).await?;
                        let _ = endpoint_write_to_disk(*route.rsc_endpoint).await?;
                    }
                }
                next_api::route::Route::AppRoute { endpoint, .. } => {
                    let _ = endpoint_write_to_disk(**endpoint).await?;
                }
                next_api::route::Route::Conflict => {}
            }
        }

        Ok(start_time.elapsed())
    }

    /// Get the number of modules in the test app
    pub fn module_count(&self) -> usize {
        self.test_app.modules().len()
    }
}

async fn setup_benchmark(module_count: usize) -> HmrBenchmark {
    register();
    HmrBenchmark::new(module_count).await.unwrap()
}

fn setup_runtime() -> Runtime {
    runtime()
}

fn setup_turbo_tasks() -> Arc<TurboTasks<impl Backend>> {
    TurboTasks::new(turbo_tasks_backend::TurboTasksBackend::new(
        turbo_tasks_backend::BackendOptions {
            storage_mode: None,
            dependency_tracking: true,
            ..Default::default()
        },
        noop_backing_storage(),
    ))
}

#[derive(TraceRawVcs)]
struct Setup {
    #[turbo_tasks(trace_ignore)]
    rt: Arc<Runtime>,
    #[turbo_tasks(trace_ignore)]
    tt: Arc<dyn TurboTasksApi>,
    #[turbo_tasks(trace_ignore)]
    benchmark: HmrBenchmark,
}

fn setup_everything(module_count: usize) -> Arc<Setup> {
    let rt = Arc::new(setup_runtime());
    let tt = setup_turbo_tasks();

    let arc = rt.clone().block_on(async move {
        tt.clone()
            .run_once(async move {
                let benchmark = setup_benchmark(module_count).await;
                benchmark.benchmark_initial_compilation().await.unwrap();

                Ok(Arc::new(Setup { rt, tt, benchmark }))
            })
            .await
            .unwrap()
    });

    // I don't know why this is needed, but it is required to avoid dropping tokio runtime from
    // async scope
    forget(arc.clone());
    arc
}

fn bench_update(bencher: divan::Bencher, module_count: usize, num_updates: usize) {
    let s = setup_everything(module_count);

    bencher
        .with_inputs(|| {
            let setup = s.clone();

            setup.clone().rt.block_on(async move {
                setup.clone().tt.run_once(Box::pin(async move {
                    let _ = setup
                        .benchmark
                        .benchmark_initial_compilation()
                        .await
                        .unwrap();
                    Ok(())
                }));
            });

            s.clone()
        })
        .bench_values(|setup| {
            setup.clone().rt.block_on(async move {
                setup.clone().tt.run_once(Box::pin(async move {
                    setup
                        .benchmark
                        .benchmark_hmr_update(num_updates)
                        .await
                        .unwrap();
                    Ok(())
                }));
            })
        });
}

#[divan::bench(sample_size = 10000, max_time = 60)]
fn hmr_updates_small_5(bencher: divan::Bencher) {
    bench_update(bencher, 100, 5);
}

#[divan::bench(sample_size = 10000, max_time = 60)]
fn hmr_updates_medium_10(bencher: divan::Bencher) {
    bench_update(bencher, 200, 10);
}

#[divan::bench(sample_size = 10000, max_time = 60)]
fn hmr_updates_large_20(bencher: divan::Bencher) {
    bench_update(bencher, 500, 20);
}

fn main() {
    divan::main();
}