@workerstack/clients 1.0.0-rc.28 → 1.0.0-rc.30
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 +403 -21
- package/assets/installers/examples/github.config.ts +17 -19
- package/assets/installers/examples/goreleaser.config.ts +16 -18
- package/assets/installers/examples/raw.config.ts +13 -15
- package/bin/clients.js +87 -66
- package/bin/installgen.js +19 -10
- package/dist/cli.d.ts +4 -4
- package/dist/cli.js +18 -12
- package/dist/emit/cli/channels.d.ts +2 -2
- package/dist/emit/cli/channels.js +18 -13
- package/dist/emit/cli/commands.d.ts +1 -1
- package/dist/emit/cli/commands.js +39 -13
- package/dist/emit/cli/discovery.d.ts +0 -6
- package/dist/emit/cli/discovery.js +9 -7
- package/dist/emit/cli/flags.d.ts +1 -3
- package/dist/emit/cli/flags.js +18 -8
- package/dist/emit/cli/install.d.ts +0 -8
- package/dist/emit/cli/install.js +3 -3
- package/dist/emit/cli/layout.d.ts +1 -1
- package/dist/emit/cli/layout.js +13 -10
- package/dist/emit/cli/module.d.ts +6 -6
- package/dist/emit/cli/module.js +10 -10
- package/dist/emit/cli/release.d.ts +0 -11
- package/dist/emit/cli/release.js +4 -4
- package/dist/emit/cli/skills.js +8 -4
- package/dist/emit/csharp/errors.js +4 -4
- package/dist/emit/csharp/json.js +8 -8
- package/dist/emit/csharp/realtime.d.ts +1 -8
- package/dist/emit/csharp/realtime.js +26 -26
- package/dist/emit/csharp/sdk-answer.d.ts +10 -2
- package/dist/emit/csharp/sdk-answer.js +4 -4
- package/dist/emit/csharp/sdk-body.js +8 -6
- package/dist/emit/csharp/sdk-client.d.ts +3 -3
- package/dist/emit/csharp/sdk-client.js +2 -2
- package/dist/emit/csharp/sdk-csproj.d.ts +7 -9
- package/dist/emit/csharp/sdk-csproj.js +10 -10
- package/dist/emit/csharp/sdk-doc.js +1 -1
- package/dist/emit/csharp/sdk-method.d.ts +0 -1
- package/dist/emit/csharp/sdk-method.js +19 -8
- package/dist/emit/csharp/sdk-plan.js +0 -1
- package/dist/emit/csharp/sdk.js +3 -3
- package/dist/emit/csharp/sse.d.ts +0 -13
- package/dist/emit/csharp/sse.js +92 -11
- package/dist/emit/csharp/transport.js +9 -9
- package/dist/emit/csharp/types-enum.js +3 -1
- 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 +13 -14
- package/dist/emit/csharp/types-record.js +3 -3
- package/dist/emit/csharp/types-union.d.ts +1 -1
- package/dist/emit/csharp/types.d.ts +0 -1
- package/dist/emit/csharp/types.js +3 -3
- package/dist/emit/csharp/ws.d.ts +0 -15
- package/dist/emit/csharp/ws.js +26 -5
- package/dist/emit/go/errors.js +1 -1
- package/dist/emit/go/http.js +2 -2
- package/dist/emit/go/module-path.js +2 -2
- package/dist/emit/go/sdk-answer.d.ts +24 -1
- package/dist/emit/go/sdk-answer.js +1 -1
- package/dist/emit/go/sdk-body.js +11 -7
- package/dist/emit/go/sdk-client.js +1 -1
- package/dist/emit/go/sdk-method.d.ts +3 -0
- package/dist/emit/go/sdk-method.js +18 -12
- package/dist/emit/go/sdk-mirror.js +2 -2
- package/dist/emit/go/sdk-opts.d.ts +0 -2
- package/dist/emit/go/sdk-opts.js +3 -3
- package/dist/emit/go/sdk.d.ts +1 -1
- package/dist/emit/go/sdk.js +9 -9
- package/dist/emit/go/sse.d.ts +2 -10
- package/dist/emit/go/sse.js +88 -13
- package/dist/emit/go/types-names.js +5 -0
- package/dist/emit/go/types-struct.d.ts +2 -1
- package/dist/emit/go/types-struct.js +1 -1
- 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 +20 -9
- package/dist/emit/go/ws.d.ts +4 -11
- package/dist/emit/go/ws.js +215 -59
- package/dist/emit/java/gradle.d.ts +7 -9
- package/dist/emit/java/gradle.js +8 -8
- package/dist/emit/java/json.d.ts +3 -0
- package/dist/emit/java/json.js +1 -1
- package/dist/emit/java/layout-ast.d.ts +4 -1
- package/dist/emit/java/layout-ast.js +1 -1
- package/dist/emit/java/layout-decl.js +5 -4
- package/dist/emit/java/layout-doc.js +13 -7
- package/dist/emit/java/layout-dot.js +1 -1
- package/dist/emit/java/layout-strings.js +4 -5
- package/dist/emit/java/layout-types.js +7 -5
- package/dist/emit/java/layout-visitor.js +4 -3
- package/dist/emit/java/layout.js +5 -4
- package/dist/emit/java/models-names.d.ts +2 -0
- package/dist/emit/java/models-names.js +6 -4
- package/dist/emit/java/models-record.d.ts +0 -1
- package/dist/emit/java/models-record.js +3 -3
- package/dist/emit/java/models-union.d.ts +13 -2
- package/dist/emit/java/models-union.js +12 -6
- package/dist/emit/java/models.d.ts +5 -1
- package/dist/emit/java/models.js +44 -20
- package/dist/emit/java/realtime.d.ts +34 -26
- package/dist/emit/java/realtime.js +45 -10
- package/dist/emit/java/sdk-client.d.ts +6 -6
- package/dist/emit/java/sdk-client.js +1 -1
- package/dist/emit/java/sdk-decl.js +2 -2
- package/dist/emit/java/sdk-errors.js +1 -1
- package/dist/emit/java/sdk-headers.js +2 -2
- package/dist/emit/java/sdk-mirror.js +7 -6
- package/dist/emit/java/sdk-models.d.ts +1 -1
- package/dist/emit/java/sdk-models.js +7 -7
- package/dist/emit/java/sdk-op.d.ts +1 -10
- package/dist/emit/java/sdk-op.js +9 -9
- package/dist/emit/java/sdk-params.d.ts +5 -5
- package/dist/emit/java/sdk-params.js +3 -2
- package/dist/emit/java/sdk-plan.js +0 -1
- package/dist/emit/java/sdk.d.ts +1 -1
- package/dist/emit/java/sdk.js +14 -13
- package/dist/emit/java/sse.d.ts +12 -13
- package/dist/emit/java/sse.js +105 -6
- package/dist/emit/java/ws.d.ts +48 -9
- package/dist/emit/java/ws.js +88 -4
- package/dist/emit/mcp/annotations.js +8 -4
- package/dist/emit/mcp/files.js +9 -9
- package/dist/emit/mcp/mounted.js +2 -2
- package/dist/emit/mcp/output-schema.d.ts +4 -2
- package/dist/emit/mcp/output-schema.js +58 -14
- package/dist/emit/mcp/registry.d.ts +0 -2
- package/dist/emit/mcp/registry.js +5 -4
- package/dist/emit/mcp/runtime.js +2 -2
- package/dist/emit/mcp/schema.js +22 -11
- package/dist/emit/mcp/server.d.ts +7 -7
- package/dist/emit/mcp/server.js +7 -6
- package/dist/emit/mcp/tools.js +7 -6
- package/dist/emit/python/errors.js +3 -3
- package/dist/emit/python/realtime.d.ts +9 -6
- package/dist/emit/python/realtime.js +22 -20
- package/dist/emit/python/sdk-answer.d.ts +8 -8
- package/dist/emit/python/sdk-answer.js +2 -2
- package/dist/emit/python/sdk-body.js +4 -5
- package/dist/emit/python/sdk-client.js +5 -5
- package/dist/emit/python/sdk-doc.js +2 -2
- package/dist/emit/python/sdk-method.d.ts +1 -1
- package/dist/emit/python/sdk-method.js +38 -11
- package/dist/emit/python/sdk-plan.js +0 -1
- package/dist/emit/python/sdk-pyproject.d.ts +0 -2
- package/dist/emit/python/sdk-pyproject.js +8 -8
- package/dist/emit/python/sdk.d.ts +1 -1
- package/dist/emit/python/sdk.js +28 -8
- package/dist/emit/python/sse.d.ts +0 -7
- package/dist/emit/python/sse.js +36 -6
- package/dist/emit/python/transport.js +4 -4
- package/dist/emit/python/types-dict.d.ts +2 -2
- package/dist/emit/python/types-dict.js +1 -1
- package/dist/emit/python/types-names.js +2 -2
- package/dist/emit/python/types-union.js +1 -1
- package/dist/emit/python/types.d.ts +7 -0
- package/dist/emit/python/types.js +23 -6
- package/dist/emit/python/ws.d.ts +21 -10
- package/dist/emit/python/ws.js +69 -3
- package/dist/emit/rust/errors.js +3 -3
- package/dist/emit/rust/http.js +4 -4
- package/dist/emit/rust/realtime.d.ts +7 -5
- package/dist/emit/rust/realtime.js +15 -18
- package/dist/emit/rust/sdk-body.js +8 -5
- package/dist/emit/rust/sdk-cargo.d.ts +16 -18
- package/dist/emit/rust/sdk-cargo.js +12 -12
- package/dist/emit/rust/sdk-client.d.ts +1 -1
- package/dist/emit/rust/sdk-client.js +3 -3
- package/dist/emit/rust/sdk-method.js +3 -3
- package/dist/emit/rust/sdk-opts.d.ts +2 -1
- package/dist/emit/rust/sdk-opts.js +2 -2
- package/dist/emit/rust/sdk-plan.js +0 -1
- package/dist/emit/rust/sdk.d.ts +1 -1
- package/dist/emit/rust/sdk.js +5 -5
- package/dist/emit/rust/sse.d.ts +11 -12
- package/dist/emit/rust/sse.js +54 -8
- package/dist/emit/rust/types-names.js +3 -3
- package/dist/emit/rust/types-struct.js +1 -1
- package/dist/emit/rust/types-union.d.ts +10 -2
- package/dist/emit/rust/types-union.js +4 -0
- package/dist/emit/rust/types.d.ts +9 -0
- package/dist/emit/rust/types.js +20 -12
- package/dist/emit/rust/ws.d.ts +22 -15
- package/dist/emit/rust/ws.js +60 -10
- package/dist/emit/shared/escape.js +17 -17
- package/dist/emit/shared/format.js +1 -1
- package/dist/emit/shared/gofmt.js +1 -1
- package/dist/emit/shared/lang.js +10 -10
- package/dist/emit/shared/literals.d.ts +5 -0
- package/dist/emit/shared/literals.js +8 -0
- package/dist/emit/shared/metadata.d.ts +0 -6
- package/dist/emit/shared/metadata.js +8 -7
- package/dist/emit/shared/ruff.js +1 -1
- package/dist/emit/shared/rustfmt.js +1 -1
- package/dist/emit/shared/type-emitter.js +37 -20
- package/dist/emit/shared/unknown-type.constants.d.ts +2 -0
- package/dist/emit/shared/unknown-type.constants.js +2 -0
- package/dist/emit/ts/http.d.ts +0 -2
- package/dist/emit/ts/http.js +4 -4
- package/dist/emit/ts/package.d.ts +14 -12
- package/dist/emit/ts/package.js +9 -8
- package/dist/emit/ts/route-tree.js +2 -2
- package/dist/emit/ts/sdk-types-preamble.d.ts +1 -1
- package/dist/emit/ts/sdk-types-preamble.js +6 -2
- package/dist/emit/ts/sdk-types.js +59 -20
- package/dist/emit/ts/sdk.js +6 -6
- package/dist/emit/ts/service-map.d.ts +10 -3
- package/dist/emit/ts/service-map.js +30 -2
- package/dist/emit/ts/tanstack-query.js +6 -6
- package/dist/emit/ts/type-gen.js +36 -21
- package/dist/emit/ts/webhooks.d.ts +0 -2
- package/dist/emit/ts/webhooks.js +3 -3
- package/dist/extract/chain.js +5 -4
- package/dist/extract/extract.js +5 -5
- package/dist/extract/serialize.d.ts +0 -2
- package/dist/extract/serialize.js +14 -15
- package/dist/extract/walk.js +15 -12
- package/dist/gen/args.js +9 -5
- package/dist/gen/formatters.js +5 -3
- package/dist/gen/shipped.js +2 -2
- package/dist/gen/targets.d.ts +2 -4
- package/dist/gen/targets.js +8 -4
- package/dist/gen/write.js +4 -2
- package/dist/index.js +2 -2
- package/dist/installers/cli.d.ts +4 -4
- package/dist/installers/cli.js +24 -24
- package/dist/installers/commands/build.d.ts +4 -4
- package/dist/installers/commands/build.js +2 -3
- package/dist/installers/commands/check.d.ts +2 -2
- package/dist/installers/commands/check.js +11 -10
- package/dist/installers/commands/init.d.ts +2 -2
- package/dist/installers/commands/init.js +1 -2
- package/dist/installers/config/define-config.d.ts +16 -16
- package/dist/installers/config/define-config.js +1 -1
- package/dist/installers/config/hooks/bun.d.ts +6 -6
- package/dist/installers/config/hooks/node.js +1 -1
- package/dist/installers/config/load.d.ts +6 -8
- package/dist/installers/config/load.js +7 -8
- package/dist/installers/config/resolve.d.ts +1 -2
- package/dist/installers/config/resolve.js +28 -33
- package/dist/installers/config/types.d.ts +6 -6
- package/dist/installers/config/types.js +0 -1
- package/dist/installers/render/quote.js +3 -5
- package/dist/installers/render/render.d.ts +6 -6
- package/dist/installers/render/render.js +26 -26
- package/dist/installers/ui.d.ts +4 -4
- package/dist/installers/ui.js +3 -3
- package/dist/ir/build.d.ts +3 -3
- package/dist/ir/build.js +12 -5
- package/dist/ir/load.js +9 -10
- package/dist/ir/model.d.ts +16 -1
- package/dist/ir/model.js +0 -1
- package/dist/ir/resolve-refs.js +2 -2
- package/dist/ir/resource-tree.js +2 -1
- package/dist/ir/route-tree-intern.js +1 -1
- package/dist/ir/schema.js +3 -3
- package/dist/ir/sdk-model.d.ts +25 -1
- package/dist/ir/sdk-model.js +38 -8
- package/dist/ir/slots.d.ts +1 -1
- package/dist/ir/slots.js +22 -11
- package/dist/ir/streams.d.ts +16 -0
- package/dist/ir/streams.js +40 -0
- package/dist/release/bootstrap.d.ts +3 -3
- package/dist/release/bootstrap.js +7 -7
- package/dist/release/bump-args.js +4 -4
- package/dist/release/bump-command.d.ts +1 -1
- package/dist/release/bump-command.js +9 -10
- package/dist/release/bump.d.ts +5 -4
- package/dist/release/bump.js +2 -2
- package/dist/release/cli.d.ts +4 -4
- package/dist/release/cli.js +4 -4
- package/dist/release/codegen.js +1 -1
- package/dist/release/digest.js +5 -7
- package/dist/release/git.js +5 -8
- package/dist/release/load.js +3 -3
- package/dist/release/manifest.js +9 -10
- package/dist/release/oasdiff.d.ts +10 -15
- package/dist/release/oasdiff.js +5 -6
- package/dist/release/registries.d.ts +0 -11
- package/dist/release/registries.js +17 -17
- package/dist/release/release-state.d.ts +16 -13
- package/dist/release/release-workflow.js +5 -7
- package/dist/release/repo-settings.d.ts +2 -1
- package/dist/release/spec-gate.d.ts +0 -2
- package/dist/release/spec-gate.js +6 -10
- package/dist/release/sync-command.d.ts +2 -2
- package/dist/release/sync-command.js +1 -1
- package/dist/release/sync-tree.js +9 -13
- package/dist/release/sync.d.ts +6 -6
- package/dist/release/sync.js +12 -13
- package/dist/release/types.d.ts +22 -22
- package/dist/release/types.js +0 -1
- package/dist/release/version-files.d.ts +3 -4
- package/dist/release/version-files.js +4 -5
- package/dist/runtime/.oxfmtrc.jsonc +8 -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/mcp/files.ts +1 -1
- package/dist/runtime/mcp/http.ts +6 -2
- package/dist/runtime/mcp/listen.ts +1 -1
- package/dist/runtime/mcp/mount.ts +2 -2
- package/dist/runtime/mcp/protocol.ts +1 -1
- 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/dist/runtime/ts-tanstack-query/query.ts +0 -2
- package/package.json +12 -40
- package/dist/emit/cli/index.d.ts +0 -1
- package/dist/emit/cli/index.js +0 -1
- package/dist/emit/csharp/index.d.ts +0 -1
- package/dist/emit/csharp/index.js +0 -1
- package/dist/emit/go/index.d.ts +0 -1
- package/dist/emit/go/index.js +0 -1
- package/dist/emit/java/index.d.ts +0 -2
- package/dist/emit/java/index.js +0 -2
- package/dist/emit/mcp/index.d.ts +0 -3
- package/dist/emit/mcp/index.js +0 -3
- package/dist/emit/python/index.d.ts +0 -1
- package/dist/emit/python/index.js +0 -1
- package/dist/emit/rust/index.d.ts +0 -1
- package/dist/emit/rust/index.js +0 -1
|
@@ -40,15 +40,8 @@ public sealed class TransportOptions
|
|
|
40
40
|
/// <summary>The first reconnect's base delay, doubled per attempt up to 30 s; an SSE <c>retry</c> replaces it.</summary>
|
|
41
41
|
public TimeSpan ReconnectDelay { get; init; } = TimeSpan.FromSeconds(1);
|
|
42
42
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
{
|
|
46
|
-
LastEventId = lastEventId,
|
|
47
|
-
ReconnectToken = reconnectToken,
|
|
48
|
-
Protocols = protocols ?? [],
|
|
49
|
-
MaxReconnectAttempts = maxReconnectAttempts ?? 5,
|
|
50
|
-
ReconnectDelay = reconnectDelay ?? TimeSpan.FromSeconds(1),
|
|
51
|
-
};
|
|
43
|
+
/* the connection's own copy: it advances the cursor, never the caller's value */
|
|
44
|
+
internal TransportOptions Copy() => (TransportOptions)MemberwiseClone();
|
|
52
45
|
|
|
53
46
|
/* past a message: its SSE id, else the payload's id or last_event_id (a string or an integer), and its reconnect_token */
|
|
54
47
|
internal void Advance(string? id, JsonElement payload)
|
|
@@ -162,12 +155,20 @@ internal sealed class Dial(Transport client, Operation op, Call call)
|
|
|
162
155
|
|
|
163
156
|
internal sealed partial class Transport
|
|
164
157
|
{
|
|
165
|
-
|
|
158
|
+
/* a connection whose operation declares no messages: a message that is no JSON reads as a JSON string */
|
|
159
|
+
public Task<ResumableConnection<TIn, TOut>> RealtimeAsync<TIn, TOut>(Operation op, Call call, TransportOptions options, JsonTypeInfo<TIn> read, JsonTypeInfo<TOut> write, CancellationToken cancellationToken) =>
|
|
160
|
+
OpenRealtimeAsync(op, call, options, read, write, false, cancellationToken);
|
|
161
|
+
|
|
162
|
+
/* a connection whose operation declares its messages: a message that is no JSON throws */
|
|
163
|
+
public Task<ResumableConnection<TIn, TOut>> TypedRealtimeAsync<TIn, TOut>(Operation op, Call call, TransportOptions options, JsonTypeInfo<TIn> read, JsonTypeInfo<TOut> write, CancellationToken cancellationToken) =>
|
|
164
|
+
OpenRealtimeAsync(op, call, options, read, write, true, cancellationToken);
|
|
165
|
+
|
|
166
|
+
private async Task<ResumableConnection<TIn, TOut>> OpenRealtimeAsync<TIn, TOut>(Operation op, Call call, TransportOptions options, JsonTypeInfo<TIn> read, JsonTypeInfo<TOut> write, bool strict, CancellationToken cancellationToken)
|
|
166
167
|
{
|
|
167
168
|
var dial = new Dial(this, op, call);
|
|
168
169
|
var url = dial.Url();
|
|
169
170
|
cancellationToken.ThrowIfCancellationRequested();
|
|
170
|
-
var connection = new ResumableConnection<
|
|
171
|
+
var connection = new ResumableConnection<TIn, TOut>(url.ToString(), [new WsAdapter(dial), new SseAdapter(dial), new LongPollAdapter(dial)], read, write, options) { Strict = strict };
|
|
171
172
|
using var bound = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
|
172
173
|
bound.CancelAfter(RealtimeLoop.OpenLimit);
|
|
173
174
|
try
|
|
@@ -10,21 +10,22 @@ using System.Threading.Tasks;
|
|
|
10
10
|
|
|
11
11
|
namespace Http.Runtime;
|
|
12
12
|
|
|
13
|
-
/// <summary>One server-sent event: its
|
|
13
|
+
/// <summary>One server-sent event: its data, its type, the stream's last event id when it came, and its <c>retry</c>.</summary>
|
|
14
14
|
public sealed record SseEvent<T>(T Data, string? Event, string? Id, TimeSpan? Retry);
|
|
15
15
|
|
|
16
16
|
/// <summary>
|
|
17
|
-
/// An open event stream, read once by <c>await foreach</c
|
|
18
|
-
///
|
|
17
|
+
/// An open event stream, read once by <c>await foreach</c>, each event decoded whole into <typeparamref name="TEvent"/>:
|
|
18
|
+
/// an <see cref="SseEvent{T}"/>, or a named-event operation's own record. No timeout bounds it. An event that does not
|
|
19
|
+
/// decode, a cap or a failed read is thrown once and ends it. The method's token or the read's own token ends it with an
|
|
19
20
|
/// OperationCanceledException; leaving the loop or <see cref="DisposeAsync"/> ends it quietly. Each end lets the
|
|
20
21
|
/// connection go: dispose it, or read it to its end.
|
|
21
22
|
/// </summary>
|
|
22
|
-
public sealed class EventStream<
|
|
23
|
+
public sealed class EventStream<TEvent> : IAsyncEnumerable<TEvent>, IAsyncDisposable
|
|
23
24
|
{
|
|
24
25
|
private const int ReadBuffer = 65_536;
|
|
25
26
|
|
|
26
27
|
private readonly HttpResponseMessage _response;
|
|
27
|
-
private readonly Func<string
|
|
28
|
+
private readonly Func<SseEvent<string>, TEvent> _decode;
|
|
28
29
|
private readonly CancellationToken _call;
|
|
29
30
|
private readonly CancellationTokenSource _end = new();
|
|
30
31
|
private readonly CancellationTokenRegistration _registration;
|
|
@@ -36,19 +37,19 @@ public sealed class EventStream<T> : IAsyncEnumerable<SseEvent<T>>, IAsyncDispos
|
|
|
36
37
|
private int _taken;
|
|
37
38
|
private int _released;
|
|
38
39
|
|
|
39
|
-
internal EventStream(HttpResponseMessage response, Func<string
|
|
40
|
+
internal EventStream(HttpResponseMessage response, Func<SseEvent<string>, TEvent> decode, CancellationToken call)
|
|
40
41
|
{
|
|
41
42
|
_response = response;
|
|
42
43
|
_decode = decode;
|
|
43
44
|
_call = call;
|
|
44
|
-
_registration = call.Register(static stream => ((EventStream<
|
|
45
|
+
_registration = call.Register(static stream => ((EventStream<TEvent>)stream!).Release(), this);
|
|
45
46
|
}
|
|
46
47
|
|
|
47
|
-
/// <summary>The id of the last event read, to resume from; empty before any.</summary>
|
|
48
|
+
/// <summary>The id of the last event read, to resume from, taken before the event decodes; empty before any.</summary>
|
|
48
49
|
public string LastEventId { get; private set; } = "";
|
|
49
50
|
|
|
50
51
|
/// <summary>The stream's events in order; a second enumeration throws InvalidOperationException.</summary>
|
|
51
|
-
public IAsyncEnumerator<
|
|
52
|
+
public IAsyncEnumerator<TEvent> GetAsyncEnumerator(CancellationToken cancellationToken = default) =>
|
|
52
53
|
Interlocked.Exchange(ref _taken, 1) == 0
|
|
53
54
|
? EventsAsync(cancellationToken)
|
|
54
55
|
: throw new InvalidOperationException("an EventStream is read once");
|
|
@@ -71,7 +72,7 @@ public sealed class EventStream<T> : IAsyncEnumerable<SseEvent<T>>, IAsyncDispos
|
|
|
71
72
|
}
|
|
72
73
|
}
|
|
73
74
|
|
|
74
|
-
private async IAsyncEnumerator<
|
|
75
|
+
private async IAsyncEnumerator<TEvent> EventsAsync(CancellationToken token)
|
|
75
76
|
{
|
|
76
77
|
using var read = CancellationTokenSource.CreateLinkedTokenSource(token, _end.Token);
|
|
77
78
|
try
|
|
@@ -81,9 +82,8 @@ public sealed class EventStream<T> : IAsyncEnumerable<SseEvent<T>>, IAsyncDispos
|
|
|
81
82
|
var cap = await PullAsync(token, read.Token).ConfigureAwait(false);
|
|
82
83
|
foreach (var raw in _pending)
|
|
83
84
|
{
|
|
84
|
-
var data = _decode(raw.Data);
|
|
85
85
|
LastEventId = raw.Id ?? "";
|
|
86
|
-
yield return new SseEvent<
|
|
86
|
+
yield return _decode(new SseEvent<string>(raw.Data, raw.Event, raw.Id, raw.Retry));
|
|
87
87
|
}
|
|
88
88
|
_pending.Clear();
|
|
89
89
|
if (cap is not null)
|
|
@@ -132,16 +132,21 @@ public sealed class EventStream<T> : IAsyncEnumerable<SseEvent<T>>, IAsyncDispos
|
|
|
132
132
|
|
|
133
133
|
internal sealed partial class Transport
|
|
134
134
|
{
|
|
135
|
-
public async Task<EventStream<T
|
|
136
|
-
new(await OpenedAsync(op, call, lastEventId, cancellationToken).ConfigureAwait(false),
|
|
135
|
+
public async Task<EventStream<SseEvent<T>>> EventsAsync<T>(Operation op, Call call, string? lastEventId, JsonTypeInfo<T> info, CancellationToken cancellationToken) =>
|
|
136
|
+
new(await OpenedAsync(op, call, lastEventId, cancellationToken).ConfigureAwait(false), e => new(EventData(e.Data, info), e.Event, e.Id, e.Retry), cancellationToken);
|
|
137
137
|
|
|
138
|
-
public async Task<EventStream<string
|
|
139
|
-
new(await OpenedAsync(op, call, lastEventId, cancellationToken).ConfigureAwait(false),
|
|
138
|
+
public async Task<EventStream<SseEvent<string>>> TextEventsAsync(Operation op, Call call, string? lastEventId, CancellationToken cancellationToken) =>
|
|
139
|
+
new(await OpenedAsync(op, call, lastEventId, cancellationToken).ConfigureAwait(false), e => e, cancellationToken);
|
|
140
|
+
|
|
141
|
+
/* a named-event operation's events, each decoded by its name through the context's options */
|
|
142
|
+
public async Task<EventStream<TEvent>> NamedEventsAsync<TEvent>(Operation op, Call call, string? lastEventId, Func<SseEvent<string>, JsonSerializerOptions, TEvent> named, CancellationToken cancellationToken) =>
|
|
143
|
+
new(await OpenedAsync(op, call, lastEventId, cancellationToken).ConfigureAwait(false), e => named(e, Json), cancellationToken);
|
|
140
144
|
|
|
141
145
|
private Task<HttpResponseMessage> OpenedAsync(Operation op, Call call, string? lastEventId, CancellationToken cancellationToken) =>
|
|
142
146
|
new Exchange(this, op, call with { Headers = [.. call.Headers, Arg.Text("Last-Event-ID", lastEventId)] }, stream: true).OpenAsync(cancellationToken);
|
|
143
147
|
|
|
144
|
-
|
|
148
|
+
/// <summary>An event's data decoded into <typeparamref name="T"/>; a misfit or null is a <see cref="DecodeException"/>.</summary>
|
|
149
|
+
internal static T EventData<T>(string data, JsonTypeInfo<T> info)
|
|
145
150
|
{
|
|
146
151
|
try
|
|
147
152
|
{
|
|
@@ -23,24 +23,33 @@ public enum ConnectionState
|
|
|
23
23
|
|
|
24
24
|
/// <summary>
|
|
25
25
|
/// A connection over a chain of transports, tried in order, read by <c>await foreach</c>: each message decoded as
|
|
26
|
-
/// <typeparamref name="
|
|
27
|
-
/// <see cref="
|
|
28
|
-
///
|
|
29
|
-
///
|
|
30
|
-
///
|
|
26
|
+
/// <typeparamref name="TIn"/>, what the server sends, the cursor in <see cref="Options"/> advanced past it first, and
|
|
27
|
+
/// <see cref="Message"/> fired before it is yielded; <see cref="SendAsync(TOut, CancellationToken)"/> sends the JSON
|
|
28
|
+
/// of a <typeparamref name="TOut"/>, what the server receives. A message that does not decode throws
|
|
29
|
+
/// <see cref="DecodeException"/> once and ends that enumeration, the connection kept, and a new <c>await foreach</c>
|
|
30
|
+
/// reads the next one; a connection of declared messages reads only JSON, any other reads a message that is no JSON
|
|
31
|
+
/// as a JSON string. After a drop it reopens the chain from the cursor, backing off from the delay (an SSE
|
|
32
|
+
/// <c>retry</c> first), doubling to 30 s, for up to <c>MaxReconnectAttempts</c> in a row; giving up throws the last
|
|
33
|
+
/// failure once, and the enumeration then ends. Leaving a loop keeps the connection; a canceled read leaves it
|
|
34
|
+
/// reconnecting. <see cref="CloseAsync"/> from any task ends a pending read with no message.
|
|
31
35
|
/// </summary>
|
|
32
|
-
public sealed class ResumableConnection<
|
|
36
|
+
public sealed class ResumableConnection<TIn, TOut> : IAsyncEnumerable<TIn>, IAsyncDisposable
|
|
33
37
|
{
|
|
34
|
-
private readonly JsonTypeInfo<
|
|
38
|
+
private readonly JsonTypeInfo<TIn> _read;
|
|
39
|
+
private readonly JsonTypeInfo<TOut> _write;
|
|
35
40
|
private readonly RealtimeLoop _loop;
|
|
36
41
|
|
|
37
|
-
/// <summary>
|
|
38
|
-
|
|
42
|
+
/// <summary>
|
|
43
|
+
/// A connection to <paramref name="url"/> over <paramref name="adapters"/>, its messages read through
|
|
44
|
+
/// <paramref name="read"/> and sent through <paramref name="write"/>; it opens at <see cref="ConnectAsync"/>.
|
|
45
|
+
/// </summary>
|
|
46
|
+
public ResumableConnection(string url, IReadOnlyList<ITransportAdapter> adapters, JsonTypeInfo<TIn> read, JsonTypeInfo<TOut> write, TransportOptions? options = null)
|
|
39
47
|
{
|
|
40
48
|
Url = url;
|
|
41
49
|
Adapters = adapters;
|
|
42
50
|
Options = options ?? new TransportOptions();
|
|
43
|
-
|
|
51
|
+
_read = read;
|
|
52
|
+
_write = write;
|
|
44
53
|
_loop = new RealtimeLoop(adapters, Options, url);
|
|
45
54
|
}
|
|
46
55
|
|
|
@@ -59,60 +68,78 @@ public sealed class ResumableConnection<T> : IAsyncEnumerable<T>, IAsyncDisposab
|
|
|
59
68
|
/// <summary>The transport that last opened; null after a drop, until the next open.</summary>
|
|
60
69
|
public TransportKind? ProvenTransport => _loop.Proven;
|
|
61
70
|
|
|
71
|
+
/// <summary>Each message as it is decoded, before the enumeration yields it; a handler that throws is ignored.</summary>
|
|
72
|
+
public event Action<TIn>? Message;
|
|
73
|
+
|
|
74
|
+
/* the operation declares its messages: a message that is no JSON is no message */
|
|
75
|
+
internal bool Strict { get; init; }
|
|
76
|
+
|
|
62
77
|
/// <summary>Opens the first adapter in order that opens; the last failure when none does.</summary>
|
|
63
78
|
public Task ConnectAsync(CancellationToken cancellationToken = default) => _loop.ConnectAsync(cancellationToken);
|
|
64
79
|
|
|
65
80
|
/// <summary>The messages in order; its token, once fired, leaves the connection reconnecting.</summary>
|
|
66
|
-
public IAsyncEnumerator<
|
|
81
|
+
public IAsyncEnumerator<TIn> GetAsyncEnumerator(CancellationToken cancellationToken = default) => MessagesAsync(cancellationToken);
|
|
82
|
+
|
|
83
|
+
/// <summary>Sends <paramref name="value"/> as its JSON text over the open transport.</summary>
|
|
84
|
+
public Task SendAsync(TOut value, CancellationToken cancellationToken = default) =>
|
|
85
|
+
_loop.SendAsync(JsonSerializer.Serialize(value, _write), cancellationToken);
|
|
67
86
|
|
|
68
87
|
/// <summary>Sends <paramref name="text"/> as it is over the open transport (an SSE or long-poll one POSTs it).</summary>
|
|
69
88
|
public Task SendAsync(string text, CancellationToken cancellationToken = default) => _loop.SendAsync(text, cancellationToken);
|
|
70
89
|
|
|
71
|
-
/// <summary>Sends <paramref name="value"/> as its JSON text.</summary>
|
|
72
|
-
public Task SendAsync<TValue>(TValue value, JsonTypeInfo<TValue> info, CancellationToken cancellationToken = default) =>
|
|
73
|
-
_loop.SendAsync(JsonSerializer.Serialize(value, info), cancellationToken);
|
|
74
|
-
|
|
75
90
|
/// <summary>Closes the open transport and ends a pending read in any task with no message.</summary>
|
|
76
91
|
public Task CloseAsync() => _loop.CloseAsync();
|
|
77
92
|
|
|
78
93
|
/// <summary>Closes the connection, as <see cref="CloseAsync"/> does.</summary>
|
|
79
94
|
public ValueTask DisposeAsync() => new(CloseAsync());
|
|
80
95
|
|
|
81
|
-
internal ResumableConnection<
|
|
96
|
+
internal ResumableConnection<TIn, TOut> Bound(CancellationToken call)
|
|
82
97
|
{
|
|
83
98
|
_loop.Bind(call);
|
|
84
99
|
return this;
|
|
85
100
|
}
|
|
86
101
|
|
|
87
|
-
private async IAsyncEnumerator<
|
|
102
|
+
private async IAsyncEnumerator<TIn> MessagesAsync(CancellationToken token)
|
|
88
103
|
{
|
|
89
104
|
while (await _loop.NextAsync(token).ConfigureAwait(false) is { } message)
|
|
90
105
|
{
|
|
91
|
-
|
|
106
|
+
var value = Deliver(message);
|
|
107
|
+
TypedWebSocket.Fire(Message, value);
|
|
108
|
+
yield return value;
|
|
92
109
|
}
|
|
93
110
|
}
|
|
94
111
|
|
|
95
|
-
/* the message as JSON, else as a JSON string of its text; the cursor advanced before it decodes */
|
|
96
|
-
private
|
|
112
|
+
/* the message as JSON, else (unless strict) as a JSON string of its text; the cursor advanced before it decodes */
|
|
113
|
+
private TIn Deliver(TransportMessage message)
|
|
97
114
|
{
|
|
98
|
-
JsonElement payload;
|
|
115
|
+
JsonElement payload = default;
|
|
116
|
+
JsonException? malformed = null;
|
|
99
117
|
try
|
|
100
118
|
{
|
|
101
119
|
using var document = JsonDocument.Parse(message.Text);
|
|
102
120
|
payload = document.RootElement.Clone();
|
|
103
121
|
}
|
|
122
|
+
catch (JsonException e) when (Strict)
|
|
123
|
+
{
|
|
124
|
+
malformed = e;
|
|
125
|
+
}
|
|
104
126
|
catch (JsonException)
|
|
105
127
|
{
|
|
106
128
|
payload = JsonSerializer.SerializeToElement(message.Text, Arg.StringInfo);
|
|
107
129
|
}
|
|
108
130
|
Options.Advance(message.Id, payload);
|
|
131
|
+
if (malformed is not null)
|
|
132
|
+
{
|
|
133
|
+
throw new DecodeException($"realtime message is not valid JSON: {malformed.Message}", malformed);
|
|
134
|
+
}
|
|
135
|
+
var what = Strict ? "realtime message" : "a message";
|
|
109
136
|
try
|
|
110
137
|
{
|
|
111
|
-
return JsonSerializer.Deserialize(payload,
|
|
138
|
+
return JsonSerializer.Deserialize(payload, _read) ?? throw new DecodeException($"{what} does not decode: it is null");
|
|
112
139
|
}
|
|
113
140
|
catch (JsonException e)
|
|
114
141
|
{
|
|
115
|
-
throw new DecodeException($"
|
|
142
|
+
throw new DecodeException($"{what} does not decode: {e.Message}", e);
|
|
116
143
|
}
|
|
117
144
|
}
|
|
118
145
|
}
|
|
@@ -10,7 +10,7 @@ using System.Threading.Tasks;
|
|
|
10
10
|
|
|
11
11
|
namespace Http.Runtime;
|
|
12
12
|
|
|
13
|
-
/* ResumableConnection<
|
|
13
|
+
/* ResumableConnection<TIn, TOut>'s loop (Python's realtime.py), its behavior documented there */
|
|
14
14
|
internal sealed class RealtimeLoop(IReadOnlyList<ITransportAdapter> adapters, TransportOptions options, string url)
|
|
15
15
|
{
|
|
16
16
|
public static readonly TimeSpan OpenLimit = TimeSpan.FromSeconds(30);
|
|
@@ -26,11 +26,11 @@ public sealed class SseAdapter : ITransportAdapter, IDialed
|
|
|
26
26
|
var x = _dial.Stream(options);
|
|
27
27
|
var live = await x.OpenAsync(cancellationToken).ConfigureAwait(false);
|
|
28
28
|
_dial.Opened(x.Raw!);
|
|
29
|
-
return new SseConnection(new EventStream<string
|
|
29
|
+
return new SseConnection(new EventStream<SseEvent<string>>(live, e => e, CancellationToken.None), _dial);
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
internal sealed class SseConnection(EventStream<string
|
|
33
|
+
internal sealed class SseConnection(EventStream<SseEvent<string>> stream, Dial dial) : ITransportConnection
|
|
34
34
|
{
|
|
35
35
|
private IAsyncEnumerator<SseEvent<string>>? _events;
|
|
36
36
|
|
|
@@ -38,7 +38,7 @@ internal sealed class SseConnection(EventStream<string> stream, Dial dial) : ITr
|
|
|
38
38
|
public async Task<TransportMessage?> ReceiveAsync(CancellationToken cancellationToken)
|
|
39
39
|
{
|
|
40
40
|
_events ??= stream.GetAsyncEnumerator();
|
|
41
|
-
using var ended = cancellationToken.Register(static stream => ((EventStream<string
|
|
41
|
+
using var ended = cancellationToken.Register(static stream => ((EventStream<SseEvent<string>>)stream!).DisposeAsync(), stream);
|
|
42
42
|
if (!await _events.MoveNextAsync().ConfigureAwait(false))
|
|
43
43
|
{
|
|
44
44
|
cancellationToken.ThrowIfCancellationRequested();
|
|
@@ -283,7 +283,7 @@ public sealed class TypedWebSocket : IAsyncDisposable
|
|
|
283
283
|
return reason[..end];
|
|
284
284
|
}
|
|
285
285
|
|
|
286
|
-
|
|
286
|
+
internal static void Fire<T>(Action<T>? handlers, T value)
|
|
287
287
|
{
|
|
288
288
|
foreach (var handler in handlers?.GetInvocationList() ?? [])
|
|
289
289
|
{
|
|
@@ -2,12 +2,14 @@
|
|
|
2
2
|
using System;
|
|
3
3
|
using System.Collections.Generic;
|
|
4
4
|
using System.IO;
|
|
5
|
+
using System.IO.Compression;
|
|
5
6
|
using System.Linq;
|
|
6
7
|
using System.Net;
|
|
7
8
|
using System.Net.Http;
|
|
8
9
|
using System.Net.WebSockets;
|
|
9
10
|
using System.Security.Cryptography;
|
|
10
11
|
using System.Text;
|
|
12
|
+
using System.Text.Json.Serialization.Metadata;
|
|
11
13
|
using System.Threading;
|
|
12
14
|
using System.Threading.Tasks;
|
|
13
15
|
|
|
@@ -18,6 +20,10 @@ internal sealed partial class Transport
|
|
|
18
20
|
public async Task<TypedWebSocket> SocketAsync(Operation op, Call call, IReadOnlyList<string>? protocols, string? reconnectToken, CancellationToken cancellationToken) =>
|
|
19
21
|
(await WsDial.DialAsync(this, new Exchange(this, op, call with { Query = [.. call.Query, Arg.Text("reconnect_token", reconnectToken)] }, stream: true), protocols ?? [], cancellationToken).ConfigureAwait(false))
|
|
20
22
|
.Bound(cancellationToken);
|
|
23
|
+
|
|
24
|
+
/* a socket whose messages are declared: read as TIn, sent as TOut */
|
|
25
|
+
public async Task<TypedWebSocket<TIn, TOut>> TypedSocketAsync<TIn, TOut>(Operation op, Call call, IReadOnlyList<string>? protocols, string? reconnectToken, JsonTypeInfo<TIn> read, JsonTypeInfo<TOut> write, CancellationToken cancellationToken) =>
|
|
26
|
+
new(await SocketAsync(op, call, protocols, reconnectToken, cancellationToken).ConfigureAwait(false), read, write);
|
|
21
27
|
}
|
|
22
28
|
|
|
23
29
|
internal static class WsDial
|
|
@@ -42,7 +48,7 @@ internal static class WsDial
|
|
|
42
48
|
throw new ApiConnectionException($"the WebSocket handshake failed: {refusal}");
|
|
43
49
|
}
|
|
44
50
|
x.Raw?.Fill(101, headers, [], SocketUrl(url));
|
|
45
|
-
var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
|
51
|
+
var stream = Connection(await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false));
|
|
46
52
|
var options = new WebSocketCreationOptions { SubProtocol = chosen, KeepAliveInterval = KeepAlive, KeepAliveTimeout = KeepAlive };
|
|
47
53
|
return new TypedWebSocket(WebSocket.CreateFromStream(stream, options), chosen, response);
|
|
48
54
|
}
|
|
@@ -53,6 +59,18 @@ internal static class WsDial
|
|
|
53
59
|
}
|
|
54
60
|
}
|
|
55
61
|
|
|
62
|
+
/*
|
|
63
|
+
* a 101's content is the connection, no coded body: a handler's decoder over it for a Content-Encoding is
|
|
64
|
+
* read-only, so the dial takes what lies beneath; .NET's deflate decoder exposes nothing beneath it
|
|
65
|
+
*/
|
|
66
|
+
private static Stream Connection(Stream stream) => stream switch
|
|
67
|
+
{
|
|
68
|
+
GZipStream gzip => gzip.BaseStream,
|
|
69
|
+
BrotliStream brotli => brotli.BaseStream,
|
|
70
|
+
{ CanWrite: false } => throw new ApiConnectionException("the WebSocket handshake failed: the handler decoded the 101's content, so the connection is read-only"),
|
|
71
|
+
_ => stream,
|
|
72
|
+
};
|
|
73
|
+
|
|
56
74
|
private static Uri SocketUrl(Uri url) => new UriBuilder(url) { Scheme = url.Scheme == Uri.UriSchemeHttps ? "wss" : "ws" }.Uri;
|
|
57
75
|
|
|
58
76
|
private static HttpRequestMessage Request(Uri url, Dictionary<string, string> headers, string key, IReadOnlyList<string> protocols)
|
|
@@ -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
|
+
}
|