@chainlink/external-adapter-framework 0.0.12 → 0.0.14

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 (278) hide show
  1. package/adapter.d.ts +107 -0
  2. package/adapter.js +115 -0
  3. package/{dist/src/package/background-executor.d.ts → background-executor.d.ts} +0 -0
  4. package/{dist/src/background-executor.js → background-executor.js} +0 -0
  5. package/{dist/src/cache → cache}/factory.d.ts +0 -0
  6. package/{dist/src/cache → cache}/factory.js +0 -0
  7. package/{dist/src/cache → cache}/index.d.ts +8 -8
  8. package/{dist/src/cache → cache}/index.js +0 -0
  9. package/{dist/src/cache → cache}/local.d.ts +0 -0
  10. package/{dist/src/cache → cache}/local.js +0 -0
  11. package/{dist/src/cache → cache}/metrics.d.ts +0 -0
  12. package/{dist/src/cache → cache}/metrics.js +0 -0
  13. package/{dist/src/cache → cache}/redis.d.ts +0 -0
  14. package/{dist/src/cache → cache}/redis.js +0 -0
  15. package/{dist/src/chainlink-external-adapter-framework-0.0.6.tgz → chainlink-external-adapter-framework-0.0.6.tgz} +0 -0
  16. package/{dist/src/config → config}/index.d.ts +0 -5
  17. package/{dist/src/config → config}/index.js +5 -5
  18. package/{dist/src/config → config}/provider-limits.d.ts +0 -0
  19. package/{dist/src/config → config}/provider-limits.js +5 -1
  20. package/{dist/src/examples → examples}/bank-frick/accounts.d.ts +1 -1
  21. package/{dist/src/examples → examples}/bank-frick/accounts.js +2 -3
  22. package/{dist/src/examples → examples}/bank-frick/config/index.d.ts +0 -0
  23. package/{dist/src/examples → examples}/bank-frick/config/index.js +0 -0
  24. package/{dist/src/package/examples/coingecko → examples/bank-frick}/index.d.ts +0 -0
  25. package/{dist/src/examples → examples}/bank-frick/index.js +2 -3
  26. package/{dist/src/examples → examples}/bank-frick/util.d.ts +0 -0
  27. package/{dist/src/examples → examples}/bank-frick/util.js +0 -0
  28. package/{dist/src/package/examples → examples}/coingecko/batch-warming.d.ts +0 -0
  29. package/{dist/src/package/examples → examples}/coingecko/batch-warming.js +0 -0
  30. package/{dist/src/package/examples/ncfx → examples/coingecko}/index.d.ts +0 -0
  31. package/{dist/src/package/examples → examples}/coingecko/index.js +0 -0
  32. package/{dist/src/package/examples → examples}/coingecko/rest.d.ts +0 -0
  33. package/{dist/src/package/examples → examples}/coingecko/rest.js +0 -0
  34. package/{dist/src/examples → examples}/ncfx/config/index.d.ts +0 -0
  35. package/{dist/src/examples → examples}/ncfx/config/index.js +0 -0
  36. package/examples/ncfx/index.d.ts +2 -0
  37. package/{dist/src/package/examples → examples}/ncfx/index.js +0 -0
  38. package/{dist/src/package/examples → examples}/ncfx/websocket.d.ts +0 -0
  39. package/{dist/src/package/examples → examples}/ncfx/websocket.js +0 -0
  40. package/{dist/src/index.d.ts → index.d.ts} +0 -0
  41. package/{dist/src/index.js → index.js} +18 -13
  42. package/{dist/src/metrics → metrics}/constants.d.ts +0 -0
  43. package/{dist/src/metrics → metrics}/constants.js +0 -0
  44. package/{dist/src/metrics → metrics}/index.d.ts +0 -0
  45. package/{dist/src/metrics → metrics}/index.js +0 -0
  46. package/metrics/util.d.ts +7 -0
  47. package/{dist/src/metrics → metrics}/util.js +0 -0
  48. package/{dist/src/package → package}/adapter.d.ts +0 -0
  49. package/{dist/src/package → package}/adapter.js +0 -0
  50. package/{dist/src → package}/background-executor.d.ts +2 -2
  51. package/{dist/src/package → package}/background-executor.js +0 -0
  52. package/{dist/src/package → package}/cache/factory.d.ts +0 -0
  53. package/{dist/src/package → package}/cache/factory.js +0 -0
  54. package/{dist/src/package → package}/cache/index.d.ts +0 -0
  55. package/{dist/src/package → package}/cache/index.js +0 -0
  56. package/{dist/src/package → package}/cache/local.d.ts +0 -0
  57. package/{dist/src/package → package}/cache/local.js +0 -0
  58. package/{dist/src/package → package}/cache/metrics.d.ts +0 -0
  59. package/{dist/src/package → package}/cache/metrics.js +0 -0
  60. package/{dist/src/package → package}/cache/redis.d.ts +0 -0
  61. package/{dist/src/package → package}/cache/redis.js +0 -0
  62. package/{dist/src/package → package}/config/index.d.ts +0 -0
  63. package/{dist/src/package → package}/config/index.js +0 -0
  64. package/{dist/src/package → package}/config/provider-limits.d.ts +0 -0
  65. package/{dist/src/package → package}/config/provider-limits.js +0 -0
  66. package/package/examples/coingecko/batch-warming.d.ts +2 -0
  67. package/{dist/src → package}/examples/coingecko/batch-warming.js +2 -3
  68. package/package/examples/coingecko/index.d.ts +2 -0
  69. package/{dist/src → package}/examples/coingecko/index.js +2 -3
  70. package/package/examples/coingecko/rest.d.ts +2 -0
  71. package/{dist/src → package}/examples/coingecko/rest.js +2 -3
  72. package/{dist/src/package → package}/examples/ncfx/config/index.d.ts +0 -0
  73. package/{dist/src/package → package}/examples/ncfx/config/index.js +0 -0
  74. package/package/examples/ncfx/index.d.ts +2 -0
  75. package/{dist/src → package}/examples/ncfx/index.js +2 -3
  76. package/{dist/src → package}/examples/ncfx/websocket.d.ts +1 -12
  77. package/{dist/src → package}/examples/ncfx/websocket.js +2 -3
  78. package/{dist/src/package → package}/index.d.ts +0 -0
  79. package/{dist/src/package → package}/index.js +0 -0
  80. package/{dist/src/package → package}/metrics/constants.d.ts +0 -0
  81. package/{dist/src/package → package}/metrics/constants.js +0 -0
  82. package/{dist/src/package → package}/metrics/index.d.ts +0 -0
  83. package/{dist/src/package → package}/metrics/index.js +0 -0
  84. package/{dist/src/package → package}/metrics/util.d.ts +0 -0
  85. package/{dist/src/package → package}/metrics/util.js +0 -0
  86. package/{dist/src → package}/package.json +0 -0
  87. package/{dist/src/package → package}/rate-limiting/background/fixed-frequency.d.ts +0 -0
  88. package/{dist/src/package → package}/rate-limiting/background/fixed-frequency.js +0 -0
  89. package/{dist/src/package → package}/rate-limiting/index.d.ts +0 -0
  90. package/{dist/src/package → package}/rate-limiting/index.js +0 -0
  91. package/{dist/src/package → package}/rate-limiting/metrics.d.ts +0 -0
  92. package/{dist/src/package → package}/rate-limiting/metrics.js +0 -0
  93. package/{dist/src/package → package}/rate-limiting/request/simple-counting.d.ts +0 -0
  94. package/{dist/src/package → package}/rate-limiting/request/simple-counting.js +0 -0
  95. package/{dist/src/package → package}/test.d.ts +0 -0
  96. package/{dist/src/package → package}/test.js +0 -0
  97. package/{dist/src/package → package}/transports/batch-warming.d.ts +0 -0
  98. package/{dist/src/package → package}/transports/batch-warming.js +0 -0
  99. package/{dist/src/package → package}/transports/index.d.ts +0 -0
  100. package/{dist/src/package → package}/transports/index.js +0 -0
  101. package/{dist/src/package → package}/transports/metrics.d.ts +0 -0
  102. package/{dist/src/package → package}/transports/metrics.js +0 -0
  103. package/{dist/src/package → package}/transports/rest.d.ts +0 -0
  104. package/{dist/src/package → package}/transports/rest.js +0 -0
  105. package/{dist/src/package → package}/transports/util.d.ts +0 -0
  106. package/{dist/src/package → package}/transports/util.js +0 -0
  107. package/{dist/src/package → package}/transports/websocket.d.ts +0 -0
  108. package/{dist/src/package → package}/transports/websocket.js +0 -0
  109. package/{dist/src/package → package}/util/expiring-sorted-set.d.ts +0 -0
  110. package/{dist/src/package → package}/util/expiring-sorted-set.js +0 -0
  111. package/{dist/src/package → package}/util/index.d.ts +0 -0
  112. package/{dist/src/package → package}/util/index.js +0 -0
  113. package/{dist/src/package → package}/util/logger.d.ts +0 -0
  114. package/{dist/src/package → package}/util/logger.js +0 -0
  115. package/{dist/src/package → package}/util/request.d.ts +0 -0
  116. package/{dist/src/package → package}/util/request.js +0 -0
  117. package/{dist/src/package → package}/validation/error.d.ts +0 -0
  118. package/{dist/src/package → package}/validation/error.js +0 -0
  119. package/{dist/src/package → package}/validation/index.d.ts +0 -0
  120. package/{dist/src/package → package}/validation/index.js +0 -0
  121. package/{dist/src/package → package}/validation/input-params.d.ts +0 -0
  122. package/{dist/src/package → package}/validation/input-params.js +0 -0
  123. package/{dist/src/package → package}/validation/override-functions.d.ts +0 -0
  124. package/{dist/src/package → package}/validation/override-functions.js +0 -0
  125. package/{dist/src/package → package}/validation/preset-tokens.json +0 -0
  126. package/{dist/src/package → package}/validation/validator.d.ts +0 -0
  127. package/{dist/src/package → package}/validation/validator.js +0 -0
  128. package/package.json +1 -1
  129. package/{dist/src/rate-limiting → rate-limiting}/background/fixed-frequency.d.ts +1 -2
  130. package/{dist/src/rate-limiting → rate-limiting}/background/fixed-frequency.js +0 -0
  131. package/{dist/src/rate-limiting → rate-limiting}/index.d.ts +1 -2
  132. package/{dist/src/rate-limiting → rate-limiting}/index.js +0 -0
  133. package/{dist/src/rate-limiting → rate-limiting}/metrics.d.ts +0 -0
  134. package/{dist/src/rate-limiting → rate-limiting}/metrics.js +0 -0
  135. package/{dist/src/rate-limiting → rate-limiting}/request/simple-counting.d.ts +1 -2
  136. package/{dist/src/rate-limiting → rate-limiting}/request/simple-counting.js +0 -0
  137. package/{dist/src/test.d.ts → test.d.ts} +0 -0
  138. package/{dist/src/test.js → test.js} +0 -0
  139. package/{dist/src/transports → transports}/batch-warming.d.ts +0 -0
  140. package/{dist/src/transports → transports}/batch-warming.js +0 -0
  141. package/{dist/src/transports → transports}/index.d.ts +2 -2
  142. package/{dist/src/transports → transports}/index.js +0 -0
  143. package/{dist/src/transports → transports}/metrics.d.ts +1 -2
  144. package/{dist/src/transports → transports}/metrics.js +0 -0
  145. package/{dist/src/transports → transports}/rest.d.ts +0 -0
  146. package/{dist/src/transports → transports}/rest.js +0 -0
  147. package/{dist/src/transports → transports}/util.d.ts +0 -0
  148. package/{dist/src/transports → transports}/util.js +0 -0
  149. package/{dist/src/transports → transports}/websocket.d.ts +3 -2
  150. package/{dist/src/transports → transports}/websocket.js +6 -4
  151. package/{dist/src/util → util}/expiring-sorted-set.d.ts +0 -0
  152. package/{dist/src/util → util}/expiring-sorted-set.js +0 -0
  153. package/{dist/src/util → util}/index.d.ts +0 -0
  154. package/{dist/src/util → util}/index.js +0 -0
  155. package/{dist/src/util → util}/logger.d.ts +0 -0
  156. package/{dist/src/util → util}/logger.js +0 -0
  157. package/{dist/src/util → util}/request.d.ts +2 -2
  158. package/{dist/src/util → util}/request.js +0 -0
  159. package/{dist/src/util → util}/subscription-set/expiring-sorted-set.d.ts +0 -0
  160. package/{dist/src/util → util}/subscription-set/expiring-sorted-set.js +0 -0
  161. package/{dist/src/util → util}/subscription-set/subscription-set.d.ts +0 -0
  162. package/{dist/src/util → util}/subscription-set/subscription-set.js +0 -0
  163. package/{dist/src/util → util}/test-payload-loader.d.ts +0 -0
  164. package/{dist/src/util → util}/test-payload-loader.js +0 -0
  165. package/{dist/src/validation → validation}/error.d.ts +2 -2
  166. package/{dist/src/validation → validation}/error.js +0 -0
  167. package/{dist/src/validation → validation}/index.d.ts +0 -0
  168. package/{dist/src/validation → validation}/index.js +0 -0
  169. package/{dist/src/validation → validation}/input-params.d.ts +0 -0
  170. package/{dist/src/validation → validation}/input-params.js +0 -0
  171. package/validation/override-functions.d.ts +3 -0
  172. package/{dist/src/validation → validation}/override-functions.js +0 -0
  173. package/{dist/src/validation → validation}/preset-tokens.json +0 -0
  174. package/{dist/src/validation → validation}/validator.d.ts +0 -0
  175. package/{dist/src/validation → validation}/validator.js +0 -0
  176. package/.c8rc.json +0 -3
  177. package/.eslintignore +0 -9
  178. package/.eslintrc.js +0 -96
  179. package/.github/README.MD +0 -17
  180. package/.github/actions/setup/action.yaml +0 -13
  181. package/.github/workflows/main.yaml +0 -39
  182. package/.github/workflows/publish.yaml +0 -20
  183. package/.prettierignore +0 -13
  184. package/.yarnrc +0 -0
  185. package/README.md +0 -103
  186. package/dist/src/adapter.d.ts +0 -135
  187. package/dist/src/adapter.js +0 -145
  188. package/dist/src/examples/bank-frick/index.d.ts +0 -2
  189. package/dist/src/examples/coingecko/batch-warming.d.ts +0 -7
  190. package/dist/src/examples/coingecko/index.d.ts +0 -2
  191. package/dist/src/examples/coingecko/rest.d.ts +0 -12
  192. package/dist/src/examples/ncfx/index.d.ts +0 -13
  193. package/dist/src/metrics/util.d.ts +0 -7
  194. package/dist/src/package/package.json +0 -72
  195. package/dist/src/validation/override-functions.d.ts +0 -3
  196. package/docker-compose.yaml +0 -35
  197. package/env.sh +0 -54
  198. package/env2.sh +0 -55
  199. package/publish.sh +0 -0
  200. package/src/adapter.ts +0 -263
  201. package/src/background-executor.ts +0 -52
  202. package/src/cache/factory.ts +0 -26
  203. package/src/cache/index.ts +0 -258
  204. package/src/cache/local.ts +0 -73
  205. package/src/cache/metrics.ts +0 -112
  206. package/src/cache/redis.ts +0 -93
  207. package/src/config/index.ts +0 -517
  208. package/src/config/provider-limits.ts +0 -130
  209. package/src/examples/bank-frick/README.MD +0 -10
  210. package/src/examples/bank-frick/accounts.ts +0 -246
  211. package/src/examples/bank-frick/config/index.ts +0 -53
  212. package/src/examples/bank-frick/index.ts +0 -13
  213. package/src/examples/bank-frick/types.d.ts +0 -38
  214. package/src/examples/bank-frick/util.ts +0 -55
  215. package/src/examples/coingecko/batch-warming.ts +0 -78
  216. package/src/examples/coingecko/index.ts +0 -9
  217. package/src/examples/coingecko/rest.ts +0 -77
  218. package/src/examples/ncfx/config/index.ts +0 -12
  219. package/src/examples/ncfx/index.ts +0 -9
  220. package/src/examples/ncfx/websocket.ts +0 -99
  221. package/src/index.ts +0 -149
  222. package/src/metrics/constants.ts +0 -23
  223. package/src/metrics/index.ts +0 -115
  224. package/src/metrics/util.ts +0 -18
  225. package/src/rate-limiting/background/fixed-frequency.ts +0 -45
  226. package/src/rate-limiting/index.ts +0 -100
  227. package/src/rate-limiting/metrics.ts +0 -18
  228. package/src/rate-limiting/request/simple-counting.ts +0 -76
  229. package/src/test.ts +0 -5
  230. package/src/transports/batch-warming.ts +0 -122
  231. package/src/transports/index.ts +0 -152
  232. package/src/transports/metrics.ts +0 -95
  233. package/src/transports/rest.ts +0 -164
  234. package/src/transports/util.ts +0 -63
  235. package/src/transports/websocket.ts +0 -245
  236. package/src/util/index.ts +0 -22
  237. package/src/util/logger.ts +0 -69
  238. package/src/util/request.ts +0 -117
  239. package/src/util/subscription-set/expiring-sorted-set.ts +0 -54
  240. package/src/util/subscription-set/subscription-set.ts +0 -35
  241. package/src/util/test-payload-loader.ts +0 -87
  242. package/src/validation/error.ts +0 -116
  243. package/src/validation/index.ts +0 -110
  244. package/src/validation/input-params.ts +0 -45
  245. package/src/validation/override-functions.ts +0 -44
  246. package/src/validation/preset-tokens.json +0 -23
  247. package/src/validation/validator.ts +0 -384
  248. package/test/adapter.test.ts +0 -27
  249. package/test/background-executor.test.ts +0 -108
  250. package/test/cache/cache-key.test.ts +0 -114
  251. package/test/cache/helper.ts +0 -100
  252. package/test/cache/local.test.ts +0 -54
  253. package/test/cache/redis.test.ts +0 -89
  254. package/test/correlation.test.ts +0 -114
  255. package/test/index.test.ts +0 -37
  256. package/test/metrics/feed-id.test.ts +0 -38
  257. package/test/metrics/helper.ts +0 -14
  258. package/test/metrics/labels.test.ts +0 -36
  259. package/test/metrics/metrics.test.ts +0 -267
  260. package/test/metrics/redis-metrics.test.ts +0 -113
  261. package/test/metrics/warmer-metrics.test.ts +0 -192
  262. package/test/metrics/ws-metrics.test.ts +0 -225
  263. package/test/rate-limit-config.test.ts +0 -242
  264. package/test/smoke.test.ts +0 -166
  265. package/test/transports/batch.test.ts +0 -465
  266. package/test/transports/rest.test.ts +0 -242
  267. package/test/transports/websocket.test.ts +0 -183
  268. package/test/tsconfig.json +0 -5
  269. package/test/util.ts +0 -77
  270. package/test/validation.test.ts +0 -178
  271. package/test-payload-fail.json +0 -3
  272. package/test-payload.js +0 -22
  273. package/test-payload.json +0 -7
  274. package/test.sh +0 -20
  275. package/test2.sh +0 -2
  276. package/tsconfig.json +0 -25
  277. package/typedoc.json +0 -6
  278. package/webpack.config.js +0 -23
@@ -1,245 +0,0 @@
1
- import WebSocket from 'ws'
2
- import { AdapterContext, AdapterDependencies } from '../adapter'
3
- import { Cache } from '../cache'
4
- import { SettingsMap } from '../config'
5
- import { BackgroundExecuteRateLimiter } from '../rate-limiting'
6
- import { makeLogger, SubscriptionSet } from '../util'
7
- import { AdapterRequest, ProviderResult } from '../util/request'
8
- import { Transport, buildCacheEntriesFromResults } from './'
9
- import * as transportMetrics from './metrics'
10
-
11
- // TODO: Config
12
- export const DEFAULT_WS_TTL = 10000
13
-
14
- const logger = makeLogger('WebSocketTransport')
15
-
16
- type WebSocketClass = new (url: string, protocols?: string | string[] | undefined) => WebSocket
17
-
18
- export class WebSocketClassProvider {
19
- static ctor: WebSocketClass = WebSocket
20
-
21
- static set(ctor: WebSocketClass): void {
22
- this.ctor = ctor
23
- }
24
-
25
- static get(): WebSocketClass {
26
- return this.ctor
27
- }
28
- }
29
-
30
- /**
31
- * Config object that is provided to the WebSocketTransport constructor.
32
- */
33
- export interface WebSocketTransportConfig<
34
- AdapterParams,
35
- ProviderDataMessage,
36
- CustomSettings extends SettingsMap,
37
- > {
38
- /** Endpoint to which to open the WS connection*/
39
- url: string
40
-
41
- /** Map of handlers for different WS lifecycle events */
42
- handlers: {
43
- /**
44
- * Handles when the WS is successfully opened
45
- *
46
- * @param wsConnection - the WebSocket with an established connection
47
- * @returns an empty Promise, or void
48
- */
49
- open: (wsConnection: WebSocket, context: AdapterContext<CustomSettings>) => Promise<void> | void
50
-
51
- /**
52
- * Handles when the WS receives a message
53
- *
54
- * @param message - the message received by the WS
55
- * @param context - the background context for the Adapter
56
- * @returns a list of cache entries of adapter responses to set in the cache
57
- */
58
- message: (
59
- message: ProviderDataMessage,
60
- context: AdapterContext<CustomSettings>,
61
- ) => ProviderResult<AdapterParams>[]
62
- }
63
-
64
- /** Map of "builders", functions that will be used to prepare specific WS messages */
65
- builders: {
66
- /**
67
- * Builds a WS message that will be sent to subscribe to a specific feed
68
- *
69
- * @param params - the body of the adapter request
70
- * @returns the WS message (can be any type as long as the [[WebSocket]] doesn't complain)
71
- */
72
- subscribeMessage: (params: AdapterParams) => unknown
73
-
74
- /**
75
- * Builds a WS message that will be sent to unsubscribe to a specific feed
76
- *
77
- * @param params - the body of the adapter request
78
- * @returns the WS message (can be any type as long as the [[WebSocket]] doesn't complain)
79
- */
80
- unsubscribeMessage: (params: AdapterParams) => unknown
81
- }
82
- }
83
-
84
- /**
85
- * Transport implementation that takes incoming requests, adds them to an [[subscriptionSet]] and,
86
- * through a WebSocket connection, subscribes to the relevant feeds to populate the cache.
87
- *
88
- * @typeParam AdapterParams - interface for the adapter request body
89
- * @typeParam ProviderDataMessage - interface for a WS message containing processable data (i.e. not part of open/close/login/etc)
90
- */
91
- export class WebSocketTransport<
92
- AdapterParams,
93
- ProviderDataMessage,
94
- CustomSettings extends SettingsMap,
95
- > implements Transport<AdapterParams, null, CustomSettings>
96
- {
97
- cache!: Cache
98
- rateLimiter!: BackgroundExecuteRateLimiter
99
- subscriptionSet!: SubscriptionSet<AdapterParams>
100
-
101
- // The double sets serve to create a simple polling mechanism instead of needing a subscription
102
- // This one would not; this is always local state
103
- localSubscriptions: AdapterParams[] = []
104
-
105
- wsConnection!: WebSocket
106
-
107
- constructor(
108
- private config: WebSocketTransportConfig<AdapterParams, ProviderDataMessage, CustomSettings>,
109
- ) {}
110
-
111
- async initialize(dependencies: AdapterDependencies): Promise<void> {
112
- this.cache = dependencies.cache
113
- this.rateLimiter = dependencies.backgroundExecuteRateLimiter
114
- this.subscriptionSet = dependencies.subscriptionSetFactory.buildSet()
115
- }
116
-
117
- async hasBeenSetUp(req: AdapterRequest<AdapterParams>): Promise<boolean> {
118
- return !!(await this.subscriptionSet.get(req.requestContext.cacheKey))
119
- }
120
-
121
- async setup(req: AdapterRequest<AdapterParams>): Promise<void> {
122
- logger.debug(
123
- `Adding entry to subscription set: [${req.requestContext.cacheKey}] = ${req.requestContext.data}`,
124
- )
125
- await this.subscriptionSet.add(
126
- req.requestContext.cacheKey,
127
- req.requestContext.data,
128
- DEFAULT_WS_TTL,
129
- )
130
- }
131
-
132
- // TODO: Maybe we don't do this, and leave the preparation on the adapter's side?
133
- // TODO: Maybe we store adapter params pre-prepared? That would be more efficient
134
- // Assuming always JSON payloads for now, makes it all cleaner
135
- serializeMessage(payload: unknown): string {
136
- return typeof payload === 'string' ? payload : JSON.stringify(payload)
137
- }
138
- deserializeMessage(data: WebSocket.Data): ProviderDataMessage {
139
- return JSON.parse(data.toString()) as ProviderDataMessage
140
- }
141
-
142
- establishWsConnection(context: AdapterContext<CustomSettings>) {
143
- return new Promise((resolve) => {
144
- const ctor = WebSocketClassProvider.get()
145
- this.wsConnection = new ctor(this.config.url)
146
- this.wsConnection.addEventListener('open', async (event: WebSocket.Event) => {
147
- logger.debug(`Opened websocket connection.`)
148
- await this.config.handlers.open(this.wsConnection, context)
149
- logger.debug('Successfully executed connection opened handler')
150
- // Record active ws connections by incrementing count on open
151
- // Using URL in label since connection_key is removed from v3
152
- transportMetrics.wsConnectionActive.inc()
153
- resolve(true)
154
- })
155
- this.wsConnection.addEventListener('message', async (event: WebSocket.MessageEvent) => {
156
- // TODO: Assuming JSON always, maybe use BSON also?
157
- const parsed = this.deserializeMessage(event.data)
158
- logger.trace(`Got ws message: ${parsed}`)
159
- const results = this.config.handlers.message(parsed, context)
160
- if (Array.isArray(results)) {
161
- const responses = buildCacheEntriesFromResults(results, context)
162
- logger.trace(`Writing ${responses.length} responses to cache`)
163
- await this.cache.setMany(responses, context.adapterConfig.CACHE_MAX_AGE)
164
- }
165
- })
166
- this.wsConnection.addEventListener('error', async (event: WebSocket.ErrorEvent) => {
167
- // Record connection error count
168
- transportMetrics.wsConnectionErrors
169
- .labels(transportMetrics.connectionErrorLabels(event.message))
170
- .inc()
171
- })
172
- this.wsConnection.addEventListener('close', (event: WebSocket.CloseEvent) => {
173
- logger.debug(
174
- `Closed websocket connection. Code: ${event.code} ; reason: ${event.reason?.toString()}`,
175
- )
176
- // Record active ws connections by decrementing count on close
177
- // Using URL in label since connection_key is removed from v3
178
- transportMetrics.wsConnectionActive.dec()
179
- })
180
- })
181
- }
182
-
183
- // Unlike cache warming, this execute will manage subscriptions
184
- async backgroundExecute(context: AdapterContext<CustomSettings>): Promise<number> {
185
- logger.debug('Starting background execute, getting subscriptions from sorted set')
186
- const desiredSubs = await this.subscriptionSet.getAll()
187
-
188
- logger.debug('Generating delta (subscribes & unsubscribes)')
189
- // TODO: More efficient algorithm, this is really easy to read, but high(er) time complexity
190
- const subscribeParams = desiredSubs.filter((s) => !this.localSubscriptions.includes(s))
191
- const subscribes = subscribeParams
192
- .map(this.config.builders.subscribeMessage)
193
- .map(this.serializeMessage)
194
-
195
- const unsubscribeParams = this.localSubscriptions.filter((s) => !desiredSubs.includes(s))
196
- const unsubscribes = unsubscribeParams
197
- .map(this.config.builders.unsubscribeMessage)
198
- .map(this.serializeMessage)
199
-
200
- logger.debug(`${subscribes.length} new subscriptions; ${unsubscribes.length} to unsubscribe`)
201
- if (subscribes.length) {
202
- logger.trace(`Will subscribe to: ${subscribes}`)
203
- }
204
- if (unsubscribes.length) {
205
- logger.trace(`Will unsubscribe to: ${unsubscribes}`)
206
- }
207
-
208
- // New subs && no connection -> connect -> add subs
209
- // No new subs && no connection -> skip
210
- // New subs && connection -> add subs
211
- // No new subs && connection -> unsubs only
212
-
213
- if (!subscribes.length && !this.wsConnection) {
214
- logger.debug('No entries in subscription set and no established connection, skipping')
215
- return this.rateLimiter.msUntilNextExecution(context.adapterEndpoint.name)
216
- }
217
-
218
- if (!this.wsConnection && subscribes.length) {
219
- logger.debug('No established connection and new subscriptions available, connecting to WS')
220
- await this.establishWsConnection(context)
221
- }
222
-
223
- // TODO: Close connection at some point?
224
-
225
- logger.debug('Sending subs/unsubs if there are any')
226
- const messages = unsubscribes.concat(subscribes)
227
- for (const message of messages) {
228
- logger.trace(`Sending message: ${JSON.stringify(message)}`)
229
- this.wsConnection.send(message)
230
- }
231
-
232
- // Record WS message and subscription metrics
233
- transportMetrics.recordWsMessageMetrics(
234
- context as AdapterContext,
235
- subscribeParams,
236
- unsubscribeParams,
237
- )
238
-
239
- logger.debug('Setting local state to cache value')
240
- this.localSubscriptions = desiredSubs
241
-
242
- logger.debug('Background execute complete')
243
- return this.rateLimiter.msUntilNextExecution(context.adapterEndpoint.name)
244
- }
245
- }
package/src/util/index.ts DELETED
@@ -1,22 +0,0 @@
1
- export * from './request'
2
- export * from './logger'
3
- export * from './subscription-set/subscription-set'
4
-
5
- /**
6
- * Sleeps for the provided number of milliseconds
7
- * @param ms - The number of milliseconds to sleep for
8
- * @returns a Promise that resolves once the specified time passes
9
- */
10
- export const sleep = (ms: number): Promise<void> => {
11
- return new Promise((resolve) => {
12
- setTimeout(resolve, ms)
13
- })
14
- }
15
-
16
- export const isObject = (o: unknown): boolean =>
17
- o !== null && typeof o === 'object' && Array.isArray(o) === false
18
-
19
- export const isArray = (o: unknown): boolean =>
20
- o !== null && typeof o === 'object' && Array.isArray(o)
21
-
22
- export type PromiseOrValue<T> = Promise<T> | T
@@ -1,69 +0,0 @@
1
- import pino from 'pino'
2
- import { BaseSettings } from '../config'
3
- import { AdapterRequest } from './request'
4
- import { FastifyReply, HookHandlerDoneFunction } from 'fastify'
5
- import { randomUUID } from 'crypto'
6
- import { AsyncLocalStorage } from 'node:async_hooks'
7
-
8
- export const asyncLocalStorage = new AsyncLocalStorage()
9
-
10
- export type Store = {
11
- correlationId: string
12
- }
13
-
14
- const debugTransport = {
15
- target: 'pino-pretty',
16
- options: {
17
- levelFirst: true,
18
- levelLabel: 'level',
19
- ignore: 'layer,pid,hostname',
20
- messageFormat: '[{correlationId}][{layer}] {msg}',
21
- translateTime: 'yyyy-mm-dd HH:MM:ss.l',
22
- },
23
- }
24
-
25
- // Base logger, shouldn't be used because we want layers to be specified
26
- const baseLogger = pino({
27
- level: process.env['LOG_LEVEL']?.toLowerCase() || BaseSettings.LOG_LEVEL.default,
28
- mixin() {
29
- if (process.env['CORRELATION_ID_ENABLED'] === 'true') {
30
- const store = asyncLocalStorage.getStore() as Store
31
- if (store) {
32
- return store
33
- }
34
- }
35
- return {}
36
- },
37
- transport: process.env['DEBUG'] === 'true' ? debugTransport : undefined,
38
- })
39
-
40
- /**
41
- * Instead of using a global logger instance, we want to force using a child logger
42
- * with a specific layer set in it, so that we can filter logs by where they're output from.
43
- *
44
- * Details on what each log level represents:
45
- * "trace": Forensic debugging of issues on a local machine.
46
- * "debug": Detailed logging level to get more context from users on their environments.
47
- * "info": High-level informational messages, to describe at a glance the high level state of the system.
48
- * "warn": A mild error occurred that might require non-urgent action.
49
- * "error": An unexpected error occurred during the regular operation of a well-maintained EA.
50
- * "fatal": The EA encountered an unrecoverable problem and had to exit.
51
- *
52
- * Full reference this is based on can be found at
53
- * https://github.com/smartcontractkit/documentation/blob/main/docs/Node%20Operators/configuration-variables.md#log_level
54
- *
55
- * @param layer - the layer name to include in the logs (e.g. "SomeMiddleware", "RedisCache", etc.)
56
- * @returns a layer specific logger
57
- */
58
- export const makeLogger = (layer: string) => baseLogger.child({ layer })
59
-
60
- export const loggingContextMiddleware = (
61
- req: AdapterRequest,
62
- res: FastifyReply,
63
- done: HookHandlerDoneFunction,
64
- ) => {
65
- const correlationId = req.headers['x-correlation-id'] || randomUUID()
66
- asyncLocalStorage.run({ correlationId: correlationId }, () => {
67
- done()
68
- })
69
- }
@@ -1,117 +0,0 @@
1
- import { FastifyReply, FastifyRequest, HookHandlerDoneFunction } from 'fastify'
2
- import { InitializedAdapter } from '../adapter'
3
- import { AdapterError } from '../validation/error'
4
- declare module 'fastify' {
5
- // eslint-disable-next-line no-shadow
6
- export interface FastifyRequest {
7
- requestContext: AdapterRequestContext
8
- }
9
- }
10
-
11
- export interface AdapterRequestBody<T = AdapterRequestData> {
12
- endpoint?: string
13
- data: T
14
- id?: string
15
- }
16
-
17
- export type AdapterRequestContext<T = AdapterRequestData> = {
18
- id: string
19
- endpointName: string
20
- cacheKey: string
21
- data: T // AdapterRequestData
22
- meta?: AdapterRequestMeta
23
- // MetricsMeta?: AdapterMetricsMeta
24
- // Debug?: AdapterDebug
25
- // RateLimitMaxAge?: number
26
- }
27
-
28
- export type AdapterRouteGeneric<T = AdapterRequestData> = {
29
- Body: AdapterRequestBody<T>
30
- }
31
-
32
- export type AdapterRequest<T = AdapterRequestData> = FastifyRequest<AdapterRouteGeneric<T>> & {
33
- // TODO: Uncomment line below & fix compile issues
34
- // body: never // So the user does not access the raw request data and uses the Validated one instead
35
- requestContext: AdapterRequestContext<T>
36
- }
37
-
38
- // Export type AdapterRequestMeta = {
39
- // AvailableFunds?: number
40
- // EligibleToSubmit?: boolean
41
- // LatestAnswer?: number
42
- // OracleCount?: number
43
- // PaymentAmount?: number
44
- // ReportableRoundID?: number
45
- // StartedAt?: number
46
- // Timeout?: number
47
- // }
48
-
49
- // Export type AdapterDebug = {
50
- // Ws?: boolean
51
- // Warmer?: boolean
52
- // CacheHit?: boolean
53
- // Staleness?: number
54
- // Performance?: number
55
- // ProviderCost?: number
56
- // BatchablePropertyPath?: cacheWarmer.reducer.BatchableProperty[]
57
- // NormalizedRequest?: Record<string, unknown>
58
- // }
59
-
60
- /**
61
- * Meta info that pertains to exposing metrics
62
- */
63
- export interface AdapterRequestMeta {
64
- metrics?: AdapterMetricsMeta
65
- error?: AdapterError | Error
66
- }
67
-
68
- /**
69
- * Meta info that pertains to exposing metrics
70
- */
71
- export interface AdapterMetricsMeta {
72
- feedId?: string
73
- cacheHit?: boolean
74
- }
75
-
76
- export type AdapterRequestData = Record<string, unknown> & {
77
- endpoint?: string
78
- }
79
-
80
- // Export interface AdapterRequest<T = AdapterRequestData> extends Request {
81
- // AdapterContext: {
82
- // Id: string
83
- // Endpoint: string
84
- // Data: T //AdapterRequestData
85
- // CacheKey: string
86
- // // meta?: AdapterRequestMeta
87
- // // metricsMeta?: AdapterMetricsMeta
88
- // // debug?: AdapterDebug
89
- // // rateLimitMaxAge?: number
90
- // }
91
- // }
92
-
93
- export interface ProviderResult<Params> {
94
- params: Params
95
- value: unknown
96
- }
97
-
98
- export type AdapterResponse<T = unknown> = {
99
- // JobRunID: string
100
- statusCode: number
101
- data: T // Response data, holds "result" for Flux Monitor. Correct way.
102
- result: unknown // Result for OCR
103
- maxAge?: number // TODO: Replace with new telemetry structure
104
- meta?: AdapterRequestMeta
105
- // Debug?: AdapterDebug
106
- providerStatusCode?: number
107
- }
108
-
109
- export type Middleware =
110
- | ((
111
- req: AdapterRequest,
112
- reply: FastifyReply,
113
- done: HookHandlerDoneFunction,
114
- ) => FastifyReply | void)
115
- | ((req: AdapterRequest, reply: FastifyReply) => Promise<FastifyReply | void>)
116
-
117
- export type AdapterMiddlewareBuilder = (adapter: InitializedAdapter) => Middleware
@@ -1,54 +0,0 @@
1
- import { SubscriptionSet } from './subscription-set'
2
-
3
- /**
4
- * An object describing an entry in the expiring sorted set.
5
- * @typeParam T - the type of the entry's value
6
- */
7
- interface ExpiringSortedSetEntry<T> {
8
- value: T
9
- expirationTimestamp: number
10
- }
11
-
12
- /**
13
- * This class implements a set of unique items, each of which has an expiration timestamp.
14
- * On reads, items that have expired will be deleted from the set and not returned.
15
- *
16
- * @typeParam T - the type of the set entries' values
17
- */
18
- export class ExpiringSortedSet<T> implements SubscriptionSet<T> {
19
- map = new Map<string, ExpiringSortedSetEntry<T>>()
20
-
21
- add(key: string, value: T, ttl: number) {
22
- this.map.set(key, {
23
- value,
24
- expirationTimestamp: Date.now() + ttl,
25
- })
26
- }
27
-
28
- get(key: string) {
29
- const entry = this.map.get(key)
30
- if (!entry) {
31
- return
32
- } else if (entry.expirationTimestamp < Date.now()) {
33
- return entry.value
34
- } else {
35
- this.map.delete(key)
36
- }
37
- }
38
-
39
- getAll(): T[] {
40
- const results: T[] = []
41
- const now = Date.now()
42
-
43
- // Since we're iterating, might as well prune here
44
- for (const [key, entry] of this.map.entries()) {
45
- if (entry.expirationTimestamp < now) {
46
- this.map.delete(key) // In theory, this shouldn't happen frequently for feeds
47
- } else {
48
- results.push(entry.value)
49
- }
50
- }
51
-
52
- return results
53
- }
54
- }
@@ -1,35 +0,0 @@
1
- import { PromiseOrValue } from '..'
2
- import { AdapterConfig } from '../../config'
3
- import { ExpiringSortedSet } from './expiring-sorted-set'
4
-
5
- /**
6
- * Set to hold items to subscribe to from a provider (regardless of protocol)
7
- */
8
- export interface SubscriptionSet<T> {
9
- /** Add a new subscription to the set */
10
- add(key: string, value: T, ttl: number): PromiseOrValue<void>
11
-
12
- /** Get a specific subscription from the set */
13
- get(key: string): PromiseOrValue<T | undefined>
14
-
15
- /** Get all subscriptions from the set as a list */
16
- getAll(): PromiseOrValue<T[]>
17
- }
18
-
19
- export class SubscriptionSetFactory {
20
- private cacheType: AdapterConfig['CACHE_TYPE']
21
-
22
- constructor(config: AdapterConfig) {
23
- this.cacheType = config.CACHE_TYPE
24
- }
25
-
26
- buildSet<T>(): SubscriptionSet<T> {
27
- switch (this.cacheType) {
28
- case 'local':
29
- return new ExpiringSortedSet<T>()
30
- case 'redis':
31
- // TODO: Implement redis set
32
- return new ExpiringSortedSet<T>()
33
- }
34
- }
35
- }
@@ -1,87 +0,0 @@
1
- import Ajv from 'ajv'
2
- import fs from 'fs'
3
- import path from 'path'
4
- import { makeLogger } from './logger'
5
- import { AdapterRequestData } from './request'
6
-
7
- const logger = makeLogger('TestPayloadLoader')
8
-
9
- /**
10
- * The test payload read in from filesystem
11
- */
12
- export interface Payload {
13
- requests: Array<AdapterRequestData>
14
- }
15
-
16
- /**
17
- * Test payload with discriminated union so we can tell when we should just do
18
- * a simple liveness check rather than a sample request
19
- */
20
- type TestPayload = (Payload & { isDefault: false }) | { isDefault: true }
21
-
22
- /**
23
- * Load in a JSON file containing a test payload for the current adapter,
24
- * used in healthchecks to make sample requests
25
- *
26
- * @param fileName - name of file that contains the test payload data for the smoke endpoint
27
- * @returns the parsed payload with individual requests
28
- */
29
- export function loadTestPayload(fileName?: string): TestPayload {
30
- const ajv = new Ajv()
31
- const schema = {
32
- type: 'object',
33
- required: ['requests'],
34
- properties: {
35
- requests: {
36
- type: 'array',
37
- items: {
38
- type: 'object',
39
- required: [],
40
- },
41
- },
42
- },
43
- }
44
- const validate = ajv.compile(schema)
45
- try {
46
- const payload = resolvePayload(fileName)
47
- if (!validate(payload) || !payload?.requests) {
48
- throw Error(JSON.stringify(validate?.errors || 'Could not validate schema for test payload'))
49
- }
50
- return { ...payload, isDefault: false }
51
- } catch (e: unknown) {
52
- logger.warn(`Could not load payload: ${(e as Error).message}`)
53
- logger.warn('Falling back to default empty payload')
54
- return { isDefault: true }
55
- }
56
- }
57
-
58
- function resolvePayload(fileName?: string): Payload | null {
59
- try {
60
- let payload = null
61
- // Find test payload by specified name, fallback to default names if not found
62
- if (fileName && fs.existsSync(path.join(process.cwd(), fileName))) {
63
- payload = require(path.join(process.cwd(), fileName))
64
- } else if (fileName && fs.existsSync(`./${fileName}`)) {
65
- payload = require(`./${fileName}`)
66
- }
67
- // Search for test payload js first if no filename specified or found
68
- else if (fs.existsSync(path.resolve('.', 'test-payload.js'))) {
69
- payload = require(path.join(process.cwd(), 'test-payload.js'))
70
- } else if (fs.existsSync(`./test-payload.js`)) {
71
- payload = require(`./test-payload.js`)
72
- }
73
- // Search for test payload json second if no filename specified or found
74
- else if (fs.existsSync(path.join(process.cwd(), 'test-payload.json'))) {
75
- payload = require(path.join(process.cwd(), 'test-payload.json'))
76
- } else if (fs.existsSync(`./test-payload.json`)) {
77
- payload = require(`./test-payload.json`)
78
- }
79
- if (typeof payload === 'string') {
80
- return JSON.parse(payload)
81
- } else {
82
- return payload
83
- }
84
- } catch {
85
- return null
86
- }
87
- }