@chainlink/external-adapter-framework 0.0.25 → 0.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/adapter.d.ts +139 -0
  2. package/background-executor.d.ts +9 -0
  3. package/cache/factory.d.ts +6 -0
  4. package/cache/index.d.ts +94 -0
  5. package/cache/local.d.ts +23 -0
  6. package/cache/metrics.d.ts +27 -0
  7. package/cache/redis.d.ts +16 -0
  8. package/config/index.d.ts +258 -0
  9. package/config/provider-limits.d.ts +27 -0
  10. package/examples/bank-frick/accounts.d.ts +39 -0
  11. package/examples/bank-frick/config/index.d.ts +4 -0
  12. package/examples/bank-frick/index.d.ts +2 -0
  13. package/examples/bank-frick/util.d.ts +4 -0
  14. package/examples/coingecko/src/config/index.d.ts +2 -0
  15. package/examples/coingecko/src/cryptoUtils.d.ts +31 -0
  16. package/examples/coingecko/src/endpoint/coins.d.ts +9 -0
  17. package/examples/coingecko/src/endpoint/crypto-marketcap.d.ts +3 -0
  18. package/examples/coingecko/src/endpoint/crypto-volume.d.ts +3 -0
  19. package/examples/coingecko/src/endpoint/crypto.d.ts +3 -0
  20. package/examples/coingecko/src/endpoint/dominance.d.ts +3 -0
  21. package/examples/coingecko/src/endpoint/global-marketcap.d.ts +3 -0
  22. package/examples/coingecko/src/endpoint/index.d.ts +6 -0
  23. package/examples/coingecko/src/globalUtils.d.ts +27 -0
  24. package/examples/coingecko/src/index.d.ts +4 -0
  25. package/examples/coingecko-old/batch-warming.d.ts +7 -0
  26. package/examples/coingecko-old/index.d.ts +2 -0
  27. package/examples/coingecko-old/rest.d.ts +12 -0
  28. package/examples/ncfx/config/index.d.ts +12 -0
  29. package/examples/ncfx/index.d.ts +13 -0
  30. package/examples/ncfx/websocket.d.ts +47 -0
  31. package/index.d.ts +11 -0
  32. package/metrics/constants.d.ts +16 -0
  33. package/metrics/index.d.ts +15 -0
  34. package/metrics/util.d.ts +7 -0
  35. package/package.json +2 -1
  36. package/rate-limiting/background/fixed-frequency.d.ts +11 -0
  37. package/rate-limiting/index.d.ts +55 -0
  38. package/rate-limiting/metrics.d.ts +3 -0
  39. package/rate-limiting/request/simple-counting.d.ts +21 -0
  40. package/transports/batch-warming.d.ts +35 -0
  41. package/transports/index.d.ts +73 -0
  42. package/transports/metrics.d.ts +22 -0
  43. package/transports/rest.d.ts +44 -0
  44. package/transports/util.d.ts +9 -0
  45. package/transports/websocket.d.ts +80 -0
  46. package/util/index.d.ts +12 -0
  47. package/util/logger.d.ts +42 -0
  48. package/util/request.d.ts +56 -0
  49. package/util/subscription-set/expiring-sorted-set.d.ts +22 -0
  50. package/util/subscription-set/subscription-set.d.ts +18 -0
  51. package/util/test-payload-loader.d.ts +25 -0
  52. package/validation/error.d.ts +50 -0
  53. package/validation/index.d.ts +5 -0
  54. package/validation/input-params.d.ts +15 -0
  55. package/validation/override-functions.d.ts +3 -0
  56. package/validation/validator.d.ts +47 -0
@@ -0,0 +1,31 @@
1
+ import { AxiosRequestConfig, AxiosResponse } from 'axios';
2
+ import { AdapterConfig } from '../../../config';
3
+ import { InputParameters } from '../../../validation';
4
+ export interface CryptoRequestParams {
5
+ coinid?: string;
6
+ base?: string;
7
+ quote: string;
8
+ }
9
+ export declare const cryptoInputParams: InputParameters;
10
+ export interface ProviderRequestBody {
11
+ ids: string;
12
+ vs_currencies: string;
13
+ include_market_cap?: boolean;
14
+ include_24hr_vol?: boolean;
15
+ }
16
+ export interface ProviderResponseBody {
17
+ [base: string]: {
18
+ [quote: string]: number;
19
+ };
20
+ }
21
+ interface ResultEntryWithoutOverrides {
22
+ value: number;
23
+ params: {
24
+ quote: string;
25
+ base?: string;
26
+ coinid?: string;
27
+ };
28
+ }
29
+ export declare const buildBatchedRequestBody: (params: CryptoRequestParams[], config: AdapterConfig) => AxiosRequestConfig<ProviderRequestBody>;
30
+ export declare const constructEntry: (res: AxiosResponse<ProviderResponseBody>, requestPayload: CryptoRequestParams, resultPath: string) => ResultEntryWithoutOverrides | undefined;
31
+ export {};
@@ -0,0 +1,9 @@
1
+ import { AdapterEndpoint } from '../../../../../src/adapter';
2
+ import { InputParameters } from '../../../../../src/validation';
3
+ export declare const inputParameters: InputParameters;
4
+ export interface CoinsResponse {
5
+ id: string;
6
+ symbol: string;
7
+ name: string;
8
+ }
9
+ export declare const endpoint: AdapterEndpoint<import("../../../../util/request").AdapterRequestData, CoinsResponse[], import("../../../../config").SettingsMap>;
@@ -0,0 +1,3 @@
1
+ import { AdapterEndpoint } from '../../../../adapter';
2
+ import { CryptoRequestParams } from '../cryptoUtils';
3
+ export declare const endpoint: AdapterEndpoint<CryptoRequestParams, unknown, import("../../../../config").SettingsMap>;
@@ -0,0 +1,3 @@
1
+ import { AdapterEndpoint } from '../../../../adapter';
2
+ import { CryptoRequestParams } from '../cryptoUtils';
3
+ export declare const endpoint: AdapterEndpoint<CryptoRequestParams, unknown, import("../../../../config").SettingsMap>;
@@ -0,0 +1,3 @@
1
+ import { AdapterEndpoint } from '../../../../adapter';
2
+ import { CryptoRequestParams } from '../cryptoUtils';
3
+ export declare const endpoint: AdapterEndpoint<CryptoRequestParams, unknown, import("../../../../config").SettingsMap>;
@@ -0,0 +1,3 @@
1
+ import { AdapterEndpoint } from '../../../../adapter';
2
+ import { AdapterRequestParams } from '../globalUtils';
3
+ export declare const endpoint: AdapterEndpoint<AdapterRequestParams, unknown, import("../../../../config").SettingsMap>;
@@ -0,0 +1,3 @@
1
+ import { AdapterEndpoint } from '../../../../adapter';
2
+ import { AdapterRequestParams } from '../globalUtils';
3
+ export declare const endpoint: AdapterEndpoint<AdapterRequestParams, unknown, import("../../../../config").SettingsMap>;
@@ -0,0 +1,6 @@
1
+ export { endpoint as coins } from './coins';
2
+ export { endpoint as crypto } from './crypto';
3
+ export { endpoint as cryptoMarketcap } from './crypto-marketcap';
4
+ export { endpoint as globalMarketcap } from './global-marketcap';
5
+ export { endpoint as dominance } from './dominance';
6
+ export { endpoint as cryptoVolume } from './crypto-volume';
@@ -0,0 +1,27 @@
1
+ import { AxiosRequestConfig, AxiosResponse } from 'axios';
2
+ import { InputParameters } from '../../../validation';
3
+ export declare const inputParameters: InputParameters;
4
+ export interface AdapterRequestParams {
5
+ market: string;
6
+ }
7
+ export interface ProviderResponseBody {
8
+ data: {
9
+ active_cryptocurrencies: number;
10
+ upcoming_icos: number;
11
+ ongoing_icos: number;
12
+ ended_icos: number;
13
+ markets: number;
14
+ total_market_cap: Record<string, number>;
15
+ total_volume: Record<string, number>;
16
+ market_cap_percentage: Record<string, number>;
17
+ market_cap_change_percentage_24h_usd: number;
18
+ updated_at: number;
19
+ };
20
+ }
21
+ interface ResultEntry {
22
+ value: number;
23
+ params: AdapterRequestParams;
24
+ }
25
+ export declare const buildGlobalRequestBody: (apiKey?: string | undefined) => AxiosRequestConfig<never>;
26
+ export declare const constructEntry: (res: AxiosResponse<ProviderResponseBody>, requestPayload: AdapterRequestParams, resultPath: 'total_market_cap' | 'market_cap_percentage') => ResultEntry | undefined;
27
+ export {};
@@ -0,0 +1,4 @@
1
+ /// <reference types="node" />
2
+ import { Adapter } from '../../../../src/adapter';
3
+ export declare const adapter: Adapter<import("../../../config").SettingsMap>;
4
+ export declare const server: () => Promise<import("fastify").FastifyInstance<import("http").Server, import("http").IncomingMessage, import("http").ServerResponse, import("fastify").FastifyLoggerInstance> | undefined>;
@@ -0,0 +1,7 @@
1
+ import { AdapterEndpoint } from '../../adapter';
2
+ interface AdapterRequestParams {
3
+ base: string;
4
+ quote: string;
5
+ }
6
+ export declare const batchEndpoint: AdapterEndpoint<AdapterRequestParams, unknown, import("../../config").SettingsMap>;
7
+ export {};
@@ -0,0 +1,2 @@
1
+ import { Adapter } from '../../adapter';
2
+ export declare const adapter: Adapter<import("../../config").SettingsMap>;
@@ -0,0 +1,12 @@
1
+ import { AdapterEndpoint } from '../../adapter';
2
+ interface AdapterRequestParams {
3
+ base: string;
4
+ quote: string;
5
+ }
6
+ interface ProviderResponseBody {
7
+ [base: string]: {
8
+ [quote: string]: number;
9
+ };
10
+ }
11
+ export declare const restEndpoint: AdapterEndpoint<AdapterRequestParams, ProviderResponseBody, import("../../config").SettingsMap>;
12
+ export {};
@@ -0,0 +1,12 @@
1
+ export declare const customSettings: {
2
+ readonly USERNAME: {
3
+ readonly description: "Username for the NCFX API";
4
+ readonly type: "string";
5
+ readonly required: true;
6
+ };
7
+ readonly PASSWORD: {
8
+ readonly description: "Password for the NCFX API";
9
+ readonly type: "string";
10
+ readonly required: true;
11
+ };
12
+ };
@@ -0,0 +1,13 @@
1
+ import { Adapter } from '../../adapter';
2
+ export declare const adapter: Adapter<{
3
+ readonly USERNAME: {
4
+ readonly description: "Username for the NCFX API";
5
+ readonly type: "string";
6
+ readonly required: true;
7
+ };
8
+ readonly PASSWORD: {
9
+ readonly description: "Password for the NCFX API";
10
+ readonly type: "string";
11
+ readonly required: true;
12
+ };
13
+ }>;
@@ -0,0 +1,47 @@
1
+ import { AdapterEndpoint } from '../../adapter';
2
+ import { WebSocketTransport } from '../../transports/websocket';
3
+ import { InputParameters } from '../../validation';
4
+ interface AdapterRequestParams {
5
+ base: string;
6
+ quote: string;
7
+ }
8
+ export declare const inputParameters: InputParameters;
9
+ interface ProviderMessage {
10
+ timestamp: string;
11
+ currencyPair: string;
12
+ bid: number;
13
+ offer: number;
14
+ mid: number;
15
+ changes: [
16
+ {
17
+ period: string;
18
+ change: number;
19
+ percentage: number;
20
+ }
21
+ ];
22
+ }
23
+ export declare const websocketTransport: WebSocketTransport<AdapterRequestParams, ProviderMessage[], {
24
+ readonly USERNAME: {
25
+ readonly description: "Username for the NCFX API";
26
+ readonly type: "string";
27
+ readonly required: true;
28
+ };
29
+ readonly PASSWORD: {
30
+ readonly description: "Password for the NCFX API";
31
+ readonly type: "string";
32
+ readonly required: true;
33
+ };
34
+ }>;
35
+ export declare const webSocketEndpoint: AdapterEndpoint<AdapterRequestParams, unknown, {
36
+ readonly USERNAME: {
37
+ readonly description: "Username for the NCFX API";
38
+ readonly type: "string";
39
+ readonly required: true;
40
+ };
41
+ readonly PASSWORD: {
42
+ readonly description: "Password for the NCFX API";
43
+ readonly type: "string";
44
+ readonly required: true;
45
+ };
46
+ }>;
47
+ export {};
package/index.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { FastifyInstance } from 'fastify';
2
+ import { Adapter, AdapterDependencies } from './adapter';
3
+ /**
4
+ * Main function for the framework.
5
+ * Initializes config and dependencies, uses those to initialize Transports, and starts listening for requests.
6
+ *
7
+ * @param adapter - an object describing an External Adapter
8
+ * @param dependencies - an optional object with adapter dependencies to inject
9
+ * @returns a Promise that resolves to the http.Server listening for connections
10
+ */
11
+ export declare const expose: (adapter: Adapter, dependencies?: Partial<AdapterDependencies> | undefined) => Promise<FastifyInstance | undefined>;
@@ -0,0 +1,16 @@
1
+ export declare enum HttpRequestType {
2
+ CACHE_HIT = "cacheHit",
3
+ DATA_PROVIDER_HIT = "dataProviderHit",
4
+ ADAPTER_ERROR = "adapterError",
5
+ INPUT_ERROR = "inputError",
6
+ RATE_LIMIT_ERROR = "rateLimitError",
7
+ DP_ERROR = "dataProviderError",
8
+ TIMEOUT_ERROR = "timeoutError",
9
+ CONNECTION_ERROR = "connectionError",
10
+ CUSTOM_ERROR = "customError"
11
+ }
12
+ /**
13
+ * Maxiumum number of characters that a feedId can contain.
14
+ */
15
+ export declare const MAX_FEED_ID_LENGTH = 300;
16
+ export declare const requestDurationBuckets: number[];
@@ -0,0 +1,15 @@
1
+ import * as client from 'prom-client';
2
+ import { AdapterRequest } from '../util';
3
+ import { AdapterConfig } from '../config';
4
+ import { FastifyReply, HookHandlerDoneFunction } from 'fastify';
5
+ export declare function setupMetricsServer(name: string, config: AdapterConfig): void;
6
+ export declare const setupMetrics: (name: string, config: AdapterConfig) => void;
7
+ /**
8
+ * Builds metrics middleware that records end to end EA response times
9
+ * and count of requests
10
+ *
11
+ * @returns the cache middleware function
12
+ */
13
+ export declare const buildMetricsMiddleware: (req: AdapterRequest, res: FastifyReply, done: HookHandlerDoneFunction) => void;
14
+ export declare const httpRequestsTotal: client.Counter<"type" | "method" | "feed_id" | "status_code" | "provider_status_code" | "retry" | "is_cache_warming">;
15
+ export declare const httpRequestDurationSeconds: client.Histogram<string>;
@@ -0,0 +1,7 @@
1
+ import { AdapterMetricsMeta, AdapterRequestData } from '../util';
2
+ import { AdapterEndpoint } from '../adapter';
3
+ import { AdapterConfig, SettingsMap } from '../config';
4
+ export declare const getMetricsMeta: <Params, Result, CustomSettings extends SettingsMap>({ adapterEndpoint, adapterConfig, }: {
5
+ adapterEndpoint: AdapterEndpoint<Params, Result, CustomSettings>;
6
+ adapterConfig: AdapterConfig<CustomSettings>;
7
+ }, data: AdapterRequestData) => AdapterMetricsMeta;
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "@chainlink/external-adapter-framework",
3
- "version": "0.0.25",
3
+ "version": "0.0.27",
4
4
  "main": "dist/index.js",
5
5
  "license": "MIT",
6
6
  "dependencies": {
7
+ "ajv": "^8.11.0",
7
8
  "axios": "^0.27.2",
8
9
  "fastify": "^4.5.3",
9
10
  "ioredis": "^5.0.4",
@@ -0,0 +1,11 @@
1
+ import { AdapterRateLimitTier, BackgroundExecuteRateLimiter } from '..';
2
+ import { AdapterEndpoint } from '../../adapter';
3
+ import { SettingsMap } from '../../config';
4
+ export declare const DEFAULT_SHARED_MS_BETWEEN_REQUESTS = 5000;
5
+ export declare class FixedFrequencyRateLimiter implements BackgroundExecuteRateLimiter {
6
+ msBetweenRequestsMap: {
7
+ [endpointName: string]: number;
8
+ };
9
+ initialize<Params, Result, CustomSettings extends SettingsMap>(endpoints: AdapterEndpoint<Params, Result, CustomSettings>[], limits?: AdapterRateLimitTier): this;
10
+ msUntilNextExecution(endpointName: string): number;
11
+ }
@@ -0,0 +1,55 @@
1
+ import { AdapterEndpoint } from '../adapter';
2
+ import { AdapterConfig, SettingsMap } from '../config';
3
+ export * from './request/simple-counting';
4
+ export * from './background/fixed-frequency';
5
+ export interface AdapterRateLimitTier {
6
+ rateLimit1s?: number;
7
+ rateLimit1m?: number;
8
+ rateLimit1h?: number;
9
+ note?: string;
10
+ }
11
+ /**
12
+ * Common interface for all RateLimiter classes to implement
13
+ */
14
+ export interface RateLimiter {
15
+ /**
16
+ * Method to ensure all RateLimiters can be initialized in the same manner.
17
+ *
18
+ * @param limits - settings for how much throughput to allow for the Adapter
19
+ * @param endpoints - list of adapter endpoints
20
+ */
21
+ initialize<Params, Result, CustomSettings extends SettingsMap>(endpoints: AdapterEndpoint<Params, Result, CustomSettings>[], limits: AdapterRateLimitTier): this;
22
+ }
23
+ /**
24
+ * RequestRateLimiters perform checks agains imminent outbound requests for any transport.
25
+ */
26
+ export interface RequestRateLimiter extends RateLimiter {
27
+ /**
28
+ * This method will check using whatever strategy is implemented to determine if
29
+ * this request can be processed. If so, it returns true; if not, returns false.
30
+ */
31
+ isUnderLimits(): boolean;
32
+ }
33
+ /**
34
+ * BackgroundExecuteFrequencyRateLimiters will implement custom logic to calculate
35
+ * the period of time to wait between background executions for a transport.
36
+ */
37
+ export interface BackgroundExecuteRateLimiter extends RateLimiter {
38
+ msUntilNextExecution(endpointName: string): number;
39
+ }
40
+ /**
41
+ * This method will convert all possible settings for a rate limit tier and
42
+ * convert them all to requests per second, returning the lowest one
43
+ *
44
+ * @param limits - the rate limit tier set for the adapter
45
+ * @returns the most restrictive of the set options, in requests per second
46
+ */
47
+ export declare const consolidateTierLimits: (limits?: AdapterRateLimitTier | undefined) => number;
48
+ /**
49
+ * Validates rate limiting tiers specified for the adapter, and returns the one to use.
50
+ *
51
+ * @param config - the adapter config containing the env vars
52
+ * @param tiers - the adapter config listing the different available API tiers
53
+ * @returns the specified API tier, or a default one if none are specified
54
+ */
55
+ export declare const getRateLimitingTier: (config: AdapterConfig, tiers?: Record<string, AdapterRateLimitTier> | undefined) => AdapterRateLimitTier | undefined;
@@ -0,0 +1,3 @@
1
+ import * as client from 'prom-client';
2
+ export declare const retrieveCost: <ProviderResponseBody>(data: ProviderResponseBody) => number;
3
+ export declare const rateLimitCreditsSpentTotal: client.Counter<"feed_id" | "participant_id">;
@@ -0,0 +1,21 @@
1
+ import { AdapterRateLimitTier, RateLimiter } from '..';
2
+ import { AdapterEndpoint } from '../../adapter';
3
+ import { SettingsMap } from '../../config';
4
+ /**
5
+ * This rate limiter is the simplest stateful option.
6
+ * On startup, it'll compare the different thresholds for each tier, calculate them all
7
+ * in the finest window we'll use (seconds), and use the most restrictive one.
8
+ * This is so if the EA were to restart, we don't need to worry about persisting state
9
+ * for things like daily quotas. The downside is that this does not work well for bursty
10
+ * loads or spikes, in cases where e.g. the per second limit is high but daily quotas low.
11
+ */
12
+ export declare class SimpleCountingRateLimiter implements RateLimiter {
13
+ latestSecondInterval: number;
14
+ requestsThisSecond: number;
15
+ latestMinuteInterval: number;
16
+ requestsThisMinute: number;
17
+ perSecondLimit: number;
18
+ perMinuteLimit: number;
19
+ initialize<Params, Result, CustomSettings extends SettingsMap>(endpoints: AdapterEndpoint<Params, Result, CustomSettings>[], limits?: AdapterRateLimitTier): this;
20
+ isUnderLimits(): boolean;
21
+ }
@@ -0,0 +1,35 @@
1
+ import { AxiosRequestConfig, AxiosResponse } from 'axios';
2
+ import { Cache } from '../cache';
3
+ import { AdapterConfig, SettingsMap } from '../config';
4
+ import { BackgroundExecuteRateLimiter } from '../rate-limiting';
5
+ import { SubscriptionSet } from '../util';
6
+ import { AdapterRequest, ProviderResult } from '../util/request';
7
+ import { Transport } from './';
8
+ import { AdapterContext, AdapterDependencies } from '../adapter';
9
+ /**
10
+ * Transport implementation that takes incoming batches requests and keeps a warm cache of values.
11
+ * Within the setup function, adapter params are added to an set that also keeps track and expires values.
12
+ * In the background execute, the list of non-expired items in the set is fetched.
13
+ * Then, the list is passed through the `prepareRequest` function, that returns an AxiosRequestConfig.
14
+ * The Data Provider response is, they are passed through the `parseResponse` function to create a [[CacheEntry]] list.
15
+ * Finally, the items in that [[CacheEntry]] list are set in the Cache so the Adapter can fetch values from there.
16
+ *
17
+ * @typeParam AdapterParams - interface for the adapter request body
18
+ * @typeParam ProviderRequestBody - interface for the body of the request to the Data Provider
19
+ * @typeParam ProviderResponseBody - interface for the body of the Data Provider's response
20
+ */
21
+ export declare class BatchWarmingTransport<AdapterParams, ProviderRequestBody, ProviderResponseBody, CustomSettings extends SettingsMap> implements Transport<AdapterParams, ProviderResponseBody, CustomSettings> {
22
+ private config;
23
+ cache: Cache;
24
+ rateLimiter: BackgroundExecuteRateLimiter;
25
+ subscriptionSet: SubscriptionSet<AdapterParams>;
26
+ WARMER_ACTIVE: boolean;
27
+ constructor(config: {
28
+ prepareRequest: (params: AdapterParams[], context: AdapterContext<CustomSettings>) => AxiosRequestConfig<ProviderRequestBody>;
29
+ parseResponse: (params: AdapterParams[], res: AxiosResponse<ProviderResponseBody>, context: AdapterContext<CustomSettings>) => ProviderResult<AdapterParams>[];
30
+ });
31
+ initialize(dependencies: AdapterDependencies): Promise<void>;
32
+ hasBeenSetUp(req: AdapterRequest<AdapterParams>): Promise<boolean>;
33
+ setup(req: AdapterRequest<AdapterParams>, config: AdapterConfig<CustomSettings>): Promise<void>;
34
+ backgroundExecute(context: AdapterContext<CustomSettings>): Promise<number>;
35
+ }
@@ -0,0 +1,73 @@
1
+ import { FastifyReply } from 'fastify';
2
+ import { AdapterContext, AdapterDependencies, Adapter } from '../adapter';
3
+ import { CacheEntry } from '../cache';
4
+ import { AdapterConfig, SettingsMap } from '../config';
5
+ import { AdapterRequest, AdapterResponse, ProviderResult } from '../util/request';
6
+ export * from './batch-warming';
7
+ export * from './rest';
8
+ export * from './websocket';
9
+ /**
10
+ * Generic interface for a Transport.
11
+ * A Transport defines the way in which an AdapterEndpoint will process incoming requests to
12
+ * fetch data from a Data Provider. The setup phase will take care of the former, while the
13
+ * backgroundExecute will be in charge of the latter.
14
+ * This separation gives us the ability of splitting these concerns, and optionally parallelizing
15
+ * the reading and writing of data to a centralized Cache.
16
+ *
17
+ * @typeParam Params - the structure of the AdapterRequest's body
18
+ * @typeParam Result - the structure of the AdapterResponse's body
19
+ */
20
+ export interface Transport<Params, Result, CustomSettings extends SettingsMap> {
21
+ /**
22
+ * Initializes the transport in the Adapter context.
23
+ *
24
+ * @param dependencies - Adapter dependencies (e.g. cache instance)
25
+ * @param config - Adapter config containing env vars
26
+ * @returns an empty Promise
27
+ */
28
+ initialize: (dependencies: AdapterDependencies, config: AdapterConfig) => Promise<void>;
29
+ /**
30
+ * Checks if the Transport has already set up the incoming request.
31
+ * This will likely use the cacheKey generated in the provided request.
32
+ *
33
+ * @param req - the incoming AdapterRequest
34
+ * @returns a Promise that returns true if setup is in place
35
+ */
36
+ hasBeenSetUp: (req: AdapterRequest<Params>) => Promise<boolean>;
37
+ /**
38
+ * Sets up the incoming request within the Transport.
39
+ * In other words, it means that the Adapter has recognized this request, and will begin
40
+ * fetching the necessary data from a Data Provider.
41
+ *
42
+ * @param req - the incoming AdapterRequest
43
+ * @param config - common configuration for the Adapter as a whole
44
+ * @returns a Promise that _optionally_ returns an AdapterResponse, if the Transport has the capability of
45
+ * immediately fetching data and returning it without the background process.
46
+ */
47
+ setup: (req: AdapterRequest<Params>, config: AdapterConfig<CustomSettings>) => Promise<AdapterResponse<Result> | void>;
48
+ /**
49
+ * If the Transport relies on an async mechanism, implementing this function will make it
50
+ * so the background task executor calls it on Adapter startup.
51
+ *
52
+ * @param context - background context for the execution (e.g. endpoint name)
53
+ */
54
+ backgroundExecute?: (context: AdapterContext<CustomSettings>) => Promise<number>;
55
+ }
56
+ /**
57
+ * Helper method to build cache entries to set after getting a bunch of responses from a DP.
58
+ *
59
+ * @param results - a list of results coming from a DataProvider
60
+ * @param context - context for the Adapter
61
+ * @returns a list of CacheEntries of AdapterResponses
62
+ */
63
+ export declare const buildCacheEntriesFromResults: <Params, CustomSettings extends SettingsMap>(results: ProviderResult<Params>[], context: AdapterContext<CustomSettings>) => CacheEntry<AdapterResponse<{
64
+ result: unknown;
65
+ }>>[];
66
+ /**
67
+ * Takes an Adapter, its configuration, and its dependencies, and it creates an express middleware
68
+ * that will pass along the AdapterRequest to the appropriate Transport (acc. to the endpoint in the req.)
69
+ *
70
+ * @param adapter - main adapter object, already initialized
71
+ * @returns the transport handler middleware function
72
+ */
73
+ export declare const buildTransportHandler: (adapter: Adapter) => (req: AdapterRequest, reply: FastifyReply) => Promise<never>;
@@ -0,0 +1,22 @@
1
+ import * as client from 'prom-client';
2
+ import { AdapterContext } from '../adapter';
3
+ import { SettingsMap } from '../config';
4
+ export declare const dataProviderMetricsLabel: (providerStatusCode?: number | undefined, method?: string) => {
5
+ provider_status_code: number | undefined;
6
+ method: string;
7
+ };
8
+ export declare const dataProviderRequests: client.Counter<"method" | "provider_status_code">;
9
+ export declare const dataProviderRequestDurationSeconds: client.Histogram<string>;
10
+ export declare const connectionErrorLabels: (message: string) => {
11
+ message: string;
12
+ };
13
+ export declare const messageSubsLabels: (feed_id: string, cache_key: string) => {
14
+ feed_id: string;
15
+ subscription_key: string;
16
+ };
17
+ export declare const recordWsMessageMetrics: <AdapterParams, CustomSettings extends SettingsMap>(context: AdapterContext<CustomSettings>, subscribes: AdapterParams[], unsubscrices: AdapterParams[]) => void;
18
+ export declare const wsConnectionActive: client.Gauge<"url">;
19
+ export declare const wsConnectionErrors: client.Counter<"message" | "url">;
20
+ export declare const wsSubscriptionActive: client.Gauge<"feed_id" | "connection_url" | "subscription_key">;
21
+ export declare const wsSubscriptionTotal: client.Counter<"feed_id" | "connection_url" | "subscription_key">;
22
+ export declare const wsMessageTotal: client.Counter<"feed_id" | "subscription_key">;
@@ -0,0 +1,44 @@
1
+ import { AdapterRequest, AdapterResponse } from '../util/request';
2
+ import { Transport } from './';
3
+ import { Cache } from '../cache';
4
+ import { AxiosRequestConfig, AxiosResponse } from 'axios';
5
+ import { AdapterConfig, SettingsMap } from '../config';
6
+ import { RequestRateLimiter } from '../rate-limiting';
7
+ import { AdapterDependencies } from '../adapter';
8
+ /**
9
+ * Transport implementation that takes incoming requests, transforms them into a DataProvider request,
10
+ * and executes that request returning the response immediately from the `setup` function.
11
+ * Optionally, setting the `coalescing` option to `true` will make it so once a request is in flight,
12
+ * new adapter requests for the same feed will not trigger a new one, but return an empty promise from
13
+ * the setup instead so the normal cache polling mechanism is used.
14
+ *
15
+ * @typeParam AdapterParams - interface for the adapter request body
16
+ * @typeParam ProviderRequestBody - interface for the body of the request to the Data Provider
17
+ * @typeParam ProviderResponseBody - interface for the body of the Data Provider's response
18
+ */
19
+ export declare class RestTransport<AdapterParams, ProviderRequestBody, ProviderResponseBody, CustomSettings extends SettingsMap> implements Transport<AdapterParams, ProviderResponseBody, CustomSettings> {
20
+ protected config: {
21
+ prepareRequest: (req: AdapterRequest<AdapterParams>, config: AdapterConfig<CustomSettings>) => AxiosRequestConfig<ProviderRequestBody> | Promise<AxiosRequestConfig<ProviderRequestBody>>;
22
+ parseResponse: (req: AdapterRequest<AdapterParams>, res: AxiosResponse<ProviderResponseBody>, config: AdapterConfig<CustomSettings>) => AdapterResponse<ProviderResponseBody> | Promise<AdapterResponse<ProviderResponseBody>>;
23
+ options: {
24
+ coalescing: boolean;
25
+ };
26
+ };
27
+ inFlightPrefix: string;
28
+ cache: Cache;
29
+ rateLimiter: RequestRateLimiter;
30
+ constructor(config: {
31
+ prepareRequest: (req: AdapterRequest<AdapterParams>, config: AdapterConfig<CustomSettings>) => AxiosRequestConfig<ProviderRequestBody> | Promise<AxiosRequestConfig<ProviderRequestBody>>;
32
+ parseResponse: (req: AdapterRequest<AdapterParams>, res: AxiosResponse<ProviderResponseBody>, config: AdapterConfig<CustomSettings>) => AdapterResponse<ProviderResponseBody> | Promise<AdapterResponse<ProviderResponseBody>>;
33
+ options: {
34
+ coalescing: boolean;
35
+ };
36
+ });
37
+ initialize(dependencies: AdapterDependencies, config: AdapterConfig): Promise<void>;
38
+ hasBeenSetUp(req: AdapterRequest<AdapterParams>): Promise<boolean>;
39
+ protected waitUntilUnderRateLimit(options: {
40
+ maxRetries: number;
41
+ msBetweenRetries: number;
42
+ }, retry?: number): Promise<void>;
43
+ setup(req: AdapterRequest<AdapterParams>, config: AdapterConfig<CustomSettings>): Promise<AdapterResponse<ProviderResponseBody> | undefined>;
44
+ }
@@ -0,0 +1,9 @@
1
+ import { AxiosRequestConfig, AxiosResponse } from 'axios';
2
+ import { AdapterConfig, SettingsMap } from '../config';
3
+ /**
4
+ * Performs axios request along with metrics recording and error handling
5
+ *
6
+ * @param request - axios request config
7
+ * @returns axios response for the request
8
+ */
9
+ export declare function axiosRequest<ProviderRequestBody, ProviderResponseBody, CustomSettings extends SettingsMap>(request: AxiosRequestConfig<ProviderRequestBody>, config: AdapterConfig<CustomSettings>): Promise<AxiosResponse<ProviderResponseBody>>;