-
Notifications
You must be signed in to change notification settings - Fork 55
/
OgmiosObservableCardanoNode.ts
164 lines (156 loc) · 6.22 KB
/
OgmiosObservableCardanoNode.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// Tested in packages/e2e/test/projection
import {
Cardano,
CardanoNodeErrors,
EraSummary,
HealthCheckResponse,
Milliseconds,
ObservableCardanoNode,
ObservableChainSync,
PointOrOrigin
} from '@cardano-sdk/core';
import {
ConnectionConfig,
createConnectionObject,
createStateQueryClient,
getServerHealth
} from '@cardano-ogmios/client';
import { InteractionContextProps, createObservableInteractionContext } from './createObservableInteractionContext';
import { Intersection, findIntersect } from '@cardano-ogmios/client/dist/ChainSync';
import { Logger } from 'ts-log';
import {
Observable,
catchError,
distinctUntilChanged,
from,
map,
of,
shareReplay,
switchMap,
throwError,
timeout
} from 'rxjs';
import { RetryBackoffConfig, retryBackoff } from 'backoff-rxjs';
import { WithLogger, contextLogger } from '@cardano-sdk/util';
import { createObservableChainSyncClient } from './createObservableChainSyncClient';
import { ogmiosServerHealthToHealthCheckResponse } from '../../util';
import { ogmiosToCorePointOrOrigin, ogmiosToCoreTipOrOrigin, pointOrOriginToOgmios } from './util';
import { queryEraSummaries, queryGenesisParameters } from '../queries';
import isEqual from 'lodash/isEqual';
const ogmiosToCoreIntersection = (intersection: Intersection) => ({
point: ogmiosToCorePointOrOrigin(intersection.point),
tip: ogmiosToCoreTipOrOrigin(intersection.tip)
});
export type LocalStateQueryRetryConfig = Pick<RetryBackoffConfig, 'initialInterval' | 'maxInterval'>;
const DEFAULT_HEALTH_CHECK_TIMEOUT = 2000;
const DEFAULT_LSQ_RETRY_CONFIG: LocalStateQueryRetryConfig = {
initialInterval: 1000,
maxInterval: 30_000
};
export type OgmiosObservableCardanoNodeProps = Omit<InteractionContextProps, 'interactionType'> & {
/** Default: 2000ms */
healthCheckTimeout?: Milliseconds;
/** Default: {initialInterval: 1000, maxInterval: 30_000} */
localStateQueryRetryConfig?: LocalStateQueryRetryConfig;
};
const stateQueryRetryBackoffConfig = (
retryConfig: LocalStateQueryRetryConfig = DEFAULT_LSQ_RETRY_CONFIG,
logger: Logger
): RetryBackoffConfig => ({
...retryConfig,
shouldRetry: (error) => {
if (error instanceof CardanoNodeErrors.CardanoClientErrors.QueryUnavailableInCurrentEraError) {
logger.info('Local state query unavailable yet, will retry...');
return true;
}
return false;
}
});
export class OgmiosObservableCardanoNode implements ObservableCardanoNode {
readonly #connectionConfig$: Observable<ConnectionConfig>;
readonly #logger: Logger;
readonly #interactionContext$;
readonly eraSummaries$: Observable<EraSummary[]>;
readonly genesisParameters$: Observable<Cardano.CompactGenesis>;
readonly healthCheck$: Observable<HealthCheckResponse>;
constructor(props: OgmiosObservableCardanoNodeProps, { logger }: WithLogger) {
this.#connectionConfig$ = props.connectionConfig$;
this.#logger = contextLogger(logger, 'ObservableOgmiosCardanoNode');
this.#interactionContext$ = createObservableInteractionContext(
{
...props,
interactionType: 'LongRunning'
},
{ logger: this.#logger }
).pipe(shareReplay({ bufferSize: 1, refCount: true }));
const stateQueryClient$ = this.#interactionContext$.pipe(
switchMap((interactionContext) => from(createStateQueryClient(interactionContext))),
distinctUntilChanged((a, b) => isEqual(a, b)),
shareReplay({ bufferSize: 1, refCount: true })
);
this.eraSummaries$ = stateQueryClient$.pipe(
switchMap((client) => from(queryEraSummaries(client, this.#logger))),
retryBackoff(stateQueryRetryBackoffConfig(props.localStateQueryRetryConfig, logger))
);
this.genesisParameters$ = stateQueryClient$.pipe(
switchMap((client) => from(queryGenesisParameters(client, this.#logger))),
retryBackoff(stateQueryRetryBackoffConfig(props.localStateQueryRetryConfig, logger)),
distinctUntilChanged(isEqual),
shareReplay({ bufferSize: 1, refCount: true })
);
this.healthCheck$ = this.#connectionConfig$.pipe(
switchMap((connectionConfig) => from(getServerHealth({ connection: createConnectionObject(connectionConfig) }))),
map(ogmiosServerHealthToHealthCheckResponse),
timeout({
first: props.healthCheckTimeout || DEFAULT_HEALTH_CHECK_TIMEOUT,
with: () => {
logger.error('healthCheck$ didnt emit within healthCheckTimeout');
return throwError(() => new CardanoNodeErrors.CardanoClientErrors.ConnectionError());
}
}),
catchError((error) => {
this.#logger.error(error);
return of({ ok: false });
}),
shareReplay({ bufferSize: 1, refCount: true })
);
}
/**
* See {@link ObservableCardanoNode.findIntersect}.
*
* This implementation of `chainSync$` in the emitted object should only have
* a single subscriber per client (instance of OgmiosObservableCardanoNode),
* because it's using a stateful connection - limited to 1 cursor per connection.
*/
findIntersect(points: PointOrOrigin[]) {
return this.#interactionContext$.pipe(
switchMap(
(interactionContext) =>
new Observable<ObservableChainSync>((subscriber) => {
// eslint-disable-next-line promise/always-return
if (subscriber.closed) return;
void findIntersect(interactionContext, points.map(pointOrOriginToOgmios))
// eslint-disable-next-line promise/always-return
.then((ogmiosIntersection) => {
const intersection = ogmiosToCoreIntersection(ogmiosIntersection);
subscriber.next({
chainSync$: createObservableChainSyncClient(
{ intersectionPoint: intersection.point },
{ interactionContext$: this.#interactionContext$, logger: this.#logger }
),
intersection
});
})
.catch((error) => {
this.#logger.error('"findIntersect" failed', error);
if (error instanceof CardanoNodeErrors.CardanoClientErrors.ConnectionError) {
// interactionContext$ will reconnect and trigger a retry
return;
}
subscriber.error(error);
});
})
)
);
}
}