Repository navigation
Conversation
|
|
||
| pub fn execute(&self, request: Request) -> Result<Response> { | ||
| self.rt.block_on(async { | ||
| // TODO: Support named pipes by replacing tokio::net::UnixStream::connect(..) with: |
There was a problem hiding this comment.
Besides Docker for Window, I couldn't find any other examples of HTTP over named pipes, so I'm not sure if it's worth supporting at this time.
There was a problem hiding this comment.
Daniel Stenberg (author of curl):
I'm not aware of any HTTP server supporting communication over a Windows named pipe, which I assume is a pretty good reason why nobody ever added this feature.
So no, there is no such option.
So I think it's OK not to support it.
I did find one more example: http://stunnix.com/a/http-over-named-pipes.shtml
| #[cfg(target_family = "unix")] | ||
| if let Some(unix_socket) = args.unix_socket { |
There was a problem hiding this comment.
There is a fork of hyperlocal that adds support for windows but it might be better to wait until it is merged upstream
| } | ||
| }); | ||
|
|
||
| // TODO: don't ignore value from --timeout option |
There was a problem hiding this comment.
Regardless of how this is handled, I need to ensure the correct exit code is used for timeout errors
There was a problem hiding this comment.
Note to self: refer to impl<B> hyper::body::Body for TotalTimeoutBody<B> for how to implement timeout for body.
Also, we should consider moving to a combination of connect_timeout and read_timeout which is closer to how it is handled in python requests/HTTPie. See https://requests.readthedocs.io/en/stable/user/advanced/#timeouts
There was a problem hiding this comment.
Hmm, it seems read_timeout is not yet implemented for reqwest::blocking::Client
blyxxyz
left a comment
There was a problem hiding this comment.
Nice! I haven't looked at everything yet
|
|
||
| /// Connect using a Unix domain socket. | ||
| /// | ||
| /// Example: --unix_socket=/var/run/temp.sock |
There was a problem hiding this comment.
With this API you still have to make up a hostname for the URL, like curl, and unlike got and the HTTPie plugin.
AFAICT the typical use cases are for local services and not for proxies, meaning that the hostname is superfluous. But it also doesn't look like we're going to get a URL-based convention for this any time soon. And splitting it off into an option prevents redirect attacks. (Not sure how it should interact with sessions though... we need to look carefully at other areas of interference.)
A full command with the : shorthand might help users, e.g.
xh :/index.html --unix-socket=/var/run/temp.sock
There was a problem hiding this comment.
There is a good chance that unix domain sockets will be treated as a proxy in reqwest. This has the advantage that anything relying on hostname like cookies and Host header will keep working. Also, see denoland/deno#8821 (comment)
However, I still think we can support xh http://unix:/var/run/docker.sock:/containers/json by treating it as a syntactic sugar for xh :/containers/json --unix-socket=/var/run/docker.sock.
There was a problem hiding this comment.
We can always add syntactic sugar later. Right now there doesn't seem to be any consensus about the URL format.
If it ever gets to the point where browsers start supporting UDS URLs (as a non-experimental feature) then we should follow suit.
| let starting_time = Instant::now(); | ||
| let mut response = self.execute(request)?; | ||
| response.extensions_mut().insert(ResponseMeta { | ||
| request_duration: starting_time.elapsed(), | ||
| content_download_duration: None, | ||
| }); |
There was a problem hiding this comment.
Don't we skip any subsequent middleware this way? I don't understand this yet but it might be the wrong layer to do it.
There was a problem hiding this comment.
It is the last layer, but returning early and short-circuiting middlewares in this way might be confusing, not to mention the duplicated logic. Let me see if I can switch between UnixSocket and reqwest client inside ClientWithMiddleware.
the former is not yet supported in blocking client
blyxxyz
left a comment
There was a problem hiding this comment.
Looks good so far! (I haven't understood everything yet.)
Do you have tips for manually testing this?
| #[clap( | ||
| long, | ||
| value_name = "FILE", | ||
| conflicts_with_all=["proxy", "verify", "cert", "cert_key", "ssl", "resolve", "interface", "ipv4", "ipv6", "https", "http_version"] |
There was a problem hiding this comment.
Many of these might plausibly appear in an alias or config file, like --https, --ssl.
If someone passes --proxy they probably made a mistake but I think the list could be shorter. Maybe a guideline could be whether the option is compatible with a normal request to http://127.0.0.1?
There was a problem hiding this comment.
Were you thinking of silently ignoring some of the flags or maybe printing a warning?
There was a problem hiding this comment.
--https for example doesn't force HTTPS, it just changes the default scheme of the URL. So maybe the user gets an error if they pass :/index.html because that gets converted to https://localhost/index.html and the socket doesn't support TLS, but if they use --https with an explicit http://localhost/index.html then that should be perfectly fine, just like in xh --https http://127.0.0.1 the --https flag is useless but harmless.
| tokio::task::spawn(async move { | ||
| if let Err(err) = conn.await { | ||
| log::error!("Connection failed: {:?}", err); | ||
| } | ||
| }); |
There was a problem hiding this comment.
Is it OK to merely log this? I assume it leads to a harder error somewhere down the line and it's just hard to get it out of the task?
| let mut sender = with_timeout(self.connect(), self.timeout).await??; | ||
| let response = with_timeout(sender.send_request(http_request), self.timeout).await??; |
There was a problem hiding this comment.
Does this mean we have a separate timeout for each stage?
Will there be a timeout for e.g. a large file upload?
There was a problem hiding this comment.
Yup, this is too aggressive. Your streaming example server times out and that kind of thing doesn't happen over TCP.
The docs say the timeout applies to individual connect/read/write operations. So I think that if you have a timeout of 1 second, as long as each individual read/write takes less than 1 second, it can go on indefinitely.
I don't know how easy it is to match that precisely but putting the timeout just on the connect step would already be decent.
| let file_name: String = rand::thread_rng() | ||
| .sample_iter(&rand::distributions::Alphanumeric) | ||
| .take(10) | ||
| .map(char::from) | ||
| .collect(); |
There was a problem hiding this comment.
Looks like tempfile can be used for this: https://docs.rs/tempfile/latest/tempfile/struct.Builder.html#examples-11
That way we also get cleanup
I have been using Docker API but you can also use Bun which natively supports unix domain sockets // bun index.js
async function* hello(times) {
for (let i = 0; i < times; i++) {
yield `data: hello ${i}\n\n`;
await Bun.sleep(1000);
}
}
const server = Bun.serve({
unix: "/tmp/my-socket.sock",
fetch(req){
return new Response(hello(10), {
headers: {
"Content-Type": "text/event-stream",
Connection: "keep-alive",
}
});
}
});
console.log(`Listening on unix:///tmp/my-socket.sock`);I'm noticing some decoding errors so I will have to investigate that Update: I'm getting a similar error in curl so it must be a server bug |
|
This one works for me without any "connection closed" errors // package.json
// { "dependencies": { "express": "^4.21.2" } }
const { setTimeout } = require('node:timers/promises');
const fs = require('fs');
const express = require("express");
const app = express();
app.get("/stream", async (req, res) => {
res.writeHead(200, {
"Connection": "keep-alive",
"Cache-Control": "no-cache",
"Content-Type": "text/event-stream",
});
res.on('close', () => {
res.end();
});
let counter = 0;
while (counter < 10) {
const chunk = JSON.stringify({chunk: counter++});
res.write(`data: ${chunk}\n\n`);
await setTimeout(1000);
}
res.end();
});
app.get("/hello", (req, res) => {
res.send("hello world");
});
const socket_path = '/tmp/my-socket.sock';
fs.unlinkSync(socket_path);
app.listen(socket_path, () => console.log('server listening on', socket_path)); |
|
Instead of emulating a Unix socket proxy (hyper)
// hyper = { version = "1", features = ["server", "http1", "client"] }
// hyper-util = { version = "0.1", features = ["tokio"] }
// tokio = { version = "1", features = ["full"] }
// xh :/stream -v --proxy http:http://127.0.0.1:3000
use hyper::{
body::Incoming, client::conn::http1, server::conn::http1 as server_http1, service::service_fn,
Request, Response,
};
use hyper_util::rt::TokioIo;
use std::net::SocketAddr;
use tokio::net::{TcpListener, UnixStream};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); // TODO: use port 0 like we do inside tests
let listener = TcpListener::bind(addr).await?;
println!("Proxy running on http://{}", addr);
// TODO: figure out how start and shutdown proxy server inside xh
loop {
let (stream, _) = listener.accept().await?;
tokio::spawn(handle_connection(stream));
}
}
async fn handle_connection(stream: tokio::net::TcpStream) {
let io = TokioIo::new(stream);
if let Err(err) = server_http1::Builder::new()
.serve_connection(io, service_fn(forward_request))
.await
{
eprintln!("Connection error: {}", err);
}
}
async fn forward_request(req: Request<Incoming>) -> Result<Response<Incoming>, hyper::Error> {
let uds_path = "/tmp/my-socket.sock";
let stream = UnixStream::connect(uds_path).await.unwrap();
let io = TokioIo::new(stream);
let (mut sender, conn) = http1::Builder::new().handshake(io).await?;
tokio::spawn(async move {
if let Err(err) = conn.await {
eprintln!("Connection error: {}", err);
}
});
sender.send_request(req).await
}Unix socket server (Node JS)
const { setTimeout } = require('node:timers/promises');
const fs = require('fs');
const express = require("express");
const app = express();
app.get("/stream", async (req, res) => {
res.writeHead(200, {
"Connection": "keep-alive",
"Cache-Control": "no-cache",
"Content-Type": "text/event-stream",
});
res.on('close', () => {
res.end();
});
let counter = 0;
while (counter < 10) {
const chunk = JSON.stringify({chunk: counter++});
res.write(`data: ${chunk}\n\n`);
await setTimeout(1000);
}
res.end();
});
app.get("/hello", (req, res) => {
res.send("hello world");
});
const socket_path = '/tmp/my-socket.sock';
if (fs.existsSync(socket_path)) {
fs.unlinkSync(socket_path);
}
app.listen(socket_path, () => console.log('server listening on', socket_path));I'll open a separate PR if I manage to get this working. |
|
Closing in favour of |
Adds a
--unix-socketoption similar to cURL for binding to a Unix domain socket. When used, all requests, including redirects, will go through the specified Unix socket.Resources used:
Resolves #230