mirror of
https://github.com/lexmount/moli.git
synced 2026-11-21 16:03:10 +00:00
fix(file-api): retain MediaSource targets in object URLs
Register branded MediaSource objects alongside Blob entries, preserving native identity, creator keys and URL lifetimes. Capture the entry kind in parsed URLs and reject MediaSource fetches with a network error. Cover identity retention through wrapper GC and isolate teardown, revocation, cross-realm receivers and worker consumers. Add the passing MediaSource WPT to the catalogue.
This commit is contained in:
+215
-37
@@ -23,6 +23,30 @@ pub struct ObjectUrlEntry<AccessKey> {
|
||||
pub access_key: Option<AccessKey>,
|
||||
}
|
||||
|
||||
/// The object associated with an object URL. MediaSource is supplied by the
|
||||
/// embedding, so the store can retain its identity without treating it as bytes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ObjectUrlTarget<MediaSource> {
|
||||
Blob(BlobId),
|
||||
MediaSource(MediaSource),
|
||||
}
|
||||
|
||||
impl<MediaSource> ObjectUrlTarget<MediaSource> {
|
||||
fn blob_id(&self) -> Option<BlobId> {
|
||||
match self {
|
||||
Self::Blob(id) => Some(*id),
|
||||
Self::MediaSource(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A resolved entry retained by a parsed URL independently of revocation.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ObjectUrlData<MediaSource> {
|
||||
Blob { bytes: Arc<[u8]>, mime_type: String },
|
||||
MediaSource(MediaSource),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct BlobState<OwnerId, PartitionId> {
|
||||
owner_id: Option<OwnerId>,
|
||||
@@ -51,10 +75,10 @@ impl<OwnerId, PartitionId> Default for BlobEntries<OwnerId, PartitionId> {
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ObjectUrlState<OwnerId, AccessKey, Metadata> {
|
||||
struct ObjectUrlState<OwnerId, AccessKey, Metadata, MediaSource> {
|
||||
owner_id: Option<OwnerId>,
|
||||
lifetime_id: Option<u64>,
|
||||
blob_id: BlobId,
|
||||
target: ObjectUrlTarget<MediaSource>,
|
||||
access_key: Option<AccessKey>,
|
||||
metadata: Option<Metadata>,
|
||||
}
|
||||
@@ -65,14 +89,20 @@ struct ObjectUrlState<OwnerId, AccessKey, Metadata> {
|
||||
/// counts. The embedding layer owns JS wrappers and calls the retain/release
|
||||
/// hooks from its finalizers.
|
||||
#[derive(Debug)]
|
||||
pub struct BlobStore<OwnerId, PartitionId, AccessKey = (), Metadata = ()> {
|
||||
pub struct BlobStore<
|
||||
OwnerId,
|
||||
PartitionId,
|
||||
AccessKey = (),
|
||||
Metadata = (),
|
||||
MediaSource = std::convert::Infallible,
|
||||
> {
|
||||
blobs: Mutex<BlobEntries<OwnerId, PartitionId>>,
|
||||
next_blob_id: AtomicU64,
|
||||
object_urls: Mutex<HashMap<String, ObjectUrlState<OwnerId, AccessKey, Metadata>>>,
|
||||
object_urls: Mutex<HashMap<String, ObjectUrlState<OwnerId, AccessKey, Metadata, MediaSource>>>,
|
||||
}
|
||||
|
||||
impl<OwnerId, PartitionId, AccessKey, Metadata> Default
|
||||
for BlobStore<OwnerId, PartitionId, AccessKey, Metadata>
|
||||
impl<OwnerId, PartitionId, AccessKey, Metadata, MediaSource> Default
|
||||
for BlobStore<OwnerId, PartitionId, AccessKey, Metadata, MediaSource>
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
@@ -83,7 +113,8 @@ impl<OwnerId, PartitionId, AccessKey, Metadata> Default
|
||||
}
|
||||
}
|
||||
|
||||
impl<OwnerId, PartitionId, AccessKey, Metadata> BlobStore<OwnerId, PartitionId, AccessKey, Metadata>
|
||||
impl<OwnerId, PartitionId, AccessKey, Metadata, MediaSource>
|
||||
BlobStore<OwnerId, PartitionId, AccessKey, Metadata, MediaSource>
|
||||
where
|
||||
OwnerId: Copy + Eq + Hash,
|
||||
PartitionId: Eq,
|
||||
@@ -285,7 +316,29 @@ where
|
||||
access_key: Option<AccessKey>,
|
||||
metadata: Option<Metadata>,
|
||||
) -> Option<String> {
|
||||
self.retain_blob_object_url_ref(blob_id)?;
|
||||
self.create_object_url_with_target(
|
||||
owner_id,
|
||||
lifetime_id,
|
||||
ObjectUrlTarget::Blob(blob_id),
|
||||
origin,
|
||||
access_key,
|
||||
metadata,
|
||||
)
|
||||
}
|
||||
|
||||
/// Register a Blob or MediaSource under its creating environment's key.
|
||||
pub fn create_object_url_with_target(
|
||||
&self,
|
||||
owner_id: Option<OwnerId>,
|
||||
lifetime_id: Option<u64>,
|
||||
target: ObjectUrlTarget<MediaSource>,
|
||||
origin: &str,
|
||||
access_key: Option<AccessKey>,
|
||||
metadata: Option<Metadata>,
|
||||
) -> Option<String> {
|
||||
if let Some(blob_id) = target.blob_id() {
|
||||
self.retain_blob_object_url_ref(blob_id)?;
|
||||
}
|
||||
let mut object_urls = self.object_urls.lock();
|
||||
let object_url = loop {
|
||||
let candidate = format!("blob:{origin}/{}", random_uuid());
|
||||
@@ -298,7 +351,7 @@ where
|
||||
ObjectUrlState {
|
||||
owner_id,
|
||||
lifetime_id,
|
||||
blob_id,
|
||||
target,
|
||||
access_key,
|
||||
metadata,
|
||||
},
|
||||
@@ -306,7 +359,7 @@ where
|
||||
Some(object_url)
|
||||
}
|
||||
|
||||
/// Revoke an object URL and release its Blob object-URL reference.
|
||||
/// Revoke an object URL and release its associated object reference.
|
||||
pub fn revoke_object_url(&self, url: &str) -> bool {
|
||||
self.revoke_object_url_if(url, |_| true)
|
||||
}
|
||||
@@ -323,7 +376,7 @@ where
|
||||
fn revoke_object_url_if(
|
||||
&self,
|
||||
url: &str,
|
||||
is_authorized: impl FnOnce(&ObjectUrlState<OwnerId, AccessKey, Metadata>) -> bool,
|
||||
is_authorized: impl FnOnce(&ObjectUrlState<OwnerId, AccessKey, Metadata, MediaSource>) -> bool,
|
||||
) -> bool {
|
||||
let state = {
|
||||
let mut object_urls = self.object_urls.lock();
|
||||
@@ -332,7 +385,9 @@ where
|
||||
}
|
||||
object_urls.remove(url).expect("authorized entry is locked")
|
||||
};
|
||||
self.release_blob_object_url_ref(state.blob_id);
|
||||
if let Some(blob_id) = state.target.blob_id() {
|
||||
self.release_blob_object_url_ref(blob_id);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -349,7 +404,7 @@ where
|
||||
let (bytes, mime_type) = {
|
||||
let url = url.split_once('#').map_or(url, |(url, _)| url);
|
||||
let object_urls = self.object_urls.lock();
|
||||
self.object_url_blob_data(object_urls.get(url)?.blob_id)?
|
||||
self.object_url_blob_data(object_urls.get(url)?.target.blob_id()?)?
|
||||
};
|
||||
Some((bytes.read_blocking().ok()?, mime_type))
|
||||
}
|
||||
@@ -370,7 +425,7 @@ where
|
||||
if state.access_key.as_ref() != Some(access_key) {
|
||||
return None;
|
||||
}
|
||||
self.object_url_blob_data(state.blob_id)
|
||||
self.object_url_blob_data(state.target.blob_id()?)
|
||||
}
|
||||
|
||||
/// Capture an object URL entry without copying its immutable body. The
|
||||
@@ -379,7 +434,7 @@ where
|
||||
let (data, mime_type) = {
|
||||
let url = url.split_once('#').map_or(url, |(url, _)| url);
|
||||
let object_urls = self.object_urls.lock();
|
||||
self.object_url_blob_data(object_urls.get(url)?.blob_id)?
|
||||
self.object_url_blob_data(object_urls.get(url)?.target.blob_id()?)?
|
||||
};
|
||||
let bytes = data
|
||||
.shared_bytes()
|
||||
@@ -397,7 +452,7 @@ where
|
||||
let url = url.split_once('#').map_or(url, |(url, _)| url);
|
||||
let object_urls = self.object_urls.lock();
|
||||
let state = object_urls.get(url)?;
|
||||
let (data, mime_type) = self.object_url_blob_data(state.blob_id)?;
|
||||
let (data, mime_type) = self.object_url_blob_data(state.target.blob_id()?)?;
|
||||
(data, mime_type, state.access_key.clone())
|
||||
};
|
||||
let bytes = data
|
||||
@@ -416,6 +471,28 @@ where
|
||||
Some((blob.bytes.clone(), blob.mime_type.clone()))
|
||||
}
|
||||
|
||||
/// Resolve the associated object, retaining the distinction between Blob
|
||||
/// bytes and MediaSource. Lookup ignores the URL fragment.
|
||||
pub fn object_url_data(&self, url: &str) -> Option<ObjectUrlData<MediaSource>>
|
||||
where
|
||||
MediaSource: Clone,
|
||||
{
|
||||
let (data, mime_type) = {
|
||||
let url = url.split_once('#').map_or(url, |(url, _)| url);
|
||||
let object_urls = self.object_urls.lock();
|
||||
match &object_urls.get(url)?.target {
|
||||
ObjectUrlTarget::Blob(id) => self.object_url_blob_data(*id)?,
|
||||
ObjectUrlTarget::MediaSource(source) => {
|
||||
return Some(ObjectUrlData::MediaSource(source.clone()));
|
||||
}
|
||||
}
|
||||
};
|
||||
let bytes = data
|
||||
.shared_bytes()
|
||||
.or_else(|| data.read_blocking().ok().map(Arc::from))?;
|
||||
Some(ObjectUrlData::Blob { bytes, mime_type })
|
||||
}
|
||||
|
||||
/// Return object URL body decoded lossily as text plus MIME type.
|
||||
pub fn object_url_body_and_type(&self, url: &str) -> Option<(String, String)> {
|
||||
let (bytes, mime_type) = self.object_url_bytes_and_type(url)?;
|
||||
@@ -439,22 +516,14 @@ where
|
||||
/// Revoke one owner's URLs for an execution-context lifetime.
|
||||
/// Lifetime identifiers are local to each resource owner.
|
||||
pub fn cleanup_object_url_lifetime(&self, owner_id: OwnerId, lifetime_id: u64) -> usize {
|
||||
let removed_blob_ids = {
|
||||
let mut object_urls = self.object_urls.lock();
|
||||
let mut removed_blob_ids = Vec::new();
|
||||
object_urls.retain(|_, state| {
|
||||
if state.owner_id == Some(owner_id) && state.lifetime_id == Some(lifetime_id) {
|
||||
removed_blob_ids.push(state.blob_id);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
removed_blob_ids
|
||||
};
|
||||
let removed_count = removed_blob_ids.len();
|
||||
for blob_id in removed_blob_ids {
|
||||
self.release_blob_object_url_ref(blob_id);
|
||||
let removed = self.take_object_urls_if(|state| {
|
||||
state.owner_id == Some(owner_id) && state.lifetime_id == Some(lifetime_id)
|
||||
});
|
||||
let removed_count = removed.len();
|
||||
for state in removed {
|
||||
if let Some(blob_id) = state.target.blob_id() {
|
||||
self.release_blob_object_url_ref(blob_id);
|
||||
}
|
||||
}
|
||||
removed_count
|
||||
}
|
||||
@@ -477,19 +546,25 @@ where
|
||||
};
|
||||
|
||||
let removed = self.take_object_urls_if(|state| {
|
||||
state.owner_id == Some(owner_id) || removed_blob_ids.contains(&state.blob_id)
|
||||
state.owner_id == Some(owner_id)
|
||||
|| state
|
||||
.target
|
||||
.blob_id()
|
||||
.is_some_and(|id| removed_blob_ids.contains(&id))
|
||||
});
|
||||
for state in removed {
|
||||
if !removed_blob_ids.contains(&state.blob_id) {
|
||||
self.release_blob_object_url_ref(state.blob_id);
|
||||
if let Some(blob_id) = state.target.blob_id()
|
||||
&& !removed_blob_ids.contains(&blob_id)
|
||||
{
|
||||
self.release_blob_object_url_ref(blob_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn take_object_urls_if(
|
||||
&self,
|
||||
mut remove: impl FnMut(&ObjectUrlState<OwnerId, AccessKey>) -> bool,
|
||||
) -> Vec<ObjectUrlState<OwnerId, AccessKey>> {
|
||||
mut remove: impl FnMut(&ObjectUrlState<OwnerId, AccessKey, Metadata, MediaSource>) -> bool,
|
||||
) -> Vec<ObjectUrlState<OwnerId, AccessKey, Metadata, MediaSource>> {
|
||||
// Removed URL state is returned so associated objects are released after the lock.
|
||||
self.object_urls
|
||||
.lock()
|
||||
@@ -688,6 +763,109 @@ mod tests {
|
||||
assert!(store.object_url_entry(&format!("{url}?query")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn media_source_urls_preserve_type_identity_and_creator_lifetimes() {
|
||||
let store = BlobStore::<u64, u64, String, String, Arc<String>>::default();
|
||||
let source = Arc::new("native MediaSource".to_owned());
|
||||
let weak = Arc::downgrade(&source);
|
||||
let key = "creator".to_owned();
|
||||
let first = store
|
||||
.create_object_url_with_target(
|
||||
Some(1),
|
||||
Some(7),
|
||||
ObjectUrlTarget::MediaSource(source.clone()),
|
||||
"https://example.test",
|
||||
Some(key.clone()),
|
||||
Some("policy".to_owned()),
|
||||
)
|
||||
.unwrap();
|
||||
let second = store
|
||||
.create_object_url_with_target(
|
||||
Some(2),
|
||||
Some(7),
|
||||
ObjectUrlTarget::MediaSource(source),
|
||||
"https://example.test",
|
||||
Some(key.clone()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_ne!(first, second);
|
||||
assert!(store.object_url_shared_bytes_and_type(&first).is_none());
|
||||
assert!(store.object_url_entry(&first).is_none());
|
||||
assert!(
|
||||
store
|
||||
.object_url_data_with_access_key(&first, &key)
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
store
|
||||
.object_url_data_with_access_key(&format!("{first}#fragment"), &key)
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(store.object_url_metadata(&first).as_deref(), Some("policy"));
|
||||
let Some(ObjectUrlData::MediaSource(captured)) =
|
||||
store.object_url_data(&format!("{first}#fragment"))
|
||||
else {
|
||||
panic!("MediaSource entry should resolve");
|
||||
};
|
||||
let Some(ObjectUrlData::MediaSource(other)) = store.object_url_data(&second) else {
|
||||
panic!("second URL should resolve");
|
||||
};
|
||||
assert!(Arc::ptr_eq(&captured, &other));
|
||||
drop(other);
|
||||
assert!(!store.revoke_object_url_with_access_key(&first, &"other partition".to_owned()));
|
||||
assert!(!store.revoke_object_url_with_access_key(&format!("{first}#fragment"), &key));
|
||||
assert!(store.revoke_object_url_with_access_key(&first, &key));
|
||||
assert!(store.object_url_data(&first).is_none());
|
||||
assert!(store.object_url_data(&second).is_some());
|
||||
assert_eq!(store.cleanup_object_url_lifetime(1, 7), 0);
|
||||
assert_eq!(store.cleanup_object_url_lifetime(2, 7), 1);
|
||||
assert!(store.object_url_data(&second).is_none());
|
||||
assert!(weak.upgrade().is_some());
|
||||
drop(captured);
|
||||
assert!(weak.upgrade().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_object_url_cleanup_releases_only_the_creating_owner() {
|
||||
let store = BlobStore::<u64, u64, (), (), Arc<String>>::default();
|
||||
let blob = store.create_blob(Some(10), Some(1), b"blob".to_vec(), "text/plain".to_owned());
|
||||
let blob_url = store
|
||||
.create_object_url(Some(1), blob, "https://example.test")
|
||||
.unwrap();
|
||||
let source = Arc::new("native MediaSource".to_owned());
|
||||
let weak = Arc::downgrade(&source);
|
||||
let media_url = store
|
||||
.create_object_url_with_target(
|
||||
Some(1),
|
||||
Some(7),
|
||||
ObjectUrlTarget::MediaSource(source.clone()),
|
||||
"https://example.test",
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let retained_url = store
|
||||
.create_object_url_with_target(
|
||||
Some(2),
|
||||
Some(7),
|
||||
ObjectUrlTarget::MediaSource(source),
|
||||
"https://example.test",
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
store.release_blob_wrapper_ref(blob);
|
||||
store.cleanup_owner_resources(1);
|
||||
assert!(store.object_url_data(&blob_url).is_none());
|
||||
assert!(store.blob_bytes(blob).is_none());
|
||||
assert!(store.object_url_data(&media_url).is_none());
|
||||
assert!(store.object_url_data(&retained_url).is_some());
|
||||
assert!(weak.upgrade().is_some());
|
||||
store.cleanup_owner_resources(2);
|
||||
assert!(weak.upgrade().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_url_metadata_follows_url_lifetime_and_preserves_captured_environment() {
|
||||
let store = BlobStore::<u64, u64, (), Arc<Mutex<String>>>::default();
|
||||
|
||||
@@ -7,7 +7,7 @@ pub mod data_transfer;
|
||||
pub mod file;
|
||||
|
||||
pub use blob_data::{BlobData, BlobReadCompletion, BlobSource};
|
||||
pub use blob_store::{BlobId, BlobStore, ObjectUrlEntry};
|
||||
pub use blob_store::{BlobId, BlobStore, ObjectUrlData, ObjectUrlEntry, ObjectUrlTarget};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BlobLineEndings {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::context_bootstrap::media_source::{MediaSourceObject, media_source_object};
|
||||
use crate::native_bridge;
|
||||
use moli_file_api::{BlobData, BlobId, BlobStore};
|
||||
use moli_file_api::{BlobData, BlobId, BlobStore, ObjectUrlData, ObjectUrlTarget};
|
||||
pub(super) use moli_v8_util::buffer_source_bytes_from_value;
|
||||
pub(crate) use moli_webapi::blob::{blob_id_from_object, world_wrapper};
|
||||
use moli_webapi::blob::{BlobReadMode, BlobRuntime};
|
||||
@@ -32,6 +33,7 @@ type RendererBlobStore = BlobStore<
|
||||
RendererStoragePartitionIdentity,
|
||||
ObjectUrlAccessKey,
|
||||
crate::content_security_policy::ContentSecurityPolicySource,
|
||||
Arc<MediaSourceObject>,
|
||||
>;
|
||||
|
||||
static BLOB_STORE: OnceLock<RendererBlobStore> = OnceLock::new();
|
||||
@@ -97,7 +99,11 @@ pub(super) fn create_object_url_for_object<'s>(
|
||||
object: v8::Local<'s, v8::Object>,
|
||||
storage_key: moli_storage_key::MoliStorageKey,
|
||||
) -> Option<String> {
|
||||
let blob_id = blob_id_from_object(scope, object)?;
|
||||
let target = if is_blob_object(scope, object) {
|
||||
ObjectUrlTarget::Blob(blob_id_from_object(scope, object)?)
|
||||
} else {
|
||||
ObjectUrlTarget::MediaSource(media_source_object(scope, object)?)
|
||||
};
|
||||
let partition = current_blob_storage_partition_identity(scope)?;
|
||||
let owner_id = current_resource_owner_id(scope);
|
||||
let origin = storage_key.origin().to_owned();
|
||||
@@ -113,10 +119,10 @@ pub(super) fn create_object_url_for_object<'s>(
|
||||
crate::worker::worker_content_security_policy_snapshot(scope)
|
||||
.map(|policy| Arc::new(parking_lot::RwLock::new(policy)))
|
||||
};
|
||||
blob_store().create_object_url_with_metadata(
|
||||
blob_store().create_object_url_with_target(
|
||||
owner_id,
|
||||
lifetime_id,
|
||||
blob_id,
|
||||
target,
|
||||
&origin,
|
||||
Some(ObjectUrlAccessKey {
|
||||
partition,
|
||||
@@ -126,6 +132,12 @@ pub(super) fn create_object_url_for_object<'s>(
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) type RendererObjectUrlData = ObjectUrlData<Arc<MediaSourceObject>>;
|
||||
|
||||
pub(crate) fn object_url_data(url: &str) -> Option<RendererObjectUrlData> {
|
||||
blob_store().object_url_data(url)
|
||||
}
|
||||
|
||||
pub(crate) fn object_url_content_security_policy(
|
||||
url: &str,
|
||||
) -> Option<crate::content_security_policy::InheritedContentSecurityPolicy> {
|
||||
@@ -178,10 +190,6 @@ pub(super) fn object_url_body_and_type(url: &str) -> Option<(String, String)> {
|
||||
blob_store().object_url_body_and_type(url)
|
||||
}
|
||||
|
||||
pub(super) fn object_url_shared_bytes_and_type(url: &str) -> Option<(Arc<[u8]>, String)> {
|
||||
blob_store().object_url_shared_bytes_and_type(url)
|
||||
}
|
||||
|
||||
#[cfg(feature = "devtools")]
|
||||
fn blob_uuid(blob_id: BlobId) -> Option<String> {
|
||||
blob_store().blob_uuid(blob_id)
|
||||
|
||||
@@ -83,7 +83,7 @@ mod media_cues;
|
||||
pub(crate) use media_cues::new_media_error_value;
|
||||
mod media_file_template;
|
||||
mod media_queries;
|
||||
use moli_webapi::media_source;
|
||||
pub(crate) mod media_source;
|
||||
mod message_ports;
|
||||
mod microtask_checkpoint;
|
||||
mod navigation_activation;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
//! Host-owned MediaSource identity for object URL lifetimes.
|
||||
//! The interface shape and MIME support remain shared value bindings.
|
||||
mod state;
|
||||
|
||||
pub(crate) use state::{MediaSourceObject, media_source_object};
|
||||
pub(super) use moli_webapi::media_source::install_media_source_template_bindings;
|
||||
|
||||
pub(super) fn media_source_constructor_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
state::initialize(scope, args.this());
|
||||
rv.set(args.this().into());
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::HashMap,
|
||||
rc::Rc,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use crate::{util::get_private_value, web_api_interfaces};
|
||||
use moli_webapi_declare::WebApiObject;
|
||||
|
||||
const MEDIA_SOURCE_ID_SLOT: &str = "__moliMediaSourceId";
|
||||
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// Native identity retained by the wrapper, object URLs and parsed URL entries.
|
||||
/// It remains independent of the V8 wrapper's lifetime and contains no Blob data.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct MediaSourceObject {
|
||||
id: u64,
|
||||
}
|
||||
|
||||
#[derive(WebApiObject)]
|
||||
#[webapi(interface = web_api_interfaces::MediaSource)]
|
||||
struct MediaSourceInstanceDeclaration<'scope> {
|
||||
#[webapi(slot = MEDIA_SOURCE_ID_SLOT)]
|
||||
id: v8::Local<'scope, v8::BigInt>,
|
||||
}
|
||||
|
||||
type Store = Rc<RefCell<MediaSourceObjects>>;
|
||||
|
||||
#[derive(Default)]
|
||||
struct MediaSourceObjects {
|
||||
entries: HashMap<u64, (v8::Weak<v8::Object>, Arc<MediaSourceObject>)>,
|
||||
}
|
||||
|
||||
pub(super) fn initialize<'s>(scope: &mut v8::PinScope<'s, '_>, object: v8::Local<'s, v8::Object>) {
|
||||
let store = if let Some(store) = scope.get_slot::<Store>() {
|
||||
store.clone()
|
||||
} else {
|
||||
let store = Store::default();
|
||||
scope.set_slot(store.clone());
|
||||
store
|
||||
};
|
||||
let id = NEXT_ID
|
||||
.try_update(Ordering::Relaxed, Ordering::Relaxed, |next| {
|
||||
next.checked_add(1)
|
||||
})
|
||||
.expect("MediaSource identity exhausted");
|
||||
let source = Arc::new(MediaSourceObject { id });
|
||||
MediaSourceInstanceDeclaration::new(v8::BigInt::new_from_u64(scope, source.id))
|
||||
.initialize(scope, object)
|
||||
.expect("MediaSource instance should initialize");
|
||||
let weak_store = Rc::downgrade(&store);
|
||||
let weak = v8::Weak::with_finalizer(
|
||||
scope,
|
||||
object,
|
||||
Box::new(move |_| {
|
||||
if let Some(store) = weak_store.upgrade() {
|
||||
store.borrow_mut().entries.remove(&id);
|
||||
}
|
||||
}),
|
||||
);
|
||||
store.borrow_mut().entries.insert(id, (weak, source));
|
||||
}
|
||||
|
||||
pub(crate) fn media_source_object<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
object: v8::Local<'s, v8::Object>,
|
||||
) -> Option<Arc<MediaSourceObject>> {
|
||||
if !web_api_interfaces::MediaSource::is_instance(scope, object) {
|
||||
return None;
|
||||
}
|
||||
let id = get_private_value(scope, object, MEDIA_SOURCE_ID_SLOT)
|
||||
.and_then(|value| v8::Local::<v8::BigInt>::try_from(value).ok())?
|
||||
.u64_value()
|
||||
.0;
|
||||
scope
|
||||
.get_slot::<Store>()?
|
||||
.borrow()
|
||||
.entries
|
||||
.get(&id)
|
||||
.map(|(_, source)| source.clone())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use moli_file_api::{BlobStore, ObjectUrlData, ObjectUrlTarget};
|
||||
|
||||
#[test]
|
||||
fn media_source_urls_retain_identity_after_wrapper_gc_and_isolate_drop() {
|
||||
moli_v8_test_util::ensure_v8();
|
||||
let urls = BlobStore::<u64, u64, (), (), Arc<MediaSourceObject>>::default();
|
||||
let (url, weak) = {
|
||||
let mut isolate = v8::Isolate::new(Default::default());
|
||||
let (url, weak) = {
|
||||
let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));
|
||||
let scope = &mut scope.init();
|
||||
let context = v8::Context::new(scope, Default::default());
|
||||
let scope = &mut v8::ContextScope::new(scope, context);
|
||||
let object = v8::Object::new(scope);
|
||||
initialize(scope, object);
|
||||
let source = media_source_object(scope, object).unwrap();
|
||||
assert!(Arc::ptr_eq(
|
||||
&source,
|
||||
&media_source_object(scope, object).unwrap()
|
||||
));
|
||||
let other = v8::Object::new(scope);
|
||||
initialize(scope, other);
|
||||
assert!(!Arc::ptr_eq(
|
||||
&source,
|
||||
&media_source_object(scope, other).unwrap()
|
||||
));
|
||||
let weak = Arc::downgrade(&source);
|
||||
let url = urls
|
||||
.create_object_url_with_target(
|
||||
Some(1),
|
||||
Some(2),
|
||||
ObjectUrlTarget::MediaSource(source),
|
||||
"https://example.test",
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
(url, weak)
|
||||
};
|
||||
isolate.low_memory_notification();
|
||||
assert!(
|
||||
isolate
|
||||
.get_slot::<Store>()
|
||||
.unwrap()
|
||||
.borrow()
|
||||
.entries
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
weak.upgrade().is_some(),
|
||||
"URL retains the associated native object"
|
||||
);
|
||||
(url, weak)
|
||||
};
|
||||
let Some(ObjectUrlData::MediaSource(captured)) = urls.object_url_data(&url) else {
|
||||
panic!("URL must retain its MediaSource kind");
|
||||
};
|
||||
assert!(Arc::ptr_eq(&captured, &weak.upgrade().unwrap()));
|
||||
assert_eq!(urls.cleanup_object_url_lifetime(1, 2), 1);
|
||||
assert!(urls.object_url_data(&url).is_none());
|
||||
assert!(
|
||||
weak.upgrade().is_some(),
|
||||
"parsed URL retains the native object"
|
||||
);
|
||||
drop(captured);
|
||||
assert!(weak.upgrade().is_none());
|
||||
}
|
||||
}
|
||||
@@ -24,14 +24,14 @@ fn url_create_object_url_callback<'s>(
|
||||
let Ok(object) = v8::Local::<v8::Object>::try_from(args.get(0)) else {
|
||||
throw_type_error(
|
||||
scope,
|
||||
"Failed to execute 'createObjectURL' on 'URL': parameter 1 is not of type 'Blob'.",
|
||||
"Failed to execute 'createObjectURL' on 'URL': parameter 1 is not of type 'Blob' or 'MediaSource'.",
|
||||
);
|
||||
return;
|
||||
};
|
||||
let Some(url) = blob::create_object_url_for_object(scope, object, storage_key) else {
|
||||
throw_type_error(
|
||||
scope,
|
||||
"Failed to execute 'createObjectURL' on 'URL': parameter 1 is not of type 'Blob'.",
|
||||
"Failed to execute 'createObjectURL' on 'URL': parameter 1 is not of type 'Blob' or 'MediaSource'.",
|
||||
);
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! URL parsing captures the blob entry, including a failed lookup. Revoking
|
||||
//! the URL must not invalidate an existing Request or a successfully opened
|
||||
//! XHR. Private carriers retain shared bytes until their last JS owner is
|
||||
//! collected; the isolate store also releases them on isolate teardown.
|
||||
//! XHR. Private carriers retain the Blob bytes or native MediaSource identity
|
||||
//! until their last JS owner is collected; isolate teardown also releases them.
|
||||
|
||||
use std::{cell::RefCell, collections::HashMap, rc::Rc, sync::Arc};
|
||||
use std::{cell::RefCell, collections::HashMap, rc::Rc};
|
||||
|
||||
use crate::util::{get_private_value, set_private_value};
|
||||
use moli_file_api::ObjectUrlData;
|
||||
|
||||
pub(in crate::network_host) const BLOB_URL_ENTRY_SLOT: &str = "__lmBlobUrlEntry";
|
||||
const ID_SLOT: &str = "__lmBlobUrlEntryId";
|
||||
@@ -13,7 +14,7 @@ const ID_SLOT: &str = "__lmBlobUrlEntryId";
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CapturedBlobUrl {
|
||||
url: url::Url,
|
||||
data: Option<(Arc<[u8]>, String)>,
|
||||
data: Option<crate::blob::RendererObjectUrlData>,
|
||||
}
|
||||
|
||||
impl CapturedBlobUrl {
|
||||
@@ -23,7 +24,7 @@ impl CapturedBlobUrl {
|
||||
}
|
||||
let mut url = url.clone();
|
||||
url.set_fragment(None);
|
||||
let data = crate::blob::object_url_shared_bytes_and_type(url.as_str());
|
||||
let data = crate::blob::object_url_data(url.as_str());
|
||||
Some(Self { url, data })
|
||||
}
|
||||
|
||||
@@ -32,7 +33,14 @@ impl CapturedBlobUrl {
|
||||
url: &url::Url,
|
||||
request_headers: &[(String, String)],
|
||||
) -> Option<Result<super::Response, super::browser_response::LocalUrlError>> {
|
||||
let (body, mime_type) = self.data.as_ref()?;
|
||||
let ObjectUrlData::Blob {
|
||||
bytes: body,
|
||||
mime_type,
|
||||
} = self.data.as_ref()?
|
||||
else {
|
||||
// Fetch's blob scheme only reads Blob objects, never MediaSource.
|
||||
return Some(Err(super::browser_response::LocalUrlError::MediaSource));
|
||||
};
|
||||
Some(super::browser_response::blob_response(
|
||||
url,
|
||||
body,
|
||||
@@ -129,11 +137,22 @@ pub(crate) fn blob_url_entry<'s>(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn bytes(entry: &CapturedBlobUrl) -> &Arc<[u8]> {
|
||||
let Some(ObjectUrlData::Blob { bytes, .. }) = &entry.data else {
|
||||
panic!("expected captured Blob bytes");
|
||||
};
|
||||
bytes
|
||||
}
|
||||
|
||||
fn entry() -> CapturedBlobUrl {
|
||||
CapturedBlobUrl {
|
||||
url: url::Url::parse("blob:https://example.test/captured").unwrap(),
|
||||
data: Some((Arc::from([0, 128, 255]), "application/example".to_owned())),
|
||||
data: Some(ObjectUrlData::Blob {
|
||||
bytes: Arc::from([0, 128, 255]),
|
||||
mime_type: "application/example".to_owned(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,7 +168,7 @@ mod tests {
|
||||
let scope = &mut v8::ContextScope::new(scope, first);
|
||||
let owner = v8::Object::new(scope);
|
||||
let entry = entry();
|
||||
let weak = Arc::downgrade(&entry.data.as_ref().unwrap().0);
|
||||
let weak = Arc::downgrade(bytes(&entry));
|
||||
set_blob_url_entry(scope, owner, Some(entry));
|
||||
let second = v8::Context::new(scope, Default::default());
|
||||
let scope = &mut v8::ContextScope::new(scope, second);
|
||||
@@ -157,10 +176,7 @@ mod tests {
|
||||
let carrier = get_private_value(scope, owner, BLOB_URL_ENTRY_SLOT).unwrap();
|
||||
set_private_value(scope, other, BLOB_URL_ENTRY_SLOT, carrier);
|
||||
let captured = blob_url_entry(scope, other).unwrap();
|
||||
assert!(Arc::ptr_eq(
|
||||
&captured.data.unwrap().0,
|
||||
&weak.upgrade().unwrap()
|
||||
));
|
||||
assert!(Arc::ptr_eq(bytes(&captured), &weak.upgrade().unwrap()));
|
||||
(weak, v8::Global::new(scope, other))
|
||||
};
|
||||
isolate.low_memory_notification();
|
||||
@@ -183,7 +199,7 @@ mod tests {
|
||||
let scope = &mut v8::ContextScope::new(scope, context);
|
||||
let owner = v8::Object::new(scope);
|
||||
let entry = entry();
|
||||
let weak = Arc::downgrade(&entry.data.as_ref().unwrap().0);
|
||||
let weak = Arc::downgrade(bytes(&entry));
|
||||
set_blob_url_entry(scope, owner, Some(entry));
|
||||
weak
|
||||
};
|
||||
|
||||
@@ -6,6 +6,7 @@ use std::fmt;
|
||||
pub(crate) enum LocalUrlError {
|
||||
BlobMethod { method: String },
|
||||
BlobRange,
|
||||
MediaSource,
|
||||
BlobUnavailable { url: url::Url },
|
||||
InvalidData { url: url::Url },
|
||||
}
|
||||
@@ -17,6 +18,7 @@ impl fmt::Display for LocalUrlError {
|
||||
Self::BlobRange => {
|
||||
f.write_str("blob URL fetch has an invalid or unsatisfiable Range header")
|
||||
}
|
||||
Self::MediaSource => f.write_str("MediaSource object URLs cannot be fetched"),
|
||||
Self::BlobUnavailable { url } => write!(f, "blob URL `{url}` is unavailable"),
|
||||
Self::InvalidData { url } => write!(f, "data URL `{url}` is invalid"),
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::service_worker_drain::drain_service_worker_test_turn;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
@@ -2162,6 +2163,41 @@ fn text_track_id_and_cue_order_follow_wpt_edges() {
|
||||
|
||||
assert_eq!(result, "LoremIpsum:true|123|231|123|312");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn media_source_object_urls_preserve_native_brands_and_reject_fetch() {
|
||||
let loader = static_http_loader([]);
|
||||
let (mut vm, browser_context_runtime) =
|
||||
new_service_worker_page_test_vm_with_loader_and_browser_context_runtime(
|
||||
"https://media-source-url.test/",
|
||||
&loader,
|
||||
);
|
||||
let fixture = include_str!("../../../../tests/fixtures/media-source-url.js");
|
||||
vm.eval("globalThis.mediaSourceUrlResult = null; if (!document.documentElement) document.appendChild(document.createElement('html'));").unwrap();
|
||||
vm.eval(&format!(
|
||||
"{fixture}\nmediaSourceUrlProbe().then(value => {{ mediaSourceUrlResult = value; }}, error => {{ mediaSourceUrlResult = {{error: String(error.stack || error)}}; }});"
|
||||
)).unwrap();
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
while vm.eval("mediaSourceUrlResult !== null").unwrap() != "true" {
|
||||
browser_context_runtime.drain_shared_worker_service_lane();
|
||||
drain_service_worker_test_turn(&mut vm, &browser_context_runtime, &loader).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("MediaSource URL checks should finish");
|
||||
let result: serde_json::Value =
|
||||
serde_json::from_str(&vm.eval("JSON.stringify(mediaSourceUrlResult)").unwrap()).unwrap();
|
||||
let checks = result["checks"]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("{result}"));
|
||||
let failures: Vec<_> = checks
|
||||
.iter()
|
||||
.filter(|check| check["pass"] != true)
|
||||
.collect();
|
||||
assert_eq!(result["state"], "pass", "{failures:?}");
|
||||
assert_eq!(checks.len(), 34);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn media_source_constructor_preserves_prototype_chain_and_static_surface() {
|
||||
let mut vm = new_storage_test_vm("https://example.com/");
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
async function mediaSourceUrlProbe() {
|
||||
const checks = [];
|
||||
const urls = [];
|
||||
const check = (label, actual, wanted) => checks.push({label, actual, wanted, pass: JSON.stringify(actual) === JSON.stringify(wanted)});
|
||||
const create = (source, api = URL) => {
|
||||
try { const url = api.createObjectURL(source); urls.push(url); return url; }
|
||||
catch (error) { return error.name; }
|
||||
};
|
||||
const isUrl = value => typeof value === 'string' && value.startsWith('blob:');
|
||||
const fetchResult = async input => {
|
||||
let promise;
|
||||
try { promise = fetch(input); } catch (error) { return 'sync:' + error.name; }
|
||||
try { await promise; return 'resolved'; } catch (error) { return 'async:' + error.name; }
|
||||
};
|
||||
try {
|
||||
const source = new MediaSource();
|
||||
const url = create(source);
|
||||
const other = create(source);
|
||||
check('create', isUrl(url), true);
|
||||
check('unique-urls', isUrl(url) && isUrl(other) && url !== other, true);
|
||||
check('origin', isUrl(url) ? new URL(url).origin : url, location.origin);
|
||||
check('uuid', isUrl(url) && /\/[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(url), true);
|
||||
const inherited = new (class extends MediaSource {})();
|
||||
check('subclass', isUrl(create(inherited)), true);
|
||||
const changedPrototype = new MediaSource();
|
||||
Object.setPrototypeOf(changedPrototype, null);
|
||||
check('changed-prototype', isUrl(create(changedPrototype)), true);
|
||||
let publicReads = 0;
|
||||
for (const key of ['constructor', 'readyState', 'toString', Symbol.toStringTag, Symbol.toPrimitive]) {
|
||||
Object.defineProperty(source, key, {get() { publicReads++; throw new Error('public member'); }});
|
||||
}
|
||||
check('private-identity', isUrl(create(source)), true);
|
||||
check('no-public-reads', publicReads, 0);
|
||||
const descriptor = Object.getOwnPropertyDescriptor(globalThis, 'MediaSource');
|
||||
try {
|
||||
globalThis.MediaSource = function() { throw new Error('replaced constructor'); };
|
||||
check('replaced-global-constructor', isUrl(create(source)), true);
|
||||
} finally { Object.defineProperty(globalThis, 'MediaSource', descriptor); }
|
||||
|
||||
let proxyReads = 0;
|
||||
const revoked = Proxy.revocable(source, {}); revoked.revoke();
|
||||
for (const [name, value] of [
|
||||
['undefined', undefined], ['null', null], ['record', {}], ['prototype', MediaSource.prototype],
|
||||
['forged', Object.create(MediaSource.prototype)], ['inherited', Object.create(source)],
|
||||
['proxy', new Proxy(source, {get() { proxyReads++; throw new Error('proxy get'); }})],
|
||||
['revoked', revoked.proxy], ['forged-blob', Object.create(Blob.prototype)],
|
||||
]) check('invalid/' + name, create(value), 'TypeError');
|
||||
check('proxy-not-observed', proxyReads, 0);
|
||||
|
||||
check('fetch', isUrl(url) ? await fetchResult(url) : 'no-url', 'async:TypeError');
|
||||
check('fetch-fragment', isUrl(url) ? await fetchResult(url + '#fragment') : 'no-url', 'async:TypeError');
|
||||
const request = isUrl(url) ? new Request(url) : null;
|
||||
check('fetch-request', request ? await fetchResult(request.clone()) : 'no-url', 'async:TypeError');
|
||||
check('fetch-no-cors', request ? await fetchResult(new Request(request, {mode: 'no-cors'})) : 'no-url', 'async:TypeError');
|
||||
if (isUrl(url)) { URL.revokeObjectURL(url); URL.revokeObjectURL(url); }
|
||||
check('captured-after-revoke', request ? await fetchResult(request.clone()) : 'no-url', 'async:TypeError');
|
||||
check('revoked-url', isUrl(url) ? await fetchResult(url) : 'no-url', 'async:TypeError');
|
||||
check('second-url', isUrl(other) ? await fetchResult(other) : 'no-url', 'async:TypeError');
|
||||
|
||||
const blobUrl = create(new Blob(['payload'], {type: 'text/plain'}));
|
||||
const blobRequest = new Request(blobUrl);
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
check('blob-captured-control', await (await fetch(blobRequest)).text(), 'payload');
|
||||
check('blob-revoked-control', await fetchResult(blobUrl), 'async:TypeError');
|
||||
const fileUrl = create(new File(['file'], 'test.txt'));
|
||||
check('file-control', await (await fetch(fileUrl)).text(), 'file');
|
||||
|
||||
for (const shared of [false, true]) {
|
||||
const kind = shared ? 'shared' : 'dedicated';
|
||||
let result = 'no-url';
|
||||
if (isUrl(other)) {
|
||||
const code = `const probe = async () => {
|
||||
try { await fetch(${JSON.stringify(other)}); return 'resolved'; }
|
||||
catch (error) { return error.name; }
|
||||
};` + (shared ? 'onconnect = event => probe().then(value => event.ports[0].postMessage(value));' : 'probe().then(postMessage);');
|
||||
const workerUrl = create(new Blob([code], {type: 'text/javascript'}));
|
||||
result = await new Promise(resolve => {
|
||||
const worker = shared ? new SharedWorker(workerUrl) : new Worker(workerUrl);
|
||||
const port = shared ? worker.port : worker;
|
||||
port.onmessage = event => {
|
||||
shared ? port.close() : worker.terminate();
|
||||
URL.revokeObjectURL(workerUrl);
|
||||
resolve(event.data);
|
||||
};
|
||||
worker.onerror = event => { event.preventDefault(); resolve('worker-error:' + event.message); };
|
||||
});
|
||||
}
|
||||
check(kind + '/fetch-media-source', result, 'TypeError');
|
||||
}
|
||||
|
||||
const frame = document.createElement('iframe');
|
||||
(document.body || document.documentElement).appendChild(frame);
|
||||
try {
|
||||
const child = frame.contentWindow;
|
||||
const childSource = new child.MediaSource();
|
||||
check('cross-realm-source', isUrl(create(childSource)), true);
|
||||
check('cross-realm-method', isUrl(create(source, child.URL)), true);
|
||||
let caught;
|
||||
try { child.URL.createObjectURL(new Proxy(source, {})); } catch (error) { caught = error; }
|
||||
check('callee-error-realm', [caught instanceof child.TypeError, caught instanceof TypeError], [true, false]);
|
||||
} finally { frame.remove(); }
|
||||
} finally {
|
||||
for (const url of urls) URL.revokeObjectURL(url);
|
||||
}
|
||||
return {state: checks.every(check => check.pass) ? 'pass' : 'fail', checks};
|
||||
}
|
||||
Reference in New Issue
Block a user