@replit/river 0.19.2 → 0.20.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.
Files changed (72) hide show
  1. package/dist/{chunk-D5PVGZPQ.js → chunk-5WFL722S.js} +15 -1
  2. package/dist/chunk-5WFL722S.js.map +1 -0
  3. package/dist/{chunk-NBE3D667.js → chunk-DT5JS6TM.js} +1 -0
  4. package/dist/chunk-DT5JS6TM.js.map +1 -0
  5. package/dist/{chunk-ZWPEZS27.js → chunk-HGBAUTIW.js} +2 -1
  6. package/dist/chunk-HGBAUTIW.js.map +1 -0
  7. package/dist/{chunk-YFPVQTWL.js → chunk-NYOK5VKK.js} +385 -246
  8. package/dist/chunk-NYOK5VKK.js.map +1 -0
  9. package/dist/{chunk-GZ7HCLLM.js → chunk-XAG3SC7R.js} +1 -0
  10. package/dist/chunk-XAG3SC7R.js.map +1 -0
  11. package/dist/{chunk-SR4DBLJ6.js → chunk-YB5LRYL6.js} +518 -260
  12. package/dist/chunk-YB5LRYL6.js.map +1 -0
  13. package/dist/{chunk-JH275HID.js → chunk-ZIWOHAQM.js} +2 -1
  14. package/dist/chunk-ZIWOHAQM.js.map +1 -0
  15. package/dist/codec/index.cjs +1 -0
  16. package/dist/codec/index.cjs.map +1 -0
  17. package/dist/codec/index.js +2 -1
  18. package/dist/codec/index.js.map +1 -0
  19. package/dist/{connection-cfec12e6.d.ts → connection-d49d5d56.d.ts} +1 -1
  20. package/dist/{connection-aa0ea000.d.ts → connection-dba95bc8.d.ts} +1 -1
  21. package/dist/{index-e2513701.d.ts → index-3ac92295.d.ts} +12 -0
  22. package/dist/logging/index.cjs +1 -0
  23. package/dist/logging/index.cjs.map +1 -0
  24. package/dist/logging/index.d.cts +1 -1
  25. package/dist/logging/index.d.ts +1 -1
  26. package/dist/logging/index.js +2 -1
  27. package/dist/logging/index.js.map +1 -0
  28. package/dist/router/index.cjs +515 -257
  29. package/dist/router/index.cjs.map +1 -0
  30. package/dist/router/index.d.cts +4 -4
  31. package/dist/router/index.d.ts +4 -4
  32. package/dist/router/index.js +4 -3
  33. package/dist/router/index.js.map +1 -0
  34. package/dist/{services-5fc5712d.d.ts → services-8496d6e8.d.ts} +1 -1
  35. package/dist/{services-4bba42d8.d.ts → services-abc077db.d.ts} +1 -1
  36. package/dist/transport/impls/uds/client.cjs +151 -74
  37. package/dist/transport/impls/uds/client.cjs.map +1 -0
  38. package/dist/transport/impls/uds/client.d.cts +2 -2
  39. package/dist/transport/impls/uds/client.d.ts +2 -2
  40. package/dist/transport/impls/uds/client.js +6 -5
  41. package/dist/transport/impls/uds/client.js.map +1 -0
  42. package/dist/transport/impls/uds/server.cjs +250 -169
  43. package/dist/transport/impls/uds/server.cjs.map +1 -0
  44. package/dist/transport/impls/uds/server.d.cts +2 -2
  45. package/dist/transport/impls/uds/server.d.ts +2 -2
  46. package/dist/transport/impls/uds/server.js +6 -5
  47. package/dist/transport/impls/uds/server.js.map +1 -0
  48. package/dist/transport/impls/ws/client.cjs +151 -74
  49. package/dist/transport/impls/ws/client.cjs.map +1 -0
  50. package/dist/transport/impls/ws/client.d.cts +2 -2
  51. package/dist/transport/impls/ws/client.d.ts +2 -2
  52. package/dist/transport/impls/ws/client.js +6 -5
  53. package/dist/transport/impls/ws/client.js.map +1 -0
  54. package/dist/transport/impls/ws/server.cjs +250 -169
  55. package/dist/transport/impls/ws/server.cjs.map +1 -0
  56. package/dist/transport/impls/ws/server.d.cts +2 -2
  57. package/dist/transport/impls/ws/server.d.ts +2 -2
  58. package/dist/transport/impls/ws/server.js +6 -5
  59. package/dist/transport/impls/ws/server.js.map +1 -0
  60. package/dist/transport/index.cjs +388 -243
  61. package/dist/transport/index.cjs.map +1 -0
  62. package/dist/transport/index.d.cts +3 -2
  63. package/dist/transport/index.d.ts +3 -2
  64. package/dist/transport/index.js +5 -4
  65. package/dist/transport/index.js.map +1 -0
  66. package/dist/util/testHelpers.cjs +2 -0
  67. package/dist/util/testHelpers.cjs.map +1 -0
  68. package/dist/util/testHelpers.d.cts +2 -2
  69. package/dist/util/testHelpers.d.ts +2 -2
  70. package/dist/util/testHelpers.js +6 -5
  71. package/dist/util/testHelpers.js.map +1 -0
  72. package/package.json +2 -1
@@ -6,14 +6,15 @@ import {
6
6
  coerceErrorString,
7
7
  handshakeRequestMessage,
8
8
  handshakeResponseMessage,
9
- isAck
10
- } from "./chunk-D5PVGZPQ.js";
9
+ isAck,
10
+ tracing_default
11
+ } from "./chunk-5WFL722S.js";
11
12
  import {
12
13
  log
13
- } from "./chunk-NBE3D667.js";
14
+ } from "./chunk-DT5JS6TM.js";
14
15
  import {
15
16
  NaiveJsonCodec
16
- } from "./chunk-GZ7HCLLM.js";
17
+ } from "./chunk-XAG3SC7R.js";
17
18
 
18
19
  // transport/session.ts
19
20
  import { customAlphabet } from "nanoid";
@@ -289,6 +290,12 @@ var EventDispatcher = class {
289
290
 
290
291
  // transport/transport.ts
291
292
  import { Value } from "@sinclair/typebox/value";
293
+ import {
294
+ context,
295
+ propagation,
296
+ SpanKind,
297
+ SpanStatusCode
298
+ } from "@opentelemetry/api";
292
299
 
293
300
  // transport/rateLimit.ts
294
301
  var LeakyBucketRateLimit = class {
@@ -789,82 +796,142 @@ var ClientTransport = class extends Transport {
789
796
  * @param to The client ID of the node to connect to.
790
797
  */
791
798
  async connect(to) {
792
- const canProceedWithConnection = () => this.state === "open";
793
- if (!canProceedWithConnection()) {
794
- log?.info(
795
- `transport state is no longer open, cancelling attempt to connect to ${to}`,
796
- { clientId: this.clientId, connectedTo: to }
797
- );
798
- return;
799
- }
800
- let reconnectPromise = this.inflightConnectionPromises.get(to);
801
- if (!reconnectPromise) {
802
- const budgetConsumed = this.retryBudget.getBudgetConsumed(to);
803
- if (!this.retryBudget.hasBudget(to)) {
804
- const errMsg = `tried to connect to ${to} but retry budget exceeded (more than ${budgetConsumed} attempts in the last ${this.retryBudget.totalBudgetRestoreTime}ms)`;
805
- log?.warn(errMsg, { clientId: this.clientId, connectedTo: to });
806
- this.protocolError(ProtocolError.RetriesExceeded, errMsg);
807
- return;
808
- }
809
- let sleep = Promise.resolve();
810
- const backoffMs = this.retryBudget.getBackoffMs(to);
811
- if (backoffMs > 0) {
812
- sleep = new Promise((resolve) => setTimeout(resolve, backoffMs));
813
- }
814
- log?.info(`attempting connection to ${to} (${backoffMs}ms backoff)`, {
815
- clientId: this.clientId,
816
- connectedTo: to
817
- });
818
- this.retryBudget.consumeBudget(to);
819
- reconnectPromise = sleep.then(() => {
820
- if (!canProceedWithConnection()) {
821
- throw new Error("transport state is no longer open");
799
+ return tracing_default.startActiveSpan(
800
+ "connect",
801
+ {
802
+ attributes: {
803
+ component: "river",
804
+ "span.kind": "client"
805
+ },
806
+ kind: SpanKind.CLIENT
807
+ },
808
+ async (span) => {
809
+ try {
810
+ await this.connectAttempt(to);
811
+ } catch (e) {
812
+ if (e instanceof Error) {
813
+ span.recordException(e);
814
+ } else {
815
+ span.recordException(coerceErrorString(e));
816
+ }
817
+ span.setStatus({ code: SpanStatusCode.ERROR });
818
+ } finally {
819
+ span.end();
822
820
  }
823
- }).then(() => this.createNewOutgoingConnection(to)).then((conn) => {
824
- if (!canProceedWithConnection()) {
825
- log?.info(
826
- `transport state is no longer open, closing pre-handshake connection to ${to}`,
827
- {
828
- clientId: this.clientId,
829
- connectedTo: to,
830
- connId: conn.debugId
821
+ }
822
+ );
823
+ }
824
+ async connectAttempt(to, attempt = 0) {
825
+ const retry = await tracing_default.startActiveSpan(
826
+ "connect",
827
+ {
828
+ attributes: {
829
+ component: "river",
830
+ "river.attempt": attempt,
831
+ "span.kind": "client"
832
+ },
833
+ kind: SpanKind.CLIENT
834
+ },
835
+ async (span) => {
836
+ try {
837
+ const canProceedWithConnection = () => this.state === "open";
838
+ if (!canProceedWithConnection()) {
839
+ log?.info(
840
+ `transport state is no longer open, cancelling attempt to connect to ${to}`,
841
+ { clientId: this.clientId, connectedTo: to }
842
+ );
843
+ return false;
844
+ }
845
+ let reconnectPromise = this.inflightConnectionPromises.get(to);
846
+ if (!reconnectPromise) {
847
+ const budgetConsumed = this.retryBudget.getBudgetConsumed(to);
848
+ if (!this.retryBudget.hasBudget(to)) {
849
+ const errMsg = `tried to connect to ${to} but retry budget exceeded (more than ${budgetConsumed} attempts in the last ${this.retryBudget.totalBudgetRestoreTime}ms)`;
850
+ log?.warn(errMsg, { clientId: this.clientId, connectedTo: to });
851
+ this.protocolError(ProtocolError.RetriesExceeded, errMsg);
852
+ return false;
831
853
  }
832
- );
833
- conn.close();
834
- throw new Error("transport state is no longer open");
835
- }
836
- return this.sendHandshake(to, conn).then((ok) => {
837
- if (!ok) {
838
- conn.close();
839
- throw new Error("failed to send handshake");
854
+ let sleep = Promise.resolve();
855
+ const backoffMs = this.retryBudget.getBackoffMs(to);
856
+ if (backoffMs > 0) {
857
+ sleep = new Promise((resolve) => setTimeout(resolve, backoffMs));
858
+ }
859
+ log?.info(
860
+ `attempting connection to ${to} (${backoffMs}ms backoff)`,
861
+ {
862
+ clientId: this.clientId,
863
+ connectedTo: to
864
+ }
865
+ );
866
+ this.retryBudget.consumeBudget(to);
867
+ reconnectPromise = sleep.then(() => {
868
+ if (!canProceedWithConnection()) {
869
+ throw new Error("transport state is no longer open");
870
+ }
871
+ }).then(() => this.createNewOutgoingConnection(to)).then((conn) => {
872
+ if (!canProceedWithConnection()) {
873
+ log?.info(
874
+ `transport state is no longer open, closing pre-handshake connection to ${to}`,
875
+ {
876
+ clientId: this.clientId,
877
+ connectedTo: to,
878
+ connId: conn.debugId
879
+ }
880
+ );
881
+ conn.close();
882
+ throw new Error("transport state is no longer open");
883
+ }
884
+ return this.sendHandshake(to, conn).then((ok) => {
885
+ if (!ok) {
886
+ conn.close();
887
+ throw new Error("failed to send handshake");
888
+ }
889
+ return conn;
890
+ });
891
+ });
892
+ this.inflightConnectionPromises.set(to, reconnectPromise);
893
+ } else {
894
+ log?.info(
895
+ `attempting connection to ${to} (reusing previous attempt)`,
896
+ {
897
+ clientId: this.clientId,
898
+ connectedTo: to
899
+ }
900
+ );
840
901
  }
841
- return conn;
842
- });
843
- });
844
- this.inflightConnectionPromises.set(to, reconnectPromise);
845
- } else {
846
- log?.info(`attempting connection to ${to} (reusing previous attempt)`, {
847
- clientId: this.clientId,
848
- connectedTo: to
849
- });
850
- }
851
- try {
852
- await reconnectPromise;
853
- } catch (error) {
854
- this.inflightConnectionPromises.delete(to);
855
- const errStr = coerceErrorString(error);
856
- if (!this.reconnectOnConnectionDrop || !canProceedWithConnection()) {
857
- log?.warn(`connection to ${to} failed (${errStr})`, {
858
- clientId: this.clientId,
859
- connectedTo: to
860
- });
861
- } else {
862
- log?.warn(`connection to ${to} failed (${errStr}), retrying`, {
863
- clientId: this.clientId,
864
- connectedTo: to
865
- });
866
- return this.connect(to);
902
+ try {
903
+ await reconnectPromise;
904
+ } catch (error) {
905
+ this.inflightConnectionPromises.delete(to);
906
+ const errStr = coerceErrorString(error);
907
+ if (!this.reconnectOnConnectionDrop || !canProceedWithConnection()) {
908
+ log?.warn(`connection to ${to} failed (${errStr})`, {
909
+ clientId: this.clientId,
910
+ connectedTo: to
911
+ });
912
+ } else {
913
+ log?.warn(`connection to ${to} failed (${errStr}), retrying`, {
914
+ clientId: this.clientId,
915
+ connectedTo: to
916
+ });
917
+ return true;
918
+ }
919
+ }
920
+ } catch (e) {
921
+ if (e instanceof Error) {
922
+ span.recordException(e);
923
+ } else {
924
+ span.recordException(coerceErrorString(e));
925
+ }
926
+ span.setStatus({ code: SpanStatusCode.ERROR });
927
+ } finally {
928
+ span.end();
929
+ }
930
+ return false;
867
931
  }
932
+ );
933
+ if (retry) {
934
+ return this.connectAttempt(to, attempt + 1);
868
935
  }
869
936
  }
870
937
  deleteSession(session) {
@@ -872,6 +939,8 @@ var ClientTransport = class extends Transport {
872
939
  super.deleteSession(session);
873
940
  }
874
941
  async sendHandshake(to, conn) {
942
+ const tracing = { traceparent: "", tracestate: "" };
943
+ propagation.inject(context.active(), tracing);
875
944
  let metadata;
876
945
  if (this.options.handshake) {
877
946
  metadata = await this.options.handshake.get();
@@ -892,7 +961,8 @@ var ClientTransport = class extends Transport {
892
961
  this.clientId,
893
962
  to,
894
963
  session.id,
895
- metadata
964
+ metadata,
965
+ tracing
896
966
  );
897
967
  log?.debug(`sending handshake request to ${to}`, {
898
968
  clientId: this.clientId,
@@ -923,78 +993,100 @@ var ServerTransport = class extends Transport {
923
993
  });
924
994
  }
925
995
  handleConnection(conn) {
926
- if (this.state !== "open")
927
- return;
928
- log?.info(`new incoming connection`, {
929
- clientId: this.clientId,
930
- connId: conn.debugId
931
- });
932
- let session = void 0;
933
- const client = () => session?.to ?? "unknown";
934
- const handshakeTimeout = setTimeout(() => {
935
- if (!session) {
936
- log?.warn(
937
- `connection to ${client()} timed out waiting for handshake, closing`,
938
- {
939
- clientId: this.clientId,
940
- connectedTo: client(),
941
- connId: conn.debugId
942
- }
943
- );
944
- conn.close();
945
- }
946
- }, this.options.sessionDisconnectGraceMs);
947
- const buffer = [];
948
- let receivedHandshakeMessage = false;
949
- const handshakeHandler = (data) => {
950
- if (receivedHandshakeMessage) {
951
- buffer.push(data);
952
- return;
953
- }
954
- receivedHandshakeMessage = true;
955
- clearTimeout(handshakeTimeout);
956
- void this.receiveHandshakeRequestMessage(data, conn).then(
957
- (maybeSession) => {
958
- if (!maybeSession) {
996
+ tracing_default.startActiveSpan(
997
+ "handleConnection",
998
+ {
999
+ attributes: {
1000
+ component: "river",
1001
+ "span.kind": "server"
1002
+ },
1003
+ kind: SpanKind.SERVER
1004
+ },
1005
+ (span) => {
1006
+ if (this.state !== "open")
1007
+ return;
1008
+ log?.info(`new incoming connection`, {
1009
+ clientId: this.clientId,
1010
+ connId: conn.debugId
1011
+ });
1012
+ let session = void 0;
1013
+ const client = () => session?.to ?? "unknown";
1014
+ const handshakeTimeout = setTimeout(() => {
1015
+ if (!session) {
1016
+ log?.warn(
1017
+ `connection to ${client()} timed out waiting for handshake, closing`,
1018
+ {
1019
+ clientId: this.clientId,
1020
+ connectedTo: client(),
1021
+ connId: conn.debugId
1022
+ }
1023
+ );
1024
+ span.setStatus({ code: SpanStatusCode.ERROR });
1025
+ span.end();
959
1026
  conn.close();
1027
+ }
1028
+ }, this.options.sessionDisconnectGraceMs);
1029
+ const buffer = [];
1030
+ let receivedHandshakeMessage = false;
1031
+ const handshakeHandler = (data) => {
1032
+ if (receivedHandshakeMessage) {
1033
+ buffer.push(data);
960
1034
  return;
961
1035
  }
962
- session = maybeSession;
963
- const dataHandler = (data2) => {
964
- const parsed = this.parseMsg(data2);
965
- if (!parsed) {
966
- conn.close();
967
- return;
1036
+ receivedHandshakeMessage = true;
1037
+ clearTimeout(handshakeTimeout);
1038
+ void this.receiveHandshakeRequestMessage(data, conn).then(
1039
+ (maybeSession) => {
1040
+ if (!maybeSession) {
1041
+ span.setStatus({ code: SpanStatusCode.ERROR });
1042
+ span.end();
1043
+ conn.close();
1044
+ return;
1045
+ }
1046
+ session = maybeSession;
1047
+ const dataHandler = (data2) => {
1048
+ const parsed = this.parseMsg(data2);
1049
+ if (!parsed) {
1050
+ conn.close();
1051
+ return;
1052
+ }
1053
+ this.handleMsg(parsed);
1054
+ };
1055
+ conn.removeDataListener(handshakeHandler);
1056
+ conn.addDataListener(dataHandler);
1057
+ for (const data2 of buffer) {
1058
+ dataHandler(data2);
1059
+ }
1060
+ buffer.length = 0;
968
1061
  }
969
- this.handleMsg(parsed);
970
- };
971
- conn.removeDataListener(handshakeHandler);
972
- conn.addDataListener(dataHandler);
973
- for (const data2 of buffer) {
974
- dataHandler(data2);
1062
+ );
1063
+ };
1064
+ conn.addDataListener(handshakeHandler);
1065
+ conn.addCloseListener(() => {
1066
+ if (session) {
1067
+ log?.info(`connection to ${client()} disconnected`, {
1068
+ clientId: this.clientId,
1069
+ connId: conn.debugId
1070
+ });
1071
+ this.onDisconnect(conn, session);
975
1072
  }
976
- buffer.length = 0;
977
- }
978
- );
979
- };
980
- conn.addDataListener(handshakeHandler);
981
- conn.addCloseListener(() => {
982
- if (!session)
983
- return;
984
- log?.info(`connection to ${client()} disconnected`, {
985
- clientId: this.clientId,
986
- connId: conn.debugId
987
- });
988
- this.onDisconnect(conn, session);
989
- });
990
- conn.addErrorListener((err) => {
991
- if (!session)
992
- return;
993
- log?.warn(
994
- `connection to ${client()} got an error: ${coerceErrorString(err)}`,
995
- { clientId: this.clientId, connId: conn.debugId }
996
- );
997
- });
1073
+ span.setStatus({ code: SpanStatusCode.OK });
1074
+ span.end();
1075
+ });
1076
+ conn.addErrorListener((err) => {
1077
+ if (session) {
1078
+ log?.warn(
1079
+ `connection to ${client()} got an error: ${coerceErrorString(
1080
+ err
1081
+ )}`,
1082
+ { clientId: this.clientId, connId: conn.debugId }
1083
+ );
1084
+ }
1085
+ span.setStatus({ code: SpanStatusCode.ERROR });
1086
+ span.end();
1087
+ });
1088
+ }
1089
+ );
998
1090
  }
999
1091
  async receiveHandshakeRequestMessage(data, conn) {
1000
1092
  const parsed = this.parseMsg(data);
@@ -1005,117 +1097,163 @@ var ServerTransport = class extends Transport {
1005
1097
  );
1006
1098
  return false;
1007
1099
  }
1008
- if (!Value.Check(ControlMessageHandshakeRequestSchema, parsed.payload)) {
1009
- const reason = "received invalid handshake msg";
1010
- const responseMsg2 = handshakeResponseMessage(this.clientId, parsed.from, {
1011
- ok: false,
1012
- reason
1013
- });
1014
- conn.send(this.codec.toBuffer(responseMsg2));
1015
- const logData = typeof parsed.payload === "object" ? { ...parsed, payload: { ...parsed.payload, metadata: "redacted" } } : { ...parsed };
1016
- log?.warn(`${reason}: ${JSON.stringify(logData)}`, {
1017
- clientId: this.clientId,
1018
- connId: conn.debugId
1019
- });
1020
- this.protocolError(
1021
- ProtocolError.HandshakeFailed,
1022
- "invalid handshake request"
1023
- );
1024
- return false;
1025
- }
1026
- const gotVersion = parsed.payload.protocolVersion;
1027
- if (gotVersion !== PROTOCOL_VERSION) {
1028
- const reason = `incorrect version (got: ${gotVersion} wanted ${PROTOCOL_VERSION})`;
1029
- const responseMsg2 = handshakeResponseMessage(this.clientId, parsed.from, {
1030
- ok: false,
1031
- reason
1032
- });
1033
- conn.send(this.codec.toBuffer(responseMsg2));
1034
- log?.warn(
1035
- `received handshake msg with incompatible protocol version (got: ${gotVersion}, expected: ${PROTOCOL_VERSION})`,
1036
- { clientId: this.clientId, connId: conn.debugId }
1037
- );
1038
- this.protocolError(ProtocolError.HandshakeFailed, reason);
1039
- return false;
1100
+ let activeContext = context.active();
1101
+ if (parsed.tracing) {
1102
+ activeContext = propagation.extract(activeContext, parsed.tracing);
1040
1103
  }
1041
- const { session, isReconnect } = this.getOrCreateSession(
1042
- parsed.from,
1043
- conn,
1044
- parsed.payload.sessionId
1045
- );
1046
- let handshakeMetadata;
1047
- if (this.options.handshake) {
1048
- if (!Value.Check(
1049
- this.options.handshake.requestSchema,
1050
- parsed.payload.metadata
1051
- )) {
1052
- const reason = "received malformed handshake metadata";
1053
- const responseMsg2 = handshakeResponseMessage(
1054
- this.clientId,
1104
+ return tracing_default.startActiveSpan(
1105
+ "receiveHandshakeRequestMessage",
1106
+ {
1107
+ attributes: {
1108
+ component: "river",
1109
+ "span.kind": "server"
1110
+ },
1111
+ kind: SpanKind.SERVER
1112
+ },
1113
+ activeContext,
1114
+ async (span) => {
1115
+ if (!Value.Check(ControlMessageHandshakeRequestSchema, parsed.payload)) {
1116
+ const reason = "received invalid handshake msg";
1117
+ const responseMsg2 = handshakeResponseMessage(
1118
+ this.clientId,
1119
+ parsed.from,
1120
+ {
1121
+ ok: false,
1122
+ reason
1123
+ }
1124
+ );
1125
+ conn.send(this.codec.toBuffer(responseMsg2));
1126
+ const logData = typeof parsed.payload === "object" ? {
1127
+ ...parsed,
1128
+ payload: { ...parsed.payload, metadata: "redacted" }
1129
+ } : { ...parsed };
1130
+ log?.warn(`${reason}: ${JSON.stringify(logData)}`, {
1131
+ clientId: this.clientId,
1132
+ connId: conn.debugId
1133
+ });
1134
+ this.protocolError(
1135
+ ProtocolError.HandshakeFailed,
1136
+ "invalid handshake request"
1137
+ );
1138
+ span.setStatus({ code: SpanStatusCode.ERROR });
1139
+ span.end();
1140
+ return false;
1141
+ }
1142
+ const gotVersion = parsed.payload.protocolVersion;
1143
+ if (gotVersion !== PROTOCOL_VERSION) {
1144
+ const reason = `incorrect version (got: ${gotVersion} wanted ${PROTOCOL_VERSION})`;
1145
+ const responseMsg2 = handshakeResponseMessage(
1146
+ this.clientId,
1147
+ parsed.from,
1148
+ {
1149
+ ok: false,
1150
+ reason
1151
+ }
1152
+ );
1153
+ conn.send(this.codec.toBuffer(responseMsg2));
1154
+ log?.warn(
1155
+ `received handshake msg with incompatible protocol version (got: ${gotVersion}, expected: ${PROTOCOL_VERSION})`,
1156
+ { clientId: this.clientId, connId: conn.debugId }
1157
+ );
1158
+ this.protocolError(ProtocolError.HandshakeFailed, reason);
1159
+ span.setStatus({ code: SpanStatusCode.ERROR });
1160
+ span.end();
1161
+ return false;
1162
+ }
1163
+ const { session, isReconnect } = this.getOrCreateSession(
1055
1164
  parsed.from,
1056
- { ok: false, reason }
1165
+ conn,
1166
+ parsed.payload.sessionId
1057
1167
  );
1058
- conn.send(this.codec.toBuffer(responseMsg2));
1059
- log?.warn(`received malformed handshake metadata from ${parsed.from}`, {
1060
- clientId: this.clientId,
1061
- connId: conn.debugId
1062
- });
1063
- this.protocolError(ProtocolError.HandshakeFailed, reason);
1064
- this.deleteSession(session);
1065
- return false;
1066
- }
1067
- const parsedMetadata = await this.options.handshake.parse(
1068
- parsed.payload.metadata,
1069
- session,
1070
- isReconnect
1071
- );
1072
- if (parsedMetadata === false) {
1073
- const reason = "rejected by server";
1074
- const responseMsg2 = handshakeResponseMessage(
1075
- this.clientId,
1076
- parsed.from,
1077
- { ok: false, reason }
1168
+ let handshakeMetadata;
1169
+ if (this.options.handshake) {
1170
+ if (!Value.Check(
1171
+ this.options.handshake.requestSchema,
1172
+ parsed.payload.metadata
1173
+ )) {
1174
+ const reason = "received malformed handshake metadata";
1175
+ const responseMsg2 = handshakeResponseMessage(
1176
+ this.clientId,
1177
+ parsed.from,
1178
+ { ok: false, reason }
1179
+ );
1180
+ conn.send(this.codec.toBuffer(responseMsg2));
1181
+ log?.warn(
1182
+ `received malformed handshake metadata from ${parsed.from}`,
1183
+ {
1184
+ clientId: this.clientId,
1185
+ connId: conn.debugId
1186
+ }
1187
+ );
1188
+ this.protocolError(ProtocolError.HandshakeFailed, reason);
1189
+ this.deleteSession(session);
1190
+ span.setStatus({ code: SpanStatusCode.ERROR });
1191
+ span.end();
1192
+ return false;
1193
+ }
1194
+ const parsedMetadata = await this.options.handshake.parse(
1195
+ parsed.payload.metadata,
1196
+ session,
1197
+ isReconnect
1198
+ );
1199
+ if (parsedMetadata === false) {
1200
+ const reason = "rejected by server";
1201
+ const responseMsg2 = handshakeResponseMessage(
1202
+ this.clientId,
1203
+ parsed.from,
1204
+ { ok: false, reason }
1205
+ );
1206
+ conn.send(this.codec.toBuffer(responseMsg2));
1207
+ log?.warn(`rejected handshake from ${parsed.from}`, {
1208
+ clientId: this.clientId,
1209
+ connId: conn.debugId
1210
+ });
1211
+ this.protocolError(ProtocolError.HandshakeFailed, reason);
1212
+ this.deleteSession(session);
1213
+ span.setStatus({ code: SpanStatusCode.ERROR });
1214
+ span.end();
1215
+ return false;
1216
+ }
1217
+ if (!Value.Check(this.options.handshake.parsedSchema, parsedMetadata)) {
1218
+ const reason = "failed to parse handshake metadata";
1219
+ const responseMsg2 = handshakeResponseMessage(
1220
+ this.clientId,
1221
+ parsed.from,
1222
+ { ok: false, reason }
1223
+ );
1224
+ conn.send(this.codec.toBuffer(responseMsg2));
1225
+ log?.error(`failed to parse handshake metadata`, {
1226
+ clientId: this.clientId,
1227
+ connId: conn.debugId
1228
+ });
1229
+ this.protocolError(ProtocolError.HandshakeFailed, reason);
1230
+ this.deleteSession(session);
1231
+ span.setStatus({ code: SpanStatusCode.ERROR });
1232
+ span.end();
1233
+ return false;
1234
+ }
1235
+ handshakeMetadata = parsedMetadata;
1236
+ }
1237
+ handshakeMetadata ??= {};
1238
+ session.metadata = handshakeMetadata;
1239
+ log?.debug(
1240
+ `handshake from ${parsed.from} ok, responding with handshake success`,
1241
+ { clientId: this.clientId, connId: conn.debugId }
1078
1242
  );
1079
- conn.send(this.codec.toBuffer(responseMsg2));
1080
- log?.warn(`rejected handshake from ${parsed.from}`, {
1081
- clientId: this.clientId,
1082
- connId: conn.debugId
1083
- });
1084
- this.protocolError(ProtocolError.HandshakeFailed, reason);
1085
- this.deleteSession(session);
1086
- return false;
1087
- }
1088
- if (!Value.Check(this.options.handshake.parsedSchema, parsedMetadata)) {
1089
- const reason = "failed to parse handshake metadata";
1090
- const responseMsg2 = handshakeResponseMessage(
1243
+ const responseMsg = handshakeResponseMessage(
1091
1244
  this.clientId,
1092
1245
  parsed.from,
1093
- { ok: false, reason }
1246
+ {
1247
+ ok: true,
1248
+ sessionId: session.id
1249
+ }
1094
1250
  );
1095
- conn.send(this.codec.toBuffer(responseMsg2));
1096
- log?.error(`failed to parse handshake metadata`, {
1097
- clientId: this.clientId,
1098
- connId: conn.debugId
1099
- });
1100
- this.protocolError(ProtocolError.HandshakeFailed, reason);
1101
- this.deleteSession(session);
1102
- return false;
1251
+ conn.send(this.codec.toBuffer(responseMsg));
1252
+ this.onConnect(conn, parsed.from, session, isReconnect);
1253
+ span.end();
1254
+ return session;
1103
1255
  }
1104
- handshakeMetadata = parsedMetadata;
1105
- }
1106
- handshakeMetadata ??= {};
1107
- session.metadata = handshakeMetadata;
1108
- log?.debug(
1109
- `handshake from ${parsed.from} ok, responding with handshake success`,
1110
- { clientId: this.clientId, connId: conn.debugId }
1111
1256
  );
1112
- const responseMsg = handshakeResponseMessage(this.clientId, parsed.from, {
1113
- ok: true,
1114
- sessionId: session.id
1115
- });
1116
- conn.send(this.codec.toBuffer(responseMsg));
1117
- this.onConnect(conn, parsed.from, session, isReconnect);
1118
- return session;
1119
1257
  }
1120
1258
  };
1121
1259
 
@@ -1128,3 +1266,4 @@ export {
1128
1266
  ClientTransport,
1129
1267
  ServerTransport
1130
1268
  };
1269
+ //# sourceMappingURL=chunk-NYOK5VKK.js.map