Skip to content

Commit e3ab39c

Browse files
committed
refactor(cardano-services): rework cli argument parsing and relative tests
1 parent 02d17d4 commit e3ab39c

File tree

12 files changed

+1178
-2682
lines changed

12 files changed

+1178
-2682
lines changed

.github/workflows/continuous-integration-unit-tests.yaml

+1
Original file line numberDiff line numberDiff line change
@@ -48,5 +48,6 @@ jobs:
4848
run: |
4949
yarn test:build:verify
5050
yarn test --forceExit
51+
yarn workspace @cardano-sdk/cardano-services test:cli
5152
env:
5253
NODE_OPTIONS: '--max_old_space_size=8192'
+9-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
1-
module.exports = {
1+
const common = {
22
...require('../../test/jest.config'),
33
globalSetup: './test/jest-setup/jest-setup.ts',
44
globalTeardown: './test/jest-setup/jest-teardown.ts',
55
setupFilesAfterEnv: ['./test/jest-setup/matchers.ts']
66
};
7+
8+
module.exports = {
9+
...common,
10+
projects: [
11+
{ ...common, displayName: 'cli', testMatch: ['<rootDir>/test/cli.test.ts'] },
12+
{ ...common, displayName: 'unit', testPathIgnorePatterns: ['cli.test'] }
13+
]
14+
};

packages/cardano-services/package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,9 @@
4747
"preview:dev": "FILES='-f ../../compose/dev.yml -f dev.yml' yarn preview:up",
4848
"preview:up": "NETWORK=preview SUBMIT_API_ARGS='--testnet-magic 2' yarn compose:up",
4949
"preview:down": "NETWORK=preview yarn compose:down",
50-
"test": "jest --runInBand -c ./jest.config.js",
50+
"test": "jest --runInBand -c ./jest.config.js --selectProjects unit",
5151
"test:build:verify": "tsc --build ./test",
52+
"test:cli": "jest --runInBand -c ./jest.config.js --selectProjects cli",
5253
"test:debug": "DEBUG=true yarn test",
5354
"test:e2e": "echo 'test:e2e' command not implemented yet",
5455
"test:load": "jest -c ./load.jest.config.js --runInBand",

packages/cardano-services/src/Program/options/common.ts

+11-14
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {
1111
import { Seconds } from '@cardano-sdk/core';
1212
import { BuildInfo as ServiceBuildInfo } from '../../Http';
1313
import { addOptions, newOption } from './util';
14-
import { buildInfoValidator, cacheTtlValidator } from '../../util/validators';
14+
import { buildInfoValidator, floatValidator, integerValidator, urlValidator } from '../../util/validators';
1515
import { loggerMethodNames } from '@cardano-sdk/util';
1616

1717
export const ENABLE_METRICS_DEFAULT = false;
@@ -21,17 +21,18 @@ export const LAST_ROS_EPOCHS_DEFAULT = 10;
2121
enum Descriptions {
2222
ApiUrl = 'API URL',
2323
BuildInfo = 'Service build info',
24+
DumpOnly = 'Dumps the input arguments and exits. Used for tests',
25+
EnableMetrics = 'Enable Prometheus Metrics',
2426
LastRosEpochs = 'Number of epochs over which lastRos is computed',
2527
LoggerMinSeverity = 'Log level',
26-
HealthCheckCacheTtl = 'Health check cache TTL in seconds between 1 and 10',
27-
EnableMetrics = 'Enable Prometheus Metrics',
2828
ServiceDiscoveryBackoffFactor = 'Exponential backoff factor for service discovery',
2929
ServiceDiscoveryTimeout = 'Timeout for service discovery attempts'
3030
}
3131

3232
export type CommonProgramOptions = {
3333
apiUrl: URL;
3434
buildInfo?: ServiceBuildInfo;
35+
dumpOnly?: boolean;
3536
enableMetrics?: boolean;
3637
lastRosEpochs?: number;
3738
loggerMinSeverity?: LogLevel;
@@ -41,27 +42,23 @@ export type CommonProgramOptions = {
4142

4243
export const withCommonOptions = (command: Command, apiUrl: URL) => {
4344
addOptions(command, [
44-
newOption('--api-url <apiUrl>', Descriptions.ApiUrl, 'API_URL', (url) => new URL(url), apiUrl),
45+
newOption('--api-url <apiUrl>', Descriptions.ApiUrl, 'API_URL', urlValidator(Descriptions.ApiUrl), apiUrl),
4546
newOption('--build-info <buildInfo>', Descriptions.BuildInfo, 'BUILD_INFO', buildInfoValidator),
47+
newOption('--dump-only <true/false>', Descriptions.DumpOnly, 'DUMP_ONLY', (dumpOnly) =>
48+
stringOptionToBoolean(dumpOnly, Programs.ProviderServer, Descriptions.DumpOnly)
49+
),
4650
newOption(
4751
'--enable-metrics <true/false>',
4852
Descriptions.EnableMetrics,
4953
'ENABLE_METRICS',
5054
(enableMetrics) => stringOptionToBoolean(enableMetrics, Programs.ProviderServer, Descriptions.EnableMetrics),
5155
ENABLE_METRICS_DEFAULT
5256
),
53-
newOption(
54-
'--health-check-cache-ttl <healthCheckCacheTTL>',
55-
Descriptions.HealthCheckCacheTtl,
56-
'HEALTH_CHECK_CACHE_TTL',
57-
(ttl: string) => cacheTtlValidator(ttl, { lowerBound: 1, upperBound: 120 }, Descriptions.HealthCheckCacheTtl),
58-
DEFAULT_HEALTH_CHECK_CACHE_TTL
59-
),
6057
newOption(
6158
'--last-ros-epochs <lastRosEpochs>',
6259
Descriptions.LastRosEpochs,
6360
'LAST_ROS_EPOCHS',
64-
(lastRosEpochs) => Number.parseInt(lastRosEpochs, 10),
61+
integerValidator(Descriptions.LastRosEpochs),
6562
LAST_ROS_EPOCHS_DEFAULT
6663
),
6764
newOption(
@@ -78,14 +75,14 @@ export const withCommonOptions = (command: Command, apiUrl: URL) => {
7875
'--service-discovery-backoff-factor <serviceDiscoveryBackoffFactor>',
7976
Descriptions.ServiceDiscoveryBackoffFactor,
8077
'SERVICE_DISCOVERY_BACKOFF_FACTOR',
81-
(factor) => Number.parseFloat(factor),
78+
floatValidator(Descriptions.ServiceDiscoveryBackoffFactor),
8279
SERVICE_DISCOVERY_BACKOFF_FACTOR_DEFAULT
8380
),
8481
newOption(
8582
'--service-discovery-timeout <serviceDiscoveryTimeout>',
8683
Descriptions.ServiceDiscoveryTimeout,
8784
'SERVICE_DISCOVERY_TIMEOUT',
88-
(interval) => Number.parseInt(interval, 10),
85+
integerValidator(Descriptions.ServiceDiscoveryTimeout),
8986
SERVICE_DISCOVERY_TIMEOUT_DEFAULT
9087
)
9188
]);

packages/cardano-services/src/Program/options/ogmios.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Command } from 'commander';
22
import { Ogmios } from '@cardano-sdk/ogmios';
33
import { addOptions, newOption } from './util';
4+
import { urlValidator } from '../../util/validators';
45

56
const OGMIOS_URL_DEFAULT = (() => {
67
const connection = Ogmios.createConnectionObject();
@@ -28,7 +29,7 @@ export const withOgmiosOptions = (command: Command) =>
2829
'--ogmios-url <ogmiosUrl>',
2930
OgmiosOptionDescriptions.Url,
3031
'OGMIOS_URL',
31-
(url) => new URL(url),
32+
urlValidator(OgmiosOptionDescriptions.Url),
3233
new URL(OGMIOS_URL_DEFAULT)
3334
).conflicts('ogmiosSrvServiceName')
3435
]);

packages/cardano-services/src/Program/options/postgres.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Command } from 'commander';
22
import { addOptions, newOption } from './util';
3-
import { existingFileValidator } from '../../util/validators';
3+
import { existingFileValidator, integerValidator } from '../../util/validators';
44

55
export enum PostgresOptionDescriptions {
66
ConnectionString = 'PostgreSQL Connection string',
@@ -120,7 +120,7 @@ export const withPostgresOptions = (command: Command, suffixes: ConnectionNames[
120120
`--postgres-pool-max${cliSuffix} <postgresPoolMax${suffix}>`,
121121
PostgresOptionDescriptions.PoolMax + descSuffix,
122122
`POSTGRES_POOL_MAX${envSuffix}`,
123-
(max) => Number.parseInt(max, 10)
123+
integerValidator(PostgresOptionDescriptions.PoolMax + descSuffix)
124124
),
125125
newOption(
126126
`--postgres-port${cliSuffix} <postgresPort${suffix}>`,

packages/cardano-services/src/Program/options/stakePoolMetadata.ts

+7-9
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { Command } from 'commander';
22
import { MissingProgramOption } from '../errors';
33
import { STAKE_POOL_METADATA_QUEUE } from '@cardano-sdk/projection-typeorm';
4-
import { URL } from 'url';
54
import { addOptions, newOption } from './util';
5+
import { urlValidator } from '../../util/validators';
66

77
export enum StakePoolMetadataOptionDescriptions {
88
Mode = 'This mode governs where the stake pool metadata is fetched from',
@@ -32,20 +32,18 @@ export const withStakePoolMetadataOptions = (command: Command) => {
3232
(mode: string) => StakePoolMetadataFetchMode[mode.toUpperCase() as keyof typeof StakePoolMetadataFetchMode],
3333
'direct'
3434
).choices(['direct', 'smash']),
35-
newOption('--smash-url <smashUrl>', StakePoolMetadataOptionDescriptions.Url, 'SMASH_URL', (url) =>
36-
new URL(url).toString()
35+
newOption(
36+
'--smash-url <smashUrl>',
37+
StakePoolMetadataOptionDescriptions.Url,
38+
'SMASH_URL',
39+
urlValidator(StakePoolMetadataOptionDescriptions.Url, true)
3740
)
3841
]);
3942

4043
return command;
4144
};
4245

4346
export const checkProgramOptions = (metadataFetchMode: StakePoolMetadataFetchMode, smashUrl: string | undefined) => {
44-
if (!metadataFetchMode) throw new MissingProgramOption(STAKE_POOL_METADATA_QUEUE, 'medata-fetch-mode');
45-
4647
if (metadataFetchMode === StakePoolMetadataFetchMode.SMASH && !smashUrl)
47-
throw new MissingProgramOption(
48-
STAKE_POOL_METADATA_QUEUE,
49-
`smash-url to be set when medata-fetch-mode is smash ${smashUrl}`
50-
);
48+
throw new MissingProgramOption(STAKE_POOL_METADATA_QUEUE, 'smash-url to be set when metadata-fetch-mode is smash');
5149
};

packages/cardano-services/src/Program/programs/blockfrostWorker.ts

-2
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,6 @@ export const loadBlockfrostWorker = async (args: BlockfrostWorkerArgs, deps: Loa
6767
BlockfrostWorkerOptionDescriptions.BlockfrostApiKey
6868
]);
6969

70-
if (!args.network) throw new MissingProgramOption(blockfrostWorker, BlockfrostWorkerOptionDescriptions.Network);
71-
7270
if (!db)
7371
throw new MissingProgramOption(blockfrostWorker, [
7472
PostgresOptionDescriptions.ConnectionString,

packages/cardano-services/src/Program/programs/types.ts

+2
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,11 @@ export enum ProviderServerOptionDescriptions {
5151
DisableStakePoolMetricApy = 'Omit this metric for improved query performance',
5252
EpochPollInterval = 'Epoch poll interval',
5353
HandleProviderServerUrl = 'URL for the Handle provider server',
54+
HealthCheckCacheTtl = 'Health check cache TTL in seconds between 1 and 10',
5455
PaginationPageSizeLimit = 'Pagination page size limit shared across all providers',
5556
SubmitApiUrl = 'cardano-submit-api URL',
5657
TokenMetadataCacheTtl = 'Token Metadata API cache TTL in seconds',
58+
TokenMetadataRequestTimeout = 'Token Metadata request timeout in milliseconds',
5759
TokenMetadataServerUrl = 'Token Metadata API server URL',
5860
UseTypeOrmStakePoolProvider = 'Enables the TypeORM Stake Pool Provider',
5961
UseBlockfrost = 'Enables Blockfrost cached data DB',

0 commit comments

Comments
 (0)