架构设计 #

一、整体架构 #

1.1 架构概览 #

text
┌─────────────────────────────────────────────────────────────────┐
│                        Tauri 应用架构                            │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                     前端层 (Frontend)                    │   │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │   │
│  │  │   React     │  │    Vue      │  │   Svelte    │     │   │
│  │  │   Vue       │  │   Solid     │  │   Vanilla   │     │   │
│  │  └─────────────┘  └─────────────┘  └─────────────┘     │   │
│  │                      │                                   │   │
│  │                      ▼                                   │   │
│  │  ┌─────────────────────────────────────────────────┐   │   │
│  │  │              @tauri-apps/api                     │   │   │
│  │  │         (JavaScript/TypeScript API)             │   │   │
│  │  └─────────────────────────────────────────────────┘   │   │
│  └─────────────────────────────────────────────────────────┘   │
│                              │                                  │
│                              │ IPC (JSON-RPC)                   │
│                              ▼                                  │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                    核心层 (Core)                         │   │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │   │
│  │  │   命令系统   │  │   事件系统   │  │   窗口管理   │     │   │
│  │  └─────────────┘  └─────────────┘  └─────────────┘     │   │
│  │                      │                                   │   │
│  │                      ▼                                   │   │
│  │  ┌─────────────────────────────────────────────────┐   │   │
│  │  │              Tauri Core (Rust)                   │   │   │
│  │  └─────────────────────────────────────────────────┘   │   │
│  └─────────────────────────────────────────────────────────┘   │
│                              │                                  │
│                              ▼                                  │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                    平台层 (Platform)                     │   │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │   │
│  │  │  Windows    │  │   macOS     │  │   Linux     │     │   │
│  │  │  WebView2   │  │  WKWebView  │  │ WebKitGTK   │     │   │
│  │  └─────────────┘  └─────────────┘  └─────────────┘     │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

1.2 核心组件 #

组件 说明
前端层 Web 技术,运行在 WebView 中
核心层 Rust 实现,处理业务逻辑
平台层 系统原生 API 和 WebView
IPC 前后端通信桥梁

二、进程模型 #

2.1 单进程模型 #

Tauri 采用单进程模型,与 Electron 的多进程模型不同:

text
Electron 多进程模型
┌─────────────────┐
│   主进程        │ ← Node.js 环境
├─────────────────┤
│ 渲染进程 1      │ ← Chromium
│ 渲染进程 2      │ ← Chromium
│ 渲染进程 3      │ ← Chromium
└─────────────────┘

Tauri 单进程模型
┌─────────────────┐
│   主进程        │ ← Rust 环境
│   WebView      │ ← 系统 WebView
└─────────────────┘

2.2 进程结构 #

text
Tauri 进程结构
├── 主线程
│   ├── 事件循环
│   ├── 窗口管理
│   └── 命令处理
│
├── WebView 线程
│   ├── JavaScript 执行
│   ├── DOM 渲染
│   └── CSS 样式
│
└── 后台线程(可选)
    ├── 异步任务
    └── 文件 I/O

2.3 内存模型 #

rust
// Tauri 使用 Arc<Mutex> 进行线程间共享
use std::sync::{Arc, Mutex};

struct AppState {
    counter: Mutex<i32>,
}

#[tauri::command]
fn increment(state: tauri::State<AppState>) -> i32 {
    let mut counter = state.counter.lock().unwrap();
    *counter += 1;
    *counter
}

三、通信机制 #

3.1 IPC 通信 #

text
┌─────────────┐                    ┌─────────────┐
│  前端       │                    │  后端       │
│  (WebView)  │                    │  (Rust)     │
├─────────────┤                    ├─────────────┤
│             │    invoke()        │             │
│  JavaScript │ ─────────────────► │  Command    │
│             │                    │  Handler    │
│             │    JSON Response   │             │
│             │ ◄───────────────── │             │
└─────────────┘                    └─────────────┘

3.2 命令调用流程 #

text
1. 前端调用 invoke()
   │
   ▼
2. 序列化参数为 JSON
   │
   ▼
3. 通过 IPC 发送到 Rust
   │
   ▼
4. Rust 反序列化参数
   │
   ▼
5. 执行命令函数
   │
   ▼
6. 序列化返回值为 JSON
   │
   ▼
7. 通过 IPC 返回前端
   │
   ▼
8. 前端反序列化结果

3.3 通信示例 #

前端调用

typescript
import { invoke } from '@tauri-apps/api/core';

// 同步风格(实际是异步)
const result = await invoke<string>('greet', { name: 'World' });
console.log(result);

后端处理

rust
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

数据流向

text
前端: { name: "World" }
    ↓ JSON 序列化
IPC:  {"name":"World"}
    ↓ JSON 反序列化
后端: name = "World"
    ↓ 处理
后端: "Hello, World!"
    ↓ JSON 序列化
IPC:  "Hello, World!"
    ↓ JSON 反序列化
前端: "Hello, World!"

四、安全模型 #

4.1 安全架构 #

text
┌─────────────────────────────────────────────────────────────┐
│                     安全边界                                 │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │                    WebView                          │   │
│  │  ┌─────────────────────────────────────────────┐   │   │
│  │  │              沙箱环境                        │   │   │
│  │  │  - 无直接文件系统访问                        │   │   │
│  │  │  - 无直接系统 API 访问                       │   │   │
│  │  │  - 受 CSP 策略限制                          │   │   │
│  │  └─────────────────────────────────────────────┘   │   │
│  └─────────────────────────────────────────────────────┘   │
│                            │                                │
│                            │ IPC(受控通道)                 │
│                            ▼                                │
│  ┌─────────────────────────────────────────────────────┐   │
│  │                    Rust Core                        │   │
│  │  ┌─────────────────────────────────────────────┐   │   │
│  │  │              权限检查                        │   │   │
│  │  │  - 命令白名单                               │   │   │
│  │  │  - 权限验证                                 │   │   │
│  │  │  - 资源访问控制                             │   │   │
│  │  └─────────────────────────────────────────────┘   │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
└─────────────────────────────────────────────────────────────┘

4.2 权限系统 #

json
// capabilities/default.json
{
    "identifier": "default",
    "permissions": [
        "core:default",
        "shell:allow-open",
        "fs:allow-read-text-file"
    ]
}

4.3 安全特性 #

特性 说明
Context Isolation 上下文隔离,防止原型污染
CSP 内容安全策略,限制资源加载
权限控制 细粒度的 API 访问控制
命令白名单 只有注册的命令可被调用
沙箱执行 WebView 沙箱隔离

五、WebView 差异 #

5.1 各平台 WebView #

平台 WebView 特点
Windows WebView2 基于 Chromium,功能完整
macOS WKWebView 基于 WebKit,性能优秀
Linux WebKitGTK 基于 WebKit,需要安装

5.2 兼容性处理 #

typescript
// 检测平台
import { platform } from '@tauri-apps/plugin-os';

const currentPlatform = await platform();

// 根据平台适配
if (currentPlatform === 'windows') {
    // Windows 特定处理
} else if (currentPlatform === 'macos') {
    // macOS 特定处理
} else if (currentPlatform === 'linux') {
    // Linux 特定处理
}

5.3 功能降级 #

typescript
// 特性检测
async function checkFeature() {
    try {
        await invoke('test_feature');
        return true;
    } catch {
        return false;
    }
}

// 降级处理
const hasFeature = await checkFeature();
if (hasFeature) {
    // 使用新特性
} else {
    // 使用降级方案
}

六、性能优化 #

6.1 启动优化 #

rust
// 延迟加载非必要模块
pub fn run() {
    tauri::Builder::default()
        .setup(|app| {
            // 只在需要时加载
            let handle = app.handle().clone();
            std::thread::spawn(move || {
                // 后台初始化
            });
            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

6.2 内存优化 #

rust
// 使用 Arc 共享数据
use std::sync::Arc;

#[tauri::command]
fn process_data(data: Arc<Vec<u8>>) -> Result<String, String> {
    // 共享数据,避免复制
    Ok(String::from_utf8_lossy(&data).to_string())
}

6.3 IPC 优化 #

typescript
// 批量操作减少 IPC 调用
const files = ['file1.txt', 'file2.txt', 'file3.txt'];

// 不好的做法:多次调用
for (const file of files) {
    await invoke('read_file', { path: file });
}

// 好的做法:批量调用
const contents = await invoke('read_files', { paths: files });

七、插件系统 #

7.1 插件架构 #

text
Tauri 插件系统
├── Core Plugins
│   ├── shell      - Shell 命令
│   ├── fs         - 文件系统
│   ├── dialog     - 对话框
│   └── http       - HTTP 请求
│
├── Official Plugins
│   ├── store      - 持久化存储
│   ├── updater    - 自动更新
│   ├── notification - 通知
│   └── sql        - 数据库
│
└── Custom Plugins
    └── 用户自定义插件

7.2 插件使用 #

rust
// 注册插件
tauri::Builder::default()
    .plugin(tauri_plugin_shell::init())
    .plugin(tauri_plugin_fs::init())
    .plugin(tauri_plugin_dialog::init())
    .run(tauri::generate_context!())
    .expect("error while running tauri application");

八、生命周期 #

8.1 应用生命周期 #

text
启动流程
├── 1. 加载配置
├── 2. 初始化插件
├── 3. 创建窗口
├── 4. 加载前端资源
├── 5. 触发 setup 回调
└── 6. 进入事件循环

关闭流程
├── 1. 触发 close_requested
├── 2. 执行清理逻辑
├── 3. 关闭窗口
└── 4. 退出进程

8.2 生命周期钩子 #

rust
tauri::Builder::default()
    .setup(|app| {
        // 应用启动时执行
        println!("App is starting!");
        Ok(())
    })
    .on_window_event(|window, event| {
        // 窗口事件处理
        match event {
            tauri::WindowEvent::CloseRequested { .. } => {
                println!("Window close requested");
            }
            _ => {}
        }
    })
    .run(tauri::generate_context!())
    .expect("error while running tauri application");

九、调试支持 #

9.1 开发工具 #

rust
// 启用调试特性
#[cfg(debug_assertions)]
fn enable_debug_features() {
    println!("Debug mode enabled");
}

9.2 日志系统 #

rust
// 添加日志支持
use log::{info, debug, error};

#[tauri::command]
fn logged_operation() {
    info!("Operation started");
    debug!("Processing...");
    error!("Something went wrong");
}

十、总结 #

10.1 核心要点 #

要点 说明
单进程模型 相比 Electron 更轻量
IPC 通信 JSON-RPC 协议,安全可靠
安全模型 多层安全防护
插件系统 灵活扩展能力

10.2 下一步 #

现在你已经了解了 Tauri 的架构设计,接下来让我们学习 命令系统,深入掌握前后端通信机制!

最后更新:2026-03-28