@workerstack/clients 1.0.0-rc.27 → 1.0.0-rc.29

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 (145) hide show
  1. package/README.md +30 -7
  2. package/dist/emit/cli/commands.js +25 -5
  3. package/dist/emit/cli/flags.js +7 -3
  4. package/dist/emit/cli/skills.js +5 -1
  5. package/dist/emit/csharp/realtime.d.ts +1 -8
  6. package/dist/emit/csharp/realtime.js +25 -25
  7. package/dist/emit/csharp/sdk-answer.d.ts +10 -2
  8. package/dist/emit/csharp/sdk-method.js +9 -2
  9. package/dist/emit/csharp/sse.d.ts +0 -11
  10. package/dist/emit/csharp/sse.js +91 -10
  11. package/dist/emit/csharp/transport.js +3 -3
  12. package/dist/emit/csharp/types-messages.d.ts +47 -0
  13. package/dist/emit/csharp/types-messages.js +172 -0
  14. package/dist/emit/csharp/types-names.js +3 -2
  15. package/dist/emit/csharp/ws.d.ts +0 -15
  16. package/dist/emit/csharp/ws.js +26 -5
  17. package/dist/emit/go/sdk-answer.d.ts +24 -1
  18. package/dist/emit/go/sdk-method.d.ts +3 -0
  19. package/dist/emit/go/sdk-method.js +16 -10
  20. package/dist/emit/go/sse.d.ts +2 -10
  21. package/dist/emit/go/sse.js +87 -12
  22. package/dist/emit/go/types-union.d.ts +3 -2
  23. package/dist/emit/go/types-union.js +2 -0
  24. package/dist/emit/go/types.d.ts +6 -0
  25. package/dist/emit/go/types.js +12 -1
  26. package/dist/emit/go/ws.d.ts +4 -11
  27. package/dist/emit/go/ws.js +214 -58
  28. package/dist/emit/java/json.d.ts +3 -0
  29. package/dist/emit/java/layout-ast.d.ts +4 -1
  30. package/dist/emit/java/layout-types.js +1 -1
  31. package/dist/emit/java/models-names.d.ts +2 -0
  32. package/dist/emit/java/models-names.js +1 -0
  33. package/dist/emit/java/models-union.d.ts +12 -1
  34. package/dist/emit/java/models-union.js +11 -5
  35. package/dist/emit/java/models.d.ts +5 -0
  36. package/dist/emit/java/models.js +22 -7
  37. package/dist/emit/java/realtime.d.ts +29 -9
  38. package/dist/emit/java/realtime.js +45 -10
  39. package/dist/emit/java/sdk-mirror.js +6 -5
  40. package/dist/emit/java/sdk-op.js +1 -1
  41. package/dist/emit/java/sse.d.ts +11 -10
  42. package/dist/emit/java/sse.js +104 -5
  43. package/dist/emit/java/ws.d.ts +46 -7
  44. package/dist/emit/java/ws.js +89 -4
  45. package/dist/emit/mcp/output-schema.d.ts +4 -2
  46. package/dist/emit/mcp/output-schema.js +56 -12
  47. package/dist/emit/python/realtime.d.ts +9 -6
  48. package/dist/emit/python/realtime.js +21 -19
  49. package/dist/emit/python/sdk-answer.d.ts +5 -1
  50. package/dist/emit/python/sdk-method.d.ts +1 -1
  51. package/dist/emit/python/sdk-method.js +33 -6
  52. package/dist/emit/python/sdk.js +22 -2
  53. package/dist/emit/python/sse.d.ts +0 -5
  54. package/dist/emit/python/sse.js +35 -5
  55. package/dist/emit/python/types.d.ts +7 -0
  56. package/dist/emit/python/types.js +20 -3
  57. package/dist/emit/python/ws.d.ts +20 -6
  58. package/dist/emit/python/ws.js +67 -1
  59. package/dist/emit/rust/realtime.d.ts +7 -5
  60. package/dist/emit/rust/realtime.js +14 -17
  61. package/dist/emit/rust/sdk-method.js +1 -1
  62. package/dist/emit/rust/sse.d.ts +11 -7
  63. package/dist/emit/rust/sse.js +52 -6
  64. package/dist/emit/rust/types-union.d.ts +9 -1
  65. package/dist/emit/rust/types-union.js +4 -0
  66. package/dist/emit/rust/types.d.ts +9 -0
  67. package/dist/emit/rust/types.js +13 -7
  68. package/dist/emit/rust/ws.d.ts +22 -4
  69. package/dist/emit/rust/ws.js +57 -7
  70. package/dist/emit/ts/route-tree.d.ts +1 -1
  71. package/dist/emit/ts/route-tree.js +0 -11
  72. package/dist/emit/ts/sdk-types-preamble.js +4 -0
  73. package/dist/emit/ts/sdk-types.js +49 -10
  74. package/dist/emit/ts/sdk.js +2 -2
  75. package/dist/emit/ts/service-map.d.ts +8 -2
  76. package/dist/emit/ts/service-map.js +30 -2
  77. package/dist/emit/ts/type-gen.d.ts +4 -3
  78. package/dist/emit/ts/type-gen.js +83 -40
  79. package/dist/extract/chain.d.ts +10 -6
  80. package/dist/extract/chain.js +5 -19
  81. package/dist/extract/extract.d.ts +2 -2
  82. package/dist/extract/extract.js +37 -23
  83. package/dist/extract/walk.d.ts +15 -4
  84. package/dist/extract/walk.js +159 -15
  85. package/dist/ir/build.js +4 -0
  86. package/dist/ir/model.d.ts +16 -0
  87. package/dist/ir/sdk-model.d.ts +25 -1
  88. package/dist/ir/sdk-model.js +35 -5
  89. package/dist/ir/slots.d.ts +1 -1
  90. package/dist/ir/slots.js +11 -3
  91. package/dist/ir/streams.d.ts +16 -0
  92. package/dist/ir/streams.js +40 -0
  93. package/dist/runtime/cli/socket.go +107 -13
  94. package/dist/runtime/cli/stream.go +18 -11
  95. package/dist/runtime/csharp/Adapters.cs +12 -11
  96. package/dist/runtime/csharp/Events.cs +22 -17
  97. package/dist/runtime/csharp/Realtime.cs +50 -23
  98. package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
  99. package/dist/runtime/csharp/TransportSse.cs +3 -3
  100. package/dist/runtime/csharp/Ws.cs +1 -1
  101. package/dist/runtime/csharp/WsDial.cs +19 -1
  102. package/dist/runtime/csharp/WsTyped.cs +109 -0
  103. package/dist/runtime/go/realtime.go +125 -41
  104. package/dist/runtime/go/realtime_loop.go +21 -18
  105. package/dist/runtime/go/result.go +2 -1
  106. package/dist/runtime/go/sse.go +11 -0
  107. package/dist/runtime/go/stream.go +29 -13
  108. package/dist/runtime/go/transport.go +15 -21
  109. package/dist/runtime/go/transport_longpoll.go +3 -4
  110. package/dist/runtime/go/transport_sse.go +6 -6
  111. package/dist/runtime/go/ws.go +157 -61
  112. package/dist/runtime/java/EventStream.java +47 -29
  113. package/dist/runtime/java/Exchange.java +5 -5
  114. package/dist/runtime/java/Flight.java +3 -3
  115. package/dist/runtime/java/Realtime.java +45 -11
  116. package/dist/runtime/java/ResumableConnection.java +77 -32
  117. package/dist/runtime/java/Socket.java +8 -4
  118. package/dist/runtime/java/SseAdapter.java +1 -1
  119. package/dist/runtime/java/TypedWebSocket.java +81 -24
  120. package/dist/runtime/java/WsAdapter.java +4 -2
  121. package/dist/runtime/java/WsDial.java +12 -5
  122. package/dist/runtime/python/events.py +25 -11
  123. package/dist/runtime/python/operation.py +6 -1
  124. package/dist/runtime/python/realtime.py +47 -33
  125. package/dist/runtime/python/send_async.py +1 -0
  126. package/dist/runtime/python/transport_sse.py +2 -2
  127. package/dist/runtime/python/transport_ws.py +1 -1
  128. package/dist/runtime/python/ws.py +100 -39
  129. package/dist/runtime/rust/events.rs +64 -41
  130. package/dist/runtime/rust/realtime.rs +80 -34
  131. package/dist/runtime/rust/realtime_loop.rs +37 -12
  132. package/dist/runtime/rust/sse.rs +3 -2
  133. package/dist/runtime/rust/transport_sse.rs +1 -1
  134. package/dist/runtime/rust/transport_ws.rs +3 -2
  135. package/dist/runtime/rust/ws.rs +122 -50
  136. package/dist/runtime/ts/realtime-connection.ts +22 -0
  137. package/dist/runtime/ts/realtime-transports.ts +13 -4
  138. package/dist/runtime/ts/realtime.ts +27 -3
  139. package/dist/runtime/ts/sdk-realtime.ts +1 -1
  140. package/dist/runtime/ts/sdk-sse.ts +31 -14
  141. package/dist/runtime/ts/sdk-ws.ts +2 -1
  142. package/dist/runtime/ts/sdk.ts +9 -2
  143. package/dist/runtime/ts/sse.ts +8 -0
  144. package/dist/runtime/ts/ws.ts +88 -50
  145. package/package.json +3 -61
@@ -5,26 +5,34 @@ import java.time.Duration;
5
5
  import java.util.Iterator;
6
6
  import java.util.List;
7
7
  import java.util.NoSuchElementException;
8
+ import java.util.concurrent.CopyOnWriteArrayList;
9
+ import java.util.function.Consumer;
8
10
  import tools.jackson.core.JacksonException;
9
11
  import tools.jackson.core.type.TypeReference;
10
12
  import tools.jackson.databind.JsonNode;
11
13
 
12
14
  /**
13
- * A connection over a chain of transports, tried in order, read by {@link #receive()} or a
14
- * for-each: each message decoded as {@code T} (a message that does not decode throws once, the
15
- * connection kept), the cursor in {@link #options()} advanced past it. After a drop it reopens the
16
- * chain from the cursor, backing off from the delay (an SSE retry first), doubling to 30 s, for up
17
- * to maxReconnectAttempts in a row; giving up throws the last failure once, and the reads then end.
18
- * Leaving a loop keeps the connection, so one thread reads at a time. An interrupt of the reading
19
- * thread throws CancellationException and leaves it reconnecting; {@link #close()} from any thread
20
- * ends a pending read with null.
15
+ * A connection over a chain of transports, tried in order, that reads {@code TIn}, what the server
16
+ * sends, by {@link #receive()} or a for-each, and sends {@code TOut}, what it receives, as JSON.
17
+ * Each message advances the cursor in {@link #options()} first, then decodes as {@code TIn}, and
18
+ * onMessage fires inside the read, on the reading thread, before it returns. A message that does
19
+ * not decode throws {@link DecodeException} once, from receive or the iterator's hasNext (it reads
20
+ * ahead), the connection kept, and the next read reads the next one; a connection of declared
21
+ * messages reads only JSON, any other reads a message that is no JSON as a JSON string. After a
22
+ * drop it reopens the chain from the cursor, backing off from the delay (an SSE retry first),
23
+ * doubling to 30 s, for up to maxReconnectAttempts in a row; giving up throws the last failure
24
+ * once, and the reads then end. Leaving a loop keeps the connection, so one thread reads at a time.
25
+ * An interrupt of the reading thread throws CancellationException and leaves it reconnecting;
26
+ * {@link #close()} from any thread ends a pending read with null.
21
27
  */
22
- public final class ResumableConnection<T> implements Iterable<T>, AutoCloseable {
28
+ public class ResumableConnection<TIn, TOut> implements Iterable<TIn>, AutoCloseable {
23
29
  private final String url;
24
30
  private final List<TransportAdapter> adapters;
25
31
  private final TransportOptions options;
26
- private final TypeReference<T> type;
32
+ private final TypeReference<TIn> type;
33
+ private final boolean strict;
27
34
  private final RealtimeLoop loop;
35
+ private final List<Consumer<TIn>> onMessage;
28
36
 
29
37
  /**
30
38
  * A connection to {@code url} over {@code adapters}, its messages read as {@code type}; it opens
@@ -33,27 +41,44 @@ public final class ResumableConnection<T> implements Iterable<T>, AutoCloseable
33
41
  public ResumableConnection(
34
42
  String url,
35
43
  List<TransportAdapter> adapters,
36
- TypeReference<T> type,
44
+ TypeReference<TIn> type,
37
45
  TransportOptions options) {
38
- this(url, adapters, type, options, RealtimeLoop.OPEN_LIMIT);
46
+ this(url, adapters, type, options, RealtimeLoop.OPEN_LIMIT, false);
39
47
  }
40
48
 
41
49
  /** A connection with the default options: no cursor, 5 attempts, a 1 s delay. */
42
- public ResumableConnection(String url, List<TransportAdapter> adapters, TypeReference<T> type) {
50
+ public ResumableConnection(String url, List<TransportAdapter> adapters, TypeReference<TIn> type) {
43
51
  this(url, adapters, type, null);
44
52
  }
45
53
 
46
54
  ResumableConnection(
47
55
  String url,
48
56
  List<TransportAdapter> adapters,
49
- TypeReference<T> type,
57
+ TypeReference<TIn> type,
50
58
  TransportOptions options,
51
- Duration openLimit) {
59
+ Duration openLimit,
60
+ boolean strict) {
52
61
  this.url = url;
53
62
  this.adapters = List.copyOf(adapters);
54
63
  this.options = options == null ? TransportOptions.builder().build() : options;
55
64
  this.type = type;
65
+ this.strict = strict;
56
66
  this.loop = new RealtimeLoop(this.adapters, this.options, url, openLimit);
67
+ this.onMessage = new CopyOnWriteArrayList<>();
68
+ }
69
+
70
+ /**
71
+ * The connection {@code opened}, its reads, sends, cursor and handlers shared: a generated
72
+ * connection's base.
73
+ */
74
+ protected ResumableConnection(ResumableConnection<TIn, TOut> opened) {
75
+ this.url = opened.url;
76
+ this.adapters = opened.adapters;
77
+ this.options = opened.options;
78
+ this.type = opened.type;
79
+ this.strict = opened.strict;
80
+ this.loop = opened.loop;
81
+ this.onMessage = opened.onMessage;
57
82
  }
58
83
 
59
84
  /** The URL each adapter connects to. */
@@ -91,17 +116,22 @@ public final class ResumableConnection<T> implements Iterable<T>, AutoCloseable
91
116
  loop.open();
92
117
  }
93
118
 
94
- /** The next message, decoded; null once DISCONNECTED. */
95
- public T receive() {
119
+ /** The next message, decoded, each onMessage handler run on it; null once DISCONNECTED. */
120
+ public TIn receive() {
96
121
  TransportMessage message = loop.next();
97
- return message == null ? null : deliver(message);
122
+ if (message == null) {
123
+ return null;
124
+ }
125
+ TIn value = deliver(message);
126
+ onMessage.forEach(handler -> Socket.run(handler, value));
127
+ return value;
98
128
  }
99
129
 
100
130
  /** The messages in order, through receive(). */
101
131
  @Override
102
- public Iterator<T> iterator() {
132
+ public Iterator<TIn> iterator() {
103
133
  return new Iterator<>() {
104
- private T ahead;
134
+ private TIn ahead;
105
135
 
106
136
  @Override
107
137
  public boolean hasNext() {
@@ -112,25 +142,30 @@ public final class ResumableConnection<T> implements Iterable<T>, AutoCloseable
112
142
  }
113
143
 
114
144
  @Override
115
- public T next() {
145
+ public TIn next() {
116
146
  if (!hasNext()) {
117
147
  throw new NoSuchElementException("the connection ended");
118
148
  }
119
- T value = ahead;
149
+ TIn value = ahead;
120
150
  ahead = null;
121
151
  return value;
122
152
  }
123
153
  };
124
154
  }
125
155
 
156
+ /** Sends {@code value} as its JSON text, through the SDK's mapper, over the open transport. */
157
+ public void send(TOut value) {
158
+ sendText(Json.MAPPER.writeValueAsString(value));
159
+ }
160
+
126
161
  /** Sends {@code text} as it is over the open transport (an SSE or long-poll one POSTs it). */
127
- public void send(String text) {
162
+ public void sendText(String text) {
128
163
  loop.send(text);
129
164
  }
130
165
 
131
- /** Sends {@code value} as its JSON text, through the SDK's mapper. */
132
- public void sendJson(Object value) {
133
- send(Json.MAPPER.writeValueAsString(value));
166
+ /** Runs {@code handler} on each message as a read delivers it, before the read returns. */
167
+ public void onMessage(Consumer<TIn> handler) {
168
+ onMessage.add(handler);
134
169
  }
135
170
 
136
171
  /** Closes the open transport and ends a pending read on any thread with null. */
@@ -139,26 +174,36 @@ public final class ResumableConnection<T> implements Iterable<T>, AutoCloseable
139
174
  loop.close();
140
175
  }
141
176
 
142
- /* the message as JSON, else as a JSON string of its text; the cursor advanced before it decodes */
143
- private T deliver(TransportMessage message) {
177
+ /*
178
+ * the message as JSON, else (unless strict) as a JSON string of its text; the cursor advanced
179
+ * before it decodes
180
+ */
181
+ private TIn deliver(TransportMessage message) {
144
182
  JsonNode payload;
183
+ JacksonException malformed = null;
145
184
  try {
146
185
  payload = Json.MAPPER.readTree(message.text());
147
186
  } catch (JacksonException e) {
148
187
  payload = null;
188
+ malformed = e;
149
189
  }
150
190
  if (payload == null || payload.isMissingNode()) {
151
- payload = Json.MAPPER.getNodeFactory().stringNode(message.text());
191
+ payload = strict ? null : Json.MAPPER.getNodeFactory().stringNode(message.text());
152
192
  }
153
193
  options.advance(message.id(), payload);
154
- T value;
194
+ if (payload == null) {
195
+ String why = malformed == null ? "it is empty" : malformed.getOriginalMessage();
196
+ throw new DecodeException("realtime message is not valid JSON: " + why, malformed);
197
+ }
198
+ String what = strict ? "realtime message" : "a message";
199
+ TIn value;
155
200
  try {
156
201
  value = Json.MAPPER.convertValue(payload, type);
157
202
  } catch (IllegalArgumentException | JacksonException e) {
158
- throw new DecodeException("a message does not decode: " + e.getMessage(), e);
203
+ throw new DecodeException(what + " does not decode: " + e.getMessage(), e);
159
204
  }
160
205
  if (value == null) {
161
- throw new DecodeException("a message does not decode: it is null", null);
206
+ throw new DecodeException(what + " does not decode: it is null", null);
162
207
  }
163
208
  return value;
164
209
  }
@@ -25,7 +25,8 @@ import java.util.function.Function;
25
25
  * A WebSocket as the SDK holds it: the JDK's listener, assembling each message's partials up to 16
26
26
  * MiB and asking for more only as the reader takes what waits (no background reader); the one send
27
27
  * gate every frame goes through, since the JDK fails a frame sent beside another; and the socket's
28
- * one end, which fires exactly one of Closed or Error, once.
28
+ * one end, which fires exactly one of Closed or Error, once; a frame that does not decode fires
29
+ * Error besides, the socket still open.
29
30
  */
30
31
  final class Socket implements WebSocket.Listener {
31
32
  private static final int CAP = 16 << 20;
@@ -40,7 +41,6 @@ final class Socket implements WebSocket.Listener {
40
41
  private final Semaphore gate = new Semaphore(1);
41
42
  private final AtomicBoolean ended = new AtomicBoolean();
42
43
  private final CountDownLatch echo = new CountDownLatch(1);
43
- final List<Consumer<WsMessage>> onMessage = new CopyOnWriteArrayList<>();
44
44
  final List<Consumer<WsClose>> onClosed = new CopyOnWriteArrayList<>();
45
45
  final List<Consumer<java.lang.Exception>> onError = new CopyOnWriteArrayList<>();
46
46
  volatile WebSocket ws;
@@ -219,7 +219,12 @@ final class Socket implements WebSocket.Listener {
219
219
  }
220
220
  }
221
221
 
222
- private static <T> void run(Consumer<T> handler, T value) {
222
+ /** A frame that does not decode: Error fired, the socket still open. */
223
+ void report(RuntimeException error) {
224
+ onError.forEach(handler -> run(handler, error));
225
+ }
226
+
227
+ static <T> void run(Consumer<T> handler, T value) {
223
228
  try {
224
229
  handler.accept(value);
225
230
  } catch (RuntimeException e) {
@@ -237,7 +242,6 @@ final class Socket implements WebSocket.Listener {
237
242
  throw new CancellationException("the read was canceled");
238
243
  }
239
244
  if (item instanceof WsMessage message) {
240
- onMessage.forEach(handler -> run(handler, message));
241
245
  if (!ended.get()) {
242
246
  ws.request(1);
243
247
  }
@@ -35,7 +35,7 @@ final class SseAdapter implements TransportAdapter, RealtimeLoop.Dialed {
35
35
  */
36
36
  @Override
37
37
  public TransportConnection connect(String url, TransportOptions options) {
38
- EventStream<String> stream = dial.stream(options);
38
+ EventStream<SseEvent<String>> stream = dial.stream(options);
39
39
  Iterator<SseEvent<String>> events = stream.iterator();
40
40
  return new TransportConnection() {
41
41
  @Override
@@ -2,45 +2,99 @@
2
2
  package http.runtime;
3
3
 
4
4
  import java.nio.ByteBuffer;
5
+ import java.util.List;
6
+ import java.util.concurrent.CopyOnWriteArrayList;
5
7
  import java.util.function.Consumer;
8
+ import java.util.function.Function;
9
+ import tools.jackson.core.JacksonException;
10
+ import tools.jackson.core.type.TypeReference;
11
+ import tools.jackson.databind.JsonNode;
6
12
 
7
13
  /**
8
- * An open WebSocket. {@link #receive()} reads the next whole message: nothing reads in the
9
- * background, so a socket no one receives from asks the server for nothing more, and onMessage
10
- * fires as receive delivers a message, on the receiving thread. The socket's end, the server's
11
- * close (echoed with its code and reason), a drop, a message over 16 MiB (closed 1008), a keepalive
12
- * ping unanswered for 20 s, or {@link #close()}, fires exactly one of onClosed or onError, once; a
13
- * throwing handler is ignored. An interrupt of the reading thread closes it 1000. Close it, or open
14
- * it in try-with-resources. Its dial runs no onRequest or onResponse hook, and a refused
15
- * handshake's 401 is its error, with no onAuthExpired refresh.
14
+ * An open WebSocket that reads {@code TIn}, what the server sends, and sends {@code TOut}, what it
15
+ * receives, as JSON; an operation that declares no read side reads each {@link WsMessage} as it
16
+ * came. {@link #receive()} reads the next whole message: nothing reads in the background, so a
17
+ * socket no one receives from asks the server for nothing more, and onMessage fires as receive
18
+ * delivers a message, on the receiving thread. A typed frame that is no JSON, or does not decode,
19
+ * throws {@link DecodeException} from receive and fires onError, and the next receive reads on; a
20
+ * binary frame is read as UTF-8 JSON. The socket's end, the server's close (echoed with its code
21
+ * and reason), a drop, a message over 16 MiB (closed 1008), a keepalive ping unanswered for 20 s,
22
+ * or {@link #close()}, fires exactly one of onClosed or onError, once; a throwing handler is
23
+ * ignored. An interrupt of the reading thread closes it 1000. Close it, or open it in
24
+ * try-with-resources. Its dial runs no onRequest or onResponse hook, and a refused handshake's 401
25
+ * is its error, with no onAuthExpired refresh.
16
26
  */
17
- public final class TypedWebSocket implements AutoCloseable {
27
+ public class TypedWebSocket<TIn, TOut> implements AutoCloseable {
18
28
  private final Socket socket;
29
+ private final Function<WsMessage, TIn> read;
30
+ private final List<Consumer<TIn>> onMessage;
19
31
 
20
- TypedWebSocket(Socket socket) {
32
+ TypedWebSocket(Socket socket, Function<WsMessage, TIn> read) {
21
33
  this.socket = socket;
34
+ this.read = read;
35
+ this.onMessage = new CopyOnWriteArrayList<>();
22
36
  }
23
37
 
24
- /** The next whole message, null once the socket ended; an end's error is thrown once. */
25
- public WsMessage receive() {
26
- return socket.receive();
38
+ /** The socket {@code opened}, its reads, sends and handlers shared: a generated socket's base. */
39
+ protected TypedWebSocket(TypedWebSocket<TIn, TOut> opened) {
40
+ this.socket = opened.socket;
41
+ this.read = opened.read;
42
+ this.onMessage = opened.onMessage;
27
43
  }
28
44
 
29
- /** Sends {@code text} as one text message. */
30
- public void send(String text) {
45
+ /** The frame reader of {@code T}: each frame's bytes as UTF-8 JSON, decoded into {@code T}. */
46
+ static <T> Function<WsMessage, T> json(TypeReference<T> type) {
47
+ return message -> {
48
+ JsonNode node;
49
+ try {
50
+ node = Json.MAPPER.readTree(message.data());
51
+ } catch (JacksonException e) {
52
+ throw new DecodeException(
53
+ "WebSocket frame is not valid JSON: " + e.getOriginalMessage(), e);
54
+ }
55
+ try {
56
+ return Json.MAPPER.readerFor(type).readValue(node);
57
+ } catch (JacksonException e) {
58
+ throw new DecodeException("WebSocket frame does not decode: " + e.getOriginalMessage(), e);
59
+ }
60
+ };
61
+ }
62
+
63
+ /**
64
+ * The next whole message, null once the socket ended; an end's error is thrown once, and a frame
65
+ * that does not decode is thrown as it is read.
66
+ */
67
+ public TIn receive() {
68
+ WsMessage message = socket.receive();
69
+ if (message == null) {
70
+ return null;
71
+ }
72
+ TIn value;
73
+ try {
74
+ value = read.apply(message);
75
+ } catch (DecodeException e) {
76
+ socket.report(e);
77
+ throw e;
78
+ }
79
+ onMessage.forEach(handler -> Socket.run(handler, value));
80
+ return value;
81
+ }
82
+
83
+ /** Sends {@code value} as one text message, its JSON through the SDK's mapper. */
84
+ public void send(TOut value) {
85
+ sendText(Json.MAPPER.writeValueAsString(value));
86
+ }
87
+
88
+ /** Sends {@code text} as one text message, as it is. */
89
+ public void sendText(String text) {
31
90
  socket.send(ws -> ws.sendText(text, true));
32
91
  }
33
92
 
34
93
  /** Sends {@code data} as one binary message. */
35
- public void send(byte[] data) {
94
+ public void sendBinary(byte[] data) {
36
95
  socket.send(ws -> ws.sendBinary(ByteBuffer.wrap(data), true));
37
96
  }
38
97
 
39
- /** Sends {@code value} as its JSON text, through the SDK's mapper. */
40
- public void sendJson(Object value) {
41
- send(Json.MAPPER.writeValueAsString(value));
42
- }
43
-
44
98
  /** Closes 1000 with no reason; on an ended socket it does nothing. */
45
99
  @Override
46
100
  public void close() {
@@ -67,8 +121,8 @@ public final class TypedWebSocket implements AutoCloseable {
67
121
  }
68
122
 
69
123
  /** Runs {@code handler} on each message as receive delivers it. */
70
- public void onMessage(Consumer<WsMessage> handler) {
71
- socket.onMessage.add(handler);
124
+ public void onMessage(Consumer<TIn> handler) {
125
+ onMessage.add(handler);
72
126
  }
73
127
 
74
128
  /** Runs {@code handler} once when the socket closes cleanly. */
@@ -76,7 +130,10 @@ public final class TypedWebSocket implements AutoCloseable {
76
130
  socket.onClosed.add(handler);
77
131
  }
78
132
 
79
- /** Runs {@code handler} once when the socket ends in an error. */
133
+ /**
134
+ * Runs {@code handler} once when the socket ends in an error, and on each frame that does not
135
+ * decode.
136
+ */
80
137
  public void onError(Consumer<java.lang.Exception> handler) {
81
138
  socket.onError.add(handler);
82
139
  }
@@ -1,6 +1,8 @@
1
1
  // @generated by clients. DO NOT EDIT.
2
2
  package http.runtime;
3
3
 
4
+ import tools.jackson.databind.JsonNode;
5
+
4
6
  /**
5
7
  * A realtime call's WebSocket: its own upgrade with the cursor as query params, no hook and no log
6
8
  * on the dial.
@@ -30,7 +32,7 @@ final class WsAdapter implements TransportAdapter, RealtimeLoop.Dialed {
30
32
  /** Dials the call's socket; {@code url} is a caller's adapter's. */
31
33
  @Override
32
34
  public TransportConnection connect(String url, TransportOptions options) {
33
- TypedWebSocket socket = dial.socket(options);
35
+ TypedWebSocket<WsMessage, JsonNode> socket = dial.socket(options);
34
36
  return new TransportConnection() {
35
37
  @Override
36
38
  public TransportMessage receive() {
@@ -40,7 +42,7 @@ final class WsAdapter implements TransportAdapter, RealtimeLoop.Dialed {
40
42
 
41
43
  @Override
42
44
  public void send(String text) {
43
- socket.send(text);
45
+ socket.sendText(text);
44
46
  }
45
47
 
46
48
  @Override
@@ -17,20 +17,27 @@ import java.util.UUID;
17
17
  import java.util.concurrent.CancellationException;
18
18
  import java.util.concurrent.CompletableFuture;
19
19
  import java.util.concurrent.ExecutionException;
20
+ import java.util.function.Function;
20
21
 
21
22
  /**
22
23
  * A WebSocket call's dial: the path checked, the call's headers layered (a fresh X-Request-Id, the
23
24
  * config's, the call's, the options', the credential) with no hook and no log, a restricted name
24
- * refused by name, the subprotocols offered, the call's timeout bounding the handshake alone. A
25
- * refusal is its status exception (its body read at most 64 KiB); no redirect is followed.
25
+ * refused by name, the subprotocols offered, the call's timeout bounding the handshake alone, each
26
+ * frame read through the operation's reader. A refusal is its status exception (its body read at
27
+ * most 64 KiB); no redirect is followed.
26
28
  */
27
29
  final class WsDial {
28
30
  private static final int ERROR_CAP = 64 * 1024;
29
31
 
30
32
  private WsDial() {}
31
33
 
32
- static TypedWebSocket open(
33
- Exchange exchange, Operation op, Call call, RequestOptions given, List<String> protocols) {
34
+ static <TIn, TOut> TypedWebSocket<TIn, TOut> open(
35
+ Exchange exchange,
36
+ Operation op,
37
+ Call call,
38
+ RequestOptions given,
39
+ List<String> protocols,
40
+ Function<WsMessage, TIn> read) {
34
41
  RequestOptions options = given == null ? RequestOptions.NONE : given;
35
42
  ClientConfig config = exchange.config();
36
43
  if (java.lang.Thread.currentThread().isInterrupted()) {
@@ -65,7 +72,7 @@ final class WsDial {
65
72
  if (options.raw() != null) {
66
73
  options.raw().fill(101, Map.of(), new byte[0], url);
67
74
  }
68
- return new TypedWebSocket(socket);
75
+ return new TypedWebSocket<>(socket, read);
69
76
  }
70
77
 
71
78
  /** The dial's headers, layered as a call's; a restricted name or a value with CR/LF refused. */
@@ -1,5 +1,6 @@
1
1
  # @generated by clients. DO NOT EDIT.
2
- """An SSE operation's answer: the open stream's events, each one's data decoded. No timeout bounds it.
2
+ """An SSE operation's answer: the open stream's events, each one's data decoded: every event's or none's, or,
3
+ for an operation that names its events, each JSON event's by its name. No timeout bounds it.
3
4
  An event that does not decode, a cap or a failed read is raised once and ends it; the call's ``cancel``,
4
5
  ``aclose`` and a cancelled read end it, the cancelled read raising ``CancelledError``. Open it with
5
6
  ``async with`` or call ``aclose()`` to free its connection; a dropped stream frees it only when collected."""
@@ -11,7 +12,7 @@ import weakref
11
12
  from collections import deque
12
13
  from collections.abc import AsyncGenerator, Awaitable
13
14
  from dataclasses import dataclass
14
- from typing import Generic, Self, TypeVar, cast
15
+ from typing import Generic, Self, TypeAlias, TypeVar, cast
15
16
 
16
17
  import httpx2
17
18
 
@@ -19,9 +20,11 @@ from .errors import APIConnectionError, CanceledError, DecodeError, HttpError, l
19
20
  from .exchange import shaped
20
21
  from .sse import RawEvent, SseParser
21
22
 
22
- __all__ = ["EventStream", "SseEvent"]
23
+ __all__ = ["EventStream", "SseEvent", "SseEventOf"]
23
24
 
24
25
  T = TypeVar("T")
26
+ N = TypeVar("N")
27
+ E = TypeVar("E")
25
28
  R = TypeVar("R")
26
29
 
27
30
  Cancel = threading.Event | asyncio.Event | None
@@ -55,16 +58,21 @@ def dropped(chunks: AsyncGenerator[bytes], response: httpx2.Response) -> None:
55
58
 
56
59
 
57
60
  @dataclass(frozen=True)
58
- class SseEvent(Generic[T]):
59
- """One event: its decoded data, its type, the stream's last event id, and its ``retry``."""
61
+ class SseEventOf(Generic[N, T]):
62
+ """One event: its decoded data, its name, the stream's last event id, and its ``retry``. A named
63
+ event's ``event`` is its name, ``message`` for an unnamed one."""
60
64
 
61
65
  data: T
62
- event: str | None = None
66
+ event: N
63
67
  id: str | None = None
64
68
  retry: int | None = None
65
69
 
66
70
 
67
- class EventStream(Generic[T]):
71
+ SseEvent: TypeAlias = SseEventOf[str | None, T]
72
+ """An event of an operation that names none: ``event`` as sent, ``None`` when unnamed."""
73
+
74
+
75
+ class EventStream(Generic[E]):
68
76
  """An open stream's events, in order (``async for``); ``aclose`` lets the connection go."""
69
77
 
70
78
  def __init__(
@@ -73,10 +81,11 @@ class EventStream(Generic[T]):
73
81
  *,
74
82
  decode: bool,
75
83
  shape: str | None = None,
84
+ events: tuple[str, ...] | None = None,
76
85
  cancel: Cancel = None,
77
86
  ) -> None:
78
87
  self.response = response
79
- self.decode, self.shape = decode, shape
88
+ self.decode, self.shape, self.events = decode, shape, events
80
89
  self.cancel = cancel
81
90
  self.chunks = response.aiter_bytes()
82
91
  weakref.finalize(self, dropped, self.chunks, response)
@@ -94,7 +103,7 @@ class EventStream(Generic[T]):
94
103
  def __aiter__(self) -> Self:
95
104
  return self
96
105
 
97
- async def __anext__(self) -> SseEvent[T]:
106
+ async def __anext__(self) -> E:
98
107
  while not self.pending and not self.ended:
99
108
  await self.pull()
100
109
  if not self.pending:
@@ -104,7 +113,12 @@ class EventStream(Generic[T]):
104
113
  raise failure
105
114
  raw = self.pending.popleft()
106
115
  data: object = raw.data
107
- if self.decode:
116
+ if self.events is None:
117
+ event, json = raw.event, self.decode
118
+ else:
119
+ event = raw.event or "message"
120
+ json = event in self.events
121
+ if json:
108
122
  try:
109
123
  data = loads(raw.data.encode())
110
124
  fits = shaped(data, self.shape)
@@ -116,7 +130,7 @@ class EventStream(Generic[T]):
116
130
  f"an event's data is not a JSON {self.shape or 'value'}"
117
131
  )
118
132
  self.delivered = raw.id or ""
119
- return SseEvent(cast("T", data), raw.event, raw.id, raw.retry)
133
+ return cast("E", SseEventOf(data, event, raw.id, raw.retry))
120
134
 
121
135
  async def pull(self) -> None:
122
136
  try:
@@ -2,7 +2,7 @@
2
2
  """One operation, as its methods call it."""
3
3
 
4
4
  from dataclasses import dataclass
5
- from typing import Generic, Literal, TypeVar
5
+ from typing import Any, Generic, Literal, TypeVar
6
6
 
7
7
  T = TypeVar("T", covariant=True)
8
8
 
@@ -23,3 +23,8 @@ class Operation(Generic[T]):
23
23
  invalidates: tuple[str, ...] = ()
24
24
  stream: Literal["realtime", "sse", "ws"] | None = None
25
25
  headers: tuple[tuple[str, str, HeaderKind, bool], ...] = ()
26
+ events: tuple[str, ...] | None = None
27
+ encode: bool = False
28
+ decode: bool = False
29
+ dispatch: str | None = None
30
+ kind: type[Any] | None = None