Skip to content

Skus threading t3 (uplift to 1.63.x) #22315

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 1 commit into from
Feb 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions components/brave_vpn/browser/brave_vpn_service_unittest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -506,7 +506,7 @@ class BraveVPNServiceTest : public testing::Test {
PurchasedState state) {
observer->ResetStates();
SetPurchasedState(env, state);
base::RunLoop().RunUntilIdle();
task_environment_.RunUntilIdle();
EXPECT_TRUE(observer->GetPurchasedState().has_value());
EXPECT_EQ(observer->GetPurchasedState().value(), state);
}
Expand Down Expand Up @@ -799,7 +799,7 @@ TEST_F(BraveVPNServiceTest, LoadPurchasedStateForAnotherEnvFailed) {
EXPECT_FALSE(observer.GetPurchasedState().has_value());

LoadPurchasedState(development);
base::RunLoop().RunUntilIdle();
task_environment_.RunUntilIdle();
// Successfully set purchased state for dev env.
EXPECT_TRUE(observer.GetPurchasedState().has_value());
EXPECT_EQ(observer.GetPurchasedState().value(), PurchasedState::PURCHASED);
Expand All @@ -813,7 +813,7 @@ TEST_F(BraveVPNServiceTest, LoadPurchasedStateForAnotherEnvFailed) {
EXPECT_FALSE(observer.GetPurchasedState().has_value());
// no order found for staging.
LoadPurchasedState(staging);
base::RunLoop().RunUntilIdle();
task_environment_.RunUntilIdle();
// The purchased state was not changed from dev env.
EXPECT_FALSE(observer.GetPurchasedState().has_value());
EXPECT_EQ(GetCurrentEnvironment(), skus::GetDefaultEnvironment());
Expand All @@ -826,7 +826,7 @@ TEST_F(BraveVPNServiceTest, LoadPurchasedStateForAnotherEnvFailed) {
// No region data for staging.
SetInterceptorResponse("");
LoadPurchasedState(staging);
base::RunLoop().RunUntilIdle();
task_environment_.RunUntilIdle();
// The purchased state was not changed from dev env.
EXPECT_FALSE(observer.GetPurchasedState().has_value());
EXPECT_EQ(GetCurrentEnvironment(), skus::GetDefaultEnvironment());
Expand Down Expand Up @@ -983,7 +983,7 @@ TEST_F(BraveVPNServiceTest, LoadPurchasedStateNotifications) {
EXPECT_TRUE(observer.GetPurchasedState().has_value());
EXPECT_EQ(PurchasedState::LOADING, observer.GetPurchasedState().value());
}
base::RunLoop().RunUntilIdle();
task_environment_.RunUntilIdle();
EXPECT_TRUE(observer.GetPurchasedState().has_value());
EXPECT_EQ(PurchasedState::NOT_PURCHASED, GetPurchasedInfoSync());
// Observer called when state will be changed.
Expand All @@ -1000,7 +1000,7 @@ TEST_F(BraveVPNServiceTest, LoadPurchasedStateForAnotherEnv) {
EXPECT_EQ(PurchasedState::NOT_PURCHASED, GetPurchasedInfoSync());
EXPECT_EQ(GetCurrentEnvironment(), skus::GetDefaultEnvironment());
LoadPurchasedState(development);
base::RunLoop().RunUntilIdle();
task_environment_.RunUntilIdle();
// Successfully set purchased state for dev env.
EXPECT_TRUE(observer.GetPurchasedState().has_value());
EXPECT_EQ(observer.GetPurchasedState().value(), PurchasedState::PURCHASED);
Expand All @@ -1011,7 +1011,7 @@ TEST_F(BraveVPNServiceTest, LoadPurchasedStateForAnotherEnv) {
EXPECT_EQ(skus::GetEnvironmentForDomain(staging), skus::kEnvStaging);
EXPECT_EQ(GetCurrentEnvironment(), skus::GetDefaultEnvironment());
LoadPurchasedState(staging);
base::RunLoop().RunUntilIdle();
task_environment_.RunUntilIdle();
// Successfully changed purchased state for dev env.
EXPECT_TRUE(observer.GetPurchasedState().has_value());
EXPECT_EQ(observer.GetPurchasedState().value(), PurchasedState::PURCHASED);
Expand Down
14 changes: 12 additions & 2 deletions components/skus/browser/rs/cxx/src/httpclient.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@ impl From<ffi::HttpResponse<'_>> for Result<http::Response<Vec<u8>>, InternalErr
)
})?;

response.headers_mut().ok_or(InternalError::BorrowFailed)?.insert(key, value);
if let Some(headers) = response.headers_mut() {
headers.insert(key, value);
}
}

response
Expand All @@ -105,9 +107,17 @@ impl NativeClient {
) -> Result<http::Response<Vec<u8>>, InternalError> {
let (tx, rx) = oneshot::channel();
let context = Box::new(HttpRoundtripContext { tx, client: self.clone() });
let ctx = self
.inner
.lock().await
.ctx
.clone();

let fetcher = ffi::shim_executeRequest(
&self.ctx.try_borrow().map_err(|_| InternalError::BorrowFailed)?.ctx,
&*ctx
.try_borrow()
.map_err(|_| InternalError::BorrowFailed)?
,
&req,
|context, resp| {
let _ = context.tx.send(resp.into());
Expand Down
124 changes: 91 additions & 33 deletions components/skus/browser/rs/cxx/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,39 @@ mod storage;
use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;
use std::thread;

use cxx::{type_id, ExternType, UniquePtr};
use futures::executor::{LocalPool, LocalSpawner};
use futures::task::LocalSpawnExt;
use futures::lock::Mutex;

use tracing::debug;

pub use skus;

use crate::httpclient::{HttpRoundtripContext, WakeupContext};
use crate::storage::{StorageGetContext, StoragePurgeContext, StorageSetContext};
use errors::result_to_string;

pub struct NativeClientContext {
pub struct NativeClientExecutor {
is_shutdown: bool,
pool: Option<LocalPool>,
spawner: LocalSpawner,
thread_id: thread::ThreadId,
}

#[derive(Clone)]
pub struct NativeClientInner {
environment: skus::Environment,
ctx: UniquePtr<ffi::SkusContext>,
executor: Rc<RefCell<NativeClientExecutor>>,
ctx: Rc<RefCell<UniquePtr<ffi::SkusContext>>>,
}

#[derive(Clone)]
pub struct NativeClient {
is_shutdown: Rc<RefCell<bool>>,
pool: Rc<RefCell<LocalPool>>,
spawner: LocalSpawner,
ctx: Rc<RefCell<NativeClientContext>>,
executor: Rc<RefCell<NativeClientExecutor>>,
inner: Rc<Mutex<NativeClientInner>>,
}

impl fmt::Debug for NativeClient {
Expand All @@ -44,11 +54,44 @@ impl fmt::Debug for NativeClient {

impl NativeClient {
fn try_run_until_stalled(&self) {
if *self.is_shutdown.borrow() {
let executor = self.executor.clone();
if let Ok(mut executor) = executor.try_borrow_mut() {
executor.try_run_until_stalled()
};
}

fn get_spawner(&self) -> LocalSpawner {
self.executor.borrow().spawner.clone()
}
}

impl NativeClientExecutor {
fn new() -> Self {
let pool = LocalPool::new();
let spawner = pool.spawner();
Self {
is_shutdown: false,
pool: Some(pool),
spawner,
thread_id: thread::current().id(),
}
}

fn shutdown(&mut self) {
// drop any existing futures
drop(self.pool.take());
// ensure lingering callbacks passed to c++ are short circuited
self.is_shutdown = true;
}

fn try_run_until_stalled(&mut self) {
assert!(thread::current().id() == self.thread_id, "sdk called on a different thread!");
let _ = thread::current().id() == self.thread_id;
if self.is_shutdown {
debug!("sdk is shutdown, exiting");
return;
}
if let Ok(mut pool) = self.pool.try_borrow_mut() {
if let Some(pool) = &mut self.pool {
pool.run_until_stalled();
}
}
Expand Down Expand Up @@ -128,6 +171,9 @@ mod ffi {
extern "Rust" {
type HttpRoundtripContext;
type WakeupContext;
type StoragePurgeContext;
type StorageSetContext;
type StorageGetContext;

type CppSDK;
fn initialize_sdk(ctx: UniquePtr<SkusContext>, env: String) -> Box<CppSDK>;
Expand Down Expand Up @@ -195,9 +241,26 @@ mod ffi {
ctx: Box<WakeupContext>,
);

fn shim_purge(ctx: Pin<&mut SkusContext>);
fn shim_set(ctx: Pin<&mut SkusContext>, key: &str, value: &str);
fn shim_get(ctx: Pin<&mut SkusContext>, key: &str) -> String;
fn shim_purge(
ctx: Pin<&mut SkusContext>,
done: fn(Box<StoragePurgeContext>, bool),
st_ctx: Box<StoragePurgeContext>,
);

fn shim_set(
ctx: Pin<&mut SkusContext>,
key: &str,
value: &str,
done: fn(Box<StorageSetContext>, bool),
st_ctx: Box<StorageSetContext>,
);

fn shim_get(
ctx: Pin<&mut SkusContext>,
key: &str,
done: fn(Box<StorageGetContext>, String, bool),
st_ctx: Box<StorageGetContext>,
);

type RefreshOrderCallbackState;
type RefreshOrderCallback = crate::RefreshOrderCallback;
Expand Down Expand Up @@ -230,14 +293,15 @@ fn initialize_sdk(ctx: UniquePtr<ffi::SkusContext>, env: String) -> Box<CppSDK>

let env = env.parse::<skus::Environment>().unwrap_or(skus::Environment::Local);

let pool = LocalPool::new();
let spawner = pool.spawner();
let executor = Rc::new(RefCell::new(NativeClientExecutor::new()));
let sdk = skus::sdk::SDK::new(
NativeClient {
is_shutdown: Rc::new(RefCell::new(false)),
pool: Rc::new(RefCell::new(pool)),
spawner: spawner.clone(),
ctx: Rc::new(RefCell::new(NativeClientContext { environment: env.clone(), ctx })),
executor: executor.clone(),
inner: Rc::new(Mutex::new(NativeClientInner {
environment: env.clone(),
executor,
ctx: Rc::new(RefCell::new(ctx)),
})),
},
env,
None,
Expand All @@ -246,23 +310,21 @@ fn initialize_sdk(ctx: UniquePtr<ffi::SkusContext>, env: String) -> Box<CppSDK>
let sdk = Rc::new(sdk);
{
let sdk = sdk.clone();
let spawner = sdk.client.get_spawner();
let init = async move { sdk.initialize().await };
if spawner.spawn_local(init).is_err() {
debug!("pool is shutdown");
}
}

sdk.client.pool.borrow_mut().run_until_stalled();
sdk.client.try_run_until_stalled();

Box::new(CppSDK { sdk })
}

impl CppSDK {
fn shutdown(&self) {
// drop any existing futures
drop(self.sdk.client.pool.take());
// ensure lingering callbacks passed to c++ are short circuited
*self.sdk.client.is_shutdown.borrow_mut() = true;
self.sdk.client.executor.borrow_mut().shutdown();
}

fn refresh_order(
Expand All @@ -271,7 +333,7 @@ impl CppSDK {
callback_state: UniquePtr<ffi::RefreshOrderCallbackState>,
order_id: String,
) {
let spawner = self.sdk.client.spawner.clone();
let spawner = self.sdk.client.get_spawner();
if spawner
.spawn_local(refresh_order_task(self.sdk.clone(), callback, callback_state, order_id))
.is_err()
Expand All @@ -288,7 +350,7 @@ impl CppSDK {
callback_state: UniquePtr<ffi::FetchOrderCredentialsCallbackState>,
order_id: String,
) {
let spawner = self.sdk.client.spawner.clone();
let spawner = self.sdk.client.get_spawner();
if spawner
.spawn_local(fetch_order_credentials_task(
self.sdk.clone(),
Expand All @@ -311,7 +373,7 @@ impl CppSDK {
domain: String,
path: String,
) {
let spawner = self.sdk.client.spawner.clone();
let spawner = self.sdk.client.get_spawner();
if spawner
.spawn_local(prepare_credentials_presentation_task(
self.sdk.clone(),
Expand All @@ -334,7 +396,7 @@ impl CppSDK {
callback_state: UniquePtr<ffi::CredentialSummaryCallbackState>,
domain: String,
) {
let spawner = self.sdk.client.spawner.clone();
let spawner = self.sdk.client.get_spawner();
if spawner
.spawn_local(credential_summary_task(
self.sdk.clone(),
Expand All @@ -357,7 +419,7 @@ impl CppSDK {
order_id: String,
receipt: String,
) {
let spawner = self.sdk.client.spawner.clone();
let spawner = self.sdk.client.get_spawner();
if spawner
.spawn_local(submit_receipt_task(
self.sdk.clone(),
Expand All @@ -379,7 +441,7 @@ impl CppSDK {
callback_state: UniquePtr<ffi::CreateOrderFromReceiptCallbackState>,
receipt: String,
) {
let spawner = self.sdk.client.spawner.clone();
let spawner = self.sdk.client.get_spawner();
if spawner
.spawn_local(create_order_from_receipt_task(
self.sdk.clone(),
Expand Down Expand Up @@ -563,11 +625,7 @@ async fn create_order_from_receipt_task(
callback_state: UniquePtr<ffi::CreateOrderFromReceiptCallbackState>,
receipt: String,
) {
match sdk
.create_order_from_receipt(&receipt)
.await
.map_err(|e| e.into())
{
match sdk.create_order_from_receipt(&receipt).await.map_err(|e| e.into()) {
Ok(order_id) => callback.0(callback_state.into_raw(), ffi::SkusResult::Ok, &order_id),
Err(e) => callback.0(callback_state.into_raw(), e, ""),
}
Expand Down
Loading