Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
25 changes: 25 additions & 0 deletions .github/workflows/pr-open.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,30 @@ jobs:
env:
MAVEN_OPTS: ${{ vars.MAVEN_OPTS }}

- name: Build & run examples
run: |
mvn \
--batch-mode \
--no-transfer-progress \
--update-snapshots \
--fail-at-end \
--errors \
-pl examples \
-am \
package \
-DskipTests

# Run from the examples module so that examples which load YAML via
# relative paths (src/main/resources/*.yml) resolve their config files.
cd examples
java -jar target/*-jar-with-dependencies.jar all \
-h 127.0.0.1 \
-p 3000 \
-n test \
--report target/example-reports/TEST-examples.xml
env:
MAVEN_OPTS: ${{ vars.MAVEN_OPTS }}

- name: Upload surefire/failsafe reports (always)
if: always()
uses: actions/upload-artifact@v4
Expand All @@ -151,5 +175,6 @@ jobs:
path: |
**/target/surefire-reports/**
**/target/failsafe-reports/**
examples/target/example-reports/**
if-no-files-found: ignore
retention-days: ${{ vars.ARTIFACT_RETENTION_DAYS }}
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,11 @@ class BehaviorFileMonitor implements Closeable {
private static final Logger log = LoggerFactory.getLogger(Loggers.BEHAVIOR);

private final BehaviorRegistry registry = BehaviorRegistry.getInstance();
// Use a scheduled executor with 2 threads: one for monitoring, one for reload tasks
private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(2, r -> {
Thread t = new Thread(r, "BehaviorFileMonitor");
t.setDaemon(true);
return t;
});
// Scheduled executor with 2 threads: one for monitoring, one for reload tasks.
// Created lazily and recreated after shutdown so that monitoring can be
// started, stopped, and started again within the same process (this is a
// singleton, so a single shut-down executor must not permanently disable it).
private ScheduledExecutorService executor;

private Path yamlFilePath;
private WatchService watchService;
Expand Down Expand Up @@ -113,13 +112,31 @@ public void startMonitoring(String yamlFilePath, long reloadDelayMs) throws IOEx

// Start monitoring thread
isMonitoring = true;
executor.submit(this::monitorFile);
ensureExecutor().submit(this::monitorFile);

if (log.isDebugEnabled()) {
log.debug("Started monitoring YAML file: %s checking every %,dms".formatted(yamlFilePath, reloadDelayMs));
}
}

/**
* Return the executor, (re)creating it if it has never been started or was
* previously shut down. Because this class is a process-wide singleton, a
* prior {@link #shutdown()} (for example via try-with-resources on the
* {@code Closeable} returned by {@code Behavior.startMonitoringWithResource})
* must not permanently prevent monitoring from being started again.
*/
private synchronized ScheduledExecutorService ensureExecutor() {
if (executor == null || executor.isShutdown()) {
executor = Executors.newScheduledThreadPool(2, r -> {
Thread t = new Thread(r, "BehaviorFileMonitor");
t.setDaemon(true);
return t;
});
}
return executor;
}

/**
* Stop monitoring the file
*/
Expand Down Expand Up @@ -240,7 +257,7 @@ private void handleFileChange() {
lastModified = currentModified;

// Schedule reload with delay to avoid multiple reloads
executor.schedule(this::loadBehaviors, reloadDelayMs, TimeUnit.MILLISECONDS);
ensureExecutor().schedule(this::loadBehaviors, reloadDelayMs, TimeUnit.MILLISECONDS);

} catch (Exception e) {
if (log.isErrorEnabled()) {
Expand Down Expand Up @@ -285,13 +302,25 @@ private void loadBehaviors() {
*/
public void shutdown() {
stopMonitoring();
executor.shutdown();

ScheduledExecutorService exec;
synchronized (this) {
exec = executor;
// Clear the reference so a subsequent startMonitoring() recreates it.
executor = null;
}

if (exec == null) {
return;
}

exec.shutdown();
try {
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
executor.shutdownNow();
if (!exec.awaitTermination(5, TimeUnit.SECONDS)) {
exec.shutdownNow();
}
} catch (InterruptedException e) {
executor.shutdownNow();
exec.shutdownNow();
Thread.currentThread().interrupt();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,8 @@ public class ErrorDetailVerbosityTest extends ClusterTest {

@BeforeAll
public static void setup() {
// Extended error-detail (subcode/message) plus the verbosity-3 expression
// build trace (SERVER-1137). The SERVER-1137 feature branch is cut from the
// 8.1.1 line and reports its base version as 8.1.1.0-start-*, so gate at
// 8.1.1 rather than the 8.1.3 release that first shipped the base tier.
Assumptions.assumeTrue(args.serverVersion.isGreaterOrEqual(8, 1, 1, 0),
"Extended error-detail requires server version 8.1.1 or later");
Assumptions.assumeTrue(args.serverVersion.isGreaterOrEqual(8, 1, 3, 0),
"Extended error-detail requires server version 8.1.3 or later");

intKey = args.set.id("edv-int-key");
strKey = args.set.id("edv-str-key");
Expand Down
2 changes: 2 additions & 0 deletions client/src/test/java/com/aerospike/client/sdk/SuiteCore.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.junit.platform.suite.api.Suite;

import com.aerospike.client.sdk.policy.AsyncRecordStreamTest;
import com.aerospike.client.sdk.policy.BehaviorFileMonitorRestartTest;
import com.aerospike.client.sdk.policy.BehaviorTest;
import com.aerospike.client.sdk.policy.BehaviorYamlTest;
import com.aerospike.client.sdk.policy.QueryProducerCancellationTest;
Expand All @@ -28,6 +29,7 @@
@Suite
@SelectClasses({
AsyncRecordStreamTest.class,
BehaviorFileMonitorRestartTest.class,
BehaviorTest.class,
BehaviorYamlTest.class,
QueryProducerCancellationTest.class,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
* Copyright 2012-2026 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more contributor
* license agreements WHICH ARE COMPATIBLE WITH THE APACHE LICENSE, VERSION 2.0.
*
* 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 com.aerospike.client.sdk.policy;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

/**
* Regression tests for {@link BehaviorFileMonitor} lifecycle.
*
* <p>The monitor is a process-wide singleton backed by a scheduled executor. A
* prior bug shut that executor down on {@code close()}/{@code shutdown()} and
* never recreated it, so the second {@code startMonitoring} in a JVM failed with
* {@code RejectedExecutionException}. Running examples in separate JVMs hid this;
* running them in one process (or any real app that stops and restarts
* monitoring) surfaced it. These tests lock in that monitoring is restartable.
*/
@DisplayName("BehaviorFileMonitor Restart Tests")
public class BehaviorFileMonitorRestartTest {

private static final String YAML = """
behaviors:
simple:
allOperations:
abandonCallAfter: 5s
maximumNumberOfCallAttempts: 3
""";

private Path writeConfig(Path dir) throws IOException {
Path file = dir.resolve("behavior-monitor-test.yml");
Files.writeString(file, YAML);
return file;
}

@AfterEach
void tearDown() {
// Reset shared singleton state so tests do not leak into one another.
Behavior.shutdownMonitor();
}

@Test
@DisplayName("Should restart monitoring after a try-with-resources close in the same process")
void shouldRestartAfterClose(@TempDir Path tempDir) throws IOException {
Path config = writeConfig(tempDir);

try (Closeable monitor = Behavior.startMonitoringWithResource(config.toString())) {
assertNotNull(monitor);
assertTrue(Behavior.isMonitoring(), "monitoring should be active during first session");
}
assertFalse(Behavior.isMonitoring(), "monitoring should stop after close");

// Before the fix, this second start reused the terminated singleton
// executor and threw RejectedExecutionException.
assertDoesNotThrow(() -> {
try (Closeable monitor = Behavior.startMonitoringWithResource(config.toString())) {
assertNotNull(monitor);
assertTrue(Behavior.isMonitoring(), "monitoring should be active during second session");
}
});
}

@Test
@DisplayName("Should restart monitoring after an explicit shutdown")
void shouldRestartAfterExplicitShutdown(@TempDir Path tempDir) throws IOException {
Path config = writeConfig(tempDir);

Behavior.startMonitoring(config.toString());
assertTrue(Behavior.isMonitoring());
Behavior.shutdownMonitor();
assertFalse(Behavior.isMonitoring());

assertDoesNotThrow(() -> Behavior.startMonitoring(config.toString()));
assertTrue(Behavior.isMonitoring());
}

@Test
@DisplayName("Should support several sequential monitoring sessions")
void shouldSupportSeveralSequentialSessions(@TempDir Path tempDir) throws IOException {
Path config = writeConfig(tempDir);

assertDoesNotThrow(() -> {
for (int i = 0; i < 3; i++) {
try (Closeable monitor = Behavior.startMonitoringWithResource(config.toString())) {
assertNotNull(monitor);
assertTrue(Behavior.isMonitoring(), "monitoring should be active in session " + i);
}
}
});
}
}
69 changes: 69 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Aerospike Java SDK Examples

The examples module contains runnable examples that double as documentation source. Example classes should focus on the SDK usage being demonstrated; the runner owns connection setup, configuration, verification, cleanup, and CI reporting.

## Run Examples

Build the examples JAR:

```bash
mvn -pl examples -am package -DskipTests
```

Run one example:

```bash
./examples/run_examples BatchExample -h localhost -p 3000 -n test
```

Run all registered examples:

```bash
./examples/run_examples all -h localhost -p 3000 -n test
```

Write a JUnit XML report:

```bash
./examples/run_examples all \
-h localhost \
-p 3000 \
-n test \
--report examples/target/example-reports/TEST-examples.xml
```

Useful runner options:

- `--fail-fast`: stop after the first failed example.
- `--include-tags smoke,records`: run examples with at least one matching tag.
- `--exclude-tags config`: skip examples with matching tags.

## Add An Example

1. Create a class in `src/main/java/com/aerospike/examples` that extends `Example`.
2. Implement `runExample()` with no constructor or runner arguments; use `cluster()`, `dataSet()`, `namespace()`, and `console` from `Example` when needed.
3. Use `dataSet()` or `dataSet("set-name")` when the example writes records, unless the example is specifically demonstrating a fixed namespace or set.
4. Register the example in `ExampleRegistry` with tags and an `ExampleFixture`.
5. Add verification in a fixture under `com.aerospike.examples.fixtures`.

Every example registered for CI should have an explicit fixture decision:

- Use a fixture with `setup`, `verify`, and `cleanup` when the example changes server state.
- Use `ExampleFixture.NONE` only when there is no meaningful post-run state to verify.
- Throw `ExampleSkipException` for server capability or configuration gates that should be reported as skipped rather than failed.

## Verification Model

The runner executes each registered example in this order:

1. Fixture setup
2. Example body
3. Fixture verification
4. Fixture cleanup
5. Result reporting

Verification should check state after the example runs. Prefer reusable helpers in `ExampleAssertions` for common checks such as truncating a dataset, counting records, checking that a record exists, and comparing bin values.

## CI

PR CI builds the examples module, runs `all` against the Aerospike server provisioned for integration tests, and writes `examples/target/example-reports/TEST-examples.xml`. The report is uploaded with the other test artifacts so example failures are visible as test failures.
5 changes: 5 additions & 0 deletions examples/run_examples
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,10 @@ if [ -z "$JAR_FILE" ]; then
exit 1
fi

# Run from the examples directory so that examples which load YAML via relative
# paths (src/main/resources/*.yml) resolve their config files regardless of the
# caller's working directory.
cd "$SCRIPT_DIR" || exit 1

# Run Main with all arguments
java -cp "$JAR_FILE" com.aerospike.examples.Main "$@"
Loading
Loading