diff --git a/src/codegen.ts b/src/codegen.ts index 33b9ea1..65e7d68 100644 --- a/src/codegen.ts +++ b/src/codegen.ts @@ -45,7 +45,7 @@ export const getTypeInfo = ( if (type instanceof GraphQLScalarType) { switch (type.name) { case 'BigInt': - return { type: 'bigint', initialValue: 0 }; + return { type: 'bigint', initialValue: 0n }; case 'Boolean': return { type: 'boolean', initialValue: false }; case 'Text': @@ -107,6 +107,19 @@ export const getJSType = ( return { isNullable, isList, baseType }; }; +const isPersistedField = (field: GraphQLField) => { + if (getComputedDirective(field)) return false; + + const fieldType = + field.type instanceof GraphQLNonNull ? field.type.ofType : field.type; + + return !( + isListType(fieldType) && + fieldType.ofType instanceof GraphQLObjectType && + getDerivedFromDirective(field) + ); +}; + export const codegen = ( controller: GqlEntityController, config: OverridesConfig, @@ -121,10 +134,8 @@ export const codegen = ( controller.schemaObjects.forEach((type, i, arr) => { const modelName = type.name; - contents += `export class ${modelName} extends Model {\n`; - contents += ` static tableName = '${getTableName(modelName.toLowerCase())}';\n\n`; - const typeFields = controller.getTypeFields(type); + const persistedFields = typeFields.filter(isPersistedField); const idField = typeFields.find(field => field.name === 'id'); const idType = idField ? getJSType(idField, decimalTypes) : null; @@ -139,27 +150,23 @@ export const codegen = ( ); } + contents += `export class ${modelName} extends Model {\n`; + contents += ` static tableName = '${getTableName(modelName.toLowerCase())}';\n\n`; + contents += ` static fieldNames = [${persistedFields.map(field => `'${field.name}'`).join(', ')}];\n\n`; + contents += format === 'javascript' ? ` constructor(id, indexerName) {\n` : ` constructor(id: ${idType.baseType}, indexerName: string) {\n`; contents += ` super(${modelName}.tableName, indexerName);\n\n`; - typeFields.forEach(field => { - if (getComputedDirective(field)) return; - - const fieldType = - field.type instanceof GraphQLNonNull ? field.type.ofType : field.type; - if ( - isListType(fieldType) && - fieldType.ofType instanceof GraphQLObjectType && - getDerivedFromDirective(field) - ) { - return; - } - + persistedFields.forEach(field => { const rawInitialValue = getInitialValue(field.type, decimalTypes); const initialValue = - field.name === 'id' ? 'id' : JSON.stringify(rawInitialValue); + field.name === 'id' + ? 'id' + : typeof rawInitialValue === 'bigint' + ? `${rawInitialValue}n` + : JSON.stringify(rawInitialValue); contents += ` this.initialSet('${field.name}', ${initialValue});\n`; }); contents += ` }\n\n`; @@ -172,7 +179,7 @@ export const codegen = ( contents += ` if (!entity) return null;\n\n`; contents += ` const model = new ${modelName}(id, indexerName);\n`; contents += ` model.setExists();\n\n`; - contents += ` for (const key in entity) {\n`; + contents += ` for (const key of ${modelName}.fieldNames) {\n`; contents += ` const value = entity[key] !== null && typeof entity[key] === 'object'\n`; contents += ` ? JSON.stringify(entity[key])\n`; contents += ` : entity[key];\n`; @@ -181,38 +188,42 @@ export const codegen = ( contents += ` return model;\n`; contents += ` }\n\n`; - typeFields.forEach(field => { - if (getComputedDirective(field)) return; - - const fieldType = - field.type instanceof GraphQLNonNull ? field.type.ofType : field.type; - if ( - isListType(fieldType) && - fieldType.ofType instanceof GraphQLObjectType && - getDerivedFromDirective(field) - ) { - return; - } - + persistedFields.forEach(field => { const { isNullable, isList, baseType } = getJSType(field, decimalTypes); const typeAnnotation = isNullable ? `${baseType} | null` : baseType; + const isBigInt = baseType === 'bigint'; contents += format === 'javascript' ? ` get ${field.name}() {\n` : ` get ${field.name}(): ${typeAnnotation} {\n`; - contents += ` return ${ - isList - ? `JSON.parse(this.get('${field.name}'))` - : `this.get('${field.name}')` - };\n`; + if (isBigInt && isNullable) { + contents += ` const value = this.get('${field.name}');\n`; + contents += ` return value === null ? null : BigInt(value);\n`; + } else { + let getterExpression = `this.get('${field.name}')`; + if (isList) getterExpression = `JSON.parse(${getterExpression})`; + if (isBigInt) getterExpression = `BigInt(${getterExpression})`; + contents += ` return ${getterExpression};\n`; + } contents += ` }\n\n`; + const setterAnnotation = isBigInt + ? `bigint | number | string${isNullable ? ' | null' : ''}` + : typeAnnotation; + let setterExpression = 'value'; + if (isList) setterExpression = 'JSON.stringify(value)'; + if (isBigInt) { + setterExpression = isNullable + ? 'value === null ? null : BigInt(value)' + : 'BigInt(value)'; + } + contents += format === 'javascript' ? ` set ${field.name}(value) {\n` - : ` set ${field.name}(value: ${typeAnnotation}) {\n`; - contents += ` this.set('${field.name}', ${isList ? `JSON.stringify(value)` : 'value'});\n`; + : ` set ${field.name}(value: ${setterAnnotation}) {\n`; + contents += ` this.set('${field.name}', ${setterExpression});\n`; contents += ` }\n\n`; }); diff --git a/src/container.ts b/src/container.ts index 15043e7..fd6fe53 100644 --- a/src/container.ts +++ b/src/container.ts @@ -1,5 +1,6 @@ import { Knex } from 'knex'; import { GqlEntityController } from './graphql/controller'; +import { EntityBuffer } from './orm/entity-buffer'; import { BaseIndexer, BlockNotFoundError, @@ -35,6 +36,15 @@ const CHECK_LATEST_BLOCK_INTERVAL = 50; const DEFAULT_FETCH_INTERVAL = 2000; +/** Maximum time buffered writes are held before a flush is forced. */ +const FLUSH_INTERVAL = 60 * 1000; + +/** Maximum entity buffer size before a flush is forced. */ +const MAX_BUFFER_SIZE = 10000; + +/** Maximum delay between flush retries when backing off. */ +const MAX_FLUSH_RETRY_DELAY = 60 * 1000; + export class Container implements Instance { private indexerName: string; @@ -51,12 +61,14 @@ export class Container implements Instance { private activeTemplates: TemplateSource[] = []; private cpBlocksCache: number[] | null = []; private blockHashCache: { blockNumber: number; hash: string } | null = null; + private entityBuffer: EntityBuffer; private preloadStep: number = BLOCK_PRELOAD_START_RANGE; private preloadedBlocks: number[] = []; private preloadEndBlock = 0; private lastPurgeBlock: number | null = null; + private lastFlushAt = Date.now(); constructor( indexerName: string, @@ -70,6 +82,8 @@ export class Container implements Instance { opts?: CheckpointOptions ) { this.indexerName = indexerName; + this.entityBuffer = register.getEntityBuffer(indexerName); + this.entityBuffer.reset(); this.log = log.child({ component: 'container', indexer: indexerName }); this.knex = knex; this.store = store; @@ -126,7 +140,10 @@ export class Container implements Instance { return this.blockHashCache.hash; } - return this.store.getBlockHash(this.indexerName, blockNumber); + return ( + this.entityBuffer.getBlockHash(blockNumber) ?? + this.store.getBlockHash(this.indexerName, blockNumber) + ); } private addSource(source: ContractSourceConfig) { @@ -188,19 +205,15 @@ export class Container implements Instance { public async setBlockHash(blockNum: number, hash: string) { this.blockHashCache = { blockNumber: blockNum, hash }; - return this.store.setBlockHash(this.indexerName, blockNum, hash); + this.entityBuffer.setBlockHash(blockNum, hash); } public async setLastIndexedBlock(block: number) { - await this.store.setMetadata( - this.indexerName, - MetadataId.LastIndexedBlock, - block - ); + this.entityBuffer.setLastIndexedBlock(block); } public async insertCheckpoints(checkpoints: CheckpointRecord[]) { - await this.store.insertCheckpoints(this.indexerName, checkpoints); + this.entityBuffer.addCheckpoints(checkpoints); } /** @@ -351,12 +364,15 @@ export class Container implements Instance { try { register.setCurrentBlock(this.indexerName, BigInt(blockNumber)); + this.entityBuffer.beginBlock(); const initialSources = this.getCurrentSources(blockNumber); const parentHash = await this.getBlockHash(blockNumber - 1); const nextBlockNumber = await this.indexer .getProvider() .processBlock(blockNumber, parentHash); + this.entityBuffer.commitBlock(); + const sources = this.getCurrentSources(nextBlockNumber); if (initialSources.length !== sources.length) { @@ -364,24 +380,18 @@ export class Container implements Instance { } blockNumber = nextBlockNumber; - - if (this.config.state_retention_blocks) { - if (this.lastPurgeBlock === null) { - this.lastPurgeBlock = blockNumber; - } else if ( - blockNumber - this.lastPurgeBlock >= - this.config.state_retention_blocks - ) { - await this.purgeOldState(blockNumber); - this.lastPurgeBlock = blockNumber; - } - } } catch (err) { + this.entityBuffer.rollbackBlock(); + if (err instanceof BlockNotFoundError) { if (this.config.optimistic_indexing) { try { + this.entityBuffer.beginBlock(); await this.indexer.getProvider().processPool(blockNumber); + this.entityBuffer.commitBlock(); + await this.flushBuffer(blockNumber); } catch (err) { + this.entityBuffer.rollbackBlock(); this.log.error( { blockNumber: blockNumber, err }, 'error occurred during pool processing' @@ -409,7 +419,55 @@ export class Container implements Instance { } await sleep(this.config.fetch_interval || DEFAULT_FETCH_INTERVAL); + continue; } + + await this.maybeFlush(blockNumber); + } + } + + private async flushBuffer(currentBlock: number) { + let retryDelay = this.config.fetch_interval || DEFAULT_FETCH_INTERVAL; + while (true) { + try { + await this.entityBuffer.flush(); + this.lastFlushAt = Date.now(); + + break; + } catch (err) { + this.log.error( + { err, currentBlock, bufferSize: this.entityBuffer.size }, + 'flush failed, retrying' + ); + await sleep(retryDelay); + retryDelay = Math.min(retryDelay * 2, MAX_FLUSH_RETRY_DELAY); + } + } + + if (!this.config.state_retention_blocks) return; + + try { + if (this.lastPurgeBlock === null) { + this.lastPurgeBlock = currentBlock; + } else if ( + currentBlock - this.lastPurgeBlock >= + this.config.state_retention_blocks + ) { + await this.purgeOldState(currentBlock); + this.lastPurgeBlock = currentBlock; + } + } catch (err) { + this.log.error({ err }, 'purging old state failed'); + } + } + + private async maybeFlush(currentBlock: number) { + const atTip = currentBlock > this.preloadEndBlock; + const stale = Date.now() - this.lastFlushAt >= FLUSH_INTERVAL; + const full = this.entityBuffer.size >= MAX_BUFFER_SIZE; + + if (atTip || stale || full) { + await this.flushBuffer(currentBlock); } } @@ -438,6 +496,8 @@ export class Container implements Instance { private async handleReorg(blockNumber: number) { this.log.info({ blockNumber }, 'handling reorg'); + await this.flushBuffer(blockNumber); + let current = blockNumber - 1; let lastGoodBlock: null | number = null; while (lastGoodBlock === null) { @@ -464,7 +524,7 @@ export class Container implements Instance { } } - const entities = await this.entityController.schemaObjects; + const entities = this.entityController.schemaObjects; const tables = entities.map(entity => getTableName(entity.name.toLowerCase()) ); @@ -490,6 +550,7 @@ export class Container implements Instance { // TODO: when we have full transaction support, we should include this in the transaction await this.store.removeFutureData(this.indexerName, lastGoodBlock); + this.entityBuffer.reset(); this.cpBlocksCache = null; this.blockHashCache = null; @@ -499,6 +560,8 @@ export class Container implements Instance { } public async reset() { + this.entityBuffer.reset(); + await this.store.setMetadata( this.indexerName, MetadataId.LastIndexedBlock, diff --git a/src/orm/entity-buffer.ts b/src/orm/entity-buffer.ts new file mode 100644 index 0000000..95f05da --- /dev/null +++ b/src/orm/entity-buffer.ts @@ -0,0 +1,442 @@ +import { Knex } from 'knex'; +import { + CheckpointRecord, + Fields, + getCheckpointId, + MetadataId, + Table +} from '../stores/checkpoints'; +import { chunk } from '../utils/helpers'; + +type EntityValues = Record; + +type PendingVersion = { + lower: bigint; + upper: bigint | null; + values: EntityValues; +}; + +type BufferedEntity = { + tableName: string; + id: string; + databaseRowValues: EntityValues | null; + hasDatabaseRow: boolean; + closeDatabaseRowAt: bigint | null; + closedVersions: PendingVersion[]; + openVersion: PendingVersion | null; + deleted: boolean; +}; + +type JournalSnapshot = { + closeDatabaseRowAt: bigint | null; + openVersion: PendingVersion | null; + deleted: boolean; + closedVersionsLength: number; +}; + +type BlockHashRecord = { blockNumber: number; hash: string }; + +const MAX_INSERT_BINDINGS = 60000; +const MAX_INSERT_ROWS = 1000; + +function cloneVersion(version: PendingVersion): PendingVersion { + return { ...version, values: { ...version.values } }; +} + +function snapshotEntity(entity: BufferedEntity): JournalSnapshot { + return { + closeDatabaseRowAt: entity.closeDatabaseRowAt, + openVersion: entity.openVersion ? cloneVersion(entity.openVersion) : null, + deleted: entity.deleted, + closedVersionsLength: entity.closedVersions.length + }; +} + +type Journal = { + entities: Map; + checkpointCount: number; + blockHashCount: number; + lastIndexedBlock: number | null; +}; + +/** + * Write-behind buffer for entity writes of a single indexer. + * + * `Model` routes all reads and writes through this buffer, `Container` + * flushes it. A flush persists all pending version rows and bookkeeping + * (checkpoints, block hashes, last indexed block) in a single transaction, + * making indexing atomic per flush window and crash replay safe. + */ +export class EntityBuffer { + private readonly indexerName: string; + private readonly getKnex: () => Knex; + + private entities = new Map(); + private checkpoints: CheckpointRecord[] = []; + private blockHashes: BlockHashRecord[] = []; + private lastIndexedBlock: number | null = null; + + private journal: Journal | null = null; + + constructor({ + indexerName, + getKnex + }: { + indexerName: string; + getKnex: () => Knex; + }) { + this.indexerName = indexerName; + this.getKnex = getKnex; + } + + get size(): number { + let count = + this.entities.size + this.checkpoints.length + this.blockHashes.length; + for (const entity of this.entities.values()) { + count += entity.closedVersions.length; + } + + return count; + } + + async load({ + tableName, + id + }: { + tableName: string; + id: string; + }): Promise { + const key = this.getKey(tableName, id); + const entity = this.entities.get(key); + if (entity) { + if (entity.openVersion) return { ...entity.openVersion.values }; + if (entity.deleted) return null; + if (entity.databaseRowValues) return { ...entity.databaseRowValues }; + } + + const row = await this.getKnex() + .table(tableName) + .select('*') + .where('id', id) + .andWhere('_indexer', this.indexerName) + .andWhereRaw('upper_inf(block_range)') + .first(); + if (!row) return null; + + this.entities.set(key, { + tableName, + id, + databaseRowValues: { ...row }, + hasDatabaseRow: true, + closeDatabaseRowAt: null, + closedVersions: [], + openVersion: null, + deleted: false + }); + + return row; + } + + save({ + tableName, + id, + values, + block, + hasDatabaseRow + }: { + tableName: string; + id: string; + values: EntityValues; + block: bigint; + hasDatabaseRow: boolean; + }) { + const entity = this.touch(tableName, id, hasDatabaseRow); + + if (entity.openVersion && entity.openVersion.lower === block) { + entity.openVersion.values = { ...values }; + } else { + this.closeCurrent(entity, block); + entity.openVersion = { lower: block, upper: null, values: { ...values } }; + } + + entity.deleted = false; + } + + delete({ + tableName, + id, + block, + hasDatabaseRow + }: { + tableName: string; + id: string; + block: bigint; + hasDatabaseRow: boolean; + }) { + const entity = this.touch(tableName, id, hasDatabaseRow); + + this.closeCurrent(entity, block); + entity.deleted = true; + } + + private closeCurrent(entity: BufferedEntity, block: bigint) { + if (entity.openVersion) { + if (entity.openVersion.lower !== block) { + entity.closedVersions.push({ ...entity.openVersion, upper: block }); + } + + entity.openVersion = null; + } else if (entity.hasDatabaseRow && entity.closeDatabaseRowAt === null) { + entity.closeDatabaseRowAt = block; + } + } + + addCheckpoints(records: CheckpointRecord[]) { + this.checkpoints.push(...records); + } + + setBlockHash(blockNumber: number, hash: string) { + this.blockHashes.push({ blockNumber, hash }); + } + + getBlockHash(blockNumber: number): string | null { + for (let i = this.blockHashes.length - 1; i >= 0; i--) { + if (this.blockHashes[i].blockNumber === blockNumber) { + return this.blockHashes[i].hash; + } + } + + return null; + } + + setLastIndexedBlock(block: number) { + this.lastIndexedBlock = block; + } + + beginBlock() { + this.journal = { + entities: new Map(), + checkpointCount: this.checkpoints.length, + blockHashCount: this.blockHashes.length, + lastIndexedBlock: this.lastIndexedBlock + }; + } + + commitBlock() { + this.journal = null; + } + + rollbackBlock() { + if (!this.journal) return; + + for (const [key, snapshot] of this.journal.entities) { + if (snapshot === null) { + this.entities.delete(key); + continue; + } + + const entity = this.entities.get(key); + if (!entity) continue; + + entity.closeDatabaseRowAt = snapshot.closeDatabaseRowAt; + entity.openVersion = snapshot.openVersion; + entity.deleted = snapshot.deleted; + entity.closedVersions.length = snapshot.closedVersionsLength; + } + + this.checkpoints.length = this.journal.checkpointCount; + this.blockHashes.length = this.journal.blockHashCount; + this.lastIndexedBlock = this.journal.lastIndexedBlock; + + this.commitBlock(); + } + + prepareFlush(knex: Knex): Knex.QueryBuilder[] { + const statements: Knex.QueryBuilder[] = []; + + const closes = new Map< + string, + { tableName: string; closeAt: bigint; ids: string[] } + >(); + const insertsByTable = new Map(); + + for (const entity of this.entities.values()) { + if (entity.closeDatabaseRowAt !== null) { + const key = `${entity.tableName}\u0000${entity.closeDatabaseRowAt}`; + const group = closes.get(key) ?? { + tableName: entity.tableName, + closeAt: entity.closeDatabaseRowAt, + ids: [] + }; + group.ids.push(entity.id); + closes.set(key, group); + } + + const versions = [ + ...entity.closedVersions, + ...(entity.openVersion ? [entity.openVersion] : []) + ]; + if (versions.length > 0) { + const inserts = insertsByTable.get(entity.tableName) ?? []; + inserts.push(...versions); + insertsByTable.set(entity.tableName, inserts); + } + } + + for (const { tableName, closeAt, ids } of closes.values()) { + statements.push( + knex + .table(tableName) + .whereIn('id', ids) + .andWhere('_indexer', this.indexerName) + .andWhereRaw('upper_inf(block_range)') + .update({ + block_range: knex.raw('int8range(lower(block_range), ?)', [ + closeAt.toString() + ]) + }) + ); + } + + for (const [tableName, versions] of insertsByTable) { + const rows = versions.map(version => ({ + ...version.values, + _indexer: this.indexerName, + block_range: + version.upper === null + ? knex.raw('int8range(?, NULL)', [version.lower.toString()]) + : knex.raw('int8range(?, ?)', [ + version.lower.toString(), + version.upper.toString() + ]) + })); + + const columnCount = Object.keys(rows[0]).length + 1; + const chunkSize = Math.min( + MAX_INSERT_ROWS, + Math.floor(MAX_INSERT_BINDINGS / columnCount) + ); + for (const rowsChunk of chunk(rows, chunkSize)) { + statements.push(knex.table(tableName).insert(rowsChunk)); + } + } + + if (this.checkpoints.length > 0) { + for (const checkpointsChunk of chunk(this.checkpoints, MAX_INSERT_ROWS)) { + statements.push( + knex + .table(Table.Checkpoints) + .insert( + checkpointsChunk.map(checkpoint => ({ + [Fields.Checkpoints.Id]: getCheckpointId( + checkpoint.contractAddress, + checkpoint.blockNumber + ), + [Fields.Checkpoints.Indexer]: this.indexerName, + [Fields.Checkpoints.BlockNumber]: checkpoint.blockNumber, + [Fields.Checkpoints.ContractAddress]: checkpoint.contractAddress + })) + ) + .onConflict([Fields.Checkpoints.Id, Fields.Checkpoints.Indexer]) + .ignore() + ); + } + } + + if (this.blockHashes.length > 0) { + const latestHashes = new Map(); + for (const record of this.blockHashes) { + latestHashes.set(record.blockNumber, record.hash); + } + + statements.push( + knex + .table(Table.Blocks) + .insert( + [...latestHashes.entries()].map(([blockNumber, hash]) => ({ + [Fields.Blocks.Indexer]: this.indexerName, + [Fields.Blocks.Number]: blockNumber, + [Fields.Blocks.Hash]: hash + })) + ) + .onConflict([Fields.Blocks.Indexer, Fields.Blocks.Number]) + .merge() + ); + } + + if (this.lastIndexedBlock !== null) { + statements.push( + knex + .table(Table.Metadata) + .insert({ + [Fields.Metadata.Id]: MetadataId.LastIndexedBlock, + [Fields.Metadata.Indexer]: this.indexerName, + [Fields.Metadata.Value]: this.lastIndexedBlock + }) + .onConflict([Fields.Metadata.Id, Fields.Metadata.Indexer]) + .merge() + ); + } + + return statements; + } + + async flush() { + const knex = this.getKnex(); + const statements = this.prepareFlush(knex); + + if (statements.length === 0) { + this.reset(); + return; + } + + await knex.transaction(async trx => { + for (const statement of statements) { + await statement.transacting(trx); + } + }); + + this.reset(); + } + + reset() { + this.entities.clear(); + this.checkpoints = []; + this.blockHashes = []; + this.lastIndexedBlock = null; + this.commitBlock(); + } + + private getKey(tableName: string, id: string): string { + return `${tableName}\u0000${id}`; + } + + private touch( + tableName: string, + id: string, + hasDatabaseRow: boolean + ): BufferedEntity { + const key = this.getKey(tableName, id); + let entity = this.entities.get(key); + + if (this.journal && !this.journal.entities.has(key)) { + this.journal.entities.set(key, entity ? snapshotEntity(entity) : null); + } + + if (!entity) { + entity = { + tableName, + id, + databaseRowValues: null, + hasDatabaseRow, + closeDatabaseRowAt: null, + closedVersions: [], + openVersion: null, + deleted: false + }; + this.entities.set(key, entity); + } + + return entity; + } +} diff --git a/src/orm/model.ts b/src/orm/model.ts index e8932b2..bfa87a3 100644 --- a/src/orm/model.ts +++ b/src/orm/model.ts @@ -4,7 +4,6 @@ export default class Model { private tableName: string; private indexerName: string; private values = new Map(); - private valuesImplicitlySet = new Set(); private exists = false; constructor(tableName: string, indexerName: string) { @@ -12,75 +11,6 @@ export default class Model { this.indexerName = indexerName; } - private async _update() { - const knex = register.getKnex(); - const currentBlock = register.getCurrentBlock(this.indexerName); - - const diff = Object.fromEntries( - [...this.values.entries()].filter(([key]) => - this.valuesImplicitlySet.has(key) - ) - ); - - return knex.transaction(async trx => { - await trx - .table(this.tableName) - .where('id', this.get('id')) - .andWhere('_indexer', this.indexerName) - .andWhereRaw('upper_inf(block_range)') - .update({ - block_range: knex.raw('int8range(lower(block_range), ?)', [ - currentBlock - ]) - }); - - const newEntity = { - ...Object.fromEntries(this.values.entries()), - ...diff - }; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const { uid, ...currentValues } = newEntity; - - await trx.table(this.tableName).insert({ - ...currentValues, - block_range: knex.raw('int8range(?, NULL)', [currentBlock]) - }); - }); - } - - private async _insert() { - const currentBlock = register.getCurrentBlock(this.indexerName); - - const entity = Object.fromEntries(this.values.entries()); - - return register - .getKnex() - .table(this.tableName) - .insert({ - ...entity, - _indexer: this.indexerName, - block_range: register - .getKnex() - .raw('int8range(?, NULL)', [currentBlock]) - }); - } - - private async _delete() { - const currentBlock = register.getCurrentBlock(this.indexerName); - - return register - .getKnex() - .table(this.tableName) - .where('id', this.get('id')) - .andWhere('_indexer', this.indexerName) - .andWhereRaw('upper_inf(block_range)') - .update({ - block_range: register - .getKnex() - .raw('int8range(lower(block_range), ?)', [currentBlock]) - }); - } - setExists() { this.exists = true; } @@ -95,7 +25,6 @@ export default class Model { set(key: string, value: any) { this.values.set(key, value); - this.valuesImplicitlySet.add(key); } static async _loadEntity( @@ -103,26 +32,34 @@ export default class Model { id: string | number, indexerName: string ): Promise | null> { - const knex = register.getKnex(); - - const entity = await knex - .table(tableName) - .select('*') - .where('id', id) - .andWhere('_indexer', indexerName) - .andWhereRaw('upper_inf(block_range)') - .first(); - if (!entity) return null; - - return entity; + return register + .getEntityBuffer(indexerName) + .load({ tableName, id: String(id) }); } async save() { - if (this.exists) return this._update(); - return this._insert(); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { uid, ...values } = Object.fromEntries(this.values.entries()); + + register.getEntityBuffer(this.indexerName).save({ + tableName: this.tableName, + id: String(this.get('id')), + values, + block: register.getCurrentBlock(this.indexerName), + hasDatabaseRow: this.exists + }); + + this.exists = true; } async delete() { - if (this.exists) this._delete(); + if (!this.exists) return; + + register.getEntityBuffer(this.indexerName).delete({ + tableName: this.tableName, + id: String(this.get('id')), + block: register.getCurrentBlock(this.indexerName), + hasDatabaseRow: this.exists + }); } } diff --git a/src/providers/starknet/provider.ts b/src/providers/starknet/provider.ts index da32d30..df588bc 100644 --- a/src/providers/starknet/provider.ts +++ b/src/providers/starknet/provider.ts @@ -182,7 +182,12 @@ export class StarknetProvider extends BaseProvider { eventsData.isPreloaded, eventsData.events[txId] || [] ); + } + // Marked only after the whole pool run succeeded: on failure the + // container rolls back all buffered pool writes, so already-handled + // transactions must be re-processed by the next pool cycle. + for (const txId of txIds) { this.seenPoolTransactions.add(txId); } diff --git a/src/register.ts b/src/register.ts index 3c36420..026f940 100644 --- a/src/register.ts +++ b/src/register.ts @@ -1,8 +1,18 @@ import { Knex } from 'knex'; +import { EntityBuffer } from './orm/entity-buffer'; function createRegister() { let knexInstance: Knex | null = null; const currentBlocks = new Map(); + const entityBuffers = new Map(); + + const getKnex = () => { + if (!knexInstance) { + throw new Error('Knex is not initialized yet.'); + } + + return knexInstance; + }; return { getCurrentBlock(indexerName: string) { @@ -11,13 +21,16 @@ function createRegister() { setCurrentBlock(indexerName: string, block: bigint) { currentBlocks.set(indexerName, block); }, - getKnex() { - if (!knexInstance) { - throw new Error('Knex is not initialized yet.'); + getEntityBuffer(indexerName: string) { + let buffer = entityBuffers.get(indexerName); + if (!buffer) { + buffer = new EntityBuffer({ indexerName, getKnex }); + entityBuffers.set(indexerName, buffer); } - return knexInstance; + return buffer; }, + getKnex, setKnex(knex: Knex) { knexInstance = knex; } diff --git a/test/unit/__snapshots__/codegen.test.ts.snap b/test/unit/__snapshots__/codegen.test.ts.snap index 4f93cf5..1f36c4e 100644 --- a/test/unit/__snapshots__/codegen.test.ts.snap +++ b/test/unit/__snapshots__/codegen.test.ts.snap @@ -1,12 +1,14 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP +// Bun Snapshot v1, https://bun.sh/docs/test/snapshots -exports[`codegen should generate javascript code 1`] = ` +exports[`codegen should generate typescript code 1`] = ` "import { Model } from '@snapshot-labs/checkpoint'; export class Space extends Model { static tableName = 'spaces'; - constructor(id, indexerName) { + static fieldNames = ['id', 'name', 'about', 'controller', 'voting_delay', 'proposal_threshold', 'quorum', 'strategies', 'strategies_nonnull', '_indexer']; + + constructor(id: string, indexerName: string) { super(Space.tableName, indexerName); this.initialSet('id', id); @@ -14,21 +16,21 @@ export class Space extends Model { this.initialSet('about', null); this.initialSet('controller', ""); this.initialSet('voting_delay', 0); - this.initialSet('proposal_threshold', 0); + this.initialSet('proposal_threshold', 0n); this.initialSet('quorum', 0); this.initialSet('strategies', "[]"); this.initialSet('strategies_nonnull', "[]"); this.initialSet('_indexer', ""); } - static async loadEntity(id, indexerName) { + static async loadEntity(id: string, indexerName: string): Promise { const entity = await super._loadEntity(Space.tableName, id, indexerName); if (!entity) return null; const model = new Space(id, indexerName); model.setExists(); - for (const key in entity) { + for (const key of Space.fieldNames) { const value = entity[key] !== null && typeof entity[key] === 'object' ? JSON.stringify(entity[key]) : entity[key]; @@ -38,83 +40,83 @@ export class Space extends Model { return model; } - get id() { + get id(): string { return this.get('id'); } - set id(value) { + set id(value: string) { this.set('id', value); } - get name() { + get name(): string | null { return this.get('name'); } - set name(value) { + set name(value: string | null) { this.set('name', value); } - get about() { + get about(): string | null { return this.get('about'); } - set about(value) { + set about(value: string | null) { this.set('about', value); } - get controller() { + get controller(): string { return this.get('controller'); } - set controller(value) { + set controller(value: string) { this.set('controller', value); } - get voting_delay() { + get voting_delay(): number { return this.get('voting_delay'); } - set voting_delay(value) { + set voting_delay(value: number) { this.set('voting_delay', value); } - get proposal_threshold() { - return this.get('proposal_threshold'); + get proposal_threshold(): bigint { + return BigInt(this.get('proposal_threshold')); } - set proposal_threshold(value) { - this.set('proposal_threshold', value); + set proposal_threshold(value: bigint | number | string) { + this.set('proposal_threshold', BigInt(value)); } - get quorum() { + get quorum(): number { return this.get('quorum'); } - set quorum(value) { + set quorum(value: number) { this.set('quorum', value); } - get strategies() { + get strategies(): string[] { return JSON.parse(this.get('strategies')); } - set strategies(value) { + set strategies(value: string[]) { this.set('strategies', JSON.stringify(value)); } - get strategies_nonnull() { + get strategies_nonnull(): string[] { return JSON.parse(this.get('strategies_nonnull')); } - set strategies_nonnull(value) { + set strategies_nonnull(value: string[]) { this.set('strategies_nonnull', JSON.stringify(value)); } - get _indexer() { + get _indexer(): string { return this.get('_indexer'); } - set _indexer(value) { + set _indexer(value: string) { this.set('_indexer', value); } } @@ -122,27 +124,29 @@ export class Space extends Model { export class Proposal extends Model { static tableName = 'proposals'; - constructor(id, indexerName) { + static fieldNames = ['id', 'proposal_id', 'space', 'title', 'scores_total', 'active', 'progress', '_indexer']; + + constructor(id: string, indexerName: string) { super(Proposal.tableName, indexerName); this.initialSet('id', id); this.initialSet('proposal_id', 0); this.initialSet('space', ""); this.initialSet('title', ""); - this.initialSet('scores_total', 0); + this.initialSet('scores_total', 0n); this.initialSet('active', false); this.initialSet('progress', "0"); this.initialSet('_indexer', ""); } - static async loadEntity(id, indexerName) { + static async loadEntity(id: string, indexerName: string): Promise { const entity = await super._loadEntity(Proposal.tableName, id, indexerName); if (!entity) return null; const model = new Proposal(id, indexerName); model.setExists(); - for (const key in entity) { + for (const key of Proposal.fieldNames) { const value = entity[key] !== null && typeof entity[key] === 'object' ? JSON.stringify(entity[key]) : entity[key]; @@ -152,80 +156,82 @@ export class Proposal extends Model { return model; } - get id() { + get id(): string { return this.get('id'); } - set id(value) { + set id(value: string) { this.set('id', value); } - get proposal_id() { + get proposal_id(): number { return this.get('proposal_id'); } - set proposal_id(value) { + set proposal_id(value: number) { this.set('proposal_id', value); } - get space() { + get space(): string { return this.get('space'); } - set space(value) { + set space(value: string) { this.set('space', value); } - get title() { + get title(): string { return this.get('title'); } - set title(value) { + set title(value: string) { this.set('title', value); } - get scores_total() { - return this.get('scores_total'); + get scores_total(): bigint { + return BigInt(this.get('scores_total')); } - set scores_total(value) { - this.set('scores_total', value); + set scores_total(value: bigint | number | string) { + this.set('scores_total', BigInt(value)); } - get active() { + get active(): boolean { return this.get('active'); } - set active(value) { + set active(value: boolean) { this.set('active', value); } - get progress() { + get progress(): string { return this.get('progress'); } - set progress(value) { + set progress(value: string) { this.set('progress', value); } - get _indexer() { + get _indexer(): string { return this.get('_indexer'); } - set _indexer(value) { + set _indexer(value: string) { this.set('_indexer', value); } } " `; -exports[`codegen should generate typescript code 1`] = ` +exports[`codegen should generate javascript code 1`] = ` "import { Model } from '@snapshot-labs/checkpoint'; export class Space extends Model { static tableName = 'spaces'; - constructor(id: string, indexerName: string) { + static fieldNames = ['id', 'name', 'about', 'controller', 'voting_delay', 'proposal_threshold', 'quorum', 'strategies', 'strategies_nonnull', '_indexer']; + + constructor(id, indexerName) { super(Space.tableName, indexerName); this.initialSet('id', id); @@ -233,21 +239,21 @@ export class Space extends Model { this.initialSet('about', null); this.initialSet('controller', ""); this.initialSet('voting_delay', 0); - this.initialSet('proposal_threshold', 0); + this.initialSet('proposal_threshold', 0n); this.initialSet('quorum', 0); this.initialSet('strategies', "[]"); this.initialSet('strategies_nonnull', "[]"); this.initialSet('_indexer', ""); } - static async loadEntity(id: string, indexerName: string): Promise { + static async loadEntity(id, indexerName) { const entity = await super._loadEntity(Space.tableName, id, indexerName); if (!entity) return null; const model = new Space(id, indexerName); model.setExists(); - for (const key in entity) { + for (const key of Space.fieldNames) { const value = entity[key] !== null && typeof entity[key] === 'object' ? JSON.stringify(entity[key]) : entity[key]; @@ -257,83 +263,83 @@ export class Space extends Model { return model; } - get id(): string { + get id() { return this.get('id'); } - set id(value: string) { + set id(value) { this.set('id', value); } - get name(): string | null { + get name() { return this.get('name'); } - set name(value: string | null) { + set name(value) { this.set('name', value); } - get about(): string | null { + get about() { return this.get('about'); } - set about(value: string | null) { + set about(value) { this.set('about', value); } - get controller(): string { + get controller() { return this.get('controller'); } - set controller(value: string) { + set controller(value) { this.set('controller', value); } - get voting_delay(): number { + get voting_delay() { return this.get('voting_delay'); } - set voting_delay(value: number) { + set voting_delay(value) { this.set('voting_delay', value); } - get proposal_threshold(): bigint { - return this.get('proposal_threshold'); + get proposal_threshold() { + return BigInt(this.get('proposal_threshold')); } - set proposal_threshold(value: bigint) { - this.set('proposal_threshold', value); + set proposal_threshold(value) { + this.set('proposal_threshold', BigInt(value)); } - get quorum(): number { + get quorum() { return this.get('quorum'); } - set quorum(value: number) { + set quorum(value) { this.set('quorum', value); } - get strategies(): string[] { + get strategies() { return JSON.parse(this.get('strategies')); } - set strategies(value: string[]) { + set strategies(value) { this.set('strategies', JSON.stringify(value)); } - get strategies_nonnull(): string[] { + get strategies_nonnull() { return JSON.parse(this.get('strategies_nonnull')); } - set strategies_nonnull(value: string[]) { + set strategies_nonnull(value) { this.set('strategies_nonnull', JSON.stringify(value)); } - get _indexer(): string { + get _indexer() { return this.get('_indexer'); } - set _indexer(value: string) { + set _indexer(value) { this.set('_indexer', value); } } @@ -341,27 +347,29 @@ export class Space extends Model { export class Proposal extends Model { static tableName = 'proposals'; - constructor(id: string, indexerName: string) { + static fieldNames = ['id', 'proposal_id', 'space', 'title', 'scores_total', 'active', 'progress', '_indexer']; + + constructor(id, indexerName) { super(Proposal.tableName, indexerName); this.initialSet('id', id); this.initialSet('proposal_id', 0); this.initialSet('space', ""); this.initialSet('title', ""); - this.initialSet('scores_total', 0); + this.initialSet('scores_total', 0n); this.initialSet('active', false); this.initialSet('progress', "0"); this.initialSet('_indexer', ""); } - static async loadEntity(id: string, indexerName: string): Promise { + static async loadEntity(id, indexerName) { const entity = await super._loadEntity(Proposal.tableName, id, indexerName); if (!entity) return null; const model = new Proposal(id, indexerName); model.setExists(); - for (const key in entity) { + for (const key of Proposal.fieldNames) { const value = entity[key] !== null && typeof entity[key] === 'object' ? JSON.stringify(entity[key]) : entity[key]; @@ -371,67 +379,67 @@ export class Proposal extends Model { return model; } - get id(): string { + get id() { return this.get('id'); } - set id(value: string) { + set id(value) { this.set('id', value); } - get proposal_id(): number { + get proposal_id() { return this.get('proposal_id'); } - set proposal_id(value: number) { + set proposal_id(value) { this.set('proposal_id', value); } - get space(): string { + get space() { return this.get('space'); } - set space(value: string) { + set space(value) { this.set('space', value); } - get title(): string { + get title() { return this.get('title'); } - set title(value: string) { + set title(value) { this.set('title', value); } - get scores_total(): bigint { - return this.get('scores_total'); + get scores_total() { + return BigInt(this.get('scores_total')); } - set scores_total(value: bigint) { - this.set('scores_total', value); + set scores_total(value) { + this.set('scores_total', BigInt(value)); } - get active(): boolean { + get active() { return this.get('active'); } - set active(value: boolean) { + set active(value) { this.set('active', value); } - get progress(): string { + get progress() { return this.get('progress'); } - set progress(value: string) { + set progress(value) { this.set('progress', value); } - get _indexer(): string { + get _indexer() { return this.get('_indexer'); } - set _indexer(value: string) { + set _indexer(value) { this.set('_indexer', value); } } diff --git a/test/unit/codegen.test.ts b/test/unit/codegen.test.ts index 46f9d53..9283484 100644 --- a/test/unit/codegen.test.ts +++ b/test/unit/codegen.test.ts @@ -88,12 +88,15 @@ describe('getInitialValue', () => { expect(getInitialValue(spaceFields['about'].type)).toBeNull(); }); - it('should return 0 for Int/Float/BigInt types', () => { + it('should return 0 for Int/Float types', () => { expect(getInitialValue(spaceFields['voting_delay'].type)).toBe(0); - expect(getInitialValue(spaceFields['proposal_threshold'].type)).toBe(0); expect(getInitialValue(spaceFields['quorum'].type)).toBe(0); }); + it('should return 0n for BigInt types', () => { + expect(getInitialValue(spaceFields['proposal_threshold'].type)).toBe(0n); + }); + it('should return 0 string for BigDecimal types', () => { expect(getInitialValue(proposalFields['progress'].type)).toBe('0'); }); diff --git a/test/unit/orm/entity-buffer.test.ts b/test/unit/orm/entity-buffer.test.ts new file mode 100644 index 0000000..8a4e867 --- /dev/null +++ b/test/unit/orm/entity-buffer.test.ts @@ -0,0 +1,506 @@ +import { describe, expect, it } from 'bun:test'; +import knex, { Knex } from 'knex'; +import { EntityBuffer } from '../../../src/orm/entity-buffer'; + +const pg = knex({ client: 'pg' }); + +/** + * Minimal stand-in for the read-through SELECT: resolves rows by + * `${tableName}:${id}` from a mutable map. + */ +function fakeDb(rows: Record> = {}): Knex { + const db = { + table(tableName: string) { + let id: unknown; + const chain = { + select: () => chain, + where: (_column: string, value: unknown) => { + id = value; + return chain; + }, + andWhere: () => chain, + andWhereRaw: () => chain, + first: async () => rows[`${tableName}:${id}`] + }; + return chain; + } + }; + + return db as unknown as Knex; +} + +function createBuffer(db: Knex = pg) { + return new EntityBuffer({ indexerName: 'eth', getKnex: () => db }); +} + +describe('EntityBuffer', () => { + describe('load', () => { + it('loads unknown entities from the database and caches them', async () => { + const rows = { 'delegates:0x1': { id: '0x1', votes: 1 } }; + const buffer = createBuffer(fakeDb(rows)); + + expect(await buffer.load({ tableName: 'delegates', id: '0x1' })).toEqual({ + id: '0x1', + votes: 1 + }); + + delete rows['delegates:0x1']; + expect(await buffer.load({ tableName: 'delegates', id: '0x1' })).toEqual({ + id: '0x1', + votes: 1 + }); + expect(buffer.size).toBe(1); + }); + + it('counts accumulated version history in size', () => { + const buffer = createBuffer(); + + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 1 }, + block: 100n, + hasDatabaseRow: false + }); + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 2 }, + block: 105n, + hasDatabaseRow: false + }); + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 3 }, + block: 110n, + hasDatabaseRow: false + }); + + expect(buffer.size).toBe(3); + }); + + it('returns null for entities missing in the database', async () => { + const buffer = createBuffer(fakeDb()); + + expect(await buffer.load({ tableName: 'delegates', id: '0x1' })).toBe( + null + ); + }); + + it('returns saved values without touching the database', async () => { + const buffer = createBuffer( + fakeDb({ 'delegates:0x1': { id: '0x1', votes: 999 } }) + ); + + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 2 }, + block: 100n, + hasDatabaseRow: false + }); + + expect(await buffer.load({ tableName: 'delegates', id: '0x1' })).toEqual({ + id: '0x1', + votes: 2 + }); + }); + + it('clones values on save and load', async () => { + const buffer = createBuffer(fakeDb()); + + const values = { id: '0x1', votes: 1 }; + buffer.save({ + tableName: 'delegates', + id: '0x1', + values, + block: 100n, + hasDatabaseRow: false + }); + values.votes = 42; + + const result = await buffer.load({ tableName: 'delegates', id: '0x1' }); + if (!result) throw new Error('expected values'); + expect(result.votes).toBe(1); + + result.votes = 43; + expect(await buffer.load({ tableName: 'delegates', id: '0x1' })).toEqual({ + id: '0x1', + votes: 1 + }); + }); + }); + + describe('version tracking', () => { + it('collapses same-block re-saves into a single version', () => { + const buffer = createBuffer(); + + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 1 }, + block: 100n, + hasDatabaseRow: false + }); + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 2 }, + block: 100n, + hasDatabaseRow: false + }); + + expect(buffer.size).toBe(1); + + const statements = buffer.prepareFlush(pg).map(s => s.toString()); + expect(statements).toHaveLength(1); + expect(statements[0]).toBe( + `insert into "delegates" ("_indexer", "block_range", "id", "votes") values ('eth', int8range('100', NULL), '0x1', 2)` + ); + }); + + it('keeps intermediate versions for saves at different blocks', () => { + const buffer = createBuffer(); + + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 1 }, + block: 100n, + hasDatabaseRow: false + }); + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 2 }, + block: 105n, + hasDatabaseRow: false + }); + + const statements = buffer.prepareFlush(pg).map(s => s.toString()); + expect(statements).toHaveLength(1); + expect(statements[0]).toBe( + `insert into "delegates" ("_indexer", "block_range", "id", "votes") values ('eth', int8range('100', '105'), '0x1', 1), ('eth', int8range('105', NULL), '0x1', 2)` + ); + }); + + it('closes the database row once when a loaded entity is updated', async () => { + const buffer = createBuffer( + fakeDb({ 'delegates:0x1': { id: '0x1', votes: 1 } }) + ); + + await buffer.load({ tableName: 'delegates', id: '0x1' }); + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 2 }, + block: 100n, + hasDatabaseRow: true + }); + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 3 }, + block: 105n, + hasDatabaseRow: true + }); + + const statements = buffer.prepareFlush(pg).map(s => s.toString()); + expect(statements).toHaveLength(2); + expect(statements[0]).toBe( + `update "delegates" set "block_range" = int8range(lower(block_range), '100') where "id" in ('0x1') and "_indexer" = 'eth' and upper_inf(block_range)` + ); + expect(statements[1]).toContain('insert into "delegates"'); + }); + + it('closes the database row for entities known to exist without a prior read', () => { + const buffer = createBuffer(); + + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 2 }, + block: 100n, + hasDatabaseRow: true + }); + + const statements = buffer.prepareFlush(pg).map(s => s.toString()); + expect(statements).toHaveLength(2); + expect(statements[0]).toContain(`int8range(lower(block_range), '100')`); + expect(statements[1]).toContain('insert into "delegates"'); + }); + + it('does not emit a close for entities created in the buffer', () => { + const buffer = createBuffer(); + + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 1 }, + block: 100n, + hasDatabaseRow: false + }); + + const statements = buffer.prepareFlush(pg).map(s => s.toString()); + expect(statements).toHaveLength(1); + expect(statements[0]).toStartWith('insert into "delegates"'); + }); + }); + + describe('delete', () => { + it('closes the database row and shields the stale row from reads', async () => { + const rows = { 'delegates:0x1': { id: '0x1', votes: 1 } }; + const buffer = createBuffer(fakeDb(rows)); + + await buffer.load({ tableName: 'delegates', id: '0x1' }); + buffer.delete({ + tableName: 'delegates', + id: '0x1', + block: 100n, + hasDatabaseRow: true + }); + + expect(await buffer.load({ tableName: 'delegates', id: '0x1' })).toBe( + null + ); + + const statements = buffer.prepareFlush(pg).map(s => s.toString()); + expect(statements).toHaveLength(1); + expect(statements[0]).toStartWith('update "delegates"'); + }); + + it('leaves nothing pending for entities created and deleted in the same block', async () => { + const rows = { 'delegates:0x1': { id: '0x1', votes: 1 } }; + const buffer = createBuffer(fakeDb(rows)); + + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 1 }, + block: 100n, + hasDatabaseRow: false + }); + buffer.delete({ + tableName: 'delegates', + id: '0x1', + block: 100n, + hasDatabaseRow: false + }); + + expect(await buffer.load({ tableName: 'delegates', id: '0x1' })).toBe( + null + ); + expect(buffer.prepareFlush(pg)).toHaveLength(0); + }); + + it('supports re-creating a deleted entity', async () => { + const buffer = createBuffer( + fakeDb({ 'delegates:0x1': { id: '0x1', votes: 1 } }) + ); + + await buffer.load({ tableName: 'delegates', id: '0x1' }); + buffer.delete({ + tableName: 'delegates', + id: '0x1', + block: 100n, + hasDatabaseRow: true + }); + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 5 }, + block: 105n, + hasDatabaseRow: true + }); + + expect(await buffer.load({ tableName: 'delegates', id: '0x1' })).toEqual({ + id: '0x1', + votes: 5 + }); + + const statements = buffer.prepareFlush(pg).map(s => s.toString()); + expect(statements).toHaveLength(2); + expect(statements[0]).toContain(`int8range(lower(block_range), '100')`); + expect(statements[1]).toContain(`int8range('105', NULL)`); + }); + }); + + describe('block journal', () => { + it('rolls back entity changes and bookkeeping from the current block', async () => { + const buffer = createBuffer( + fakeDb({ 'delegates:0x1': { id: '0x1', votes: 1 } }) + ); + + await buffer.load({ tableName: 'delegates', id: '0x1' }); + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 2 }, + block: 100n, + hasDatabaseRow: true + }); + buffer.setLastIndexedBlock(100); + + buffer.beginBlock(); + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 3 }, + block: 105n, + hasDatabaseRow: true + }); + buffer.save({ + tableName: 'delegates', + id: '0x2', + values: { id: '0x2', votes: 1 }, + block: 105n, + hasDatabaseRow: false + }); + buffer.addCheckpoints([{ blockNumber: 105, contractAddress: '0xc' }]); + buffer.setBlockHash(105, '0xhash'); + buffer.setLastIndexedBlock(105); + buffer.rollbackBlock(); + + expect(await buffer.load({ tableName: 'delegates', id: '0x1' })).toEqual({ + id: '0x1', + votes: 2 + }); + expect(await buffer.load({ tableName: 'delegates', id: '0x2' })).toBe( + null + ); + expect(buffer.getBlockHash(105)).toBe(null); + // entity close + entity insert + restored lastIndexedBlock upsert + expect(buffer.prepareFlush(pg)).toHaveLength(3); + }); + + it('rolls back closed versions appended in the current block', async () => { + const buffer = createBuffer(fakeDb()); + + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 1 }, + block: 100n, + hasDatabaseRow: false + }); + + buffer.beginBlock(); + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 2 }, + block: 105n, + hasDatabaseRow: false + }); + buffer.rollbackBlock(); + + expect(await buffer.load({ tableName: 'delegates', id: '0x1' })).toEqual({ + id: '0x1', + votes: 1 + }); + + const statements = buffer.prepareFlush(pg).map(s => s.toString()); + expect(statements).toHaveLength(1); + expect(statements[0]).toBe( + `insert into "delegates" ("_indexer", "block_range", "id", "votes") values ('eth', int8range('100', NULL), '0x1', 1)` + ); + }); + + it('keeps changes after commitBlock', async () => { + const buffer = createBuffer(fakeDb()); + + buffer.beginBlock(); + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 1 }, + block: 100n, + hasDatabaseRow: false + }); + buffer.commitBlock(); + buffer.rollbackBlock(); + + expect(await buffer.load({ tableName: 'delegates', id: '0x1' })).toEqual({ + id: '0x1', + votes: 1 + }); + }); + }); + + describe('bookkeeping', () => { + it('builds checkpoint, block hash and metadata statements', () => { + const buffer = createBuffer(); + + buffer.addCheckpoints([ + { blockNumber: 100, contractAddress: '0xc' }, + { blockNumber: 105, contractAddress: '0xc' } + ]); + buffer.setBlockHash(105, '0xhash'); + buffer.setLastIndexedBlock(105); + + const statements = buffer.prepareFlush(pg).map(s => s.toString()); + expect(statements).toHaveLength(3); + expect(statements[0]).toContain('insert into "_checkpoints"'); + expect(statements[0]).toContain( + 'on conflict ("id", "indexer") do nothing' + ); + expect(statements[1]).toContain('insert into "_blocks"'); + expect(statements[1]).toContain( + 'on conflict ("indexer", "block_number") do update' + ); + expect(statements[2]).toContain('insert into "_metadatas"'); + expect(statements[2]).toContain( + 'on conflict ("id", "indexer") do update' + ); + }); + + it('keeps only the latest hash per block number', () => { + const buffer = createBuffer(); + + buffer.setBlockHash(100, '0xold'); + buffer.setBlockHash(100, '0xnew'); + + const statements = buffer.prepareFlush(pg).map(s => s.toString()); + expect(statements).toHaveLength(1); + expect(statements[0]).toContain('0xnew'); + expect(statements[0]).not.toContain('0xold'); + }); + + it('returns the latest buffered block hash', () => { + const buffer = createBuffer(); + + buffer.setBlockHash(100, '0xaaa'); + buffer.setBlockHash(105, '0xbbb'); + + expect(buffer.getBlockHash(100)).toBe('0xaaa'); + expect(buffer.getBlockHash(105)).toBe('0xbbb'); + expect(buffer.getBlockHash(110)).toBe(null); + }); + }); + + describe('reset', () => { + it('clears all pending state', async () => { + const buffer = createBuffer(fakeDb()); + + buffer.save({ + tableName: 'delegates', + id: '0x1', + values: { id: '0x1', votes: 1 }, + block: 100n, + hasDatabaseRow: false + }); + buffer.addCheckpoints([{ blockNumber: 100, contractAddress: '0xc' }]); + buffer.setBlockHash(100, '0xhash'); + buffer.setLastIndexedBlock(100); + buffer.reset(); + + expect(buffer.size).toBe(0); + expect(await buffer.load({ tableName: 'delegates', id: '0x1' })).toBe( + null + ); + expect(buffer.getBlockHash(100)).toBe(null); + expect(buffer.prepareFlush(pg)).toHaveLength(0); + }); + }); +});