|
| 1 | +import { createClient } from '@clickhouse/client' |
| 2 | +import nano from 'nano' |
| 3 | + |
| 4 | +import { config } from './config' |
| 5 | +import { initDbs } from './initDbs' |
| 6 | +import { asStandardTx, DbTx, StandardTx, wasDbTx } from './types' |
| 7 | +import { datelog, snooze } from './util' |
| 8 | + |
| 9 | +// Clickhouse recommends large batch inserts. We consider the couchdb |
| 10 | +// query size as well. |
| 11 | +const PAGE_SIZE = 10_000 |
| 12 | + |
| 13 | +const nanoDb = nano(config.couchDbFullpath) |
| 14 | +const clickhouseDb = createClient(config.clickhouseConnection) |
| 15 | + |
| 16 | +export async function clickhouseEngine(): Promise<void> { |
| 17 | + await initDbs() |
| 18 | + await initClickhouseDb() |
| 19 | + |
| 20 | + const dbTransactions = nanoDb.db.use<StandardTx>('reports_transactions') |
| 21 | + |
| 22 | + let afterTime = new Date(0).toISOString() |
| 23 | + let bookmark: string | undefined |
| 24 | + |
| 25 | + while (true) { |
| 26 | + const response = await dbTransactions.find({ |
| 27 | + selector: { |
| 28 | + status: { $eq: 'complete' }, |
| 29 | + updateTime: { $gt: afterTime } |
| 30 | + }, |
| 31 | + sort: [{ updateTime: 'asc' }], |
| 32 | + use_index: 'status-updatetime', |
| 33 | + limit: PAGE_SIZE, |
| 34 | + bookmark |
| 35 | + }) |
| 36 | + |
| 37 | + bookmark = response.bookmark |
| 38 | + |
| 39 | + const startDocId = response.docs[0]?._id |
| 40 | + const endDocId = response.docs[response.docs.length - 1]?._id |
| 41 | + |
| 42 | + if (response.docs.length > 0) { |
| 43 | + datelog( |
| 44 | + `Processing ${response.docs.length} rows from ${startDocId} to ${endDocId}.` |
| 45 | + ) |
| 46 | + } else { |
| 47 | + datelog(`Queried for new documents after ${afterTime}.`) |
| 48 | + } |
| 49 | + |
| 50 | + const newDocs: DbTx[] = [] |
| 51 | + const newRows: any[][] = [] |
| 52 | + let lastDocUpdateTime: string | undefined |
| 53 | + |
| 54 | + for (const doc of response.docs) { |
| 55 | + const { appId, partnerId } = getDocumentIdentifiers(doc._id) |
| 56 | + |
| 57 | + const standardTx = asStandardTx(doc) |
| 58 | + |
| 59 | + newRows.push([ |
| 60 | + appId, |
| 61 | + partnerId, |
| 62 | + standardTx.orderId, |
| 63 | + standardTx.countryCode, |
| 64 | + standardTx.depositTxid, |
| 65 | + standardTx.depositAddress, |
| 66 | + standardTx.depositCurrency, |
| 67 | + standardTx.depositAmount, |
| 68 | + standardTx.direction, |
| 69 | + standardTx.exchangeType, |
| 70 | + standardTx.paymentType, |
| 71 | + standardTx.payoutTxid, |
| 72 | + standardTx.payoutAddress, |
| 73 | + standardTx.payoutCurrency, |
| 74 | + standardTx.payoutAmount, |
| 75 | + standardTx.status, |
| 76 | + Math.round(standardTx.timestamp), |
| 77 | + standardTx.usdValue, |
| 78 | + config.clickhouseIndexVersion |
| 79 | + ]) |
| 80 | + |
| 81 | + newDocs.push( |
| 82 | + wasDbTx({ |
| 83 | + _id: doc._id, |
| 84 | + _rev: doc._rev, |
| 85 | + ...standardTx |
| 86 | + }) |
| 87 | + ) |
| 88 | + |
| 89 | + lastDocUpdateTime = standardTx.updateTime.toISOString() |
| 90 | + } |
| 91 | + |
| 92 | + // Add the standardTx to the clickhouse database |
| 93 | + await clickhouseDb.insert({ |
| 94 | + table: 'reports_transactions', |
| 95 | + columns: [ |
| 96 | + 'appId', |
| 97 | + 'partnerId', |
| 98 | + 'orderId', |
| 99 | + 'countryCode', |
| 100 | + 'depositTxid', |
| 101 | + 'depositAddress', |
| 102 | + 'depositCurrency', |
| 103 | + 'depositAmount', |
| 104 | + 'direction', |
| 105 | + 'exchangeType', |
| 106 | + 'paymentType', |
| 107 | + 'payoutTxid', |
| 108 | + 'payoutAddress', |
| 109 | + 'payoutCurrency', |
| 110 | + 'payoutAmount', |
| 111 | + 'status', |
| 112 | + 'timestamp', |
| 113 | + 'usdValue', |
| 114 | + 'indexVersion' |
| 115 | + ], |
| 116 | + values: newRows |
| 117 | + }) |
| 118 | + // Update all documents processed |
| 119 | + await dbTransactions.bulk({ docs: newDocs }) |
| 120 | + |
| 121 | + // We've reached the end of the view index, so we'll continue but with a |
| 122 | + // delay so as not to thrash the couchdb unnecessarily. |
| 123 | + if (response.docs.length !== PAGE_SIZE) { |
| 124 | + bookmark = undefined |
| 125 | + if (lastDocUpdateTime != null) { |
| 126 | + afterTime = lastDocUpdateTime |
| 127 | + } |
| 128 | + await snooze(5000) |
| 129 | + } |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +function getDocumentIdentifiers( |
| 134 | + documentId: string |
| 135 | +): { appId: string; partnerId: string } { |
| 136 | + const parts = documentId.split(':')[0].split('_') |
| 137 | + if (parts.length === 0) { |
| 138 | + throw new Error(`Invalid documentId ${documentId}`) |
| 139 | + } |
| 140 | + const partnerId = parts.pop() as string |
| 141 | + const appId = parts.join('_') |
| 142 | + return { appId, partnerId } |
| 143 | +} |
| 144 | + |
| 145 | +const REPORTS_TRANSACTIONS_SCHEMA = `\ |
| 146 | +CREATE TABLE default.reports_transactions |
| 147 | +( |
| 148 | + \`partnerId\` String, |
| 149 | + \`appId\` String, |
| 150 | + \`orderId\` String, |
| 151 | + \`countryCode\` String, |
| 152 | + \`depositTxid\` String, |
| 153 | + \`depositAddress\` String, |
| 154 | + \`depositCurrency\` String, |
| 155 | + \`depositAmount\` Float64, |
| 156 | + \`direction\` String, |
| 157 | + \`exchangeType\` String, |
| 158 | + \`paymentType\` String, |
| 159 | + \`payoutTxid\` String, |
| 160 | + \`payoutAddress\` String, |
| 161 | + \`payoutCurrency\` String, |
| 162 | + \`payoutAmount\` Float64, |
| 163 | + \`status\` String, |
| 164 | + \`timestamp\` DateTime DEFAULT now(), |
| 165 | + \`usdValue\` Float64, |
| 166 | + \`indexVersion\` UInt16 |
| 167 | +) |
| 168 | +ENGINE = ReplacingMergeTree |
| 169 | +PRIMARY KEY (appId, partnerId, orderId) |
| 170 | +ORDER BY (appId, partnerId, orderId, timestamp) |
| 171 | +SETTINGS index_granularity = 8192` |
| 172 | + |
| 173 | +async function initClickhouseDb(): Promise<void> { |
| 174 | + // Check if the table exists |
| 175 | + const tableExists = await clickhouseDb.query({ |
| 176 | + query: ` |
| 177 | + SELECT 1 |
| 178 | + FROM system.tables |
| 179 | + WHERE database = 'default' AND name = 'reports_transactions' |
| 180 | + LIMIT 1; |
| 181 | + `, |
| 182 | + format: 'JSONEachRow' |
| 183 | + }) |
| 184 | + |
| 185 | + const result = await tableExists.json() |
| 186 | + if (result.length > 0) { |
| 187 | + const response = await clickhouseDb.query({ |
| 188 | + query: 'SHOW CREATE reports_transactions' |
| 189 | + }) |
| 190 | + const result = await response.json() |
| 191 | + const tableSchema = (result.data[0] as any).statement |
| 192 | + |
| 193 | + if (tableSchema !== REPORTS_TRANSACTIONS_SCHEMA) { |
| 194 | + console.log(tableSchema) |
| 195 | + throw new Error('Table "reports_transactions" schema does not match.') |
| 196 | + } |
| 197 | + |
| 198 | + datelog('Table "reports_transactions" exists.') |
| 199 | + return |
| 200 | + } |
| 201 | + |
| 202 | + // Create the table |
| 203 | + await clickhouseDb.command({ |
| 204 | + query: REPORTS_TRANSACTIONS_SCHEMA |
| 205 | + }) |
| 206 | + datelog('Table "reports_transactions" has been created.') |
| 207 | +} |
0 commit comments