Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 84 additions & 4 deletions src/scheduler/ticket-status-reconciliation.job.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ describe('TicketStatusReconciliationJob', () => {
let job: TicketStatusReconciliationJob;
let prisma: {
ticket: { findMany: jest.Mock; updateMany: jest.Mock };
user: { findUnique: jest.Mock };
};
let stellar: { verifyTicket: jest.Mock };
let scheduler: {
Expand All @@ -55,6 +56,7 @@ describe('TicketStatusReconciliationJob', () => {
findMany: jest.fn(),
updateMany: jest.fn().mockResolvedValue({ count: 1 }),
},
user: { findUnique: jest.fn() },
};
stellar = { verifyTicket: jest.fn() };
scheduler = {
Expand Down Expand Up @@ -98,21 +100,27 @@ describe('TicketStatusReconciliationJob', () => {
id: 'ticket-drifted',
chainTicketId: 1n,
status: TicketStatus.VALID,
ownerId: 'owner-1',
owner: { stellarPublicKey: 'GOWNER1' },
},
{
id: 'ticket-current',
chainTicketId: 2n,
status: TicketStatus.USED,
ownerId: 'owner-1',
owner: { stellarPublicKey: 'GOWNER1' },
},
{
id: 'ticket-failed',
chainTicketId: 3n,
status: TicketStatus.VALID,
ownerId: 'owner-1',
owner: { stellarPublicKey: 'GOWNER1' },
},
]);
stellar.verifyTicket
.mockResolvedValueOnce({ status: 'Used' })
.mockResolvedValueOnce({ status: 'Used' })
.mockResolvedValueOnce({ status: 'Used', owner: 'GOWNER1' })
.mockResolvedValueOnce({ status: 'Used', owner: 'GOWNER1' })
.mockRejectedValueOnce(new Error('RPC unavailable'));

await expect(job.reconcileOnce()).resolves.toEqual({
Expand All @@ -123,7 +131,11 @@ describe('TicketStatusReconciliationJob', () => {
failed: 1,
});
expect(prisma.ticket.updateMany).toHaveBeenCalledWith({
where: { id: 'ticket-drifted', status: TicketStatus.VALID },
where: {
id: 'ticket-drifted',
status: TicketStatus.VALID,
ownerId: 'owner-1',
},
data: { status: TicketStatus.USED },
});
expect(log).toHaveBeenCalledWith(
Expand All @@ -135,16 +147,84 @@ describe('TicketStatusReconciliationJob', () => {
);
});

it('repairs owner drift when the chain wallet belongs to a known user', async () => {
prisma.ticket.findMany.mockResolvedValue([
{
id: 'ticket-owner-drifted',
chainTicketId: 4n,
status: TicketStatus.VALID,
ownerId: 'stale-owner',
owner: { stellarPublicKey: 'GOLDOWNER' },
},
]);
stellar.verifyTicket.mockResolvedValue({
status: 'Valid',
owner: 'GNEWOWNER',
});
prisma.user.findUnique.mockResolvedValue({ id: 'chain-owner' });

await expect(job.reconcileOnce()).resolves.toEqual({
checked: 1,
drifted: 1,
repaired: 1,
raced: 0,
failed: 0,
});
expect(prisma.user.findUnique).toHaveBeenCalledWith({
where: { stellarPublicKey: 'GNEWOWNER' },
select: { id: true },
});
expect(prisma.ticket.updateMany).toHaveBeenCalledWith({
where: {
id: 'ticket-owner-drifted',
status: TicketStatus.VALID,
ownerId: 'stale-owner',
},
data: { ownerId: 'chain-owner' },
});
});

it('does not replace the owner when the chain wallet is not a known user', async () => {
prisma.ticket.findMany.mockResolvedValue([
{
id: 'ticket-unknown-owner',
chainTicketId: 5n,
status: TicketStatus.VALID,
ownerId: 'current-owner',
owner: { stellarPublicKey: 'GCURRENT' },
},
]);
stellar.verifyTicket.mockResolvedValue({
status: 'Valid',
owner: 'GUNKNOWN',
});
prisma.user.findUnique.mockResolvedValue(null);

await expect(job.reconcileOnce()).resolves.toMatchObject({
checked: 1,
drifted: 0,
repaired: 0,
raced: 0,
failed: 0,
});
expect(prisma.ticket.updateMany).not.toHaveBeenCalled();
});

it('does not overwrite a status changed since the ticket was read', async () => {
const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation();
prisma.ticket.findMany.mockResolvedValue([
{
id: 'ticket-raced',
chainTicketId: 7n,
status: TicketStatus.VALID,
ownerId: 'owner-1',
owner: { stellarPublicKey: 'GOWNER1' },
},
]);
stellar.verifyTicket.mockResolvedValue({ status: 'Used' });
stellar.verifyTicket.mockResolvedValue({
status: 'Used',
owner: 'GOWNER1',
});
prisma.ticket.updateMany.mockResolvedValue({ count: 0 });

await expect(job.reconcileOnce()).resolves.toMatchObject({
Expand Down
44 changes: 37 additions & 7 deletions src/scheduler/ticket-status-reconciliation.job.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export function ticketReconciliationIntervalMs(
return minutes * 60_000;
}

/** Reconciles the cached ticket status against the contract's source of truth. */
/** Reconciles cached ticket status and ownership against the contract. */
@Injectable()
export class TicketStatusReconciliationJob
implements OnModuleInit, OnModuleDestroy
Expand Down Expand Up @@ -105,7 +105,13 @@ export class TicketStatusReconciliationJob
while (true) {
const tickets = await this.prisma.ticket.findMany({
...(afterId ? { where: { id: { gt: afterId } } } : {}),
select: { id: true, chainTicketId: true, status: true },
select: {
id: true,
chainTicketId: true,
status: true,
ownerId: true,
owner: { select: { stellarPublicKey: true } },
},
orderBy: { id: 'asc' },
take: RECONCILIATION_PAGE_SIZE,
});
Expand All @@ -118,26 +124,50 @@ export class TicketStatusReconciliationJob
try {
const onChain = await this.stellar.verifyTicket(ticket.chainTicketId);
const expectedStatus = CHAIN_STATUS_TO_DB_STATUS[onChain.status];
if (expectedStatus === ticket.status) {
const statusDrifted = expectedStatus !== ticket.status;
const ownerWalletDrifted =
onChain.owner !== ticket.owner.stellarPublicKey;

// A chain wallet without a corresponding account cannot be represented
// as a Ticket owner, so preserve the current owner in that case.
const chainOwner = ownerWalletDrifted
? await this.prisma.user.findUnique({
where: { stellarPublicKey: onChain.owner },
select: { id: true },
})
: null;
const expectedOwnerId = chainOwner?.id;
const ownerDrifted =
expectedOwnerId !== undefined && expectedOwnerId !== ticket.ownerId;

if (!statusDrifted && !ownerDrifted) {
continue;
}

counts.drifted++;
const data = {
...(statusDrifted ? { status: expectedStatus } : {}),
...(ownerDrifted ? { ownerId: expectedOwnerId } : {}),
};
const result = await this.prisma.ticket.updateMany({
where: { id: ticket.id, status: ticket.status },
data: { status: expectedStatus },
where: {
id: ticket.id,
status: ticket.status,
ownerId: ticket.ownerId,
},
data,
});
if (result.count === 0) {
counts.raced++;
this.logger.warn(
`Ticket status drift changed during reconciliation (ticketId=${ticket.id}, chainStatus=${expectedStatus})`,
`Ticket drift changed during reconciliation (ticketId=${ticket.id}, chainStatus=${expectedStatus}, chainOwner=${onChain.owner})`,
);
continue;
}

counts.repaired++;
this.logger.warn(
`Repaired ticket status drift (ticketId=${ticket.id}, databaseStatus=${ticket.status}, chainStatus=${expectedStatus})`,
`Repaired ticket drift (ticketId=${ticket.id}, statusDrifted=${statusDrifted}, ownerDrifted=${ownerDrifted})`,
);
} catch (err) {
counts.failed++;
Expand Down