-
Notifications
You must be signed in to change notification settings - Fork 4
ChannelTask can be terminated #22
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Roba1993
wants to merge
2
commits into
paberr:main
Choose a base branch
from
Roba1993:terminate-worker
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,9 +1,16 @@ | ||
| use std::marker::PhantomData; | ||
| use std::{ | ||
| cell::{Cell, RefCell}, | ||
| marker::PhantomData, | ||
| rc::Rc, | ||
| }; | ||
|
|
||
| use futures::{future::select, pin_mut}; | ||
| use serde::{de::DeserializeOwned, Serialize}; | ||
| use tokio::sync::oneshot; | ||
| use tokio::sync::{oneshot, watch}; | ||
|
|
||
| use crate::{channel::Channel, convert::from_bytes}; | ||
| use crate::{channel::Channel, convert::from_bytes, error::TaskError}; | ||
|
|
||
| type LifecycleCallback = Box<dyn FnOnce()>; | ||
|
|
||
| /// A handle to a running channel task on a WebWorker. | ||
| /// | ||
|
|
@@ -24,38 +31,138 @@ use crate::{channel::Channel, convert::from_bytes}; | |
| /// let progress: Progress = task.recv().await.expect("progress"); | ||
| /// task.send(&Continue { should_continue: true }); | ||
| /// | ||
| /// let result: ProcessResult = task.result().await; | ||
| /// let result: ProcessResult = task.result().await.expect("worker terminated"); | ||
| /// ``` | ||
| pub struct ChannelTask<R> { | ||
| channel: Channel, | ||
| result_rx: oneshot::Receiver<Vec<u8>>, | ||
| result_rx: Option<oneshot::Receiver<Vec<u8>>>, | ||
| control: ChannelTaskControl, | ||
| on_complete: Option<LifecycleCallback>, | ||
| _phantom: PhantomData<R>, | ||
| } | ||
|
|
||
| /// A cloneable handle for terminating a running [`ChannelTask`]. | ||
| #[derive(Clone)] | ||
| pub struct ChannelTaskControl { | ||
| inner: Rc<ChannelTaskControlInner>, | ||
| } | ||
|
|
||
| struct ChannelTaskControlInner { | ||
| terminated: Cell<bool>, | ||
| on_terminate: RefCell<Option<LifecycleCallback>>, | ||
| close_tx: watch::Sender<bool>, | ||
| } | ||
|
|
||
| impl ChannelTaskControl { | ||
| fn new(on_terminate: Option<LifecycleCallback>) -> Self { | ||
| let (close_tx, _) = watch::channel(false); | ||
| Self { | ||
| inner: Rc::new(ChannelTaskControlInner { | ||
| terminated: Cell::new(false), | ||
| on_terminate: RefCell::new(on_terminate), | ||
| close_tx, | ||
| }), | ||
| } | ||
| } | ||
|
|
||
| /// Terminate the worker running the associated channel task. | ||
| /// | ||
| /// Repeated calls are harmless. | ||
| pub fn terminate(&self) { | ||
| if self.inner.terminated.replace(true) { | ||
| return; | ||
| } | ||
|
|
||
| let _ = self.inner.close_tx.send(true); | ||
| if let Some(callback) = self.inner.on_terminate.borrow_mut().take() { | ||
| callback(); | ||
| } | ||
| } | ||
|
|
||
| fn subscribe(&self) -> watch::Receiver<bool> { | ||
| self.inner.close_tx.subscribe() | ||
| } | ||
|
|
||
| fn is_terminated(&self) -> bool { | ||
| self.inner.terminated.get() | ||
| } | ||
|
|
||
| fn is_armed(&self) -> bool { | ||
| self.inner.on_terminate.borrow().is_some() | ||
| } | ||
|
|
||
| fn disarm(&self) { | ||
| self.inner.on_terminate.borrow_mut().take(); | ||
| } | ||
|
|
||
| fn set_on_terminate(&self, callback: LifecycleCallback) { | ||
| *self.inner.on_terminate.borrow_mut() = Some(callback); | ||
| } | ||
| } | ||
|
|
||
| impl<R: DeserializeOwned> ChannelTask<R> { | ||
| /// Create a new `ChannelTask` from a channel and a result receiver. | ||
| #[doc(hidden)] | ||
| pub fn new(channel: Channel, result_rx: oneshot::Receiver<Vec<u8>>) -> Self { | ||
| Self::with_lifecycle(channel, result_rx, None, None) | ||
| } | ||
|
|
||
| #[doc(hidden)] | ||
| pub(crate) fn with_lifecycle( | ||
| channel: Channel, | ||
| result_rx: oneshot::Receiver<Vec<u8>>, | ||
| on_complete: Option<LifecycleCallback>, | ||
| on_terminate: Option<LifecycleCallback>, | ||
| ) -> Self { | ||
| Self { | ||
| channel, | ||
| result_rx, | ||
| result_rx: Some(result_rx), | ||
| control: ChannelTaskControl::new(on_terminate), | ||
| on_complete, | ||
| _phantom: PhantomData, | ||
| } | ||
| } | ||
|
|
||
| pub(crate) fn with_callbacks( | ||
| mut self, | ||
| on_complete: LifecycleCallback, | ||
| on_terminate: LifecycleCallback, | ||
| ) -> Self { | ||
| self.on_complete = Some(on_complete); | ||
| self.control.set_on_terminate(on_terminate); | ||
| self | ||
| } | ||
|
|
||
| /// Return a cloneable controller that can terminate this task externally. | ||
| pub fn control(&self) -> ChannelTaskControl { | ||
| self.control.clone() | ||
| } | ||
|
|
||
| /// Receive the next deserialized message from the worker. | ||
| /// | ||
| /// Returns `None` if the channel's sender side has been dropped | ||
| /// (i.e., the worker has finished and closed the channel). | ||
| /// Returns `None` if the channel closes or the task is terminated. | ||
| pub async fn recv<T: DeserializeOwned>(&self) -> Option<T> { | ||
| self.channel.recv().await | ||
| let bytes = self.recv_bytes().await?; | ||
| Some(from_bytes(&bytes)) | ||
| } | ||
|
|
||
| /// Receive raw bytes from the worker. | ||
| /// | ||
| /// Returns `None` if the channel's sender side has been dropped. | ||
| /// Returns `None` if the channel closes or the task is terminated. | ||
| pub async fn recv_bytes(&self) -> Option<Box<[u8]>> { | ||
| self.channel.recv_bytes().await | ||
| if self.control.is_terminated() { | ||
| return None; | ||
| } | ||
|
|
||
| let mut close_rx = self.control.subscribe(); | ||
| let message = self.channel.recv_bytes(); | ||
| let closed = close_rx.changed(); | ||
| pin_mut!(message, closed); | ||
|
|
||
| match select(message, closed).await { | ||
| futures::future::Either::Left((message, _)) if !self.control.is_terminated() => message, | ||
| _ => None, | ||
| } | ||
| } | ||
|
|
||
| /// Send a serialized message to the worker. | ||
|
|
@@ -69,11 +176,41 @@ impl<R: DeserializeOwned> ChannelTask<R> { | |
| } | ||
|
|
||
| /// Await the task's final result, consuming the `ChannelTask`. | ||
| pub async fn result(self) -> R { | ||
| let bytes = self | ||
| pub async fn result(mut self) -> Result<R, TaskError> { | ||
| let result_rx = self | ||
| .result_rx | ||
| .await | ||
| .expect("WebWorker result sender dropped"); | ||
| from_bytes(&bytes) | ||
| .take() | ||
| .ok_or(TaskError::ResultAlreadyConsumed)?; | ||
| let result = result_rx.await.map_err(|_| TaskError::WorkerTerminated); | ||
|
|
||
| match result { | ||
| Ok(bytes) if !self.control.is_terminated() => { | ||
| self.control.disarm(); | ||
| if let Some(on_complete) = self.on_complete.take() { | ||
| on_complete(); | ||
| } | ||
| Ok(from_bytes(&bytes)) | ||
| } | ||
| Ok(_) | Err(_) => { | ||
| self.control.terminate(); | ||
| Err(TaskError::WorkerTerminated) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Terminate the worker running this task. | ||
| /// | ||
| /// Pool tasks exclusively lease their worker. The pool replaces the terminated | ||
| /// worker in the same slot before making that slot schedulable again. | ||
| pub fn terminate(&self) { | ||
| self.control.terminate(); | ||
| } | ||
| } | ||
|
|
||
| impl<R> Drop for ChannelTask<R> { | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Dropping a task whose function already completed (result unconsumed) still kills and replaces a healthy worker. A |
||
| fn drop(&mut self) { | ||
| if self.control.is_armed() { | ||
| self.control.terminate(); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this variant is unreachable.
result(mut self)consumesself, soresult_rxcan only be taken once (theOptionexists only becauseDropis implemented). Consider.expect("result_rx is only taken here")and droppingResultAlreadyConsumedfrom the publicTaskErrorenum, so callers don't have to handle an impossible error.