From b80cffbeac0c732156a65d6bfa50f81a4927d4e6 Mon Sep 17 00:00:00 2001 From: Justin Ridgewell Date: Thu, 18 May 2023 14:29:39 -0400 Subject: [PATCH] Add ServerInfo struct for node rendering --- crates/turbopack-core/src/environment.rs | 66 ++++++++++++++++++++++-- 1 file changed, 62 insertions(+), 4 deletions(-) diff --git a/crates/turbopack-core/src/environment.rs b/crates/turbopack-core/src/environment.rs index 9d26015a9bb5d..ac3f9acda677b 100644 --- a/crates/turbopack-core/src/environment.rs +++ b/crates/turbopack-core/src/environment.rs @@ -1,10 +1,12 @@ use std::{ + fmt, net::SocketAddr, process::{Command, Stdio}, str::FromStr, }; -use anyhow::{anyhow, Context, Result}; +use anyhow::{anyhow, bail, Context, Result}; +use serde::{Deserialize, Serialize}; use swc_core::ecma::preset_env::{Version, Versions}; use turbo_tasks::{ primitives::{BoolVc, OptionStringVc, StringVc, StringsVc}, @@ -55,10 +57,10 @@ impl ServerAddr { .hostname() .zip(self.port()) .context("expected some server address")?; + let protocol = Protocol::from(port); Ok(match port { - 80 => format!("http://{hostname}"), - 443 => format!("https://{hostname}"), - _ => format!("http://{hostname}:{port}"), + 80 | 443 => format!("{protocol}://{hostname}"), + _ => format!("{protocol}://{hostname}:{port}"), }) } } @@ -71,6 +73,62 @@ impl ServerAddrVc { } } +/// A simple serializable structure meant to carry information about Turbopack's +/// server to node rendering processes. +#[derive(Debug, Serialize, Deserialize)] +pub struct ServerInfo { + pub ip: String, + pub port: u16, + + /// The protocol, either `http` or `https` + pub protocol: Protocol, + + /// A formatted hostname (eg, "localhost") or the IP address of the server + pub hostname: String, +} + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Protocol { + HTTP, + HTTPS, +} + +impl From for Protocol { + fn from(value: u16) -> Self { + match value { + 443 => Self::HTTPS, + _ => Self::HTTP, + } + } +} + +impl fmt::Display for Protocol { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::HTTP => f.write_str("http"), + Self::HTTPS => f.write_str("https"), + } + } +} + +impl TryFrom<&ServerAddr> for ServerInfo { + type Error = anyhow::Error; + + fn try_from(addr: &ServerAddr) -> Result { + if addr.0.is_none() { + bail!("cannot unwrap ServerAddr"); + }; + let port = addr.port().unwrap(); + Ok(ServerInfo { + ip: addr.ip().unwrap(), + hostname: addr.hostname().unwrap(), + port, + protocol: Protocol::from(port), + }) + } +} + #[turbo_tasks::value] #[derive(Default)] pub enum Rendering {