Add debug logs to download handler for production troubleshooting

This commit is contained in:
Warren
2026-09-21 14:06:33 +08:00
parent 864379af40
commit cb9810490a
21 changed files with 5430 additions and 0 deletions
+79
View File
@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>com.accusys.markbasefs</string>
<key>CFBundleName</key>
<string>MarkBaseFS</string>
<key>CFBundleVersion</key>
<string>1.0.0</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleExecutable</key>
<string>markbasefs</string>
<!-- FSKit Configuration -->
<key>FSKitSupportedSchemes</key>
<array>
<string>markbasefs</string>
</array>
<key>FSKitShortName</key>
<string>markbasefs</string>
<!-- Mount Options -->
<key>FSKitPersonalities</key>
<dict>
<key>MarkBaseFS</key>
<dict>
<key>FSKitMountOptions</key>
<array>
<string>user</string>
<string>db</string>
</array>
<key>FSKitDisplayName</key>
<string>MarkBase File System</string>
<key>FSKitDescription</key>
<string>MarkBase virtual file system with VFS backend support</string>
</dict>
</dict>
<!-- Supported Media Types -->
<key>FSKitMediaTypes</key>
<dict>
<key>com.accusys.markbasefs.database</key>
<dict>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>com.accusys.markbasefs.database</string>
</array>
</dict>
</dict>
<!-- URL Types -->
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.accusys.markbasefs</string>
<key>CFBundleURLSchemes</key>
<array>
<string>markbasefs</string>
</array>
</dict>
</array>
<!-- System Requirements -->
<key>LSMinimumSystemVersion</key>
<string>15.4</string>
<!-- Security -->
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 AccuSys. All rights reserved.</string>
</dict>
</plist>
+136
View File
@@ -0,0 +1,136 @@
use crate::fskit::volume::MarkBaseFSItem;
use block2::DynBlock;
use markbase_core::vfs::{open_flags::OpenFlags, VfsBackend, VfsDirEntry, VfsError, VfsStat};
use objc2::rc::Retained;
use objc2_foundation::{NSError, NSString};
use objc2_fs_kit::{
FSDeactivateOptions, FSDirectoryCookie, FSDirectoryEntryPacker, FSDirectoryVerifier,
FSFileName, FSItem, FSItemAttributes, FSItemGetAttributesRequest, FSItemID,
FSItemSetAttributesRequest, FSItemType, FSMutableFileDataBuffer, FSTaskOptions, FSVolume,
FSVolumeSupportedCapabilities,
};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::ptr::null_mut;
use std::sync::{Arc, Mutex};
pub struct VfsAdapter {
backend: Arc<Box<dyn VfsBackend>>,
user_id: String,
root_id: String,
item_map: Mutex<HashMap<u64, String>>,
path_cache: Mutex<HashMap<String, PathBuf>>,
}
impl VfsAdapter {
pub fn new(backend: Box<dyn VfsBackend>, user_id: String, root_id: String) -> Self {
Self {
backend: Arc::new(backend),
user_id,
root_id,
item_map: Mutex::new(HashMap::new()),
path_cache: Mutex::new(HashMap::new()),
}
}
pub fn get_backend(&self) -> Arc<Box<dyn VfsBackend>> {
self.backend.clone()
}
pub fn get_user_id(&self) -> &str {
&self.user_id
}
pub fn get_root_id(&self) -> &str {
&self.root_id
}
pub fn register_item(&self, item_id: u64, node_id: String) {
self.item_map.lock().unwrap().insert(item_id, node_id);
}
pub fn unregister_item(&self, item_id: u64) {
self.item_map.lock().unwrap().remove(&item_id);
}
pub fn get_node_id(&self, item_id: u64) -> Option<String> {
self.item_map.lock().unwrap().get(&item_id).cloned()
}
pub fn cache_path(&self, node_id: String, path: PathBuf) {
self.path_cache.lock().unwrap().insert(node_id, path);
}
pub fn get_cached_path(&self, node_id: &str) -> Option<PathBuf> {
self.path_cache.lock().unwrap().get(node_id).cloned()
}
pub fn vfs_error_to_nserror(error: VfsError, code: i64) -> *mut NSError {
let msg = format!("{}", error);
let domain = NSString::from_str("com.accusys.markbase.fskit");
let nserror = unsafe {
NSError::errorWithDomain_code_userInfo(
&domain,
code as isize,
None,
)
};
Retained::into_raw(nserror)
}
pub fn stat_to_attributes(stat: &VfsStat) -> Retained<FSItemAttributes> {
let attrs = unsafe { FSItemAttributes::new() };
unsafe {
let item_type = if stat.is_symlink {
FSItemType::Symlink
} else if stat.is_dir {
FSItemType::Directory
} else {
FSItemType::File
};
attrs.setType(item_type);
attrs.setSize(stat.size);
}
attrs
}
pub fn read_dir_to_entries(entries: Vec<VfsDirEntry>) -> Vec<(String, Retained<FSItemAttributes>, bool)> {
entries
.into_iter()
.map(|entry| {
let attrs = Self::stat_to_attributes(&entry.stat);
(entry.name, attrs, entry.stat.is_dir)
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use markbase_core::vfs::local_fs::LocalFs;
#[test]
fn test_vfs_adapter_creation() {
let backend = Box::new(LocalFs::new());
let adapter = VfsAdapter::new(backend, "test_user".to_string(), "root".to_string());
assert_eq!(adapter.get_user_id(), "test_user");
assert_eq!(adapter.get_root_id(), "root");
}
#[test]
fn test_item_registration() {
let backend = Box::new(LocalFs::new());
let adapter = VfsAdapter::new(backend, "test".to_string(), "root".to_string());
adapter.register_item(1, "node_1".to_string());
assert_eq!(adapter.get_node_id(1), Some("node_1".to_string()));
adapter.unregister_item(1);
assert_eq!(adapter.get_node_id(1), None);
}
}
+239
View File
@@ -0,0 +1,239 @@
use crate::fskit::vfs_adapter::VfsAdapter;
use crate::fskit::volume::MarkBaseFSItem;
use block2::DynBlock;
use markbase_core::vfs::local_fs::LocalFs;
use objc2::rc::Retained;
use objc2::{define_class, AnyThread, DefinedClass};
use objc2_foundation::{NSError, NSInteger, NSObjectProtocol, NSString};
use objc2_fs_kit::{
FSDeactivateOptions, FSDirectoryCookie, FSDirectoryEntryPacker, FSDirectoryVerifier,
FSFileName, FSItem, FSItemAttributes, FSItemGetAttributesRequest, FSItemID,
FSItemSetAttributesRequest, FSItemType, FSMutableFileDataBuffer, FSStatFSResult, FSSyncFlags,
FSTaskOptions, FSVolume, FSVolumeSupportedCapabilities,
};
use rusqlite::Connection;
use std::collections::HashMap;
use std::path::PathBuf;
use std::ptr::null_mut;
use std::sync::{Arc, Mutex};
pub struct MarkBaseVolumeVfsIvars {
vfs: Arc<VfsAdapter>,
user_id: String,
root_id: String,
item_map: Mutex<HashMap<u64, String>>,
node_to_path: Mutex<HashMap<String, PathBuf>>,
}
define_class!(
#[unsafe(super(FSVolume))]
#[thread_kind = AnyThread]
#[ivars = MarkBaseVolumeVfsIvars]
#[name = "MarkBaseVolumeVfs"]
pub struct MarkBaseVolumeVfs;
unsafe impl NSObjectProtocol for MarkBaseVolumeVfs {}
impl MarkBaseVolumeVfs {
#[unsafe(method(maximumLinkCount))]
fn maximum_link_count(&self) -> NSInteger {
1
}
#[unsafe(method(maximumNameLength))]
fn maximum_name_length(&self) -> NSInteger {
255
}
#[unsafe(method(restrictsOwnershipChanges))]
fn restricts_ownership_changes(&self) -> bool {
false
}
#[unsafe(method(truncatesLongNames))]
fn truncates_long_names(&self) -> bool {
false
}
#[unsafe(method(maximumXattrSize))]
fn maximum_xattr_size(&self) -> NSInteger {
4096
}
#[unsafe(method(maximumXattrSizeInBits))]
fn maximum_xattr_size_in_bits(&self) -> NSInteger {
12
}
#[unsafe(method(maximumFileSize))]
fn maximum_file_size(&self) -> u64 {
u64::MAX
}
#[unsafe(method(maximumFileSizeInBits))]
fn maximum_file_size_in_bits(&self) -> NSInteger {
64
}
#[unsafe(method_id(supportedVolumeCapabilities))]
fn supported_volume_capabilities(&self) -> Retained<FSVolumeSupportedCapabilities> {
let caps = unsafe {
FSVolumeSupportedCapabilities::init(FSVolumeSupportedCapabilities::alloc())
};
unsafe {
caps.setSupportsPersistentObjectIDs(true);
caps.setSupports64BitObjectIDs(true);
}
caps
}
#[unsafe(method_id(volumeStatistics))]
fn volume_statistics(&self) -> Retained<FSStatFSResult> {
let result = unsafe { FSStatFSResult::new() };
let ivars = self.ivars();
let vfs = ivars.vfs.get_backend();
if let Ok(root_path) = Self::get_root_path(&ivars) {
if let Ok(stat) = vfs.stat(&root_path) {
unsafe {
result.setTotalBytes(stat.size);
result.setAvailableBytes(stat.size);
}
}
}
unsafe { result.setBlockSize(4096) };
result
}
#[unsafe(method(unmountWithReplyHandler:))]
fn unmount_with_reply_handler(&self, reply: &DynBlock<dyn Fn()>) {
reply.call(());
}
#[unsafe(method(synchronizeWithFlags:replyHandler:))]
fn synchronize_with_flags_reply_handler(
&self,
_flags: FSSyncFlags,
reply: &DynBlock<dyn Fn(*mut NSError)>,
) {
reply.call((null_mut(),));
}
#[unsafe(method(activateWithOptions:replyHandler:))]
fn activate_with_options_reply_handler(
&self,
_options: &FSTaskOptions,
reply: &DynBlock<dyn Fn(*mut FSItem, *mut NSError)>,
) {
let ivars = self.ivars();
let root_id = &ivars.root_id;
let root_item_id = Self::node_id_to_item_id(root_id);
ivars.item_map.lock().unwrap().insert(root_item_id.0, root_id.clone());
let root_item = MarkBaseFSItem::new(root_id.clone(), root_item_id.0);
let root_ptr = Retained::into_raw(root_item) as *mut FSItem;
reply.call((root_ptr, null_mut()));
}
#[unsafe(method(deactivateWithOptions:replyHandler:))]
fn deactivate_with_options_reply_handler(
&self,
_options: FSDeactivateOptions,
reply: &DynBlock<dyn Fn(*mut NSError)>,
) {
reply.call((null_mut(),));
}
}
);
impl MarkBaseVolumeVfs {
pub fn new(conn: Connection, user_id: String, root_path: PathBuf) -> Retained<Self> {
let root_id = Self::find_root_node(&conn);
let backend = Box::new(LocalFs::new());
let vfs = VfsAdapter::new(backend, user_id.clone(), root_id.clone());
let mut node_to_path = HashMap::new();
node_to_path.insert(root_id.clone(), root_path);
let ivars = MarkBaseVolumeVfsIvars {
vfs: Arc::new(vfs),
user_id,
root_id,
item_map: Mutex::new(HashMap::new()),
node_to_path: Mutex::new(node_to_path),
};
let this = Self::alloc().set_ivars(ivars);
unsafe { objc2::msg_send![super(this), init] }
}
fn find_root_node(conn: &Connection) -> String {
conn.query_row(
"SELECT node_id FROM file_nodes WHERE parent_id IS NULL LIMIT 1",
[],
|row| row.get::<_, String>(0),
)
.unwrap_or_else(|_| "root".to_string())
}
fn node_id_to_item_id(node_id: &str) -> FSItemID {
let bytes = if node_id.len() >= 16 {
&node_id[0..16]
} else {
node_id
};
let hex_bytes = bytes.as_bytes();
let mut result: u64 = 0;
for i in 0..8 {
if i < hex_bytes.len() {
result |= (hex_bytes[i] as u64) << (i * 8);
}
}
FSItemID(result)
}
fn get_root_path(ivars: &MarkBaseVolumeVfsIvars) -> Result<PathBuf, String> {
ivars.node_to_path
.lock()
.unwrap()
.get(&ivars.root_id)
.cloned()
.ok_or_else(|| "Root path not found".to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use rusqlite::Connection;
#[test]
fn test_volume_vfs_creation() {
let conn = Connection::open_in_memory().unwrap();
conn.execute(
"CREATE TABLE file_nodes (
node_id TEXT PRIMARY KEY,
label TEXT,
node_type TEXT,
parent_id TEXT,
aliases_json TEXT DEFAULT '{}',
file_size INTEGER
)",
[],
).unwrap();
conn.execute(
"INSERT INTO file_nodes (node_id, label, node_type, parent_id)
VALUES ('root', 'Root', 'folder', NULL)",
[],
).unwrap();
let volume = MarkBaseVolumeVfs::new(conn, "test_user".to_string(), PathBuf::from("/tmp"));
assert_eq!(volume.ivars().user_id, "test_user");
}
}