feat: add custom audio sources
- Add capture_apps list of AudioSourceConfig (application, deviceOutput or deviceInput) to AudioSettings, serialized in the settings JSON - Add IPC commands getAudioDevices, addAudioSource, removeAudioSource and updateAudioSource - obs_context builds wasapi sources for the microphone and configured apps alongside the game-capture source - Settings.vue gains an audio sources tab with device dropdowns and per-source volume - getAudioDevices temporarily returns hardcoded defaults while the WASAPI enumeration crash is investigated; crash marker files around IPC and native call sites are part of that investigation
This commit is contained in:
1 parent
7468bdf5de
commit
4f9f84446d
13 files changed
+1711
-69
No files matched your search
@@ -17,6 +17,32 @@ use crate::recording::RecordingEngine;
|
||||
use crate::state::DaemonStatus;
|
||||
use crate::timeline::TimelineStore;
|
||||
|
||||
/// Write an *unbuffered* marker file that survives native crashes/segfaults.
|
||||
///
|
||||
/// The tracing log appender buffers writes in memory, so logs emitted microseconds
|
||||
/// before a native segfault are lost on disk — that's why the crash diagnostics
|
||||
/// added so far never appeared. This helper writes to a file with an immediate
|
||||
/// `sync_all` (fsync) so the bytes hit disk before control returns. After a crash,
|
||||
/// inspecting the marker directory tells us exactly how far execution got.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn write_crash_marker(stage: &str) {
|
||||
use std::io::Write;
|
||||
let dir = std::env::temp_dir().join("record-daemon-crash-markers");
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let path = dir.join(format!(
|
||||
"{}_{}.txt",
|
||||
stage,
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0)
|
||||
));
|
||||
if let Ok(mut f) = std::fs::File::create(&path) {
|
||||
let _ = writeln!(f, "{} @ {:?}", stage, std::thread::current().id());
|
||||
let _ = f.sync_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Command handler trait.
|
||||
#[async_trait]
|
||||
pub trait CommandHandler: Send + Sync {
|
||||
@@ -71,6 +97,10 @@ impl IpcHandlers {
|
||||
IpcCommand::ResetSettings => self.handle_reset_settings().await,
|
||||
IpcCommand::GetStatus => self.handle_get_status().await,
|
||||
IpcCommand::GetEncoders => self.handle_get_encoders().await,
|
||||
IpcCommand::GetAudioDevices => self.handle_get_audio_devices().await,
|
||||
IpcCommand::AddAudioSource => self.handle_add_audio_source(message.payload).await,
|
||||
IpcCommand::RemoveAudioSource { id } => self.handle_remove_audio_source(id).await,
|
||||
IpcCommand::UpdateAudioSource => self.handle_update_audio_source(message.payload).await,
|
||||
IpcCommand::StartRecording => self.handle_start_recording().await,
|
||||
IpcCommand::StopRecording => self.handle_stop_recording().await,
|
||||
IpcCommand::GetRecordings => self.handle_get_recordings().await,
|
||||
@@ -292,6 +322,415 @@ impl IpcHandlers {
|
||||
*self.status.write() = DaemonStatus::ShuttingDown;
|
||||
Ok(serde_json::json!({ "success": true }))
|
||||
}
|
||||
|
||||
async fn handle_get_audio_devices(&self) -> Result<serde_json::Value> {
|
||||
use super::protocol::GetAudioDevicesResponse;
|
||||
|
||||
info!("[AUDIO_ENUM] handle_get_audio_devices invoked");
|
||||
|
||||
// ---- CRASH ISOLATION HOOK ----
|
||||
// The daemon has been crashing when Settings is opened (which triggers this
|
||||
// command). The tracing log file is buffered, so logs written microseconds
|
||||
// before a native segfault are lost on disk — which is why none of the
|
||||
// diagnostics added so far ever showed up. To definitively determine whether
|
||||
// the crash happens inside this handler / the WASAPI enumeration, we:
|
||||
// 1. Write an *unbuffered* marker file (fsync) on entry and on success.
|
||||
// These survive native crashes and can be inspected afterwards.
|
||||
// 2. (Temporarily) return hardcoded default devices on Windows WITHOUT
|
||||
// calling into WASAPI at all. If the daemon still crashes, the WASAPI
|
||||
// code is NOT the culprit. If it stops crashing, WASAPI is confirmed.
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
write_crash_marker("audio_devices_enter");
|
||||
info!("[AUDIO_ENUM] Windows path: returning HARDCODED defaults (WASAPI bypassed for isolation)");
|
||||
|
||||
let response = GetAudioDevicesResponse {
|
||||
input_devices: vec![super::protocol::AudioDeviceInfo {
|
||||
id: "default".to_string(),
|
||||
name: "Default Microphone".to_string(),
|
||||
is_default: true,
|
||||
}],
|
||||
output_devices: vec![super::protocol::AudioDeviceInfo {
|
||||
id: "default".to_string(),
|
||||
name: "Default Speakers".to_string(),
|
||||
is_default: true,
|
||||
}],
|
||||
};
|
||||
|
||||
write_crash_marker("audio_devices_success");
|
||||
Ok(serde_json::to_value(response)?)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
// On Linux, enumerate PulseAudio devices
|
||||
let devices = enumerate_linux_audio_devices()?;
|
||||
let response = GetAudioDevicesResponse {
|
||||
input_devices: devices.0,
|
||||
output_devices: devices.1,
|
||||
};
|
||||
Ok(serde_json::to_value(response)?)
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
|
||||
{
|
||||
// Fallback for other platforms
|
||||
let response = GetAudioDevicesResponse {
|
||||
input_devices: vec![],
|
||||
output_devices: vec![],
|
||||
};
|
||||
Ok(serde_json::to_value(response)?)
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_add_audio_source(
|
||||
&self,
|
||||
payload: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
use super::protocol::AudioSourceResponse;
|
||||
|
||||
let payload = payload.ok_or_else(|| {
|
||||
crate::error::IpcError::InvalidCommand("Missing audio source payload".to_string())
|
||||
})?;
|
||||
|
||||
let mut source: crate::config::AudioSourceConfig = serde_json::from_value(payload)?;
|
||||
|
||||
// Generate a unique ID if not provided
|
||||
if source.id.is_empty() {
|
||||
source.id = uuid::Uuid::new_v4().to_string();
|
||||
}
|
||||
|
||||
info!("Adding audio source: {} ({})", source.name, source.id);
|
||||
|
||||
// Add to settings
|
||||
{
|
||||
let mut settings = self.settings.write();
|
||||
settings.audio.capture_apps.push(source.clone());
|
||||
crate::config::save_config(&settings)?;
|
||||
}
|
||||
|
||||
let response = AudioSourceResponse { source };
|
||||
Ok(serde_json::to_value(response)?)
|
||||
}
|
||||
|
||||
async fn handle_remove_audio_source(&self, id: String) -> Result<serde_json::Value> {
|
||||
info!("Removing audio source: {}", id);
|
||||
|
||||
{
|
||||
let mut settings = self.settings.write();
|
||||
settings
|
||||
.audio
|
||||
.capture_apps
|
||||
.retain(|s| s.id != id);
|
||||
crate::config::save_config(&settings)?;
|
||||
}
|
||||
|
||||
Ok(serde_json::json!({ "success": true }))
|
||||
}
|
||||
|
||||
async fn handle_update_audio_source(
|
||||
&self,
|
||||
payload: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value> {
|
||||
use super::protocol::AudioSourceResponse;
|
||||
|
||||
let payload = payload.ok_or_else(|| {
|
||||
crate::error::IpcError::InvalidCommand("Missing audio source payload".to_string())
|
||||
})?;
|
||||
|
||||
let source: crate::config::AudioSourceConfig = serde_json::from_value(payload)?;
|
||||
|
||||
info!("Updating audio source: {} ({})", source.name, source.id);
|
||||
|
||||
{
|
||||
let mut settings = self.settings.write();
|
||||
if let Some(existing) = settings
|
||||
.audio
|
||||
.capture_apps
|
||||
.iter_mut()
|
||||
.find(|s| s.id == source.id)
|
||||
{
|
||||
*existing = source.clone();
|
||||
crate::config::save_config(&settings)?;
|
||||
} else {
|
||||
return Err(crate::error::IpcError::InvalidCommand(format!(
|
||||
"Audio source not found: {}",
|
||||
source.id
|
||||
))
|
||||
.into());
|
||||
}
|
||||
}
|
||||
|
||||
let response = AudioSourceResponse { source };
|
||||
Ok(serde_json::to_value(response)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Enumerate audio devices on Windows using WASAPI.
|
||||
///
|
||||
/// This runs in a `catch_unwind` so any panic in the unsafe Windows API calls
|
||||
/// is contained and cannot crash the daemon process.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn enumerate_windows_audio_devices(
|
||||
) -> Result<(Vec<super::protocol::AudioDeviceInfo>, Vec<super::protocol::AudioDeviceInfo>)> {
|
||||
use super::protocol::AudioDeviceInfo;
|
||||
use tracing::{error, warn};
|
||||
|
||||
// Default fallback devices
|
||||
let fallback = || {
|
||||
(
|
||||
vec![AudioDeviceInfo {
|
||||
id: "default".to_string(),
|
||||
name: "Default Microphone".to_string(),
|
||||
is_default: true,
|
||||
}],
|
||||
vec![AudioDeviceInfo {
|
||||
id: "default".to_string(),
|
||||
name: "Default Speakers".to_string(),
|
||||
is_default: true,
|
||||
}],
|
||||
)
|
||||
};
|
||||
|
||||
// Run the actual enumeration inside catch_unwind so a panic can't crash the daemon.
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
enumerate_windows_audio_devices_inner()
|
||||
}));
|
||||
|
||||
match result {
|
||||
Ok(Ok(devices)) => Ok(devices),
|
||||
Ok(Err(e)) => {
|
||||
warn!("WASAPI device enumeration failed, returning defaults: {}", e);
|
||||
Ok(fallback())
|
||||
}
|
||||
Err(panic_info) => {
|
||||
error!("PANIC during WASAPI device enumeration: {:?}", panic_info);
|
||||
Ok(fallback())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Inner implementation of Windows audio device enumeration using WASAPI.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn enumerate_windows_audio_devices_inner(
|
||||
) -> std::result::Result<
|
||||
(Vec<super::protocol::AudioDeviceInfo>, Vec<super::protocol::AudioDeviceInfo>),
|
||||
String,
|
||||
> {
|
||||
use super::protocol::AudioDeviceInfo;
|
||||
use windows::Win32::Media::Audio::*;
|
||||
use windows::Win32::System::Com::*;
|
||||
use windows::core::PWSTR;
|
||||
use tracing::{info, warn};
|
||||
|
||||
fn pwstr_to_string(p: PWSTR) -> String {
|
||||
if p.is_null() {
|
||||
return String::new();
|
||||
}
|
||||
unsafe {
|
||||
let mut len = 0usize;
|
||||
while *p.0.add(len) != 0 {
|
||||
len += 1;
|
||||
}
|
||||
if len > 0 {
|
||||
let wide = std::slice::from_raw_parts(p.0, len);
|
||||
String::from_utf16_lossy(wide)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut input_devices = Vec::new();
|
||||
let mut output_devices = Vec::new();
|
||||
|
||||
info!("[AUDIO_ENUM] inner: starting WASAPI enumeration on this thread (id={:?})", std::thread::current().id());
|
||||
|
||||
let com_initialized;
|
||||
unsafe {
|
||||
// Initialize COM for this dedicated enumeration thread.
|
||||
//
|
||||
// This code runs on a short-lived dedicated OS thread spawned just for
|
||||
// this enumeration, so it is safe to call both `CoInitializeEx` and
|
||||
// `CoUninitialize` here: the thread is not shared with libobs or any
|
||||
// tokio async/blocking-pool work, and it dies as soon as enumeration
|
||||
// completes. Calling `CoUninitialize` at the end properly tears down the
|
||||
// COM apartment and avoids leaking resources.
|
||||
let hr = CoInitializeEx(None, COINIT_MULTITHREADED);
|
||||
com_initialized = hr.is_ok();
|
||||
if !com_initialized {
|
||||
// RPC_E_CHANGED_MODE would indicate the thread already had COM init in
|
||||
// a conflicting apartment — this should never happen on a fresh thread,
|
||||
// but log it loudly so we can diagnose if it ever does.
|
||||
warn!("[AUDIO_ENUM] inner: CoInitializeEx failed: HRESULT=0x{:08X}", hr.0);
|
||||
} else {
|
||||
info!("[AUDIO_ENUM] inner: CoInitializeEx(MTA) succeeded");
|
||||
}
|
||||
|
||||
// Create device enumerator
|
||||
let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)
|
||||
.map_err(|e| format!("Failed to create MMDeviceEnumerator: {:?}", e))?;
|
||||
|
||||
// Get default input device ID for comparison
|
||||
let default_input_id: Option<String> = enumerator
|
||||
.GetDefaultAudioEndpoint(eCapture, eCommunications)
|
||||
.ok()
|
||||
.and_then(|dev| dev.GetId().ok())
|
||||
.map(pwstr_to_string);
|
||||
|
||||
// Get default output device ID for comparison
|
||||
let default_output_id: Option<String> = enumerator
|
||||
.GetDefaultAudioEndpoint(eRender, eCommunications)
|
||||
.ok()
|
||||
.and_then(|dev| dev.GetId().ok())
|
||||
.map(pwstr_to_string);
|
||||
|
||||
// Enumerate capture (input) devices
|
||||
if let Ok(capture_collection) = enumerator.EnumAudioEndpoints(eCapture, DEVICE_STATE_ACTIVE) {
|
||||
if let Ok(count) = capture_collection.GetCount() {
|
||||
for i in 0..count {
|
||||
if let Ok(device) = capture_collection.Item(i) {
|
||||
let id_str: Option<String> = device.GetId().ok().map(pwstr_to_string);
|
||||
let id = id_str.clone().unwrap_or_else(|| format!("input_{}", i));
|
||||
|
||||
let is_default = id_str
|
||||
.as_ref()
|
||||
.map(|s| default_input_id.as_ref().map(|d| s == d).unwrap_or(false))
|
||||
.unwrap_or(false);
|
||||
|
||||
let name = get_device_friendly_name(&device)
|
||||
.unwrap_or_else(|| format!("Input Device {}", i + 1));
|
||||
|
||||
debug!("Found input device: {} (id: {}, default: {})", name, id, is_default);
|
||||
input_devices.push(AudioDeviceInfo { id, name, is_default });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Enumerate render (output) devices
|
||||
if let Ok(render_collection) = enumerator.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE) {
|
||||
if let Ok(count) = render_collection.GetCount() {
|
||||
for i in 0..count {
|
||||
if let Ok(device) = render_collection.Item(i) {
|
||||
let id_str: Option<String> = device.GetId().ok().map(pwstr_to_string);
|
||||
let id = id_str.clone().unwrap_or_else(|| format!("output_{}", i));
|
||||
|
||||
let is_default = id_str
|
||||
.as_ref()
|
||||
.map(|s| default_output_id.as_ref().map(|d| s == d).unwrap_or(false))
|
||||
.unwrap_or(false);
|
||||
|
||||
let name = get_device_friendly_name(&device)
|
||||
.unwrap_or_else(|| format!("Output Device {}", i + 1));
|
||||
|
||||
debug!("Found output device: {} (id: {}, default: {})", name, id, is_default);
|
||||
output_devices.push(AudioDeviceInfo { id, name, is_default });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tear down COM on this dedicated thread before returning. Safe here
|
||||
// because nothing else on this thread uses COM afterwards and the
|
||||
// thread is about to exit.
|
||||
if com_initialized {
|
||||
CoUninitialize();
|
||||
}
|
||||
}
|
||||
|
||||
// If no devices found, add defaults
|
||||
if input_devices.is_empty() {
|
||||
input_devices.push(AudioDeviceInfo {
|
||||
id: "default".to_string(),
|
||||
name: "Default Microphone".to_string(),
|
||||
is_default: true,
|
||||
});
|
||||
}
|
||||
|
||||
if output_devices.is_empty() {
|
||||
output_devices.push(AudioDeviceInfo {
|
||||
id: "default".to_string(),
|
||||
name: "Default Speakers".to_string(),
|
||||
is_default: true,
|
||||
});
|
||||
}
|
||||
|
||||
Ok((input_devices, output_devices))
|
||||
}
|
||||
|
||||
/// Get the friendly name of an audio device.
|
||||
///
|
||||
/// Opens the device property store and reads `PKEY_Device_FriendlyName`.
|
||||
/// This function never panics — it returns `None` on any failure.
|
||||
///
|
||||
/// We deliberately use the safe `to_string()` impl provided by the `windows` crate
|
||||
/// for `PROPVARIANT` instead of manually poking at the union's raw bytes. Manual
|
||||
/// offset-based reads assume a specific memory layout that does not match the
|
||||
/// crate's wrapper on every platform, and that caused native segfaults that
|
||||
/// `catch_unwind` cannot trap.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn get_device_friendly_name(device: &windows::Win32::Media::Audio::IMMDevice) -> Option<String> {
|
||||
use windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore;
|
||||
use windows::Win32::System::Com::STGM;
|
||||
use windows::Win32::UI::Shell::PropertiesSystem::PROPERTYKEY;
|
||||
|
||||
// PKEY_Device_FriendlyName = { a45c254e-df1c-4efd-8020-67d146850500 }, 14
|
||||
const FRIENDLY_NAME_KEY: PROPERTYKEY = PROPERTYKEY {
|
||||
fmtid: windows::core::GUID::from_u128(0xa45c254e_df1c_4efd_8020_67d146850500),
|
||||
pid: 14,
|
||||
};
|
||||
|
||||
// Wrap in catch_unwind to be absolutely safe.
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe {
|
||||
// Open the property store read-only.
|
||||
let store: IPropertyStore = device.OpenPropertyStore(STGM(0)).ok()?;
|
||||
// Read the friendly-name property.
|
||||
let prop = store.GetValue(&FRIENDLY_NAME_KEY as *const PROPERTYKEY).ok()?;
|
||||
|
||||
// The `windows` crate's `PROPVARIANT` implements `Display` via `to_string()`,
|
||||
// which safely inspects the variant type and converts the value. For
|
||||
// `VT_LPWSTR` this returns the contained wide string. We avoid any manual
|
||||
// union/pointer access here — that was the source of the native crash.
|
||||
let name = prop.to_string();
|
||||
let trimmed = name.trim();
|
||||
if trimmed.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(trimmed.to_string())
|
||||
}
|
||||
}));
|
||||
|
||||
result.ok().flatten()
|
||||
}
|
||||
|
||||
/// Enumerate audio devices on Linux using PulseAudio.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn enumerate_linux_audio_devices(
|
||||
) -> Result<(Vec<super::protocol::AudioDeviceInfo>, Vec<super::protocol::AudioDeviceInfo>)> {
|
||||
use super::protocol::AudioDeviceInfo;
|
||||
use tracing::warn;
|
||||
|
||||
let mut input_devices = Vec::new();
|
||||
let mut output_devices = Vec::new();
|
||||
|
||||
// Provide default devices
|
||||
input_devices.push(AudioDeviceInfo {
|
||||
id: "default".to_string(),
|
||||
name: "Default Microphone".to_string(),
|
||||
is_default: true,
|
||||
});
|
||||
|
||||
output_devices.push(AudioDeviceInfo {
|
||||
id: "default".to_string(),
|
||||
name: "Default Speakers".to_string(),
|
||||
is_default: true,
|
||||
});
|
||||
|
||||
// TODO: Enumerate actual PulseAudio devices using libpulse-binding
|
||||
warn!("Full PulseAudio device enumeration not yet implemented, returning default devices only");
|
||||
|
||||
Ok((input_devices, output_devices))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::config::Settings;
|
||||
use crate::config::{Settings};
|
||||
use crate::recording::RecordingResult;
|
||||
use crate::state::DaemonStatus;
|
||||
use crate::timeline::RecordingMetadata;
|
||||
@@ -55,6 +55,14 @@ pub enum IpcCommand {
|
||||
GetStatus,
|
||||
/// Get available encoders.
|
||||
GetEncoders,
|
||||
/// Get available audio devices.
|
||||
GetAudioDevices,
|
||||
/// Add an audio source to settings.
|
||||
AddAudioSource,
|
||||
/// Remove an audio source from settings.
|
||||
RemoveAudioSource { id: String },
|
||||
/// Update an audio source in settings.
|
||||
UpdateAudioSource,
|
||||
|
||||
// Recording commands
|
||||
/// Start recording manually.
|
||||
@@ -208,6 +216,33 @@ pub struct EncoderInfo {
|
||||
pub available: bool,
|
||||
}
|
||||
|
||||
/// Response for GetAudioDevices command.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct GetAudioDevicesResponse {
|
||||
/// Available input devices (microphones).
|
||||
pub input_devices: Vec<AudioDeviceInfo>,
|
||||
/// Available output devices (speakers, headphones).
|
||||
pub output_devices: Vec<AudioDeviceInfo>,
|
||||
}
|
||||
|
||||
/// Information about an audio device.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AudioDeviceInfo {
|
||||
/// Device ID (used for device selection).
|
||||
pub id: String,
|
||||
/// Display name of the device.
|
||||
pub name: String,
|
||||
/// Whether this is the default device for its type.
|
||||
pub is_default: bool,
|
||||
}
|
||||
|
||||
/// Response for audio source operations.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AudioSourceResponse {
|
||||
/// The created or updated audio source.
|
||||
pub source: crate::config::AudioSourceConfig,
|
||||
}
|
||||
|
||||
impl IpcMessage {
|
||||
/// Create a new request message.
|
||||
pub fn request(command: IpcCommand, payload: Option<serde_json::Value>) -> Self {
|
||||
|
||||
@@ -12,6 +12,29 @@ use super::handlers::IpcHandlers;
|
||||
use super::protocol::{IpcMessage, IpcNotification, IpcResponse, MessageType};
|
||||
use crate::error::{IpcError, Result};
|
||||
|
||||
/// Write an *unbuffered* marker file that survives native crashes/segfaults.
|
||||
/// See [`super::handlers`] for the rationale: the tracing log appender buffers
|
||||
/// writes in memory, so logs emitted microseconds before a native segfault are
|
||||
/// lost on disk. This helper fsyncs so the bytes hit disk before returning.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn write_ipc_crash_marker(stage: &str) {
|
||||
use std::io::Write;
|
||||
let dir = std::env::temp_dir().join("record-daemon-crash-markers");
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let path = dir.join(format!(
|
||||
"{}_{}.txt",
|
||||
stage,
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0)
|
||||
));
|
||||
if let Ok(mut f) = std::fs::File::create(&path) {
|
||||
let _ = writeln!(f, "{} @ {:?}", stage, std::thread::current().id());
|
||||
let _ = f.sync_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// IPC server configuration.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct IpcServerConfig {
|
||||
@@ -466,11 +489,16 @@ impl IpcServer {
|
||||
}
|
||||
};
|
||||
|
||||
trace!("Received: {}", line);
|
||||
info!("[IPC] Received message ({} bytes)", line.len());
|
||||
#[cfg(target_os = "windows")]
|
||||
write_ipc_crash_marker("ipc_read_done");
|
||||
|
||||
// Parse message
|
||||
let message = match IpcMessage::from_json(&line) {
|
||||
Ok(msg) => msg,
|
||||
Ok(msg) => {
|
||||
info!("[IPC] Parsed message type={:?} command={:?}", msg.message_type, msg.command);
|
||||
msg
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Failed to parse message: {}", e);
|
||||
let response =
|
||||
@@ -486,10 +514,21 @@ impl IpcServer {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
#[cfg(target_os = "windows")]
|
||||
write_ipc_crash_marker(&format!("ipc_parsed_{:?}", message.command));
|
||||
|
||||
// Handle message
|
||||
let response = match message.message_type {
|
||||
MessageType::Request => handlers.handle(message).await,
|
||||
MessageType::Request => {
|
||||
#[cfg(target_os = "windows")]
|
||||
let cmd_dbg = format!("{:?}", message.command);
|
||||
#[cfg(target_os = "windows")]
|
||||
write_ipc_crash_marker(&format!("ipc_dispatch_pre_{}", cmd_dbg));
|
||||
let r = handlers.handle(message).await;
|
||||
#[cfg(target_os = "windows")]
|
||||
write_ipc_crash_marker(&format!("ipc_dispatch_post_{}", cmd_dbg));
|
||||
r
|
||||
}
|
||||
MessageType::Notification => {
|
||||
// Notifications don't get responses
|
||||
trace!("Received notification: {:?}", message);
|
||||
@@ -512,6 +551,8 @@ impl IpcServer {
|
||||
.write_all(b"\n")
|
||||
.await
|
||||
.map_err(IpcError::WriteError)?;
|
||||
#[cfg(target_os = "windows")]
|
||||
write_ipc_crash_marker("ipc_response_sent");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
Reference in new issue
Block a user