Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@snapshot-labs/checkpoint",
"version": "0.1.0-beta.69",
"name": "checkpoint-playground",
"version": "0.1.4",
"license": "MIT",
"bin": {
"checkpoint": "dist/src/bin/index.js"
Expand All @@ -10,7 +10,7 @@
"scripts": {
"lint": "eslint src/ test/ --ext .ts --fix",
"build": "tsc",
"prepare": "yarn build",
"prepare": "npm run build",
"prepublishOnly": "yarn run lint",
"test": "jest"
},
Expand Down
2 changes: 1 addition & 1 deletion src/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ export const codegen = (
) => {
const decimalTypes = config.decimal_types || DEFAULT_DECIMAL_TYPES;

const preamble = `import { Model } from '@snapshot-labs/checkpoint';\n\n`;
const preamble = `import { Model } from 'checkpoint-playground';\n\n`;

let contents = `${preamble}`;

Expand Down
107 changes: 84 additions & 23 deletions src/container.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Knex } from 'knex';
import { GqlEntityController } from './graphql/controller';
import { EntityWriteBuffer } from './orm/buffer';
import {
BaseIndexer,
BlockNotFoundError,
Expand All @@ -16,6 +17,7 @@ import {
CheckpointConfig,
CheckpointOptions,
ContractSourceConfig,
PreloadTarget,
TemplateSource
} from './types';
import { getConfigChecksum, getContractsFromConfig } from './utils/checkpoint';
Expand All @@ -35,6 +37,10 @@ const CHECK_LATEST_BLOCK_INTERVAL = 50;

const DEFAULT_FETCH_INTERVAL = 2000;

const DEFAULT_BATCH_SIZE = 100;

const REORG_MAX_WALK_BACK = 128;

export class Container implements Instance {
private indexerName: string;

Expand All @@ -47,15 +53,18 @@ export class Container implements Instance {
private readonly indexer: BaseIndexer;
private readonly entityController: GqlEntityController;
private knex: Knex;
private buffer: EntityWriteBuffer;

private activeTemplates: TemplateSource[] = [];
private cpBlocksCache: number[] | null = [];
private blockHashCache: { blockNumber: number; hash: string } | null = null;

private preloadStep: number = BLOCK_PRELOAD_START_RANGE;
private preloadedBlocks: number[] = [];
private preloadEndBlock = 0;

private blocksInBatch = 0;
private batchStartBlock: number | null = null;

constructor(
indexerName: string,
log: Logger,
Expand All @@ -76,6 +85,8 @@ export class Container implements Instance {
this.indexer = indexer;
this.schema = schema;
this.opts = opts;
this.buffer = new EntityWriteBuffer(indexerName, knex, store);
register.setBuffer(indexerName, this.buffer);

this.indexer.init({
instance: this,
Expand Down Expand Up @@ -117,12 +128,8 @@ export class Container implements Instance {
}

private async getBlockHash(blockNumber: number): Promise<string | null> {
if (
this.blockHashCache &&
this.blockHashCache.blockNumber === blockNumber
) {
return this.blockHashCache.hash;
}
const pending = this.buffer.getPendingBlockHash(blockNumber);
if (pending !== null) return pending;

return this.store.getBlockHash(this.indexerName, blockNumber);
}
Expand Down Expand Up @@ -183,22 +190,45 @@ export class Container implements Instance {
};
}

public async setBlockHash(blockNum: number, hash: string) {
this.blockHashCache = { blockNumber: blockNum, hash };
public insertCheckpoints(checkpoints: CheckpointRecord[]) {
this.buffer.pushCheckpoints(checkpoints);
}

return this.store.setBlockHash(this.indexerName, blockNum, hash);
public async prefetchEntities(targets: PreloadTarget[]) {
await this.buffer.prefetch(targets);
}

public async setLastIndexedBlock(block: number) {
await this.store.setMetadata(
this.indexerName,
MetadataId.LastIndexedBlock,
block
);
public async flushBlock(blockNumber: number, blockHash: string | null) {
if (blockHash !== null) {
this.buffer.pushBlockHash(blockNumber, blockHash);
}

if (this.blocksInBatch === 0) {
this.batchStartBlock = blockNumber;
}
this.blocksInBatch += 1;

if (this.blocksInBatch >= this.getEffectiveBatchSize(blockNumber)) {
await this.buffer.flush(blockNumber);
this.blocksInBatch = 0;
this.batchStartBlock = null;
}
}

public async insertCheckpoints(checkpoints: CheckpointRecord[]) {
await this.store.insertCheckpoints(this.indexerName, checkpoints);
public clearBuffer(): number | null {
const restart = this.batchStartBlock;
this.buffer.clear();
this.blocksInBatch = 0;
this.batchStartBlock = null;
return restart;
}

private getEffectiveBatchSize(blockNumber: number): number {
const configured = this.config.batch_size ?? DEFAULT_BATCH_SIZE;
if (configured <= 1) return 1;
// Near tip, flush every block so reorgs and live queries stay correct.
if (blockNumber >= this.preloadEndBlock) return 1;
return configured;
}

/**
Expand Down Expand Up @@ -354,6 +384,11 @@ export class Container implements Instance {

blockNumber = nextBlockNumber;
} catch (err) {
const restartBlock = this.clearBuffer();
if (restartBlock !== null && restartBlock < blockNumber) {
blockNumber = restartBlock;
}

if (err instanceof BlockNotFoundError) {
if (this.config.optimistic_indexing) {
try {
Expand Down Expand Up @@ -393,9 +428,24 @@ export class Container implements Instance {
private async handleReorg(blockNumber: number) {
this.log.info({ blockNumber }, 'handling reorg');

let current = blockNumber - 1;
// Any in-flight batch state was discarded by the caller (process() catch),
// so start the walk-back from the last committed block — never from an
// uncommitted block that would have been dropped with the buffer.
const dbLastIndexedBlock =
(await this.store.getMetadataNumber(
this.indexerName,
MetadataId.LastIndexedBlock
)) ?? 0;

const walkStart = Math.min(blockNumber - 1, dbLastIndexedBlock);
let current = walkStart;
let lastGoodBlock: null | number = null;
while (lastGoodBlock === null) {
if (walkStart - current >= REORG_MAX_WALK_BACK) {
throw new Error(
`reorg walk-back exceeded ${REORG_MAX_WALK_BACK} blocks (started at ${walkStart}, now at ${current})`
);
}
try {
const storedBlockHash = await this.store.getBlockHash(
this.indexerName,
Expand Down Expand Up @@ -446,7 +496,6 @@ export class Container implements Instance {
await this.store.removeFutureData(this.indexerName, lastGoodBlock);

this.cpBlocksCache = null;
this.blockHashCache = null;

this.log.info({ blockNumber: lastGoodBlock }, 'reorg resolved');

Expand Down Expand Up @@ -534,14 +583,18 @@ export class Container implements Instance {
...sources.map(source => source.abi),
...templates.map(template => template.abi)
].filter(abi => abi) as string[];
const usedWriters = [
const usedEvents = [
...sources.flatMap(source => source.events),
...templates.flatMap(template => template.events)
];

const missingAbis = usedAbis.filter(abi => !this.config.abis?.[abi]);
const missingWriters = usedWriters.filter(
writer => !this.indexer.getHandlers().includes(writer.fn)
const missingWriters = usedEvents.filter(
event => !this.indexer.getHandlers().includes(event.fn)
);
const knownPreloaders = this.indexer.getPreloaders();
const missingPreloaders = usedEvents.filter(
event => event.preload_fn && !knownPreloaders.includes(event.preload_fn)
);

if (missingAbis.length > 0) {
Expand All @@ -557,6 +610,14 @@ export class Container implements Instance {
.join(', ')}), but they are not defined`
);
}

if (missingPreloaders.length > 0) {
throw new Error(
`Following preloaders are used (${missingPreloaders
.map(event => event.preload_fn)
.join(', ')}), but they are not defined`
);
}
}

public async validateStore() {
Expand Down
Loading
Loading