Skip to content

Commit

Permalink
merge
Browse files Browse the repository at this point in the history
  • Loading branch information
dydxwill committed Jun 14, 2024
2 parents 6a8939f + f3b6fd7 commit 7bf3954
Show file tree
Hide file tree
Showing 341 changed files with 11,575 additions and 10,128 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/indexer-build-and-push-dev-staging.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ on: # yamllint disable-line rule:truthy
push:
branches:
- main
- 'release/[a-z]+/v[0-9]+.[0-9]+.x' # e.g. release/indexer/v0.1.x
- 'release/[a-z]+/v[0-9]+.x' # e.g. release/indexer/v1.x
- 'release/indexer/v[0-9]+.[0-9]+.x' # e.g. release/indexer/v0.1.x
- 'release/indexer/v[0-9]+.x' # e.g. release/indexer/v1.x
# TODO(DEC-837): Customize github build and push to ECR by service with paths

jobs:
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/indexer-build-and-push-mainnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ on: # yamllint disable-line rule:truthy
push:
branches:
- main
- 'release/[a-z]+/v[0-9]+.[0-9]+.x' # e.g. release/indexer/v0.1.x
- 'release/[a-z]+/v[0-9]+.x' # e.g. release/indexer/v1.x
- 'release/indexer/v[0-9]+.[0-9]+.x' # e.g. release/indexer/v0.1.x
- 'release/indexer/v[0-9]+.x' # e.g. release/indexer/v1.x
# TODO(DEC-837): Customize github build and push to ECR by service with paths

jobs:
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/indexer-build-and-push-testnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ on: # yamllint disable-line rule:truthy
push:
branches:
- main
- 'release/[a-z]+/v[0-9]+.[0-9]+.x' # e.g. release/indexer/v0.1.x
- 'release/[a-z]+/v[0-9]+.x' # e.g. release/indexer/v1.x
- 'release/indexer/v[0-9]+.[0-9]+.x' # e.g. release/indexer/v0.1.x
- 'release/indexer/v[0-9]+.x' # e.g. release/indexer/v1.x
# TODO(DEC-837): Customize github build and push to ECR by service with paths

jobs:
Expand Down
46 changes: 46 additions & 0 deletions .github/workflows/protocol-benchmark.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
name: Protocol Benchmark
on: # yamllint disable-line rule:truthy
pull_request:
paths:
- 'protocol/**'
push:
branches:
- main
- 'release/protocol/v[0-9]+.[0-9]+.x' # e.g. release/protocol/v0.1.x
- 'release/protocol/v[0-9]+.x' # e.g. release/protocol/v1.x
paths:
- 'protocol/**'

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true

jobs:
benchmark:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./protocol
steps:
- name: Check out repository code
uses: actions/checkout@v3
- name: Setup Golang
uses: actions/setup-go@v3
with:
go-version: 1.22
- name: Run Benchmarks
run: make benchmark | tee ./benchmark_output.txt
- name: Download previous benchmark data
uses: actions/cache@v4
with:
path: ./cache
key: ${{ runner.os }}-benchmark
- name: Store benchmark result
uses: benchmark-action/github-action-benchmark@v1
with:
tool: 'go'
output-file-path: ./protocol/benchmark_output.txt
external-data-json-path: ./cache/benchmark-data.json
fail-on-alert: true
alert-threshold: '150%'
save-data-file: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
4 changes: 2 additions & 2 deletions .github/workflows/protocol-build-and-push-snapshot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ on: # yamllint disable-line rule:truthy
push:
branches:
- main
- 'release/[a-z]+/v[0-9]+.[0-9]+.x' # e.g. release/protocol/v0.1.x
- 'release/[a-z]+/v[0-9]+.x' # e.g. release/protocol/v1.x
- 'release/protocol/v[0-9]+.[0-9]+.x' # e.g. release/protocol/v0.1.x
- 'release/protocol/v[0-9]+.x' # e.g. release/protocol/v1.x

jobs:
build-and-push-snapshot-dev:
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/protocol-build-and-push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ on: # yamllint disable-line rule:truthy
push:
branches:
- main
- 'release/[a-z]+/v[0-9]+.[0-9]+.x' # e.g. release/protocol/v0.1.x
- 'release/[a-z]+/v[0-9]+.x' # e.g. release/protocol/v1.x
- 'release/protocol/v[0-9]+.[0-9]+.x' # e.g. release/protocol/v0.1.x
- 'release/protocol/v[0-9]+.x' # e.g. release/protocol/v1.x

jobs:
build-and-push-dev:
Expand Down
16 changes: 2 additions & 14 deletions .github/workflows/protocol-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,17 @@ jobs:
- name: install go
uses: actions/setup-go@v3
with:
go-version: '1.21'
go-version: '1.22'
check-latest: true
- name: Create Directory
run: mkdir ./build
- name: Build Reproducible Linux Binaries
run: make distclean build-reproducible
run: make distclean build-reproducible-linux-amd64
- name: Rename Binaries
run: |
mv ./build/dydxprotocold:linux-arm64 ./build/dydxprotocold-${{ env.VERSION }}-linux-arm64
mv ./build/dydxprotocold:linux-amd64 ./build/dydxprotocold-${{ env.VERSION }}-linux-amd64
- name: Compress binaries
run: |
tar -cvzf dydxprotocold-${{ env.VERSION }}-linux-arm64.tar.gz \
./build/dydxprotocold-${{ env.VERSION }}-linux-arm64
tar -cvzf dydxprotocold-${{ env.VERSION }}-linux-amd64.tar.gz \
./build/dydxprotocold-${{ env.VERSION }}-linux-amd64
- name: Create Release
Expand All @@ -63,15 +60,6 @@ jobs:
asset_path: protocol/dydxprotocold-${{ env.VERSION }}-linux-amd64.tar.gz
asset_name: dydxprotocold-${{ env.VERSION }}-linux-amd64.tar.gz
asset_content_type: application/gzip
- name: Upload linux-arm64 tar.gz
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ github.token }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: protocol/dydxprotocold-${{ env.VERSION }}-linux-arm64.tar.gz
asset_name: dydxprotocold-${{ env.VERSION }}-linux-arm64.tar.gz
asset_content_type: application/gzip
# TODO(DEC-1743): add build report and binary check sums

v4-proto-py-release:
Expand Down
2 changes: 2 additions & 0 deletions indexer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ pnpm run test:all

If you change any logic, you'll have to re-build the services and packages before running unit tests.

### To run a single test file:
`cd services/{service_name} && pnpm build && pnpm test -- {test_name}`

# Running Dockerfile locally
TODO(DEC-671): Add e2e tests
Expand Down
4 changes: 1 addition & 3 deletions indexer/packages/base/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import winston from 'winston';

import config from './config';
import { redact } from './sanitization';
import { InfoObject } from './types';

// Fix types. The methods available depend on the levels used. We're using syslog levels, so these
Expand Down Expand Up @@ -38,8 +37,7 @@ const logger: LoggerExport = winston.createLogger({
winston.format((info) => {
return {
...info, // info contains some symbols that are lost when the object is cloned.
...redact(info),
error: info.error, // cloning with redact() may break the error object
error: info.error,
};
})(),
winston.format.json(),
Expand Down
25 changes: 0 additions & 25 deletions indexer/packages/base/src/sanitization.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,7 @@
import traverse from 'traverse';

// Common request headers which should be redacted. Normalized to all-lowercase.
export const DEFAULT_SECRET_KEYS = [
'Authorization',
'X-Routing-Key', // Used by PagerDuty.
];

const DEFAULT_REDACTED_PLACEHOLDER = '[REDACTED]';
const JSON_CIRCULAR_PLACEHOLDER = '[CIRCULAR]';

/**
* Creates a deep copy of an object with values redacted where the key matches `secretKeys`.
*/
export function redact<T>(
obj: T,
secretKeys: string[] = DEFAULT_SECRET_KEYS,
placeholder: string = DEFAULT_REDACTED_PLACEHOLDER,
): T {
const normalizedSecretKeys = secretKeys.map((s) => s.toLowerCase());

// eslint-disable-next-line array-callback-return
return traverse(obj).map(function traverseFunction(this: traverse.TraverseContext, value: {}) {
if (normalizedSecretKeys.includes(this.key?.toLowerCase() as string) && value !== null) {
this.update(placeholder);
}
});
}

/**
* Creates a deep copy of an object with circular references removed or replaced.
*/
Expand Down
2 changes: 1 addition & 1 deletion indexer/packages/kafka/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export const TO_ENDER_TOPIC: string = 'to-ender';

export const ORDERBOOKS_WEBSOCKET_MESSAGE_VERSION: string = '1.0.0';
export const SUBACCOUNTS_WEBSOCKET_MESSAGE_VERSION: string = '2.4.0';
export const SUBACCOUNTS_WEBSOCKET_MESSAGE_VERSION: string = '3.0.0';
export const TRADES_WEBSOCKET_MESSAGE_VERSION: string = '2.1.0';
export const MARKETS_WEBSOCKET_MESSAGE_VERSION: string = '1.0.0';
export const CANDLES_WEBSOCKET_MESSAGE_VERSION: string = '1.0.0';
4 changes: 4 additions & 0 deletions indexer/packages/kafka/src/websocket-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export function generateSubaccountMessageContents(
order: OrderFromDatabase | undefined,
perpetualMarket: PerpetualMarketFromDatabase,
placementStatus: OrderPlaceV1_OrderPlacementStatus,
blockHeight: string | undefined,
): SubaccountMessageContents {
const orderTIF: TimeInForce = protocolTranslations.protocolOrderTIFToTIF(
redisOrder.order!.timeInForce,
Expand Down Expand Up @@ -89,6 +90,7 @@ export function generateSubaccountMessageContents(
triggerPrice: getTriggerPrice(redisOrder.order!, perpetualMarket),
},
],
...(blockHeight && { blockHeight }),
};
return contents;
}
Expand All @@ -98,12 +100,14 @@ export function createSubaccountWebsocketMessage(
order: OrderFromDatabase | undefined,
perpetualMarket: PerpetualMarketFromDatabase,
placementStatus: OrderPlaceV1_OrderPlacementStatus,
blockHeight: string | undefined,
): Buffer {
const contents: SubaccountMessageContents = generateSubaccountMessageContents(
redisOrder,
order,
perpetualMarket,
placementStatus,
blockHeight,
);

const subaccountMessage: SubaccountMessage = SubaccountMessage.fromPartial({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,12 +230,6 @@ describe('protocolTranslations', () => {
describe('orderTypeToProtocolConditionType', () => {
it.each([
['LIMIT', OrderType.LIMIT, IndexerOrder_ConditionType.CONDITION_TYPE_UNSPECIFIED],
['HARD_TRADE', OrderType.HARD_TRADE, IndexerOrder_ConditionType.CONDITION_TYPE_UNSPECIFIED],
[
'FAILED_HARD_TRADE',
OrderType.FAILED_HARD_TRADE,
IndexerOrder_ConditionType.CONDITION_TYPE_UNSPECIFIED,
],
['MARKET', OrderType.MARKET, IndexerOrder_ConditionType.CONDITION_TYPE_UNSPECIFIED],
[
'TRAILING_STOP',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { clearData, migrate, teardown } from '../../src/helpers/db-helpers';
import { clear, getLatestBlockHeight, updateBlockHeight } from '../../src/loops/block-height-refresher';
import { defaultBlock2 } from '../helpers/constants';
import { seedData } from '../helpers/mock-generators';
import config from '../../src/config';

describe('blockHeightRefresher', () => {
beforeAll(async () => {
await migrate();
await seedData();
await updateBlockHeight();
});

afterAll(async () => {
await clearData();
await teardown();
});

describe('getLatestBlockHeight', () => {
it('successfully gets the latest block height after update', async () => {
await updateBlockHeight();
expect(getLatestBlockHeight()).toBe(defaultBlock2.blockHeight);
});
});

describe('clear', () => {
it('throws an error if block height does not exist', () => {
clear();
expect(() => getLatestBlockHeight()).toThrowError('Unable to find latest block height');
});

it('throws an error when clear is called in non-test environment', () => {
const originalEnv = config.NODE_ENV;
config.NODE_ENV = 'production';
expect(() => clear()).toThrowError('clear cannot be used in non-test env');
config.NODE_ENV = originalEnv;
});
});
});
1 change: 1 addition & 0 deletions indexer/packages/postgres/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export const postgresConfigSchema = {
ASSET_REFRESHER_INTERVAL_MS: parseInteger({ default: 30_000 }), // 30 seconds
MARKET_REFRESHER_INTERVAL_MS: parseInteger({ default: 30_000 }), // 30 seconds
LIQUIDITY_TIER_REFRESHER_INTERVAL_MS: parseInteger({ default: 30_000 }), // 30 seconds
BLOCK_HEIGHT_REFRESHER_INTERVAL_MS: parseInteger({ default: 1_000 }), // 1 second
USE_READ_REPLICA: parseBoolean({ default: false }),

// Optional environment variables.
Expand Down
1 change: 1 addition & 0 deletions indexer/packages/postgres/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export * as TradingRewardAggregationTable from './stores/trading-reward-aggregat

export * as perpetualMarketRefresher from './loops/perpetual-market-refresher';
export * as assetRefresher from './loops/asset-refresher';
export * as blockHeightRefresher from './loops/block-height-refresher';
export * as liquidityTierRefresher from './loops/liquidity-tier-refresher';

export * as uuid from './helpers/uuid';
Expand Down
3 changes: 0 additions & 3 deletions indexer/packages/postgres/src/lib/protocol-translations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,7 @@ const ORDER_TYPE_TO_CONDITION_TYPE_MAP: Record<OrderType, IndexerOrder_Condition

// TODO(IND-356): Remove irrelevant order types
// Unused order types
[OrderType.HARD_TRADE]: IndexerOrder_ConditionType.CONDITION_TYPE_UNSPECIFIED,
[OrderType.FAILED_HARD_TRADE]: IndexerOrder_ConditionType.CONDITION_TYPE_UNSPECIFIED,
[OrderType.MARKET]: IndexerOrder_ConditionType.CONDITION_TYPE_UNSPECIFIED,
[OrderType.TRANSFER_PLACEHOLDER]: IndexerOrder_ConditionType.CONDITION_TYPE_UNSPECIFIED,
[OrderType.TRAILING_STOP]: IndexerOrder_ConditionType.CONDITION_TYPE_UNSPECIFIED,
};

Expand Down
61 changes: 61 additions & 0 deletions indexer/packages/postgres/src/loops/block-height-refresher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import {
stats,
logger,
NodeEnv,
} from '@dydxprotocol-indexer/base';

import config from '../config';
import * as BlockTable from '../stores/block-table';
import { BlockFromDatabase, Options } from '../types';
import { startUpdateLoop } from './loopHelper';

let latestBlockHeight: string = '';

/**
* Refresh loop to cache the latest block height from the database in-memory.
*/
export async function start(): Promise<void> {
await startUpdateLoop(
updateBlockHeight,
config.BLOCK_HEIGHT_REFRESHER_INTERVAL_MS,
'updateBlockHeight',
);
}

/**
* Updates in-memory latest block height.
*/
export async function updateBlockHeight(options?: Options): Promise<void> {
const startTime: number = Date.now();
try {
const latestBlock: BlockFromDatabase = await BlockTable.getLatest(
options || { readReplica: true },
);
latestBlockHeight = latestBlock.blockHeight;
stats.timing(`${config.SERVICE_NAME}.loops.update_block_height`, Date.now() - startTime);
// eslint-disable-next-line no-empty
} catch (error) { }
}

/**
* Gets the latest block height.
*/
export function getLatestBlockHeight(): string {
if (!latestBlockHeight) {
const message: string = 'Unable to find latest block height';
logger.error({
at: 'block-height-refresher#getLatestBlockHeight',
message,
});
throw new Error(message);
}
return latestBlockHeight;
}

export function clear(): void {
if (config.NODE_ENV !== NodeEnv.TEST) {
throw new Error('clear cannot be used in non-test env');
}

latestBlockHeight = '';
}
3 changes: 0 additions & 3 deletions indexer/packages/postgres/src/types/order-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@ export enum OrderType {
TRAILING_STOP = 'TRAILING_STOP',
TAKE_PROFIT = 'TAKE_PROFIT',
TAKE_PROFIT_MARKET = 'TAKE_PROFIT_MARKET',
HARD_TRADE = 'HARD_TRADE',
FAILED_HARD_TRADE = 'FAILED_HARD_TRADE',
TRANSFER_PLACEHOLDER = 'TRANSFER_PLACEHOLDER',
}

export enum TimeInForce {
Expand Down
Loading

0 comments on commit 7bf3954

Please sign in to comment.