-
Notifications
You must be signed in to change notification settings - Fork 124
/
recon.ts
241 lines (221 loc) · 6.95 KB
/
recon.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import { type CAR } from 'cartonne'
import {
Subject,
defer,
concatMap,
expand,
of,
retry,
timer,
Observable,
Subscription,
filter,
tap,
takeUntil,
Subscriber,
TeardownLogic,
ReplaySubject,
} from 'rxjs'
import { DiagnosticsLogger, FetchRequest, fetchJson, AbortOptions } from '@ceramicnetwork/common'
import { EventID, StreamID } from '@ceramicnetwork/streamid'
import { Model } from '@ceramicnetwork/stream-model'
const DEFAULT_POLL_INTERVAL = 1_000 // 1 seconds
// Note this limit is arbitrary. This limit represents the upper bound on being able to recover after being down
const FEED_LIMIT = 1000
/**
* Configuration for the Recon API
*/
export type ReconApiConfig = {
// Whether the Recon API is enabled
enabled: boolean
// URL of the Recon API or a promise that resolves to the URL
url: string | Promise<string>
// Whether the event feed is enabled
feedEnabled: boolean
}
/**
* Recon Event
*/
export interface ReconEvent {
id: EventID
data: CAR
}
/**
* Recon Event Feed Response
*/
export interface ReconEventFeedResponse {
events: Array<ReconEvent>
cursor: string
}
/**
* Recon API Interface
*/
export interface IReconApi extends Observable<ReconEventFeedResponse> {
init(initialCursor?: string): Promise<void>
registerInterest(model: StreamID): Promise<void>
put(event: ReconEvent, opts?: AbortOptions): Promise<void>
enabled: boolean
stop(): void
}
export class ReconApi extends Observable<ReconEventFeedResponse> implements IReconApi {
readonly #config: ReconApiConfig
readonly #logger: DiagnosticsLogger
readonly #sendRequest: FetchRequest
#url: string
#initialized = false
readonly #pollInterval: number
#eventsSubscription: Subscription
readonly #feed$: Subject<ReconEventFeedResponse> = new Subject()
readonly #stopSignal: Subject<void> = new Subject<void>()
constructor(
config: ReconApiConfig,
logger: DiagnosticsLogger,
sendRequest: FetchRequest = fetchJson,
pollInterval: number = DEFAULT_POLL_INTERVAL
) {
super((subscriber: Subscriber<ReconEventFeedResponse>): TeardownLogic => {
return this.#feed$.subscribe(subscriber)
})
this.#config = config
this.#logger = logger
this.#sendRequest = sendRequest
this.#pollInterval = pollInterval
}
/**
* Initialization tasks. Registers interest in the model and starts polling the feed for new events to emit to subscribers.
* @param initialCursor
* @returns
*/
async init(initialCursor = '0'): Promise<void> {
if (this.#initialized) {
return
}
this.#initialized = true
if (!this.enabled) {
return
}
this.#url = await this.#config.url
await this.registerInterest(Model.MODEL)
if (this.#config.feedEnabled) {
this.#eventsSubscription = this.createSubscription(initialCursor).subscribe(this.#feed$)
}
}
/**
* Registers interest in a model
* @param model stream id of the model to register interest in
*/
async registerInterest(model: StreamID): Promise<void> {
if (!this.enabled) {
throw new Error(`Recon: disabled, not registering interest in model ${model.toString()}`)
}
try {
await this.#sendRequest(this.#url + `/ceramic/interests/model/${model.toString()}`, {
method: 'POST',
})
this.#logger.debug(`Recon: added interest for model ${model.toString()}`)
} catch (err) {
this.#logger.err(
`Recon: failed to register interest in model ${model.toString()} with error ${err}`
)
throw err
}
}
/**
* Put an event to the Recon API
* @param event The event to put
* @param opts Abort options
* @returns
*/
async put(event: ReconEvent, opts: AbortOptions = {}): Promise<void> {
if (!this.enabled) {
this.#logger.imp(`Recon: disabled, not putting event ${event.id}`)
return
}
const body = {
id: event.id.toString(),
data: event.data.toString(),
}
try {
await this.#sendRequest(this.#url + '/ceramic/events', {
method: 'POST',
body,
signal: opts.signal,
})
this.#logger.debug(`Recon: put event ${event.id}`)
} catch (err) {
this.#logger.err(`Recon: failed to add event ${event.id} with error ${err}`)
throw err
}
}
/**
* Whether the Recon API is enabled
*/
get enabled(): boolean {
return this.#config.enabled
}
/**
* Stops the Recon API. This stops the polling and sends a complete signal to subscribers.
*/
stop(): void {
this.#stopSignal.next()
this.#stopSignal.complete()
if (this.#eventsSubscription) {
this.#eventsSubscription.unsubscribe()
}
this.#feed$.complete()
}
/**
* Polls the Recon API for new events using the feed endpoint. This is a turned into an observable that emits the events.
* @param initialCursor The cursor to start polling from
* @returns An observable that emits the events and cursor so it can be stored and used to resume polling during restart
*/
private createSubscription(initialCursor: string): Observable<ReconEventFeedResponse> {
// start event
return of({ events: [], cursor: initialCursor, first: true }).pipe(
// projects the starting event to an Observable that emits the next events. Then it recursively projects each event to an Observable that emits the next event
expand((prev) => {
// creates an observable that emits the next event after a certain delay (pollInterval) unless this is the first event
return timer(prev.first ? 0 : this.#pollInterval).pipe(
// concat map is used to ensure that the next event is only emitted after the previous event has been processed
concatMap(() =>
// defer allows lazy creation of the observable
defer(async () => {
const response = await this.#sendRequest(
this.#url + `/ceramic/feed/events?resumeAt=${prev.cursor}&limit=${FEED_LIMIT}`,
{
method: 'GET',
}
)
return {
events: response.events.map(({ id, _data }) => {
return {
id: EventID.fromString(id),
data: undefined,
}
}),
cursor: response.resumeToken,
first: false,
}
}).pipe(
// if the request fails retry after a certain delay (pollInterval)
retry({
delay: (err) => {
this.#logger.warn(
`Recon: event feed failed, due to error ${err}; attempting to retry in ${
this.#pollInterval
}ms`
)
return timer(this.#pollInterval)
},
})
)
)
)
}),
// filter out events with no data
filter(({ events }) => events.length > 0),
// stop the polling when the stop signal is emitted
takeUntil(this.#stopSignal)
)
}
}