@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
@@ -37,6 +37,7 @@ from .errors import (
37
37
  )
38
38
  from .events import Cancel, raced
39
39
  from .exchange import CallArgs, Exchange
40
+ from .hooks import detach, invalidation
40
41
  from .operation import Operation
41
42
  from .send_async import AsyncTransport
42
43
 
@@ -324,7 +325,10 @@ class AsyncWsTransport(AsyncTransport):
324
325
  resume = {"reconnect_token": reconnect_token or None}
325
326
  query = {**(args.get("query") or {}), **resume}
326
327
  x = Exchange(self, op, {**args, "query": query}, stream=True)
327
- return cast("T", await self.socket(x, protocols, op))
328
+ socket = await self.socket(x, protocols, op)
329
+ self.stale.settle(x.meta, op.invalidates, x.params)
330
+ detach(self.config.on_invalidate, invalidation(op, x.params), x.log)
331
+ return cast("T", socket)
328
332
 
329
333
  async def socket(
330
334
  self,
@@ -12,7 +12,7 @@ use reqwest::header::HeaderName;
12
12
 
13
13
  use crate::auth::AuthState;
14
14
  use crate::errors::Error;
15
- use crate::hooks::{HookState, OnAuthExpiredHook, OnRequestHook, OnResponseHook};
15
+ use crate::hooks::{HookState, OnAuthExpiredHook, OnInvalidateHook, OnRequestHook, OnResponseHook};
16
16
  use crate::invalidation::InvalidationConfig;
17
17
  use crate::log::OnLogHook;
18
18
  use crate::redirect::RedirectPolicy;
@@ -56,6 +56,8 @@ pub struct ClientConfig {
56
56
  pub on_request: Vec<OnRequestHook>,
57
57
  pub on_response: Vec<OnResponseHook>,
58
58
  pub on_auth_expired: Option<OnAuthExpiredHook>,
59
+ /// Called with the reads each successful write made stale (`OnInvalidateHook`).
60
+ pub on_invalidate: Vec<OnInvalidateHook>,
59
61
  pub on_log: Option<OnLogHook>,
60
62
  pub state: Option<HookState>,
61
63
  }
@@ -78,6 +80,7 @@ impl Default for ClientConfig {
78
80
  on_request: Vec::new(),
79
81
  on_response: Vec::new(),
80
82
  on_auth_expired: None,
83
+ on_invalidate: Vec::new(),
81
84
  on_log: None,
82
85
  state: None,
83
86
  }
@@ -160,6 +163,7 @@ pub(crate) struct Inner {
160
163
  pub(crate) on_request: Vec<OnRequestHook>,
161
164
  pub(crate) on_response: Vec<OnResponseHook>,
162
165
  pub(crate) on_auth_expired: Option<OnAuthExpiredHook>,
166
+ pub(crate) on_invalidate: Vec<OnInvalidateHook>,
163
167
  pub(crate) on_log: Option<OnLogHook>,
164
168
  pub(crate) state: HookState,
165
169
  pub(crate) stale: StaleTracker,
@@ -242,6 +246,7 @@ impl Client {
242
246
  on_request: config.on_request,
243
247
  on_response: config.on_response,
244
248
  on_auth_expired: config.on_auth_expired,
249
+ on_invalidate: config.on_invalidate,
245
250
  on_log: config.on_log,
246
251
  state,
247
252
  stale: StaleTracker::new(config.invalidation.as_ref()),
@@ -1,7 +1,7 @@
1
1
  // @generated by clients. DO NOT EDIT.
2
2
  //! The exchange every call shares: the URL, the header layers, the hooks in declaration order, one
3
- //! retry with a refreshed token on a 401, the capped body read, the timeout, the log and the stale
4
- //! tracker. A body past the cap is still an answer: its status and headers arrived, its body unread.
3
+ //! retry with a refreshed token on a 401, the capped body read, the timeout, the log, the stale
4
+ //! tracker and, after a 2xx, the `on_invalidate` hooks. A body past the cap is still an answer: its status and headers arrived, its body unread.
5
5
 
6
6
  use bytes::Bytes;
7
7
  use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
@@ -11,7 +11,7 @@ use crate::body::Content;
11
11
  use crate::call::{Overrides, RawResponse};
12
12
  use crate::config::{Inner, parse_base};
13
13
  use crate::errors::{ApiError, Error};
14
- use crate::hooks::{RequestContext, ResponseContext};
14
+ use crate::hooks::{RequestContext, ResponseContext, detached, invalidated};
15
15
  use crate::invalidation::RequestMeta;
16
16
  use crate::log::CallLog;
17
17
  use crate::redirect::{Hop, send_following};
@@ -141,6 +141,7 @@ async fn run(
141
141
  .unwrap_or(Err(Error::Timeout)),
142
142
  None => x.with_auth().await,
143
143
  };
144
+ let mut event = None;
144
145
  match &answer {
145
146
  Ok(Answer { raw, .. }) => {
146
147
  log.answered(raw.status);
@@ -148,6 +149,7 @@ async fn run(
148
149
  inner
149
150
  .stale
150
151
  .settle(&x.meta, x.spec.invalidates, &x.spec.params);
152
+ event = x.spec.invalidate_event();
151
153
  } else if inner.on_log.is_some() {
152
154
  /* an error status logs the error its call ends with, as Go's does */
153
155
  log.failed(&Error::Api(ApiError::new(
@@ -159,6 +161,16 @@ async fn run(
159
161
  }
160
162
  Err(e) => log.failed(e),
161
163
  }
164
+ /* after the timeout: a hook never fails the call, and a stream's open never waits on one */
165
+ if let Some(event) = event {
166
+ let operation = x.spec.operation();
167
+ if stream {
168
+ detached(inner, operation, event);
169
+ } else {
170
+ let on_log = inner.on_log.as_ref();
171
+ invalidated(&inner.on_invalidate, on_log, &operation, event).await;
172
+ }
173
+ }
162
174
  answer
163
175
  }
164
176
 
@@ -1,16 +1,22 @@
1
1
  // @generated by clients. DO NOT EDIT.
2
2
  //! The caller's async hooks (TypeScript parity): `on_request` before each send, `on_response` on
3
- //! each answer, `on_auth_expired` on a 401, and the `state` map every hook of a client shares.
3
+ //! each answer, `on_auth_expired` on a 401, `on_invalidate` after a successful write, and the
4
+ //! `state` map every hook of a client shares.
4
5
 
5
- use std::collections::HashMap;
6
+ use std::collections::{BTreeMap, HashMap};
6
7
  use std::future::Future;
8
+ use std::panic::AssertUnwindSafe;
7
9
  use std::pin::Pin;
8
10
  use std::sync::Arc;
11
+ use std::time::Instant;
9
12
 
10
13
  use bytes::Bytes;
14
+ use futures_util::FutureExt;
11
15
  use reqwest::header::HeaderMap;
12
16
 
17
+ use crate::config::Inner;
13
18
  use crate::errors::Error;
19
+ use crate::log::{LogEntry, OnLogHook, emit};
14
20
 
15
21
  /// The map every hook of one client shares: `ClientConfig::state`, or a fresh one per client.
16
22
  pub type HookState = Arc<tokio::sync::Mutex<HashMap<String, serde_json::Value>>>;
@@ -61,3 +67,122 @@ pub struct ResponseContext {
61
67
  pub invalidated_by: Vec<String>,
62
68
  pub state: HookState,
63
69
  }
70
+
71
+ /// One read a write made stale: its operationId, and the write's values for the read's own path
72
+ /// params. A param the write lacks, or holds as `""`, `"."` or `".."`, is left out.
73
+ #[derive(Debug, Clone, PartialEq, Eq)]
74
+ pub struct InvalidateTarget {
75
+ pub operation_id: String,
76
+ pub params: BTreeMap<String, String>,
77
+ }
78
+
79
+ /// What each `on_invalidate` hook sees after a successful write, or as a stream or socket opens:
80
+ /// the operation's operationId and every read it made stale.
81
+ #[derive(Debug, Clone, PartialEq, Eq)]
82
+ pub struct InvalidateEvent {
83
+ pub by: String,
84
+ pub targets: Vec<InvalidateTarget>,
85
+ }
86
+
87
+ /// Runs once per successful write (after its final answer, an auth retry included, or a 2xx whose
88
+ /// body does not decode), in declaration order, each awaited before the next and before the call
89
+ /// returns, outside its timeout. An `Err` or a panic goes to `on_log` as an `error` entry, never to
90
+ /// the call; the next hook still runs. A stream or socket calls them as it opens, without waiting.
91
+ pub type OnInvalidateHook = Arc<dyn Fn(InvalidateEvent) -> HookFuture<'static> + Send + Sync>;
92
+
93
+ /// An `OnInvalidateHook` of an async closure: `on_invalidate(|e| async move { ... Ok(()) })`.
94
+ pub fn on_invalidate<F, Fut>(f: F) -> OnInvalidateHook
95
+ where
96
+ F: Fn(InvalidateEvent) -> Fut + Send + Sync + 'static,
97
+ Fut: Future<Output = Result<(), Error>> + Send + 'static,
98
+ {
99
+ Arc::new(move |e| Box::pin(f(e)))
100
+ }
101
+
102
+ /// The reads a success makes stale, as the emitter resolved them: each read's operationId and its
103
+ /// own path params.
104
+ pub(crate) type Reads = &'static [(&'static str, &'static [&'static str])];
105
+
106
+ /// The event of a success of `by`, its targets filled from `params`; `None` when it stales nothing.
107
+ pub(crate) fn event_of(
108
+ by: &str,
109
+ reads: Reads,
110
+ params: &[(&str, String)],
111
+ ) -> Option<InvalidateEvent> {
112
+ if reads.is_empty() {
113
+ return None;
114
+ }
115
+ let value = |name: &str| {
116
+ params
117
+ .iter()
118
+ .find(|(k, _)| *k == name)
119
+ .map(|(_, v)| v.as_str())
120
+ .filter(|v| !matches!(*v, "" | "." | ".."))
121
+ };
122
+ let targets = reads
123
+ .iter()
124
+ .map(|(operation_id, names)| InvalidateTarget {
125
+ operation_id: (*operation_id).to_owned(),
126
+ params: names
127
+ .iter()
128
+ .filter_map(|name| Some(((*name).to_owned(), value(name)?.to_owned())))
129
+ .collect(),
130
+ })
131
+ .collect();
132
+ Some(InvalidateEvent {
133
+ by: by.to_owned(),
134
+ targets,
135
+ })
136
+ }
137
+
138
+ /// A panic's message, as its payload holds it.
139
+ fn panicked(payload: Box<dyn std::any::Any + Send>) -> String {
140
+ let text = payload
141
+ .downcast_ref::<&str>()
142
+ .map(|s| (*s).to_owned())
143
+ .or_else(|| payload.downcast_ref::<String>().cloned())
144
+ .unwrap_or_default();
145
+ format!("on_invalidate hook panicked: {text}")
146
+ }
147
+
148
+ /// One hook on `event`: its `Err` or its panic (calling it or awaiting it) as the error text.
149
+ async fn run_hook(hook: &OnInvalidateHook, event: InvalidateEvent) -> Result<(), String> {
150
+ let future = std::panic::catch_unwind(AssertUnwindSafe(|| hook(event))).map_err(panicked)?;
151
+ match AssertUnwindSafe(future).catch_unwind().await {
152
+ Ok(done) => done.map_err(|e| e.to_string()),
153
+ Err(payload) => Err(panicked(payload)),
154
+ }
155
+ }
156
+
157
+ /// Calls `hooks` in order on `event`, each after the last; a failure goes to `on_log` as the
158
+ /// `error` entry of `operation`, or nowhere without one.
159
+ pub(crate) async fn invalidated(
160
+ hooks: &[OnInvalidateHook],
161
+ on_log: Option<&OnLogHook>,
162
+ operation: &str,
163
+ event: InvalidateEvent,
164
+ ) {
165
+ for hook in hooks {
166
+ let start = Instant::now();
167
+ if let Err(error) = run_hook(hook, event.clone()).await {
168
+ let entry = LogEntry {
169
+ level: "error",
170
+ event: "error",
171
+ operation: operation.to_owned(),
172
+ duration_ms: start.elapsed().as_millis() as u64,
173
+ status: None,
174
+ error: Some(error),
175
+ };
176
+ emit(on_log, entry);
177
+ }
178
+ }
179
+ }
180
+
181
+ /// Calls `inner`'s hooks on `event` detached, so a stream's or socket's open never waits on them.
182
+ pub(crate) fn detached(inner: &Inner, operation: String, event: InvalidateEvent) {
183
+ if inner.on_invalidate.is_empty() {
184
+ return;
185
+ }
186
+ let (hooks, on_log) = (inner.on_invalidate.clone(), inner.on_log.clone());
187
+ tokio::spawn(async move { invalidated(&hooks, on_log.as_ref(), &operation, event).await });
188
+ }
@@ -23,6 +23,13 @@ pub struct LogEntry {
23
23
  /// Receives each `LogEntry`; a panic in it is caught, so a faulty logger cannot break a call.
24
24
  pub type OnLogHook = Arc<dyn Fn(LogEntry) + Send + Sync>;
25
25
 
26
+ /// Hands `entry` to `hook`, if any; a panic in it is caught.
27
+ pub(crate) fn emit(hook: Option<&OnLogHook>, entry: LogEntry) {
28
+ let Some(hook) = hook else { return };
29
+ let hook = Arc::clone(hook);
30
+ let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || hook(entry)));
31
+ }
32
+
26
33
  /// One call's log: its operation, when it started, and whether it is in flight. A call dropped in
27
34
  /// flight (`cancel_on`, a caller's own timeout, a dropped future) logs its `error` entry as it goes.
28
35
  pub(crate) struct CallLog<'a> {
@@ -49,7 +56,9 @@ impl<'a> CallLog<'a> {
49
56
  status: Option<u16>,
50
57
  error: Option<String>,
51
58
  ) {
52
- let Some(hook) = self.hook else { return };
59
+ if self.hook.is_none() {
60
+ return;
61
+ }
53
62
  let entry = LogEntry {
54
63
  level,
55
64
  event,
@@ -58,8 +67,7 @@ impl<'a> CallLog<'a> {
58
67
  status,
59
68
  error,
60
69
  };
61
- let hook = Arc::clone(hook);
62
- let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || hook(entry)));
70
+ emit(self.hook, entry);
63
71
  }
64
72
 
65
73
  pub(crate) fn started(&mut self) {
@@ -8,6 +8,7 @@ use bytes::Bytes;
8
8
  use crate::auth::new_v4;
9
9
  use crate::body::{Body, Content};
10
10
  use crate::errors::Error;
11
+ use crate::hooks::{InvalidateEvent, Reads, event_of};
11
12
  use crate::path::expand_path;
12
13
  use crate::query::{form_encode, object_pairs, texts, to_value};
13
14
 
@@ -22,6 +23,9 @@ pub(crate) struct RequestSpec {
22
23
  pub(crate) body: Option<Body>,
23
24
  pub(crate) content_type: Option<String>,
24
25
  pub(crate) invalidates: &'static [&'static str],
26
+ /// the operationId an `InvalidateEvent` names, and the reads a success makes stale
27
+ pub(crate) by: &'static str,
28
+ pub(crate) reads: Reads,
25
29
  /// what made the request unsendable (a path param, a body that would not encode)
26
30
  pub(crate) failed: Option<Error>,
27
31
  }
@@ -55,6 +59,8 @@ impl RequestSpec {
55
59
  body: None,
56
60
  content_type: None,
57
61
  invalidates: &[],
62
+ by: "",
63
+ reads: &[],
58
64
  failed,
59
65
  }
60
66
  }
@@ -113,6 +119,17 @@ impl RequestSpec {
113
119
  self.invalidates = targets;
114
120
  }
115
121
 
122
+ /// The operationId `by` and the reads a success makes stale, for `on_invalidate`.
123
+ pub(crate) fn reads(&mut self, by: &'static str, reads: Reads) {
124
+ self.by = by;
125
+ self.reads = reads;
126
+ }
127
+
128
+ /// The `on_invalidate` event of this request's success; `None` when it stales no read.
129
+ pub(crate) fn invalidate_event(&self) -> Option<InvalidateEvent> {
130
+ event_of(self.by, self.reads, &self.params)
131
+ }
132
+
116
133
  fn bytes(&mut self, body: impl Into<Bytes>, content_type: impl Into<String>) {
117
134
  self.body = Some(Body::from(body.into()));
118
135
  self.content_type = Some(content_type.into());
@@ -25,6 +25,7 @@ use crate::call::{Overrides, RawResponse, Run, Signal};
25
25
  use crate::config::Inner;
26
26
  use crate::errors::{ApiError, Error};
27
27
  use crate::exchange::{headers_of, token_of, url_of};
28
+ use crate::hooks::detached;
28
29
  use crate::request::RequestSpec;
29
30
 
30
31
  /// The largest message either side may send.
@@ -387,7 +388,14 @@ fn opened<In: Send + 'static, Out: 'static>(
387
388
  if let Some(e) = spec.take_failure() {
388
389
  return Err(e.into());
389
390
  }
390
- Ok(connect(&inner, &spec, &ov, &protocols, read).await?)
391
+ let meta = inner.stale.begin(spec.method.as_str(), &spec.path);
392
+ let dialed = connect(&inner, &spec, &ov, &protocols, read).await?;
393
+ /* an open marks its targets stale and calls the hooks without waiting on them */
394
+ inner.stale.settle(&meta, spec.invalidates, &spec.params);
395
+ if let Some(event) = spec.invalidate_event() {
396
+ detached(&inner, spec.operation(), event);
397
+ }
398
+ Ok(dialed)
391
399
  })
392
400
  },
393
401
  )
@@ -1,3 +1,5 @@
1
+ import type { RequestOptions } from "./request.ts"
2
+
1
3
  export type HeadersContext = {
2
4
  method: string
3
5
  path: string
@@ -71,6 +73,64 @@ export type LogEntry = {
71
73
  status?: number
72
74
  }
73
75
 
76
+ /**
77
+ * One read a write made stale: its operationId, and the write's values for the read's own path params it knows. A
78
+ * generated SDK's config narrows `Read` to the reads its API invalidates.
79
+ */
80
+ export type InvalidateTarget<Read extends string = string> = {
81
+ operationId: Read
82
+ params: Record<string, string | number | boolean>
83
+ }
84
+
85
+ /**
86
+ * What a successful write made stale: `by` is the write's operationId, `targets` the reads it invalidates. A
87
+ * generated SDK's config narrows `Write` and `Read` to its API's operationIds.
88
+ */
89
+ export type InvalidateEvent<Write extends string = string, Read extends string = string> = {
90
+ by: Write
91
+ /** the reads a single-flight batch brought back with the write, by the id `select` gave each; unset otherwise */
92
+ fresh?: FreshReads
93
+ targets: InvalidateTarget<Read>[]
94
+ }
95
+
96
+ /** The reads a single-flight batch brought back: each answered read's data by its id, and the ids that failed. */
97
+ export type FreshReads = { data: Map<string, unknown>; failed: Set<string> }
98
+
99
+ /** One read a single-flight batch asks for: an id of the caller's, the read's operationId and its input. */
100
+ export type SingleFlightReadRequest<Read extends string = string> = {
101
+ id: string
102
+ input: { params?: InvalidateTarget["params"]; search?: RequestOptions["search"] }
103
+ operationId: Read
104
+ }
105
+
106
+ /** The batch a single-flight write sends: the write's operationId and input, and the reads to bring back. */
107
+ export type SingleFlightBatch = {
108
+ input: Pick<RequestOptions, "idempotencyKey" | "json" | "params" | "search">
109
+ op: string
110
+ reads: SingleFlightReadRequest[]
111
+ v: 1
112
+ }
113
+
114
+ /**
115
+ * Send each eligible write to a single-flight handler with the reads it makes stale, in one request, and hand the
116
+ * reads it brings back to the `onInvalidate` hooks as `fresh`. A write is eligible when it is a REST JSON write with
117
+ * `x-invalidate` reads, called with no headers, cookies, baseURL, body, form or raw, not in `exclude`, not
118
+ * `singleFlight: false`, and `select` picks a read for it; every other call goes direct. A refusal resends the write
119
+ * direct, with the same Idempotency-Key; any other failure of the batch throws, and nothing is resent.
120
+ */
121
+ export type SingleFlightConfig<Write extends string = string, Read extends string = string> = {
122
+ /** the writes that always go direct */
123
+ exclude?: readonly Write[]
124
+ /** the most reads one batch brings back; past it the rest are cut. Default 10, the handler's own default. */
125
+ maxReads?: number
126
+ /** the handler's path under `baseURL`. Default `"_mutate"`. */
127
+ path?: string
128
+ /** the reads to bring back of those the write made stale; none sends the write direct */
129
+ select: (targets: InvalidateTarget<Read>[]) => SingleFlightReadRequest<Read>[]
130
+ /** send the batch some other way (a server function): it resolves the handler's envelope, and throws on a refusal */
131
+ send?: (batch: SingleFlightBatch) => Promise<object>
132
+ }
133
+
74
134
  export type AuthExpiredContext = {
75
135
  /** The token the 401 rejected (read from the auth header), so concurrent 401s can share one refresh. */
76
136
  rejectedToken: string | null
@@ -103,6 +163,15 @@ export type ClientConfig = {
103
163
  * is a stream are not retried.
104
164
  */
105
165
  onAuthExpired?: (ctx: AuthExpiredContext) => Promise<string | null | undefined> | string | null | undefined
166
+ /**
167
+ * Called once per call, never once per attempt, after a write's final answer (an auth refresh or an `onResponse`
168
+ * retry included) is a 2xx, or a 2xx whose body does not decode, with the reads its `x-invalidate` makes stale. A
169
+ * write with no such reads calls none. `onResponse` runs once per attempt, so do not rebuild this there. Each hook
170
+ * runs in order and is awaited, and the write resolves after the last: a hook that never settles holds the write
171
+ * past `timeout`. A hook's error never changes the write's result; it goes to `onLog` as an `error` entry, and is
172
+ * dropped with no `onLog`. An event stream or WebSocket calls them once it opens, detached: nothing waits on them.
173
+ */
174
+ onInvalidate?: Array<(event: InvalidateEvent) => Promise<void> | void>
106
175
  /** Called at each exchange's start, its answer and its failure (v0's entry shape). */
107
176
  onLog?: (entry: LogEntry) => void
108
177
  onReconnected?: () => void
@@ -14,7 +14,7 @@ import {
14
14
  requestInit,
15
15
  requestSignal,
16
16
  } from "./request.ts"
17
- import { type Answer, finishRequest, type Reading, type Sent } from "./response.ts"
17
+ import { type Answer, discard, finishRequest, type Reading, type Sent } from "./response.ts"
18
18
 
19
19
  /** One request, ready to send: where, with what, and the hooks' view of it. */
20
20
  type Prepared = { body: BodyInit | undefined; headers: Headers; url: URL }
@@ -29,6 +29,9 @@ export const REFRESH_AUTH: unique symbol = /* @__PURE__ */ Symbol("http.refreshA
29
29
  export const SEND: unique symbol = /* @__PURE__ */ Symbol("http.send")
30
30
  export const CONFIG: unique symbol = /* @__PURE__ */ Symbol("http.config")
31
31
 
32
+ /** The token in place, for a caller that refreshes on a 401 it reads itself (a single-flight write's). */
33
+ export const AUTH_TOKEN: unique symbol = /* @__PURE__ */ Symbol("http.authToken")
34
+
32
35
  /** One operation of a generated SDK: the call, how it is read, and its stale view for the hooks. */
33
36
  export type Operation = Call & {
34
37
  /** the non-JSON media type the operation declares, read as that type; null when it declares no body */
@@ -36,12 +39,6 @@ export type Operation = Call & {
36
39
  meta?: RequestMeta | undefined
37
40
  }
38
41
 
39
- /** Ignore a failed cancel: the body is being discarded either way. */
40
- const discard = (response: Response) =>
41
- response.body?.cancel().catch(() => {
42
- /* discarded */
43
- })
44
-
45
42
  export class HTTPClient {
46
43
  readonly #config: ClientConfig
47
44
  readonly #fetch: typeof fetch
@@ -58,6 +55,11 @@ export class HTTPClient {
58
55
  this.#disposal = disposal
59
56
  }
60
57
 
58
+ /** @internal The token in place, null before any refresh. */
59
+ get [AUTH_TOKEN](): string | null {
60
+ return this.#token
61
+ }
62
+
61
63
  /** The base URL, parsed once; a per-call base (C2) is parsed for that call. */
62
64
  #baseFor(opts: RequestOptions): URL {
63
65
  if (opts.baseURL !== undefined) return parseClientBaseURL(opts.baseURL)
@@ -131,9 +133,9 @@ export class HTTPClient {
131
133
  return this.#send(call, kind, meta)
132
134
  }
133
135
 
134
- /** @internal The client's one shared refresh; whether a new token is in place. */
135
- async [REFRESH_AUTH](): Promise<boolean> {
136
- return (await this.#refresh(this.#token)) !== null
136
+ /** @internal The client's one shared refresh of `rejected` (the token in place); whether a new token is in place. */
137
+ async [REFRESH_AUTH](rejected: string | null = this.#token): Promise<boolean> {
138
+ return (await this.#refresh(rejected)) !== null
137
139
  }
138
140
 
139
141
  /** Build the request and let the `onRequest` hooks see and change it. */
@@ -19,6 +19,8 @@ export type RequestOptions = {
19
19
  raw?: boolean | undefined
20
20
  search?: Record<string, unknown> | undefined
21
21
  signal?: AbortSignal | undefined
22
+ /** `false` sends this write direct, never in a single-flight batch */
23
+ singleFlight?: boolean | undefined
22
24
  /** Per-call timeout in milliseconds; overrides `config.timeout`, `0` disables it. */
23
25
  timeout?: number | undefined
24
26
  }
@@ -10,6 +10,13 @@ export type Sent = {
10
10
  response: Response
11
11
  }
12
12
 
13
+ /** Ignore a failed cancel: the body is being discarded either way. */
14
+ export function discard(response: Response): Promise<void> | undefined {
15
+ return response.body?.cancel().catch(() => {
16
+ /* discarded */
17
+ })
18
+ }
19
+
13
20
  /** A REST call's answer: its value (the response itself when raw) and the response. */
14
21
  export type Answer = { data: unknown; response: Response }
15
22
 
@@ -0,0 +1,82 @@
1
+ import type { ClientConfig, FreshReads, InvalidateEvent, InvalidateTarget } from "./config.ts"
2
+
3
+ /** One read a write makes stale, as the service map holds it: its operationId and its own path params. */
4
+ export type ServiceRead = { operationId: string; params: readonly string[] }
5
+
6
+ /** A value a target's param can hold: what a generated call takes for a path param. */
7
+ type ParamValue = InvalidateTarget["params"][string]
8
+
9
+ /** The path params a call was made with, as a generated call passes them: a param may be left undefined. */
10
+ type CallParams = Readonly<Record<string, ParamValue | undefined>>
11
+
12
+ /**
13
+ * A successful call that may make reads stale: its operationId, `METHOD path` for the log, its reads and params, and
14
+ * the reads a single-flight batch brought back with it.
15
+ */
16
+ export type InvalidatingCall = {
17
+ by: string
18
+ /** the reads a single-flight batch brought back */
19
+ fresh?: FreshReads | undefined
20
+ operation: string
21
+ params: CallParams | undefined
22
+ reads: readonly ServiceRead[] | undefined
23
+ }
24
+
25
+ /** A param value a target can address a resource by: a number, a boolean, or a string that is a path segment. */
26
+ function isSegmentValue(value: ParamValue | undefined): value is ParamValue {
27
+ if (typeof value === "number" || typeof value === "boolean") return true
28
+ return typeof value === "string" && value !== "" && value !== "." && value !== ".."
29
+ }
30
+
31
+ /** Each read of `reads` with the write's raw `params` values for its own params; one it does not know is left out. */
32
+ export function targetsOf(reads: readonly ServiceRead[], params: CallParams | undefined): InvalidateTarget[] {
33
+ return reads.map(({ operationId, params: names }) => {
34
+ const known: InvalidateTarget["params"] = {}
35
+ for (const name of names) {
36
+ const value = params !== undefined && Object.hasOwn(params, name) ? params[name] : undefined
37
+ if (isSegmentValue(value)) known[name] = value
38
+ }
39
+ return { operationId, params: known }
40
+ })
41
+ }
42
+
43
+ /**
44
+ * Call each `onInvalidate` hook of `config` in order, each after the last settles, with what `call` made stale;
45
+ * none when it makes nothing stale. Never rejects: a hook's error, sync or async, goes to `onLog` as an `error` entry,
46
+ * and with no `onLog`, or one that throws too, it is dropped, as a consumer callback's is on a realtime connection.
47
+ */
48
+ export function runInvalidateHooks(config: ClientConfig, call: InvalidatingCall): Promise<void> {
49
+ const hooks = config.onInvalidate ?? []
50
+ const reads = call.reads ?? []
51
+ if (reads.length === 0 || hooks.length === 0) return Promise.resolve()
52
+ const event: InvalidateEvent = { by: call.by, targets: targetsOf(reads, call.params) }
53
+ if (call.fresh !== undefined) event.fresh = call.fresh
54
+ function failed(cause: unknown, durationMs: number): void {
55
+ try {
56
+ config.onLog?.({
57
+ duration_ms: durationMs,
58
+ error: cause,
59
+ event: "error",
60
+ level: "error",
61
+ operation: call.operation,
62
+ })
63
+ } catch {
64
+ /* an onLog that throws has nowhere left to report to: the write's result stands */
65
+ }
66
+ }
67
+ let settled = Promise.resolve()
68
+ for (const hook of hooks) settled = settled.then(() => runHook(hook, event, failed))
69
+ return settled
70
+ }
71
+
72
+ /** One hook called with `event`, settled whether it returns, throws or rejects; its failure handed to `failed`. */
73
+ function runHook(
74
+ hook: NonNullable<ClientConfig["onInvalidate"]>[number],
75
+ event: InvalidateEvent,
76
+ failed: (cause: unknown, durationMs: number) => void,
77
+ ): Promise<void> {
78
+ const start = Date.now()
79
+ return new Promise<void>((resolve) => resolve(hook(event))).catch((cause: unknown) =>
80
+ failed(cause, Date.now() - start),
81
+ )
82
+ }
@@ -0,0 +1,25 @@
1
+ /** The one batch version a single-flight handler reads, and the client sends. */
2
+ export const BATCH_VERSION = 1
3
+
4
+ /** The methods a single-flight write may be. */
5
+ export const WRITE_METHODS: readonly string[] = ["DELETE", "PATCH", "POST", "PUT"]
6
+
7
+ /** The problem `type` and status a handler refuses a batch with: the client resends the write direct. */
8
+ export const REFUSED = "urn:workerstack:single-flight:refused"
9
+ export const REFUSED_STATUS = 400
10
+
11
+ /** The most reads one batch asks for, the client's and the handler's default. */
12
+ export const DEFAULT_MAX_READS = 10
13
+
14
+ /** The handler's path under the base URL when the config names none. */
15
+ export const DEFAULT_FLIGHT_PATH = "_mutate"
16
+
17
+ /** The status of a write's 401, which comes back inside the envelope. */
18
+ export const UNAUTHORIZED_STATUS = 401
19
+
20
+ /** The statuses a write's answer may have: a response's own range, past its informational ones. */
21
+ export const MIN_WRITE_STATUS = 200
22
+ export const MAX_WRITE_STATUS = 599
23
+
24
+ /** The statuses whose answer has no body. */
25
+ export const NO_BODY_STATUSES: readonly number[] = [204, 205, 304]