-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathHasuraBackgroundClient.ts
More file actions
466 lines (442 loc) · 14.5 KB
/
Copy pathHasuraBackgroundClient.ts
File metadata and controls
466 lines (442 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
import { exec } from 'child_process'
import util, { ModuleState } from '@cardano-graphql/util'
import { GraphQLSchema } from 'graphql'
import { GraphQLClient, gql } from 'graphql-request'
import { Client } from 'pg'
import pRetry from 'p-retry'
import path from 'path'
import { dummyLogger, Logger } from 'ts-log'
import { Asset, Block } from './graphql_types'
import {
AssetMetadataAndHash,
AssetMetadataHashAndId,
AssetWithoutTokens,
DbConfig
} from './typeAliases'
const epochInformationNotYetAvailable =
'Epoch information not yet available. This is expected during the initial chain-sync.'
const ASSET_BACKFILL_ADVISORY_LOCK_KEY = 4021991017
const ASSET_BACKFILL_DEFAULT_BATCH_SIZE = 500000
const withHexPrefix = (value: string) =>
`\\x${value !== undefined ? value : ''}`
export class HasuraBackgroundClient {
private client: GraphQLClient
private applyingSchemaAndMetadata: boolean
private state: ModuleState
public schema: GraphQLSchema
constructor (
readonly hasuraCliPath: string,
readonly hasuraCliExtPath: string,
readonly hasuraUri: string,
private logger: Logger = dummyLogger
) {
this.state = null
this.applyingSchemaAndMetadata = false
this.client = new GraphQLClient(`${this.hasuraUri}/v1/graphql`, {
headers: {
'X-Hasura-Role': 'cardano-graphql'
}
})
}
private async hasuraCli (command: string) {
return new Promise((resolve, reject) => {
exec(
`${this.hasuraCliPath} --cli-ext-path ${this.hasuraCliExtPath} --skip-update-check --project ${path.resolve(__dirname, '..', 'hasura', 'project')} --endpoint ${this.hasuraUri} ${command}`,
(error, stdout) => {
if (error) {
reject(error)
}
if (stdout !== '') { this.logger.debug({ module: 'HasuraBackgroundClient' }, stdout) }
resolve({ module: 'HasuraBackgroundClient' })
}
)
})
}
public async initialize () {
if (this.state !== null) return
this.state = 'initializing'
this.logger.info({ module: 'HasuraBackgroundClient' }, 'Initializing')
await pRetry(
async () => {
const result = await this.client.request(gql`
query {
epochs(limit: 1, order_by: { number: desc }) {
number
}
}
`)
if (result.epochs.length === 0) {
this.logger.debug(
{ module: 'HasuraBackgroundClient' },
epochInformationNotYetAvailable
)
throw new Error(epochInformationNotYetAvailable)
}
},
{
factor: 1.05,
retries: 10,
onFailedAttempt: util.onFailedAttemptFor(
'Detecting DB sync state has reached minimum progress',
this.logger
)
}
)
this.logger.debug(
{ module: 'HasuraBackgroundClient' },
'DB sync state has reached minimum progress'
)
this.state = 'initialized'
this.logger.info({ module: 'HasuraBackgroundClient' }, 'Initialized')
}
public async shutdown () {
this.state = null
}
public async applySchemaAndMetadata (): Promise<void> {
if (this.applyingSchemaAndMetadata) return
this.applyingSchemaAndMetadata = true
this.logger.info({ module: 'HasuraBackgroundClient' }, 'Applying PostgreSQL schema migrations')
await pRetry(
async () => {
await this.hasuraCli('migrate --database-name default apply --down all')
await this.hasuraCli('migrate --database-name default apply --up all')
},
{
factor: 1.75,
retries: 9,
onFailedAttempt: util.onFailedAttemptFor(
'Applying PostgreSQL schema migrations',
this.logger
)
}
)
this.logger.info({ module: 'HasuraBackgroundClient' }, 'Applying Hasura metadata')
await pRetry(
async () => {
await this.hasuraCli('metadata clear')
await this.hasuraCli('metadata apply')
},
{
factor: 1.75,
retries: 9,
onFailedAttempt: util.onFailedAttemptFor(
'Applying Hasura metadata',
this.logger
)
}
)
this.logger.info({ module: 'HasuraBackgroundClient' }, 'Hasura setup complete')
this.applyingSchemaAndMetadata = false
}
public async deleteAssetsAfterSlot (slotNo: Block['slotNo']): Promise<number> {
this.logger.debug(
{ module: 'HasuraClient', slotNo },
'deleting assets found in tokens after slot'
)
const result = await this.client.request(
gql`
mutation DeleteAssetsAfterSlot($slotNo: Int!) {
delete_assets(where: { firstAppearedInSlot: { _gt: $slotNo } }) {
affected_rows
}
}
`,
{
slotNo
}
)
return result.delete_assets.affected_rows
}
public async hasAsset (assetId: Asset['assetId']): Promise<boolean> {
const result = await this.client.request(
gql`
query HasAsset($assetId: bytea!) {
assets(where: { assetId: { _eq: $assetId } }) {
assetId
}
}
`,
{
assetId: withHexPrefix(assetId)
}
)
const response = result.assets.length > 0
this.logger.debug(
{ module: 'HasuraClient', assetId, hasAsset: response },
'Has asset?'
)
return response
}
public async addAssetMetadata (asset: AssetMetadataAndHash) {
this.logger.info(
{ module: 'HasuraClient', assetId: asset.assetId },
'Adding metadata to asset'
)
const result = await this.client.request(
gql`
mutation AddAssetMetadata(
$assetId: bytea!
$decimals: Int
$description: String
$logo: String
$metadataHash: bpchar!
$name: String
$ticker: String
$url: String
) {
update_assets(
where: { assetId: { _eq: $assetId } }
_set: {
decimals: $decimals
description: $description
logo: $logo
metadataHash: $metadataHash
name: $name
ticker: $ticker
url: $url
}
) {
affected_rows
returning {
assetId
}
}
}
`,
{
...asset,
assetId: withHexPrefix(asset.assetId),
ticker: asset.ticker && asset.ticker.length > 9 ? undefined : asset.ticker
}
)
if (result.errors !== undefined) {
throw new Error(result.errors)
}
}
public async insertAssets (assets: AssetWithoutTokens[]) {
this.logger.debug(
{ module: 'HasuraClient', qty: assets.length },
'inserting assets found in tokens'
)
const result = await this.client.request(
gql`
mutation InsertAssets($assets: [Asset_insert_input!]!) {
insert_assets(
objects: $assets
on_conflict: { constraint: Asset_pkey, update_columns: [] }
) {
returning {
name
policyId
description
assetName
assetId
}
affected_rows
}
}
`,
{
assets: assets.map((asset) => ({
...asset,
...{
assetId: withHexPrefix(asset.assetId),
assetName: withHexPrefix(asset.assetName),
policyId: withHexPrefix(asset.policyId)
}
}))
}
)
return result
}
public async getAssetMetadataHashesById (
assetIds: Asset['assetId'][]
): Promise<AssetMetadataHashAndId[]> {
const result = await this.client.request(
gql`
query AssetMetadataHashes($assetIds: [bytea!]!) {
assets(where: { assetId: { _in: $assetIds } }) {
assetId
metadataHash
}
}
`,
{
assetIds: assetIds.map((id) => withHexPrefix(id))
}
)
return result.assets
}
public async getMaxMultiAssetId (dbConfig: DbConfig): Promise<number> {
const client = new Client(dbConfig)
await client.connect()
try {
const result = await client.query<{ maxId: string }>('SELECT COALESCE(MAX(id), 0) AS "maxId" FROM multi_asset')
return Number(result.rows[0].maxId)
} finally {
await client.end()
}
}
public async pollNewAssets (dbConfig: DbConfig, lastSeenId: number): Promise<{ assetIds: string[], nextLastSeenId: number }> {
const client = new Client(dbConfig)
await client.connect()
try {
const boundaryResult = await client.query<{ maxConfirmedId: string }>(`
SELECT COALESCE(MAX(ma.id), $1) AS "maxConfirmedId"
FROM multi_asset ma
JOIN ma_tx_mint mtm ON mtm.ident = ma.id
JOIN tx ON tx.id = mtm.tx_id
JOIN block b ON b.id = tx.block_id
WHERE ma.id > $1
AND b.slot_no < (SELECT slot_no FROM block ORDER BY id DESC LIMIT 1) - 120
`, [lastSeenId])
const nextLastSeenId = Number(boundaryResult.rows[0].maxConfirmedId)
if (nextLastSeenId === lastSeenId) {
return { assetIds: [], nextLastSeenId }
}
const result = await client.query<{ assetId: string }>(`
INSERT INTO "Asset" ("assetId", "assetName", "policyId", "fingerprint", "firstAppearedInSlot")
SELECT
CAST(CONCAT(ma.policy, RIGHT(CONCAT(E'\\\\', ma.name), -3)) AS BYTEA),
ma.name,
ma.policy,
ma.fingerprint,
MIN(b.slot_no)
FROM multi_asset ma
JOIN ma_tx_mint mtm ON mtm.ident = ma.id
JOIN tx ON tx.id = mtm.tx_id
JOIN block b ON b.id = tx.block_id
LEFT JOIN "Asset" a
ON a."assetId" = CAST(CONCAT(ma.policy, RIGHT(CONCAT(E'\\\\', ma.name), -3)) AS BYTEA)
WHERE a."assetId" IS NULL
AND ma.id > $1
AND ma.id <= $2
GROUP BY ma.id, ma.policy, ma.name, ma.fingerprint
ON CONFLICT ("assetId") DO NOTHING
RETURNING encode("assetId", 'hex') AS "assetId"
`, [lastSeenId, nextLastSeenId])
if (result.rowCount > 0) {
this.logger.info(
{ module: 'HasuraBackgroundClient', inserted: result.rowCount },
'Polled and inserted new assets from multi_asset'
)
}
return {
assetIds: result.rows.map((row) => row.assetId),
nextLastSeenId
}
} finally {
await client.end()
}
}
public async getAssetIdsWithoutMetadata (dbConfig: DbConfig): Promise<string[]> {
const client = new Client(dbConfig)
await client.connect()
try {
const result = await client.query<{ assetId: string }>(`
SELECT encode("assetId", 'hex') AS "assetId"
FROM "Asset"
WHERE "metadataHash" IS NULL
`)
this.logger.info(
{ module: 'HasuraBackgroundClient', qty: result.rowCount },
'Found assets without metadata'
)
return result.rows.map(row => row.assetId)
} finally {
await client.end()
}
}
public async getRecentAssetIdsWithoutMetadata (dbConfig: DbConfig): Promise<string[]> {
const NINETY_DAYS_IN_SLOTS = 7_776_000
const client = new Client(dbConfig)
await client.connect()
try {
const result = await client.query<{ assetId: string }>(`
SELECT encode("assetId", 'hex') AS "assetId"
FROM "Asset"
WHERE "metadataHash" IS NULL
AND "firstAppearedInSlot" > (SELECT MAX("firstAppearedInSlot") FROM "Asset") - $1
`, [NINETY_DAYS_IN_SLOTS])
this.logger.info(
{ module: 'HasuraBackgroundClient', qty: result.rowCount },
'Found recent assets without metadata'
)
return result.rows.map(row => row.assetId)
} finally {
await client.end()
}
}
public async backfillMissingAssets (dbConfig: DbConfig, batchSize: number = ASSET_BACKFILL_DEFAULT_BATCH_SIZE): Promise<string[]> {
const client = new Client(dbConfig)
await client.connect()
try {
const lockResult = await client.query<{ locked: boolean }>(
'SELECT pg_try_advisory_lock($1) AS locked',
[ASSET_BACKFILL_ADVISORY_LOCK_KEY]
)
if (!lockResult.rows[0].locked) {
this.logger.warn(
{ module: 'HasuraBackgroundClient' },
'Asset backfill already in progress on another connection, skipping'
)
return []
}
try {
await client.query(`
UPDATE "Asset" a
SET fingerprint = ma.fingerprint
FROM multi_asset ma
WHERE a."assetId" = CAST(CONCAT(ma.policy, RIGHT(CONCAT(E'\\\\', ma.name), -3)) AS BYTEA)
AND a.fingerprint IS NULL
`)
const maxResult = await client.query<{ maxId: string }>(
'SELECT COALESCE(MAX(id), 0) AS "maxId" FROM multi_asset'
)
const maxId = Number(maxResult.rows[0].maxId)
const insertedAssetIds: string[] = []
for (let cur = 0; cur < maxId; cur += batchSize) {
const result = await client.query(`
INSERT INTO "Asset" ("assetId", "assetName", "policyId", "fingerprint", "firstAppearedInSlot")
SELECT
CAST(CONCAT(ma.policy, RIGHT(CONCAT(E'\\\\', ma.name), -3)) AS BYTEA),
ma.name,
ma.policy,
ma.fingerprint,
MIN(b.slot_no)
FROM multi_asset ma
JOIN ma_tx_mint mtm ON mtm.ident = ma.id
JOIN tx ON tx.id = mtm.tx_id
JOIN block b ON b.id = tx.block_id
LEFT JOIN "Asset" a
ON a."assetId" = CAST(CONCAT(ma.policy, RIGHT(CONCAT(E'\\\\', ma.name), -3)) AS BYTEA)
WHERE a."assetId" IS NULL
AND ma.id > $1
AND ma.id <= $2
GROUP BY ma.id, ma.policy, ma.name, ma.fingerprint
ON CONFLICT ("assetId") DO NOTHING
RETURNING encode("assetId", 'hex') AS "assetId"
`, [cur, cur + batchSize])
if (result.rowCount > 0) {
for (const row of result.rows as { assetId: string }[]) {
insertedAssetIds.push(row.assetId)
}
this.logger.info(
{ module: 'HasuraBackgroundClient', upToId: cur + batchSize, inserted: result.rowCount, total: insertedAssetIds.length },
'Backfilled asset batch from multi_asset'
)
}
}
this.logger.info(
{ module: 'HasuraBackgroundClient', inserted: insertedAssetIds.length },
'Backfilled missing assets from multi_asset'
)
return insertedAssetIds
} finally {
await client.query('SELECT pg_advisory_unlock($1)', [ASSET_BACKFILL_ADVISORY_LOCK_KEY])
}
} finally {
await client.end()
}
}
}