@chainlink/external-adapter-framework 0.12.1 → 0.13.0

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 (57) hide show
  1. package/adapter/basic.js +3 -3
  2. package/adapter/basic.js.map +1 -1
  3. package/adapter/endpoint.d.ts +9 -1
  4. package/adapter/endpoint.js +23 -0
  5. package/adapter/endpoint.js.map +1 -1
  6. package/cache/index.d.ts +2 -2
  7. package/cache/index.js +1 -1
  8. package/cache/index.js.map +1 -1
  9. package/cache/local.js +7 -3
  10. package/cache/local.js.map +1 -1
  11. package/cache/metrics.d.ts +1 -1
  12. package/cache/metrics.js +9 -1
  13. package/cache/metrics.js.map +1 -1
  14. package/cache/redis.js +12 -4
  15. package/cache/redis.js.map +1 -1
  16. package/cache/response.d.ts +36 -0
  17. package/cache/response.js +58 -0
  18. package/cache/response.js.map +1 -0
  19. package/config/index.d.ts +6 -6
  20. package/config/index.js +6 -10
  21. package/config/index.js.map +1 -1
  22. package/index.js +4 -1
  23. package/index.js.map +1 -1
  24. package/metrics/util.d.ts +1 -1
  25. package/metrics/util.js +2 -2
  26. package/metrics/util.js.map +1 -1
  27. package/package.json +1 -1
  28. package/rate-limiting/metrics.js +1 -1
  29. package/rate-limiting/metrics.js.map +1 -1
  30. package/transports/abstract/streaming.d.ts +34 -0
  31. package/transports/abstract/streaming.js +44 -0
  32. package/transports/abstract/streaming.js.map +1 -0
  33. package/transports/abstract/subscription.d.ts +38 -0
  34. package/transports/abstract/subscription.js +63 -0
  35. package/transports/abstract/subscription.js.map +1 -0
  36. package/transports/batch-warming.d.ts +7 -12
  37. package/transports/batch-warming.js +42 -28
  38. package/transports/batch-warming.js.map +1 -1
  39. package/transports/index.d.ts +20 -13
  40. package/transports/index.js +0 -35
  41. package/transports/index.js.map +1 -1
  42. package/transports/metrics.d.ts +11 -4
  43. package/transports/metrics.js +30 -20
  44. package/transports/metrics.js.map +1 -1
  45. package/transports/rest.d.ts +10 -7
  46. package/transports/rest.js +22 -12
  47. package/transports/rest.js.map +1 -1
  48. package/transports/routing.d.ts +9 -3
  49. package/transports/routing.js +4 -4
  50. package/transports/routing.js.map +1 -1
  51. package/transports/sse.d.ts +8 -12
  52. package/transports/sse.js +29 -39
  53. package/transports/sse.js.map +1 -1
  54. package/transports/websocket.d.ts +14 -14
  55. package/transports/websocket.js +76 -60
  56. package/transports/websocket.js.map +1 -1
  57. package/util/request.d.ts +90 -11
@@ -1 +1 @@
1
- {"version":3,"file":"metrics.js","sourceRoot":"","sources":["../../../src/rate-limiting/metrics.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oDAAqC;AAErC,8CAA8C;AAC9C,kCAAkC;AAC3B,MAAM,YAAY,GAAG,CAAuB,IAA0B,EAAU,EAAE;IACvF,MAAM,IAAI,GAAI,IAAgC,CAAC,MAAM,CAAC,CAAA;IACtD,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACxD,OAAO,MAAM,CAAC,IAAI,CAAC,CAAA;KACpB;SAAM;QACL,OAAO,CAAC,CAAA;KACT;AACH,CAAC,CAAA;AAPY,QAAA,YAAY,gBAOxB;AAEY,QAAA,0BAA0B,GAAG,IAAI,MAAM,CAAC,OAAO,CAAC;IAC3D,IAAI,EAAE,gCAAgC;IACtC,IAAI,EAAE,8DAA8D;IACpE,UAAU,EAAE,CAAC,gBAAgB,EAAE,SAAS,CAAU;CACnD,CAAC,CAAA"}
1
+ {"version":3,"file":"metrics.js","sourceRoot":"","sources":["../../../src/rate-limiting/metrics.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oDAAqC;AAErC,8CAA8C;AAC9C,kCAAkC;AAC3B,MAAM,YAAY,GAAG,CAAuB,IAA0B,EAAU,EAAE;IACvF,MAAM,IAAI,GAAI,IAAgC,EAAE,CAAC,MAAM,CAAC,CAAA;IACxD,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACxD,OAAO,MAAM,CAAC,IAAI,CAAC,CAAA;KACpB;SAAM;QACL,OAAO,CAAC,CAAA;KACT;AACH,CAAC,CAAA;AAPY,QAAA,YAAY,gBAOxB;AAEY,QAAA,0BAA0B,GAAG,IAAI,MAAM,CAAC,OAAO,CAAC;IAC3D,IAAI,EAAE,gCAAgC;IACtC,IAAI,EAAE,8DAA8D;IACpE,UAAU,EAAE,CAAC,gBAAgB,EAAE,SAAS,CAAU;CACnD,CAAC,CAAA"}
@@ -0,0 +1,34 @@
1
+ import { TransportGenerics } from '..';
2
+ import { EndpointContext } from '../../adapter';
3
+ import { SubscriptionTransport } from './subscription';
4
+ /**
5
+ * Object to carry details about the current subscriptions for a StreamingTransport.
6
+ */
7
+ export declare type SubscriptionDeltas<T> = {
8
+ /** All the subscriptions that are valid at this point in time */
9
+ desired: T[];
10
+ /** The subscriptions that have not been processed yet (also included in the desired property) */
11
+ new: T[];
12
+ /** Subscriptions that have expired from the subscription set */
13
+ stale: T[];
14
+ };
15
+ /**
16
+ * Abstract Transport that will take incoming requests and add them to a subscription set as part
17
+ * of the registration. It also defines an abstract stream handler method, that will be called by the
18
+ * background execute and provided with calculated subscription deltas.
19
+ *
20
+ * @typeParam T - all types related to the [[Transport]]
21
+ */
22
+ export declare abstract class StreamingTransport<T extends TransportGenerics> extends SubscriptionTransport<T> {
23
+ localSubscriptions: T['Request']['Params'][];
24
+ providerDataStreamEstablished: number;
25
+ backgroundHandler(context: EndpointContext<T>, desiredSubs: T['Request']['Params'][]): Promise<void>;
26
+ /**
27
+ * Abstract method that will be provided with context and subscription details, and should take care of
28
+ * handling the connection and messages sent to whatever streaming source is used.
29
+ *
30
+ * @param context - the context related to this background execution
31
+ * @param subscriptions - object containing details for the desired, new, and stale subscriptions
32
+ */
33
+ abstract streamHandler(context: EndpointContext<T>, subscriptions: SubscriptionDeltas<T['Request']['Params']>): Promise<void>;
34
+ }
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StreamingTransport = void 0;
4
+ const util_1 = require("../../util");
5
+ const subscription_1 = require("./subscription");
6
+ const logger = (0, util_1.makeLogger)('StreamingTransport');
7
+ /**
8
+ * Abstract Transport that will take incoming requests and add them to a subscription set as part
9
+ * of the registration. It also defines an abstract stream handler method, that will be called by the
10
+ * background execute and provided with calculated subscription deltas.
11
+ *
12
+ * @typeParam T - all types related to the [[Transport]]
13
+ */
14
+ class StreamingTransport extends subscription_1.SubscriptionTransport {
15
+ constructor() {
16
+ super(...arguments);
17
+ // The double sets serve to create a simple polling mechanism instead of needing a subscription
18
+ // This one would not; this is always local state
19
+ this.localSubscriptions = [];
20
+ // This only tracks when the connection was established, not when the subscription was requested
21
+ this.providerDataStreamEstablished = 0;
22
+ }
23
+ async backgroundHandler(context, desiredSubs) {
24
+ logger.debug('Generating delta (subscribes & unsubscribes)');
25
+ const subscriptions = {
26
+ desired: desiredSubs,
27
+ new: desiredSubs.filter((s) => !this.localSubscriptions.map((ls) => JSON.stringify(ls)).includes(JSON.stringify(s))),
28
+ stale: this.localSubscriptions.filter((s) => !desiredSubs.map((ds) => JSON.stringify(ds)).includes(JSON.stringify(s))),
29
+ };
30
+ logger.debug(`${subscriptions.new.length} new subscriptions; ${subscriptions.stale.length} to unsubscribe`);
31
+ if (subscriptions.new.length) {
32
+ logger.trace(`Will subscribe to: ${JSON.stringify(subscriptions.new)}`);
33
+ }
34
+ if (subscriptions.stale.length) {
35
+ logger.trace(`Will unsubscribe to: ${JSON.stringify(subscriptions.stale)}`);
36
+ }
37
+ await this.streamHandler(context, subscriptions);
38
+ logger.debug('Setting local state to subscription set value');
39
+ this.localSubscriptions = desiredSubs;
40
+ return;
41
+ }
42
+ }
43
+ exports.StreamingTransport = StreamingTransport;
44
+ //# sourceMappingURL=streaming.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streaming.js","sourceRoot":"","sources":["../../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CAAC,aAAa,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;SACxE;QACD,IAAI,aAAa,CAAC,KAAK,CAAC,MAAM,EAAE;YAC9B,MAAM,CAAC,KAAK,CAAC,wBAAwB,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;SAC5E;QAED,MAAM,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,aAAa,CAAC,CAAA;QAEhD,MAAM,CAAC,KAAK,CAAC,+CAA+C,CAAC,CAAA;QAC7D,IAAI,CAAC,kBAAkB,GAAG,WAAW,CAAA;QAErC,OAAM;IACR,CAAC;CAaF;AAtDD,gDAsDC"}
@@ -0,0 +1,38 @@
1
+ import { EndpointContext } from '../../adapter';
2
+ import { ResponseCache } from '../../cache/response';
3
+ import { AdapterConfig } from '../../config';
4
+ import { BackgroundExecuteRateLimiter } from '../../rate-limiting';
5
+ import { SubscriptionSet } from '../../util';
6
+ import { AdapterRequest } from '../../util/request';
7
+ import { Transport, TransportDependencies, TransportGenerics } from '..';
8
+ /**
9
+ * Abstract Transport that will take incoming requests and add them to a subscription set as part
10
+ * of the registration. Then it will provide those entries to the (abstract) backgroundHandler method.
11
+ *
12
+ * @typeParam T - all types related to the [[Transport]]
13
+ */
14
+ export declare abstract class SubscriptionTransport<T extends TransportGenerics> implements Transport<T> {
15
+ responseCache: ResponseCache<{
16
+ Request: T['Request'];
17
+ Response: T['Response'];
18
+ }>;
19
+ rateLimiter: BackgroundExecuteRateLimiter;
20
+ subscriptionSet: SubscriptionSet<T['Request']['Params']>;
21
+ subscriptionTtl: number;
22
+ initialize(dependencies: TransportDependencies<T>, config: AdapterConfig<T['CustomSettings']>, endpointName: string): Promise<void>;
23
+ registerRequest(req: AdapterRequest<T['Request']>, _: AdapterConfig<T['CustomSettings']>): Promise<void>;
24
+ backgroundExecute(context: EndpointContext<T>): Promise<number>;
25
+ /**
26
+ * Handler specific to the subscription transport, that is provided all entries in the subscription set.
27
+ *
28
+ * @param context - background context for the execution of this handler
29
+ * @param entries - all the entries in the subscription set
30
+ */
31
+ abstract backgroundHandler(context: EndpointContext<T>, entries: T['Request']['Params'][]): Promise<void>;
32
+ /**
33
+ * Helper method to be defined in subclasses, for each of them to carry their own TTL definition in the EA config.
34
+ *
35
+ * @param config - the config for this adapter
36
+ */
37
+ abstract getSubscriptionTtlFromConfig(config: AdapterConfig<T['CustomSettings']>): number;
38
+ }
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.SubscriptionTransport = void 0;
27
+ const util_1 = require("../../util");
28
+ const transportMetrics = __importStar(require("../metrics"));
29
+ const logger = (0, util_1.makeLogger)('SubscriptionTransport');
30
+ /**
31
+ * Abstract Transport that will take incoming requests and add them to a subscription set as part
32
+ * of the registration. Then it will provide those entries to the (abstract) backgroundHandler method.
33
+ *
34
+ * @typeParam T - all types related to the [[Transport]]
35
+ */
36
+ class SubscriptionTransport {
37
+ async initialize(dependencies, config, endpointName) {
38
+ this.responseCache = dependencies.responseCache;
39
+ this.rateLimiter = dependencies.backgroundExecuteRateLimiter;
40
+ this.subscriptionSet = dependencies.subscriptionSetFactory.buildSet(endpointName);
41
+ this.subscriptionTtl = this.getSubscriptionTtlFromConfig(config); // Will be implemented by subclasses
42
+ }
43
+ async registerRequest(req, _) {
44
+ logger.debug(`Adding entry to subscription set (ttl ${this.subscriptionTtl}): [${req.requestContext.cacheKey}] = ${req.requestContext.data}`);
45
+ // This might need coalescing to avoid too frequent ttl updates
46
+ await this.subscriptionSet.add(req.requestContext.cacheKey, req.requestContext.data, this.subscriptionTtl);
47
+ }
48
+ async backgroundExecute(context) {
49
+ logger.debug('Starting background execute');
50
+ const entries = await this.subscriptionSet.getAll();
51
+ // Keep track of active subscriptions for background execute
52
+ // Note: for those coming from reasonable OOP languages, don't fret; this is JS:
53
+ // this.constructor.name will resolve to the instance name, not the class one (i.e., will use the implementing class' name)
54
+ transportMetrics.bgExecuteSubscriptionSetCount
55
+ .labels({ endpoint: context.endpointName, transport_type: this.constructor.name })
56
+ .set(entries.length);
57
+ const interval = this.rateLimiter.msUntilNextExecution(context.endpointName);
58
+ await this.backgroundHandler(context, entries);
59
+ return interval;
60
+ }
61
+ }
62
+ exports.SubscriptionTransport = SubscriptionTransport;
63
+ //# sourceMappingURL=subscription.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subscription.js","sourceRoot":"","sources":["../../../../src/transports/abstract/subscription.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,qCAAwD;AAGxD,6DAA8C;AAE9C,MAAM,MAAM,GAAG,IAAA,iBAAU,EAAC,uBAAuB,CAAC,CAAA;AAElD;;;;;GAKG;AACH,MAAsB,qBAAqB;IASzC,KAAK,CAAC,UAAU,CACd,YAAsC,EACtC,MAA0C,EAC1C,YAAoB;QAEpB,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC,aAAa,CAA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CAmBF;AAvED,sDAuEC"}
@@ -1,11 +1,9 @@
1
1
  import { AxiosRequestConfig, AxiosResponse } from 'axios';
2
- import { Cache } from '../cache';
2
+ import { EndpointContext } from '../adapter';
3
3
  import { AdapterConfig } from '../config';
4
- import { BackgroundExecuteRateLimiter } from '../rate-limiting';
5
- import { SubscriptionSet } from '../util';
6
- import { AdapterRequest, AdapterResponse, ProviderResult } from '../util/request';
7
- import { Transport, TransportGenerics } from './';
8
- import { EndpointContext, AdapterDependencies } from '../adapter';
4
+ import { AdapterRequest, ProviderResult } from '../util/request';
5
+ import { TransportGenerics } from './';
6
+ import { SubscriptionTransport } from './abstract/subscription';
9
7
  /**
10
8
  * Helper struct type that will be used to pass types to the generic parameters of a Transport.
11
9
  * Extends the common TransportGenerics, adding Provider specific types for this Batch endpoint.
@@ -42,16 +40,13 @@ export interface BatchWarmingTransportConfig<T extends BatchWarmingTransportGene
42
40
  *
43
41
  * @typeParam T - all types related to the [[Transport]]
44
42
  */
45
- export declare class BatchWarmingTransport<T extends BatchWarmingTransportGenerics> implements Transport<T> {
43
+ export declare class BatchWarmingTransport<T extends BatchWarmingTransportGenerics> extends SubscriptionTransport<T> {
46
44
  private config;
47
- cache: Cache<AdapterResponse<T['Response']>>;
48
- rateLimiter: BackgroundExecuteRateLimiter;
49
- subscriptionSet: SubscriptionSet<T['Request']['Params']>;
50
45
  WARMER_ACTIVE: boolean;
51
46
  constructor(config: BatchWarmingTransportConfig<T>);
52
- initialize(dependencies: AdapterDependencies, _: AdapterConfig<T['CustomSettings']>, endpointName: string): Promise<void>;
47
+ getSubscriptionTtlFromConfig(config: AdapterConfig<T['CustomSettings']>): number;
53
48
  registerRequest(req: AdapterRequest<T['Request']>, config: AdapterConfig<T['CustomSettings']>): Promise<void>;
54
- backgroundExecute(context: EndpointContext<T>): Promise<number>;
49
+ backgroundHandler(context: EndpointContext<T>, entries: T['Request']['Params'][]): Promise<void>;
55
50
  private makeRequest;
56
51
  }
57
52
  export {};
@@ -24,13 +24,12 @@ var __importStar = (this && this.__importStar) || function (mod) {
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.BatchWarmingTransport = void 0;
27
- const util_1 = require("../util");
28
- const _1 = require("./");
29
- const util_2 = require("./util");
30
- const rateLimitMetrics = __importStar(require("../rate-limiting/metrics"));
31
27
  const cacheMetrics = __importStar(require("../cache/metrics"));
32
- const transportMetrics = __importStar(require("./metrics"));
28
+ const rateLimitMetrics = __importStar(require("../rate-limiting/metrics"));
29
+ const util_1 = require("../util");
33
30
  const error_1 = require("../validation/error");
31
+ const subscription_1 = require("./abstract/subscription");
32
+ const util_2 = require("./util");
34
33
  const WARMUP_BATCH_REQUEST_ID = '9002';
35
34
  const logger = (0, util_1.makeLogger)('BatchWarmingTransport');
36
35
  /**
@@ -43,21 +42,18 @@ const logger = (0, util_1.makeLogger)('BatchWarmingTransport');
43
42
  *
44
43
  * @typeParam T - all types related to the [[Transport]]
45
44
  */
46
- class BatchWarmingTransport {
45
+ class BatchWarmingTransport extends subscription_1.SubscriptionTransport {
47
46
  constructor(config) {
47
+ super();
48
48
  this.config = config;
49
49
  // Flag used to track whether the warmer has moved from having no entries to having some and vice versa
50
50
  // Used for recording the cache warmer active metrics accurately
51
51
  this.WARMER_ACTIVE = false;
52
52
  }
53
- async initialize(dependencies, _, endpointName) {
54
- this.cache = dependencies.cache;
55
- this.rateLimiter = dependencies.backgroundExecuteRateLimiter;
56
- this.subscriptionSet = dependencies.subscriptionSetFactory.buildSet(endpointName);
53
+ getSubscriptionTtlFromConfig(config) {
54
+ return config.WARMUP_SUBSCRIPTION_TTL;
57
55
  }
58
- // This might need coalescing to avoid too frequent ttl updates
59
56
  async registerRequest(req, config) {
60
- logger.debug(`Adding entry to subscription set (ttl ${config.WARMUP_SUBSCRIPTION_TTL}): [${req.requestContext.cacheKey}] = ${req.requestContext.data}`);
61
57
  if (config.BATCH_TRANSPORT_SETUP_VALIDATION) {
62
58
  const response = await this.makeRequest([req.requestContext.data], config);
63
59
  if (!response.results.length) {
@@ -69,16 +65,9 @@ class BatchWarmingTransport {
69
65
  });
70
66
  }
71
67
  }
72
- await this.subscriptionSet.add(req.requestContext.cacheKey, req.requestContext.data, config.WARMUP_SUBSCRIPTION_TTL);
68
+ return super.registerRequest(req, config);
73
69
  }
74
- async backgroundExecute(context) {
75
- logger.debug('Starting background execute');
76
- const entries = await this.subscriptionSet.getAll();
77
- // Keep track of active subscriptions for background execute
78
- transportMetrics.bgExecuteSubscriptionSetCount
79
- .labels({ endpoint: context.endpointName, transport_type: 'batch' })
80
- .set(entries.length);
81
- const interval = this.rateLimiter.msUntilNextExecution(context.endpointName);
70
+ async backgroundHandler(context, entries) {
82
71
  if (!entries.length) {
83
72
  logger.debug('No entries in batch warming set, skipping');
84
73
  if (this.WARMER_ACTIVE) {
@@ -86,7 +75,7 @@ class BatchWarmingTransport {
86
75
  cacheMetrics.cacheWarmerCount.labels({ isBatched: 'true' }).dec();
87
76
  this.WARMER_ACTIVE = false;
88
77
  }
89
- return interval;
78
+ return;
90
79
  }
91
80
  else if (this.WARMER_ACTIVE === false) {
92
81
  // Increment count when warmer changed from having no entries to having some
@@ -95,11 +84,10 @@ class BatchWarmingTransport {
95
84
  }
96
85
  const response = await this.makeRequest(entries, context.adapterConfig);
97
86
  if (!response.results?.length) {
98
- return interval;
87
+ return;
99
88
  }
100
- const cacheEntries = (0, _1.buildCacheEntriesFromResults)(response.results, context);
101
89
  logger.debug('Setting adapter responses in cache');
102
- await this.cache.setMany(cacheEntries, context.adapterConfig.CACHE_MAX_AGE);
90
+ await this.responseCache.write(response.results);
103
91
  // Record cost of data provider call
104
92
  const cost = rateLimitMetrics.retrieveCost(response.providerResponse.data);
105
93
  rateLimitMetrics.rateLimitCreditsSpentTotal
@@ -108,26 +96,52 @@ class BatchWarmingTransport {
108
96
  participant_id: WARMUP_BATCH_REQUEST_ID,
109
97
  })
110
98
  .inc(cost);
111
- return interval;
99
+ return;
112
100
  }
113
101
  async makeRequest(entries, config) {
114
102
  logger.trace(`Have ${entries.length} entries in batch, preparing request...`);
115
103
  const request = this.config.prepareRequest(entries, config);
116
104
  logger.trace(`Sending request to data provider: ${JSON.stringify(request)}`);
105
+ const providerDataRequested = Date.now();
117
106
  let providerResponse;
118
107
  try {
119
108
  providerResponse = await (0, util_2.axiosRequest)(request, config);
120
109
  }
121
110
  catch (e) {
111
+ const err = e.cause;
112
+ const providerDataReceived = Date.now();
122
113
  logger.warn(`There was an error while performing the batch request: ${e}`);
123
114
  return {
124
- results: [],
115
+ results: entries.map((entry) => ({
116
+ params: entry,
117
+ response: {
118
+ errorMessage: `Provider request failed with status ${err?.status}: "${err?.response?.data}"`,
119
+ statusCode: 502,
120
+ timestamps: {
121
+ providerDataRequested,
122
+ providerDataReceived,
123
+ providerIndicatedTime: undefined,
124
+ },
125
+ },
126
+ })),
125
127
  providerResponse: e,
126
128
  };
127
129
  }
130
+ const providerDataReceived = Date.now();
131
+ // Parse responses and apply timestamps
132
+ const results = this.config.parseResponse(entries, providerResponse, config).map((r) => {
133
+ const result = r;
134
+ const partialResponse = r.response;
135
+ result.response.timestamps = {
136
+ providerDataRequested,
137
+ providerDataReceived,
138
+ providerIndicatedTime: partialResponse.timestamps?.providerIndicatedTime,
139
+ };
140
+ return result;
141
+ });
128
142
  logger.debug(`Got response from provider, parsing (raw body: ${providerResponse.data})`);
129
143
  return {
130
- results: this.config.parseResponse(entries, providerResponse, config),
144
+ results,
131
145
  providerResponse,
132
146
  };
133
147
  }
@@ -1 +1 @@
1
- {"version":3,"file":"batch-warming.js","sourceRoot":"","sources":["../../../src/transports/batch-warming.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,kCAAqD;AAErD,yBAA+E;AAC/E,iCAAqC;AACrC,2EAA4D;AAC5D,+DAAgD;AAEhD,4DAA6C;AAC7C,+CAAkD;AAElD,MAAM,uBAAuB,GAAG,MAAM,CAAA;AAEtC,MAAM,MAAM,GAAG,IAAA,iBAA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EAAE,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;YACrF,MAAM,MAAM,GAAG,CAAiC,CAAA;YAChD,MAAM,eAAe,GAAG,CAAC,CAAC,QAAoD,CAAA;YAC9E,MAAM,CAAC,QAAQ,CAAC,UAAU,GAAG;gBAC3B,qBAAqB;gBACrB,oBAAoB;gBACpB,qBAAqB,EAAE,eAAe,CAAC,UAAU,EAAE,qBAAqB;aACzE,CAAA;YACD,OAAO,MAAM,CAAA;QACf,CAAC,CAAC,CAAA;QAEF,MAAM,CAAC,KAAK,CAAC,kDAAkD,gBAAgB,CAAC,IAAI,GAAG,CAAC,CAAA;QACxF,OAAO;YACL,OAAO;YACP,gBAAgB;SACjB,CAAA;IACH,CAAC;CACF;AAtID,sDAsIC"}
@@ -1,7 +1,7 @@
1
- import { EndpointContext, AdapterDependencies } from '../adapter';
2
- import { Cache, CacheEntry } from '../cache';
1
+ import { AdapterDependencies, EndpointContext } from '../adapter';
2
+ import { ResponseCache } from '../cache/response';
3
3
  import { AdapterConfig, SettingsMap } from '../config';
4
- import { AdapterRequest, AdapterResponse, ProviderResult, RequestGenerics, ResponseGenerics } from '../util/request';
4
+ import { AdapterRequest, AdapterResponse, RequestGenerics, ResponseGenerics } from '../util/request';
5
5
  export * from './batch-warming';
6
6
  export * from './rest';
7
7
  export * from './sse';
@@ -28,6 +28,18 @@ export declare type TransportGenerics = {
28
28
  */
29
29
  CustomSettings: SettingsMap;
30
30
  };
31
+ /**
32
+ * Extended dependencies with necessary tools for a transport
33
+ */
34
+ export declare type TransportDependencies<T extends TransportGenerics> = AdapterDependencies & {
35
+ /**
36
+ * Cache that will be used to write responses that the Transport will return
37
+ */
38
+ responseCache: ResponseCache<{
39
+ Request: T['Request'];
40
+ Response: T['Response'];
41
+ }>;
42
+ };
31
43
  /**
32
44
  * Generic interface for a Transport.
33
45
  * A Transport defines the way in which an AdapterEndpoint will process incoming requests to
@@ -39,7 +51,10 @@ export declare type TransportGenerics = {
39
51
  * @typeParam T - Helper struct type that will be used to pass types to the generic parameters (check [[TransportGenerics]])
40
52
  */
41
53
  export interface Transport<T extends TransportGenerics> {
42
- cache?: Cache<AdapterResponse<T['Response']>>;
54
+ responseCache: ResponseCache<{
55
+ Request: T['Request'];
56
+ Response: T['Response'];
57
+ }>;
43
58
  /**
44
59
  * Initializes the transport in the Adapter context.
45
60
  *
@@ -47,7 +62,7 @@ export interface Transport<T extends TransportGenerics> {
47
62
  * @param config - Adapter config containing env vars
48
63
  * @returns an empty Promise
49
64
  */
50
- initialize: (dependencies: AdapterDependencies, config: AdapterConfig<T['CustomSettings']>, endpointName: string) => Promise<void>;
65
+ initialize: (dependencies: TransportDependencies<T>, config: AdapterConfig<T['CustomSettings']>, endpointName: string) => Promise<void>;
51
66
  /**
52
67
  * Registers a request within the context of the transport.
53
68
  * This means things like adding the request to a subscription set.
@@ -98,11 +113,3 @@ export interface MetaTransport<T extends TransportGenerics> extends Transport<T>
98
113
  [key: string]: Transport<T>;
99
114
  };
100
115
  }
101
- /**
102
- * Helper method to build cache entries to set after getting a bunch of responses from a DP.
103
- *
104
- * @param results - a list of results coming from a DataProvider
105
- * @param context - context for the Adapter
106
- * @returns a list of CacheEntries of AdapterResponses
107
- */
108
- export declare const buildCacheEntriesFromResults: <T extends TransportGenerics>(results: ProviderResult<T>[], context: EndpointContext<T>) => CacheEntry<AdapterResponse<T["Response"]>>[];
@@ -14,43 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.buildCacheEntriesFromResults = void 0;
18
- const cache_1 = require("../cache");
19
17
  __exportStar(require("./batch-warming"), exports);
20
18
  __exportStar(require("./rest"), exports);
21
19
  __exportStar(require("./sse"), exports);
22
20
  __exportStar(require("./websocket"), exports);
23
- /**
24
- * Helper method to build cache entries to set after getting a bunch of responses from a DP.
25
- *
26
- * @param results - a list of results coming from a DataProvider
27
- * @param context - context for the Adapter
28
- * @returns a list of CacheEntries of AdapterResponses
29
- */
30
- const buildCacheEntriesFromResults = (results, context) => results.map((r) => {
31
- const cacheEntry = {
32
- key: (0, cache_1.calculateCacheKey)(context, r.params),
33
- value: {
34
- result: r.value,
35
- statusCode: 200,
36
- data: {
37
- result: r.value,
38
- },
39
- },
40
- };
41
- if (context.adapterConfig.METRICS_ENABLED &&
42
- context.adapterConfig.EXPERIMENTAL_METRICS_ENABLED) {
43
- const metrics = {
44
- maxAge: Date.now() + context.adapterConfig.CACHE_MAX_AGE,
45
- meta: {
46
- metrics: {
47
- feedId: (0, cache_1.calculateFeedId)(context, r.params),
48
- },
49
- },
50
- };
51
- cacheEntry.value = { ...cacheEntry.value, ...metrics };
52
- }
53
- return cacheEntry;
54
- });
55
- exports.buildCacheEntriesFromResults = buildCacheEntriesFromResults;
56
21
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/transports/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AACA,oCAAgF;AAUhF,kDAA+B;AAC/B,yCAAsB;AACtB,wCAAqB;AACrB,8CAA2B;AAgH3B;;;;;;GAMG;AACI,MAAM,4BAA4B,GAAG,CAC1C,OAA4B,EAC5B,OAA2B,EACmB,EAAE,CAChD,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;IAChB,MAAM,UAAU,GAAG;QACjB,GAAG,EAAE,IAAA,yBAAiB,EAAC,OAAO,EAAE,CAAC,CAAC,MAAM,CAAC;QACzC,KAAK,EAAE;YACL,MAAM,EAAE,CAAC,CAAC,KAAK;YACf,UAAU,EAAE,GAAG;YACf,IAAI,EAAE;gBACJ,MAAM,EAAE,CAAC,CAAC,KAAK;aAChB;SACF;KACF,CAAA;IAED,IACE,OAAO,CAAC,aAAa,CAAC,eAAe;QACrC,OAAO,CAAC,aAAa,CAAC,4BAA4B,EAClD;QACA,MAAM,OAAO,GAAG;YACd,MAAM,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,OAAO,CAAC,aAAa,CAAC,aAAa;YACxD,IAAI,EAAE;gBACJ,OAAO,EAAE;oBACP,MAAM,EAAE,IAAA,uBAAe,EAAC,OAAO,EAAE,CAAC,CAAC,MAAM,CAAC;iBAC3C;aACF;SACF,CAAA;QACD,UAAU,CAAC,KAAK,GAAG,EAAE,GAAG,UAAU,CAAC,KAAK,EAAE,GAAG,OAAO,EAAE,CAAA;KACvD;IACD,OAAO,UAAU,CAAA;AACnB,CAAC,CAAC,CAAA;AA/BS,QAAA,4BAA4B,gCA+BrC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/transports/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAKA,kDAA+B;AAC/B,yCAAsB;AACtB,wCAAqB;AACrB,8CAA2B"}
@@ -1,6 +1,8 @@
1
1
  import * as client from 'prom-client';
2
2
  import { TransportGenerics } from '.';
3
3
  import { EndpointContext } from '../adapter';
4
+ import { AdapterConfig } from '../config';
5
+ import { InputParameters } from '../validation';
4
6
  export declare const dataProviderMetricsLabel: (providerStatusCode?: number, method?: string) => {
5
7
  provider_status_code: number | undefined;
6
8
  method: string;
@@ -10,16 +12,21 @@ export declare const dataProviderRequestDurationSeconds: client.Histogram<string
10
12
  export declare const connectionErrorLabels: (message: string) => {
11
13
  message: string;
12
14
  };
13
- export declare const messageSubsLabels: (feed_id: string, cache_key: string) => {
15
+ export declare type MessageDirection = 'sent' | 'received';
16
+ export declare const messageSubsLabels: <T extends TransportGenerics>(context: {
17
+ inputParameters: InputParameters;
18
+ endpointName: string;
19
+ adapterConfig: AdapterConfig<T["CustomSettings"]>;
20
+ }, params: T["Request"]["Params"]) => {
14
21
  feed_id: string;
15
22
  subscription_key: string;
16
23
  };
17
24
  export declare const recordWsMessageMetrics: <T extends TransportGenerics>(context: EndpointContext<T>, subscribes: T["Request"]["Params"][], unsubscribes: T["Request"]["Params"][]) => void;
18
25
  export declare const wsConnectionActive: client.Gauge<"url">;
19
26
  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">;
27
+ export declare const wsSubscriptionActive: client.Gauge<"feed_id" | "subscription_key" | "connection_url">;
28
+ export declare const wsSubscriptionTotal: client.Counter<"feed_id" | "subscription_key" | "connection_url">;
29
+ export declare const wsMessageTotal: client.Counter<"direction" | "feed_id" | "subscription_key">;
23
30
  export declare const bgExecuteSubscriptionSetCount: client.Gauge<"endpoint" | "transport_type">;
24
31
  export declare const transportPollingFailureCount: client.Counter<"endpoint">;
25
32
  export declare const transportPollingDurationSeconds: client.Gauge<"succeeded" | "endpoint">;
@@ -49,32 +49,42 @@ const connectionErrorLabels = (message) => ({
49
49
  message,
50
50
  });
51
51
  exports.connectionErrorLabels = connectionErrorLabels;
52
- const messageSubsLabels = (feed_id, cache_key) => ({
53
- feed_id,
54
- subscription_key: cache_key,
55
- });
52
+ const messageSubsLabels = (context, params) => {
53
+ const feedId = (0, cache_1.calculateFeedId)(context, params);
54
+ const cacheKey = (0, cache_1.calculateCacheKey)(context, params);
55
+ return {
56
+ feed_id: feedId,
57
+ subscription_key: cacheKey,
58
+ };
59
+ };
56
60
  exports.messageSubsLabels = messageSubsLabels;
57
61
  // Record WS message and subscription metrics
58
62
  // Recalculate cacheKey and feedId for metrics
59
63
  // since avoiding storing extra info in expiring sorted set
60
64
  const recordWsMessageMetrics = (context, subscribes, unsubscribes) => {
61
- subscribes.forEach((param) => {
62
- const feedId = (0, cache_1.calculateFeedId)(context, param);
63
- const cacheKey = (0, cache_1.calculateCacheKey)(context, param);
65
+ const recordMetrics = (params, type) => {
66
+ const baseLabels = (0, exports.messageSubsLabels)(context, params);
64
67
  // Record total number of ws messages sent
65
- exports.wsMessageTotal.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).inc();
68
+ exports.wsMessageTotal
69
+ .labels({
70
+ ...baseLabels,
71
+ direction: 'sent',
72
+ })
73
+ .inc();
66
74
  // Record total number of subscriptions made
67
- exports.wsSubscriptionTotal.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).inc();
68
- // Record number of active ws subscriptions
69
- exports.wsSubscriptionActive.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).inc();
75
+ if (type === 'sub') {
76
+ exports.wsSubscriptionTotal.labels(baseLabels).inc();
77
+ exports.wsSubscriptionActive.labels(baseLabels).inc();
78
+ }
79
+ else {
80
+ exports.wsSubscriptionActive.labels(baseLabels).dec();
81
+ }
82
+ };
83
+ subscribes.forEach((params) => {
84
+ recordMetrics(params, 'sub');
70
85
  });
71
- unsubscribes.forEach((param) => {
72
- const feedId = (0, cache_1.calculateFeedId)(context, param);
73
- const cacheKey = (0, cache_1.calculateCacheKey)(context, param);
74
- // Record total number of ws messages sent
75
- exports.wsMessageTotal.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).inc();
76
- // Record number of active ws subscriptions
77
- exports.wsSubscriptionActive.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).dec();
86
+ unsubscribes.forEach((params) => {
87
+ recordMetrics(params, 'unsub');
78
88
  });
79
89
  };
80
90
  exports.recordWsMessageMetrics = recordWsMessageMetrics;
@@ -100,8 +110,8 @@ exports.wsSubscriptionTotal = new client.Counter({
100
110
  });
101
111
  exports.wsMessageTotal = new client.Counter({
102
112
  name: 'ws_message_total',
103
- help: 'The number of messages received in total',
104
- labelNames: ['feed_id', 'subscription_key'],
113
+ help: 'The number of messages sent in total',
114
+ labelNames: ['feed_id', 'subscription_key', 'direction'],
105
115
  });
106
116
  // V3 specific metrics
107
117
  exports.bgExecuteSubscriptionSetCount = new client.Gauge({