@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
@@ -0,0 +1,109 @@
1
+ // @generated by clients. DO NOT EDIT.
2
+ using System;
3
+ using System.Net.WebSockets;
4
+ using System.Text.Json;
5
+ using System.Text.Json.Serialization.Metadata;
6
+ using System.Threading;
7
+ using System.Threading.Tasks;
8
+
9
+ namespace Http.Runtime;
10
+
11
+ /// <summary>
12
+ /// An open WebSocket whose messages are declared: each read is the JSON of a <typeparamref name="TIn"/>, each
13
+ /// <see cref="SendAsync(TOut, CancellationToken)"/> the JSON of a <typeparamref name="TOut"/>, over the socket it
14
+ /// wraps, which ends, closes and caps as <see cref="TypedWebSocket"/> does. A frame that is no JSON, or JSON that is
15
+ /// no <typeparamref name="TIn"/>, throws <see cref="DecodeException"/> from <see cref="ReceiveAsync"/> and fires
16
+ /// <see cref="Error"/>, and the next read reads on.
17
+ /// </summary>
18
+ public sealed class TypedWebSocket<TIn, TOut> : IAsyncDisposable
19
+ {
20
+ private readonly TypedWebSocket _socket;
21
+ private readonly JsonTypeInfo<TIn> _read;
22
+ private readonly JsonTypeInfo<TOut> _write;
23
+
24
+ internal TypedWebSocket(TypedWebSocket socket, JsonTypeInfo<TIn> read, JsonTypeInfo<TOut> write)
25
+ {
26
+ _socket = socket;
27
+ _read = read;
28
+ _write = write;
29
+ socket.Error += e => TypedWebSocket.Fire(Error, e);
30
+ }
31
+
32
+ /// <summary>The subprotocol the server chose; null when it chose none.</summary>
33
+ public string? Subprotocol => _socket.Subprotocol;
34
+
35
+ /// <summary>The server's close frame, once it closed the socket.</summary>
36
+ public WsClose? ClosedBy => _socket.ClosedBy;
37
+
38
+ /// <summary>Each message as it is read and decoded; a handler that throws is ignored.</summary>
39
+ public event Action<TIn>? Message;
40
+
41
+ /// <summary>The socket's close, the server's or the client's own; a handler that throws is ignored.</summary>
42
+ public event Action<WsClose>? Closed
43
+ {
44
+ add => _socket.Closed += value;
45
+ remove => _socket.Closed -= value;
46
+ }
47
+
48
+ /// <summary>The failure that ended the socket, or a frame that does not decode; a handler that throws is ignored.</summary>
49
+ public event Action<Exception>? Error;
50
+
51
+ /// <summary>
52
+ /// The next message, decoded; once the socket ended, the default: null, or a <see cref="JsonElement"/> whose
53
+ /// <see cref="JsonElement.ValueKind"/> is <see cref="JsonValueKind.Undefined"/>. Its token, once fired, closes
54
+ /// the socket.
55
+ /// </summary>
56
+ public async Task<TIn?> ReceiveAsync(CancellationToken cancellationToken = default)
57
+ {
58
+ if (await _socket.ReceiveAsync(cancellationToken).ConfigureAwait(false) is not { } message)
59
+ {
60
+ return default;
61
+ }
62
+ var value = Decoded(message.Data);
63
+ TypedWebSocket.Fire(Message, value);
64
+ return value;
65
+ }
66
+
67
+ /// <summary>Sends <paramref name="value"/> as one text message of its JSON.</summary>
68
+ public Task SendAsync(TOut value, CancellationToken cancellationToken = default) =>
69
+ _socket.SendAsync(value, _write, cancellationToken);
70
+
71
+ /// <summary>Sends <paramref name="text"/> as one text message, as it is.</summary>
72
+ public Task SendAsync(string text, CancellationToken cancellationToken = default) =>
73
+ _socket.SendAsync(text, cancellationToken);
74
+
75
+ /// <summary>Closes the socket as <see cref="TypedWebSocket.CloseAsync"/> does.</summary>
76
+ public Task CloseAsync(WebSocketCloseStatus status = WebSocketCloseStatus.NormalClosure, string reason = "", CancellationToken cancellationToken = default) =>
77
+ _socket.CloseAsync(status, reason, cancellationToken);
78
+
79
+ /// <summary>Closes the socket with 1000, as <see cref="CloseAsync"/> does.</summary>
80
+ public ValueTask DisposeAsync() => _socket.DisposeAsync();
81
+
82
+ /* parsed first, so a frame that is no JSON is told from JSON that is no TIn; a null TIn is no message */
83
+ private TIn Decoded(byte[] data)
84
+ {
85
+ try
86
+ {
87
+ using var parsed = JsonDocument.Parse(data);
88
+ }
89
+ catch (JsonException e)
90
+ {
91
+ throw Failed($"WebSocket frame is not valid JSON: {e.Message}", e);
92
+ }
93
+ try
94
+ {
95
+ return JsonSerializer.Deserialize(data, _read) ?? throw Failed("WebSocket frame does not decode: it is null", null);
96
+ }
97
+ catch (JsonException e)
98
+ {
99
+ throw Failed($"WebSocket frame does not decode: {e.Message}", e);
100
+ }
101
+ }
102
+
103
+ private DecodeException Failed(string message, Exception? inner)
104
+ {
105
+ var error = new DecodeException(message, inner);
106
+ TypedWebSocket.Fire(Error, error);
107
+ return error;
108
+ }
109
+ }
@@ -48,19 +48,32 @@ const (
48
48
  var ErrConnectionClosed = errors.New("httpsdk: ResumableConnection closed")
49
49
 
50
50
  // ResumableConnection runs a chain of Transports: the last one that worked is tried first, then
51
- // the whole chain in order. Events arrive on Events() and a terminal error on Errors(); Close stops
52
- // the read goroutine and then closes both channels.
51
+ // the whole chain in order. Send writes what the server receives (Out) and Events() gives what it
52
+ // sends (In), each message also handed to the OnMessage handlers first; a typed connection sends
53
+ // every message as JSON and decodes every one it reads, and SendText sends text as is. Errors()
54
+ // gives a terminal error, and each message that did not decode while the connection reads on.
55
+ // Close stops the read goroutine and then closes both channels.
53
56
  //
54
57
  // Each delivered event advances the resume cursor (LastEventID and ReconnectToken), so a reconnect
55
58
  // resumes after the last event delivered. Reconnects back off exponentially from ReconnectDelayMs
56
59
  // (default 1s, capped at 30s, with jitter) for up to MaxReconnectAttempts (default 5; negative
57
60
  // means unlimited); exhaustion is reported on Errors().
58
- type ResumableConnection struct {
61
+ type ResumableConnection[In, Out any] struct {
62
+ /* the chain, the loop and the cursor, one copy for every message type */
63
+ r *resumable
64
+ read func([]byte) (In, error)
65
+ write func(Out) (any, error)
66
+ onMessage handlers[In]
67
+ events chan In
68
+ }
69
+
70
+ // resumable is a connection's chain, read loop and cursor; it hands each message's bytes to deliver.
71
+ type resumable struct {
59
72
  url string
60
73
  transports []Transport
74
+ deliver func([]byte) error /* nil once delivered; a *DecodeError, or the ctx's error once closed */
61
75
 
62
- events chan any
63
- errs chan error
76
+ errs chan error
64
77
  /* ctx is canceled by Close; every wait in the read loop selects on it */
65
78
  ctx context.Context
66
79
  cancel context.CancelFunc
@@ -75,9 +88,21 @@ type ResumableConnection struct {
75
88
  loopDone chan struct{}
76
89
  }
77
90
 
78
- // NewResumableConnection builds a connection over transports; opts is copied (nil means
79
- // defaults). It panics when transports is empty, a programming error.
80
- func NewResumableConnection(baseURL string, transports []Transport, opts *TransportOpts) *ResumableConnection {
91
+ // NewResumableConnection builds an untyped connection over transports: it reads each message as
92
+ // its JSON value, or its text when it is not JSON, and sends a value as TransportConn.Send does.
93
+ // opts is copied (nil means defaults). It panics when transports is empty, a programming error.
94
+ func NewResumableConnection(baseURL string, transports []Transport, opts *TransportOpts) *ResumableConnection[any, any] {
95
+ return newConnection(baseURL, transports, opts, framePayload, messageAsIs)
96
+ }
97
+
98
+ // newConnection builds a connection reading each message by read and writing each by write.
99
+ func newConnection[In, Out any](baseURL string, transports []Transport, opts *TransportOpts, read func([]byte) (In, error), write func(Out) (any, error)) *ResumableConnection[In, Out] {
100
+ c := &ResumableConnection[In, Out]{r: newResumable(baseURL, transports, opts), read: read, write: write, events: make(chan In, 16)}
101
+ c.r.deliver = c.deliver
102
+ return c
103
+ }
104
+
105
+ func newResumable(baseURL string, transports []Transport, opts *TransportOpts) *resumable {
81
106
  if len(transports) == 0 {
82
107
  panic("httpsdk: NewResumableConnection requires at least one transport")
83
108
  }
@@ -86,21 +111,34 @@ func NewResumableConnection(baseURL string, transports []Transport, opts *Transp
86
111
  o = *opts
87
112
  }
88
113
  ctx, cancel := context.WithCancel(context.Background())
89
- return &ResumableConnection{
90
- url: baseURL, transports: transports, opts: o,
91
- events: make(chan any, 16), errs: make(chan error, 4),
114
+ return &resumable{
115
+ url: baseURL, transports: transports, opts: o, errs: make(chan error, 4),
92
116
  ctx: ctx, cancel: cancel, state: StateDisconnected, provenIdx: -1,
93
117
  }
94
118
  }
95
119
 
96
120
  // newRealtime connects the call's connection over the default WebSocket, SSE and long-poll chain,
97
- // with the client's auth (its current token at each dial), headers and redirect policy; ctx bounds
98
- // the open. The headers hold no X-Request-Id unless the caller set one: each dial mints its own.
99
- func newRealtime(ctx context.Context, cfg Config, c *call, topts TransportOpts, opts []RequestOption) (*ResumableConnection, error) {
121
+ // with the client's auth (its current token at each dial), headers and redirect policy, reading
122
+ // each message by read and writing each by write; ctx bounds the open. The headers hold no
123
+ // X-Request-Id unless the caller set one: each dial mints its own.
124
+ func newRealtime[In, Out any](ctx context.Context, cfg Config, c *call, topts TransportOpts, read func([]byte) (In, error), write func(Out) (any, error), opts []RequestOption) (*ResumableConnection[In, Out], error) {
125
+ u, err := realtimeDial(cfg, c, &topts, opts)
126
+ if err != nil {
127
+ return nil, err
128
+ }
129
+ conn := newConnection(u, []Transport{&WsTransport{}, &SseTransport{}, &LongpollTransport{}}, &topts, read, write)
130
+ if err := conn.r.connect(ctx); err != nil {
131
+ return nil, err
132
+ }
133
+ return conn, nil
134
+ }
135
+
136
+ // realtimeDial is the call's URL, and topts set to dial it as the client calls.
137
+ func realtimeDial(cfg Config, c *call, topts *TransportOpts, opts []RequestOption) (string, error) {
100
138
  rc := newRequestConfig(cfg, opts)
101
139
  u, err := buildURL(rc.baseURL, c.path, c.query)
102
140
  if err != nil {
103
- return nil, err
141
+ return "", err
104
142
  }
105
143
  topts.HTTPClient = streamClient(cfg)
106
144
  if topts.KeepAlive == 0 {
@@ -118,35 +156,88 @@ func newRealtime(ctx context.Context, cfg Config, c *call, topts TransportOpts,
118
156
  return err == nil
119
157
  }
120
158
  }
121
- r := NewResumableConnection(u, []Transport{&WsTransport{}, &SseTransport{}, &LongpollTransport{}}, &topts)
122
- if err := r.Connect(ctx); err != nil {
123
- return nil, err
159
+ return u, nil
160
+ }
161
+
162
+ // deliver decodes one message, hands it to the OnMessage handlers and then to Events.
163
+ func (c *ResumableConnection[In, Out]) deliver(data []byte) error {
164
+ msg, err := c.read(data)
165
+ if err != nil {
166
+ return frameError("realtime message", err)
167
+ }
168
+ c.onMessage.call(msg)
169
+ select {
170
+ case c.events <- msg:
171
+ return nil
172
+ case <-c.r.ctx.Done():
173
+ return c.r.ctx.Err()
124
174
  }
125
- return r, nil
126
175
  }
127
176
 
128
- // Events returns the decoded payloads.
129
- func (r *ResumableConnection) Events() <-chan any { return r.events }
177
+ // Events returns the messages, decoded.
178
+ func (c *ResumableConnection[In, Out]) Events() <-chan In { return c.events }
179
+
180
+ // Errors returns the terminal transport error, and each message that did not decode as a
181
+ // *DecodeError.
182
+ func (c *ResumableConnection[In, Out]) Errors() <-chan error { return c.r.errs }
130
183
 
131
- // Errors returns the terminal transport errors.
132
- func (r *ResumableConnection) Errors() <-chan error { return r.errs }
184
+ // OnMessage registers a handler for each message, run on the read goroutine before Events gets it.
185
+ func (c *ResumableConnection[In, Out]) OnMessage(handler func(msg In)) { c.onMessage.add(handler) }
133
186
 
134
187
  // State reports the lifecycle state.
135
- func (r *ResumableConnection) State() ConnectionState {
188
+ func (c *ResumableConnection[In, Out]) State() ConnectionState { return c.r.lifecycle() }
189
+
190
+ // Cursor reports the resume cursor: the last delivered event ID and reconnect token.
191
+ func (c *ResumableConnection[In, Out]) Cursor() (lastEventID, reconnectToken string) {
192
+ return c.r.cursor()
193
+ }
194
+
195
+ // ProvenTransport reports the kind of the last transport that opened, if any.
196
+ func (c *ResumableConnection[In, Out]) ProvenTransport() (TransportKind, bool) { return c.r.proven() }
197
+
198
+ // Connect opens the chain and starts the read goroutine. ctx bounds the open only; the stream
199
+ // lives until Close. It returns once a transport opened, or the last transport error. It is a
200
+ // no-op while connected or connecting; after the read goroutine gave up, it starts over.
201
+ func (c *ResumableConnection[In, Out]) Connect(ctx context.Context) error { return c.r.connect(ctx) }
202
+
203
+ // Close stops the read goroutine, closes the active transport, then closes Events and Errors. It
204
+ // is safe to call more than once and concurrently with reads; Connect afterwards fails.
205
+ func (c *ResumableConnection[In, Out]) Close() error {
206
+ if c.r.close() {
207
+ close(c.events)
208
+ }
209
+ return nil
210
+ }
211
+
212
+ // Send writes one message on the active transport: a WebSocket frame, else a POST answered as a
213
+ // call is (a 2xx past MaxResponseBytes a *DecodeError). A typed connection sends it as JSON; an
214
+ // untyped one sends it as TransportConn.Send does.
215
+ func (c *ResumableConnection[In, Out]) Send(ctx context.Context, msg Out) error {
216
+ data, err := c.write(msg)
217
+ if err != nil {
218
+ return err
219
+ }
220
+ return c.r.send(ctx, data)
221
+ }
222
+
223
+ // SendText writes text as is: a text frame on WebSocket, else a text/plain POST.
224
+ func (c *ResumableConnection[In, Out]) SendText(ctx context.Context, text string) error {
225
+ return c.r.send(ctx, text)
226
+ }
227
+
228
+ func (r *resumable) lifecycle() ConnectionState {
136
229
  r.mu.Lock()
137
230
  defer r.mu.Unlock()
138
231
  return r.state
139
232
  }
140
233
 
141
- // Cursor reports the resume cursor: the last delivered event ID and reconnect token.
142
- func (r *ResumableConnection) Cursor() (lastEventID, reconnectToken string) {
234
+ func (r *resumable) cursor() (lastEventID, reconnectToken string) {
143
235
  r.mu.Lock()
144
236
  defer r.mu.Unlock()
145
237
  return r.opts.LastEventID, r.opts.ReconnectToken
146
238
  }
147
239
 
148
- // ProvenTransport reports the kind of the last transport that opened, if any.
149
- func (r *ResumableConnection) ProvenTransport() (TransportKind, bool) {
240
+ func (r *resumable) proven() (TransportKind, bool) {
150
241
  r.mu.Lock()
151
242
  defer r.mu.Unlock()
152
243
  if r.provenIdx < 0 || r.provenIdx >= len(r.transports) {
@@ -155,10 +246,7 @@ func (r *ResumableConnection) ProvenTransport() (TransportKind, bool) {
155
246
  return r.transports[r.provenIdx].Kind(), true
156
247
  }
157
248
 
158
- // Connect opens the chain and starts the read goroutine. ctx bounds the open only; the stream
159
- // lives until Close. It returns once a transport opened, or the last transport error. It is a
160
- // no-op while connected or connecting; after the read goroutine gave up, it starts over.
161
- func (r *ResumableConnection) Connect(ctx context.Context) error {
249
+ func (r *resumable) connect(ctx context.Context) error {
162
250
  r.mu.Lock()
163
251
  if r.closed {
164
252
  r.mu.Unlock()
@@ -189,13 +277,12 @@ func (r *ResumableConnection) Connect(ctx context.Context) error {
189
277
  return nil
190
278
  }
191
279
 
192
- // Close stops the read goroutine, closes the active transport, then closes Events and Errors. It
193
- // is safe to call more than once and concurrently with reads; Connect afterwards fails.
194
- func (r *ResumableConnection) Close() error {
280
+ // close stops the loop and closes the transport, then Errors; whether this call closed it.
281
+ func (r *resumable) close() bool {
195
282
  r.mu.Lock()
196
283
  if r.closed {
197
284
  r.mu.Unlock()
198
- return nil
285
+ return false
199
286
  }
200
287
  r.closed = true
201
288
  conn := r.conn
@@ -211,14 +298,11 @@ func (r *ResumableConnection) Close() error {
211
298
  if done != nil {
212
299
  <-done
213
300
  }
214
- close(r.events)
215
301
  close(r.errs)
216
- return nil
302
+ return true
217
303
  }
218
304
 
219
- // Send writes data on the active transport: a WebSocket frame, else a POST answered as a call is
220
- // (a 2xx past MaxResponseBytes a *DecodeError).
221
- func (r *ResumableConnection) Send(ctx context.Context, data any) error {
305
+ func (r *resumable) send(ctx context.Context, data any) error {
222
306
  r.mu.Lock()
223
307
  conn := r.conn
224
308
  r.mu.Unlock()
@@ -14,7 +14,7 @@ import (
14
14
  // resume cursor. The first that opens becomes the connection and the proven transport. Once ctx
15
15
  // ends it tries no further transport: one that opens lazily (long-poll) would otherwise succeed.
16
16
  // The chain fails with its last transient failure, else its most specific refusal; a 401 restarts it once.
17
- func (r *ResumableConnection) openChain(ctx context.Context) error {
17
+ func (r *resumable) openChain(ctx context.Context) error {
18
18
  r.mu.Lock()
19
19
  proven := r.provenIdx
20
20
  opts := r.opts
@@ -64,10 +64,10 @@ func (r *ResumableConnection) openChain(ctx context.Context) error {
64
64
  return refusal
65
65
  }
66
66
 
67
- // advance moves the resume cursor past a delivered value: the connection's own event ID when it
68
- // tracks one (SSE), else the payload's id or last_event_id, and the payload's reconnect_token.
69
- func (r *ResumableConnection) advance(conn TransportConn, v any) {
70
- id, token := payloadCursor(v)
67
+ // advance moves the resume cursor past a delivered message: the connection's own event ID when it
68
+ // tracks one (SSE), else the message's id or last_event_id, and its reconnect_token.
69
+ func (r *resumable) advance(conn TransportConn, data []byte) {
70
+ id, token := payloadCursor(data)
71
71
  if cc, ok := conn.(cursorConn); ok {
72
72
  if sid := cc.lastEventID(); sid != "" {
73
73
  id = sid
@@ -78,7 +78,7 @@ func (r *ResumableConnection) advance(conn TransportConn, v any) {
78
78
  r.mu.Unlock()
79
79
  }
80
80
 
81
- func (r *ResumableConnection) maxAttempts() int {
81
+ func (r *resumable) maxAttempts() int {
82
82
  switch {
83
83
  case r.opts.MaxReconnectAttempts < 0:
84
84
  return -1
@@ -90,7 +90,7 @@ func (r *ResumableConnection) maxAttempts() int {
90
90
 
91
91
  // backoff is the delay before reconnect attempt n (1-based): exponential from the base delay,
92
92
  // capped, with jitter so clients do not reconnect in lockstep.
93
- func (r *ResumableConnection) backoff(n int) time.Duration {
93
+ func (r *resumable) backoff(n int) time.Duration {
94
94
  d := defaultReconnectDelay
95
95
  if r.opts.ReconnectDelayMs > 0 {
96
96
  d = time.Duration(r.opts.ReconnectDelayMs) * time.Millisecond
@@ -103,17 +103,18 @@ func (r *ResumableConnection) backoff(n int) time.Duration {
103
103
  return half + time.Duration(rand.Int64N(int64(half)+1))
104
104
  }
105
105
 
106
- func (r *ResumableConnection) fail(err error) {
106
+ func (r *resumable) fail(err error) {
107
107
  select {
108
108
  case r.errs <- err:
109
109
  default:
110
110
  }
111
111
  }
112
112
 
113
- // readLoop pumps Recv into Events. A transport error reconnects through the whole chain (the
114
- // proven transport is forgotten) with backoff; exhaustion is sent on Errors and ends the loop.
115
- // Close cuts every wait short.
116
- func (r *ResumableConnection) readLoop(done chan struct{}) {
113
+ // readLoop delivers each Recv; a message that does not decode is a *DecodeError on Errors, and the
114
+ // loop reads on. A transport error
115
+ // reconnects through the whole chain (the proven transport is forgotten) with backoff; exhaustion
116
+ // is sent on Errors and ends the loop. Close cuts every wait short.
117
+ func (r *resumable) readLoop(done chan struct{}) {
117
118
  defer func() {
118
119
  r.mu.Lock()
119
120
  conn := r.conn
@@ -132,14 +133,16 @@ func (r *ResumableConnection) readLoop(done chan struct{}) {
132
133
  if conn == nil {
133
134
  return
134
135
  }
135
- v, err := conn.Recv(r.ctx)
136
+ data, err := conn.Recv(r.ctx)
136
137
  if err == nil {
137
- select {
138
- case r.events <- v:
139
- r.advance(conn, v)
138
+ switch err := r.deliver(data); {
139
+ case err == nil:
140
+ r.advance(conn, data)
140
141
  attempts = 0
141
- case <-r.ctx.Done():
142
+ case r.ctx.Err() != nil:
142
143
  return
144
+ default:
145
+ r.fail(err)
143
146
  }
144
147
  continue
145
148
  }
@@ -152,7 +155,7 @@ func (r *ResumableConnection) readLoop(done chan struct{}) {
152
155
  // reconnect drops the failed connection and reopens the chain with backoff, counting into
153
156
  // attempts; it reports false when attempts ran out or the connection closed (Close ends the
154
157
  // transport before its ctx, so a read can fail first).
155
- func (r *ResumableConnection) reconnect(failed TransportConn, err error, attempts *int) bool {
158
+ func (r *resumable) reconnect(failed TransportConn, err error, attempts *int) bool {
156
159
  if refused(err) {
157
160
  _ = failed.Close()
158
161
  r.fail(err)
@@ -23,7 +23,8 @@ type Result[T any] struct {
23
23
  func (r Result[T]) Ok() bool { return r.Err == nil }
24
24
 
25
25
  // DecodeError is a 2xx whose body did not decode, or ran past Config.MaxResponseBytes (Err is
26
- // then ErrResponseTooLarge, the Body empty).
26
+ // then ErrResponseTooLarge, the Body empty); or a server-sent event, WebSocket frame or realtime
27
+ // message that did not decode, its Response nil.
27
28
  type DecodeError struct {
28
29
  Response *http.Response
29
30
  Err error
@@ -5,6 +5,7 @@ package sdk
5
5
  import (
6
6
  "bufio"
7
7
  "context"
8
+ "encoding/json"
8
9
  "errors"
9
10
  "io"
10
11
  "iter"
@@ -24,6 +25,16 @@ type SSEEvent[T any] struct {
24
25
  Retry int
25
26
  }
26
27
 
28
+ // Untyped is the event with Data as text: as sent for SSEEvent[string], else its JSON.
29
+ func (e SSEEvent[T]) Untyped() SSEEvent[string] {
30
+ data, ok := any(e.Data).(string)
31
+ if !ok {
32
+ text, _ := json.Marshal(e.Data)
33
+ data = string(text)
34
+ }
35
+ return SSEEvent[string]{Data: data, Event: e.Event, ID: e.ID, Retry: e.Retry}
36
+ }
37
+
27
38
  // sseMaxLine caps one line, and sseMaxEvent the data of one event.
28
39
  const (
29
40
  sseMaxLine = 1 << 20
@@ -9,6 +9,7 @@ import (
9
9
  "io"
10
10
  "iter"
11
11
  "net/http"
12
+ "strconv"
12
13
  "time"
13
14
  )
14
15
 
@@ -75,19 +76,19 @@ func streamText(ctx context.Context, cfg Config, c *call, opts []RequestOption)
75
76
  }
76
77
  }
77
78
 
78
- // streamJSON yields the call's server-sent events with Data decoded from JSON into T. An event
79
- // that does not decode yields an error and ends the stream.
80
- func streamJSON[T any](ctx context.Context, cfg Config, c *call, opts []RequestOption) iter.Seq2[SSEEvent[T], error] {
79
+ // streamEvents yields the call's server-sent events, each read by decode. An event that does not
80
+ // decode yields its error and ends the stream.
81
+ func streamEvents[E any](ctx context.Context, cfg Config, c *call, decode func(SSEEvent[string]) (E, error), opts []RequestOption) iter.Seq2[E, error] {
81
82
  text := streamText(ctx, cfg, c, opts)
82
- return func(yield func(SSEEvent[T], error) bool) {
83
+ return func(yield func(E, error) bool) {
84
+ var zero E
83
85
  for raw, err := range text {
84
- if err != nil {
85
- yield(SSEEvent[T]{}, err)
86
- return
86
+ var ev E
87
+ if err == nil {
88
+ ev, err = decode(raw)
87
89
  }
88
- ev := SSEEvent[T]{Event: raw.Event, ID: raw.ID, Retry: raw.Retry}
89
- if err := json.Unmarshal([]byte(raw.Data), &ev.Data); err != nil {
90
- yield(SSEEvent[T]{}, fmt.Errorf("httpsdk: decode sse event: %w", err))
90
+ if err != nil {
91
+ yield(zero, err)
91
92
  return
92
93
  }
93
94
  if !yield(ev, nil) {
@@ -97,9 +98,24 @@ func streamJSON[T any](ctx context.Context, cfg Config, c *call, opts []RequestO
97
98
  }
98
99
  }
99
100
 
101
+ // sseData is raw with its Data decoded from JSON into T; data that does not decode is a
102
+ // *DecodeError naming the event.
103
+ func sseData[T any](raw SSEEvent[string]) (SSEEvent[T], error) {
104
+ ev := SSEEvent[T]{Event: raw.Event, ID: raw.ID, Retry: raw.Retry}
105
+ if err := json.Unmarshal([]byte(raw.Data), &ev.Data); err != nil {
106
+ what := "sse event"
107
+ if raw.Event != "" {
108
+ what += " " + strconv.Quote(raw.Event)
109
+ }
110
+ return SSEEvent[T]{}, &DecodeError{Err: fmt.Errorf("%s: %w", what, err)}
111
+ }
112
+ return ev, nil
113
+ }
114
+
100
115
  // sseFail is a stream that yields err and ends, for a call that fails before it opens.
101
- func sseFail[T any](err error) iter.Seq2[SSEEvent[T], error] {
102
- return func(yield func(SSEEvent[T], error) bool) {
103
- yield(SSEEvent[T]{}, err)
116
+ func sseFail[E any](err error) iter.Seq2[E, error] {
117
+ return func(yield func(E, error) bool) {
118
+ var zero E
119
+ yield(zero, err)
104
120
  }
105
121
  }
@@ -101,10 +101,11 @@ func (o *TransportOpts) maxMessageBytes() int64 {
101
101
  return o.MaxMessageBytes
102
102
  }
103
103
 
104
- // TransportConn is one live transport connection. Recv returns the decoded JSON payload, or the
105
- // raw text when it is not JSON.
104
+ // TransportConn is one live transport connection. Recv returns one message's bytes, as sent; the
105
+ // connection decodes them. Send writes a []byte, a string or a json.RawMessage as is (a []byte a
106
+ // binary frame on WebSocket) and any other value as JSON.
106
107
  type TransportConn interface {
107
- Recv(ctx context.Context) (any, error)
108
+ Recv(ctx context.Context) ([]byte, error)
108
109
  Send(ctx context.Context, data any) error
109
110
  Close() error
110
111
  Kind() TransportKind
@@ -123,16 +124,18 @@ type cursorConn interface {
123
124
  lastEventID() string
124
125
  }
125
126
 
126
- // payloadCursor reads a resume cursor from a delivered payload: its reconnect_token, and its
127
- // last_event_id or id (a string or a number).
128
- func payloadCursor(v any) (id, token string) {
129
- m, ok := v.(map[string]any)
130
- if !ok {
127
+ // payloadCursor reads a resume cursor from a delivered message's bytes, a JSON object: its
128
+ // reconnect_token, and its last_event_id or id (a string or a number).
129
+ func payloadCursor(data []byte) (id, token string) {
130
+ var fields map[string]json.RawMessage
131
+ if json.Unmarshal(data, &fields) != nil {
131
132
  return "", ""
132
133
  }
133
- token, _ = m["reconnect_token"].(string)
134
+ _ = json.Unmarshal(fields["reconnect_token"], &token) // absent or no string: no token
134
135
  for _, key := range []string{"id", "last_event_id"} {
135
- switch x := m[key].(type) {
136
+ var v any
137
+ _ = json.Unmarshal(fields[key], &v) // absent: nil, no id
138
+ switch x := v.(type) {
136
139
  case string:
137
140
  id = x
138
141
  case float64:
@@ -164,15 +167,6 @@ func withQuery(u string, opts *TransportOpts, lastIDParam bool) string {
164
167
  return u + sep + q.Encode()
165
168
  }
166
169
 
167
- // decodePayload is the JSON value of data, or its text when it is not JSON.
168
- func decodePayload(data []byte) any {
169
- var v any
170
- if json.Unmarshal(data, &v) != nil {
171
- return string(data)
172
- }
173
- return v
174
- }
175
-
176
170
  // WsTransport is the default WebSocket adapter.
177
171
  type WsTransport struct {
178
172
  Subprotocols []string
@@ -217,13 +211,13 @@ type wsConn struct {
217
211
 
218
212
  func (c *wsConn) Kind() TransportKind { return TransportWs }
219
213
 
220
- func (c *wsConn) Recv(ctx context.Context) (any, error) {
214
+ func (c *wsConn) Recv(ctx context.Context) ([]byte, error) {
221
215
  _, data, err := c.conn.Read(ctx)
222
216
  if err != nil {
223
217
  c.stop()
224
218
  return nil, err
225
219
  }
226
- return decodePayload(data), nil
220
+ return data, nil
227
221
  }
228
222
 
229
223
  func (c *wsConn) Send(ctx context.Context, data any) error { return writeFrame(ctx, c.conn, data) }
@@ -57,7 +57,7 @@ type longpollConn struct {
57
57
 
58
58
  func (c *longpollConn) Kind() TransportKind { return TransportLongpoll }
59
59
 
60
- func (c *longpollConn) Recv(ctx context.Context) (any, error) {
60
+ func (c *longpollConn) Recv(ctx context.Context) ([]byte, error) {
61
61
  c.mu.Lock()
62
62
  if c.closed {
63
63
  c.mu.Unlock()
@@ -90,13 +90,12 @@ func (c *longpollConn) Recv(ctx context.Context) (any, error) {
90
90
  if err := raiseForStatus(resp, body); err != nil {
91
91
  return nil, err
92
92
  }
93
- v := decodePayload(body)
94
- if id, token := payloadCursor(v); id != "" || token != "" {
93
+ if id, token := payloadCursor(body); id != "" || token != "" {
95
94
  c.mu.Lock()
96
95
  advanceCursor(&c.cursor, id, token)
97
96
  c.mu.Unlock()
98
97
  }
99
- return v, nil
98
+ return body, nil
100
99
  }
101
100
 
102
101
  // advanceCursor moves a resume cursor to the non-empty id and token.