@chainlink/external-adapter-framework 0.0.25 → 0.0.26

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 +1 -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,80 @@
1
+ import WebSocket from 'ws';
2
+ import { AdapterContext, AdapterDependencies } from '../adapter';
3
+ import { Cache } from '../cache';
4
+ import { AdapterConfig, SettingsMap } from '../config';
5
+ import { BackgroundExecuteRateLimiter } from '../rate-limiting';
6
+ import { SubscriptionSet } from '../util';
7
+ import { AdapterRequest, ProviderResult } from '../util/request';
8
+ import { Transport } from './';
9
+ declare type WebSocketClass = new (url: string, protocols?: string | string[] | undefined) => WebSocket;
10
+ export declare class WebSocketClassProvider {
11
+ static ctor: WebSocketClass;
12
+ static set(ctor: WebSocketClass): void;
13
+ static get(): WebSocketClass;
14
+ }
15
+ /**
16
+ * Config object that is provided to the WebSocketTransport constructor.
17
+ */
18
+ export interface WebSocketTransportConfig<AdapterParams, ProviderDataMessage, CustomSettings extends SettingsMap> {
19
+ /** Endpoint to which to open the WS connection*/
20
+ url: string;
21
+ /** Map of handlers for different WS lifecycle events */
22
+ handlers: {
23
+ /**
24
+ * Handles when the WS is successfully opened
25
+ *
26
+ * @param wsConnection - the WebSocket with an established connection
27
+ * @returns an empty Promise, or void
28
+ */
29
+ open: (wsConnection: WebSocket, context: AdapterContext<CustomSettings>) => Promise<void> | void;
30
+ /**
31
+ * Handles when the WS receives a message
32
+ *
33
+ * @param message - the message received by the WS
34
+ * @param context - the background context for the Adapter
35
+ * @returns a list of cache entries of adapter responses to set in the cache
36
+ */
37
+ message: (message: ProviderDataMessage, context: AdapterContext<CustomSettings>) => ProviderResult<AdapterParams>[];
38
+ };
39
+ /** Map of "builders", functions that will be used to prepare specific WS messages */
40
+ builders: {
41
+ /**
42
+ * Builds a WS message that will be sent to subscribe to a specific feed
43
+ *
44
+ * @param params - the body of the adapter request
45
+ * @returns the WS message (can be any type as long as the [[WebSocket]] doesn't complain)
46
+ */
47
+ subscribeMessage: (params: AdapterParams) => unknown;
48
+ /**
49
+ * Builds a WS message that will be sent to unsubscribe to a specific feed
50
+ *
51
+ * @param params - the body of the adapter request
52
+ * @returns the WS message (can be any type as long as the [[WebSocket]] doesn't complain)
53
+ */
54
+ unsubscribeMessage: (params: AdapterParams) => unknown;
55
+ };
56
+ }
57
+ /**
58
+ * Transport implementation that takes incoming requests, adds them to an [[subscriptionSet]] and,
59
+ * through a WebSocket connection, subscribes to the relevant feeds to populate the cache.
60
+ *
61
+ * @typeParam AdapterParams - interface for the adapter request body
62
+ * @typeParam ProviderDataMessage - interface for a WS message containing processable data (i.e. not part of open/close/login/etc)
63
+ */
64
+ export declare class WebSocketTransport<AdapterParams, ProviderDataMessage, CustomSettings extends SettingsMap> implements Transport<AdapterParams, null, CustomSettings> {
65
+ private config;
66
+ cache: Cache;
67
+ rateLimiter: BackgroundExecuteRateLimiter;
68
+ subscriptionSet: SubscriptionSet<AdapterParams>;
69
+ localSubscriptions: AdapterParams[];
70
+ wsConnection: WebSocket;
71
+ constructor(config: WebSocketTransportConfig<AdapterParams, ProviderDataMessage, CustomSettings>);
72
+ initialize(dependencies: AdapterDependencies): Promise<void>;
73
+ hasBeenSetUp(req: AdapterRequest<AdapterParams>): Promise<boolean>;
74
+ setup(req: AdapterRequest<AdapterParams>, config: AdapterConfig<CustomSettings>): Promise<void>;
75
+ serializeMessage(payload: unknown): string;
76
+ deserializeMessage(data: WebSocket.Data): ProviderDataMessage;
77
+ establishWsConnection(context: AdapterContext<CustomSettings>): Promise<unknown>;
78
+ backgroundExecute(context: AdapterContext<CustomSettings>): Promise<number>;
79
+ }
80
+ export {};
@@ -0,0 +1,12 @@
1
+ export * from './request';
2
+ export * from './logger';
3
+ export * from './subscription-set/subscription-set';
4
+ /**
5
+ * Sleeps for the provided number of milliseconds
6
+ * @param ms - The number of milliseconds to sleep for
7
+ * @returns a Promise that resolves once the specified time passes
8
+ */
9
+ export declare const sleep: (ms: number) => Promise<void>;
10
+ export declare const isObject: (o: unknown) => boolean;
11
+ export declare const isArray: (o: unknown) => boolean;
12
+ export declare type PromiseOrValue<T> = Promise<T> | T;
@@ -0,0 +1,42 @@
1
+ /// <reference types="node" />
2
+ import pino from 'pino';
3
+ import { AdapterRequest } from './request';
4
+ import { FastifyReply, HookHandlerDoneFunction } from 'fastify';
5
+ import { AsyncLocalStorage } from 'node:async_hooks';
6
+ export declare const asyncLocalStorage: AsyncLocalStorage<unknown>;
7
+ export declare type Store = {
8
+ correlationId: string;
9
+ };
10
+ /**
11
+ * Instead of using a global logger instance, we want to force using a child logger
12
+ * with a specific layer set in it, so that we can filter logs by where they're output from.
13
+ *
14
+ * Details on what each log level represents:
15
+ * "trace": Forensic debugging of issues on a local machine.
16
+ * "debug": Detailed logging level to get more context from users on their environments.
17
+ * "info": High-level informational messages, to describe at a glance the high level state of the system.
18
+ * "warn": A mild error occurred that might require non-urgent action.
19
+ * "error": An unexpected error occurred during the regular operation of a well-maintained EA.
20
+ * "fatal": The EA encountered an unrecoverable problem and had to exit.
21
+ *
22
+ * Full reference this is based on can be found at
23
+ * https://github.com/smartcontractkit/documentation/blob/main/docs/Node%20Operators/configuration-variables.md#log_level
24
+ *
25
+ * @param layer - the layer name to include in the logs (e.g. "SomeMiddleware", "RedisCache", etc.)
26
+ * @returns a layer specific logger
27
+ */
28
+ export declare const makeLogger: (layer: string) => pino.Logger<{
29
+ level: string;
30
+ mixin(): {};
31
+ transport: {
32
+ target: string;
33
+ options: {
34
+ levelFirst: boolean;
35
+ levelLabel: string;
36
+ ignore: string;
37
+ messageFormat: string;
38
+ translateTime: string;
39
+ };
40
+ } | undefined;
41
+ } & pino.ChildLoggerOptions>;
42
+ export declare const loggingContextMiddleware: (req: AdapterRequest, res: FastifyReply, done: HookHandlerDoneFunction) => void;
@@ -0,0 +1,56 @@
1
+ import { FastifyReply, FastifyRequest, HookHandlerDoneFunction } from 'fastify';
2
+ import { Adapter } from '../adapter';
3
+ import { AdapterError } from '../validation/error';
4
+ declare module 'fastify' {
5
+ interface FastifyRequest {
6
+ requestContext: AdapterRequestContext;
7
+ }
8
+ }
9
+ export interface AdapterRequestBody<T = AdapterRequestData> {
10
+ endpoint?: string;
11
+ data: T;
12
+ id?: string;
13
+ }
14
+ export declare type AdapterRequestContext<T = AdapterRequestData> = {
15
+ id: string;
16
+ endpointName: string;
17
+ cacheKey: string;
18
+ data: T;
19
+ meta?: AdapterRequestMeta;
20
+ };
21
+ export declare type AdapterRouteGeneric<T = AdapterRequestData> = {
22
+ Body: AdapterRequestBody<T>;
23
+ };
24
+ export declare type AdapterRequest<T = AdapterRequestData> = FastifyRequest<AdapterRouteGeneric<T>> & {
25
+ requestContext: AdapterRequestContext<T>;
26
+ };
27
+ /**
28
+ * Meta info that pertains to exposing metrics
29
+ */
30
+ export interface AdapterRequestMeta {
31
+ metrics?: AdapterMetricsMeta;
32
+ error?: AdapterError | Error;
33
+ }
34
+ /**
35
+ * Meta info that pertains to exposing metrics
36
+ */
37
+ export interface AdapterMetricsMeta {
38
+ feedId?: string;
39
+ cacheHit?: boolean;
40
+ }
41
+ export declare type AdapterRequestData = Record<string, unknown> & {
42
+ endpoint?: string;
43
+ };
44
+ export interface ProviderResult<Params> {
45
+ params: Params;
46
+ value: unknown;
47
+ }
48
+ export declare type AdapterResponse<T = unknown> = {
49
+ statusCode: number;
50
+ data: T;
51
+ result: unknown;
52
+ maxAge?: number;
53
+ meta?: AdapterRequestMeta;
54
+ };
55
+ export declare type Middleware = ((req: AdapterRequest, reply: FastifyReply, done: HookHandlerDoneFunction) => FastifyReply | void) | ((req: AdapterRequest, reply: FastifyReply) => Promise<FastifyReply | void>);
56
+ export declare type AdapterMiddlewareBuilder = (adapter: Adapter) => Middleware;
@@ -0,0 +1,22 @@
1
+ import { SubscriptionSet } from './subscription-set';
2
+ /**
3
+ * An object describing an entry in the expiring sorted set.
4
+ * @typeParam T - the type of the entry's value
5
+ */
6
+ interface ExpiringSortedSetEntry<T> {
7
+ value: T;
8
+ expirationTimestamp: number;
9
+ }
10
+ /**
11
+ * This class implements a set of unique items, each of which has an expiration timestamp.
12
+ * On reads, items that have expired will be deleted from the set and not returned.
13
+ *
14
+ * @typeParam T - the type of the set entries' values
15
+ */
16
+ export declare class ExpiringSortedSet<T> implements SubscriptionSet<T> {
17
+ map: Map<string, ExpiringSortedSetEntry<T>>;
18
+ add(key: string, value: T, ttl: number): void;
19
+ get(key: string): T | undefined;
20
+ getAll(): T[];
21
+ }
22
+ export {};
@@ -0,0 +1,18 @@
1
+ import { PromiseOrValue } from '..';
2
+ import { AdapterConfig } from '../../config';
3
+ /**
4
+ * Set to hold items to subscribe to from a provider (regardless of protocol)
5
+ */
6
+ export interface SubscriptionSet<T> {
7
+ /** Add a new subscription to the set */
8
+ add(key: string, value: T, ttl: number): PromiseOrValue<void>;
9
+ /** Get a specific subscription from the set */
10
+ get(key: string): PromiseOrValue<T | undefined>;
11
+ /** Get all subscriptions from the set as a list */
12
+ getAll(): PromiseOrValue<T[]>;
13
+ }
14
+ export declare class SubscriptionSetFactory {
15
+ private cacheType;
16
+ constructor(config: AdapterConfig);
17
+ buildSet<T>(): SubscriptionSet<T>;
18
+ }
@@ -0,0 +1,25 @@
1
+ import { AdapterRequestData } from './request';
2
+ /**
3
+ * The test payload read in from filesystem
4
+ */
5
+ export interface Payload {
6
+ requests: Array<AdapterRequestData>;
7
+ }
8
+ /**
9
+ * Test payload with discriminated union so we can tell when we should just do
10
+ * a simple liveness check rather than a sample request
11
+ */
12
+ declare type TestPayload = (Payload & {
13
+ isDefault: false;
14
+ }) | {
15
+ isDefault: true;
16
+ };
17
+ /**
18
+ * Load in a JSON file containing a test payload for the current adapter,
19
+ * used in healthchecks to make sample requests
20
+ *
21
+ * @param fileName - name of file that contains the test payload data for the smoke endpoint
22
+ * @returns the parsed payload with individual requests
23
+ */
24
+ export declare function loadTestPayload(fileName?: string): TestPayload;
25
+ export {};
@@ -0,0 +1,50 @@
1
+ import { HttpRequestType } from '../metrics/constants';
2
+ declare type ErrorBasic = {
3
+ name: string;
4
+ message: string;
5
+ };
6
+ declare type ErrorFull = ErrorBasic & {
7
+ stack: string;
8
+ cause: string;
9
+ };
10
+ export declare type AdapterErrorResponse = {
11
+ jobRunID: string;
12
+ status: string;
13
+ statusCode: number;
14
+ providerStatusCode?: number;
15
+ error: ErrorBasic | ErrorFull;
16
+ };
17
+ export declare class AdapterError extends Error {
18
+ jobRunID: string;
19
+ status: string;
20
+ statusCode: number;
21
+ cause: unknown;
22
+ url?: string;
23
+ errorResponse: unknown;
24
+ feedID?: string;
25
+ providerStatusCode?: number;
26
+ metricsLabel?: HttpRequestType;
27
+ name: string;
28
+ message: string;
29
+ constructor({ jobRunID, status, statusCode, name, message, cause, url, errorResponse, feedID, providerStatusCode, metricsLabel, }: Partial<AdapterError>);
30
+ toJSONResponse(): AdapterErrorResponse;
31
+ }
32
+ export declare class AdapterInputError extends AdapterError {
33
+ constructor(input: Partial<AdapterError>);
34
+ }
35
+ export declare class AdapterRateLimitError extends AdapterError {
36
+ constructor(input: Partial<AdapterError>);
37
+ }
38
+ export declare class AdapterTimeoutError extends AdapterError {
39
+ constructor(input: Partial<AdapterError>);
40
+ }
41
+ export declare class AdapterDataProviderError extends AdapterError {
42
+ constructor(input: Partial<AdapterError>);
43
+ }
44
+ export declare class AdapterConnectionError extends AdapterError {
45
+ constructor(input: Partial<AdapterError>);
46
+ }
47
+ export declare class AdapterCustomError extends AdapterError {
48
+ constructor(input: Partial<AdapterError>);
49
+ }
50
+ export {};
@@ -0,0 +1,5 @@
1
+ import { FastifyReply, FastifyRequest } from 'fastify';
2
+ import { AdapterMiddlewareBuilder } from '../util/request';
3
+ export { InputParameters } from './input-params';
4
+ export declare const validatorMiddleware: AdapterMiddlewareBuilder;
5
+ export declare const errorCatchingMiddleware: (err: Error, req: FastifyRequest, res: FastifyReply) => void;
@@ -0,0 +1,15 @@
1
+ export declare type Override = Map<string, Map<string, string>>;
2
+ export declare type InputParameter = {
3
+ aliases?: string[];
4
+ description?: string;
5
+ type?: 'bigint' | 'boolean' | 'array' | 'number' | 'object' | 'string';
6
+ required?: boolean;
7
+ options?: unknown[];
8
+ default?: unknown;
9
+ dependsOn?: string[];
10
+ exclusive?: string[];
11
+ };
12
+ export declare type InputParameters = {
13
+ [name: string]: InputParameter | boolean | string[];
14
+ };
15
+ export declare const baseInputParameters: InputParameters;
@@ -0,0 +1,3 @@
1
+ import { Adapter } from '../adapter';
2
+ import { AdapterRequest } from '../util/request';
3
+ export declare const performSymbolOverrides: (adapter: Adapter, req: AdapterRequest) => void;
@@ -0,0 +1,47 @@
1
+ import { AdapterError, AdapterErrorResponse } from './error';
2
+ import { InputParameters, Override } from './input-params';
3
+ export declare type OverrideType = 'overrides' | 'tokenOverrides' | 'includes';
4
+ declare type InputType = {
5
+ id?: string;
6
+ data?: any;
7
+ };
8
+ export interface ValidatorOptions {
9
+ shouldThrowError?: boolean;
10
+ includes?: any[];
11
+ overrides?: any;
12
+ }
13
+ export declare type IncludePair = {
14
+ from: string;
15
+ to: string;
16
+ adapters?: string[];
17
+ inverse?: boolean;
18
+ tokens?: boolean;
19
+ };
20
+ export declare type Includes = {
21
+ from: string;
22
+ to: string;
23
+ includes: IncludePair[];
24
+ };
25
+ export declare class Validator {
26
+ input: InputType;
27
+ inputConfigs: InputParameters;
28
+ inputOptions: Record<string, any[]>;
29
+ validatorOptions: ValidatorOptions;
30
+ validated: any;
31
+ error: AdapterError | undefined;
32
+ errored: AdapterErrorResponse | undefined;
33
+ constructor(input?: InputType, inputConfigs?: {}, inputOptions?: {}, validatorOptions?: ValidatorOptions);
34
+ validateInput(): void;
35
+ validateOverrides(path: 'overrides' | 'tokenOverrides', preset: Record<string, any>): void;
36
+ checkDuplicateInputParams(inputConfig: InputParameters): void;
37
+ validateIncludeOverrides(): void;
38
+ parseError(error: unknown): void;
39
+ formatOverride: (param: any) => Override;
40
+ formatIncludeOverrides: (param: any) => Override;
41
+ throwInvalid: (message: string) => void;
42
+ validateObjectParam(key: string, shouldThrowError?: boolean): void;
43
+ validateOptionalParam(param: any, key: string, options: any[]): void;
44
+ validateRequiredParam(param: any, key: string, options: any[]): void;
45
+ getUsedKey(key: string, keyArray: string[]): string | undefined;
46
+ }
47
+ export {};