Allow extensions to control the redirect policy for the HTTP client (#16162)

This PR extends the extension API with support for controlling the
redirect policy used by the HTTP client.

Release Notes:

- N/A
This commit is contained in:
Marshall Bowers 2024-08-13 10:40:21 -04:00 committed by GitHub
parent 98a2ab0686
commit 4450ebff6b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 42 additions and 14 deletions

View file

@ -136,7 +136,7 @@ impl http_client::Host for WasmState {
) -> wasmtime::Result<Result<http_client::HttpResponse, String>> { ) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
maybe!(async { maybe!(async {
let url = &request.url; let url = &request.url;
let request = convert_request(&request, true)?; let request = convert_request(&request)?;
let mut response = self.host.http_client.send(request).await?; let mut response = self.host.http_client.send(request).await?;
if response.status().is_client_error() || response.status().is_server_error() { if response.status().is_client_error() || response.status().is_server_error() {
@ -152,7 +152,7 @@ impl http_client::Host for WasmState {
&mut self, &mut self,
request: http_client::HttpRequest, request: http_client::HttpRequest,
) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> { ) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
let request = convert_request(&request, true)?; let request = convert_request(&request)?;
let response = self.host.http_client.send(request); let response = self.host.http_client.send(request);
maybe!(async { maybe!(async {
let response = response.await?; let response = response.await?;
@ -208,15 +208,14 @@ impl From<http_client::HttpMethod> for ::http_client::Method {
fn convert_request( fn convert_request(
extension_request: &http_client::HttpRequest, extension_request: &http_client::HttpRequest,
follow_redirects: bool,
) -> Result<::http_client::Request<AsyncBody>, anyhow::Error> { ) -> Result<::http_client::Request<AsyncBody>, anyhow::Error> {
let mut request = ::http_client::Request::builder() let mut request = ::http_client::Request::builder()
.method(::http_client::Method::from(extension_request.method)) .method(::http_client::Method::from(extension_request.method))
.uri(&extension_request.url) .uri(&extension_request.url)
.redirect_policy(if follow_redirects { .redirect_policy(match extension_request.redirect_policy {
RedirectPolicy::Follow http_client::RedirectPolicy::NoFollow => RedirectPolicy::None,
} else { http_client::RedirectPolicy::FollowLimit(limit) => RedirectPolicy::Limit(limit),
RedirectPolicy::None http_client::RedirectPolicy::FollowAll => RedirectPolicy::Follow,
}); });
for (key, value) in &extension_request.headers { for (key, value) in &extension_request.headers {
request = request.header(key, value); request = request.header(key, value);

View file

@ -21,6 +21,7 @@ pub use wit::{
}, },
zed::extension::http_client::{ zed::extension::http_client::{
fetch, fetch_stream, HttpMethod, HttpRequest, HttpResponse, HttpResponseStream, fetch, fetch_stream, HttpMethod, HttpRequest, HttpResponse, HttpResponseStream,
RedirectPolicy,
}, },
zed::extension::nodejs::{ zed::extension::nodejs::{
node_binary_path, npm_install_package, npm_package_installed_version, node_binary_path, npm_install_package, npm_package_installed_version,

View file

@ -5,23 +5,44 @@ interface http-client {
method: http-method, method: http-method,
/// The URL to which the request should be made. /// The URL to which the request should be made.
url: string, url: string,
/// Headers for the request. /// The headers for the request.
headers: list<tuple<string, string>>, headers: list<tuple<string, string>>,
/// The request body. /// The request body.
body: option<list<u8>>, body: option<list<u8>>,
/// The policy to use for redirects.
redirect-policy: redirect-policy,
} }
/// HTTP methods. /// HTTP methods.
enum http-method { enum http-method {
/// `GET`
get, get,
post, /// `HEAD`
put,
delete,
head, head,
/// `POST`
post,
/// `PUT`
put,
/// `DELETE`
delete,
/// `OPTIONS`
options, options,
/// `PATCH`
patch, patch,
} }
/// The policy for dealing with redirects received from the server.
variant redirect-policy {
/// Redirects from the server will not be followed.
///
/// This is the default behavior.
no-follow,
/// Redirects from the server will be followed up to the specified limit.
follow-limit(u32),
/// All redirects from the server will be followed.
follow-all,
}
/// An HTTP response. /// An HTTP response.
record http-response { record http-response {
/// The response headers. /// The response headers.
@ -36,7 +57,8 @@ interface http-client {
/// An HTTP response stream. /// An HTTP response stream.
resource http-response-stream { resource http-response-stream {
/// Retrieves the next chunk of data from the response stream. /// Retrieves the next chunk of data from the response stream.
/// Returns None if the stream has ended. ///
/// Returns `Ok(None)` if the stream has ended.
next-chunk: func() -> result<option<list<u8>>, string>; next-chunk: func() -> result<option<list<u8>>, string>;
} }

View file

@ -4,7 +4,8 @@ use std::{fs, io};
use zed::lsp::CompletionKind; use zed::lsp::CompletionKind;
use zed::{ use zed::{
CodeLabel, CodeLabelSpan, HttpMethod, HttpRequest, KeyValueStore, LanguageServerId, CodeLabel, CodeLabelSpan, HttpMethod, HttpRequest, KeyValueStore, LanguageServerId,
SlashCommand, SlashCommandArgumentCompletion, SlashCommandOutput, SlashCommandOutputSection, RedirectPolicy, SlashCommand, SlashCommandArgumentCompletion, SlashCommandOutput,
SlashCommandOutputSection,
}; };
use zed_extension_api::{self as zed, Result}; use zed_extension_api::{self as zed, Result};
@ -208,6 +209,7 @@ impl zed::Extension for GleamExtension {
"Zed (Gleam Extension)".to_string(), "Zed (Gleam Extension)".to_string(),
)], )],
body: None, body: None,
redirect_policy: RedirectPolicy::FollowAll,
})?; })?;
let (markdown, _modules) = let (markdown, _modules) =

View file

@ -10,7 +10,9 @@ use html_to_markdown::{
convert_html_to_markdown, HandleTag, HandlerOutcome, HtmlElement, MarkdownWriter, convert_html_to_markdown, HandleTag, HandlerOutcome, HtmlElement, MarkdownWriter,
StartTagOutcome, TagHandler, StartTagOutcome, TagHandler,
}; };
use zed_extension_api::{self as zed, HttpMethod, HttpRequest, KeyValueStore, Result}; use zed_extension_api::{
self as zed, HttpMethod, HttpRequest, KeyValueStore, RedirectPolicy, Result,
};
pub fn index(package: String, database: &KeyValueStore) -> Result<()> { pub fn index(package: String, database: &KeyValueStore) -> Result<()> {
let headers = vec![( let headers = vec![(
@ -23,6 +25,7 @@ pub fn index(package: String, database: &KeyValueStore) -> Result<()> {
url: format!("https://hexdocs.pm/{package}"), url: format!("https://hexdocs.pm/{package}"),
headers: headers.clone(), headers: headers.clone(),
body: None, body: None,
redirect_policy: RedirectPolicy::FollowAll,
})?; })?;
let (package_root_markdown, modules) = let (package_root_markdown, modules) =
@ -36,6 +39,7 @@ pub fn index(package: String, database: &KeyValueStore) -> Result<()> {
url: format!("https://hexdocs.pm/{package}/{module}.html"), url: format!("https://hexdocs.pm/{package}/{module}.html"),
headers: headers.clone(), headers: headers.clone(),
body: None, body: None,
redirect_policy: RedirectPolicy::FollowAll,
})?; })?;
let (markdown, _modules) = let (markdown, _modules) =