Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d741ef9a7 | ||
|
|
23a0a3f8dd | ||
|
|
e349684523 | ||
|
|
9d7c888b0a |
No files matched your search
@@ -1,10 +1,11 @@
|
||||
// @ts-check
|
||||
import eslint from '@eslint/js';
|
||||
import { defineConfig } from 'eslint/config';
|
||||
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
|
||||
import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
export default tseslint.config(
|
||||
export default defineConfig(
|
||||
{
|
||||
ignores: ['eslint.config.mjs'],
|
||||
},
|
||||
|
||||
@@ -35,19 +35,20 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@lolympus/contracts": "workspace:*",
|
||||
"@nats-io/jetstream": "^3.4.0",
|
||||
"@nats-io/transport-node": "^3.4.0",
|
||||
"@nestjs/common": "^11.1.28",
|
||||
"@nestjs/config": "^4.0.4",
|
||||
"@nestjs/core": "^11.1.28",
|
||||
"@nestjs/platform-express": "^11.1.28",
|
||||
"@nestjs/platform-socket.io": "^11.1.28",
|
||||
"@nestjs/swagger": "^11.4.6",
|
||||
"@nestjs/swagger": "^11.4.8",
|
||||
"@nestjs/websockets": "^11.1.28",
|
||||
"@socket.io/redis-adapter": "^8.3.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.15.1",
|
||||
"jose": "^6.2.2",
|
||||
"mongoose": "9.11.4",
|
||||
"nats": "^2.29.3",
|
||||
"mongoose": "9.12.1",
|
||||
"newrelic": "^14.3.3",
|
||||
"redis": "^5.12.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
@@ -56,8 +57,7 @@
|
||||
"temporal-polyfill": "^0.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
"@eslint/js": "^9.18.0",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@nestjs/cli": "^11.0.0",
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@nestjs/testing": "^11.0.1",
|
||||
@@ -65,7 +65,7 @@
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/node": "^26.1.1",
|
||||
"@types/supertest": "^7.0.0",
|
||||
"eslint": "^9.18.0",
|
||||
"eslint": "^10.14.0",
|
||||
"eslint-config-prettier": "^10.0.1",
|
||||
"eslint-plugin-prettier": "^5.2.2",
|
||||
"globals": "^17.0.0",
|
||||
|
||||
@@ -233,6 +233,56 @@ describe('auction durability projection helpers', () => {
|
||||
expect(session.endSession).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('notifies history only after commit, including when state rebroadcast is disabled', async () => {
|
||||
let finishCommit!: () => void;
|
||||
const session = {
|
||||
startTransaction: jest.fn(),
|
||||
commitTransaction: jest.fn().mockImplementation(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
finishCommit = resolve;
|
||||
}),
|
||||
),
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
endSession: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const updateOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
|
||||
});
|
||||
const broadcastHistoryUpdated = jest.fn();
|
||||
const scheduler = new AuctionDurabilityScheduler(
|
||||
{
|
||||
createSession: async () => session,
|
||||
getModel: async () => ({ updateOne }),
|
||||
} as never,
|
||||
{} as never,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ broadcastHistoryUpdated } as never,
|
||||
);
|
||||
const pending = scheduler.applyDurabilityPayload({
|
||||
...payload,
|
||||
shouldBroadcastState: false,
|
||||
});
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||
expect(broadcastHistoryUpdated).not.toHaveBeenCalled();
|
||||
finishCommit();
|
||||
await pending;
|
||||
expect(broadcastHistoryUpdated).toHaveBeenCalledWith({
|
||||
matchId: 'match-1',
|
||||
auctionLifecycleId: 'life-1',
|
||||
auctionStateTransitionId: 'transition-1',
|
||||
});
|
||||
session.commitTransaction.mockRejectedValueOnce(new Error('commit failed'));
|
||||
await expect(scheduler.applyDurabilityPayload(payload)).rejects.toThrow(
|
||||
'commit failed',
|
||||
);
|
||||
expect(broadcastHistoryUpdated).toHaveBeenCalledTimes(1);
|
||||
expect(session.abortTransaction).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('broadcasts latest Redis state when durability payload requests it', async () => {
|
||||
const session = {
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
@@ -265,7 +315,7 @@ describe('auction durability projection helpers', () => {
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ broadcastState } as never,
|
||||
{ broadcastState, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
{ readAuctionStateView } as never,
|
||||
);
|
||||
|
||||
@@ -315,7 +365,7 @@ describe('auction durability projection helpers', () => {
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ broadcastState } as never,
|
||||
{ broadcastState, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
{ readAuctionStateView } as never,
|
||||
);
|
||||
|
||||
@@ -407,60 +457,71 @@ describe('auction durability projection helpers', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('skips destructive history mutation for stale payloads', async () => {
|
||||
const session = {
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
endSession: jest.fn().mockResolvedValue(undefined),
|
||||
startTransaction: jest.fn(),
|
||||
};
|
||||
const historyDeleteMany = jest.fn();
|
||||
const historyUpdateOne = jest.fn();
|
||||
const auctionUpdateOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ matchedCount: 0, modifiedCount: 0 }),
|
||||
});
|
||||
const projectionExec = jest.fn().mockResolvedValue({
|
||||
auctionLifecycleId: 'life-1',
|
||||
revision: 10,
|
||||
});
|
||||
const auctionFindById = jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({ exec: projectionExec }),
|
||||
it.each(['life-1', 'new-life'])(
|
||||
'skips stale history changes and notifications for current lifecycle %s',
|
||||
async (auctionLifecycleId) => {
|
||||
const broadcastHistoryUpdated = jest.fn();
|
||||
const session = {
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
endSession: jest.fn().mockResolvedValue(undefined),
|
||||
startTransaction: jest.fn(),
|
||||
};
|
||||
const historyDeleteMany = jest.fn();
|
||||
const historyUpdateOne = jest.fn();
|
||||
const auctionUpdateOne = jest.fn().mockReturnValue({
|
||||
exec: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ matchedCount: 0, modifiedCount: 0 }),
|
||||
});
|
||||
const projectionExec = jest.fn().mockResolvedValue({
|
||||
auctionLifecycleId,
|
||||
revision: 10,
|
||||
});
|
||||
const auctionFindById = jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({ exec: projectionExec }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
const scheduler = new AuctionDurabilityScheduler(
|
||||
{
|
||||
createSession: jest.fn().mockResolvedValue(session),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return {
|
||||
deleteMany: historyDeleteMany,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||
}
|
||||
return { updateOne: jest.fn() };
|
||||
}),
|
||||
} as never,
|
||||
{ raw: jest.fn() } as never,
|
||||
);
|
||||
});
|
||||
const scheduler = new AuctionDurabilityScheduler(
|
||||
{
|
||||
createSession: jest.fn().mockResolvedValue(session),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return {
|
||||
deleteMany: historyDeleteMany,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||
}
|
||||
return { updateOne: jest.fn() };
|
||||
}),
|
||||
} as never,
|
||||
{ raw: jest.fn() } as never,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ broadcastHistoryUpdated } as never,
|
||||
);
|
||||
|
||||
await scheduler.applyDurabilityPayload({
|
||||
...payload,
|
||||
historyMutation: {
|
||||
targetHistorySequence: 2,
|
||||
type: 'deleteAfterSequenceAndAppendUndo',
|
||||
},
|
||||
});
|
||||
await scheduler.applyDurabilityPayload({
|
||||
...payload,
|
||||
historyMutation: {
|
||||
targetHistorySequence: 2,
|
||||
type: 'deleteAfterSequenceAndAppendUndo',
|
||||
},
|
||||
});
|
||||
|
||||
expect(historyDeleteMany).not.toHaveBeenCalled();
|
||||
expect(historyUpdateOne).not.toHaveBeenCalled();
|
||||
expect(auctionUpdateOne).not.toHaveBeenCalled();
|
||||
});
|
||||
expect(historyDeleteMany).not.toHaveBeenCalled();
|
||||
expect(historyUpdateOne).not.toHaveBeenCalled();
|
||||
expect(auctionUpdateOne).not.toHaveBeenCalled();
|
||||
expect(broadcastHistoryUpdated).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('recovers stale append payloads as history-only records', async () => {
|
||||
const session = {
|
||||
@@ -597,6 +658,7 @@ describe('auction durability projection helpers', () => {
|
||||
});
|
||||
|
||||
it('clears stale append payloads after history-only recovery', async () => {
|
||||
const broadcastHistoryUpdated = jest.fn();
|
||||
const sendCommand = jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce(['payload-1'])
|
||||
@@ -653,6 +715,10 @@ describe('auction durability projection helpers', () => {
|
||||
getCurrentRedisTimestampMS: jest.fn().mockResolvedValue(1000),
|
||||
raw: jest.fn().mockReturnValue({ sendCommand }),
|
||||
} as never,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ broadcastHistoryUpdated } as never,
|
||||
);
|
||||
|
||||
await expect(scheduler.processDueDurabilityPayloads(10)).resolves.toEqual({
|
||||
@@ -662,6 +728,11 @@ describe('auction durability projection helpers', () => {
|
||||
});
|
||||
|
||||
expect(historyUpdateOne).toHaveBeenCalledTimes(1);
|
||||
expect(broadcastHistoryUpdated).toHaveBeenCalledWith({
|
||||
matchId: 'match-1',
|
||||
auctionLifecycleId: 'life-1',
|
||||
auctionStateTransitionId: 'transition-1',
|
||||
});
|
||||
expect(auctionUpdateOne).not.toHaveBeenCalled();
|
||||
expect(sideEffectUpdateOne).not.toHaveBeenCalled();
|
||||
expect(sendCommand).toHaveBeenNthCalledWith(3, [
|
||||
@@ -1006,7 +1077,7 @@ describe('auction durability projection helpers', () => {
|
||||
{ reserveForMatch } as never,
|
||||
{ scheduleInitialPoll } as never,
|
||||
{ mirrorMatchSideEffectStatus } as never,
|
||||
{ broadcastMatchSideEffect } as never,
|
||||
{ broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
);
|
||||
|
||||
await scheduler.applyDurabilityPayload(completePayload);
|
||||
@@ -1203,7 +1274,7 @@ describe('auction durability projection helpers', () => {
|
||||
{ reserveForMatch } as never,
|
||||
{ scheduleInitialPoll } as never,
|
||||
{ mirrorMatchSideEffectStatus } as never,
|
||||
{ broadcastMatchSideEffect } as never,
|
||||
{ broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
);
|
||||
|
||||
await expect(
|
||||
@@ -1332,7 +1403,7 @@ describe('auction durability projection helpers', () => {
|
||||
{ releaseFromMatch } as never,
|
||||
{ cancelPolling } as never,
|
||||
{ mirrorMatchSideEffectStatus } as never,
|
||||
{ broadcastMatchSideEffect } as never,
|
||||
{ broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
);
|
||||
|
||||
await scheduler.applyDurabilityPayload(resetPayload);
|
||||
|
||||
@@ -356,6 +356,15 @@ export class AuctionDurabilityScheduler
|
||||
if (session) await session.endSession();
|
||||
}
|
||||
|
||||
if (shouldApplyHistoryMutation) {
|
||||
// This is independent of the primary state broadcast. HTTP reads on every
|
||||
// node can see the committed history before clients are notified.
|
||||
this.auctionEventBusService?.broadcastHistoryUpdated({
|
||||
matchId: String(payload.matchId),
|
||||
auctionLifecycleId: payload.auctionLifecycleId,
|
||||
auctionStateTransitionId: payload.auctionStateTransitionId,
|
||||
});
|
||||
}
|
||||
await this.broadcastLatestRedisAuctionStateIfRequested(payload);
|
||||
|
||||
if (sideEffectMutation && shouldApplySideEffects) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { Namespace } from 'socket.io';
|
||||
import type { AuctionHistoryUpdatedEvent } from '@lolympus/contracts';
|
||||
import type { AuctionStateResponse } from './auction.service';
|
||||
import type { MatchSideEffectDelta } from './auction-side-effect.service';
|
||||
import { serializeRealtimeAuction } from './auction-realtime-serializer';
|
||||
@@ -25,6 +26,10 @@ export class AuctionEventBusService {
|
||||
.emit('state', serializeRealtimeAuction(state));
|
||||
}
|
||||
|
||||
public broadcastHistoryUpdated(event: AuctionHistoryUpdatedEvent): void {
|
||||
this.auctionNamespace?.to(event.matchId).emit('history-updated', event);
|
||||
}
|
||||
|
||||
public broadcastReset(matchId: string, auctionLifecycleId: string): void {
|
||||
this.auctionNamespace
|
||||
?.to(matchId)
|
||||
|
||||
@@ -37,7 +37,11 @@ describe('AuctionGateway', () => {
|
||||
{} as never,
|
||||
);
|
||||
const socket = { data: { matchId }, join: jest.fn(), emit: jest.fn() };
|
||||
await gateway.handleJoin(socket as never, { matchId });
|
||||
const ack = jest.fn();
|
||||
await gateway.handleJoin(socket as never, { matchId }, ack);
|
||||
expect(ack).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ ok: false, code: 'AUCTION_STATE_RECOVERING' }),
|
||||
);
|
||||
expect(socket.emit).toHaveBeenCalledTimes(1);
|
||||
expect(socket.emit).toHaveBeenCalledWith('state-pending', {
|
||||
retryAfterMS: 500,
|
||||
@@ -92,9 +96,12 @@ describe('AuctionGateway', () => {
|
||||
function createGateway(params?: {
|
||||
getCurrentRedisTimestampMS?: jest.Mock;
|
||||
placeBidDelta?: jest.Mock;
|
||||
getRealtimeIdentity?: jest.Mock;
|
||||
}) {
|
||||
const auctionService = {
|
||||
placeBidDelta: params?.placeBidDelta ?? jest.fn(),
|
||||
getRealtimeIdentity:
|
||||
params?.getRealtimeIdentity ?? jest.fn().mockResolvedValue(null),
|
||||
};
|
||||
const auctionRedisService = {
|
||||
getCurrentRedisTimestampMS:
|
||||
@@ -387,6 +394,46 @@ describe('AuctionGateway', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('adds lightweight auction identity to heartbeats for the joined match', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
const identity = {
|
||||
auctionLifecycleId: 'life-1',
|
||||
revision: 11,
|
||||
matchSideEffectRevision: 3,
|
||||
};
|
||||
const getRealtimeIdentity = jest.fn().mockResolvedValue(identity);
|
||||
const { gateway } = createGateway({ getRealtimeIdentity });
|
||||
const ack = jest.fn();
|
||||
await gateway.handleTimeSync({ sequence: 1 }, ack, {
|
||||
data: { matchId },
|
||||
} as never);
|
||||
expect(getRealtimeIdentity).toHaveBeenCalledWith(matchId);
|
||||
expect(ack).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ ok: true, auctionState: identity }),
|
||||
);
|
||||
});
|
||||
|
||||
it('continues clock sync when the optional auction identity read fails', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
const { gateway } = createGateway({
|
||||
getRealtimeIdentity: jest
|
||||
.fn()
|
||||
.mockRejectedValue(new Error('identity unavailable')),
|
||||
});
|
||||
const ack = jest.fn();
|
||||
await gateway.handleTimeSync({ sequence: 2 }, ack, {
|
||||
data: { matchId },
|
||||
} as never);
|
||||
expect(ack).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
ok: true,
|
||||
sequence: 2,
|
||||
currentServerTimestampMS: 1780000000000,
|
||||
auctionStateUnavailable: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('rate limits excessive bid requests from the same socket', async () => {
|
||||
jest.spyOn(Date, 'now').mockReturnValue(1780000000000);
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
|
||||
@@ -114,6 +114,14 @@ const REACTION_KINDS: Record<AuctionReactionKind, true> = {
|
||||
sad: true,
|
||||
fire: true,
|
||||
celebrate: true,
|
||||
eyes: true,
|
||||
thinking: true,
|
||||
'skull-crossbones': true,
|
||||
poop: true,
|
||||
pray: true,
|
||||
'sweat-smile': true,
|
||||
money: true,
|
||||
trophy: true,
|
||||
};
|
||||
const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8;
|
||||
const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED';
|
||||
@@ -172,9 +180,11 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
public async handleJoin(
|
||||
@ConnectedSocket() socket: AuctionSocket,
|
||||
@MessageBody() payload: JoinAuctionPayload,
|
||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||
) {
|
||||
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
|
||||
this.emitError(socket, 'Invalid matchId.');
|
||||
ack?.({ ok: false, code: 'INVALID_MATCH_ID' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -193,8 +203,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
);
|
||||
this.emitChatHistory(socket, auction);
|
||||
socket.emit('state', serializeRealtimeAuction(auctionState));
|
||||
ack?.({ ok: true });
|
||||
} catch (error) {
|
||||
const rejection = this.resolveErrorPayload(error);
|
||||
ack?.({ ...rejection, ok: false });
|
||||
if (rejection.code === 'AUCTION_STATE_RECOVERING') {
|
||||
socket.emit('state-pending', { retryAfterMS: 500 });
|
||||
} else {
|
||||
@@ -339,14 +351,27 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
public async handleTimeSync(
|
||||
@MessageBody() payload: TimeSyncPayload,
|
||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||
@ConnectedSocket() socket?: AuctionSocket,
|
||||
) {
|
||||
const receivedAtMonotonicMS = performance.now();
|
||||
try {
|
||||
const currentServerTimestampMS =
|
||||
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
||||
const [currentServerTimestampMS, auctionState] = await Promise.all([
|
||||
this.auctionRedisService.getCurrentRedisTimestampMS(),
|
||||
socket?.data.matchId
|
||||
? this.auctionService
|
||||
.getRealtimeIdentity(socket.data.matchId)
|
||||
.catch(() => undefined)
|
||||
: undefined,
|
||||
]);
|
||||
ack?.({
|
||||
clientSentAtTimestampMS: payload?.clientSentAtTimestampMS,
|
||||
currentServerTimestampMS,
|
||||
...(socket?.data.matchId
|
||||
? {
|
||||
auctionState,
|
||||
auctionStateUnavailable: auctionState === undefined,
|
||||
}
|
||||
: {}),
|
||||
ok: true,
|
||||
sequence: payload?.sequence,
|
||||
serverProcessingDurationMS:
|
||||
|
||||
@@ -215,8 +215,7 @@ describe('AuctionService', () => {
|
||||
expect(auctionRedisCommandService.placeBid).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('lists auction history with a summary projection and short local cache', async () => {
|
||||
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1000);
|
||||
it('reads committed history on every node without retaining a local cache', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
@@ -242,7 +241,7 @@ describe('AuctionService', () => {
|
||||
const historySort = jest.fn().mockReturnValue({ limit: historyLimit });
|
||||
const historySelect = jest.fn().mockReturnValue({ sort: historySort });
|
||||
const historyFind = jest.fn().mockReturnValue({ select: historySelect });
|
||||
const { service } = createService({
|
||||
const models = {
|
||||
auctionHistory: {
|
||||
find: historyFind,
|
||||
},
|
||||
@@ -251,7 +250,9 @@ describe('AuctionService', () => {
|
||||
select: jest.fn().mockResolvedValue(match),
|
||||
}),
|
||||
},
|
||||
});
|
||||
};
|
||||
const { service } = createService(models);
|
||||
const otherNode = createService(models).service;
|
||||
|
||||
await expect(
|
||||
service.listHistory({ matchId, communityId }),
|
||||
@@ -271,7 +272,7 @@ describe('AuctionService', () => {
|
||||
]);
|
||||
await service.listHistory({ matchId, communityId });
|
||||
|
||||
expect(historyFind).toHaveBeenCalledTimes(1);
|
||||
expect(historyFind).toHaveBeenCalledTimes(2);
|
||||
expect(historySelect).toHaveBeenCalledWith({
|
||||
_id: 0,
|
||||
action: 1,
|
||||
@@ -281,9 +282,17 @@ describe('AuctionService', () => {
|
||||
expect(historySort).toHaveBeenCalledWith({ sequence: -1 });
|
||||
expect(historyLimit).toHaveBeenCalledWith(100);
|
||||
|
||||
nowSpy.mockReturnValue(3101);
|
||||
await service.listHistory({ matchId, communityId });
|
||||
expect(historyFind).toHaveBeenCalledTimes(2);
|
||||
historyExec.mockResolvedValue([
|
||||
{ action: 'undo', sequence: 5, takenAt: new Date() },
|
||||
historyRows[1],
|
||||
]);
|
||||
const [firstNodeHistory, secondNodeHistory] = await Promise.all([
|
||||
service.listHistory({ matchId, communityId }),
|
||||
otherNode.listHistory({ matchId, communityId }),
|
||||
]);
|
||||
expect(firstNodeHistory.map(({ sequence }) => sequence)).toEqual([5, 3]);
|
||||
expect(secondNodeHistory).toEqual(firstNodeHistory);
|
||||
expect(historyFind).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it('starts an auction without reserving tournament codes before teams are complete', async () => {
|
||||
@@ -1895,7 +1904,7 @@ describe('AuctionService', () => {
|
||||
expect(findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ matchId, 'chatMessages.id': { $ne: appended.message.id } },
|
||||
{ $push: { chatMessages: { $each: [appended.message], $slice: -200 } } },
|
||||
{ new: true },
|
||||
{ returnDocument: 'after' },
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
Optional,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import type { AuctionStateIdentity } from '@lolympus/contracts';
|
||||
import {
|
||||
AuctionLifecycleLock,
|
||||
AuctionLifecycleBusyError,
|
||||
@@ -69,8 +70,6 @@ const AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT = 500;
|
||||
const AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS = 5 * 60 * 1000;
|
||||
const AUCTION_ACTION_REQUEST_LEASE_DURATION_MS = 15 * 1000;
|
||||
const AUCTION_HISTORY_LIST_LIMIT = 100;
|
||||
const AUCTION_HISTORY_LIST_CACHE_TTL_MS = 2 * 1000;
|
||||
const AUCTION_HISTORY_LIST_CACHE_MAX_ENTRIES = 256;
|
||||
|
||||
interface StartAuctionParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
@@ -163,11 +162,6 @@ interface AuctionHistorySummaryRecord {
|
||||
takenAt: Date;
|
||||
}
|
||||
|
||||
interface AuctionHistoryListCacheEntry {
|
||||
entries: AuctionHistoryView[];
|
||||
expiresAtTimestampMS: number;
|
||||
}
|
||||
|
||||
export type AuctionStateResponse = AuctionDocument | Record<string, unknown>;
|
||||
|
||||
export interface AuctionBidDeltaResponse {
|
||||
@@ -211,10 +205,6 @@ function isMongoDuplicateKeyError(error: unknown): boolean {
|
||||
@Injectable()
|
||||
export class AuctionService {
|
||||
private readonly logger = new Logger(AuctionService.name);
|
||||
private readonly auctionHistoryListCache = new Map<
|
||||
string,
|
||||
AuctionHistoryListCacheEntry
|
||||
>();
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
@@ -579,6 +569,12 @@ export class AuctionService {
|
||||
}
|
||||
}
|
||||
|
||||
public getRealtimeIdentity(
|
||||
matchId: string,
|
||||
): Promise<AuctionStateIdentity | null> {
|
||||
return this.auctionRedisStateReaderService.readLiveStateIdentity(matchId);
|
||||
}
|
||||
|
||||
private async getStateByMatchIdOnce(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
): Promise<AuctionStateResponse> {
|
||||
@@ -706,7 +702,7 @@ export class AuctionService {
|
||||
},
|
||||
},
|
||||
},
|
||||
{ new: true },
|
||||
{ returnDocument: 'after' },
|
||||
);
|
||||
if (auction) return { auction, message, created: true };
|
||||
|
||||
@@ -737,10 +733,6 @@ export class AuctionService {
|
||||
throw new BadRequestException('Match does not belong to this community.');
|
||||
}
|
||||
|
||||
const cacheKey = this.buildAuctionHistoryListCacheKey(params);
|
||||
const cachedHistory = this.getCachedAuctionHistoryList(cacheKey);
|
||||
if (cachedHistory) return cachedHistory;
|
||||
|
||||
const entries = (await AuctionHistoryModel.find({ matchId: params.matchId })
|
||||
.select({ _id: 0, action: 1, sequence: 1, takenAt: 1 })
|
||||
.sort({ sequence: -1 })
|
||||
@@ -754,49 +746,9 @@ export class AuctionService {
|
||||
actionLabel: this.formatHistoryActionLabel(entry.action),
|
||||
takenAt: entry.takenAt,
|
||||
}));
|
||||
this.setCachedAuctionHistoryList(cacheKey, history);
|
||||
return history;
|
||||
}
|
||||
|
||||
private buildAuctionHistoryListCacheKey(params: {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
}): string {
|
||||
return `${params.communityId.toString()}:${params.matchId.toString()}`;
|
||||
}
|
||||
|
||||
private getCachedAuctionHistoryList(
|
||||
cacheKey: string,
|
||||
): AuctionHistoryView[] | null {
|
||||
const cached = this.auctionHistoryListCache.get(cacheKey);
|
||||
if (!cached) return null;
|
||||
if (cached.expiresAtTimestampMS <= Date.now()) {
|
||||
this.auctionHistoryListCache.delete(cacheKey);
|
||||
return null;
|
||||
}
|
||||
return cached.entries;
|
||||
}
|
||||
|
||||
private setCachedAuctionHistoryList(
|
||||
cacheKey: string,
|
||||
entries: AuctionHistoryView[],
|
||||
): void {
|
||||
if (
|
||||
!this.auctionHistoryListCache.has(cacheKey) &&
|
||||
this.auctionHistoryListCache.size >=
|
||||
AUCTION_HISTORY_LIST_CACHE_MAX_ENTRIES
|
||||
) {
|
||||
const oldestKey = this.auctionHistoryListCache.keys().next().value as
|
||||
| string
|
||||
| undefined;
|
||||
if (oldestKey) this.auctionHistoryListCache.delete(oldestKey);
|
||||
}
|
||||
this.auctionHistoryListCache.set(cacheKey, {
|
||||
entries,
|
||||
expiresAtTimestampMS: Date.now() + AUCTION_HISTORY_LIST_CACHE_TTL_MS,
|
||||
});
|
||||
}
|
||||
|
||||
public async openBidding(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
actionRequest: AuctionStructureActionRequestParams = {},
|
||||
|
||||
@@ -30,17 +30,23 @@ function makeService(
|
||||
|
||||
describe('AuctionRedisStateReaderService', () => {
|
||||
it('reads live state identity', async () => {
|
||||
const { service, sendCommand } = makeService([['life-1', '7']]);
|
||||
const { service, sendCommand } = makeService([
|
||||
['life-1', '7', '3', 'transition-1'],
|
||||
]);
|
||||
|
||||
await expect(service.readLiveStateIdentity('match-1')).resolves.toEqual({
|
||||
auctionLifecycleId: 'life-1',
|
||||
revision: 7,
|
||||
matchSideEffectRevision: 3,
|
||||
matchSideEffectTransitionId: 'transition-1',
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledWith([
|
||||
'HMGET',
|
||||
'auction:match-1:liveAuctionState',
|
||||
'auctionLifecycleId',
|
||||
'revision',
|
||||
'matchSideEffectRevision',
|
||||
'matchSideEffectTransitionId',
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -118,7 +124,9 @@ describe('AuctionRedisStateReaderService', () => {
|
||||
|
||||
expect(view).toMatchObject({
|
||||
auctionBidHistory: [{ bidPointAmount: 100, bidderTeamIndex: 2 }],
|
||||
auctionEngineVersion: 'redis-v1',
|
||||
auctionLifecycleId: 'life-1',
|
||||
matchId: 'match-1',
|
||||
auctionTeams: [{ teamIndex: 1 }],
|
||||
canPlaceBidInCurrentBidRound: false,
|
||||
currentHighestBidderTeamIndex: 2,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { AuctionStateIdentity } from '@lolympus/contracts';
|
||||
import { buildAuctionRedisKeys } from './auction-redis.keys';
|
||||
import { AuctionRedisService } from './auction-redis.service';
|
||||
import { assembleAuctionViewFromRedisState } from './auction-redis.state';
|
||||
@@ -17,10 +18,7 @@ const NUMERIC_LIVE_STATE_FIELDS = new Set([
|
||||
'revision',
|
||||
]);
|
||||
|
||||
export interface AuctionRedisLiveStateIdentity {
|
||||
auctionLifecycleId?: string;
|
||||
revision?: number;
|
||||
}
|
||||
export type AuctionRedisLiveStateIdentity = AuctionStateIdentity;
|
||||
|
||||
export interface AuctionRedisBidContext {
|
||||
auctionLifecycleId: string;
|
||||
@@ -49,6 +47,8 @@ export class AuctionRedisStateReaderService {
|
||||
keys.liveStateKey,
|
||||
'auctionLifecycleId',
|
||||
'revision',
|
||||
'matchSideEffectRevision',
|
||||
'matchSideEffectTransitionId',
|
||||
]);
|
||||
if (!Array.isArray(reply)) return null;
|
||||
const auctionLifecycleId =
|
||||
@@ -61,6 +61,12 @@ export class AuctionRedisStateReaderService {
|
||||
return {
|
||||
auctionLifecycleId,
|
||||
revision: Number.isFinite(revision) ? revision : undefined,
|
||||
matchSideEffectRevision:
|
||||
reply[2] !== null && Number.isFinite(Number(reply[2]))
|
||||
? Number(reply[2])
|
||||
: undefined,
|
||||
matchSideEffectTransitionId:
|
||||
typeof reply[3] === 'string' && reply[3] ? reply[3] : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -147,6 +153,7 @@ export class AuctionRedisStateReaderService {
|
||||
structureState: parseJsonRecord(structureStateJson),
|
||||
});
|
||||
view.matchId = matchId;
|
||||
view.auctionEngineVersion = 'redis-v1';
|
||||
if (options.includeInternalLiveStateFields) {
|
||||
view.redisInternalPhase = liveState.phase;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { connect } from 'nats';
|
||||
import type { NatsConnection } from 'nats';
|
||||
import { connect, type NatsConnection } from '@nats-io/transport-node';
|
||||
import { SecretModule } from '../secret/secret.module';
|
||||
import { SecretService } from '../secret/secret.service';
|
||||
import { NATS_CLIENT } from './nats.constants';
|
||||
|
||||
@@ -2,20 +2,21 @@ import { Inject, Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
|
||||
import {
|
||||
AckPolicy,
|
||||
DeliverPolicy,
|
||||
nanos,
|
||||
jetstream,
|
||||
jetstreamManager,
|
||||
ReplayPolicy,
|
||||
RetentionPolicy,
|
||||
StorageType,
|
||||
StringCodec,
|
||||
} from 'nats';
|
||||
import type {
|
||||
ConsumerMessages,
|
||||
JsMsg,
|
||||
Msg,
|
||||
NatsConnection,
|
||||
PubAck,
|
||||
Subscription,
|
||||
} from 'nats';
|
||||
type ConsumerMessages,
|
||||
type JsMsg,
|
||||
type PubAck,
|
||||
} from '@nats-io/jetstream';
|
||||
import {
|
||||
nanos,
|
||||
type Msg,
|
||||
type NatsConnection,
|
||||
type Subscription,
|
||||
} from '@nats-io/transport-node';
|
||||
import { NATS_CLIENT } from './nats.constants';
|
||||
|
||||
export type NatsMessageHandler<T = unknown> = (
|
||||
@@ -64,7 +65,6 @@ const JET_STREAM_CONSUMER_RESTART_DELAY_MILLISECONDS = 1_000;
|
||||
@Injectable()
|
||||
export class NatsService implements OnModuleDestroy {
|
||||
private readonly logger = new Logger(NatsService.name);
|
||||
private readonly stringCodec = StringCodec();
|
||||
private readonly subscriptions = new Set<Subscription>();
|
||||
private readonly jetStreamConsumers = new Set<ConsumerMessages>();
|
||||
private isDestroying = false;
|
||||
@@ -108,10 +108,7 @@ export class NatsService implements OnModuleDestroy {
|
||||
}
|
||||
|
||||
public async publish<T = unknown>(subject: string, data: T): Promise<void> {
|
||||
this.natsClient.publish(
|
||||
subject,
|
||||
this.stringCodec.encode(JSON.stringify(data)),
|
||||
);
|
||||
this.natsClient.publish(subject, JSON.stringify(data));
|
||||
await this.natsClient.flush();
|
||||
}
|
||||
|
||||
@@ -133,19 +130,16 @@ export class NatsService implements OnModuleDestroy {
|
||||
data: T,
|
||||
options?: { messageId?: string; timeoutMs?: number },
|
||||
): Promise<PubAck> {
|
||||
const ack = await this.natsClient
|
||||
.jetstream()
|
||||
.publish(subject, this.stringCodec.encode(JSON.stringify(data)), {
|
||||
msgID: options?.messageId,
|
||||
timeout: options?.timeoutMs ?? 5000,
|
||||
});
|
||||
return ack;
|
||||
return jetstream(this.natsClient).publish(subject, JSON.stringify(data), {
|
||||
msgID: options?.messageId,
|
||||
timeout: options?.timeoutMs ?? 5000,
|
||||
});
|
||||
}
|
||||
|
||||
public async ensureJetStreamStream(
|
||||
options: JetStreamStreamOptions,
|
||||
): Promise<void> {
|
||||
const manager = await this.natsClient.jetstreamManager();
|
||||
const manager = await jetstreamManager(this.natsClient);
|
||||
const config = {
|
||||
name: options.name,
|
||||
subjects: options.subjects,
|
||||
@@ -173,7 +167,7 @@ export class NatsService implements OnModuleDestroy {
|
||||
public async ensureJetStreamConsumer(
|
||||
options: JetStreamConsumerOptions,
|
||||
): Promise<void> {
|
||||
const manager = await this.natsClient.jetstreamManager();
|
||||
const manager = await jetstreamManager(this.natsClient);
|
||||
const config = {
|
||||
durable_name: options.durable,
|
||||
name: options.durable,
|
||||
@@ -206,9 +200,10 @@ export class NatsService implements OnModuleDestroy {
|
||||
): Promise<void> {
|
||||
while (!this.isDestroying) {
|
||||
try {
|
||||
const consumer = await this.natsClient
|
||||
.jetstream()
|
||||
.consumers.get(options.stream, options.durable);
|
||||
const consumer = await jetstream(this.natsClient).consumers.get(
|
||||
options.stream,
|
||||
options.durable,
|
||||
);
|
||||
const messages = await consumer.consume({
|
||||
max_messages: options.maxMessages ?? 10,
|
||||
expires: options.expiresMs ?? 30000,
|
||||
@@ -263,8 +258,7 @@ export class NatsService implements OnModuleDestroy {
|
||||
): Promise<void> {
|
||||
let data: T;
|
||||
try {
|
||||
const decoded = this.stringCodec.decode(msg.data);
|
||||
data = JSON.parse(decoded) as T;
|
||||
data = msg.json<T>();
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Failed to decode NATS message on subject="${msg.subject}": ${
|
||||
@@ -292,7 +286,7 @@ export class NatsService implements OnModuleDestroy {
|
||||
): Promise<void> {
|
||||
let data: T;
|
||||
try {
|
||||
data = JSON.parse(msg.string()) as T;
|
||||
data = msg.json<T>();
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Terminating undecodable JetStream message subject="${msg.subject}" stream="${options.stream}": ${
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import os from 'node:os';
|
||||
import mongoose from 'mongoose';
|
||||
import { AuctionService } from '../src/modules/auction/auction.service';
|
||||
import { AuctionDurabilityScheduler } from '../src/modules/auction/auction-durability.scheduler';
|
||||
@@ -16,7 +17,7 @@ import {
|
||||
} from '../src/modules/global/database/schema';
|
||||
|
||||
let connection: mongoose.Connection;
|
||||
let models: Record<string, mongoose.Model<any>>;
|
||||
let models: ReturnType<typeof createModels>;
|
||||
const redis = {
|
||||
acquireTokenLock: async () => true,
|
||||
releaseTokenLock: async () => true,
|
||||
@@ -27,19 +28,8 @@ const redis = {
|
||||
}),
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
if (
|
||||
process.env.MONGO_TEST_ISOLATED !== '1' ||
|
||||
!process.env.MONGO_TEST_URL?.startsWith('mongodb://127.0.0.1:')
|
||||
)
|
||||
throw new Error('Use test:mongodb with an isolated local replica set.');
|
||||
connection = await mongoose
|
||||
.createConnection(process.env.MONGO_TEST_URL, {
|
||||
autoIndex: false,
|
||||
autoCreate: false,
|
||||
})
|
||||
.asPromise();
|
||||
models = {
|
||||
function createModels(connection: mongoose.Connection) {
|
||||
return {
|
||||
match: connection.model('match', MatchSchema),
|
||||
auction: connection.model('auction', AuctionSchema),
|
||||
auctionHistory: connection.model(
|
||||
@@ -56,12 +46,29 @@ beforeAll(async () => {
|
||||
AuctionBidRecordSchema,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
if (
|
||||
process.env.MONGO_TEST_ISOLATED !== '1' ||
|
||||
!process.env.MONGO_TEST_URL?.startsWith('mongodb://127.0.0.1:')
|
||||
)
|
||||
throw new Error('Use test:mongodb with an isolated local replica set.');
|
||||
connection = await mongoose
|
||||
.createConnection(process.env.MONGO_TEST_URL, {
|
||||
autoIndex: false,
|
||||
autoCreate: false,
|
||||
// NODE-7832: the driver's default OS adapter breaks the Jest handshake.
|
||||
runtimeAdapters: { os },
|
||||
})
|
||||
.asPromise();
|
||||
models = createModels(connection);
|
||||
await Promise.all(
|
||||
Object.values(models).map((model) => model.createCollection()),
|
||||
);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await Promise.all(Object.values(models).map((model) => model.deleteMany({})));
|
||||
await Promise.all(Object.values(models).map((model) => model.deleteMany()));
|
||||
});
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
afterAll(async () => {
|
||||
@@ -84,7 +91,6 @@ async function fixture(reserved: boolean) {
|
||||
participants: [],
|
||||
tournamentCodeIds: reserved ? [codeId] : [],
|
||||
gameSchedule: [],
|
||||
__v: 0,
|
||||
});
|
||||
await models.auction.collection.insertOne({
|
||||
_id: auctionId,
|
||||
@@ -104,7 +110,7 @@ async function fixture(reserved: boolean) {
|
||||
matchId,
|
||||
});
|
||||
const database = {
|
||||
getModel: async (name: string) => models[name],
|
||||
getModel: async (name: keyof typeof models) => models[name],
|
||||
createSession: () => connection.startSession(),
|
||||
};
|
||||
const codes = new TournamentCodeService(database as never, redis as never);
|
||||
@@ -611,10 +617,7 @@ it('reads an uncommitted Match in the provided session when cancelling polling b
|
||||
{ session },
|
||||
);
|
||||
expect(await models.match.findById(created._id)).toBeNull();
|
||||
await f.results.cancelPolling(
|
||||
created._id as mongoose.Types.ObjectId,
|
||||
session,
|
||||
);
|
||||
await f.results.cancelPolling(created._id, session);
|
||||
expect(
|
||||
await models.match.findById(created._id).session(session),
|
||||
).not.toBeNull();
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
* text eol=lf
|
||||
@@ -0,0 +1 @@
|
||||
results/
|
||||
@@ -0,0 +1,13 @@
|
||||
FROM node:26-bookworm-slim
|
||||
RUN npm install --global pnpm@10.4.1
|
||||
WORKDIR /workspace
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||
COPY packages/contracts ./packages/contracts
|
||||
COPY apps/api/package.json ./apps/api/package.json
|
||||
COPY apps/web/package.json ./apps/web/package.json
|
||||
RUN pnpm install --frozen-lockfile --filter api --filter web --ignore-scripts
|
||||
COPY apps/api ./apps/api
|
||||
COPY apps/web/src/api ./apps/web/src/api
|
||||
WORKDIR /workspace/apps/api
|
||||
ENV NODE_ENV=test NEW_RELIC_ENABLED=false
|
||||
CMD ["node", "-r", "ts-node/register/transpile-only", "test/auction-cluster/node.ts"]
|
||||
@@ -0,0 +1,61 @@
|
||||
x-app: &app
|
||||
image: ${COMPOSE_PROJECT_NAME}-app
|
||||
build:
|
||||
context: ../../../..
|
||||
dockerfile: apps/api/test/auction-cluster/Dockerfile
|
||||
environment: &environment
|
||||
MONGO_TEST_URL: mongodb://mongo:27017/auction_cluster?replicaSet=auction_cluster
|
||||
REDIS_TEST_URL: redis://redis-proxy:6379
|
||||
NODE_ENV: test
|
||||
NEW_RELIC_ENABLED: 'false'
|
||||
volumes:
|
||||
- ./results:/results
|
||||
networks: [cluster]
|
||||
mem_limit: 1g
|
||||
|
||||
services:
|
||||
redis:
|
||||
image: redis:8-alpine
|
||||
command: [redis-server, --save, '', --appendonly, 'no']
|
||||
networks: [cluster]
|
||||
mem_limit: 256m
|
||||
mongo:
|
||||
# MongoDB 8+ refuses the test host's Linux 7.0.0 kernel (SERVER-121912).
|
||||
image: ${MONGO_TEST_IMAGE:-mongo:7.0}
|
||||
command:
|
||||
[
|
||||
mongod,
|
||||
--replSet,
|
||||
auction_cluster,
|
||||
--bind_ip_all,
|
||||
--wiredTigerCacheSizeGB,
|
||||
'0.25',
|
||||
]
|
||||
networks: [cluster]
|
||||
mem_limit: 768m
|
||||
redis-proxy:
|
||||
<<: *app
|
||||
command: [node, test/auction-cluster/fault-proxy.mjs]
|
||||
mem_limit: 128m
|
||||
api-a:
|
||||
<<: *app
|
||||
environment:
|
||||
<<: *environment
|
||||
CLUSTER_NODE: api-a
|
||||
api-b:
|
||||
<<: *app
|
||||
environment:
|
||||
<<: *environment
|
||||
CLUSTER_NODE: api-b
|
||||
lb:
|
||||
image: nginx:stable-alpine
|
||||
volumes:
|
||||
- ./nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
networks: [cluster]
|
||||
mem_limit: 128m
|
||||
runner:
|
||||
<<: *app
|
||||
command: [node, test/auction-cluster/run.mjs, verify]
|
||||
|
||||
networks:
|
||||
cluster: {}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { createServer as createTcpServer, connect } from 'node:net';
|
||||
import { createServer as createHttpServer } from 'node:http';
|
||||
|
||||
// Real TCP connections; only connections issuing SUBSCRIBE/PSUBSCRIBE are cut.
|
||||
// Redis commands, TIME and PUBLISH continue through the same proxy.
|
||||
let blocked = false;
|
||||
let dropped = 0;
|
||||
const connections = new Set();
|
||||
createTcpServer((socket) => {
|
||||
const upstream = connect(6379, 'redis');
|
||||
const connection = { socket, upstream, subscriber: false, prefix: '' };
|
||||
connections.add(connection);
|
||||
const close = () => {
|
||||
socket.destroy();
|
||||
upstream.destroy();
|
||||
connections.delete(connection);
|
||||
};
|
||||
socket.on('error', close);
|
||||
upstream.on('error', close);
|
||||
socket.on('close', close);
|
||||
upstream.on('close', close);
|
||||
socket.on('data', (chunk) => {
|
||||
connection.prefix = (connection.prefix + chunk.toString('utf8')).slice(
|
||||
-4096,
|
||||
);
|
||||
if (/\r\n(?:p?subscribe|ssubscribe)\r\n/i.test(connection.prefix)) {
|
||||
connection.subscriber = true;
|
||||
}
|
||||
if (blocked && connection.subscriber) {
|
||||
dropped += 1;
|
||||
close();
|
||||
} else upstream.write(chunk);
|
||||
});
|
||||
upstream.on('data', (chunk) => socket.write(chunk));
|
||||
}).listen(6379, '0.0.0.0');
|
||||
|
||||
createHttpServer((request, response) => {
|
||||
if (request.method === 'POST' && request.url === '/block') {
|
||||
blocked = true;
|
||||
for (const connection of connections) {
|
||||
if (!connection.subscriber) continue;
|
||||
dropped += 1;
|
||||
connection.socket.destroy();
|
||||
connection.upstream.destroy();
|
||||
}
|
||||
} else if (request.method === 'POST' && request.url === '/restore') {
|
||||
blocked = false;
|
||||
} else if (request.url !== '/status') {
|
||||
response.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
response.setHeader('content-type', 'application/json');
|
||||
response.end(
|
||||
JSON.stringify({
|
||||
blocked,
|
||||
dropped,
|
||||
subscribers: [...connections].filter((c) => c.subscriber).length,
|
||||
}),
|
||||
);
|
||||
}).listen(8081, '0.0.0.0');
|
||||
@@ -0,0 +1,18 @@
|
||||
events {}
|
||||
http {
|
||||
upstream auction {
|
||||
server api-a:3000;
|
||||
server api-b:3000;
|
||||
}
|
||||
server {
|
||||
listen 8080;
|
||||
location / {
|
||||
proxy_pass http://auction;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_read_timeout 120s;
|
||||
add_header X-Cluster-Upstream $upstream_addr always;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import 'reflect-metadata';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { Body, Controller, Get, Module, Post } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import mongoose from 'mongoose';
|
||||
import { createClient } from 'redis';
|
||||
import type { Namespace } from 'socket.io';
|
||||
import { RedisIoAdapter } from '../../src/redis-io.adapter';
|
||||
import { AuctionController } from '../../src/modules/auction/auction.controller';
|
||||
import { AuctionGateway } from '../../src/modules/auction/auction.gateway';
|
||||
import { AuctionEventBusService } from '../../src/modules/auction/auction-event-bus.service';
|
||||
import { AuctionService } from '../../src/modules/auction/auction.service';
|
||||
import { AuctionBidArchiveService } from '../../src/modules/auction/auction-bid-archive.service';
|
||||
import {
|
||||
AuctionDurabilityScheduler,
|
||||
type AuctionDurabilityPayload,
|
||||
} from '../../src/modules/auction/auction-durability.scheduler';
|
||||
import { AuctionRedisService } from '../../src/modules/auction/redis/auction-redis.service';
|
||||
import { AuctionRedisCommandService } from '../../src/modules/auction/redis/auction-redis-command.service';
|
||||
import { AuctionRedisStateReaderService } from '../../src/modules/auction/redis/auction-redis-state-reader.service';
|
||||
import { AuthService } from '../../src/modules/auth/auth.service';
|
||||
import { JwtService } from '../../src/modules/auth/jwt.service';
|
||||
import { IdentityService } from '../../src/modules/auth/identity.service';
|
||||
import { ConnectionService } from '../../src/modules/global/database/connection.service';
|
||||
import {
|
||||
AuctionSchema,
|
||||
AuctionHistoryEntrySchema,
|
||||
AuctionSideEffectApplicationSchema,
|
||||
MatchSchema,
|
||||
} from '../../src/modules/global/database/schema';
|
||||
|
||||
async function bootstrap() {
|
||||
if (
|
||||
!process.env.MONGO_TEST_URL?.startsWith(
|
||||
'mongodb://mongo:27017/auction_cluster?',
|
||||
) ||
|
||||
process.env.REDIS_TEST_URL !== 'redis://redis-proxy:6379'
|
||||
) {
|
||||
throw new Error(
|
||||
'This test node only accepts the isolated Compose services.',
|
||||
);
|
||||
}
|
||||
const fixture = JSON.parse(
|
||||
await readFile('/results/fixture.json', 'utf8'),
|
||||
) as { communityId: string };
|
||||
const connection = await mongoose
|
||||
.createConnection(process.env.MONGO_TEST_URL, { autoIndex: false })
|
||||
.asPromise();
|
||||
const models = {
|
||||
match: connection.model('match', MatchSchema),
|
||||
auction: connection.model('auction', AuctionSchema),
|
||||
auctionHistory: connection.model(
|
||||
'auctionHistory',
|
||||
AuctionHistoryEntrySchema,
|
||||
),
|
||||
auctionSideEffectApplication: connection.model(
|
||||
'auctionSideEffectApplication',
|
||||
AuctionSideEffectApplicationSchema,
|
||||
),
|
||||
};
|
||||
let releaseCommit: (() => void) | undefined;
|
||||
let commitGate: Promise<void> | undefined;
|
||||
let commitsWaiting = 0;
|
||||
const database = {
|
||||
getModel: async (name: keyof typeof models) => {
|
||||
if (!models[name]) throw new Error(`Unexpected test model: ${name}`);
|
||||
return models[name];
|
||||
},
|
||||
createSession: async () => {
|
||||
const session = await connection.startSession();
|
||||
const commit = session.commitTransaction.bind(session);
|
||||
session.commitTransaction = async () => {
|
||||
if (commitGate) {
|
||||
commitsWaiting += 1;
|
||||
await commitGate;
|
||||
commitsWaiting -= 1;
|
||||
}
|
||||
await commit();
|
||||
};
|
||||
return session;
|
||||
},
|
||||
};
|
||||
const client = createClient({ url: process.env.REDIS_TEST_URL });
|
||||
client.on('error', (error) =>
|
||||
console.error('command-client:', error.message),
|
||||
);
|
||||
await client.connect();
|
||||
const redis = new AuctionRedisService(client);
|
||||
const commands = new AuctionRedisCommandService(redis);
|
||||
const reader = new AuctionRedisStateReaderService(redis);
|
||||
const bus = new AuctionEventBusService();
|
||||
const service = new AuctionService(
|
||||
database as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
redis,
|
||||
commands,
|
||||
reader,
|
||||
bus,
|
||||
);
|
||||
// Explicit draining lets the test hold real Mongo commits and reorder durable
|
||||
// payloads; no in-memory database or fake Redis adapter is involved.
|
||||
const scheduler = new AuctionDurabilityScheduler(
|
||||
database as never,
|
||||
redis,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
bus,
|
||||
reader,
|
||||
service,
|
||||
);
|
||||
|
||||
@Controller('_cluster')
|
||||
class ControlController {
|
||||
@Get('health') health() {
|
||||
const namespace = Reflect.get(gateway, 'server') as Namespace;
|
||||
return {
|
||||
node: process.env.CLUSTER_NODE,
|
||||
sockets: [...namespace.sockets.keys()],
|
||||
pid: process.pid,
|
||||
commitsWaiting,
|
||||
};
|
||||
}
|
||||
@Post('hold-commit') hold() {
|
||||
if (commitGate) throw new Error('Commit already held');
|
||||
commitGate = new Promise<void>((resolve) => {
|
||||
releaseCommit = resolve;
|
||||
});
|
||||
return { held: true };
|
||||
}
|
||||
@Post('release-commit') release() {
|
||||
releaseCommit?.();
|
||||
commitGate = undefined;
|
||||
releaseCommit = undefined;
|
||||
return { released: true };
|
||||
}
|
||||
@Post('drain') drain() {
|
||||
return scheduler.processDueDurabilityPayloads(100);
|
||||
}
|
||||
@Post('apply') async apply(@Body() payload: AuctionDurabilityPayload) {
|
||||
await scheduler.applyDurabilityPayload(payload);
|
||||
return { applied: true };
|
||||
}
|
||||
}
|
||||
@Module({
|
||||
controllers: [AuctionController, ControlController],
|
||||
providers: [
|
||||
AuctionGateway,
|
||||
{ provide: AuctionService, useValue: service },
|
||||
{ provide: ConnectionService, useValue: database },
|
||||
{ provide: AuctionRedisService, useValue: redis },
|
||||
{ provide: AuctionEventBusService, useValue: bus },
|
||||
{ provide: AuctionBidArchiveService, useValue: {} },
|
||||
{
|
||||
provide: AuthService,
|
||||
useValue: { resolveDevUserById: async () => null },
|
||||
},
|
||||
{ provide: JwtService, useValue: {} },
|
||||
{ provide: IdentityService, useValue: {} },
|
||||
],
|
||||
})
|
||||
class TestModule {}
|
||||
const app = await NestFactory.create(TestModule, {
|
||||
logger: ['error', 'warn'],
|
||||
});
|
||||
// Identity-provider authentication is outside this transport/durability test.
|
||||
// The real controller's RolesGuard still checks this isolated fixture admin.
|
||||
app.use(
|
||||
(
|
||||
request: { user?: unknown },
|
||||
response: { setHeader(name: string, value: string): void },
|
||||
next: () => void,
|
||||
) => {
|
||||
request.user = {
|
||||
role: 'admin',
|
||||
communityId: new mongoose.Types.ObjectId(fixture.communityId),
|
||||
};
|
||||
response.setHeader(
|
||||
'X-Cluster-Node',
|
||||
process.env.CLUSTER_NODE ?? 'unknown',
|
||||
);
|
||||
next();
|
||||
},
|
||||
);
|
||||
const adapter = new RedisIoAdapter(app);
|
||||
await adapter.connectToRedis();
|
||||
app.useWebSocketAdapter(adapter);
|
||||
const gateway = app.get(AuctionGateway);
|
||||
await app.listen(3000, '0.0.0.0');
|
||||
console.log(`cluster node ready: ${process.env.CLUSTER_NODE}`);
|
||||
process.on('SIGTERM', () => {
|
||||
void app
|
||||
.close()
|
||||
.then(() => connection.close())
|
||||
.then(() => process.exit(0));
|
||||
});
|
||||
}
|
||||
void bootstrap().catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,641 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import { request } from 'node:http';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import mongoose from 'mongoose';
|
||||
import { createClient } from 'redis';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
require('ts-node/register/transpile-only');
|
||||
const {
|
||||
AuctionRedisService,
|
||||
} = require('../../src/modules/auction/redis/auction-redis.service.ts');
|
||||
const {
|
||||
AuctionRedisCommandService,
|
||||
} = require('../../src/modules/auction/redis/auction-redis-command.service.ts');
|
||||
const {
|
||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||
} = require('../../src/modules/auction/redis/auction-redis.keys.ts');
|
||||
const {
|
||||
MatchSchema,
|
||||
AuctionSchema,
|
||||
AuctionHistoryEntrySchema,
|
||||
AuctionSideEffectApplicationSchema,
|
||||
} = require('../../src/modules/global/database/schema.ts');
|
||||
const webRequire = createRequire(
|
||||
new URL('../../../web/package.json', import.meta.url),
|
||||
);
|
||||
const { io } = webRequire('socket.io-client');
|
||||
const { QueryClient, QueryObserver, environmentManager } = webRequire(
|
||||
'@tanstack/react-query',
|
||||
);
|
||||
const {
|
||||
createAuctionHeartbeatMonitor,
|
||||
shouldApplyPolledAuctionState,
|
||||
mergeAuctionState,
|
||||
} = await import('../../../web/src/api/auction-state.ts');
|
||||
const { createAuctionResyncRequester } =
|
||||
await import('../../../web/src/api/auction-resync.ts');
|
||||
const { AUCTION_SAFETY_POLL_INTERVAL_MS } =
|
||||
await import('../../../web/src/api/auction-polling.ts');
|
||||
|
||||
if (
|
||||
process.env.REDIS_TEST_URL !== 'redis://redis-proxy:6379' ||
|
||||
!process.env.MONGO_TEST_URL?.startsWith(
|
||||
'mongodb://mongo:27017/auction_cluster?',
|
||||
)
|
||||
) {
|
||||
throw new Error('Only the isolated Compose services are allowed.');
|
||||
}
|
||||
const redis = createClient({ url: 'redis://redis:6379' });
|
||||
redis.on('error', () => {});
|
||||
await redis.connect();
|
||||
const cleanup = [() => (redis.isOpen ? redis.quit() : undefined)];
|
||||
const report = {
|
||||
startedAt: new Date().toISOString(),
|
||||
checks: [],
|
||||
requests: [],
|
||||
limitation:
|
||||
'Real API processes, Nginx, Redis TCP faults and Mongo transactions; fixture identity replaces the external login provider. Client recovery uses production helpers and QueryObserver, without rendering the React page.',
|
||||
};
|
||||
|
||||
async function until(check, description, timeout = 15_000) {
|
||||
const deadline = Date.now() + timeout;
|
||||
let lastError;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const value = await check();
|
||||
if (value) return value;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
await delay(50);
|
||||
}
|
||||
throw new Error(
|
||||
`Timed out: ${description}${lastError ? `: ${lastError.message}` : ''}`,
|
||||
);
|
||||
}
|
||||
async function http(url, body) {
|
||||
const started = Date.now();
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = request(
|
||||
url,
|
||||
{
|
||||
method: body === undefined ? 'GET' : 'POST',
|
||||
agent: false,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on('end', () => {
|
||||
report.requests.push({
|
||||
url,
|
||||
node: res.headers['x-cluster-node'],
|
||||
status: res.statusCode,
|
||||
durationMS: Date.now() - started,
|
||||
});
|
||||
if (res.statusCode < 200 || res.statusCode >= 300)
|
||||
return reject(new Error(`${url}: ${res.statusCode} ${data}`));
|
||||
try {
|
||||
resolve({
|
||||
body: JSON.parse(data),
|
||||
node: res.headers['x-cluster-node'],
|
||||
});
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
req.setTimeout(10_000, () =>
|
||||
req.destroy(new Error(`HTTP timeout: ${url}`)),
|
||||
);
|
||||
req.on('error', reject);
|
||||
req.end(body === undefined ? undefined : JSON.stringify(body));
|
||||
});
|
||||
}
|
||||
const pass = (name, details = {}) => {
|
||||
report.checks.push({ name, passed: true, ...details });
|
||||
console.log(`PASS ${name} ${JSON.stringify(details)}`);
|
||||
};
|
||||
|
||||
async function initialize() {
|
||||
const admin = new mongoose.mongo.MongoClient(
|
||||
'mongodb://mongo:27017/?directConnection=true',
|
||||
{ serverSelectionTimeoutMS: 1000 },
|
||||
);
|
||||
await until(
|
||||
async () => {
|
||||
await admin.connect();
|
||||
return true;
|
||||
},
|
||||
'Mongo startup',
|
||||
60_000,
|
||||
);
|
||||
await admin.db('admin').command({
|
||||
replSetInitiate: {
|
||||
_id: 'auction_cluster',
|
||||
members: [{ _id: 0, host: 'mongo:27017' }],
|
||||
},
|
||||
});
|
||||
await until(
|
||||
async () =>
|
||||
(await admin.db('admin').command({ hello: 1 })).isWritablePrimary,
|
||||
'Mongo primary',
|
||||
60_000,
|
||||
);
|
||||
const build = await admin.db('admin').command({ buildInfo: 1 });
|
||||
await admin.close();
|
||||
const connection = await mongoose
|
||||
.createConnection(process.env.MONGO_TEST_URL, { autoIndex: false })
|
||||
.asPromise();
|
||||
try {
|
||||
const models = {
|
||||
match: connection.model('match', MatchSchema),
|
||||
auction: connection.model('auction', AuctionSchema),
|
||||
history: connection.model('auctionHistory', AuctionHistoryEntrySchema),
|
||||
sideEffects: connection.model(
|
||||
'auctionSideEffectApplication',
|
||||
AuctionSideEffectApplicationSchema,
|
||||
),
|
||||
};
|
||||
await Promise.all(
|
||||
Object.values(models).map((model) => model.createCollection()),
|
||||
);
|
||||
await models.history.createIndexes();
|
||||
const matchId = new mongoose.Types.ObjectId(),
|
||||
communityId = new mongoose.Types.ObjectId(),
|
||||
auctionId = new mongoose.Types.ObjectId();
|
||||
const lifecycle = `cluster:${matchId}`;
|
||||
const playerA = new mongoose.Types.ObjectId(),
|
||||
playerB = new mongoose.Types.ObjectId(),
|
||||
captain = new mongoose.Types.ObjectId();
|
||||
const structure = {
|
||||
auctionPlayerOrder: [
|
||||
{ userId: playerA.toString() },
|
||||
{ userId: playerB.toString() },
|
||||
],
|
||||
auctionTeams: [
|
||||
{
|
||||
teamIndex: 1,
|
||||
captainUserId: captain.toString(),
|
||||
remainingBidPointAmount: 1000,
|
||||
members: [],
|
||||
},
|
||||
],
|
||||
currentAuctionPlayerOrderIndex: 0,
|
||||
currentAuctionRound: 1,
|
||||
passedAuctionPlayerQueue: [],
|
||||
maximumBidRoundDurationSeconds: 600,
|
||||
bidRoundExtensionSeconds: 5,
|
||||
initialTeamBidPointAmount: 1000,
|
||||
topTierAuctionPriorityThreshold: 'NONE',
|
||||
manualTopTierAuctionPriorityUserIds: [],
|
||||
};
|
||||
await models.match.collection.insertOne({
|
||||
_id: matchId,
|
||||
communityId,
|
||||
title: 'Isolated cluster test',
|
||||
participants: [],
|
||||
teams: [],
|
||||
status: 'team-building',
|
||||
scheduledAt: new Date(),
|
||||
});
|
||||
await models.auction.collection.insertOne({
|
||||
_id: auctionId,
|
||||
matchId,
|
||||
auctionEngineVersion: 'redis-v1',
|
||||
auctionLifecycleId: lifecycle,
|
||||
phase: 'presenting',
|
||||
revision: 0,
|
||||
currentAuctionHistorySequence: 0,
|
||||
chatMessages: [],
|
||||
...structure,
|
||||
});
|
||||
const commands = new AuctionRedisCommandService(
|
||||
new AuctionRedisService(redis),
|
||||
);
|
||||
await commands.hydrateState(matchId.toString(), {
|
||||
matchId: matchId.toString(),
|
||||
auctionLifecycleId: lifecycle,
|
||||
phase: 'presenting',
|
||||
revision: 0,
|
||||
auctionHistorySequence: 0,
|
||||
maximumBidRoundDurationSeconds: 600,
|
||||
structureStateJson: JSON.stringify(structure),
|
||||
liveStatePatch: {
|
||||
currentAuctionPlayerOrderIndex: 0,
|
||||
currentBidRoundPlayerUserId: playerA.toString(),
|
||||
currentBidRoundId: 'initial',
|
||||
currentHighestBidPointAmount: 0,
|
||||
currentHighestBidderTeamIndex: -1,
|
||||
maximumBidRoundDurationSeconds: 600,
|
||||
bidRoundExtensionSeconds: 5,
|
||||
'team:1:captainUserId': captain.toString(),
|
||||
'team:1:remainingBidPointAmount': 1000,
|
||||
'team:1:assignedAuctionTeamMemberCount': 1,
|
||||
},
|
||||
});
|
||||
const fixture = {
|
||||
matchId: matchId.toString(),
|
||||
communityId: communityId.toString(),
|
||||
auctionId: auctionId.toString(),
|
||||
lifecycle,
|
||||
mongoVersion: build.version,
|
||||
redisVersion: (await redis.info('server')).match(
|
||||
/redis_version:([^\r\n]+)/,
|
||||
)?.[1],
|
||||
};
|
||||
await writeFile('/results/fixture.json', JSON.stringify(fixture, null, 2));
|
||||
console.log(
|
||||
`Initialized isolated MongoDB ${build.version} and Redis ${fixture.redisVersion}`,
|
||||
);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function verify() {
|
||||
const fixture = JSON.parse(await readFile('/results/fixture.json', 'utf8'));
|
||||
report.versions = {
|
||||
node: process.version,
|
||||
mongo: fixture.mongoVersion,
|
||||
redis: fixture.redisVersion,
|
||||
};
|
||||
const route = `/communities/${fixture.communityId}/matches/${fixture.matchId}/auction`;
|
||||
const url = `http://lb:8080${route}`;
|
||||
await until(
|
||||
async () => (await http('http://api-a:3000/_cluster/health')).body.node,
|
||||
'API A startup',
|
||||
60_000,
|
||||
);
|
||||
await until(
|
||||
async () => (await http('http://api-b:3000/_cluster/health')).body.node,
|
||||
'API B startup',
|
||||
60_000,
|
||||
);
|
||||
const routedNodes = new Set();
|
||||
for (let i = 0; i < 4; i += 1) routedNodes.add((await http(url)).node);
|
||||
assert.deepEqual([...routedNodes].sort(), ['api-a', 'api-b']);
|
||||
pass('Nginx routes real HTTP requests to both API processes');
|
||||
|
||||
async function connectViewer() {
|
||||
const socket = io('http://lb:8080/auction', {
|
||||
transports: ['websocket'],
|
||||
autoConnect: false,
|
||||
reconnection: false,
|
||||
});
|
||||
const viewer = {
|
||||
socket,
|
||||
state: null,
|
||||
states: [],
|
||||
histories: [],
|
||||
errors: [],
|
||||
};
|
||||
socket.on('state', (state) => {
|
||||
viewer.state = state;
|
||||
viewer.states.push(state);
|
||||
});
|
||||
socket.on('error', (error) => viewer.errors.push(error));
|
||||
socket.on('connect_error', (error) => viewer.errors.push(error.message));
|
||||
socket.on('history-updated', (event) => {
|
||||
void http(`${url}/history`)
|
||||
.then(({ body, node }) => viewer.histories.push({ event, body, node }))
|
||||
.catch((error) => viewer.errors.push(error.message));
|
||||
});
|
||||
cleanup.push(() => socket.disconnect());
|
||||
socket.connect();
|
||||
await until(
|
||||
() => socket.connected,
|
||||
`socket connect: ${viewer.errors.join(',')}`,
|
||||
);
|
||||
const ack = await socket
|
||||
.timeout(5000)
|
||||
.emitWithAck('join', { matchId: fixture.matchId });
|
||||
assert.equal(ack.ok, true);
|
||||
assert.equal(viewer.state.matchId, fixture.matchId);
|
||||
assert.equal(viewer.state.auctionEngineVersion, 'redis-v1');
|
||||
const health = await Promise.all(
|
||||
['api-a', 'api-b'].map((node) =>
|
||||
http(`http://${node}:3000/_cluster/health`),
|
||||
),
|
||||
);
|
||||
viewer.node = health.find((entry) =>
|
||||
entry.body.sockets.includes(socket.id),
|
||||
).body.node;
|
||||
return viewer;
|
||||
}
|
||||
const one = await connectViewer(),
|
||||
two = await connectViewer();
|
||||
assert.notEqual(one.node, two.node);
|
||||
const a = one.node === 'api-a' ? one : two;
|
||||
const b = one.node === 'api-b' ? one : two;
|
||||
const initialRevision = a.state.revision;
|
||||
const revisionFor = (sequence) => initialRevision + sequence;
|
||||
assert.equal(b.state.revision, initialRevision);
|
||||
pass('WebSocket viewers join different nodes through Nginx', {
|
||||
nodes: [one.node, two.node],
|
||||
});
|
||||
|
||||
const sequences = async () =>
|
||||
(await http(`${url}/history`)).body.map((entry) => entry.sequence);
|
||||
const action = async (viewer, name) => {
|
||||
const ack = await viewer.socket
|
||||
.timeout(5000)
|
||||
.emitWithAck(name, { auctionActionRequestId: randomUUID() });
|
||||
assert.equal(ack.ok, true, JSON.stringify(ack));
|
||||
};
|
||||
for (let i = 0; i < 4; i += 1) assert.deepEqual(await sequences(), []);
|
||||
await action(a, 'open-bidding');
|
||||
await until(
|
||||
() =>
|
||||
a.state.revision === revisionFor(1) &&
|
||||
b.state.revision === revisionFor(1),
|
||||
'cross-node full state',
|
||||
);
|
||||
assert.equal(a.histories.length + b.histories.length, 0);
|
||||
await http('http://api-a:3000/_cluster/hold-commit', {});
|
||||
const pendingDrain = http('http://api-a:3000/_cluster/drain', {});
|
||||
await until(
|
||||
async () =>
|
||||
(await http('http://api-a:3000/_cluster/health')).body.commitsWaiting ===
|
||||
1,
|
||||
'real Mongo commit barrier',
|
||||
);
|
||||
for (let i = 0; i < 4; i += 1) assert.deepEqual(await sequences(), []);
|
||||
assert.equal(a.histories.length + b.histories.length, 0);
|
||||
await http('http://api-a:3000/_cluster/release-commit', {});
|
||||
assert.equal((await pendingDrain).body.applied, 1);
|
||||
await until(
|
||||
() => a.histories.length === 1 && b.histories.length === 1,
|
||||
'post-commit history event on both nodes',
|
||||
);
|
||||
for (const viewer of [a, b])
|
||||
assert.deepEqual(
|
||||
viewer.histories[0].body.map((entry) => entry.sequence),
|
||||
[1],
|
||||
);
|
||||
pass(
|
||||
'History notification crosses nodes only after a real Mongo transaction commits',
|
||||
);
|
||||
|
||||
await action(a, 'passed');
|
||||
await action(b, 'next');
|
||||
await until(
|
||||
() =>
|
||||
a.state.revision === revisionFor(3) &&
|
||||
b.state.revision === revisionFor(3),
|
||||
'state fanout in both directions',
|
||||
);
|
||||
const keys = await redis.zRange(AUCTION_DURABILITY_RETRY_QUEUE_KEY, 0, -1);
|
||||
const queued = await Promise.all(
|
||||
keys.map(async (key) => ({
|
||||
key,
|
||||
payload: JSON.parse(await redis.hGet(key, 'payloadJson')),
|
||||
})),
|
||||
);
|
||||
const third = queued.find(
|
||||
({ payload }) => payload.auctionHistorySequence === 3,
|
||||
);
|
||||
const second = queued.find(
|
||||
({ payload }) => payload.auctionHistorySequence === 2,
|
||||
);
|
||||
assert.ok(third && second);
|
||||
await http('http://api-b:3000/_cluster/apply', third.payload);
|
||||
assert.deepEqual(await sequences(), [3, 1]);
|
||||
const previousEvents = b.histories.length;
|
||||
await http('http://api-a:3000/_cluster/apply', second.payload);
|
||||
await until(
|
||||
() =>
|
||||
b.histories.length > previousEvents &&
|
||||
b.histories.at(-1).body.some((entry) => entry.sequence === 2),
|
||||
'late append history refresh',
|
||||
);
|
||||
assert.deepEqual(await sequences(), [3, 2, 1]);
|
||||
for (const item of queued) {
|
||||
await redis.zRem(AUCTION_DURABILITY_RETRY_QUEUE_KEY, item.key);
|
||||
await redis.del(item.key);
|
||||
}
|
||||
pass(
|
||||
'A delayed history append refreshes another node with the same maximum sequence',
|
||||
{ maximumSequence: 3 },
|
||||
);
|
||||
|
||||
const undo = await http(`${url}/undo`, {
|
||||
sequence: 1,
|
||||
auctionActionRequestId: randomUUID(),
|
||||
});
|
||||
assert.equal(undo.body.auctionEngineVersion, 'redis-v1');
|
||||
assert.equal(undo.body.revision, revisionFor(4));
|
||||
assert.deepEqual(await sequences(), [3, 2, 1]);
|
||||
await http('http://api-b:3000/_cluster/drain', {});
|
||||
await until(
|
||||
async () => JSON.stringify(await sequences()) === '[4,1]',
|
||||
'durable Undo history',
|
||||
);
|
||||
await until(
|
||||
() => b.histories.at(-1)?.body[0]?.sequence === 4,
|
||||
'Undo history event',
|
||||
);
|
||||
pass('Undo increases sequence and replaces history on every node', {
|
||||
sequence: 4,
|
||||
history: [4, 1],
|
||||
});
|
||||
|
||||
await until(
|
||||
async () =>
|
||||
(await http('http://redis-proxy:8081/status')).body.subscribers >= 2,
|
||||
'Redis subscriptions',
|
||||
);
|
||||
await http('http://redis-proxy:8081/block', {});
|
||||
console.log(
|
||||
'FAULT Pub/Sub TCP connections blocked; Redis commands and HTTP stay available',
|
||||
);
|
||||
await delay(500);
|
||||
assert.equal(
|
||||
(await http('http://api-a:3000/_cluster/health')).body.node,
|
||||
'api-a',
|
||||
);
|
||||
assert.equal(
|
||||
(await http('http://api-b:3000/_cluster/health')).body.node,
|
||||
'api-b',
|
||||
);
|
||||
assert.equal(a.socket.connected && b.socket.connected, true);
|
||||
const timestamp = await b.socket
|
||||
.timeout(3000)
|
||||
.emitWithAck('time-sync', { sequence: 1 });
|
||||
assert.equal(timestamp.ok, true);
|
||||
pass(
|
||||
'Both API processes and socket clock sync survive Pub/Sub-only TCP disconnection',
|
||||
);
|
||||
|
||||
environmentManager.setIsServer(() => false);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, gcTime: Infinity } },
|
||||
});
|
||||
cleanup.push(() => queryClient.clear());
|
||||
let stateByHttp = b.state,
|
||||
historyByHttp,
|
||||
statePolls = 0,
|
||||
historyPolls = 0;
|
||||
const pollingStarted = Date.now();
|
||||
const stateObserver = new QueryObserver(queryClient, {
|
||||
queryKey: ['auction', fixture.matchId],
|
||||
refetchInterval: AUCTION_SAFETY_POLL_INTERVAL_MS,
|
||||
queryFn: async () => {
|
||||
statePolls += 1;
|
||||
return (await http(url)).body;
|
||||
},
|
||||
});
|
||||
const historyObserver = new QueryObserver(queryClient, {
|
||||
queryKey: ['auction-history', fixture.matchId],
|
||||
refetchInterval: AUCTION_SAFETY_POLL_INTERVAL_MS,
|
||||
queryFn: async () => {
|
||||
historyPolls += 1;
|
||||
return (await http(`${url}/history`)).body;
|
||||
},
|
||||
});
|
||||
cleanup.push(
|
||||
stateObserver.subscribe((result) => {
|
||||
if (
|
||||
result.data &&
|
||||
shouldApplyPolledAuctionState(stateByHttp, result.data, fixture.matchId)
|
||||
)
|
||||
stateByHttp = mergeAuctionState(stateByHttp, result.data);
|
||||
}),
|
||||
);
|
||||
cleanup.push(
|
||||
historyObserver.subscribe((result) => {
|
||||
if (result.data) historyByHttp = result.data;
|
||||
}),
|
||||
);
|
||||
await until(
|
||||
() =>
|
||||
stateByHttp.revision === revisionFor(4) &&
|
||||
historyByHttp?.[0]?.sequence === 4,
|
||||
'baseline HTTP reads',
|
||||
);
|
||||
const beforeHistoryEvents = b.histories.length;
|
||||
await action(a, 'open-bidding');
|
||||
await http('http://api-a:3000/_cluster/drain', {});
|
||||
await delay(250);
|
||||
assert.equal(b.state.revision, revisionFor(4));
|
||||
assert.equal(b.histories.length, beforeHistoryEvents);
|
||||
assert.equal(a.state.revision, revisionFor(5));
|
||||
// Do not run heartbeat recovery yet: verify the independent 30-second safety
|
||||
// route even if the client identity checker fails to notice a missed event.
|
||||
console.log(
|
||||
'WAIT Real 30-second HTTP safety polling with Pub/Sub still blocked',
|
||||
);
|
||||
await until(
|
||||
() =>
|
||||
stateByHttp.revision === revisionFor(5) &&
|
||||
historyByHttp?.[0]?.sequence === 5,
|
||||
'30-second HTTP safety fallback',
|
||||
35_000,
|
||||
);
|
||||
assert.ok(Date.now() - pollingStarted >= 29_000);
|
||||
pass(
|
||||
'Real 30-second HTTP polls repair missed state and history through Nginx',
|
||||
{ elapsedMS: Date.now() - pollingStarted, statePolls, historyPolls },
|
||||
);
|
||||
|
||||
const monitor = createAuctionHeartbeatMonitor();
|
||||
const heartbeat = async (sequence) => {
|
||||
const ack = await b.socket
|
||||
.timeout(3000)
|
||||
.emitWithAck('time-sync', { sequence });
|
||||
assert.equal(ack.ok, true);
|
||||
return monitor.inspect(b.state, ack.auctionState);
|
||||
};
|
||||
assert.equal((await heartbeat(2)).needsResync, false);
|
||||
await delay(10_000);
|
||||
assert.equal((await heartbeat(3)).needsResync, true);
|
||||
let resyncs = 0;
|
||||
const requester = createAuctionResyncRequester(
|
||||
async () => {
|
||||
resyncs += 1;
|
||||
return b.socket.timeout(3000).emitWithAck('resync', {});
|
||||
},
|
||||
(state) => {
|
||||
b.state = state;
|
||||
},
|
||||
);
|
||||
await requester.request(revisionFor(5), fixture.lifecycle);
|
||||
assert.equal(b.state.revision, revisionFor(5));
|
||||
assert.equal(resyncs, 1);
|
||||
pass(
|
||||
'Two real heartbeats detect a persistent gap and private socket resync works during Pub/Sub outage',
|
||||
{ resyncs },
|
||||
);
|
||||
|
||||
await http('http://redis-proxy:8081/restore', {});
|
||||
await until(
|
||||
async () =>
|
||||
(await http('http://redis-proxy:8081/status')).body.subscribers >= 2,
|
||||
'Pub/Sub resubscription',
|
||||
20_000,
|
||||
);
|
||||
await action(a, 'passed');
|
||||
await http('http://api-a:3000/_cluster/drain', {});
|
||||
await until(
|
||||
() =>
|
||||
b.state.revision === revisionFor(6) &&
|
||||
b.histories.at(-1)?.body[0]?.sequence === 6,
|
||||
'events after Pub/Sub restoration',
|
||||
);
|
||||
pass(
|
||||
'Cross-node state and history events recover after restoring the TCP path',
|
||||
);
|
||||
const fault = (await http('http://redis-proxy:8081/status')).body;
|
||||
report.fault = fault;
|
||||
const previousId = b.socket.id;
|
||||
b.socket.disconnect();
|
||||
b.socket.connect();
|
||||
await until(
|
||||
() => b.socket.connected && b.socket.id !== previousId,
|
||||
'socket reconnect through Nginx',
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await b.socket
|
||||
.timeout(5000)
|
||||
.emitWithAck('join', { matchId: fixture.matchId })
|
||||
).ok,
|
||||
true,
|
||||
);
|
||||
await until(
|
||||
() => b.state.revision === revisionFor(6),
|
||||
'reconnect full state',
|
||||
);
|
||||
pass('A reconnected viewer receives the latest snapshot through Nginx');
|
||||
}
|
||||
|
||||
try {
|
||||
if (process.argv[2] === 'init') await initialize();
|
||||
else {
|
||||
await verify();
|
||||
report.passed = true;
|
||||
}
|
||||
} catch (error) {
|
||||
report.passed = false;
|
||||
report.failure = { message: error.message, stack: error.stack };
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
if (process.argv[2] !== 'init') {
|
||||
await http('http://redis-proxy:8081/restore', {}).catch(() => {});
|
||||
report.finishedAt = new Date().toISOString();
|
||||
await writeFile('/results/report.json', JSON.stringify(report, null, 2));
|
||||
}
|
||||
for (const close of cleanup.reverse()) {
|
||||
try {
|
||||
await close();
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
# From the repository root: sh apps/api/test/auction-cluster/run.sh
|
||||
# Requires Docker Compose. No host ports or production credentials are used.
|
||||
# Results and container logs remain in this directory's ignored results/ folder.
|
||||
# Authentication uses a fixture admin; client recovery uses the production
|
||||
# helpers and QueryObserver without rendering React. MongoDB 7 is the default
|
||||
# for the test host's kernel; set MONGO_TEST_IMAGE on a compatible host to match
|
||||
# the production database version.
|
||||
set -eu
|
||||
cd "$(dirname "$0")"
|
||||
export COMPOSE_PROJECT_NAME="${COMPOSE_PROJECT_NAME:-lolympus-auction-cluster-$(date +%s)}"
|
||||
case "$COMPOSE_PROJECT_NAME" in
|
||||
lolympus-auction-cluster-*) ;;
|
||||
*) echo 'Refusing to use a Compose project outside the auction-cluster test prefix.' >&2; exit 1 ;;
|
||||
esac
|
||||
mkdir -p results
|
||||
cleanup() {
|
||||
docker compose logs --no-color api-a api-b redis-proxy > results/containers.log 2>&1 || true
|
||||
docker compose down --volumes --remove-orphans
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
docker compose build runner
|
||||
docker compose up -d redis mongo redis-proxy
|
||||
docker compose run --rm runner node test/auction-cluster/run.mjs init
|
||||
docker compose up -d api-a api-b lb
|
||||
docker compose run --rm runner node test/auction-cluster/run.mjs verify
|
||||
@@ -324,7 +324,13 @@ describe('Community Hash response cache', () => {
|
||||
|
||||
it('does not share an old in-flight detail request after invalidation or overwrite the fresh response', async () => {
|
||||
const service = new CommunityStatsService(
|
||||
{} as never,
|
||||
{
|
||||
getModel: async () => ({
|
||||
findOne: () => ({
|
||||
select: () => ({ lean: () => ({ exec: async () => null }) }),
|
||||
}),
|
||||
}),
|
||||
} as never,
|
||||
cache,
|
||||
{} as never,
|
||||
{} as never,
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
"@azure/msal-browser": "^5.8.0",
|
||||
"@azure/msal-react": "^5.3.1",
|
||||
"@lolympus/contracts": "workspace:*",
|
||||
"@newrelic/browser-agent": "^1.318.0",
|
||||
"@newrelic/browser-agent": "^1.324.1",
|
||||
"@stylexjs/stylex": "0.19.1",
|
||||
"@tanstack/react-query": "^5.100.1",
|
||||
"lucide-react": "^1.14.0",
|
||||
@@ -35,20 +35,20 @@
|
||||
"socket.io-client": "^4.8.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.4",
|
||||
"@tailwindcss/vite": "^4.2.2",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@tailwindcss/vite": "^4.3.5",
|
||||
"@types/node": "^26.1.1",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"eslint": "^9.39.4",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"@vitejs/plugin-react": "^6.3.0",
|
||||
"eslint": "^10.14.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.4.0",
|
||||
"tailwindcss": "^4.2.2",
|
||||
"tailwindcss": "^4.3.5",
|
||||
"typescript": "~6.0.2",
|
||||
"typescript-eslint": "^8.58.0",
|
||||
"vite": "^8.1.5",
|
||||
"vite": "^8.3.8",
|
||||
"wrangler": "^4.114.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export const AUCTION_SAFETY_POLL_INTERVAL_MS = 30_000;
|
||||
|
||||
/** Supplements the fixed safety poll without restarting its timer. */
|
||||
export function startAuctionRecoveryPolling(
|
||||
refetch: () => void,
|
||||
isVisible = () => document.visibilityState === 'visible',
|
||||
): () => void {
|
||||
const timer = setInterval(() => {
|
||||
if (isVisible()) refetch();
|
||||
}, 5000);
|
||||
return () => clearInterval(timer);
|
||||
}
|
||||
@@ -16,10 +16,18 @@ export const AUCTION_REACTIONS: Record<
|
||||
sad: { emoji: "😢", label: "아쉬움" },
|
||||
fire: { emoji: "🔥", label: "불꽃" },
|
||||
celebrate: { emoji: "🎉", label: "축하" },
|
||||
eyes: { emoji: "👀", label: "관심" },
|
||||
thinking: { emoji: "🤔", label: "고민" },
|
||||
"skull-crossbones": { emoji: "☠️", label: "해골과 뼈" },
|
||||
poop: { emoji: "💩", label: "똥" },
|
||||
pray: { emoji: "🙏", label: "간절함" },
|
||||
"sweat-smile": { emoji: "😅", label: "식은땀" },
|
||||
money: { emoji: "💸", label: "플렉스" },
|
||||
trophy: { emoji: "🏆", label: "우승각" },
|
||||
};
|
||||
|
||||
export const REACTION_LIFETIME_MS = 3200;
|
||||
export const MAX_VISIBLE_REACTIONS = 12;
|
||||
export const MAX_VISIBLE_REACTIONS = 16;
|
||||
export type ActiveAuctionReaction = AuctionReactionEvent & {
|
||||
receivedAt: number;
|
||||
};
|
||||
|
||||
@@ -27,6 +27,7 @@ export function createAuctionResyncRequester(
|
||||
fetchState: () => Promise<AuctionResyncReply>,
|
||||
applyState: (state: ApiAuction) => void,
|
||||
wait = waitForRetry,
|
||||
onFailure?: () => void,
|
||||
) {
|
||||
let pending: Promise<void> | undefined;
|
||||
let controller = new AbortController();
|
||||
@@ -67,6 +68,7 @@ export function createAuctionResyncRequester(
|
||||
}
|
||||
if (attempt < 2 && !signal.aborted) await wait(retryAfterMS, signal);
|
||||
}
|
||||
if (!signal.aborted) onFailure?.();
|
||||
})().finally(() => {
|
||||
if (!signal.aborted) pending = undefined;
|
||||
});
|
||||
|
||||
@@ -1,4 +1,69 @@
|
||||
import type { ApiAuction } from "./types";
|
||||
import type { AuctionStateIdentity } from "@lolympus/contracts";
|
||||
|
||||
export function resolveCurrentBidPointAmount(auction: ApiAuction): number {
|
||||
const amount = Number(
|
||||
auction.currentHighestBidPointAmount ?? auction.currentBid ?? 0,
|
||||
);
|
||||
return Number.isFinite(amount) ? Math.max(0, amount) : 0;
|
||||
}
|
||||
|
||||
export function shouldResyncForAuctionIdentity(
|
||||
current: ApiAuction | null,
|
||||
identity: AuctionStateIdentity | null,
|
||||
): boolean {
|
||||
if (!current) return true;
|
||||
// Completed runtimes expire while their archived Mongo state remains valid.
|
||||
if (!identity) {
|
||||
return (
|
||||
current.auctionEngineVersion === "redis-v1" &&
|
||||
current.phase !== "complete"
|
||||
);
|
||||
}
|
||||
if (identity.auctionLifecycleId !== current.auctionLifecycleId) return true;
|
||||
if ((identity.revision ?? -1) > (current.revision ?? -1)) return true;
|
||||
// A delayed heartbeat must not undo a newer state already received by socket.
|
||||
if ((identity.revision ?? -1) < (current.revision ?? -1)) return false;
|
||||
return (
|
||||
(identity.matchSideEffectRevision ?? -1) >
|
||||
(current.matchSideEffectRevision ?? -1)
|
||||
);
|
||||
}
|
||||
|
||||
export function createAuctionHeartbeatMonitor() {
|
||||
let pendingIdentity: AuctionStateIdentity | null | undefined;
|
||||
let consecutiveFailures = 0;
|
||||
return {
|
||||
reset() {
|
||||
pendingIdentity = undefined;
|
||||
consecutiveFailures = 0;
|
||||
},
|
||||
recordFailure(): boolean {
|
||||
pendingIdentity = undefined;
|
||||
consecutiveFailures += 1;
|
||||
return consecutiveFailures >= 2;
|
||||
},
|
||||
inspect(
|
||||
current: ApiAuction | null,
|
||||
identity: AuctionStateIdentity | null | undefined,
|
||||
) {
|
||||
consecutiveFailures = 0;
|
||||
const previousIdentity = pendingIdentity;
|
||||
const isCurrent =
|
||||
identity === undefined ||
|
||||
!shouldResyncForAuctionIdentity(current, identity);
|
||||
pendingIdentity = undefined;
|
||||
if (isCurrent) return { isCurrent: true, needsResync: false };
|
||||
// Bids received since the first heartbeat may have closed that gap, even
|
||||
// when this heartbeat observes another newer bid still in transit.
|
||||
const needsResync =
|
||||
previousIdentity !== undefined &&
|
||||
shouldResyncForAuctionIdentity(current, previousIdentity);
|
||||
if (!needsResync) pendingIdentity = identity;
|
||||
return { isCurrent: false, needsResync };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export interface BidDeltaPayload {
|
||||
currentBidRoundId?: string;
|
||||
|
||||
@@ -423,10 +423,10 @@ export function useAuction(
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ['auction', communityId, matchId ?? null],
|
||||
queryFn: () =>
|
||||
queryFn: ({ signal }) =>
|
||||
apiFetch<ApiAuction>(
|
||||
`/communities/${communityId}/matches/${matchId}/auction`,
|
||||
{ auth: 'none' },
|
||||
{ auth: 'none', signal },
|
||||
),
|
||||
enabled: Boolean(communityId && matchId),
|
||||
retry: false,
|
||||
@@ -441,9 +441,10 @@ export function useAuctionHistory(
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ['auction-history', communityId, matchId ?? null],
|
||||
queryFn: () =>
|
||||
queryFn: ({ signal }) =>
|
||||
apiFetch<ApiAuctionHistoryEntry[]>(
|
||||
`/communities/${communityId}/matches/${matchId}/auction/history`,
|
||||
{ signal },
|
||||
),
|
||||
enabled: Boolean(communityId && matchId && (options.enabled ?? true)),
|
||||
retry: false,
|
||||
|
||||
@@ -196,6 +196,7 @@ export interface ApiAuctionChatMessage {
|
||||
export interface ApiAuction {
|
||||
_id: string;
|
||||
matchId: string;
|
||||
auctionEngineVersion?: 'legacy-renamed' | 'redis-v1';
|
||||
phase: AuctionPhase;
|
||||
teams?: ApiAuctionTeam[];
|
||||
auctionTeams: ApiAuctionTeam[];
|
||||
|
||||
@@ -2,7 +2,12 @@ import { InteractionStatus } from '@azure/msal-browser';
|
||||
import { useMsal } from '@azure/msal-react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { io, type Socket } from 'socket.io-client';
|
||||
import type { AuctionReactionKind, AuctionReactionReply } from '@lolympus/contracts';
|
||||
import type {
|
||||
AuctionHistoryUpdatedEvent,
|
||||
AuctionReactionKind,
|
||||
AuctionReactionReply,
|
||||
AuctionStateIdentity,
|
||||
} from '@lolympus/contracts';
|
||||
import { appendAuctionReaction, isAuctionReaction, REACTION_LIFETIME_MS, sendAuctionReaction, type ActiveAuctionReaction } from './auction-reactions';
|
||||
import { API_BASE_URL, useAuthUserId } from '../config';
|
||||
import { acquireAccessToken } from '../lib/auth/token-provider';
|
||||
@@ -19,6 +24,8 @@ import {
|
||||
shouldResyncForBidDelta,
|
||||
shouldApplyPolledAuctionState,
|
||||
mergeAuctionState,
|
||||
resolveCurrentBidPointAmount,
|
||||
createAuctionHeartbeatMonitor,
|
||||
type BidDeltaPayload,
|
||||
} from './auction-state';
|
||||
import { resolveAuctionActionRejection } from './auction-action-retry';
|
||||
@@ -105,6 +112,8 @@ interface BidAckPayload {
|
||||
}
|
||||
|
||||
interface TimeSyncAckPayload {
|
||||
auctionState?: AuctionStateIdentity | null;
|
||||
auctionStateUnavailable?: boolean;
|
||||
clientSentAtTimestampMS?: number;
|
||||
currentServerTimestampMS?: number;
|
||||
ok?: boolean;
|
||||
@@ -169,6 +178,8 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
const timeSyncSequenceRef = useRef(0);
|
||||
const hasSyncedServerTimeRef = useRef(false);
|
||||
const latestAuctionRef = useRef<ApiAuction | null>(null);
|
||||
const synchronizedSocketRef = useRef<Socket | null>(null);
|
||||
const heartbeatMonitorRef = useRef(createAuctionHeartbeatMonitor());
|
||||
const cancelledLifecycleIdsRef = useRef(new Set<string>());
|
||||
const latestConfirmedBidPointAmountRef = useRef(0);
|
||||
const [auction, setAuction] = useState<ApiAuction | null>(null);
|
||||
@@ -207,6 +218,11 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
key: string;
|
||||
status: ConnectionStatus;
|
||||
}>({ key: '', status: 'idle' });
|
||||
const [synchronizationState, setSynchronizationState] = useState({
|
||||
key: '',
|
||||
ready: false,
|
||||
});
|
||||
const [historyUpdateState, setHistoryUpdateState] = useState({ key: '', count: 0 });
|
||||
const [errorState, setErrorState] = useState<{
|
||||
key: string;
|
||||
message: string | null;
|
||||
@@ -334,15 +350,32 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
timeSyncTimeoutsRef.current = {};
|
||||
}
|
||||
|
||||
function requestServerTimeSync(socket: Socket) {
|
||||
const markSynchronized = useCallback(
|
||||
(socket: Socket, key: string, ready: boolean) => {
|
||||
if (socketRef.current !== socket) return;
|
||||
setSynchronizationState((current) =>
|
||||
current.key === key && current.ready === ready ? current : { key, ready },
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const requestServerTimeSync = useCallback((socket: Socket, key: string) => {
|
||||
if (!socket.connected) return;
|
||||
|
||||
const recordFailure = () => {
|
||||
if (socketRef.current === socket && heartbeatMonitorRef.current.recordFailure()) {
|
||||
markSynchronized(socket, key, false);
|
||||
}
|
||||
};
|
||||
|
||||
const sequence = timeSyncSequenceRef.current + 1;
|
||||
timeSyncSequenceRef.current = sequence;
|
||||
const clientSentAtTimestampMS = Date.now();
|
||||
|
||||
timeSyncTimeoutsRef.current[sequence] = setTimeout(() => {
|
||||
delete timeSyncTimeoutsRef.current[sequence];
|
||||
recordFailure();
|
||||
}, TIME_SYNC_TIMEOUT_MS);
|
||||
|
||||
socket.emit(
|
||||
@@ -354,15 +387,35 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
if (!timeoutId) return;
|
||||
clearTimeout(timeoutId);
|
||||
delete timeSyncTimeoutsRef.current[sequence];
|
||||
if (socketRef.current !== socket) return;
|
||||
|
||||
if (
|
||||
!ack?.ok ||
|
||||
ack.sequence !== sequence ||
|
||||
typeof ack.currentServerTimestampMS !== 'number'
|
||||
) {
|
||||
recordFailure();
|
||||
return;
|
||||
}
|
||||
|
||||
if (ack.auctionStateUnavailable) {
|
||||
recordFailure();
|
||||
} else {
|
||||
const inspection = heartbeatMonitorRef.current.inspect(
|
||||
latestAuctionRef.current,
|
||||
ack.auctionState,
|
||||
);
|
||||
if (inspection.needsResync) {
|
||||
markSynchronized(socket, key, false);
|
||||
void resyncRequesterRef.current?.request(
|
||||
ack.auctionState?.revision,
|
||||
ack.auctionState?.auctionLifecycleId,
|
||||
);
|
||||
} else if (inspection.isCurrent) {
|
||||
markSynchronized(socket, key, synchronizedSocketRef.current === socket);
|
||||
}
|
||||
}
|
||||
|
||||
const totalRoundTripDurationMS = Math.max(
|
||||
0,
|
||||
clientReceivedAtTimestampMS - clientSentAtTimestampMS,
|
||||
@@ -391,7 +444,7 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}, [markSynchronized]);
|
||||
|
||||
function captureBidLatencyDiagnostics(ack?: BidAckPayload) {
|
||||
if (!ack?.bidDiagnostics && !ack?.bidServerTiming) return;
|
||||
@@ -472,6 +525,8 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
const activeConnectionKey = connectionKey;
|
||||
const cancelledLifecycleIds = cancelledLifecycleIdsRef.current;
|
||||
let disposed = false;
|
||||
let removeResumeListeners = () => {};
|
||||
let hasReceivedSnapshot = false;
|
||||
|
||||
void (async () => {
|
||||
const accessToken = await acquireAccessToken().catch((error) => {
|
||||
@@ -490,7 +545,16 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
});
|
||||
|
||||
socketRef.current = socket;
|
||||
const notifyHistoryUpdated = () => {
|
||||
setHistoryUpdateState((current) => ({
|
||||
key: activeConnectionKey,
|
||||
count: current.key === activeConnectionKey ? current.count + 1 : 1,
|
||||
}));
|
||||
};
|
||||
const receiveAuctionState = (nextAuction: ApiAuction, source: string) => {
|
||||
if (
|
||||
disposed || socketRef.current !== socket || nextAuction.matchId !== matchId
|
||||
) return;
|
||||
const previousRevision = latestAuctionRef.current?.revision ?? -1;
|
||||
const didApplyState = commitAuctionState(nextAuction, source);
|
||||
if (didApplyState && (nextAuction.revision ?? 0) > previousRevision) {
|
||||
@@ -501,6 +565,13 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
setChatMessages(mergeChatMessages([], nextAuction.chatMessages));
|
||||
}
|
||||
if (didApplyState) {
|
||||
if (hasReceivedSnapshot && synchronizedSocketRef.current !== socket) {
|
||||
notifyHistoryUpdated();
|
||||
}
|
||||
hasReceivedSnapshot = true;
|
||||
synchronizedSocketRef.current = socket;
|
||||
heartbeatMonitorRef.current.reset();
|
||||
markSynchronized(socket, activeConnectionKey, true);
|
||||
setError(null);
|
||||
}
|
||||
};
|
||||
@@ -515,27 +586,44 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
(state) => {
|
||||
receiveAuctionState(state, 'socket-resync');
|
||||
},
|
||||
undefined,
|
||||
() => markSynchronized(socket, activeConnectionKey, false),
|
||||
);
|
||||
resyncRequesterRef.current = resyncRequester;
|
||||
|
||||
socket.on('connect', () => {
|
||||
synchronizedSocketRef.current = null;
|
||||
heartbeatMonitorRef.current.reset();
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
setConnectionState({
|
||||
key: activeConnectionKey,
|
||||
status: 'connected',
|
||||
});
|
||||
setError(null);
|
||||
socket.emit('join', { matchId });
|
||||
requestServerTimeSync(socket);
|
||||
void socket.timeout(3000).emitWithAck('join', { matchId })
|
||||
.then((reply: { ok?: boolean }) => {
|
||||
if (!reply?.ok && synchronizedSocketRef.current !== socket) {
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
}
|
||||
}).catch(() => {
|
||||
if (synchronizedSocketRef.current !== socket) {
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
}
|
||||
});
|
||||
requestServerTimeSync(socket, activeConnectionKey);
|
||||
if (timeSyncIntervalRef.current) {
|
||||
clearInterval(timeSyncIntervalRef.current);
|
||||
}
|
||||
timeSyncIntervalRef.current = setInterval(
|
||||
() => requestServerTimeSync(socket),
|
||||
() => requestServerTimeSync(socket, activeConnectionKey),
|
||||
TIME_SYNC_INTERVAL_MS,
|
||||
);
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
synchronizedSocketRef.current = null;
|
||||
heartbeatMonitorRef.current.reset();
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
setReactionState({ key: activeConnectionKey, items: [] });
|
||||
resyncRequester.cancel();
|
||||
clearTimeSyncTimers();
|
||||
@@ -545,6 +633,34 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('connect_error', (error: Error) => {
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
setConnectionState({ key: activeConnectionKey, status: 'error' });
|
||||
if (!socket.active) setError(resolveAuctionErrorMessage(error.message));
|
||||
});
|
||||
|
||||
socket.on('history-updated', (event: AuctionHistoryUpdatedEvent) => {
|
||||
if (event.matchId !== matchId) return;
|
||||
const lifecycle = latestAuctionRef.current?.auctionLifecycleId;
|
||||
if (lifecycle && lifecycle !== event.auctionLifecycleId) return;
|
||||
// Older append retries may fill a gap without increasing the maximum
|
||||
// sequence. Every committed-history notification refreshes the list.
|
||||
notifyHistoryUpdated();
|
||||
});
|
||||
|
||||
const resyncAfterResume = () => {
|
||||
if (document.visibilityState === 'visible' && socket.connected) {
|
||||
notifyHistoryUpdated();
|
||||
void resyncRequester.request();
|
||||
}
|
||||
};
|
||||
document.addEventListener('visibilitychange', resyncAfterResume);
|
||||
window.addEventListener('online', resyncAfterResume);
|
||||
removeResumeListeners = () => {
|
||||
document.removeEventListener('visibilitychange', resyncAfterResume);
|
||||
window.removeEventListener('online', resyncAfterResume);
|
||||
};
|
||||
|
||||
socket.on('state-pending', () => {
|
||||
void resyncRequester.request();
|
||||
});
|
||||
@@ -673,6 +789,7 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
removeResumeListeners();
|
||||
resyncRequesterRef.current?.cancel();
|
||||
resyncRequesterRef.current = null;
|
||||
const socket = socketRef.current;
|
||||
@@ -689,6 +806,7 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
pendingBidTimeoutsRef.current = {};
|
||||
pendingActionTimeoutsRef.current = {};
|
||||
latestAuctionRef.current = null;
|
||||
synchronizedSocketRef.current = null;
|
||||
cancelledLifecycleIds.clear();
|
||||
latestConfirmedBidPointAmountRef.current = 0;
|
||||
hasSyncedServerTimeRef.current = false;
|
||||
@@ -707,6 +825,8 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
connectionKey,
|
||||
matchId,
|
||||
receiveReaction,
|
||||
markSynchronized,
|
||||
requestServerTimeSync,
|
||||
setError,
|
||||
]);
|
||||
|
||||
@@ -906,6 +1026,11 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
pendingBidRequests,
|
||||
resetAt,
|
||||
connectionStatus: visibleConnectionStatus,
|
||||
isSynchronized:
|
||||
synchronizationState.key === connectionKey &&
|
||||
synchronizationState.ready && visibleConnectionStatus === 'connected',
|
||||
historyUpdateCount:
|
||||
historyUpdateState.key === connectionKey ? historyUpdateState.count : 0,
|
||||
error: visibleError,
|
||||
bidLatencyDiagnostics,
|
||||
serverRoundTripMs: matchId ? serverRoundTripMs : null,
|
||||
@@ -1027,15 +1152,6 @@ function createClientRequestId(): string {
|
||||
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
}
|
||||
|
||||
function resolveCurrentBidPointAmount(auction: ApiAuction): number {
|
||||
const bidPointAmount = Math.max(
|
||||
Number(auction.currentHighestBidPointAmount),
|
||||
Number(auction.currentBid),
|
||||
0,
|
||||
);
|
||||
return Number.isFinite(bidPointAmount) ? bidPointAmount : 0;
|
||||
}
|
||||
|
||||
// [AUCTION-DEBUG] 아래 텔레메트리 헬퍼들과 호출부는 조사 종료 후 제거 대상.
|
||||
type AuctionTelemetryAttributes = Record<
|
||||
string,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useMemo, useRef, useState, type SubmitEvent } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import type {
|
||||
CompetitionCommandResponse,
|
||||
@@ -170,7 +170,7 @@ export function CompetitionAdminControls({
|
||||
resetCommandFeedback();
|
||||
}
|
||||
|
||||
function handleAdjudicationSubmit(event: React.FormEvent) {
|
||||
function handleAdjudicationSubmit(event: SubmitEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!selectedSeries || !canAdjudicate || !adjudicationReason.trim()) {
|
||||
return;
|
||||
@@ -216,7 +216,7 @@ export function CompetitionAdminControls({
|
||||
);
|
||||
}
|
||||
|
||||
function handlePreviewSubmit(event: React.FormEvent) {
|
||||
function handlePreviewSubmit(event: SubmitEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!selectedSeries || !canReverse || !reversalReason.trim()) return;
|
||||
|
||||
|
||||
@@ -37,6 +37,10 @@ import {
|
||||
} from "../config";
|
||||
import { ApiError } from "../lib/api";
|
||||
import { mergeAuctionState } from "../api/auction-state";
|
||||
import {
|
||||
AUCTION_SAFETY_POLL_INTERVAL_MS,
|
||||
startAuctionRecoveryPolling,
|
||||
} from "../api/auction-polling";
|
||||
import {
|
||||
profileIconUrl,
|
||||
} from "../lib/ddragon";
|
||||
@@ -1196,16 +1200,23 @@ export default function AuctionPage() {
|
||||
currentUser?.role === "owner" ||
|
||||
currentUser?.role === "admin";
|
||||
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
|
||||
const socket = useAuctionSocket(id);
|
||||
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID, {
|
||||
refetchInterval: 5000,
|
||||
refetchInterval: AUCTION_SAFETY_POLL_INTERVAL_MS,
|
||||
});
|
||||
const { refetch: refetchAuction } = auctionQuery;
|
||||
useEffect(() => {
|
||||
if (!id || socket.isSynchronized) return;
|
||||
return startAuctionRecoveryPolling(() => {
|
||||
void refetchAuction({ cancelRefetch: false });
|
||||
});
|
||||
}, [id, socket.isSynchronized, refetchAuction]);
|
||||
const historyQuery = useAuctionHistory(id, DEFAULT_COMMUNITY_ID, {
|
||||
enabled: canManageAuction,
|
||||
refetchInterval: 3000,
|
||||
refetchInterval: AUCTION_SAFETY_POLL_INTERVAL_MS,
|
||||
});
|
||||
const undoMutation = useUndoAuction(DEFAULT_COMMUNITY_ID);
|
||||
const resetAuctionMutation = useResetAuction(DEFAULT_COMMUNITY_ID);
|
||||
const socket = useAuctionSocket(id);
|
||||
const savedCaptainTeamIndex = useAuctionCaptainTeamIndex(id);
|
||||
const [assignedPositionDraft, setAssignedPositionDraft] = useState<{
|
||||
playerId: string | null;
|
||||
@@ -1256,6 +1267,13 @@ export default function AuctionPage() {
|
||||
useEffect(() => {
|
||||
syncPolledAuctionState(auctionQuery.data);
|
||||
}, [auctionQuery.data, syncPolledAuctionState]);
|
||||
useEffect(() => {
|
||||
if (!id || !canManageAuction || !socket.historyUpdateCount) return;
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["auction-history", DEFAULT_COMMUNITY_ID, id],
|
||||
exact: true,
|
||||
});
|
||||
}, [id, canManageAuction, queryClient, socket.historyUpdateCount]);
|
||||
const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data);
|
||||
const auctionState = useMemo(
|
||||
() =>
|
||||
@@ -1384,18 +1402,25 @@ export default function AuctionPage() {
|
||||
sequence,
|
||||
},
|
||||
{
|
||||
onSuccess: async () => {
|
||||
await Promise.all([
|
||||
onSuccess: async (updatedAuction) => {
|
||||
const refreshes = [
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["auction", DEFAULT_COMMUNITY_ID, id],
|
||||
}),
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["auction-history", DEFAULT_COMMUNITY_ID, id],
|
||||
}),
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["match", DEFAULT_COMMUNITY_ID, id],
|
||||
}),
|
||||
]);
|
||||
];
|
||||
// Redis history refreshes on its post-durability event. Legacy Undo
|
||||
// commits before responding and does not emit that event.
|
||||
if (updatedAuction.auctionEngineVersion !== "redis-v1") {
|
||||
refreshes.push(
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["auction-history", DEFAULT_COMMUNITY_ID, id],
|
||||
}),
|
||||
);
|
||||
}
|
||||
await Promise.all(refreshes);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { setImmediate } from 'node:timers/promises';
|
||||
import {
|
||||
environmentManager,
|
||||
QueryClient,
|
||||
QueryObserver,
|
||||
} from '@tanstack/react-query';
|
||||
import {
|
||||
AUCTION_SAFETY_POLL_INTERVAL_MS,
|
||||
startAuctionRecoveryPolling,
|
||||
} from '../src/api/auction-polling.ts';
|
||||
|
||||
test('repeated short recovery periods cannot postpone the safety HTTP poll', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: 0 });
|
||||
const wasServer = environmentManager.isServer();
|
||||
environmentManager.setIsServer(() => false);
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, gcTime: Infinity } },
|
||||
});
|
||||
const requests: number[] = [];
|
||||
const observer = new QueryObserver(client, {
|
||||
queryKey: ['auction', 'match-1'],
|
||||
queryFn: async () => {
|
||||
requests.push(Date.now());
|
||||
return { revision: 1 };
|
||||
},
|
||||
refetchInterval: AUCTION_SAFETY_POLL_INTERVAL_MS,
|
||||
});
|
||||
const unsubscribe = observer.subscribe(() => {});
|
||||
let stopRecovery: (() => void) | undefined;
|
||||
t.after(() => {
|
||||
stopRecovery?.();
|
||||
unsubscribe();
|
||||
client.clear();
|
||||
environmentManager.setIsServer(() => wasServer);
|
||||
});
|
||||
await setImmediate();
|
||||
|
||||
for (let attempt = 0; attempt < 6; attempt += 1) {
|
||||
stopRecovery = startAuctionRecoveryPolling(
|
||||
() => { void observer.refetch({ cancelRefetch: false }); },
|
||||
() => true,
|
||||
);
|
||||
t.mock.timers.tick(1000);
|
||||
await setImmediate();
|
||||
stopRecovery();
|
||||
t.mock.timers.tick(9000);
|
||||
await setImmediate();
|
||||
}
|
||||
|
||||
assert.deepEqual(requests, [0, 30_000, 60_000]);
|
||||
});
|
||||
|
||||
test('recovery polls every five seconds while visible and stops after cleanup', (t) => {
|
||||
t.mock.timers.enable({ apis: ['setInterval'] });
|
||||
let visible = true;
|
||||
let requests = 0;
|
||||
const stop = startAuctionRecoveryPolling(
|
||||
() => { requests += 1; },
|
||||
() => visible,
|
||||
);
|
||||
t.after(stop);
|
||||
t.mock.timers.tick(5000);
|
||||
assert.equal(requests, 1);
|
||||
visible = false;
|
||||
t.mock.timers.tick(10_000);
|
||||
assert.equal(requests, 1);
|
||||
visible = true;
|
||||
t.mock.timers.tick(5000);
|
||||
assert.equal(requests, 2);
|
||||
stop();
|
||||
t.mock.timers.tick(10_000);
|
||||
assert.equal(requests, 2);
|
||||
});
|
||||
@@ -72,6 +72,24 @@ test('bounds retries and honors retry delay without rejoining the room', async (
|
||||
assert.deepEqual(waits, [1500, 1500]);
|
||||
});
|
||||
|
||||
test('reports failure when all replies remain behind the required revision', async () => {
|
||||
let failed = 0;
|
||||
let applied = 0;
|
||||
const sync = createAuctionResyncRequester(
|
||||
async () => ({ ok: true, state: state(10) }),
|
||||
() => {
|
||||
applied++;
|
||||
},
|
||||
noWait,
|
||||
() => {
|
||||
failed++;
|
||||
},
|
||||
);
|
||||
await sync.request(12, 'life');
|
||||
assert.equal(applied, 3);
|
||||
assert.equal(failed, 1);
|
||||
});
|
||||
|
||||
test('drops an old connection reply after cancellation and permits a new request', async () => {
|
||||
let finish!: (reply: AuctionResyncReply) => void;
|
||||
let calls = 0;
|
||||
|
||||
@@ -6,9 +6,192 @@ import {
|
||||
shouldApplyIncomingAuctionState,
|
||||
shouldApplyPolledAuctionState,
|
||||
shouldResyncForBidDelta,
|
||||
resolveCurrentBidPointAmount,
|
||||
shouldResyncForAuctionIdentity,
|
||||
createAuctionHeartbeatMonitor,
|
||||
} from "../src/api/auction-state.ts";
|
||||
import type { ApiAuction } from "../src/api/types.ts";
|
||||
|
||||
test("Redis-only snapshots retain the bid amount without a legacy alias", () => {
|
||||
assert.equal(
|
||||
resolveCurrentBidPointAmount({
|
||||
currentHighestBidPointAmount: 310,
|
||||
} as ApiAuction),
|
||||
310,
|
||||
);
|
||||
assert.equal(
|
||||
resolveCurrentBidPointAmount({ currentBid: 120 } as ApiAuction),
|
||||
120,
|
||||
);
|
||||
assert.equal(
|
||||
resolveCurrentBidPointAmount({
|
||||
currentHighestBidPointAmount: 0,
|
||||
currentBid: 120,
|
||||
} as ApiAuction),
|
||||
0,
|
||||
);
|
||||
assert.equal(
|
||||
resolveCurrentBidPointAmount({
|
||||
currentHighestBidPointAmount: NaN,
|
||||
} as ApiAuction),
|
||||
0,
|
||||
);
|
||||
});
|
||||
|
||||
test("heartbeats detect missed state and separately versioned side effects", () => {
|
||||
const state = {
|
||||
auctionLifecycleId: "life",
|
||||
revision: 10,
|
||||
matchSideEffectRevision: 2,
|
||||
} as ApiAuction;
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(state, {
|
||||
auctionLifecycleId: "life",
|
||||
revision: 11,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(state, {
|
||||
auctionLifecycleId: "life",
|
||||
revision: 10,
|
||||
matchSideEffectRevision: 3,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(state, {
|
||||
auctionLifecycleId: "life",
|
||||
revision: 10,
|
||||
matchSideEffectRevision: 2,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(state, {
|
||||
auctionLifecycleId: "new-life",
|
||||
revision: 1,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("a delayed heartbeat cannot pull an advanced socket backward", () => {
|
||||
const advanced = { auctionLifecycleId: "life", revision: 12 } as ApiAuction;
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(advanced, {
|
||||
auctionLifecycleId: "life",
|
||||
revision: 11,
|
||||
matchSideEffectRevision: 9,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("expired complete runtimes and legacy archives do not repeatedly resync", () => {
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(
|
||||
{ auctionLifecycleId: "life", phase: "complete" } as ApiAuction,
|
||||
null,
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity({ phase: "bidding" } as ApiAuction, null),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(
|
||||
{
|
||||
auctionEngineVersion: "legacy-renamed",
|
||||
auctionLifecycleId: "legacy-auction:1",
|
||||
phase: "bidding",
|
||||
} as ApiAuction,
|
||||
null,
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(
|
||||
{
|
||||
auctionEngineVersion: "redis-v1",
|
||||
auctionLifecycleId: "life",
|
||||
phase: "bidding",
|
||||
} as ApiAuction,
|
||||
null,
|
||||
),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("a new in-flight bid does not confirm an earlier gap that already closed", () => {
|
||||
const monitor = createAuctionHeartbeatMonitor();
|
||||
const client = {
|
||||
auctionEngineVersion: "redis-v1",
|
||||
auctionLifecycleId: "life",
|
||||
revision: 10,
|
||||
} as ApiAuction;
|
||||
assert.equal(
|
||||
monitor.inspect(client, { auctionLifecycleId: "life", revision: 11 })
|
||||
.needsResync,
|
||||
false,
|
||||
);
|
||||
const caughtUp = { ...client, revision: 11 };
|
||||
assert.equal(
|
||||
monitor.inspect(caughtUp, { auctionLifecycleId: "life", revision: 12 })
|
||||
.needsResync,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
monitor.inspect(caughtUp, { auctionLifecycleId: "life", revision: 13 })
|
||||
.needsResync,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("heartbeat failures require two misses and reset after a healthy reply", () => {
|
||||
const monitor = createAuctionHeartbeatMonitor();
|
||||
assert.equal(monitor.recordFailure(), false);
|
||||
assert.equal(monitor.recordFailure(), true);
|
||||
monitor.inspect(
|
||||
{ auctionEngineVersion: "legacy-renamed" } as ApiAuction,
|
||||
null,
|
||||
);
|
||||
assert.equal(monitor.recordFailure(), false);
|
||||
monitor.reset();
|
||||
assert.equal(monitor.recordFailure(), false);
|
||||
});
|
||||
|
||||
test("heartbeat confirmation covers side effects and missing runtimes", () => {
|
||||
const monitor = createAuctionHeartbeatMonitor();
|
||||
const client = {
|
||||
auctionEngineVersion: "redis-v1",
|
||||
auctionLifecycleId: "life",
|
||||
revision: 10,
|
||||
matchSideEffectRevision: 1,
|
||||
} as ApiAuction;
|
||||
const identity = {
|
||||
auctionLifecycleId: "life",
|
||||
revision: 10,
|
||||
matchSideEffectRevision: 2,
|
||||
};
|
||||
assert.equal(monitor.inspect(client, identity).needsResync, false);
|
||||
assert.equal(
|
||||
monitor.inspect({ ...client, matchSideEffectRevision: 2 }, identity)
|
||||
.isCurrent,
|
||||
true,
|
||||
);
|
||||
assert.equal(monitor.inspect(client, null).needsResync, false);
|
||||
assert.equal(monitor.inspect(client, null).needsResync, true);
|
||||
monitor.reset();
|
||||
const legacy = {
|
||||
...client,
|
||||
auctionEngineVersion: "legacy-renamed",
|
||||
} as ApiAuction;
|
||||
assert.equal(monitor.inspect(legacy, null).isCurrent, true);
|
||||
assert.equal(monitor.inspect(legacy, null).needsResync, false);
|
||||
});
|
||||
|
||||
const current = {
|
||||
auctionLifecycleId: "life",
|
||||
revision: 10,
|
||||
|
||||
+14
-11
@@ -8,6 +8,12 @@ import path from "node:path";
|
||||
const ES_TOOLKIT_COMPAT_RE = /^es-toolkit\/compat\/[A-Za-z0-9_$]+$/;
|
||||
const VIRTUAL_ES_TOOLKIT_COMPAT_PREFIX = "\0es-toolkit-compat-esm:";
|
||||
|
||||
// Share resolved modules between the app and dependency optimizer plugins.
|
||||
const resolvedCompatModules = new Map<
|
||||
string,
|
||||
{ exportName: string; esmPath: string }
|
||||
>();
|
||||
|
||||
function esToolkitCompatEsm() {
|
||||
return {
|
||||
name: "es-toolkit-compat-esm",
|
||||
@@ -34,21 +40,18 @@ function esToolkitCompatEsm() {
|
||||
`${esmPathWithoutExtension}.mjs`,
|
||||
);
|
||||
|
||||
return `${VIRTUAL_ES_TOOLKIT_COMPAT_PREFIX}${encodeURIComponent(
|
||||
const id = `${VIRTUAL_ES_TOOLKIT_COMPAT_PREFIX}${encodeURIComponent(
|
||||
exportName,
|
||||
)}:${encodeURIComponent(esmPath)}`;
|
||||
resolvedCompatModules.set(id, { exportName, esmPath });
|
||||
return id;
|
||||
},
|
||||
load(id: string) {
|
||||
if (!id.startsWith(VIRTUAL_ES_TOOLKIT_COMPAT_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [encodedExportName, encodedEsmPath] = id
|
||||
.slice(VIRTUAL_ES_TOOLKIT_COMPAT_PREFIX.length)
|
||||
.split(":");
|
||||
const exportName = decodeURIComponent(encodedExportName);
|
||||
const esmPath = decodeURIComponent(encodedEsmPath);
|
||||
|
||||
// A dev-server request can supply a virtual ID directly. Only load IDs
|
||||
// previously produced by resolving an installed es-toolkit module.
|
||||
const module = resolvedCompatModules.get(id);
|
||||
if (!module) return null;
|
||||
const { exportName, esmPath } = module;
|
||||
return `export { ${exportName} as default, ${exportName} } from ${JSON.stringify(
|
||||
esmPath,
|
||||
)};`;
|
||||
|
||||
+11
-7
@@ -35,16 +35,19 @@
|
||||
"overrides": {
|
||||
"@babel/core@7.29.0": "7.29.6",
|
||||
"@grpc/grpc-js@>=1.14.0 <1.14.5": "1.14.7",
|
||||
"baseline-browser-mapping@>=2.10.0 <2.11.0": "2.11.35",
|
||||
"body-parser@>=2.0.0 <2.4.0": "2.4.0",
|
||||
"brace-expansion@1.1.13": "1.1.16",
|
||||
"brace-expansion@2.0.3": "2.1.2",
|
||||
"brace-expansion@5.0.5": "5.0.8",
|
||||
"brace-expansion@>=1.1.13 <1.1.21": "1.1.22",
|
||||
"brace-expansion@>=2.0.3 <2.1.7": "2.1.8",
|
||||
"brace-expansion@>=5.0.5 <5.0.12": "5.0.13",
|
||||
"browserslist@>=4.28.2 <4.28.7": "4.29.5",
|
||||
"engine.io@>=6.6.0 <6.6.10": "6.6.11",
|
||||
"fast-uri@3.1.0": "3.1.4",
|
||||
"fast-uri@>=3.1.0 <3.1.9": "3.1.9",
|
||||
"form-data@4.0.5": "4.0.6",
|
||||
"handlebars@>=3.0.0 <4.7.10": "4.7.10",
|
||||
"js-yaml@4.1.1": "4.3.0",
|
||||
"js-yaml@5.2.1": "5.2.2",
|
||||
"js-yaml@>=3.0.0 <3.15.2": "3.15.2",
|
||||
"js-yaml@>=4.0.0 <4.3.2": "4.3.2",
|
||||
"miniflare>sharp@0.35.2": "0.35.5",
|
||||
"multer@>=2.0.0 <2.5.0": "2.5.0",
|
||||
"nanoid@3.3.16": "3.3.18",
|
||||
"proxy-addr@>=2.0.0 <2.0.8": "2.0.8",
|
||||
@@ -52,7 +55,8 @@
|
||||
"socket.io-parser@4.2.6": "4.2.7",
|
||||
"source-map-js@>=1.0.0 <1.2.2": "1.2.2",
|
||||
"undici@>=7.0.0 <7.30.1": "7.30.2",
|
||||
"ws@8.18.3": "8.21.0"
|
||||
"ws@8.18.3": "8.21.0",
|
||||
"zod@>=4.3.6 <4.6.6": "4.6.7"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,15 @@ export type AuctionReactionKind =
|
||||
| "wow"
|
||||
| "sad"
|
||||
| "fire"
|
||||
| "celebrate";
|
||||
| "celebrate"
|
||||
| "eyes"
|
||||
| "thinking"
|
||||
| "skull-crossbones"
|
||||
| "poop"
|
||||
| "pray"
|
||||
| "sweat-smile"
|
||||
| "money"
|
||||
| "trophy";
|
||||
|
||||
export interface AuctionReactionEvent {
|
||||
id: string;
|
||||
@@ -22,3 +30,16 @@ export interface AuctionReactionReply {
|
||||
reaction?: AuctionReactionEvent;
|
||||
code?: "NOT_JOINED" | "INVALID_REACTION" | "REACTION_RATE_LIMITED";
|
||||
}
|
||||
|
||||
export interface AuctionStateIdentity {
|
||||
auctionLifecycleId?: string;
|
||||
revision?: number;
|
||||
matchSideEffectRevision?: number;
|
||||
matchSideEffectTransitionId?: string;
|
||||
}
|
||||
|
||||
export interface AuctionHistoryUpdatedEvent {
|
||||
matchId: string;
|
||||
auctionLifecycleId: string;
|
||||
auctionStateTransitionId: string;
|
||||
}
|
||||
Generated
+817
-807
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,7 @@ import { once } from "node:events";
|
||||
import http from "node:http";
|
||||
import { createRequire } from "node:module";
|
||||
import { test } from "node:test";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { gzipSync } from "node:zlib";
|
||||
|
||||
const apiRequire = createRequire(
|
||||
@@ -158,3 +159,34 @@ test(
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("Vite only loads compatibility modules resolved from real imports", async (t) => {
|
||||
const { createServer } = await import(
|
||||
pathToFileURL(webRequire.resolve("vite")).href
|
||||
);
|
||||
const server = await createServer({
|
||||
root: fileURLToPath(new URL("../apps/web", import.meta.url)),
|
||||
logLevel: "silent",
|
||||
optimizeDeps: { noDiscovery: true },
|
||||
server: { middlewareMode: true, ws: false, hmr: false, watch: null },
|
||||
});
|
||||
t.after(() => server.close());
|
||||
|
||||
const canary = fileURLToPath(
|
||||
new URL("../apps/api/src/app.service.ts", import.meta.url),
|
||||
).replaceAll("\\", "/");
|
||||
const forgedId =
|
||||
"\0es-toolkit-compat-esm:AppService:" +
|
||||
encodeURIComponent(canary);
|
||||
await assert.rejects(server.transformRequest(forgedId), {
|
||||
code: "ERR_LOAD_URL",
|
||||
});
|
||||
|
||||
const resolved = await server.environments.client.pluginContainer.resolveId(
|
||||
"es-toolkit/compat/sortBy",
|
||||
webRequire.resolve("recharts"),
|
||||
);
|
||||
assert.ok(resolved?.id.startsWith("\0es-toolkit-compat-esm:"));
|
||||
const transformed = await server.transformRequest(resolved.id);
|
||||
assert.match(transformed?.code ?? "", /sortBy/);
|
||||
});
|
||||
Reference in new issue
Block a user