-
Notifications
You must be signed in to change notification settings - Fork 431
feat(http): persist cookies on disk #1978
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
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
7ef9a00
enhance(http): persist cookies on disk
amrbashir 24f1e76
clippy
amrbashir e4eed02
Merge branch 'v2' into feat/http/persist-cookies
amrbashir 514afdb
inline reqwest_cookie_store to fix clippy
amrbashir 8f5b6ca
clippy
amrbashir f2fcf2b
Update .changes/persist-cookies.md
amrbashir 10ce353
Update plugins/http/src/reqwest_cookie_store.rs
amrbashir dbf5695
Merge branch 'v2' into feat/http/persist-cookies
lucasfernog 5881ee3
update example
lucasfernog 39bc197
fallback to empty store if failed to load
lucasfernog ea860c4
fix example
lucasfernog 356b7ec
persist cookies immediately
lucasfernog c74db78
clone
lucasfernog b3cec50
lint
lucasfernog e76347b
.cookies filename
lucasfernog be11ca8
prevent race condition
lucasfernog 3d8ce8e
Merge remote-tracking branch 'origin/v2' into feat/http/persist-cookies
lucasfernog 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
--- | ||
"http": "patch" | ||
"http-js": "patch" | ||
--- | ||
|
||
Persist cookies to disk and load it on next app start. | ||
|
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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
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
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 |
---|---|---|
@@ -0,0 +1,133 @@ | ||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// SPDX-License-Identifier: MIT | ||
|
||
// taken from https://github.com/pfernie/reqwest_cookie_store/blob/2ec4afabcd55e24d3afe3f0626ee6dc97bed938d/src/lib.rs | ||
amrbashir marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
use std::{ | ||
path::PathBuf, | ||
sync::{mpsc::Receiver, Mutex}, | ||
}; | ||
|
||
use cookie_store::{CookieStore, RawCookie, RawCookieParseError}; | ||
use reqwest::header::HeaderValue; | ||
|
||
fn set_cookies( | ||
cookie_store: &mut CookieStore, | ||
cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, | ||
url: &url::Url, | ||
) { | ||
let cookies = cookie_headers.filter_map(|val| { | ||
std::str::from_utf8(val.as_bytes()) | ||
.map_err(RawCookieParseError::from) | ||
.and_then(RawCookie::parse) | ||
.map(|c| c.into_owned()) | ||
.ok() | ||
}); | ||
cookie_store.store_response_cookies(cookies, url); | ||
} | ||
|
||
fn cookies(cookie_store: &CookieStore, url: &url::Url) -> Option<HeaderValue> { | ||
let s = cookie_store | ||
.get_request_values(url) | ||
.map(|(name, value)| format!("{}={}", name, value)) | ||
.collect::<Vec<_>>() | ||
.join("; "); | ||
|
||
if s.is_empty() { | ||
return None; | ||
} | ||
|
||
HeaderValue::from_maybe_shared(bytes::Bytes::from(s)).ok() | ||
} | ||
|
||
/// A [`cookie_store::CookieStore`] wrapped internally by a [`std::sync::Mutex`], suitable for use in | ||
/// async/concurrent contexts. | ||
#[derive(Debug)] | ||
pub struct CookieStoreMutex { | ||
pub path: PathBuf, | ||
store: Mutex<CookieStore>, | ||
save_task: Mutex<Option<CancellableTask>>, | ||
} | ||
|
||
impl CookieStoreMutex { | ||
/// Create a new [`CookieStoreMutex`] from an existing [`cookie_store::CookieStore`]. | ||
pub fn new(path: PathBuf, cookie_store: CookieStore) -> CookieStoreMutex { | ||
CookieStoreMutex { | ||
path, | ||
store: Mutex::new(cookie_store), | ||
save_task: Default::default(), | ||
} | ||
} | ||
|
||
pub fn load<R: std::io::BufRead>( | ||
path: PathBuf, | ||
reader: R, | ||
) -> cookie_store::Result<CookieStoreMutex> { | ||
cookie_store::serde::load(reader, |c| serde_json::from_str(c)) | ||
.map(|store| CookieStoreMutex::new(path, store)) | ||
} | ||
|
||
fn cookies_to_str(&self) -> Result<String, serde_json::Error> { | ||
let mut cookies = Vec::new(); | ||
for cookie in self | ||
.store | ||
.lock() | ||
.expect("poisoned cookie jar mutex") | ||
.iter_unexpired() | ||
{ | ||
if cookie.is_persistent() { | ||
cookies.push(cookie.clone()); | ||
} | ||
} | ||
serde_json::to_string(&cookies) | ||
} | ||
|
||
pub fn request_save(&self) -> cookie_store::Result<Receiver<()>> { | ||
let cookie_str = self.cookies_to_str()?; | ||
let path = self.path.clone(); | ||
let (tx, rx) = std::sync::mpsc::channel(); | ||
let task = tauri::async_runtime::spawn(async move { | ||
match tokio::fs::write(&path, &cookie_str).await { | ||
Ok(()) => { | ||
let _ = tx.send(()); | ||
} | ||
Err(_e) => { | ||
#[cfg(feature = "tracing")] | ||
tracing::error!("failed to save cookie jar: {_e}"); | ||
} | ||
} | ||
}); | ||
self.save_task | ||
.lock() | ||
.unwrap() | ||
.replace(CancellableTask(task)); | ||
Ok(rx) | ||
} | ||
} | ||
|
||
impl reqwest::cookie::CookieStore for CookieStoreMutex { | ||
fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) { | ||
set_cookies(&mut self.store.lock().unwrap(), cookie_headers, url); | ||
|
||
// try to persist cookies immediately asynchronously | ||
if let Err(_e) = self.request_save() { | ||
#[cfg(feature = "tracing")] | ||
tracing::error!("failed to save cookie jar: {_e}"); | ||
} | ||
} | ||
|
||
fn cookies(&self, url: &url::Url) -> Option<HeaderValue> { | ||
let store = self.store.lock().unwrap(); | ||
cookies(&store, url) | ||
} | ||
} | ||
|
||
#[derive(Debug)] | ||
struct CancellableTask(tauri::async_runtime::JoinHandle<()>); | ||
|
||
impl Drop for CancellableTask { | ||
fn drop(&mut self) { | ||
self.0.abort(); | ||
} | ||
} |
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.
Uh oh!
There was an error while loading. Please reload this page.