Skip to content

Commit 2816e6a

Browse files
author
Philip Z
committed
Fail fast on non-contention JDBC Business ID errors
1 parent 7eb2838 commit 2816e6a

2 files changed

Lines changed: 129 additions & 37 deletions

File tree

‎examples/business-id-runtime/src/test/java/io/teaql/examples/businessid/BusinessIdRuntimeExampleTest.java‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,58 @@ public void sqliteAllocatorIsExplicitCrossInstanceAndRestartSafe() throws Except
186186
}
187187
}
188188

189+
@Test
190+
public void sqliteAllocatorReportsMissingSchemaWithoutRetryExhaustion() throws Exception {
191+
Path databasePath = Files.createTempFile("teaql-business-id-missing-schema", ".db");
192+
try (Connection connection = open(databasePath)) {
193+
JdbcBusinessIdAllocator allocator =
194+
new JdbcBusinessIdAllocator(database(connection));
195+
BusinessIdPlan plan = new DailySequenceBusinessIdProfile().plan(
196+
new BusinessIdGenerationRequest(
197+
ORDER_NUMBER, "tenant-a", "commerce_order",
198+
LocalDate.of(2026, 9, 20)));
199+
200+
IllegalStateException failure = Assert.assertThrows(
201+
IllegalStateException.class, () -> allocator.allocate(plan));
202+
Assert.assertTrue(failure.getMessage(),
203+
failure.getMessage().contains("context.ensureSchema()"));
204+
Assert.assertNotNull(failure.getCause());
205+
} finally {
206+
Files.deleteIfExists(databasePath);
207+
}
208+
}
209+
210+
@Test
211+
public void sqliteAllocatorRejectsMalformedSequenceRowWithoutRetryExhaustion()
212+
throws Exception {
213+
Path databasePath = Files.createTempFile("teaql-business-id-malformed", ".db");
214+
try (Connection connection = open(databasePath)) {
215+
JdbcBusinessIdAllocator allocator =
216+
new JdbcBusinessIdAllocator(database(connection));
217+
LocalDate businessDate = LocalDate.of(2026, 9, 20);
218+
BusinessIdPlan plan = new DailySequenceBusinessIdProfile().plan(
219+
new BusinessIdGenerationRequest(
220+
ORDER_NUMBER, "tenant-a", "commerce_order", businessDate));
221+
UserContext context = context(businessDate, allocator);
222+
context.putAttribute(SchemaExecutor.class.getName(), noOpSchemaExecutor());
223+
context.ensureSchema();
224+
try (PreparedStatement insert = connection.prepareStatement(
225+
"INSERT INTO teaql_business_id_space"
226+
+ " (scope_key, current_value, version, updated_at)"
227+
+ " VALUES (?, 'invalid', 1, 0)")) {
228+
insert.setString(1, plan.scope().canonicalKey());
229+
Assert.assertEquals(1, insert.executeUpdate());
230+
}
231+
232+
IllegalStateException failure = Assert.assertThrows(
233+
IllegalStateException.class, () -> allocator.allocate(plan));
234+
Assert.assertTrue(failure.getMessage(),
235+
failure.getMessage().contains("current_value"));
236+
} finally {
237+
Files.deleteIfExists(databasePath);
238+
}
239+
}
240+
189241
@Test
190242
public void sqliteAllocatorRejectsExhaustedAndOverflowedSequencesWithoutMutation()
191243
throws Exception {

‎teaql-business-id-jdbc/src/main/java/io/teaql/businessid/jdbc/JdbcBusinessIdAllocator.java‎

Lines changed: 77 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import java.time.ZoneOffset;
77
import java.util.List;
88
import java.util.Map;
9-
import java.util.concurrent.atomic.AtomicReference;
109

1110
/** Portable optimistic Business ID allocator backed by a TeaQLDatabase. */
1211
public final class JdbcBusinessIdAllocator
@@ -48,47 +47,88 @@ public BusinessIdAllocation allocate(BusinessIdPlan plan) {
4847
.toEpochMilli();
4948
RuntimeException lastConflict = null;
5049
for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
51-
AtomicReference<BusinessIdAllocation> result = new AtomicReference<>();
50+
List<Map<String, Object>> rows;
5251
try {
53-
database.executeInTransaction(() -> {
54-
List<Map<String, Object>> rows = database.query(
55-
"SELECT current_value, version FROM " + table
56-
+ " WHERE scope_key = ?",
57-
new Object[]{scopeKey});
58-
if (rows == null || rows.isEmpty()) {
59-
database.executeUpdate(
60-
"INSERT INTO " + table
61-
+ " (scope_key, current_value, version, updated_at)"
62-
+ " VALUES (?, 1, 1, ?)",
63-
new Object[]{scopeKey, updatedAt});
64-
result.set(new BusinessIdAllocation(plan.scope(), 1));
65-
return;
52+
rows = database.query(
53+
"SELECT current_value, version FROM " + table
54+
+ " WHERE scope_key = ?",
55+
new Object[]{scopeKey});
56+
} catch (RuntimeException failure) {
57+
throw new IllegalStateException(
58+
"Cannot read Business ID table " + table
59+
+ "; verify database access and call context.ensureSchema()",
60+
failure);
61+
}
62+
if (rows == null) {
63+
throw new IllegalStateException(
64+
"Business ID database returned a null result set for " + scopeKey);
65+
}
66+
if (rows.isEmpty()) {
67+
Integer inserted = null;
68+
try {
69+
inserted = database.executeUpdate(
70+
"INSERT INTO " + table
71+
+ " (scope_key, current_value, version, updated_at)"
72+
+ " VALUES (?, 1, 1, ?)",
73+
new Object[]{scopeKey, updatedAt});
74+
} catch (RuntimeException insertionFailure) {
75+
lastConflict = insertionFailure;
76+
// A competing instance may have inserted this key. Do not retry an
77+
// unrelated write failure unless that exact row is now observable.
78+
List<Map<String, Object>> observed;
79+
try {
80+
observed = database.query(
81+
"SELECT current_value, version FROM " + table
82+
+ " WHERE scope_key = ?",
83+
new Object[]{scopeKey});
84+
} catch (RuntimeException readFailure) {
85+
readFailure.addSuppressed(insertionFailure);
86+
throw new IllegalStateException(
87+
"Cannot verify Business ID insert for " + scopeKey,
88+
readFailure);
6689
}
67-
Map<String, Object> row = rows.get(0);
68-
long current = number(row, "current_value");
69-
long version = number(row, "version");
70-
if (current >= plan.maximumSequence()) {
71-
throw new BusinessIdException(
72-
BusinessIdErrorCode.BUSINESS_ID_RANGE_EXHAUSTED,
73-
"Business ID range exhausted for " + scopeKey);
90+
if (observed == null || observed.isEmpty()) {
91+
throw new IllegalStateException(
92+
"Business ID insert failed without a matching row for "
93+
+ scopeKey,
94+
insertionFailure);
7495
}
75-
long next = current + 1;
76-
int updated = database.executeUpdate(
77-
"UPDATE " + table
78-
+ " SET current_value = ?, version = version + 1, updated_at = ?"
79-
+ " WHERE scope_key = ? AND version = ?",
80-
new Object[]{next, updatedAt, scopeKey, version});
81-
if (updated == 1) {
82-
result.set(new BusinessIdAllocation(plan.scope(), next));
96+
}
97+
if (inserted != null) {
98+
if (inserted == 1) {
99+
return new BusinessIdAllocation(plan.scope(), 1);
83100
}
84-
});
85-
if (result.get() != null) {
86-
return result.get();
101+
throw new IllegalStateException(
102+
"Expected one inserted Business ID row for " + scopeKey
103+
+ ", inserted " + inserted);
104+
}
105+
} else {
106+
Map<String, Object> row = rows.get(0);
107+
long current = number(row, "current_value");
108+
long version = number(row, "version");
109+
if (current < 1 || version < 1) {
110+
throw new IllegalStateException(
111+
"Invalid Business ID sequence row for " + scopeKey);
112+
}
113+
if (current >= plan.maximumSequence()) {
114+
throw new BusinessIdException(
115+
BusinessIdErrorCode.BUSINESS_ID_RANGE_EXHAUSTED,
116+
"Business ID range exhausted for " + scopeKey);
117+
}
118+
long next = current + 1;
119+
int updated = database.executeUpdate(
120+
"UPDATE " + table
121+
+ " SET current_value = ?, version = version + 1, updated_at = ?"
122+
+ " WHERE scope_key = ? AND version = ? AND current_value = ?",
123+
new Object[]{next, updatedAt, scopeKey, version, current});
124+
if (updated == 1) {
125+
return new BusinessIdAllocation(plan.scope(), next);
126+
}
127+
if (updated != 0) {
128+
throw new IllegalStateException(
129+
"Expected at most one updated Business ID row for " + scopeKey
130+
+ ", updated " + updated);
87131
}
88-
} catch (BusinessIdException error) {
89-
throw error;
90-
} catch (RuntimeException conflict) {
91-
lastConflict = conflict;
92132
}
93133
java.util.concurrent.locks.LockSupport.parkNanos(1_000_000L);
94134
}

0 commit comments

Comments
 (0)