Skip to content
Open
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/scripts/runtime-matrix.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Discover every stable release line from the existing CI minimum.
const metadataUrl = 'https://api.adoptium.net/v3/info/available_releases';
const compare = (a, b) => a.localeCompare(b, 'en', {numeric: true});

module.exports = async function discover({core, fetch = globalThis.fetch}) {
const response = await fetch(metadataUrl, {
headers: {'User-Agent': 'sailthru-ci-runtime-matrix'},
signal: AbortSignal.timeout(30000)
});
if (!response.ok) throw new Error(`Runtime metadata request failed: ${response.status}`);
const releases = await response.json();
// The feature release is GA; tip_version/most_recent_feature_version may be EA.
const latest = releases.most_recent_feature_release;
if (!Number.isSafeInteger(latest) || latest < 17 || latest > 272) {
throw new Error('Invalid latest stable Java feature release');
}
const versions = Array.from({length: latest - 16}, (_, index) => String(index + 17));

const matrix = [...new Set(versions)].sort(compare);
if (!matrix.includes('17') || matrix.length > 256) {
throw new Error('Runtime matrix is incomplete or exceeds the GitHub Actions limit');
}
core.info(`Testing java release lines: ${matrix.join(', ')}`);
core.setOutput('versions', JSON.stringify(matrix));
};
35 changes: 35 additions & 0 deletions .github/scripts/runtime-matrix.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const {test} = require('node:test');
const assert = require('node:assert/strict');
const discover = require('./runtime-matrix.cjs');

async function resolve(releases) {
let output;
await discover({
core: {info() {}, setOutput(name, value) {
assert.equal(name, 'versions');
output = JSON.parse(value);
}},
fetch: async () => ({ok: true, json: async () => releases})
});
return output;
}

test('includes intermediate and future stable releases, excludes prereleases and duplicates', async () => {
const releases = {most_recent_feature_release: 30, most_recent_feature_version: 31, tip_version: 32};
assert.deepEqual(await resolve(releases), Array.from({length: 14}, (_, index) => String(index + 17)));
});

test('fails rather than quietly running an empty or incomplete matrix', async () => {
await assert.rejects(resolve({}));
await assert.rejects(resolve({most_recent_feature_release: 16}));
await assert.rejects(resolve(null));
});

test('metadata HTTP, JSON and network failures fail discovery without emitting a matrix', async () => {
const core = {info() {}, setOutput() {assert.fail('Must not emit a fallback matrix');}};
await assert.rejects(discover({core, fetch: async () => ({ok: false, status: 503})}), /503/);
await assert.rejects(discover({core, fetch: async () => ({
ok: true, json: async () => {throw new SyntaxError('Invalid JSON');}
})}), /Invalid JSON/);
await assert.rejects(discover({core, fetch: async () => {throw new Error('Network failure');}}), /Network failure/);
});
58 changes: 58 additions & 0 deletions .github/workflows/code-check.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
name: Code Quality Check

on:
push:
branches: [main]
pull_request:
schedule:
# Check runtime compatibility every Monday at 04:27 UTC.
- cron: '27 4 * * 1'
workflow_dispatch:

permissions:
contents: read

jobs:
discover:
name: Discover runtimes
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
versions: ${{ steps.versions.outputs.versions }}
steps:
- uses: actions/checkout@v4
- name: Test discovery and list stable runtimes
id: versions
uses: actions/github-script@v7
with:
script: |
require('node:child_process').execFileSync(process.execPath,
['--test', '.github/scripts/runtime-matrix.test.cjs'], {stdio: 'inherit'});
await require('./.github/scripts/runtime-matrix.cjs')({core});

build:
needs: discover
name: Java ${{ matrix.java }}
runs-on: ubuntu-latest
timeout-minutes: 15

strategy:
fail-fast: false
matrix:
java: ${{ fromJSON(needs.discover.outputs.versions) }}

steps:
- name: Checkout
uses: actions/checkout@v4

- name: Setup Java
uses: actions/setup-java@v5
with:
distribution: temurin
java-version: ${{ matrix.java }}
check-latest: true
cache: maven
overwrite-settings: false

- name: Test and smoke-test the packaged client
run: mvn --batch-mode --no-transfer-progress clean verify
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,20 @@ A simple client library to remotely access the `Sailthru REST API` as per [http:

By default, it will make request in `JSON` format.

Development and compatibility checks
------------------------------------

Use Maven 3.9 and JDK 17+; the library retains its Java 8 compilation target.
CI discovers every Java feature version from 17 through the latest stable Temurin
JDK on PRs, pushes to `main`, weekly, and manual runs.

```bash
mvn --batch-mode --no-transfer-progress clean verify
```

This runs unit tests and tests the built JAR through a separate consumer using a
local server and dummy credentials. It does not publish. Use `mvn test` for unit tests only.

Examples
--------

Expand Down
39 changes: 38 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@
<maven-javadoc-plugin.version>3.12.0</maven-javadoc-plugin.version>
<maven-source-plugin.version>3.3.1</maven-source-plugin.version>
<maven-gpg-plugin.version>3.2.8</maven-gpg-plugin.version>
<maven-invoker-plugin.version>3.10.1</maven-invoker-plugin.version>
<maven-surefire-plugin.version>3.5.4</maven-surefire-plugin.version>
</properties>

<dependencies>
Expand Down Expand Up @@ -204,6 +206,41 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<failIfNoTests>true</failIfNoTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-invoker-plugin</artifactId>
<version>${maven-invoker-plugin.version}</version>
<configuration>
<projectsDirectory>src/it</projectsDirectory>
<cloneProjectsTo>${project.build.directory}/package-smoke</cloneProjectsTo>
<localRepositoryPath>${project.build.directory}/package-smoke-repository</localRepositoryPath>
<javaHome>${java.home}</javaHome>
<goals>
<goal>verify</goal>
</goals>
<streamLogs>true</streamLogs>
<timeoutInSeconds>300</timeoutInSeconds>
</configuration>
<executions>
<execution>
<id>smoke-test-packaged-client</id>
<!-- Verify the actual JAR and consumer dependencies before deploy. -->
<phase>verify</phase>
<goals>
<goal>install</goal>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
Expand Down Expand Up @@ -293,4 +330,4 @@
</build>
</profile>
</profiles>
</project>
</project>
55 changes: 55 additions & 0 deletions src/it/package-smoke/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sailthru.smoke</groupId>
<artifactId>packaged-client-consumer</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>17</maven.compiler.release>
</properties>

<!-- The Invoker filters these coordinates and installs the freshly built JAR/POM. -->
<dependencies>
<dependency>
<groupId>@project.groupId@</groupId>
<artifactId>@project.artifactId@</artifactId>
<version>@project.version@</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.6.4</version>
<executions>
<execution>
<id>exercise-installed-client</id>
<phase>verify</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>${java.home}/bin/java</executable>
<arguments>
<argument>-classpath</argument>
<classpath/>
<argument>PackageSmoke</argument>
</arguments>
<classpathScope>runtime</classpathScope>
<timeout>30000</timeout>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
90 changes: 90 additions & 0 deletions src/it/package-smoke/src/main/java/PackageSmoke.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import com.google.gson.Gson;
import com.sailthru.client.ApiAction;
import com.sailthru.client.SailthruClient;
import com.sailthru.client.handler.response.JsonResponse;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/** A consumer of the packaged JAR, with no library source classes or test dependencies. */
public class PackageSmoke {
public static void main(String[] args) throws Exception {
String location = SailthruClient.class.getProtectionDomain().getCodeSource().getLocation().getPath();
check(location.endsWith(".jar"), "The client must load from the installed JAR: " + location);

AtomicReference<Throwable> serverFailure = new AtomicReference<>();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/user", exchange -> {
try {
check("POST".equals(exchange.getRequestMethod()), "Expected a POST request");
check("/user".equals(exchange.getRequestURI().getPath()), "Expected the /user endpoint");
Map<String, String> params = formParameters(exchange);
check("smoke-key".equals(params.get("api_key")), "API key was not preserved");
check("json".equals(params.get("format")), "Expected the JSON response format");
Map<?, ?> payload = new Gson().fromJson(params.get("json"), Map.class);
check("smoke@example.com".equals(payload.get("id")), "User payload was not preserved");
String signature = params.get("sig");
check(signature != null && signature.matches("[a-f0-9]{32}"), "Missing or malformed signature");
reply(exchange, 200, "{\"ok\":true}");
} catch (Exception | AssertionError failure) {
serverFailure.set(failure);
reply(exchange, 500, "{\"error\":\"smoke request validation failed\"}");
} finally {
exchange.close();
}
});
server.start();

SailthruClient client = null;
try {
String apiUrl = "http://127.0.0.1:" + server.getAddress().getPort();
client = new SailthruClient("smoke-key", "smoke-secret", apiUrl);
Map<String, Object> user = new HashMap<>();
user.put("id", "smoke@example.com");
JsonResponse result = client.apiPost(ApiAction.user, user);

if (serverFailure.get() != null) {
throw new AssertionError("Local server rejected the client request", serverFailure.get());
}
check(result.isOK(), "Client reported an unsuccessful response");
check(Boolean.TRUE.equals(result.getResponse().get("ok")), "Client did not parse the response");
System.out.println("Packaged client loaded and completed a local API request.");
} finally {
if (client != null) {
client.getSailthruHttpClient().getConnectionManager().shutdown();
}
server.stop(0);
}
}

private static Map<String, String> formParameters(HttpExchange exchange) throws IOException {
String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
Map<String, String> params = new HashMap<>();
for (String field : body.split("&")) {
String[] pair = field.split("=", 2);
check(pair.length == 2, "Malformed form field");
params.put(URLDecoder.decode(pair[0], StandardCharsets.UTF_8),
URLDecoder.decode(pair[1], StandardCharsets.UTF_8));
}
return params;
}

private static void reply(HttpExchange exchange, int status, String json) throws IOException {
byte[] body = json.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(status, body.length);
exchange.getResponseBody().write(body);
}

private static void check(boolean condition, String message) {
if (!condition) {
throw new AssertionError(message);
}
}
}
Loading