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
use futures::{SinkExt,Stream,StreamExt};
use leptos::{provide_context, use_context, LeptosOptions, RuntimeId};
use leptos_router::RouteListing;
use route_table::RouteMatch;
use spin_sdk::http::{Headers, IncomingRequest, OutgoingResponse, ResponseOutparam};
pub mod request;
pub mod request_parts;
pub mod response;
pub mod response_options;
pub mod route_table;
pub mod server_fn;

use crate::server_fn::handle_server_fns_with_context;
pub use request_parts::RequestParts;
pub use response_options::ResponseOptions;
pub use route_table::RouteTable;
use leptos::server_fn::redirect::REDIRECT_HEADER;

pub async fn render_best_match_to_stream<IV>(
    req: IncomingRequest,
    resp_out: ResponseOutparam,
    routes: &RouteTable,
    app_fn: impl Fn() -> IV + 'static + Clone,
    leptos_opts: &LeptosOptions,
) where
    IV: leptos::IntoView + 'static,
{
    render_best_match_to_stream_with_context(req, resp_out, routes, app_fn, || {},  leptos_opts).await;
}
pub async fn render_best_match_to_stream_with_context<IV>(
    req: IncomingRequest,
    resp_out: ResponseOutparam,
    routes: &RouteTable,
    app_fn: impl Fn() -> IV + 'static + Clone,
    additional_context: impl Fn() + Clone + Send + 'static,
    leptos_opts: &LeptosOptions,
) where
    IV: leptos::IntoView + 'static,
{
    // req.uri() doesn't provide the full URI on Cloud (https://github.com/fermyon/spin/issues/2110). For now, use the header instead
    let url = url::Url::parse(&url(&req)).unwrap();
    let path = url.path();

    match routes.best_match(path) {
        RouteMatch::Route(best_listing) => {
            render_route_with_context(url, req, resp_out, app_fn, additional_context, leptos_opts, &best_listing).await
        }
        RouteMatch::ServerFn => handle_server_fns_with_context(req, resp_out, additional_context).await,
        RouteMatch::None => {
            eprintln!("No route found for {url}");
            not_found(resp_out).await
        }
    }
}

async fn render_route<IV>(
    url: url::Url,
    req: IncomingRequest,
    resp_out: ResponseOutparam,
    app_fn: impl Fn() -> IV + 'static + Clone,
    leptos_opts: &LeptosOptions,
    listing: &RouteListing,
) where
    IV: leptos::IntoView + 'static,
{
    render_route_with_context(url, req, resp_out, app_fn, ||{}, leptos_opts, listing).await;
}

async fn render_route_with_context<IV>(
    url: url::Url,
    req: IncomingRequest,
    resp_out: ResponseOutparam,
    app_fn: impl Fn() -> IV + 'static + Clone,
    additional_context: impl Fn() + Clone + Send + 'static,
    leptos_opts: &LeptosOptions,
    listing: &RouteListing,
) where
    IV: leptos::IntoView + 'static,
{
    if listing.static_mode().is_some() {
        log_and_server_error("Static routes are not supported on Spin", resp_out);
        return;
    }

    match listing.mode() {
        leptos_router::SsrMode::OutOfOrder => {
            let resp_opts = ResponseOptions::default();
            let req_parts = RequestParts::new_from_req(&req);

            let app = {
                let app_fn2 = app_fn.clone();
                let res_options = resp_opts.clone();
                move || {
                    provide_contexts(&url, req_parts, res_options, additional_context);
                    (app_fn2)().into_view()
                }
            };
            render_view_into_response_stm(app, resp_opts, leptos_opts, resp_out).await;
        }
        leptos_router::SsrMode::Async => {
            let resp_opts = ResponseOptions::default();
            let req_parts = RequestParts::new_from_req(&req);

            let app = {
                let app_fn2 = app_fn.clone();
                let res_options = resp_opts.clone();
                move || {
                    provide_contexts(&url, req_parts, res_options, additional_context);
                    (app_fn2)().into_view()
                }
            };
            render_view_into_response_stm_async_mode(app, resp_opts, leptos_opts, resp_out).await;
        }
        leptos_router::SsrMode::InOrder => {
            let resp_opts = ResponseOptions::default();
            let req_parts = RequestParts::new_from_req(&req);

            let app = {
                let app_fn2 = app_fn.clone();
                let res_options = resp_opts.clone();
                move || {
                    provide_contexts(&url, req_parts, res_options, additional_context);
                    (app_fn2)().into_view()
                }
            };
            render_view_into_response_stm_in_order_mode(app, leptos_opts, resp_opts, resp_out)
                .await;
        }
        leptos_router::SsrMode::PartiallyBlocked => {
            let resp_opts = ResponseOptions::default();
            let req_parts = RequestParts::new_from_req(&req);

            let app = {
                let app_fn2 = app_fn.clone();
                let res_options = resp_opts.clone();
                move || {

                    provide_contexts(&url, req_parts, res_options, additional_context);
                    (app_fn2)().into_view()
                }
            };
            render_view_into_response_stm_partially_blocked_mode(
                app,
                leptos_opts,
                resp_opts,
                resp_out,
            )
            .await;
        }
    }
}

// This is a backstop - the app should normally include a "/*"" route
// mapping to a NotFound Leptos component.
async fn not_found(resp_out: ResponseOutparam) {
    let og = OutgoingResponse::new(Headers::new());
    og.set_status_code(404).expect("Failed to set status'");
    resp_out.set(og);
}

async fn render_view_into_response_stm(
    app: impl FnOnce() -> leptos::View + 'static,
    resp_opts: ResponseOptions,
    leptos_opts: &leptos::leptos_config::LeptosOptions,
    resp_out: ResponseOutparam,
) {
    let (stm, runtime) = leptos::leptos_dom::ssr::render_to_stream_with_prefix_undisposed_with_context_and_block_replacement(
        app,
        || leptos_meta::generate_head_metadata_separated().1.into(),
        || {},
        false);
    build_stream_response(stm, leptos_opts, resp_opts, resp_out, runtime).await;
}

async fn render_view_into_response_stm_async_mode(
    app: impl FnOnce() -> leptos::View + 'static,
    resp_opts: ResponseOptions,
    leptos_opts: &leptos::leptos_config::LeptosOptions,
    resp_out: ResponseOutparam,
) {
    // In the Axum integration, all this happens in a separate task, and sends back
    // to the function via a futures::channel::oneshot(). WASI doesn't have an
    // equivalent for that yet, so for now, just truck along.
    let (stm, runtime) = leptos::ssr::render_to_stream_in_order_with_prefix_undisposed_with_context(
        app,
        move || "".into(),
        || {},
    );
    let html = leptos_integration_utils::build_async_response(stm, leptos_opts, runtime).await;

    let status_code = resp_opts.status().unwrap_or(200);
    let headers = resp_opts.headers();

    let og = OutgoingResponse::new(headers);
    og.set_status_code(status_code).expect("Failed to set status");
    let mut ogbod = og.take_body();
    resp_out.set(og);
    ogbod.send(html.into_bytes()).await.unwrap();
}

async fn render_view_into_response_stm_in_order_mode(
    app: impl FnOnce() -> leptos::View + 'static,
    leptos_opts: &LeptosOptions,
    resp_opts: ResponseOptions,
    resp_out: ResponseOutparam,
) {
    let (stm, runtime) = leptos::ssr::render_to_stream_in_order_with_prefix_undisposed_with_context(
        app,
        || leptos_meta::generate_head_metadata_separated().1.into(),
        || {},
    );

    build_stream_response(stm, leptos_opts, resp_opts, resp_out, runtime).await;
}

async fn render_view_into_response_stm_partially_blocked_mode(
    app: impl FnOnce() -> leptos::View + 'static,
    leptos_opts: &LeptosOptions,
    resp_opts: ResponseOptions,
    resp_out: ResponseOutparam,
) {
    let (stm, runtime) =
        leptos::ssr::render_to_stream_with_prefix_undisposed_with_context_and_block_replacement(
            app,
            move || leptos_meta::generate_head_metadata_separated().1.into(),
            || (),
            true,
        );
    build_stream_response(stm, leptos_opts, resp_opts, resp_out, runtime).await;
}

async fn build_stream_response(
    stm: impl Stream<Item = String>,
    leptos_opts: &LeptosOptions,
    resp_opts: ResponseOptions,
    resp_out: ResponseOutparam,
    runtime: RuntimeId,
) {
    let mut stm2 = Box::pin(stm);

    let first_app_chunk = stm2.next().await.unwrap_or_default();
    let (head, tail) = leptos_integration_utils::html_parts_separated(
        leptos_opts,
        leptos::use_context::<leptos_meta::MetaContext>().as_ref(),
    );

    let mut stm3 = Box::pin(
        futures::stream::once(async move { head.clone() })
            .chain(futures::stream::once(async move { first_app_chunk }).chain(stm2))
            .map(|html| html.into_bytes()),
    );

    let first_chunk = stm3.next().await;
    let second_chunk = stm3.next().await;

    let status_code = resp_opts.status().unwrap_or(200);
    let headers = resp_opts.headers();

    let og = OutgoingResponse::new(headers);
    og.set_status_code(status_code).expect("Failed to set status");
    let mut ogbod = og.take_body();
    resp_out.set(og);

    let mut stm4 = Box::pin(
        futures::stream::iter([first_chunk.unwrap(), second_chunk.unwrap()])
            .chain(stm3)
            .chain(
                futures::stream::once(async move {
                    runtime.dispose();
                    tail.to_string()
                })
                .map(|html| html.into_bytes()),
            ),
    );

    while let Some(ch) = stm4.next().await {
        ogbod.send(ch).await.unwrap();
    }
}

/// Provides an easy way to redirect the user from within a server function.
///
/// This sets the `Location` header to the URL given.
///
/// If the route or server function in which this is called is being accessed
/// by an ordinary `GET` request or an HTML `<form>` without any enhancement, it also sets a
/// status code of `302` for a temporary redirect. (This is determined by whether the `Accept`
/// header contains `text/html` as it does for an ordinary navigation.)
///
/// Otherwise, it sets a custom header that indicates to the client that it should redirect,
/// without actually setting the status code. This means that the client will not follow the
/// redirect, and can therefore return the value of the server function and then handle
/// the redirect with client-side routing.
pub fn redirect(path: &str) {
    if let (Some(req), Some(res)) = (
        use_context::<RequestParts>(),
        use_context::<ResponseOptions>(),
    ) {
        // insert the Location header in any case
        res.insert_header("location", path);

        let req_headers = Headers::from_list(req.headers()).expect("Failed to construct Headers from Request Headers");
        let accepts_html = &req_headers.get(&"Accept".to_string())[0];
        let accepts_html_bool = String::from_utf8_lossy(accepts_html).contains("text/html");
        if accepts_html_bool {
            // if the request accepts text/html, it's a plain form request and needs
            // to have the 302 code set
            res.set_status(302);
        } else {
            // otherwise, we sent it from the server fn client and actually don't want
            // to set a real redirect, as this will break the ability to return data
            // instead, set the REDIRECT_HEADER to indicate that the client should redirect
            res.insert_header(REDIRECT_HEADER, "");
        }
    } else {
        tracing::warn!(
            "Couldn't retrieve either Parts or ResponseOptions while trying \
             to redirect()."
        );
    }
}

fn provide_contexts(url: &url::Url, req_parts: RequestParts, res_options: ResponseOptions, additional_context: impl Fn() + Clone + Send + 'static) {
    let path = leptos_corrected_path(url);

    let integration = leptos_router::ServerIntegration { path };
    provide_context(leptos_router::RouterIntegrationContext::new(integration));
    provide_context(leptos_meta::MetaContext::new());
    provide_context(res_options);
    provide_context(req_parts);
    additional_context();
    leptos_router::provide_server_redirect(redirect);
    #[cfg(feature = "nonce")]
    leptos::nonce::provide_nonce();
}

fn leptos_corrected_path(req: &url::Url) -> String {
    let path = req.path();
    let query = req.query();
    if query.unwrap_or_default().is_empty() {
        "http://leptos".to_string() + path
    } else {
        "http://leptos".to_string() + path + "?" + query.unwrap_or_default()
    }
}

fn url(req: &IncomingRequest) -> String {
    let full_url = &req.headers().get(&"spin-full-url".to_string())[0];
    String::from_utf8_lossy(full_url).to_string()
}

fn log_and_server_error(message: impl Into<String>, resp_out: ResponseOutparam) {
    println!("Error: {}", message.into());
    let response = spin_sdk::http::OutgoingResponse::new(spin_sdk::http::Fields::new());
    response.set_status_code(500).expect("Failed to set status");
    resp_out.set(response);
}