S++Core systems, human-reviewable
SDK DOCUMENTATION ยท 1.0-SNAPSHOTStart the tutorial

BasicPersistenceTest.java

sdk-tools/samples/custom-services/src/test/java/example/technical/BasicPersistenceTest.java

1package example.technical;23import com.fasterxml.jackson.databind.JsonNode;4import com.fasterxml.jackson.databind.ObjectMapper;5import com.servpp.service.jdbc.DriverManagerJdbcDataSource;6import com.servpp.service.runtime.ExampleServiceBarrier;7import com.servpp.service.runtime.GeneratedApplicationDeployment;8import com.servpp.service.runtime.LocalGeneratedServiceRuntime;9import com.servpp.service.server.DefaultServiceContainer;10import java.util.LinkedHashMap;11import java.util.Map;12import java.util.UUID;13import java.util.concurrent.Executors;14import java.util.concurrent.TimeUnit;15import org.junit.Test;16import static org.junit.Assert.*;1718/** Only input, generated-service calls and assertions; business updates remain in ledger.spp. */19public class BasicPersistenceTest {20    @Test public void generatedFullUpdatePersistsNullWithoutOfficialTracking() throws Exception {21        try (var fixture = new Fixture()) {22            fixture.create();23            var revision = new LinkedHashMap<String,Object>();24            revision.put("note", null);25            revision.put("amount", 14);26            fixture.call("reviseRecord", Map.of("entry", Map.of("code", "A"), "revision", revision));27            var entry = fixture.read();28            assertEquals(14, entry.path("amount").asInt());29            assertTrue(entry.path("note").isNull());30            try (var connection = fixture.dataSource.getConnection();31                 var statement = connection.createStatement();32                 var rows = statement.executeQuery("SELECT note, amount FROM LEDGER_ENTRIES WHERE code = 'A'")) {33                assertTrue(rows.next());34                assertNull(rows.getString(1));35                assertEquals(14, rows.getInt(2));36                assertFalse(rows.next());37            }38            assertFalse(com.servpp.service.idempotency.BusinessIdempotencyManager.isAvailable());39            assertThrows(ClassNotFoundException.class,40                    () -> Class.forName("com.servpp.service.runtime.OfficialPropertyChanges"));41        }42    }4344    @Test public void generatedScenarioReadsUsingAnotherParticipantWithoutCalculation() throws Exception {45        try (var fixture = new Fixture()) {46            fixture.create();47            fixture.call("createRecord", Map.of("entry", Map.of("code", "B"),48                    "revision", Map.of("note", "other row", "amount", 19)));49            var entry = fixture.call("readSelectedRecord",50                    Map.of("entry", Map.of("code", "B"), "lookup", Map.of("entryCode", "A"))).path("entry");51            assertEquals("A", entry.path("code").asText());52            assertEquals("original", entry.path("note").asText());53            assertEquals(7, entry.path("amount").asInt());54            var missing = fixture.call("readSelectedRecord",55                    Map.of("entry", Map.of("code", "B"), "lookup", Map.of("entryCode", "missing"))).path("entry");56            assertEquals("missing", missing.path("code").asText());57        }58    }5960    @Test public void generatedReadonlyInquiryProjectsStoredFactsWithoutWriting() throws Exception {61        try (var fixture = new Fixture()) {62            fixture.create();63            var response = fixture.call("previewRecord", Map.of("entry", Map.of("code", "A"),64                    "facts", Map.of("amount", 0)));65            assertEquals("original", response.path("entry").path("note").asText());66            assertEquals(14, response.path("facts").path("amount").asInt());67            try (var connection = fixture.dataSource.getConnection();68                 var statement = connection.createStatement();69                 var rows = statement.executeQuery("SELECT code, note, amount FROM LEDGER_ENTRIES")) {70                assertTrue(rows.next());71                assertEquals("A", rows.getString("code"));72                assertEquals("original", rows.getString("note"));73                assertEquals(7, rows.getInt("amount"));74                assertFalse(rows.next());75            }76        }77    }7879    @Test public void concurrentGeneratedUpdatesRejectOneStaleBaseline() throws Exception {80        try (var fixture = new Fixture()) {81            fixture.create();82            var pool = Executors.newFixedThreadPool(2);83            try (var barrier = ExampleServiceBarrier.activate("ledger.applyRevision", 2)) {84                var first = pool.submit(() -> fixture.revise(21));85                var second = pool.submit(() -> fixture.revise(35));86                String a = first.get(40, TimeUnit.SECONDS);87                String b = second.get(40, TimeUnit.SECONDS);88                barrier.verifyReached();89                assertEquals(java.util.Set.of("OK", "PERSISTENCE_VERSION_CONFLICT"), java.util.Set.of(a, b));90                var stored = fixture.read();91                int winner = a.equals("OK") ? 21 : 35;92                assertEquals(winner, stored.path("amount").asInt());93                assertEquals("revision-" + winner, stored.path("note").asText());94            } finally {95                pool.shutdownNow();96                assertTrue(pool.awaitTermination(10, TimeUnit.SECONDS));97            }98        }99    }100101    private static final class Fixture implements AutoCloseable {102        final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();103        final DriverManagerJdbcDataSource dataSource;104        final LocalGeneratedServiceRuntime runtime;105        final String previousUrl = System.getProperty("spp.basic-ledger.datasource-url");106        Fixture() {107            String url = "jdbc:h2:mem:basic_ledger_" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1";108            System.setProperty("spp.basic-ledger.datasource-url", url);109            dataSource = new DriverManagerJdbcDataSource("org.h2.Driver", url, null, null);110            DefaultServiceContainer.getInstance().clear();111            runtime = LocalGeneratedServiceRuntime.jsonSnapshots(dataSource, mapper, ignored -> null);112            runtime.enableExampleFaults();113            GeneratedApplicationDeployment.install(runtime, "basicLedger");114        }115        JsonNode call(String service, Map<String,?> input) throws Exception {116            var type = Class.forName("example.generated.ledger.model." + Character.toUpperCase(service.charAt(0))117                    + service.substring(1) + "Request");118            Object request = mapper.convertValue(input, type);119            runtime.executeGeneratedService("ledger." + service, request);120            return mapper.valueToTree(request);121        }122        JsonNode read() throws Exception {123            return call("readRecord", Map.of("entry", Map.of("code", "A"))).path("entry");124        }125        void create() throws Exception {126            call("createRecord", Map.of("entry", Map.of("code", "A"),127                    "revision", Map.of("note", "original", "amount", 7)));128        }129        String revise(int amount) throws Exception {130            try {131                call("reviseRecord", Map.of("entry", Map.of("code", "A"),132                        "revision", Map.of("note", "revision-" + amount, "amount", amount)));133                return "OK";134            } catch (IllegalStateException failure) {135                if (!"PERSISTENCE_VERSION_CONFLICT".equals(failure.getMessage())) throw failure;136                return failure.getMessage();137            }138        }139        @Override public void close() {140            DefaultServiceContainer.getInstance().clear();141            CallCounter.reset();142            if (previousUrl == null) System.clearProperty("spp.basic-ledger.datasource-url");143            else System.setProperty("spp.basic-ledger.datasource-url", previousUrl);144        }145    }146}