@workerstack/clients 1.0.0-rc.30 → 1.0.0-rc.31

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 (115) hide show
  1. package/README.md +175 -21
  2. package/bin/clients.js +5 -6
  3. package/bin/installgen.js +5 -9
  4. package/dist/cli.js +3 -1
  5. package/dist/emit/csharp/sdk-method.d.ts +18 -1
  6. package/dist/emit/csharp/sdk-method.js +14 -3
  7. package/dist/emit/csharp/sdk.js +4 -1
  8. package/dist/emit/go/sdk-method.d.ts +9 -0
  9. package/dist/emit/go/sdk-method.js +10 -1
  10. package/dist/emit/go/sdk.js +4 -3
  11. package/dist/emit/java/sdk-client.js +1 -0
  12. package/dist/emit/java/sdk-op.d.ts +6 -1
  13. package/dist/emit/java/sdk-op.js +15 -3
  14. package/dist/emit/java/sdk.js +7 -1
  15. package/dist/emit/python/sdk-method.d.ts +11 -0
  16. package/dist/emit/python/sdk-method.js +15 -0
  17. package/dist/emit/python/sdk.js +5 -1
  18. package/dist/emit/rust/sdk-method.d.ts +12 -1
  19. package/dist/emit/rust/sdk-method.js +10 -2
  20. package/dist/emit/rust/sdk.js +4 -1
  21. package/dist/emit/ts/http.d.ts +8 -0
  22. package/dist/emit/ts/http.js +48 -3
  23. package/dist/emit/ts/package.js +1 -0
  24. package/dist/emit/ts/sdk-types-preamble.js +10 -2
  25. package/dist/emit/ts/sdk-types.d.ts +0 -5
  26. package/dist/emit/ts/sdk-types.js +52 -8
  27. package/dist/emit/ts/sdk.d.ts +3 -1
  28. package/dist/emit/ts/sdk.js +40 -8
  29. package/dist/emit/ts/service-map.d.ts +5 -0
  30. package/dist/emit/ts/service-map.js +10 -1
  31. package/dist/emit/ts/single-flight-text.d.ts +3 -0
  32. package/dist/emit/ts/single-flight-text.js +38 -0
  33. package/dist/emit/ts/tanstack-query.d.ts +3 -2
  34. package/dist/emit/ts/tanstack-query.js +54 -29
  35. package/dist/gen/process.js +2 -1
  36. package/dist/gen/switch-on.constants.d.ts +2 -0
  37. package/dist/gen/switch-on.constants.js +2 -0
  38. package/dist/gen/targets.d.ts +4 -3
  39. package/dist/gen/targets.js +4 -3
  40. package/dist/ir/invalidate-reads.d.ts +17 -0
  41. package/dist/ir/invalidate-reads.js +104 -0
  42. package/dist/ir/load.d.ts +10 -0
  43. package/dist/ir/load.js +62 -14
  44. package/dist/ir/read-method.constants.d.ts +2 -0
  45. package/dist/ir/read-method.constants.js +2 -0
  46. package/dist/release/load.js +1 -1
  47. package/dist/runtime/csharp/Config.cs +9 -1
  48. package/dist/runtime/csharp/Exchange.cs +56 -4
  49. package/dist/runtime/csharp/Hooks.cs +9 -0
  50. package/dist/runtime/csharp/Operation.cs +6 -1
  51. package/dist/runtime/csharp/WsDial.cs +3 -1
  52. package/dist/runtime/go/config.go +5 -0
  53. package/dist/runtime/go/hooks.go +70 -0
  54. package/dist/runtime/go/request.go +6 -2
  55. package/dist/runtime/go/stream.go +4 -1
  56. package/dist/runtime/go/ws.go +3 -1
  57. package/dist/runtime/java/ClientConfig.java +11 -0
  58. package/dist/runtime/java/Flight.java +2 -12
  59. package/dist/runtime/java/Hooks.java +45 -0
  60. package/dist/runtime/java/InvalidateEvent.java +10 -0
  61. package/dist/runtime/java/InvalidateHook.java +12 -0
  62. package/dist/runtime/java/InvalidateTarget.java +7 -0
  63. package/dist/runtime/java/Operation.java +23 -3
  64. package/dist/runtime/java/Realtime.java +3 -1
  65. package/dist/runtime/java/WsDial.java +3 -0
  66. package/dist/runtime/python/config.py +8 -2
  67. package/dist/runtime/python/exchange.py +3 -1
  68. package/dist/runtime/python/hooks.py +110 -5
  69. package/dist/runtime/python/operation.py +2 -0
  70. package/dist/runtime/python/send_async.py +14 -2
  71. package/dist/runtime/python/send_sync.py +4 -2
  72. package/dist/runtime/python/ws.py +5 -1
  73. package/dist/runtime/rust/config.rs +6 -1
  74. package/dist/runtime/rust/exchange.rs +15 -3
  75. package/dist/runtime/rust/hooks.rs +127 -2
  76. package/dist/runtime/rust/log.rs +11 -3
  77. package/dist/runtime/rust/request.rs +17 -0
  78. package/dist/runtime/rust/ws.rs +9 -1
  79. package/dist/runtime/ts/config.ts +69 -0
  80. package/dist/runtime/ts/http.ts +12 -10
  81. package/dist/runtime/ts/request.ts +2 -0
  82. package/dist/runtime/ts/response.ts +7 -0
  83. package/dist/runtime/ts/sdk-invalidate.ts +82 -0
  84. package/dist/runtime/ts/sdk-single-flight.constants.ts +25 -0
  85. package/dist/runtime/ts/sdk-single-flight.ts +203 -0
  86. package/dist/runtime/ts/sdk-sse.ts +5 -1
  87. package/dist/runtime/ts/sdk-ws.ts +9 -3
  88. package/dist/runtime/ts/sdk.ts +55 -31
  89. package/dist/runtime/ts/single-flight-batch.ts +184 -0
  90. package/dist/runtime/ts/single-flight-body.ts +59 -0
  91. package/dist/runtime/ts/single-flight-run.ts +160 -0
  92. package/dist/runtime/ts/single-flight.constants.ts +31 -0
  93. package/dist/runtime/ts/single-flight.ts +158 -0
  94. package/dist/runtime/ts-tanstack-query/invalidate.ts +96 -92
  95. package/dist/runtime/ts-tanstack-query/query.ts +140 -168
  96. package/package.json +10 -18
  97. package/references/INDEX.md +31 -0
  98. package/references/cli.md +33 -0
  99. package/references/configuring.md +29 -0
  100. package/references/documentation.md +15 -0
  101. package/references/errors.md +23 -0
  102. package/references/flags.md +104 -0
  103. package/references/gates.md +46 -0
  104. package/references/generate.md +29 -0
  105. package/references/install-scripts.md +28 -0
  106. package/references/install.md +38 -0
  107. package/references/license.md +8 -0
  108. package/references/mcp.md +76 -0
  109. package/references/output.md +45 -0
  110. package/references/overview.md +14 -0
  111. package/references/release-tooling.md +34 -0
  112. package/references/release.md +305 -0
  113. package/references/sdks.md +393 -0
  114. package/references/start.md +22 -0
  115. package/references/tdd.md +16 -0
@@ -3,8 +3,10 @@
3
3
  package sdk
4
4
 
5
5
  import (
6
+ "context"
6
7
  "fmt"
7
8
  "net/http"
9
+ "time"
8
10
  )
9
11
 
10
12
  // RequestContext is what each OnRequest hook sees, in declaration order. A hook may change
@@ -51,3 +53,71 @@ func (m *RequestMeta) stale() (string, bool, []string) {
51
53
  }
52
54
  return m.Selector, m.IsStale, m.InvalidatedBy
53
55
  }
56
+
57
+ // InvalidateTarget is one read a write made stale: its operationId, and the write's values for the
58
+ // read's own path params. A param the write lacks, or holds as "", "." or "..", is left out.
59
+ type InvalidateTarget struct {
60
+ OperationID string
61
+ Params map[string]string
62
+ }
63
+
64
+ // InvalidateEvent is what each OnInvalidate hook sees after a successful write: the write's
65
+ // operationId and every read it made stale.
66
+ type InvalidateEvent struct {
67
+ By string
68
+ Targets []InvalidateTarget
69
+ }
70
+
71
+ // staleRead is one read a write makes stale, as the emitter resolved it: its operationId and its
72
+ // own path params.
73
+ type staleRead struct {
74
+ op string
75
+ params []string
76
+ }
77
+
78
+ // invalidated calls each OnInvalidate hook in order, each after the last returned, with what c
79
+ // made stale; none when c makes nothing stale. A hook's error or panic goes to OnLog as an error
80
+ // entry, never to the call, and is dropped without OnLog; the next hook still runs.
81
+ func invalidated(ctx context.Context, cfg Config, c *call) {
82
+ if len(c.reads) == 0 || len(cfg.OnInvalidate) == 0 {
83
+ return
84
+ }
85
+ event := InvalidateEvent{By: c.by, Targets: make([]InvalidateTarget, len(c.reads))}
86
+ for i, read := range c.reads {
87
+ known := map[string]string{}
88
+ for _, name := range read.params {
89
+ if v := c.params[name]; v != "" && v != "." && v != ".." {
90
+ known[name] = v
91
+ }
92
+ }
93
+ event.Targets[i] = InvalidateTarget{OperationID: read.op, Params: known}
94
+ }
95
+ for _, hook := range cfg.OnInvalidate {
96
+ start := time.Now()
97
+ if err := runInvalidateHook(ctx, hook, event); err != nil {
98
+ emitLog(cfg, errorEntry(c.operation, start, err))
99
+ }
100
+ }
101
+ }
102
+
103
+ // runInvalidateHook calls hook, its panic recovered as its error (wrapping a panicked error), so
104
+ // a faulty hook neither crashes a detached open nor changes the write's result.
105
+ func runInvalidateHook(ctx context.Context, hook func(context.Context, InvalidateEvent) error, event InvalidateEvent) (err error) {
106
+ defer func() {
107
+ switch r := recover().(type) {
108
+ case nil:
109
+ case error:
110
+ err = fmt.Errorf("httpsdk: OnInvalidate hook panicked: %w", r)
111
+ default:
112
+ err = fmt.Errorf("httpsdk: OnInvalidate hook panicked: %v", r)
113
+ }
114
+ }()
115
+ return hook(ctx, event)
116
+ }
117
+
118
+ // opened settles a stream or socket once it opened: its targets marked stale, and the
119
+ // OnInvalidate hooks called detached, so the open never waits on them nor ends their context.
120
+ func opened(ctx context.Context, cfg Config, c *call) {
121
+ c.stale.settle(c)
122
+ go invalidated(context.WithoutCancel(ctx), cfg, c)
123
+ }
@@ -26,6 +26,8 @@ type call struct {
26
26
  invalidates []string // declared invalidation targets, `METHOD /template`
27
27
  params map[string]string // path params, to expand templated targets
28
28
  meta *RequestMeta
29
+ by string // the operationId an InvalidateEvent names
30
+ reads []staleRead // the reads a success makes stale, for OnInvalidate
29
31
  }
30
32
 
31
33
  // requestResult is a buffered answer: its body after the OnResponse hooks, the response, and
@@ -50,8 +52,8 @@ type exchange struct {
50
52
  var ErrResponseTooLarge = errors.New("httpsdk: response body exceeds MaxResponseBytes")
51
53
 
52
54
  // doRequest sends c and buffers its answer (run), honoring the call's timeout and the stale
53
- // tracker. A ctx already done sends nothing: OnLog sees only its error. A 2xx past the cap is a
54
- // *DecodeError.
55
+ // tracker, then runs the OnInvalidate hooks with the caller's ctx. A ctx already done sends
56
+ // nothing: OnLog sees only its error. A 2xx past the cap is a *DecodeError.
55
57
  func doRequest(ctx context.Context, cfg Config, c *call, opts []RequestOption) (*requestResult, error) {
56
58
  x := &exchange{cfg: cfg, rc: newRequestConfig(cfg, opts), c: c}
57
59
  if ctx.Err() != nil {
@@ -59,6 +61,7 @@ func doRequest(ctx context.Context, cfg Config, c *call, opts []RequestOption) (
59
61
  emitLog(cfg, errorEntry(c.operation, time.Now(), err))
60
62
  return nil, err
61
63
  }
64
+ caller := ctx
62
65
  if x.rc.timeout > 0 {
63
66
  var cancel context.CancelFunc
64
67
  ctx, cancel = context.WithTimeout(ctx, x.rc.timeout)
@@ -70,6 +73,7 @@ func doRequest(ctx context.Context, cfg Config, c *call, opts []RequestOption) (
70
73
  return nil, err
71
74
  }
72
75
  c.stale.settle(c)
76
+ invalidated(caller, cfg, c)
73
77
  if result.over {
74
78
  return nil, &DecodeError{result.resp, ErrResponseTooLarge}
75
79
  }
@@ -14,7 +14,8 @@ import (
14
14
  )
15
15
 
16
16
  // openStream sends a streaming request through every call's exchange (run), the call's timeout
17
- // bounding it up to the headers, never the body. A non-2xx is a typed error. The caller owns the body.
17
+ // bounding it up to the headers, never the body. A non-2xx is a typed error; a 2xx settles the call
18
+ // (opened). The caller owns the body.
18
19
  func openStream(ctx context.Context, cfg Config, c *call, opts []RequestOption) (*http.Response, error) {
19
20
  if c.headers == nil {
20
21
  c.headers = map[string]string{}
@@ -28,6 +29,7 @@ func openStream(ctx context.Context, cfg Config, c *call, opts []RequestOption)
28
29
  if err != nil {
29
30
  return nil, err
30
31
  }
32
+ opened(ctx, cfg, c)
31
33
  return result.resp, nil
32
34
  }
33
35
  open, cancel := context.WithCancelCause(ctx)
@@ -38,6 +40,7 @@ func openStream(ctx context.Context, cfg Config, c *call, opts []RequestOption)
38
40
  cancel(nil)
39
41
  return nil, err
40
42
  }
43
+ opened(ctx, cfg, c)
41
44
  result.resp.Body = releasing{result.resp.Body, cancel}
42
45
  return result.resp, nil
43
46
  }
@@ -90,7 +90,8 @@ func dialWebSocket[In, Out any](ctx context.Context, cfg Config, c *call, read f
90
90
  return &TypedWebSocket[In, Out]{conn: conn, stop: keepAlive(conn, cfg.WSKeepalive), read: read, write: write}, nil
91
91
  }
92
92
 
93
- // dialSocket opens the call's WebSocket as the client calls; an error status is its *APIError.
93
+ // dialSocket opens the call's WebSocket as the client calls, settling it once open (opened); an
94
+ // error status is its *APIError.
94
95
  func dialSocket(ctx context.Context, cfg Config, c *call, opts []RequestOption) (*websocket.Conn, error) {
95
96
  rc := newRequestConfig(cfg, opts)
96
97
  u, err := buildURL(rc.baseURL, c.path, c.query)
@@ -115,6 +116,7 @@ func dialSocket(ctx context.Context, cfg Config, c *call, opts []RequestOption)
115
116
  }
116
117
  rc.deliver(resp, nil)
117
118
  conn.SetReadLimit(defaultWSReadLimit)
119
+ opened(ctx, cfg, c)
118
120
  return conn, nil
119
121
  }
120
122
 
@@ -24,6 +24,7 @@ final class ClientConfig {
24
24
  private final List<RequestHook> onRequest;
25
25
  private final List<ResponseHook> onResponse;
26
26
  private final Supplier<String> onAuthExpired;
27
+ private final List<InvalidateHook> onInvalidate;
27
28
  private final Consumer<LogEntry> onLog;
28
29
  private final RedirectPolicy redirect;
29
30
  private final long maxResponseBytes;
@@ -39,6 +40,7 @@ final class ClientConfig {
39
40
  this.onRequest = List.copyOf(builder.onRequest);
40
41
  this.onResponse = List.copyOf(builder.onResponse);
41
42
  this.onAuthExpired = builder.onAuthExpired;
43
+ this.onInvalidate = List.copyOf(builder.onInvalidate);
42
44
  this.onLog = builder.onLog;
43
45
  this.redirect = builder.redirect;
44
46
  this.maxResponseBytes = builder.maxResponseBytes;
@@ -100,6 +102,10 @@ final class ClientConfig {
100
102
  return onAuthExpired;
101
103
  }
102
104
 
105
+ List<InvalidateHook> onInvalidate() {
106
+ return onInvalidate;
107
+ }
108
+
103
109
  Consumer<LogEntry> onLog() {
104
110
  return onLog;
105
111
  }
@@ -135,6 +141,7 @@ final class ClientConfig {
135
141
  private final List<RequestHook> onRequest = new ArrayList<>();
136
142
  private final List<ResponseHook> onResponse = new ArrayList<>();
137
143
  private Supplier<String> onAuthExpired;
144
+ private final List<InvalidateHook> onInvalidate = new ArrayList<>();
138
145
  private Consumer<LogEntry> onLog;
139
146
  private String token;
140
147
  private String authHeader;
@@ -189,6 +196,10 @@ final class ClientConfig {
189
196
  this.onAuthExpired = refresh;
190
197
  }
191
198
 
199
+ void onInvalidate(InvalidateHook hook) {
200
+ this.onInvalidate.add(hook);
201
+ }
202
+
192
203
  void onLog(Consumer<LogEntry> log) {
193
204
  this.onLog = log;
194
205
  }
@@ -285,22 +285,12 @@ final class Flight {
285
285
  log.failed(error, error.status());
286
286
  }
287
287
  if (hop.status() >= 200 && hop.status() < 300) {
288
- exchange.stale().settle(meta, op.invalidates(), pathValues());
288
+ exchange.stale().settle(meta, op.invalidates(), op.values(call.path()));
289
+ Hooks.onInvalidate(config, op, call.path(), stream);
289
290
  if (over) {
290
291
  throw new DecodeException(Decode.exceeds(config.maxResponseBytes()), null);
291
292
  }
292
293
  }
293
294
  return new Answer(route, raw, error, hop.body());
294
295
  }
295
-
296
- /**
297
- * The call's path values by their template names: what a stale target's placeholders fill from.
298
- */
299
- private Map<String, String> pathValues() {
300
- Map<String, String> values = new TreeMap<>();
301
- for (int i = 0; i < op.names().length; i++) {
302
- values.put(op.names()[i], call.path()[i]);
303
- }
304
- return values;
305
- }
306
296
  }
@@ -1,8 +1,12 @@
1
1
  // @generated by clients. DO NOT EDIT.
2
2
  package http.runtime;
3
3
 
4
+ import java.util.ArrayList;
5
+ import java.util.LinkedHashMap;
4
6
  import java.util.List;
7
+ import java.util.Map;
5
8
  import java.util.concurrent.CancellationException;
9
+ import java.util.concurrent.CompletableFuture;
6
10
 
7
11
  /**
8
12
  * Runs the hooks in order; a hook's own failure is the call's {@link HookException}, an SDK error
@@ -19,6 +23,47 @@ final class Hooks {
19
23
  run(hooks, hook -> hook.apply(context));
20
24
  }
21
25
 
26
+ /**
27
+ * A successful write's onInvalidate hooks, in order, each after the last, a throw logged and the
28
+ * next still run; none when {@code op} makes nothing stale. A stream's or socket's open runs them
29
+ * on the common pool, never waiting.
30
+ */
31
+ static void onInvalidate(ClientConfig config, Operation op, String[] path, boolean detached) {
32
+ List<InvalidateHook> hooks = config.onInvalidate();
33
+ if (op.reads().length == 0 || hooks.isEmpty()) {
34
+ return;
35
+ }
36
+ Map<String, String> values = op.values(path);
37
+ List<InvalidateTarget> targets = new ArrayList<>();
38
+ for (Operation.Read read : op.reads()) {
39
+ Map<String, String> known = new LinkedHashMap<>();
40
+ for (String name : read.params()) {
41
+ String value = values.get(name);
42
+ if (value != null && !value.isEmpty() && !".".equals(value) && !"..".equals(value)) {
43
+ known.put(name, value);
44
+ }
45
+ }
46
+ targets.add(new InvalidateTarget(read.op(), Map.copyOf(known)));
47
+ }
48
+ InvalidateEvent event = new InvalidateEvent(op.by(), List.copyOf(targets));
49
+ CallLog log = new CallLog(config.onLog(), op.route());
50
+ Runnable run =
51
+ () -> {
52
+ for (InvalidateHook hook : hooks) {
53
+ try {
54
+ hook.apply(event);
55
+ } catch (java.lang.Exception e) {
56
+ log.failed(e, null);
57
+ }
58
+ }
59
+ };
60
+ if (detached) {
61
+ CompletableFuture.runAsync(run);
62
+ } else {
63
+ run.run();
64
+ }
65
+ }
66
+
22
67
  /**
23
68
  * The error a failed {@code label} throws: an SDK error or a cancellation as it is, any other
24
69
  * failure wrapped as the call's {@link HookException}.
@@ -0,0 +1,10 @@
1
+ // @generated by clients. DO NOT EDIT.
2
+ package http.runtime;
3
+
4
+ import java.util.List;
5
+
6
+ /**
7
+ * What each {@link InvalidateHook} sees after a successful write: the write's operationId, and
8
+ * every read its {@code x-invalidate} made stale.
9
+ */
10
+ public record InvalidateEvent(String by, List<InvalidateTarget> targets) {}
@@ -0,0 +1,12 @@
1
+ // @generated by clients. DO NOT EDIT.
2
+ package http.runtime;
3
+
4
+ /**
5
+ * Runs once per successful write with what it made stale; a throw goes to the log as an error
6
+ * entry, never to the call.
7
+ */
8
+ @FunctionalInterface
9
+ public interface InvalidateHook {
10
+ /** Told of {@code event}. */
11
+ void apply(InvalidateEvent event) throws java.lang.Exception;
12
+ }
@@ -0,0 +1,7 @@
1
+ // @generated by clients. DO NOT EDIT.
2
+ package http.runtime;
3
+
4
+ import java.util.Map;
5
+
6
+ /** One read a write made stale: its operationId, and the write's values for its path params. */
7
+ public record InvalidateTarget(String operationId, Map<String, String> params) {}
@@ -1,17 +1,37 @@
1
1
  // @generated by clients. DO NOT EDIT.
2
2
  package http.runtime;
3
3
 
4
- /** One operation's fixed description: its path params by spec name in path order. */
4
+ import java.util.Map;
5
+ import java.util.TreeMap;
6
+
7
+ /**
8
+ * One operation's fixed description: its path params by spec name in path order; a write's
9
+ * operationId and the reads its success makes stale, for onInvalidate.
10
+ */
5
11
  record Operation(
6
12
  String method,
7
13
  String template,
8
14
  String[] names,
9
15
  String accept,
10
16
  boolean idempotent,
11
- String[] invalidates) {
17
+ String[] invalidates,
18
+ String by,
19
+ Read[] reads) {
20
+ /** One read a write makes stale, as the generator resolved it: its operationId and params. */
21
+ record Read(String op, String[] params) {}
22
+
12
23
  /** An operation with no x-invalidate targets. */
13
24
  Operation(String method, String template, String[] names, String accept, boolean idempotent) {
14
- this(method, template, names, accept, idempotent, new String[0]);
25
+ this(method, template, names, accept, idempotent, new String[0], null, new Read[0]);
26
+ }
27
+
28
+ /** The call's path values by their template names: what a stale target's placeholders fill. */
29
+ Map<String, String> values(String[] path) {
30
+ Map<String, String> values = new TreeMap<>();
31
+ for (int i = 0; i < names.length; i++) {
32
+ values.put(names[i], path[i]);
33
+ }
34
+ return values;
15
35
  }
16
36
 
17
37
  /** The route as the log and the errors name it: {@code METHOD /template}. */
@@ -109,7 +109,9 @@ final class Realtime {
109
109
  op.names(),
110
110
  "text/event-stream",
111
111
  op.idempotent(),
112
- op.invalidates());
112
+ op.invalidates(),
113
+ op.by(),
114
+ op.reads());
113
115
  Call at =
114
116
  new Call(
115
117
  call.path(),
@@ -72,6 +72,9 @@ final class WsDial {
72
72
  if (options.raw() != null) {
73
73
  options.raw().fill(101, Map.of(), new byte[0], url);
74
74
  }
75
+ StaleTracker stale = exchange.stale();
76
+ stale.settle(stale.begin(op.method(), path), op.invalidates(), op.values(call.path()));
77
+ Hooks.onInvalidate(config, op, call.path(), true);
75
78
  return new TypedWebSocket<>(socket, read);
76
79
  }
77
80
 
@@ -15,7 +15,7 @@ import httpx2
15
15
  from .errors import ConfigError
16
16
 
17
17
  if TYPE_CHECKING:
18
- from .hooks import RequestContext, ResponseContext
18
+ from .hooks import InvalidateEvent, RequestContext, ResponseContext
19
19
  from .log import LogEntry
20
20
 
21
21
  __all__ = ["ClientConfig", "InvalidationConfig", "RawResponse", "RequestOptions"]
@@ -41,7 +41,11 @@ class ClientConfig:
41
41
  WebSocket's ping interval and pong wait. A redirect to another origin is followed only under ``"follow"``, and
42
42
  never carries credentials, a body, or what an ``http_client`` adds. ``SDK`` runs the ``*_sync``
43
43
  hooks and a plain ``on_auth_expired``; ``AsyncSDK`` runs the others, and coroutine functions too.
44
- Either refuses, at construction, a hook it would not run.
44
+ Either refuses, at construction, a hook it would not run. ``on_invalidate`` (``on_invalidate_sync``)
45
+ runs once per call, after the final answer (an auth refresh included), for a 2xx write, its body
46
+ decoded or not, with the reads it made stale; the call returns after the last hook, so a hung one
47
+ holds it past ``timeout``. A stream's or socket's open runs them detached, waiting on none. A hook
48
+ that raises is an ``on_log`` error entry (dropped without ``on_log``), never the call's error.
45
49
  """
46
50
 
47
51
  base_url: str = ""
@@ -60,6 +64,8 @@ class ClientConfig:
60
64
  on_response: Sequence[Callable[[ResponseContext], Awaitable[None] | None]] = ()
61
65
  on_request_sync: Sequence[Callable[[RequestContext], None]] = ()
62
66
  on_response_sync: Sequence[Callable[[ResponseContext], None]] = ()
67
+ on_invalidate: Sequence[Callable[[InvalidateEvent], Awaitable[None] | None]] = ()
68
+ on_invalidate_sync: Sequence[Callable[[InvalidateEvent], None]] = ()
63
69
  on_log: Callable[[LogEntry], None] | None = None
64
70
  on_auth_expired: Callable[[], Awaitable[str | None] | str | None] | None = None
65
71
  invalidation: InvalidationConfig | None = None
@@ -29,7 +29,7 @@ from .errors import (
29
29
  loads,
30
30
  status_error,
31
31
  )
32
- from .hooks import RequestContext, ResponseContext
32
+ from .hooks import InvalidateEvent, RequestContext, ResponseContext, invalidation
33
33
  from .log import CallLog
34
34
  from .operation import Operation
35
35
  from .path import expand
@@ -112,6 +112,7 @@ class Exchange:
112
112
  self.hops = 0
113
113
  self.raw = options.get("raw") or RawResponse()
114
114
  self.failure: APIStatusError | None = None
115
+ self.invalidated: InvalidateEvent | None = None
115
116
 
116
117
  def check(self) -> float | None:
117
118
  cancel = self.options.get("cancel")
@@ -226,6 +227,7 @@ class Exchange:
226
227
  self.log.answered(answer.status)
227
228
  if 200 <= answer.status < 300:
228
229
  self.core.stale.settle(self.meta, self.op.invalidates, self.params)
230
+ self.invalidated = invalidation(self.op, self.params)
229
231
  else:
230
232
  self.failure = failure(answer, self.core)
231
233
  self.log.failed(self.failure)
@@ -1,9 +1,12 @@
1
1
  # @generated by clients. DO NOT EDIT.
2
2
  """The caller's hooks, TypeScript parity: ``on_request`` before each send, ``on_response`` on each
3
- answer, in order, sharing one ``state``; a hook that raises ends the call."""
3
+ answer, in order, sharing one ``state``; a hook that raises ends the call. ``on_invalidate`` once per
4
+ successful write (or stream open), in order, with what it made stale; a hook that raises is logged,
5
+ never the call's error."""
4
6
 
5
7
  from __future__ import annotations
6
8
 
9
+ import asyncio
7
10
  import inspect
8
11
  from collections.abc import Awaitable, Callable, Mapping, Sequence
9
12
  from dataclasses import dataclass, field
@@ -13,8 +16,10 @@ from .errors import ConfigError, HookError, HttpError
13
16
 
14
17
  if TYPE_CHECKING:
15
18
  from .config import ClientConfig
19
+ from .log import CallLog
20
+ from .operation import Operation
16
21
 
17
- __all__ = ["RequestContext", "ResponseContext"]
22
+ __all__ = ["InvalidateEvent", "InvalidateTarget", "RequestContext", "ResponseContext"]
18
23
 
19
24
  C = TypeVar("C")
20
25
 
@@ -49,6 +54,102 @@ class ResponseContext:
49
54
  state: dict[str, Any] = field(default_factory=dict, repr=False)
50
55
 
51
56
 
57
+ @dataclass(frozen=True)
58
+ class InvalidateTarget:
59
+ """One read a write made stale: its operationId, and the write's values for the read's own path
60
+ params; one the write lacks, or holds as ``""``, ``"."`` or ``".."``, is left out."""
61
+
62
+ operation_id: str
63
+ params: Mapping[str, str]
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class InvalidateEvent:
68
+ """What each ``on_invalidate`` hook sees: the write's operationId and every read it made stale."""
69
+
70
+ by: str
71
+ targets: tuple[InvalidateTarget, ...]
72
+
73
+
74
+ # a detached open's hook runs, held until they end so none is garbage-collected mid-run
75
+ DETACHED: set[asyncio.Task[None]] = set()
76
+
77
+ SEGMENTS = ("", ".", "..")
78
+
79
+
80
+ def invalidation(
81
+ op: Operation[object], params: Mapping[str, str]
82
+ ) -> InvalidateEvent | None:
83
+ """What a success of ``op`` with ``params`` made stale; ``None`` when it makes nothing stale."""
84
+ if not op.reads:
85
+ return None
86
+ targets = tuple(
87
+ InvalidateTarget(
88
+ read,
89
+ {n: params[n] for n in names if params.get(n, "") not in SEGMENTS},
90
+ )
91
+ for read, names in op.reads
92
+ )
93
+ return InvalidateEvent(op.by, targets)
94
+
95
+
96
+ class Logged:
97
+ """An ``Exception`` the block raises, swallowed as an ``on_log`` error entry."""
98
+
99
+ def __init__(self, log: CallLog) -> None:
100
+ self.log = log
101
+
102
+ def __enter__(self) -> None:
103
+ pass
104
+
105
+ def __exit__(
106
+ self, kind: object, error: BaseException | None, trace: object
107
+ ) -> bool:
108
+ if isinstance(error, Exception):
109
+ self.log.failed(error)
110
+ return True
111
+ return False
112
+
113
+
114
+ def invalidate_sync(
115
+ hooks: Sequence[Callable[[InvalidateEvent], None]],
116
+ event: InvalidateEvent | None,
117
+ log: CallLog,
118
+ ) -> None:
119
+ if event is None:
120
+ return
121
+ for hook in hooks:
122
+ with Logged(log):
123
+ hook(event)
124
+
125
+
126
+ async def invalidate_async(
127
+ hooks: Sequence[Callable[[InvalidateEvent], Awaitable[None] | None]],
128
+ event: InvalidateEvent | None,
129
+ log: CallLog,
130
+ ) -> None:
131
+ if event is None:
132
+ return
133
+ for hook in hooks:
134
+ with Logged(log):
135
+ result = hook(event)
136
+ if inspect.isawaitable(result):
137
+ await result
138
+
139
+
140
+ def detach(
141
+ hooks: Sequence[Callable[[InvalidateEvent], Awaitable[None] | None]],
142
+ event: InvalidateEvent | None,
143
+ log: CallLog,
144
+ ) -> None:
145
+ """The hooks run as a task the open never awaits; their errors logged as ``invalidate_async``'s."""
146
+ if event is None or not hooks:
147
+ return
148
+ task = asyncio.get_running_loop().create_task(invalidate_async(hooks, event, log))
149
+ DETACHED.add(task)
150
+ task.add_done_callback(DETACHED.discard)
151
+
152
+
52
153
  def wrapped(error: Exception, what: str = "hook") -> HttpError:
53
154
  return error if isinstance(error, HttpError) else HookError(f"{what}: {error}")
54
155
 
@@ -57,13 +158,17 @@ def refuse_hooks(config: ClientConfig, sync: bool) -> None:
57
158
  if sync and (
58
159
  config.on_request
59
160
  or config.on_response
161
+ or config.on_invalidate
60
162
  or inspect.iscoroutinefunction(config.on_auth_expired)
61
163
  ):
62
164
  raise ConfigError(
63
- "SDK runs on_request_sync, on_response_sync and a plain on_auth_expired"
165
+ "SDK runs on_request_sync, on_response_sync, on_invalidate_sync"
166
+ " and a plain on_auth_expired"
64
167
  )
65
- if not sync and (config.on_request_sync or config.on_response_sync):
66
- raise ConfigError("AsyncSDK runs on_request and on_response")
168
+ if not sync and (
169
+ config.on_request_sync or config.on_response_sync or config.on_invalidate_sync
170
+ ):
171
+ raise ConfigError("AsyncSDK runs on_request, on_response and on_invalidate")
67
172
 
68
173
 
69
174
  def run_sync(hooks: Sequence[Callable[[C], None]], context: C) -> None:
@@ -21,6 +21,8 @@ class Operation(Generic[T]):
21
21
  shape: Literal["array", "boolean", "number", "object", "string"] | None = None
22
22
  idempotent: bool = False
23
23
  invalidates: tuple[str, ...] = ()
24
+ by: str = ""
25
+ reads: tuple[tuple[str, tuple[str, ...]], ...] = ()
24
26
  stream: Literal["realtime", "sse", "ws"] | None = None
25
27
  headers: tuple[tuple[str, str, HeaderKind, bool], ...] = ()
26
28
  events: tuple[str, ...] | None = None
@@ -12,7 +12,13 @@ from .config import ClientConfig, Defaults
12
12
  from .errors import APIConnectionError, APITimeoutError, HttpError
13
13
  from .events import EventStream, raced
14
14
  from .exchange import CallArgs, ClientCore, Exchange, HttpAnswer, failure
15
- from .hooks import RequestContext, refuse_hooks, run_async
15
+ from .hooks import (
16
+ RequestContext,
17
+ detach,
18
+ invalidate_async,
19
+ refuse_hooks,
20
+ run_async,
21
+ )
16
22
  from .operation import Operation
17
23
  from .redirect import Hop, cross
18
24
  from .result import ANSWERS, Err, Ok, Result
@@ -108,7 +114,13 @@ class AsyncTransport(ClientCore):
108
114
  except asyncio.CancelledError:
109
115
  x.log.emit("error", "error", error="the call was canceled")
110
116
  raise
111
- return x.done(answer), live
117
+ x.done(answer)
118
+ hooks = self.config.on_invalidate
119
+ if x.stream:
120
+ detach(hooks, x.invalidated, x.log)
121
+ else:
122
+ await invalidate_async(hooks, x.invalidated, x.log)
123
+ return answer, live
112
124
 
113
125
  async def prepared(
114
126
  self, x: Exchange, token: str | None, is_retry: bool = False
@@ -9,7 +9,7 @@ from .auth import refresh_sync
9
9
  from .config import ClientConfig, Defaults
10
10
  from .errors import APIConnectionError, APITimeoutError, HttpError
11
11
  from .exchange import CallArgs, ClientCore, Exchange, HttpAnswer
12
- from .hooks import refuse_hooks, run_sync
12
+ from .hooks import invalidate_sync, refuse_hooks, run_sync
13
13
  from .operation import Operation
14
14
  from .redirect import Hop, cross
15
15
  from .result import ANSWERS, Err, Ok, Result
@@ -47,7 +47,9 @@ class SyncTransport(ClientCore):
47
47
  except HttpError as error:
48
48
  x.log.failed(error)
49
49
  raise
50
- return x.done(answer)
50
+ x.done(answer)
51
+ invalidate_sync(self.config.on_invalidate_sync, x.invalidated, x.log)
52
+ return answer
51
53
 
52
54
  def attempt(self, x: Exchange, token: str | None, is_retry: bool) -> HttpAnswer:
53
55
  ctx = x.request(token, is_retry)