-
Notifications
You must be signed in to change notification settings - Fork 72
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import { ResourceCacheManager } from '@/abacus-ts/lib/resourceCacheManager'; | ||
import stableStringify from 'fast-json-stable-stringify'; | ||
|
||
import { IndexerWebsocket } from './indexerWebsocket'; | ||
import { IndexerWebsocketManager } from './indexerWebsocketManager'; | ||
import { WebsocketDerivedValue } from './websocketDerivedValue'; | ||
|
||
type WebsocketValueCreator<Args, ReturnType> = ( | ||
websocket: IndexerWebsocket, | ||
args: Args | ||
) => WebsocketDerivedValue<ReturnType>; | ||
|
||
export function makeWsValueManager<Args, ReturnType>( | ||
creator: WebsocketValueCreator<Args, ReturnType> | ||
): ResourceCacheManager<WebsocketDerivedValue<ReturnType>, Args & { wsUrl: string }> { | ||
return new ResourceCacheManager({ | ||
constructor: (allArgs: Args & { wsUrl: string }) => | ||
creator(IndexerWebsocketManager.use(allArgs.wsUrl), allArgs), | ||
|
||
destroyer: (instance, { wsUrl }) => { | ||
instance.teardown(); | ||
IndexerWebsocketManager.markDone(wsUrl); | ||
}, | ||
|
||
// take care - extra properties on the key will cause divergent behavior | ||
// (cache misses, unexpected new object creation, marking incorrect objects as done, etc) | ||
// only ever pass the exact key type for correct behavior | ||
keySerializer: (allArgs) => stableStringify(allArgs), | ||
|
||
// this is set to just above the websocket subscribe timeout because of race conditions in the indexer backend | ||
destroyDelayMs: 21000, | ||
}); | ||
} | ||
|
||
export function subscribeToWsValue<Args, ReturnType>( | ||
manager: ResourceCacheManager<WebsocketDerivedValue<ReturnType>, Args & { wsUrl: string }>, | ||
args: NoInfer<Args> & { wsUrl: string }, | ||
handleChange: (val: NoInfer<ReturnType>) => void | ||
): () => void { | ||
const value = manager.use(args); | ||
const unsub = value.subscribe(handleChange); | ||
return () => { | ||
unsub(); | ||
manager.markDone(args); | ||
}; | ||
} |