lambda-simulator 0.1.5

High-fidelity AWS Lambda Runtime API simulator for testing Lambda runtimes and extensions locally
Documentation
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
//! Main simulator orchestration and builder.

use crate::error::{SimulatorError, SimulatorResult};
use crate::extension::{
    ExtensionState, LifecycleEvent, RegisteredExtension, ShutdownReason, TracingInfo,
};
use crate::extension_readiness::ExtensionReadinessTracker;
use crate::extensions_api::{ExtensionsApiState, create_extensions_api_router};
use crate::freeze::{FreezeMode, FreezeState};
use crate::invocation::Invocation;
use crate::invocation::InvocationStatus;
use crate::runtime_api::{RuntimeApiState, create_runtime_api_router};
use crate::state::{InvocationState, RuntimeState};
use crate::telemetry::{
    InitializationType, Phase, PlatformInitStart, TelemetryEvent, TelemetryEventType,
};
use crate::telemetry_api::{TelemetryApiState, create_telemetry_api_router};
use crate::telemetry_state::TelemetryState;
use chrono::Utc;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpListener;
use tokio::task::JoinHandle;

/// The lifecycle phase of the simulator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SimulatorPhase {
    /// Extensions can register, waiting for runtime to initialize.
    Initializing,
    /// Runtime is initialized, ready for invocations.
    Ready,
    /// Shutting down.
    ShuttingDown,
}

/// Configuration for the Lambda runtime simulator.
///
/// # Timeout Limitations
///
/// Timeout values are used for calculating invocation deadlines
/// (the `Lambda-Runtime-Deadline-Ms` header). Actual timeout enforcement
/// is not yet implemented - invocations will not be automatically
/// terminated when they exceed their configured timeout.
#[derive(Debug, Clone)]
pub struct SimulatorConfig {
    /// Default timeout for invocations in milliseconds.
    ///
    /// Used for deadline calculation in the `Lambda-Runtime-Deadline-Ms` header.
    /// Timeout enforcement is not currently implemented.
    pub invocation_timeout_ms: u64,

    /// Timeout for initialisation phase in milliseconds.
    ///
    /// Not currently enforced.
    pub init_timeout_ms: u64,

    /// Lambda function name, used in telemetry events and environment variables.
    pub function_name: String,

    /// Lambda function version (e.g., "$LATEST" or a published version number).
    pub function_version: String,

    /// Function memory allocation in MB, used in telemetry metrics.
    pub memory_size_mb: u32,

    /// CloudWatch Logs group name for the function.
    pub log_group_name: String,

    /// CloudWatch Logs stream name for this execution environment.
    pub log_stream_name: String,

    /// Timeout for waiting for extensions to be ready in milliseconds.
    ///
    /// After the runtime completes an invocation, this is the maximum time
    /// to wait for all extensions to signal readiness before proceeding
    /// with platform.report emission and process freezing.
    pub extension_ready_timeout_ms: u64,

    /// Timeout for graceful shutdown in milliseconds.
    ///
    /// During graceful shutdown, this is the maximum time to wait for
    /// extensions subscribed to SHUTDOWN events to complete their cleanup
    /// work by polling `/next` again.
    pub shutdown_timeout_ms: u64,

    /// Unique instance identifier for this simulator run.
    ///
    /// Used in telemetry events to identify the Lambda execution environment.
    pub instance_id: String,

    /// Function handler name (e.g., "index.handler").
    ///
    /// Used in extension registration responses.
    pub handler: Option<String>,

    /// AWS account ID.
    ///
    /// Used in extension registration responses and ARN construction.
    pub account_id: Option<String>,

    /// AWS region.
    ///
    /// Used for environment variables and ARN construction.
    /// Defaults to "us-east-1".
    pub region: String,
}

impl Default for SimulatorConfig {
    fn default() -> Self {
        Self {
            invocation_timeout_ms: 3000,
            init_timeout_ms: 10000,
            function_name: "test-function".to_string(),
            function_version: "$LATEST".to_string(),
            memory_size_mb: 128,
            log_group_name: "/aws/lambda/test-function".to_string(),
            log_stream_name: "2024/01/01/[$LATEST]test".to_string(),
            extension_ready_timeout_ms: 2000,
            shutdown_timeout_ms: 2000,
            instance_id: uuid::Uuid::new_v4().to_string(),
            handler: None,
            account_id: None,
            region: "us-east-1".to_string(),
        }
    }
}

/// Builder for creating a Lambda runtime simulator.
///
/// # Examples
///
/// ```no_run
/// use lambda_simulator::Simulator;
/// use std::time::Duration;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let simulator = Simulator::builder()
///     .invocation_timeout(Duration::from_secs(30))
///     .function_name("my-function")
///     .build()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Default)]
#[must_use = "builders do nothing unless .build() is called"]
pub struct SimulatorBuilder {
    config: SimulatorConfig,
    port: Option<u16>,
    freeze_mode: FreezeMode,
    runtime_pid: Option<u32>,
    extension_pids: Vec<u32>,
}

impl SimulatorBuilder {
    /// Creates a new simulator builder with default configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the invocation timeout.
    ///
    /// This timeout is used to calculate the `Lambda-Runtime-Deadline-Ms` header
    /// sent to the runtime. However, timeout enforcement is not yet implemented
    /// in Phase 1 - invocations will not be automatically terminated.
    pub fn invocation_timeout(mut self, timeout: Duration) -> Self {
        self.config.invocation_timeout_ms = timeout.as_millis() as u64;
        self
    }

    /// Sets the initialization timeout.
    ///
    /// **Note:** Timeout enforcement is not yet implemented in Phase 1.
    pub fn init_timeout(mut self, timeout: Duration) -> Self {
        self.config.init_timeout_ms = timeout.as_millis() as u64;
        self
    }

    /// Sets the function name.
    pub fn function_name(mut self, name: impl Into<String>) -> Self {
        self.config.function_name = name.into();
        self
    }

    /// Sets the function version.
    pub fn function_version(mut self, version: impl Into<String>) -> Self {
        self.config.function_version = version.into();
        self
    }

    /// Sets the function memory size in MB.
    pub fn memory_size_mb(mut self, memory: u32) -> Self {
        self.config.memory_size_mb = memory;
        self
    }

    /// Sets the function handler name.
    ///
    /// This is used in extension registration responses and the `_HANDLER`
    /// environment variable.
    pub fn handler(mut self, handler: impl Into<String>) -> Self {
        self.config.handler = Some(handler.into());
        self
    }

    /// Sets the AWS region.
    ///
    /// This is used for `AWS_REGION` and `AWS_DEFAULT_REGION` environment
    /// variables, as well as ARN construction.
    ///
    /// Default: "us-east-1"
    pub fn region(mut self, region: impl Into<String>) -> Self {
        self.config.region = region.into();
        self
    }

    /// Sets the AWS account ID.
    ///
    /// This is used in extension registration responses and ARN construction.
    pub fn account_id(mut self, account_id: impl Into<String>) -> Self {
        self.config.account_id = Some(account_id.into());
        self
    }

    /// Sets the port to bind to. If not specified, a random available port will be used.
    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    /// Sets the timeout for waiting for extensions to be ready.
    ///
    /// After the runtime completes an invocation, the simulator will wait up to
    /// this duration for all extensions to signal readiness by polling `/next`.
    /// If the timeout expires, the simulator proceeds anyway.
    ///
    /// Default: 2 seconds
    pub fn extension_ready_timeout(mut self, timeout: Duration) -> Self {
        self.config.extension_ready_timeout_ms = timeout.as_millis() as u64;
        self
    }

    /// Sets the timeout for graceful shutdown.
    ///
    /// During graceful shutdown, extensions subscribed to SHUTDOWN events have
    /// this amount of time to complete their cleanup work and signal readiness.
    /// If the timeout expires, shutdown proceeds anyway.
    ///
    /// Default: 2 seconds
    pub fn shutdown_timeout(mut self, timeout: Duration) -> Self {
        self.config.shutdown_timeout_ms = timeout.as_millis() as u64;
        self
    }

    /// Sets the freeze mode for process freezing simulation.
    ///
    /// When set to `FreezeMode::Process`, the simulator will send SIGSTOP/SIGCONT
    /// signals to simulate Lambda's freeze/thaw behaviour. This requires a runtime
    /// PID to be configured via `runtime_pid()`.
    ///
    /// # Platform Support
    ///
    /// Process freezing is only supported on Unix platforms. On other platforms,
    /// `FreezeMode::Process` will fail at build time.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::{Simulator, FreezeMode};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder()
    ///     .freeze_mode(FreezeMode::Process)
    ///     .runtime_pid(12345)
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn freeze_mode(mut self, mode: FreezeMode) -> Self {
        self.freeze_mode = mode;
        self
    }

    /// Sets the PID of the runtime process for freeze/thaw simulation.
    ///
    /// This is required when using `FreezeMode::Process`. The simulator will
    /// send SIGSTOP to this process after each invocation response is fully
    /// sent, and SIGCONT when a new invocation is enqueued.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::{Simulator, FreezeMode};
    /// use std::process;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Use current process PID (for testing)
    /// let simulator = Simulator::builder()
    ///     .freeze_mode(FreezeMode::Process)
    ///     .runtime_pid(process::id())
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn runtime_pid(mut self, pid: u32) -> Self {
        self.runtime_pid = Some(pid);
        self
    }

    /// Sets the PIDs of extension processes for freeze/thaw simulation.
    ///
    /// In real AWS Lambda, the entire execution environment is frozen between
    /// invocations, including all extension processes. Use this method to
    /// register extension PIDs that should be frozen along with the runtime.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::{Simulator, FreezeMode};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder()
    ///     .freeze_mode(FreezeMode::Process)
    ///     .runtime_pid(12345)
    ///     .extension_pids(vec![12346, 12347])
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn extension_pids(mut self, pids: Vec<u32>) -> Self {
        self.extension_pids = pids;
        self
    }

    /// Builds and starts the simulator.
    ///
    /// # Returns
    ///
    /// A running simulator instance.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The server fails to start or bind to the specified address.
    /// - `FreezeMode::Process` is used on a non-Unix platform.
    pub async fn build(self) -> SimulatorResult<Simulator> {
        // Note: FreezeMode::Process no longer requires runtime_pid at build time.
        // PIDs can be registered dynamically using register_freeze_pid() after
        // spawning processes. This supports the realistic workflow where the
        // simulator must be running before processes can connect to it.

        #[cfg(not(unix))]
        if self.freeze_mode == FreezeMode::Process {
            return Err(SimulatorError::InvalidConfiguration(
                "FreezeMode::Process is only supported on Unix platforms".to_string(),
            ));
        }

        let all_pids: Vec<u32> = self
            .runtime_pid
            .into_iter()
            .chain(self.extension_pids)
            .collect();
        let freeze_state = Arc::new(FreezeState::with_pids(self.freeze_mode, all_pids));
        let runtime_state = Arc::new(RuntimeState::new());
        let extension_state = Arc::new(ExtensionState::new());
        let telemetry_state = Arc::new(TelemetryState::new());
        let readiness_tracker = Arc::new(ExtensionReadinessTracker::new());
        let config = Arc::new(self.config);

        let runtime_api_state = RuntimeApiState {
            runtime: runtime_state.clone(),
            telemetry: telemetry_state.clone(),
            freeze: freeze_state.clone(),
            readiness: readiness_tracker.clone(),
            config: config.clone(),
        };
        let runtime_router = create_runtime_api_router(runtime_api_state);

        let extensions_api_state = ExtensionsApiState {
            extensions: extension_state.clone(),
            readiness: readiness_tracker.clone(),
            config: config.clone(),
            runtime: runtime_state.clone(),
        };
        let extensions_router = create_extensions_api_router(extensions_api_state);

        let telemetry_api_state = TelemetryApiState {
            telemetry: telemetry_state.clone(),
        };
        let telemetry_router = create_telemetry_api_router(telemetry_api_state);

        let combined_router = runtime_router
            .merge(extensions_router)
            .merge(telemetry_router)
            .fallback(|req: axum::extract::Request| async move {
                tracing::warn!(
                    method = %req.method(),
                    uri = %req.uri(),
                    "Unhandled request"
                );
                axum::http::StatusCode::NOT_FOUND
            });

        let addr: SocketAddr = if let Some(port) = self.port {
            ([127, 0, 0, 1], port).into()
        } else {
            ([127, 0, 0, 1], 0).into()
        };

        let listener = TcpListener::bind(addr)
            .await
            .map_err(|e| SimulatorError::BindError(e.to_string()))?;

        let local_addr = listener
            .local_addr()
            .map_err(|e| SimulatorError::ServerStart(e.to_string()))?;

        let server_handle = tokio::spawn(async move {
            axum::serve(listener, combined_router)
                .await
                .map_err(|e| SimulatorError::ServerStart(e.to_string()))
        });

        // Emit platform.initStart telemetry event
        let init_start = PlatformInitStart {
            initialization_type: InitializationType::OnDemand,
            phase: Phase::Init,
            function_name: Some(config.function_name.clone()),
            function_version: Some(config.function_version.clone()),
            instance_id: Some(config.instance_id.clone()),
            instance_max_memory: Some(config.memory_size_mb),
            runtime_version: None,
            runtime_version_arn: None,
            tracing: None,
        };

        let init_start_event = TelemetryEvent {
            time: runtime_state.init_started_at(),
            event_type: "platform.initStart".to_string(),
            record: json!(init_start),
        };

        telemetry_state
            .broadcast_event(init_start_event, TelemetryEventType::Platform)
            .await;

        tracing::info!(target: "lambda_lifecycle", "");
        tracing::info!(target: "lambda_lifecycle", "═══════════════════════════════════════════════════════════");
        tracing::info!(target: "lambda_lifecycle", "  INIT PHASE");
        tracing::info!(target: "lambda_lifecycle", "═══════════════════════════════════════════════════════════");
        tracing::info!(target: "lambda_lifecycle", "📋 platform.initStart (function: {})", config.function_name);

        Ok(Simulator {
            runtime_state,
            extension_state,
            telemetry_state,
            freeze_state,
            readiness_tracker,
            config,
            addr: local_addr,
            server_handle,
        })
    }
}

/// A running Lambda runtime simulator.
///
/// The simulator provides an HTTP server that implements both the Lambda Runtime API
/// and Extensions API, allowing Lambda runtimes and extensions to be tested locally.
pub struct Simulator {
    runtime_state: Arc<RuntimeState>,
    extension_state: Arc<ExtensionState>,
    telemetry_state: Arc<TelemetryState>,
    freeze_state: Arc<FreezeState>,
    readiness_tracker: Arc<ExtensionReadinessTracker>,
    config: Arc<SimulatorConfig>,
    addr: SocketAddr,
    server_handle: JoinHandle<SimulatorResult<()>>,
}

impl Simulator {
    /// Creates a new simulator builder.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::Simulator;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder()
    ///     .function_name("my-function")
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn builder() -> SimulatorBuilder {
        SimulatorBuilder::new()
    }

    /// Returns the base URL for the Runtime API.
    ///
    /// This should be set as the `AWS_LAMBDA_RUNTIME_API` environment variable
    /// for Lambda runtimes.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::Simulator;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder().build().await?;
    /// let runtime_api_url = simulator.runtime_api_url();
    /// println!("Set AWS_LAMBDA_RUNTIME_API={}", runtime_api_url);
    /// # Ok(())
    /// # }
    /// ```
    pub fn runtime_api_url(&self) -> String {
        format!("http://{}", self.addr)
    }

    /// Returns the socket address the simulator is listening on.
    pub fn addr(&self) -> SocketAddr {
        self.addr
    }

    /// Enqueues an invocation for processing.
    ///
    /// If process freezing is enabled and the process is currently frozen,
    /// this method will unfreeze (SIGCONT) the process before enqueuing
    /// the invocation.
    ///
    /// # Arguments
    ///
    /// * `invocation` - The invocation to enqueue
    ///
    /// # Returns
    ///
    /// The request ID of the enqueued invocation.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::{Simulator, InvocationBuilder};
    /// use serde_json::json;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder().build().await?;
    ///
    /// let invocation = InvocationBuilder::new()
    ///     .payload(json!({"key": "value"}))
    ///     .build()?;
    ///
    /// let request_id = simulator.enqueue(invocation).await;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn enqueue(&self, invocation: Invocation) -> String {
        let was_frozen = self.freeze_state.is_frozen();
        if let Err(e) = self.freeze_state.unfreeze() {
            panic!(
                "Failed to unfreeze processes before invocation: {}. \
                 The target processes are stuck in SIGSTOP state and cannot continue.",
                e
            );
        }

        let request_id = invocation.request_id.clone();

        tracing::info!(target: "lambda_lifecycle", "");
        tracing::info!(target: "lambda_lifecycle", "═══════════════════════════════════════════════════════════");
        tracing::info!(target: "lambda_lifecycle", "  INVOKE PHASE");
        tracing::info!(target: "lambda_lifecycle", "═══════════════════════════════════════════════════════════");
        if was_frozen {
            tracing::info!(target: "lambda_lifecycle", "🔥 Thawing environment (SIGCONT)");
        }
        tracing::info!(target: "lambda_lifecycle", "▶️  platform.start (request_id: {})", &invocation.request_id[..8]);

        let invoke_subscribers = self.extension_state.get_invoke_subscribers().await;
        self.readiness_tracker
            .start_invocation(&request_id, invoke_subscribers)
            .await;

        let event = LifecycleEvent::Invoke {
            deadline_ms: invocation.deadline_ms(),
            request_id: invocation.request_id.clone(),
            invoked_function_arn: invocation.invoked_function_arn.clone(),
            tracing: TracingInfo {
                trace_type: "X-Amzn-Trace-Id".to_string(),
                value: invocation.trace_id.clone(),
            },
        };

        self.runtime_state.enqueue_invocation(invocation).await;

        tracing::info!(target: "lambda_lifecycle", "📤 Broadcasting INVOKE event to extensions");
        self.extension_state.broadcast_event(event).await;

        request_id
    }

    /// Enqueues a simple invocation with just a payload.
    ///
    /// # Arguments
    ///
    /// * `payload` - The JSON payload for the invocation
    ///
    /// # Returns
    ///
    /// The request ID of the enqueued invocation.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::Simulator;
    /// use serde_json::json;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder().build().await?;
    /// let request_id = simulator.enqueue_payload(json!({"key": "value"})).await;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn enqueue_payload(&self, payload: Value) -> String {
        let invocation = Invocation::new(payload, self.config.invocation_timeout_ms);
        self.enqueue(invocation).await
    }

    /// Gets the state of a specific invocation.
    ///
    /// # Arguments
    ///
    /// * `request_id` - The request ID to look up
    ///
    /// # Returns
    ///
    /// The invocation state if found.
    pub async fn get_invocation_state(&self, request_id: &str) -> Option<InvocationState> {
        self.runtime_state.get_invocation_state(request_id).await
    }

    /// Gets all invocation states.
    pub async fn get_all_invocation_states(&self) -> Vec<InvocationState> {
        self.runtime_state.get_all_states().await
    }

    /// Checks if the runtime has been initialized.
    pub async fn is_initialized(&self) -> bool {
        self.runtime_state.is_initialized().await
    }

    /// Gets the initialization error if one occurred.
    pub async fn get_init_error(&self) -> Option<String> {
        self.runtime_state.get_init_error().await
    }

    /// Gets all registered extensions.
    ///
    /// # Returns
    ///
    /// A list of all extensions that have registered with the simulator.
    pub async fn get_registered_extensions(&self) -> Vec<RegisteredExtension> {
        self.extension_state.get_all_extensions().await
    }

    /// Gets the number of registered extensions.
    pub async fn extension_count(&self) -> usize {
        self.extension_state.extension_count().await
    }

    /// Shuts down the simulator immediately without waiting for extensions.
    ///
    /// This will unfreeze any frozen process, abort the HTTP server,
    /// clean up background telemetry tasks, and wait for everything to finish.
    ///
    /// For graceful shutdown that allows extensions to complete cleanup work,
    /// use [`graceful_shutdown`](Self::graceful_shutdown) instead.
    pub async fn shutdown(self) {
        self.freeze_state.force_unfreeze();

        self.telemetry_state.shutdown().await;

        self.server_handle.abort();
        let _ = self.server_handle.await;
    }

    /// Gracefully shuts down the simulator, allowing extensions to complete cleanup.
    ///
    /// This method performs a graceful shutdown sequence that matches Lambda's
    /// actual behavior:
    ///
    /// 1. Unfreezes the runtime process (if frozen)
    /// 2. Transitions to `ShuttingDown` phase
    /// 3. Broadcasts a `SHUTDOWN` event to all subscribed extensions
    /// 4. Waits for extensions to acknowledge by polling `/next`
    /// 5. Cleans up resources and stops the HTTP server
    ///
    /// # Arguments
    ///
    /// * `reason` - The reason for shutdown (Spindown, Timeout, or Failure)
    ///
    /// # Extension Behavior
    ///
    /// Extensions subscribed to SHUTDOWN events will receive the event when they
    /// poll `/next`. After receiving the SHUTDOWN event, extensions should perform
    /// their cleanup work (e.g., flushing buffers, sending final telemetry batches)
    /// and then poll `/next` again to signal completion.
    ///
    /// If extensions don't complete within the configured `shutdown_timeout`,
    /// the simulator proceeds with shutdown anyway.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::{Simulator, ShutdownReason};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder().build().await?;
    ///
    /// // ... run invocations ...
    ///
    /// // Graceful shutdown with SPINDOWN reason
    /// simulator.graceful_shutdown(ShutdownReason::Spindown).await;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn graceful_shutdown(self, reason: ShutdownReason) {
        tracing::info!(target: "lambda_lifecycle", "");
        tracing::info!(target: "lambda_lifecycle", "═══════════════════════════════════════════════════════════");
        tracing::info!(target: "lambda_lifecycle", "  SHUTDOWN PHASE");
        tracing::info!(target: "lambda_lifecycle", "═══════════════════════════════════════════════════════════");
        tracing::info!(target: "lambda_lifecycle", "🛑 Shutdown initiated (reason: {:?})", reason);

        self.freeze_state.force_unfreeze();

        self.runtime_state.mark_shutting_down().await;

        // Flush any buffered telemetry events before sending SHUTDOWN.
        // The telemetry delivery task uses an interval timer, so events like
        // platform.report may still be buffered. Flushing ensures extensions
        // receive all telemetry before they begin shutdown processing.
        self.telemetry_state.flush_all().await;

        // Wait for the flush operation to fully complete.
        // This ensures extensions have received and processed all telemetry
        // before we send the SHUTDOWN event.
        self.telemetry_state
            .wait_for_flush_complete(Duration::from_millis(100))
            .await;

        let shutdown_subscribers = self.extension_state.get_shutdown_subscribers().await;
        let has_shutdown_subscribers = !shutdown_subscribers.is_empty();

        if has_shutdown_subscribers {
            self.extension_state.clear_shutdown_acknowledged().await;

            let deadline_ms = Utc::now()
                .timestamp_millis()
                .saturating_add(self.config.shutdown_timeout_ms as i64);

            let shutdown_event = LifecycleEvent::Shutdown {
                shutdown_reason: reason,
                deadline_ms,
            };

            tracing::info!(target: "lambda_lifecycle", "📤 Broadcasting SHUTDOWN event to extensions");
            self.extension_state.broadcast_event(shutdown_event).await;

            let timeout = Duration::from_millis(self.config.shutdown_timeout_ms);
            let _ = tokio::time::timeout(
                timeout,
                self.extension_state
                    .wait_for_shutdown_acknowledged(&shutdown_subscribers),
            )
            .await;
        }

        self.telemetry_state.shutdown().await;

        self.server_handle.abort();
        let _ = self.server_handle.await;
    }

    /// Waits for an invocation to reach a terminal state (Success, Error, or Timeout).
    ///
    /// This method uses efficient event-driven waiting instead of polling,
    /// making tests more reliable and faster.
    ///
    /// # Arguments
    ///
    /// * `request_id` - The request ID to wait for
    /// * `timeout` - Maximum duration to wait
    ///
    /// # Returns
    ///
    /// The final invocation state
    ///
    /// # Errors
    ///
    /// Returns `SimulatorError::Timeout` if the invocation doesn't complete within the timeout,
    /// or `SimulatorError::InvocationNotFound` if the request ID doesn't exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::Simulator;
    /// use serde_json::json;
    /// use std::time::Duration;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder().build().await?;
    /// let request_id = simulator.enqueue_payload(json!({"test": "data"})).await;
    ///
    /// let state = simulator.wait_for_invocation_complete(&request_id, Duration::from_secs(5)).await?;
    /// assert_eq!(state.status, lambda_simulator::InvocationStatus::Success);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn wait_for_invocation_complete(
        &self,
        request_id: &str,
        timeout: Duration,
    ) -> SimulatorResult<InvocationState> {
        let deadline = tokio::time::Instant::now() + timeout;

        loop {
            if let Some(state) = self.runtime_state.get_invocation_state(request_id).await {
                match state.status {
                    InvocationStatus::Success
                    | InvocationStatus::Error
                    | InvocationStatus::Timeout => {
                        return Ok(state);
                    }
                    _ => {}
                }
            } else {
                return Err(SimulatorError::InvocationNotFound(request_id.to_string()));
            }

            if tokio::time::Instant::now() >= deadline {
                return Err(SimulatorError::Timeout(format!(
                    "Invocation {} did not complete within {:?}",
                    request_id, timeout
                )));
            }

            tokio::select! {
                _ = self.runtime_state.wait_for_state_change() => {},
                _ = tokio::time::sleep_until(deadline) => {
                    return Err(SimulatorError::Timeout(format!(
                        "Invocation {} did not complete within {:?}",
                        request_id, timeout
                    )));
                }
            }
        }
    }

    /// Waits for a condition to become true.
    ///
    /// This is a general-purpose helper that polls a condition function.
    /// For common conditions, use specific helpers like `wait_for_invocation_complete`.
    ///
    /// # Arguments
    ///
    /// * `condition` - Async function that returns true when the condition is met
    /// * `timeout` - Maximum duration to wait
    ///
    /// # Errors
    ///
    /// Returns `SimulatorError::Timeout` if the condition doesn't become true within the timeout.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::Simulator;
    /// use std::time::Duration;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder().build().await?;
    ///
    /// // Wait for 3 extensions to register
    /// simulator.wait_for(
    ///     || async { simulator.extension_count().await >= 3 },
    ///     Duration::from_secs(5)
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn wait_for<F, Fut>(&self, condition: F, timeout: Duration) -> SimulatorResult<()>
    where
        F: Fn() -> Fut,
        Fut: std::future::Future<Output = bool>,
    {
        let deadline = tokio::time::Instant::now() + timeout;
        let poll_interval = Duration::from_millis(10);

        loop {
            if condition().await {
                return Ok(());
            }

            if tokio::time::Instant::now() >= deadline {
                return Err(SimulatorError::Timeout(format!(
                    "Condition did not become true within {:?}",
                    timeout
                )));
            }

            tokio::time::sleep(poll_interval).await;
        }
    }

    /// Enables test mode telemetry capture.
    ///
    /// When enabled, all telemetry events are captured in memory,
    /// avoiding the need to set up HTTP servers in tests.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::Simulator;
    /// use serde_json::json;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder().build().await?;
    /// simulator.enable_telemetry_capture().await;
    ///
    /// simulator.enqueue_payload(json!({"test": "data"})).await;
    ///
    /// let events = simulator.get_telemetry_events().await;
    /// assert!(!events.is_empty());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn enable_telemetry_capture(&self) {
        self.telemetry_state.enable_capture().await;
    }

    /// Gets all captured telemetry events.
    ///
    /// Returns an empty vector if telemetry capture is not enabled.
    pub async fn get_telemetry_events(&self) -> Vec<TelemetryEvent> {
        self.telemetry_state.get_captured_events().await
    }

    /// Gets captured telemetry events filtered by event type.
    ///
    /// # Arguments
    ///
    /// * `event_type` - The event type to filter by (e.g., "platform.start")
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::Simulator;
    /// use serde_json::json;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder().build().await?;
    /// simulator.enable_telemetry_capture().await;
    ///
    /// simulator.enqueue_payload(json!({"test": "data"})).await;
    ///
    /// let start_events = simulator.get_telemetry_events_by_type("platform.start").await;
    /// assert_eq!(start_events.len(), 1);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_telemetry_events_by_type(&self, event_type: &str) -> Vec<TelemetryEvent> {
        self.telemetry_state
            .get_captured_events_by_type(event_type)
            .await
    }

    /// Clears all captured telemetry events.
    pub async fn clear_telemetry_events(&self) {
        self.telemetry_state.clear_captured_events().await;
    }

    /// Gets the current lifecycle phase of the simulator.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::{Simulator, SimulatorPhase};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder().build().await?;
    /// assert_eq!(simulator.phase().await, SimulatorPhase::Initializing);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn phase(&self) -> SimulatorPhase {
        self.runtime_state.get_phase().await
    }

    /// Waits for the simulator to reach a specific phase.
    ///
    /// # Arguments
    ///
    /// * `target_phase` - The phase to wait for
    /// * `timeout` - Maximum duration to wait
    ///
    /// # Errors
    ///
    /// Returns `SimulatorError::Timeout` if the phase is not reached within the timeout.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::{Simulator, SimulatorPhase};
    /// use std::time::Duration;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder().build().await?;
    ///
    /// // Wait for runtime to initialize
    /// simulator.wait_for_phase(SimulatorPhase::Ready, Duration::from_secs(5)).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn wait_for_phase(
        &self,
        target_phase: SimulatorPhase,
        timeout: Duration,
    ) -> SimulatorResult<()> {
        let deadline = tokio::time::Instant::now() + timeout;

        tokio::select! {
            _ = self.runtime_state.wait_for_phase(target_phase) => Ok(()),
            _ = tokio::time::sleep_until(deadline) => {
                Err(SimulatorError::Timeout(format!(
                    "Simulator did not reach phase {:?} within {:?}",
                    target_phase, timeout
                )))
            }
        }
    }

    /// Marks the runtime as initialized and transitions to Ready phase.
    ///
    /// This is typically called internally when the first runtime polls for an invocation,
    /// but can be called explicitly in tests.
    pub async fn mark_initialized(&self) {
        self.runtime_state.mark_initialized().await;
    }

    /// Returns whether the runtime process is currently frozen.
    ///
    /// This is useful in tests to verify freeze behaviour.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::{Simulator, FreezeMode};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder()
    ///     .freeze_mode(FreezeMode::Process)
    ///     .runtime_pid(12345)
    ///     .build()
    ///     .await?;
    ///
    /// assert!(!simulator.is_frozen());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_frozen(&self) -> bool {
        self.freeze_state.is_frozen()
    }

    /// Waits for the process to become frozen.
    ///
    /// This is useful in tests to verify freeze behaviour after sending
    /// an invocation response.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Maximum duration to wait
    ///
    /// # Errors
    ///
    /// Returns `SimulatorError::Timeout` if the process doesn't freeze within the timeout.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::{Simulator, FreezeMode};
    /// use std::time::Duration;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder()
    ///     .freeze_mode(FreezeMode::Process)
    ///     .runtime_pid(12345)
    ///     .build()
    ///     .await?;
    ///
    /// // After an invocation completes...
    /// simulator.wait_for_frozen(Duration::from_secs(5)).await?;
    /// assert!(simulator.is_frozen());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn wait_for_frozen(&self, timeout: Duration) -> SimulatorResult<()> {
        let deadline = tokio::time::Instant::now() + timeout;

        loop {
            if self.freeze_state.is_frozen() {
                return Ok(());
            }

            if tokio::time::Instant::now() >= deadline {
                return Err(SimulatorError::Timeout(
                    "Process did not freeze within timeout".to_string(),
                ));
            }

            tokio::select! {
                _ = self.freeze_state.wait_for_state_change() => {},
                _ = tokio::time::sleep_until(deadline) => {
                    return Err(SimulatorError::Timeout(
                        "Process did not freeze within timeout".to_string(),
                    ));
                }
            }
        }
    }

    /// Returns the current freeze mode.
    pub fn freeze_mode(&self) -> FreezeMode {
        self.freeze_state.mode()
    }

    /// Returns the current freeze epoch.
    ///
    /// The epoch increments on each unfreeze operation. This can be used
    /// in tests to verify freeze/thaw cycles.
    pub fn freeze_epoch(&self) -> u64 {
        self.freeze_state.current_epoch()
    }

    /// Registers a process ID for freeze/thaw operations.
    ///
    /// In real AWS Lambda, the entire execution environment is frozen between
    /// invocations - this includes the runtime and all extension processes.
    /// Use this method to register PIDs after spawning processes, so they
    /// will be included in freeze/thaw cycles.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::{Simulator, FreezeMode};
    /// use std::process::Command;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder()
    ///     .freeze_mode(FreezeMode::Process)
    ///     .build()
    ///     .await?;
    ///
    /// // Spawn runtime and extension processes
    /// let runtime = Command::new("my-runtime")
    ///     .env("AWS_LAMBDA_RUNTIME_API", simulator.runtime_api_url().replace("http://", ""))
    ///     .spawn()?;
    ///
    /// let extension = Command::new("my-extension")
    ///     .env("AWS_LAMBDA_RUNTIME_API", simulator.runtime_api_url().replace("http://", ""))
    ///     .spawn()?;
    ///
    /// // Register PIDs for freezing
    /// simulator.register_freeze_pid(runtime.id());
    /// simulator.register_freeze_pid(extension.id());
    /// # Ok(())
    /// # }
    /// ```
    pub fn register_freeze_pid(&self, pid: u32) {
        self.freeze_state.register_pid(pid);
    }

    /// Spawns a process with Lambda environment variables and registers it for freeze/thaw.
    ///
    /// This method:
    /// 1. Injects all Lambda environment variables (from `lambda_env_vars()`)
    /// 2. Spawns the process with the given configuration
    /// 3. Automatically registers the PID for freeze/thaw if `FreezeMode::Process` is enabled
    ///
    /// The spawned process will be automatically terminated when the returned
    /// `ManagedProcess` is dropped.
    ///
    /// # Arguments
    ///
    /// * `binary_path` - Path to the executable binary
    /// * `role` - Whether this is a runtime or extension process
    ///
    /// # Errors
    ///
    /// Returns `ProcessError::BinaryNotFound` if the binary doesn't exist.
    /// Returns `ProcessError::SpawnFailed` if the process fails to start.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::{Simulator, FreezeMode};
    /// use lambda_simulator::process::ProcessRole;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder()
    ///     .freeze_mode(FreezeMode::Process)
    ///     .build()
    ///     .await?;
    ///
    /// // Spawn a runtime process
    /// // In tests, use env!("CARGO_BIN_EXE_<name>") for binary path resolution
    /// let runtime = simulator.spawn_process(
    ///     "/path/to/runtime",
    ///     ProcessRole::Runtime,
    /// )?;
    ///
    /// println!("Runtime PID: {}", runtime.pid());
    /// # Ok(())
    /// # }
    /// ```
    pub fn spawn_process(
        &self,
        binary_path: impl Into<std::path::PathBuf>,
        role: crate::process::ProcessRole,
    ) -> Result<crate::process::ManagedProcess, crate::process::ProcessError> {
        let config = crate::process::ProcessConfig::new(binary_path, role);
        self.spawn_process_with_config(config)
    }

    /// Spawns a process with custom configuration.
    ///
    /// This is like `spawn_process` but allows full control over the process
    /// configuration, including additional environment variables and arguments.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::Simulator;
    /// use lambda_simulator::process::{ProcessConfig, ProcessRole};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder().build().await?;
    ///
    /// let config = ProcessConfig::new("/path/to/runtime", ProcessRole::Runtime)
    ///     .env("CUSTOM_VAR", "value")
    ///     .arg("--verbose")
    ///     .inherit_stdio(false);
    ///
    /// let runtime = simulator.spawn_process_with_config(config)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn spawn_process_with_config(
        &self,
        config: crate::process::ProcessConfig,
    ) -> Result<crate::process::ManagedProcess, crate::process::ProcessError> {
        let lambda_env = self.lambda_env_vars();
        let process = crate::process::spawn_process(config, lambda_env)?;

        if self.freeze_state.mode() == FreezeMode::Process {
            self.register_freeze_pid(process.pid());
            tracing::info!(
                target: "lambda_lifecycle",
                "📦 Spawned {} process: {} (PID: {}, registered for freeze/thaw)",
                process.role(),
                process.binary_name(),
                process.pid()
            );
        } else {
            tracing::info!(
                target: "lambda_lifecycle",
                "📦 Spawned {} process: {} (PID: {})",
                process.role(),
                process.binary_name(),
                process.pid()
            );
        }

        Ok(process)
    }

    /// Waits for all extensions to signal readiness for a specific invocation.
    ///
    /// Extensions signal readiness by polling the `/next` endpoint after
    /// the runtime has submitted its response. This method blocks until
    /// all extensions subscribed to INVOKE events have signalled readiness.
    ///
    /// # Arguments
    ///
    /// * `request_id` - The request ID to wait for
    /// * `timeout` - Maximum duration to wait
    ///
    /// # Errors
    ///
    /// Returns `SimulatorError::Timeout` if not all extensions become ready within the timeout.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::Simulator;
    /// use serde_json::json;
    /// use std::time::Duration;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder().build().await?;
    /// let request_id = simulator.enqueue_payload(json!({"test": "data"})).await;
    ///
    /// // Wait for extensions to be ready
    /// simulator.wait_for_extensions_ready(&request_id, Duration::from_secs(5)).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn wait_for_extensions_ready(
        &self,
        request_id: &str,
        timeout: Duration,
    ) -> SimulatorResult<()> {
        let deadline = tokio::time::Instant::now() + timeout;

        tokio::select! {
            _ = self.readiness_tracker.wait_for_all_ready(request_id) => Ok(()),
            _ = tokio::time::sleep_until(deadline) => {
                Err(SimulatorError::Timeout(format!(
                    "Extensions did not become ready for {} within {:?}",
                    request_id, timeout
                )))
            }
        }
    }

    /// Checks if all extensions are ready for a specific invocation.
    ///
    /// This is a non-blocking check that returns immediately.
    ///
    /// # Arguments
    ///
    /// * `request_id` - The request ID to check
    ///
    /// # Returns
    ///
    /// `true` if all expected extensions have signalled readiness.
    pub async fn are_extensions_ready(&self, request_id: &str) -> bool {
        self.readiness_tracker.is_all_ready(request_id).await
    }

    /// Gets the extension overhead time for an invocation.
    ///
    /// The overhead is the time between when the runtime completed its response
    /// and when all extensions signalled readiness.
    ///
    /// # Arguments
    ///
    /// * `request_id` - The request ID to get overhead for
    ///
    /// # Returns
    ///
    /// The overhead in milliseconds, or `None` if the invocation is not complete
    /// or extensions are not yet ready.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::Simulator;
    /// use serde_json::json;
    /// use std::time::Duration;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder().build().await?;
    /// let request_id = simulator.enqueue_payload(json!({"test": "data"})).await;
    ///
    /// // After invocation completes...
    /// if let Some(overhead_ms) = simulator.get_extension_overhead_ms(&request_id).await {
    ///     println!("Extension overhead: {:.2}ms", overhead_ms);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_extension_overhead_ms(&self, request_id: &str) -> Option<f64> {
        self.readiness_tracker
            .get_extension_overhead_ms(request_id)
            .await
    }

    /// Generates a map of standard AWS Lambda environment variables.
    ///
    /// This method creates a `HashMap` containing all the environment variables
    /// that AWS Lambda sets for function execution. These can be used when
    /// spawning a Lambda runtime process to simulate the real Lambda environment.
    ///
    /// # Environment Variables Included
    ///
    /// - `AWS_LAMBDA_FUNCTION_NAME` - Function name
    /// - `AWS_LAMBDA_FUNCTION_VERSION` - Function version
    /// - `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` - Memory allocation in MB
    /// - `AWS_LAMBDA_FUNCTION_ARN` - Function ARN (if account_id configured)
    /// - `AWS_LAMBDA_LOG_GROUP_NAME` - CloudWatch log group name
    /// - `AWS_LAMBDA_LOG_STREAM_NAME` - CloudWatch log stream name
    /// - `AWS_LAMBDA_RUNTIME_API` - Runtime API endpoint (host:port)
    /// - `AWS_LAMBDA_INITIALIZATION_TYPE` - Always "on-demand" for simulator
    /// - `AWS_REGION` / `AWS_DEFAULT_REGION` - AWS region
    /// - `AWS_ACCOUNT_ID` - AWS account ID (if configured)
    /// - `AWS_EXECUTION_ENV` - Runtime identifier
    /// - `LAMBDA_TASK_ROOT` - Path to function code (/var/task)
    /// - `LAMBDA_RUNTIME_DIR` - Path to runtime libraries (/var/runtime)
    /// - `TZ` - Timezone (UTC)
    /// - `LANG` - Locale (en_US.UTF-8)
    /// - `PATH` - System path
    /// - `LD_LIBRARY_PATH` - Library search path
    /// - `_HANDLER` - Handler identifier (if configured)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use lambda_simulator::Simulator;
    /// use std::process::Command;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let simulator = Simulator::builder()
    ///     .function_name("my-function")
    ///     .handler("bootstrap")
    ///     .build()
    ///     .await?;
    ///
    /// let env_vars = simulator.lambda_env_vars();
    ///
    /// let mut cmd = Command::new("./bootstrap");
    /// for (key, value) in &env_vars {
    ///     cmd.env(key, value);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn lambda_env_vars(&self) -> HashMap<String, String> {
        let mut env = HashMap::new();
        let config = &self.config;

        env.insert(
            "AWS_LAMBDA_FUNCTION_NAME".to_string(),
            config.function_name.clone(),
        );
        env.insert(
            "AWS_LAMBDA_FUNCTION_VERSION".to_string(),
            config.function_version.clone(),
        );
        env.insert(
            "AWS_LAMBDA_FUNCTION_MEMORY_SIZE".to_string(),
            config.memory_size_mb.to_string(),
        );
        env.insert(
            "AWS_LAMBDA_LOG_GROUP_NAME".to_string(),
            config.log_group_name.clone(),
        );
        env.insert(
            "AWS_LAMBDA_LOG_STREAM_NAME".to_string(),
            config.log_stream_name.clone(),
        );

        let host_port = format!("127.0.0.1:{}", self.addr.port());
        env.insert("AWS_LAMBDA_RUNTIME_API".to_string(), host_port);

        env.insert(
            "AWS_LAMBDA_INITIALIZATION_TYPE".to_string(),
            "on-demand".to_string(),
        );

        env.insert("AWS_REGION".to_string(), config.region.clone());
        env.insert("AWS_DEFAULT_REGION".to_string(), config.region.clone());

        env.insert(
            "AWS_EXECUTION_ENV".to_string(),
            "AWS_Lambda_provided.al2".to_string(),
        );

        env.insert("LAMBDA_TASK_ROOT".to_string(), "/var/task".to_string());
        env.insert("LAMBDA_RUNTIME_DIR".to_string(), "/var/runtime".to_string());

        if let Some(handler) = &config.handler {
            env.insert("_HANDLER".to_string(), handler.clone());
        }

        if let Some(account_id) = &config.account_id {
            env.insert("AWS_ACCOUNT_ID".to_string(), account_id.clone());
            let arn = format!(
                "arn:aws:lambda:{}:{}:function:{}",
                config.region, account_id, config.function_name
            );
            env.insert("AWS_LAMBDA_FUNCTION_ARN".to_string(), arn);
        }

        env.insert("TZ".to_string(), ":UTC".to_string());
        env.insert("LANG".to_string(), "en_US.UTF-8".to_string());
        env.insert(
            "PATH".to_string(),
            "/usr/local/bin:/usr/bin:/bin:/opt/bin".to_string(),
        );
        env.insert(
            "LD_LIBRARY_PATH".to_string(),
            "/var/lang/lib:/lib64:/usr/lib64:/var/runtime:/var/runtime/lib:/var/task:/var/task/lib:/opt/lib".to_string(),
        );

        env
    }
}