Skip to content

Commit

Permalink
fix(events): Prevent infinite loops when using events on hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
cristiands7 committed Jul 19, 2021
1 parent a0d8f72 commit 3b9a542
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/core/flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1022,6 +1022,21 @@ describe('infinite loops', () => {
client.moves.endTurn();
expect(client.getState().ctx.currentPlayer).toBe('1');
});

test('loop 5', () => {
const onBegin = (G, ctx) => ctx.events.endPhase();
const game = {
phases: {
A: { onBegin, next: 'B', start: true },
B: { onBegin, next: 'C' },
C: { onBegin, next: 'A' },
},
};

const client = Client({ game, numPlayers: 3 });

expect(client.getState().ctx.phase).toBe(null);
});
});

describe('activePlayers', () => {
Expand Down
13 changes: 13 additions & 0 deletions src/plugins/events/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,15 @@ export class Events {
phase: string;
turn: number;
}>;
initialTurn: number;
currentPhase: string;
currentTurn: number;

constructor(flow: Game['flow'], ctx: Ctx, playerID?: PlayerID) {
this.flow = flow;
this.playerID = playerID;
this.dispatch = [];
this.initialTurn = ctx.turn;
this.storeMetadata(ctx);
}

Expand Down Expand Up @@ -83,6 +85,17 @@ export class Events {
*/
update(state: State) {
for (let i = 0; i < this.dispatch.length; i++) {
const endedTurns = this.currentTurn - this.initialTurn;
// This is an arbitrarily large number.
const threshold = state.ctx.numPlayers * 10;

// This protects against potential infinite loops if specific events are called on hooks.
// The moment we exceed the defined threshold, we just bail out of all phases.
if (endedTurns > threshold) {
state = { ...state, ctx: { ...state.ctx, phase: null } };
break;
}

const item = this.dispatch[i];

// If the turn already ended,
Expand Down

0 comments on commit 3b9a542

Please sign in to comment.