diff --git a/constants/index.ts b/constants/index.ts index ec9f9783..4565777b 100644 --- a/constants/index.ts +++ b/constants/index.ts @@ -280,7 +280,7 @@ export const CHRONIK_INITIALIZATION_DELAY = 2000 export const MEMPOOL_PROCESS_DELAY = 100 export const CONFIRMED_TX_PROCESS_DELAY = 100 -export const CHRONIK_WS_MAX_CONNECTION_ATTEMPTS = 10 +export const CHRONIK_WS_MAX_DELAY_MS = 60000 export const CHRONIK_WS_BASE_DELAY_MS = 5000 // Number of tries before failing a chronik HTTP call (min 1) diff --git a/services/chronikService.ts b/services/chronikService.ts index f55f0526..3197ab14 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -1,7 +1,7 @@ import { BlockInfo, ChronikClient, ConnectionStrategy, ScriptUtxo, Tx, WsConfig, WsEndpoint, WsMsgClient, WsSubScriptClient } from 'chronik-client' import { encodeCashAddress, decodeCashAddress } from 'ecashaddrjs' import { AddressWithTransaction, BlockchainInfo, TransactionDetails, ProcessedMessages, SubbedAddressesLog, SyncAndSubscriptionReturn, SubscriptionReturn, SimpleBlockInfo } from 'types/chronikTypes' -import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CONFIRMED_TX_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_MAX_CONNECTION_ATTEMPTS, CHRONIK_WS_BASE_DELAY_MS } from 'constants/index' +import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CONFIRMED_TX_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_BASE_DELAY_MS, CHRONIK_WS_MAX_DELAY_MS } from 'constants/index' import { productionAddresses } from 'prisma-local/seeds/addresses' import prisma from 'prisma-local/clientInstance' import { @@ -137,7 +137,10 @@ export class ChronikBlockchainClient { mempoolTxsBeingProcessed!: number private latencyTestFinished: boolean - private wsReconnecting = false + // Bumped every time a new chronik WS endpoint is created, so callbacks and + // retry loops belonging to a replaced endpoint can tell they are stale. + private wsGeneration = 0 + private wsClosedOnPurpose = false private confirmedTxsBeingProcessed = 0 constructor (networkSlug: string) { @@ -156,12 +159,10 @@ export class ChronikBlockchainClient { config.networkBlockchainURLs[networkSlug] ) this.latencyTestFinished = true - this.chronikWSEndpoint = this.chronik.ws(this.getWsConfig()) + this.CHRONIK_MSG_PREFIX = `[CHRONIK — ${networkSlug}]` this.confirmedTxsHashesFromLastBlock = [] - this.chronikWSEndpoint.subscribeToBlocks() - void this.connectWsWithRetry() + this.openWs() this.lastProcessedMessages = { confirmed: {}, unconfirmed: {} } - this.CHRONIK_MSG_PREFIX = `[CHRONIK — ${networkSlug}]` this.wsEndpoint = io(`${config.wsBaseURL}/broadcast`, { query: { key: process.env.WS_AUTH_KEY @@ -183,40 +184,49 @@ export class ChronikBlockchainClient { } } - private async connectWsWithRetry (maxAttempts = CHRONIK_WS_MAX_CONNECTION_ATTEMPTS, baseDelay = CHRONIK_WS_BASE_DELAY_MS): Promise { - for (let attempt = 1; attempt <= maxAttempts; attempt++) { + private isCurrentWs (generation: number): boolean { + return !this.wsClosedOnPurpose && generation === this.wsGeneration + } + + // Creates a fresh chronik WS endpoint (carrying over the given address + // subscriptions) and keeps trying to connect it until it opens or is replaced. + private openWs (addresses: string[] = []): void { + const generation = ++this.wsGeneration + const endpoint = this.chronik.ws(this.getWsConfig(generation)) + endpoint.subscribeToBlocks() + for (const addr of addresses) { + endpoint.subscribeToAddress(addr) + } + this.chronikWSEndpoint = endpoint + void this.connectWsWithRetry(endpoint, generation) + } + + private async connectWsWithRetry (endpoint: WsEndpoint, generation: number, baseDelay = CHRONIK_WS_BASE_DELAY_MS): Promise { + // Never give up: without this socket no new payments are detected and no triggers run. + for (let attempt = 1; this.isCurrentWs(generation); attempt++) { try { - await this.chronikWSEndpoint.waitForOpen() + await endpoint.waitForOpen() console.log(`${this.CHRONIK_MSG_PREFIX}: WebSocket connected.`) return } catch (err: any) { - console.error(`${this.CHRONIK_MSG_PREFIX}: WebSocket connection attempt ${attempt}/${maxAttempts} failed: ${err.message as string}`) - if (attempt < maxAttempts) { - const delay = Math.min(baseDelay * Math.pow(2, attempt - 1), 60000) - console.log(`${this.CHRONIK_MSG_PREFIX}: Retrying WebSocket in ${delay / 1000}s...`) - await new Promise(resolve => setTimeout(resolve, delay)) - } + const delay = Math.min(baseDelay * Math.pow(2, Math.min(attempt - 1, 16)), CHRONIK_WS_MAX_DELAY_MS) + console.error(`${this.CHRONIK_MSG_PREFIX}: WebSocket connection attempt ${attempt} failed: ${err.message as string}. Retrying in ${delay / 1000}s...`) + await new Promise(resolve => setTimeout(resolve, delay)) } } - console.error(`${this.CHRONIK_MSG_PREFIX}: WebSocket failed after ${maxAttempts} attempts. Continuing without real-time updates.`) } - private async reconnectWs (): Promise { - if (this.wsReconnecting) return - this.wsReconnecting = true - try { - const addresses = this.getSubscribedAddresses() - this.chronikWSEndpoint = this.chronik.ws(this.getWsConfig()) - this.chronikWSEndpoint.subscribeToBlocks() - for (const addr of addresses) { - this.chronikWSEndpoint.subscribeToAddress(addr) - } - await this.connectWsWithRetry() - } catch (err: any) { - console.error(`${this.CHRONIK_MSG_PREFIX}: WebSocket reconnection error: ${err.message as string}`) - } finally { - this.wsReconnecting = false - } + private async handleWsEnded (generation: number): Promise { + if (!this.isCurrentWs(generation)) return + console.log(`${this.CHRONIK_MSG_PREFIX}: Reconnecting chronik WebSocket in ${CHRONIK_WS_BASE_DELAY_MS / 1000}s...`) + await new Promise(resolve => setTimeout(resolve, CHRONIK_WS_BASE_DELAY_MS)) + if (!this.isCurrentWs(generation)) return + this.openWs(this.getSubscribedAddresses()) + } + + public closeWs (): void { + this.wsClosedOnPurpose = true + this.chronikWSEndpoint?.close() } public getUrls (): string[] { @@ -736,16 +746,19 @@ export class ChronikBlockchainClient { return details } - private getWsConfig (): WsConfig { + private getWsConfig (generation: number): WsConfig { return { onMessage: (msg: WsMsgClient) => { void this.processWsMessage(msg) }, onError: (e: ws.ErrorEvent) => { console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik webSocket error, type: ${e.type} | message: ${e.message} | error: ${e.error as string}`) }, - onReconnect: (_: ws.Event) => { - console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik webSocket unexpectedly closed. Attempting reconnection...`) - void this.reconnectWs() - }, onConnect: (_: ws.Event) => { console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik webSocket connection (re)established.`) }, - onEnd: (e: ws.Event) => { console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik WebSocket ended, type: ${e.type}.`) }, + // chronik-client's own reconnect is unreliable: a socket error marks the + // endpoint as manually closed (so it never reconnects), and a failed failover + // round is not retried. With autoReconnect off every close ends up in onEnd + // (onReconnect is never called), and we reconnect from there ourselves. + onEnd: (e: ws.Event) => { + console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik WebSocket ended, type: ${e.type}.`) + void this.handleWsEnded(generation) + }, autoReconnect: false } } @@ -1505,7 +1518,7 @@ class MultiBlockchainClient { await Promise.all( Object.values(this.clients).map(async (c) => { try { - c.chronikWSEndpoint.close() + c.closeWs() c.wsEndpoint.close() } catch (err: any) { console.error(`Failed to close connections for client: ${err.message as string}`) diff --git a/services/triggerService.ts b/services/triggerService.ts index 862dc34a..a546af7f 100644 --- a/services/triggerService.ts +++ b/services/triggerService.ts @@ -1,6 +1,6 @@ import { PaybuttonTrigger, Prisma } from '@prisma/client' import axios from 'axios' -import { RESPONSE_MESSAGES, NETWORK_TICKERS_FROM_ID, SUPPORTED_QUOTES_FROM_ID, TRIGGER_LOG_BATCH_SIZE, TRIGGER_POST_CONCURRENCY, TRIGGER_EMAIL_CONCURRENCY } from 'constants/index' +import { RESPONSE_MESSAGES, NETWORK_TICKERS_FROM_ID, SUPPORTED_QUOTES_FROM_ID, TRIGGER_LOG_BATCH_SIZE, TRIGGER_POST_CONCURRENCY, TRIGGER_EMAIL_CONCURRENCY, N_OF_QUOTES } from 'constants/index' import prisma from 'prisma-local/clientInstance' import { EMPTY_OP_RETURN, OpReturnData, parseTriggerPostData } from 'utils/validators' import { BroadcastTxData, SimplifiedTransaction } from 'ws-service/types' @@ -8,6 +8,7 @@ import { fetchPaybuttonById, fetchPaybuttonWithTriggers } from './paybuttonServi import config from 'config' import { MAIL_FROM, MAIL_HTML_REPLACER, MAIL_SUBJECT, getMailerTransporter } from 'constants/mail' import { getTransactionValue } from './transactionService' +import { AllPrices, QuoteValues, fetchPricesForNetworkAndTimestamp, flattenTimestamp } from './priceService' import { runAsyncInBatches } from 'utils/index' // Include Paybutton.owner user inline so we don't refetch per trigger @@ -330,6 +331,31 @@ async function fetchTriggersGroupedByAddress (addresses: string[]): Promise> +): Promise { + if (tx.prices?.length === N_OF_QUOTES) { + return getTransactionValue(tx) + } + const day = flattenTimestamp(tx.timestamp) + let dayPrices = pricesByDay.get(day) + if (dayPrices === undefined) { + dayPrices = fetchPricesForNetworkAndTimestamp(networkId, day, prisma, true) + pricesByDay.set(day, dayPrices) + } + const { usd, cad } = await dayPrices + return { + usd: usd.value.times(tx.amount), + cad: cad.value.times(tx.amount) + } +} + function buildPostParams ( trigger: TriggerWithPaybuttonAndUser, tx: SimplifiedTransaction, @@ -566,11 +592,23 @@ export async function executeTriggersBatch (broadcasts: BroadcastTxData[], netwo // Build queues console.log(`[TRIGGER ${currency}]: preparing triggers for ${txItems.length} txs belonging to ${uniqueAddresses.length} addresses`) + const pricesByDay = new Map>() for (const { address, tx } of txItems) { const triggers = triggersByAddress.get(address) ?? [] if (triggers.length === 0) continue - const values = getTransactionValue(tx) + // Only post triggers that use need prices; a missing price must not + // block email triggers or post triggers that don't send the value. + let values: QuoteValues | undefined + let valuesError: any + if (triggers.some(t => !t.isEmailTrigger && t.postData.includes(VALUE_POST_VARIABLE))) { + try { + values = await resolveTransactionValues(tx, networkId, pricesByDay) + } catch (err: any) { + valuesError = err + console.error(`[TRIGGER ${currency}]: could not get value of tx ${tx.hash}: ${err?.message as string}`) + } + } for (const trigger of triggers) { const user = trigger.paybutton.user @@ -582,10 +620,28 @@ export async function executeTriggersBatch (broadcasts: BroadcastTxData[], netwo actionType: 'SendEmail' }) } else { + let valueStr = '' + if (trigger.postData.includes(VALUE_POST_VARIABLE)) { + if (values === undefined) { + logs.push({ + triggerId: trigger.id, + isError: true, + actionType: 'PostData', + data: JSON.stringify({ + errorName: valuesError?.name ?? 'Error', + errorMessage: `Could not get the value of tx ${tx.hash}: ${valuesError?.message as string}`, + errorStack: valuesError?.stack ?? '', + triggerPostData: trigger.postData, + triggerPostURL: trigger.postURL + }) + }) + continue + } + valueStr = values[SUPPORTED_QUOTES_FROM_ID[user.preferredCurrencyId]].toString() + } userPostCredits[user.id] ??= user.postCredits - const quoteSlug = SUPPORTED_QUOTES_FROM_ID[user.preferredCurrencyId] ;(postTaskQueueByUser[user.id] ??= []).push({ - run: makePostTask(trigger, tx, currency, values[quoteSlug].toString(), logs, address), + run: makePostTask(trigger, tx, currency, valueStr, logs, address), triggerId: trigger.id, actionType: 'PostData' }) diff --git a/tests/unittests/chronikService.test.ts b/tests/unittests/chronikService.test.ts index 08b0ae95..f9e34232 100644 --- a/tests/unittests/chronikService.test.ts +++ b/tests/unittests/chronikService.test.ts @@ -1554,3 +1554,102 @@ describe('WS onMessage matrix (no re-mocks)', () => { logSpy.mockRestore() }) }) + +describe('chronik WebSocket reconnection', () => { + const WS_BASE_DELAY_MS = 5000 + const subscribedAddresses = ['ecash:qqkv9wr69ry2p9l53lxp635va4h86wv435995w8p2h'] + + let client: any + let endpoints: any[] + let configs: any[] + + const mkEndpoint = (): any => ({ + waitForOpen: jest.fn(async () => {}), + subscribeToBlocks: jest.fn(), + subscribeToAddress: jest.fn(), + close: jest.fn(), + subs: { scripts: [] } + }) + + beforeEach(async () => { + process.env.WS_AUTH_KEY = 'test-auth-key' + client = new ChronikBlockchainClient('ecash') + await new Promise(resolve => setImmediate(resolve)) // let the async ctor finish + + endpoints = [] + configs = [] + client.chronik = { + ws: jest.fn((config: any) => { + configs.push(config) + const endpoint = mkEndpoint() + endpoints.push(endpoint) + return endpoint + }) + } + jest.spyOn(client, 'getSubscribedAddresses').mockReturnValue(subscribedAddresses) + client.openWs() + await Promise.resolve() + jest.useFakeTimers() + }) + + afterEach(() => { + jest.useRealTimers() + }) + + it('opens a new endpoint with the previous subscriptions when the socket ends', async () => { + configs[0].onEnd({ type: 'close' }) + await jest.advanceTimersByTimeAsync(WS_BASE_DELAY_MS) + + expect(client.chronik.ws).toHaveBeenCalledTimes(2) + const newEndpoint = endpoints[1] + expect(client.chronikWSEndpoint).toBe(newEndpoint) + expect(newEndpoint.subscribeToBlocks).toHaveBeenCalled() + expect(newEndpoint.subscribeToAddress).toHaveBeenCalledWith(subscribedAddresses[0]) + expect(newEndpoint.waitForOpen).toHaveBeenCalled() + }) + + it('keeps reconnecting on every subsequent end', async () => { + configs[0].onEnd({ type: 'close' }) + await jest.advanceTimersByTimeAsync(WS_BASE_DELAY_MS) + configs[1].onEnd({ type: 'close' }) + await jest.advanceTimersByTimeAsync(WS_BASE_DELAY_MS) + + expect(client.chronik.ws).toHaveBeenCalledTimes(3) + }) + + it('ignores ends from endpoints that were already replaced', async () => { + configs[0].onEnd({ type: 'close' }) + await jest.advanceTimersByTimeAsync(WS_BASE_DELAY_MS) + configs[0].onEnd({ type: 'close' }) + await jest.advanceTimersByTimeAsync(WS_BASE_DELAY_MS) + + expect(client.chronik.ws).toHaveBeenCalledTimes(2) + }) + + it('does not reconnect after closeWs (shutdown)', async () => { + client.closeWs() + expect(endpoints[0].close).toHaveBeenCalled() + configs[0].onEnd({ type: 'close' }) + await jest.advanceTimersByTimeAsync(WS_BASE_DELAY_MS * 10) + + expect(client.chronik.ws).toHaveBeenCalledTimes(1) + }) + + it('keeps retrying the connection instead of giving up after a fixed number of attempts', async () => { + jest.spyOn(console, 'error').mockImplementation(() => {}) + const endpoint = mkEndpoint() + let failures = 0 + endpoint.waitForOpen.mockImplementation(async () => { + if (failures < 15) { + failures += 1 + throw new Error('Error connecting to known Chronik websockets') + } + }) + const generation = client.wsGeneration + const done = client.connectWsWithRetry(endpoint, generation) + await jest.advanceTimersByTimeAsync(60000 * 16) + await done + + expect(endpoint.waitForOpen).toHaveBeenCalledTimes(16) + }) +}) diff --git a/tests/unittests/triggerService.test.ts b/tests/unittests/triggerService.test.ts index 5883395e..76c44a2f 100644 --- a/tests/unittests/triggerService.test.ts +++ b/tests/unittests/triggerService.test.ts @@ -21,6 +21,7 @@ import { import { parseTriggerPostData } from 'utils/validators' import { fetchPaybuttonById as fetchPaybuttonByIdMock, fetchPaybuttonWithTriggers as fetchPaybuttonWithTriggersMock } from 'services/paybuttonService' +import { fetchPricesForNetworkAndTimestamp } from 'services/priceService' jest.mock('axios', () => ({ __esModule: true, @@ -79,6 +80,11 @@ jest.mock('utils/index', () => ({ }) })) +jest.mock('services/priceService', () => ({ + ...jest.requireActual('services/priceService'), + fetchPricesForNetworkAndTimestamp: jest.fn() +})) + // Keep original parseTriggerPostData behavior by default jest.mock('utils/validators', () => { const original = jest.requireActual('utils/validators') @@ -594,6 +600,104 @@ describe('executeTriggersBatch mechanics', () => { }) }) +// ------------------------------ +// txs without linked prices (bulk sync path) +// ------------------------------ +describe('executeTriggersBatch with txs missing linked prices', () => { + const mockedFetchPrices = fetchPricesForNetworkAndTimestamp as jest.MockedFunction + const user = makeUser({ id: 'u', emailCredits: 5, postCredits: 5, preferredCurrencyId: 1 }) + const mkTrigger = (id: string, postData: string): any => ({ + id, + isEmailTrigger: false, + deletedAt: null, + postURL: `https://p/${id}`, + postData, + paybutton: { name: 'PB', providerUserId: 'u', user, addresses: [{ address: { address: primaryAddr } }] } + }) + const trigWithValue = mkTrigger('tValue', '{"value": }') + const trigNoValue = mkTrigger('tNoValue', '{"address":
}') + const trigMail = { + id: 'tM', + isEmailTrigger: true, + deletedAt: null, + postData: '', + emails: 'to@x.com', + paybutton: { name: 'PB', providerUserId: 'u', user, addresses: [{ address: { address: primaryAddr } }] } + } + // Same shape as the stub chronikService builds for txs committed by the bulk sync + const unpricedTx = (h: string, timestamp = 1700000000): any => ({ + hash: h, + amount: new Prisma.Decimal(2), + paymentId: '', + confirmed: true, + message: '', + timestamp, + address: primaryAddr, + rawMessage: '', + inputAddresses: [], + outputAddresses: [], + prices: [] + }) + const allLogs = (): any[] => prismaMock.triggerLog.createMany.mock.calls.flatMap((c: any[]) => c[0].data as any[]) + + beforeEach((): void => { + ;(Mail.getMailerTransporter as jest.Mock).mockReturnValue({ sendMail: jest.fn(async () => ({ accepted: ['to@x.com'], response: '250 OK' })) }) + mockedParse.mockImplementation(jest.requireActual('utils/validators').parseTriggerPostData) + mockedAxios.post.mockResolvedValue({ status: 200, data: 'ok' }) + prismaMock.triggerLog.createMany.mockResolvedValue({ count: 0 } as any) + prismaMock.userProfile.findMany.mockResolvedValue([user]) + prismaMock.userProfile.update.mockResolvedValue({} as any) + }) + + it('looks up the day prices to fill , once per day', async () => { + mockedFetchPrices.mockResolvedValue({ + usd: { value: new Prisma.Decimal('0.5') }, + cad: { value: new Prisma.Decimal('0.6') } + } as any) + prismaMock.paybuttonTrigger.findMany.mockResolvedValue([trigWithValue] as any) + + await executeTriggersBatch([ + { address: primaryAddr, txs: [unpricedTx('h1', 1700000000), unpricedTx('h2', 1700000100)] } + ] as any, 1) + + expect(mockedFetchPrices).toHaveBeenCalledTimes(1) + expect(mockedAxios.post).toHaveBeenCalledTimes(2) + expect(mockedAxios.post.mock.calls[0][1]).toEqual({ value: '1' }) // 2 * 0.5 USD + expect(allLogs().every(l => l.isError === false)).toBe(true) + }) + + it('does not look up prices when no trigger uses ', async () => { + prismaMock.paybuttonTrigger.findMany.mockResolvedValue([trigNoValue, trigMail] as any) + + await executeTriggersBatch([{ address: primaryAddr, txs: [unpricedTx('h1')] }] as any, 1) + + expect(mockedFetchPrices).not.toHaveBeenCalled() + expect(mockedAxios.post).toHaveBeenCalledTimes(1) + expect(allLogs().filter(l => l.isError === false)).toHaveLength(2) + }) + + it('when the price is unavailable, logs an error for triggers and still runs the others', async () => { + mockedFetchPrices.mockRejectedValue(new Error('No Price found')) + prismaMock.paybuttonTrigger.findMany.mockResolvedValue([trigWithValue, trigNoValue, trigMail] as any) + + await executeTriggersBatch([{ address: primaryAddr, txs: [unpricedTx('h1')] }] as any, 1) + + expect(mockedAxios.post).toHaveBeenCalledTimes(1) + expect(mockedAxios.post.mock.calls[0][0]).toBe('https://p/tNoValue') + + const logs = allLogs() + const valueLog = logs.find(l => l.triggerId === 'tValue') + expect(valueLog.isError).toBe(true) + expect(JSON.parse(valueLog.data).errorMessage).toContain('No Price found') + expect(logs.find(l => l.triggerId === 'tNoValue').isError).toBe(false) + expect(logs.find(l => l.triggerId === 'tM').isError).toBe(false) + + // the skipped trigger is not charged + const upd = prismaMock.userProfile.update.mock.calls[0][0] as any + expect(upd.data.postCredits.decrement).toBe(1) + }) +}) + // ------------------------------ // task-level error handling // ------------------------------