-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathpublisher.rs
More file actions
10045 lines (9359 loc) · 393 KB
/
Copy pathpublisher.rs
File metadata and controls
10045 lines (9359 loc) · 393 KB
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Publisher response handler.
//!
//! Publisher fallback has three delivery modes that must remain explicit at
//! the API boundary:
//! - pass-through for non-processable `2xx` content
//! - streamed processing for stream-safe processable responses
//! - buffered responses for unsupported encodings or `204/205`
//!
//! Unsupported `Content-Encoding` values must bypass rewriting entirely. The
//! streaming processor treats unknown encodings as identity, so publisher code
//! must gate them out before the body enters the rewrite pipeline.
//!
//! **Note on platform coupling:** The handler boundaries use portable HTTP
//! types: [`handle_publisher_request`] and [`stream_publisher_body`] take and
//! return `http::Request`/`http::Response` over `EdgeBody`, and platform I/O is
//! reached through `RuntimeServices` rather than `fastly::*` directly. The
//! streaming processor itself is generic: `process_response_streaming` writes
//! into any [`Write`] (a `Vec<u8>` for buffered routes, a streaming writer for
//! the streaming route). It is not a content-rewriting concern.
use std::borrow::Cow;
use std::io::Write;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use brotli::Decompressor;
use brotli::enc::BrotliEncoderParams;
use brotli::enc::writer::CompressorWriter;
use cookie::CookieJar;
use edgezero_core::body::Body as EdgeBody;
use error_stack::{Report, ResultExt};
use flate2::read::ZlibDecoder;
use flate2::write::{GzEncoder, ZlibEncoder};
use futures::StreamExt as _;
use http::{HeaderValue, Method, Request, Response, StatusCode, Uri, header};
use crate::auction::endpoints::{
merge_auction_eids, resolve_auction_eids, resolve_client_auction_eids,
};
use crate::auction::orchestrator::{
AuctionOrchestrator, DispatchAuctionOutcome, DispatchedAuction,
};
use crate::auction::telemetry::{
AuctionObservationContext, AuctionSource, AuctionTerminalOutcome, build_auction_events,
emit_auction_events_best_effort_lazy,
};
use crate::auction::types::{
AuctionContext, AuctionRequest, Bid, DeviceInfo, PublisherInfo, SiteInfo, UserInfo,
};
use crate::consent::{consent_allows_server_side_auction, gate_eids_by_consent};
use crate::constants::{COOKIE_TS_EIDS, HEADER_X_COMPRESS_HINT};
use crate::cookies::handle_request_cookies;
use crate::ec::EcContext;
use crate::ec::kv::KvIdentityGraph;
use crate::ec::registry::PartnerRegistry;
use crate::error::TrustedServerError;
use crate::http_util::{RequestInfo, is_navigation_request, serve_static_with_etag};
use crate::integrations::IntegrationRegistry;
use crate::platform::{GeoInfo, PlatformBackendSpec, PlatformHttpRequest, RuntimeServices};
use crate::price_bucket::{PriceGranularity, price_bucket};
use crate::response_privacy::CDN_CACHE_HEADERS;
use crate::rsc_flight::RscFlightUrlRewriter;
use crate::settings::Settings;
use crate::streaming_processor::{
BodyStreamDecoder, BodyStreamEncoder, Compression, GzipDecodeReader, PipelineConfig,
STREAM_CHUNK_SIZE, StreamProcessor, StreamingPipeline,
};
use crate::streaming_replacer::create_url_replacer;
const SUPPORTED_ENCODING_VALUES: [&str; 3] = ["gzip", "deflate", "br"];
const DEFAULT_PUBLISHER_FIRST_BYTE_TIMEOUT: Duration = Duration::from_secs(15);
fn body_as_reader(
body: EdgeBody,
) -> Result<std::io::Cursor<bytes::Bytes>, Report<TrustedServerError>> {
let bytes = body.into_bytes().ok_or_else(|| {
Report::new(TrustedServerError::Proxy {
message: "streaming body cannot be processed by sync publisher pipeline".to_string(),
})
})?;
Ok(std::io::Cursor::new(bytes))
}
struct BodyChunkSource {
body: Option<EdgeBody>,
chunk_size: usize,
max_bytes: usize,
bytes_seen: usize,
once_offset: usize,
}
impl BodyChunkSource {
fn new(body: EdgeBody, chunk_size: usize) -> Self {
Self {
body: Some(body),
chunk_size,
max_bytes: usize::MAX,
bytes_seen: 0,
once_offset: 0,
}
}
fn with_max_bytes(mut self, max_bytes: usize) -> Self {
self.max_bytes = max_bytes;
self
}
async fn next_chunk(&mut self) -> Result<Option<bytes::Bytes>, Report<TrustedServerError>> {
// The body is polled in place (never moved out across an await) so a
// cancelled `next_chunk` future leaves the source resumable instead of
// silently reporting end-of-stream on the next call.
let pulled = match &mut self.body {
None => Ok(None),
Some(EdgeBody::Once(bytes)) => {
let end = (self.once_offset + self.chunk_size).min(bytes.len());
if self.once_offset >= end {
Ok(None)
} else {
let chunk = bytes.slice(self.once_offset..end);
self.once_offset = end;
Ok(Some(chunk))
}
}
Some(EdgeBody::Stream(stream)) => match stream.next().await {
Some(Ok(chunk)) => Ok(Some(chunk)),
Some(Err(err)) => Err(Report::new(TrustedServerError::Proxy {
message: format!("Failed to read publisher origin body stream: {err}"),
})),
None => Ok(None),
},
};
let chunk = match pulled {
Ok(Some(chunk)) => chunk,
Ok(None) => {
self.body = None;
return Ok(None);
}
Err(err) => {
self.body = None;
return Err(err);
}
};
self.bytes_seen = self.bytes_seen.checked_add(chunk.len()).ok_or_else(|| {
Report::new(TrustedServerError::Proxy {
message: "publisher origin body byte count overflowed".to_string(),
})
})?;
if self.bytes_seen > self.max_bytes {
return Err(Report::new(TrustedServerError::Proxy {
message: format!(
"publisher origin body exceeded {}-byte streaming limit",
self.max_bytes
),
}));
}
Ok(Some(chunk))
}
}
fn process_and_encode_chunk<P: StreamProcessor>(
processor: &mut P,
encoder: &mut BodyStreamEncoder,
chunk: &[u8],
is_last: bool,
process_error: &str,
) -> Result<Option<bytes::Bytes>, Report<TrustedServerError>> {
let processed =
processor
.process_chunk(chunk, is_last)
.change_context(TrustedServerError::Proxy {
message: process_error.to_string(),
})?;
if processed.is_empty() {
return Ok(None);
}
let encoded = encoder.encode_chunk(processed)?;
if encoded.is_empty() {
return Ok(None);
}
Ok(Some(bytes::Bytes::from(encoded)))
}
// By-value signature so `map_err(publisher_stream_error)` works directly.
#[allow(clippy::needless_pass_by_value)]
fn publisher_stream_error(err: Report<TrustedServerError>) -> std::io::Error {
std::io::Error::other(format!("{err:?}"))
}
fn not_found_response() -> Response<EdgeBody> {
let mut response = Response::new(EdgeBody::from("Not Found"));
*response.status_mut() = StatusCode::NOT_FOUND;
response
}
fn restrict_accept_encoding(req: &mut Request<EdgeBody>) {
// If the client sent no Accept-Encoding, leave the request unchanged so the
// origin responds without compression. Adding encodings here would cause the
// origin to compress its response even though the client never asked for it,
// and the client would then receive content it cannot decode.
let Some(current) = req
.headers()
.get(header::ACCEPT_ENCODING)
.and_then(|value| value.to_str().ok())
.map(str::to_owned)
else {
return;
};
req.headers_mut().insert(
header::ACCEPT_ENCODING,
HeaderValue::from_str(&select_supported_accept_encoding(¤t))
.expect("supported accept-encoding should be a valid header value"),
);
}
fn select_supported_accept_encoding(client_accept_encoding: &str) -> String {
let supported_subset = SUPPORTED_ENCODING_VALUES
.into_iter()
.filter(|encoding| client_accepts_content_encoding(client_accept_encoding, encoding))
.collect::<Vec<_>>();
if supported_subset.is_empty() {
return "identity".to_string();
}
supported_subset.join(", ")
}
fn client_accepts_content_encoding(header_value: &str, encoding: &str) -> bool {
accept_encoding_qvalue(header_value, encoding)
.or_else(|| accept_encoding_qvalue(header_value, "*"))
.is_some_and(|qvalue| qvalue > 0.0)
}
fn accept_encoding_qvalue(header_value: &str, target: &str) -> Option<f32> {
let mut matched_qvalue = None;
for item in header_value.split(',') {
let item = item.trim();
if item.is_empty() {
continue;
}
let mut parts = item.split(';');
let Some(token) = parts.next().map(str::trim) else {
continue;
};
if !token.eq_ignore_ascii_case(target) {
continue;
}
let mut qvalue = 1.0;
for parameter in parts {
let Some((name, value)) = parameter.trim().split_once('=') else {
continue;
};
if name.trim().eq_ignore_ascii_case("q")
&& let Ok(parsed_qvalue) = value.trim().parse::<f32>()
{
qvalue = parsed_qvalue;
}
}
// First match wins per RFC 7231 — duplicate tokens are non-normative,
// but using first-match is the conventional interpretation.
matched_qvalue = Some(qvalue);
break;
}
matched_qvalue
}
/// Unified tsjs static serving: `/static/tsjs=<filename>`
///
/// Serves two types of bundles:
/// - **Unified bundle** (`tsjs-unified.min.js`): core + immediate (non-deferred)
/// integration modules.
/// - **Deferred module** (`tsjs-{id}.min.js`): a single self-contained IIFE for
/// modules loaded with `defer` (e.g., prebid).
///
/// # Errors
///
/// This function never returns an error; the Result type is for API consistency.
pub fn handle_tsjs_dynamic(
req: &Request<EdgeBody>,
integration_registry: &IntegrationRegistry,
) -> Result<Response<EdgeBody>, Report<TrustedServerError>> {
const PREFIX: &str = "/static/tsjs=";
const UNIFIED_FILENAMES: &[&str] = &["tsjs-unified.js", "tsjs-unified.min.js"];
let path = req.uri().path();
if !path.starts_with(PREFIX) {
return Ok(not_found_response());
}
let filename = &path[PREFIX.len()..];
if UNIFIED_FILENAMES.contains(&filename) {
// Serve core + immediate modules (excludes deferred like prebid)
let module_ids = integration_registry.js_module_ids_immediate();
let body = trusted_server_js::concatenate_modules(&module_ids);
let mut resp = serve_static_with_etag(&body, req, "application/javascript; charset=utf-8");
resp.headers_mut()
.insert(HEADER_X_COMPRESS_HINT, HeaderValue::from_static("on"));
return Ok(resp);
}
if let Some(module_id) = parse_single_module_filename(filename) {
// Deferred modules and the conditionally injected diagnostics module
// are served as content-addressed standalone assets. Delivery remains
// cookie-independent so the static response can stay publicly cached.
let deferred_ids = integration_registry.js_module_ids_deferred();
let diagnostics_standalone = module_id
== crate::integrations::gpt_diagnostics::GPT_DIAGNOSTICS_INTEGRATION_ID
&& integration_registry.integration_enabled(module_id);
if !deferred_ids.contains(&module_id) && !diagnostics_standalone {
return Ok(not_found_response());
}
if let Some(content) = trusted_server_js::module_bundle(module_id) {
let mut resp =
serve_static_with_etag(content, req, "application/javascript; charset=utf-8");
resp.headers_mut()
.insert(HEADER_X_COMPRESS_HINT, HeaderValue::from_static("on"));
return Ok(resp);
}
}
Ok(not_found_response())
}
/// Extract a module ID from a deferred-module filename like `tsjs-sourcepoint.min.js`.
///
/// Returns `Some(&'static str)` if the filename matches a known JS module ID,
/// `None` otherwise. The caller must additionally verify that the module is
/// both deferred and enabled via the [`IntegrationRegistry`].
#[must_use]
fn parse_single_module_filename(filename: &str) -> Option<&'static str> {
let stem = filename
.strip_prefix("tsjs-")
.and_then(|s| s.strip_suffix(".min.js").or_else(|| s.strip_suffix(".js")))?;
trusted_server_js::all_module_ids()
.into_iter()
.find(|&id| id == stem)
}
/// Parameters for processing response streaming.
struct ProcessResponseParams<'a> {
content_encoding: &'a str,
origin_host: &'a str,
origin_url: &'a str,
request_host: &'a str,
request_scheme: &'a str,
settings: &'a Settings,
content_type: &'a str,
integration_registry: &'a IntegrationRegistry,
ad_slots_script: Option<&'a str>,
ad_bids_state: &'a Arc<Mutex<Option<String>>>,
gpt_diagnostics:
Option<&'a crate::integrations::gpt_diagnostics::GptDiagnosticsRequestDecision>,
}
struct PublisherBodyProcessor {
inner: Box<dyn StreamProcessor>,
}
impl PublisherBodyProcessor {
fn new(
params: &OwnedProcessResponseParams,
settings: &Settings,
integration_registry: &IntegrationRegistry,
) -> Result<Self, Report<TrustedServerError>> {
let is_html = is_html_content_type(¶ms.content_type);
let is_rsc_flight =
content_type_contains_ascii_case_insensitive(¶ms.content_type, "text/x-component");
let inner: Box<dyn StreamProcessor> = if is_html {
Box::new(create_html_stream_processor(HtmlStreamProcessorParams {
origin_host: ¶ms.origin_host,
request_host: ¶ms.request_host,
request_scheme: ¶ms.request_scheme,
settings,
integration_registry,
ad_slots_script: params.ad_slots_script.as_deref().map(str::to_string),
ad_bids_state: Arc::clone(¶ms.ad_bids_state),
gpt_diagnostics: params.gpt_diagnostics.clone(),
})?)
} else if is_rsc_flight {
Box::new(RscFlightUrlRewriter::new(
¶ms.origin_host,
¶ms.origin_url,
¶ms.request_host,
¶ms.request_scheme,
))
} else {
Box::new(create_url_replacer(
¶ms.origin_host,
¶ms.origin_url,
¶ms.request_host,
¶ms.request_scheme,
))
};
Ok(Self { inner })
}
}
impl StreamProcessor for PublisherBodyProcessor {
fn process_chunk(&mut self, chunk: &[u8], is_last: bool) -> Result<Vec<u8>, std::io::Error> {
self.inner.process_chunk(chunk, is_last)
}
}
/// Process response body through the streaming pipeline.
///
/// Selects the appropriate processor based on content type (HTML rewriter,
/// RSC Flight rewriter, or URL replacer) and pipes chunks from `body`
/// through it into `output`. The caller decides what `output` is — a
/// `Vec<u8>` for buffered responses, or a `StreamingBody` for streaming.
///
/// # Errors
///
/// Returns an error if processor creation or chunk processing fails.
fn process_response_streaming<W: Write>(
body: EdgeBody,
output: &mut W,
params: &ProcessResponseParams,
) -> Result<(), Report<TrustedServerError>> {
let is_html = is_html_content_type(params.content_type);
let is_rsc_flight =
content_type_contains_ascii_case_insensitive(params.content_type, "text/x-component");
log::debug!(
"process_response_streaming: content_type={}, content_encoding={}, is_html={}, is_rsc_flight={}",
params.content_type,
params.content_encoding,
is_html,
is_rsc_flight
);
let compression = Compression::from_content_encoding(params.content_encoding);
let config = PipelineConfig {
input_compression: compression,
output_compression: compression,
chunk_size: 8192,
};
// Bound how much decoded gzip output may sit in the heap at once, using the
// same ceiling the buffered writer enforces on the rewritten output: a gzip
// bomb is then rejected mid-decode instead of materializing its full
// expansion first. The bound is per-step, so a large honest body still
// streams through and only the buffered writer judges the total — otherwise
// gzip would reject bodies the identity, deflate and brotli paths accept.
let max_pending_decoded_bytes = params.settings.publisher.max_buffered_body_bytes;
if is_html {
let processor = create_html_stream_processor(HtmlStreamProcessorParams {
origin_host: params.origin_host,
request_host: params.request_host,
request_scheme: params.request_scheme,
settings: params.settings,
integration_registry: params.integration_registry,
ad_slots_script: params.ad_slots_script.map(str::to_string),
ad_bids_state: params.ad_bids_state.clone(),
gpt_diagnostics: params.gpt_diagnostics.cloned(),
})?;
StreamingPipeline::new(config, processor)
.with_max_pending_decoded_bytes(max_pending_decoded_bytes)
.process(body_as_reader(body)?, output)?;
} else if is_rsc_flight {
// RSC Flight responses are length-prefixed (T rows). A naive string replacement will
// corrupt the stream by changing byte lengths without updating the prefixes.
let processor = RscFlightUrlRewriter::new(
params.origin_host,
params.origin_url,
params.request_host,
params.request_scheme,
);
StreamingPipeline::new(config, processor)
.with_max_pending_decoded_bytes(max_pending_decoded_bytes)
.process(body_as_reader(body)?, output)?;
} else {
let replacer = create_url_replacer(
params.origin_host,
params.origin_url,
params.request_host,
params.request_scheme,
);
StreamingPipeline::new(config, replacer)
.with_max_pending_decoded_bytes(max_pending_decoded_bytes)
.process(body_as_reader(body)?, output)?;
}
Ok(())
}
async fn process_response_streaming_async<W: Write>(
body: EdgeBody,
output: &mut W,
params: &OwnedProcessResponseParams,
settings: &Settings,
integration_registry: &IntegrationRegistry,
) -> Result<(), Report<TrustedServerError>> {
log::debug!(
"process_response_streaming_async: content_type={}, content_encoding={}",
params.content_type,
params.content_encoding
);
let compression = Compression::from_content_encoding(¶ms.content_encoding);
let mut processor = PublisherBodyProcessor::new(params, settings, integration_registry)?;
process_body_chunks_async(
body,
output,
&mut processor,
compression,
settings.publisher.max_buffered_body_bytes,
)
.await
}
/// Pull, decode, process, and encode the next chunk of a no-hold pipeline.
///
/// Returns `Ok(None)` when the source is exhausted; the caller must then emit
/// [`passthrough_finish_segments`]. Shared by the write-sink driver
/// ([`process_body_chunks_async`]) and the lazy publisher body stream so the
/// two no-hold paths cannot drift apart.
async fn passthrough_step<P: StreamProcessor>(
source: &mut BodyChunkSource,
decoder: &mut BodyStreamDecoder,
encoder: &mut BodyStreamEncoder,
processor: &mut P,
) -> Result<Option<Vec<bytes::Bytes>>, Report<TrustedServerError>> {
let Some(raw_chunk) = source.next_chunk().await? else {
return Ok(None);
};
let decoded = decoder.decode_chunk(raw_chunk)?;
if decoded.is_empty() {
return Ok(Some(Vec::new()));
}
let mut segments = Vec::new();
if let Some(encoded) = process_and_encode_chunk(
processor,
encoder,
&decoded,
false,
"Failed to process chunk",
)? {
segments.push(encoded);
}
Ok(Some(segments))
}
async fn process_body_chunks_async<W: Write, P: StreamProcessor>(
body: EdgeBody,
writer: &mut W,
processor: &mut P,
compression: Compression,
max_body_bytes: usize,
) -> Result<(), Report<TrustedServerError>> {
let mut decoder = BodyStreamDecoder::new(compression, max_body_bytes);
let mut encoder = BodyStreamEncoder::new(compression);
let mut source = BodyChunkSource::new(body, STREAM_CHUNK_SIZE).with_max_bytes(max_body_bytes);
while let Some(segments) =
passthrough_step(&mut source, &mut decoder, &mut encoder, processor).await?
{
for encoded in segments {
write_encoded_segment(writer, &encoded)?;
}
}
for encoded in passthrough_finish_segments(processor, &mut decoder, &mut encoder)? {
write_encoded_segment(writer, &encoded)?;
}
writer.flush().change_context(TrustedServerError::Proxy {
message: "Failed to flush output".to_string(),
})?;
Ok(())
}
/// Write one encoded output segment produced by the chunk pipeline.
fn write_encoded_segment<W: Write>(
writer: &mut W,
encoded: &[u8],
) -> Result<(), Report<TrustedServerError>> {
writer
.write_all(encoded)
.change_context(TrustedServerError::Proxy {
message: "Failed to write encoded chunk".to_string(),
})
}
/// Finalize a no-hold chunk pipeline: drain the decoder tail through the
/// processor, signal end-of-stream to the processor, and emit the encoder
/// trailer. Returns the encoded segments for the caller to emit.
fn passthrough_finish_segments<P: StreamProcessor>(
processor: &mut P,
decoder: &mut BodyStreamDecoder,
encoder: &mut BodyStreamEncoder,
) -> Result<Vec<bytes::Bytes>, Report<TrustedServerError>> {
let mut segments = Vec::new();
let decoded_tail = decoder.finish()?;
if !decoded_tail.is_empty()
&& let Some(encoded) = process_and_encode_chunk(
processor,
encoder,
&decoded_tail,
false,
"Failed to process decoded tail",
)?
{
segments.push(encoded);
}
if let Some(encoded) = process_and_encode_chunk(
processor,
encoder,
&[],
true,
"Failed to finalize processor",
)? {
segments.push(encoded);
}
let trailer = encoder.finish()?;
if !trailer.is_empty() {
segments.push(bytes::Bytes::from(trailer));
}
Ok(segments)
}
/// Owns a [`DispatchedAuction`] and logs if it is dropped uncollected.
///
/// The lazy publisher body stream can be dropped at any await point — a
/// client disconnect aborts the transfer mid-body, or the response may never
/// be polled at all. Async telemetry cannot run in `Drop`, so the loss is
/// surfaced in logs; the abandoned-auction telemetry event is only emitted on
/// error paths that can still await (see [`abandon_hold_auction`]).
struct DispatchedAuctionGuard {
dispatched: Option<DispatchedAuction>,
/// Stays `true` from dispatch until collection (or telemetry-emitting
/// abandonment) reaches a terminal result. [`Self::take`] removes the
/// dispatched auction to hand it to the async collector but deliberately
/// leaves the guard armed, so a drop *while collection is still pending* —
/// a client disconnect at the collection await point — still logs the
/// loss. [`Self::disarm`] clears it only once collection has completed.
armed: bool,
}
impl DispatchedAuctionGuard {
fn new(dispatched: DispatchedAuction) -> Self {
Self {
dispatched: Some(dispatched),
armed: true,
}
}
/// Remove the dispatched auction to begin collection. The guard stays armed
/// until [`Self::disarm`] is called, so a drop before collection reaches a
/// terminal result is still reported.
fn take(&mut self) -> Option<DispatchedAuction> {
self.dispatched.take()
}
/// Disarm the drop warning once collection (or telemetry-emitting
/// abandonment) has reached a terminal result.
fn disarm(&mut self) {
self.armed = false;
}
}
impl Drop for DispatchedAuctionGuard {
fn drop(&mut self) {
if self.armed {
log::warn!(
"Dispatched server-side auction dropped without collection; SSP bid responses discarded (publisher body stream aborted or never polled)"
);
}
}
}
/// Mutable auction-hold state threaded through the streaming hold pipeline.
struct AuctionHoldState {
hold: Option<BodyCloseHoldBuffer>,
dispatched: DispatchedAuctionGuard,
telemetry: AuctionTelemetryCarry,
}
impl AuctionHoldState {
fn new(dispatched: DispatchedAuctionGuard, telemetry: AuctionTelemetryCarry) -> Self {
Self {
hold: Some(BodyCloseHoldBuffer::new()),
dispatched,
telemetry,
}
}
}
/// Abandon the in-flight auction (if still pending) with the given telemetry
/// reason. No-op once the auction has been collected or already abandoned.
async fn abandon_hold_auction(
state: &mut AuctionHoldState,
services: &RuntimeServices,
reason: &'static str,
) {
if let Some(dispatched) = state.dispatched.take() {
emit_abandoned_auction(
services,
state.telemetry.observation.take(),
dispatched,
reason,
)
.await;
// Abandonment with telemetry is a terminal result, so the drop warning
// is no longer warranted. (A drop *during* the emit above still fires
// it, since the guard stays armed until here.)
state.dispatched.disarm();
}
}
/// Output of a single close-body hold step, split at the auction-collection
/// barrier.
///
/// `ready` is the prefix the caller must emit *before* collecting the auction,
/// so a small page whose `</body>` lands in the first source chunk still
/// streams its document prefix immediately instead of stalling behind the
/// auction. `close_found` signals that `</body` was seen: the caller emits
/// `ready`, then awaits [`hold_collect_close_tail`] to collect the auction and
/// emit the held closing tail.
struct HoldStepSegments {
ready: Vec<bytes::Bytes>,
close_found: bool,
}
/// Feed one decoded chunk through the close-body hold and processor.
///
/// Returns the ready prefix for the caller to emit — written to a client stream
/// by [`body_close_hold_loop_stream`], yielded from the lazy body by
/// [`publisher_response_into_streaming_response`]. Both async hold paths share
/// this function so their behavior cannot drift apart.
///
/// This step never awaits auction collection: it processes only the bytes the
/// hold buffer releases as ready and reports whether `</body` was seen. Holding
/// the collection out of this step is what lets callers emit the prefix before
/// the auction resolves. On processing failure the pending auction is abandoned
/// before the error is returned.
async fn hold_step_decoded_chunk<P: StreamProcessor>(
processor: &mut P,
encoder: &mut BodyStreamEncoder,
chunk: &[u8],
state: &mut AuctionHoldState,
collect_refs: &AuctionCollectDeps<'_>,
) -> Result<HoldStepSegments, Report<TrustedServerError>> {
let mut ready = Vec::new();
let bytes: Cow<'_, [u8]> = match state.hold.as_mut() {
// Once the hold has been released the chunk streams straight through,
// borrowed rather than copied.
None => Cow::Borrowed(chunk),
Some(hold_buffer) => Cow::Owned(hold_buffer.push(chunk)),
};
match process_and_encode_chunk(processor, encoder, &bytes, false, "Failed to process chunk") {
Ok(Some(encoded)) => ready.push(encoded),
Ok(None) => {}
Err(err) => {
abandon_hold_auction(state, collect_refs.services, "stream_process_error").await;
return Err(err);
}
}
let close_found = state
.hold
.as_ref()
.is_some_and(BodyCloseHoldBuffer::found_close);
Ok(HoldStepSegments { ready, close_found })
}
/// Collect the dispatched auction and process the held `</body>` tail.
///
/// Call only after [`hold_step_decoded_chunk`] (or
/// [`hold_finish_ready_segments`]) reports `close_found` and the ready prefix
/// has already been emitted:
/// collecting here — after the prefix streams — is what keeps the auction
/// riding alongside transfer instead of blocking it. Collection runs before the
/// tail is processed so `lol_html` sees live bids at the injection point.
async fn hold_collect_close_tail<P: StreamProcessor>(
processor: &mut P,
encoder: &mut BodyStreamEncoder,
state: &mut AuctionHoldState,
collect_refs: &AuctionCollectDeps<'_>,
) -> Result<Vec<bytes::Bytes>, Report<TrustedServerError>> {
let mut segments = Vec::new();
let dispatched = state
.dispatched
.take()
.expect("should have dispatched auction to collect");
collect_stream_auction(dispatched, state.telemetry.take(), collect_refs).await;
// Collection reached a terminal result; disarm only now so a drop while the
// collect await above was still pending is reported.
state.dispatched.disarm();
let held = state
.hold
.take()
.expect("should have close-body hold buffer")
.finish();
if let Some(encoded) = process_and_encode_chunk(
processor,
encoder,
&held,
false,
"Failed to process held body close",
)? {
segments.push(encoded);
}
Ok(segments)
}
/// Pull and decode the next chunk of the close-body hold pipeline, feeding it
/// through [`hold_step_decoded_chunk`].
///
/// Returns `Ok(None)` when the source is exhausted; the caller must then emit
/// [`hold_finish_ready_segments`] followed by [`hold_finish_tail_segments`]. On
/// read or decode failure the pending auction is
/// abandoned before the error is returned. Shared by the write-sink driver
/// ([`body_close_hold_loop_stream`]) and the lazy publisher body stream so
/// the two hold paths cannot drift apart.
async fn hold_step_next_chunk<P: StreamProcessor>(
source: &mut BodyChunkSource,
decoder: &mut BodyStreamDecoder,
encoder: &mut BodyStreamEncoder,
processor: &mut P,
state: &mut AuctionHoldState,
collect_refs: &AuctionCollectDeps<'_>,
) -> Result<Option<HoldStepSegments>, Report<TrustedServerError>> {
let raw_chunk = match source.next_chunk().await {
Ok(Some(chunk)) => chunk,
Ok(None) => return Ok(None),
Err(err) => {
abandon_hold_auction(state, collect_refs.services, "stream_read_error").await;
return Err(err);
}
};
let decoded = match decoder.decode_chunk(raw_chunk) {
Ok(decoded) => decoded,
Err(err) => {
abandon_hold_auction(state, collect_refs.services, "stream_decode_error").await;
return Err(err);
}
};
if decoded.is_empty() {
return Ok(Some(HoldStepSegments {
ready: Vec::new(),
close_found: false,
}));
}
hold_step_decoded_chunk(processor, encoder, &decoded, state, collect_refs)
.await
.map(Some)
}
/// Drain the decoder tail at end of the origin stream, returning the prefix the
/// caller must emit before [`hold_finish_tail_segments`].
///
/// A codec can hold document bytes back until its own finalization — the gzip
/// decoder releases the remainder of the final member at `finish()` — and that
/// remainder may be the whole document for a small page. Returning it ahead of
/// collection keeps the invariant the mid-stream path already has: only the
/// closing `</body>` tail waits for the auction, never renderable content.
///
/// On decoder failure the pending auction is abandoned before the error is
/// returned.
async fn hold_finish_ready_segments<P: StreamProcessor>(
processor: &mut P,
decoder: &mut BodyStreamDecoder,
encoder: &mut BodyStreamEncoder,
state: &mut AuctionHoldState,
collect_refs: &AuctionCollectDeps<'_>,
) -> Result<Vec<bytes::Bytes>, Report<TrustedServerError>> {
let decoded_tail = match decoder.finish() {
Ok(decoded_tail) => decoded_tail,
Err(err) => {
abandon_hold_auction(state, collect_refs.services, "stream_decode_error").await;
return Err(err);
}
};
if decoded_tail.is_empty() {
return Ok(Vec::new());
}
let step =
hold_step_decoded_chunk(processor, encoder, &decoded_tail, state, collect_refs).await?;
Ok(step.ready)
}
/// Finalize the close-body hold pipeline after [`hold_finish_ready_segments`].
///
/// Collects the auction if the close-body tag never streamed, processes the held
/// tail plus the processor's final chunk, and emits the encoder trailer. Returns
/// the encoded segments for the caller to emit.
async fn hold_finish_tail_segments<P: StreamProcessor>(
processor: &mut P,
encoder: &mut BodyStreamEncoder,
state: &mut AuctionHoldState,
collect_refs: &AuctionCollectDeps<'_>,
) -> Result<Vec<bytes::Bytes>, Report<TrustedServerError>> {
let mut segments = Vec::new();
// If the hold is still armed the auction was never collected mid-stream:
// `</body>` arrived only in the decoder tail, or the document had none at
// all. Collect now and flush the held remainder before finalizing.
if state.hold.is_some() {
segments.extend(hold_collect_close_tail(processor, encoder, state, collect_refs).await?);
}
if let Some(encoded) = process_and_encode_chunk(
processor,
encoder,
&[],
true,
"Failed to finalize processor",
)? {
segments.push(encoded);
}
let trailer = encoder.finish()?;
if !trailer.is_empty() {
segments.push(bytes::Bytes::from(trailer));
}
Ok(segments)
}
/// Create a unified HTML stream processor.
///
/// Builds the config via [`HtmlProcessorConfig::from_settings`] and then
/// layers the auction-hold streaming fields on top via
/// [`HtmlProcessorConfig::with_ad_state`], so the canonical builder stays the
/// single source of truth: a future field added to `from_settings` is
/// inherited here automatically.
///
/// The returned processor owns its state and borrows none of the arguments.
/// `use<>` states that explicitly: without it, Rust 2024 would have the opaque
/// type capture every input lifetime, forcing callers to keep the settings and
/// registry alive for as long as the processor.
struct HtmlStreamProcessorParams<'a> {
origin_host: &'a str,
request_host: &'a str,
request_scheme: &'a str,
settings: &'a Settings,
integration_registry: &'a IntegrationRegistry,
ad_slots_script: Option<String>,
ad_bids_state: Arc<Mutex<Option<String>>>,
gpt_diagnostics: Option<crate::integrations::gpt_diagnostics::GptDiagnosticsRequestDecision>,
}
fn create_html_stream_processor(
params: HtmlStreamProcessorParams<'_>,
) -> Result<impl StreamProcessor + use<>, Report<TrustedServerError>> {
use crate::html_processor::{HtmlProcessorConfig, create_html_processor};
let config = HtmlProcessorConfig::from_settings(
params.settings,
params.integration_registry,
params.origin_host,
params.request_host,
params.request_scheme,
)
.with_ad_state(params.ad_slots_script, params.ad_bids_state)
.with_gpt_diagnostics(params.gpt_diagnostics);
Ok(create_html_processor(config))
}
/// Result of publisher request handling, indicating whether the response body
/// should be streamed or has already been buffered.
pub enum PublisherResponse {
/// Response returned unmodified, ready to send via `send_to_client()`.
///
/// On streaming adapters the unmodified body may still be a live
/// [`EdgeBody::Stream`] (the origin fetch requested streaming before the
/// response was classified); it passes through to the client untouched.
Buffered(Response<EdgeBody>),
/// Response headers are ready for a streaming response. Covers processable
/// content on any status (2xx or non-2xx — e.g., branded 404/500 HTML and
/// error JSON still get URL rewriting) where the encoding is supported.
/// Post-processors run inside the streaming processor, so processable HTML
/// is streamed regardless of whether any are registered.
///
/// Adapters with platform streaming support preserve `body` as
/// [`EdgeBody::Stream`] and attach a lazy processed stream via
/// [`publisher_response_into_streaming_response`]. Buffered adapters use
/// [`buffer_publisher_response_async`] and are bounded by
/// `settings.publisher.max_buffered_body_bytes`.
Stream {
/// Response with all headers set (EC ID, cookies, etc.)
/// but body not yet written. `Content-Length` already removed.
response: Response<EdgeBody>,
/// Origin body to be piped through the streaming pipeline.
body: EdgeBody,
/// Parameters for [`process_response_streaming`].
params: Box<OwnedProcessResponseParams>,
},
/// Non-processable 2xx response (images, fonts, video). The adapter must
/// reattach the body via setting the body before returning.
/// `finalize_response()` and `send_to_client()` are applied at the outer
/// response-dispatch level, not in this arm.