diff --git a/CLAUDE.md b/CLAUDE.md index 23fe4a5..0c8f756 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -460,6 +460,7 @@ chore(docker): 添加 PostgreSQL 健康检查 | Phase 5 | 消息中心 (Message) | ✅ 完成 | | Phase 6 | 整合与打磨 | ✅ 完成 | | - | WASM 插件原型 (V1-V6) | ✅ 验证通过 | +| - | 插件系统集成到主服务 | ✅ 已集成 | ### 已实现模块 @@ -472,6 +473,7 @@ chore(docker): 添加 PostgreSQL 健康检查 | erp-workflow | 工作流引擎 (BPMN 解析/Token 驱动/任务分配) | ✅ 完成 | | erp-message | 消息中心 (CRUD/模板/订阅/通知面板) | ✅ 完成 | | erp-config | 系统配置 (字典/菜单/设置/编号规则/主题) | ✅ 完成 | +| erp-plugin | 插件管理 (WASM 运行时/生命周期/动态表/数据CRUD) | ✅ 已集成 | | erp-plugin-prototype | WASM 插件 Host 运行时 (Wasmtime + bindgen + Host API) | ✅ 原型验证 | | erp-plugin-test-sample | WASM 测试插件 (Guest trait + Host API 回调) | ✅ 原型验证 | diff --git a/Cargo.lock b/Cargo.lock index 31f2f87..a09fdec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -256,6 +256,7 @@ dependencies = [ "matchit", "memchr", "mime", + "multer", "percent-encoding", "pin-project-lite", "serde_core", @@ -985,6 +986,20 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "dashmap" +version = "6.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + [[package]] name = "debugid" version = "0.8.0" @@ -1189,6 +1204,7 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tracing", + "utoipa", "uuid", ] @@ -1212,6 +1228,29 @@ dependencies = [ "validator", ] +[[package]] +name = "erp-plugin" +version = "0.1.0" +dependencies = [ + "async-trait", + "axum", + "chrono", + "dashmap", + "erp-core", + "sea-orm", + "serde", + "serde_json", + "sha2", + "thiserror 2.0.18", + "tokio", + "toml 0.8.23", + "tracing", + "utoipa", + "uuid", + "wasmtime", + "wasmtime-wasi", +] + [[package]] name = "erp-plugin-prototype" version = "0.1.0" @@ -1246,6 +1285,7 @@ dependencies = [ "erp-config", "erp-core", "erp-message", + "erp-plugin", "erp-server-migration", "erp-workflow", "redis", @@ -2285,6 +2325,23 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + [[package]] name = "nix" version = "0.29.0" diff --git a/Cargo.toml b/Cargo.toml index e632cb4..e9cbe7b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ members = [ "crates/erp-server/migration", "crates/erp-plugin-prototype", "crates/erp-plugin-test-sample", + "crates/erp-plugin", ] [workspace.package] @@ -22,7 +23,7 @@ license = "MIT" tokio = { version = "1", features = ["full"] } # Web -axum = "0.8" +axum = { version = "0.8", features = ["multipart"] } tower = "0.5" tower-http = { version = "0.6", features = ["cors", "trace", "compression-gzip"] } @@ -80,3 +81,4 @@ erp-auth = { path = "crates/erp-auth" } erp-workflow = { path = "crates/erp-workflow" } erp-message = { path = "crates/erp-message" } erp-config = { path = "crates/erp-config" } +erp-plugin = { path = "crates/erp-plugin" } diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 0d07f8c..52520e0 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -14,6 +14,8 @@ const Organizations = lazy(() => import('./pages/Organizations')); const Workflow = lazy(() => import('./pages/Workflow')); const Messages = lazy(() => import('./pages/Messages')); const Settings = lazy(() => import('./pages/Settings')); +const PluginAdmin = lazy(() => import('./pages/PluginAdmin')); +const PluginCRUDPage = lazy(() => import('./pages/PluginCRUDPage')); function PrivateRoute({ children }: { children: React.ReactNode }) { const isAuthenticated = useAuthStore((s) => s.isAuthenticated); @@ -135,6 +137,8 @@ export default function App() { } /> } /> } /> + } /> + } /> diff --git a/apps/web/src/api/pluginData.ts b/apps/web/src/api/pluginData.ts new file mode 100644 index 0000000..4e629a8 --- /dev/null +++ b/apps/web/src/api/pluginData.ts @@ -0,0 +1,71 @@ +import client from './client'; + +export interface PluginDataRecord { + id: string; + data: Record; + created_at?: string; + updated_at?: string; + version?: number; +} + +interface PaginatedDataResponse { + data: PluginDataRecord[]; + total: number; + page: number; + page_size: number; + total_pages: number; +} + +export async function listPluginData( + pluginId: string, + entity: string, + page = 1, + pageSize = 20, +) { + const { data } = await client.get<{ success: boolean; data: PaginatedDataResponse }>( + `/plugins/${pluginId}/${entity}`, + { params: { page, page_size: pageSize } }, + ); + return data.data; +} + +export async function getPluginData(pluginId: string, entity: string, id: string) { + const { data } = await client.get<{ success: boolean; data: PluginDataRecord }>( + `/plugins/${pluginId}/${entity}/${id}`, + ); + return data.data; +} + +export async function createPluginData( + pluginId: string, + entity: string, + recordData: Record, +) { + const { data } = await client.post<{ success: boolean; data: PluginDataRecord }>( + `/plugins/${pluginId}/${entity}`, + { data: recordData }, + ); + return data.data; +} + +export async function updatePluginData( + pluginId: string, + entity: string, + id: string, + recordData: Record, + version: number, +) { + const { data } = await client.put<{ success: boolean; data: PluginDataRecord }>( + `/plugins/${pluginId}/${entity}/${id}`, + { data: recordData, version }, + ); + return data.data; +} + +export async function deletePluginData( + pluginId: string, + entity: string, + id: string, +) { + await client.delete(`/plugins/${pluginId}/${entity}/${id}`); +} diff --git a/apps/web/src/api/plugins.ts b/apps/web/src/api/plugins.ts new file mode 100644 index 0000000..bbceb47 --- /dev/null +++ b/apps/web/src/api/plugins.ts @@ -0,0 +1,121 @@ +import client from './client'; + +export interface PaginatedResponse { + data: T[]; + total: number; + page: number; + page_size: number; + total_pages: number; +} + +export interface PluginEntityInfo { + name: string; + display_name: string; + table_name: string; +} + +export interface PluginPermissionInfo { + code: string; + name: string; + description: string; +} + +export type PluginStatus = 'uploaded' | 'installed' | 'enabled' | 'running' | 'disabled' | 'uninstalled'; + +export interface PluginInfo { + id: string; + name: string; + version: string; + description?: string; + author?: string; + status: PluginStatus; + config: Record; + installed_at?: string; + enabled_at?: string; + entities: PluginEntityInfo[]; + permissions?: PluginPermissionInfo[]; + record_version: number; +} + +export async function listPlugins(page = 1, pageSize = 20, status?: string) { + const { data } = await client.get<{ success: boolean; data: PaginatedResponse }>( + '/admin/plugins', + { params: { page, page_size: pageSize, status: status || undefined } }, + ); + return data.data; +} + +export async function getPlugin(id: string) { + const { data } = await client.get<{ success: boolean; data: PluginInfo }>( + `/admin/plugins/${id}`, + ); + return data.data; +} + +export async function uploadPlugin(wasmFile: File, manifestToml: string) { + const formData = new FormData(); + formData.append('wasm', wasmFile); + formData.append('manifest', manifestToml); + + const { data } = await client.post<{ success: boolean; data: PluginInfo }>( + '/admin/plugins/upload', + formData, + { headers: { 'Content-Type': 'multipart/form-data' }, timeout: 60000 }, + ); + return data.data; +} + +export async function installPlugin(id: string) { + const { data } = await client.post<{ success: boolean; data: PluginInfo }>( + `/admin/plugins/${id}/install`, + ); + return data.data; +} + +export async function enablePlugin(id: string) { + const { data } = await client.post<{ success: boolean; data: PluginInfo }>( + `/admin/plugins/${id}/enable`, + ); + return data.data; +} + +export async function disablePlugin(id: string) { + const { data } = await client.post<{ success: boolean; data: PluginInfo }>( + `/admin/plugins/${id}/disable`, + ); + return data.data; +} + +export async function uninstallPlugin(id: string) { + const { data } = await client.post<{ success: boolean; data: PluginInfo }>( + `/admin/plugins/${id}/uninstall`, + ); + return data.data; +} + +export async function purgePlugin(id: string) { + await client.delete(`/admin/plugins/${id}`); +} + +export async function getPluginHealth(id: string) { + const { data } = await client.get<{ + success: boolean; + data: { plugin_id: string; status: string; details: Record }; + }>(`/admin/plugins/${id}/health`); + return data.data; +} + +export async function updatePluginConfig(id: string, config: Record, version: number) { + const { data } = await client.put<{ success: boolean; data: PluginInfo }>( + `/admin/plugins/${id}/config`, + { config, version }, + ); + return data.data; +} + +export async function getPluginSchema(id: string) { + const { data } = await client.get<{ success: boolean; data: Record }>( + `/admin/plugins/${id}/schema`, + ); + return data.data; +} diff --git a/apps/web/src/layouts/MainLayout.tsx b/apps/web/src/layouts/MainLayout.tsx index 9744e30..2382793 100644 --- a/apps/web/src/layouts/MainLayout.tsx +++ b/apps/web/src/layouts/MainLayout.tsx @@ -1,4 +1,4 @@ -import { useCallback, memo } from 'react'; +import { useCallback, memo, useEffect } from 'react'; import { Layout, Avatar, Space, Dropdown, Tooltip, theme } from 'antd'; import { HomeOutlined, @@ -14,10 +14,12 @@ import { SearchOutlined, BulbOutlined, BulbFilled, + AppstoreOutlined, } from '@ant-design/icons'; import { useNavigate, useLocation } from 'react-router-dom'; import { useAppStore } from '../stores/app'; import { useAuthStore } from '../stores/auth'; +import { usePluginStore } from '../stores/plugin'; import NotificationPanel from '../components/NotificationPanel'; const { Header, Sider, Content, Footer } = Layout; @@ -42,6 +44,7 @@ const bizMenuItems: MenuItem[] = [ const sysMenuItems: MenuItem[] = [ { key: '/settings', icon: , label: '系统设置' }, + { key: '/plugins/admin', icon: , label: '插件管理' }, ]; const routeTitleMap: Record = { @@ -52,6 +55,7 @@ const routeTitleMap: Record = { '/workflow': '工作流', '/messages': '消息中心', '/settings': '系统设置', + '/plugins/admin': '插件管理', }; // 侧边栏菜单项 - 提取为独立组件避免重复渲染 @@ -82,11 +86,17 @@ const SidebarMenuItem = memo(function SidebarMenuItem({ export default function MainLayout({ children }: { children: React.ReactNode }) { const { sidebarCollapsed, toggleSidebar, theme: themeMode, setTheme } = useAppStore(); const { user, logout } = useAuthStore(); + const { pluginMenuItems, fetchPlugins } = usePluginStore(); theme.useToken(); const navigate = useNavigate(); const location = useLocation(); const currentPath = location.pathname || '/'; + // 加载插件菜单 + useEffect(() => { + fetchPlugins(1, 'running'); + }, [fetchPlugins]); + const handleLogout = useCallback(async () => { await logout(); navigate('/login'); @@ -159,6 +169,28 @@ export default function MainLayout({ children }: { children: React.ReactNode }) ))} + {/* 菜单组:插件 */} + {pluginMenuItems.length > 0 && ( + <> + {!sidebarCollapsed && 插件} + + {pluginMenuItems.map((item) => ( + , + label: item.label, + }} + isActive={currentPath === item.key} + collapsed={sidebarCollapsed} + onClick={() => navigate(item.key)} + /> + ))} + + > + )} + {/* 菜单组:系统 */} {!sidebarCollapsed && 系统} @@ -187,7 +219,9 @@ export default function MainLayout({ children }: { children: React.ReactNode }) {sidebarCollapsed ? : } - {routeTitleMap[currentPath] || '页面'} + {routeTitleMap[currentPath] || + pluginMenuItems.find((p) => p.key === currentPath)?.label || + '页面'} diff --git a/apps/web/src/pages/PluginAdmin.tsx b/apps/web/src/pages/PluginAdmin.tsx new file mode 100644 index 0000000..0e5e4ff --- /dev/null +++ b/apps/web/src/pages/PluginAdmin.tsx @@ -0,0 +1,342 @@ +import { useEffect, useState, useCallback } from 'react'; +import { + Table, + Button, + Space, + Tag, + message, + Upload, + Modal, + Input, + Drawer, + Descriptions, + Popconfirm, + Form, + theme, +} from 'antd'; +import { + UploadOutlined, + PlayCircleOutlined, + PauseCircleOutlined, + CloudDownloadOutlined, + DeleteOutlined, + ReloadOutlined, + AppstoreOutlined, + HeartOutlined, +} from '@ant-design/icons'; +import type { PluginInfo, PluginStatus } from '../api/plugins'; +import { + listPlugins, + uploadPlugin, + installPlugin, + enablePlugin, + disablePlugin, + uninstallPlugin, + purgePlugin, + getPluginHealth, +} from '../api/plugins'; + +const STATUS_CONFIG: Record = { + uploaded: { color: '#64748B', label: '已上传' }, + installed: { color: '#2563EB', label: '已安装' }, + enabled: { color: '#059669', label: '已启用' }, + running: { color: '#059669', label: '运行中' }, + disabled: { color: '#DC2626', label: '已禁用' }, + uninstalled: { color: '#9333EA', label: '已卸载' }, +}; + +export default function PluginAdmin() { + const [plugins, setPlugins] = useState([]); + const [total, setTotal] = useState(0); + const [page, setPage] = useState(1); + const [loading, setLoading] = useState(false); + const [uploadModalOpen, setUploadModalOpen] = useState(false); + const [manifestText, setManifestText] = useState(''); + const [wasmFile, setWasmFile] = useState(null); + const [detailPlugin, setDetailPlugin] = useState(null); + const [healthDetail, setHealthDetail] = useState | null>(null); + const [actionLoading, setActionLoading] = useState(null); + const { token } = theme.useToken(); + + const fetchPlugins = useCallback(async (p = page) => { + setLoading(true); + try { + const result = await listPlugins(p); + setPlugins(result.data); + setTotal(result.total); + } catch { + message.error('加载插件列表失败'); + } + setLoading(false); + }, [page]); + + useEffect(() => { + fetchPlugins(); + }, [fetchPlugins]); + + const handleUpload = async () => { + if (!wasmFile || !manifestText.trim()) { + message.warning('请选择 WASM 文件并填写 Manifest'); + return; + } + try { + await uploadPlugin(wasmFile, manifestText); + message.success('插件上传成功'); + setUploadModalOpen(false); + setWasmFile(null); + setManifestText(''); + fetchPlugins(); + } catch { + message.error('插件上传失败'); + } + }; + + const handleAction = async (id: string, action: () => Promise, label: string) => { + setActionLoading(id); + try { + await action(); + message.success(`${label}成功`); + fetchPlugins(); + if (detailPlugin?.id === id) { + setDetailPlugin(null); + } + } catch { + message.error(`${label}失败`); + } + setActionLoading(null); + }; + + const handleHealthCheck = async (id: string) => { + try { + const result = await getPluginHealth(id); + setHealthDetail(result.details); + } catch { + message.error('健康检查失败'); + } + }; + + const getActions = (record: PluginInfo) => { + const id = record.id; + const btns: React.ReactNode[] = []; + + switch (record.status) { + case 'uploaded': + btns.push( + } + loading={actionLoading === id} + onClick={() => handleAction(id, () => installPlugin(id), '安装')} + > + 安装 + , + ); + break; + case 'installed': + btns.push( + } + loading={actionLoading === id} + onClick={() => handleAction(id, () => enablePlugin(id), '启用')} + > + 启用 + , + ); + break; + case 'enabled': + case 'running': + btns.push( + } + loading={actionLoading === id} + onClick={() => handleAction(id, () => disablePlugin(id), '停用')} + > + 停用 + , + ); + break; + case 'disabled': + btns.push( + } + loading={actionLoading === id} + onClick={() => handleAction(id, () => uninstallPlugin(id), '卸载')} + > + 卸载 + , + ); + break; + } + + return btns; + }; + + const columns = [ + { title: '名称', dataIndex: 'name', key: 'name', width: 180 }, + { title: '版本', dataIndex: 'version', key: 'version', width: 80 }, + { + title: '状态', + dataIndex: 'status', + key: 'status', + width: 100, + render: (status: PluginStatus) => { + const cfg = STATUS_CONFIG[status] || { color: '#64748B', label: status }; + return {cfg.label}; + }, + }, + { title: '作者', dataIndex: 'author', key: 'author', width: 120 }, + { + title: '描述', + dataIndex: 'description', + key: 'description', + ellipsis: true, + }, + { + title: '操作', + key: 'action', + width: 320, + render: (_: unknown, record: PluginInfo) => ( + + {getActions(record)} + setDetailPlugin(record)}> + 详情 + + handleAction(record.id, async () => { await purgePlugin(record.id); return record; }, '清除')} + > + + 清除 + + + + ), + }, + ]; + + return ( + + + + } type="primary" onClick={() => setUploadModalOpen(true)}> + 上传插件 + + } onClick={() => fetchPlugins()}> + 刷新 + + + + + setPage(p), + showTotal: (t) => `共 ${t} 个插件`, + }} + /> + + setUploadModalOpen(false)} + okText="上传" + width={600} + > + + + { + setWasmFile(file); + return false; + }} + maxCount={1} + accept=".wasm" + fileList={wasmFile ? [wasmFile as unknown as Parameters[0]] : []} + onRemove={() => setWasmFile(null)} + > + }>选择 WASM 文件 + + + + setManifestText(e.target.value)} + placeholder="[metadata] +id = "my-plugin" +name = "我的插件" +version = "0.1.0"" + /> + + + + + { + setDetailPlugin(null); + setHealthDetail(null); + }} + width={500} + > + {detailPlugin && ( + + {detailPlugin.id} + {detailPlugin.name} + {detailPlugin.version} + + + {STATUS_CONFIG[detailPlugin.status]?.label || detailPlugin.status} + + + {detailPlugin.author || '-'} + {detailPlugin.description || '-'} + {detailPlugin.installed_at || '-'} + {detailPlugin.enabled_at || '-'} + {detailPlugin.entities.length} + + )} + + + } + onClick={() => detailPlugin && handleHealthCheck(detailPlugin.id)} + style={{ marginBottom: 8 }} + > + 健康检查 + + {healthDetail && ( + + {JSON.stringify(healthDetail, null, 2)} + + )} + + + + ); +} diff --git a/apps/web/src/pages/PluginCRUDPage.tsx b/apps/web/src/pages/PluginCRUDPage.tsx new file mode 100644 index 0000000..5977e90 --- /dev/null +++ b/apps/web/src/pages/PluginCRUDPage.tsx @@ -0,0 +1,256 @@ +import { useEffect, useState, useCallback } from 'react'; +import { useParams } from 'react-router-dom'; +import { + Table, + Button, + Space, + Modal, + Form, + Input, + InputNumber, + DatePicker, + Switch, + Select, + Tag, + message, + Popconfirm, +} from 'antd'; +import { PlusOutlined, EditOutlined, DeleteOutlined, ReloadOutlined } from '@ant-design/icons'; +import { + listPluginData, + createPluginData, + updatePluginData, + deletePluginData, +} from '../api/pluginData'; +import { getPluginSchema } from '../api/plugins'; + +interface FieldDef { + name: string; + field_type: string; + required: boolean; + display_name?: string; + ui_widget?: string; + options?: { label: string; value: string }[]; +} + +interface EntitySchema { + name: string; + display_name: string; + fields: FieldDef[]; +} + +export default function PluginCRUDPage() { + const { pluginId, entityName } = useParams<{ pluginId: string; entityName: string }>(); + const [records, setRecords] = useState[]>([]); + const [total, setTotal] = useState(0); + const [page, setPage] = useState(1); + const [loading, setLoading] = useState(false); + const [fields, setFields] = useState([]); + const [displayName, setDisplayName] = useState(entityName || ''); + const [modalOpen, setModalOpen] = useState(false); + const [editRecord, setEditRecord] = useState | null>(null); + const [form] = Form.useForm(); + + // 加载 schema + useEffect(() => { + if (!pluginId) return; + getPluginSchema(pluginId) + .then((schema) => { + const entities = (schema as { entities?: EntitySchema[] }).entities || []; + const entity = entities.find((e) => e.name === entityName); + if (entity) { + setFields(entity.fields); + setDisplayName(entity.display_name || entityName || ''); + } + }) + .catch(() => { + // schema 加载失败时仍可使用 + }); + }, [pluginId, entityName]); + + const fetchData = useCallback(async (p = page) => { + if (!pluginId || !entityName) return; + setLoading(true); + try { + const result = await listPluginData(pluginId, entityName, p); + setRecords(result.data.map((r) => ({ ...r.data, _id: r.id, _version: r.version }))); + setTotal(result.total); + } catch { + message.error('加载数据失败'); + } + setLoading(false); + }, [pluginId, entityName, page]); + + useEffect(() => { + fetchData(); + }, [fetchData]); + + const handleSubmit = async (values: Record) => { + if (!pluginId || !entityName) return; + // 去除内部字段 + const { _id, _version, ...data } = values as Record & { _id?: string; _version?: number }; + + try { + if (editRecord) { + await updatePluginData( + pluginId, + entityName, + editRecord._id as string, + data, + editRecord._version as number, + ); + message.success('更新成功'); + } else { + await createPluginData(pluginId, entityName, data); + message.success('创建成功'); + } + setModalOpen(false); + setEditRecord(null); + fetchData(); + } catch { + message.error('操作失败'); + } + }; + + const handleDelete = async (record: Record) => { + if (!pluginId || !entityName) return; + try { + await deletePluginData(pluginId, entityName, record._id as string); + message.success('删除成功'); + fetchData(); + } catch { + message.error('删除失败'); + } + }; + + // 动态生成列 + const columns = [ + ...fields.slice(0, 5).map((f) => ({ + title: f.display_name || f.name, + dataIndex: f.name, + key: f.name, + ellipsis: true, + render: (val: unknown) => { + if (typeof val === 'boolean') return val ? 是 : 否; + return String(val ?? '-'); + }, + })), + { + title: '操作', + key: 'action', + width: 150, + render: (_: unknown, record: Record) => ( + + } + onClick={() => { + setEditRecord(record); + form.setFieldsValue(record); + setModalOpen(true); + }} + > + 编辑 + + handleDelete(record)}> + }> + 删除 + + + + ), + }, + ]; + + // 动态生成表单字段 + const renderFormField = (field: FieldDef) => { + const widget = field.ui_widget || field.field_type; + switch (widget) { + case 'number': + case 'integer': + case 'float': + case 'decimal': + return ; + case 'boolean': + return ; + case 'date': + case 'datetime': + return ; + case 'select': + return ( + + {(field.options || []).map((opt) => ( + + {opt.label} + + ))} + + ); + default: + return ; + } + }; + + return ( + + + {displayName} + + } + type="primary" + onClick={() => { + setEditRecord(null); + form.resetFields(); + setModalOpen(true); + }} + > + 新增 + + } onClick={() => fetchData()}> + 刷新 + + + + + setPage(p), + showTotal: (t) => `共 ${t} 条`, + }} + /> + + { + setModalOpen(false); + setEditRecord(null); + }} + onOk={() => form.submit()} + destroyOnClose + > + + {fields.map((field) => ( + + {renderFormField(field)} + + ))} + + + + ); +} diff --git a/apps/web/src/stores/plugin.ts b/apps/web/src/stores/plugin.ts new file mode 100644 index 0000000..4ba5d6a --- /dev/null +++ b/apps/web/src/stores/plugin.ts @@ -0,0 +1,59 @@ +import { create } from 'zustand'; +import type { PluginInfo, PluginStatus } from '../api/plugins'; +import { listPlugins } from '../api/plugins'; + +export interface PluginMenuItem { + key: string; + icon: string; + label: string; + pluginId: string; + entity: string; + menuGroup?: string; +} + +interface PluginStore { + plugins: PluginInfo[]; + loading: boolean; + pluginMenuItems: PluginMenuItem[]; + fetchPlugins: (page?: number, status?: PluginStatus) => Promise; + refreshMenuItems: () => void; +} + +export const usePluginStore = create((set, get) => ({ + plugins: [], + loading: false, + pluginMenuItems: [], + + fetchPlugins: async (page = 1, status?: PluginStatus) => { + set({ loading: true }); + try { + const result = await listPlugins(page, 100, status); + set({ plugins: result.data }); + get().refreshMenuItems(); + } finally { + set({ loading: false }); + } + }, + + refreshMenuItems: () => { + const { plugins } = get(); + const items: PluginMenuItem[] = []; + + for (const plugin of plugins) { + if (plugin.status !== 'running' && plugin.status !== 'enabled') continue; + + for (const entity of plugin.entities) { + items.push({ + key: `/plugins/${plugin.id}/${entity.name}`, + icon: 'AppstoreOutlined', + label: entity.display_name || entity.name, + pluginId: plugin.id, + entity: entity.name, + menuGroup: undefined, + }); + } + } + + set({ pluginMenuItems: items }); + }, +})); diff --git a/crates/erp-auth/src/service/seed.rs b/crates/erp-auth/src/service/seed.rs index 489d247..bb6ec87 100644 --- a/crates/erp-auth/src/service/seed.rs +++ b/crates/erp-auth/src/service/seed.rs @@ -302,6 +302,21 @@ const DEFAULT_PERMISSIONS: &[(&str, &str, &str, &str, &str)] = &[ "create", "创建消息模板", ), + // === Plugin module === + ( + "plugin.admin", + "插件管理", + "plugin", + "admin", + "管理插件全生命周期", + ), + ( + "plugin.list", + "查看插件", + "plugin", + "list", + "查看插件列表", + ), ]; /// Indices of read-only (list/read) permissions within DEFAULT_PERMISSIONS. @@ -324,6 +339,7 @@ const READ_PERM_INDICES: &[usize] = &[ 44, // workflow.read 49, // message.list 51, // message.template.list + 53, // plugin.list ]; /// Seed default auth data for a new tenant. diff --git a/crates/erp-core/src/events.rs b/crates/erp-core/src/events.rs index 488a5a2..58b5482 100644 --- a/crates/erp-core/src/events.rs +++ b/crates/erp-core/src/events.rs @@ -1,7 +1,7 @@ use chrono::Utc; use sea_orm::{ActiveModelTrait, Set}; use serde::{Deserialize, Serialize}; -use tokio::sync::broadcast; +use tokio::sync::{broadcast, mpsc}; use tracing::{error, info}; use uuid::Uuid; @@ -31,6 +31,32 @@ impl DomainEvent { } } +/// 过滤事件接收器 — 只接收匹配 `event_type_prefix` 的事件 +pub struct FilteredEventReceiver { + receiver: mpsc::Receiver, +} + +impl FilteredEventReceiver { + /// 接收下一个匹配的事件 + pub async fn recv(&mut self) -> Option { + self.receiver.recv().await + } +} + +/// 订阅句柄 — 用于取消过滤订阅 +pub struct SubscriptionHandle { + cancel_tx: mpsc::Sender<()>, + join_handle: tokio::task::JoinHandle<()>, +} + +impl SubscriptionHandle { + /// 取消订阅并等待后台任务结束 + pub async fn cancel(self) { + let _ = self.cancel_tx.send(()).await; + let _ = self.join_handle.await; + } +} + /// 进程内事件总线 #[derive(Clone)] pub struct EventBus { @@ -84,4 +110,57 @@ impl EventBus { pub fn subscribe(&self) -> broadcast::Receiver { self.sender.subscribe() } + + /// 按事件类型前缀过滤订阅。 + /// + /// 为每次调用 spawn 一个 Tokio task 从 broadcast channel 读取, + /// 只转发匹配 `event_type_prefix` 的事件到 mpsc channel(capacity 256)。 + pub fn subscribe_filtered( + &self, + event_type_prefix: String, + ) -> (FilteredEventReceiver, SubscriptionHandle) { + let mut broadcast_rx = self.sender.subscribe(); + let (mpsc_tx, mpsc_rx) = mpsc::channel(256); + let (cancel_tx, mut cancel_rx) = mpsc::channel::<()>(1); + + let prefix = event_type_prefix.clone(); + let join_handle = tokio::spawn(async move { + loop { + tokio::select! { + biased; + _ = cancel_rx.recv() => { + tracing::info!(prefix = %prefix, "Filtered subscription cancelled"); + break; + } + event = broadcast_rx.recv() => { + match event { + Ok(event) => { + if event.event_type.starts_with(&prefix) { + if mpsc_tx.send(event).await.is_err() { + break; + } + } + } + Err(broadcast::error::RecvError::Lagged(n)) => { + tracing::warn!(prefix = %prefix, lagged = n, "Filtered subscriber lagged"); + } + Err(broadcast::error::RecvError::Closed) => { + break; + } + } + } + } + } + }); + + tracing::info!(prefix = %event_type_prefix, "Filtered subscription created"); + + ( + FilteredEventReceiver { receiver: mpsc_rx }, + SubscriptionHandle { + cancel_tx, + join_handle, + }, + ) + } } diff --git a/crates/erp-core/src/lib.rs b/crates/erp-core/src/lib.rs index 8177c84..b4c2a50 100644 --- a/crates/erp-core/src/lib.rs +++ b/crates/erp-core/src/lib.rs @@ -6,3 +6,6 @@ pub mod events; pub mod module; pub mod rbac; pub mod types; + +// 便捷导出 +pub use module::{ModuleContext, ModuleType}; diff --git a/crates/erp-core/src/module.rs b/crates/erp-core/src/module.rs index c21862c..98239e7 100644 --- a/crates/erp-core/src/module.rs +++ b/crates/erp-core/src/module.rs @@ -1,11 +1,27 @@ use std::any::Any; +use std::collections::HashMap; use std::sync::Arc; use uuid::Uuid; -use crate::error::AppResult; +use crate::error::{AppError, AppResult}; use crate::events::EventBus; +/// 模块类型 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ModuleType { + /// 内置模块(编译时链接) + Builtin, + /// 插件模块(运行时加载) + Plugin, +} + +/// 模块启动上下文 — 在 on_startup 时提供给模块 +pub struct ModuleContext { + pub db: sea_orm::DatabaseConnection, + pub event_bus: EventBus, +} + /// 模块注册接口 /// 所有业务模块(Auth, Workflow, Message, Config, 行业模块)都实现此 trait #[async_trait::async_trait] @@ -13,11 +29,21 @@ pub trait ErpModule: Send + Sync { /// 模块名称(唯一标识) fn name(&self) -> &str; + /// 模块唯一 ID(默认等于 name) + fn id(&self) -> &str { + self.name() + } + /// 模块版本 fn version(&self) -> &str { env!("CARGO_PKG_VERSION") } + /// 模块类型 + fn module_type(&self) -> ModuleType { + ModuleType::Builtin + } + /// 依赖的其他模块名称 fn dependencies(&self) -> Vec<&str> { vec![] @@ -26,6 +52,21 @@ pub trait ErpModule: Send + Sync { /// 注册事件处理器 fn register_event_handlers(&self, _bus: &EventBus) {} + /// 模块启动钩子 — 服务启动时调用 + async fn on_startup(&self, _ctx: &ModuleContext) -> AppResult<()> { + Ok(()) + } + + /// 模块关闭钩子 — 服务关闭时调用 + async fn on_shutdown(&self) -> AppResult<()> { + Ok(()) + } + + /// 健康检查 + async fn health_check(&self) -> AppResult { + Ok(serde_json::json!({"status": "healthy"})) + } + /// 租户创建时的初始化钩子。 /// /// 用于为新建租户创建默认角色、管理员用户等初始数据。 @@ -72,7 +113,9 @@ impl ModuleRegistry { pub fn register(mut self, module: impl ErpModule + 'static) -> Self { tracing::info!( module = module.name(), + id = module.id(), version = module.version(), + module_type = ?module.module_type(), "Module registered" ); let mut modules = (*self.modules).clone(); @@ -90,4 +133,202 @@ impl ModuleRegistry { pub fn modules(&self) -> &[Arc] { &self.modules } + + /// 按名称获取模块 + pub fn get_module(&self, name: &str) -> Option> { + self.modules.iter().find(|m| m.name() == name).cloned() + } + + /// 按拓扑排序返回模块(依赖在前,被依赖在后) + /// + /// 使用 Kahn 算法,环检测返回 Validation 错误。 + pub fn sorted_modules(&self) -> AppResult>> { + let modules = &*self.modules; + let n = modules.len(); + if n == 0 { + return Ok(vec![]); + } + + // 构建名称到索引的映射 + let name_to_idx: HashMap<&str, usize> = modules + .iter() + .enumerate() + .map(|(i, m)| (m.name(), i)) + .collect(); + + // 构建邻接表和入度 + let mut adjacency: Vec> = vec![vec![]; n]; + let mut in_degree: Vec = vec![0; n]; + + for (idx, module) in modules.iter().enumerate() { + for dep in module.dependencies() { + if let Some(&dep_idx) = name_to_idx.get(dep) { + adjacency[dep_idx].push(idx); + in_degree[idx] += 1; + } + // 依赖未注册的模块不阻断(可能是可选依赖) + } + } + + // Kahn 算法 + let mut queue: Vec = (0..n).filter(|&i| in_degree[i] == 0).collect(); + let mut sorted_indices = Vec::with_capacity(n); + + while let Some(idx) = queue.pop() { + sorted_indices.push(idx); + for &next in &adjacency[idx] { + in_degree[next] -= 1; + if in_degree[next] == 0 { + queue.push(next); + } + } + } + + if sorted_indices.len() != n { + let cycle_modules: Vec<&str> = (0..n) + .filter(|i| !sorted_indices.contains(i)) + .filter_map(|i| modules.get(i).map(|m| m.name())) + .collect(); + return Err(AppError::Validation(format!( + "模块依赖存在循环: {}", + cycle_modules.join(", ") + ))); + } + + Ok(sorted_indices + .into_iter() + .map(|i| modules[i].clone()) + .collect()) + } + + /// 按拓扑顺序启动所有模块 + pub async fn startup_all(&self, ctx: &ModuleContext) -> AppResult<()> { + let sorted = self.sorted_modules()?; + for module in sorted { + tracing::info!(module = module.name(), "Starting module"); + module.on_startup(ctx).await?; + tracing::info!(module = module.name(), "Module started"); + } + Ok(()) + } + + /// 按拓扑逆序关闭所有模块 + pub async fn shutdown_all(&self) -> AppResult<()> { + let sorted = self.sorted_modules()?; + for module in sorted.into_iter().rev() { + tracing::info!(module = module.name(), "Shutting down module"); + if let Err(e) = module.on_shutdown().await { + tracing::error!(module = module.name(), error = %e, "Module shutdown failed"); + } + } + Ok(()) + } + + /// 对所有模块执行健康检查 + pub async fn health_check_all(&self) -> Vec<(String, AppResult)> { + let mut results = Vec::with_capacity(self.modules.len()); + for module in self.modules.iter() { + let result = module.health_check().await; + results.push((module.name().to_string(), result)); + } + results + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct TestModule { + name: &'static str, + deps: Vec<&'static str>, + } + + #[async_trait::async_trait] + impl ErpModule for TestModule { + fn name(&self) -> &str { + self.name + } + fn dependencies(&self) -> Vec<&str> { + self.deps.clone() + } + fn as_any(&self) -> &dyn Any { + self + } + } + + #[test] + fn sorted_modules_empty() { + let registry = ModuleRegistry::new(); + let sorted = registry.sorted_modules().unwrap(); + assert!(sorted.is_empty()); + } + + #[test] + fn sorted_modules_no_deps() { + let registry = ModuleRegistry::new() + .register(TestModule { + name: "a", + deps: vec![], + }) + .register(TestModule { + name: "b", + deps: vec![], + }); + let sorted = registry.sorted_modules().unwrap(); + assert_eq!(sorted.len(), 2); + } + + #[test] + fn sorted_modules_with_deps() { + let registry = ModuleRegistry::new() + .register(TestModule { + name: "auth", + deps: vec![], + }) + .register(TestModule { + name: "plugin", + deps: vec!["auth", "config"], + }) + .register(TestModule { + name: "config", + deps: vec!["auth"], + }); + let sorted = registry.sorted_modules().unwrap(); + let names: Vec<&str> = sorted.iter().map(|m| m.name()).collect(); + let auth_pos = names.iter().position(|&n| n == "auth").unwrap(); + let config_pos = names.iter().position(|&n| n == "config").unwrap(); + let plugin_pos = names.iter().position(|&n| n == "plugin").unwrap(); + assert!(auth_pos < config_pos); + assert!(config_pos < plugin_pos); + } + + #[test] + fn sorted_modules_circular_dep() { + let registry = ModuleRegistry::new() + .register(TestModule { + name: "a", + deps: vec!["b"], + }) + .register(TestModule { + name: "b", + deps: vec!["a"], + }); + let result = registry.sorted_modules(); + assert!(result.is_err()); + match result.err().unwrap() { + AppError::Validation(msg) => assert!(msg.contains("循环")), + other => panic!("Expected Validation, got {:?}", other), + } + } + + #[test] + fn get_module_found() { + let registry = ModuleRegistry::new().register(TestModule { + name: "auth", + deps: vec![], + }); + assert!(registry.get_module("auth").is_some()); + assert!(registry.get_module("unknown").is_none()); + } } diff --git a/crates/erp-plugin/Cargo.toml b/crates/erp-plugin/Cargo.toml new file mode 100644 index 0000000..b50d7b5 --- /dev/null +++ b/crates/erp-plugin/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "erp-plugin" +version = "0.1.0" +edition = "2024" +description = "ERP WASM 插件运行时 — 生产级 Host API" + +[dependencies] +wasmtime = "43" +wasmtime-wasi = "43" +erp-core = { workspace = true } +tokio = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +sea-orm = { workspace = true } +uuid = { workspace = true } +chrono = { workspace = true } +tracing = { workspace = true } +thiserror = { workspace = true } +dashmap = "6" +toml = "0.8" +axum = { workspace = true } +utoipa = { workspace = true } +async-trait = { workspace = true } +sha2 = { workspace = true } diff --git a/crates/erp-plugin/src/data_dto.rs b/crates/erp-plugin/src/data_dto.rs new file mode 100644 index 0000000..f4934c9 --- /dev/null +++ b/crates/erp-plugin/src/data_dto.rs @@ -0,0 +1,33 @@ +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +/// 插件数据记录响应 +#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)] +pub struct PluginDataResp { + pub id: String, + pub data: serde_json::Value, + pub created_at: Option>, + pub updated_at: Option>, + pub version: Option, +} + +/// 创建插件数据请求 +#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)] +pub struct CreatePluginDataReq { + pub data: serde_json::Value, +} + +/// 更新插件数据请求 +#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)] +pub struct UpdatePluginDataReq { + pub data: serde_json::Value, + pub version: i32, +} + +/// 插件数据列表查询参数 +#[derive(Debug, Serialize, Deserialize, utoipa::IntoParams)] +pub struct PluginDataListParams { + pub page: Option, + pub page_size: Option, + pub search: Option, +} diff --git a/crates/erp-plugin/src/data_service.rs b/crates/erp-plugin/src/data_service.rs new file mode 100644 index 0000000..8f5960e --- /dev/null +++ b/crates/erp-plugin/src/data_service.rs @@ -0,0 +1,250 @@ +use sea_orm::{ColumnTrait, ConnectionTrait, EntityTrait, FromQueryResult, QueryFilter, Statement}; +use uuid::Uuid; + +use erp_core::error::AppResult; +use erp_core::events::EventBus; + +use crate::data_dto::PluginDataResp; +use crate::dynamic_table::DynamicTableManager; +use crate::entity::plugin_entity; +use crate::error::PluginError; + +pub struct PluginDataService; + +impl PluginDataService { + /// 创建插件数据 + pub async fn create( + plugin_id: Uuid, + entity_name: &str, + tenant_id: Uuid, + operator_id: Uuid, + data: serde_json::Value, + db: &sea_orm::DatabaseConnection, + _event_bus: &EventBus, + ) -> AppResult { + let table_name = resolve_table_name(plugin_id, entity_name, tenant_id, db).await?; + let (sql, values) = + DynamicTableManager::build_insert_sql(&table_name, tenant_id, operator_id, &data); + + #[derive(FromQueryResult)] + struct InsertResult { + id: Uuid, + data: serde_json::Value, + created_at: chrono::DateTime, + updated_at: chrono::DateTime, + version: i32, + } + + let result = InsertResult::find_by_statement(Statement::from_sql_and_values( + sea_orm::DatabaseBackend::Postgres, + sql, + values, + )) + .one(db) + .await? + .ok_or_else(|| PluginError::DatabaseError("INSERT 未返回结果".to_string()))?; + + Ok(PluginDataResp { + id: result.id.to_string(), + data: result.data, + created_at: Some(result.created_at), + updated_at: Some(result.updated_at), + version: Some(result.version), + }) + } + + /// 列表查询 + pub async fn list( + plugin_id: Uuid, + entity_name: &str, + tenant_id: Uuid, + page: u64, + page_size: u64, + db: &sea_orm::DatabaseConnection, + ) -> AppResult<(Vec, u64)> { + let table_name = resolve_table_name(plugin_id, entity_name, tenant_id, db).await?; + + // Count + let (count_sql, count_values) = DynamicTableManager::build_count_sql(&table_name, tenant_id); + #[derive(FromQueryResult)] + struct CountResult { + count: i64, + } + let total = CountResult::find_by_statement(Statement::from_sql_and_values( + sea_orm::DatabaseBackend::Postgres, + count_sql, + count_values, + )) + .one(db) + .await? + .map(|r| r.count as u64) + .unwrap_or(0); + + // Query + let offset = (page.saturating_sub(1)) * page_size; + let (sql, values) = DynamicTableManager::build_query_sql(&table_name, tenant_id, page_size, offset); + + #[derive(FromQueryResult)] + struct DataRow { + id: Uuid, + data: serde_json::Value, + created_at: chrono::DateTime, + updated_at: chrono::DateTime, + version: i32, + } + + let rows = DataRow::find_by_statement(Statement::from_sql_and_values( + sea_orm::DatabaseBackend::Postgres, + sql, + values, + )) + .all(db) + .await?; + + let items = rows + .into_iter() + .map(|r| PluginDataResp { + id: r.id.to_string(), + data: r.data, + created_at: Some(r.created_at), + updated_at: Some(r.updated_at), + version: Some(r.version), + }) + .collect(); + + Ok((items, total)) + } + + /// 按 ID 获取 + pub async fn get_by_id( + plugin_id: Uuid, + entity_name: &str, + id: Uuid, + tenant_id: Uuid, + db: &sea_orm::DatabaseConnection, + ) -> AppResult { + let table_name = resolve_table_name(plugin_id, entity_name, tenant_id, db).await?; + let (sql, values) = DynamicTableManager::build_get_by_id_sql(&table_name, id, tenant_id); + + #[derive(FromQueryResult)] + struct DataRow { + id: Uuid, + data: serde_json::Value, + created_at: chrono::DateTime, + updated_at: chrono::DateTime, + version: i32, + } + + let row = DataRow::find_by_statement(Statement::from_sql_and_values( + sea_orm::DatabaseBackend::Postgres, + sql, + values, + )) + .one(db) + .await? + .ok_or_else(|| erp_core::error::AppError::NotFound("记录不存在".to_string()))?; + + Ok(PluginDataResp { + id: row.id.to_string(), + data: row.data, + created_at: Some(row.created_at), + updated_at: Some(row.updated_at), + version: Some(row.version), + }) + } + + /// 更新 + pub async fn update( + plugin_id: Uuid, + entity_name: &str, + id: Uuid, + tenant_id: Uuid, + operator_id: Uuid, + data: serde_json::Value, + expected_version: i32, + db: &sea_orm::DatabaseConnection, + _event_bus: &EventBus, + ) -> AppResult { + let table_name = resolve_table_name(plugin_id, entity_name, tenant_id, db).await?; + let (sql, values) = DynamicTableManager::build_update_sql( + &table_name, + id, + tenant_id, + operator_id, + &data, + expected_version, + ); + + #[derive(FromQueryResult)] + struct UpdateResult { + id: Uuid, + data: serde_json::Value, + created_at: chrono::DateTime, + updated_at: chrono::DateTime, + version: i32, + } + + let result = UpdateResult::find_by_statement(Statement::from_sql_and_values( + sea_orm::DatabaseBackend::Postgres, + sql, + values, + )) + .one(db) + .await? + .ok_or_else(|| erp_core::error::AppError::VersionMismatch)?; + + Ok(PluginDataResp { + id: result.id.to_string(), + data: result.data, + created_at: Some(result.created_at), + updated_at: Some(result.updated_at), + version: Some(result.version), + }) + } + + /// 删除(软删除) + pub async fn delete( + plugin_id: Uuid, + entity_name: &str, + id: Uuid, + tenant_id: Uuid, + db: &sea_orm::DatabaseConnection, + _event_bus: &EventBus, + ) -> AppResult<()> { + let table_name = resolve_table_name(plugin_id, entity_name, tenant_id, db).await?; + let (sql, values) = DynamicTableManager::build_delete_sql(&table_name, id, tenant_id); + + db.execute(Statement::from_sql_and_values( + sea_orm::DatabaseBackend::Postgres, + sql, + values, + )) + .await?; + + Ok(()) + } +} + +/// 从 plugin_entities 表解析 table_name(带租户隔离) +async fn resolve_table_name( + plugin_id: Uuid, + entity_name: &str, + tenant_id: Uuid, + db: &sea_orm::DatabaseConnection, +) -> AppResult { + let entity = plugin_entity::Entity::find() + .filter(plugin_entity::Column::PluginId.eq(plugin_id)) + .filter(plugin_entity::Column::TenantId.eq(tenant_id)) + .filter(plugin_entity::Column::EntityName.eq(entity_name)) + .filter(plugin_entity::Column::DeletedAt.is_null()) + .one(db) + .await? + .ok_or_else(|| { + erp_core::error::AppError::NotFound(format!( + "插件实体 {}/{} 不存在", + plugin_id, entity_name + )) + })?; + + Ok(entity.table_name) +} diff --git a/crates/erp-plugin/src/dto.rs b/crates/erp-plugin/src/dto.rs new file mode 100644 index 0000000..fafbcd7 --- /dev/null +++ b/crates/erp-plugin/src/dto.rs @@ -0,0 +1,65 @@ +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +/// 插件信息响应 +#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)] +pub struct PluginResp { + pub id: Uuid, + pub name: String, + pub version: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub author: Option, + pub status: String, + pub config: serde_json::Value, + #[serde(skip_serializing_if = "Option::is_none")] + pub installed_at: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub enabled_at: Option>, + pub entities: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub permissions: Option>, + pub record_version: i32, +} + +/// 插件实体信息 +#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)] +pub struct PluginEntityResp { + pub name: String, + pub display_name: String, + pub table_name: String, +} + +/// 插件权限信息 +#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)] +pub struct PluginPermissionResp { + pub code: String, + pub name: String, + pub description: String, +} + +/// 插件健康检查响应 +#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)] +pub struct PluginHealthResp { + pub plugin_id: Uuid, + pub status: String, + pub details: serde_json::Value, +} + +/// 更新插件配置请求 +#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)] +pub struct UpdatePluginConfigReq { + pub config: serde_json::Value, + pub version: i32, +} + +/// 插件列表查询参数 +#[derive(Debug, Serialize, Deserialize, utoipa::IntoParams)] +pub struct PluginListParams { + pub page: Option, + pub page_size: Option, + pub status: Option, + pub search: Option, +} diff --git a/crates/erp-plugin/src/dynamic_table.rs b/crates/erp-plugin/src/dynamic_table.rs new file mode 100644 index 0000000..c1ceb30 --- /dev/null +++ b/crates/erp-plugin/src/dynamic_table.rs @@ -0,0 +1,250 @@ +use sea_orm::{ConnectionTrait, DatabaseConnection, FromQueryResult, Statement, Value}; +use uuid::Uuid; + +use crate::error::{PluginError, PluginResult}; +use crate::manifest::PluginEntity; + +/// 消毒标识符:只保留 ASCII 字母、数字、下划线,防止 SQL 注入 +fn sanitize_identifier(input: &str) -> String { + input + .chars() + .map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }) + .collect() +} + +/// 动态表管理器 — 处理插件动态创建/删除的数据库表 +pub struct DynamicTableManager; + +impl DynamicTableManager { + /// 生成动态表名: `plugin_{sanitized_id}_{sanitized_entity}` + pub fn table_name(plugin_id: &str, entity_name: &str) -> String { + let sanitized_id = sanitize_identifier(plugin_id); + let sanitized_entity = sanitize_identifier(entity_name); + format!("plugin_{}_{}", sanitized_id, sanitized_entity) + } + + /// 创建动态表 + pub async fn create_table( + db: &DatabaseConnection, + plugin_id: &str, + entity: &PluginEntity, + ) -> PluginResult<()> { + let table_name = Self::table_name(plugin_id, &entity.name); + + // 创建表 + let create_sql = format!( + "CREATE TABLE IF NOT EXISTS \"{table_name}\" (\ + \"id\" UUID PRIMARY KEY, \ + \"tenant_id\" UUID NOT NULL, \ + \"data\" JSONB NOT NULL DEFAULT '{{}}', \ + \"created_at\" TIMESTAMPTZ NOT NULL DEFAULT NOW(), \ + \"updated_at\" TIMESTAMPTZ NOT NULL DEFAULT NOW(), \ + \"created_by\" UUID, \ + \"updated_by\" UUID, \ + \"deleted_at\" TIMESTAMPTZ, \ + \"version\" INT NOT NULL DEFAULT 1)" + ); + + db.execute(Statement::from_string( + sea_orm::DatabaseBackend::Postgres, + create_sql, + )) + .await + .map_err(|e| PluginError::DatabaseError(e.to_string()))?; + + // 创建租户索引 + let tenant_idx_sql = format!( + "CREATE INDEX IF NOT EXISTS \"idx_{t}_tenant\" ON \"{table_name}\" (\"tenant_id\") WHERE \"deleted_at\" IS NULL", + t = sanitize_identifier(&table_name) + ); + db.execute(Statement::from_string( + sea_orm::DatabaseBackend::Postgres, + tenant_idx_sql, + )) + .await + .map_err(|e| PluginError::DatabaseError(e.to_string()))?; + + // 为字段创建索引(使用参数化方式避免 SQL 注入) + for field in &entity.fields { + if field.unique || field.required { + let sanitized_field = sanitize_identifier(&field.name); + let idx_name = format!( + "idx_{}_{}_{}", + sanitize_identifier(&table_name), + sanitized_field, + if field.unique { "uniq" } else { "idx" } + ); + let idx_sql = format!( + "CREATE INDEX IF NOT EXISTS \"{idx_name}\" ON \"{table_name}\" (\"data\"->>'{sanitized_field}') WHERE \"deleted_at\" IS NULL" + ); + db.execute(Statement::from_string( + sea_orm::DatabaseBackend::Postgres, + idx_sql, + )) + .await + .map_err(|e| PluginError::DatabaseError(e.to_string()))?; + } + } + + tracing::info!(table = %table_name, "Dynamic table created"); + Ok(()) + } + + /// 删除动态表 + pub async fn drop_table( + db: &DatabaseConnection, + plugin_id: &str, + entity_name: &str, + ) -> PluginResult<()> { + let table_name = Self::table_name(plugin_id, entity_name); + let sql = format!("DROP TABLE IF EXISTS \"{}\"", table_name); + db.execute(Statement::from_string( + sea_orm::DatabaseBackend::Postgres, + sql, + )) + .await + .map_err(|e| PluginError::DatabaseError(e.to_string()))?; + tracing::info!(table = %table_name, "Dynamic table dropped"); + Ok(()) + } + + /// 检查表是否存在 + pub async fn table_exists(db: &DatabaseConnection, table_name: &str) -> PluginResult { + #[derive(FromQueryResult)] + struct ExistsResult { + exists: bool, + } + let result = ExistsResult::find_by_statement(Statement::from_sql_and_values( + sea_orm::DatabaseBackend::Postgres, + "SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = $1)", + [table_name.into()], + )) + .one(db) + .await + .map_err(|e| PluginError::DatabaseError(e.to_string()))?; + + Ok(result.map(|r| r.exists).unwrap_or(false)) + } + + /// 构建 INSERT SQL + pub fn build_insert_sql( + table_name: &str, + tenant_id: Uuid, + user_id: Uuid, + data: &serde_json::Value, + ) -> (String, Vec) { + let id = Uuid::now_v7(); + Self::build_insert_sql_with_id(table_name, id, tenant_id, user_id, data) + } + + /// 构建 INSERT SQL(指定 ID) + pub fn build_insert_sql_with_id( + table_name: &str, + id: Uuid, + tenant_id: Uuid, + user_id: Uuid, + data: &serde_json::Value, + ) -> (String, Vec) { + let sql = format!( + "INSERT INTO \"{}\" (id, tenant_id, data, created_by, updated_by, version) \ + VALUES ($1, $2, $3, $4, $5, 1) \ + RETURNING id, tenant_id, data, created_at, updated_at, version", + table_name + ); + let values = vec![ + id.into(), + tenant_id.into(), + serde_json::to_string(data).unwrap_or_default().into(), + user_id.into(), + user_id.into(), + ]; + (sql, values) + } + + /// 构建 SELECT SQL + pub fn build_query_sql( + table_name: &str, + tenant_id: Uuid, + limit: u64, + offset: u64, + ) -> (String, Vec) { + let sql = format!( + "SELECT id, data, created_at, updated_at, version \ + FROM \"{}\" \ + WHERE tenant_id = $1 AND deleted_at IS NULL \ + ORDER BY created_at DESC \ + LIMIT $2 OFFSET $3", + table_name + ); + let values = vec![tenant_id.into(), (limit as i64).into(), (offset as i64).into()]; + (sql, values) + } + + /// 构建 COUNT SQL + pub fn build_count_sql(table_name: &str, tenant_id: Uuid) -> (String, Vec) { + let sql = format!( + "SELECT COUNT(*) as count FROM \"{}\" WHERE tenant_id = $1 AND deleted_at IS NULL", + table_name + ); + let values = vec![tenant_id.into()]; + (sql, values) + } + + /// 构建 UPDATE SQL(含乐观锁) + pub fn build_update_sql( + table_name: &str, + id: Uuid, + tenant_id: Uuid, + user_id: Uuid, + data: &serde_json::Value, + version: i32, + ) -> (String, Vec) { + let sql = format!( + "UPDATE \"{}\" \ + SET data = $1, updated_at = NOW(), updated_by = $2, version = version + 1 \ + WHERE id = $3 AND tenant_id = $4 AND version = $5 AND deleted_at IS NULL \ + RETURNING id, data, created_at, updated_at, version", + table_name + ); + let values = vec![ + serde_json::to_string(data).unwrap_or_default().into(), + user_id.into(), + id.into(), + tenant_id.into(), + version.into(), + ]; + (sql, values) + } + + /// 构建 DELETE SQL(软删除) + pub fn build_delete_sql( + table_name: &str, + id: Uuid, + tenant_id: Uuid, + ) -> (String, Vec) { + let sql = format!( + "UPDATE \"{}\" \ + SET deleted_at = NOW(), updated_at = NOW() \ + WHERE id = $1 AND tenant_id = $2 AND deleted_at IS NULL", + table_name + ); + let values = vec![id.into(), tenant_id.into()]; + (sql, values) + } + + /// 构建单条查询 SQL + pub fn build_get_by_id_sql( + table_name: &str, + id: Uuid, + tenant_id: Uuid, + ) -> (String, Vec) { + let sql = format!( + "SELECT id, data, created_at, updated_at, version \ + FROM \"{}\" \ + WHERE id = $1 AND tenant_id = $2 AND deleted_at IS NULL", + table_name + ); + let values = vec![id.into(), tenant_id.into()]; + (sql, values) + } +} diff --git a/crates/erp-plugin/src/engine.rs b/crates/erp-plugin/src/engine.rs new file mode 100644 index 0000000..ac2dc70 --- /dev/null +++ b/crates/erp-plugin/src/engine.rs @@ -0,0 +1,664 @@ +use std::panic::AssertUnwindSafe; +use std::sync::Arc; + +use dashmap::DashMap; +use sea_orm::{ConnectionTrait, DatabaseConnection, Statement, TransactionTrait}; +use serde_json::json; +use tokio::sync::RwLock; +use uuid::Uuid; +use wasmtime::component::{Component, HasSelf, Linker}; +use wasmtime::{Config, Engine, Store}; + +use erp_core::events::EventBus; + +use crate::PluginWorld; +use crate::dynamic_table::DynamicTableManager; +use crate::error::{PluginError, PluginResult}; +use crate::host::{HostState, PendingOp}; +use crate::manifest::PluginManifest; + +/// 插件引擎配置 +#[derive(Debug, Clone)] +pub struct PluginEngineConfig { + /// 默认 Fuel 限制 + pub default_fuel: u64, + /// 执行超时(秒) + pub execution_timeout_secs: u64, +} + +impl Default for PluginEngineConfig { + fn default() -> Self { + Self { + default_fuel: 10_000_000, + execution_timeout_secs: 30, + } + } +} + +/// 插件运行状态 +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PluginStatus { + /// 已加载到内存 + Loaded, + /// 已初始化(init() 已调用) + Initialized, + /// 运行中(事件监听已启动) + Running, + /// 错误状态 + Error(String), + /// 已禁用 + Disabled, +} + +/// 已加载的插件实例 +pub struct LoadedPlugin { + pub id: String, + pub manifest: PluginManifest, + pub component: Component, + pub linker: Linker, + pub status: RwLock, + pub event_handles: RwLock>>, +} + +/// WASM 执行上下文 — 传递真实的租户和用户信息 +#[derive(Debug, Clone)] +pub struct ExecutionContext { + pub tenant_id: Uuid, + pub user_id: Uuid, + pub permissions: Vec, +} + +/// 插件引擎 — 管理所有已加载插件的 WASM 运行时 +#[derive(Clone)] +pub struct PluginEngine { + engine: Arc, + db: DatabaseConnection, + event_bus: EventBus, + plugins: Arc>>, + config: PluginEngineConfig, +} + +impl PluginEngine { + /// 创建新的插件引擎 + pub fn new( + db: DatabaseConnection, + event_bus: EventBus, + config: PluginEngineConfig, + ) -> PluginResult { + let mut wasm_config = Config::new(); + wasm_config.wasm_component_model(true); + wasm_config.consume_fuel(true); + let engine = Engine::new(&wasm_config) + .map_err(|e| PluginError::InstantiationError(e.to_string()))?; + + Ok(Self { + engine: Arc::new(engine), + db, + event_bus, + plugins: Arc::new(DashMap::new()), + config, + }) + } + + /// 加载插件到内存(不初始化) + pub async fn load( + &self, + plugin_id: &str, + wasm_bytes: &[u8], + manifest: PluginManifest, + ) -> PluginResult<()> { + if self.plugins.contains_key(plugin_id) { + return Err(PluginError::AlreadyExists(plugin_id.to_string())); + } + + let component = Component::from_binary(&self.engine, wasm_bytes) + .map_err(|e| PluginError::InstantiationError(e.to_string()))?; + + let mut linker = Linker::new(&self.engine); + // 注册 Host API 到 Linker + PluginWorld::add_to_linker::<_, HasSelf>(&mut linker, |state| state) + .map_err(|e| PluginError::InstantiationError(e.to_string()))?; + + let loaded = Arc::new(LoadedPlugin { + id: plugin_id.to_string(), + manifest, + component, + linker, + status: RwLock::new(PluginStatus::Loaded), + event_handles: RwLock::new(vec![]), + }); + + self.plugins.insert(plugin_id.to_string(), loaded); + tracing::info!(plugin_id, "Plugin loaded into memory"); + Ok(()) + } + + /// 初始化插件(调用 init()) + pub async fn initialize(&self, plugin_id: &str) -> PluginResult<()> { + let loaded = self.get_loaded(plugin_id)?; + + // 检查状态 + { + let status = loaded.status.read().await; + if *status != PluginStatus::Loaded { + return Err(PluginError::InvalidState { + expected: "Loaded".to_string(), + actual: format!("{:?}", *status), + }); + } + } + + let ctx = ExecutionContext { + tenant_id: Uuid::nil(), + user_id: Uuid::nil(), + permissions: vec![], + }; + + let result = self + .execute_wasm(plugin_id, &ctx, |store, instance| { + instance.erp_plugin_plugin_api().call_init(store) + .map_err(|e| PluginError::ExecutionError(e.to_string()))? + .map_err(|e| PluginError::ExecutionError(e))?; + Ok(()) + }) + .await; + + match result { + Ok(()) => { + *loaded.status.write().await = PluginStatus::Initialized; + tracing::info!(plugin_id, "Plugin initialized"); + Ok(()) + } + Err(e) => { + *loaded.status.write().await = PluginStatus::Error(e.to_string()); + Err(e) + } + } + } + + /// 启动事件监听 + pub async fn start_event_listener(&self, plugin_id: &str) -> PluginResult<()> { + let loaded = self.get_loaded(plugin_id)?; + + // 检查状态 + { + let status = loaded.status.read().await; + if *status != PluginStatus::Initialized { + return Err(PluginError::InvalidState { + expected: "Initialized".to_string(), + actual: format!("{:?}", *status), + }); + } + } + + let events_config = &loaded.manifest.events; + if let Some(events) = events_config { + for pattern in &events.subscribe { + let (mut rx, sub_handle) = self.event_bus.subscribe_filtered(pattern.clone()); + let pid = plugin_id.to_string(); + let engine = self.clone(); + + let join_handle = tokio::spawn(async move { + // sub_handle 保存在此 task 中,task 结束时自动 drop 触发优雅取消 + let _sub_guard = sub_handle; + while let Some(event) = rx.recv().await { + if let Err(e) = engine + .handle_event_inner( + &pid, + &event.event_type, + &event.payload, + event.tenant_id, + ) + .await + { + tracing::error!( + plugin_id = %pid, + error = %e, + "Plugin event handler failed" + ); + } + } + }); + + loaded.event_handles.write().await.push(join_handle); + } + } + + *loaded.status.write().await = PluginStatus::Running; + tracing::info!(plugin_id, "Plugin event listener started"); + Ok(()) + } + + /// 处理单个事件 + pub async fn handle_event( + &self, + plugin_id: &str, + event_type: &str, + payload: &serde_json::Value, + tenant_id: Uuid, + ) -> PluginResult<()> { + self.handle_event_inner(plugin_id, event_type, payload, tenant_id) + .await + } + + async fn handle_event_inner( + &self, + plugin_id: &str, + event_type: &str, + payload: &serde_json::Value, + tenant_id: Uuid, + ) -> PluginResult<()> { + let payload_bytes = serde_json::to_vec(payload).unwrap_or_default(); + let event_type = event_type.to_owned(); + + let ctx = ExecutionContext { + tenant_id, + user_id: Uuid::nil(), + permissions: vec![], + }; + + self.execute_wasm(plugin_id, &ctx, move |store, instance| { + instance + .erp_plugin_plugin_api() + .call_handle_event(store, &event_type, &payload_bytes) + .map_err(|e| PluginError::ExecutionError(e.to_string()))? + .map_err(|e| PluginError::ExecutionError(e))?; + Ok(()) + }) + .await + } + + /// 租户创建时调用插件的 on_tenant_created + pub async fn on_tenant_created(&self, plugin_id: &str, tenant_id: Uuid) -> PluginResult<()> { + let tenant_id_str = tenant_id.to_string(); + + let ctx = ExecutionContext { + tenant_id, + user_id: Uuid::nil(), + permissions: vec![], + }; + + self.execute_wasm(plugin_id, &ctx, move |store, instance| { + instance + .erp_plugin_plugin_api() + .call_on_tenant_created(store, &tenant_id_str) + .map_err(|e| PluginError::ExecutionError(e.to_string()))? + .map_err(|e| PluginError::ExecutionError(e))?; + Ok(()) + }) + .await + } + + /// 禁用插件(停止事件监听 + 更新状态) + pub async fn disable(&self, plugin_id: &str) -> PluginResult<()> { + let loaded = self.get_loaded(plugin_id)?; + + // 取消所有事件监听 + let mut handles = loaded.event_handles.write().await; + for handle in handles.drain(..) { + handle.abort(); + } + drop(handles); + + *loaded.status.write().await = PluginStatus::Disabled; + tracing::info!(plugin_id, "Plugin disabled"); + Ok(()) + } + + /// 从内存卸载插件 + pub async fn unload(&self, plugin_id: &str) -> PluginResult<()> { + if self.plugins.contains_key(plugin_id) { + self.disable(plugin_id).await.ok(); + } + self.plugins.remove(plugin_id); + tracing::info!(plugin_id, "Plugin unloaded"); + Ok(()) + } + + /// 健康检查 + pub async fn health_check(&self, plugin_id: &str) -> PluginResult { + let loaded = self.get_loaded(plugin_id)?; + let status = loaded.status.read().await; + match &*status { + PluginStatus::Running => Ok(json!({ + "status": "healthy", + "plugin_id": plugin_id, + })), + PluginStatus::Error(e) => Ok(json!({ + "status": "error", + "plugin_id": plugin_id, + "error": e, + })), + other => Ok(json!({ + "status": "unhealthy", + "plugin_id": plugin_id, + "state": format!("{:?}", other), + })), + } + } + + /// 列出所有已加载插件的信息 + pub fn list_plugins(&self) -> Vec { + self.plugins + .iter() + .map(|entry| { + let loaded = entry.value(); + PluginInfo { + id: loaded.id.clone(), + name: loaded.manifest.metadata.name.clone(), + version: loaded.manifest.metadata.version.clone(), + } + }) + .collect() + } + + /// 获取插件清单 + pub fn get_manifest(&self, plugin_id: &str) -> Option { + self.plugins + .get(plugin_id) + .map(|entry| entry.manifest.clone()) + } + + /// 检查插件是否正在运行 + pub async fn is_running(&self, plugin_id: &str) -> bool { + if let Some(loaded) = self.plugins.get(plugin_id) { + matches!(*loaded.status.read().await, PluginStatus::Running) + } else { + false + } + } + + /// 恢复数据库中状态为 running/enabled 的插件。 + /// + /// 服务器重启后调用此方法,重新加载 WASM 到内存并启动事件监听。 + pub async fn recover_plugins( + &self, + db: &DatabaseConnection, + ) -> PluginResult> { + use sea_orm::{ColumnTrait, EntityTrait, QueryFilter}; + use crate::entity::plugin; + + // 查询所有运行中的插件 + let running_plugins = plugin::Entity::find() + .filter(plugin::Column::Status.eq("running")) + .filter(plugin::Column::DeletedAt.is_null()) + .all(db) + .await + .map_err(|e| PluginError::DatabaseError(e.to_string()))?; + + let mut recovered = Vec::new(); + for model in running_plugins { + let manifest: PluginManifest = serde_json::from_value(model.manifest_json.clone()) + .map_err(|e| PluginError::InvalidManifest(e.to_string()))?; + let plugin_id_str = &manifest.metadata.id; + + // 加载 WASM 到内存 + if let Err(e) = self.load(plugin_id_str, &model.wasm_binary, manifest.clone()).await { + tracing::error!( + plugin_id = %plugin_id_str, + error = %e, + "Failed to recover plugin (load)" + ); + continue; + } + + // 初始化 + if let Err(e) = self.initialize(plugin_id_str).await { + tracing::error!( + plugin_id = %plugin_id_str, + error = %e, + "Failed to recover plugin (initialize)" + ); + continue; + } + + // 启动事件监听 + if let Err(e) = self.start_event_listener(plugin_id_str).await { + tracing::error!( + plugin_id = %plugin_id_str, + error = %e, + "Failed to recover plugin (start_event_listener)" + ); + continue; + } + + tracing::info!(plugin_id = %plugin_id_str, "Plugin recovered"); + recovered.push(plugin_id_str.clone()); + } + + tracing::info!(count = recovered.len(), "Plugins recovered"); + Ok(recovered) + } + + // ---- 内部方法 ---- + + fn get_loaded(&self, plugin_id: &str) -> PluginResult> { + self.plugins + .get(plugin_id) + .map(|e| e.value().clone()) + .ok_or_else(|| PluginError::NotFound(plugin_id.to_string())) + } + + /// 在 spawn_blocking + catch_unwind + fuel + timeout 中执行 WASM 操作, + /// 执行完成后自动刷新 pending_ops 到数据库。 + async fn execute_wasm( + &self, + plugin_id: &str, + exec_ctx: &ExecutionContext, + operation: F, + ) -> PluginResult + where + F: FnOnce(&mut Store, &PluginWorld) -> PluginResult + + Send + + std::panic::UnwindSafe + + 'static, + R: Send + 'static, + { + let loaded = self.get_loaded(plugin_id)?; + + // 创建新的 Store + HostState,使用真实的租户/用户上下文 + let state = HostState::new( + plugin_id.to_string(), + exec_ctx.tenant_id, + exec_ctx.user_id, + exec_ctx.permissions.clone(), + ); + let mut store = Store::new(&self.engine, state); + store + .set_fuel(self.config.default_fuel) + .map_err(|e| PluginError::ExecutionError(e.to_string()))?; + store.limiter(|state| &mut state.limits); + + // 实例化 + let instance = PluginWorld::instantiate_async(&mut store, &loaded.component, &loaded.linker) + .await + .map_err(|e| PluginError::InstantiationError(e.to_string()))?; + + let timeout_secs = self.config.execution_timeout_secs; + let pid_owned = plugin_id.to_owned(); + + // spawn_blocking 闭包执行 WASM,正常完成时收集 pending_ops + let (result, pending_ops): (PluginResult, Vec) = + tokio::time::timeout( + std::time::Duration::from_secs(timeout_secs), + tokio::task::spawn_blocking(move || { + match std::panic::catch_unwind(AssertUnwindSafe(|| { + let r = operation(&mut store, &instance); + // catch_unwind 内部不能调用 into_data(需要 &mut self), + // 但这里 operation 已完成,store 仍可用 + let ops = std::mem::take(&mut store.data_mut().pending_ops); + (r, ops) + })) { + Ok((r, ops)) => (r, ops), + Err(_) => { + // panic 后丢弃所有 pending_ops,避免半完成状态写入数据库 + tracing::warn!(plugin = %pid_owned, "WASM panic, discarding pending ops"); + ( + Err(PluginError::ExecutionError("WASM panic".to_string())), + Vec::new(), + ) + } + } + }), + ) + .await + .map_err(|_| { + PluginError::ExecutionError(format!("插件执行超时 ({}s)", timeout_secs)) + })? + .map_err(|e| PluginError::ExecutionError(e.to_string()))?; + + // 刷新写操作到数据库 + Self::flush_ops( + &self.db, + plugin_id, + pending_ops, + exec_ctx.tenant_id, + exec_ctx.user_id, + &self.event_bus, + ) + .await?; + + result + } + + /// 刷新 HostState 中的 pending_ops 到数据库。 + /// + /// 使用事务包裹所有数据库操作确保原子性。 + /// 事件发布在事务提交后执行(best-effort)。 + pub(crate) async fn flush_ops( + db: &DatabaseConnection, + plugin_id: &str, + ops: Vec, + tenant_id: Uuid, + user_id: Uuid, + event_bus: &EventBus, + ) -> PluginResult<()> { + if ops.is_empty() { + return Ok(()); + } + + // 使用事务确保所有数据库操作的原子性 + let txn = db.begin().await.map_err(|e| PluginError::DatabaseError(e.to_string()))?; + + for op in &ops { + match op { + PendingOp::Insert { id, entity, data } => { + let table_name = DynamicTableManager::table_name(plugin_id, entity); + let parsed_data: serde_json::Value = + serde_json::from_slice(data).unwrap_or_default(); + let id_uuid = id.parse::().map_err(|e| { + PluginError::ExecutionError(format!("无效的 ID: {}", e)) + })?; + let (sql, values) = + DynamicTableManager::build_insert_sql_with_id(&table_name, id_uuid, tenant_id, user_id, &parsed_data); + txn.execute(Statement::from_sql_and_values( + sea_orm::DatabaseBackend::Postgres, + sql, + values, + )) + .await + .map_err(|e| PluginError::DatabaseError(e.to_string()))?; + + tracing::debug!( + plugin_id, + entity = %entity, + "Flushed INSERT op" + ); + } + PendingOp::Update { + entity, + id, + data, + version, + } => { + let table_name = DynamicTableManager::table_name(plugin_id, entity); + let parsed_data: serde_json::Value = + serde_json::from_slice(data).unwrap_or_default(); + let id_uuid = id.parse::().map_err(|e| { + PluginError::ExecutionError(format!("无效的 ID: {}", e)) + })?; + let (sql, values) = DynamicTableManager::build_update_sql( + &table_name, + id_uuid, + tenant_id, + user_id, + &parsed_data, + *version as i32, + ); + txn.execute(Statement::from_sql_and_values( + sea_orm::DatabaseBackend::Postgres, + sql, + values, + )) + .await + .map_err(|e| PluginError::DatabaseError(e.to_string()))?; + + tracing::debug!( + plugin_id, + entity = %entity, + id = %id, + "Flushed UPDATE op" + ); + } + PendingOp::Delete { entity, id } => { + let table_name = DynamicTableManager::table_name(plugin_id, entity); + let id_uuid = id.parse::().map_err(|e| { + PluginError::ExecutionError(format!("无效的 ID: {}", e)) + })?; + let (sql, values) = + DynamicTableManager::build_delete_sql(&table_name, id_uuid, tenant_id); + txn.execute(Statement::from_sql_and_values( + sea_orm::DatabaseBackend::Postgres, + sql, + values, + )) + .await + .map_err(|e| PluginError::DatabaseError(e.to_string()))?; + + tracing::debug!( + plugin_id, + entity = %entity, + id = %id, + "Flushed DELETE op" + ); + } + PendingOp::PublishEvent { .. } => { + // 事件发布在事务提交后处理 + } + } + } + + // 提交事务 + txn.commit().await.map_err(|e| PluginError::DatabaseError(e.to_string()))?; + + // 事务提交成功后发布事件(best-effort,不阻塞主流程) + for op in ops { + if let PendingOp::PublishEvent { event_type, payload } = op { + let parsed_payload: serde_json::Value = + serde_json::from_slice(&payload).unwrap_or_default(); + let event = erp_core::events::DomainEvent::new( + &event_type, + tenant_id, + parsed_payload, + ); + event_bus.publish(event, db).await; + + tracing::debug!( + plugin_id, + event_type = %event_type, + "Flushed PUBLISH_EVENT op" + ); + } + } + + Ok(()) + } +} + +/// 插件信息摘要 +#[derive(Debug, Clone, serde::Serialize)] +pub struct PluginInfo { + pub id: String, + pub name: String, + pub version: String, +} diff --git a/crates/erp-plugin/src/entity/mod.rs b/crates/erp-plugin/src/entity/mod.rs new file mode 100644 index 0000000..0ae3634 --- /dev/null +++ b/crates/erp-plugin/src/entity/mod.rs @@ -0,0 +1,3 @@ +pub mod plugin; +pub mod plugin_entity; +pub mod plugin_event_subscription; diff --git a/crates/erp-plugin/src/entity/plugin.rs b/crates/erp-plugin/src/entity/plugin.rs new file mode 100644 index 0000000..a867b9e --- /dev/null +++ b/crates/erp-plugin/src/entity/plugin.rs @@ -0,0 +1,54 @@ +use sea_orm::entity::prelude::*; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)] +#[sea_orm(table_name = "plugins")] +pub struct Model { + #[sea_orm(primary_key, auto_increment = false)] + pub id: Uuid, + pub tenant_id: Uuid, + pub name: String, + #[sea_orm(column_name = "plugin_version")] + pub plugin_version: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub author: Option, + pub status: String, + pub manifest_json: serde_json::Value, + #[serde(skip)] + pub wasm_binary: Vec, + pub wasm_hash: String, + pub config_json: serde_json::Value, + #[serde(skip_serializing_if = "Option::is_none")] + pub error_message: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub installed_at: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub enabled_at: Option, + pub created_at: DateTimeUtc, + pub updated_at: DateTimeUtc, + #[serde(skip_serializing_if = "Option::is_none")] + pub created_by: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub updated_by: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub deleted_at: Option, + pub version: i32, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation { + #[sea_orm(has_many = "super::plugin_entity::Entity")] + PluginEntity, + #[sea_orm(has_many = "super::plugin_event_subscription::Entity")] + PluginEventSubscription, +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::PluginEntity.def() + } +} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/crates/erp-plugin/src/entity/plugin_entity.rs b/crates/erp-plugin/src/entity/plugin_entity.rs new file mode 100644 index 0000000..08ecf26 --- /dev/null +++ b/crates/erp-plugin/src/entity/plugin_entity.rs @@ -0,0 +1,41 @@ +use sea_orm::entity::prelude::*; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)] +#[sea_orm(table_name = "plugin_entities")] +pub struct Model { + #[sea_orm(primary_key, auto_increment = false)] + pub id: Uuid, + pub tenant_id: Uuid, + pub plugin_id: Uuid, + pub entity_name: String, + pub table_name: String, + pub schema_json: serde_json::Value, + pub created_at: DateTimeUtc, + pub updated_at: DateTimeUtc, + #[serde(skip_serializing_if = "Option::is_none")] + pub created_by: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub updated_by: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub deleted_at: Option, + pub version: i32, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation { + #[sea_orm( + belongs_to = "super::plugin::Entity", + from = "Column::PluginId", + to = "super::plugin::Column::Id" + )] + Plugin, +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::Plugin.def() + } +} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/crates/erp-plugin/src/entity/plugin_event_subscription.rs b/crates/erp-plugin/src/entity/plugin_event_subscription.rs new file mode 100644 index 0000000..de73dc1 --- /dev/null +++ b/crates/erp-plugin/src/entity/plugin_event_subscription.rs @@ -0,0 +1,30 @@ +use sea_orm::entity::prelude::*; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)] +#[sea_orm(table_name = "plugin_event_subscriptions")] +pub struct Model { + #[sea_orm(primary_key, auto_increment = false)] + pub id: Uuid, + pub plugin_id: Uuid, + pub event_pattern: String, + pub created_at: DateTimeUtc, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation { + #[sea_orm( + belongs_to = "super::plugin::Entity", + from = "Column::PluginId", + to = "super::plugin::Column::Id" + )] + Plugin, +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::Plugin.def() + } +} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/crates/erp-plugin/src/error.rs b/crates/erp-plugin/src/error.rs new file mode 100644 index 0000000..7e2968c --- /dev/null +++ b/crates/erp-plugin/src/error.rs @@ -0,0 +1,51 @@ +use erp_core::error::AppError; + +/// 插件模块错误类型 +#[derive(Debug, thiserror::Error)] +pub enum PluginError { + #[error("插件未找到: {0}")] + NotFound(String), + + #[error("插件已存在: {0}")] + AlreadyExists(String), + + #[error("无效的插件清单: {0}")] + InvalidManifest(String), + + #[error("无效的插件状态: 期望 {expected}, 实际 {actual}")] + InvalidState { expected: String, actual: String }, + + #[error("插件执行错误: {0}")] + ExecutionError(String), + + #[error("插件实例化错误: {0}")] + InstantiationError(String), + + #[error("插件 Fuel 耗尽: {0}")] + FuelExhausted(String), + + #[error("依赖未满足: {0}")] + DependencyNotSatisfied(String), + + #[error("数据库错误: {0}")] + DatabaseError(String), + + #[error("权限不足: {0}")] + PermissionDenied(String), +} + +impl From for AppError { + fn from(err: PluginError) -> Self { + match &err { + PluginError::NotFound(_) => AppError::NotFound(err.to_string()), + PluginError::AlreadyExists(_) => AppError::Conflict(err.to_string()), + PluginError::InvalidManifest(_) + | PluginError::InvalidState { .. } + | PluginError::DependencyNotSatisfied(_) => AppError::Validation(err.to_string()), + PluginError::PermissionDenied(_) => AppError::Forbidden(err.to_string()), + _ => AppError::Internal(err.to_string()), + } + } +} + +pub type PluginResult = Result; diff --git a/crates/erp-plugin/src/handler/data_handler.rs b/crates/erp-plugin/src/handler/data_handler.rs new file mode 100644 index 0000000..cc1d0b1 --- /dev/null +++ b/crates/erp-plugin/src/handler/data_handler.rs @@ -0,0 +1,194 @@ +use axum::Extension; +use axum::extract::{FromRef, Path, Query, State}; +use axum::response::Json; +use uuid::Uuid; + +use erp_core::error::AppError; +use erp_core::rbac::require_permission; +use erp_core::types::{ApiResponse, PaginatedResponse, TenantContext}; + +use crate::data_dto::{CreatePluginDataReq, PluginDataListParams, PluginDataResp, UpdatePluginDataReq}; +use crate::data_service::PluginDataService; +use crate::state::PluginState; + +#[utoipa::path( + get, + path = "/api/v1/plugins/{plugin_id}/{entity}", + params(PluginDataListParams), + responses( + (status = 200, description = "成功", body = ApiResponse>), + ), + security(("bearer_auth" = [])), + tag = "插件数据" +)] +/// GET /api/v1/plugins/{plugin_id}/{entity} — 列表 +pub async fn list_plugin_data( + State(state): State, + Extension(ctx): Extension, + Path((plugin_id, entity)): Path<(Uuid, String)>, + Query(params): Query, +) -> Result>>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.list")?; + + let page = params.page.unwrap_or(1); + let page_size = params.page_size.unwrap_or(20); + + let (items, total) = PluginDataService::list( + plugin_id, + &entity, + ctx.tenant_id, + page, + page_size, + &state.db, + ) + .await?; + + Ok(Json(ApiResponse::ok(PaginatedResponse { + data: items, + total, + page, + page_size, + total_pages: (total as f64 / page_size as f64).ceil() as u64, + }))) +} + +#[utoipa::path( + post, + path = "/api/v1/plugins/{plugin_id}/{entity}", + request_body = CreatePluginDataReq, + responses( + (status = 200, description = "创建成功", body = ApiResponse), + ), + security(("bearer_auth" = [])), + tag = "插件数据" +)] +/// POST /api/v1/plugins/{plugin_id}/{entity} — 创建 +pub async fn create_plugin_data( + State(state): State, + Extension(ctx): Extension, + Path((plugin_id, entity)): Path<(Uuid, String)>, + Json(req): Json, +) -> Result>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.admin")?; + + let result = PluginDataService::create( + plugin_id, + &entity, + ctx.tenant_id, + ctx.user_id, + req.data, + &state.db, + &state.event_bus, + ) + .await?; + + Ok(Json(ApiResponse::ok(result))) +} + +#[utoipa::path( + get, + path = "/api/v1/plugins/{plugin_id}/{entity}/{id}", + responses( + (status = 200, description = "成功", body = ApiResponse), + ), + security(("bearer_auth" = [])), + tag = "插件数据" +)] +/// GET /api/v1/plugins/{plugin_id}/{entity}/{id} — 详情 +pub async fn get_plugin_data( + State(state): State, + Extension(ctx): Extension, + Path((plugin_id, entity, id)): Path<(Uuid, String, Uuid)>, +) -> Result>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.list")?; + + let result = + PluginDataService::get_by_id(plugin_id, &entity, id, ctx.tenant_id, &state.db).await?; + + Ok(Json(ApiResponse::ok(result))) +} + +#[utoipa::path( + put, + path = "/api/v1/plugins/{plugin_id}/{entity}/{id}", + request_body = UpdatePluginDataReq, + responses( + (status = 200, description = "更新成功", body = ApiResponse), + ), + security(("bearer_auth" = [])), + tag = "插件数据" +)] +/// PUT /api/v1/plugins/{plugin_id}/{entity}/{id} — 更新 +pub async fn update_plugin_data( + State(state): State, + Extension(ctx): Extension, + Path((plugin_id, entity, id)): Path<(Uuid, String, Uuid)>, + Json(req): Json, +) -> Result>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.admin")?; + + let result = PluginDataService::update( + plugin_id, + &entity, + id, + ctx.tenant_id, + ctx.user_id, + req.data, + req.version, + &state.db, + &state.event_bus, + ) + .await?; + + Ok(Json(ApiResponse::ok(result))) +} + +#[utoipa::path( + delete, + path = "/api/v1/plugins/{plugin_id}/{entity}/{id}", + responses( + (status = 200, description = "删除成功"), + ), + security(("bearer_auth" = [])), + tag = "插件数据" +)] +/// DELETE /api/v1/plugins/{plugin_id}/{entity}/{id} — 删除 +pub async fn delete_plugin_data( + State(state): State, + Extension(ctx): Extension, + Path((plugin_id, entity, id)): Path<(Uuid, String, Uuid)>, +) -> Result>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.admin")?; + + PluginDataService::delete( + plugin_id, + &entity, + id, + ctx.tenant_id, + &state.db, + &state.event_bus, + ) + .await?; + + Ok(Json(ApiResponse::ok(()))) +} diff --git a/crates/erp-plugin/src/handler/mod.rs b/crates/erp-plugin/src/handler/mod.rs new file mode 100644 index 0000000..f82418d --- /dev/null +++ b/crates/erp-plugin/src/handler/mod.rs @@ -0,0 +1,2 @@ +pub mod data_handler; +pub mod plugin_handler; diff --git a/crates/erp-plugin/src/handler/plugin_handler.rs b/crates/erp-plugin/src/handler/plugin_handler.rs new file mode 100644 index 0000000..6e6d06d --- /dev/null +++ b/crates/erp-plugin/src/handler/plugin_handler.rs @@ -0,0 +1,379 @@ +use axum::Extension; +use axum::extract::{FromRef, Multipart, Path, Query, State}; +use axum::response::Json; +use uuid::Uuid; + +use erp_core::error::AppError; +use erp_core::rbac::require_permission; +use erp_core::types::{ApiResponse, PaginatedResponse, Pagination, TenantContext}; + +use crate::dto::{ + PluginHealthResp, PluginListParams, PluginResp, UpdatePluginConfigReq, +}; +use crate::service::PluginService; +use crate::state::PluginState; + +#[utoipa::path( + post, + path = "/api/v1/admin/plugins/upload", + request_body(content_type = "multipart/form-data"), + responses( + (status = 200, description = "上传成功", body = ApiResponse), + (status = 401, description = "未授权"), + ), + security(("bearer_auth" = [])), + tag = "插件管理" +)] +/// POST /api/v1/admin/plugins/upload — 上传插件 (multipart: wasm + manifest) +pub async fn upload_plugin( + State(state): State, + Extension(ctx): Extension, + mut multipart: Multipart, +) -> Result>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.admin")?; + + let mut wasm_binary: Option> = None; + let mut manifest_toml: Option = None; + + while let Some(field) = multipart.next_field().await.map_err(|e| { + AppError::Validation(format!("Multipart 解析失败: {}", e)) + })? { + let name = field.name().unwrap_or(""); + match name { + "wasm" => { + wasm_binary = Some(field.bytes().await.map_err(|e| { + AppError::Validation(format!("读取 WASM 文件失败: {}", e)) + })?.to_vec()); + } + "manifest" => { + let text = field.text().await.map_err(|e| { + AppError::Validation(format!("读取 Manifest 失败: {}", e)) + })?; + manifest_toml = Some(text); + } + _ => {} + } + } + + let wasm = wasm_binary.ok_or_else(|| { + AppError::Validation("缺少 wasm 文件".to_string()) + })?; + let manifest = manifest_toml.ok_or_else(|| { + AppError::Validation("缺少 manifest 文件".to_string()) + })?; + + let result = PluginService::upload( + ctx.tenant_id, + ctx.user_id, + wasm, + &manifest, + &state.db, + ) + .await?; + + Ok(Json(ApiResponse::ok(result))) +} + +#[utoipa::path( + get, + path = "/api/v1/admin/plugins", + params(PluginListParams), + responses( + (status = 200, description = "成功", body = ApiResponse>), + ), + security(("bearer_auth" = [])), + tag = "插件管理" +)] +/// GET /api/v1/admin/plugins — 列表 +pub async fn list_plugins( + State(state): State, + Extension(ctx): Extension, + Query(params): Query, +) -> Result>>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.list")?; + + let pagination = Pagination { + page: params.page, + page_size: params.page_size, + }; + + let (plugins, total) = PluginService::list( + ctx.tenant_id, + pagination.page.unwrap_or(1), + pagination.page_size.unwrap_or(20), + params.status.as_deref(), + params.search.as_deref(), + &state.db, + ) + .await?; + + Ok(Json(ApiResponse::ok(PaginatedResponse { + data: plugins, + total, + page: pagination.page.unwrap_or(1), + page_size: pagination.page_size.unwrap_or(20), + total_pages: (total as f64 / pagination.page_size.unwrap_or(20) as f64).ceil() as u64, + }))) +} + +#[utoipa::path( + get, + path = "/api/v1/admin/plugins/{id}", + responses( + (status = 200, description = "成功", body = ApiResponse), + ), + security(("bearer_auth" = [])), + tag = "插件管理" +)] +/// GET /api/v1/admin/plugins/{id} — 详情 +pub async fn get_plugin( + State(state): State, + Extension(ctx): Extension, + Path(id): Path, +) -> Result>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.list")?; + let result = PluginService::get_by_id(id, ctx.tenant_id, &state.db).await?; + Ok(Json(ApiResponse::ok(result))) +} + +#[utoipa::path( + get, + path = "/api/v1/admin/plugins/{id}/schema", + responses( + (status = 200, description = "成功"), + ), + security(("bearer_auth" = [])), + tag = "插件管理" +)] +/// GET /api/v1/admin/plugins/{id}/schema — 实体 schema +pub async fn get_plugin_schema( + State(state): State, + Extension(ctx): Extension, + Path(id): Path, +) -> Result>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.list")?; + let schema = PluginService::get_schema(id, ctx.tenant_id, &state.db).await?; + Ok(Json(ApiResponse::ok(schema))) +} + +#[utoipa::path( + post, + path = "/api/v1/admin/plugins/{id}/install", + responses( + (status = 200, description = "安装成功", body = ApiResponse), + ), + security(("bearer_auth" = [])), + tag = "插件管理" +)] +/// POST /api/v1/admin/plugins/{id}/install — 安装 +pub async fn install_plugin( + State(state): State, + Extension(ctx): Extension, + Path(id): Path, +) -> Result>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.admin")?; + let result = PluginService::install( + id, + ctx.tenant_id, + ctx.user_id, + &state.db, + &state.engine, + ) + .await?; + Ok(Json(ApiResponse::ok(result))) +} + +#[utoipa::path( + post, + path = "/api/v1/admin/plugins/{id}/enable", + responses( + (status = 200, description = "启用成功", body = ApiResponse), + ), + security(("bearer_auth" = [])), + tag = "插件管理" +)] +/// POST /api/v1/admin/plugins/{id}/enable — 启用 +pub async fn enable_plugin( + State(state): State, + Extension(ctx): Extension, + Path(id): Path, +) -> Result>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.admin")?; + let result = PluginService::enable( + id, + ctx.tenant_id, + ctx.user_id, + &state.db, + &state.engine, + ) + .await?; + Ok(Json(ApiResponse::ok(result))) +} + +#[utoipa::path( + post, + path = "/api/v1/admin/plugins/{id}/disable", + responses( + (status = 200, description = "停用成功", body = ApiResponse), + ), + security(("bearer_auth" = [])), + tag = "插件管理" +)] +/// POST /api/v1/admin/plugins/{id}/disable — 停用 +pub async fn disable_plugin( + State(state): State, + Extension(ctx): Extension, + Path(id): Path, +) -> Result>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.admin")?; + let result = PluginService::disable( + id, + ctx.tenant_id, + ctx.user_id, + &state.db, + &state.engine, + ) + .await?; + Ok(Json(ApiResponse::ok(result))) +} + +#[utoipa::path( + post, + path = "/api/v1/admin/plugins/{id}/uninstall", + responses( + (status = 200, description = "卸载成功", body = ApiResponse), + ), + security(("bearer_auth" = [])), + tag = "插件管理" +)] +/// POST /api/v1/admin/plugins/{id}/uninstall — 卸载 +pub async fn uninstall_plugin( + State(state): State, + Extension(ctx): Extension, + Path(id): Path, +) -> Result>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.admin")?; + let result = PluginService::uninstall( + id, + ctx.tenant_id, + ctx.user_id, + &state.db, + &state.engine, + ) + .await?; + Ok(Json(ApiResponse::ok(result))) +} + +#[utoipa::path( + delete, + path = "/api/v1/admin/plugins/{id}", + responses( + (status = 200, description = "清除成功"), + ), + security(("bearer_auth" = [])), + tag = "插件管理" +)] +/// DELETE /api/v1/admin/plugins/{id} — 清除(软删除) +pub async fn purge_plugin( + State(state): State, + Extension(ctx): Extension, + Path(id): Path, +) -> Result>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.admin")?; + PluginService::purge(id, ctx.tenant_id, ctx.user_id, &state.db).await?; + Ok(Json(ApiResponse::ok(()))) +} + +#[utoipa::path( + get, + path = "/api/v1/admin/plugins/{id}/health", + responses( + (status = 200, description = "健康检查", body = ApiResponse), + ), + security(("bearer_auth" = [])), + tag = "插件管理" +)] +/// GET /api/v1/admin/plugins/{id}/health — 健康检查 +pub async fn health_check_plugin( + State(state): State, + Extension(ctx): Extension, + Path(id): Path, +) -> Result>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.list")?; + let result = PluginService::health_check(id, ctx.tenant_id, &state.db, &state.engine).await?; + Ok(Json(ApiResponse::ok(result))) +} + +#[utoipa::path( + put, + path = "/api/v1/admin/plugins/{id}/config", + request_body = UpdatePluginConfigReq, + responses( + (status = 200, description = "更新成功", body = ApiResponse), + ), + security(("bearer_auth" = [])), + tag = "插件管理" +)] +/// PUT /api/v1/admin/plugins/{id}/config — 更新配置 +pub async fn update_plugin_config( + State(state): State, + Extension(ctx): Extension, + Path(id): Path, + Json(req): Json, +) -> Result>, AppError> +where + PluginState: FromRef, + S: Clone + Send + Sync + 'static, +{ + require_permission(&ctx, "plugin.admin")?; + let result = PluginService::update_config( + id, + ctx.tenant_id, + ctx.user_id, + req.config, + req.version, + &state.db, + ) + .await?; + Ok(Json(ApiResponse::ok(result))) +} diff --git a/crates/erp-plugin/src/host.rs b/crates/erp-plugin/src/host.rs new file mode 100644 index 0000000..d163e8c --- /dev/null +++ b/crates/erp-plugin/src/host.rs @@ -0,0 +1,170 @@ +use std::collections::HashMap; + +use uuid::Uuid; +use wasmtime::StoreLimits; + +use crate::erp::plugin::host_api; + +/// 待刷新的写操作 +#[derive(Debug)] +pub enum PendingOp { + Insert { + id: String, + entity: String, + data: Vec, + }, + Update { + entity: String, + id: String, + data: Vec, + version: i64, + }, + Delete { + entity: String, + id: String, + }, + PublishEvent { + event_type: String, + payload: Vec, + }, +} + +/// Host 端状态 — 绑定到每个 WASM Store 实例 +/// +/// 采用延迟执行模式: +/// - 读操作 (db_query, config_get, current_user) → 调用前预填充 +/// - 写操作 (db_insert, db_update, db_delete, event_publish) → 入队 pending_ops +/// - WASM 调用结束后由 engine 刷新 pending_ops 执行真实 DB 操作 +pub struct HostState { + pub(crate) limits: StoreLimits, + #[allow(dead_code)] + pub(crate) tenant_id: Uuid, + #[allow(dead_code)] + pub(crate) user_id: Uuid, + pub(crate) permissions: Vec, + pub(crate) plugin_id: String, + // 预填充的读取缓存 + pub(crate) query_results: HashMap>, + pub(crate) config_cache: HashMap>, + pub(crate) current_user_json: Vec, + // 待刷新的写操作 + pub(crate) pending_ops: Vec, + // 日志 + pub(crate) logs: Vec<(String, String)>, +} + +impl HostState { + pub fn new( + plugin_id: String, + tenant_id: Uuid, + user_id: Uuid, + permissions: Vec, + ) -> Self { + let current_user = serde_json::json!({ + "id": user_id.to_string(), + "tenant_id": tenant_id.to_string(), + }); + Self { + limits: wasmtime::StoreLimitsBuilder::new().build(), + tenant_id, + user_id, + permissions, + plugin_id, + query_results: HashMap::new(), + config_cache: HashMap::new(), + current_user_json: serde_json::to_vec(¤t_user).unwrap_or_default(), + pending_ops: Vec::new(), + logs: Vec::new(), + } + } +} + +// 实现 bindgen 生成的 Host trait — 插件调用 Host API 的入口 +impl host_api::Host for HostState { + fn db_insert(&mut self, entity: String, data: Vec) -> Result, String> { + let id = Uuid::now_v7().to_string(); + let response = serde_json::json!({ + "id": id, + "entity": entity, + "status": "queued", + }); + self.pending_ops.push(PendingOp::Insert { + id: id.clone(), + entity, + data, + }); + serde_json::to_vec(&response).map_err(|e| e.to_string()) + } + + fn db_query( + &mut self, + entity: String, + _filter: Vec, + _pagination: Vec, + ) -> Result, String> { + self.query_results + .get(&entity) + .cloned() + .ok_or_else(|| format!("实体 '{}' 的查询结果未预填充", entity)) + } + + fn db_update( + &mut self, + entity: String, + id: String, + data: Vec, + version: i64, + ) -> Result, String> { + let response = serde_json::json!({ + "id": id, + "entity": entity, + "version": version + 1, + "status": "queued", + }); + self.pending_ops.push(PendingOp::Update { + entity, + id, + data, + version, + }); + serde_json::to_vec(&response).map_err(|e| e.to_string()) + } + + fn db_delete(&mut self, entity: String, id: String) -> Result<(), String> { + self.pending_ops.push(PendingOp::Delete { entity, id }); + Ok(()) + } + + fn event_publish(&mut self, event_type: String, payload: Vec) -> Result<(), String> { + self.pending_ops.push(PendingOp::PublishEvent { + event_type, + payload, + }); + Ok(()) + } + + fn config_get(&mut self, key: String) -> Result, String> { + self.config_cache + .get(&key) + .cloned() + .ok_or_else(|| format!("配置项 '{}' 未预填充", key)) + } + + fn log_write(&mut self, level: String, message: String) { + tracing::info!( + plugin = %self.plugin_id, + level = %level, + "Plugin log: {}", + message + ); + self.logs.push((level, message)); + } + + fn current_user(&mut self) -> Result, String> { + Ok(self.current_user_json.clone()) + } + + fn check_permission(&mut self, permission: String) -> Result { + Ok(self.permissions.contains(&permission)) + } +} diff --git a/crates/erp-plugin/src/lib.rs b/crates/erp-plugin/src/lib.rs new file mode 100644 index 0000000..bc3c4b6 --- /dev/null +++ b/crates/erp-plugin/src/lib.rs @@ -0,0 +1,24 @@ +//! ERP WASM 插件运行时 — 生产级 Host API +//! +//! 完整插件管理链路:加载 → 初始化 → 运行 → 停用 → 卸载 + +// bindgen! 生成类型化绑定(包含 Host trait 和 PluginWorld 类型) +// 生成: erp::plugin::host_api::Host trait, PluginWorld 类型 +wasmtime::component::bindgen!({ + path: "wit/plugin.wit", + world: "plugin-world", +}); + +pub mod data_dto; +pub mod data_service; +pub mod dynamic_table; +pub mod dto; +pub mod engine; +pub mod entity; +pub mod error; +pub mod handler; +pub mod host; +pub mod manifest; +pub mod module; +pub mod service; +pub mod state; diff --git a/crates/erp-plugin/src/manifest.rs b/crates/erp-plugin/src/manifest.rs new file mode 100644 index 0000000..ed6a4e4 --- /dev/null +++ b/crates/erp-plugin/src/manifest.rs @@ -0,0 +1,262 @@ +use serde::{Deserialize, Serialize}; + +use crate::error::{PluginError, PluginResult}; + +/// 插件清单 — 从 TOML 文件解析 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PluginManifest { + pub metadata: PluginMetadata, + pub schema: Option, + pub events: Option, + pub ui: Option, + pub permissions: Option>, +} + +/// 插件元数据 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PluginMetadata { + pub id: String, + pub name: String, + pub version: String, + #[serde(default)] + pub description: String, + #[serde(default)] + pub author: String, + #[serde(default)] + pub min_platform_version: Option, + #[serde(default)] + pub dependencies: Vec
+ {JSON.stringify(healthDetail, null, 2)} +