Skip to content

Commit dc5a452

Browse files
author
Philip Z
committed
fix: make legacy business ID allocation explicit and collision-safe
1 parent bf7b93d commit dc5a452

9 files changed

Lines changed: 387 additions & 84 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,10 @@ dialect for the target database.
164164
| `teaql-utils`, `teaql-utils-json` | Framework-neutral utility abstractions |
165165
| `teaql-utils-reflection`, `teaql-utils-spring` | Optional reflection- and Spring-backed utility implementations |
166166

167+
For business IDs, use the context-owned `BusinessIdService` and explicit
168+
`context.ensureSchema()` lifecycle. The [focused runtime example](examples/business-id-runtime/README.md)
169+
documents the preferred contract and the deprecated legacy boundary.
170+
167171
## Framework Notes
168172

169173
### Spring Boot and SQLite

‎examples/business-id-runtime/README.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,26 @@ daily sequence, controlled Context date, root scoping, Mutation Ledger retry
66
stability, explicit SQLite schema setup, cross-instance allocation, restart,
77
strong `OrderNumber` parsing, and immutable established aggregates.
88

9+
The preferred contract is `context.businessIds().ensure(context, definition,
10+
domainRootKey, aggregateType, slot)`. Install the allocator with
11+
`TeaQLRuntime.builder().businessIdInfrastructure(allocator)`, then explicitly
12+
call `context.ensureSchema()` before allocation. The business date comes from
13+
the context's `BusinessClock`; tests can replace that clock. The JDBC allocator
14+
uses root/aggregate/namespace/date scoping, optimistic allocation, bounded
15+
retry, and a range error when the configured digits are exhausted.
16+
17+
`BusinessIdGenerator`, `UserContext.generateBusinessId(...)`,
18+
`InMemoryBusinessIdGenerator`, and `JdbcBusinessIdGenerator` are deprecated
19+
compatibility APIs. They retain the old `PREFIXyyyyMMddNNNN` format and separate
20+
sequence namespace; do not mix their sequence state with `BusinessIdService`.
21+
The legacy JDBC implementation no longer creates a table in its constructor or
22+
during allocation. If an existing integration must keep it, register it as a
23+
`BusinessIdSchemaContributor` on the context and call `context.ensureSchema()`
24+
explicitly. Both legacy implementations now use `context.businessDate()` and
25+
reject an exhausted digit range. Repository source and generated-template
26+
search found only the public API and tests using the legacy path; external
27+
consumers have not been inventoried and must be treated as unknown.
28+
929
```bash
1030
mvn -pl examples/business-id-runtime -am \
1131
-Dtest=BusinessIdRuntimeExampleTest \

‎teaql-business-id-jdbc/pom.xml‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@
3131
<artifactId>teaql-sql-portable</artifactId>
3232
</dependency>
3333
<!-- Test dependencies -->
34+
<dependency>
35+
<groupId>io.teaql</groupId>
36+
<artifactId>teaql-runtime</artifactId>
37+
<scope>test</scope>
38+
</dependency>
3439
<dependency>
3540
<groupId>io.teaql</groupId>
3641
<artifactId>teaql-sqlite</artifactId>
@@ -50,4 +55,16 @@
5055
</dependency>
5156
</dependencies>
5257

58+
<build>
59+
<plugins>
60+
<plugin>
61+
<groupId>org.apache.maven.plugins</groupId>
62+
<artifactId>maven-surefire-plugin</artifactId>
63+
<configuration>
64+
<argLine>--add-reads io.teaql.businessid.jdbc=io.teaql.runtime</argLine>
65+
</configuration>
66+
</plugin>
67+
</plugins>
68+
</build>
69+
5370
</project>

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

Lines changed: 99 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,27 @@
44
import io.teaql.core.Entity;
55
import io.teaql.core.TeaQLRuntimeException;
66
import io.teaql.core.UserContext;
7+
import io.teaql.core.businessid.BusinessIdErrorCode;
8+
import io.teaql.core.businessid.BusinessIdException;
9+
import io.teaql.core.businessid.BusinessIdSchemaContributor;
710
import io.teaql.core.meta.EntityDescriptor;
811
import io.teaql.core.meta.PropertyDescriptor;
912
import io.teaql.core.sql.portable.TeaQLDatabase;
1013
import io.teaql.core.utils.StrUtil;
1114

12-
import java.time.LocalDate;
1315
import java.time.format.DateTimeFormatter;
1416
import java.util.List;
1517
import java.util.Map;
16-
import java.util.concurrent.atomic.AtomicLong;
17-
import java.util.logging.Level;
18-
import java.util.logging.Logger;
1918

2019
/**
21-
* JDBC implementation of BusinessIdGenerator.
22-
* Uses a dedicated sequence table {@code teaql_biz_sequence} to generate unique IDs.
20+
* Legacy JDBC business ID format, retained for existing callers. Prefer the
21+
* context-owned BusinessIdService and JdbcBusinessIdAllocator for new models.
22+
* Schema creation is explicit through context.ensureSchema().
2323
*/
24-
public class JdbcBusinessIdGenerator implements BusinessIdGenerator {
24+
@Deprecated
25+
public class JdbcBusinessIdGenerator implements BusinessIdGenerator, BusinessIdSchemaContributor {
2526

26-
private static final Logger LOG = Logger.getLogger(JdbcBusinessIdGenerator.class.getName());
27+
private static final int MAX_ATTEMPTS = 100;
2728

2829
private final TeaQLDatabase database;
2930
private final String sequenceTable;
@@ -33,20 +34,19 @@ public JdbcBusinessIdGenerator(TeaQLDatabase database) {
3334
}
3435

3536
public JdbcBusinessIdGenerator(TeaQLDatabase database, String sequenceTable) {
36-
this.database = database;
37+
this.database = java.util.Objects.requireNonNull(database, "database");
38+
if (sequenceTable == null || !sequenceTable.matches("[A-Za-z][A-Za-z0-9_]*")) {
39+
throw new IllegalArgumentException("Invalid Business ID table name: " + sequenceTable);
40+
}
3741
this.sequenceTable = sequenceTable;
38-
ensureSequenceTable();
3942
}
4043

41-
private void ensureSequenceTable() {
44+
@Override
45+
public void ensureSchema(UserContext context) {
4246
String ddl = "CREATE TABLE IF NOT EXISTS " + sequenceTable + " ("
4347
+ "sequence_key VARCHAR(100) PRIMARY KEY, "
4448
+ "current_value BIGINT NOT NULL)";
45-
try {
46-
database.execute(ddl);
47-
} catch (Exception e) {
48-
LOG.log(Level.FINE, "teaql_biz_sequence table may already exist: " + e.getMessage());
49-
}
49+
database.execute(java.util.Objects.requireNonNull(context, "context"), ddl);
5050
}
5151

5252
@Override
@@ -60,67 +60,101 @@ public String generateBusinessId(UserContext context, Entity entity, EntityDescr
6060
String prefix = parts[0].trim();
6161
int length = parts.length > 1 ? Integer.parseInt(parts[1].trim()) : 6;
6262

63-
String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
63+
String dateStr = java.util.Objects.requireNonNull(context, "context")
64+
.businessDate().format(DateTimeFormatter.BASIC_ISO_DATE);
6465
String sequenceKey = prefix + ":" + dateStr;
6566

66-
long seq = nextSequence(sequenceKey);
67+
if (length < 1 || length > 18) {
68+
throw new IllegalArgumentException("Legacy Business ID digits must be between 1 and 18");
69+
}
70+
long maximum = 1;
71+
for (int i = 0; i < length; i++) maximum = Math.multiplyExact(maximum, 10);
72+
long seq = nextSequence(context, sequenceKey, maximum - 1);
6773

68-
return String.format("%s%s%0" + length + "d", prefix, dateStr, seq);
74+
return String.format(java.util.Locale.ROOT,
75+
"%s%s%0" + length + "d", prefix, dateStr, seq);
6976
}
7077

71-
private long nextSequence(String sequenceKey) {
72-
AtomicLong result = new AtomicLong(-1);
73-
74-
database.executeInTransaction(() -> {
75-
Number dbCurrent = null;
78+
private long nextSequence(UserContext context, String sequenceKey, long maximum) {
79+
RuntimeException lastConflict = null;
80+
for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
81+
List<Map<String, Object>> rows;
7682
try {
77-
List<Map<String, Object>> rows = database.query(
83+
rows = database.query(context,
7884
"SELECT current_value FROM " + sequenceTable + " WHERE sequence_key = ?",
79-
new Object[]{sequenceKey}
80-
);
81-
if (rows != null && !rows.isEmpty()) {
82-
dbCurrent = (Number) rows.get(0).get("current_value");
83-
}
84-
} catch (Exception e) {
85-
// Table might not exist or other error, fallback will attempt to fix
86-
ensureSequenceTable();
85+
new Object[]{sequenceKey});
86+
} catch (RuntimeException failure) {
87+
throw new TeaQLRuntimeException(
88+
"Cannot read legacy Business ID table " + sequenceTable
89+
+ "; call context.ensureSchema() before generating IDs",
90+
failure);
8791
}
88-
89-
if (dbCurrent == null) {
92+
if (rows == null) {
93+
throw new TeaQLRuntimeException("Legacy Business ID query returned no result set");
94+
}
95+
if (rows.isEmpty()) {
96+
RuntimeException conflict = null;
9097
try {
91-
database.executeUpdate(
92-
"INSERT INTO " + sequenceTable + " (sequence_key, current_value) VALUES (?, 1)",
93-
new Object[]{sequenceKey}
94-
);
95-
result.set(1);
96-
} catch (Exception e) {
97-
// Concurrent insert collision, retry as update
98-
int updated = database.executeUpdate(
99-
"UPDATE " + sequenceTable + " SET current_value = current_value + 1 WHERE sequence_key = ?",
100-
new Object[]{sequenceKey}
101-
);
102-
if (updated == 0) {
103-
throw new TeaQLRuntimeException("Failed to initialize or update sequence: " + sequenceKey, e);
98+
int inserted = database.executeUpdate(context,
99+
"INSERT INTO " + sequenceTable
100+
+ " (sequence_key, current_value) VALUES (?, 1)",
101+
new Object[]{sequenceKey});
102+
if (inserted == 1) return 1;
103+
conflict = new TeaQLRuntimeException(
104+
"Expected one inserted Business ID row, got " + inserted);
105+
} catch (RuntimeException insertionFailure) {
106+
conflict = insertionFailure;
107+
}
108+
lastConflict = conflict;
109+
// A collision is retried only after a fresh exact-key read proves a row exists.
110+
try {
111+
List<Map<String, Object>> observed = database.query(context,
112+
"SELECT current_value FROM " + sequenceTable
113+
+ " WHERE sequence_key = ?",
114+
new Object[]{sequenceKey});
115+
if (observed == null || observed.isEmpty()) {
116+
throw new TeaQLRuntimeException(
117+
"Business ID insert failed without a matching row for "
118+
+ sequenceKey,
119+
conflict);
104120
}
105-
List<Map<String, Object>> rows = database.query(
106-
"SELECT current_value FROM " + sequenceTable + " WHERE sequence_key = ?",
107-
new Object[]{sequenceKey}
108-
);
109-
result.set(((Number) rows.get(0).get("current_value")).longValue());
121+
} catch (TeaQLRuntimeException failure) {
122+
throw failure;
123+
} catch (RuntimeException readFailure) {
124+
readFailure.addSuppressed(conflict);
125+
throw new TeaQLRuntimeException(
126+
"Cannot verify Business ID insert for " + sequenceKey,
127+
readFailure);
128+
}
129+
} else {
130+
Object value = rows.get(0).get("current_value");
131+
if (value == null) value = rows.get(0).get("CURRENT_VALUE");
132+
if (!(value instanceof Number)) {
133+
throw new TeaQLRuntimeException(
134+
"Invalid legacy Business ID current_value for " + sequenceKey);
135+
}
136+
long current = ((Number) value).longValue();
137+
if (current >= maximum) {
138+
throw new BusinessIdException(
139+
BusinessIdErrorCode.BUSINESS_ID_RANGE_EXHAUSTED,
140+
"Business ID range exhausted for " + sequenceKey);
141+
}
142+
int updated = database.executeUpdate(context,
143+
"UPDATE " + sequenceTable
144+
+ " SET current_value = ?"
145+
+ " WHERE sequence_key = ? AND current_value = ?",
146+
new Object[]{current + 1, sequenceKey, current});
147+
if (updated == 1) return current + 1;
148+
if (updated != 0) {
149+
throw new TeaQLRuntimeException(
150+
"Expected one updated Business ID row, got " + updated);
110151
}
111-
return;
112152
}
113-
database.executeUpdate(
114-
"UPDATE " + sequenceTable + " SET current_value = current_value + 1 WHERE sequence_key = ?",
115-
new Object[]{sequenceKey}
116-
);
117-
result.set(dbCurrent.longValue() + 1);
118-
});
119-
120-
if (result.get() == -1) {
121-
throw new TeaQLRuntimeException("Failed to read sequence value for key: " + sequenceKey);
153+
java.util.concurrent.locks.LockSupport.parkNanos(1_000_000L);
122154
}
123-
124-
return result.get();
155+
throw new BusinessIdException(
156+
BusinessIdErrorCode.BUSINESS_ID_ALLOCATION_RETRY_EXHAUSTED,
157+
"Legacy Business ID allocation did not converge for " + sequenceKey,
158+
lastConflict);
125159
}
126160
}

0 commit comments

Comments
 (0)