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
382 changes: 339 additions & 43 deletions package-lock.json

Large diffs are not rendered by default.

9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start": "nest start | pino-pretty",
"start:dev": "nest start --watch | pino-pretty",
"start:debug": "nest start --debug --watch | pino-pretty",
"start:prod": "node dist/main",
"migration:deploy": "prisma migrate deploy",
"migration:generate": "prisma generate --sql",
Expand Down Expand Up @@ -49,7 +49,9 @@
"luxon": "^3.7.2",
"multiaddr": "^10.0.1",
"multiformats": "^14.0.5",
"nestjs-pino": "^5.3.2",
"pg": "^8.23.1",
"pino-http": "^11.0.0",
"prom-client": "^15.1.3",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2",
Expand All @@ -67,6 +69,7 @@
"eslint": "^8.57.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.7",
"pino-pretty": "^13.2.0",
"prettier": "^3.10.1",
"prisma": "7.10.0",
"prisma-kysely": "^3.2.1",
Expand Down
20 changes: 13 additions & 7 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { HttpModule, HttpService } from '@nestjs/axios';
import { CacheInterceptor, CacheModule } from '@nestjs/cache-manager';
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';
import { ScheduleModule } from '@nestjs/schedule';
import { TerminusModule } from '@nestjs/terminus';
import axios from 'axios';
import axiosBetterStacktrace from 'axios-better-stacktrace';
import { LoggerModule } from 'nestjs-pino';
import { AppController } from './controller/app/app.controller';
import { ClientsController } from './controller/clients/clients.controller';
import { FilecoinPayController } from './controller/filecoin-pay/filecoin-pay.controller';
Expand All @@ -16,7 +17,6 @@ import { DbModule } from './db/db.module';
import { PrismaService } from './db/prisma.service';
import { IpniAdvertisementFetcherJobService } from './jobs/ipni-advertisement-fetcher-job/ipni-advertisement-fetcher-job.service';
import { ErrorHandlerMiddleware } from './middleware/error-handler.middleware';
import { RequestLoggerMiddleware } from './middleware/request-logger.middleware';
import { PoRepIndexerModule } from './po-rep-indexer';
import { PrometheusMetricModule } from './prometheus';
import { CidContactService } from './service/cid-contact/cid-contact.service';
Expand All @@ -32,6 +32,16 @@ import { IPNIController } from 'src/controller/ipni/ipni.controller';

@Module({
imports: [
LoggerModule.forRoot({
pinoHttp: {
level: process.env.NODE_ENV === 'test' ? 'silent' : 'debug',
formatters: {
level(label) {
return { level: label };
},
},
},
}),
ConfigModule.forRoot(),
ScheduleModule.forRoot(),
HttpModule.register({ timeout: 5000 }), // 5 seconds
Expand Down Expand Up @@ -73,12 +83,8 @@ import { IPNIController } from 'src/controller/ipni/ipni.controller';
},
],
})
export class AppModule implements NestModule {
export class AppModule {
constructor(private readonly httpService: HttpService) {
axiosBetterStacktrace(this.httpService.axiosRef);
}

configure(consumer: MiddlewareConsumer) {
consumer.apply(RequestLoggerMiddleware).forRoutes('*');
}
}
2 changes: 2 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ConsoleLogger, ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { Logger } from 'nestjs-pino';
import * as packageJson from '../package.json';
import { AppModule } from './app.module';

Expand Down Expand Up @@ -32,6 +33,7 @@ process.on('unhandledRejection', exitOnFatalError('Unhandled rejection'));

async function bootstrap() {
const app = await NestFactory.create(AppModule, { logger: logger });
app.useLogger(app.get(Logger));
app.enableShutdownHooks();
app.enableCors();
app.useGlobalPipes(
Expand Down
32 changes: 0 additions & 32 deletions src/middleware/request-logger.middleware.ts

This file was deleted.

18 changes: 14 additions & 4 deletions src/po-rep-indexer/po-rep-indexer.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,32 +16,41 @@ import {
createClientForChainOrThrow,
validatePoRepConfig,
} from './po-rep-indexer.utils';
import { RpcMetricsContext } from './rpc-metrics-context.service';
import { AbstractPoRepIndexerRunner } from './runners/abstract-po-rep-indexer.runner';
import { FilecoinPayIndexerRunner } from './runners/filecoin-pay-indexer.runner';
import { PoRepProvidersAndDealsIndexerRunner } from './runners/po-rep-providers-and-deals.runner';

const recentNodeClient: FactoryProvider<PoRepPublicClient> = {
provide: RECENT_NODE_CLIENT,
useFactory: (configService: ConfigService<PoRepConfig, true>) => {
useFactory: (
configService: ConfigService<PoRepConfig, true>,
rpcMetricsContext: RpcMetricsContext,
) => {
return createClientForChainOrThrow({
chainId: configService.get('PO_REP_CHAIN_ID'),
rpcUrl: configService.get('PO_REP_RECENT_RPC_URL'),
authToken: configService.get('PO_REP_RECENT_RPC_AUTH_TOKEN'),
rpcMetricsContext,
});
},
inject: [ConfigService],
inject: [ConfigService, RpcMetricsContext],
};

const archiveNodeClient: FactoryProvider<PoRepPublicClient> = {
provide: ARCHIVE_NODE_CLIENT,
useFactory: (configService: ConfigService<PoRepConfig, true>) => {
useFactory: (
configService: ConfigService<PoRepConfig, true>,
rpcMetricsContext: RpcMetricsContext,
) => {
return createClientForChainOrThrow({
chainId: configService.get('PO_REP_CHAIN_ID'),
rpcUrl: configService.get('PO_REP_ARCHIVE_RPC_URL'),
authToken: configService.get('PO_REP_ARCHIVE_RPC_AUTH_TOKEN'),
rpcMetricsContext,
});
},
inject: [ConfigService],
inject: [ConfigService, RpcMetricsContext],
};

@Module({
Expand All @@ -56,6 +65,7 @@ const archiveNodeClient: FactoryProvider<PoRepPublicClient> = {
PrismaService,
PoRepProvidersAndDealsIndexerRunner,
FilecoinPayIndexerRunner,
RpcMetricsContext,
recentNodeClient,
archiveNodeClient,
DealManifestService,
Expand Down
42 changes: 42 additions & 0 deletions src/po-rep-indexer/po-rep-indexer.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,48 @@ export type PoRepPublicClient = PublicClient<
> &
FilecoinActions;

export interface RpcMetrics {
totalCallsCount: number;
totalCallsDurationMs: number;
averageCallDurationMs: number;
rpcCallsByMethod: Record<
string,
{
count: number;
totalDurationMs: number;
averageDurationMs: number;
}
>;
}

export interface IndexerBatchMetrics {
fromBlock?: bigint;
toBlock?: bigint;
batchBlockSize?: bigint;
nodeType?: 'archive' | 'recent';
changesReadDurationMs?: number;
changesWriteDurationMs?: number;
}

export interface IndexerBatchResultContext {
event: 'indexer.batch.result';
indexer: string;
batchStartEpoch?: string;
batchEndEpoch?: string;
batchBlockSize?: string;
nodeType?: 'archive' | 'recent';
timeoutCount: number;
error: boolean;
keepRunning: boolean;
totalDurationMs: number;
changesReadDurationMs?: number;
changesWriteDurationMs?: number;
rpcCalls: number;
rpcTotalDurationMs: number;
rpcCallAverageDurationMs: number;
rpcByMethod: RpcMetrics['rpcCallsByMethod'];
}

export type PoRepConfig = z.infer<typeof PO_REP_CONFIG_SCHEMA>;

export type DealManifest = z.infer<typeof DEAL_MANIFEST_SCHEMA>;
Expand Down
78 changes: 76 additions & 2 deletions src/po-rep-indexer/po-rep-indexer.utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { createPublicClient, extractChain, http, rpcSchema } from 'viem';
import { Logger } from '@nestjs/common';
import {
createPublicClient,
extractChain,
http,
HttpTransport,
rpcSchema,
} from 'viem';
import z from 'zod';
import {
PO_REP_CONFIG_SCHEMA,
Expand All @@ -9,13 +16,17 @@ import {
PoRepConfig,
PoRepPublicClient,
} from './po-rep-indexer.types';
import { RpcMetricsContext } from './rpc-metrics-context.service';

type SupportedChainId = (typeof PO_REP_SUPPORTED_CHAINS)[number]['id'];

const rpcLogger = new Logger('RpcRequest');

export interface GetClientForChainOptions {
chainId: number;
rpcUrl?: string | null;
authToken?: string | null;
rpcMetricsContext: RpcMetricsContext;
}

const filecoinRpcSchema = rpcSchema<FilecoinRpcSchema>();
Expand All @@ -32,15 +43,71 @@ function assertIsSupportedChainId(
}
}

function withRpcMetrics(
transport: HttpTransport,
rpcMetricsContext: RpcMetricsContext,
): HttpTransport {
return (parameters) => {
const instance = transport(parameters);
const request: typeof instance.request = async (args, options) => {
const metrics = rpcMetricsContext.current();
const startTime = performance.now();

try {
return await instance.request(args, options);
} finally {
if (metrics) {
const requestDurationMs = performance.now() - startTime;
metrics.totalCallsCount++;
metrics.totalCallsDurationMs += requestDurationMs;
metrics.averageCallDurationMs =
metrics.totalCallsDurationMs / metrics.totalCallsCount;

const methodMetrics = (metrics.rpcCallsByMethod[args.method] ??= {
count: 0,
totalDurationMs: 0,
averageDurationMs: 0,
});

methodMetrics.count++;
methodMetrics.totalDurationMs += requestDurationMs;
methodMetrics.averageDurationMs =
methodMetrics.totalDurationMs / methodMetrics.count;
}
}
};

return { ...instance, request };
};
}

function withGetLogsRetryCount(
transport: HttpTransport,
retryCount: number,
): HttpTransport {
return (parameters) => {
const instance = transport(parameters);
const request: typeof instance.request = (args, options) => {
return instance.request(
args,
args.method === 'eth_getLogs' ? { ...options, retryCount } : options,
);
};

return { ...instance, request };
};
}

export function createClientForChainOrThrow({
chainId,
rpcUrl,
authToken,
rpcMetricsContext,
}: GetClientForChainOptions): PoRepPublicClient {
assertIsSupportedChainId(chainId);

const chain = extractChain({ chains: PO_REP_SUPPORTED_CHAINS, id: chainId });
const transport = http(rpcUrl ?? undefined, {
const httpTransport = http(rpcUrl ?? undefined, {
fetchOptions:
typeof authToken === 'string' && authToken !== ''
? {
Expand All @@ -49,8 +116,15 @@ export function createClientForChainOrThrow({
},
}
: undefined,
onFetchRequest: (request, init) => {
rpcLogger.debug({ url: request.url, body: init.body }, 'RPC request');
},
timeout: 60_000,
});
const transport = withRpcMetrics(
withGetLogsRetryCount(httpTransport, 1),
rpcMetricsContext,
);

const client = createPublicClient({
chain: chain,
Expand Down
25 changes: 25 additions & 0 deletions src/po-rep-indexer/rpc-metrics-context.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Injectable } from '@nestjs/common';
import { AsyncLocalStorage } from 'node:async_hooks';
import { RpcMetrics } from './po-rep-indexer.types';

@Injectable()
export class RpcMetricsContext {
private readonly storage = new AsyncLocalStorage<RpcMetrics>();

public run<T>(metrics: RpcMetrics, callback: () => Promise<T>): Promise<T> {
return this.storage.run(metrics, callback);
}

public current(): RpcMetrics | undefined {
return this.storage.getStore();
}

public empty(): RpcMetrics {
return {
totalCallsCount: 0,
totalCallsDurationMs: 0,
averageCallDurationMs: 0,
rpcCallsByMethod: {},
};
}
}
Loading
Loading