File size: 17,750 Bytes
1e92f2d |
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 |
pub mod asset_graph;
pub mod combined;
pub mod conditional;
pub mod headers;
pub mod issue_context;
pub mod lazy_instantiated;
pub mod query;
pub mod request;
pub(crate) mod resolve;
pub mod route_tree;
pub mod router;
pub mod static_assets;
pub mod wrapping_source;
use std::collections::BTreeSet;
use anyhow::Result;
use futures::{TryStreamExt, stream::Stream as StreamTrait};
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_tasks::{
Completion, NonLocalValue, OperationVc, ResolvedVc, TaskInput, Upcast, ValueDefault, Vc,
trace::TraceRawVcs, util::SharedError,
};
use turbo_tasks_bytes::{Bytes, Stream, StreamRead};
use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_hash::{DeterministicHash, DeterministicHasher, Xxh3Hash64Hasher};
use turbopack_core::version::{Version, VersionedContent};
use self::{
headers::Headers, issue_context::IssueFilePathContentSource, query::Query,
route_tree::RouteTree,
};
/// The result of proxying a request to another HTTP server.
#[turbo_tasks::value(shared, operation)]
pub struct ProxyResult {
/// The HTTP status code to return.
pub status: u16,
/// Headers arranged as contiguous (name, value) pairs.
pub headers: Vec<(RcStr, RcStr)>,
/// The body to return.
#[turbo_tasks(trace_ignore)]
pub body: Body,
}
#[turbo_tasks::value_impl]
impl Version for ProxyResult {
#[turbo_tasks::function]
async fn id(&self) -> Result<Vc<RcStr>> {
let mut hash = Xxh3Hash64Hasher::new();
hash.write_u16(self.status);
for (name, value) in &self.headers {
name.deterministic_hash(&mut hash);
value.deterministic_hash(&mut hash);
}
let mut read = self.body.read();
while let Some(chunk) = read.try_next().await? {
hash.write_bytes(&chunk);
}
Ok(Vc::cell(hash.finish().to_string().into()))
}
}
/// A functor to receive the actual content of a content source result.
#[turbo_tasks::value_trait]
pub trait GetContentSourceContent {
/// Specifies data requirements for the get function. Restricting data
/// passed allows to cache the get method.
#[turbo_tasks::function]
fn vary(self: Vc<Self>) -> Vc<ContentSourceDataVary> {
ContentSourceDataVary::default().cell()
}
/// Get the content
#[turbo_tasks::function]
fn get(self: Vc<Self>, path: RcStr, data: ContentSourceData) -> Vc<ContentSourceContent>;
}
#[turbo_tasks::value(transparent)]
pub struct GetContentSourceContents(Vec<ResolvedVc<Box<dyn GetContentSourceContent>>>);
#[turbo_tasks::value]
pub struct StaticContent {
pub content: ResolvedVc<Box<dyn VersionedContent>>,
pub status_code: u16,
pub headers: ResolvedVc<HeaderList>,
}
#[turbo_tasks::value(shared)]
// TODO add Dynamic variant in future to allow streaming and server responses
/// The content of a result that is returned by a content source.
pub enum ContentSourceContent {
NotFound,
Static(ResolvedVc<StaticContent>),
HttpProxy(OperationVc<ProxyResult>),
Rewrite(ResolvedVc<Rewrite>),
/// Continue with the next route
Next,
}
/// This trait can be emitted as collectible and will be applied after the
/// request is handled and it's ensured that it finishes before the next request
/// is handled.
#[turbo_tasks::value_trait]
pub trait ContentSourceSideEffect {
#[turbo_tasks::function]
fn apply(self: Vc<Self>) -> Vc<Completion>;
}
#[turbo_tasks::value_impl]
impl GetContentSourceContent for ContentSourceContent {
#[turbo_tasks::function]
fn get(self: Vc<Self>, _path: RcStr, _data: ContentSourceData) -> Vc<ContentSourceContent> {
self
}
}
#[turbo_tasks::value_impl]
impl ContentSourceContent {
#[turbo_tasks::function]
pub async fn static_content(
content: ResolvedVc<Box<dyn VersionedContent>>,
) -> Result<Vc<ContentSourceContent>> {
Ok(ContentSourceContent::Static(
StaticContent {
content,
status_code: 200,
headers: HeaderList::empty().to_resolved().await?,
}
.resolved_cell(),
)
.cell())
}
#[turbo_tasks::function]
pub fn static_with_headers(
content: ResolvedVc<Box<dyn VersionedContent>>,
status_code: u16,
headers: ResolvedVc<HeaderList>,
) -> Vc<ContentSourceContent> {
ContentSourceContent::Static(
StaticContent {
content,
status_code,
headers,
}
.resolved_cell(),
)
.cell()
}
#[turbo_tasks::function]
pub fn not_found() -> Vc<ContentSourceContent> {
ContentSourceContent::NotFound.cell()
}
}
/// A list of headers arranged as contiguous (name, value) pairs.
#[turbo_tasks::value(transparent)]
pub struct HeaderList(Vec<(RcStr, RcStr)>);
#[turbo_tasks::value_impl]
impl HeaderList {
#[turbo_tasks::function]
pub fn new(headers: Vec<(RcStr, RcStr)>) -> Vc<Self> {
HeaderList(headers).cell()
}
#[turbo_tasks::function]
pub fn empty() -> Vc<Self> {
HeaderList(vec![]).cell()
}
}
/// Additional info passed to the ContentSource. It was extracted from the http
/// request.
///
/// Note that you might not receive information that has not been requested via
/// `ContentSource::vary()`. So make sure to request all information that's
/// needed.
#[derive(
PartialEq,
Eq,
NonLocalValue,
TraceRawVcs,
Serialize,
Deserialize,
Clone,
Debug,
Hash,
Default,
TaskInput,
)]
pub struct ContentSourceData {
/// HTTP method, if requested.
pub method: Option<RcStr>,
/// The full url (including query string), if requested.
pub url: Option<RcStr>,
/// The full url (including query string) before rewrites where applied, if
/// requested.
pub original_url: Option<RcStr>,
/// Query string items, if requested.
pub query: Option<Query>,
/// raw query string, if requested. Does not include the `?`.
pub raw_query: Option<RcStr>,
/// HTTP headers, might contain multiple headers with the same name, if
/// requested.
pub headers: Option<Headers>,
/// Raw HTTP headers, might contain multiple headers with the same name, if
/// requested.
pub raw_headers: Option<Vec<(RcStr, RcStr)>>,
/// Request body, if requested.
pub body: Option<ResolvedVc<Body>>,
/// See [ContentSourceDataVary::cache_buster].
pub cache_buster: u64,
}
pub type BodyChunk = Result<Bytes, SharedError>;
/// A request body.
#[turbo_tasks::value(shared)]
#[derive(Default, Clone, Debug)]
pub struct Body {
#[turbo_tasks(trace_ignore)]
chunks: Stream<BodyChunk>,
}
impl Body {
/// Creates a new body from a list of chunks.
pub fn new(chunks: Vec<BodyChunk>) -> Self {
Self {
chunks: Stream::new_closed(chunks),
}
}
/// Returns an iterator over the body's chunks.
pub fn read(&self) -> StreamRead<BodyChunk> {
self.chunks.read()
}
pub fn from_stream<T: StreamTrait<Item = BodyChunk> + Send + Unpin + 'static>(
source: T,
) -> Self {
Self {
chunks: Stream::from(source),
}
}
}
impl<T: Into<Bytes>> From<T> for Body {
fn from(value: T) -> Self {
Body::new(vec![Ok(value.into())])
}
}
impl ValueDefault for Body {
fn value_default() -> Vc<Self> {
Body::default().cell()
}
}
/// Filter function that describes which information is required.
#[derive(Debug, Clone, PartialEq, Eq, TraceRawVcs, Hash, Serialize, Deserialize, NonLocalValue)]
pub enum ContentSourceDataFilter {
All,
Subset(BTreeSet<String>),
}
impl ContentSourceDataFilter {
/// Merges the filtering to get a filter that covers both filters.
pub fn extend(&mut self, other: &ContentSourceDataFilter) {
match self {
ContentSourceDataFilter::All => {}
ContentSourceDataFilter::Subset(set) => match other {
ContentSourceDataFilter::All => *self = ContentSourceDataFilter::All,
ContentSourceDataFilter::Subset(set2) => set.extend(set2.iter().cloned()),
},
}
}
/// Merges the filtering to get a filter that covers both filters. Works on
/// Option<DataFilter> where None is considers as empty filter.
pub fn extend_options(
this: &mut Option<ContentSourceDataFilter>,
other: &Option<ContentSourceDataFilter>,
) {
if let Some(this) = this.as_mut() {
if let Some(other) = other.as_ref() {
this.extend(other);
}
} else {
this.clone_from(other);
}
}
/// Returns true if the filter contains the given key.
pub fn contains(&self, key: &str) -> bool {
match self {
ContentSourceDataFilter::All => true,
ContentSourceDataFilter::Subset(set) => set.contains(key),
}
}
/// Returns true if the first argument at least contains all values that the
/// second argument would contain.
pub fn fulfills(
this: &Option<ContentSourceDataFilter>,
other: &Option<ContentSourceDataFilter>,
) -> bool {
match (this, other) {
(_, None) => true,
(None, Some(_)) => false,
(Some(this), Some(other)) => match (this, other) {
(ContentSourceDataFilter::All, _) => true,
(_, ContentSourceDataFilter::All) => false,
(ContentSourceDataFilter::Subset(this), ContentSourceDataFilter::Subset(other)) => {
this.is_superset(other)
}
},
}
}
}
/// Describes additional information that need to be sent to requests to
/// ContentSource. By sending these information ContentSource responses are
/// cached-keyed by them and they can access them.
#[turbo_tasks::value(shared)]
#[derive(Debug, Default, Clone, Hash)]
pub struct ContentSourceDataVary {
pub method: bool,
pub url: bool,
pub original_url: bool,
pub query: Option<ContentSourceDataFilter>,
pub raw_query: bool,
pub headers: Option<ContentSourceDataFilter>,
pub raw_headers: bool,
pub body: bool,
/// When true, a `cache_buster` value is added to the [ContentSourceData].
/// This value will be different on every request, which ensures the
/// content is never cached.
pub cache_buster: bool,
pub placeholder_for_future_extensions: (),
}
impl ContentSourceDataVary {
/// Merges two vary specification to create a combination of both that cover
/// all information requested by either one
pub fn extend(&mut self, other: &ContentSourceDataVary) {
let ContentSourceDataVary {
method,
url,
original_url,
query,
raw_query,
headers,
raw_headers,
body,
cache_buster,
placeholder_for_future_extensions: _,
} = self;
*method = *method || other.method;
*url = *url || other.url;
*original_url = *original_url || other.original_url;
*body = *body || other.body;
*cache_buster = *cache_buster || other.cache_buster;
*raw_query = *raw_query || other.raw_query;
*raw_headers = *raw_headers || other.raw_headers;
ContentSourceDataFilter::extend_options(query, &other.query);
ContentSourceDataFilter::extend_options(headers, &other.headers);
}
/// Returns true if `self` at least contains all values that the
/// argument would contain.
pub fn fulfills(&self, other: &ContentSourceDataVary) -> bool {
// All fields must be used!
let ContentSourceDataVary {
method,
url,
original_url,
query,
raw_query,
headers,
raw_headers,
body,
cache_buster,
placeholder_for_future_extensions: _,
} = self;
if other.method && !method {
return false;
}
if other.url && !url {
return false;
}
if other.original_url && !original_url {
return false;
}
if other.body && !body {
return false;
}
if other.raw_query && !raw_query {
return false;
}
if other.raw_headers && !raw_headers {
return false;
}
if other.cache_buster && !cache_buster {
return false;
}
if !ContentSourceDataFilter::fulfills(query, &other.query) {
return false;
}
if !ContentSourceDataFilter::fulfills(headers, &other.headers) {
return false;
}
true
}
}
/// A source of content that the dev server uses to respond to http requests.
#[turbo_tasks::value_trait]
pub trait ContentSource {
#[turbo_tasks::function]
fn get_routes(self: Vc<Self>) -> Vc<RouteTree>;
/// Gets any content sources wrapped in this content source.
#[turbo_tasks::function]
fn get_children(self: Vc<Self>) -> Vc<ContentSources> {
ContentSources::empty()
}
}
pub trait ContentSourceExt {
fn issue_file_path(
self: Vc<Self>,
file_path: FileSystemPath,
description: RcStr,
) -> Vc<Box<dyn ContentSource>>;
}
impl<T> ContentSourceExt for T
where
T: Upcast<Box<dyn ContentSource>>,
{
fn issue_file_path(
self: Vc<Self>,
file_path: FileSystemPath,
description: RcStr,
) -> Vc<Box<dyn ContentSource>> {
Vc::upcast(IssueFilePathContentSource::new_file_path(
file_path,
description,
Vc::upcast(self),
))
}
}
#[turbo_tasks::value(transparent)]
pub struct ContentSources(Vec<ResolvedVc<Box<dyn ContentSource>>>);
#[turbo_tasks::value_impl]
impl ContentSources {
#[turbo_tasks::function]
pub fn empty() -> Vc<Self> {
Vc::cell(Vec::new())
}
}
/// An empty ContentSource implementation that responds with NotFound for every
/// request.
#[turbo_tasks::value]
pub struct NoContentSource;
#[turbo_tasks::value_impl]
impl NoContentSource {
#[turbo_tasks::function]
pub fn new() -> Vc<Self> {
NoContentSource.cell()
}
}
#[turbo_tasks::value_impl]
impl ContentSource for NoContentSource {
#[turbo_tasks::function]
fn get_routes(&self) -> Vc<RouteTree> {
RouteTree::empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, NonLocalValue)]
pub enum RewriteType {
Location {
/// The new path and query used to lookup content. This _does not_ need to be the original
/// path or query.
path_and_query: RcStr,
},
ContentSource {
/// [`ContentSource`]s from which to restart the lookup process. This _does not_ need to be
/// the original content source.
source: OperationVc<Box<dyn ContentSource>>,
/// The new path and query used to lookup content. This _does not_ need
/// to be the original path or query.
path_and_query: RcStr,
},
Sources {
/// [`GetContentSourceContent`]s from which to restart the lookup process. This _does not_
/// need to be the original content source.
sources: OperationVc<GetContentSourceContents>,
},
}
/// A rewrite returned from a [ContentSource]. This tells the dev server to
/// update its parsed url, path, and queries with this new information.
#[turbo_tasks::value(shared)]
#[derive(Debug)]
pub struct Rewrite {
pub ty: RewriteType,
/// A [Headers] which will be appended to the eventual, fully resolved
/// content result. This overwrites any previous matching headers.
pub response_headers: Option<ResolvedVc<HeaderList>>,
/// A [HeaderList] which will overwrite the values used during the lookup
/// process. All headers not present in this list will be deleted.
pub request_headers: Option<ResolvedVc<HeaderList>>,
}
pub struct RewriteBuilder {
rewrite: Rewrite,
}
impl RewriteBuilder {
pub fn new(path_and_query: RcStr) -> Self {
Self {
rewrite: Rewrite {
ty: RewriteType::Location { path_and_query },
response_headers: None,
request_headers: None,
},
}
}
pub fn new_source_with_path_and_query(
source: OperationVc<Box<dyn ContentSource>>,
path_and_query: RcStr,
) -> Self {
Self {
rewrite: Rewrite {
ty: RewriteType::ContentSource {
source,
path_and_query,
},
response_headers: None,
request_headers: None,
},
}
}
pub fn new_sources(sources: OperationVc<GetContentSourceContents>) -> Self {
Self {
rewrite: Rewrite {
ty: RewriteType::Sources { sources },
response_headers: None,
request_headers: None,
},
}
}
/// Sets response headers to append to the eventual, fully resolved content
/// result.
pub fn response_headers(mut self, headers: ResolvedVc<HeaderList>) -> Self {
self.rewrite.response_headers = Some(headers);
self
}
/// Sets request headers to overwrite the headers used during the lookup
/// process.
pub fn request_headers(mut self, headers: ResolvedVc<HeaderList>) -> Self {
self.rewrite.request_headers = Some(headers);
self
}
pub fn build(self) -> Vc<Rewrite> {
self.rewrite.cell()
}
}
|