Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
597d123
Automatic priming of powertools-metrics
subhash686 May 8, 2025
ec43605
Merge remote-tracking branch 'upstream/v2' into support_crac_on_power…
subhash686 May 8, 2025
91ee9df
Fixed resource name and added unit tests and javadoc comments
subhash686 May 14, 2025
e10a624
Invoke prime Dynamo persistent store
subhash686 May 17, 2025
747dad8
Merge branch 'v2' into support_crac_on_powertools_metrics
subhash686 May 28, 2025
c8d2404
Merge branch 'main' into support_crac_on_powertools_metrics
subhash686 Jun 12, 2025
7ba4cfa
Merge branch 'main' into support_crac_on_powertools_metrics
subhash686 Jun 13, 2025
8b2dba4
Merge branch 'main' into support_crac_on_powertools_metrics
subhash686 Jun 24, 2025
85513ea
Fixed Sonar issues
subhash686 Jul 2, 2025
e1906e9
Merge branch 'main' into support_crac_on_powertools_metrics
subhash686 Jul 7, 2025
0c80204
Update classesloaded.txt
subhash686 Jul 9, 2025
babd855
Merge branch 'main' into support_crac_on_powertools_metrics
phipag Jul 9, 2025
789564b
Moved priming to MetricsFactory and DynamoDBPersistenceStore, added P…
subhash686 Jul 22, 2025
4cebb6b
Update classesloaded.txt
subhash686 Jul 22, 2025
6336252
Update LambdaMetricsAspect.java
subhash686 Jul 22, 2025
27dad71
Update DynamoDBPersistenceStore.java
subhash686 Jul 22, 2025
685877e
Merge branch 'main' into support_crac_on_powertools_metrics
subhash686 Jul 22, 2025
ec37b49
Merge branch 'main' into support_crac_on_powertools_metrics
subhash686 Jul 28, 2025
a1e1545
Improved priming.md documentation and static initialization of classe…
subhash686 Jul 30, 2025
6261d06
Merge branch 'support_crac_on_powertools_metrics' of https://github.c…
subhash686 Jul 30, 2025
844dad7
Fixed a Sonarqube finding and added more unit tests to ensure all ava…
subhash686 Jul 31, 2025
9b6e5f9
Merge branch 'main' into support_crac_on_powertools_metrics
subhash686 Jul 31, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@
<mockito.version>5.18.0</mockito.version>
<mockito-junit-jupiter.version>5.18.0</mockito-junit-jupiter.version>
<junit-pioneer.version>2.3.0</junit-pioneer.version>
<crac.version>1.4.0</crac.version>

<!-- As we have a .mvn directory at the root of the project, this will evaluate to the root directory
regardless of where maven is run - sub-module, or root. -->
Expand Down Expand Up @@ -264,6 +265,11 @@
<artifactId>logback-ecs-encoder</artifactId>
<version>${elastic.version}</version>
</dependency>
<dependency>
<groupId>org.crac</groupId>
<artifactId>crac</artifactId>
<version>${crac.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* Copyright 2023 Amazon.com, Inc. or its affiliates.
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package software.amazon.lambda.powertools.common.internal;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;

/**
* Used to preload classes to support automatic priming for SnapStart
*/
public class ClassPreLoader {

Check failure on line 28 in powertools-common/src/main/java/software/amazon/lambda/powertools/common/internal/ClassPreLoader.java

View workflow job for this annotation

GitHub Actions / pmd_analyse

This class has only private constructors and may be final

Reports classes that may be made final because they cannot be extended from outside their compilation unit anyway. This is because all their constructors are private, so a subclass could not call the super constructor. ClassWithOnlyPrivateConstructorsShouldBeFinal (Priority: 1, Ruleset: Design) https://docs.pmd-code.org/snapshot/pmd_rules_java_design.html#classwithonlyprivateconstructorsshouldbefinal
public static final String CLASSES_FILE = "classesloaded.txt";

private ClassPreLoader() {
// Hide default constructor
}
/**
* Initializes the classes listed in the classesloaded resource
*/
public static void preloadClasses() {
try {
Enumeration<URL> files = ClassPreLoader.class.getClassLoader().getResources(CLASSES_FILE);
// If there are multiple files, preload classes from all of them
while (files.hasMoreElements()) {
URL url = files.nextElement();
URLConnection conn = url.openConnection();
conn.setUseCaches(false);
InputStream is = conn.getInputStream();

Check failure on line 45 in powertools-common/src/main/java/software/amazon/lambda/powertools/common/internal/ClassPreLoader.java

View workflow job for this annotation

GitHub Actions / pmd_analyse

Ensure that resources like this InputStream object are closed after use

Ensure that resources (like `java.sql.Connection`, `java.sql.Statement`, and `java.sql.ResultSet` objects and any subtype of `java.lang.AutoCloseable`) are always closed after use. Failing to do so might result in resource leaks. Note: It suffices to configure the super type, e.g. `java.lang.AutoCloseable`, so that this rule automatically triggers on any subtype (e.g. `java.io.FileInputStream`). Additionally specifying `java.sql.Connection` helps in detecting the types, if the type resolution / auxclasspath is not correctly setup. Note: Since PMD 6.16.0 the default value for the property `types` contains `java.lang.AutoCloseable` and detects now cases where the standard `java.io.*Stream` classes are involved. In order to restore the old behaviour, just remove "AutoCloseable" from the types. CloseResource (Priority: 1, Ruleset: Error Prone) https://docs.pmd-code.org/snapshot/pmd_rules_java_errorprone.html#closeresource
preloadClassesFromStream(is);
}
} catch (IOException ignored) {
// No action is required if preloading fails for any reason
}
}

/**
* Loads the list of classes passed as a stream
*
* @param is
*/
private static void preloadClassesFromStream(InputStream is) {
try (is;
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(isr)) {
String line;
while ((line = reader.readLine()) != null) {
int idx = line.indexOf('#');
if (idx != -1) {
line = line.substring(0, idx);
}
final String className = line.stripTrailing();
if (!className.isBlank()) {
Class.forName(className, true, ClassPreLoader.class.getClassLoader());
}
}
} catch (Exception ignored) {
// No action is required if preloading fails for any reason
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package software.amazon.lambda.powertools.common.internal;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class ClassPreLoaderTest {

@Test
void preloadClasses_shouldIgnoreInvalidClassesAndLoadValidClasses() {
// Verify that the missing class did not throw any exception
assertDoesNotThrow(ClassPreLoader::preloadClasses);
}
}
1 change: 1 addition & 0 deletions powertools-common/src/test/resources/classesloaded.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
software.amazon.lambda.powertools.common.internal.NonExistingClass
4 changes: 4 additions & 0 deletions powertools-idempotency/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@
<groupId>software.amazon.lambda</groupId>
<artifactId>powertools-common</artifactId>
</dependency>
<dependency>
<groupId>org.crac</groupId>
<artifactId>crac</artifactId>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>org.junit.jupiter</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.crac.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -46,7 +47,7 @@
* {@link software.amazon.lambda.powertools.idempotency.persistence.PersistenceStore}
* to store the result of previous calls.
*/
public class IdempotencyHandler {
public class IdempotencyHandler implements Resource{
private static final Logger LOG = LoggerFactory.getLogger(IdempotencyHandler.class);
private static final int MAX_RETRIES = 2;

Expand All @@ -63,6 +64,28 @@
persistenceStore.configure(Idempotency.getInstance().getConfig(), functionName);
}

/**
* Primes the persistent store by invoking the get record method with a key that doesn't exist.
*
* @param context
* @throws Exception
*/
@Override
public void beforeCheckpoint(org.crac.Context<? extends Resource> context) throws Exception {
try {
persistenceStore.getRecord("__invoke_prime__");
} catch (IdempotencyItemNotFoundException keyNotFound) {
// This is expected, as we are priming the store
} catch (Exception unknown) {

Check failure on line 79 in powertools-idempotency/powertools-idempotency-core/src/main/java/software/amazon/lambda/powertools/idempotency/internal/IdempotencyHandler.java

View workflow job for this annotation

GitHub Actions / pmd_analyse

Avoid empty catch blocks

Empty Catch Block finds instances where an exception is caught, but nothing is done. In most circumstances, this swallows an exception which should either be acted on or reported. EmptyCatchBlock (Priority: 1, Ruleset: Error Prone) https://docs.pmd-code.org/snapshot/pmd_rules_java_errorprone.html#emptycatchblock
// This is unexpected but we must continue without any interruption
}

Check failure on line 81 in powertools-idempotency/powertools-idempotency-core/src/main/java/software/amazon/lambda/powertools/idempotency/internal/IdempotencyHandler.java

View workflow job for this annotation

GitHub Actions / pmd_analyse

Avoid empty catch blocks

Empty Catch Block finds instances where an exception is caught, but nothing is done. In most circumstances, this swallows an exception which should either be acted on or reported. EmptyCatchBlock (Priority: 1, Ruleset: Error Prone) https://docs.pmd-code.org/snapshot/pmd_rules_java_errorprone.html#emptycatchblock

Check warning on line 81 in powertools-idempotency/powertools-idempotency-core/src/main/java/software/amazon/lambda/powertools/idempotency/internal/IdempotencyHandler.java

View workflow job for this annotation

GitHub Actions / pmd_analyse

'catch' branch identical to 'IdempotencyItemNotFoundException' branch

Identical `catch` branches use up vertical space and increase the complexity of code without adding functionality. It's better style to collapse identical branches into a single multi-catch branch. IdenticalCatchBranches (Priority: 3, Ruleset: Code Style) https://docs.pmd-code.org/snapshot/pmd_rules_java_codestyle.html#identicalcatchbranches
}

@Override
public void afterRestore(org.crac.Context<? extends Resource> context) throws Exception {
// This is a no-op, as we don't need to do anything after restore
}

/**
* Main entry point for handling idempotent execution of a function.
*
Expand Down Expand Up @@ -204,7 +227,7 @@
Object response;
try {
response = pjp.proceed(pjp.getArgs());
} catch (Throwable handlerException) {

Check failure on line 230 in powertools-idempotency/powertools-idempotency-core/src/main/java/software/amazon/lambda/powertools/idempotency/internal/IdempotencyHandler.java

View workflow job for this annotation

GitHub Actions / pmd_analyse

A catch statement should never catch throwable since it includes errors.

Catching Throwable errors is not recommended since its scope is very broad. It includes runtime issues such as OutOfMemoryError that should be exposed and managed separately. AvoidCatchingThrowable (Priority: 1, Ruleset: Error Prone) https://docs.pmd-code.org/snapshot/pmd_rules_java_errorprone.html#avoidcatchingthrowable
// We need these nested blocks to preserve function's exception in case the persistence store operation
// also raises an exception
try {
Expand Down
4 changes: 4 additions & 0 deletions powertools-metrics/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@
<artifactId>aspectjrt</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.crac</groupId>
<artifactId>crac</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.lambda</groupId>
<artifactId>powertools-common</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,12 @@
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import org.crac.Core;
import org.crac.Resource;

import com.amazonaws.services.lambda.runtime.Context;

import software.amazon.lambda.powertools.common.internal.ClassPreLoader;
import software.amazon.lambda.powertools.common.internal.LambdaConstants;
import software.amazon.lambda.powertools.common.internal.LambdaHandlerProcessor;
import software.amazon.lambda.powertools.metrics.FlushMetrics;
Expand All @@ -33,12 +37,16 @@
import software.amazon.lambda.powertools.metrics.model.DimensionSet;

@Aspect
public class LambdaMetricsAspect {
public class LambdaMetricsAspect implements Resource {
public static final String TRACE_ID_PROPERTY = "xray_trace_id";
public static final String REQUEST_ID_PROPERTY = "function_request_id";
private static final String SERVICE_DIMENSION = "Service";
private static final String FUNCTION_NAME_ENV_VAR = "POWERTOOLS_METRICS_FUNCTION_NAME";

public LambdaMetricsAspect() {
Core.getGlobalContext().register(this);
}

private String functionName(FlushMetrics metrics, Context context) {
if (!"".equals(metrics.functionName())) {
return metrics.functionName();
Expand Down Expand Up @@ -139,4 +147,14 @@ private void captureColdStartMetricIfEnabled(Context extractedContext, FlushMetr
metricsInstance.captureColdStartMetric(extractedContext, coldStartDimensions);
}
}

@Override
public void beforeCheckpoint(org.crac.Context<? extends Resource> context) throws Exception {
ClassPreLoader.preloadClasses();
}

@Override
public void afterRestore(org.crac.Context<? extends Resource> context) throws Exception {
// No action needed after restore
}
}
Loading