Skip to content

Commit 3ae4bf0

Browse files
author
Philip Z
committed
test(id): cover bounded and concurrent allocation
1 parent e357d83 commit 3ae4bf0

2 files changed

Lines changed: 188 additions & 0 deletions

File tree

‎teaql-sql-portable/src/test/java/io/teaql/core/sql/portable/IdSpaceIdGeneratorTest.java‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,12 +68,44 @@ public void failsClosedWhenPersistentIdSpaceTableCannotBeEnsured() {
6868
assertSame(providerFailure, failure.getCause());
6969
}
7070

71+
@Test
72+
public void reportsBoundedAllocationContentionWithTypeAndAttemptCount() {
73+
RecordingDatabase database = new RecordingDatabase();
74+
database.levels.put("Order", 7L);
75+
database.alwaysCompareAndSetConflict = true;
76+
77+
IllegalStateException failure = assertThrows(
78+
IllegalStateException.class,
79+
() -> new IdSpaceIdGenerator(database).nextId("Order"));
80+
81+
assertTrue(failure.getMessage().contains("Order"));
82+
assertTrue(failure.getMessage().contains("100 optimistic-lock attempts"));
83+
assertEquals(100, database.updates.size());
84+
}
85+
86+
@Test
87+
public void reportsBoundedFloorContentionWithoutMovingFloorBackwards() {
88+
RecordingDatabase database = new RecordingDatabase();
89+
database.levels.put("SchoolType", 1L);
90+
database.alwaysCompareAndSetConflict = true;
91+
92+
IllegalStateException failure = assertThrows(
93+
IllegalStateException.class,
94+
() -> new IdSpaceIdGenerator(database).ensureFloor("SchoolType", 1002L));
95+
96+
assertTrue(failure.getMessage().contains("SchoolType"));
97+
assertTrue(failure.getMessage().contains("100 optimistic-lock attempts"));
98+
assertEquals(Long.valueOf(1L), database.levels.get("SchoolType"));
99+
assertEquals(100, database.updates.size());
100+
}
101+
71102
private static final class RecordingDatabase implements TeaQLDatabase {
72103
private final Map<String, Long> levels = new HashMap<>();
73104
private final List<String> queries = new ArrayList<>();
74105
private final List<String> updates = new ArrayList<>();
75106
private boolean failFirstInsertAsRace;
76107
private boolean failFirstCompareAndSetAsRace;
108+
private boolean alwaysCompareAndSetConflict;
77109
private RuntimeException executeFailure;
78110

79111
@Override
@@ -100,6 +132,9 @@ public int executeUpdate(String sql, Object[] args) {
100132
updates.add(sql);
101133
String typeName = String.valueOf(args[1]);
102134
long expected = ((Number) args[2]).longValue();
135+
if (alwaysCompareAndSetConflict) {
136+
return 0;
137+
}
103138
if (failFirstCompareAndSetAsRace) {
104139
failFirstCompareAndSetAsRace = false;
105140
levels.put(typeName, expected + 1); // Simulates a competing successful CAS.
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
package io.teaql.core.sql.portable;
2+
3+
import static org.junit.Assert.assertEquals;
4+
import static org.junit.Assert.assertTrue;
5+
6+
import java.nio.file.Files;
7+
import java.nio.file.Path;
8+
import java.sql.Connection;
9+
import java.sql.DriverManager;
10+
import java.sql.PreparedStatement;
11+
import java.sql.ResultSet;
12+
import java.sql.Statement;
13+
import java.util.ArrayList;
14+
import java.util.List;
15+
import java.util.Map;
16+
import java.util.Set;
17+
import java.util.concurrent.Callable;
18+
import java.util.concurrent.ConcurrentHashMap;
19+
import java.util.concurrent.CountDownLatch;
20+
import java.util.concurrent.Executors;
21+
import java.util.concurrent.Future;
22+
import java.util.concurrent.TimeUnit;
23+
import org.junit.Test;
24+
25+
/** Exercises the portable optimistic allocator through independent SQLite connections. */
26+
public class SqliteIdSpaceConcurrencyTest {
27+
28+
@Test
29+
public void independentInstancesAllocateUniqueIdsAndRespectBootstrapFloor() throws Exception {
30+
Path databaseFile = Files.createTempFile("teaql-id-space-", ".db");
31+
try {
32+
String url = "jdbc:sqlite:" + databaseFile;
33+
SqliteDatabase database = new SqliteDatabase(url);
34+
IdSpaceIdGenerator initializer = new IdSpaceIdGenerator(database);
35+
initializer.ensureIdSpaceTable();
36+
initializer.ensureFloor("SchoolType", 1002L);
37+
assertEquals(
38+
1003L,
39+
new IdSpaceIdGenerator(new SqliteDatabase(url)).nextId("SchoolType"));
40+
41+
int workers = 4;
42+
int allocationsPerWorker = 20;
43+
CountDownLatch start = new CountDownLatch(1);
44+
Set<Long> ids = ConcurrentHashMap.newKeySet();
45+
var pool = Executors.newFixedThreadPool(workers);
46+
try {
47+
List<Future<Void>> futures = new ArrayList<>();
48+
for (int worker = 0; worker < workers; worker++) {
49+
futures.add(pool.submit(new Callable<>() {
50+
@Override
51+
public Void call() throws Exception {
52+
IdSpaceIdGenerator generator = new IdSpaceIdGenerator(
53+
new SqliteDatabase(url));
54+
start.await();
55+
for (int index = 0; index < allocationsPerWorker; index++) {
56+
assertTrue("duplicate ID allocated", ids.add(generator.nextId("Order")));
57+
}
58+
return null;
59+
}
60+
}));
61+
}
62+
start.countDown();
63+
for (Future<Void> future : futures) {
64+
future.get(30, TimeUnit.SECONDS);
65+
}
66+
} finally {
67+
pool.shutdownNow();
68+
}
69+
70+
assertEquals(workers * allocationsPerWorker, ids.size());
71+
for (long id = 1; id <= workers * allocationsPerWorker; id++) {
72+
assertTrue("missing ID " + id, ids.contains(id));
73+
}
74+
assertEquals(
75+
81L,
76+
new IdSpaceIdGenerator(new SqliteDatabase(url)).nextId("Order"));
77+
} finally {
78+
Files.deleteIfExists(databaseFile);
79+
}
80+
}
81+
82+
private static final class SqliteDatabase implements TeaQLDatabase {
83+
private final String url;
84+
85+
private SqliteDatabase(String url) {
86+
this.url = url;
87+
}
88+
89+
private Connection connect() throws Exception {
90+
Connection connection = DriverManager.getConnection(url);
91+
try (Statement statement = connection.createStatement()) {
92+
statement.execute("PRAGMA busy_timeout = 5000");
93+
}
94+
return connection;
95+
}
96+
97+
@Override
98+
public List<Map<String, Object>> query(String sql, Object[] args) {
99+
try (Connection connection = connect();
100+
PreparedStatement statement = connection.prepareStatement(sql)) {
101+
bind(statement, args);
102+
try (ResultSet result = statement.executeQuery()) {
103+
return result.next()
104+
? List.of(Map.of("current_level", result.getLong("current_level")))
105+
: List.of();
106+
}
107+
} catch (Exception error) {
108+
throw new IllegalStateException(error);
109+
}
110+
}
111+
112+
@Override
113+
public int executeUpdate(String sql, Object[] args) {
114+
try (Connection connection = connect();
115+
PreparedStatement statement = connection.prepareStatement(sql)) {
116+
bind(statement, args);
117+
return statement.executeUpdate();
118+
} catch (Exception error) {
119+
throw new IllegalStateException(error);
120+
}
121+
}
122+
123+
@Override
124+
public void execute(String sql) {
125+
try (Connection connection = connect(); Statement statement = connection.createStatement()) {
126+
statement.execute(sql);
127+
} catch (Exception error) {
128+
throw new IllegalStateException(error);
129+
}
130+
}
131+
132+
private static void bind(PreparedStatement statement, Object[] args) throws Exception {
133+
for (int index = 0; index < args.length; index++) {
134+
statement.setObject(index + 1, args[index]);
135+
}
136+
}
137+
138+
@Override
139+
public int[] batchUpdate(String sql, List<Object[]> batchArgs) {
140+
throw new UnsupportedOperationException("not used by ID allocation");
141+
}
142+
143+
@Override
144+
public void executeInTransaction(Runnable action) {
145+
throw new UnsupportedOperationException("not used by ID allocation");
146+
}
147+
148+
@Override
149+
public List<Map<String, Object>> getTableColumns(String tableName) {
150+
throw new UnsupportedOperationException("not used by ID allocation");
151+
}
152+
}
153+
}

0 commit comments

Comments
 (0)