@chainlink/external-adapter-framework 0.0.14 → 0.0.15

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 (292) hide show
  1. package/.c8rc.json +3 -0
  2. package/.eslintignore +10 -0
  3. package/.eslintrc.js +96 -0
  4. package/.github/README.MD +42 -0
  5. package/.github/actions/setup/action.yaml +13 -0
  6. package/.github/workflows/label.yaml +39 -0
  7. package/.github/workflows/main.yaml +39 -0
  8. package/.github/workflows/publish.yaml +17 -0
  9. package/.prettierignore +13 -0
  10. package/.yarnrc +0 -0
  11. package/README.md +103 -0
  12. package/dist/examples/coingecko/test/e2e/adapter.test.ts.js +82953 -0
  13. package/dist/examples/coingecko/test/integration/adapter.test.ts.js +91672 -0
  14. package/dist/main.js +72703 -0
  15. package/docker-compose.yaml +35 -0
  16. package/env.sh +54 -0
  17. package/env2.sh +55 -0
  18. package/jest.config.js +5 -0
  19. package/package.json +14 -3
  20. package/publish.sh +0 -0
  21. package/src/adapter.ts +263 -0
  22. package/src/background-executor.ts +52 -0
  23. package/src/cache/factory.ts +26 -0
  24. package/src/cache/index.ts +258 -0
  25. package/src/cache/local.ts +73 -0
  26. package/src/cache/metrics.ts +112 -0
  27. package/src/cache/redis.ts +93 -0
  28. package/src/config/index.ts +517 -0
  29. package/src/config/provider-limits.ts +127 -0
  30. package/src/examples/bank-frick/README.MD +10 -0
  31. package/src/examples/bank-frick/accounts.ts +246 -0
  32. package/src/examples/bank-frick/config/index.ts +53 -0
  33. package/src/examples/bank-frick/index.ts +13 -0
  34. package/src/examples/bank-frick/types.d.ts +38 -0
  35. package/src/examples/bank-frick/util.ts +55 -0
  36. package/src/examples/coingecko/src/config/index.ts +12 -0
  37. package/src/examples/coingecko/src/config/overrides.json +10826 -0
  38. package/src/examples/coingecko/src/cryptoUtils.ts +88 -0
  39. package/src/examples/coingecko/src/endpoint/coins.ts +54 -0
  40. package/src/examples/coingecko/src/endpoint/crypto-marketcap.ts +66 -0
  41. package/src/examples/coingecko/src/endpoint/crypto-volume.ts +66 -0
  42. package/src/examples/coingecko/src/endpoint/crypto.ts +63 -0
  43. package/src/examples/coingecko/src/endpoint/dominance.ts +40 -0
  44. package/src/examples/coingecko/src/endpoint/global-marketcap.ts +40 -0
  45. package/src/examples/coingecko/src/endpoint/index.ts +6 -0
  46. package/src/examples/coingecko/src/globalUtils.ts +78 -0
  47. package/src/examples/coingecko/src/index.ts +17 -0
  48. package/src/examples/coingecko/test/e2e/adapter.test.ts +278 -0
  49. package/src/examples/coingecko/test/integration/__snapshots__/adapter.test.ts.snap +15 -0
  50. package/src/examples/coingecko/test/integration/adapter.test.ts +281 -0
  51. package/src/examples/coingecko/test/integration/capturedRequests.json +1 -0
  52. package/src/examples/coingecko/test/integration/fixtures.ts +42 -0
  53. package/src/examples/coingecko-old/batch-warming.ts +79 -0
  54. package/src/examples/coingecko-old/index.ts +9 -0
  55. package/src/examples/coingecko-old/rest.ts +77 -0
  56. package/src/examples/ncfx/config/index.ts +12 -0
  57. package/src/examples/ncfx/index.ts +9 -0
  58. package/src/examples/ncfx/websocket.ts +99 -0
  59. package/src/index.ts +149 -0
  60. package/src/metrics/constants.ts +23 -0
  61. package/src/metrics/index.ts +115 -0
  62. package/src/metrics/util.ts +18 -0
  63. package/src/rate-limiting/background/fixed-frequency.ts +45 -0
  64. package/src/rate-limiting/index.ts +100 -0
  65. package/src/rate-limiting/metrics.ts +18 -0
  66. package/src/rate-limiting/request/simple-counting.ts +76 -0
  67. package/src/transports/batch-warming.ts +127 -0
  68. package/src/transports/index.ts +152 -0
  69. package/src/transports/metrics.ts +95 -0
  70. package/src/transports/rest.ts +168 -0
  71. package/src/transports/util.ts +63 -0
  72. package/src/transports/websocket.ts +245 -0
  73. package/src/util/index.ts +23 -0
  74. package/src/util/logger.ts +69 -0
  75. package/src/util/recordRequests.ts +47 -0
  76. package/src/util/request.ts +117 -0
  77. package/src/util/subscription-set/expiring-sorted-set.ts +54 -0
  78. package/src/util/subscription-set/subscription-set.ts +35 -0
  79. package/src/util/test-payload-loader.ts +87 -0
  80. package/src/validation/error.ts +116 -0
  81. package/src/validation/index.ts +110 -0
  82. package/src/validation/input-params.ts +45 -0
  83. package/src/validation/override-functions.ts +44 -0
  84. package/src/validation/overrideFunctions.ts +44 -0
  85. package/src/validation/preset-tokens.json +23 -0
  86. package/src/validation/validator.ts +384 -0
  87. package/test/adapter.test.ts +27 -0
  88. package/test/background-executor.test.ts +108 -0
  89. package/test/cache/cache-key.test.ts +114 -0
  90. package/test/cache/helper.ts +100 -0
  91. package/test/cache/local.test.ts +54 -0
  92. package/test/cache/redis.test.ts +89 -0
  93. package/test/correlation.test.ts +114 -0
  94. package/test/index.test.ts +37 -0
  95. package/test/metrics/feed-id.test.ts +38 -0
  96. package/test/metrics/helper.ts +14 -0
  97. package/test/metrics/labels.test.ts +36 -0
  98. package/test/metrics/metrics.test.ts +267 -0
  99. package/test/metrics/redis-metrics.test.ts +113 -0
  100. package/test/metrics/warmer-metrics.test.ts +193 -0
  101. package/test/metrics/ws-metrics.test.ts +225 -0
  102. package/test/rate-limit-config.test.ts +242 -0
  103. package/test/smoke/smoke.test.ts +166 -0
  104. package/test/smoke/test-payload-fail.json +3 -0
  105. package/test/smoke/test-payload.js +22 -0
  106. package/test/smoke/test-payload.json +7 -0
  107. package/test/transports/batch.test.ts +466 -0
  108. package/test/transports/rest.test.ts +242 -0
  109. package/test/transports/websocket.test.ts +183 -0
  110. package/test/tsconfig.json +5 -0
  111. package/test/util.ts +77 -0
  112. package/test/validation.test.ts +178 -0
  113. package/test.sh +20 -0
  114. package/test2.sh +2 -0
  115. package/tsconfig.json +28 -0
  116. package/typedoc.json +6 -0
  117. package/webpack.config.js +57 -0
  118. package/yarn-error.log +3778 -0
  119. package/adapter.d.ts +0 -107
  120. package/adapter.js +0 -115
  121. package/background-executor.d.ts +0 -11
  122. package/background-executor.js +0 -45
  123. package/cache/factory.d.ts +0 -6
  124. package/cache/factory.js +0 -55
  125. package/cache/index.d.ts +0 -94
  126. package/cache/index.js +0 -173
  127. package/cache/local.d.ts +0 -23
  128. package/cache/local.js +0 -83
  129. package/cache/metrics.d.ts +0 -27
  130. package/cache/metrics.js +0 -120
  131. package/cache/redis.d.ts +0 -16
  132. package/cache/redis.js +0 -100
  133. package/chainlink-external-adapter-framework-0.0.6.tgz +0 -0
  134. package/config/index.d.ts +0 -209
  135. package/config/index.js +0 -380
  136. package/config/provider-limits.d.ts +0 -31
  137. package/config/provider-limits.js +0 -79
  138. package/examples/bank-frick/accounts.d.ts +0 -39
  139. package/examples/bank-frick/accounts.js +0 -191
  140. package/examples/bank-frick/config/index.d.ts +0 -4
  141. package/examples/bank-frick/config/index.js +0 -54
  142. package/examples/bank-frick/index.d.ts +0 -2
  143. package/examples/bank-frick/index.js +0 -14
  144. package/examples/bank-frick/util.d.ts +0 -4
  145. package/examples/bank-frick/util.js +0 -39
  146. package/examples/coingecko/batch-warming.d.ts +0 -2
  147. package/examples/coingecko/batch-warming.js +0 -52
  148. package/examples/coingecko/index.d.ts +0 -2
  149. package/examples/coingecko/index.js +0 -10
  150. package/examples/coingecko/rest.d.ts +0 -2
  151. package/examples/coingecko/rest.js +0 -50
  152. package/examples/ncfx/config/index.d.ts +0 -12
  153. package/examples/ncfx/config/index.js +0 -15
  154. package/examples/ncfx/index.d.ts +0 -2
  155. package/examples/ncfx/index.js +0 -10
  156. package/examples/ncfx/websocket.d.ts +0 -36
  157. package/examples/ncfx/websocket.js +0 -72
  158. package/index.d.ts +0 -11
  159. package/index.js +0 -133
  160. package/metrics/constants.d.ts +0 -16
  161. package/metrics/constants.js +0 -25
  162. package/metrics/index.d.ts +0 -15
  163. package/metrics/index.js +0 -122
  164. package/metrics/util.d.ts +0 -7
  165. package/metrics/util.js +0 -9
  166. package/package/adapter.d.ts +0 -88
  167. package/package/adapter.js +0 -112
  168. package/package/background-executor.d.ts +0 -11
  169. package/package/background-executor.js +0 -45
  170. package/package/cache/factory.d.ts +0 -6
  171. package/package/cache/factory.js +0 -57
  172. package/package/cache/index.d.ts +0 -90
  173. package/package/cache/index.js +0 -169
  174. package/package/cache/local.d.ts +0 -23
  175. package/package/cache/local.js +0 -83
  176. package/package/cache/metrics.d.ts +0 -27
  177. package/package/cache/metrics.js +0 -120
  178. package/package/cache/redis.d.ts +0 -16
  179. package/package/cache/redis.js +0 -100
  180. package/package/config/index.d.ts +0 -195
  181. package/package/config/index.js +0 -365
  182. package/package/config/provider-limits.d.ts +0 -31
  183. package/package/config/provider-limits.js +0 -76
  184. package/package/examples/coingecko/batch-warming.d.ts +0 -2
  185. package/package/examples/coingecko/batch-warming.js +0 -52
  186. package/package/examples/coingecko/index.d.ts +0 -2
  187. package/package/examples/coingecko/index.js +0 -10
  188. package/package/examples/coingecko/rest.d.ts +0 -2
  189. package/package/examples/coingecko/rest.js +0 -50
  190. package/package/examples/ncfx/config/index.d.ts +0 -12
  191. package/package/examples/ncfx/config/index.js +0 -15
  192. package/package/examples/ncfx/index.d.ts +0 -2
  193. package/package/examples/ncfx/index.js +0 -10
  194. package/package/examples/ncfx/websocket.d.ts +0 -36
  195. package/package/examples/ncfx/websocket.js +0 -72
  196. package/package/index.d.ts +0 -12
  197. package/package/index.js +0 -92
  198. package/package/metrics/constants.d.ts +0 -16
  199. package/package/metrics/constants.js +0 -25
  200. package/package/metrics/index.d.ts +0 -15
  201. package/package/metrics/index.js +0 -123
  202. package/package/metrics/util.d.ts +0 -3
  203. package/package/metrics/util.js +0 -9
  204. package/package/package.json +0 -72
  205. package/package/rate-limiting/background/fixed-frequency.d.ts +0 -10
  206. package/package/rate-limiting/background/fixed-frequency.js +0 -37
  207. package/package/rate-limiting/index.d.ts +0 -54
  208. package/package/rate-limiting/index.js +0 -63
  209. package/package/rate-limiting/metrics.d.ts +0 -3
  210. package/package/rate-limiting/metrics.js +0 -44
  211. package/package/rate-limiting/request/simple-counting.d.ts +0 -20
  212. package/package/rate-limiting/request/simple-counting.js +0 -62
  213. package/package/test.d.ts +0 -1
  214. package/package/test.js +0 -6
  215. package/package/transports/batch-warming.d.ts +0 -34
  216. package/package/transports/batch-warming.js +0 -101
  217. package/package/transports/index.d.ts +0 -87
  218. package/package/transports/index.js +0 -87
  219. package/package/transports/metrics.d.ts +0 -21
  220. package/package/transports/metrics.js +0 -105
  221. package/package/transports/rest.d.ts +0 -43
  222. package/package/transports/rest.js +0 -129
  223. package/package/transports/util.d.ts +0 -8
  224. package/package/transports/util.js +0 -85
  225. package/package/transports/websocket.d.ts +0 -80
  226. package/package/transports/websocket.js +0 -169
  227. package/package/util/expiring-sorted-set.d.ts +0 -21
  228. package/package/util/expiring-sorted-set.js +0 -47
  229. package/package/util/index.d.ts +0 -11
  230. package/package/util/index.js +0 -35
  231. package/package/util/logger.d.ts +0 -42
  232. package/package/util/logger.js +0 -62
  233. package/package/util/request.d.ts +0 -55
  234. package/package/util/request.js +0 -2
  235. package/package/validation/error.d.ts +0 -50
  236. package/package/validation/error.js +0 -79
  237. package/package/validation/index.d.ts +0 -5
  238. package/package/validation/index.js +0 -86
  239. package/package/validation/input-params.d.ts +0 -15
  240. package/package/validation/input-params.js +0 -30
  241. package/package/validation/override-functions.d.ts +0 -3
  242. package/package/validation/override-functions.js +0 -40
  243. package/package/validation/preset-tokens.json +0 -23
  244. package/package/validation/validator.d.ts +0 -47
  245. package/package/validation/validator.js +0 -303
  246. package/rate-limiting/background/fixed-frequency.d.ts +0 -10
  247. package/rate-limiting/background/fixed-frequency.js +0 -35
  248. package/rate-limiting/index.d.ts +0 -54
  249. package/rate-limiting/index.js +0 -63
  250. package/rate-limiting/metrics.d.ts +0 -3
  251. package/rate-limiting/metrics.js +0 -44
  252. package/rate-limiting/request/simple-counting.d.ts +0 -20
  253. package/rate-limiting/request/simple-counting.js +0 -62
  254. package/test.d.ts +0 -1
  255. package/test.js +0 -6
  256. package/transports/batch-warming.d.ts +0 -35
  257. package/transports/batch-warming.js +0 -101
  258. package/transports/index.d.ts +0 -70
  259. package/transports/index.js +0 -87
  260. package/transports/metrics.d.ts +0 -21
  261. package/transports/metrics.js +0 -105
  262. package/transports/rest.d.ts +0 -44
  263. package/transports/rest.js +0 -131
  264. package/transports/util.d.ts +0 -8
  265. package/transports/util.js +0 -85
  266. package/transports/websocket.d.ts +0 -81
  267. package/transports/websocket.js +0 -168
  268. package/util/expiring-sorted-set.d.ts +0 -21
  269. package/util/expiring-sorted-set.js +0 -47
  270. package/util/index.d.ts +0 -12
  271. package/util/index.js +0 -35
  272. package/util/logger.d.ts +0 -42
  273. package/util/logger.js +0 -62
  274. package/util/request.d.ts +0 -57
  275. package/util/request.js +0 -2
  276. package/util/subscription-set/expiring-sorted-set.d.ts +0 -22
  277. package/util/subscription-set/expiring-sorted-set.js +0 -47
  278. package/util/subscription-set/subscription-set.d.ts +0 -18
  279. package/util/subscription-set/subscription-set.js +0 -19
  280. package/util/test-payload-loader.d.ts +0 -25
  281. package/util/test-payload-loader.js +0 -83
  282. package/validation/error.d.ts +0 -50
  283. package/validation/error.js +0 -79
  284. package/validation/index.d.ts +0 -5
  285. package/validation/index.js +0 -91
  286. package/validation/input-params.d.ts +0 -15
  287. package/validation/input-params.js +0 -30
  288. package/validation/override-functions.d.ts +0 -3
  289. package/validation/override-functions.js +0 -40
  290. package/validation/preset-tokens.json +0 -23
  291. package/validation/validator.d.ts +0 -47
  292. package/validation/validator.js +0 -303
@@ -1,303 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.Validator = void 0;
7
- const error_1 = require("./error");
8
- const input_params_1 = require("./input-params");
9
- const util_1 = require("../util");
10
- const preset_tokens_json_1 = __importDefault(require("./preset-tokens.json"));
11
- // Don't want to get requester in just yet, only copying the static method 'errored'
12
- const requesterErrored = (jobRunID = '1', error = undefined, statusCode = 500, feedID = undefined) => {
13
- if (error instanceof error_1.AdapterError) {
14
- error.jobRunID = jobRunID;
15
- if (feedID) {
16
- error.feedID = feedID;
17
- }
18
- return error.toJSONResponse();
19
- }
20
- if (error instanceof Error) {
21
- return new error_1.AdapterError({
22
- jobRunID,
23
- statusCode,
24
- message: error.message,
25
- cause: error,
26
- feedID,
27
- }).toJSONResponse();
28
- }
29
- return new error_1.AdapterError({ jobRunID, statusCode, message: error, feedID }).toJSONResponse();
30
- };
31
- class Validator {
32
- constructor(input = { id: '1', data: {} }, inputConfigs = {}, inputOptions = {}, validatorOptions = {}) {
33
- // OverrideSymbol = (adapter: string, symbol?: string | string[]): string | string[] => {
34
- // Const defaultSymbol = symbol || this.validated.data.base
35
- // If (!defaultSymbol) this.throwInvalid(`Required parameter not supplied: base`)
36
- // // TODO: Will never be reached, because the presetSymbols are used as default overrides
37
- // If (!this.validated.overrides) return defaultSymbol
38
- // If (!Array.isArray(defaultSymbol))
39
- // Return (
40
- // This.validated.overrides.get(adapter.toLowerCase())?.get(defaultSymbol.toLowerCase()) ||
41
- // DefaultSymbol
42
- // )
43
- // Const multiple: string[] = []
44
- // For (const sym of defaultSymbol) {
45
- // Const overrided = this.validated.overrides.get(adapter.toLowerCase())?.get(sym.toLowerCase())
46
- // If (!overrided) multiple.push(sym)
47
- // Else multiple.push(overrided)
48
- // }
49
- // Return multiple
50
- // }
51
- // OverrideToken = (symbol: string, network = 'ethereum'): string | undefined => {
52
- // Return this.validated.tokenOverrides?.get(network.toLowerCase())?.get(symbol.toLowerCase())
53
- // }
54
- // OverrideIncludes = (from: string, to: string): IncludePair | undefined => {
55
- // // Search through `presetIncludes` to find matching override for adapter and to/from pairing.
56
- // Const pairs = (
57
- // This.validated.includes?.filter(
58
- // (val: string | Includes) => typeof val !== 'string',
59
- // ) as Includes[]
60
- // ).filter(
61
- // (pair) =>
62
- // Pair.from.toLowerCase() === from.toLowerCase() &&
63
- // Pair.to.toLowerCase() === to.toLowerCase(),
64
- // )
65
- // If (!pairs || !pairs[0] || !pairs[0].includes || !pairs[0].includes[0]) {
66
- // Return
67
- // }
68
- // Return pairs[0].includes[0]
69
- // }
70
- // OverrideReverseLookup = (adapter: string, type: OverrideType, symbol: string): string => {
71
- // Const overrides: Map<string, string> | undefined = this.validated?.[type]?.get(
72
- // Adapter.toLowerCase(),
73
- // )
74
- // If (!overrides) return symbol
75
- // Let originalSymbol: string | undefined
76
- // Overrides.forEach((overridden, original) => {
77
- // If (overridden.toLowerCase() === symbol.toLowerCase()) originalSymbol = original
78
- // })
79
- // Return originalSymbol || symbol
80
- // }
81
- this.formatOverride = (param) => {
82
- const _throwInvalid = () => this.throwInvalid(`Parameter supplied with wrong format: "override"`);
83
- if (!(0, util_1.isObject)(param)) {
84
- _throwInvalid();
85
- }
86
- const _isValid = Object.values(param).every(util_1.isObject);
87
- if (!_isValid) {
88
- _throwInvalid();
89
- }
90
- const _keyToLowerCase = (entry) => {
91
- return [entry[0].toLowerCase(), entry[1]];
92
- };
93
- return new Map(Object.entries(param)
94
- .map(_keyToLowerCase)
95
- .map(([key, value]) => [key, new Map(Object.entries(value).map(_keyToLowerCase))]));
96
- };
97
- this.formatIncludeOverrides = (param) => {
98
- const _throwInvalid = () => this.throwInvalid(`Parameter supplied with wrong format: "includes"`);
99
- if (!(0, util_1.isArray)(param)) {
100
- _throwInvalid();
101
- }
102
- const _isValid = Object.values(param).every((val) => (0, util_1.isObject)(val) || typeof val === 'string');
103
- if (!_isValid) {
104
- _throwInvalid();
105
- }
106
- return param;
107
- };
108
- this.throwInvalid = (message) => {
109
- throw new error_1.AdapterError({ jobRunID: this.validated.id, statusCode: 400, message });
110
- };
111
- this.input = { ...input };
112
- if (!this.input.id) {
113
- this.input.id = '1';
114
- } // TODO Please remove these once "no any" strict typing is enabled
115
- if (!this.input.data) {
116
- this.input.data = {};
117
- }
118
- this.inputConfigs = { ...input_params_1.baseInputParameters, ...inputConfigs };
119
- this.inputOptions = { ...inputOptions };
120
- this.validatorOptions = {
121
- shouldThrowError: true,
122
- includes: [],
123
- overrides: {},
124
- ...validatorOptions,
125
- };
126
- this.validated = { id: this.input.id, data: {} };
127
- this.validateInput();
128
- this.validateOverrides('overrides', this.validatorOptions.overrides);
129
- this.validateOverrides('tokenOverrides', preset_tokens_json_1.default);
130
- this.validateIncludeOverrides();
131
- this.checkDuplicateInputParams(inputConfigs);
132
- }
133
- validateInput() {
134
- try {
135
- for (const key in this.inputConfigs) {
136
- this.validateObjectParam(key, this.validatorOptions.shouldThrowError);
137
- }
138
- }
139
- catch (e) {
140
- this.parseError(e);
141
- }
142
- }
143
- validateOverrides(path, preset) {
144
- try {
145
- if (!this.input.data?.[path]) {
146
- this.validated[path] = this.formatOverride(preset);
147
- return;
148
- }
149
- this.validated[path] = this.formatOverride({ ...preset, ...this.input.data[path] });
150
- }
151
- catch (e) {
152
- this.parseError(e);
153
- }
154
- }
155
- checkDuplicateInputParams(inputConfig) {
156
- let aliases = [];
157
- for (const key in inputConfig) {
158
- const param = inputConfig[key];
159
- if (Array.isArray(param)) {
160
- aliases = aliases.concat(param);
161
- }
162
- else if (typeof inputConfig === 'boolean') {
163
- return;
164
- }
165
- else {
166
- aliases.push(key);
167
- if (typeof param === 'object' && 'aliases' in param && Array.isArray(param.aliases)) {
168
- aliases = aliases.concat(param.aliases);
169
- }
170
- }
171
- }
172
- if (aliases.length !== new Set(aliases).size) {
173
- this.throwInvalid('Duplicate Input Aliases');
174
- }
175
- }
176
- validateIncludeOverrides() {
177
- try {
178
- this.validated.includes = this.formatIncludeOverrides([
179
- ...(Array.isArray(this.input.data?.includes) ? this.input.data.includes : []),
180
- ...(this.validatorOptions.includes || []),
181
- ]);
182
- }
183
- catch (e) {
184
- this.parseError(e);
185
- }
186
- }
187
- parseError(error) {
188
- if (!(error instanceof Error)) {
189
- return;
190
- }
191
- const message = 'Error validating input.';
192
- if (error instanceof error_1.AdapterError) {
193
- this.error = error;
194
- }
195
- else {
196
- this.error = new error_1.AdapterError({
197
- jobRunID: this.validated.id,
198
- statusCode: 400,
199
- message,
200
- cause: error,
201
- });
202
- }
203
- this.errored = requesterErrored(this.validated.id, this.error);
204
- if (this.validatorOptions.shouldThrowError) {
205
- throw this.error;
206
- }
207
- }
208
- validateObjectParam(key, shouldThrowError = true) {
209
- const inputConfig = this.inputConfigs[key];
210
- const usedKey = this.getUsedKey(key, inputConfig.aliases ?? []);
211
- const param = usedKey
212
- ? this.input.data[usedKey] ?? inputConfig.default
213
- : inputConfig.default;
214
- if (shouldThrowError) {
215
- const paramIsDefined = !(param === undefined || param === null || param === '');
216
- if (inputConfig.required && !paramIsDefined) {
217
- this.throwInvalid(`Required parameter ${key} must be non-null and non-empty`);
218
- }
219
- if (paramIsDefined) {
220
- if (inputConfig.type) {
221
- const primitiveTypes = ['boolean', 'number', 'bigint', 'string'];
222
- if (![...primitiveTypes, 'array', 'object'].includes(inputConfig.type)) {
223
- this.throwInvalid(`${key} parameter has unrecognized type ${inputConfig.type}`);
224
- }
225
- if (primitiveTypes.includes(inputConfig.type) && typeof param !== inputConfig.type) {
226
- this.throwInvalid(`${key} parameter must be of type ${inputConfig.type}`);
227
- }
228
- if (inputConfig.type === 'array' && (!Array.isArray(param) || param.length === 0)) {
229
- this.throwInvalid(`${key} parameter must be a non-empty array`);
230
- }
231
- if (inputConfig.type === 'object' &&
232
- (!param ||
233
- Array.isArray(param) ||
234
- typeof param !== inputConfig.type ||
235
- Object.keys(param).length === 0)) {
236
- this.throwInvalid(`${key} parameter must be an object with at least one property`);
237
- }
238
- }
239
- // If (inputConfig.options) {
240
- // Const tolcase = (o: any) => (typeof o === 'string' ? o.toLowerCase() : o)
241
- // Const formattedOptions = inputConfig.options.map(tolcase)
242
- // Const formattedParam = tolcase(param)
243
- // If (!formattedOptions.includes(formattedParam))
244
- // This.throwInvalid(
245
- // `${key} parameter '${formattedParam}' is not in the set of available options: ${formattedOptions.join(
246
- // ',',
247
- // )}`,
248
- // )
249
- // }
250
- // For (const dependency of inputConfig.dependsOn ?? []) {
251
- // Const usedDependencyKey = this.getUsedKey(
252
- // Dependency,
253
- // (this.inputConfigs[dependency] as InputParameter).aliases ?? [],
254
- // )
255
- // If (!usedDependencyKey) this.throwInvalid(`${key} dependency ${dependency} not supplied`)
256
- // }
257
- // For (const exclusive of inputConfig.exclusive ?? []) {
258
- // Const usedExclusiveKey = this.getUsedKey(
259
- // Exclusive,
260
- // (this.inputConfigs[exclusive] as InputParameter).aliases ?? [],
261
- // )
262
- // If (usedExclusiveKey)
263
- // This.throwInvalid(`${key} cannot be supplied concurrently with ${exclusive}`)
264
- // }
265
- }
266
- }
267
- this.validated.data[key] = param;
268
- }
269
- validateOptionalParam(param, key, options) {
270
- if (param && options) {
271
- if (!Array.isArray(options)) {
272
- this.throwInvalid(`Parameter options for ${key} must be of an Array type`);
273
- }
274
- if (!options.includes(param)) {
275
- this.throwInvalid(`${param} is not a supported ${key} option. Must be one of ${options}`);
276
- }
277
- }
278
- this.validated.data[key] = param;
279
- }
280
- validateRequiredParam(param, key, options) {
281
- if (typeof param === 'undefined' || param === '') {
282
- this.throwInvalid(`Required parameter not supplied: ${key}`);
283
- }
284
- if (options) {
285
- if (!Array.isArray(options)) {
286
- this.throwInvalid(`Parameter options for ${key} must be of an Array type`);
287
- }
288
- if (!options.includes(param)) {
289
- this.throwInvalid(`${param} is not a supported ${key} option. Must be one of ${options.join(' || ')}`);
290
- }
291
- }
292
- this.validated.data[key] = param;
293
- }
294
- getUsedKey(key, keyArray) {
295
- const comparisonArray = [...keyArray];
296
- if (!comparisonArray.includes(key)) {
297
- comparisonArray.push(key);
298
- }
299
- const inputParamKeys = Object.keys(this.input.data);
300
- return inputParamKeys.find((k) => comparisonArray.includes(k));
301
- }
302
- }
303
- exports.Validator = Validator;
@@ -1,10 +0,0 @@
1
- import { AdapterRateLimitTier, BackgroundExecuteRateLimiter } from '..';
2
- import { AdapterEndpoint } from '../../adapter';
3
- export declare const DEFAULT_SHARED_MS_BETWEEN_REQUESTS = 5000;
4
- export declare class FixedFrequencyRateLimiter implements BackgroundExecuteRateLimiter {
5
- msBetweenRequestsMap: {
6
- [endpointName: string]: number;
7
- };
8
- initialize(endpoints: AdapterEndpoint[], limits?: AdapterRateLimitTier): this;
9
- msUntilNextExecution(endpointName: string): number;
10
- }
@@ -1,35 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FixedFrequencyRateLimiter = exports.DEFAULT_SHARED_MS_BETWEEN_REQUESTS = void 0;
4
- const __1 = require("..");
5
- const util_1 = require("../../util");
6
- const logger = (0, util_1.makeLogger)('FixedFrequencyRateLimiter');
7
- exports.DEFAULT_SHARED_MS_BETWEEN_REQUESTS = 5000;
8
- class FixedFrequencyRateLimiter {
9
- constructor() {
10
- this.msBetweenRequestsMap = {};
11
- }
12
- initialize(endpoints, limits) {
13
- // Translate the hourly limit into reqs per minute
14
- let sharedMsBetweenRequests = 1000 / (0, __1.consolidateTierLimits)(limits);
15
- // If there is no limit set, we use some reasonable number
16
- if (!limits?.rateLimit1h && !limits?.rateLimit1m && !limits?.rateLimit1s) {
17
- // 5s period for all seems good
18
- sharedMsBetweenRequests = exports.DEFAULT_SHARED_MS_BETWEEN_REQUESTS;
19
- }
20
- logger.debug('Using fixed frequency batch rate limiting');
21
- for (const endpoint of endpoints) {
22
- if (endpoint.rateLimiting?.allocationPercentage == null) {
23
- throw new Error(`Allocation percentage for endpoint "${endpoint.name}" is null`);
24
- }
25
- this.msBetweenRequestsMap[endpoint.name] =
26
- (sharedMsBetweenRequests / endpoint.rateLimiting?.allocationPercentage) * 100;
27
- logger.debug(`Endpoint [${endpoint.name}]: ${this.msBetweenRequestsMap[endpoint.name] / 1000}s between requests`);
28
- }
29
- return this;
30
- }
31
- msUntilNextExecution(endpointName) {
32
- return this.msBetweenRequestsMap[endpointName];
33
- }
34
- }
35
- exports.FixedFrequencyRateLimiter = FixedFrequencyRateLimiter;
@@ -1,54 +0,0 @@
1
- import { AdapterEndpoint } from '../adapter';
2
- export * from './request/simple-counting';
3
- export * from './background/fixed-frequency';
4
- export interface AdapterRateLimitTier {
5
- rateLimit1s?: number;
6
- rateLimit1m?: number;
7
- rateLimit1h?: number;
8
- note?: string;
9
- }
10
- /**
11
- * Common interface for all RateLimiter classes to implement
12
- */
13
- export interface RateLimiter {
14
- /**
15
- * Method to ensure all RateLimiters can be initialized in the same manner.
16
- *
17
- * @param limits - settings for how much throughput to allow for the Adapter
18
- * @param endpoints - list of adapter endpoints
19
- */
20
- initialize(endpoints: AdapterEndpoint[], limits: AdapterRateLimitTier): this;
21
- }
22
- /**
23
- * RequestRateLimiters perform checks agains imminent outbound requests for any transport.
24
- */
25
- export interface RequestRateLimiter extends RateLimiter {
26
- /**
27
- * This method will check using whatever strategy is implemented to determine if
28
- * this request can be processed. If so, it returns true; if not, returns false.
29
- */
30
- isUnderLimits(): boolean;
31
- }
32
- /**
33
- * BackgroundExecuteFrequencyRateLimiters will implement custom logic to calculate
34
- * the period of time to wait between background executions for a transport.
35
- */
36
- export interface BackgroundExecuteRateLimiter extends RateLimiter {
37
- msUntilNextExecution(endpointName: string): number;
38
- }
39
- /**
40
- * This method will convert all possible settings for a rate limit tier and
41
- * convert them all to requests per second, returning the lowest one
42
- *
43
- * @param limits - the rate limit tier set for the adapter
44
- * @returns the most restrictive of the set options, in requests per second
45
- */
46
- export declare const consolidateTierLimits: (limits?: AdapterRateLimitTier) => number;
47
- /**
48
- * Validates rate limiting tiers specified for the adapter, and returns the one to use.
49
- *
50
- * @param tiers - the adapter config listing the different available API tiers
51
- * @param selectedTier - chosen API tier from settings, if present
52
- * @returns the specified API tier, or a default one if none are specified
53
- */
54
- export declare const getRateLimitingTier: (tiers?: Record<string, AdapterRateLimitTier>, selectedTier?: string) => AdapterRateLimitTier | undefined;
@@ -1,63 +0,0 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.getRateLimitingTier = exports.consolidateTierLimits = void 0;
18
- __exportStar(require("./request/simple-counting"), exports);
19
- __exportStar(require("./background/fixed-frequency"), exports);
20
- /**
21
- * This method will convert all possible settings for a rate limit tier and
22
- * convert them all to requests per second, returning the lowest one
23
- *
24
- * @param limits - the rate limit tier set for the adapter
25
- * @returns the most restrictive of the set options, in requests per second
26
- */
27
- const consolidateTierLimits = (limits) => {
28
- const perHourLimit = (limits?.rateLimit1h || Infinity) / (60 * 60);
29
- const perMinuteLimit = (limits?.rateLimit1m || Infinity) / 60;
30
- const perSecondLimit = limits?.rateLimit1s || Infinity;
31
- return Math.min(perHourLimit, perMinuteLimit, perSecondLimit);
32
- };
33
- exports.consolidateTierLimits = consolidateTierLimits;
34
- /**
35
- * Validates rate limiting tiers specified for the adapter, and returns the one to use.
36
- *
37
- * @param tiers - the adapter config listing the different available API tiers
38
- * @param selectedTier - chosen API tier from settings, if present
39
- * @returns the specified API tier, or a default one if none are specified
40
- */
41
- const getRateLimitingTier = (tiers, selectedTier) => {
42
- if (!tiers) {
43
- return;
44
- }
45
- // Check that if the tiers object is defined, it has values
46
- if (Object.values(tiers).length === 0) {
47
- throw new Error(`The tiers object is defined, but has no entries`);
48
- }
49
- // Check that the tier set in the AdapterConfig is a valid one
50
- if (selectedTier && !tiers[selectedTier]) {
51
- const validTiersString = Object.keys(tiers)
52
- .map((t) => `"${t}"`)
53
- .join(', ');
54
- throw new Error(`The selected rate limit tier "${selectedTier}" is not valid (can be one of ${validTiersString})`);
55
- }
56
- if (!selectedTier) {
57
- // Sort the tiers by most to least restrictive
58
- const sortedTiers = Object.values(tiers).sort((t1, t2) => (0, exports.consolidateTierLimits)(t1) - (0, exports.consolidateTierLimits)(t2));
59
- return sortedTiers[0];
60
- }
61
- return tiers[selectedTier];
62
- };
63
- exports.getRateLimitingTier = getRateLimitingTier;
@@ -1,3 +0,0 @@
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">;
@@ -1,44 +0,0 @@
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.rateLimitCreditsSpentTotal = exports.retrieveCost = void 0;
27
- const client = __importStar(require("prom-client"));
28
- // Retrieve cost field from response if exists
29
- // If not return default cost of 1
30
- const retrieveCost = (data) => {
31
- const cost = data['cost'];
32
- if (typeof cost === 'number' || typeof cost === 'string') {
33
- return Number(cost);
34
- }
35
- else {
36
- return 1;
37
- }
38
- };
39
- exports.retrieveCost = retrieveCost;
40
- exports.rateLimitCreditsSpentTotal = new client.Counter({
41
- name: 'rate_limit_credits_spent_total',
42
- help: 'The number of data provider credits the adapter is consuming',
43
- labelNames: ['participant_id', 'feed_id'],
44
- });
@@ -1,20 +0,0 @@
1
- import { AdapterRateLimitTier, RateLimiter } from '..';
2
- import { AdapterEndpoint } from '../../adapter';
3
- /**
4
- * This rate limiter is the simplest stateful option.
5
- * On startup, it'll compare the different thresholds for each tier, calculate them all
6
- * in the finest window we'll use (seconds), and use the most restrictive one.
7
- * This is so if the EA were to restart, we don't need to worry about persisting state
8
- * for things like daily quotas. The downside is that this does not work well for bursty
9
- * loads or spikes, in cases where e.g. the per second limit is high but daily quotas low.
10
- */
11
- export declare class SimpleCountingRateLimiter implements RateLimiter {
12
- latestSecondInterval: number;
13
- requestsThisSecond: number;
14
- latestMinuteInterval: number;
15
- requestsThisMinute: number;
16
- perSecondLimit: number;
17
- perMinuteLimit: number;
18
- initialize(endpoints: AdapterEndpoint[], limits?: AdapterRateLimitTier): this;
19
- isUnderLimits(): boolean;
20
- }
@@ -1,62 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SimpleCountingRateLimiter = void 0;
4
- const util_1 = require("../../util");
5
- const logger = (0, util_1.makeLogger)('SimpleCountingRateLimiter');
6
- /**
7
- * This rate limiter is the simplest stateful option.
8
- * On startup, it'll compare the different thresholds for each tier, calculate them all
9
- * in the finest window we'll use (seconds), and use the most restrictive one.
10
- * This is so if the EA were to restart, we don't need to worry about persisting state
11
- * for things like daily quotas. The downside is that this does not work well for bursty
12
- * loads or spikes, in cases where e.g. the per second limit is high but daily quotas low.
13
- */
14
- class SimpleCountingRateLimiter {
15
- constructor() {
16
- this.latestSecondInterval = 0;
17
- this.requestsThisSecond = 0;
18
- this.latestMinuteInterval = 0;
19
- this.requestsThisMinute = 0;
20
- }
21
- initialize(endpoints, limits) {
22
- // Translate the hourly limit into reqs per minute
23
- const perHourLimit = (limits?.rateLimit1h || Infinity) / 60;
24
- this.perMinuteLimit = Math.min(limits?.rateLimit1m || Infinity, perHourLimit);
25
- this.perSecondLimit = limits?.rateLimit1s || Infinity;
26
- logger.debug(`Using rate limiting settings: perMinute = ${this.perMinuteLimit} | perSecond: = ${this.perSecondLimit}`);
27
- return this;
28
- }
29
- isUnderLimits() {
30
- // If the limit is set to infinity, there was no tier limit specified
31
- if (this.perSecondLimit === Infinity && this.perMinuteLimit === Infinity) {
32
- return true;
33
- }
34
- const now = Date.now();
35
- const nearestSecondInterval = Math.floor(now / 1000);
36
- const nearestMinuteInterval = Math.floor(now / (1000 * 60));
37
- // This should always run to completion, even if it doesn't look atomic; therefore the
38
- // Ops should be "thread safe". Thank JS and its infinite single threaded dumbness.
39
- if (nearestSecondInterval !== this.latestSecondInterval) {
40
- logger.trace(`Clearing latest second interval, # of requests logged was: ${this.requestsThisSecond} `);
41
- this.latestSecondInterval = nearestSecondInterval;
42
- this.requestsThisSecond = 0;
43
- }
44
- if (nearestMinuteInterval !== this.latestMinuteInterval) {
45
- logger.trace(`Clearing latest second minute, # of requests logged was: ${this.requestsThisMinute} `);
46
- this.latestMinuteInterval = nearestMinuteInterval;
47
- this.requestsThisMinute = 0;
48
- }
49
- if (this.requestsThisSecond < this.perSecondLimit &&
50
- this.requestsThisMinute < this.perMinuteLimit) {
51
- logger.trace('Request under limits, counting +1');
52
- this.requestsThisSecond++;
53
- this.requestsThisMinute++;
54
- return true;
55
- }
56
- else {
57
- logger.trace('Requests seen this interval are above limits');
58
- return false;
59
- }
60
- }
61
- }
62
- exports.SimpleCountingRateLimiter = SimpleCountingRateLimiter;
package/test.d.ts DELETED
@@ -1 +0,0 @@
1
- export {};
package/test.js DELETED
@@ -1,6 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const _1 = require(".");
4
- const bank_frick_1 = require("./examples/bank-frick");
5
- // Start sample adapter
6
- (0, _1.expose)(bank_frick_1.adapter);
@@ -1,35 +0,0 @@
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: (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
- }