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