@midnightntwrk/wallet-sdk-indexer-client 2.0.0-rc.0 → 2.0.0-rc.1
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.
- package/dist/effect/DeflateWebSocket.d.ts +34 -0
- package/dist/effect/DeflateWebSocket.js +90 -0
- package/dist/effect/WsSubscriptionClient.d.ts +39 -1
- package/dist/effect/WsSubscriptionClient.js +50 -4
- package/dist/effect/test/composeEnvironment.d.ts +20 -0
- package/dist/effect/test/composeEnvironment.js +50 -0
- package/dist/effect/test/deflateWebSocket.test.d.ts +1 -0
- package/dist/effect/test/deflateWebSocket.test.js +146 -0
- package/dist/effect/test/deflateWireStats.d.ts +53 -0
- package/dist/effect/test/deflateWireStats.js +109 -0
- package/dist/effect/test/httpConnectionReuse.integration.test.d.ts +1 -0
- package/dist/effect/test/httpConnectionReuse.integration.test.js +136 -0
- package/dist/effect/test/syncThroughput.integration.test.d.ts +1 -0
- package/dist/effect/test/syncThroughput.integration.test.js +133 -0
- package/dist/effect/test/throttledProxy.d.ts +25 -0
- package/dist/effect/test/throttledProxy.integration.test.d.ts +1 -0
- package/dist/effect/test/throttledProxy.integration.test.js +95 -0
- package/dist/effect/test/throttledProxy.js +83 -0
- package/dist/effect/test/wsDeflate.integration.test.d.ts +1 -0
- package/dist/effect/test/wsDeflate.integration.test.js +154 -0
- package/dist/effect/test/wsDeflateFallback.integration.test.d.ts +1 -0
- package/dist/effect/test/wsDeflateFallback.integration.test.js +58 -0
- package/dist/effect/test/wsSubscriptionClient.test.js +162 -2
- package/dist/graphql/generated/graphql.d.ts +1 -0
- package/dist/graphql/generated/graphql.js +1111 -15
- package/package.json +8 -7
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The indexer's opt-in compression subprotocol. Servers offering it send graphql-transport-ws JSON messages of >= 256
|
|
3
|
+
* bytes as binary frames containing the zlib-compressed (RFC 1950) UTF-8 JSON; smaller messages remain plain text
|
|
4
|
+
* frames. See midnight-indexer `indexer-api/src/infra/api/v4/ws_deflate.rs` for the wire format.
|
|
5
|
+
*/
|
|
6
|
+
export declare const GRAPHQL_TRANSPORT_WS_DEFLATE = "graphql-transport-ws+deflate";
|
|
7
|
+
/**
|
|
8
|
+
* The wrapper's constructor shape, as consumed by `graphql-ws`'s `webSocketImpl` option (typed `unknown` there).
|
|
9
|
+
* Deliberately not `typeof WebSocket`: only the surface `graphql-ws` uses is implemented — which includes the
|
|
10
|
+
* readyState constants it reads off the constructor itself, hence their presence here.
|
|
11
|
+
*/
|
|
12
|
+
export type DeflateWebSocketConstructor = {
|
|
13
|
+
new (url: string | URL, protocols?: string | string[]): unknown;
|
|
14
|
+
readonly CONNECTING: number;
|
|
15
|
+
readonly OPEN: number;
|
|
16
|
+
readonly CLOSING: number;
|
|
17
|
+
readonly CLOSED: number;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Creates a WebSocket-constructor for `graphql-ws`'s `webSocketImpl` option that negotiates the indexer's
|
|
21
|
+
* {@link GRAPHQL_TRANSPORT_WS_DEFLATE} subprotocol and transparently inflates the resulting binary frames back into the
|
|
22
|
+
* text messages `graphql-ws` expects.
|
|
23
|
+
*
|
|
24
|
+
* `graphql-ws` hardcodes the offered subprotocol to `graphql-transport-ws`, so this wrapper replaces the offer with
|
|
25
|
+
* both protocols; per the indexer's wire contract the standard protocol must be offered alongside the deflate variant.
|
|
26
|
+
* Against a server that does not offer the deflate variant, negotiation falls back to the standard protocol and this
|
|
27
|
+
* wrapper is a pass-through.
|
|
28
|
+
*
|
|
29
|
+
* Only the surface `graphql-ws` actually uses is exposed: the readyState statics, `readyState`, `send`, `close`, and
|
|
30
|
+
* the `onopen`/`onmessage`/`onclose`/`onerror` setters.
|
|
31
|
+
*
|
|
32
|
+
* @param Base - The underlying WebSocket constructor (default: the global `WebSocket`)
|
|
33
|
+
*/
|
|
34
|
+
export declare const makeDeflateWebSocket: (Base?: typeof WebSocket) => DeflateWebSocketConstructor;
|
|
@@ -0,0 +1,90 @@
|
|
|
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 { strFromU8, unzlibSync } from 'fflate';
|
|
14
|
+
import { GRAPHQL_TRANSPORT_WS_PROTOCOL } from 'graphql-ws';
|
|
15
|
+
/**
|
|
16
|
+
* The indexer's opt-in compression subprotocol. Servers offering it send graphql-transport-ws JSON messages of >= 256
|
|
17
|
+
* bytes as binary frames containing the zlib-compressed (RFC 1950) UTF-8 JSON; smaller messages remain plain text
|
|
18
|
+
* frames. See midnight-indexer `indexer-api/src/infra/api/v4/ws_deflate.rs` for the wire format.
|
|
19
|
+
*/
|
|
20
|
+
export const GRAPHQL_TRANSPORT_WS_DEFLATE = 'graphql-transport-ws+deflate';
|
|
21
|
+
/**
|
|
22
|
+
* Creates a WebSocket-constructor for `graphql-ws`'s `webSocketImpl` option that negotiates the indexer's
|
|
23
|
+
* {@link GRAPHQL_TRANSPORT_WS_DEFLATE} subprotocol and transparently inflates the resulting binary frames back into the
|
|
24
|
+
* text messages `graphql-ws` expects.
|
|
25
|
+
*
|
|
26
|
+
* `graphql-ws` hardcodes the offered subprotocol to `graphql-transport-ws`, so this wrapper replaces the offer with
|
|
27
|
+
* both protocols; per the indexer's wire contract the standard protocol must be offered alongside the deflate variant.
|
|
28
|
+
* Against a server that does not offer the deflate variant, negotiation falls back to the standard protocol and this
|
|
29
|
+
* wrapper is a pass-through.
|
|
30
|
+
*
|
|
31
|
+
* Only the surface `graphql-ws` actually uses is exposed: the readyState statics, `readyState`, `send`, `close`, and
|
|
32
|
+
* the `onopen`/`onmessage`/`onclose`/`onerror` setters.
|
|
33
|
+
*
|
|
34
|
+
* @param Base - The underlying WebSocket constructor (default: the global `WebSocket`)
|
|
35
|
+
*/
|
|
36
|
+
export const makeDeflateWebSocket = (Base = WebSocket) => class DeflateWebSocket {
|
|
37
|
+
static CONNECTING = 0;
|
|
38
|
+
static OPEN = 1;
|
|
39
|
+
static CLOSING = 2;
|
|
40
|
+
static CLOSED = 3;
|
|
41
|
+
#socket;
|
|
42
|
+
// graphql-ws passes its hardcoded subprotocol as the second argument; it is deliberately
|
|
43
|
+
// ignored and replaced with the deflate + standard pair.
|
|
44
|
+
constructor(url, _protocols) {
|
|
45
|
+
this.#socket = new Base(url, [GRAPHQL_TRANSPORT_WS_DEFLATE, GRAPHQL_TRANSPORT_WS_PROTOCOL]);
|
|
46
|
+
this.#socket.binaryType = 'arraybuffer';
|
|
47
|
+
}
|
|
48
|
+
get readyState() {
|
|
49
|
+
return this.#socket.readyState;
|
|
50
|
+
}
|
|
51
|
+
get protocol() {
|
|
52
|
+
return this.#socket.protocol;
|
|
53
|
+
}
|
|
54
|
+
set onopen(handler) {
|
|
55
|
+
this.#socket.onopen = handler;
|
|
56
|
+
}
|
|
57
|
+
set onclose(handler) {
|
|
58
|
+
this.#socket.onclose = handler;
|
|
59
|
+
}
|
|
60
|
+
set onerror(handler) {
|
|
61
|
+
this.#socket.onerror = handler;
|
|
62
|
+
}
|
|
63
|
+
set onmessage(handler) {
|
|
64
|
+
this.#socket.onmessage =
|
|
65
|
+
handler &&
|
|
66
|
+
((event) => {
|
|
67
|
+
handler.call(this.#socket, event.data instanceof ArrayBuffer ? inflate(event) : event);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
send(data) {
|
|
71
|
+
this.#socket.send(data);
|
|
72
|
+
}
|
|
73
|
+
close(code, reason) {
|
|
74
|
+
this.#socket.close(code, reason);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
// On a corrupt frame the original binary event is passed through instead: graphql-ws's own
|
|
78
|
+
// message parsing then fails and closes the socket with 4400 Bad Response, which is exactly
|
|
79
|
+
// the treatment a malformed server message deserves.
|
|
80
|
+
const inflate = (event) => {
|
|
81
|
+
try {
|
|
82
|
+
// Type cast required because: the `instanceof ArrayBuffer` check at the call site narrows
|
|
83
|
+
// `event.data`, but the narrowing does not survive extraction into this helper.
|
|
84
|
+
const data = strFromU8(unzlibSync(new Uint8Array(event.data)));
|
|
85
|
+
return new MessageEvent('message', { data });
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return event;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
@@ -1,4 +1,42 @@
|
|
|
1
1
|
import { Layer, type Scope } from 'effect';
|
|
2
2
|
import { SubscriptionClient } from './SubscriptionClient.js';
|
|
3
3
|
import { type InvalidProtocolSchemeError } from '@midnightntwrk/wallet-sdk-utilities/networking';
|
|
4
|
-
|
|
4
|
+
/**
|
|
5
|
+
* @internal Test-only transport seams for {@link layer} — deliberately NOT part of
|
|
6
|
+
* {@link SubscriptionClient.ServerConfig}. Compression is always offered (falling back
|
|
7
|
+
* automatically against servers without it) and connection reuse is fixed policy; consumers get
|
|
8
|
+
* no knobs for either. These seams exist solely so integration tests can run a compression-off
|
|
9
|
+
* reference and observe raw frames on the wire.
|
|
10
|
+
*/
|
|
11
|
+
export interface TransportInternals {
|
|
12
|
+
/** Offer the deflate compression subprotocol (default: true). */
|
|
13
|
+
readonly compression?: boolean | undefined;
|
|
14
|
+
/** The underlying WebSocket constructor (default: the global `WebSocket`). */
|
|
15
|
+
readonly webSocketImpl?: typeof WebSocket | undefined;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Builds a {@link SubscriptionClient} layer backed by a `graphql-ws` WebSocket connection to the indexer.
|
|
19
|
+
*
|
|
20
|
+
* The connection negotiates the indexer's compression subprotocol (with automatic fallback against servers that predate
|
|
21
|
+
* compression) and is held open for the client's entire scope (`lazy: false`), so backpressure pause/resume cycles and
|
|
22
|
+
* re-subscriptions always reuse it instead of paying a reconnect handshake. Correctness never depends on connection
|
|
23
|
+
* lifetime (resume is always cursor-based), so this is pure policy, not configuration. Non-lazy mode also makes
|
|
24
|
+
* disposal total: graphql-ws never arms its lazy-close timer, whose handle its `dispose()` leaks — a pending timer that
|
|
25
|
+
* would otherwise keep a short-lived Node process alive after the wallet stopped. The client is scoped — it is
|
|
26
|
+
* disposed, closing the connection and cancelling its timers, when the surrounding scope closes.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* const events = ZswapEvents.run({ id: 0 }).pipe(
|
|
31
|
+
* Stream.runCollect,
|
|
32
|
+
* Effect.provide(WsSubscriptionClient.layer({ url: 'ws://localhost:8088/api/v4/graphql/ws' })),
|
|
33
|
+
* Effect.scoped,
|
|
34
|
+
* );
|
|
35
|
+
* ```;
|
|
36
|
+
*
|
|
37
|
+
* @param config - The indexer WebSocket endpoint and optional keep-alive interval
|
|
38
|
+
* @param internals - `@internal` test-only transport seams; production callers omit this
|
|
39
|
+
* @returns A scoped layer providing `SubscriptionClient`, failing with `InvalidProtocolSchemeError` if `config.url` is
|
|
40
|
+
* not a WebSocket URL
|
|
41
|
+
*/
|
|
42
|
+
export declare const layer: (config: SubscriptionClient.ServerConfig, internals?: TransportInternals) => Layer.Layer<SubscriptionClient, InvalidProtocolSchemeError, Scope.Scope>;
|
|
@@ -15,6 +15,7 @@ import { createClient } from 'graphql-ws';
|
|
|
15
15
|
import { print } from 'graphql';
|
|
16
16
|
import { SubscriptionClient } from './SubscriptionClient.js';
|
|
17
17
|
import { withBackpressure } from './Backpressure.js';
|
|
18
|
+
import { makeDeflateWebSocket } from './DeflateWebSocket.js';
|
|
18
19
|
import { WsURL, ClientError, ServerError, } from '@midnightntwrk/wallet-sdk-utilities/networking';
|
|
19
20
|
// ============================================================================
|
|
20
21
|
// Error classification
|
|
@@ -31,10 +32,55 @@ const isGraphQLErrorArray = (err) => {
|
|
|
31
32
|
const toClientOrServerError = (err) => isGraphQLErrorArray(err)
|
|
32
33
|
? new ClientError({ message: err.map((e) => e.message).join('; '), cause: err })
|
|
33
34
|
: new ServerError({ message: String(err) });
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
35
|
+
/**
|
|
36
|
+
* Builds a {@link SubscriptionClient} layer backed by a `graphql-ws` WebSocket connection to the indexer.
|
|
37
|
+
*
|
|
38
|
+
* The connection negotiates the indexer's compression subprotocol (with automatic fallback against servers that predate
|
|
39
|
+
* compression) and is held open for the client's entire scope (`lazy: false`), so backpressure pause/resume cycles and
|
|
40
|
+
* re-subscriptions always reuse it instead of paying a reconnect handshake. Correctness never depends on connection
|
|
41
|
+
* lifetime (resume is always cursor-based), so this is pure policy, not configuration. Non-lazy mode also makes
|
|
42
|
+
* disposal total: graphql-ws never arms its lazy-close timer, whose handle its `dispose()` leaks — a pending timer that
|
|
43
|
+
* would otherwise keep a short-lived Node process alive after the wallet stopped. The client is scoped — it is
|
|
44
|
+
* disposed, closing the connection and cancelling its timers, when the surrounding scope closes.
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* ```typescript
|
|
48
|
+
* const events = ZswapEvents.run({ id: 0 }).pipe(
|
|
49
|
+
* Stream.runCollect,
|
|
50
|
+
* Effect.provide(WsSubscriptionClient.layer({ url: 'ws://localhost:8088/api/v4/graphql/ws' })),
|
|
51
|
+
* Effect.scoped,
|
|
52
|
+
* );
|
|
53
|
+
* ```;
|
|
54
|
+
*
|
|
55
|
+
* @param config - The indexer WebSocket endpoint and optional keep-alive interval
|
|
56
|
+
* @param internals - `@internal` test-only transport seams; production callers omit this
|
|
57
|
+
* @returns A scoped layer providing `SubscriptionClient`, failing with `InvalidProtocolSchemeError` if `config.url` is
|
|
58
|
+
* not a WebSocket URL
|
|
59
|
+
*/
|
|
60
|
+
export const layer = (config, internals) => Layer.scoped(SubscriptionClient, WsURL.make(config.url).pipe(Effect.flatMap((url) => Effect.acquireRelease(Effect.sync(() => {
|
|
61
|
+
// Resolved at acquire time, guarded so runtimes without the global reach graphql-ws's
|
|
62
|
+
// own probing and descriptive "implementation missing" error instead of a ReferenceError.
|
|
63
|
+
const webSocketImpl = internals?.webSocketImpl ?? (typeof WebSocket === 'undefined' ? undefined : WebSocket);
|
|
64
|
+
return createClient({
|
|
65
|
+
url: url.toString(),
|
|
66
|
+
shouldRetry: () => false,
|
|
67
|
+
lazy: false,
|
|
68
|
+
// A connection failing while nothing is subscribed needs no handling: active
|
|
69
|
+
// subscriptions surface transport errors through their own sinks, and the next
|
|
70
|
+
// subscribe dials afresh. Without this graphql-ws would console.error the event.
|
|
71
|
+
onNonLazyError: () => undefined,
|
|
72
|
+
keepAlive: config.keepAlive ?? 15_000,
|
|
73
|
+
webSocketImpl: internals?.compression === false
|
|
74
|
+
? internals.webSocketImpl
|
|
75
|
+
: webSocketImpl === undefined
|
|
76
|
+
? undefined
|
|
77
|
+
: makeDeflateWebSocket(webSocketImpl),
|
|
78
|
+
});
|
|
79
|
+
}),
|
|
80
|
+
// dispose() is async and rejects when the connection attempt it awaits has already
|
|
81
|
+
// failed — which still means "nothing left to close", i.e. successful disposal. Await
|
|
82
|
+
// it so the rejection is absorbed here instead of floating as an unhandled rejection.
|
|
83
|
+
(client) => Effect.promise(() => Promise.resolve(client.dispose()).then(undefined, () => undefined)))), Effect.map((client) => new WebSocketSubscriptionClientImpl(client))));
|
|
38
84
|
class WebSocketSubscriptionClientImpl {
|
|
39
85
|
constructor(client) {
|
|
40
86
|
this.client = client;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Converts minutes to the milliseconds vitest hook/test timeouts expect. */
|
|
2
|
+
export declare const timeoutMinutes: (mins: number) => number;
|
|
3
|
+
/** A started (or startable) indexer+node compose stack, scoped to one test file. */
|
|
4
|
+
export interface ComposeTestEnvironment {
|
|
5
|
+
/** Starts the stack; wire into `beforeAll` (allow `timeoutMinutes(3)` — image pulls are slow). */
|
|
6
|
+
readonly start: () => Promise<void>;
|
|
7
|
+
/** Tears the stack down; wire into `afterAll`. */
|
|
8
|
+
readonly stop: () => Promise<void>;
|
|
9
|
+
/** The indexer's mapped host port (falls back to 8088 before `start` resolves). */
|
|
10
|
+
readonly getIndexerPort: () => number;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The one compose scaffold every indexer-client integration test shares: a uniquely-named indexer+node environment
|
|
14
|
+
* (unique so parallel test files never collide on container names), readiness gated on the node listening and the
|
|
15
|
+
* indexer having indexed a block — connecting any earlier races indexer startup and flakes.
|
|
16
|
+
*
|
|
17
|
+
* @param composeFiles - Compose file name(s) under the shared compose directory; overrides later in the list win, e.g.
|
|
18
|
+
* `['docker-compose.yml', 'docker-compose.ws-no-deflate.yml']`.
|
|
19
|
+
*/
|
|
20
|
+
export declare const makeComposeEnvironment: (composeFiles: string | string[]) => ComposeTestEnvironment;
|
|
@@ -0,0 +1,50 @@
|
|
|
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 { buildTestEnvironmentVariables, getComposeDirectory } from '@midnightntwrk/wallet-sdk-utilities/testing';
|
|
14
|
+
import { randomUUID } from 'node:crypto';
|
|
15
|
+
import { DockerComposeEnvironment, Wait } from 'testcontainers';
|
|
16
|
+
/** Converts minutes to the milliseconds vitest hook/test timeouts expect. */
|
|
17
|
+
export const timeoutMinutes = (mins) => 1_000 * 60 * mins;
|
|
18
|
+
/**
|
|
19
|
+
* The one compose scaffold every indexer-client integration test shares: a uniquely-named indexer+node environment
|
|
20
|
+
* (unique so parallel test files never collide on container names), readiness gated on the node listening and the
|
|
21
|
+
* indexer having indexed a block — connecting any earlier races indexer startup and flakes.
|
|
22
|
+
*
|
|
23
|
+
* @param composeFiles - Compose file name(s) under the shared compose directory; overrides later in the list win, e.g.
|
|
24
|
+
* `['docker-compose.yml', 'docker-compose.ws-no-deflate.yml']`.
|
|
25
|
+
*/
|
|
26
|
+
export const makeComposeEnvironment = (composeFiles) => {
|
|
27
|
+
const environmentId = randomUUID();
|
|
28
|
+
const environmentVars = buildTestEnvironmentVariables(['APP_INFRA_SECRET'], {
|
|
29
|
+
additionalVars: {
|
|
30
|
+
TESTCONTAINERS_UID: environmentId,
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
const environment = new DockerComposeEnvironment(getComposeDirectory(), composeFiles)
|
|
34
|
+
.withWaitStrategy(`node_${environmentId}`, Wait.forListeningPorts())
|
|
35
|
+
.withWaitStrategy(`indexer_${environmentId}`, Wait.forLogMessage(/block indexed/))
|
|
36
|
+
.withEnvironment(environmentVars);
|
|
37
|
+
// Mutation is deliberate and confined to this helper: the started environment only exists
|
|
38
|
+
// after the async `start` hook runs, which is inherently stateful test setup
|
|
39
|
+
// (`.claude/rules/functional-style.md` permits this).
|
|
40
|
+
let startedEnvironment = undefined;
|
|
41
|
+
return {
|
|
42
|
+
start: async () => {
|
|
43
|
+
startedEnvironment = await environment.up();
|
|
44
|
+
},
|
|
45
|
+
stop: async () => {
|
|
46
|
+
await startedEnvironment?.down();
|
|
47
|
+
},
|
|
48
|
+
getIndexerPort: () => startedEnvironment?.getContainer(`indexer_${environmentId}`).getMappedPort(8088) ?? 8088,
|
|
49
|
+
};
|
|
50
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,146 @@
|
|
|
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 { strToU8, zlibSync } from 'fflate';
|
|
14
|
+
import { GRAPHQL_TRANSPORT_WS_PROTOCOL } from 'graphql-ws';
|
|
15
|
+
import { describe, expect, it } from 'vitest';
|
|
16
|
+
import { GRAPHQL_TRANSPORT_WS_DEFLATE, makeDeflateWebSocket } from '../DeflateWebSocket.js';
|
|
17
|
+
/**
|
|
18
|
+
* A `typeof WebSocket` stand-in that opens no connection, appending each construction to `instances`.
|
|
19
|
+
*
|
|
20
|
+
* Mutation is deliberate and confined to this test fake: the wrapper reaches its underlying socket through assignments
|
|
21
|
+
* and method calls, so recording them is inherently stateful. `.claude/rules/functional-style.md` permits this for test
|
|
22
|
+
* setup.
|
|
23
|
+
*/
|
|
24
|
+
const makeFakeBase = (instances) => {
|
|
25
|
+
class FakeWebSocket {
|
|
26
|
+
url;
|
|
27
|
+
protocols;
|
|
28
|
+
binaryType = 'blob';
|
|
29
|
+
readyState = 0;
|
|
30
|
+
protocol = '';
|
|
31
|
+
onmessage = null;
|
|
32
|
+
sent = [];
|
|
33
|
+
closeCalls = [];
|
|
34
|
+
constructor(url, protocols) {
|
|
35
|
+
this.url = url;
|
|
36
|
+
this.protocols = protocols;
|
|
37
|
+
instances.push(this);
|
|
38
|
+
}
|
|
39
|
+
send(data) {
|
|
40
|
+
this.sent.push(data);
|
|
41
|
+
}
|
|
42
|
+
close(code, reason) {
|
|
43
|
+
this.closeCalls.push({ code, reason });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
// Type cast required because: `typeof WebSocket` describes the full DOM constructor, while the wrapper only ever
|
|
47
|
+
// touches the members implemented above — implementing the remainder would add noise without adding coverage.
|
|
48
|
+
return FakeWebSocket;
|
|
49
|
+
};
|
|
50
|
+
/** Builds a standalone `ArrayBuffer` so `event.data instanceof ArrayBuffer` holds, as it does for a real binary frame. */
|
|
51
|
+
const toArrayBuffer = (bytes) => {
|
|
52
|
+
const buffer = new ArrayBuffer(bytes.byteLength);
|
|
53
|
+
new Uint8Array(buffer).set(bytes);
|
|
54
|
+
return buffer;
|
|
55
|
+
};
|
|
56
|
+
const binaryFrame = (data) => new MessageEvent('message', { data });
|
|
57
|
+
const deflated = (json) => toArrayBuffer(zlibSync(strToU8(json)));
|
|
58
|
+
/** Constructs the wrapper over a fresh fake, returning both halves. */
|
|
59
|
+
const connect = () => {
|
|
60
|
+
const instances = [];
|
|
61
|
+
const DeflateWebSocket = makeDeflateWebSocket(makeFakeBase(instances));
|
|
62
|
+
// Type cast required because: the constructor is typed to return `unknown` for graphql-ws's `webSocketImpl` option,
|
|
63
|
+
// so the surface under test has to be named here.
|
|
64
|
+
const socket = new DeflateWebSocket('ws://indexer.test/graphql/ws', GRAPHQL_TRANSPORT_WS_PROTOCOL);
|
|
65
|
+
return { socket, fake: instances[0] };
|
|
66
|
+
};
|
|
67
|
+
describe('makeDeflateWebSocket', () => {
|
|
68
|
+
describe('subprotocol negotiation', () => {
|
|
69
|
+
it('should offer the deflate subprotocol ahead of the standard one, replacing what graphql-ws asked for', () => {
|
|
70
|
+
const { fake } = connect();
|
|
71
|
+
// Both must be offered, deflate first: the indexer requires the standard protocol alongside the variant, and
|
|
72
|
+
// ordering is what expresses the preference. graphql-ws's own single-protocol argument is discarded.
|
|
73
|
+
expect(fake.protocols).toEqual([GRAPHQL_TRANSPORT_WS_DEFLATE, GRAPHQL_TRANSPORT_WS_PROTOCOL]);
|
|
74
|
+
});
|
|
75
|
+
it('should switch the underlying socket to arraybuffer frames', () => {
|
|
76
|
+
const { fake } = connect();
|
|
77
|
+
// Without this the compressed frames would arrive as Blobs and the inflate path would never match.
|
|
78
|
+
expect(fake.binaryType).toBe('arraybuffer');
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
describe('inbound frames', () => {
|
|
82
|
+
it('should inflate a zlib binary frame into the text message graphql-ws expects', () => {
|
|
83
|
+
const { socket, fake } = connect();
|
|
84
|
+
const payload = JSON.stringify({ type: 'next', id: '1', payload: { data: { blocks: [1, 2, 3] } } });
|
|
85
|
+
const received = [];
|
|
86
|
+
socket.onmessage = (event) => received.push(event);
|
|
87
|
+
fake.onmessage?.(binaryFrame(deflated(payload)));
|
|
88
|
+
expect(received).toHaveLength(1);
|
|
89
|
+
expect(received[0].data).toBe(payload);
|
|
90
|
+
});
|
|
91
|
+
it('should pass a corrupt binary frame through untouched, leaving graphql-ws to reject it', () => {
|
|
92
|
+
const { socket, fake } = connect();
|
|
93
|
+
// Not valid zlib — inflation must fail.
|
|
94
|
+
const corrupt = binaryFrame(toArrayBuffer(new Uint8Array([0x00, 0x01, 0x02, 0x03])));
|
|
95
|
+
const received = [];
|
|
96
|
+
socket.onmessage = (event) => received.push(event);
|
|
97
|
+
fake.onmessage?.(corrupt);
|
|
98
|
+
// The very same event, not a rewritten one: graphql-ws's message parsing then fails and closes the socket with
|
|
99
|
+
// 4400 Bad Response, which is the right treatment for a malformed server message. Swallowing it or throwing
|
|
100
|
+
// inside the handler would both strand the client instead.
|
|
101
|
+
expect(received).toHaveLength(1);
|
|
102
|
+
expect(received[0]).toBe(corrupt);
|
|
103
|
+
});
|
|
104
|
+
it('should leave text frames untouched', () => {
|
|
105
|
+
const { socket, fake } = connect();
|
|
106
|
+
// Messages below the server's 256 B compression threshold stay plain text and must not be touched.
|
|
107
|
+
const ack = new MessageEvent('message', { data: JSON.stringify({ type: 'connection_ack' }) });
|
|
108
|
+
const received = [];
|
|
109
|
+
socket.onmessage = (event) => received.push(event);
|
|
110
|
+
fake.onmessage?.(ack);
|
|
111
|
+
expect(received).toEqual([ack]);
|
|
112
|
+
});
|
|
113
|
+
it('should clear the underlying handler when onmessage is set to null', () => {
|
|
114
|
+
const { socket, fake } = connect();
|
|
115
|
+
socket.onmessage = () => undefined;
|
|
116
|
+
socket.onmessage = null;
|
|
117
|
+
// A wrapper that installed its own closure regardless would keep the socket referenced and keep delivering.
|
|
118
|
+
expect(fake.onmessage).toBeNull();
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
describe('delegation to the underlying socket', () => {
|
|
122
|
+
it('should report the underlying readyState and negotiated protocol', () => {
|
|
123
|
+
const { socket, fake } = connect();
|
|
124
|
+
fake.readyState = 1;
|
|
125
|
+
fake.protocol = GRAPHQL_TRANSPORT_WS_DEFLATE;
|
|
126
|
+
expect(socket.readyState).toBe(1);
|
|
127
|
+
expect(socket.protocol).toBe(GRAPHQL_TRANSPORT_WS_DEFLATE);
|
|
128
|
+
});
|
|
129
|
+
it('should forward sends and closes', () => {
|
|
130
|
+
const { socket, fake } = connect();
|
|
131
|
+
socket.send('{"type":"ping"}');
|
|
132
|
+
socket.close(1000, 'done');
|
|
133
|
+
expect(fake.sent).toEqual(['{"type":"ping"}']);
|
|
134
|
+
expect(fake.closeCalls).toEqual([{ code: 1000, reason: 'done' }]);
|
|
135
|
+
});
|
|
136
|
+
it('should expose the readyState constants graphql-ws reads off the constructor', () => {
|
|
137
|
+
const DeflateWebSocket = makeDeflateWebSocket(makeFakeBase([]));
|
|
138
|
+
expect([
|
|
139
|
+
DeflateWebSocket.CONNECTING,
|
|
140
|
+
DeflateWebSocket.OPEN,
|
|
141
|
+
DeflateWebSocket.CLOSING,
|
|
142
|
+
DeflateWebSocket.CLOSED,
|
|
143
|
+
]).toEqual([0, 1, 2, 3]);
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
});
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { type TestContext } from 'vitest';
|
|
2
|
+
/** Per-frame wire observation, taken below the deflate wrapper (i.e. before any inflation). */
|
|
3
|
+
export interface Frame {
|
|
4
|
+
readonly binary: boolean;
|
|
5
|
+
/** Bytes on the wire. */
|
|
6
|
+
readonly wire: number;
|
|
7
|
+
/** Bytes after inflation (equal to `wire` for text frames). */
|
|
8
|
+
readonly inflated: number;
|
|
9
|
+
/** The graphql-transport-ws message type (`connection_ack`, `next`, `complete`, ...). */
|
|
10
|
+
readonly type: string;
|
|
11
|
+
}
|
|
12
|
+
export interface WireStats {
|
|
13
|
+
readonly frames: Frame[];
|
|
14
|
+
protocol: string;
|
|
15
|
+
/** Number of physical WebSocket connections constructed. */
|
|
16
|
+
sockets: number;
|
|
17
|
+
}
|
|
18
|
+
export declare const emptyWireStats: () => WireStats;
|
|
19
|
+
/**
|
|
20
|
+
* Records every frame as it arrives on the underlying socket, accumulating into `stats`. Observation only
|
|
21
|
+
* (`addEventListener`), so the deflate wrapper's `onmessage` interception is unaffected.
|
|
22
|
+
*
|
|
23
|
+
* Mutation of `stats` is deliberate and the reason `WireStats` has mutable fields: frames arrive one event at a time
|
|
24
|
+
* over the life of a connection, so there is no value to fold over and no functional alternative that a plain DOM event
|
|
25
|
+
* listener can express. `.claude/rules/functional-style.md` permits this for test instrumentation; it stays confined to
|
|
26
|
+
* this file, and every reader of `stats` treats it as read-only.
|
|
27
|
+
*/
|
|
28
|
+
export declare const makeCountingWebSocket: (stats: WireStats) => typeof WebSocket;
|
|
29
|
+
export declare const total: (frames: readonly Frame[], of: (f: Frame) => number) => number;
|
|
30
|
+
/**
|
|
31
|
+
* The fraction of bytes compression kept off the wire, as observed within a single run: total wire bytes against the
|
|
32
|
+
* total the same frames occupy once inflated. This is the measure the tests assert a floor on.
|
|
33
|
+
*
|
|
34
|
+
* Deliberately intra-run — comparing a compressed run's totals against a separate uncompressed run's is racy, because
|
|
35
|
+
* frames already in flight when a stream is torn down still reach the wire and their number varies between runs.
|
|
36
|
+
*
|
|
37
|
+
* @returns A ratio in `[0, 1)`; `0` for a run in which nothing was compressed.
|
|
38
|
+
*/
|
|
39
|
+
export declare const savingsRatio: (stats: WireStats) => number;
|
|
40
|
+
/** The `annotate` function from a test's context, used to attach evidence to the test in the reporter output. */
|
|
41
|
+
export type Annotate = TestContext['annotate'];
|
|
42
|
+
/**
|
|
43
|
+
* Attaches `lines` to the running test as reporter annotations, in order. Preferred over `console.log`: the notes are
|
|
44
|
+
* attached to the specific test rather than emitted as loose stdout, they survive into the JUnit and HTML reports, and
|
|
45
|
+
* concurrent tests cannot interleave them.
|
|
46
|
+
*/
|
|
47
|
+
export declare const annotateAll: (annotate: Annotate, lines: readonly string[]) => Promise<unknown>;
|
|
48
|
+
/**
|
|
49
|
+
* Records the savings a deflate-offered run actually achieved, optionally alongside a compression-off reference run
|
|
50
|
+
* (omitted for fallback scenarios where only one run makes sense). Evidence only — the pass/fail decision lives in the
|
|
51
|
+
* tests' own assertions; this keeps the achieved numbers visible instead of having to be re-derived by hand.
|
|
52
|
+
*/
|
|
53
|
+
export declare const report: (annotate: Annotate, label: string, events: number, deflate: WireStats, plain?: WireStats) => Promise<unknown>;
|
|
@@ -0,0 +1,109 @@
|
|
|
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
|
+
/**
|
|
14
|
+
* Test kit for the WebSocket deflate-compression integration tests: a counting WebSocket that observes raw frames below
|
|
15
|
+
* the deflate wrapper, the wire-savings measure the tests assert on, and a human-readable report of the same numbers so
|
|
16
|
+
* a run's actual savings stay visible in the test output.
|
|
17
|
+
*/
|
|
18
|
+
import { strFromU8, unzlibSync } from 'fflate';
|
|
19
|
+
export const emptyWireStats = () => ({ frames: [], protocol: '', sockets: 0 });
|
|
20
|
+
const messageType = (json) => {
|
|
21
|
+
try {
|
|
22
|
+
// Type cast required because: JSON.parse returns `any`; the ?? fallback below covers a
|
|
23
|
+
// missing/non-string field, which is the only shape risk that matters here.
|
|
24
|
+
return (JSON.parse(json).type ?? 'unknown') || 'unknown';
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return 'unknown';
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Records every frame as it arrives on the underlying socket, accumulating into `stats`. Observation only
|
|
32
|
+
* (`addEventListener`), so the deflate wrapper's `onmessage` interception is unaffected.
|
|
33
|
+
*
|
|
34
|
+
* Mutation of `stats` is deliberate and the reason `WireStats` has mutable fields: frames arrive one event at a time
|
|
35
|
+
* over the life of a connection, so there is no value to fold over and no functional alternative that a plain DOM event
|
|
36
|
+
* listener can express. `.claude/rules/functional-style.md` permits this for test instrumentation; it stays confined to
|
|
37
|
+
* this file, and every reader of `stats` treats it as read-only.
|
|
38
|
+
*/
|
|
39
|
+
export const makeCountingWebSocket = (stats) => class CountingWebSocket extends WebSocket {
|
|
40
|
+
constructor(...args) {
|
|
41
|
+
super(...args);
|
|
42
|
+
stats.sockets += 1;
|
|
43
|
+
this.addEventListener('open', () => {
|
|
44
|
+
stats.protocol = this.protocol;
|
|
45
|
+
});
|
|
46
|
+
this.addEventListener('message', (event) => {
|
|
47
|
+
const data = event.data;
|
|
48
|
+
const binary = data instanceof ArrayBuffer;
|
|
49
|
+
// Inflate once and derive everything from the result: this runs for every frame of every
|
|
50
|
+
// replay, and inflating twice to measure and to classify was pure waste.
|
|
51
|
+
const text = binary ? strFromU8(unzlibSync(new Uint8Array(data))) : String(data);
|
|
52
|
+
const inflated = new TextEncoder().encode(text).byteLength;
|
|
53
|
+
stats.frames.push({
|
|
54
|
+
binary,
|
|
55
|
+
wire: binary ? data.byteLength : inflated,
|
|
56
|
+
inflated,
|
|
57
|
+
type: messageType(text),
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
export const total = (frames, of) => frames.reduce((sum, f) => sum + of(f), 0);
|
|
63
|
+
/**
|
|
64
|
+
* The fraction of bytes compression kept off the wire, as observed within a single run: total wire bytes against the
|
|
65
|
+
* total the same frames occupy once inflated. This is the measure the tests assert a floor on.
|
|
66
|
+
*
|
|
67
|
+
* Deliberately intra-run — comparing a compressed run's totals against a separate uncompressed run's is racy, because
|
|
68
|
+
* frames already in flight when a stream is torn down still reach the wire and their number varies between runs.
|
|
69
|
+
*
|
|
70
|
+
* @returns A ratio in `[0, 1)`; `0` for a run in which nothing was compressed.
|
|
71
|
+
*/
|
|
72
|
+
export const savingsRatio = (stats) => {
|
|
73
|
+
const inflated = total(stats.frames, (f) => f.inflated);
|
|
74
|
+
return inflated === 0 ? 0 : 1 - total(stats.frames, (f) => f.wire) / inflated;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Attaches `lines` to the running test as reporter annotations, in order. Preferred over `console.log`: the notes are
|
|
78
|
+
* attached to the specific test rather than emitted as loose stdout, they survive into the JUnit and HTML reports, and
|
|
79
|
+
* concurrent tests cannot interleave them.
|
|
80
|
+
*/
|
|
81
|
+
export const annotateAll = (annotate, lines) => lines.reduce((queued, line) => queued.then(() => annotate(line)), Promise.resolve());
|
|
82
|
+
/**
|
|
83
|
+
* Records the savings a deflate-offered run actually achieved, optionally alongside a compression-off reference run
|
|
84
|
+
* (omitted for fallback scenarios where only one run makes sense). Evidence only — the pass/fail decision lives in the
|
|
85
|
+
* tests' own assertions; this keeps the achieved numbers visible instead of having to be re-derived by hand.
|
|
86
|
+
*/
|
|
87
|
+
export const report = (annotate, label, events, deflate, plain) => {
|
|
88
|
+
const compressed = deflate.frames.filter((f) => f.binary);
|
|
89
|
+
const uncompressed = deflate.frames.filter((f) => !f.binary);
|
|
90
|
+
const wire = total(deflate.frames, (f) => f.wire);
|
|
91
|
+
const inflated = total(deflate.frames, (f) => f.inflated);
|
|
92
|
+
// e.g. "1 connection_ack, 19 complete" — the protocol chatter that stays below the server's
|
|
93
|
+
// 256 B compression threshold and therefore remains plain text.
|
|
94
|
+
const byType = [...new Set(uncompressed.map((f) => f.type))]
|
|
95
|
+
.map((type) => `${uncompressed.filter((f) => f.type === type).length} ${type}`)
|
|
96
|
+
.join(', ');
|
|
97
|
+
return annotateAll(annotate, [
|
|
98
|
+
`ws compression savings — ${label}`,
|
|
99
|
+
`events drained: ${events}`,
|
|
100
|
+
...(plain
|
|
101
|
+
? [`plain run: ${total(plain.frames, (f) => f.wire)} B over ${plain.frames.length} frames (all text)`]
|
|
102
|
+
: []),
|
|
103
|
+
`deflate run (wire): ${wire} B over ${deflate.frames.length} frames (${compressed.length} compressed)`,
|
|
104
|
+
`uncompressed: ${uncompressed.length} frames / ${total(uncompressed, (f) => f.wire)} B (${byType}) — ` +
|
|
105
|
+
'below the server 256 B threshold or server without deflate support, sent as plain text',
|
|
106
|
+
`deflate (inflated): ${inflated} B`,
|
|
107
|
+
`saved: ${inflated - wire} B (${(100 * savingsRatio(deflate)).toFixed(1)}%)`,
|
|
108
|
+
]);
|
|
109
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|