mm_os
Version:
MM_OS服务端架构,用于快速构建应用程序,支持网站建设、小程序后台、AI应用、物联网(IOT/AIOT)、游戏服务端等多种场景。
506 lines (421 loc) • 14 kB
Markdown
# MM_OS Server Architecture
[](https://badge.fury.io/js/mm_os)
[](https://www.npmjs.com/package/mm_os)
[](https://gitee.com/qiuwenwu91/mm_os/blob/master/LICENSE)
## Project Introduction
MM_OS is a lightweight server architecture that provides a complete server development framework, including support for multiple communication protocols such as Web, WebSocket, MQTT, Socket, as well as rich components and modules.
**Use Cases:**
- **Website Development**: Quickly build enterprise websites, e-commerce platforms, content management systems
- **Mini Programs**: Backend services for WeChat Mini Programs, Alipay Mini Programs, etc.
- **AI Applications**: AI API services, intelligent assistants, machine learning inference services
- **IoT/AIoT**: IoT device management, sensor data collection, smart hardware control
- **Game Servers**: Small-to-medium game servers, real-time battle games, game backend management
Supports **AI, GAME, IOT, AIOT, Games, Internet of Things, Mini Programs, Website Development** and other application scenarios.
## Core Features
- **Multi-protocol support**: Web, WebSocket, MQTT, Socket
- **Modular design**: Application, Module, Middleware, Notifier, Sender, Pusher
- **Infrastructure**: Database, Cache, Log, File Management
- **Event-driven**: Asynchronous processing based on event bus
- **Plugin system**: Support for function extension
## Design Philosophy: Configuration and Logic Separation
The core design principle of MM_OS framework is **separation of configuration and logic**. Both `core` modules and `com` components follow a unified structure:
### Module Composition
Each module consists of the following files:
| File Type | File Name | Purpose |
|-----------|-----------|---------|
| **Configuration** | `config.tpl.json` / `com.json` | Declarative definition of module configuration and metadata |
| **Logic** | `index.js` / `script.tpl.js` | Implementation of business logic and functionality |
| **Driver** | `drive.js` (optional) | Protocol driver and adapter logic |
### Design Advantages
**1. Declarative Configuration**
- JSON files define module metadata and configuration declaratively
- Module registration and parameter configuration can be completed without writing code
- Easy to manage and configure through visual tools
**2. Logic and Configuration Decoupling**
- Configuration changes do not require code modification, reducing maintenance costs
- The same business logic can be reused with different configurations
- Configuration files can be independently version-managed and deployed
**3. Automation Capabilities**
- Framework can automatically scan JSON configurations for module registration
- Automatically generate documentation and configuration forms
- Automatically perform parameter validation, reducing repetitive code
**4. Hot Update Support**
- Configuration files can be hot-updated without restarting the service
- Supports dynamic addition/modification of module configurations
**5. Team Collaboration Optimization**
- Configuration personnel and developers can work in parallel
- Non-developers can also participate in module configuration
- Unified configuration format reduces communication costs
### Module Types
**core modules**: Framework base modules including app, controller, model, logic, plugin, service, view, middleware, etc.
**com components**: Reusable common components including sql, cache, api, event, task, static, template, MQTT, Socket, etc.
## Quick Start
### Installation
```bash
npm install mm_os
```
### Basic Usage
```javascript
const { MM_os } = require('mm_os');
// Set runtime path
$.run_path = __dirname;
// Create server instance
const server = new MM_os({
web: {
host: '0.0.0.0',
port: 8000,
socket: true
},
mysql: {
host: '127.0.0.1',
port: 3306,
user: 'root',
password: '123456',
database: 'test'
},
cache: {
way: 'memory'
}
});
// Start server
async function startServer() {
await server.init();
await server.start();
console.log('Server started successfully');
}
startServer();
```
## Project Directory Structure
Projects developed with MM_OS framework follow a standardized directory structure:
```
├── app/ # Application directory containing multiple apps
│ ├── app_name/ # Application name
│ │ ├── event_api/ # Event API directory
│ │ │ ├── web/ # Web route handling
│ │ │ │ ├── event.json # Event configuration
│ │ │ │ └── main.js # Entry file
│ │ │ ├── api/ # API route
│ │ │ ├── client/ # Client API route
│ │ │ └── manage/ # Management backend route
│ │ ├── plugin/ # Plugin directory
│ │ │ ├── main/ # Main plugins (business logic)
│ │ │ │ └── api_{app}_{channel}/{api_name}/
│ │ │ │ ├── api.json # API configuration
│ │ │ │ ├── param.json # Parameter validation config
│ │ │ │ └── index.js # API implementation
│ │ │ └── server/ # Server plugins (data management)
│ │ ├── pendant/ # Pendant component directory
│ │ ├── static/ # Static resources
│ │ ├── app.json # Application configuration
│ │ └── index.js # Application entry
├── cache/ # Cache configuration directory
├── com/ # Common components directory
├── config/ # Global configuration directory
│ ├── local.json # Local configuration
│ ├── development.json # Development configuration
│ └── production.json # Production configuration
├── db/ # Database files directory (SQLite, etc.)
├── static/ # Global static resources
├── index.js # Project entry
└── config.json # Main configuration file
```
## Application Development
### Create Application
Each application contains independent business logic. Application configuration file `app.json`:
```json
{
"name": "user",
"version": "1.0",
"title": "User",
"description": "User authentication service",
"author": "developer",
"scope": "server",
"main": "./index.js",
"func_name": "main",
"sort": 10,
"state": 1,
"sql": {
"way": "mysql",
"mysql": {
"host": "127.0.0.1",
"port": 3306,
"user": "root",
"password": "password",
"database": "example"
}
},
"cache": {
"way": "redis"
}
}
```
### Event Route Configuration (event.json)
Define application routing rules:
```json
{
"/api/user/list": {
"method": "GET",
"title": "Get User List",
"auth": false
},
"/api/user/create": {
"method": "POST",
"title": "Create User",
"auth": true
},
"/user/*": {
"method": "ALL",
"title": "User Page Routes",
"auth": false
}
}
```
### Create API Interface
API is the core component of MM_OS framework. Each API consists of three files:
#### 1. api.json - API Configuration
```json
{
"name": "user_sign_in",
"title": "User Login",
"description": "User login interface, supports username/password, phone/code, and social login",
"path": "/api/user/sign_in",
"type": "api",
"method": "ALL",
"cache": 0,
"param_path": "./param.json",
"check_param": true,
"sort": 1
}
```
**api.json Field Description:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| name | string | Yes | Unique API identifier |
| title | string | Yes | Display name |
| description | string | No | Description |
| path | string | Yes | Access path |
| type | string | Yes | Type, fixed as "api" |
| method | string | Yes | HTTP method: GET, POST, ALL |
| cache | number | No | Cache time in seconds, 0 means no cache |
| param_path | string | No | Parameter validation config path |
| check_param | boolean | No | Whether to validate parameters |
| sort | number | No | Sort order |
#### 2. param.json - Parameter Validation Configuration
```json
{
"title": "User Login Validation Model",
"name": "user_sign_in",
"filter": true,
"get": {
"query": ["account", "password", "code"],
"query_required": ["account"]
},
"post": {
"body": ["account", "password", "code", "phone"],
"body_required": ["account"]
},
"list": [
{
"name": "account",
"title": "Account",
"type": "string",
"string": {
"min": 5,
"max": 16,
"format": "username"
}
},
{
"name": "password",
"title": "Password",
"type": "string",
"string": {
"min": 32,
"max": 32,
"format": "password"
}
},
{
"name": "phone",
"title": "Phone Number",
"type": "string",
"string": {
"format": "phone",
"range": [11, 11]
}
},
{
"name": "code",
"title": "Verification Code",
"type": "string"
}
]
}
```
**param.json Field Description:**
| Field | Type | Description |
|-------|------|-------------|
| title | string | Validation model name |
| name | string | Model identifier |
| filter | boolean | Whether to enable filtering |
| get.query | array | Acceptable query parameters for GET |
| get.query_required | array | Required parameters for GET |
| post.body | array | Acceptable body parameters for POST |
| post.body_required | array | Required parameters for POST |
| list | array | Parameter validation rules |
**Supported Parameter Types:**
- `string`: String type, supports format (phone, email, username, password), min, max, range
- `number`: Number type, supports min, max, range
- `boolean`: Boolean type
- `array`: Array type
- `object`: Object type
#### 3. index.js - API Implementation
```javascript
/**
* User Login API
* @param {Object} ctx HTTP context
* @param {Object} db Data manager
* @return {Object} Execution result
*/
async function main(ctx, db) {
// Get request parameters
var params = ctx.method === "POST" ? ctx.request.body : ctx.request.query;
// Validate parameters
var account = params['account'];
var password = params['password'];
if (!account) {
return { code: 30001, message: 'Account cannot be empty' };
}
if (!password) {
return { code: 30002, message: 'Password cannot be empty' };
}
// Query user
db.table = "user_account";
db.key = "user_id";
var users = await db.get({ username: account });
if (users.length === 0) {
return { code: 60001, message: 'User does not exist' };
}
var user = users[0];
// Validate password
var pass = (password + user.salt).md5();
if (pass !== user.password) {
return { code: 30003, message: 'Incorrect password' };
}
// Set login state
ctx.session.user = user;
// Return result
return {
code: 200,
message: 'Login successful',
data: {
user_id: user.user_id,
username: user.username,
nickname: user.nickname
}
};
}
exports.main = main;
```
### Event Handler Entry (main.js)
```javascript
// Use API manager
var api = $.admin.api('user_web', 'Website - User Management');
api.call('update');
/**
* @description Main handler function
* @param {Object} ctx HTTP context
* @param {Object} db Data manager
* @return {Object} Execution result
*/
async function main(ctx, db) {
// Set database connection
$.push(db, $.admin.sql('sys').db(), true);
// Use template engine
db.tpl = new $.Tpl();
var bag = db.tpl.viewBag;
bag.path = ctx.path;
bag.query = ctx.query;
// Execute API routing
return await api.run(ctx, db);
}
exports.main = main;
```
## Configuration
MM_OS supports multiple configuration options:
- **web**: Web server configuration
- **mysql**: MySQL database configuration
- **sqlite**: SQLite database configuration
- **cache**: Cache configuration (`way` specifies type: `memory`, `redis`, `mongodb`)
- **redis**: Redis cache configuration
- **mongodb**: MongoDB configuration
- **mqtt**: MQTT server configuration
- **socket**: Socket server configuration
### Configuration File Example
```json
{
"name": "mos",
"title": "Server System",
"log": {
"level": "debug",
"file": true
},
"web": {
"state": true,
"host": "0.0.0.0",
"port": 8000,
"socket": false,
"cos": {
"status": true,
"origin": "*"
},
"static": {
"state": 1,
"root": "./static"
}
},
"mysql": {
"host": "127.0.0.1",
"port": 3306,
"user": "root",
"password": "password",
"database": "example"
},
"cache": {
"way": "redis"
},
"redis": {
"host": "localhost",
"port": 6379,
"password": "",
"database": 0
}
}
```
## Global Objects
MM_OS provides rich global objects for development:
### `$` Object
| Property | Description |
|----------|-------------|
| `$.sql` | Database operation object |
| `$.cache` | Cache operation object |
| `$.log` | Log object |
| `$.admin` | Admin object |
| `$.eventer` | Event bus |
| `$.config` | Configuration manager |
| `$.Tpl` | Template engine class |
| `$.ret` | Response utility |
| `$.run_path` | Current runtime path |
### `$.ret` Response Utility
```javascript
// Success response
return $.ret.body(data); // { code: 200, message: 'success', data: data }
// Error response
return $.ret.error(code, message); // { code: code, message: message }
```
## Development Guide
1. **Install dependencies**: `npm install`
2. **Development and debugging**: `npm run dev`
3. **Run tests**: `npm run test`
## License
ISC