1+ using System ;
2+ using System . Threading ;
3+
4+ namespace AWS . Lambda . Powertools . Common . Core ;
5+
6+ /// <summary>
7+ /// Tracks Lambda lifecycle state including cold starts
8+ /// </summary>
9+ internal static class LambdaLifecycleTracker
10+ {
11+ // Static flag that's true only for the first Lambda container initialization
12+ private static bool _isFirstContainer = true ;
13+
14+ // Store the cold start state for the current invocation
15+ private static readonly AsyncLocal < bool ? > CurrentInvocationColdStart = new AsyncLocal < bool ? > ( ) ;
16+
17+ private static string _lambdaInitType ;
18+ private static string LambdaInitType => _lambdaInitType ?? Environment . GetEnvironmentVariable ( Constants . AWSInitializationTypeEnv ) ;
19+
20+ /// <summary>
21+ /// Returns true if the current Lambda invocation is a cold start
22+ /// </summary>
23+ public static bool IsColdStart
24+ {
25+ get
26+ {
27+ if ( LambdaInitType == "provisioned-concurrency" )
28+ {
29+ // If the Lambda is provisioned concurrency, it is not a cold start
30+ return false ;
31+ }
32+
33+ // Initialize the cold start state for this invocation if not already set
34+ if ( ! CurrentInvocationColdStart . Value . HasValue )
35+ {
36+ // Capture the container's cold start state for this entire invocation
37+ CurrentInvocationColdStart . Value = _isFirstContainer ;
38+
39+ // After detecting the first invocation, mark future ones as warm
40+ if ( _isFirstContainer )
41+ {
42+ _isFirstContainer = false ;
43+ }
44+ }
45+
46+ // Return the cold start state for this invocation (cannot change during the invocation)
47+ return CurrentInvocationColdStart . Value ?? false ;
48+ }
49+ }
50+
51+
52+
53+ /// <summary>
54+ /// Resets the cold start state for testing
55+ /// </summary>
56+ /// <param name="resetContainer">Whether to reset the container state (defaults to true)</param>
57+ internal static void Reset ( bool resetContainer = true )
58+ {
59+ if ( resetContainer )
60+ {
61+ _isFirstContainer = true ;
62+ }
63+ CurrentInvocationColdStart . Value = null ;
64+ _lambdaInitType = null ;
65+ }
66+ }
0 commit comments