입찰 장수가 사라진 유니크 경매를 복구하고 시스템 공지를 지원한다
This commit is contained in:
1 parent
0ae14d5ee0
commit
3f51bec90a
6 files changed
+344
-23
No files matched your search
@@ -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}`);
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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 };
|
||||
|
||||
Reference in new issue
Block a user