@midnightntwrk/wallet-sdk-indexer-client 2.0.0-rc.1 → 2.0.0
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.
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// This file is part of MIDNIGHT-WALLET-SDK.
|
|
2
|
+
// Copyright (C) Midnight Foundation
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
// You may not use this file except in compliance with the License.
|
|
6
|
+
// You may obtain a copy of the License at
|
|
7
|
+
// http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
// Unless required by applicable law or agreed to in writing, software
|
|
9
|
+
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
10
|
+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
|
+
// See the License for the specific language governing permissions and
|
|
12
|
+
// limitations under the License.
|
|
13
|
+
import { Array as EArray, Chunk, Deferred, Effect, Fiber, Stream } from 'effect';
|
|
14
|
+
import { describe, expect, it } from 'vitest';
|
|
15
|
+
import { withBackpressure } from '../Backpressure.js';
|
|
16
|
+
const newLog = () => ({
|
|
17
|
+
sessions: [],
|
|
18
|
+
disposals: 0,
|
|
19
|
+
delivered: 0,
|
|
20
|
+
fresh: 0,
|
|
21
|
+
consumed: 0,
|
|
22
|
+
peakUnconsumed: 0,
|
|
23
|
+
maxDeliveredKey: 0n,
|
|
24
|
+
});
|
|
25
|
+
const nextMacrotask = () => new Promise((resolve) => setImmediate(resolve));
|
|
26
|
+
/**
|
|
27
|
+
* A source over the keys `1..total` with an inclusive cursor, like the indexer's event subscriptions: opened at cursor
|
|
28
|
+
* `c` it re-delivers `c` itself (when `c >= 1`) and then everything after it. It delivers one item per macrotask, the
|
|
29
|
+
* way WebSocket frames arrive, and honours the {@link Source} contract by delivering nothing once disposed.
|
|
30
|
+
*/
|
|
31
|
+
const fakeSource = (total, log) => ({ variables, onItem, onComplete }) => {
|
|
32
|
+
const state = { disposed: false, next: variables.cursor < 1n ? 1n : variables.cursor };
|
|
33
|
+
log.sessions.push({
|
|
34
|
+
cursor: variables.cursor,
|
|
35
|
+
maxKeyAtOpen: log.maxDeliveredKey,
|
|
36
|
+
unconsumedAtOpen: log.fresh - log.consumed,
|
|
37
|
+
});
|
|
38
|
+
const step = () => {
|
|
39
|
+
if (state.disposed)
|
|
40
|
+
return;
|
|
41
|
+
if (state.next > total) {
|
|
42
|
+
onComplete();
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const key = state.next;
|
|
46
|
+
state.next = key + 1n;
|
|
47
|
+
log.delivered += 1;
|
|
48
|
+
if (key > log.maxDeliveredKey) {
|
|
49
|
+
log.fresh += 1;
|
|
50
|
+
log.maxDeliveredKey = key;
|
|
51
|
+
}
|
|
52
|
+
log.peakUnconsumed = Math.max(log.peakUnconsumed, log.fresh - log.consumed);
|
|
53
|
+
onItem(key);
|
|
54
|
+
setImmediate(step);
|
|
55
|
+
};
|
|
56
|
+
setImmediate(step);
|
|
57
|
+
return () => {
|
|
58
|
+
state.disposed = true;
|
|
59
|
+
log.disposals += 1;
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
const options = (bufferSize, resumeThreshold) => ({
|
|
63
|
+
bufferSize,
|
|
64
|
+
resumeThreshold,
|
|
65
|
+
from: 0n,
|
|
66
|
+
variables: (cursor) => ({ cursor }),
|
|
67
|
+
key: (item) => item,
|
|
68
|
+
});
|
|
69
|
+
/** Resolves once the source has gone `quietFor` macrotasks without delivering anything. */
|
|
70
|
+
const sourceQuiescent = async (log, quietFor = 50) => {
|
|
71
|
+
const settle = async (lastDelivered, quiet) => {
|
|
72
|
+
if (quiet >= quietFor)
|
|
73
|
+
return;
|
|
74
|
+
await nextMacrotask();
|
|
75
|
+
return settle(log.delivered, log.delivered === lastDelivered ? quiet + 1 : 0);
|
|
76
|
+
};
|
|
77
|
+
return settle(log.delivered, 0);
|
|
78
|
+
};
|
|
79
|
+
describe('withBackpressure', () => {
|
|
80
|
+
const bufferSize = 10;
|
|
81
|
+
const resumeThreshold = 3;
|
|
82
|
+
// Long enough that an unbounded queue is unmistakable next to the bound.
|
|
83
|
+
const total = 200n;
|
|
84
|
+
it('stops the source once the consumer falls bufferSize behind, and keeps no more than that queued', async () => {
|
|
85
|
+
const log = newLog();
|
|
86
|
+
const release = Effect.runSync(Deferred.make());
|
|
87
|
+
// The consumer takes the first item and then stalls, so everything after it can only queue up.
|
|
88
|
+
const run = withBackpressure(fakeSource(total, log), options(bufferSize, resumeThreshold)).pipe(Stream.mapEffect((item) => Effect.sync(() => {
|
|
89
|
+
log.consumed += 1;
|
|
90
|
+
}).pipe(Effect.zipRight(Deferred.await(release)), Effect.as(item))), Stream.runDrain, Effect.runFork);
|
|
91
|
+
await sourceQuiescent(log);
|
|
92
|
+
// The item held by the stalled consumer was handed to it, so it is the one item above bufferSize.
|
|
93
|
+
expect(log.disposals).toBe(1);
|
|
94
|
+
expect(log.delivered).toBeLessThanOrEqual(bufferSize + 1);
|
|
95
|
+
expect(log.peakUnconsumed).toBeLessThanOrEqual(bufferSize + 1);
|
|
96
|
+
await Effect.runPromise(Fiber.interrupt(run));
|
|
97
|
+
});
|
|
98
|
+
it('closes the live source session when the consumer stops early', async () => {
|
|
99
|
+
const log = newLog();
|
|
100
|
+
const taken = await withBackpressure(fakeSource(total, log), options(bufferSize, resumeThreshold)).pipe(Stream.take(3), Stream.runCollect, Effect.runPromise);
|
|
101
|
+
const deliveredAtClose = log.delivered;
|
|
102
|
+
await sourceQuiescent(log, 20);
|
|
103
|
+
expect(Chunk.toReadonlyArray(taken)).toEqual([1n, 2n, 3n]);
|
|
104
|
+
expect(log.disposals).toBe(log.sessions.length);
|
|
105
|
+
// Nothing reaches the closed session afterwards.
|
|
106
|
+
expect(log.delivered).toBe(deliveredAtClose);
|
|
107
|
+
});
|
|
108
|
+
it('resumes from the last emitted key after draining, delivering every key exactly once across many pauses', async () => {
|
|
109
|
+
const log = newLog();
|
|
110
|
+
// The consumer takes three macrotasks per item against the source's one, so it keeps falling behind and the
|
|
111
|
+
// source is paused and resumed over and over.
|
|
112
|
+
const received = await withBackpressure(fakeSource(total, log), options(bufferSize, resumeThreshold)).pipe(Stream.tap(() => Effect.promise(async () => {
|
|
113
|
+
// A resume is opened from this tap's drain accounting, before the consumer has finished with the item, so
|
|
114
|
+
// the bookkeeping must happen before awaiting.
|
|
115
|
+
log.consumed += 1;
|
|
116
|
+
await nextMacrotask();
|
|
117
|
+
await nextMacrotask();
|
|
118
|
+
await nextMacrotask();
|
|
119
|
+
})), Stream.runCollect, Effect.map(Chunk.toReadonlyArray), Effect.runPromise);
|
|
120
|
+
expect(received).toEqual(EArray.makeBy(Number(total), (i) => BigInt(i + 1)));
|
|
121
|
+
const resumes = log.sessions.slice(1);
|
|
122
|
+
expect(log.sessions[0]?.cursor).toBe(0n);
|
|
123
|
+
expect(resumes.length).toBeGreaterThanOrEqual(5);
|
|
124
|
+
expect(log.disposals).toBeGreaterThanOrEqual(resumes.length);
|
|
125
|
+
resumes.forEach((session) => {
|
|
126
|
+
// Reopened from where it left off, not from the start: with an inclusive cursor only the boundary item is
|
|
127
|
+
// delivered twice.
|
|
128
|
+
expect(session.cursor).toBe(session.maxKeyAtOpen);
|
|
129
|
+
// And only once the consumer had drained to the threshold (plus the item it is holding).
|
|
130
|
+
expect(session.unconsumedAtOpen).toBeLessThanOrEqual(resumeThreshold + 1);
|
|
131
|
+
});
|
|
132
|
+
// Each resume cursor is the previous session's last key, so the source re-sends one item per resume and no more.
|
|
133
|
+
expect(log.delivered).toBe(Number(total) + resumes.length);
|
|
134
|
+
expect(log.peakUnconsumed).toBeLessThanOrEqual(bufferSize + 1);
|
|
135
|
+
});
|
|
136
|
+
});
|
|
@@ -10,10 +10,13 @@
|
|
|
10
10
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
11
|
// See the License for the specific language governing permissions and
|
|
12
12
|
// limitations under the License.
|
|
13
|
-
import { Cause, Effect, Exit, Stream } from 'effect';
|
|
13
|
+
import { Cause, Chunk, Effect, Either, Exit, Stream } from 'effect';
|
|
14
|
+
import { strToU8, zlibSync } from 'fflate';
|
|
14
15
|
import { parse } from 'graphql';
|
|
15
16
|
import { GRAPHQL_TRANSPORT_WS_PROTOCOL } from 'graphql-ws';
|
|
16
17
|
import { describe, expect, it, vi } from 'vitest';
|
|
18
|
+
import { ServerError } from '@midnightntwrk/wallet-sdk-utilities/networking';
|
|
19
|
+
import { GRAPHQL_TRANSPORT_WS_DEFLATE } from '../DeflateWebSocket.js';
|
|
17
20
|
import * as SubscriptionClient from '../SubscriptionClient.js';
|
|
18
21
|
import * as WsSubscriptionClient from '../WsSubscriptionClient.js';
|
|
19
22
|
/**
|
|
@@ -93,6 +96,55 @@ const makeUnreachableFake = () => {
|
|
|
93
96
|
// graphql-ws only ever touches the members implemented above.
|
|
94
97
|
return UnreachableFakeWebSocket;
|
|
95
98
|
};
|
|
99
|
+
/**
|
|
100
|
+
* A `typeof WebSocket` stand-in for an indexer that negotiates deflate, answers a subscription with one zlib-compressed
|
|
101
|
+
* `next` frame, and then drops the connection uncleanly (1006) — what a wallet sees when the indexer restarts or a load
|
|
102
|
+
* balancer cuts the socket mid-sync. Mutation confined to test setup, as with the fakes above.
|
|
103
|
+
*/
|
|
104
|
+
const makeDroppingDeflateFake = (payload) => {
|
|
105
|
+
class DroppingDeflateFakeWebSocket {
|
|
106
|
+
static CONNECTING = 0;
|
|
107
|
+
static OPEN = 1;
|
|
108
|
+
static CLOSING = 2;
|
|
109
|
+
static CLOSED = 3;
|
|
110
|
+
readyState = DroppingDeflateFakeWebSocket.CONNECTING;
|
|
111
|
+
protocol = GRAPHQL_TRANSPORT_WS_DEFLATE;
|
|
112
|
+
binaryType = 'blob';
|
|
113
|
+
onopen = null;
|
|
114
|
+
onmessage = null;
|
|
115
|
+
onclose = null;
|
|
116
|
+
onerror = null;
|
|
117
|
+
constructor() {
|
|
118
|
+
void Promise.resolve().then(() => {
|
|
119
|
+
this.readyState = DroppingDeflateFakeWebSocket.OPEN;
|
|
120
|
+
this.onopen?.();
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
send(data) {
|
|
124
|
+
const message = JSON.parse(data);
|
|
125
|
+
if (message.type === 'connection_init') {
|
|
126
|
+
void Promise.resolve().then(() => this.onmessage?.(new MessageEvent('message', { data: JSON.stringify({ type: 'connection_ack' }) })));
|
|
127
|
+
}
|
|
128
|
+
if (message.type === 'subscribe') {
|
|
129
|
+
const compressed = zlibSync(strToU8(JSON.stringify({ id: message.id, type: 'next', payload })));
|
|
130
|
+
const frame = new ArrayBuffer(compressed.byteLength);
|
|
131
|
+
new Uint8Array(frame).set(compressed);
|
|
132
|
+
void Promise.resolve()
|
|
133
|
+
.then(() => this.onmessage?.(new MessageEvent('message', { data: frame })))
|
|
134
|
+
.then(() => {
|
|
135
|
+
this.readyState = DroppingDeflateFakeWebSocket.CLOSED;
|
|
136
|
+
this.onclose?.({ code: 1006, reason: '', wasClean: false });
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
close() {
|
|
141
|
+
this.readyState = DroppingDeflateFakeWebSocket.CLOSED;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// Type cast required because: `typeof WebSocket` describes the full DOM constructor, while
|
|
145
|
+
// the deflate wrapper and graphql-ws only ever touch the members implemented above.
|
|
146
|
+
return DroppingDeflateFakeWebSocket;
|
|
147
|
+
};
|
|
96
148
|
/** Awaits `n` chained microtask ticks, letting promise-driven library internals settle. */
|
|
97
149
|
const flushMicrotasks = (n) => n === 0 ? Promise.resolve() : Promise.resolve().then(() => flushMicrotasks(n - 1));
|
|
98
150
|
// Type cast required because: the fake server ignores the query text entirely; any syntactically
|
|
@@ -189,4 +241,25 @@ describe('WsSubscriptionClient', () => {
|
|
|
189
241
|
: Effect.succeed(void 0)), Effect.scoped, Effect.runPromise);
|
|
190
242
|
});
|
|
191
243
|
});
|
|
244
|
+
describe('subscribe', () => {
|
|
245
|
+
// The deflate wrapper sits between the socket and graphql-ws, so every event graphql-ws relies on has to pass
|
|
246
|
+
// through it. If the close is lost on the way, graphql-ws never learns the indexer went away: the subscription
|
|
247
|
+
// neither ends nor fails, and the wallet's sync stalls silently instead of failing into its retry. The timeout turns
|
|
248
|
+
// that stall into a failure of this test rather than a hang.
|
|
249
|
+
it('delivers the inflated event, then fails with a ServerError when the indexer drops the connection', async () => {
|
|
250
|
+
const payload = { data: { events: 'first' } };
|
|
251
|
+
const outcome = await Effect.gen(function* () {
|
|
252
|
+
const client = yield* SubscriptionClient.SubscriptionClient;
|
|
253
|
+
return yield* Stream.runCollect(Stream.either(client.subscribe(anySubscription, {})));
|
|
254
|
+
}).pipe(Effect.provide(WsSubscriptionClient.layer({ url: 'ws://indexer.test/graphql/ws' }, { webSocketImpl: makeDroppingDeflateFake(payload) })), Effect.scoped, Effect.timeoutFail({
|
|
255
|
+
duration: '2 seconds',
|
|
256
|
+
onTimeout: () => 'subscription stalled after the connection dropped',
|
|
257
|
+
}), Effect.runPromise);
|
|
258
|
+
const [delivered, ended] = Chunk.toReadonlyArray(outcome);
|
|
259
|
+
// The compressed frame reached graphql-ws as text and was parsed into the subscription's data.
|
|
260
|
+
expect(delivered).toEqual(Either.right(payload.data));
|
|
261
|
+
// The drop surfaced as a transport failure the sync's retry can act on, not a stall or a GraphQL error.
|
|
262
|
+
expect(Either.isLeft(ended) ? ended.left : undefined).toBeInstanceOf(ServerError);
|
|
263
|
+
});
|
|
264
|
+
});
|
|
192
265
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@midnightntwrk/wallet-sdk-indexer-client",
|
|
3
|
-
"version": "2.0.0
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"module": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
32
|
"@graphql-typed-document-node/core": "^3.2.0",
|
|
33
|
-
"@midnightntwrk/wallet-sdk-utilities": "1.
|
|
33
|
+
"@midnightntwrk/wallet-sdk-utilities": "1.3.0",
|
|
34
34
|
"effect": "^3.19.19",
|
|
35
35
|
"fflate": "^0.8.2",
|
|
36
36
|
"graphql": "^17.0.0",
|
|
@@ -45,10 +45,10 @@
|
|
|
45
45
|
"@effect/rpc": "0.76.2",
|
|
46
46
|
"@effect/sql": "0.52.1",
|
|
47
47
|
"@effect/workflow": "0.19.1",
|
|
48
|
-
"@graphql-codegen/cli": "7.4.
|
|
49
|
-
"@graphql-codegen/client-preset": "6.2.
|
|
48
|
+
"@graphql-codegen/cli": "7.4.6",
|
|
49
|
+
"@graphql-codegen/client-preset": "6.2.3",
|
|
50
50
|
"tsx": "4.23.15",
|
|
51
|
-
"yaml": "
|
|
51
|
+
"yaml": "2.9.1"
|
|
52
52
|
},
|
|
53
53
|
"scripts": {
|
|
54
54
|
"gql:codegen": "graphql-codegen --clean --config codegen.ts",
|