diff --git a/.github/scripts/runtime-matrix.cjs b/.github/scripts/runtime-matrix.cjs new file mode 100644 index 0000000..52321b9 --- /dev/null +++ b/.github/scripts/runtime-matrix.cjs @@ -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)); +}; diff --git a/.github/scripts/runtime-matrix.test.cjs b/.github/scripts/runtime-matrix.test.cjs new file mode 100644 index 0000000..94a7239 --- /dev/null +++ b/.github/scripts/runtime-matrix.test.cjs @@ -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/); +}); diff --git a/.github/workflows/code-check.yml b/.github/workflows/code-check.yml new file mode 100644 index 0000000..36c390f --- /dev/null +++ b/.github/workflows/code-check.yml @@ -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 diff --git a/README.md b/README.md index f094c59..969856e 100644 --- a/README.md +++ b/README.md @@ -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 -------- diff --git a/pom.xml b/pom.xml index 9d47b99..4acb98a 100644 --- a/pom.xml +++ b/pom.xml @@ -80,6 +80,8 @@ 3.12.0 3.3.1 3.2.8 + 3.10.1 + 3.5.4 @@ -204,6 +206,41 @@ + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + true + + + + org.apache.maven.plugins + maven-invoker-plugin + ${maven-invoker-plugin.version} + + src/it + ${project.build.directory}/package-smoke + ${project.build.directory}/package-smoke-repository + ${java.home} + + verify + + true + 300 + + + + smoke-test-packaged-client + + verify + + install + run + + + + org.apache.maven.plugins maven-release-plugin @@ -293,4 +330,4 @@ - \ No newline at end of file + diff --git a/src/it/package-smoke/pom.xml b/src/it/package-smoke/pom.xml new file mode 100644 index 0000000..8d14933 --- /dev/null +++ b/src/it/package-smoke/pom.xml @@ -0,0 +1,55 @@ + + 4.0.0 + com.sailthru.smoke + packaged-client-consumer + 1.0-SNAPSHOT + + + UTF-8 + 17 + + + + + + @project.groupId@ + @project.artifactId@ + @project.version@ + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.1 + + + org.codehaus.mojo + exec-maven-plugin + 3.6.4 + + + exercise-installed-client + verify + + exec + + + ${java.home}/bin/java + + -classpath + + PackageSmoke + + runtime + 30000 + + + + + + + diff --git a/src/it/package-smoke/src/main/java/PackageSmoke.java b/src/it/package-smoke/src/main/java/PackageSmoke.java new file mode 100644 index 0000000..deb16a4 --- /dev/null +++ b/src/it/package-smoke/src/main/java/PackageSmoke.java @@ -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 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 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 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 formParameters(HttpExchange exchange) throws IOException { + String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); + Map 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); + } + } +}