osproxy-sink 1.0.1

Write sink: Sink trait + OpenSearchSink now; QueueSink (Kafka) redundancy later behind the same trait.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! The [`Reader`] trait: fetching a single document by physical id.
//!
//! Reads are always direct-to-cluster, unlike writes, they cannot be served by
//! a queue, so the read seam is separate from [`Sink`](crate::Sink). The same
//! backend type may implement both (`OpenSearchSink` does, sharing its pooled
//! connection), while a write-only `QueueSink` implements only [`Sink`].
//!
//! [`Sink`]: crate::Sink
//
// JUSTIFY(file-length): one cohesive family of read-path value types, the
// `Reader` trait plus the op (`ReadOp`/`SearchOp`/`CursorOp`) and outcome
// (`ReadOutcome`/`SearchOutcome`/`CountOutcome`/`CursorOutcome`) structs they
// exchange. They share the same builders and conventions; splitting them would
// scatter one small vocabulary across files for no real separation.

use osproxy_core::{ClusterId, Target, TraceContext};
use osproxy_spi::{HttpMethod, Protocol};

use crate::error::SinkError;

/// A read-by-id operation against a resolved [`Target`].
///
/// The id is already the **physical** id (the tenancy adapter mapped the
/// client's logical id, `docs/04` §5); the reader does no rewriting.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct ReadOp {
    /// The physical destination to read from.
    pub target: Target,
    /// The physical document id to fetch.
    pub id: String,
    /// The `_routing` value (the partition id), if the placement routes.
    pub routing: Option<String>,
    /// The upstream wire protocol this read is dispatched over. Defaults to
    /// [`Protocol::Http1`].
    pub protocol: Protocol,
    /// The W3C trace context to forward downstream (`traceparent`), so the
    /// upstream's spans join this request's distributed trace. `None` = no
    /// propagation header is sent.
    pub trace: Option<TraceContext>,
    /// Client headers to relay verbatim to the upstream (the forwarding policy's
    /// output). Applied before [`trace`](Self::trace). Empty by default.
    pub forward_headers: Vec<(String, String)>,
}

impl ReadOp {
    /// Constructs a read operation (defaulting to HTTP/1.1 upstream).
    #[must_use]
    pub fn new(target: Target, id: impl Into<String>, routing: Option<String>) -> Self {
        Self {
            target,
            id: id.into(),
            routing,
            protocol: Protocol::Http1,
            trace: None,
            forward_headers: Vec::new(),
        }
    }

    /// Sets the upstream protocol for this op (builder style).
    #[must_use]
    pub fn with_protocol(mut self, protocol: Protocol) -> Self {
        self.protocol = protocol;
        self
    }

    /// Sets the trace context to propagate downstream (builder style).
    #[must_use]
    pub fn with_trace(mut self, trace: Option<TraceContext>) -> Self {
        self.trace = trace;
        self
    }

    /// Sets the client headers to relay verbatim to the upstream (builder style).
    #[must_use]
    pub fn with_forward_headers(mut self, headers: Vec<(String, String)>) -> Self {
        self.forward_headers = headers;
        self
    }
}

/// The outcome of a read: whether the document was found, and its raw upstream
/// body (the document as stored, before the read-path field strip).
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct ReadOutcome {
    /// The upstream HTTP status.
    pub status: u16,
    /// Whether the document exists.
    pub found: bool,
    /// The raw upstream response body (the stored document when `found`).
    pub body: Vec<u8>,
    /// Whether this read rode a reused pooled connection (NFR-P telemetry).
    pub pool_reuse: bool,
}

impl ReadOutcome {
    /// A hit carrying the stored document body.
    #[must_use]
    pub fn found(status: u16, body: Vec<u8>) -> Self {
        Self {
            status,
            found: true,
            body,
            pool_reuse: false,
        }
    }

    /// A miss (no such document).
    #[must_use]
    pub fn not_found(status: u16, body: Vec<u8>) -> Self {
        Self {
            status,
            found: false,
            body,
            pool_reuse: false,
        }
    }

    /// Records whether the dispatch reused a pooled connection (builder style).
    #[must_use]
    pub fn with_pool_reuse(mut self, reused: bool) -> Self {
        self.pool_reuse = reused;
        self
    }
}

/// A search operation against a resolved [`Target`].
///
/// The body is the **already-wrapped** query (the tenancy partition filter has
/// been applied, `docs/04` §4); the reader forwards it verbatim.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct SearchOp {
    /// The physical destination to search.
    pub target: Target,
    /// The query body to forward upstream (already partition-filtered).
    pub body: Vec<u8>,
    /// The upstream wire protocol this search is dispatched over. Defaults to
    /// [`Protocol::Http1`].
    pub protocol: Protocol,
    /// An already-allow-listed query string (without the `?`) to append to the
    /// upstream URL, e.g. `scroll=1m` to open a scroll. The engine filters this
    /// to cursor-safe params before it reaches here; the sink appends it verbatim.
    pub query: Option<String>,
    /// The W3C trace context to forward downstream (`traceparent`).
    pub trace: Option<TraceContext>,
    /// Client headers to relay verbatim to the upstream (the forwarding policy's
    /// output). Applied before [`trace`](Self::trace). Empty by default.
    pub forward_headers: Vec<(String, String)>,
}

impl SearchOp {
    /// Constructs a search operation (defaulting to HTTP/1.1 upstream).
    #[must_use]
    pub fn new(target: Target, body: Vec<u8>) -> Self {
        Self {
            target,
            body,
            protocol: Protocol::Http1,
            query: None,
            trace: None,
            forward_headers: Vec::new(),
        }
    }

    /// Sets the upstream protocol for this op (builder style).
    #[must_use]
    pub fn with_protocol(mut self, protocol: Protocol) -> Self {
        self.protocol = protocol;
        self
    }

    /// Sets the (already allow-listed) upstream query string (builder style).
    #[must_use]
    pub fn with_query(mut self, query: Option<String>) -> Self {
        self.query = query;
        self
    }

    /// Sets the trace context to propagate downstream (builder style).
    #[must_use]
    pub fn with_trace(mut self, trace: Option<TraceContext>) -> Self {
        self.trace = trace;
        self
    }

    /// Sets the client headers to relay verbatim to the upstream (builder style).
    #[must_use]
    pub fn with_forward_headers(mut self, headers: Vec<(String, String)>) -> Self {
        self.forward_headers = headers;
        self
    }
}

/// The outcome of a search: the upstream status and raw response body (the
/// hits, before the read-path field strip).
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct SearchOutcome {
    /// The upstream HTTP status.
    pub status: u16,
    /// The raw upstream response body (the hits envelope).
    pub body: Vec<u8>,
    /// Whether this search rode a reused pooled connection (NFR-P telemetry).
    pub pool_reuse: bool,
}

impl SearchOutcome {
    /// Constructs a search outcome.
    #[must_use]
    pub fn new(status: u16, body: Vec<u8>) -> Self {
        Self {
            status,
            body,
            pool_reuse: false,
        }
    }

    /// Records whether the dispatch reused a pooled connection (builder style).
    #[must_use]
    pub fn with_pool_reuse(mut self, reused: bool) -> Self {
        self.pool_reuse = reused;
        self
    }
}

/// The outcome of a count: the upstream status and the matched document count.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct CountOutcome {
    /// The upstream HTTP status.
    pub status: u16,
    /// The number of matching documents.
    pub count: u64,
    /// Whether this count rode a reused pooled connection (NFR-P telemetry).
    pub pool_reuse: bool,
}

impl CountOutcome {
    /// Constructs a count outcome.
    #[must_use]
    pub fn new(status: u16, count: u64) -> Self {
        Self {
            status,
            count,
            pool_reuse: false,
        }
    }

    /// Records whether the dispatch reused a pooled connection (builder style).
    #[must_use]
    pub fn with_pool_reuse(mut self, reused: bool) -> Self {
        self.pool_reuse = reused;
        self
    }
}

/// A raw cursor passthrough op (`docs/03` §6): forward `method path` with `body`
/// to the specific `cluster` the cursor is pinned to, scroll/PIT continue,
/// clear, or close. Unlike the typed ops, the destination is *already resolved*
/// (the engine recovered it from the cursor's signed envelope), so this carries
/// the cluster directly rather than a partition.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct CursorOp {
    /// The cluster the cursor is pinned to.
    pub cluster: ClusterId,
    /// The HTTP method to forward (continue is `POST`/`GET`, clear/close `DELETE`).
    pub method: HttpMethod,
    /// The upstream path (e.g. `/_search/scroll`), already with the real cursor id.
    pub path: String,
    /// The request body to forward (the real, unwrapped cursor id substituted in).
    pub body: Vec<u8>,
    /// An already-allow-listed query string (without the `?`) to append to the
    /// upstream URL, e.g. `keep_alive=1m` on PIT create. Filtered by the engine.
    pub query: Option<String>,
    /// The pinned cluster's base URL, when the engine knows it (the placement that
    /// opened the cursor supplied it). `None` for an affinity continue recovered
    /// from the envelope alone: the sink then reuses the pool the opening request
    /// already built for this cluster, erroring only if none exists.
    pub endpoint: Option<String>,
    /// The upstream wire protocol. Defaults to [`Protocol::Http1`].
    pub protocol: Protocol,
    /// The W3C trace context to forward downstream.
    pub trace: Option<TraceContext>,
    /// Client headers to relay verbatim to the upstream (the forwarding policy's
    /// output). Applied before [`trace`](Self::trace), so a proxy-injected trace
    /// header wins when span export is on. Empty by default.
    pub forward_headers: Vec<(String, String)>,
}

impl CursorOp {
    /// Constructs a cursor passthrough op (defaulting to HTTP/1.1 upstream).
    #[must_use]
    pub fn new(
        cluster: ClusterId,
        method: HttpMethod,
        path: impl Into<String>,
        body: Vec<u8>,
    ) -> Self {
        Self {
            cluster,
            method,
            path: path.into(),
            body,
            query: None,
            endpoint: None,
            protocol: Protocol::Http1,
            trace: None,
            forward_headers: Vec::new(),
        }
    }

    /// Sets the client headers to relay verbatim to the upstream (builder style).
    #[must_use]
    pub fn with_forward_headers(mut self, headers: Vec<(String, String)>) -> Self {
        self.forward_headers = headers;
        self
    }

    /// Sets the pinned cluster's base URL (builder style), when the engine knows
    /// it. Lets the sink build the pool for an affinity request even on an
    /// instance that did not serve the opening call.
    #[must_use]
    pub fn with_endpoint(mut self, endpoint: Option<String>) -> Self {
        self.endpoint = endpoint;
        self
    }

    /// Sets the upstream wire protocol (builder style).
    #[must_use]
    pub fn with_protocol(mut self, protocol: Protocol) -> Self {
        self.protocol = protocol;
        self
    }

    /// Sets the (already allow-listed) upstream query string (builder style).
    #[must_use]
    pub fn with_query(mut self, query: Option<String>) -> Self {
        self.query = query;
        self
    }

    /// Sets the trace context to propagate downstream (builder style).
    #[must_use]
    pub fn with_trace(mut self, trace: Option<TraceContext>) -> Self {
        self.trace = trace;
        self
    }
}

/// A verbatim forward whose request body is a **stream**, not buffered bytes
/// (ADR-014 stage 2): the same destination shape as [`CursorOp`] but the body is
/// supplied separately as a [`ByteBody`](crate::ByteBody) so it can be
/// piped from the downstream connection straight to the upstream without ever
/// being collected. Used by the tenant-agnostic passthrough path.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct ForwardOp {
    /// The cluster to forward to.
    pub cluster: ClusterId,
    /// The HTTP method to forward.
    pub method: HttpMethod,
    /// The upstream path, forwarded verbatim.
    pub path: String,
    /// An already-allow-listed query string (without the `?`) to append upstream.
    pub query: Option<String>,
    /// The cluster's base URL, when known (so the pool can be built on any
    /// instance). `None` reuses an existing pool, erroring if none exists.
    pub endpoint: Option<String>,
    /// The upstream wire protocol. Defaults to [`Protocol::Http1`].
    pub protocol: Protocol,
    /// The W3C trace context to forward downstream.
    pub trace: Option<TraceContext>,
    /// Client headers to relay verbatim to the upstream (the forwarding policy's
    /// output). Applied before [`trace`](Self::trace). Empty by default.
    pub forward_headers: Vec<(String, String)>,
}

impl ForwardOp {
    /// Constructs a streaming forward op (defaulting to HTTP/1.1 upstream).
    #[must_use]
    pub fn new(cluster: ClusterId, method: HttpMethod, path: impl Into<String>) -> Self {
        Self {
            cluster,
            method,
            path: path.into(),
            query: None,
            endpoint: None,
            protocol: Protocol::Http1,
            trace: None,
            forward_headers: Vec::new(),
        }
    }

    /// Sets the client headers to relay verbatim to the upstream (builder style).
    #[must_use]
    pub fn with_forward_headers(mut self, headers: Vec<(String, String)>) -> Self {
        self.forward_headers = headers;
        self
    }

    /// Sets the cluster's base URL (builder style).
    #[must_use]
    pub fn with_endpoint(mut self, endpoint: Option<String>) -> Self {
        self.endpoint = endpoint;
        self
    }

    /// Sets the (already allow-listed) upstream query string (builder style).
    #[must_use]
    pub fn with_query(mut self, query: Option<String>) -> Self {
        self.query = query;
        self
    }

    /// Sets the upstream wire protocol (builder style).
    #[must_use]
    pub fn with_protocol(mut self, protocol: Protocol) -> Self {
        self.protocol = protocol;
        self
    }

    /// Sets the trace context to propagate downstream (builder style).
    #[must_use]
    pub fn with_trace(mut self, trace: Option<TraceContext>) -> Self {
        self.trace = trace;
        self
    }
}

/// The outcome of a **streaming** verbatim forward (ADR-014): the upstream status
/// and its response body as a live [`ByteBody`](crate::ByteBody) stream, piped
/// back to the client without ever being collected. Unlike [`CursorOutcome`], the
/// body is not materialized here, so this carries no derives (the stream is
/// one-shot).
pub struct StreamingForward {
    /// The upstream HTTP status.
    pub status: u16,
    /// The upstream response body, streamed back verbatim.
    pub body: crate::ByteBody,
    /// The upstream `Content-Type`, forwarded verbatim so a non-JSON passthrough
    /// body is not mislabeled `application/json`. `None` ⇒ the caller defaults to
    /// JSON.
    pub content_type: Option<String>,
    /// Whether this op rode a reused pooled connection (NFR-P telemetry).
    pub pool_reuse: bool,
}

impl std::fmt::Debug for StreamingForward {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // The streamed body is not `Debug`; show the shape.
        f.debug_struct("StreamingForward")
            .field("status", &self.status)
            .field("pool_reuse", &self.pool_reuse)
            .finish_non_exhaustive()
    }
}

/// The outcome of a **streaming** search (ADR-014, final stage): the upstream
/// status and its response body as a live [`ByteBody`](crate::ByteBody), piped
/// back through the engine's hit transform without ever being collected. Like
/// [`StreamingForward`], the body is one-shot, so this carries no derives.
pub struct StreamingSearch {
    /// The upstream HTTP status.
    pub status: u16,
    /// The upstream response body, streamed back to be transformed on the fly.
    pub body: crate::ByteBody,
    /// Whether this search rode a reused pooled connection (NFR-P telemetry).
    pub pool_reuse: bool,
}

impl std::fmt::Debug for StreamingSearch {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StreamingSearch")
            .field("status", &self.status)
            .field("pool_reuse", &self.pool_reuse)
            .finish_non_exhaustive()
    }
}

/// The outcome of a cursor passthrough: the upstream status and raw body,
/// forwarded back to the client verbatim.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct CursorOutcome {
    /// The upstream HTTP status.
    pub status: u16,
    /// The raw upstream response body.
    pub body: Vec<u8>,
    /// The upstream `Content-Type`, forwarded verbatim so an admin/cursor
    /// passthrough body (e.g. a `_cat` `text/plain`) is not mislabeled
    /// `application/json`. `None` ⇒ the caller defaults to JSON.
    pub content_type: Option<String>,
    /// Whether this op rode a reused pooled connection (NFR-P telemetry).
    pub pool_reuse: bool,
}

impl CursorOutcome {
    /// Constructs a cursor outcome.
    #[must_use]
    pub fn new(status: u16, body: Vec<u8>) -> Self {
        Self {
            status,
            body,
            content_type: None,
            pool_reuse: false,
        }
    }

    /// Records whether the dispatch reused a pooled connection (builder style).
    #[must_use]
    pub fn with_pool_reuse(mut self, reused: bool) -> Self {
        self.pool_reuse = reused;
        self
    }

    /// Carries the upstream `Content-Type` (builder style).
    #[must_use]
    pub fn with_content_type(mut self, content_type: Option<String>) -> Self {
        self.content_type = content_type;
        self
    }
}

/// Where reads come from.
///
/// The read counterpart of [`Sink`](crate::Sink). Kept separate because a read
/// is inherently direct-to-cluster: a redundancy `QueueSink` can absorb writes
/// but cannot answer a get-by-id or a search.
///
/// # Invariants
///
/// - MUST NOT panic; return [`SinkError`] for every transport/upstream failure
///   (NFR-R1). A missing document is *not* an error, it is a
///   [`ReadOutcome`] with `found == false`.
pub trait Reader: Send + Sync {
    /// Fetches a single document by physical id.
    ///
    /// # Errors
    ///
    /// Returns [`SinkError`] if the upstream cannot be reached or returns a
    /// server error (a 404 for a missing document is a normal not-found
    /// outcome, not an error).
    fn get(
        &self,
        op: ReadOp,
    ) -> impl std::future::Future<Output = Result<ReadOutcome, SinkError>> + Send;

    /// Runs a search, returning the raw hits envelope.
    ///
    /// # Errors
    ///
    /// Returns [`SinkError`] if the upstream cannot be reached or returns a
    /// server error.
    fn search(
        &self,
        op: SearchOp,
    ) -> impl std::future::Future<Output = Result<SearchOutcome, SinkError>> + Send;

    /// Counts the documents matching a (partition-filtered) query.
    ///
    /// Takes the same [`SearchOp`] as [`Reader::search`], the wrapped query is
    /// identical, but hits the count endpoint, returning only the total.
    ///
    /// # Errors
    ///
    /// Returns [`SinkError`] if the upstream cannot be reached or returns a
    /// server error.
    fn count(
        &self,
        op: SearchOp,
    ) -> impl std::future::Future<Output = Result<CountOutcome, SinkError>> + Send;

    /// Forwards a raw cursor request to its pinned cluster (scroll/PIT continue,
    /// clear, close). The default is **unsupported**, a sink that cannot
    /// passthrough (the in-memory test sink, a write-only queue) rejects it;
    /// `OpenSearchSink` overrides it with a real upstream call.
    ///
    /// # Errors
    ///
    /// Returns [`SinkError`] if the sink does not support passthrough or the
    /// upstream cannot be reached.
    fn cursor(
        &self,
        _op: CursorOp,
    ) -> impl std::future::Future<Output = Result<CursorOutcome, SinkError>> + Send {
        async {
            Err(SinkError::Transport {
                kind: "cursor passthrough not supported by this sink",
            })
        }
    }

    /// Runs a search whose **response** streams back (ADR-014, final stage): the
    /// upstream hits envelope is piped to the engine's hit transform without being
    /// collected, so a large response (e.g. heavy `aggregations`) never lands in
    /// memory. The default is **unsupported**; `OpenSearchSink` overrides it with a
    /// real streamed upstream call.
    ///
    /// # Errors
    ///
    /// Returns [`SinkError`] if the sink does not support streaming search or the
    /// upstream cannot be reached or returns a server error.
    fn search_stream(
        &self,
        _op: SearchOp,
    ) -> impl std::future::Future<Output = Result<StreamingSearch, SinkError>> + Send {
        async {
            Err(SinkError::Transport {
                kind: "streaming search not supported by this sink",
            })
        }
    }

    /// Forwards a request to a cluster with the body supplied as a **stream**
    /// (ADR-014 stage 2): the verbatim-passthrough path pipes the downstream body
    /// straight upstream without buffering. The default is **unsupported**;
    /// `OpenSearchSink` overrides it with a real streamed upstream call.
    ///
    /// # Errors
    ///
    /// Returns [`SinkError`] if the sink does not support streaming forward or the
    /// upstream cannot be reached.
    fn forward_stream(
        &self,
        _op: ForwardOp,
        _body: crate::opensearch::ByteBody,
    ) -> impl std::future::Future<Output = Result<StreamingForward, SinkError>> + Send {
        async {
            Err(SinkError::Transport {
                kind: "streaming forward not supported by this sink",
            })
        }
    }
}