Skip to content

Commit db7d43a

Browse files
committed
fix: publish interactions only after scene commit
1 parent 7a97b82 commit db7d43a

2 files changed

Lines changed: 187 additions & 7 deletions

File tree

‎modules/mahjong-craftengine/src/main/java/top/ellan/mahjong/craftengine/CraftEngineSceneBackend.java‎

Lines changed: 47 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ public void submit(SceneDiff diff) {
6161
if (diff.toRevision() > table.desiredRevision) {
6262
table.failed = false;
6363
}
64+
table.bindingsInstalled = false;
65+
interactions.replaceBindings(diff.tableId(), List.of());
6466
for (SceneNodeId removal : diff.removals()) {
6567
table.desired.remove(removal);
6668
table.dirty.add(removal);
@@ -71,6 +73,7 @@ public void submit(SceneDiff diff) {
7173
}
7274
if (table.desired.size() > config.maxNodesPerTable()) {
7375
table.failed = true;
76+
table.desiredRevision = diff.toRevision();
7477
failureSink.accept(
7578
new CraftEngineTableFailure(
7679
diff.tableId(), diff.toRevision(), "scene-node-capacity"));
@@ -86,9 +89,9 @@ public void submit(SceneDiff diff) {
8689
binding.playerId(),
8790
binding.actionToken()))
8891
.toList();
89-
interactions.replaceBindings(diff.tableId(), table.bindings);
9092
}
9193
markReady(diff.tableId(), table);
94+
installBindingsIfReady(diff.tableId(), table);
9295
}
9396

9497
/** Called only after CraftEngineReloadEvent confirms the atomically installed bundle is live. */
@@ -102,6 +105,9 @@ public void onCraftEngineReloaded() {
102105
table.actual.clear();
103106
table.dirty.addAll(table.forced);
104107
table.failed = false;
108+
table.applyEpoch++;
109+
table.bindingsInstalled = false;
110+
interactions.replaceBindings(tableId, List.of());
105111
}
106112
markReady(tableId, table);
107113
});
@@ -123,8 +129,14 @@ public void onCraftEngineReloadStarted() {
123129
region.scheduled = false;
124130
}
125131
});
126-
tables.keySet().forEach(
127-
tableId -> interactions.replaceBindings(tableId, List.of()));
132+
tables.forEach(
133+
(tableId, table) -> {
134+
synchronized (table) {
135+
table.applyEpoch++;
136+
table.bindingsInstalled = false;
137+
interactions.replaceBindings(tableId, List.of());
138+
}
139+
});
128140
}
129141

130142
public boolean ready() {
@@ -141,6 +153,7 @@ public void removeTable(TableId tableId) {
141153
table.failed = false;
142154
table.desired.clear();
143155
table.dirty.addAll(table.actual.keySet());
156+
table.bindingsInstalled = false;
144157
interactions.replaceBindings(tableId, List.of());
145158
}
146159
markReady(tableId, table);
@@ -243,6 +256,7 @@ private void runRegion(RegionKey key, RegionState region) {
243256
}
244257
Mutation mutation = nextMutation(table);
245258
if (mutation == null) {
259+
installBindingsIfReady(tableId, table);
246260
finishClosedTable(tableId, table);
247261
continue;
248262
}
@@ -276,7 +290,7 @@ private Mutation nextMutation(TableState table) {
276290
iterator.remove();
277291
continue;
278292
}
279-
return new Mutation(id, desired);
293+
return new Mutation(id, desired, table.applyEpoch);
280294
}
281295
return null;
282296
}
@@ -290,17 +304,27 @@ private boolean apply(TableId tableId, TableState table, Mutation mutation) {
290304
gateway.upsert(tableId, mutation.desired());
291305
}
292306
synchronized (table) {
307+
if (mutation.applyEpoch() != table.applyEpoch) {
308+
return true;
309+
}
293310
if (mutation.desired() == null) {
294311
table.actual.remove(mutation.id());
295312
} else {
296313
table.actual.put(mutation.id(), mutation.desired());
297314
}
298-
table.dirty.remove(mutation.id());
299315
table.forced.remove(mutation.id());
316+
if (Objects.equals(table.desired.get(mutation.id()), mutation.desired())) {
317+
table.dirty.remove(mutation.id());
318+
} else {
319+
table.dirty.add(mutation.id());
320+
}
300321
}
301322
return true;
302323
} catch (RuntimeException failure) {
303324
synchronized (table) {
325+
if (mutation.applyEpoch() != table.applyEpoch) {
326+
return true;
327+
}
304328
table.failed = true;
305329
}
306330
failureSink.accept(
@@ -336,13 +360,28 @@ private void deferToNextTick(
336360
}
337361

338362
private void finishClosedTable(TableId tableId, TableState table) {
363+
installBindingsIfReady(tableId, table);
339364
synchronized (table) {
340365
if (table.closed && table.actual.isEmpty() && table.dirty.isEmpty()) {
341366
tables.remove(tableId, table);
342367
}
343368
}
344369
}
345370

371+
private void installBindingsIfReady(TableId tableId, TableState table) {
372+
synchronized (table) {
373+
if (!ready.get()
374+
|| table.closed
375+
|| table.failed
376+
|| !table.dirty.isEmpty()
377+
|| table.bindingsInstalled) {
378+
return;
379+
}
380+
interactions.replaceBindings(tableId, table.bindings);
381+
table.bindingsInstalled = true;
382+
}
383+
}
384+
346385
private static final class TableState {
347386
private final Map<SceneNodeId, SceneNode> desired = new LinkedHashMap<>();
348387
private final Map<SceneNodeId, SceneNode> actual = new LinkedHashMap<>();
@@ -353,12 +392,14 @@ private static final class TableState {
353392
private boolean regionQueued;
354393
private boolean failed;
355394
private boolean closed;
395+
private boolean bindingsInstalled;
396+
private long applyEpoch;
356397
}
357398

358399
private static final class RegionState {
359400
private final ArrayDeque<TableId> ready = new ArrayDeque<>();
360401
private boolean scheduled;
361402
}
362403

363-
private record Mutation(SceneNodeId id, SceneNode desired) {}
404+
private record Mutation(SceneNodeId id, SceneNode desired, long applyEpoch) {}
364405
}

‎modules/mahjong-craftengine/src/test/java/top/ellan/mahjong/craftengine/CraftEngineSceneBackendTest.java‎

Lines changed: 140 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,21 @@
99
import java.util.HashMap;
1010
import java.util.List;
1111
import java.util.Map;
12+
import java.util.UUID;
1213
import org.junit.jupiter.api.Test;
14+
import top.ellan.mahjong.application.InteractionHandle;
1315
import top.ellan.mahjong.application.InteractionRouter;
1416
import top.ellan.mahjong.application.TableActorRegistry;
1517
import top.ellan.mahjong.domain.TableId;
18+
import top.ellan.mahjong.presentation.SceneInteractionBinding;
1619
import top.ellan.mahjong.presentation.FurnitureNode;
1720
import top.ellan.mahjong.presentation.SceneDiff;
1821
import top.ellan.mahjong.presentation.SceneNode;
1922
import top.ellan.mahjong.presentation.SceneNodeId;
2023
import top.ellan.mahjong.presentation.SceneTransform;
2124
import top.ellan.mahjong.presentation.SceneVisibility;
25+
import top.ellan.mahjong.spi.ActionToken;
26+
import top.ellan.mahjong.spi.PlayerId;
2227

2328
class CraftEngineSceneBackendTest {
2429
private static final RegionKey REGION = new RegionKey("world", 0, 0);
@@ -123,19 +128,147 @@ void removalDuringReloadStillDeletesThePreviouslyAppliedFurniture() {
123128
assertFalse(gateway.live.getOrDefault(table, Map.of()).containsKey(node));
124129
}
125130

131+
@Test
132+
void interactionTokensOpenOnlyAfterTheirSceneRevisionIsApplied() {
133+
ManualRegionScheduler scheduler = new ManualRegionScheduler();
134+
RecordingGateway gateway = new RecordingGateway();
135+
InteractionRouter interactions = new InteractionRouter(new TableActorRegistry());
136+
CraftEngineSceneBackend backend =
137+
backend(gateway, scheduler, interactions, ignored -> {});
138+
TableId table = TableId.random();
139+
PlayerId player = new PlayerId(UUID.randomUUID());
140+
InteractionHandle handle = new InteractionHandle(UUID.randomUUID());
141+
SceneDiff initial = withBinding(diff(table, 1), handle, player, 1);
142+
143+
backend.submit(initial);
144+
assertEquals(0, interactions.routeCount());
145+
backend.onCraftEngineReloaded();
146+
assertEquals(0, interactions.routeCount());
147+
148+
scheduler.runUntilIdle(REGION, 4);
149+
assertEquals(1, interactions.routeCount());
150+
151+
SceneNode changed =
152+
new FurnitureNode(
153+
new SceneNodeId("tile/0"),
154+
SceneVisibility.publicToAll(),
155+
"mahjong:tile/back",
156+
new SceneTransform(2, 0, 0, 0, 0, 0, 1));
157+
SceneDiff next =
158+
new SceneDiff(
159+
table,
160+
1,
161+
2,
162+
List.of(),
163+
List.of(changed),
164+
List.of(
165+
new SceneInteractionBinding(
166+
handle,
167+
player,
168+
new ActionToken(UUID.randomUUID(), player, 2))));
169+
170+
backend.submit(next);
171+
assertEquals(0, interactions.routeCount());
172+
173+
scheduler.runUntilIdle(REGION, 4);
174+
assertEquals(1, interactions.routeCount());
175+
}
176+
177+
@Test
178+
void newerSceneSubmittedDuringMutationCannotBeClearedByTheOlderResult() {
179+
ManualRegionScheduler scheduler = new ManualRegionScheduler();
180+
RecordingGateway gateway = new RecordingGateway();
181+
CraftEngineSceneBackend backend = backend(gateway, scheduler, ignored -> {});
182+
TableId table = TableId.random();
183+
SceneNodeId nodeId = new SceneNodeId("tile/0");
184+
SceneNode newest =
185+
new FurnitureNode(
186+
nodeId,
187+
SceneVisibility.publicToAll(),
188+
"mahjong:tile/back",
189+
new SceneTransform(3, 0, 0, 0, 0, 0, 1));
190+
gateway.duringFirstUpsert =
191+
() ->
192+
backend.submit(
193+
new SceneDiff(
194+
table,
195+
1,
196+
2,
197+
List.of(),
198+
List.of(newest),
199+
List.of()));
200+
201+
backend.submit(diff(table, 1));
202+
backend.onCraftEngineReloaded();
203+
scheduler.runUntilIdle(REGION, 4);
204+
205+
assertEquals(2, gateway.upserted.getOrDefault(table, 0));
206+
assertEquals(newest, gateway.live.getOrDefault(table, Map.of()).get(nodeId));
207+
}
208+
209+
@Test
210+
void failedCraftEngineRevisionNeverOpensItsInteractionTokens() {
211+
ManualRegionScheduler scheduler = new ManualRegionScheduler();
212+
RecordingGateway gateway = new RecordingGateway();
213+
InteractionRouter interactions = new InteractionRouter(new TableActorRegistry());
214+
CraftEngineSceneBackend backend =
215+
backend(gateway, scheduler, interactions, ignored -> {});
216+
TableId table = TableId.random();
217+
PlayerId player = new PlayerId(UUID.randomUUID());
218+
gateway.broken = table;
219+
220+
backend.submit(
221+
withBinding(
222+
diff(table, 1),
223+
new InteractionHandle(UUID.randomUUID()),
224+
player,
225+
1));
226+
backend.onCraftEngineReloaded();
227+
scheduler.runUntilIdle(REGION, 4);
228+
229+
assertEquals(0, interactions.routeCount());
230+
}
231+
126232
private static CraftEngineSceneBackend backend(
127233
RecordingGateway gateway,
128234
ManualRegionScheduler scheduler,
129235
java.util.function.Consumer<CraftEngineTableFailure> failures) {
236+
return backend(
237+
gateway,
238+
scheduler,
239+
new InteractionRouter(new TableActorRegistry()),
240+
failures);
241+
}
242+
243+
private static CraftEngineSceneBackend backend(
244+
RecordingGateway gateway,
245+
ManualRegionScheduler scheduler,
246+
InteractionRouter interactions,
247+
java.util.function.Consumer<CraftEngineTableFailure> failures) {
130248
return new CraftEngineSceneBackend(
131249
gateway,
132250
scheduler,
133251
ignored -> REGION,
134-
new InteractionRouter(new TableActorRegistry()),
252+
interactions,
135253
new CraftEngineBackendConfig(16, 1_000_000_000L, 1_024, 256),
136254
failures);
137255
}
138256

257+
private static SceneDiff withBinding(
258+
SceneDiff diff, InteractionHandle handle, PlayerId player, long revision) {
259+
return new SceneDiff(
260+
diff.tableId(),
261+
diff.fromRevision(),
262+
diff.toRevision(),
263+
diff.removals(),
264+
diff.upserts(),
265+
List.of(
266+
new SceneInteractionBinding(
267+
handle,
268+
player,
269+
new ActionToken(UUID.randomUUID(), player, revision))));
270+
}
271+
139272
private static SceneDiff diff(TableId table, int nodes) {
140273
List<SceneNode> upserts = new ArrayList<>();
141274
for (int index = 0; index < nodes; index++) {
@@ -185,13 +318,19 @@ private static final class RecordingGateway implements CraftEngineMutationGatewa
185318
private final Map<TableId, Integer> upserted = new HashMap<>();
186319
private final Map<TableId, Map<SceneNodeId, SceneNode>> live = new HashMap<>();
187320
private TableId broken;
321+
private Runnable duringFirstUpsert;
188322

189323
@Override
190324
public void upsert(TableId tableId, SceneNode node) {
191325
if (tableId.equals(broken)) {
192326
throw new IllegalStateException("isolated CE failure");
193327
}
194328
upserted.merge(tableId, 1, Integer::sum);
329+
Runnable callback = duringFirstUpsert;
330+
duringFirstUpsert = null;
331+
if (callback != null) {
332+
callback.run();
333+
}
195334
live.computeIfAbsent(tableId, ignored -> new HashMap<>()).put(node.id(), node);
196335
}
197336

0 commit comments

Comments
 (0)