Skip to content

Design feedback: Recursion v2 - #465

Closed
mre wants to merge 14 commits into
masterfrom
recursion-v2
Closed

mre wants to merge 14 commits into
masterfrom
recursion-v2

Conversation

@mre

@mre mre commented Jan 16, 2022 •

Copy link
Copy Markdown
Member

This is not a good design for recursion. Instead I'm looking for design feedback.

Ideally I'd like to have the collector (1) take "something that can be converted into a stream of inputs" as an input parameter and (2) the already existing stream of requests as its output.
I couldn't get it to work, though. Had issues with expressing (1) as some type and with returning the stream (2). Didn't know how to yield the requests to the caller.

So instead I added another method from_chan and that works but it's around 30% slower in my tests and quite ugly.
I'd rather get rid of that method again and have a single from method for all inputs. Can it be done?

Thanks for any feedback. Also feel free to create another PR for recursion support. Most likely I'm making this harder than it needs to be. 😃

Previous attempt for reference.

@mre

mre commented Jan 18, 2022

Copy link
Copy Markdown
Member Author

@lebensterben, since you know more about streams than me, is there a way to have a function that takes a vec or a stream and converts the input into a stream if needed?
Something like param: Into<impl Stream<Item=Input>>? Couldn't find any examples for that.

@mre

mre commented Jan 18, 2022

Copy link
Copy Markdown
Member Author

Oh I guess I could use something similar to this:

use futures::stream::Stream;
use std::pin::Pin;

pub struct Input {
    // ...
}

pub enum InputType {
    Stream(Pin<Box<dyn Stream<Item = Input>>>),
    Seq(Vec<Input>),
}

fn from(input: InputType) {
 // ...
}

or even

use futures::stream::Stream;
use std::pin::Pin;

pub struct Input {
    // ...
}

pub enum InputType {
    Stream(Pin<Box<dyn Stream<Item = Input>>>),
    Seq(Vec<Input>),
}

impl From<Vec<Input>> for InputType {
    fn from(i: Vec<Input>) -> Self {
        Self::Seq(i)
    }
}

impl From<Pin<Box<dyn Stream<Item = Input>>>> for InputType {
    fn from(i: Pin<Box<dyn Stream<Item = Input>>>) -> Self {
        Self::Stream(i)
    }
}


fn from<T: Into<InputType>>(input: T) {
 // ...
}

Most likely there is a more idiomatic way to do it.
On the plus side, the user could pass a vec or a stream to the same method.

@lebensterben

Copy link
Copy Markdown
Member

If I'm not mistaken, what you described is very similar to into_stream method:

a function that takes a vec or a stream and converts the input into a stream if needed

But the issue is, it's implemented for

impl<T: ?Sized> FutureExt for T where T: Future {}

That should be fine, I guess, for a stream of input, since

impl<F, A> Future for Box<F, A> where
    F: Future + Unpin + ?Sized,
    A: Allocator + 'static, 

But I doubt Vec<Input> implements Future.


If the above issue is solved, you can simply have the parameter to accept T: FutureExt.

@mre

mre commented Jan 19, 2022 •

Copy link
Copy Markdown
Member Author

But I doubt Vec implements Future.

Yeah, that's the issue.
At this point I don't think a stream is the right abstraction for inputs because I don't think I can keep pushing into it once I pass it to the collector. I might be wrong, though.

I played around with channels again yesterday night and I think I'm getting to a point where I'm okay with the design.
What I did was use a channel for inputs and a stream for the output. The stream gets closed when the channel gets closed.

Haven't pushed anything, but I will probably update this branch tonight if I get a chance.
It's still failing for some weird reason and doesn't handle any requests, but I think I can fix that.

@mre

mre commented Jan 24, 2022

Copy link
Copy Markdown
Member Author

Somewhere I introduced a bug. The program never ends. I'm assuming it's a deadlock somewhere. Can anyone see it?

@mre

mre commented Jan 27, 2022

Copy link
Copy Markdown
Member Author

I had very little time to look at the issue so far, but it hangs because the input channel does not get dropped, leading to a dangling connection.
I thought that the channel would be closed (and dropped) automatically once futures::StreamExt::for_each_concurrent finishes. Does anyone have an idea on how to fix this? Might be a simple thing I'm missing.

@mre mre mentioned this pull request Feb 4, 2022
}
}

if !response.is_success() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder though. What if the 404 site contains links that are otherwise not reachable? The user can still click on them.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. We should probably change that to response. is_failure() || response.is_timeout(), which is just a subset of !response.is_success(). Thoughts?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does is_failure include 404? reading the code doesn't make that obvious

.expect("Cannot send input to channel");
}

// Explicitly drop the channel to stop the stream inside the collector

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You want to drop the sender once there's nothing to process anymore right? But won't for_each_concurrent hang forever because you didn't do that yet? (and can't, because you need the sender for more cloning)

I can repro a deadlock even with time lychee --offline -b . '**/*.htm*' -T1 on an empty directory.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I'm beginning to think that there is no way to avoid a deadlock if I both the sender and the receiver have to be empty for the program to terminate. I had a longer discussion on the Tokio Discord about it and the conclusion was that I should use a Semaphore lock and "normal" recursion + tokio_spawn instead.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah im on their discord but didn't see you already were asking this a while ago

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically this was what we ended up with. Thoughts?

use std::sync::Arc;
use tokio::{
    sync::{OwnedSemaphorePermit, Semaphore},
    task::JoinHandle,
};

const MAX_CONCURRENCY: usize = 10;

fn recurse(permit: OwnedSemaphorePermit, i: usize) -> JoinHandle<()> {
    tokio::spawn(async move {
        handle_input(permit, i).await;
    })
}

async fn handle_input(permit: OwnedSemaphorePermit, i: usize) {
    println!("got = {i}");
    if i % 9 == 0 {
        recurse(permit, 10).await.unwrap();
    }
}

#[tokio::main]
async fn main() {
    let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENCY));

    tokio::spawn(async move {
        for i in 0..10 {
            let permit = semaphore.clone().acquire_owned().await.unwrap();
            handle_input(permit, i).await;
        }
    })
    .await
    .unwrap();
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried this model on the branch, but it gets quite ugly because of ownership and Send. We'll probably need an Arc to pass some recursion state around (which encapsulates all the moving parts like the config, the client, and maybe even the progress bar).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is the way to go. I wish there was a higher-level primitive for this, for_each_concurrent seemed perfect.

What ownership problems do you have?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Had to lock the state with an Arc<RwLock<State>>, but I guess I locked once too often. 😆 Let me push the branch and create a new PR so you can have a look if you like. 😉

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here you go: #489

@mre

mre commented Jul 1, 2022

Copy link
Copy Markdown
Member Author

I'm closing this PR because it will not be merged in its current form. We will try again to add recursion support at a later point. In any case, thanks for the design feedback.

@mre mre closed this Jul 1, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants