fix: prevent empty-team auction completion state
This commit is contained in:
1 parent
2984bd1604
commit
ab721873f3
6 files changed
+748
-452
No files matched your search
@@ -92,7 +92,10 @@ describe('auction durability projection helpers', () => {
|
|||||||
it.each([
|
it.each([
|
||||||
{ current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true },
|
{ current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true },
|
||||||
{ current: { auctionLifecycleId: 'life-1', revision: 9 }, expected: false },
|
{ current: { auctionLifecycleId: 'life-1', revision: 9 }, expected: false },
|
||||||
{ current: { auctionLifecycleId: 'new-life', revision: 1 }, expected: false },
|
{
|
||||||
|
current: { auctionLifecycleId: 'new-life', revision: 1 },
|
||||||
|
expected: false,
|
||||||
|
},
|
||||||
])('decides whether projection can apply %#', ({ current, expected }) => {
|
])('decides whether projection can apply %#', ({ current, expected }) => {
|
||||||
expect(shouldApplyAuctionProjection(current, payload)).toBe(expected);
|
expect(shouldApplyAuctionProjection(current, payload)).toBe(expected);
|
||||||
});
|
});
|
||||||
@@ -100,14 +103,23 @@ describe('auction durability projection helpers', () => {
|
|||||||
it.each([
|
it.each([
|
||||||
{ current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true },
|
{ current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true },
|
||||||
{ current: { auctionLifecycleId: 'life-1', revision: 9 }, expected: true },
|
{ current: { auctionLifecycleId: 'life-1', revision: 9 }, expected: true },
|
||||||
{ current: { auctionLifecycleId: 'life-1', revision: 10 }, expected: false },
|
{
|
||||||
{ current: { auctionLifecycleId: 'new-life', revision: 1 }, expected: false },
|
current: { auctionLifecycleId: 'life-1', revision: 10 },
|
||||||
|
expected: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
current: { auctionLifecycleId: 'new-life', revision: 1 },
|
||||||
|
expected: false,
|
||||||
|
},
|
||||||
{ current: {}, expected: false },
|
{ current: {}, expected: false },
|
||||||
])('decides whether a durability payload can be processed %#', ({ current, expected }) => {
|
])(
|
||||||
expect(shouldProcessAuctionDurabilityPayload(current, payload)).toBe(
|
'decides whether a durability payload can be processed %#',
|
||||||
expected,
|
({ current, expected }) => {
|
||||||
);
|
expect(shouldProcessAuctionDurabilityPayload(current, payload)).toBe(
|
||||||
});
|
expected,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
it('reads due durability payload keys from Redis', async () => {
|
it('reads due durability payload keys from Redis', async () => {
|
||||||
const sendCommand = jest.fn().mockResolvedValue(['payload-1']);
|
const sendCommand = jest.fn().mockResolvedValue(['payload-1']);
|
||||||
@@ -333,7 +345,10 @@ describe('auction durability projection helpers', () => {
|
|||||||
createSession: jest.fn().mockResolvedValue(session),
|
createSession: jest.fn().mockResolvedValue(session),
|
||||||
getModel: jest.fn((name: string) => {
|
getModel: jest.fn((name: string) => {
|
||||||
if (name === 'auctionHistory') {
|
if (name === 'auctionHistory') {
|
||||||
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
|
return {
|
||||||
|
deleteMany: historyDeleteMany,
|
||||||
|
updateOne: historyUpdateOne,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
if (name === 'auction') {
|
if (name === 'auction') {
|
||||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||||
@@ -404,7 +419,10 @@ describe('auction durability projection helpers', () => {
|
|||||||
createSession: jest.fn().mockResolvedValue(session),
|
createSession: jest.fn().mockResolvedValue(session),
|
||||||
getModel: jest.fn((name: string) => {
|
getModel: jest.fn((name: string) => {
|
||||||
if (name === 'auctionHistory') {
|
if (name === 'auctionHistory') {
|
||||||
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
|
return {
|
||||||
|
deleteMany: historyDeleteMany,
|
||||||
|
updateOne: historyUpdateOne,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
if (name === 'auction') {
|
if (name === 'auction') {
|
||||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||||
@@ -613,7 +631,9 @@ describe('auction durability projection helpers', () => {
|
|||||||
.spyOn(scheduler, 'processDueDurabilityPayloads')
|
.spyOn(scheduler, 'processDueDurabilityPayloads')
|
||||||
.mockResolvedValue({ applied: 0, failed: 0, skipped: 0 });
|
.mockResolvedValue({ applied: 0, failed: 0, skipped: 0 });
|
||||||
|
|
||||||
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick();
|
await (
|
||||||
|
scheduler as unknown as { safeTick: () => Promise<void> }
|
||||||
|
).safeTick();
|
||||||
|
|
||||||
const auctionRedisService = (
|
const auctionRedisService = (
|
||||||
scheduler as unknown as {
|
scheduler as unknown as {
|
||||||
@@ -649,7 +669,9 @@ describe('auction durability projection helpers', () => {
|
|||||||
.spyOn(scheduler, 'processDueDurabilityPayloads')
|
.spyOn(scheduler, 'processDueDurabilityPayloads')
|
||||||
.mockResolvedValue({ applied: 0, failed: 0, skipped: 0 });
|
.mockResolvedValue({ applied: 0, failed: 0, skipped: 0 });
|
||||||
|
|
||||||
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick();
|
await (
|
||||||
|
scheduler as unknown as { safeTick: () => Promise<void> }
|
||||||
|
).safeTick();
|
||||||
|
|
||||||
const auctionRedisService = (
|
const auctionRedisService = (
|
||||||
scheduler as unknown as {
|
scheduler as unknown as {
|
||||||
@@ -747,7 +769,8 @@ describe('auction durability projection helpers', () => {
|
|||||||
if (name === 'auctionSideEffectApplication') {
|
if (name === 'auctionSideEffectApplication') {
|
||||||
return { updateOne: sideEffectUpdateOne };
|
return { updateOne: sideEffectUpdateOne };
|
||||||
}
|
}
|
||||||
if (name === 'match') return { findById: jest.fn().mockReturnValue(match) };
|
if (name === 'match')
|
||||||
|
return { findById: jest.fn().mockReturnValue(match) };
|
||||||
return {};
|
return {};
|
||||||
}),
|
}),
|
||||||
} as never,
|
} as never,
|
||||||
@@ -829,26 +852,18 @@ describe('auction durability projection helpers', () => {
|
|||||||
matchSideEffectRevision: 3,
|
matchSideEffectRevision: 3,
|
||||||
matchSideEffectStatus: 'completed',
|
matchSideEffectStatus: 'completed',
|
||||||
});
|
});
|
||||||
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(
|
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(1, 'match-1', {
|
||||||
1,
|
auctionLifecycleId: 'life-1',
|
||||||
'match-1',
|
currentServerTimestampMS: 2000,
|
||||||
{
|
matchSideEffectRevision: 2,
|
||||||
auctionLifecycleId: 'life-1',
|
matchSideEffectStatus: 'processing',
|
||||||
currentServerTimestampMS: 2000,
|
});
|
||||||
matchSideEffectRevision: 2,
|
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(2, 'match-1', {
|
||||||
matchSideEffectStatus: 'processing',
|
auctionLifecycleId: 'life-1',
|
||||||
},
|
currentServerTimestampMS: 3000,
|
||||||
);
|
matchSideEffectRevision: 3,
|
||||||
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(
|
matchSideEffectStatus: 'completed',
|
||||||
2,
|
});
|
||||||
'match-1',
|
|
||||||
{
|
|
||||||
auctionLifecycleId: 'life-1',
|
|
||||||
currentServerTimestampMS: 3000,
|
|
||||||
matchSideEffectRevision: 3,
|
|
||||||
matchSideEffectStatus: 'completed',
|
|
||||||
},
|
|
||||||
);
|
|
||||||
expect(sendCommand).toHaveBeenCalledWith([
|
expect(sendCommand).toHaveBeenCalledWith([
|
||||||
'EVAL',
|
'EVAL',
|
||||||
expect.stringContaining("redis.call('EXPIRE'"),
|
expect.stringContaining("redis.call('EXPIRE'"),
|
||||||
@@ -870,6 +885,101 @@ describe('auction durability projection helpers', () => {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('fails sync match teams side effect when the completed projection has no teams', async () => {
|
||||||
|
const completePayload = {
|
||||||
|
...payload,
|
||||||
|
afterAuctionMongoProjection: {
|
||||||
|
auctionTeams: [],
|
||||||
|
matchSideEffectRevision: 1,
|
||||||
|
phase: 'complete',
|
||||||
|
revision: 10,
|
||||||
|
},
|
||||||
|
auctionActionType: 'complete',
|
||||||
|
matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' },
|
||||||
|
revision: 10,
|
||||||
|
} as const;
|
||||||
|
const match = {
|
||||||
|
participants: [],
|
||||||
|
save: jest.fn().mockResolvedValue(undefined),
|
||||||
|
status: 'team-built',
|
||||||
|
teamBuiltAt: undefined,
|
||||||
|
teams: [],
|
||||||
|
};
|
||||||
|
const historyUpdateOne = jest.fn().mockReturnValue({
|
||||||
|
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
|
||||||
|
});
|
||||||
|
const auctionUpdateOne = jest.fn().mockReturnValue({
|
||||||
|
exec: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
|
||||||
|
});
|
||||||
|
const auctionFindOneAndUpdate = jest
|
||||||
|
.fn()
|
||||||
|
.mockReturnValueOnce({
|
||||||
|
exec: jest.fn().mockResolvedValue({
|
||||||
|
auctionLifecycleId: 'life-1',
|
||||||
|
matchSideEffectRevision: 2,
|
||||||
|
matchSideEffectStatus: 'processing',
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.mockReturnValueOnce({
|
||||||
|
exec: jest.fn().mockResolvedValue({
|
||||||
|
auctionLifecycleId: 'life-1',
|
||||||
|
matchSideEffectRevision: 3,
|
||||||
|
matchSideEffectStatus: 'failed',
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const sideEffectUpdateOne = jest.fn().mockReturnValue({
|
||||||
|
exec: jest.fn().mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }),
|
||||||
|
});
|
||||||
|
const reserveForMatch = jest.fn().mockResolvedValue(match);
|
||||||
|
const scheduleInitialPoll = jest.fn().mockResolvedValue(null);
|
||||||
|
const mirrorMatchSideEffectStatus = jest.fn().mockResolvedValue(true);
|
||||||
|
const broadcastMatchSideEffect = jest.fn();
|
||||||
|
const scheduler = new AuctionDurabilityScheduler(
|
||||||
|
{
|
||||||
|
createSession: jest.fn().mockResolvedValue(null),
|
||||||
|
getModel: jest.fn((name: string) => {
|
||||||
|
if (name === 'auctionHistory') return { updateOne: historyUpdateOne };
|
||||||
|
if (name === 'auction') {
|
||||||
|
return {
|
||||||
|
findOneAndUpdate: auctionFindOneAndUpdate,
|
||||||
|
updateOne: auctionUpdateOne,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (name === 'auctionSideEffectApplication') {
|
||||||
|
return { updateOne: sideEffectUpdateOne };
|
||||||
|
}
|
||||||
|
if (name === 'match')
|
||||||
|
return { findById: jest.fn().mockReturnValue(match) };
|
||||||
|
return {};
|
||||||
|
}),
|
||||||
|
} as never,
|
||||||
|
{
|
||||||
|
getCurrentRedisTimestampMS: jest
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(2000)
|
||||||
|
.mockResolvedValueOnce(3000),
|
||||||
|
raw: jest.fn().mockReturnValue({ sendCommand: jest.fn() }),
|
||||||
|
} as never,
|
||||||
|
{ reserveForMatch } as never,
|
||||||
|
{ scheduleInitialPoll } as never,
|
||||||
|
{ mirrorMatchSideEffectStatus } as never,
|
||||||
|
{ broadcastMatchSideEffect } as never,
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
scheduler.applyDurabilityPayload(completePayload),
|
||||||
|
).rejects.toThrow('produced no match teams');
|
||||||
|
|
||||||
|
expect(match.save).not.toHaveBeenCalled();
|
||||||
|
expect(reserveForMatch).not.toHaveBeenCalled();
|
||||||
|
expect(scheduleInitialPoll).not.toHaveBeenCalled();
|
||||||
|
expect(mirrorMatchSideEffectStatus).toHaveBeenLastCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
matchSideEffectStatus: 'failed',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('applies reset match side effect after durable projection', async () => {
|
it('applies reset match side effect after durable projection', async () => {
|
||||||
const resetPayload = {
|
const resetPayload = {
|
||||||
...payload,
|
...payload,
|
||||||
@@ -943,7 +1053,10 @@ describe('auction durability projection helpers', () => {
|
|||||||
createSession: jest.fn().mockResolvedValue(null),
|
createSession: jest.fn().mockResolvedValue(null),
|
||||||
getModel: jest.fn((name: string) => {
|
getModel: jest.fn((name: string) => {
|
||||||
if (name === 'auctionHistory') {
|
if (name === 'auctionHistory') {
|
||||||
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
|
return {
|
||||||
|
deleteMany: historyDeleteMany,
|
||||||
|
updateOne: historyUpdateOne,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
if (name === 'auction') {
|
if (name === 'auction') {
|
||||||
return {
|
return {
|
||||||
@@ -955,7 +1068,8 @@ describe('auction durability projection helpers', () => {
|
|||||||
if (name === 'auctionSideEffectApplication') {
|
if (name === 'auctionSideEffectApplication') {
|
||||||
return { updateOne: sideEffectUpdateOne };
|
return { updateOne: sideEffectUpdateOne };
|
||||||
}
|
}
|
||||||
if (name === 'match') return { findById: jest.fn().mockReturnValue(match) };
|
if (name === 'match')
|
||||||
|
return { findById: jest.fn().mockReturnValue(match) };
|
||||||
return {};
|
return {};
|
||||||
}),
|
}),
|
||||||
} as never,
|
} as never,
|
||||||
@@ -985,7 +1099,10 @@ describe('auction durability projection helpers', () => {
|
|||||||
teams: [],
|
teams: [],
|
||||||
tournamentCodeIds: [],
|
tournamentCodeIds: [],
|
||||||
});
|
});
|
||||||
expect(match.participants).toEqual([{ excluded: false }, { excluded: false }]);
|
expect(match.participants).toEqual([
|
||||||
|
{ excluded: false },
|
||||||
|
{ excluded: false },
|
||||||
|
]);
|
||||||
expect(match.save).toHaveBeenCalledTimes(1);
|
expect(match.save).toHaveBeenCalledTimes(1);
|
||||||
expect(sideEffectUpdateOne).toHaveBeenCalledWith(
|
expect(sideEffectUpdateOne).toHaveBeenCalledWith(
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
|
|||||||
@@ -128,15 +128,17 @@ export class AuctionDurabilityScheduler
|
|||||||
currentRedisTimestampMS: number,
|
currentRedisTimestampMS: number,
|
||||||
batchLimit: number,
|
batchLimit: number,
|
||||||
): Promise<string[]> {
|
): Promise<string[]> {
|
||||||
const reply = await this.auctionRedisService.raw().sendCommand([
|
const reply = await this.auctionRedisService
|
||||||
'ZRANGEBYSCORE',
|
.raw()
|
||||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
.sendCommand([
|
||||||
'-inf',
|
'ZRANGEBYSCORE',
|
||||||
String(currentRedisTimestampMS),
|
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||||
'LIMIT',
|
'-inf',
|
||||||
'0',
|
String(currentRedisTimestampMS),
|
||||||
String(batchLimit),
|
'LIMIT',
|
||||||
]);
|
'0',
|
||||||
|
String(batchLimit),
|
||||||
|
]);
|
||||||
return Array.isArray(reply) ? reply.map(String) : [];
|
return Array.isArray(reply) ? reply.map(String) : [];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,12 +170,11 @@ export class AuctionDurabilityScheduler
|
|||||||
await this.clearDurabilityPayload(payloadKey);
|
await this.clearDurabilityPayload(payloadKey);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
failed += 1;
|
failed += 1;
|
||||||
const failureDisposition =
|
const failureDisposition = await this.recordDurabilityPayloadFailure(
|
||||||
await this.recordDurabilityPayloadFailure(
|
payloadKey,
|
||||||
payloadKey,
|
currentRedisTimestampMS,
|
||||||
currentRedisTimestampMS,
|
error,
|
||||||
error,
|
);
|
||||||
);
|
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Auction durability payload failed for ${payloadKey} (${failureDisposition}): ${
|
`Auction durability payload failed for ${payloadKey} (${failureDisposition}): ${
|
||||||
error instanceof Error ? error.message : error
|
error instanceof Error ? error.message : error
|
||||||
@@ -195,7 +196,9 @@ export class AuctionDurabilityScheduler
|
|||||||
const payloadJson = hash.payloadJson;
|
const payloadJson = hash.payloadJson;
|
||||||
if (!payloadJson) return null;
|
if (!payloadJson) return null;
|
||||||
const payload = JSON.parse(payloadJson) as AuctionDurabilityPayload;
|
const payload = JSON.parse(payloadJson) as AuctionDurabilityPayload;
|
||||||
const committedAtRedisTimestampMS = Number(hash.committedAtRedisTimestampMS);
|
const committedAtRedisTimestampMS = Number(
|
||||||
|
hash.committedAtRedisTimestampMS,
|
||||||
|
);
|
||||||
if (Number.isFinite(committedAtRedisTimestampMS)) {
|
if (Number.isFinite(committedAtRedisTimestampMS)) {
|
||||||
payload.committedAtRedisTimestampMS = committedAtRedisTimestampMS;
|
payload.committedAtRedisTimestampMS = committedAtRedisTimestampMS;
|
||||||
}
|
}
|
||||||
@@ -223,12 +226,15 @@ export class AuctionDurabilityScheduler
|
|||||||
try {
|
try {
|
||||||
session?.startTransaction();
|
session?.startTransaction();
|
||||||
if (typeof AuctionModel.findById === 'function') {
|
if (typeof AuctionModel.findById === 'function') {
|
||||||
const currentProjection = await readAuctionProjectionIdentityForMutation(
|
const currentProjection =
|
||||||
AuctionModel,
|
await readAuctionProjectionIdentityForMutation(
|
||||||
payload.auctionId,
|
AuctionModel,
|
||||||
session,
|
payload.auctionId,
|
||||||
);
|
session,
|
||||||
if (!shouldProcessAuctionDurabilityPayload(currentProjection, payload)) {
|
);
|
||||||
|
if (
|
||||||
|
!shouldProcessAuctionDurabilityPayload(currentProjection, payload)
|
||||||
|
) {
|
||||||
if (session) await session.commitTransaction();
|
if (session) await session.commitTransaction();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -370,15 +376,17 @@ export class AuctionDurabilityScheduler
|
|||||||
);
|
);
|
||||||
if (!hasMatchedDocument(leaseResult)) return;
|
if (!hasMatchedDocument(leaseResult)) return;
|
||||||
|
|
||||||
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus({
|
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
|
||||||
AuctionModel,
|
{
|
||||||
currentServerTimestampMS: currentRedisTimestampMS,
|
AuctionModel,
|
||||||
expectedMatchSideEffectRevision: Number(
|
currentServerTimestampMS: currentRedisTimestampMS,
|
||||||
payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
|
expectedMatchSideEffectRevision: Number(
|
||||||
),
|
payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
|
||||||
payload,
|
),
|
||||||
status: 'processing',
|
payload,
|
||||||
});
|
status: 'processing',
|
||||||
|
},
|
||||||
|
);
|
||||||
if (!processingDelta) return;
|
if (!processingDelta) return;
|
||||||
let expectedMatchSideEffectRevision =
|
let expectedMatchSideEffectRevision =
|
||||||
processingDelta.matchSideEffectRevision;
|
processingDelta.matchSideEffectRevision;
|
||||||
@@ -396,11 +404,18 @@ export class AuctionDurabilityScheduler
|
|||||||
teamBuiltAt?: Date;
|
teamBuiltAt?: Date;
|
||||||
teams: ReturnType<typeof buildMatchTeamsFromProjection>;
|
teams: ReturnType<typeof buildMatchTeamsFromProjection>;
|
||||||
} | null;
|
} | null;
|
||||||
if (!match) throw new Error(`Match not found: ${String(payload.matchId)}`);
|
if (!match)
|
||||||
match.teams = buildMatchTeamsFromProjection(
|
throw new Error(`Match not found: ${String(payload.matchId)}`);
|
||||||
|
const matchTeams = buildMatchTeamsFromProjection(
|
||||||
payload.afterAuctionMongoProjection,
|
payload.afterAuctionMongoProjection,
|
||||||
match,
|
match,
|
||||||
);
|
);
|
||||||
|
if (matchTeams.length === 0) {
|
||||||
|
throw new Error(
|
||||||
|
`Auction complete side effect produced no match teams for match ${String(payload.matchId)}.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
match.teams = matchTeams;
|
||||||
match.status = 'team-built';
|
match.status = 'team-built';
|
||||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||||
await match.save();
|
await match.save();
|
||||||
@@ -553,15 +568,18 @@ export class AuctionDurabilityScheduler
|
|||||||
);
|
);
|
||||||
if (!hasMatchedDocument(leaseResult)) return;
|
if (!hasMatchedDocument(leaseResult)) return;
|
||||||
|
|
||||||
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus({
|
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
|
||||||
AuctionModel,
|
{
|
||||||
currentServerTimestampMS: currentRedisTimestampMS,
|
AuctionModel,
|
||||||
expectedMatchSideEffectRevision: Number(
|
currentServerTimestampMS: currentRedisTimestampMS,
|
||||||
params.payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
|
expectedMatchSideEffectRevision: Number(
|
||||||
),
|
params.payload.afterAuctionMongoProjection.matchSideEffectRevision ??
|
||||||
payload: params.payload,
|
0,
|
||||||
status: 'processing',
|
),
|
||||||
});
|
payload: params.payload,
|
||||||
|
status: 'processing',
|
||||||
|
},
|
||||||
|
);
|
||||||
if (!processingDelta) return;
|
if (!processingDelta) return;
|
||||||
let expectedMatchSideEffectRevision =
|
let expectedMatchSideEffectRevision =
|
||||||
processingDelta.matchSideEffectRevision;
|
processingDelta.matchSideEffectRevision;
|
||||||
@@ -605,7 +623,8 @@ export class AuctionDurabilityScheduler
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
const failureTimestampMS =
|
const failureTimestampMS =
|
||||||
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
||||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
const errorMessage =
|
||||||
|
error instanceof Error ? error.message : String(error);
|
||||||
await execMaybe(
|
await execMaybe(
|
||||||
AuctionSideEffectApplicationModel.updateOne(
|
AuctionSideEffectApplicationModel.updateOne(
|
||||||
identity as never,
|
identity as never,
|
||||||
@@ -658,7 +677,9 @@ export class AuctionDurabilityScheduler
|
|||||||
payload: AuctionDurabilityPayload;
|
payload: AuctionDurabilityPayload;
|
||||||
session: mongoose.ClientSession | null | undefined;
|
session: mongoose.ClientSession | null | undefined;
|
||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
const mutation = parseAuctionHistoryMutation(params.payload.historyMutation);
|
const mutation = parseAuctionHistoryMutation(
|
||||||
|
params.payload.historyMutation,
|
||||||
|
);
|
||||||
if (isDestructiveHistoryMutation(mutation)) {
|
if (isDestructiveHistoryMutation(mutation)) {
|
||||||
if (mutation.type === 'deleteAfterSequenceAndAppendUndo') {
|
if (mutation.type === 'deleteAfterSequenceAndAppendUndo') {
|
||||||
if (!params.AuctionHistoryModel.deleteMany) {
|
if (!params.AuctionHistoryModel.deleteMany) {
|
||||||
@@ -689,7 +710,9 @@ export class AuctionDurabilityScheduler
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const historyOperation = buildAuctionHistoryUpsert(params.payload).updateOne;
|
const historyOperation = buildAuctionHistoryUpsert(
|
||||||
|
params.payload,
|
||||||
|
).updateOne;
|
||||||
await execMaybe(
|
await execMaybe(
|
||||||
params.AuctionHistoryModel.updateOne(
|
params.AuctionHistoryModel.updateOne(
|
||||||
historyOperation.filter as never,
|
historyOperation.filter as never,
|
||||||
@@ -731,7 +754,9 @@ export class AuctionDurabilityScheduler
|
|||||||
: {}),
|
: {}),
|
||||||
matchSideEffectStatus: params.status,
|
matchSideEffectStatus: params.status,
|
||||||
},
|
},
|
||||||
...(params.errorMessage ? {} : { $unset: { matchSideEffectError: '' } }),
|
...(params.errorMessage
|
||||||
|
? {}
|
||||||
|
: { $unset: { matchSideEffectError: '' } }),
|
||||||
} as never,
|
} as never,
|
||||||
{
|
{
|
||||||
projection: {
|
projection: {
|
||||||
@@ -742,13 +767,11 @@ export class AuctionDurabilityScheduler
|
|||||||
returnDocument: 'after',
|
returnDocument: 'after',
|
||||||
} as never,
|
} as never,
|
||||||
),
|
),
|
||||||
)) as
|
)) as {
|
||||||
| {
|
auctionLifecycleId?: string;
|
||||||
auctionLifecycleId?: string;
|
matchSideEffectRevision?: number;
|
||||||
matchSideEffectRevision?: number;
|
matchSideEffectStatus?: AuctionMatchSideEffectStatus;
|
||||||
matchSideEffectStatus?: AuctionMatchSideEffectStatus;
|
} | null;
|
||||||
}
|
|
||||||
| null;
|
|
||||||
if (!updatedAuction?.auctionLifecycleId) return null;
|
if (!updatedAuction?.auctionLifecycleId) return null;
|
||||||
|
|
||||||
const delta = buildMatchSideEffectDelta({
|
const delta = buildMatchSideEffectDelta({
|
||||||
@@ -815,12 +838,14 @@ export class AuctionDurabilityScheduler
|
|||||||
payloadKey: string,
|
payloadKey: string,
|
||||||
retryAtRedisTimestampMS: number,
|
retryAtRedisTimestampMS: number,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await this.auctionRedisService.raw().sendCommand([
|
await this.auctionRedisService
|
||||||
'ZADD',
|
.raw()
|
||||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
.sendCommand([
|
||||||
String(retryAtRedisTimestampMS),
|
'ZADD',
|
||||||
payloadKey,
|
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||||
]);
|
String(retryAtRedisTimestampMS),
|
||||||
|
payloadKey,
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async recordDurabilityPayloadFailure(
|
private async recordDurabilityPayloadFailure(
|
||||||
@@ -829,43 +854,44 @@ export class AuctionDurabilityScheduler
|
|||||||
error: unknown,
|
error: unknown,
|
||||||
): Promise<'dead-lettered' | 'requeued'> {
|
): Promise<'dead-lettered' | 'requeued'> {
|
||||||
const errorMessage = formatErrorMessageForRedis(error);
|
const errorMessage = formatErrorMessageForRedis(error);
|
||||||
const attemptReply = await this.auctionRedisService.raw().sendCommand([
|
const attemptReply = await this.auctionRedisService
|
||||||
'HINCRBY',
|
.raw()
|
||||||
payloadKey,
|
.sendCommand(['HINCRBY', payloadKey, 'attempts', '1']);
|
||||||
'attempts',
|
|
||||||
'1',
|
|
||||||
]);
|
|
||||||
const attempts = Number(attemptReply);
|
const attempts = Number(attemptReply);
|
||||||
await this.auctionRedisService.raw().sendCommand([
|
await this.auctionRedisService
|
||||||
'HSET',
|
.raw()
|
||||||
payloadKey,
|
.sendCommand([
|
||||||
'lastError',
|
'HSET',
|
||||||
errorMessage,
|
payloadKey,
|
||||||
'lastFailedAtRedisTimestampMS',
|
'lastError',
|
||||||
String(currentRedisTimestampMS),
|
errorMessage,
|
||||||
]);
|
'lastFailedAtRedisTimestampMS',
|
||||||
|
String(currentRedisTimestampMS),
|
||||||
|
]);
|
||||||
|
|
||||||
if (
|
if (
|
||||||
Number.isFinite(attempts) &&
|
Number.isFinite(attempts) &&
|
||||||
attempts >= AUCTION_DURABILITY_MAX_ATTEMPTS
|
attempts >= AUCTION_DURABILITY_MAX_ATTEMPTS
|
||||||
) {
|
) {
|
||||||
await this.auctionRedisService.raw().sendCommand([
|
await this.auctionRedisService
|
||||||
'ZREM',
|
.raw()
|
||||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
.sendCommand(['ZREM', AUCTION_DURABILITY_RETRY_QUEUE_KEY, payloadKey]);
|
||||||
payloadKey,
|
await this.auctionRedisService
|
||||||
]);
|
.raw()
|
||||||
await this.auctionRedisService.raw().sendCommand([
|
.sendCommand([
|
||||||
'HSET',
|
'HSET',
|
||||||
payloadKey,
|
payloadKey,
|
||||||
'deadLetteredAtRedisTimestampMS',
|
'deadLetteredAtRedisTimestampMS',
|
||||||
String(currentRedisTimestampMS),
|
String(currentRedisTimestampMS),
|
||||||
]);
|
]);
|
||||||
await this.auctionRedisService.raw().sendCommand([
|
await this.auctionRedisService
|
||||||
'ZADD',
|
.raw()
|
||||||
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
|
.sendCommand([
|
||||||
String(currentRedisTimestampMS),
|
'ZADD',
|
||||||
payloadKey,
|
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
|
||||||
]);
|
String(currentRedisTimestampMS),
|
||||||
|
payloadKey,
|
||||||
|
]);
|
||||||
return 'dead-lettered';
|
return 'dead-lettered';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -881,38 +907,40 @@ export class AuctionDurabilityScheduler
|
|||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const matchId = String(payload.matchId);
|
const matchId = String(payload.matchId);
|
||||||
const keys = buildAuctionRedisKeys(matchId);
|
const keys = buildAuctionRedisKeys(matchId);
|
||||||
await this.auctionRedisService.raw().sendCommand([
|
await this.auctionRedisService
|
||||||
'EVAL',
|
.raw()
|
||||||
[
|
.sendCommand([
|
||||||
"local expectedAuctionLifecycleId = ARGV[2]",
|
'EVAL',
|
||||||
"local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
|
[
|
||||||
"if currentAuctionLifecycleId ~= expectedAuctionLifecycleId then",
|
'local expectedAuctionLifecycleId = ARGV[2]',
|
||||||
' return 0',
|
"local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
|
||||||
'end',
|
'if currentAuctionLifecycleId ~= expectedAuctionLifecycleId then',
|
||||||
"redis.call('ZREM', KEYS[2], ARGV[1])",
|
' return 0',
|
||||||
'for index = 1, #KEYS do',
|
'end',
|
||||||
' if index ~= 2 then',
|
"redis.call('ZREM', KEYS[2], ARGV[1])",
|
||||||
" redis.call('EXPIRE', KEYS[index], ARGV[3])",
|
'for index = 1, #KEYS do',
|
||||||
' end',
|
' if index ~= 2 then',
|
||||||
'end',
|
" redis.call('EXPIRE', KEYS[index], ARGV[3])",
|
||||||
'return 1',
|
' end',
|
||||||
].join('\n'),
|
'end',
|
||||||
'11',
|
'return 1',
|
||||||
keys.liveStateKey,
|
].join('\n'),
|
||||||
keys.deadlineQueueKey,
|
'11',
|
||||||
keys.structureStateKey,
|
keys.liveStateKey,
|
||||||
keys.appliedTransitionIdsKey,
|
keys.deadlineQueueKey,
|
||||||
keys.bidHistoryKey,
|
keys.structureStateKey,
|
||||||
keys.bidRequestResultsKey,
|
keys.appliedTransitionIdsKey,
|
||||||
keys.bidRequestResultOrderKey,
|
keys.bidHistoryKey,
|
||||||
keys.actionRequestResultsKey,
|
keys.bidRequestResultsKey,
|
||||||
keys.actionRequestResultOrderKey,
|
keys.bidRequestResultOrderKey,
|
||||||
keys.rehydrateLockKey,
|
keys.actionRequestResultsKey,
|
||||||
keys.stateTransitionLockKey,
|
keys.actionRequestResultOrderKey,
|
||||||
matchId,
|
keys.rehydrateLockKey,
|
||||||
payload.auctionLifecycleId,
|
keys.stateTransitionLockKey,
|
||||||
String(AUCTION_REDIS_COMPLETED_RETAIN_SECONDS),
|
matchId,
|
||||||
]);
|
payload.auctionLifecycleId,
|
||||||
|
String(AUCTION_REDIS_COMPLETED_RETAIN_SECONDS),
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -961,7 +989,9 @@ export function parseAuctionHistoryMutation(
|
|||||||
}
|
}
|
||||||
if (record.type === 'reset') {
|
if (record.type === 'reset') {
|
||||||
const resetMode =
|
const resetMode =
|
||||||
record.resetMode === 'preserve-audit' ? 'preserve-audit' : 'clear-history';
|
record.resetMode === 'preserve-audit'
|
||||||
|
? 'preserve-audit'
|
||||||
|
: 'clear-history';
|
||||||
return { resetMode, type: 'reset' };
|
return { resetMode, type: 'reset' };
|
||||||
}
|
}
|
||||||
return { type: 'append' };
|
return { type: 'append' };
|
||||||
@@ -1055,7 +1085,10 @@ export function buildSideEffectApplicationUpsert(
|
|||||||
payload: AuctionDurabilityPayload,
|
payload: AuctionDurabilityPayload,
|
||||||
mutation: ParsedMatchSideEffectMutation,
|
mutation: ParsedMatchSideEffectMutation,
|
||||||
) {
|
) {
|
||||||
const identity = buildSideEffectApplicationIdentityFromPayload(payload, mutation);
|
const identity = buildSideEffectApplicationIdentityFromPayload(
|
||||||
|
payload,
|
||||||
|
mutation,
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
filter: identity,
|
filter: identity,
|
||||||
update: {
|
update: {
|
||||||
@@ -1100,7 +1133,12 @@ function buildSideEffectApplicationIdentityFromPayload(
|
|||||||
|
|
||||||
function hashStableJson(value: unknown): string {
|
function hashStableJson(value: unknown): string {
|
||||||
return createHash('sha256')
|
return createHash('sha256')
|
||||||
.update(JSON.stringify(value, Object.keys(value as Record<string, unknown>).sort()))
|
.update(
|
||||||
|
JSON.stringify(
|
||||||
|
value,
|
||||||
|
Object.keys(value as Record<string, unknown>).sort(),
|
||||||
|
),
|
||||||
|
)
|
||||||
.digest('hex');
|
.digest('hex');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1140,13 +1178,16 @@ function buildMatchTeamsFromProjection(
|
|||||||
const members: MatchTeamMember[] = [
|
const members: MatchTeamMember[] = [
|
||||||
{
|
{
|
||||||
assignedPosition:
|
assignedPosition:
|
||||||
(captain?.preferredPositions?.[0]?.position as Position | undefined) ??
|
(captain?.preferredPositions?.[0]?.position as
|
||||||
'MID',
|
| Position
|
||||||
|
| undefined) ?? 'MID',
|
||||||
cost: 0,
|
cost: 0,
|
||||||
userId: captainUserId,
|
userId: captainUserId,
|
||||||
},
|
},
|
||||||
...rawMembers
|
...rawMembers
|
||||||
.filter((member) => member.userId?.toString() !== captainUserId.toString())
|
.filter(
|
||||||
|
(member) => member.userId?.toString() !== captainUserId.toString(),
|
||||||
|
)
|
||||||
.map((member) => ({
|
.map((member) => ({
|
||||||
assignedPosition: (member.assignedPosition ?? 'MID') as Position,
|
assignedPosition: (member.assignedPosition ?? 'MID') as Position,
|
||||||
cost: Number(member.memberAcquisitionBidPointAmount ?? 0),
|
cost: Number(member.memberAcquisitionBidPointAmount ?? 0),
|
||||||
@@ -1198,7 +1239,9 @@ function calculateDurabilityRetryDelayMS(attempts: number): number {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function execMaybe<T>(queryOrPromise: Promise<T> | { exec(): Promise<T> }) {
|
async function execMaybe<T>(
|
||||||
|
queryOrPromise: Promise<T> | { exec(): Promise<T> },
|
||||||
|
) {
|
||||||
if (
|
if (
|
||||||
queryOrPromise &&
|
queryOrPromise &&
|
||||||
typeof (queryOrPromise as { exec?: unknown }).exec === 'function'
|
typeof (queryOrPromise as { exec?: unknown }).exec === 'function'
|
||||||
|
|||||||
@@ -158,11 +158,12 @@ describe('AuctionService', () => {
|
|||||||
it('rejects non-positive or fractional bid amounts before loading auction state', async () => {
|
it('rejects non-positive or fractional bid amounts before loading auction state', async () => {
|
||||||
const matchId = new mongoose.Types.ObjectId();
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
const auctionFindOne = jest.fn();
|
const auctionFindOne = jest.fn();
|
||||||
const { service, auctionRedisCommandService, auctionRedisService } = createService({
|
const { service, auctionRedisCommandService, auctionRedisService } =
|
||||||
auction: {
|
createService({
|
||||||
findOne: auctionFindOne,
|
auction: {
|
||||||
},
|
findOne: auctionFindOne,
|
||||||
});
|
},
|
||||||
|
});
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
service.placeBid({
|
service.placeBid({
|
||||||
@@ -266,7 +267,7 @@ describe('AuctionService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
expect(match.status).toBe('team-built');
|
expect(match.status).toBe('team-built');
|
||||||
expect(match.teamBuiltAt).toBeInstanceOf(Date);
|
expect(match.teamBuiltAt).toBeUndefined();
|
||||||
expect(match.save).toHaveBeenCalledTimes(1);
|
expect(match.save).toHaveBeenCalledTimes(1);
|
||||||
expect(tournamentCodeService.reserveForMatch).not.toHaveBeenCalled();
|
expect(tournamentCodeService.reserveForMatch).not.toHaveBeenCalled();
|
||||||
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
|
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
|
||||||
@@ -542,44 +543,45 @@ describe('AuctionService', () => {
|
|||||||
}));
|
}));
|
||||||
const auctionDeleteOne = jest.fn().mockResolvedValue({ deletedCount: 1 });
|
const auctionDeleteOne = jest.fn().mockResolvedValue({ deletedCount: 1 });
|
||||||
const historyDeleteMany = jest.fn().mockResolvedValue({ deletedCount: 2 });
|
const historyDeleteMany = jest.fn().mockResolvedValue({ deletedCount: 2 });
|
||||||
const { service, auctionRedisCommandService, auctionRedisService } = createService({
|
const { service, auctionRedisCommandService, auctionRedisService } =
|
||||||
match: {
|
createService({
|
||||||
findById: jest.fn().mockResolvedValue(match),
|
match: {
|
||||||
},
|
findById: jest.fn().mockResolvedValue(match),
|
||||||
user: {
|
},
|
||||||
find: jest.fn().mockResolvedValue(users),
|
user: {
|
||||||
},
|
find: jest.fn().mockResolvedValue(users),
|
||||||
auction: {
|
},
|
||||||
create: auctionCreate,
|
auction: {
|
||||||
deleteOne: auctionDeleteOne,
|
create: auctionCreate,
|
||||||
findOne: jest.fn().mockResolvedValue(existingAuction),
|
deleteOne: auctionDeleteOne,
|
||||||
},
|
findOne: jest.fn().mockResolvedValue(existingAuction),
|
||||||
auctionHistory: {
|
},
|
||||||
create: jest.fn().mockResolvedValue(undefined),
|
auctionHistory: {
|
||||||
deleteMany: historyDeleteMany,
|
create: jest.fn().mockResolvedValue(undefined),
|
||||||
findOne: jest.fn().mockReturnValue({
|
deleteMany: historyDeleteMany,
|
||||||
sort: jest.fn().mockReturnValue({
|
findOne: jest.fn().mockReturnValue({
|
||||||
|
sort: jest.fn().mockReturnValue({
|
||||||
|
select: jest.fn().mockReturnValue({
|
||||||
|
lean: jest.fn().mockReturnValue({
|
||||||
|
exec: jest.fn().mockResolvedValue(null),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
community: {
|
||||||
|
findById: jest.fn().mockReturnValue({
|
||||||
select: jest.fn().mockReturnValue({
|
select: jest.fn().mockReturnValue({
|
||||||
lean: jest.fn().mockReturnValue({
|
lean: jest.fn().mockReturnValue({
|
||||||
exec: jest.fn().mockResolvedValue(null),
|
exec: jest.fn().mockResolvedValue({
|
||||||
|
riotPlatform: 'kr',
|
||||||
|
riotRegion: 'asia',
|
||||||
|
}),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
}),
|
},
|
||||||
},
|
});
|
||||||
community: {
|
|
||||||
findById: jest.fn().mockReturnValue({
|
|
||||||
select: jest.fn().mockReturnValue({
|
|
||||||
lean: jest.fn().mockReturnValue({
|
|
||||||
exec: jest.fn().mockResolvedValue({
|
|
||||||
riotPlatform: 'kr',
|
|
||||||
riotRegion: 'asia',
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
await service.start({
|
await service.start({
|
||||||
matchId,
|
matchId,
|
||||||
@@ -800,7 +802,9 @@ describe('AuctionService', () => {
|
|||||||
findOne: jest.fn().mockResolvedValue(auction),
|
findOne: jest.fn().mockResolvedValue(auction),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
auctionRedisStateReaderService.readLiveStateIdentity.mockResolvedValue(null);
|
auctionRedisStateReaderService.readLiveStateIdentity.mockResolvedValue(
|
||||||
|
null,
|
||||||
|
);
|
||||||
auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue(
|
auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue(
|
||||||
redisState,
|
redisState,
|
||||||
);
|
);
|
||||||
@@ -870,12 +874,15 @@ describe('AuctionService', () => {
|
|||||||
phase: 'bidding',
|
phase: 'bidding',
|
||||||
revision: 2,
|
revision: 2,
|
||||||
};
|
};
|
||||||
const { service, auctionRedisCommandService, auctionRedisStateReaderService } =
|
const {
|
||||||
createService({
|
service,
|
||||||
auction: {
|
auctionRedisCommandService,
|
||||||
findOne: jest.fn().mockResolvedValue(auction),
|
auctionRedisStateReaderService,
|
||||||
},
|
} = createService({
|
||||||
});
|
auction: {
|
||||||
|
findOne: jest.fn().mockResolvedValue(auction),
|
||||||
|
},
|
||||||
|
});
|
||||||
auctionRedisStateReaderService.readAuctionStateView
|
auctionRedisStateReaderService.readAuctionStateView
|
||||||
.mockResolvedValueOnce(presentingState)
|
.mockResolvedValueOnce(presentingState)
|
||||||
.mockResolvedValueOnce(biddingState);
|
.mockResolvedValueOnce(biddingState);
|
||||||
@@ -973,12 +980,15 @@ describe('AuctionService', () => {
|
|||||||
currentHighestBidPointAmount: 120,
|
currentHighestBidPointAmount: 120,
|
||||||
revision: 3,
|
revision: 3,
|
||||||
};
|
};
|
||||||
const { service, auctionRedisCommandService, auctionRedisStateReaderService } =
|
const {
|
||||||
createService({
|
service,
|
||||||
auction: {
|
auctionRedisCommandService,
|
||||||
findOne: jest.fn().mockResolvedValue(auction),
|
auctionRedisStateReaderService,
|
||||||
},
|
} = createService({
|
||||||
});
|
auction: {
|
||||||
|
findOne: jest.fn().mockResolvedValue(auction),
|
||||||
|
},
|
||||||
|
});
|
||||||
auctionRedisStateReaderService.readAuctionStateView
|
auctionRedisStateReaderService.readAuctionStateView
|
||||||
.mockResolvedValueOnce(biddingState)
|
.mockResolvedValueOnce(biddingState)
|
||||||
.mockResolvedValueOnce(afterBidState);
|
.mockResolvedValueOnce(afterBidState);
|
||||||
@@ -1189,15 +1199,14 @@ describe('AuctionService', () => {
|
|||||||
auctionRedisStateReaderService,
|
auctionRedisStateReaderService,
|
||||||
tournamentCodeService,
|
tournamentCodeService,
|
||||||
tournamentResultService,
|
tournamentResultService,
|
||||||
} =
|
} = createService({
|
||||||
createService({
|
auction: {
|
||||||
auction: {
|
findOne: jest.fn().mockResolvedValue(auction),
|
||||||
findOne: jest.fn().mockResolvedValue(auction),
|
},
|
||||||
},
|
match: {
|
||||||
match: {
|
findById: jest.fn().mockResolvedValue(match),
|
||||||
findById: jest.fn().mockResolvedValue(match),
|
},
|
||||||
},
|
});
|
||||||
});
|
|
||||||
auctionRedisStateReaderService.readAuctionStateView
|
auctionRedisStateReaderService.readAuctionStateView
|
||||||
.mockResolvedValueOnce(soldState)
|
.mockResolvedValueOnce(soldState)
|
||||||
.mockResolvedValueOnce(completeState);
|
.mockResolvedValueOnce(completeState);
|
||||||
@@ -1377,8 +1386,7 @@ describe('AuctionService', () => {
|
|||||||
|
|
||||||
const signupOrder = userIds.slice(2).map((userId) => userId.toString());
|
const signupOrder = userIds.slice(2).map((userId) => userId.toString());
|
||||||
const auctionOrder = auctionCreate.mock.calls[0][0].order.map(
|
const auctionOrder = auctionCreate.mock.calls[0][0].order.map(
|
||||||
(player: { userId: mongoose.Types.ObjectId }) =>
|
(player: { userId: mongoose.Types.ObjectId }) => player.userId.toString(),
|
||||||
player.userId.toString(),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(auctionOrder).not.toEqual(signupOrder);
|
expect(auctionOrder).not.toEqual(signupOrder);
|
||||||
@@ -1647,9 +1655,7 @@ describe('AuctionService', () => {
|
|||||||
amount: 20,
|
amount: 20,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(auction.currentDeadline).toEqual(
|
expect(auction.currentDeadline).toEqual(new Date(now.getTime() + 12000));
|
||||||
new Date(now.getTime() + 12000),
|
|
||||||
);
|
|
||||||
expect(auction.save).toHaveBeenCalledTimes(1);
|
expect(auction.save).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -2151,21 +2157,25 @@ describe('AuctionService', () => {
|
|||||||
const auctionReplaceOne = jest.fn().mockReturnValue({
|
const auctionReplaceOne = jest.fn().mockReturnValue({
|
||||||
exec: jest.fn().mockResolvedValue(undefined),
|
exec: jest.fn().mockResolvedValue(undefined),
|
||||||
});
|
});
|
||||||
const { service, connectionService, tournamentCodeService, tournamentResultService } =
|
const {
|
||||||
createService({
|
service,
|
||||||
auction: {
|
connectionService,
|
||||||
findOne: jest.fn().mockReturnValue(auctionFindOneQuery),
|
tournamentCodeService,
|
||||||
replaceOne: auctionReplaceOne,
|
tournamentResultService,
|
||||||
findById: jest.fn().mockResolvedValue(restored),
|
} = createService({
|
||||||
},
|
auction: {
|
||||||
auctionHistory: {
|
findOne: jest.fn().mockReturnValue(auctionFindOneQuery),
|
||||||
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
|
replaceOne: auctionReplaceOne,
|
||||||
deleteMany: jest.fn().mockReturnValue(historyDeleteManyQuery),
|
findById: jest.fn().mockResolvedValue(restored),
|
||||||
},
|
},
|
||||||
match: {
|
auctionHistory: {
|
||||||
findById: jest.fn().mockReturnValue(matchFindByIdQuery),
|
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
|
||||||
},
|
deleteMany: jest.fn().mockReturnValue(historyDeleteManyQuery),
|
||||||
});
|
},
|
||||||
|
match: {
|
||||||
|
findById: jest.fn().mockReturnValue(matchFindByIdQuery),
|
||||||
|
},
|
||||||
|
});
|
||||||
connectionService.createSession.mockResolvedValue(session);
|
connectionService.createSession.mockResolvedValue(session);
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
@@ -2261,23 +2271,27 @@ describe('AuctionService', () => {
|
|||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
const auctionReplaceOne = jest.fn();
|
const auctionReplaceOne = jest.fn();
|
||||||
const { service, connectionService, auctionRedisCommandService, auctionRedisStateReaderService } =
|
const {
|
||||||
createService({
|
service,
|
||||||
auction: {
|
connectionService,
|
||||||
findOne: jest.fn().mockReturnValue({
|
auctionRedisCommandService,
|
||||||
session: jest.fn().mockResolvedValue(auction),
|
auctionRedisStateReaderService,
|
||||||
}),
|
} = createService({
|
||||||
replaceOne: auctionReplaceOne,
|
auction: {
|
||||||
},
|
findOne: jest.fn().mockReturnValue({
|
||||||
auctionHistory: {
|
session: jest.fn().mockResolvedValue(auction),
|
||||||
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
|
}),
|
||||||
},
|
replaceOne: auctionReplaceOne,
|
||||||
match: {
|
},
|
||||||
findById: jest.fn().mockReturnValue({
|
auctionHistory: {
|
||||||
session: jest.fn().mockResolvedValue(match),
|
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
|
||||||
}),
|
},
|
||||||
},
|
match: {
|
||||||
});
|
findById: jest.fn().mockReturnValue({
|
||||||
|
session: jest.fn().mockResolvedValue(match),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
connectionService.createSession.mockResolvedValue(session);
|
connectionService.createSession.mockResolvedValue(session);
|
||||||
auctionRedisStateReaderService.readAuctionStateView
|
auctionRedisStateReaderService.readAuctionStateView
|
||||||
.mockResolvedValueOnce(currentRedisState)
|
.mockResolvedValueOnce(currentRedisState)
|
||||||
@@ -2298,7 +2312,9 @@ describe('AuctionService', () => {
|
|||||||
).resolves.toBe(restoredRedisState);
|
).resolves.toBe(restoredRedisState);
|
||||||
|
|
||||||
expect(auctionReplaceOne).not.toHaveBeenCalled();
|
expect(auctionReplaceOne).not.toHaveBeenCalled();
|
||||||
expect(auctionRedisCommandService.reserveActionRequest).toHaveBeenCalledWith(
|
expect(
|
||||||
|
auctionRedisCommandService.reserveActionRequest,
|
||||||
|
).toHaveBeenCalledWith(
|
||||||
matchId.toString(),
|
matchId.toString(),
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
auctionActionRequestId: '00000000-0000-4000-8000-000000000070',
|
auctionActionRequestId: '00000000-0000-4000-8000-000000000070',
|
||||||
@@ -2319,9 +2335,7 @@ describe('AuctionService', () => {
|
|||||||
durationSeconds: 30,
|
durationSeconds: 30,
|
||||||
mode: 'set-relative',
|
mode: 'set-relative',
|
||||||
});
|
});
|
||||||
const durabilityPayload = JSON.parse(
|
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
|
||||||
transitionInput.durabilityPayloadJson,
|
|
||||||
);
|
|
||||||
expect(durabilityPayload).toMatchObject({
|
expect(durabilityPayload).toMatchObject({
|
||||||
auctionActionType: 'undo',
|
auctionActionType: 'undo',
|
||||||
historyMutation: {
|
historyMutation: {
|
||||||
|
|||||||
@@ -230,7 +230,9 @@ export class AuctionService {
|
|||||||
const activeParticipants = this.applyAuctionCut(match);
|
const activeParticipants = this.applyAuctionCut(match);
|
||||||
const desiredAuctionCount = activeParticipants.length;
|
const desiredAuctionCount = activeParticipants.length;
|
||||||
if (desiredAuctionCount < 10) {
|
if (desiredAuctionCount < 10) {
|
||||||
throw new BadRequestException('Not enough participants (need at least 10).');
|
throw new BadRequestException(
|
||||||
|
'Not enough participants (need at least 10).',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
const expectedCaptainCount = desiredAuctionCount / AUCTION_MAX_TEAM_SIZE;
|
const expectedCaptainCount = desiredAuctionCount / AUCTION_MAX_TEAM_SIZE;
|
||||||
if (params.captains.length !== expectedCaptainCount) {
|
if (params.captains.length !== expectedCaptainCount) {
|
||||||
@@ -262,7 +264,8 @@ export class AuctionService {
|
|||||||
const enrichCooldownCutoff = Date.now() - AUCTION_ENRICHMENT_COOLDOWN_MS;
|
const enrichCooldownCutoff = Date.now() - AUCTION_ENRICHMENT_COOLDOWN_MS;
|
||||||
const enrichTargets = basePlayerUsers.flatMap((user) => {
|
const enrichTargets = basePlayerUsers.flatMap((user) => {
|
||||||
const account =
|
const account =
|
||||||
user.riotAccounts.find((entry) => entry.isPrimary) ?? user.riotAccounts[0];
|
user.riotAccounts.find((entry) => entry.isPrimary) ??
|
||||||
|
user.riotAccounts[0];
|
||||||
if (!account?.puuid) return [];
|
if (!account?.puuid) return [];
|
||||||
if (this.wasRecentlyRefreshed(account, enrichCooldownCutoff)) return [];
|
if (this.wasRecentlyRefreshed(account, enrichCooldownCutoff)) return [];
|
||||||
return [{ userId: user._id, puuid: account.puuid }];
|
return [{ userId: user._id, puuid: account.puuid }];
|
||||||
@@ -316,8 +319,7 @@ export class AuctionService {
|
|||||||
const legacyTeams = params.captains.map((c) => ({
|
const legacyTeams = params.captains.map((c) => ({
|
||||||
teamIndex: c.teamIndex,
|
teamIndex: c.teamIndex,
|
||||||
captainUserId: c.userId,
|
captainUserId: c.userId,
|
||||||
points:
|
points: c.initialTeamBidPointAmount ?? params.initialTeamBidPointAmount,
|
||||||
c.initialTeamBidPointAmount ?? params.initialTeamBidPointAmount,
|
|
||||||
members: [],
|
members: [],
|
||||||
}));
|
}));
|
||||||
const auctionTeams = convertLegacyAuctionTeamsToRedisTeams(legacyTeams);
|
const auctionTeams = convertLegacyAuctionTeamsToRedisTeams(legacyTeams);
|
||||||
@@ -391,26 +393,30 @@ export class AuctionService {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!isMongoDuplicateKeyError(error)) throw error;
|
if (!isMongoDuplicateKeyError(error)) throw error;
|
||||||
const raceWinner = await AuctionModel.findOne({ matchId: params.matchId });
|
const raceWinner = await AuctionModel.findOne({
|
||||||
|
matchId: params.matchId,
|
||||||
|
});
|
||||||
if (raceWinner?.startAuctionRequestId === params.startAuctionRequestId) {
|
if (raceWinner?.startAuctionRequestId === params.startAuctionRequestId) {
|
||||||
return raceWinner;
|
return raceWinner;
|
||||||
}
|
}
|
||||||
throw new BadRequestException('Auction already exists for this match.');
|
throw new BadRequestException('Auction already exists for this match.');
|
||||||
}
|
}
|
||||||
await this.recordSnapshot(auction, 'start');
|
await this.recordSnapshot(auction, 'start');
|
||||||
await this.auctionRedisCommandService.hydrateState(params.matchId.toString(), {
|
await this.auctionRedisCommandService.hydrateState(
|
||||||
auctionHistorySequence: 1,
|
params.matchId.toString(),
|
||||||
auctionLifecycleId,
|
{
|
||||||
maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds,
|
auctionHistorySequence: 1,
|
||||||
liveStatePatch,
|
auctionLifecycleId,
|
||||||
matchId: params.matchId.toString(),
|
maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds,
|
||||||
phase: 'presenting',
|
liveStatePatch,
|
||||||
revision: 0,
|
matchId: params.matchId.toString(),
|
||||||
structureStateJson,
|
phase: 'presenting',
|
||||||
});
|
revision: 0,
|
||||||
|
structureStateJson,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
match.status = 'team-built';
|
match.status = 'team-built';
|
||||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
|
||||||
await match.save();
|
await match.save();
|
||||||
this.enqueueBackgroundOrderEnrichment({
|
this.enqueueBackgroundOrderEnrichment({
|
||||||
auctionId: auction._id,
|
auctionId: auction._id,
|
||||||
@@ -624,9 +630,8 @@ export class AuctionService {
|
|||||||
params: PlaceBidParams,
|
params: PlaceBidParams,
|
||||||
): Promise<AuctionBidDeltaResponse | AuctionStateResponse> {
|
): Promise<AuctionBidDeltaResponse | AuctionStateResponse> {
|
||||||
this.assertValidBidPointAmount(params.amount);
|
this.assertValidBidPointAmount(params.amount);
|
||||||
const redisBidDelta = await this.tryPlaceRedisBidDeltaFromRealtimeState(
|
const redisBidDelta =
|
||||||
params,
|
await this.tryPlaceRedisBidDeltaFromRealtimeState(params);
|
||||||
);
|
|
||||||
if (redisBidDelta) return redisBidDelta;
|
if (redisBidDelta) return redisBidDelta;
|
||||||
|
|
||||||
const auction = await this.getByMatchId(params.matchId);
|
const auction = await this.getByMatchId(params.matchId);
|
||||||
@@ -712,11 +717,10 @@ export class AuctionService {
|
|||||||
const serviceStartedAtMS = performance.now();
|
const serviceStartedAtMS = performance.now();
|
||||||
const matchId = params.matchId.toString();
|
const matchId = params.matchId.toString();
|
||||||
const bidContextReadStartedAtMS = performance.now();
|
const bidContextReadStartedAtMS = performance.now();
|
||||||
const bidContext =
|
const bidContext = await this.auctionRedisStateReaderService.readBidContext(
|
||||||
await this.auctionRedisStateReaderService.readBidContext(
|
matchId,
|
||||||
matchId,
|
params.teamIndex,
|
||||||
params.teamIndex,
|
);
|
||||||
);
|
|
||||||
const redisBidContextReadDurationMS =
|
const redisBidContextReadDurationMS =
|
||||||
performance.now() - bidContextReadStartedAtMS;
|
performance.now() - bidContextReadStartedAtMS;
|
||||||
if (!bidContext) return null;
|
if (!bidContext) return null;
|
||||||
@@ -1321,12 +1325,10 @@ export class AuctionService {
|
|||||||
if (!session) {
|
if (!session) {
|
||||||
throw new InternalServerErrorException('Failed to start DB session.');
|
throw new InternalServerErrorException('Failed to start DB session.');
|
||||||
}
|
}
|
||||||
let redisRuntimeToClear:
|
let redisRuntimeToClear: {
|
||||||
| {
|
auctionLifecycleId?: string;
|
||||||
auctionLifecycleId?: string;
|
matchId: string;
|
||||||
matchId: string;
|
} | null = null;
|
||||||
}
|
|
||||||
| null = null;
|
|
||||||
try {
|
try {
|
||||||
session.startTransaction();
|
session.startTransaction();
|
||||||
const auction = await AuctionModel.findOne({
|
const auction = await AuctionModel.findOne({
|
||||||
@@ -1349,15 +1351,15 @@ export class AuctionService {
|
|||||||
await AuctionSideEffectApplicationModel.deleteMany({
|
await AuctionSideEffectApplicationModel.deleteMany({
|
||||||
auctionId: auction._id,
|
auctionId: auction._id,
|
||||||
}).session(session);
|
}).session(session);
|
||||||
await AuctionHistoryModel.deleteMany({ auctionId: auction._id }).session(
|
await AuctionHistoryModel.deleteMany({
|
||||||
session,
|
auctionId: auction._id,
|
||||||
);
|
}).session(session);
|
||||||
await auction.deleteOne({ session });
|
await auction.deleteOne({ session });
|
||||||
} else {
|
} else {
|
||||||
await auction.deleteOne({ session });
|
await auction.deleteOne({ session });
|
||||||
await AuctionHistoryModel.deleteMany({ auctionId: auction._id }).session(
|
await AuctionHistoryModel.deleteMany({
|
||||||
session,
|
auctionId: auction._id,
|
||||||
);
|
}).session(session);
|
||||||
if (match.status === 'team-built') {
|
if (match.status === 'team-built') {
|
||||||
await this.tournamentCodeService.releaseFromMatch(match);
|
await this.tournamentCodeService.releaseFromMatch(match);
|
||||||
match.status = 'recruiting';
|
match.status = 'recruiting';
|
||||||
@@ -1410,15 +1412,13 @@ export class AuctionService {
|
|||||||
throw new InternalServerErrorException('Failed to start DB session.');
|
throw new InternalServerErrorException('Failed to start DB session.');
|
||||||
}
|
}
|
||||||
|
|
||||||
let redisUndoContext:
|
let redisUndoContext: {
|
||||||
| {
|
actionRequestParams?: AuctionStructureActionRequestParams;
|
||||||
actionRequestParams?: AuctionStructureActionRequestParams;
|
auction: AuctionDocument;
|
||||||
auction: AuctionDocument;
|
snapshot: Record<string, unknown>;
|
||||||
snapshot: Record<string, unknown>;
|
targetHistorySequence: number;
|
||||||
targetHistorySequence: number;
|
undoingCompletedAuction: boolean;
|
||||||
undoingCompletedAuction: boolean;
|
} | null = null;
|
||||||
}
|
|
||||||
| null = null;
|
|
||||||
let restored: AuctionDocument | null = null;
|
let restored: AuctionDocument | null = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -1460,27 +1460,27 @@ export class AuctionService {
|
|||||||
};
|
};
|
||||||
await session.commitTransaction();
|
await session.commitTransaction();
|
||||||
} else {
|
} else {
|
||||||
if (undoingCompletedAuction) {
|
if (undoingCompletedAuction) {
|
||||||
await this.tournamentCodeService.releaseFromMatch(match);
|
await this.tournamentCodeService.releaseFromMatch(match);
|
||||||
await this.tournamentResultService.cancelPolling(match);
|
await this.tournamentResultService.cancelPolling(match);
|
||||||
match.status = 'team-built';
|
match.status = 'team-built';
|
||||||
match.result = undefined;
|
match.result = undefined;
|
||||||
await match.save({ session });
|
await match.save({ session });
|
||||||
}
|
}
|
||||||
|
|
||||||
await AuctionModel.replaceOne({ _id: auction._id }, snapshot, {
|
await AuctionModel.replaceOne({ _id: auction._id }, snapshot, {
|
||||||
session,
|
session,
|
||||||
}).exec();
|
}).exec();
|
||||||
await AuctionHistoryModel.deleteMany({
|
await AuctionHistoryModel.deleteMany({
|
||||||
auctionId: auction._id,
|
auctionId: auction._id,
|
||||||
sequence: { $gt: params.sequence },
|
sequence: { $gt: params.sequence },
|
||||||
})
|
})
|
||||||
.session(session)
|
.session(session)
|
||||||
.exec();
|
.exec();
|
||||||
|
|
||||||
await session.commitTransaction();
|
await session.commitTransaction();
|
||||||
restored = await AuctionModel.findById(auction._id);
|
restored = await AuctionModel.findById(auction._id);
|
||||||
if (!restored) throw new NotFoundException('Auction not found.');
|
if (!restored) throw new NotFoundException('Auction not found.');
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await session.abortTransaction();
|
await session.abortTransaction();
|
||||||
@@ -1534,28 +1534,27 @@ export class AuctionService {
|
|||||||
const processingOwnerToken = randomUUID();
|
const processingOwnerToken = randomUUID();
|
||||||
const auctionStateTransitionId = `${params.action}:${expectedAuctionLifecycleId}:${auctionActionRequestId}`;
|
const auctionStateTransitionId = `${params.action}:${expectedAuctionLifecycleId}:${auctionActionRequestId}`;
|
||||||
|
|
||||||
const reserved =
|
const reserved = await this.auctionRedisCommandService.reserveActionRequest(
|
||||||
await this.auctionRedisCommandService.reserveActionRequest(
|
params.matchId,
|
||||||
params.matchId,
|
{
|
||||||
{
|
auctionActionRequestId,
|
||||||
auctionActionRequestId,
|
auctionActionType: params.action,
|
||||||
auctionActionType: params.action,
|
auctionStateTransitionId,
|
||||||
auctionStateTransitionId,
|
clientObservedAuctionLifecycleId: expectedAuctionLifecycleId,
|
||||||
clientObservedAuctionLifecycleId: expectedAuctionLifecycleId,
|
clientObservedCurrentAuctionPlayerOrderIndex:
|
||||||
clientObservedCurrentAuctionPlayerOrderIndex:
|
expectedCurrentAuctionPlayerOrderIndex,
|
||||||
expectedCurrentAuctionPlayerOrderIndex,
|
clientObservedCurrentBidRoundPlayerUserId:
|
||||||
clientObservedCurrentBidRoundPlayerUserId:
|
expectedCurrentBidRoundPlayerUserId,
|
||||||
expectedCurrentBidRoundPlayerUserId,
|
clientObservedPhase: expectedPhase,
|
||||||
clientObservedPhase: expectedPhase,
|
clientObservedRevision: expectedRevision,
|
||||||
clientObservedRevision: expectedRevision,
|
leaseDurationMS: AUCTION_ACTION_REQUEST_LEASE_DURATION_MS,
|
||||||
leaseDurationMS: AUCTION_ACTION_REQUEST_LEASE_DURATION_MS,
|
maximumStoredAuctionActionRequestResultCount:
|
||||||
maximumStoredAuctionActionRequestResultCount:
|
AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT,
|
||||||
AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT,
|
minimumAuctionActionRequestResultReplayWindowMS:
|
||||||
minimumAuctionActionRequestResultReplayWindowMS:
|
AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS,
|
||||||
AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS,
|
processingOwnerToken,
|
||||||
processingOwnerToken,
|
},
|
||||||
},
|
);
|
||||||
);
|
|
||||||
|
|
||||||
if ('rejected' in reserved) {
|
if ('rejected' in reserved) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
@@ -1579,8 +1578,7 @@ export class AuctionService {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
actionRequest: {
|
actionRequest: {
|
||||||
observedProcessingLeaseVersion:
|
observedProcessingLeaseVersion: reserved.observedProcessingLeaseVersion,
|
||||||
reserved.observedProcessingLeaseVersion,
|
|
||||||
processingOwnerToken,
|
processingOwnerToken,
|
||||||
scopeKey: reserved.actionRequestScopeKey,
|
scopeKey: reserved.actionRequestScopeKey,
|
||||||
},
|
},
|
||||||
@@ -1627,7 +1625,10 @@ export class AuctionService {
|
|||||||
| { durationSeconds: number; mode: 'set-relative' };
|
| { durationSeconds: number; mode: 'set-relative' };
|
||||||
expectedPhase: string;
|
expectedPhase: string;
|
||||||
historyMutation?: Record<string, unknown>;
|
historyMutation?: Record<string, unknown>;
|
||||||
liveStatePatch: Record<string, string | number | boolean | null | undefined>;
|
liveStatePatch: Record<
|
||||||
|
string,
|
||||||
|
string | number | boolean | null | undefined
|
||||||
|
>;
|
||||||
matchSideEffectMutation?: Record<string, unknown>;
|
matchSideEffectMutation?: Record<string, unknown>;
|
||||||
shouldBroadcastStateAfterDurability?: boolean;
|
shouldBroadcastStateAfterDurability?: boolean;
|
||||||
shouldResetBidRuntime?: boolean;
|
shouldResetBidRuntime?: boolean;
|
||||||
@@ -1644,8 +1645,7 @@ export class AuctionService {
|
|||||||
const expectedAuctionHistorySequence = this.numberFromState(
|
const expectedAuctionHistorySequence = this.numberFromState(
|
||||||
params.state.currentAuctionHistorySequence,
|
params.state.currentAuctionHistorySequence,
|
||||||
);
|
);
|
||||||
const auctionHistorySequence =
|
const auctionHistorySequence = expectedAuctionHistorySequence + 1;
|
||||||
expectedAuctionHistorySequence + 1;
|
|
||||||
const auctionStateTransitionId =
|
const auctionStateTransitionId =
|
||||||
params.actionRequest?.auctionStateTransitionId ||
|
params.actionRequest?.auctionStateTransitionId ||
|
||||||
params.auctionStateTransitionId ||
|
params.auctionStateTransitionId ||
|
||||||
@@ -1695,7 +1695,8 @@ export class AuctionService {
|
|||||||
),
|
),
|
||||||
auctionHistorySequence,
|
auctionHistorySequence,
|
||||||
auctionLifecycleId:
|
auctionLifecycleId:
|
||||||
params.actionRequest?.expectedAuctionLifecycleId ?? auctionLifecycleId,
|
params.actionRequest?.expectedAuctionLifecycleId ??
|
||||||
|
auctionLifecycleId,
|
||||||
auctionStateTransitionId,
|
auctionStateTransitionId,
|
||||||
broadcastStateRevision: expectedRevision + 1,
|
broadcastStateRevision: expectedRevision + 1,
|
||||||
deadline: params.deadline,
|
deadline: params.deadline,
|
||||||
@@ -1709,7 +1710,8 @@ export class AuctionService {
|
|||||||
? this.stringFromState(params.state.currentBidRoundPlayerUserId)
|
? this.stringFromState(params.state.currentBidRoundPlayerUserId)
|
||||||
: undefined),
|
: undefined),
|
||||||
expectedAuctionHistorySequence,
|
expectedAuctionHistorySequence,
|
||||||
expectedPhase: params.actionRequest?.expectedPhase ?? params.expectedPhase,
|
expectedPhase:
|
||||||
|
params.actionRequest?.expectedPhase ?? params.expectedPhase,
|
||||||
expectedRevision,
|
expectedRevision,
|
||||||
liveStatePatch: params.liveStatePatch,
|
liveStatePatch: params.liveStatePatch,
|
||||||
matchId,
|
matchId,
|
||||||
@@ -1762,9 +1764,8 @@ export class AuctionService {
|
|||||||
)) {
|
)) {
|
||||||
const teamIndex = this.numberFromState(team.teamIndex);
|
const teamIndex = this.numberFromState(team.teamIndex);
|
||||||
if (teamIndex < 1) continue;
|
if (teamIndex < 1) continue;
|
||||||
clearedTeamLiveStatePatch[
|
clearedTeamLiveStatePatch[`team:${teamIndex}:remainingBidPointAmount`] =
|
||||||
`team:${teamIndex}:remainingBidPointAmount`
|
0;
|
||||||
] = 0;
|
|
||||||
clearedTeamLiveStatePatch[
|
clearedTeamLiveStatePatch[
|
||||||
`team:${teamIndex}:assignedAuctionTeamMemberCount`
|
`team:${teamIndex}:assignedAuctionTeamMemberCount`
|
||||||
] = 0;
|
] = 0;
|
||||||
@@ -1829,7 +1830,8 @@ export class AuctionService {
|
|||||||
-1,
|
-1,
|
||||||
);
|
);
|
||||||
const currentHighestBidPointAmount = this.numberFromState(
|
const currentHighestBidPointAmount = this.numberFromState(
|
||||||
params.snapshot.currentHighestBidPointAmount ?? params.snapshot.currentBid,
|
params.snapshot.currentHighestBidPointAmount ??
|
||||||
|
params.snapshot.currentBid,
|
||||||
0,
|
0,
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1898,10 +1900,11 @@ export class AuctionService {
|
|||||||
passedAuctionPlayerQueue: this.arrayFromState(
|
passedAuctionPlayerQueue: this.arrayFromState(
|
||||||
state.passedAuctionPlayerQueue,
|
state.passedAuctionPlayerQueue,
|
||||||
),
|
),
|
||||||
topTierAuctionPriorityThreshold:
|
topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold(
|
||||||
this.isAuctionTopTierThreshold(state.topTierAuctionPriorityThreshold)
|
state.topTierAuctionPriorityThreshold,
|
||||||
? state.topTierAuctionPriorityThreshold
|
)
|
||||||
: 'NONE',
|
? state.topTierAuctionPriorityThreshold
|
||||||
|
: 'NONE',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1913,9 +1916,10 @@ export class AuctionService {
|
|||||||
auctionPlayerOrder: this.arrayFromState(
|
auctionPlayerOrder: this.arrayFromState(
|
||||||
snapshot.auctionPlayerOrder ?? snapshot.order,
|
snapshot.auctionPlayerOrder ?? snapshot.order,
|
||||||
),
|
),
|
||||||
auctionTeams: this.arrayFromState(snapshot.auctionTeams).length > 0
|
auctionTeams:
|
||||||
? this.arrayFromState(snapshot.auctionTeams)
|
this.arrayFromState(snapshot.auctionTeams).length > 0
|
||||||
: convertLegacyAuctionTeamsToRedisTeams(legacyTeams as never),
|
? this.arrayFromState(snapshot.auctionTeams)
|
||||||
|
: convertLegacyAuctionTeamsToRedisTeams(legacyTeams as never),
|
||||||
bidRoundExtensionSeconds: this.numberFromState(
|
bidRoundExtensionSeconds: this.numberFromState(
|
||||||
snapshot.bidRoundExtensionSeconds ?? snapshot.bidExtensionSeconds,
|
snapshot.bidRoundExtensionSeconds ?? snapshot.bidExtensionSeconds,
|
||||||
5,
|
5,
|
||||||
@@ -1945,8 +1949,8 @@ export class AuctionService {
|
|||||||
topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold(
|
topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold(
|
||||||
snapshot.topTierAuctionPriorityThreshold ?? snapshot.topTierThreshold,
|
snapshot.topTierAuctionPriorityThreshold ?? snapshot.topTierThreshold,
|
||||||
)
|
)
|
||||||
? (snapshot.topTierAuctionPriorityThreshold ??
|
? ((snapshot.topTierAuctionPriorityThreshold ??
|
||||||
snapshot.topTierThreshold) as never
|
snapshot.topTierThreshold) as never)
|
||||||
: 'NONE',
|
: 'NONE',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -2064,7 +2068,9 @@ export class AuctionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private convertRedisTeamsToLegacyTeams(
|
private convertRedisTeamsToLegacyTeams(
|
||||||
auctionTeams: Parameters<typeof stringifyAuctionRedisStructureState>[0]['auctionTeams'],
|
auctionTeams: Parameters<
|
||||||
|
typeof stringifyAuctionRedisStructureState
|
||||||
|
>[0]['auctionTeams'],
|
||||||
): AuctionTeam[] {
|
): AuctionTeam[] {
|
||||||
return auctionTeams.map((team) => ({
|
return auctionTeams.map((team) => ({
|
||||||
captainUserId: team.captainUserId as mongoose.Types.ObjectId,
|
captainUserId: team.captainUserId as mongoose.Types.ObjectId,
|
||||||
@@ -2096,7 +2102,7 @@ export class AuctionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private stringFromState(value: unknown): string {
|
private stringFromState(value: unknown): string {
|
||||||
return typeof value === 'string' ? value : value?.toString() ?? '';
|
return typeof value === 'string' ? value : (value?.toString() ?? '');
|
||||||
}
|
}
|
||||||
|
|
||||||
private isAuctionTopTierThreshold(
|
private isAuctionTopTierThreshold(
|
||||||
@@ -2218,7 +2224,9 @@ export class AuctionService {
|
|||||||
({ I: 4, II: 3, III: 2, IV: 1, '': 0 } as Record<string, number>)[
|
({ I: 4, II: 3, III: 2, IV: 1, '': 0 } as Record<string, number>)[
|
||||||
solo.rank
|
solo.rank
|
||||||
] ?? 0;
|
] ?? 0;
|
||||||
return tierIdx * 1000 + rankBonus * 100 + (solo.leaguePoints ?? 0) * 0.001;
|
return (
|
||||||
|
tierIdx * 1000 + rankBonus * 100 + (solo.leaguePoints ?? 0) * 0.001
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const top = order
|
const top = order
|
||||||
@@ -2507,7 +2515,7 @@ export class AuctionService {
|
|||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
|
|
||||||
match.teams = auction.teams.map((team) => {
|
const matchTeams = auction.teams.map((team) => {
|
||||||
const captain = participantByUserId.get(team.captainUserId.toString());
|
const captain = participantByUserId.get(team.captainUserId.toString());
|
||||||
const members: MatchTeamMember[] = [
|
const members: MatchTeamMember[] = [
|
||||||
{
|
{
|
||||||
@@ -2531,6 +2539,12 @@ export class AuctionService {
|
|||||||
members,
|
members,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
if (matchTeams.length === 0) {
|
||||||
|
throw new Error(
|
||||||
|
`Auction completed without teams for match ${match._id.toString()}.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
match.teams = matchTeams;
|
||||||
match.status = 'team-built';
|
match.status = 'team-built';
|
||||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||||
await match.save();
|
await match.save();
|
||||||
@@ -2557,7 +2571,7 @@ export class AuctionService {
|
|||||||
structureInput.auctionTeams,
|
structureInput.auctionTeams,
|
||||||
);
|
);
|
||||||
|
|
||||||
match.teams = teams.map((team) => {
|
const matchTeams = teams.map((team) => {
|
||||||
const captain = participantByUserId.get(team.captainUserId.toString());
|
const captain = participantByUserId.get(team.captainUserId.toString());
|
||||||
const members: MatchTeamMember[] = [
|
const members: MatchTeamMember[] = [
|
||||||
{
|
{
|
||||||
@@ -2566,7 +2580,10 @@ export class AuctionService {
|
|||||||
cost: 0,
|
cost: 0,
|
||||||
},
|
},
|
||||||
...team.members
|
...team.members
|
||||||
.filter((member) => member.userId.toString() !== team.captainUserId.toString())
|
.filter(
|
||||||
|
(member) =>
|
||||||
|
member.userId.toString() !== team.captainUserId.toString(),
|
||||||
|
)
|
||||||
.map((member) => ({
|
.map((member) => ({
|
||||||
userId: member.userId,
|
userId: member.userId,
|
||||||
assignedPosition: member.assignedPosition,
|
assignedPosition: member.assignedPosition,
|
||||||
@@ -2581,6 +2598,12 @@ export class AuctionService {
|
|||||||
members,
|
members,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
if (matchTeams.length === 0) {
|
||||||
|
throw new Error(
|
||||||
|
`Redis auction completed without teams for match ${match._id.toString()}.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
match.teams = matchTeams;
|
||||||
match.status = 'team-built';
|
match.status = 'team-built';
|
||||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||||
await match.save();
|
await match.save();
|
||||||
@@ -2602,7 +2625,8 @@ export class AuctionService {
|
|||||||
auction.bidRoundExtensionSeconds ?? auction.bidExtensionSeconds ?? 5,
|
auction.bidRoundExtensionSeconds ?? auction.bidExtensionSeconds ?? 5,
|
||||||
currentAuctionPlayerOrderIndex:
|
currentAuctionPlayerOrderIndex:
|
||||||
auction.currentAuctionPlayerOrderIndex ?? auction.currentIndex ?? 0,
|
auction.currentAuctionPlayerOrderIndex ?? auction.currentIndex ?? 0,
|
||||||
currentAuctionRound: auction.currentAuctionRound ?? auction.auctionRound ?? 1,
|
currentAuctionRound:
|
||||||
|
auction.currentAuctionRound ?? auction.auctionRound ?? 1,
|
||||||
initialTeamBidPointAmount:
|
initialTeamBidPointAmount:
|
||||||
auction.initialTeamBidPointAmount ?? auction.initialPoints ?? 1000,
|
auction.initialTeamBidPointAmount ?? auction.initialPoints ?? 1000,
|
||||||
manualTopTierAuctionPriorityUserIds:
|
manualTopTierAuctionPriorityUserIds:
|
||||||
@@ -2614,7 +2638,9 @@ export class AuctionService {
|
|||||||
passedAuctionPlayerQueue:
|
passedAuctionPlayerQueue:
|
||||||
auction.passedAuctionPlayerQueue ?? auction.passedQueue ?? [],
|
auction.passedAuctionPlayerQueue ?? auction.passedQueue ?? [],
|
||||||
topTierAuctionPriorityThreshold:
|
topTierAuctionPriorityThreshold:
|
||||||
auction.topTierAuctionPriorityThreshold ?? auction.topTierThreshold ?? 'NONE',
|
auction.topTierAuctionPriorityThreshold ??
|
||||||
|
auction.topTierThreshold ??
|
||||||
|
'NONE',
|
||||||
};
|
};
|
||||||
await this.auctionRedisCommandService.hydrateState(
|
await this.auctionRedisCommandService.hydrateState(
|
||||||
auction.matchId.toString(),
|
auction.matchId.toString(),
|
||||||
@@ -2647,35 +2673,37 @@ export class AuctionService {
|
|||||||
expectedAuctionLifecycleId?: string,
|
expectedAuctionLifecycleId?: string,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const keys = buildAuctionRedisKeys(matchId);
|
const keys = buildAuctionRedisKeys(matchId);
|
||||||
const cleared = await this.auctionRedisService.raw().sendCommand([
|
const cleared = await this.auctionRedisService
|
||||||
'EVAL',
|
.raw()
|
||||||
[
|
.sendCommand([
|
||||||
"local expectedAuctionLifecycleId = ARGV[2]",
|
'EVAL',
|
||||||
"if expectedAuctionLifecycleId ~= '' then",
|
[
|
||||||
" local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
|
'local expectedAuctionLifecycleId = ARGV[2]',
|
||||||
" if currentAuctionLifecycleId and currentAuctionLifecycleId ~= expectedAuctionLifecycleId then",
|
"if expectedAuctionLifecycleId ~= '' then",
|
||||||
" return 0",
|
" local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
|
||||||
' end',
|
' if currentAuctionLifecycleId and currentAuctionLifecycleId ~= expectedAuctionLifecycleId then',
|
||||||
'end',
|
' return 0',
|
||||||
"redis.call('ZREM', KEYS[2], ARGV[1])",
|
' end',
|
||||||
"redis.call('DEL', KEYS[1], KEYS[3], KEYS[4], KEYS[5], KEYS[6], KEYS[7], KEYS[8], KEYS[9], KEYS[10], KEYS[11])",
|
'end',
|
||||||
'return 1',
|
"redis.call('ZREM', KEYS[2], ARGV[1])",
|
||||||
].join('\n'),
|
"redis.call('DEL', KEYS[1], KEYS[3], KEYS[4], KEYS[5], KEYS[6], KEYS[7], KEYS[8], KEYS[9], KEYS[10], KEYS[11])",
|
||||||
'11',
|
'return 1',
|
||||||
keys.liveStateKey,
|
].join('\n'),
|
||||||
keys.deadlineQueueKey,
|
'11',
|
||||||
keys.structureStateKey,
|
keys.liveStateKey,
|
||||||
keys.appliedTransitionIdsKey,
|
keys.deadlineQueueKey,
|
||||||
keys.bidHistoryKey,
|
keys.structureStateKey,
|
||||||
keys.bidRequestResultsKey,
|
keys.appliedTransitionIdsKey,
|
||||||
keys.bidRequestResultOrderKey,
|
keys.bidHistoryKey,
|
||||||
keys.actionRequestResultsKey,
|
keys.bidRequestResultsKey,
|
||||||
keys.actionRequestResultOrderKey,
|
keys.bidRequestResultOrderKey,
|
||||||
keys.rehydrateLockKey,
|
keys.actionRequestResultsKey,
|
||||||
keys.stateTransitionLockKey,
|
keys.actionRequestResultOrderKey,
|
||||||
matchId,
|
keys.rehydrateLockKey,
|
||||||
expectedAuctionLifecycleId ?? '',
|
keys.stateTransitionLockKey,
|
||||||
]);
|
matchId,
|
||||||
|
expectedAuctionLifecycleId ?? '',
|
||||||
|
]);
|
||||||
if (Number(cleared) !== 1) return;
|
if (Number(cleared) !== 1) return;
|
||||||
await this.clearRedisDurabilityPayloadsForLifecycle(
|
await this.clearRedisDurabilityPayloadsForLifecycle(
|
||||||
keys,
|
keys,
|
||||||
@@ -2689,14 +2717,16 @@ export class AuctionService {
|
|||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
let cursor = '0';
|
let cursor = '0';
|
||||||
do {
|
do {
|
||||||
const reply = await this.auctionRedisService.raw().sendCommand([
|
const reply = await this.auctionRedisService
|
||||||
'SCAN',
|
.raw()
|
||||||
cursor,
|
.sendCommand([
|
||||||
'MATCH',
|
'SCAN',
|
||||||
`${keys.durabilityPayloadKeyPrefix}*`,
|
cursor,
|
||||||
'COUNT',
|
'MATCH',
|
||||||
'100',
|
`${keys.durabilityPayloadKeyPrefix}*`,
|
||||||
]);
|
'COUNT',
|
||||||
|
'100',
|
||||||
|
]);
|
||||||
if (!Array.isArray(reply) || reply.length < 2) return;
|
if (!Array.isArray(reply) || reply.length < 2) return;
|
||||||
cursor = String(reply[0]);
|
cursor = String(reply[0]);
|
||||||
const payloadKeys = Array.isArray(reply[1]) ? reply[1].map(String) : [];
|
const payloadKeys = Array.isArray(reply[1]) ? reply[1].map(String) : [];
|
||||||
@@ -2714,20 +2744,23 @@ export class AuctionService {
|
|||||||
);
|
);
|
||||||
if (payloadKeysToDelete.length === 0) continue;
|
if (payloadKeysToDelete.length === 0) continue;
|
||||||
|
|
||||||
await this.auctionRedisService.raw().sendCommand([
|
await this.auctionRedisService
|
||||||
'ZREM',
|
.raw()
|
||||||
keys.durabilityRetryQueueKey,
|
.sendCommand([
|
||||||
...payloadKeysToDelete,
|
'ZREM',
|
||||||
]);
|
keys.durabilityRetryQueueKey,
|
||||||
await this.auctionRedisService.raw().sendCommand([
|
...payloadKeysToDelete,
|
||||||
'ZREM',
|
]);
|
||||||
keys.durabilityDeadLetterQueueKey,
|
await this.auctionRedisService
|
||||||
...payloadKeysToDelete,
|
.raw()
|
||||||
]);
|
.sendCommand([
|
||||||
await this.auctionRedisService.raw().sendCommand([
|
'ZREM',
|
||||||
'DEL',
|
keys.durabilityDeadLetterQueueKey,
|
||||||
...payloadKeysToDelete,
|
...payloadKeysToDelete,
|
||||||
]);
|
]);
|
||||||
|
await this.auctionRedisService
|
||||||
|
.raw()
|
||||||
|
.sendCommand(['DEL', ...payloadKeysToDelete]);
|
||||||
} while (cursor !== '0');
|
} while (cursor !== '0');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2742,7 +2775,9 @@ export class AuctionService {
|
|||||||
const payload = JSON.parse(payloadValue) as Record<string, unknown>;
|
const payload = JSON.parse(payloadValue) as Record<string, unknown>;
|
||||||
return payload.auctionLifecycleId === expectedAuctionLifecycleId;
|
return payload.auctionLifecycleId === expectedAuctionLifecycleId;
|
||||||
} catch {
|
} catch {
|
||||||
this.logger.warn(`Failed to parse auction durability payload ${payloadKey}.`);
|
this.logger.warn(
|
||||||
|
`Failed to parse auction durability payload ${payloadKey}.`,
|
||||||
|
);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2855,13 +2890,16 @@ async function runWithConcurrency<T>(
|
|||||||
if (items.length === 0) return;
|
if (items.length === 0) return;
|
||||||
|
|
||||||
const queue = [...items];
|
const queue = [...items];
|
||||||
const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
|
const runners = Array.from(
|
||||||
while (queue.length > 0) {
|
{ length: Math.min(concurrency, queue.length) },
|
||||||
const item = queue.shift();
|
async () => {
|
||||||
if (item === undefined) return;
|
while (queue.length > 0) {
|
||||||
await worker(item);
|
const item = queue.shift();
|
||||||
}
|
if (item === undefined) return;
|
||||||
});
|
await worker(item);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
await Promise.allSettled(runners);
|
await Promise.allSettled(runners);
|
||||||
}
|
}
|
||||||
@@ -226,8 +226,10 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
|||||||
(game) => game.roundNumber === roundNumber,
|
(game) => game.roundNumber === roundNumber,
|
||||||
);
|
);
|
||||||
expect(round).toHaveLength(4);
|
expect(round).toHaveLength(4);
|
||||||
expect(new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex])).size)
|
expect(
|
||||||
.toBe(8);
|
new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex]))
|
||||||
|
.size,
|
||||||
|
).toBe(8);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -405,6 +407,69 @@ describe('TournamentCodeService pool stats', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('TournamentCodeService pending match attachment', () => {
|
||||||
|
it('does not attach tournament codes before match teams are built', async () => {
|
||||||
|
const invalidMatch = {
|
||||||
|
...createMatch({
|
||||||
|
status: 'team-built',
|
||||||
|
teams: [],
|
||||||
|
tournamentCodeIds: [],
|
||||||
|
} as unknown as MatchOverrides),
|
||||||
|
isModified: jest.fn().mockReturnValue(false),
|
||||||
|
};
|
||||||
|
const validMatch = {
|
||||||
|
...createMatch({
|
||||||
|
status: 'team-built',
|
||||||
|
teams: [
|
||||||
|
{
|
||||||
|
teamIndex: 1,
|
||||||
|
members: [{ userId: new mongoose.Types.ObjectId() }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
teamIndex: 2,
|
||||||
|
members: [{ userId: new mongoose.Types.ObjectId() }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
tournamentCodeIds: [],
|
||||||
|
} as unknown as MatchOverrides),
|
||||||
|
isModified: jest.fn().mockReturnValue(false),
|
||||||
|
};
|
||||||
|
const codeId = new mongoose.Types.ObjectId();
|
||||||
|
const MatchModel = {
|
||||||
|
find: jest.fn().mockReturnValue({
|
||||||
|
exec: jest.fn().mockResolvedValue([invalidMatch, validMatch]),
|
||||||
|
}),
|
||||||
|
findById: jest.fn().mockResolvedValue(validMatch),
|
||||||
|
};
|
||||||
|
const TournamentCodeModel = {
|
||||||
|
findOneAndUpdate: jest.fn().mockReturnValue({
|
||||||
|
exec: jest.fn().mockResolvedValue({ _id: codeId }),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockImplementation((modelName: string) => {
|
||||||
|
if (modelName === 'match') return Promise.resolve(MatchModel);
|
||||||
|
if (modelName === 'tournamentCode') {
|
||||||
|
return Promise.resolve(TournamentCodeModel);
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected model: ${modelName}`);
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const service = new TournamentCodeService(connectionService as never);
|
||||||
|
|
||||||
|
const matches = await service.attachPendingMatchDocuments();
|
||||||
|
|
||||||
|
expect(matches).toEqual([validMatch]);
|
||||||
|
expect(MatchModel.findById).toHaveBeenCalledTimes(1);
|
||||||
|
expect(MatchModel.findById).toHaveBeenCalledWith(validMatch._id);
|
||||||
|
expect(TournamentCodeModel.findOneAndUpdate).toHaveBeenCalledTimes(1);
|
||||||
|
expect(validMatch.tournamentCodeIds.map((id) => id.toString())).toEqual([
|
||||||
|
codeId.toString(),
|
||||||
|
]);
|
||||||
|
expect(invalidMatch.tournamentCodeIds).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('TournamentCodeService code replacement', () => {
|
describe('TournamentCodeService code replacement', () => {
|
||||||
function queryResult<T>(value: T) {
|
function queryResult<T>(value: T) {
|
||||||
return { exec: jest.fn().mockResolvedValue(value) };
|
return { exec: jest.fn().mockResolvedValue(value) };
|
||||||
|
|||||||
@@ -164,10 +164,9 @@ export class TournamentCodeService {
|
|||||||
_id: TournamentCodeState;
|
_id: TournamentCodeState;
|
||||||
count: number;
|
count: number;
|
||||||
}>([{ $group: { _id: '$state', count: { $sum: 1 } } }]).exec();
|
}>([{ $group: { _id: '$state', count: { $sum: 1 } } }]).exec();
|
||||||
const byState = Object.fromEntries(states.map((state) => [state, 0])) as Record<
|
const byState = Object.fromEntries(
|
||||||
TournamentCodeState,
|
states.map((state) => [state, 0]),
|
||||||
number
|
) as Record<TournamentCodeState, number>;
|
||||||
>;
|
|
||||||
for (const entry of counts) byState[entry._id] = entry.count;
|
for (const entry of counts) byState[entry._id] = entry.count;
|
||||||
|
|
||||||
const expiringSoon = await TournamentCodeModel.countDocuments({
|
const expiringSoon = await TournamentCodeModel.countDocuments({
|
||||||
@@ -189,7 +188,9 @@ export class TournamentCodeService {
|
|||||||
state: 'available',
|
state: 'available',
|
||||||
}).exec();
|
}).exec();
|
||||||
if (result.deletedCount === 0) {
|
if (result.deletedCount === 0) {
|
||||||
throw new BadRequestException('Only available tournament codes can be deleted.');
|
throw new BadRequestException(
|
||||||
|
'Only available tournament codes can be deleted.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -249,7 +250,9 @@ export class TournamentCodeService {
|
|||||||
|
|
||||||
const reservedIds: mongoose.Types.ObjectId[] = [];
|
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||||
const startGameNumber = match.tournamentCodeIds.length + 1;
|
const startGameNumber = match.tournamentCodeIds.length + 1;
|
||||||
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
|
const expiresAfter = new Date(
|
||||||
|
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
||||||
|
);
|
||||||
|
|
||||||
for (let index = 0; index < need; index += 1) {
|
for (let index = 0; index < need; index += 1) {
|
||||||
const code = await TournamentCodeModel.findOneAndUpdate(
|
const code = await TournamentCodeModel.findOneAndUpdate(
|
||||||
@@ -334,10 +337,14 @@ export class TournamentCodeService {
|
|||||||
throw new NotFoundException('Assigned tournament code not found.');
|
throw new NotFoundException('Assigned tournament code not found.');
|
||||||
}
|
}
|
||||||
if (currentCode.state === 'used' || currentCode.riotMatchId) {
|
if (currentCode.state === 'used' || currentCode.riotMatchId) {
|
||||||
throw new BadRequestException('Used tournament codes cannot be replaced.');
|
throw new BadRequestException(
|
||||||
|
'Used tournament codes cannot be replaced.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
|
const expiresAfter = new Date(
|
||||||
|
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
||||||
|
);
|
||||||
const replacement = await TournamentCodeModel.findOneAndUpdate(
|
const replacement = await TournamentCodeModel.findOneAndUpdate(
|
||||||
{
|
{
|
||||||
state: 'available',
|
state: 'available',
|
||||||
@@ -358,7 +365,9 @@ export class TournamentCodeService {
|
|||||||
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
||||||
).exec();
|
).exec();
|
||||||
if (!replacement) {
|
if (!replacement) {
|
||||||
throw new BadRequestException('No available tournament code to replace with.');
|
throw new BadRequestException(
|
||||||
|
'No available tournament code to replace with.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
currentCode.state = 'released';
|
currentCode.state = 'released';
|
||||||
@@ -449,6 +458,7 @@ export class TournamentCodeService {
|
|||||||
const matches = await MatchModel.find(filter).exec();
|
const matches = await MatchModel.find(filter).exec();
|
||||||
const touched: MatchDocument[] = [];
|
const touched: MatchDocument[] = [];
|
||||||
for (const match of matches) {
|
for (const match of matches) {
|
||||||
|
if (!this.hasBuiltTeams(match)) continue;
|
||||||
if (
|
if (
|
||||||
(match.tournamentCodeIds?.length ?? 0) >=
|
(match.tournamentCodeIds?.length ?? 0) >=
|
||||||
this.resolveRequiredSlots(match)
|
this.resolveRequiredSlots(match)
|
||||||
@@ -463,7 +473,16 @@ export class TournamentCodeService {
|
|||||||
return touched;
|
return touched;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async buildSlots(match: MatchDocument): Promise<TournamentCodeSlotView[]> {
|
private hasBuiltTeams(match: MatchDocument): boolean {
|
||||||
|
return Boolean(
|
||||||
|
match.teams.length >= 2 &&
|
||||||
|
match.teams.every((team) => team.members.length > 0),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async buildSlots(
|
||||||
|
match: MatchDocument,
|
||||||
|
): Promise<TournamentCodeSlotView[]> {
|
||||||
if (
|
if (
|
||||||
(match.gameMode ?? 'pair') === 'round-robin' &&
|
(match.gameMode ?? 'pair') === 'round-robin' &&
|
||||||
(match.gameSchedule?.length ?? 0) === 0 &&
|
(match.gameSchedule?.length ?? 0) === 0 &&
|
||||||
|
|||||||
Reference in new issue
Block a user