-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathpostgres-store.ts
6469 lines (6188 loc) · 216 KB
/
postgres-store.ts
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as path from 'path';
import * as fs from 'fs';
import { EventEmitter } from 'events';
import { Readable, Writable } from 'stream';
import PgMigrate, { RunnerOption } from 'node-pg-migrate';
import {
Pool,
PoolClient,
ClientConfig,
Client,
ClientBase,
QueryResult,
QueryConfig,
PoolConfig,
} from 'pg';
import * as pgCopyStreams from 'pg-copy-streams';
import * as PgCursor from 'pg-cursor';
import {
parseArgBoolean,
parsePort,
APP_DIR,
isTestEnv,
isDevEnv,
bufferToHexPrefixString,
hexToBuffer,
stopwatch,
timeout,
logger,
logError,
FoundOrNot,
getOrAdd,
assertNotNullish,
batchIterate,
distinctBy,
unwrapOptional,
pipelineAsync,
isProdEnv,
has0xPrefix,
} from '../helpers';
import {
DataStore,
DbBlock,
DbTx,
DbStxEvent,
DbFtEvent,
DbNftEvent,
DbTxTypeId,
DbSmartContractEvent,
DbSmartContract,
DbEvent,
DbFaucetRequest,
DataStoreEventEmitter,
DbEventTypeId,
DataStoreBlockUpdateData,
DbFaucetRequestCurrency,
DbMempoolTx,
DbMempoolTxId,
DbSearchResult,
DbStxBalance,
DbStxLockEvent,
DbFtBalance,
DbMinerReward,
DbBurnchainReward,
DbInboundStxTransfer,
DbTxStatus,
AddressNftEventIdentifier,
DbRewardSlotHolder,
DbBnsName,
DbBnsNamespace,
DbBnsZoneFile,
DbBnsSubdomain,
DbConfigState,
DbTokenOfferingLocked,
DbTxWithAssetTransfers,
DataStoreMicroblockUpdateData,
DbMicroblock,
DbTxAnchorMode,
DbGetBlockWithMetadataOpts,
DbGetBlockWithMetadataResponse,
DbMicroblockPartial,
DataStoreTxEventData,
DbRawEventRequest,
BlockIdentifier,
StxUnlockEvent,
DbNonFungibleTokenMetadata,
DbFungibleTokenMetadata,
DbTokenMetadataQueueEntry,
} from './common';
import {
AddressTokenOfferingLocked,
TransactionType,
AddressUnlockSchedule,
} from '@stacks/stacks-blockchain-api-types';
import { getTxTypeId } from '../api/controllers/db-controller';
import { isProcessableTokenMetadata } from '../event-stream/tokens-contract-handler';
import { ClarityAbi } from '@stacks/transactions';
import {
PgAddressNotificationPayload,
PgBlockNotificationPayload,
PgMicroblockNotificationPayload,
PgNameNotificationPayload,
PgNotifier,
PgTokenMetadataNotificationPayload,
PgTokensNotificationPayload,
PgTxNotificationPayload,
} from './postgres-notifier';
const MIGRATIONS_TABLE = 'pgmigrations';
const MIGRATIONS_DIR = path.join(APP_DIR, 'migrations');
type PgClientConfig = ClientConfig & { schema?: string };
export function getPgClientConfig(): PgClientConfig {
const pgEnvVars = {
database: process.env['PG_DATABASE'],
user: process.env['PG_USER'],
password: process.env['PG_PASSWORD'],
host: process.env['PG_HOST'],
port: process.env['PG_PORT'],
ssl: process.env['PG_SSL'],
schema: process.env['PG_SCHEMA'],
};
const pgConnectionUri = process.env['PG_CONNECTION_URI'];
const pgConfigEnvVar = Object.entries(pgEnvVars).find(([, v]) => typeof v === 'string')?.[0];
if (pgConfigEnvVar && pgConnectionUri) {
throw new Error(
`Both PG_CONNECTION_URI and ${pgConfigEnvVar} environmental variables are defined. PG_CONNECTION_URI must be defined without others or omitted.`
);
}
if (pgConnectionUri) {
const uri = new URL(pgConnectionUri);
const searchParams = Object.fromEntries(
[...uri.searchParams.entries()].map(([k, v]) => [k.toLowerCase(), v])
);
// Not really standardized
const schema: string | undefined =
searchParams['currentschema'] ??
searchParams['current_schema'] ??
searchParams['searchpath'] ??
searchParams['search_path'] ??
searchParams['schema'];
const config: PgClientConfig = {
connectionString: pgConnectionUri,
schema,
};
return config;
} else {
const config: PgClientConfig = {
database: pgEnvVars.database,
user: pgEnvVars.user,
password: pgEnvVars.password,
host: pgEnvVars.host,
port: parsePort(pgEnvVars.port),
ssl: parseArgBoolean(pgEnvVars.ssl),
schema: pgEnvVars.schema,
};
return config;
}
}
export async function runMigrations(
clientConfig: PgClientConfig = getPgClientConfig(),
direction: 'up' | 'down' = 'up',
opts?: {
// Bypass the NODE_ENV check when performing a "down" migration which irreversibly drops data.
dangerousAllowDataLoss?: boolean;
}
): Promise<void> {
if (!opts?.dangerousAllowDataLoss && direction !== 'up' && !isTestEnv && !isDevEnv) {
throw new Error(
'Whoa there! This is a testing function that will drop all data from PG. ' +
'Set NODE_ENV to "test" or "development" to enable migration testing.'
);
}
clientConfig = clientConfig ?? getPgClientConfig();
const client = new Client(clientConfig);
try {
await client.connect();
const runnerOpts: RunnerOption = {
dbClient: client,
ignorePattern: '.*map',
dir: MIGRATIONS_DIR,
direction: direction,
migrationsTable: MIGRATIONS_TABLE,
count: Infinity,
logger: {
info: msg => {},
warn: msg => logger.warn(msg),
error: msg => logger.error(msg),
},
};
if (clientConfig.schema) {
runnerOpts.schema = clientConfig.schema;
}
await PgMigrate(runnerOpts);
} catch (error) {
logError(`Error running pg-migrate`, error);
throw error;
} finally {
await client.end();
}
}
export async function cycleMigrations(opts?: {
// Bypass the NODE_ENV check when performing a "down" migration which irreversibly drops data.
dangerousAllowDataLoss?: boolean;
}): Promise<void> {
const clientConfig = getPgClientConfig();
await runMigrations(clientConfig, 'down', opts);
await runMigrations(clientConfig, 'up', opts);
}
export async function dangerousDropAllTables(opts?: {
acknowledgePotentialCatastrophicConsequences?: 'yes';
}) {
if (opts?.acknowledgePotentialCatastrophicConsequences !== 'yes') {
throw new Error('Dangerous usage error.');
}
const clientConfig = getPgClientConfig();
const client = new Client(clientConfig);
try {
await client.connect();
await client.query('BEGIN');
const getTablesQuery = await client.query<{ table_name: string }>(
`
SELECT table_name
FROM information_schema.tables
WHERE table_schema = $1
AND table_catalog = $2
AND table_type = 'BASE TABLE'
`,
[clientConfig.schema, clientConfig.database]
);
const tables = getTablesQuery.rows.map(r => r.table_name);
for (const table of tables) {
await client.query(`DROP TABLE IF EXISTS ${table} CASCADE`);
}
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
await client.end();
}
}
const TX_COLUMNS = `
-- required columns
tx_id, raw_tx, tx_index, index_block_hash, parent_index_block_hash, block_hash, parent_block_hash, block_height, burn_block_time, parent_burn_block_time,
type_id, anchor_mode, status, canonical, post_conditions, nonce, fee_rate, sponsored, sponsor_address, sender_address, origin_hash_mode,
microblock_canonical, microblock_sequence, microblock_hash,
-- token-transfer tx columns
token_transfer_recipient_address, token_transfer_amount, token_transfer_memo,
-- smart-contract tx columns
smart_contract_contract_id, smart_contract_source_code,
-- contract-call tx columns
contract_call_contract_id, contract_call_function_name, contract_call_function_args,
-- poison-microblock tx columns
poison_microblock_header_1, poison_microblock_header_2,
-- coinbase tx columns
coinbase_payload,
-- tx result
raw_result,
-- event count
event_count,
-- execution cost
execution_cost_read_count, execution_cost_read_length, execution_cost_runtime, execution_cost_write_count, execution_cost_write_length
`;
const MEMPOOL_TX_COLUMNS = `
-- required columns
pruned, tx_id, raw_tx, type_id, anchor_mode, status, receipt_time,
post_conditions, nonce, fee_rate, sponsored, sponsor_address, sender_address, origin_hash_mode,
-- token-transfer tx columns
token_transfer_recipient_address, token_transfer_amount, token_transfer_memo,
-- smart-contract tx columns
smart_contract_contract_id, smart_contract_source_code,
-- contract-call tx columns
contract_call_contract_id, contract_call_function_name, contract_call_function_args,
-- poison-microblock tx columns
poison_microblock_header_1, poison_microblock_header_2,
-- coinbase tx columns
coinbase_payload
`;
const MEMPOOL_TX_ID_COLUMNS = `
-- required columns
tx_id
`;
const BLOCK_COLUMNS = `
block_hash, index_block_hash,
parent_index_block_hash, parent_block_hash, parent_microblock_hash, parent_microblock_sequence,
block_height, burn_block_time, burn_block_hash, burn_block_height, miner_txid, canonical,
execution_cost_read_count, execution_cost_read_length, execution_cost_runtime,
execution_cost_write_count, execution_cost_write_length
`;
const MICROBLOCK_COLUMNS = `
canonical, microblock_canonical, microblock_hash, microblock_sequence, microblock_parent_hash,
parent_index_block_hash, block_height, parent_block_height, parent_block_hash,
parent_burn_block_height, parent_burn_block_time, parent_burn_block_hash,
index_block_hash, block_hash
`;
interface BlockQueryResult {
block_hash: Buffer;
index_block_hash: Buffer;
parent_index_block_hash: Buffer;
parent_block_hash: Buffer;
parent_microblock_hash: Buffer;
parent_microblock_sequence: number;
block_height: number;
burn_block_time: number;
burn_block_hash: Buffer;
burn_block_height: number;
miner_txid: Buffer;
canonical: boolean;
execution_cost_read_count: string;
execution_cost_read_length: string;
execution_cost_runtime: string;
execution_cost_write_count: string;
execution_cost_write_length: string;
}
interface MicroblockQueryResult {
canonical: boolean;
microblock_canonical: boolean;
microblock_hash: Buffer;
microblock_sequence: number;
microblock_parent_hash: Buffer;
parent_index_block_hash: Buffer;
block_height: number;
parent_block_height: number;
parent_block_hash: Buffer;
index_block_hash: Buffer;
block_hash: Buffer;
parent_burn_block_height: number;
parent_burn_block_hash: Buffer;
parent_burn_block_time: number;
}
interface MempoolTxQueryResult {
pruned: boolean;
tx_id: Buffer;
nonce: number;
type_id: number;
anchor_mode: number;
status: number;
receipt_time: number;
canonical: boolean;
post_conditions: Buffer;
fee_rate: string;
sponsored: boolean;
sponsor_address: string | null;
sender_address: string;
origin_hash_mode: number;
raw_tx: Buffer;
// `token_transfer` tx types
token_transfer_recipient_address?: string;
token_transfer_amount?: string;
token_transfer_memo?: Buffer;
// `smart_contract` tx types
smart_contract_contract_id?: string;
smart_contract_source_code?: string;
// `contract_call` tx types
contract_call_contract_id?: string;
contract_call_function_name?: string;
contract_call_function_args?: Buffer;
// `poison_microblock` tx types
poison_microblock_header_1?: Buffer;
poison_microblock_header_2?: Buffer;
// `coinbase` tx types
coinbase_payload?: Buffer;
}
interface TxQueryResult {
tx_id: Buffer;
tx_index: number;
index_block_hash: Buffer;
parent_index_block_hash: Buffer;
block_hash: Buffer;
parent_block_hash: Buffer;
block_height: number;
burn_block_time: number;
parent_burn_block_time: number;
nonce: number;
type_id: number;
anchor_mode: number;
status: number;
raw_result: Buffer;
canonical: boolean;
microblock_canonical: boolean;
microblock_sequence: number;
microblock_hash: Buffer;
post_conditions: Buffer;
fee_rate: string;
sponsored: boolean;
sponsor_address: string | null;
sender_address: string;
origin_hash_mode: number;
raw_tx: Buffer;
// `token_transfer` tx types
token_transfer_recipient_address?: string;
token_transfer_amount?: string;
token_transfer_memo?: Buffer;
// `smart_contract` tx types
smart_contract_contract_id?: string;
smart_contract_source_code?: string;
// `contract_call` tx types
contract_call_contract_id?: string;
contract_call_function_name?: string;
contract_call_function_args?: Buffer;
// `poison_microblock` tx types
poison_microblock_header_1?: Buffer;
poison_microblock_header_2?: Buffer;
// `coinbase` tx types
coinbase_payload?: Buffer;
// events count
event_count: number;
execution_cost_read_count: string;
execution_cost_read_length: string;
execution_cost_runtime: string;
execution_cost_write_count: string;
execution_cost_write_length: string;
}
interface MempoolTxIdQueryResult {
tx_id: Buffer;
}
interface FaucetRequestQueryResult {
currency: string;
ip: string;
address: string;
occurred_at: string;
}
interface UpdatedEntities {
markedCanonical: {
blocks: number;
microblocks: number;
minerRewards: number;
txs: number;
stxLockEvents: number;
stxEvents: number;
ftEvents: number;
nftEvents: number;
contractLogs: number;
smartContracts: number;
names: number;
namespaces: number;
subdomains: number;
};
markedNonCanonical: {
blocks: number;
microblocks: number;
minerRewards: number;
txs: number;
stxLockEvents: number;
stxEvents: number;
ftEvents: number;
nftEvents: number;
contractLogs: number;
smartContracts: number;
names: number;
namespaces: number;
subdomains: number;
};
}
interface TransferQueryResult {
sender: string;
memo: Buffer;
block_height: number;
tx_index: number;
tx_id: Buffer;
transfer_type: string;
amount: string;
}
interface NonFungibleTokenMetadataQueryResult {
token_uri: string;
name: string;
description: string;
image_uri: string;
image_canonical_uri: string;
contract_id: string;
tx_id: Buffer;
sender_address: string;
}
interface FungibleTokenMetadataQueryResult {
token_uri: string;
name: string;
description: string;
image_uri: string;
image_canonical_uri: string;
contract_id: string;
symbol: string;
decimals: number;
tx_id: Buffer;
sender_address: string;
}
interface DbTokenMetadataQueueEntryQuery {
queue_id: number;
tx_id: Buffer;
contract_id: string;
contract_abi: string;
block_height: number;
processed: boolean;
}
export interface RawTxQueryResult {
raw_tx: Buffer;
}
class MicroblockGapError extends Error {
constructor(message: string) {
super(message);
this.message = message;
this.name = this.constructor.name;
}
}
// Enable this when debugging potential sql leaks.
const SQL_QUERY_LEAK_DETECTION = false;
// Tables containing tx metadata, like events (stx, ft, nft transfers), contract logs, bns data, etc.
const TX_METADATA_TABLES = [
'stx_events',
'ft_events',
'nft_events',
'contract_logs',
'stx_lock_events',
'smart_contracts',
'names',
'namespaces',
'subdomains',
] as const;
function getSqlQueryString(query: QueryConfig | string): string {
if (typeof query === 'string') {
return query;
} else {
return query.text;
}
}
export class PgDataStore
extends (EventEmitter as { new (): DataStoreEventEmitter })
implements DataStore {
readonly pool: Pool;
readonly notifier?: PgNotifier;
private constructor(pool: Pool, notifier: PgNotifier | undefined = undefined) {
// eslint-disable-next-line constructor-super
super();
this.pool = pool;
this.notifier = notifier;
}
/**
* Connects to the `PgNotifier`. Its messages will be forwarded to the rest of the API components
* though the EventEmitter.
*/
async connectPgNotifier() {
await this.notifier?.connect(notification => {
switch (notification.type) {
case 'blockUpdate':
const block = notification.payload as PgBlockNotificationPayload;
this.emit(
'blockUpdate',
block.blockHash,
block.microblocksAccepted,
block.microblocksStreamed
);
break;
case 'microblockUpdate':
const microblock = notification.payload as PgMicroblockNotificationPayload;
this.emit('microblockUpdate', microblock.microblockHash);
break;
case 'txUpdate':
const tx = notification.payload as PgTxNotificationPayload;
this.emit('txUpdate', tx.txId);
break;
case 'addressUpdate':
const address = notification.payload as PgAddressNotificationPayload;
this.emit('addressUpdate', address.address, address.blockHeight);
break;
case 'tokensUpdate':
const tokens = notification.payload as PgTokensNotificationPayload;
this.emit('tokensUpdate', tokens.contractID);
break;
case 'nameUpdate':
const name = notification.payload as PgNameNotificationPayload;
this.emit('nameUpdate', name.nameInfo);
break;
case 'tokenMetadataUpdateQueued':
const metadata = notification.payload as PgTokenMetadataNotificationPayload;
this.emit('tokenMetadataUpdateQueued', metadata.entry);
break;
}
});
}
/**
* Creates a postgres pool client connection. If the connection fails due to a transient error, it is retried until successful.
* You'd expect that the pg lib to handle this, but it doesn't, see https://github.com/brianc/node-postgres/issues/1789
*/
async connectWithRetry(): Promise<PoolClient> {
for (let retryAttempts = 1; ; retryAttempts++) {
try {
const client = await this.pool.connect();
return client;
} catch (error: any) {
// Check for transient errors, and retry after 1 second
if (error.code === 'ECONNREFUSED') {
logger.warn(`Postgres connection ECONNREFUSED, will retry, attempt #${retryAttempts}`);
await timeout(1000);
} else if (error.code === 'ETIMEDOUT') {
logger.warn(`Postgres connection ETIMEDOUT, will retry, attempt #${retryAttempts}`);
await timeout(1000);
} else if (error.message === 'the database system is starting up') {
logger.warn(
`Postgres connection failed while database system is restarting, will retry, attempt #${retryAttempts}`
);
await timeout(1000);
} else if (error.message === 'Connection terminated unexpectedly') {
logger.warn(
`Postgres connection terminated unexpectedly, will retry, attempt #${retryAttempts}`
);
await timeout(1000);
} else {
throw error;
}
}
}
}
/**
* Execute queries against the connection pool.
*/
async query<T>(cb: (client: ClientBase) => Promise<T>): Promise<T> {
const client = await this.connectWithRetry();
try {
if (SQL_QUERY_LEAK_DETECTION) {
// Monkey patch in some query leak detection. Taken from the lib's docs:
// https://node-postgres.com/guides/project-structure
// eslint-disable-next-line @typescript-eslint/unbound-method
const query = client.query;
// eslint-disable-next-line @typescript-eslint/unbound-method
const release = client.release;
const lastQueries: any[] = [];
const timeout = setTimeout(() => {
const queries = lastQueries.map(q => getSqlQueryString(q));
logger.error(`Pg client has been checked out for more than 5 seconds`);
logger.error(`Last query: ${queries.join('|')}`);
}, 5000);
// @ts-expect-error hacky typing
client.query = (...args) => {
lastQueries.push(args[0]);
// @ts-expect-error hacky typing
return query.apply(client, args);
};
client.release = () => {
clearTimeout(timeout);
client.query = query;
client.release = release;
return release.apply(client);
};
}
const result = await cb(client);
return result;
} finally {
client.release();
}
}
/**
* Execute queries within a sql transaction.
*/
async queryTx<T>(cb: (client: ClientBase) => Promise<T>): Promise<T> {
return await this.query(async client => {
try {
await client.query('BEGIN');
const result = await cb(client);
await client.query('COMMIT');
return result;
} catch (error) {
await client.query('ROLLBACK');
throw error;
}
});
}
async storeRawEventRequest(eventPath: string, payload: string): Promise<void> {
await this.query(async client => {
const insertResult = await client.query<{ id: string }>(
`
INSERT INTO event_observer_requests(
event_path, payload
) values($1, $2)
RETURNING id
`,
[eventPath, payload]
);
if (insertResult.rowCount !== 1) {
throw new Error(
`Unexpected row count ${insertResult.rowCount} when storing event_observer_requests entry`
);
}
const exportEventsFile = process.env['STACKS_EXPORT_EVENTS_FILE'];
if (exportEventsFile) {
const writeStream = fs.createWriteStream(exportEventsFile, {
flags: 'a', // append or create if not exists
});
try {
const queryStream = client.query(
pgCopyStreams.to(
`COPY (SELECT * FROM event_observer_requests WHERE id = ${insertResult.rows[0].id}) TO STDOUT ENCODING 'UTF8'`
)
);
await pipelineAsync(queryStream, writeStream);
} finally {
writeStream.close();
}
}
});
}
static async exportRawEventRequests(targetStream: Writable): Promise<void> {
const pg = await this.connect(true);
try {
await pg.query(async client => {
const copyQuery = pgCopyStreams.to(
`
COPY (SELECT id, receive_timestamp, event_path, payload FROM event_observer_requests ORDER BY id ASC)
TO STDOUT ENCODING 'UTF8'
`
);
const queryStream = client.query(copyQuery);
await pipelineAsync(queryStream, targetStream);
});
} finally {
await pg.close();
}
}
static async *getRawEventRequests(
readStream: Readable,
onStatusUpdate?: (msg: string) => void
): AsyncGenerator<DbRawEventRequest[], void, unknown> {
// 1. Pipe input stream into a temp table
// 2. Use `pg-cursor` to async read rows from temp table (order by `id` ASC)
// 3. Drop temp table
// 4. Close db connection
const pg = await this.connect(true);
try {
const client = await pg.pool.connect();
try {
await client.query('BEGIN');
await client.query(
`
CREATE TEMPORARY TABLE temp_event_observer_requests(
id bigint PRIMARY KEY,
receive_timestamp timestamptz NOT NULL,
event_path text NOT NULL,
payload jsonb NOT NULL
) ON COMMIT DROP
`
);
onStatusUpdate?.('Importing raw event requests into temporary table...');
const importStream = client.query(
pgCopyStreams.from(`COPY temp_event_observer_requests FROM STDIN`)
);
await pipelineAsync(readStream, importStream);
const totalRowCountQuery = await client.query<{ count: string }>(
`SELECT COUNT(id) count FROM temp_event_observer_requests`
);
const totalRowCount = parseInt(totalRowCountQuery.rows[0].count);
let lastStatusUpdatePercent = 0;
onStatusUpdate?.('Streaming raw event requests from temporary table...');
const cursor = new PgCursor<{ id: string; event_path: string; payload: string }>(
`
SELECT id, event_path, payload::text
FROM temp_event_observer_requests
ORDER BY id ASC
`
);
const cursorQuery = client.query(cursor);
const rowBatchSize = 100;
let rowsReadCount = 0;
let rows: DbRawEventRequest[] = [];
do {
rows = await new Promise<DbRawEventRequest[]>((resolve, reject) => {
cursorQuery.read(rowBatchSize, (error, rows) => {
if (error) {
reject(error);
} else {
rowsReadCount += rows.length;
if ((rowsReadCount / totalRowCount) * 100 > lastStatusUpdatePercent + 1) {
lastStatusUpdatePercent = Math.floor((rowsReadCount / totalRowCount) * 100);
onStatusUpdate?.(
`Raw event requests processed: ${lastStatusUpdatePercent}% (${rowsReadCount} / ${totalRowCount})`
);
}
resolve(rows);
}
});
});
if (rows.length > 0) {
yield rows;
}
} while (rows.length > 0);
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
} finally {
await pg.close();
}
}
static async containsAnyRawEventRequests(): Promise<boolean> {
const pg = await this.connect(true);
try {
return await pg.query(async client => {
try {
const result = await client.query('SELECT id from event_observer_requests LIMIT 1');
return result.rowCount > 0;
} catch (error: any) {
if (error.message?.includes('does not exist')) {
return false;
}
throw error;
}
});
} finally {
await pg.close();
}
}
async getChainTip(
client: ClientBase,
checkMissingChainTip?: boolean
): Promise<{ blockHeight: number; blockHash: string; indexBlockHash: string }> {
const currentTipBlock = await client.query<{
block_height: number;
block_hash: Buffer;
index_block_hash: Buffer;
}>(
`
SELECT block_height, block_hash, index_block_hash
FROM blocks
WHERE canonical = true AND block_height = (SELECT MAX(block_height) FROM blocks)
`
);
if (checkMissingChainTip && currentTipBlock.rowCount === 0) {
throw new Error(`No canonical block exists. The node is likely still syncing.`);
}
const height = currentTipBlock.rows[0]?.block_height ?? 0;
return {
blockHeight: height,
blockHash: bufferToHexPrefixString(currentTipBlock.rows[0]?.block_hash ?? Buffer.from([])),
indexBlockHash: bufferToHexPrefixString(
currentTipBlock.rows[0]?.index_block_hash ?? Buffer.from([])
),
};
}
async updateMicroblocks(data: DataStoreMicroblockUpdateData): Promise<void> {
try {
await this.updateMicroblocksInternal(data);
} catch (error) {
if (error instanceof MicroblockGapError) {
// Log and ignore this error for now, see https://github.com/blockstack/stacks-blockchain/issues/2850
// for more details.
// In theory it would be possible for the API to cache out-of-order microblock data and use it to
// restore data in this condition, but it would require several changes to sensitive re-org code,
// as well as introduce a new kind of statefulness and responsibility to the API.
logger.warn(error.message);
} else {
throw error;
}
}
}
async updateMicroblocksInternal(data: DataStoreMicroblockUpdateData): Promise<void> {
await this.queryTx(async client => {
// Sanity check: ensure incoming microblocks have a `parent_index_block_hash` that matches the API's
// current known canonical chain tip. We assume this holds true so incoming microblock data is always
// treated as being built off the current canonical anchor block.
const chainTip = await this.getChainTip(client);
const nonCanonicalMicroblock = data.microblocks.find(
mb => mb.parent_index_block_hash !== chainTip.indexBlockHash
);
// Note: the stacks-node event emitter can send old microblocks that have already been processed by a previous anchor block.
// Log warning and return, nothing to do.
if (nonCanonicalMicroblock) {
logger.info(
`Failure in microblock ingestion, microblock ${nonCanonicalMicroblock.microblock_hash} ` +
`points to parent index block hash ${nonCanonicalMicroblock.parent_index_block_hash} rather ` +
`than the current canonical tip's index block hash ${chainTip.indexBlockHash}.`
);
return;
}
// The block height is just one after the current chain tip height
const blockHeight = chainTip.blockHeight + 1;
const dbMicroblocks = data.microblocks.map(mb => {
const dbMicroBlock: DbMicroblock = {
canonical: true,
microblock_canonical: true,
microblock_hash: mb.microblock_hash,
microblock_sequence: mb.microblock_sequence,
microblock_parent_hash: mb.microblock_parent_hash,
parent_index_block_hash: mb.parent_index_block_hash,
parent_burn_block_height: mb.parent_burn_block_height,
parent_burn_block_hash: mb.parent_burn_block_hash,
parent_burn_block_time: mb.parent_burn_block_time,
block_height: blockHeight,
parent_block_height: chainTip.blockHeight,
parent_block_hash: chainTip.blockHash,
index_block_hash: '', // Empty until microblock is confirmed in an anchor block
block_hash: '', // Empty until microblock is confirmed in an anchor block
};
return dbMicroBlock;
});
const txs: DataStoreTxEventData[] = [];
for (const entry of data.txs) {
// Note: the properties block_hash and burn_block_time are empty here because the anchor block with that data doesn't yet exist.
const dbTx: DbTx = {
...entry.tx,
parent_block_hash: chainTip.blockHash,
block_height: blockHeight,
};
// Set all the `block_height` properties for the related tx objects, since it wasn't known
// when creating the objects using only the stacks-node message payload.
txs.push({
tx: dbTx,
stxEvents: entry.stxEvents.map(e => ({ ...e, block_height: blockHeight })),
contractLogEvents: entry.contractLogEvents.map(e => ({
...e,
block_height: blockHeight,
})),
stxLockEvents: entry.stxLockEvents.map(e => ({ ...e, block_height: blockHeight })),
ftEvents: entry.ftEvents.map(e => ({ ...e, block_height: blockHeight })),
nftEvents: entry.nftEvents.map(e => ({ ...e, block_height: blockHeight })),
smartContracts: entry.smartContracts.map(e => ({ ...e, block_height: blockHeight })),
names: entry.names.map(e => ({ ...e, registered_at: blockHeight })),
namespaces: entry.namespaces.map(e => ({ ...e, ready_block: blockHeight })),
});
}
await this.insertMicroblockData(client, dbMicroblocks, txs);
dbMicroblocks.forEach(microblock =>
this.notifier?.sendMicroblock({ microblockHash: microblock.microblock_hash })
);
// Find any microblocks that have been orphaned by this latest microblock chain tip.
// This function also checks that each microblock parent hash points to an existing microblock in the db.
const currentMicroblockTip = dbMicroblocks[dbMicroblocks.length - 1];
const unanchoredMicroblocksAtTip = await this.findUnanchoredMicroblocksAtChainTip(
client,