입찰 장수가 사라진 유니크 경매를 복구하고 시스템 공지를 지원한다

This commit is contained in:
Hide_D committed 2026-12-04 09:57:02 +09:00
1 parent 0ae14d5ee0
commit 3f51bec90a
6 files changed
+344 -23

No files matched your search

+19 -5
View File
@@ -8,6 +8,7 @@ import {
resolvePostgresConfigFromEnv,
resolveRedisConfigFromEnv,
} from '@sammo-ts/infra';
import { asRecord } from '@sammo-ts/common';
import { resolveGameApiConfigFromEnv } from '../config.js';
import { createBestEffortResourceCloser } from '../services/bestEffortResourceCloser.js';
@@ -258,7 +259,7 @@ export const processDueAuctionId = async (options: {
}
const current = await transaction.auction.findUnique({
where: { id: auctionId },
select: { status: true, closeAt: true, closeTick: true },
select: { type: true, status: true, closeAt: true, closeTick: true },
});
if (!current) {
return { status: 'IGNORED' as const };
@@ -278,7 +279,8 @@ export const processDueAuctionId = async (options: {
if (current.closeTick === null) throw new Error(`Auction ${auctionId} has no GAME_TIME close authority.`);
const deadline = { closeAt: current.closeAt, closeTick: current.closeTick };
for (let retry = 0; retry <= AUCTION_FINALIZE_RECOVERY_LIMIT; retry += 1) {
let retryLimit = AUCTION_FINALIZE_RECOVERY_LIMIT;
for (let retry = 0; retry <= retryLimit; retry += 1) {
const requestId = buildAuctionFinalizeRequestId(auctionId, deadline, retry);
const existing = await transaction.inputEvent.findUnique({
where: { requestId },
@@ -304,9 +306,21 @@ export const processDueAuctionId = async (options: {
return { status: 'PENDING' as const };
}
if (existing.status === 'SUCCEEDED' && isSuccessfulAuctionFinalizeResult(existing.result, auctionId)) {
throw new Error(
`Auction remained ${current.status} after successful durable event: ${requestId}`
);
throw new Error(`Auction remained ${current.status} after successful durable event: ${requestId}`);
}
const result = asRecord(existing.result);
if (
retry === AUCTION_FINALIZE_RECOVERY_LIMIT &&
current.type === 'UNIQUE_ITEM' &&
current.status === 'FINALIZING' &&
existing.status === 'SUCCEEDED' &&
result.type === 'auctionFinalize' &&
result.auctionId === auctionId &&
result.ok === false &&
result.reason === '입찰자를 찾을 수 없습니다.'
) {
// Re-enqueue once for rows left behind by the previous finalizer.
retryLimit += 1;
}
}
throw new Error(`Auction finalization recovery exhausted: ${auctionId}`);
+13 -1
View File
@@ -1,7 +1,7 @@
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { asRecord, ChangeJournal } from '@sammo-ts/common';
import { writeReadModelChangeJournal } from '@sammo-ts/infra';
import { publishPublicSystemMessage, writeReadModelChangeJournal } from '@sammo-ts/infra';
import type { UserSanctions } from '@sammo-ts/common/auth/gameToken';
import { isMessageAccessBlocked } from '@sammo-ts/common/auth/sanctions';
@@ -492,6 +492,18 @@ export const messagesRouter = router({
...messageBuckets,
};
}),
sendSystem: wallAuthedProcedure
.input(
z.object({ noticeId: z.string().regex(/^[a-zA-Z0-9._-]{1,100}$/), text: z.string().trim().min(1).max(500) })
)
.mutation(async ({ ctx, input }) => {
const roles = ctx.auth?.user.roles ?? [];
if (!roles.includes('superuser') && !roles.includes('admin.superuser')) {
throw new TRPCError({ code: 'FORBIDDEN', message: '시스템 메시지를 보낼 권한이 없습니다.' });
}
const msgId = await publishPublicSystemMessage(ctx.db, input);
return { msgId };
}),
send: accessWallAuthedInputProcedure(
z.object({
generalId: z.number().int().positive(),
+81 -1
View File
@@ -233,6 +233,40 @@ const refundInheritancePoint = async (options: {
}
};
const findUniqueAuctionEscrowOwner = async (
db: AuctionDb,
auctionId: number,
bid: AuctionBidRow
): Promise<string | null> => {
const owners = await db.$queryRaw<{ userId: string }[]>(
GamePrisma.sql`
SELECT e.actor_user_id AS "userId"
FROM auction_bid b
JOIN input_event e
ON e.created_at = b.requested_at_wall
AND e.processing_game_tick = b.occurred_game_tick
WHERE b.id = ${bid.id}
AND b.auction_id = ${auctionId}
AND e.target = 'ENGINE'
AND e.status = 'SUCCEEDED'
AND e.event_type IN ('auctionOpen', 'auctionBid')
AND e.result->>'type' = e.event_type
AND e.result->'ok' = 'true'::jsonb
AND e.result->'auctionId' = to_jsonb(b.auction_id)
AND e.payload->'generalId' = to_jsonb(b.general_id)
AND e.payload->'amount' = to_jsonb(b.amount)
AND (
(e.event_type = 'auctionOpen' AND e.payload->>'auctionType' = 'UNIQUE_ITEM')
OR (e.event_type = 'auctionBid' AND e.payload->'auctionId' = to_jsonb(b.auction_id))
)
AND e.actor_user_id IS NOT NULL
AND e.actor_user_id = e.payload->>'userId'
LIMIT 2
`
);
return owners.length === 1 ? (owners[0]?.userId ?? null) : null;
};
export const createAuctionFinalizer = async (options: {
databaseUrl: string;
world: InMemoryTurnWorld;
@@ -494,7 +528,54 @@ export const createAuctionFinalizer = async (options: {
return { type: 'auctionFinalize', ok: true, auctionId };
}
const bidder = world.getGeneralById(highestBid.generalId);
if (auction.type === 'UNIQUE_ITEM') {
const escrowOwner = await findUniqueAuctionEscrowOwner(db, auctionId, highestBid);
if (!bidder || (escrowOwner !== null && bidder.userId !== escrowOwner)) {
// Only the current escrow is outstanding. Earlier bids were refunded when outbid.
const refunded =
escrowOwner !== null && highestBid.amount > 0
? await db.inheritancePoint.updateManyAndReturn({
where: { userId: escrowOwner, key: 'previous' },
data: { value: { increment: highestBid.amount } },
select: { value: true },
})
: [];
if (escrowOwner !== null && refunded[0]) {
const liveGeneral = world.listGenerals().find((general) => general.userId === escrowOwner);
if (liveGeneral) {
world.updateGeneral(liveGeneral.id, {
inheritancePoints: { ...liveGeneral.inheritancePoints, previous: refunded[0].value },
});
}
const state = world.getState();
await db.inheritanceLog.create({
data: {
userId: escrowOwner,
year: state.currentYear,
month: state.currentMonth,
text: `경매 ${auctionId}번 취소로 유산 ${highestBid.amount}포인트 환불`,
},
});
} else {
await db.errorLog.create({
data: {
category: 'AUCTION',
source: 'auction-finalizer',
message:
'최고 입찰 장수가 없는 유니크 경매를 취소했으나 유산 환불을 확인할 수 없습니다.',
context: { auctionId, bidId: highestBid.id, amount: highestBid.amount },
},
});
}
globalLogger.pushGlobalActionLog(
`경매 ${auctionId}번이 최고 입찰 장수 부재로 취소되었습니다.`,
LogFormat.PLAIN
);
pushLogs(world, globalLogger.flush());
await finalizeStatus('CANCELED');
return { type: 'auctionFinalize', ok: true, auctionId };
}
const bidMeta = parseDetail(highestBid.meta);
const remainExtension = detail.remainCloseDateExtensionCnt ?? 0;
if (bidMeta.tryExtendCloseDate === true && remainExtension > 0) {
@@ -531,7 +612,6 @@ export const createAuctionFinalizer = async (options: {
}
}
const bidder = world.getGeneralById(highestBid.generalId);
if (!bidder) {
return {
type: 'auctionFinalize',
@@ -153,6 +153,61 @@ describe('unique auction inheritance log compatibility', () => {
expect(resolveAuctionResourceAmount(undefined, 'invalid')).toBeNull();
});
it.each([
{ description: '장수 ID를 새 소유자가 사용함', provenOwner: 'original-account', refund: true },
{ description: '사라진 장수의 입찰 계정을 확인할 수 없음', provenOwner: null, refund: false },
])('유니크 경매를 끝낸다. $description', async ({ provenOwner, refund }) => {
const closeAt = new Date('0193-07-01T00:00:00.000Z');
const reusedGeneral = { id: 7, userId: 'new-account' };
const db = {
$queryRaw: vi.fn(async (query: { strings: readonly string[] }) => {
const sql = query.strings.join(' ');
if (sql.includes('JOIN input_event')) return provenOwner ? [{ userId: provenOwner }] : [];
if (sql.includes('FROM auction_bid')) return [{ id: 9, generalId: 7, amount: 5_100, meta: {} }];
return [{ id: 31, type: 'UNIQUE_ITEM', status: 'FINALIZING', detail: {}, closeAt }];
}),
$executeRaw: vi.fn(async () => 1),
inheritancePoint: { updateManyAndReturn: vi.fn(async () => [{ value: 6_100 }]) },
inheritanceLog: { create: vi.fn(async () => undefined) },
errorLog: { create: vi.fn(async () => undefined) },
};
const world = {
getGeneralById: () => (provenOwner ? reusedGeneral : null),
getState: () => ({ currentYear: 193, currentMonth: 7 }),
gameTickToDate: () => closeAt,
listGenerals: () => [reusedGeneral],
updateGeneral: vi.fn(),
pushLog: vi.fn(),
};
const finalizer = await createAuctionFinalizer({
databaseUrl: 'postgresql://unused',
world: world as unknown as Parameters<typeof createAuctionFinalizer>[0]['world'],
});
await expect(
finalizer.finalize(
withDaemonBoundary({ type: 'auctionFinalize', auctionId: 31, expectedCloseTick: 72_000_000 }),
db as unknown as NonNullable<Parameters<typeof finalizer.finalize>[1]>
)
).resolves.toMatchObject({ ok: true });
expect(db.$executeRaw).toHaveBeenCalledWith(expect.objectContaining({ values: ['CANCELED', 31] }));
expect(world.updateGeneral).not.toHaveBeenCalled();
if (refund) {
expect(db.inheritancePoint.updateManyAndReturn).toHaveBeenCalledWith(
expect.objectContaining({
where: { userId: provenOwner, key: 'previous' },
data: { value: { increment: 5_100 } },
})
);
expect(db.inheritanceLog.create).toHaveBeenCalledOnce();
expect(db.errorLog.create).not.toHaveBeenCalled();
} else {
expect(db.inheritancePoint.updateManyAndReturn).not.toHaveBeenCalled();
expect(db.errorLog.create).toHaveBeenCalledOnce();
}
await finalizer.close();
});
it('uses the Ref-inclusive close boundary and the logical tick as the deadline generation', () => {
const closeAt = new Date('0193-07-01T00:00:00.000Z');
const auction = { closeAt, closeTick: 72_000_000n };
+48 -1
View File
@@ -1,6 +1,13 @@
import type { MessageRecordDraft } from '@sammo-ts/logic';
import {
MESSAGE_MAILBOX_PUBLIC,
resolveMessageTargetIcon,
sendMessage,
type MessageRecordDraft,
} from '@sammo-ts/logic';
import { GamePrisma } from './gamePrisma.js';
import { acquireGameSchemaAdvisoryXactLock } from './gameSchemaAdvisoryLock.js';
import { writeReadModelChangeJournal } from './readModelChangeJournal.js';
export interface MessageGameContext {
occurredGameTick: bigint;
@@ -96,3 +103,43 @@ export const persistMessageEnvelope = async (
if (!id) throw new Error('Failed to persist message envelope.');
return id;
};
export const publishPublicSystemMessage = async (
transaction: Pick<GamePrisma.TransactionClient, '$executeRaw' | '$queryRaw' | 'message'>,
notice: { noticeId: string; text: string }
): Promise<number> => {
await acquireGameSchemaAdvisoryXactLock(transaction, `public-system-message:${notice.noticeId}`);
const existing = await transaction.message.findFirst({
where: {
mailbox: MESSAGE_MAILBOX_PUBLIC,
type: 'public',
src: 0,
message: { path: ['option', 'noticeId'], equals: notice.noticeId },
},
select: { id: true },
});
if (existing) return existing.id;
const system = {
generalId: 0,
generalName: '시스템',
nationId: 0,
nationName: '',
color: '#000000',
icon: resolveMessageTargetIcon(),
};
const { receiverId } = await sendMessage(
{ insertMessage: (draft) => persistMessageEnvelope(transaction, draft) },
{
msgType: 'public',
src: system,
dest: system,
text: notice.text,
time: new Date(),
validUntil: new Date('9999-12-31T00:00:00Z'),
option: { noticeId: notice.noticeId },
}
);
await writeReadModelChangeJournal(transaction, [{ domain: 'messages.mailbox', entityId: MESSAGE_MAILBOX_PUBLIC }]);
return receiverId;
};
+128 -15
View File
@@ -13,6 +13,8 @@ import type { AppRouter as GameAppRouter } from '@sammo-ts/game-api';
import {
createGameApiServer,
buildAuctionTimerKeys,
buildAuctionFinalizeRequestId,
processDueAuctionId,
seedAuctionTimers,
DatabaseTurnDaemonTransport,
} from '@sammo-ts/game-api';
@@ -412,6 +414,33 @@ describe('auction integration flow', () => {
}
}, 30_000);
it('restricts public system messages to superusers and publishes a notice once', async () => {
if (!gameServer || !gameClient || !gameConnector || !userSessions[0]) {
throw new Error('runtime not ready');
}
const notice = {
noticeId: 'auction-system-notice-test',
text: '[Codex] 유니크 경매 정산 오류를 수정했습니다.',
};
const anonymous = createGameClient(gameUrl, gameServer.config.trpcPath, {});
const player = createGameClient(gameUrl, gameServer.config.trpcPath, { value: userSessions[0].accessToken });
await expect(anonymous.messages.sendSystem.mutate(notice)).rejects.toMatchObject({
data: { code: 'UNAUTHORIZED' },
});
await expect(player.messages.sendSystem.mutate(notice)).rejects.toMatchObject({ data: { code: 'FORBIDDEN' } });
await expect(gameClient.messages.sendSystem.mutate({ ...notice, text: ' ' })).rejects.toMatchObject({
data: { code: 'BAD_REQUEST' },
});
const sent = await gameClient.messages.sendSystem.mutate(notice);
await expect(gameClient.messages.sendSystem.mutate(notice)).resolves.toEqual(sent);
await expect(gameConnector.prisma.message.findUnique({ where: { id: sent.msgId } })).resolves.toMatchObject({
type: 'public',
mailbox: 9999,
src: 0,
message: { text: notice.text, src: { generalName: '시스템' } },
});
});
it('handles resource auction flow with bidding, extension, and finalization', async () => {
if (!gameConnector || !redisConnector || !gameServer) {
throw new Error('runtime not ready');
@@ -1085,14 +1114,14 @@ describe('auction integration flow', () => {
});
}, 60_000);
it('starts from inheritance, accepts another user bid, and awards a default-pool unique', async () => {
it('awards a default-pool unique and recovers a later auction whose highest bidder disappears', async () => {
if (!gameConnector || !redisConnector || !gameServer) {
throw new Error('runtime not ready');
}
const prisma = gameConnector.prisma;
const redis = redisConnector.client;
const [host, bidder] = userSessions;
if (!host || !bidder) {
const [host, bidder, laterBidder] = userSessions;
if (!host || !bidder || !laterBidder) {
throw new Error('not enough bidders');
}
@@ -1102,11 +1131,7 @@ describe('auction integration flow', () => {
await turnDaemonLoop;
}
const uniquePair = await findUniqueItemPair();
const slotField = resolveSlotField(uniquePair.slot);
if (!slotField) {
throw new Error('unsupported item slot');
}
const itemKey = 'che_무기_07_맥궁';
const state = await prisma.worldState.findFirstOrThrow();
const config =
state.config && typeof state.config === 'object' && !Array.isArray(state.config) ? state.config : {};
@@ -1133,7 +1158,7 @@ describe('auction integration flow', () => {
data: { status: 'CANCELED', finishedAt: new Date() },
});
for (const session of [host, bidder]) {
for (const session of [host, bidder, laterBidder]) {
const row = await prisma.general.findUniqueOrThrow({
where: { id: session.generalId },
select: { meta: true },
@@ -1161,8 +1186,8 @@ describe('auction integration flow', () => {
});
}
await prisma.general.updateMany({
where: { [slotField]: uniquePair.keyA } as GamePrisma.GeneralWhereInput,
data: { [slotField]: 'None' } as GamePrisma.GeneralUpdateManyMutationInput,
where: { weaponCode: itemKey },
data: { weaponCode: 'None' },
});
const gameDatabaseUrl = resolvePostgresConfigFromEnv({ schema: 'che' }).url;
@@ -1181,17 +1206,17 @@ describe('auction integration flow', () => {
const inheritStatus = await hostClient.inherit.getStatus.query();
expect(inheritStatus.availableUnique.length).toBeGreaterThan(80);
expect(inheritStatus.availableUnique).toEqual(
expect.arrayContaining([expect.objectContaining({ key: uniquePair.keyA })])
expect.arrayContaining([expect.objectContaining({ key: itemKey })])
);
const opened = await hostClient.inherit.openUniqueAuction.mutate({
itemId: uniquePair.keyA,
itemId: itemKey,
amount: 5_000,
});
const auction = await prisma.auction.findUniqueOrThrow({ where: { id: opened.auctionId } });
expect(auction).toMatchObject({
type: 'UNIQUE_ITEM',
targetCode: uniquePair.keyA,
targetCode: itemKey,
hostGeneralId: host.generalId,
status: 'OPEN',
});
@@ -1230,11 +1255,99 @@ describe('auction integration flow', () => {
where: { id: bidder.generalId },
select: { weaponCode: true, bookCode: true, horseCode: true, itemCode: true },
});
expect(Object.values(winner)).toContain(uniquePair.keyA);
expect(Object.values(winner)).toContain(itemKey);
await expect(
prisma.inheritancePoint.findUniqueOrThrow({
where: { userId_key: { userId: bidder.userId, key: 'previous' } },
})
).resolves.toMatchObject({ value: 94_900 });
const stuck = await hostClient.inherit.openUniqueAuction.mutate({ itemId: itemKey, amount: 5_000 });
const laterBidderClient = createGameClient(gameUrl, gameServer.config.trpcPath, {
value: laterBidder.accessToken,
});
await laterBidderClient.auction.bidUnique.mutate({ auctionId: stuck.auctionId, amount: 5_100 });
const pointsOf = (userId: string) =>
prisma.inheritancePoint.findUniqueOrThrow({
where: { userId_key: { userId, key: 'previous' } },
});
await expect(pointsOf(laterBidder.userId)).resolves.toMatchObject({ value: 94_900 });
await expect(pointsOf(host.userId)).resolves.toMatchObject({ value: 100_000 });
await turnDaemon.lifecycle.stop('simulate-missing-auction-bidder');
await turnDaemon.close();
await turnDaemonLoop;
await prisma.general.delete({ where: { id: laterBidder.generalId } });
await prisma.auction.update({
where: { id: stuck.auctionId },
data: {
closeAt: finalizeAt,
closeTick: BigInt(finalizeTick),
status: 'FINALIZING',
finalizingAt: new Date(),
},
});
const deadline = { closeAt: finalizeAt, closeTick: BigInt(finalizeTick) };
const legacyFailure = {
type: 'auctionFinalize',
auctionId: stuck.auctionId,
ok: false,
reason: '입찰자를 찾을 수 없습니다.',
};
for (const retry of [0, 1]) {
const requestId = buildAuctionFinalizeRequestId(stuck.auctionId, deadline, retry);
await prisma.inputEvent.create({
data: {
requestId,
target: 'ENGINE',
eventType: 'auctionFinalize',
status: 'SUCCEEDED',
result: legacyFailure,
payload: {
requestId,
type: 'auctionFinalize',
auctionId: stuck.auctionId,
expectedCloseTick: finalizeTick,
expectedCloseAt: finalizeAt.toISOString(),
},
},
});
}
await expect(
processDueAuctionId({ db: prisma, redis, ...timerKeys, id: String(stuck.auctionId), nowMs: Date.now() })
).resolves.toBe('PENDING');
turnDaemon = await createTurnDaemonRuntime({
profile: 'che',
profileName: 'che:908',
databaseUrl: gameDatabaseUrl,
gatewayDatabaseUrl,
});
turnDaemonLoop = turnDaemon.lifecycle.start();
const recoveredRequestId = buildAuctionFinalizeRequestId(stuck.auctionId, deadline, 2);
await expect
.poll(async () => prisma.inputEvent.findUnique({ where: { requestId: recoveredRequestId } }), {
timeout: 10_000,
})
.toMatchObject({ status: 'SUCCEEDED', result: { ok: true } });
await expect(prisma.auction.findUniqueOrThrow({ where: { id: stuck.auctionId } })).resolves.toMatchObject({
status: 'CANCELED',
});
await expect(
transport.requestCommand(
{ type: 'auctionFinalize', auctionId: stuck.auctionId, expectedCloseTick: finalizeTick },
30_000
)
).resolves.toMatchObject({ ok: true });
await expect(pointsOf(laterBidder.userId)).resolves.toMatchObject({ value: 100_000 });
await expect(pointsOf(host.userId)).resolves.toMatchObject({ value: 100_000 });
await expect(
prisma.inheritanceLog.count({
where: { userId: laterBidder.userId, text: `경매 ${stuck.auctionId}번 취소로 유산 5100포인트 환불` },
})
).resolves.toBe(1);
await expect(
hostClient.inherit.openUniqueAuction.mutate({ itemId: itemKey, amount: 5_000 })
).resolves.toMatchObject({ ok: true });
}, 60_000);
});