|
| 1 | +import { describe, it, expect, vi, beforeEach } from 'vitest' |
| 2 | + |
| 3 | +vi.mock('@/lib/db', () => ({ |
| 4 | + sql: Object.assign(vi.fn(), { unsafe: vi.fn() }), |
| 5 | +})) |
| 6 | + |
| 7 | +const { mockGetLatestLedger, mockGetEvents, MockSorobanServer } = vi.hoisted(() => { |
| 8 | + const mGetLatestLedger = vi.fn().mockResolvedValue({ sequence: 100 }) |
| 9 | + const mGetEvents = vi.fn().mockResolvedValue({ events: [] }) |
| 10 | + |
| 11 | + const MServer = class { |
| 12 | + getLatestLedger = mGetLatestLedger |
| 13 | + getEvents = mGetEvents |
| 14 | + } |
| 15 | + |
| 16 | + return { |
| 17 | + mockGetLatestLedger: mGetLatestLedger, |
| 18 | + mockGetEvents: mGetEvents, |
| 19 | + MockSorobanServer: MServer, |
| 20 | + } |
| 21 | +}) |
| 22 | + |
| 23 | +vi.mock('@stellar/stellar-sdk', () => ({ |
| 24 | + default: MockSorobanServer, |
| 25 | +})) |
| 26 | + |
| 27 | +import { sql } from '@/lib/db' |
| 28 | +import { ContractSyncService } from '@/lib/contract-sync/service' |
| 29 | +import type { SorobanEventPayload } from '@/lib/contract-sync/types' |
| 30 | + |
| 31 | +function makePayload(overrides: Partial<SorobanEventPayload> = {}): SorobanEventPayload { |
| 32 | + return { |
| 33 | + event: 'fund', |
| 34 | + contractAddress: 'CA1234', |
| 35 | + ledgerSequence: 1000, |
| 36 | + timestamp: Date.now(), |
| 37 | + txHash: 'abc123', |
| 38 | + data: [], |
| 39 | + ...overrides, |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +describe('ContractSyncService', () => { |
| 44 | + beforeEach(() => { |
| 45 | + vi.clearAllMocks() |
| 46 | + }) |
| 47 | + |
| 48 | + describe('onEvent (duplicate protection)', () => { |
| 49 | + it('skips enqueueing an event that was already synced successfully', async () => { |
| 50 | + const service = new ContractSyncService({ contractAddresses: ['CA1'] }) |
| 51 | + const enqueueSpy = vi.spyOn(service.getQueue(), 'enqueue') |
| 52 | + |
| 53 | + ;(sql as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce([{ '?column?': 1 }]) |
| 54 | + |
| 55 | + await (service as any).onEvent(makePayload()) |
| 56 | + |
| 57 | + expect(enqueueSpy).not.toHaveBeenCalled() |
| 58 | + expect(sql).toHaveBeenCalledTimes(1) |
| 59 | + }) |
| 60 | + |
| 61 | + it('enqueues and logs an event that has not been synced before', async () => { |
| 62 | + const service = new ContractSyncService({ contractAddresses: ['CA1'] }) |
| 63 | + const enqueueSpy = vi.spyOn(service.getQueue(), 'enqueue') |
| 64 | + |
| 65 | + ;(sql as unknown as ReturnType<typeof vi.fn>) |
| 66 | + .mockResolvedValueOnce([]) // isAlreadySynced -> not found |
| 67 | + .mockResolvedValueOnce([]) // createSyncLog insert |
| 68 | + |
| 69 | + await (service as any).onEvent(makePayload({ txHash: 'new-tx' })) |
| 70 | + |
| 71 | + expect(enqueueSpy).toHaveBeenCalledWith(expect.objectContaining({ txHash: 'new-tx' })) |
| 72 | + expect(sql).toHaveBeenCalledTimes(2) |
| 73 | + }) |
| 74 | + }) |
| 75 | + |
| 76 | + describe('checkpoint persistence', () => { |
| 77 | + it('loadCheckpoint returns null when no row exists', async () => { |
| 78 | + const service = new ContractSyncService({ contractAddresses: ['CA1'] }) |
| 79 | + ;(sql as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce([]) |
| 80 | + |
| 81 | + const result = await (service as any).loadCheckpoint() |
| 82 | + expect(result).toBeNull() |
| 83 | + }) |
| 84 | + |
| 85 | + it('loadCheckpoint returns the persisted ledger as a number', async () => { |
| 86 | + const service = new ContractSyncService({ contractAddresses: ['CA1'] }) |
| 87 | + ;(sql as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce([{ last_ledger: '4242' }]) |
| 88 | + |
| 89 | + const result = await (service as any).loadCheckpoint() |
| 90 | + expect(result).toBe(4242) |
| 91 | + }) |
| 92 | + |
| 93 | + it('persistCheckpoint issues an upsert', async () => { |
| 94 | + const service = new ContractSyncService({ contractAddresses: ['CA1'] }) |
| 95 | + ;(sql as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce([]) |
| 96 | + |
| 97 | + await (service as any).persistCheckpoint(555) |
| 98 | + expect(sql).toHaveBeenCalledTimes(1) |
| 99 | + }) |
| 100 | + |
| 101 | + it('start() seeds the listener from a persisted checkpoint instead of the chain tip', async () => { |
| 102 | + const service = new ContractSyncService({ contractAddresses: ['CA1'] }) |
| 103 | + ;(sql as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce([{ last_ledger: '777' }]) |
| 104 | + |
| 105 | + await service.start() |
| 106 | + service.stop() |
| 107 | + |
| 108 | + expect(mockGetLatestLedger).not.toHaveBeenCalled() |
| 109 | + }) |
| 110 | + }) |
| 111 | + |
| 112 | + describe('failure / dead-letter audit logging', () => { |
| 113 | + it('records a failed sync attempt with the error message on retry', async () => { |
| 114 | + const service = new ContractSyncService({ contractAddresses: ['CA1'], maxRetries: 5 }) |
| 115 | + const updateSpy = vi.spyOn(service as any, 'updateSyncLog').mockResolvedValue(undefined) |
| 116 | + |
| 117 | + const queue = service.getQueue() |
| 118 | + queue.setHandler(async () => { |
| 119 | + throw new Error('boom') |
| 120 | + }) |
| 121 | + |
| 122 | + vi.useFakeTimers() |
| 123 | + queue.enqueue(makePayload({ txHash: 'fail-tx' })) |
| 124 | + queue.start() |
| 125 | + await vi.advanceTimersByTimeAsync(1000) |
| 126 | + queue.stop() |
| 127 | + vi.useRealTimers() |
| 128 | + |
| 129 | + expect(updateSpy).toHaveBeenCalledWith( |
| 130 | + 'fail-tx:fund:0', |
| 131 | + expect.objectContaining({ status: 'failed', errorMessage: 'boom' }) |
| 132 | + ) |
| 133 | + }) |
| 134 | + |
| 135 | + it('records dead_letter status once retries are exhausted', async () => { |
| 136 | + const service = new ContractSyncService({ contractAddresses: ['CA1'], maxRetries: 1 }) |
| 137 | + const updateSpy = vi.spyOn(service as any, 'updateSyncLog').mockResolvedValue(undefined) |
| 138 | + |
| 139 | + const queue = service.getQueue() |
| 140 | + queue.setHandler(async () => { |
| 141 | + throw new Error('permanent failure') |
| 142 | + }) |
| 143 | + |
| 144 | + vi.useFakeTimers() |
| 145 | + queue.enqueue(makePayload({ txHash: 'dead-tx' })) |
| 146 | + queue.start() |
| 147 | + await vi.advanceTimersByTimeAsync(1000) |
| 148 | + queue.stop() |
| 149 | + vi.useRealTimers() |
| 150 | + |
| 151 | + expect(updateSpy).toHaveBeenCalledWith( |
| 152 | + 'dead-tx:fund:0', |
| 153 | + expect.objectContaining({ status: 'dead_letter', errorMessage: 'permanent failure' }) |
| 154 | + ) |
| 155 | + }) |
| 156 | + }) |
| 157 | +}) |
0 commit comments