From dc5a4527e3fbec8bd11b152b7d23acfe292eb98b Mon Sep 17 00:00:00 2001 From: Philip Z Date: Wed, 23 Sep 2026 12:46:20 +0800 Subject: [PATCH] fix: make legacy business ID allocation explicit and collision-safe --- README.md | 4 + examples/business-id-runtime/README.md | 20 ++ teaql-business-id-jdbc/pom.xml | 17 ++ .../jdbc/JdbcBusinessIdGenerator.java | 164 +++++++++------- .../jdbc/JdbcBusinessIdGeneratorTest.java | 182 +++++++++++++++++- .../io/teaql/core/BusinessIdGenerator.java | 6 +- .../main/java/io/teaql/core/UserContext.java | 4 +- .../runtime/InMemoryBusinessIdGenerator.java | 30 ++- .../InMemoryBusinessIdGeneratorTest.java | 44 ++++- 9 files changed, 387 insertions(+), 84 deletions(-) diff --git a/README.md b/README.md index fd9b12028..55846ce82 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,10 @@ dialect for the target database. | `teaql-utils`, `teaql-utils-json` | Framework-neutral utility abstractions | | `teaql-utils-reflection`, `teaql-utils-spring` | Optional reflection- and Spring-backed utility implementations | +For business IDs, use the context-owned `BusinessIdService` and explicit +`context.ensureSchema()` lifecycle. The [focused runtime example](examples/business-id-runtime/README.md) +documents the preferred contract and the deprecated legacy boundary. + ## Framework Notes ### Spring Boot and SQLite diff --git a/examples/business-id-runtime/README.md b/examples/business-id-runtime/README.md index 0a95d559f..78eb2d4c8 100644 --- a/examples/business-id-runtime/README.md +++ b/examples/business-id-runtime/README.md @@ -6,6 +6,26 @@ daily sequence, controlled Context date, root scoping, Mutation Ledger retry stability, explicit SQLite schema setup, cross-instance allocation, restart, strong `OrderNumber` parsing, and immutable established aggregates. +The preferred contract is `context.businessIds().ensure(context, definition, +domainRootKey, aggregateType, slot)`. Install the allocator with +`TeaQLRuntime.builder().businessIdInfrastructure(allocator)`, then explicitly +call `context.ensureSchema()` before allocation. The business date comes from +the context's `BusinessClock`; tests can replace that clock. The JDBC allocator +uses root/aggregate/namespace/date scoping, optimistic allocation, bounded +retry, and a range error when the configured digits are exhausted. + +`BusinessIdGenerator`, `UserContext.generateBusinessId(...)`, +`InMemoryBusinessIdGenerator`, and `JdbcBusinessIdGenerator` are deprecated +compatibility APIs. They retain the old `PREFIXyyyyMMddNNNN` format and separate +sequence namespace; do not mix their sequence state with `BusinessIdService`. +The legacy JDBC implementation no longer creates a table in its constructor or +during allocation. If an existing integration must keep it, register it as a +`BusinessIdSchemaContributor` on the context and call `context.ensureSchema()` +explicitly. Both legacy implementations now use `context.businessDate()` and +reject an exhausted digit range. Repository source and generated-template +search found only the public API and tests using the legacy path; external +consumers have not been inventoried and must be treated as unknown. + ```bash mvn -pl examples/business-id-runtime -am \ -Dtest=BusinessIdRuntimeExampleTest \ diff --git a/teaql-business-id-jdbc/pom.xml b/teaql-business-id-jdbc/pom.xml index ab12a1352..211605ce1 100644 --- a/teaql-business-id-jdbc/pom.xml +++ b/teaql-business-id-jdbc/pom.xml @@ -31,6 +31,11 @@ teaql-sql-portable + + io.teaql + teaql-runtime + test + io.teaql teaql-sqlite @@ -50,4 +55,16 @@ + + + + org.apache.maven.plugins + maven-surefire-plugin + + --add-reads io.teaql.businessid.jdbc=io.teaql.runtime + + + + + diff --git a/teaql-business-id-jdbc/src/main/java/io/teaql/businessid/jdbc/JdbcBusinessIdGenerator.java b/teaql-business-id-jdbc/src/main/java/io/teaql/businessid/jdbc/JdbcBusinessIdGenerator.java index 843f321cf..ccf37d6ae 100644 --- a/teaql-business-id-jdbc/src/main/java/io/teaql/businessid/jdbc/JdbcBusinessIdGenerator.java +++ b/teaql-business-id-jdbc/src/main/java/io/teaql/businessid/jdbc/JdbcBusinessIdGenerator.java @@ -4,26 +4,27 @@ import io.teaql.core.Entity; import io.teaql.core.TeaQLRuntimeException; import io.teaql.core.UserContext; +import io.teaql.core.businessid.BusinessIdErrorCode; +import io.teaql.core.businessid.BusinessIdException; +import io.teaql.core.businessid.BusinessIdSchemaContributor; import io.teaql.core.meta.EntityDescriptor; import io.teaql.core.meta.PropertyDescriptor; import io.teaql.core.sql.portable.TeaQLDatabase; import io.teaql.core.utils.StrUtil; -import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; -import java.util.logging.Level; -import java.util.logging.Logger; /** - * JDBC implementation of BusinessIdGenerator. - * Uses a dedicated sequence table {@code teaql_biz_sequence} to generate unique IDs. + * Legacy JDBC business ID format, retained for existing callers. Prefer the + * context-owned BusinessIdService and JdbcBusinessIdAllocator for new models. + * Schema creation is explicit through context.ensureSchema(). */ -public class JdbcBusinessIdGenerator implements BusinessIdGenerator { +@Deprecated +public class JdbcBusinessIdGenerator implements BusinessIdGenerator, BusinessIdSchemaContributor { - private static final Logger LOG = Logger.getLogger(JdbcBusinessIdGenerator.class.getName()); + private static final int MAX_ATTEMPTS = 100; private final TeaQLDatabase database; private final String sequenceTable; @@ -33,20 +34,19 @@ public JdbcBusinessIdGenerator(TeaQLDatabase database) { } public JdbcBusinessIdGenerator(TeaQLDatabase database, String sequenceTable) { - this.database = database; + this.database = java.util.Objects.requireNonNull(database, "database"); + if (sequenceTable == null || !sequenceTable.matches("[A-Za-z][A-Za-z0-9_]*")) { + throw new IllegalArgumentException("Invalid Business ID table name: " + sequenceTable); + } this.sequenceTable = sequenceTable; - ensureSequenceTable(); } - private void ensureSequenceTable() { + @Override + public void ensureSchema(UserContext context) { String ddl = "CREATE TABLE IF NOT EXISTS " + sequenceTable + " (" + "sequence_key VARCHAR(100) PRIMARY KEY, " + "current_value BIGINT NOT NULL)"; - try { - database.execute(ddl); - } catch (Exception e) { - LOG.log(Level.FINE, "teaql_biz_sequence table may already exist: " + e.getMessage()); - } + database.execute(java.util.Objects.requireNonNull(context, "context"), ddl); } @Override @@ -60,67 +60,101 @@ public String generateBusinessId(UserContext context, Entity entity, EntityDescr String prefix = parts[0].trim(); int length = parts.length > 1 ? Integer.parseInt(parts[1].trim()) : 6; - String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); + String dateStr = java.util.Objects.requireNonNull(context, "context") + .businessDate().format(DateTimeFormatter.BASIC_ISO_DATE); String sequenceKey = prefix + ":" + dateStr; - long seq = nextSequence(sequenceKey); + if (length < 1 || length > 18) { + throw new IllegalArgumentException("Legacy Business ID digits must be between 1 and 18"); + } + long maximum = 1; + for (int i = 0; i < length; i++) maximum = Math.multiplyExact(maximum, 10); + long seq = nextSequence(context, sequenceKey, maximum - 1); - return String.format("%s%s%0" + length + "d", prefix, dateStr, seq); + return String.format(java.util.Locale.ROOT, + "%s%s%0" + length + "d", prefix, dateStr, seq); } - private long nextSequence(String sequenceKey) { - AtomicLong result = new AtomicLong(-1); - - database.executeInTransaction(() -> { - Number dbCurrent = null; + private long nextSequence(UserContext context, String sequenceKey, long maximum) { + RuntimeException lastConflict = null; + for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) { + List> rows; try { - List> rows = database.query( + rows = database.query(context, "SELECT current_value FROM " + sequenceTable + " WHERE sequence_key = ?", - new Object[]{sequenceKey} - ); - if (rows != null && !rows.isEmpty()) { - dbCurrent = (Number) rows.get(0).get("current_value"); - } - } catch (Exception e) { - // Table might not exist or other error, fallback will attempt to fix - ensureSequenceTable(); + new Object[]{sequenceKey}); + } catch (RuntimeException failure) { + throw new TeaQLRuntimeException( + "Cannot read legacy Business ID table " + sequenceTable + + "; call context.ensureSchema() before generating IDs", + failure); } - - if (dbCurrent == null) { + if (rows == null) { + throw new TeaQLRuntimeException("Legacy Business ID query returned no result set"); + } + if (rows.isEmpty()) { + RuntimeException conflict = null; try { - database.executeUpdate( - "INSERT INTO " + sequenceTable + " (sequence_key, current_value) VALUES (?, 1)", - new Object[]{sequenceKey} - ); - result.set(1); - } catch (Exception e) { - // Concurrent insert collision, retry as update - int updated = database.executeUpdate( - "UPDATE " + sequenceTable + " SET current_value = current_value + 1 WHERE sequence_key = ?", - new Object[]{sequenceKey} - ); - if (updated == 0) { - throw new TeaQLRuntimeException("Failed to initialize or update sequence: " + sequenceKey, e); + int inserted = database.executeUpdate(context, + "INSERT INTO " + sequenceTable + + " (sequence_key, current_value) VALUES (?, 1)", + new Object[]{sequenceKey}); + if (inserted == 1) return 1; + conflict = new TeaQLRuntimeException( + "Expected one inserted Business ID row, got " + inserted); + } catch (RuntimeException insertionFailure) { + conflict = insertionFailure; + } + lastConflict = conflict; + // A collision is retried only after a fresh exact-key read proves a row exists. + try { + List> observed = database.query(context, + "SELECT current_value FROM " + sequenceTable + + " WHERE sequence_key = ?", + new Object[]{sequenceKey}); + if (observed == null || observed.isEmpty()) { + throw new TeaQLRuntimeException( + "Business ID insert failed without a matching row for " + + sequenceKey, + conflict); } - List> rows = database.query( - "SELECT current_value FROM " + sequenceTable + " WHERE sequence_key = ?", - new Object[]{sequenceKey} - ); - result.set(((Number) rows.get(0).get("current_value")).longValue()); + } catch (TeaQLRuntimeException failure) { + throw failure; + } catch (RuntimeException readFailure) { + readFailure.addSuppressed(conflict); + throw new TeaQLRuntimeException( + "Cannot verify Business ID insert for " + sequenceKey, + readFailure); + } + } else { + Object value = rows.get(0).get("current_value"); + if (value == null) value = rows.get(0).get("CURRENT_VALUE"); + if (!(value instanceof Number)) { + throw new TeaQLRuntimeException( + "Invalid legacy Business ID current_value for " + sequenceKey); + } + long current = ((Number) value).longValue(); + if (current >= maximum) { + throw new BusinessIdException( + BusinessIdErrorCode.BUSINESS_ID_RANGE_EXHAUSTED, + "Business ID range exhausted for " + sequenceKey); + } + int updated = database.executeUpdate(context, + "UPDATE " + sequenceTable + + " SET current_value = ?" + + " WHERE sequence_key = ? AND current_value = ?", + new Object[]{current + 1, sequenceKey, current}); + if (updated == 1) return current + 1; + if (updated != 0) { + throw new TeaQLRuntimeException( + "Expected one updated Business ID row, got " + updated); } - return; } - database.executeUpdate( - "UPDATE " + sequenceTable + " SET current_value = current_value + 1 WHERE sequence_key = ?", - new Object[]{sequenceKey} - ); - result.set(dbCurrent.longValue() + 1); - }); - - if (result.get() == -1) { - throw new TeaQLRuntimeException("Failed to read sequence value for key: " + sequenceKey); + java.util.concurrent.locks.LockSupport.parkNanos(1_000_000L); } - - return result.get(); + throw new BusinessIdException( + BusinessIdErrorCode.BUSINESS_ID_ALLOCATION_RETRY_EXHAUSTED, + "Legacy Business ID allocation did not converge for " + sequenceKey, + lastConflict); } } diff --git a/teaql-business-id-jdbc/src/test/java/io/teaql/businessid/jdbc/JdbcBusinessIdGeneratorTest.java b/teaql-business-id-jdbc/src/test/java/io/teaql/businessid/jdbc/JdbcBusinessIdGeneratorTest.java index 928b009d3..8c352eab6 100644 --- a/teaql-business-id-jdbc/src/test/java/io/teaql/businessid/jdbc/JdbcBusinessIdGeneratorTest.java +++ b/teaql-business-id-jdbc/src/test/java/io/teaql/businessid/jdbc/JdbcBusinessIdGeneratorTest.java @@ -2,10 +2,19 @@ import io.teaql.core.Entity; import io.teaql.core.UserContext; +import io.teaql.core.SchemaExecutor; +import io.teaql.core.TeaQLRuntimeException; +import io.teaql.core.businessid.BusinessClock; +import io.teaql.core.businessid.BusinessIdErrorCode; +import io.teaql.core.businessid.BusinessIdException; +import io.teaql.core.businessid.BusinessIdSchemaContributor; import io.teaql.core.meta.EntityDescriptor; import io.teaql.core.meta.PropertyDescriptor; +import io.teaql.core.meta.SimpleEntityMetaFactory; import io.teaql.core.meta.SimplePropertyType; import io.teaql.core.sql.portable.TeaQLDatabase; +import io.teaql.runtime.DefaultUserContext; +import io.teaql.runtime.TeaQLRuntime; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -21,11 +30,21 @@ import java.util.List; import java.util.Map; import java.time.LocalDate; -import java.time.format.DateTimeFormatter; +import java.util.Set; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; public class JdbcBusinessIdGeneratorTest { + private static final LocalDate FIXED_DATE = LocalDate.of(2026, 9, 20); + private Connection connection; + private TeaQLDatabase testDatabase; private JdbcBusinessIdGenerator generator; private EntityDescriptor entityDesc; private PropertyDescriptor propDesc; @@ -38,7 +57,7 @@ public void setUp() throws Exception { Class.forName("org.sqlite.JDBC"); connection = DriverManager.getConnection("jdbc:sqlite::memory:"); - TeaQLDatabase testDatabase = new TeaQLDatabase() { + testDatabase = new TeaQLDatabase() { @Override public List> query(String sql, Object[] args) { try (PreparedStatement stmt = connection.prepareStatement(sql)) { @@ -125,7 +144,17 @@ public List> getTableColumns(String tableName) { propDesc = new PropertyDescriptor("orderNumber", new SimplePropertyType(String.class)); - dummyContext = null; + DefaultUserContext context = new DefaultUserContext( + TeaQLRuntime.builder().metadata(new SimpleEntityMetaFactory()).build()); + context.putAttribute(BusinessClock.class.getName(), + (BusinessClock) ignored -> FIXED_DATE); + context.putAttribute(BusinessIdSchemaContributor.class.getName(), generator); + context.putAttribute(SchemaExecutor.class.getName(), + (SchemaExecutor) java.lang.reflect.Proxy.newProxyInstance( + SchemaExecutor.class.getClassLoader(), + new Class[] {SchemaExecutor.class}, + (proxy, method, args) -> null)); + dummyContext = context; dummyEntity = null; } @@ -139,11 +168,12 @@ public void tearDown() throws Exception { @Test public void testGenerateBusinessId_Success() { propDesc.getAdditionalInfo().put("business_id_rule", "ORD, 6"); + dummyContext.ensureSchema(); String id1 = generator.generateBusinessId(dummyContext, dummyEntity, entityDesc, propDesc); String id2 = generator.generateBusinessId(dummyContext, dummyEntity, entityDesc, propDesc); - String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); + String dateStr = "20260920"; Assert.assertEquals("ORD" + dateStr + "000001", id1); Assert.assertEquals("ORD" + dateStr + "000002", id2); @@ -152,15 +182,157 @@ public void testGenerateBusinessId_Success() { @Test public void testGenerateBusinessId_MultipleKeys() { propDesc.getAdditionalInfo().put("business_id_rule", "ORD, 4"); + dummyContext.ensureSchema(); String id1 = generator.generateBusinessId(dummyContext, dummyEntity, entityDesc, propDesc); PropertyDescriptor anotherProp = new PropertyDescriptor("logisticsNumber", new SimplePropertyType(String.class)); anotherProp.getAdditionalInfo().put("business_id_rule", "LOG, 4"); String id2 = generator.generateBusinessId(dummyContext, dummyEntity, entityDesc, anotherProp); - String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); + String dateStr = "20260920"; Assert.assertEquals("ORD" + dateStr + "0001", id1); Assert.assertEquals("LOG" + dateStr + "0001", id2); } + + @Test + public void testConstructorAndGenerationDoNotCreateSchema() throws Exception { + propDesc.getAdditionalInfo().put("business_id_rule", "ORD, 6"); + Assert.assertTrue(testTableNames().isEmpty()); + + TeaQLRuntimeException missing = Assert.assertThrows( + TeaQLRuntimeException.class, + () -> generator.generateBusinessId( + dummyContext, dummyEntity, entityDesc, propDesc)); + Assert.assertTrue(missing.getMessage().contains("context.ensureSchema()")); + Assert.assertTrue(testTableNames().isEmpty()); + + dummyContext.ensureSchema(); + dummyContext.ensureSchema(); + Assert.assertEquals(List.of("teaql_biz_sequence"), testTableNames()); + Assert.assertEquals("ORD20260920000001", + generator.generateBusinessId(dummyContext, dummyEntity, entityDesc, propDesc)); + } + + @Test + public void testFixedContextDateAndRangeExhaustion() throws Exception { + propDesc.getAdditionalInfo().put("business_id_rule", "ORD, 1"); + dummyContext.ensureSchema(); + for (int i = 1; i <= 9; i++) { + Assert.assertEquals("ORD20260920" + i, + generator.generateBusinessId( + dummyContext, dummyEntity, entityDesc, propDesc)); + } + BusinessIdException exhausted = Assert.assertThrows(BusinessIdException.class, + () -> generator.generateBusinessId( + dummyContext, dummyEntity, entityDesc, propDesc)); + Assert.assertEquals(BusinessIdErrorCode.BUSINESS_ID_RANGE_EXHAUSTED, + exhausted.getCode()); + ((DefaultUserContext) dummyContext).putAttribute(BusinessClock.class.getName(), + (BusinessClock) ignored -> LocalDate.of(2026, 9, 21)); + Assert.assertEquals("ORD202609211", + generator.generateBusinessId( + dummyContext, dummyEntity, entityDesc, propDesc)); + } + + @Test + public void testConcurrentReadersCannotReuseOneLegacySequenceNumber() throws Exception { + AtomicLong stored = new AtomicLong(1); + AtomicInteger reads = new AtomicInteger(); + CyclicBarrier firstReads = new CyclicBarrier(2); + TeaQLDatabase competingDatabase = new TeaQLDatabase() { + @Override + public List> query(String sql, Object[] args) { + long snapshot = stored.get(); + if (reads.incrementAndGet() <= 2) { + try { + firstReads.await(5, TimeUnit.SECONDS); + } catch (Exception failure) { + throw new RuntimeException(failure); + } + } + return List.of(Map.of("current_value", snapshot)); + } + + @Override + public int executeUpdate(String sql, Object[] args) { + long next = ((Number) args[0]).longValue(); + long expected = ((Number) args[2]).longValue(); + return stored.compareAndSet(expected, next) ? 1 : 0; + } + + @Override public int[] batchUpdate(String sql, List args) { + throw new UnsupportedOperationException(); + } + + @Override public void execute(String sql) { + throw new AssertionError("allocation must not execute DDL"); + } + + @Override public void executeInTransaction(Runnable action) { + action.run(); + } + + @Override public List> getTableColumns(String table) { + return List.of(); + } + }; + JdbcBusinessIdGenerator competing = new JdbcBusinessIdGenerator(competingDatabase); + propDesc.getAdditionalInfo().put("business_id_rule", "ORD, 6"); + ExecutorService workers = Executors.newFixedThreadPool(2); + try { + Future first = workers.submit(() -> competing.generateBusinessId( + dummyContext, dummyEntity, entityDesc, propDesc)); + Future second = workers.submit(() -> competing.generateBusinessId( + dummyContext, dummyEntity, entityDesc, propDesc)); + Assert.assertEquals(Set.of("ORD20260920000002", "ORD20260920000003"), + Set.of(first.get(10, TimeUnit.SECONDS), second.get(10, TimeUnit.SECONDS))); + Assert.assertEquals(3L, stored.get()); + } finally { + workers.shutdownNow(); + } + } + + @Test + public void testRejectsUnsafeLegacyTableName() { + Assert.assertThrows(IllegalArgumentException.class, + () -> new JdbcBusinessIdGenerator( + testDatabase, "teaql_biz_sequence;DROP TABLE x")); + } + + @Test + public void testZeroRowInsertWithoutObservedSequenceFailsImmediately() { + AtomicInteger queries = new AtomicInteger(); + TeaQLDatabase noInsert = (TeaQLDatabase) java.lang.reflect.Proxy.newProxyInstance( + TeaQLDatabase.class.getClassLoader(), + new Class[] {TeaQLDatabase.class}, + (proxy, method, args) -> { + if (method.getName().equals("query")) { + queries.incrementAndGet(); + return List.of(); + } + if (method.getName().equals("executeUpdate")) return 0; + throw new AssertionError("Unexpected database call " + method.getName()); + }); + JdbcBusinessIdGenerator noInsertGenerator = new JdbcBusinessIdGenerator(noInsert); + propDesc.getAdditionalInfo().put("business_id_rule", "ORD, 6"); + + TeaQLRuntimeException failure = Assert.assertThrows( + TeaQLRuntimeException.class, + () -> noInsertGenerator.generateBusinessId( + dummyContext, dummyEntity, entityDesc, propDesc)); + Assert.assertTrue(failure.getMessage().contains("without a matching row")); + Assert.assertEquals(2, queries.get()); + } + + private List testTableNames() throws Exception { + try (PreparedStatement statement = connection.prepareStatement( + "SELECT name FROM sqlite_master WHERE type = 'table'" + + " AND name = 'teaql_biz_sequence'"); + ResultSet rows = statement.executeQuery()) { + List names = new ArrayList<>(); + while (rows.next()) names.add(rows.getString(1)); + return names; + } + } } diff --git a/teaql-core/src/main/java/io/teaql/core/BusinessIdGenerator.java b/teaql-core/src/main/java/io/teaql/core/BusinessIdGenerator.java index 804c54c06..0733dc8b1 100644 --- a/teaql-core/src/main/java/io/teaql/core/BusinessIdGenerator.java +++ b/teaql-core/src/main/java/io/teaql/core/BusinessIdGenerator.java @@ -4,9 +4,11 @@ import io.teaql.core.meta.PropertyDescriptor; /** - * 通用业务 ID 生成器接口。 - * 用于生成像“订单号”、“物流单号”这样带有规则和业务语义的字符串 ID。 + * Legacy business ID generator retained for existing integrations. + * New applications should use {@link io.teaql.core.businessid.BusinessIdService} + * through {@link UserContext#businessIds()} instead. */ +@Deprecated public interface BusinessIdGenerator { /** diff --git a/teaql-core/src/main/java/io/teaql/core/UserContext.java b/teaql-core/src/main/java/io/teaql/core/UserContext.java index 5e1106769..36b8be456 100644 --- a/teaql-core/src/main/java/io/teaql/core/UserContext.java +++ b/teaql-core/src/main/java/io/teaql/core/UserContext.java @@ -251,8 +251,10 @@ default DynamicFieldsFacade dynamicFields() { /** * Generates a business string ID (like an order number) based on the entity and property descriptors. - * Delegates to the registered BusinessIdGenerator capability. + * Legacy compatibility path. New applications should use {@link #businessIds()} + * with a model-derived BusinessIdDefinition and a context-owned allocator. */ + @Deprecated default String generateBusinessId(Entity entity, io.teaql.core.meta.EntityDescriptor entityDesc, io.teaql.core.meta.PropertyDescriptor propertyDesc) { BusinessIdGenerator generator = capability(BusinessIdGenerator.class); if (generator == null) { diff --git a/teaql-runtime/src/main/java/io/teaql/runtime/InMemoryBusinessIdGenerator.java b/teaql-runtime/src/main/java/io/teaql/runtime/InMemoryBusinessIdGenerator.java index e4f9e8001..c66735e3c 100644 --- a/teaql-runtime/src/main/java/io/teaql/runtime/InMemoryBusinessIdGenerator.java +++ b/teaql-runtime/src/main/java/io/teaql/runtime/InMemoryBusinessIdGenerator.java @@ -3,11 +3,12 @@ import io.teaql.core.BusinessIdGenerator; import io.teaql.core.Entity; import io.teaql.core.UserContext; +import io.teaql.core.businessid.BusinessIdErrorCode; +import io.teaql.core.businessid.BusinessIdException; import io.teaql.core.meta.EntityDescriptor; import io.teaql.core.meta.PropertyDescriptor; import io.teaql.core.utils.StrUtil; -import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -18,6 +19,7 @@ * It uses a ConcurrentHashMap to store AtomicLong sequences for each sequence key. * This guarantees uniqueness within a single process but is not suitable for clustered deployments. */ +@Deprecated public class InMemoryBusinessIdGenerator implements BusinessIdGenerator { private final ConcurrentMap sequences = new ConcurrentHashMap<>(); @@ -33,16 +35,32 @@ public String generateBusinessId(UserContext context, Entity entity, EntityDescr String[] parts = rule.split(","); String prefix = parts[0].trim(); int length = parts.length > 1 ? Integer.parseInt(parts[1].trim()) : 6; + if (length < 1 || length > 18) { + throw new IllegalArgumentException("Legacy Business ID digits must be between 1 and 18"); + } - String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); + String dateStr = java.util.Objects.requireNonNull(context, "context") + .businessDate().format(DateTimeFormatter.BASIC_ISO_DATE); String sequenceKey = prefix + ":" + dateStr; - long seq = nextSequence(sequenceKey); + long maximum = 1; + for (int i = 0; i < length; i++) maximum = Math.multiplyExact(maximum, 10); + long seq = nextSequence(sequenceKey, maximum - 1); - return String.format("%s%s%0" + length + "d", prefix, dateStr, seq); + return String.format(java.util.Locale.ROOT, + "%s%s%0" + length + "d", prefix, dateStr, seq); } - private long nextSequence(String sequenceKey) { - return sequences.computeIfAbsent(sequenceKey, k -> new AtomicLong(0)).incrementAndGet(); + private long nextSequence(String sequenceKey, long maximum) { + AtomicLong counter = sequences.computeIfAbsent(sequenceKey, k -> new AtomicLong()); + while (true) { + long current = counter.get(); + if (current >= maximum) { + throw new BusinessIdException( + BusinessIdErrorCode.BUSINESS_ID_RANGE_EXHAUSTED, + "Business ID range exhausted for " + sequenceKey); + } + if (counter.compareAndSet(current, current + 1)) return current + 1; + } } } diff --git a/teaql-runtime/src/test/java/io/teaql/runtime/InMemoryBusinessIdGeneratorTest.java b/teaql-runtime/src/test/java/io/teaql/runtime/InMemoryBusinessIdGeneratorTest.java index 0eecdc226..138f227bb 100644 --- a/teaql-runtime/src/test/java/io/teaql/runtime/InMemoryBusinessIdGeneratorTest.java +++ b/teaql-runtime/src/test/java/io/teaql/runtime/InMemoryBusinessIdGeneratorTest.java @@ -5,15 +5,20 @@ import io.teaql.core.meta.EntityDescriptor; import io.teaql.core.meta.PropertyDescriptor; import io.teaql.core.meta.SimplePropertyType; +import io.teaql.core.meta.SimpleEntityMetaFactory; +import io.teaql.core.businessid.BusinessClock; +import io.teaql.core.businessid.BusinessIdErrorCode; +import io.teaql.core.businessid.BusinessIdException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.time.LocalDate; -import java.time.format.DateTimeFormatter; public class InMemoryBusinessIdGeneratorTest { + private static final LocalDate FIXED_DATE = LocalDate.of(2026, 9, 20); + private InMemoryBusinessIdGenerator generator; private EntityDescriptor entityDesc; private PropertyDescriptor propDesc; @@ -28,7 +33,11 @@ public void setUp() { propDesc = new PropertyDescriptor("orderNumber", new SimplePropertyType(String.class)); - dummyContext = null; + DefaultUserContext context = new DefaultUserContext( + TeaQLRuntime.builder().metadata(new SimpleEntityMetaFactory()).build()); + context.putAttribute(BusinessClock.class.getName(), + (BusinessClock) ignored -> FIXED_DATE); + dummyContext = context; dummyEntity = null; } @@ -39,7 +48,7 @@ public void testGenerateBusinessId_Success() { String id1 = generator.generateBusinessId(dummyContext, dummyEntity, entityDesc, propDesc); String id2 = generator.generateBusinessId(dummyContext, dummyEntity, entityDesc, propDesc); - String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); + String dateStr = "20260920"; Assert.assertEquals("ORD" + dateStr + "000001", id1); Assert.assertEquals("ORD" + dateStr + "000002", id2); @@ -51,7 +60,7 @@ public void testGenerateBusinessId_DefaultLength() { propDesc.getAdditionalInfo().put("business_id_rule", "LOG"); String id = generator.generateBusinessId(dummyContext, dummyEntity, entityDesc, propDesc); - String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); + String dateStr = "20260920"; Assert.assertEquals("LOG" + dateStr + "000001", id); } @@ -66,7 +75,7 @@ public void testGenerateBusinessId_DifferentPrefixes() { String id2 = generator.generateBusinessId(dummyContext, dummyEntity, entityDesc, anotherProp); - String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); + String dateStr = "20260920"; Assert.assertEquals("ORD" + dateStr + "0001", id1); Assert.assertEquals("LOG" + dateStr + "0001", id2); @@ -77,4 +86,29 @@ public void testGenerateBusinessId_MissingRule() { // No rule configured generator.generateBusinessId(dummyContext, dummyEntity, entityDesc, propDesc); } + + @Test + public void testContextDateControlsReset() { + propDesc.getAdditionalInfo().put("business_id_rule", "ORD, 2"); + Assert.assertEquals("ORD2026092001", + generator.generateBusinessId(dummyContext, dummyEntity, entityDesc, propDesc)); + dummyContext.putAttribute(BusinessClock.class.getName(), + (BusinessClock) ignored -> LocalDate.of(2026, 9, 21)); + Assert.assertEquals("ORD2026092101", + generator.generateBusinessId(dummyContext, dummyEntity, entityDesc, propDesc)); + } + + @Test + public void testRangeExhaustionDoesNotOverflowDigits() { + propDesc.getAdditionalInfo().put("business_id_rule", "ORD, 1"); + for (int i = 1; i <= 9; i++) { + Assert.assertEquals("ORD20260920" + i, + generator.generateBusinessId(dummyContext, dummyEntity, entityDesc, propDesc)); + } + BusinessIdException failure = Assert.assertThrows(BusinessIdException.class, + () -> generator.generateBusinessId( + dummyContext, dummyEntity, entityDesc, propDesc)); + Assert.assertEquals(BusinessIdErrorCode.BUSINESS_ID_RANGE_EXHAUSTED, + failure.getCode()); + } }