@lovrozagar/honey 0.1.0
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 +51 -0
- package/docs/api-ref/go.md +399 -0
- package/docs/api-ref/python.md +399 -0
- package/docs/api-ref/rust.md +399 -0
- package/docs/api-ref/typescript.md +399 -0
- package/docs/invalidate-spec.md +303 -0
- package/docs/sdk.md +722 -0
- package/package.json +120 -0
- package/src/accepts.ts +78 -0
- package/src/body-limit.ts +100 -0
- package/src/build/index.ts +174 -0
- package/src/cli-go/auth.go +15 -0
- package/src/cli-go/config.go +165 -0
- package/src/cli-go/errors.go +57 -0
- package/src/cli-go/multipart.go +55 -0
- package/src/cli-go/output.go +109 -0
- package/src/cli-go/root.go +30 -0
- package/src/cli-go/stream.go +88 -0
- package/src/cli-go/version.go +5 -0
- package/src/cli.ts +204 -0
- package/src/client/error.ts +27 -0
- package/src/client/http.ts +502 -0
- package/src/client/index.ts +127 -0
- package/src/client/sdk.ts +265 -0
- package/src/client/sse.ts +102 -0
- package/src/client/types.ts +211 -0
- package/src/client/ws.ts +115 -0
- package/src/client-go/errors.go +207 -0
- package/src/client-go/invalidation.go +373 -0
- package/src/client-go/realtime.go +317 -0
- package/src/client-go/result.go +20 -0
- package/src/client-go/runtime.go +413 -0
- package/src/client-go/sse.go +149 -0
- package/src/client-go/transport.go +452 -0
- package/src/client-go/ws.go +104 -0
- package/src/client-mcp/README.md +10 -0
- package/src/client-mcp/server.ts +94 -0
- package/src/client-mcp/types.ts +19 -0
- package/src/client-python/_errors.py +115 -0
- package/src/client-python/_invalidation.py +578 -0
- package/src/client-python/_realtime.py +156 -0
- package/src/client-python/_runtime.py +469 -0
- package/src/client-python/_sse.py +99 -0
- package/src/client-python/_transport.py +335 -0
- package/src/client-python/_ws.py +131 -0
- package/src/client-python/py.typed +0 -0
- package/src/client-rust/errors.rs +200 -0
- package/src/client-rust/invalidation.rs +441 -0
- package/src/client-rust/invalidation_sync.rs +306 -0
- package/src/client-rust/realtime.rs +695 -0
- package/src/client-rust/result.rs +22 -0
- package/src/client-rust/runtime.rs +547 -0
- package/src/client-rust/runtime_sync.rs +452 -0
- package/src/client-rust/sse.rs +167 -0
- package/src/client-rust/ws.rs +143 -0
- package/src/cloudflare/realtime.ts +236 -0
- package/src/codegen-go-cli.ts +1180 -0
- package/src/codegen-go.ts +1010 -0
- package/src/codegen-hash.ts +8 -0
- package/src/codegen-ir.ts +517 -0
- package/src/codegen-loaders.ts +53 -0
- package/src/codegen-mcp.ts +364 -0
- package/src/codegen-python.ts +1028 -0
- package/src/codegen-rust.ts +1652 -0
- package/src/codegen-sanitize.ts +67 -0
- package/src/codegen-schema-naming.ts +146 -0
- package/src/codegen.ts +5015 -0
- package/src/context.ts +210 -0
- package/src/cookie-sign.ts +58 -0
- package/src/cookie.ts +89 -0
- package/src/cors.ts +96 -0
- package/src/crypto.ts +19 -0
- package/src/csrf.ts +54 -0
- package/src/curl-logger.ts +235 -0
- package/src/detect-runtime.ts +19 -0
- package/src/error.ts +52 -0
- package/src/errors.ts +87 -0
- package/src/etag.ts +74 -0
- package/src/feature-load.ts +23 -0
- package/src/go-type-emitter.ts +404 -0
- package/src/honey-response.ts +354 -0
- package/src/i18n-slot.ts +20 -0
- package/src/i18n.ts +234 -0
- package/src/index.ts +3843 -0
- package/src/init.ts +149 -0
- package/src/input.ts +8 -0
- package/src/ip-restrict.ts +192 -0
- package/src/logger.ts +149 -0
- package/src/middleware.ts +199 -0
- package/src/node-request.ts +240 -0
- package/src/node.ts +212 -0
- package/src/openapi/register.ts +19 -0
- package/src/openapi/scalar.ts +33 -0
- package/src/openapi/spec-factory.ts +46 -0
- package/src/openapi/spec.ts +31 -0
- package/src/openapi/swagger.ts +34 -0
- package/src/plugin.ts +771 -0
- package/src/powered-by.ts +17 -0
- package/src/pretty-json.ts +39 -0
- package/src/proxy.ts +155 -0
- package/src/python-type-emitter.ts +144 -0
- package/src/realtime/buffer.ts +101 -0
- package/src/realtime/bus.ts +93 -0
- package/src/realtime/longpoll.ts +148 -0
- package/src/realtime/protocol.ts +128 -0
- package/src/realtime/route.ts +104 -0
- package/src/realtime/runtime.ts +430 -0
- package/src/request-id.ts +23 -0
- package/src/request-to-curl.ts +34 -0
- package/src/response.ts +414 -0
- package/src/rust-type-emitter.ts +412 -0
- package/src/secure-headers.ts +69 -0
- package/src/serve-register.ts +8 -0
- package/src/serve-slot.ts +20 -0
- package/src/serve.ts +141 -0
- package/src/server-timing.ts +66 -0
- package/src/static.ts +60 -0
- package/src/telemetry/otel.ts +139 -0
- package/src/testing.ts +114 -0
- package/src/timeout.ts +36 -0
- package/src/tree.ts +464 -0
- package/src/ts-type-emitter.ts +106 -0
- package/src/type-emitter.ts +524 -0
- package/src/type-extractor.ts +749 -0
- package/src/types.ts +638 -0
- package/src/validation.ts +300 -0
- package/src/ws/bun.ts +89 -0
- package/src/ws/cloudflare.ts +133 -0
- package/src/ws/deno.ts +109 -0
- package/src/ws/node.ts +161 -0
- package/src/yaml.ts +80 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/* Code generated by honey. DO NOT EDIT. */
|
|
2
|
+
|
|
3
|
+
use std::fmt;
|
|
4
|
+
|
|
5
|
+
/// ApiError is the trait implemented by all SDK typed error types.
|
|
6
|
+
/// Use `downcast_ref` on the inner `Box<dyn ApiError>` to discriminate by status.
|
|
7
|
+
pub trait ApiError: fmt::Display + std::error::Error + Send + Sync {
|
|
8
|
+
fn status(&self) -> u16;
|
|
9
|
+
fn body(&self) -> &[u8];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
macro_rules! define_api_error {
|
|
13
|
+
($name:ident, $code:expr, $phrase:expr) => {
|
|
14
|
+
pub struct $name {
|
|
15
|
+
pub message: String,
|
|
16
|
+
pub body: Vec<u8>,
|
|
17
|
+
pub status_code: u16,
|
|
18
|
+
pub data: Option<serde_json::Value>,
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
impl fmt::Display for $name {
|
|
22
|
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
23
|
+
write!(f, "{} {}: {}", $code, $phrase, self.message)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
impl fmt::Debug for $name {
|
|
28
|
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
29
|
+
write!(f, "{} {{ message: {:?}, status_code: {} }}", stringify!($name), self.message, self.status_code)
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
impl std::error::Error for $name {}
|
|
34
|
+
|
|
35
|
+
impl ApiError for $name {
|
|
36
|
+
fn status(&self) -> u16 {
|
|
37
|
+
$code
|
|
38
|
+
}
|
|
39
|
+
fn body(&self) -> &[u8] {
|
|
40
|
+
&self.body
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
define_api_error!(BadRequestError, 400, "Bad Request");
|
|
47
|
+
define_api_error!(UnauthorizedError, 401, "Unauthorized");
|
|
48
|
+
define_api_error!(ForbiddenError, 403, "Forbidden");
|
|
49
|
+
define_api_error!(NotFoundError, 404, "Not Found");
|
|
50
|
+
define_api_error!(ConflictError, 409, "Conflict");
|
|
51
|
+
define_api_error!(UnprocessableEntityError, 422, "Unprocessable Entity");
|
|
52
|
+
define_api_error!(RateLimitError, 429, "Too Many Requests");
|
|
53
|
+
define_api_error!(InternalServerError, 500, "Internal Server Error");
|
|
54
|
+
define_api_error!(BadGatewayError, 502, "Bad Gateway");
|
|
55
|
+
define_api_error!(ServiceUnavailableError, 503, "Service Unavailable");
|
|
56
|
+
define_api_error!(GatewayTimeoutError, 504, "Gateway Timeout");
|
|
57
|
+
|
|
58
|
+
/// StatusError is the fallback for any non-2xx status not covered by a concrete type.
|
|
59
|
+
pub struct StatusError {
|
|
60
|
+
pub message: String,
|
|
61
|
+
pub status_code: u16,
|
|
62
|
+
pub body: Vec<u8>,
|
|
63
|
+
pub data: Option<serde_json::Value>,
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
impl fmt::Display for StatusError {
|
|
67
|
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
68
|
+
write!(f, "{}: {}", self.status_code, self.message)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
impl fmt::Debug for StatusError {
|
|
73
|
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
74
|
+
write!(f, "StatusError {{ status_code: {}, message: {:?} }}", self.status_code, self.message)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
impl std::error::Error for StatusError {}
|
|
79
|
+
|
|
80
|
+
impl ApiError for StatusError {
|
|
81
|
+
fn status(&self) -> u16 {
|
|
82
|
+
self.status_code
|
|
83
|
+
}
|
|
84
|
+
fn body(&self) -> &[u8] {
|
|
85
|
+
&self.body
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/// Error is the top-level error enum for all SDK operations.
|
|
90
|
+
pub enum Error {
|
|
91
|
+
/// A typed API error (non-2xx HTTP response).
|
|
92
|
+
Api(Box<dyn ApiError + Send + Sync>),
|
|
93
|
+
/// A transport-level error from reqwest.
|
|
94
|
+
Transport(reqwest::Error),
|
|
95
|
+
/// A JSON serialization/deserialization error.
|
|
96
|
+
Json(serde_json::Error),
|
|
97
|
+
/// A URL parse error.
|
|
98
|
+
UrlParse(url::ParseError),
|
|
99
|
+
/// The request was canceled before completion.
|
|
100
|
+
Canceled,
|
|
101
|
+
/// The request timed out.
|
|
102
|
+
Timeout,
|
|
103
|
+
/// Authentication expired; string carries the refresh error message.
|
|
104
|
+
AuthExpired(String),
|
|
105
|
+
/// WebSocket close frame (or stream end). `code` is the RFC 6455 status
|
|
106
|
+
/// (1005 = no status received, 1006 = abnormal / no close frame).
|
|
107
|
+
Closed { code: u16, reason: String },
|
|
108
|
+
/// Any other error not covered by the above variants.
|
|
109
|
+
Other(String),
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
impl fmt::Display for Error {
|
|
113
|
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
114
|
+
match self {
|
|
115
|
+
Error::Api(e) => write!(f, "api error: {}", e),
|
|
116
|
+
Error::Transport(e) => write!(f, "transport error: {}", e),
|
|
117
|
+
Error::Json(e) => write!(f, "json error: {}", e),
|
|
118
|
+
Error::UrlParse(e) => write!(f, "url parse error: {}", e),
|
|
119
|
+
Error::Canceled => write!(f, "request canceled"),
|
|
120
|
+
Error::Timeout => write!(f, "request timed out"),
|
|
121
|
+
Error::AuthExpired(msg) => write!(f, "auth expired: {}", msg),
|
|
122
|
+
Error::Closed { code, reason } => {
|
|
123
|
+
if reason.is_empty() {
|
|
124
|
+
write!(f, "connection closed: {}", code)
|
|
125
|
+
} else {
|
|
126
|
+
write!(f, "connection closed: {} {}", code, reason)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
Error::Other(msg) => write!(f, "error: {}", msg),
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
impl fmt::Debug for Error {
|
|
135
|
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
136
|
+
fmt::Display::fmt(self, f)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
impl std::error::Error for Error {
|
|
141
|
+
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
|
142
|
+
match self {
|
|
143
|
+
Error::Transport(e) => Some(e),
|
|
144
|
+
Error::Json(e) => Some(e),
|
|
145
|
+
Error::UrlParse(e) => Some(e),
|
|
146
|
+
_ => None,
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
impl From<reqwest::Error> for Error {
|
|
152
|
+
fn from(e: reqwest::Error) -> Self {
|
|
153
|
+
if e.is_timeout() {
|
|
154
|
+
Error::Timeout
|
|
155
|
+
} else {
|
|
156
|
+
Error::Transport(e)
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
impl From<serde_json::Error> for Error {
|
|
162
|
+
fn from(e: serde_json::Error) -> Self {
|
|
163
|
+
Error::Json(e)
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
impl From<url::ParseError> for Error {
|
|
168
|
+
fn from(e: url::ParseError) -> Self {
|
|
169
|
+
Error::UrlParse(e)
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/// raise_for_status returns None for 2xx responses, Some(Error::Api(...)) for
|
|
174
|
+
/// non-2xx responses, mapping to the appropriate concrete error type when known.
|
|
175
|
+
pub(crate) fn raise_for_status(status: u16, body: Vec<u8>) -> Option<Error> {
|
|
176
|
+
if (200..300).contains(&status) {
|
|
177
|
+
return None;
|
|
178
|
+
}
|
|
179
|
+
let data: Option<serde_json::Value> = if body.is_empty() {
|
|
180
|
+
None
|
|
181
|
+
} else {
|
|
182
|
+
serde_json::from_slice(&body).ok()
|
|
183
|
+
};
|
|
184
|
+
let message = String::from_utf8_lossy(&body).to_string();
|
|
185
|
+
let api_err: Box<dyn ApiError + Send + Sync> = match status {
|
|
186
|
+
400 => Box::new(BadRequestError { message, body, status_code: 400, data }),
|
|
187
|
+
401 => Box::new(UnauthorizedError { message, body, status_code: 401, data }),
|
|
188
|
+
403 => Box::new(ForbiddenError { message, body, status_code: 403, data }),
|
|
189
|
+
404 => Box::new(NotFoundError { message, body, status_code: 404, data }),
|
|
190
|
+
409 => Box::new(ConflictError { message, body, status_code: 409, data }),
|
|
191
|
+
422 => Box::new(UnprocessableEntityError { message, body, status_code: 422, data }),
|
|
192
|
+
429 => Box::new(RateLimitError { message, body, status_code: 429, data }),
|
|
193
|
+
500 => Box::new(InternalServerError { message, body, status_code: 500, data }),
|
|
194
|
+
502 => Box::new(BadGatewayError { message, body, status_code: 502, data }),
|
|
195
|
+
503 => Box::new(ServiceUnavailableError { message, body, status_code: 503, data }),
|
|
196
|
+
504 => Box::new(GatewayTimeoutError { message, body, status_code: 504, data }),
|
|
197
|
+
_ => Box::new(StatusError { message, body, status_code: status, data }),
|
|
198
|
+
};
|
|
199
|
+
Some(Error::Api(api_err))
|
|
200
|
+
}
|
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
/* Code generated by honey. DO NOT EDIT. */
|
|
2
|
+
|
|
3
|
+
#![allow(dead_code)]
|
|
4
|
+
|
|
5
|
+
use crate::runtime::InvalidationConfig;
|
|
6
|
+
use once_cell::sync::Lazy;
|
|
7
|
+
use regex::Regex;
|
|
8
|
+
use std::collections::HashMap;
|
|
9
|
+
use std::time::{Duration, Instant};
|
|
10
|
+
use tokio::sync::Mutex;
|
|
11
|
+
|
|
12
|
+
/* PLACEHOLDER_RE matches `{name}` and `:name` placeholders. */
|
|
13
|
+
static PLACEHOLDER_RE: Lazy<Regex> =
|
|
14
|
+
Lazy::new(|| Regex::new(r"\{([a-zA-Z_][a-zA-Z0-9_]*)\}|:([a-zA-Z_][a-zA-Z0-9_]*)").unwrap());
|
|
15
|
+
|
|
16
|
+
/* PATTERN_REGEX_CACHE caches compiled placeholder→`[^/]+` regexps per pattern key.
|
|
17
|
+
* std::sync::Mutex is fine — pure CPU work, never held across an .await point. */
|
|
18
|
+
static PATTERN_REGEX_CACHE: Lazy<std::sync::Mutex<HashMap<String, Regex>>> =
|
|
19
|
+
Lazy::new(|| std::sync::Mutex::new(HashMap::new()));
|
|
20
|
+
|
|
21
|
+
/// StaleEntry is the per-key invalidation record. `by` records mutation
|
|
22
|
+
/// selectors that contributed to the entry, `seq` is the monotonic version
|
|
23
|
+
/// stamp at write time, `until` is the absolute expiry.
|
|
24
|
+
#[derive(Clone, Debug)]
|
|
25
|
+
pub struct StaleEntry {
|
|
26
|
+
pub by: Vec<String>,
|
|
27
|
+
pub seq: u64,
|
|
28
|
+
pub until: Instant,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// RequestMeta is the per-request invalidation snapshot consumers see on hook
|
|
32
|
+
/// contexts. Mirrors TS `_RequestMeta`, Python `_RequestMeta`, Go `RequestMeta`.
|
|
33
|
+
#[derive(Clone, Debug)]
|
|
34
|
+
pub struct RequestMeta {
|
|
35
|
+
pub selector: String,
|
|
36
|
+
pub is_stale: bool,
|
|
37
|
+
pub invalidated_by: Vec<String>,
|
|
38
|
+
pub seq_snapshot: u64,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/// compile_pattern returns a cached anchored regex for the given pattern,
|
|
42
|
+
/// substituting `{name}` and `:name` placeholders with `[^/]+`.
|
|
43
|
+
pub fn compile_pattern(pattern: &str) -> Regex {
|
|
44
|
+
{
|
|
45
|
+
let cache = PATTERN_REGEX_CACHE.lock().unwrap();
|
|
46
|
+
if let Some(re) = cache.get(pattern) {
|
|
47
|
+
return re.clone();
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
let mut out = String::with_capacity(pattern.len() + 4);
|
|
51
|
+
out.push('^');
|
|
52
|
+
let mut last = 0usize;
|
|
53
|
+
for m in PLACEHOLDER_RE.find_iter(pattern) {
|
|
54
|
+
out.push_str(®ex::escape(&pattern[last..m.start()]));
|
|
55
|
+
out.push_str("[^/]+");
|
|
56
|
+
last = m.end();
|
|
57
|
+
}
|
|
58
|
+
out.push_str(®ex::escape(&pattern[last..]));
|
|
59
|
+
out.push('$');
|
|
60
|
+
let re = Regex::new(&out).unwrap();
|
|
61
|
+
let mut cache = PATTERN_REGEX_CACHE.lock().unwrap();
|
|
62
|
+
cache.entry(pattern.to_string()).or_insert(re).clone()
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/// path_has_placeholders returns true when `path` contains a `{name}` or `:name` segment.
|
|
66
|
+
pub fn path_has_placeholders(path: &str) -> bool {
|
|
67
|
+
PLACEHOLDER_RE.is_match(path)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/// path_matches_pattern returns true when `concrete_path` matches `pattern`,
|
|
71
|
+
/// where `pattern` may contain `{name}` / `:name` placeholders.
|
|
72
|
+
pub fn path_matches_pattern(concrete_path: &str, pattern: &str) -> bool {
|
|
73
|
+
if concrete_path == pattern {
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
compile_pattern(pattern).is_match(concrete_path)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/// interpolate_path substitutes `{name}` / `:name` placeholders in `template`
|
|
80
|
+
/// using `params`. Returns Err(missing_key) if any placeholder is not in params.
|
|
81
|
+
pub fn interpolate_path(
|
|
82
|
+
template: &str,
|
|
83
|
+
params: &HashMap<String, String>,
|
|
84
|
+
) -> Result<String, String> {
|
|
85
|
+
if !path_has_placeholders(template) {
|
|
86
|
+
return Ok(template.to_string());
|
|
87
|
+
}
|
|
88
|
+
let mut missing: Option<String> = None;
|
|
89
|
+
let mut out = String::with_capacity(template.len());
|
|
90
|
+
let mut last = 0usize;
|
|
91
|
+
for caps in PLACEHOLDER_RE.captures_iter(template) {
|
|
92
|
+
let m = caps.get(0).unwrap();
|
|
93
|
+
out.push_str(&template[last..m.start()]);
|
|
94
|
+
let key = caps
|
|
95
|
+
.get(1)
|
|
96
|
+
.or_else(|| caps.get(2))
|
|
97
|
+
.map(|c| c.as_str())
|
|
98
|
+
.unwrap_or_default();
|
|
99
|
+
match params.get(key) {
|
|
100
|
+
Some(v) => out.push_str(&urlencoding::encode(v)),
|
|
101
|
+
None => {
|
|
102
|
+
if missing.is_none() {
|
|
103
|
+
missing = Some(key.to_string());
|
|
104
|
+
}
|
|
105
|
+
out.push_str(m.as_str());
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
last = m.end();
|
|
109
|
+
}
|
|
110
|
+
out.push_str(&template[last..]);
|
|
111
|
+
if let Some(k) = missing {
|
|
112
|
+
return Err(k);
|
|
113
|
+
}
|
|
114
|
+
Ok(out)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/// resolve_invalidation_targets_for_mutation expands templated `METHOD /path/{x}`
|
|
118
|
+
/// invalidation entries to concrete `METHOD /path/abc` selectors using params.
|
|
119
|
+
/// Pattern-only entries (no placeholders) pass through; entries whose
|
|
120
|
+
/// placeholders cannot be resolved are dropped.
|
|
121
|
+
pub fn resolve_invalidation_targets_for_mutation(
|
|
122
|
+
targets: &[String],
|
|
123
|
+
params: &HashMap<String, String>,
|
|
124
|
+
) -> Vec<String> {
|
|
125
|
+
let mut out = Vec::with_capacity(targets.len());
|
|
126
|
+
for entry in targets {
|
|
127
|
+
let space_idx = match entry.find(' ') {
|
|
128
|
+
Some(i) => i,
|
|
129
|
+
None => {
|
|
130
|
+
out.push(entry.clone());
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
let method = &entry[..space_idx];
|
|
135
|
+
let template = &entry[space_idx + 1..];
|
|
136
|
+
if !path_has_placeholders(template) {
|
|
137
|
+
out.push(entry.clone());
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
match interpolate_path(template, params) {
|
|
141
|
+
Ok(concrete) => out.push(format!("{} {}", method, concrete)),
|
|
142
|
+
Err(_) => continue,
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
out
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
struct TrackerState {
|
|
149
|
+
entries: HashMap<String, StaleEntry>,
|
|
150
|
+
/* insertion order; oldest at index 0 */
|
|
151
|
+
order: Vec<String>,
|
|
152
|
+
seq: u64,
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/// StaleTracker tracks invalidation state per `METHOD /path` selector with TS-
|
|
156
|
+
/// parity semantics: exact-key + pattern-key two-tier lookup, TTL stale window,
|
|
157
|
+
/// LRU eviction at cap, monotonic seq for clear-after-mutate ordering.
|
|
158
|
+
/// All public methods are safe for concurrent async use (interior tokio Mutex).
|
|
159
|
+
pub struct StaleTracker {
|
|
160
|
+
state: Mutex<TrackerState>,
|
|
161
|
+
enabled: bool,
|
|
162
|
+
stale_time: Duration,
|
|
163
|
+
max_entries: usize,
|
|
164
|
+
max_sources: usize,
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
impl StaleTracker {
|
|
168
|
+
/// new constructs a tracker from an InvalidationConfig.
|
|
169
|
+
/// Tracker is disabled (cheap no-op) when cfg is None or stale_time ≤ 0.
|
|
170
|
+
pub fn new(cfg: Option<&InvalidationConfig>) -> Self {
|
|
171
|
+
let mut enabled = false;
|
|
172
|
+
let mut stale_time = Duration::from_millis(0);
|
|
173
|
+
let mut max_entries = 1000usize;
|
|
174
|
+
let mut max_sources = 16usize;
|
|
175
|
+
if let Some(c) = cfg {
|
|
176
|
+
if c.stale_time > 0 {
|
|
177
|
+
enabled = true;
|
|
178
|
+
stale_time = Duration::from_millis(c.stale_time as u64);
|
|
179
|
+
if c.stale_max_entries > 0 {
|
|
180
|
+
max_entries = c.stale_max_entries;
|
|
181
|
+
}
|
|
182
|
+
if c.max_sources_per_target > 0 {
|
|
183
|
+
max_sources = c.max_sources_per_target;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
StaleTracker {
|
|
188
|
+
state: Mutex::new(TrackerState {
|
|
189
|
+
entries: HashMap::new(),
|
|
190
|
+
order: Vec::new(),
|
|
191
|
+
seq: 0,
|
|
192
|
+
}),
|
|
193
|
+
enabled,
|
|
194
|
+
stale_time,
|
|
195
|
+
max_entries,
|
|
196
|
+
max_sources,
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/// enabled reports whether the tracker will record / report stale entries.
|
|
201
|
+
pub fn enabled(&self) -> bool {
|
|
202
|
+
self.enabled
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/// mark_stale bumps seq, expands templated invalidation entries with
|
|
206
|
+
/// `params`, and records each resolved target as freshly stale.
|
|
207
|
+
/// `mutation_selector` is appended to each entry's `by` list (capped at
|
|
208
|
+
/// max_sources, deduped).
|
|
209
|
+
pub async fn mark_stale(
|
|
210
|
+
&self,
|
|
211
|
+
invalidate: &[String],
|
|
212
|
+
params: &HashMap<String, String>,
|
|
213
|
+
mutation_selector: &str,
|
|
214
|
+
) {
|
|
215
|
+
if !self.enabled || invalidate.is_empty() {
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
let mut s = self.state.lock().await;
|
|
219
|
+
s.seq += 1;
|
|
220
|
+
let seq = s.seq;
|
|
221
|
+
let until = Instant::now() + self.stale_time;
|
|
222
|
+
let resolved = resolve_invalidation_targets_for_mutation(invalidate, params);
|
|
223
|
+
for target in resolved {
|
|
224
|
+
upsert_locked(&mut s, &target, until, seq, mutation_selector, self.max_sources);
|
|
225
|
+
}
|
|
226
|
+
enforce_capacity_locked(&mut s, self.max_entries);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/// lookup_stale returns (invalidated_by, is_stale): exact + pattern lookup
|
|
230
|
+
/// with expired-key sweep. Disabled tracker → (vec![], false).
|
|
231
|
+
pub async fn lookup_stale(
|
|
232
|
+
&self,
|
|
233
|
+
concrete_selector: &str,
|
|
234
|
+
concrete_path: &str,
|
|
235
|
+
method: &str,
|
|
236
|
+
now: Instant,
|
|
237
|
+
) -> (Vec<String>, bool) {
|
|
238
|
+
if !self.enabled {
|
|
239
|
+
return (Vec::new(), false);
|
|
240
|
+
}
|
|
241
|
+
let mut s = self.state.lock().await;
|
|
242
|
+
lookup_locked(&mut s, concrete_selector, concrete_path, method, now)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/// clear_stale drops stale entries whose seq ≤ seq_snapshot and which match
|
|
246
|
+
/// the given concrete_path under method (exact key + pattern keys).
|
|
247
|
+
pub async fn clear_stale(
|
|
248
|
+
&self,
|
|
249
|
+
concrete_selector: &str,
|
|
250
|
+
concrete_path: &str,
|
|
251
|
+
method: &str,
|
|
252
|
+
seq_snapshot: u64,
|
|
253
|
+
) {
|
|
254
|
+
if !self.enabled {
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
let mut s = self.state.lock().await;
|
|
258
|
+
if let Some(entry) = s.entries.get(concrete_selector) {
|
|
259
|
+
if entry.seq <= seq_snapshot {
|
|
260
|
+
delete_locked(&mut s, concrete_selector);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
let mut to_delete: Vec<String> = Vec::new();
|
|
264
|
+
for (key, entry) in s.entries.iter() {
|
|
265
|
+
if entry.seq > seq_snapshot {
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
if !key.contains('{') && !key.contains(':') {
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
let space_idx = match key.find(' ') {
|
|
272
|
+
Some(i) => i,
|
|
273
|
+
None => continue,
|
|
274
|
+
};
|
|
275
|
+
if &key[..space_idx] != method {
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
if path_matches_pattern(concrete_path, &key[space_idx + 1..]) {
|
|
279
|
+
to_delete.push(key.clone());
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
for key in to_delete {
|
|
283
|
+
delete_locked(&mut s, &key);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/// is_stale reports whether (method, path) currently sits inside an active
|
|
288
|
+
/// stale window. Walks pattern entries too. Disabled tracker → false.
|
|
289
|
+
pub async fn is_stale(&self, method: &str, path: &str) -> bool {
|
|
290
|
+
if !self.enabled {
|
|
291
|
+
return false;
|
|
292
|
+
}
|
|
293
|
+
let mut s = self.state.lock().await;
|
|
294
|
+
let selector = format!("{} {}", method, path);
|
|
295
|
+
let (_, is_stale) = lookup_locked(&mut s, &selector, path, method, Instant::now());
|
|
296
|
+
is_stale
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/// build_request_meta returns a RequestMeta snapshot for the request about
|
|
300
|
+
/// to fire, or None when tracker is disabled.
|
|
301
|
+
pub async fn build_request_meta(
|
|
302
|
+
&self,
|
|
303
|
+
concrete_selector: &str,
|
|
304
|
+
concrete_path: &str,
|
|
305
|
+
method: &str,
|
|
306
|
+
) -> Option<RequestMeta> {
|
|
307
|
+
if !self.enabled {
|
|
308
|
+
return None;
|
|
309
|
+
}
|
|
310
|
+
let mut s = self.state.lock().await;
|
|
311
|
+
let (by, is_stale) =
|
|
312
|
+
lookup_locked(&mut s, concrete_selector, concrete_path, method, Instant::now());
|
|
313
|
+
Some(RequestMeta {
|
|
314
|
+
selector: concrete_selector.to_string(),
|
|
315
|
+
is_stale,
|
|
316
|
+
invalidated_by: by,
|
|
317
|
+
seq_snapshot: s.seq,
|
|
318
|
+
})
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
fn upsert_locked(
|
|
323
|
+
s: &mut TrackerState,
|
|
324
|
+
key: &str,
|
|
325
|
+
until: Instant,
|
|
326
|
+
seq: u64,
|
|
327
|
+
mutation_selector: &str,
|
|
328
|
+
max_sources: usize,
|
|
329
|
+
) {
|
|
330
|
+
if let Some(existing) = s.entries.get_mut(key) {
|
|
331
|
+
existing.until = until;
|
|
332
|
+
existing.seq = seq;
|
|
333
|
+
if !mutation_selector.is_empty() && existing.by.len() < max_sources {
|
|
334
|
+
let already = existing.by.iter().any(|b| b == mutation_selector);
|
|
335
|
+
if !already {
|
|
336
|
+
existing.by.push(mutation_selector.to_string());
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
touch_order_locked(s, key);
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
let by = if mutation_selector.is_empty() {
|
|
343
|
+
Vec::new()
|
|
344
|
+
} else {
|
|
345
|
+
vec![mutation_selector.to_string()]
|
|
346
|
+
};
|
|
347
|
+
s.entries.insert(key.to_string(), StaleEntry { by, seq, until });
|
|
348
|
+
s.order.push(key.to_string());
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
fn touch_order_locked(s: &mut TrackerState, key: &str) {
|
|
352
|
+
if let Some(idx) = s.order.iter().position(|k| k == key) {
|
|
353
|
+
s.order.remove(idx);
|
|
354
|
+
}
|
|
355
|
+
s.order.push(key.to_string());
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
fn delete_locked(s: &mut TrackerState, key: &str) {
|
|
359
|
+
if s.entries.remove(key).is_none() {
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
if let Some(idx) = s.order.iter().position(|k| k == key) {
|
|
363
|
+
s.order.remove(idx);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
fn lookup_locked(
|
|
368
|
+
s: &mut TrackerState,
|
|
369
|
+
concrete_selector: &str,
|
|
370
|
+
concrete_path: &str,
|
|
371
|
+
method: &str,
|
|
372
|
+
now: Instant,
|
|
373
|
+
) -> (Vec<String>, bool) {
|
|
374
|
+
let mut all_by: Vec<String> = Vec::new();
|
|
375
|
+
let mut exact_expired = false;
|
|
376
|
+
if let Some(exact) = s.entries.get(concrete_selector) {
|
|
377
|
+
if exact.until > now {
|
|
378
|
+
all_by.extend(exact.by.iter().cloned());
|
|
379
|
+
} else {
|
|
380
|
+
exact_expired = true;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if exact_expired {
|
|
384
|
+
delete_locked(s, concrete_selector);
|
|
385
|
+
}
|
|
386
|
+
let mut expired: Vec<String> = Vec::new();
|
|
387
|
+
for (key, entry) in s.entries.iter() {
|
|
388
|
+
if entry.until <= now {
|
|
389
|
+
expired.push(key.clone());
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
if key == concrete_selector {
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
if !key.contains('{') && !key.contains(':') {
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
let space_idx = match key.find(' ') {
|
|
399
|
+
Some(i) => i,
|
|
400
|
+
None => continue,
|
|
401
|
+
};
|
|
402
|
+
if &key[..space_idx] != method {
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
405
|
+
if path_matches_pattern(concrete_path, &key[space_idx + 1..]) {
|
|
406
|
+
all_by.extend(entry.by.iter().cloned());
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
for key in expired {
|
|
410
|
+
delete_locked(s, &key);
|
|
411
|
+
}
|
|
412
|
+
let mut deduped: Vec<String> = Vec::with_capacity(all_by.len());
|
|
413
|
+
for src in all_by {
|
|
414
|
+
if !deduped.iter().any(|d| d == &src) {
|
|
415
|
+
deduped.push(src);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
let any = !deduped.is_empty();
|
|
419
|
+
(deduped, any)
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
fn enforce_capacity_locked(s: &mut TrackerState, max_entries: usize) {
|
|
423
|
+
if s.entries.len() <= max_entries {
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
let now = Instant::now();
|
|
427
|
+
let expired: Vec<String> = s
|
|
428
|
+
.entries
|
|
429
|
+
.iter()
|
|
430
|
+
.filter(|(_, e)| e.until <= now)
|
|
431
|
+
.map(|(k, _)| k.clone())
|
|
432
|
+
.collect();
|
|
433
|
+
for key in expired {
|
|
434
|
+
delete_locked(s, &key);
|
|
435
|
+
}
|
|
436
|
+
let target = if max_entries / 2 < 1 { 1 } else { max_entries / 2 };
|
|
437
|
+
while s.entries.len() > target && !s.order.is_empty() {
|
|
438
|
+
let oldest = s.order[0].clone();
|
|
439
|
+
delete_locked(s, &oldest);
|
|
440
|
+
}
|
|
441
|
+
}
|