@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.
- package/README.md +30 -7
- package/dist/emit/cli/commands.js +25 -5
- package/dist/emit/cli/flags.js +7 -3
- package/dist/emit/cli/skills.js +5 -1
- package/dist/emit/csharp/realtime.d.ts +1 -8
- package/dist/emit/csharp/realtime.js +25 -25
- package/dist/emit/csharp/sdk-answer.d.ts +10 -2
- package/dist/emit/csharp/sdk-method.js +9 -2
- package/dist/emit/csharp/sse.d.ts +0 -11
- package/dist/emit/csharp/sse.js +91 -10
- package/dist/emit/csharp/transport.js +3 -3
- package/dist/emit/csharp/types-messages.d.ts +47 -0
- package/dist/emit/csharp/types-messages.js +172 -0
- package/dist/emit/csharp/types-names.js +3 -2
- package/dist/emit/csharp/ws.d.ts +0 -15
- package/dist/emit/csharp/ws.js +26 -5
- package/dist/emit/go/sdk-answer.d.ts +24 -1
- package/dist/emit/go/sdk-method.d.ts +3 -0
- package/dist/emit/go/sdk-method.js +16 -10
- package/dist/emit/go/sse.d.ts +2 -10
- package/dist/emit/go/sse.js +87 -12
- package/dist/emit/go/types-union.d.ts +3 -2
- package/dist/emit/go/types-union.js +2 -0
- package/dist/emit/go/types.d.ts +6 -0
- package/dist/emit/go/types.js +12 -1
- package/dist/emit/go/ws.d.ts +4 -11
- package/dist/emit/go/ws.js +214 -58
- package/dist/emit/java/json.d.ts +3 -0
- package/dist/emit/java/layout-ast.d.ts +4 -1
- package/dist/emit/java/layout-types.js +1 -1
- package/dist/emit/java/models-names.d.ts +2 -0
- package/dist/emit/java/models-names.js +1 -0
- package/dist/emit/java/models-union.d.ts +12 -1
- package/dist/emit/java/models-union.js +11 -5
- package/dist/emit/java/models.d.ts +5 -0
- package/dist/emit/java/models.js +22 -7
- package/dist/emit/java/realtime.d.ts +29 -9
- package/dist/emit/java/realtime.js +45 -10
- package/dist/emit/java/sdk-mirror.js +6 -5
- package/dist/emit/java/sdk-op.js +1 -1
- package/dist/emit/java/sse.d.ts +11 -10
- package/dist/emit/java/sse.js +104 -5
- package/dist/emit/java/ws.d.ts +46 -7
- package/dist/emit/java/ws.js +89 -4
- package/dist/emit/mcp/output-schema.d.ts +4 -2
- package/dist/emit/mcp/output-schema.js +56 -12
- package/dist/emit/python/realtime.d.ts +9 -6
- package/dist/emit/python/realtime.js +21 -19
- package/dist/emit/python/sdk-answer.d.ts +5 -1
- package/dist/emit/python/sdk-method.d.ts +1 -1
- package/dist/emit/python/sdk-method.js +33 -6
- package/dist/emit/python/sdk.js +22 -2
- package/dist/emit/python/sse.d.ts +0 -5
- package/dist/emit/python/sse.js +35 -5
- package/dist/emit/python/types.d.ts +7 -0
- package/dist/emit/python/types.js +20 -3
- package/dist/emit/python/ws.d.ts +20 -6
- package/dist/emit/python/ws.js +67 -1
- package/dist/emit/rust/realtime.d.ts +7 -5
- package/dist/emit/rust/realtime.js +14 -17
- package/dist/emit/rust/sdk-method.js +1 -1
- package/dist/emit/rust/sse.d.ts +11 -7
- package/dist/emit/rust/sse.js +52 -6
- package/dist/emit/rust/types-union.d.ts +9 -1
- package/dist/emit/rust/types-union.js +4 -0
- package/dist/emit/rust/types.d.ts +9 -0
- package/dist/emit/rust/types.js +13 -7
- package/dist/emit/rust/ws.d.ts +22 -4
- package/dist/emit/rust/ws.js +57 -7
- package/dist/emit/ts/route-tree.d.ts +1 -1
- package/dist/emit/ts/route-tree.js +0 -11
- package/dist/emit/ts/sdk-types-preamble.js +4 -0
- package/dist/emit/ts/sdk-types.js +49 -10
- package/dist/emit/ts/sdk.js +2 -2
- package/dist/emit/ts/service-map.d.ts +8 -2
- package/dist/emit/ts/service-map.js +30 -2
- package/dist/emit/ts/type-gen.d.ts +4 -3
- package/dist/emit/ts/type-gen.js +83 -40
- package/dist/extract/chain.d.ts +10 -6
- package/dist/extract/chain.js +5 -19
- package/dist/extract/extract.d.ts +2 -2
- package/dist/extract/extract.js +37 -23
- package/dist/extract/walk.d.ts +15 -4
- package/dist/extract/walk.js +159 -15
- package/dist/ir/build.js +4 -0
- package/dist/ir/model.d.ts +16 -0
- package/dist/ir/sdk-model.d.ts +25 -1
- package/dist/ir/sdk-model.js +35 -5
- package/dist/ir/slots.d.ts +1 -1
- package/dist/ir/slots.js +11 -3
- package/dist/ir/streams.d.ts +16 -0
- package/dist/ir/streams.js +40 -0
- package/dist/runtime/cli/socket.go +107 -13
- package/dist/runtime/cli/stream.go +18 -11
- package/dist/runtime/csharp/Adapters.cs +12 -11
- package/dist/runtime/csharp/Events.cs +22 -17
- package/dist/runtime/csharp/Realtime.cs +50 -23
- package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
- package/dist/runtime/csharp/TransportSse.cs +3 -3
- package/dist/runtime/csharp/Ws.cs +1 -1
- package/dist/runtime/csharp/WsDial.cs +19 -1
- package/dist/runtime/csharp/WsTyped.cs +109 -0
- package/dist/runtime/go/realtime.go +125 -41
- package/dist/runtime/go/realtime_loop.go +21 -18
- package/dist/runtime/go/result.go +2 -1
- package/dist/runtime/go/sse.go +11 -0
- package/dist/runtime/go/stream.go +29 -13
- package/dist/runtime/go/transport.go +15 -21
- package/dist/runtime/go/transport_longpoll.go +3 -4
- package/dist/runtime/go/transport_sse.go +6 -6
- package/dist/runtime/go/ws.go +157 -61
- package/dist/runtime/java/EventStream.java +47 -29
- package/dist/runtime/java/Exchange.java +5 -5
- package/dist/runtime/java/Flight.java +3 -3
- package/dist/runtime/java/Realtime.java +45 -11
- package/dist/runtime/java/ResumableConnection.java +77 -32
- package/dist/runtime/java/Socket.java +8 -4
- package/dist/runtime/java/SseAdapter.java +1 -1
- package/dist/runtime/java/TypedWebSocket.java +81 -24
- package/dist/runtime/java/WsAdapter.java +4 -2
- package/dist/runtime/java/WsDial.java +12 -5
- package/dist/runtime/python/events.py +25 -11
- package/dist/runtime/python/operation.py +6 -1
- package/dist/runtime/python/realtime.py +47 -33
- package/dist/runtime/python/send_async.py +1 -0
- package/dist/runtime/python/transport_sse.py +2 -2
- package/dist/runtime/python/transport_ws.py +1 -1
- package/dist/runtime/python/ws.py +100 -39
- package/dist/runtime/rust/events.rs +64 -41
- package/dist/runtime/rust/realtime.rs +80 -34
- package/dist/runtime/rust/realtime_loop.rs +37 -12
- package/dist/runtime/rust/sse.rs +3 -2
- package/dist/runtime/rust/transport_sse.rs +1 -1
- package/dist/runtime/rust/transport_ws.rs +3 -2
- package/dist/runtime/rust/ws.rs +122 -50
- package/dist/runtime/ts/realtime-connection.ts +22 -0
- package/dist/runtime/ts/realtime-transports.ts +13 -4
- package/dist/runtime/ts/realtime.ts +27 -3
- package/dist/runtime/ts/sdk-realtime.ts +1 -1
- package/dist/runtime/ts/sdk-sse.ts +31 -14
- package/dist/runtime/ts/sdk-ws.ts +2 -1
- package/dist/runtime/ts/sdk.ts +9 -2
- package/dist/runtime/ts/sse.ts +8 -0
- package/dist/runtime/ts/ws.ts +88 -50
- package/package.json +3 -61
|
@@ -95,9 +95,9 @@ func checkEventStream(resp *http.Response) error {
|
|
|
95
95
|
}
|
|
96
96
|
|
|
97
97
|
type sseResult struct {
|
|
98
|
-
|
|
99
|
-
id
|
|
100
|
-
err
|
|
98
|
+
data []byte
|
|
99
|
+
id string
|
|
100
|
+
err error
|
|
101
101
|
}
|
|
102
102
|
|
|
103
103
|
type sseConn struct {
|
|
@@ -119,7 +119,7 @@ func (c *sseConn) run(ctx context.Context) {
|
|
|
119
119
|
for ev, err := range parseSSEStream(ctx, c.resp) {
|
|
120
120
|
r := sseResult{err: err}
|
|
121
121
|
if err == nil {
|
|
122
|
-
r.
|
|
122
|
+
r.data, r.id = []byte(ev.Data), ev.ID
|
|
123
123
|
}
|
|
124
124
|
select {
|
|
125
125
|
case c.next <- r:
|
|
@@ -141,7 +141,7 @@ func (c *sseConn) finish() {
|
|
|
141
141
|
}
|
|
142
142
|
}
|
|
143
143
|
|
|
144
|
-
func (c *sseConn) Recv(ctx context.Context) (
|
|
144
|
+
func (c *sseConn) Recv(ctx context.Context) ([]byte, error) {
|
|
145
145
|
select {
|
|
146
146
|
case r, ok := <-c.next:
|
|
147
147
|
if !ok {
|
|
@@ -152,7 +152,7 @@ func (c *sseConn) Recv(ctx context.Context) (any, error) {
|
|
|
152
152
|
c.lastID = r.id
|
|
153
153
|
c.mu.Unlock()
|
|
154
154
|
}
|
|
155
|
-
return r.
|
|
155
|
+
return r.data, r.err
|
|
156
156
|
case <-ctx.Done():
|
|
157
157
|
return nil, ctx.Err()
|
|
158
158
|
}
|
package/dist/runtime/go/ws.go
CHANGED
|
@@ -6,6 +6,7 @@ import (
|
|
|
6
6
|
"context"
|
|
7
7
|
"encoding/json"
|
|
8
8
|
"errors"
|
|
9
|
+
"fmt"
|
|
9
10
|
"io"
|
|
10
11
|
"net"
|
|
11
12
|
"strings"
|
|
@@ -62,20 +63,35 @@ func keepAlive(conn *websocket.Conn, every time.Duration) func() {
|
|
|
62
63
|
return stop
|
|
63
64
|
}
|
|
64
65
|
|
|
65
|
-
// TypedWebSocket is an operation's WebSocket: Send
|
|
66
|
-
//
|
|
67
|
-
//
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
66
|
+
// TypedWebSocket is an operation's WebSocket: Send writes what the server receives (Out), Read
|
|
67
|
+
// returns what it sends (In), and OnMessage, OnClose and OnError handlers run beside Read. A typed
|
|
68
|
+
// socket sends every message as JSON and parses every frame; SendText writes a text frame as is.
|
|
69
|
+
// Its dial runs no OnRequest or OnResponse hook, and a refused handshake's 401 is its error, with
|
|
70
|
+
// no OnAuthExpired refresh.
|
|
71
|
+
type TypedWebSocket[In, Out any] struct {
|
|
72
|
+
conn *websocket.Conn
|
|
73
|
+
stop func()
|
|
74
|
+
read func([]byte) (In, error)
|
|
75
|
+
write func(Out) (any, error)
|
|
76
|
+
onMessage handlers[In]
|
|
77
|
+
onClose handlers[string]
|
|
78
|
+
onError handlers[error]
|
|
79
|
+
closed sync.Once
|
|
74
80
|
}
|
|
75
81
|
|
|
76
|
-
// dialWebSocket opens the call's WebSocket with the client's auth, headers and redirect policy
|
|
77
|
-
//
|
|
78
|
-
|
|
82
|
+
// dialWebSocket opens the call's WebSocket with the client's auth, headers and redirect policy,
|
|
83
|
+
// reading each frame by read and writing each message by write. A refused handshake with an
|
|
84
|
+
// error status is a typed error, as for any other call.
|
|
85
|
+
func dialWebSocket[In, Out any](ctx context.Context, cfg Config, c *call, read func([]byte) (In, error), write func(Out) (any, error), opts []RequestOption) (*TypedWebSocket[In, Out], error) {
|
|
86
|
+
conn, err := dialSocket(ctx, cfg, c, opts)
|
|
87
|
+
if err != nil {
|
|
88
|
+
return nil, err
|
|
89
|
+
}
|
|
90
|
+
return &TypedWebSocket[In, Out]{conn: conn, stop: keepAlive(conn, cfg.WSKeepalive), read: read, write: write}, nil
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// dialSocket opens the call's WebSocket as the client calls; an error status is its *APIError.
|
|
94
|
+
func dialSocket(ctx context.Context, cfg Config, c *call, opts []RequestOption) (*websocket.Conn, error) {
|
|
79
95
|
rc := newRequestConfig(cfg, opts)
|
|
80
96
|
u, err := buildURL(rc.baseURL, c.path, c.query)
|
|
81
97
|
if err != nil {
|
|
@@ -98,41 +114,33 @@ func dialWebSocket(ctx context.Context, cfg Config, c *call, opts []RequestOptio
|
|
|
98
114
|
return nil, wrapTransportError(ctx, err)
|
|
99
115
|
}
|
|
100
116
|
rc.deliver(resp, nil)
|
|
101
|
-
return newTypedWebSocket(conn, cfg.WSKeepalive), nil
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
func newTypedWebSocket(conn *websocket.Conn, every time.Duration) *TypedWebSocket {
|
|
105
117
|
conn.SetReadLimit(defaultWSReadLimit)
|
|
106
|
-
return
|
|
118
|
+
return conn, nil
|
|
107
119
|
}
|
|
108
120
|
|
|
109
121
|
// SetReadLimit sets the largest inbound message, in bytes (default 16 MiB).
|
|
110
|
-
func (w *TypedWebSocket) SetReadLimit(n int64) {
|
|
122
|
+
func (w *TypedWebSocket[In, Out]) SetReadLimit(n int64) {
|
|
111
123
|
w.conn.SetReadLimit(n)
|
|
112
124
|
}
|
|
113
125
|
|
|
114
|
-
// Send writes
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
func writeFrame(ctx context.Context, conn *websocket.Conn, data any) error {
|
|
120
|
-
switch v := data.(type) {
|
|
121
|
-
case []byte:
|
|
122
|
-
return conn.Write(ctx, websocket.MessageBinary, v)
|
|
123
|
-
case string:
|
|
124
|
-
return conn.Write(ctx, websocket.MessageText, []byte(v))
|
|
125
|
-
}
|
|
126
|
-
encoded, err := json.Marshal(data)
|
|
126
|
+
// Send writes one message: as JSON text on a typed socket; on an untyped one a []byte as a binary
|
|
127
|
+
// frame, a string as a text frame, and anything else as JSON text.
|
|
128
|
+
func (w *TypedWebSocket[In, Out]) Send(ctx context.Context, msg Out) error {
|
|
129
|
+
data, err := w.write(msg)
|
|
127
130
|
if err != nil {
|
|
128
131
|
return err
|
|
129
132
|
}
|
|
130
|
-
return
|
|
133
|
+
return writeFrame(ctx, w.conn, data)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// SendText writes text as one text frame, as is.
|
|
137
|
+
func (w *TypedWebSocket[In, Out]) SendText(ctx context.Context, text string) error {
|
|
138
|
+
return w.conn.Write(ctx, websocket.MessageText, []byte(text))
|
|
131
139
|
}
|
|
132
140
|
|
|
133
141
|
// Close sends a close frame with code and reason, the reason cut at a rune boundary to fit 123
|
|
134
142
|
// bytes. On a conn already closed it returns nil.
|
|
135
|
-
func (w *TypedWebSocket) Close(code websocket.StatusCode, reason string) error {
|
|
143
|
+
func (w *TypedWebSocket[In, Out]) Close(code websocket.StatusCode, reason string) error {
|
|
136
144
|
for len(reason) > maxCloseReason {
|
|
137
145
|
_, size := utf8.DecodeLastRuneInString(reason)
|
|
138
146
|
reason = reason[:len(reason)-size]
|
|
@@ -146,51 +154,139 @@ func (w *TypedWebSocket) Close(code websocket.StatusCode, reason string) error {
|
|
|
146
154
|
return err
|
|
147
155
|
}
|
|
148
156
|
|
|
149
|
-
// Read returns the next message
|
|
150
|
-
//
|
|
151
|
-
|
|
152
|
-
|
|
157
|
+
// Read returns the next message and hands it to the OnMessage handlers. A frame that does not
|
|
158
|
+
// parse is a *DecodeError, handed to OnError, and the socket stays open. A close frame fires
|
|
159
|
+
// OnClose with its reason (the code is in the error: websocket.CloseStatus(err)); any other
|
|
160
|
+
// failure fires OnError.
|
|
161
|
+
func (w *TypedWebSocket[In, Out]) Read(ctx context.Context) (In, error) {
|
|
162
|
+
var zero In
|
|
163
|
+
_, frame, err := w.conn.Read(ctx)
|
|
153
164
|
if err != nil {
|
|
154
165
|
w.stop()
|
|
155
166
|
var ce websocket.CloseError
|
|
156
167
|
if errors.As(err, &ce) {
|
|
157
168
|
w.fireClose(ce.Reason)
|
|
158
169
|
} else {
|
|
159
|
-
w.
|
|
170
|
+
w.onError.call(err)
|
|
160
171
|
}
|
|
161
|
-
return
|
|
172
|
+
return zero, err
|
|
162
173
|
}
|
|
163
|
-
w.
|
|
174
|
+
msg, err := w.read(frame)
|
|
175
|
+
if err != nil {
|
|
176
|
+
err = frameError("WebSocket frame", err)
|
|
177
|
+
w.onError.call(err)
|
|
178
|
+
return zero, err
|
|
179
|
+
}
|
|
180
|
+
w.onMessage.call(msg)
|
|
164
181
|
return msg, nil
|
|
165
182
|
}
|
|
166
183
|
|
|
167
|
-
//
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
184
|
+
// OnMessage registers a handler for each message Read returns.
|
|
185
|
+
func (w *TypedWebSocket[In, Out]) OnMessage(handler func(msg In)) { w.onMessage.add(handler) }
|
|
186
|
+
|
|
187
|
+
// OnClose registers a handler for the close, with its reason; it runs once.
|
|
188
|
+
func (w *TypedWebSocket[In, Out]) OnClose(handler func(reason string)) { w.onClose.add(handler) }
|
|
189
|
+
|
|
190
|
+
// OnError registers a handler for a frame that does not parse and for a read that fails.
|
|
191
|
+
func (w *TypedWebSocket[In, Out]) OnError(handler func(err error)) { w.onError.add(handler) }
|
|
192
|
+
|
|
193
|
+
func (w *TypedWebSocket[In, Out]) fireClose(reason string) {
|
|
194
|
+
w.closed.Do(func() { w.onClose.call(reason) })
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// handlers is a list of callbacks, registered and called from any goroutine.
|
|
198
|
+
type handlers[T any] struct {
|
|
199
|
+
mu sync.Mutex
|
|
200
|
+
list []func(T)
|
|
174
201
|
}
|
|
175
202
|
|
|
176
|
-
func (
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
203
|
+
func (h *handlers[T]) add(handler func(T)) {
|
|
204
|
+
h.mu.Lock()
|
|
205
|
+
defer h.mu.Unlock()
|
|
206
|
+
h.list = append(h.list, handler)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// call runs each handler registered when it starts with v.
|
|
210
|
+
func (h *handlers[T]) call(v T) {
|
|
211
|
+
h.mu.Lock()
|
|
212
|
+
calls := append([]func(T){}, h.list...)
|
|
213
|
+
h.mu.Unlock()
|
|
214
|
+
for _, handler := range calls {
|
|
215
|
+
handler(v)
|
|
181
216
|
}
|
|
182
|
-
w.closed = true
|
|
183
|
-
w.mu.Unlock()
|
|
184
|
-
w.fanout("close", []byte(reason))
|
|
185
217
|
}
|
|
186
218
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
219
|
+
// frameBytes reads a frame as sent: an untyped socket's messages.
|
|
220
|
+
func frameBytes(data []byte) ([]byte, error) { return data, nil }
|
|
221
|
+
|
|
222
|
+
// framePayload reads a frame as its JSON value, or its text when it is not JSON: an untyped
|
|
223
|
+
// connection's messages.
|
|
224
|
+
func framePayload(data []byte) (any, error) {
|
|
225
|
+
var v any
|
|
226
|
+
if json.Unmarshal(data, &v) != nil {
|
|
227
|
+
return string(data), nil
|
|
193
228
|
}
|
|
229
|
+
return v, nil
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// frameJSON reads a frame as JSON decoded into T.
|
|
233
|
+
func frameJSON[T any](data []byte) (T, error) {
|
|
234
|
+
var msg T
|
|
235
|
+
err := json.Unmarshal(data, &msg)
|
|
236
|
+
return msg, err
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// frameKey is the string a JSON frame holds at key, "" when it is not an object holding a string
|
|
240
|
+
// there; a frame that is no JSON is its syntax error.
|
|
241
|
+
func frameKey(data []byte, key string) (string, error) {
|
|
242
|
+
var fields map[string]json.RawMessage
|
|
243
|
+
if err := json.Unmarshal(data, &fields); err != nil {
|
|
244
|
+
var syntax *json.SyntaxError
|
|
245
|
+
if errors.As(err, &syntax) {
|
|
246
|
+
return "", err
|
|
247
|
+
}
|
|
248
|
+
return "", nil
|
|
249
|
+
}
|
|
250
|
+
var value string
|
|
251
|
+
_ = json.Unmarshal(fields[key], &value) // no string there: no member's value
|
|
252
|
+
return value, nil
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// frameError is a frame, named what, that did not decode: a *DecodeError with no response.
|
|
256
|
+
func frameError(what string, err error) error {
|
|
257
|
+
var syntax *json.SyntaxError
|
|
258
|
+
if errors.As(err, &syntax) {
|
|
259
|
+
return &DecodeError{Err: fmt.Errorf("%s is not valid JSON: %w", what, err)}
|
|
260
|
+
}
|
|
261
|
+
return &DecodeError{Err: fmt.Errorf("%s does not decode: %w", what, err)}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// messageAsIs writes an untyped message as given: a []byte as a binary frame, a string as text,
|
|
265
|
+
// anything else as JSON.
|
|
266
|
+
func messageAsIs(msg any) (any, error) { return msg, nil }
|
|
267
|
+
|
|
268
|
+
// messageJSON writes a typed message as JSON, whatever its Go type.
|
|
269
|
+
func messageJSON[T any](msg T) (any, error) {
|
|
270
|
+
data, err := json.Marshal(msg)
|
|
271
|
+
return json.RawMessage(data), err
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// writeFrame writes data as one frame: a []byte binary, a string or json.RawMessage text as is,
|
|
275
|
+
// anything else as JSON text.
|
|
276
|
+
func writeFrame(ctx context.Context, conn *websocket.Conn, data any) error {
|
|
277
|
+
switch v := data.(type) {
|
|
278
|
+
case []byte:
|
|
279
|
+
return conn.Write(ctx, websocket.MessageBinary, v)
|
|
280
|
+
case string:
|
|
281
|
+
return conn.Write(ctx, websocket.MessageText, []byte(v))
|
|
282
|
+
case json.RawMessage:
|
|
283
|
+
return conn.Write(ctx, websocket.MessageText, v)
|
|
284
|
+
}
|
|
285
|
+
encoded, err := json.Marshal(data)
|
|
286
|
+
if err != nil {
|
|
287
|
+
return err
|
|
288
|
+
}
|
|
289
|
+
return conn.Write(ctx, websocket.MessageText, encoded)
|
|
194
290
|
}
|
|
195
291
|
|
|
196
292
|
// toWsURL swaps an http(s) scheme for ws(s); a URL inside the query is untouched.
|
|
@@ -8,40 +8,66 @@ import java.time.Duration;
|
|
|
8
8
|
import java.util.Iterator;
|
|
9
9
|
import java.util.NoSuchElementException;
|
|
10
10
|
import java.util.concurrent.CancellationException;
|
|
11
|
+
import java.util.function.Function;
|
|
11
12
|
import tools.jackson.core.JacksonException;
|
|
12
13
|
import tools.jackson.core.type.TypeReference;
|
|
13
14
|
|
|
14
15
|
/**
|
|
15
|
-
* An open event stream, read once as an {@code Iterable} of
|
|
16
|
-
*
|
|
16
|
+
* An open event stream, read once as an {@code Iterable} of its events, each decoded whole into
|
|
17
|
+
* {@code E}: an {@link SseEvent}, or a named-event operation's own sealed interface. An event that
|
|
18
|
+
* does not decode is thrown once and ends it, the cursor already past it. Its connection is let go
|
|
19
|
+
* by its end: the server's end, an error (thrown once, then the end), {@link #close()} from any
|
|
17
20
|
* thread (a pending read then ends quietly), or an interrupt of the reading thread (a {@link
|
|
18
21
|
* CancellationException}). Open it in try-with-resources: a for-each break without one keeps the
|
|
19
22
|
* connection. No timeout bounds it once open.
|
|
20
23
|
*/
|
|
21
|
-
public final class EventStream<
|
|
24
|
+
public final class EventStream<E> implements Iterable<E>, AutoCloseable {
|
|
22
25
|
private final InputStream body;
|
|
23
26
|
private final Sse parser;
|
|
24
|
-
private final
|
|
27
|
+
private final Function<SseEvent<String>, E> decode;
|
|
25
28
|
private boolean taken;
|
|
26
29
|
private volatile boolean closed;
|
|
27
30
|
private boolean ended;
|
|
28
|
-
private
|
|
31
|
+
private E pending;
|
|
32
|
+
private String pendingId;
|
|
29
33
|
private String lastEventId = "";
|
|
30
34
|
|
|
31
|
-
EventStream(InputStream body,
|
|
35
|
+
EventStream(InputStream body, Function<SseEvent<String>, E> decode) {
|
|
32
36
|
this.body = body;
|
|
33
37
|
this.parser = new Sse(body);
|
|
34
|
-
this.
|
|
38
|
+
this.decode = decode;
|
|
35
39
|
}
|
|
36
40
|
|
|
37
|
-
/**
|
|
41
|
+
/**
|
|
42
|
+
* Each event's data decoded into {@code T}, its name, id and retry as parsed: a one-schema
|
|
43
|
+
* stream's decode.
|
|
44
|
+
*/
|
|
45
|
+
static <T> Function<SseEvent<String>, SseEvent<T>> typed(TypeReference<T> type) {
|
|
46
|
+
return e -> new SseEvent<>(data(e.data(), type), e.event(), e.id(), e.retry());
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** An event's data decoded into {@code T}; data that does not decode is a DecodeException. */
|
|
50
|
+
static <T> T data(String data, TypeReference<T> type) {
|
|
51
|
+
try {
|
|
52
|
+
return Json.MAPPER.readValue(data, type);
|
|
53
|
+
} catch (JacksonException e) {
|
|
54
|
+
throw new DecodeException("an event's data does not decode: " + e.getOriginalMessage(), e);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** An event's name: {@code message}, the SSE default, when it came unnamed. */
|
|
59
|
+
static String nameOf(SseEvent<String> e) {
|
|
60
|
+
return e.event() == null || e.event().isEmpty() ? "message" : e.event();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The id of the last event read, taken before it decodes; empty before any. */
|
|
38
64
|
public String lastEventId() {
|
|
39
65
|
return lastEventId;
|
|
40
66
|
}
|
|
41
67
|
|
|
42
68
|
/** The stream's one iterator; a second call throws IllegalStateException. */
|
|
43
69
|
@Override
|
|
44
|
-
public synchronized Iterator<
|
|
70
|
+
public synchronized Iterator<E> iterator() {
|
|
45
71
|
if (taken) {
|
|
46
72
|
throw new IllegalStateException("an EventStream is read once");
|
|
47
73
|
}
|
|
@@ -53,13 +79,13 @@ public final class EventStream<T> implements Iterable<SseEvent<T>>, AutoCloseabl
|
|
|
53
79
|
}
|
|
54
80
|
|
|
55
81
|
@Override
|
|
56
|
-
public
|
|
82
|
+
public E next() {
|
|
57
83
|
if (!advance()) {
|
|
58
84
|
throw new NoSuchElementException("the event stream ended");
|
|
59
85
|
}
|
|
60
|
-
|
|
86
|
+
E event = pending;
|
|
61
87
|
pending = null;
|
|
62
|
-
lastEventId =
|
|
88
|
+
lastEventId = pendingId;
|
|
63
89
|
return event;
|
|
64
90
|
}
|
|
65
91
|
};
|
|
@@ -78,7 +104,15 @@ public final class EventStream<T> implements Iterable<SseEvent<T>>, AutoCloseabl
|
|
|
78
104
|
end();
|
|
79
105
|
return false;
|
|
80
106
|
}
|
|
81
|
-
|
|
107
|
+
String id = event.id() == null ? "" : event.id();
|
|
108
|
+
Duration retry = event.retry() == null ? null : Duration.ofMillis(event.retry());
|
|
109
|
+
try {
|
|
110
|
+
pending = decode.apply(new SseEvent<>(event.data(), event.event(), event.id(), retry));
|
|
111
|
+
} catch (RuntimeException e) {
|
|
112
|
+
lastEventId = id;
|
|
113
|
+
throw e;
|
|
114
|
+
}
|
|
115
|
+
pendingId = id;
|
|
82
116
|
return true;
|
|
83
117
|
} catch (InterruptedIOException e) {
|
|
84
118
|
end();
|
|
@@ -96,22 +130,6 @@ public final class EventStream<T> implements Iterable<SseEvent<T>>, AutoCloseabl
|
|
|
96
130
|
}
|
|
97
131
|
}
|
|
98
132
|
|
|
99
|
-
@SuppressWarnings("unchecked")
|
|
100
|
-
private SseEvent<T> decoded(Sse.Event event) {
|
|
101
|
-
Duration retry = event.retry() == null ? null : Duration.ofMillis(event.retry());
|
|
102
|
-
T data;
|
|
103
|
-
if (type.getType() == String.class) {
|
|
104
|
-
data = (T) event.data();
|
|
105
|
-
} else {
|
|
106
|
-
try {
|
|
107
|
-
data = Json.MAPPER.readValue(event.data(), type);
|
|
108
|
-
} catch (JacksonException e) {
|
|
109
|
-
throw new DecodeException("an event's data does not decode: " + e.getOriginalMessage(), e);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
return new SseEvent<>(data, event.event(), event.id(), retry);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
133
|
private void end() {
|
|
116
134
|
ended = true;
|
|
117
135
|
close();
|
|
@@ -4,7 +4,7 @@ package http.runtime;
|
|
|
4
4
|
import java.net.http.HttpClient;
|
|
5
5
|
import java.util.Map;
|
|
6
6
|
import java.util.function.Consumer;
|
|
7
|
-
import
|
|
7
|
+
import java.util.function.Function;
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* A client's exchange: its config, its one HTTP client (never following a redirect on its own), its
|
|
@@ -28,14 +28,14 @@ final class Exchange {
|
|
|
28
28
|
return new Flight(this, op, call, options).run();
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
/** Opens one stream call: its events, once an error status has not thrown. */
|
|
32
|
-
<
|
|
31
|
+
/** Opens one stream call: its events, each decoded whole, once an error status has not thrown. */
|
|
32
|
+
<E> EventStream<E> events(
|
|
33
33
|
Operation op,
|
|
34
34
|
Call call,
|
|
35
35
|
RequestOptions options,
|
|
36
36
|
Consumer<Map<String, String>> headers,
|
|
37
|
-
|
|
38
|
-
return new Flight(this, op, call, options).events(headers,
|
|
37
|
+
Function<SseEvent<String>, E> decode) {
|
|
38
|
+
return new Flight(this, op, call, options).events(headers, decode);
|
|
39
39
|
}
|
|
40
40
|
|
|
41
41
|
Flight dial(Operation op, Call call, RequestOptions options) {
|
|
@@ -17,7 +17,6 @@ import java.util.concurrent.CancellationException;
|
|
|
17
17
|
import java.util.concurrent.Flow;
|
|
18
18
|
import java.util.function.Consumer;
|
|
19
19
|
import java.util.function.Function;
|
|
20
|
-
import tools.jackson.core.type.TypeReference;
|
|
21
20
|
|
|
22
21
|
/**
|
|
23
22
|
* One call's exchange: its hops, its auth retry, and its one deadline over all of them, which
|
|
@@ -85,7 +84,8 @@ final class Flight {
|
|
|
85
84
|
/**
|
|
86
85
|
* Opens the stream: an error status throws; a 2xx fills headersInto and raw, and settles stale.
|
|
87
86
|
*/
|
|
88
|
-
<
|
|
87
|
+
<E> EventStream<E> events(
|
|
88
|
+
Consumer<Map<String, String>> headersInto, Function<SseEvent<String>, E> decode) {
|
|
89
89
|
stream = true;
|
|
90
90
|
Hop hop = exchanged();
|
|
91
91
|
ApiException error = finish(hop).error();
|
|
@@ -96,7 +96,7 @@ final class Flight {
|
|
|
96
96
|
if (headersInto != null) {
|
|
97
97
|
headersInto.accept(hop.headers());
|
|
98
98
|
}
|
|
99
|
-
return new EventStream<>(hop.live(),
|
|
99
|
+
return new EventStream<>(hop.live(), decode);
|
|
100
100
|
} catch (RuntimeException e) {
|
|
101
101
|
Pump.release(hop.live());
|
|
102
102
|
throw e;
|
|
@@ -6,8 +6,10 @@ import java.time.Duration;
|
|
|
6
6
|
import java.util.ArrayList;
|
|
7
7
|
import java.util.List;
|
|
8
8
|
import java.util.Map;
|
|
9
|
+
import java.util.function.Function;
|
|
9
10
|
import java.util.function.Supplier;
|
|
10
11
|
import tools.jackson.core.type.TypeReference;
|
|
12
|
+
import tools.jackson.databind.JsonNode;
|
|
11
13
|
|
|
12
14
|
/**
|
|
13
15
|
* A realtime call's entry and its dials (C#'s RealtimeAsync and Dial): the WebSocket upgrade with
|
|
@@ -33,19 +35,45 @@ final class Realtime {
|
|
|
33
35
|
this.options = options;
|
|
34
36
|
}
|
|
35
37
|
|
|
36
|
-
/**
|
|
37
|
-
|
|
38
|
+
/**
|
|
39
|
+
* The call's connection over WebSocket, else SSE, else long-poll, opened within 30 s; a message
|
|
40
|
+
* that is no JSON read as a JSON string.
|
|
41
|
+
*/
|
|
42
|
+
static <TIn, TOut> ResumableConnection<TIn, TOut> open(
|
|
38
43
|
Exchange exchange,
|
|
39
44
|
Operation op,
|
|
40
45
|
Call call,
|
|
41
46
|
RequestOptions given,
|
|
42
47
|
TransportOptions transport,
|
|
43
|
-
TypeReference<
|
|
48
|
+
TypeReference<TIn> type) {
|
|
49
|
+
return connected(exchange, op, call, given, transport, type, false);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The connection of an operation that declares its messages: one that is no JSON throws. */
|
|
53
|
+
static <TIn, TOut> ResumableConnection<TIn, TOut> typed(
|
|
54
|
+
Exchange exchange,
|
|
55
|
+
Operation op,
|
|
56
|
+
Call call,
|
|
57
|
+
RequestOptions given,
|
|
58
|
+
TransportOptions transport,
|
|
59
|
+
TypeReference<TIn> type) {
|
|
60
|
+
return connected(exchange, op, call, given, transport, type, true);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private static <TIn, TOut> ResumableConnection<TIn, TOut> connected(
|
|
64
|
+
Exchange exchange,
|
|
65
|
+
Operation op,
|
|
66
|
+
Call call,
|
|
67
|
+
RequestOptions given,
|
|
68
|
+
TransportOptions transport,
|
|
69
|
+
TypeReference<TIn> type,
|
|
70
|
+
boolean strict) {
|
|
44
71
|
Realtime dial = new Realtime(exchange, op, call, given == null ? RequestOptions.NONE : given);
|
|
45
72
|
List<TransportAdapter> chain =
|
|
46
73
|
List.of(new WsAdapter(dial), new SseAdapter(dial), new LongPollAdapter(dial));
|
|
47
|
-
ResumableConnection<
|
|
48
|
-
new ResumableConnection<>(
|
|
74
|
+
ResumableConnection<TIn, TOut> connection =
|
|
75
|
+
new ResumableConnection<>(
|
|
76
|
+
dial.url(call), chain, type, transport, RealtimeLoop.OPEN_LIMIT, strict);
|
|
49
77
|
connection.open();
|
|
50
78
|
return connection;
|
|
51
79
|
}
|
|
@@ -59,15 +87,21 @@ final class Realtime {
|
|
|
59
87
|
+ (query.isEmpty() ? "" : "?" + query);
|
|
60
88
|
}
|
|
61
89
|
|
|
62
|
-
TypedWebSocket socket(TransportOptions cursor) {
|
|
90
|
+
TypedWebSocket<WsMessage, JsonNode> socket(TransportOptions cursor) {
|
|
63
91
|
RawResponse raw = new RawResponse();
|
|
64
|
-
TypedWebSocket socket =
|
|
65
|
-
WsDial.open(
|
|
92
|
+
TypedWebSocket<WsMessage, JsonNode> socket =
|
|
93
|
+
WsDial.open(
|
|
94
|
+
exchange,
|
|
95
|
+
op,
|
|
96
|
+
cursored(cursor),
|
|
97
|
+
with(raw, null),
|
|
98
|
+
cursor.protocols(),
|
|
99
|
+
Function.identity());
|
|
66
100
|
opened(raw);
|
|
67
101
|
return socket;
|
|
68
102
|
}
|
|
69
103
|
|
|
70
|
-
EventStream<String
|
|
104
|
+
EventStream<SseEvent<String>> stream(TransportOptions cursor) {
|
|
71
105
|
Operation sse =
|
|
72
106
|
new Operation(
|
|
73
107
|
op.method(),
|
|
@@ -83,8 +117,8 @@ final class Realtime {
|
|
|
83
117
|
plus(call.headers(), Call.Arg.cursor("Last-Event-ID", cursor.lastEventId())),
|
|
84
118
|
call.body());
|
|
85
119
|
RawResponse raw = new RawResponse();
|
|
86
|
-
EventStream<String
|
|
87
|
-
exchange.dial(sse, at, with(raw, null)).events(null,
|
|
120
|
+
EventStream<SseEvent<String>> stream =
|
|
121
|
+
exchange.dial(sse, at, with(raw, null)).events(null, e -> e);
|
|
88
122
|
opened(raw);
|
|
89
123
|
return stream;
|
|
90
124
|
}
|