Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SHARD-1104 - Postgres DB support #17

Open
wants to merge 71 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
71 commits
Select commit Hold shift + click to select a range
e979002
added the pg package
yaseen-oakrev Jul 23, 2024
995904f
added PG-related env variables to config
yaseen-oakrev Jul 23, 2024
9323b59
created pgStorage file for abstracting PG db operations
yaseen-oakrev Jul 23, 2024
7fcac00
pg package update restricted
yaseen-oakrev Jul 23, 2024
b95bdea
pg db usage is disabled by default
yaseen-oakrev Jul 23, 2024
42ac829
corrected DB config options for PG
yaseen-oakrev Jul 23, 2024
be08d9e
changed to follow js convention
yaseen-oakrev Jul 23, 2024
a98a952
modified db initialisation for PG
yaseen-oakrev Jul 23, 2024
49ed72c
changes for different query types
yaseen-oakrev Jul 24, 2024
8990155
changes for different query types
yaseen-oakrev Jul 24, 2024
f203a42
changed db.run for account, accountEntry, accountHistoryState, block,…
shobhitic Jul 25, 2024
b577d57
converted db.run for originalTxData and receipt
shobhitic Jul 25, 2024
2e90b01
changed db.run to use pg
yaseen-oakrev Jul 25, 2024
03ebd52
letting pg automatically determine presence of conflict from the prei…
yaseen-oakrev Jul 25, 2024
2be9d1e
db.get modifications for account.ts
yaseen-oakrev Jul 25, 2024
813b5be
db.get method changes
yaseen-oakrev Jul 26, 2024
3c81cf0
db.all pg-specific changes
yaseen-oakrev Jul 29, 2024
12c82af
using the default db for any db namespace
yaseen-oakrev Jul 29, 2024
e38a826
added key to check if sqlite db is to be used
yaseen-oakrev Jul 29, 2024
6338ce9
reverted sqlite check change
yaseen-oakrev Jul 29, 2024
cae8ffd
changes for the queries that were missed
yaseen-oakrev Jul 29, 2024
984b7f7
mentioned the columns used as the primary key in conflict resolution
yaseen-oakrev Jul 29, 2024
d3f631c
converting postgres' bigint to js number using the pg library
yaseen-oakrev Jul 29, 2024
0f33ddf
getting json data as string from pg to maintain parity with sqlite
yaseen-oakrev Jul 29, 2024
265e93a
creating case-sensitive column names
yaseen-oakrev Jul 29, 2024
722d6e2
using qoutes for postgresql case sensitive column names
shobhitic Jul 29, 2024
706ab6b
using Number as the typeParser for BigInt since sqlite returns Number…
yaseen-oakrev Jul 29, 2024
fafc935
added transformation for the transaction model for analytics
yaseen-oakrev Jul 30, 2024
224d298
fixed on conflict for analytics
shobhitic Jul 30, 2024
c402e71
added transform for cycle
shobhitic Jul 30, 2024
71be9c9
added support for version and added analyticsCycle table creation sql…
yaseen-oakrev Jul 30, 2024
fd8d489
added more columns to add double-quotes to
yaseen-oakrev Jul 30, 2024
effc172
set version in correct table
shobhitic Jul 30, 2024
508bd2c
changed table name
yaseen-oakrev Jul 30, 2024
5058b1c
added transformations for account and transaction table
shobhitic Jul 30, 2024
ca2882a
completed analyticsCycle insertion
shobhitic Jul 30, 2024
696d1ac
Merge remote-tracking branch 'origin/pg-collector' into pg-collector …
yaseen-oakrev Jul 31, 2024
6f5d42c
added 4 way primary key for analyticsCycle table
shobhitic Jul 31, 2024
e6e63fc
using new primary key for analyticsCycle
shobhitic Aug 1, 2024
f5de027
changed analyticsCycle to be simple
shobhitic Aug 5, 2024
fa7dcd2
made the changes for transform transaction
shobhitic Aug 6, 2024
ebfbb44
changing endCycle and startCycle to activeStartCycle and activeEndCycle
shobhitic Aug 7, 2024
0f3d470
fixed the transformation for edge cases
shobhitic Aug 8, 2024
8b848da
using metadata to sequentially processing analytics cycle
shobhitic Aug 8, 2024
bceb6c3
added more checks to analytics data
shobhitic Aug 8, 2024
bcbc43f
adding index on timestamp on the transactions table
yaseen-oakrev Aug 19, 2024
3be4751
Merge remote-tracking branch 'origin/pg-collector' into pg-collector
yaseen-oakrev Aug 19, 2024
d1476f5
using TIMESTAMPTZ for the timestamp column in the transactions table
yaseen-oakrev Aug 19, 2024
ac436f1
using TIMESTAMPTZ instead of bigint for timestamp for the accounts table
yaseen-oakrev Aug 19, 2024
c3c096b
changed updateAccount method to use timestamptz too
yaseen-oakrev Aug 19, 2024
2779531
timestamptz changes to analycticsCycle table corrections elsewhere
yaseen-oakrev Aug 20, 2024
6eecc04
Merge remote-tracking branch 'origin/dev' into pg-collector
yaseen-oakrev Sep 5, 2024
ed105dc
added new columns to fix casing
yaseen-oakrev Sep 5, 2024
e1b1de0
trying to fix github reviewer issue #1
shobhitic Sep 5, 2024
bc2f87a
trying to fix github reviewer issue #2
shobhitic Sep 5, 2024
b60069f
trying to fix github reviewer issue #3
shobhitic Sep 5, 2024
a630996
trying to fix github reviewer issue #4
shobhitic Sep 5, 2024
6f6bafb
trying to fix github reviewer issue #5
shobhitic Sep 5, 2024
0090f89
installed pg-format
shobhitic Sep 5, 2024
5f5d8b2
github reviewer fix #1
shobhitic Sep 5, 2024
38922e9
github reviewer fix #2
shobhitic Sep 5, 2024
606a5e8
github reviewer fix #3
shobhitic Sep 5, 2024
3b3b726
github reviewer fix #4
shobhitic Sep 5, 2024
63337f0
github reviewer fix #5
shobhitic Sep 5, 2024
a8987b7
github reviewer fix #6
shobhitic Sep 5, 2024
36ccd2d
testing whether numbers are fine for github reviewer
shobhitic Sep 5, 2024
2643275
abstracted away db methods through the dbStorage.ts
yaseen-oakrev Sep 6, 2024
434cdc2
default value for optional field
yaseen-oakrev Sep 6, 2024
73d3dd4
Merge remote-tracking branch 'origin/pg-collector' into pg-collector
yaseen-oakrev Sep 6, 2024
136e99e
Add nodeVersion to analyticsCycle table
tanuj-shardeum Sep 17, 2024
21d1921
fix analyticscycle insert query (#23)
tanuj-shardeum Sep 30, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.development
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
HOST='127.0.0.1'
PG_ENABLED=false
PG_DEFAULT_DB_CONNECTION_STRING='postgresql://localhost/default?user=postgres&password=password'
PG_SHARDEUM_INDEXER_CONNECTION_STRING='postgresql://localhost/shardeumIndexer?user=postgres&password=password'
COLLECTOR_MODE='MQ'
RMQ_HOST='127.0.0.1'
RMQ_USER='user'
Expand Down
133 changes: 133 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
"morgan": "1.9.1",
"node-cron": "3.0.2",
"nodemon": "^2.0.20",
"pg": "8.12.0",
"pg-format": "^1.0.4",

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"pg-format": "^1.0.4",
"pg-format": "1.0.4",

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please also commit necessary changes in package-lock.json

"point-of-view": "4.6.0",
"qs": "6.11.0",
"socket.io": "4.7.1",
Expand All @@ -76,6 +78,7 @@
"@typescript-eslint/eslint-plugin": "5.60.1",
"@typescript-eslint/parser": "5.60.1",
"@typescript-eslint/typescript-estree": "5.61.0",
"@types/pg-format": "^1.0.5",

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"@types/pg-format": "^1.0.5",
"@types/pg-format": "1.0.5",

"eslint": "8.44.0",
"eslint-config-prettier": "8.8.0",
"eslint-config-standard": "17.1.0",
Expand Down
2 changes: 1 addition & 1 deletion scripts/repair_account_state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ const saveAccount = async (account: AccountCopy): Promise<void> => {
config.processData.decodeContractInfo &&
accountType === AccountType.Account &&
'account' in accObj.account &&
bytesToHex(Uint8Array.from(Object.values(accObj.account.account.codeHash))) !== AccountDB.EOA_CodeHash
bytesToHex(Uint8Array.from(Object.values(accObj.account.account?.codeHash || []))) !== AccountDB.EOA_CodeHash
) {
const accountExist = await AccountDB.queryAccountByAccountId(accObj.accountId)
if (config.verbose) console.log('accountExist', accountExist)
Expand Down
6 changes: 3 additions & 3 deletions scripts/repair_missing_cycle_block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ dotenv.config()

import * as Crypto from '../src/utils/crypto'
import * as Storage from '../src/storage'
import * as db from '../src/storage/sqlite3storage'
import * as db from '../src/storage/dbStorage'
import * as CycleDB from '../src/storage/cycle'
import * as BlockDB from '../src/storage/block'
import { config, overrideDefaultConfig } from '../src/config'
Expand Down Expand Up @@ -65,7 +65,7 @@ async function checkCycleData(startCycleNumber = 0, latestCycleNumber: number):
const batchSize = 1000
const cycleBatches: number[][] = []
let end = startCycleNumber + batchSize
for (let start = startCycleNumber; start <= latestCycleNumber; ) {
for (let start = startCycleNumber; start <= latestCycleNumber;) {
if (end > latestCycleNumber) end = latestCycleNumber
cycleBatches.push(generateNumberArray(start, end))
start = end + 1
Expand Down Expand Up @@ -104,7 +104,7 @@ async function checkBlockData(startBlockNumber = 0, latestBlockNumber: number):
const batchSize = 1000
const blockBatches: number[][] = []
let end = startBlockNumber + batchSize
for (let start = startBlockNumber; start <= latestBlockNumber; ) {
for (let start = startBlockNumber; start <= latestBlockNumber;) {
if (end > latestBlockNumber) end = latestBlockNumber
blockBatches.push(generateNumberArray(start, end))
start = end + 1
Expand Down
22 changes: 10 additions & 12 deletions src/cache/LatestBlockCache.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { config } from '../config'
import { blockQueryDelayInMillis } from '../utils/block'
import * as db from '../storage/sqlite3storage'
import * as db from '../storage/dbStorage'
import { DbBlock } from '../types'
import { sleep } from '../utils'

Expand All @@ -10,38 +10,36 @@ let getLatestBlockFromDB_running = false

async function getLatestBlockFromDB(): Promise<DbBlock> {
const before = Date.now()

const delayInMillis = blockQueryDelayInMillis()
const sql = `SELECT * FROM (SELECT * FROM blocks ORDER BY number DESC LIMIT 100) AS subquery WHERE timestamp <= ${
Date.now() - delayInMillis
}`
const sql = `SELECT * FROM (SELECT *${config.postgresEnabled ? ', readableBlock::TEXT' : ''} FROM blocks ORDER BY number DESC LIMIT 100) AS subquery WHERE timestamp <= ${Date.now() - delayInMillis}`

//Shouldn't the highest block number always be the latest block?
//This query seems much faster for the same thing
// A: nope, some reason this only updates once only 10 cycles or so.. even if they come to us out
// A: nope, some reason this only updates once only 10 cycles or so.. even if they come to us out
// of order I would think the sort on primary key would still work... oh... it could be because
// earlier blocks are sent. I think maybe this also needs the timestamp check,
// or we get 10 and then sort through and find one that works
// or we get 10 and then sort through and find one that works

//const sql = `SELECT * FROM blocks ORDER BY number DESC LIMIT 1`

const block: DbBlock = await db.get(sql)

const elapsed = Date.now() - before
console.log('SLOW QUERY? getLatestBlockFromDB ', elapsed, 'ms' , block.number)
console.log('SLOW QUERY? getLatestBlockFromDB ', elapsed, 'ms', block.number)

return block
}

async function updateLatestBlockCacheIfNeeded(): Promise<void> {
const now = Date.now()
if (latestBlock === null || now - lastCacheUpdateTimestamp >= config.blockCache.cacheUpdateIntervalInMillis) {
try{
if(getLatestBlockFromDB_running === true) {
try {
if (getLatestBlockFromDB_running === true) {
while (getLatestBlockFromDB_running === true) {
await sleep(200)
}
console.log('SLOW QUERY? getLatestBlockFromDB skipped', latestBlock.number )
console.log('SLOW QUERY? getLatestBlockFromDB skipped', latestBlock.number)
return //other process updated latestBlock
}
getLatestBlockFromDB_running = true
Expand Down
12 changes: 10 additions & 2 deletions src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ export interface Config {
port: string
publicKey: string
}
postgresEnabled: boolean
sqliteEnabled: boolean
pgDefaultDBConnectionString: string
rpcUrl: string
apiUrl: string
verbose: boolean
Expand All @@ -59,6 +62,7 @@ export interface Config {
findTxHashInOriginalTx: boolean
enableShardeumIndexer: boolean
shardeumIndexerSqlitePath: string
pgShardeumIndexerDBConnectionString: string
blockIndexing: {
enabled: boolean
blockProductionRate: number
Expand Down Expand Up @@ -93,14 +97,17 @@ let config: Config = {
enableCollectorSocketServer: false,
port: {
collector: process.env.COLLECTOR_PORT || '4444',
server: process.env.PORT || '6101',
server: process.env.PORT || '6100',
log_server: process.env.LOG_SERVER_PORT || '4446',
},
distributorInfo: {
ip: process.env.DISTRIBUTOR_IP || '127.0.0.1',
port: process.env.DISTRIBUTOR_PORT || '6100',
publicKey: '',
},
postgresEnabled: process.env.PG_ENABLED === 'true',
sqliteEnabled: !(process.env.PG_ENABLED === 'true'),
pgDefaultDBConnectionString: process.env.PG_DEFAULT_DB_CONNECTION_STRING || 'postgresql://localhost/shardeum_default&user=root&password=password',
rpcUrl: 'http://127.0.0.1:8080',
apiUrl: '',
verbose: false,
Expand All @@ -117,8 +124,9 @@ let config: Config = {
},
enableTxHashCache: false,
findTxHashInOriginalTx: false,
enableShardeumIndexer: true,
enableShardeumIndexer: false,
shardeumIndexerSqlitePath: 'shardeum.sqlite',
pgShardeumIndexerDBConnectionString: process.env.PG_SHARDEUM_INDEXER_CONNECTION_STRING || 'postgresql://localhost/shardeum_indexer&user=root&password=password',
blockIndexing: {
enabled: true,
blockProductionRate: 6,
Expand Down
6 changes: 5 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ import { registerCache } from './cache/LatestBlockCache'
import { Utils as StringUtils } from '@shardus/types'
import { healthCheckRouter } from './routes/healthCheck'

import pgFormat from "pg-format"


if (config.env == envEnum.DEV) {
//default debug mode keys
// pragma: allowlist nextline secret
Expand Down Expand Up @@ -1403,7 +1406,8 @@ const start = async (): Promise<void> => {
filter.address = StringUtils.safeJsonParse(q.address)
}
if (typeof q.address === 'string') {
filter.address = [q.address]
const address = pgFormat('%s', q.address)
filter.address = [address]
}

if (isValidJson(q.topics) && Array.isArray(StringUtils.safeJsonParse(q.topics))) {
Expand Down
Loading
Loading