@contello/client 3.4.1 → 3.5.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.
package/dist/index.js CHANGED
@@ -1,9 +1,114 @@
1
1
  import { createOperationTelemetry, graphqlOperationAttributes, injectTraceContext } from "@contello/opentelemetry";
2
2
  import { concatAsync, exponentialBackoff, firstAsync, mapAsync } from "@entwico/dash/async";
3
3
  import { createClient } from "graphql-ws";
4
+ import WebSocket from "ws";
4
5
  import { Agent, request } from "undici";
5
6
  import { createHash } from "node:crypto";
6
- //#region src/http.ts
7
+ // src/reply-watchdog.ts
8
+ const REPLY_TIMEOUT = 1e4;
9
+ /**
10
+ * Gives up a connection whose server stopped answering: a new one that is not acknowledged, or an
11
+ * established one that sends no pong to a ping. A connection that died without a close frame looks
12
+ * open forever, and every operation on it waits.
13
+ *
14
+ * `terminate` has to drop the connection without waiting for it (graphql-ws `client.terminate()`):
15
+ * closing a socket whose peer is gone waits for that same peer.
16
+ */
17
+ function createReplyWatchdog(terminate, timeout = REPLY_TIMEOUT) {
18
+ let timer;
19
+ function disarm() {
20
+ clearTimeout(timer);
21
+ timer = void 0;
22
+ }
23
+ function arm() {
24
+ disarm();
25
+ timer = setTimeout(terminate, timeout);
26
+ timer.unref?.();
27
+ }
28
+ return {
29
+ connecting: arm,
30
+ connected: disarm,
31
+ ping(received) {
32
+ if (!received) arm();
33
+ },
34
+ pong(received) {
35
+ if (received) disarm();
36
+ },
37
+ closed: disarm
38
+ };
39
+ }
40
+ // src/websocket.ts
41
+ const CLOSE_CODE_TERMINATED = 4499;
42
+ /**
43
+ * The socket class graphql-ws connects with. Node's own WebSocket cannot be forced shut: closed
44
+ * against a peer that stopped answering it stays in `CLOSING` and keeps its file descriptor for as
45
+ * long as the peer stays silent, one more with every reconnect. This one is destroyed when it was
46
+ * given up, and after `replyTimeout` when a handshake, opening or closing, gets no answer.
47
+ */
48
+ function createWebSocketClass(replyTimeout) {
49
+ const options = {
50
+ handshakeTimeout: replyTimeout,
51
+ closeTimeout: replyTimeout
52
+ };
53
+ return class ContelloWebSocket extends WebSocket {
54
+ constructor(address, protocols) {
55
+ super(address, protocols, options);
56
+ }
57
+ close(code, data) {
58
+ if (code !== CLOSE_CODE_TERMINATED) {
59
+ super.close(code, data);
60
+ return;
61
+ }
62
+ this.on("error", () => {});
63
+ this.terminate();
64
+ }
65
+ };
66
+ }
67
+ // src/connection.ts
68
+ const KEEP_ALIVE_INTERVAL = 3e4;
69
+ /**
70
+ * One websocket to Contello that stays up: it connects right away, reconnects forever, and gives up
71
+ * a socket whose server stopped answering, so operations move to a new one.
72
+ */
73
+ function createConnection(options) {
74
+ const { onError, onFatalError } = options;
75
+ const replyTimeout = options.replyTimeout ?? 1e4;
76
+ const watchdog = createReplyWatchdog(() => client.terminate(), replyTimeout);
77
+ const client = createClient({
78
+ url: options.url,
79
+ webSocketImpl: createWebSocketClass(replyTimeout),
80
+ connectionParams: { token: options.token },
81
+ lazy: false,
82
+ keepAlive: options.keepAlive ?? KEEP_ALIVE_INTERVAL,
83
+ retryAttempts: Infinity,
84
+ retryWait: options.retryWait ?? exponentialBackoff,
85
+ shouldRetry: () => true,
86
+ jsonMessageReplacer: (key, value) => {
87
+ if (!key) return injectTraceContext(value);
88
+ return value;
89
+ },
90
+ ...onFatalError && { onNonLazyError: onFatalError },
91
+ on: {
92
+ connecting: () => {
93
+ watchdog.connecting();
94
+ options.onConnecting?.();
95
+ },
96
+ connected: () => {
97
+ watchdog.connected();
98
+ options.onConnected?.();
99
+ },
100
+ ping: (received) => watchdog.ping(received),
101
+ pong: (received) => watchdog.pong(received),
102
+ closed: () => {
103
+ watchdog.closed();
104
+ options.onClosed?.();
105
+ },
106
+ ...onError && { error: onError }
107
+ }
108
+ });
109
+ return client;
110
+ }
111
+ // src/http.ts
7
112
  const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
8
113
  const FORWARDED_PROXY_HEADERS = /* @__PURE__ */ new Set([
9
114
  "content-type",
@@ -158,8 +263,7 @@ function toWebStream(body, signal) {
158
263
  }
159
264
  });
160
265
  }
161
- //#endregion
162
- //#region src/introspection.ts
266
+ // src/introspection.ts
163
267
  const INTROSPECT_QUERY = `query ContelloIntrospectToken($token: String!) {
164
268
  contelloIntrospectToken(token: $token) {
165
269
  active audience expiresAt user { id username firstName lastName email } permissions { resourceType scope actions }
@@ -219,15 +323,13 @@ function createTokenIntrospector(introspect, options) {
219
323
  return running;
220
324
  } };
221
325
  }
222
- //#endregion
223
- //#region src/ping.ts
326
+ // src/ping.ts
224
327
  const PING_QUERY = `query ContelloPing { contelloPing { response } }`;
225
328
  async function ping(execute) {
226
329
  const data = await execute(PING_QUERY);
227
330
  if (data.contelloPing.response !== "pong") throw new Error(`unexpected ping response: ${data.contelloPing.response}`);
228
331
  }
229
- //#endregion
230
- //#region src/pool.ts
332
+ // src/pool.ts
231
333
  const DEFAULT_CONNECT_TIMEOUT = 1e4;
232
334
  var ConnectionPool = class {
233
335
  _createClient;
@@ -284,12 +386,13 @@ var ConnectionPool = class {
284
386
  return client;
285
387
  }
286
388
  async disconnect() {
287
- const closed = this._clients.map((client) => new Promise((resolve) => {
389
+ const closed = this._clients.map((client, index) => new Promise((resolve) => {
288
390
  const unsubscribe = client.on("closed", () => {
289
391
  unsubscribe();
290
392
  resolve();
291
393
  });
292
- client.dispose();
394
+ Promise.resolve(client.dispose()).catch(() => {});
395
+ if (this._connected[index] !== true) client.terminate();
293
396
  }));
294
397
  this._clients = [];
295
398
  this._connected = [];
@@ -297,11 +400,9 @@ var ConnectionPool = class {
297
400
  await Promise.all(closed);
298
401
  }
299
402
  };
300
- //#endregion
301
- //#region src/telemetry.ts
403
+ // src/telemetry.ts
302
404
  const { wrap } = createOperationTelemetry("@contello/client");
303
- //#endregion
304
- //#region src/scalars.ts
405
+ // src/scalars.ts
305
406
  const LOCAL_DATE_TIME_KEYS = [
306
407
  "year",
307
408
  "month",
@@ -365,8 +466,7 @@ function encodeLocalDateTime(value) {
365
466
  function encodeLocalDate(value) {
366
467
  return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T00:00:00Z`;
367
468
  }
368
- //#endregion
369
- //#region src/transform-variables.ts
469
+ // src/transform-variables.ts
370
470
  /**
371
471
  * encodes outgoing variables: LocalDateTime / LocalDate POJOs become wire strings.
372
472
  * detection is by shape — generated input types use the struct types, so consumers
@@ -384,8 +484,7 @@ function transformVariables(value) {
384
484
  for (const [key, val] of Object.entries(obj)) out[key] = transformVariables(val);
385
485
  return out;
386
486
  }
387
- //#endregion
388
- //#region src/rpc.ts
487
+ // src/rpc.ts
389
488
  function buildRpc(operations, subscribe) {
390
489
  const rpc = {};
391
490
  for (const [name, def] of Object.entries(operations)) rpc[name] = def.kind === "subscription" ? (variables) => subscribe(def.document, transformVariables(variables)) : (variables) => {
@@ -394,8 +493,7 @@ function buildRpc(operations, subscribe) {
394
493
  };
395
494
  return rpc;
396
495
  }
397
- //#endregion
398
- //#region src/source-mutation.ts
496
+ // src/source-mutation.ts
399
497
  const cache$1 = /* @__PURE__ */ new WeakMap();
400
498
  /**
401
499
  * A create/update answers with the entity itself, so it selects the source's own fragment — the
@@ -443,8 +541,7 @@ function createSourceMutationVariables(binding, values) {
443
541
  function readSourceMutationId(binding, result) {
444
542
  return binding.result === "idScalar" ? result : result.id;
445
543
  }
446
- //#endregion
447
- //#region src/source-subscription.ts
544
+ // src/source-subscription.ts
448
545
  const cache = /* @__PURE__ */ new WeakMap();
449
546
  function createSelection(source) {
450
547
  const spread = `{ ...${source.fragment} }`;
@@ -463,8 +560,7 @@ function createSourceSubscription(source) {
463
560
  cache.set(source, doc);
464
561
  return doc;
465
562
  }
466
- //#endregion
467
- //#region src/sources.ts
563
+ // src/sources.ts
468
564
  const WRITE_KINDS = [
469
565
  "create",
470
566
  "update",
@@ -534,8 +630,7 @@ function createSourceAccessor(name, def, doc, subscribe) {
534
630
  } };
535
631
  }
536
632
  }
537
- //#endregion
538
- //#region src/transform-response.ts
633
+ // src/transform-response.ts
539
634
  const FLAT_PREFIX = "_flat_";
540
635
  const LDT_PREFIX = "_ldt_";
541
636
  const LD_PREFIX = "_ld_";
@@ -616,33 +711,79 @@ function resolveRefs(refs, flatMap) {
616
711
  }
617
712
  return resolved;
618
713
  }
619
- //#endregion
620
- //#region src/upload.ts
621
- const DEFAULT_CHUNK_SIZE = 4194304;
714
+ // src/upload.ts
715
+ function parseServerMessage(data) {
716
+ try {
717
+ return JSON.parse(String(data));
718
+ } catch {
719
+ return;
720
+ }
721
+ }
722
+ const DEFAULT_CHUNK_SIZE = 262144;
723
+ const DEFAULT_TIMINGS = {
724
+ replyTimeout: REPLY_TIMEOUT,
725
+ stallTimeout: 6e4,
726
+ heartbeatTimeout: 15e3
727
+ };
622
728
  function isUint8Array(data) {
623
729
  return data instanceof Uint8Array;
624
730
  }
625
- function upload(url, project, token, data, meta, options) {
731
+ /**
732
+ * Sends a file over the upload websocket and answers with the id of the asset.
733
+ *
734
+ * The server acknowledges the start and every chunk, so while it owes an answer its silence has a
735
+ * limit: `stallTimeout` without a message from it and without a byte leaving for it ends the upload.
736
+ *
737
+ * The server pings for as long as the upload is open, storing the file after the last chunk
738
+ * included, and is alive for as long as its pings come: `heartbeatTimeout` without a ping or a
739
+ * message ends the upload. That takes a Contello that pings its uploads.
740
+ */
741
+ function upload(url, project, token, data, meta, options, { replyTimeout, stallTimeout, heartbeatTimeout } = DEFAULT_TIMINGS) {
626
742
  const chunkSize = options?.chunkSize ?? DEFAULT_CHUNK_SIZE;
627
743
  const wsUrl = `${url.replace(/^http/i, "ws")}/api/v1/assets/ws`;
628
744
  const size = isUint8Array(data) ? data.length : meta.size;
629
745
  return new Promise((resolve, reject) => {
630
- const ws = new WebSocket(wsUrl, "contello-file-upload-v1");
746
+ const ws = new (createWebSocketClass(replyTimeout))(wsUrl, "contello-file-upload-v1");
631
747
  let done = false;
748
+ let awaitingAck = false;
749
+ let bytesSent = 0;
750
+ let bytesAcknowledged = 0;
751
+ let lastProgress = Date.now();
752
+ let lastBuffered = 0;
753
+ let lastHeard;
754
+ let cancelSource;
755
+ const stallCheck = setInterval(() => {
756
+ const buffered = ws.bufferedAmount;
757
+ if (buffered < lastBuffered) lastProgress = Date.now();
758
+ lastBuffered = buffered;
759
+ const owed = awaitingAck || bytesAcknowledged < bytesSent;
760
+ if (lastHeard !== void 0 && Date.now() - lastHeard > heartbeatTimeout || owed && Date.now() - lastProgress > stallTimeout) fail(/* @__PURE__ */ new Error("upload stalled: the server stopped answering"));
761
+ }, Math.min(1e3, stallTimeout / 4, heartbeatTimeout / 4));
762
+ stallCheck.unref?.();
632
763
  const cleanup = () => {
764
+ clearInterval(stallCheck);
633
765
  options?.abort?.removeEventListener("abort", abortHandler);
634
766
  };
635
- const abortHandler = () => {
767
+ function fail(error) {
636
768
  if (done) return;
637
- ws.close();
638
- reject(/* @__PURE__ */ new Error("upload aborted"));
639
- };
769
+ done = true;
770
+ cleanup();
771
+ cancelSource?.();
772
+ ws.terminate();
773
+ reject(error);
774
+ }
775
+ const abortHandler = () => fail(/* @__PURE__ */ new Error("upload aborted"));
640
776
  options?.abort?.addEventListener("abort", abortHandler);
777
+ function send(chunk) {
778
+ if (bytesAcknowledged === bytesSent) lastProgress = Date.now();
779
+ bytesSent += chunk.length;
780
+ ws.send(chunk);
781
+ }
641
782
  function sendBuffer(buf) {
642
783
  let offset = 0;
643
784
  while (offset < buf.length) {
644
785
  const chunk = buf.subarray(offset, offset + chunkSize);
645
- ws.send(chunk);
786
+ send(chunk);
646
787
  offset += chunk.length;
647
788
  }
648
789
  ws.send(JSON.stringify({ type: "done" }));
@@ -651,8 +792,8 @@ function upload(url, project, token, data, meta, options) {
651
792
  function waitForBufferedDrain() {
652
793
  return new Promise((resolveDrain, rejectDrain) => {
653
794
  const check = () => {
654
- if (options?.abort?.aborted) {
655
- rejectDrain(/* @__PURE__ */ new Error("upload aborted"));
795
+ if (done) {
796
+ rejectDrain(/* @__PURE__ */ new Error("upload ended"));
656
797
  return;
657
798
  }
658
799
  if (ws.bufferedAmount <= MAX_BUFFER_SIZE) {
@@ -666,17 +807,19 @@ function upload(url, project, token, data, meta, options) {
666
807
  }
667
808
  async function sendStream(stream) {
668
809
  const reader = stream.getReader();
810
+ cancelSource = () => void reader.cancel().catch(() => {});
669
811
  try {
670
812
  while (true) {
671
813
  const { done: streamDone, value } = await reader.read();
672
814
  if (streamDone) break;
673
- await waitForBufferedDrain();
674
- ws.send(value);
815
+ for (let offset = 0; offset < value.length; offset += chunkSize) {
816
+ await waitForBufferedDrain();
817
+ send(value.subarray(offset, offset + chunkSize));
818
+ }
675
819
  }
676
820
  ws.send(JSON.stringify({ type: "done" }));
677
821
  } catch (error) {
678
- reject(error);
679
- ws.close();
822
+ fail(error instanceof Error ? error : new Error(String(error)));
680
823
  }
681
824
  }
682
825
  ws.addEventListener("open", () => {
@@ -689,11 +832,29 @@ function upload(url, project, token, data, meta, options) {
689
832
  },
690
833
  token
691
834
  };
835
+ awaitingAck = true;
836
+ lastProgress = Date.now();
837
+ lastHeard = Date.now();
692
838
  ws.send(JSON.stringify(initFrame));
693
839
  });
694
840
  ws.addEventListener("message", (event) => {
695
- const message = JSON.parse(String(event.data));
841
+ const message = parseServerMessage(event.data);
842
+ if (!message) {
843
+ fail(/* @__PURE__ */ new Error(`upload failed: ${String(event.data)}`));
844
+ return;
845
+ }
846
+ if (message.type === "error") {
847
+ fail(/* @__PURE__ */ new Error(`upload failed: ${message.error}`));
848
+ return;
849
+ }
850
+ lastProgress = Date.now();
851
+ lastHeard = Date.now();
852
+ if (message.type === "progress") {
853
+ bytesAcknowledged = Math.max(bytesAcknowledged, message.bytesReceived);
854
+ return;
855
+ }
696
856
  if (message.type === "ack") {
857
+ awaitingAck = false;
697
858
  if (isUint8Array(data)) sendBuffer(data);
698
859
  else sendStream(data);
699
860
  return;
@@ -704,18 +865,14 @@ function upload(url, project, token, data, meta, options) {
704
865
  ws.close();
705
866
  resolve(message.id);
706
867
  });
707
- ws.addEventListener("error", () => {
708
- cleanup();
709
- reject(/* @__PURE__ */ new Error("upload websocket error"));
710
- });
711
- ws.addEventListener("close", () => {
712
- cleanup();
713
- if (!done) reject(/* @__PURE__ */ new Error("connection closed before upload completed"));
868
+ ws.on("ping", () => {
869
+ lastHeard = Date.now();
714
870
  });
871
+ ws.addEventListener("error", () => fail(/* @__PURE__ */ new Error("upload websocket error")));
872
+ ws.addEventListener("close", () => fail(/* @__PURE__ */ new Error("connection closed before upload completed")));
715
873
  });
716
874
  }
717
- //#endregion
718
- //#region src/client.ts
875
+ // src/client.ts
719
876
  var ContelloClient = class {
720
877
  _pool;
721
878
  _rpc;
@@ -750,36 +907,23 @@ var ContelloClient = class {
750
907
  connectionId: id,
751
908
  websocketUrl
752
909
  });
753
- return createClient({
910
+ return createConnection({
754
911
  url: websocketUrl,
755
- connectionParams: { token },
756
- lazy: false,
757
- keepAlive: 3e4,
758
- retryAttempts: Infinity,
759
- retryWait: exponentialBackoff,
760
- shouldRetry: () => true,
761
- jsonMessageReplacer: (key, value) => {
762
- if (!key) return injectTraceContext(value);
763
- return value;
912
+ token,
913
+ onFatalError: options.onError,
914
+ onConnecting: () => connectionEvents?.onConnecting?.(context),
915
+ onConnected: () => {
916
+ onConnectionUp();
917
+ connectionEvents?.onConnected?.(context);
764
918
  },
765
- ...options.onError && { onNonLazyError: (e) => options.onError(e) },
766
- on: {
767
- connected: () => {
768
- onConnectionUp();
769
- connectionEvents?.onConnected?.(context);
770
- },
771
- connecting: () => {
772
- connectionEvents?.onConnecting?.(context);
773
- },
774
- closed: () => {
775
- onConnectionDown();
776
- connectionEvents?.onClosed?.(context);
777
- },
778
- ...(options.onError || connectionEvents?.onError) && { error: (e) => {
779
- options.onError?.(e);
780
- connectionEvents?.onError?.(context, e);
781
- } }
782
- }
919
+ onClosed: () => {
920
+ onConnectionDown();
921
+ connectionEvents?.onClosed?.(context);
922
+ },
923
+ ...(options.onError || connectionEvents?.onError) && { onError: (e) => {
924
+ options.onError?.(e);
925
+ connectionEvents?.onError?.(context, e);
926
+ } }
783
927
  });
784
928
  }, connections);
785
929
  this._rpc = schema?.operations ? buildRpc(schema.operations, (q, v) => this.subscribe(q, v)) : void 0;
@@ -911,8 +1055,7 @@ var ContelloClient = class {
911
1055
  function createContelloClient(options) {
912
1056
  return new ContelloClient(options);
913
1057
  }
914
- //#endregion
915
- //#region src/built-in-mutations.ts
1058
+ // src/built-in-mutations.ts
916
1059
  /**
917
1060
  * Write bindings for the built-in sources. Unlike entity mutations these are not derived — their
918
1061
  * field and argument names are fixed parts of every Contello schema — but the generator still
@@ -976,7 +1119,6 @@ const BUILT_IN_MUTATIONS = {
976
1119
  }
977
1120
  }
978
1121
  };
979
- //#endregion
980
1122
  export { BUILT_IN_MUTATIONS, ContelloClient, createContelloClient, createSourceMutation, createSourceMutationVariables, createSourceSubscription, createTokenIntrospector, readSourceMutationId };
981
1123
 
982
1124
  //# sourceMappingURL=index.js.map