use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use tokio::sync::watch;
use super::handle::owned;
use super::state::{Lifecycle, Phase};
use super::{
NativeRecording, NativeRecordingOptions, RecordingError, RecordingSlot, RecordingState,
};
use crate::cdp::types::{RuntimeEvaluate, RuntimeEvaluateResult, ScreenRecordingResult};
use crate::util::LockExt;
use crate::{Error, Page};
fn classify_start(error: Error) -> RecordingError {
use crate::error::classify::{recording_start_failure, RecordingStartFailure};
let message = || error.message().to_owned();
match recording_start_failure(&error) {
Some(RecordingStartFailure::Unsupported) => RecordingError::Unsupported(message()),
Some(RecordingStartFailure::AlreadyActive) => RecordingError::AlreadyActive,
Some(RecordingStartFailure::Precondition) => RecordingError::Precondition(message()),
None => RecordingError::Core(error),
}
}
async fn abandon(
state: &RecordingState,
lifecycle: &mut Lifecycle,
slot: &RecordingSlot,
error: RecordingError,
) -> RecordingError {
match state.cleanup_locked(lifecycle, slot).await {
Ok(()) => error,
Err(cleanup) => RecordingError::CleanupUncertain(format!("start: {error}; {cleanup}")),
}
}
impl Page {
pub async fn start_recording(
&self,
options: NativeRecordingOptions,
) -> Result<NativeRecording, RecordingError> {
let params = options.params()?;
let slot = self.session.recording_slot();
let (state, transport) = {
let mut active = slot.lock_unpoisoned();
if active.is_some() {
return Err(RecordingError::AlreadyActive);
}
let transport = Arc::clone(self.session.transport());
let (loss, _) = watch::channel(None);
let state = Arc::new(RecordingState {
transport: Arc::downgrade(&transport),
session_id: self.session.session_id().into(),
target_id: self.session.target_id().into(),
lifecycle: tokio::sync::Mutex::new(Lifecycle::new()),
loss,
finished: AtomicBool::new(false),
cleanup_requested: AtomicBool::new(false),
read_in_flight: AtomicBool::new(false),
});
*active = Some(Arc::clone(&state));
(state, transport)
};
RecordingState::monitor(&state, &transport);
owned(async move {
let mut lifecycle = state.lifecycle.lock().await;
if lifecycle.phase != Phase::Starting {
return Err(RecordingError::InvalidState(
"start was cancelled before native dispatch".into(),
));
}
let ready: Result<RuntimeEvaluateResult, _> = state
.command(
"Runtime.evaluate",
&RuntimeEvaluate {
expression:
"({ready:document.readyState==='complete',top:window===window.top})"
.into(),
return_by_value: Some(true),
await_promise: Some(false),
},
)
.await;
let preflight = ready.and_then(|ready| {
if ready.exception_details.is_some()
|| ready
.result
.value
.as_ref()
.is_none_or(|value| value["ready"] != true || value["top"] != true)
{
Err(RecordingError::Precondition(
"document must be complete and top-level".into(),
))
} else {
state.check_operable()
}
});
if let Err(error) = preflight {
state.finish_locked(&mut lifecycle, &slot);
return Err(error);
}
lifecycle.start_dispatched = true;
let started: Result<ScreenRecordingResult, _> =
state.command("Page.startScreenRecording", ¶ms).await;
match started {
Ok(result) => {
lifecycle.streams[0] = Some(result.stream);
lifecycle.phase = Phase::Running;
if let Err(error) = state.check_operable() {
return Err(abandon(&state, &mut lifecycle, &slot, error).await);
}
drop(lifecycle);
Ok(NativeRecording {
state,
slot,
transport,
})
}
Err(RecordingError::Core(error)) if error.cdp_context().is_some() => {
state.finish_locked(&mut lifecycle, &slot);
Err(classify_start(error))
}
Err(error) => Err(abandon(&state, &mut lifecycle, &slot, error).await),
}
})
.await
}
}