Skip to content
Merged
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
89 changes: 50 additions & 39 deletions src/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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':
Expand Down Expand Up @@ -107,6 +107,19 @@ export const getJSType = (
return { isNullable, isList, baseType };
};

const isPersistedField = (field: GraphQLField<any, any>) => {
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,
Expand All @@ -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;

Expand All @@ -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`;
Expand All @@ -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`;
Expand All @@ -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`;
});

Expand Down
105 changes: 84 additions & 21 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 { EntityBuffer } from './orm/entity-buffer';
import {
BaseIndexer,
BlockNotFoundError,
Expand Down Expand Up @@ -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;
Comment thread
tony8713 marked this conversation as resolved.
Resolved

/** 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;

Expand All @@ -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,
Expand All @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
}

/**
Expand Down Expand Up @@ -351,37 +364,34 @@ 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) {
this.preloadedBlocks = [];
}

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'
Expand Down Expand Up @@ -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;
Comment thread
Sekhmet marked this conversation as resolved.
Resolved

if (atTip || stale || full) {
await this.flushBuffer(currentBlock);
}
}

Expand Down Expand Up @@ -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) {
Expand All @@ -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())
);
Expand All @@ -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;

Expand All @@ -499,6 +560,8 @@ export class Container implements Instance {
}

public async reset() {
this.entityBuffer.reset();

await this.store.setMetadata(
this.indexerName,
MetadataId.LastIndexedBlock,
Expand Down
Loading
Loading