aim

module
v0.0.0-...-34eca9f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: MIT

README

AIM — 分布式多人在线即时通讯系统

AIM 是一个基于 go-zero 微服务架构的分布式即时通讯系统,内置可自部署的 AI 助手(Bot OpenAPI)。


核心特性

通信能力
  • 实时消息:WebSocket + Protobuf 帧协议,支持私聊与群聊
  • 已读回执 & 输入状态:消息级已读追踪、typing indicator 实时推送
  • 多端同步:基于 DeviceId 的多设备登录,消息一致投递
  • 断线重连:WS 帧等待队列 + 重放机制
雪花ID
  • 小回拨: 时间戳不变序列号递增
  • 大回拨: 等待系统时钟追赶/直接抛出错误
事务消息
  • 需要与业务事务同生共死的事件(user-created、群管理通知、附件上传完成)走 RocketMQ 事务消息:half message → 本地事务(业务行 + event_journal 行)→ commit/rollback
  • commit 丢失时由 broker 回查 event_journal 决定最终结果,因此不再需要发件箱轮询器
穿透 读/写 缓存模式
  • 由缓存组件负责读取数据库并回写缓存
  • 内存 + redis 双层缓存
  • 基于 go-zero 缓存组件 封装
  • 内置 singleflight 语义,防止缓存击穿
  • 内置 key ttl 随机抖动,防止缓存雪崩
限流算法
  • 基于 redis zset(sorted set) 数据结构的滑动窗口算法
熔断器
Bot OpenAPI
  • 第三方 Bot 接入:独立 /api/bot/v1 路由,Token 鉴权 + Webhook 事件推送
  • Bot 会话操作:发消息、查历史、获取成员、标记已读
  • 用户侧 Bot 管理:创建/编辑/启用/禁用 Bot、Token 生命周期管理
  • 详见 Bot SDK 文档 及 aim-bot-domain Skill
社交功能
  • 好友管理:申请/接受/拒绝 + 自定义标签体系
  • 群组管理:创建、加人/踢人、群主转让、管理员授予/撤销、退群、解散
  • 聚合搜索:统一搜索用户、好友、群组、消息内容
  • 在线状态:Presence 状态广播
附件系统
  • 预签名直传 SeaweedFS(S3 协议),支持 image/video/audio/file
  • 异步解析媒体元数据,自动转码生成缩略图
  • 详见 aim-attachment-domain Skill
可观测性
  • OpenTelemetry 全链路追踪 → Grafana Tempo
  • Prometheus 指标 → Grafana 仪表盘
  • Loki + Promtail 日志聚合
  • 详见 aim-docker-datastore Skill

技术架构

架构图
graph TB
    subgraph Client
        Web[Web 客户端]
        Desktop[桌面客户端]
    end
    subgraph Gateway
        GW[aim-gateway<br/>REST + WebSocket]
    end
    subgraph "Business Services"
        Auth[aim-auth<br/>认证服务]
        Logic[aim-logic<br/>业务逻辑服务]
        Attachment[aim-attachment<br/>附件服务]
    end
    subgraph CoreDomain
        Core[aim-core<br/>消息投递域]
        DataParsing[aim-data-parsing<br/>数据解析]
    end
    subgraph Infrastructure
        RocketMQ[(RocketMQ)]
        Redis[(Redis Stack)]
        PG[(PostgreSQL)]
        SeaweedFS[SeaweedFS]
        Etcd[etcd]
    end

    Web -->|WS/REST| GW
    Desktop -->|WS/REST| GW
    GW -->|gRPC| Auth
    GW -->|gRPC| Logic
    GW -->|gRPC| Core
    GW -->|gRPC| Attachment
    Core -->|gRPC| Logic

    GW -->|produce presence/typing/read-receipt| RocketMQ
    Core -->|produce FIFO transfer| RocketMQ
    RocketMQ -->|consume| Core
    Auth -.->|事务消息 + 本地事务<br/>写 event_journal| PG
    Logic -.->|事务消息 + 本地事务<br/>写 event_journal| PG
    Attachment -.->|事务消息 + 本地事务<br/>写 event_journal| PG

    RocketMQ -->|consume| Logic
    RocketMQ -->|consume| DataParsing

    RocketMQ -.->|回查 event_journal| Auth
    RocketMQ -.->|回查 event_journal| Logic
    RocketMQ -.->|回查 event_journal| Attachment

    Auth --> Redis & PG
    Logic --> Redis & PG
    Core --> Redis & PG
    Attachment --> Redis & PG
    DataParsing --> Redis & PG

    Web -.->|预签名直传| SeaweedFS
    Desktop -.->|预签名直传| SeaweedFS
    GW -->|签发预签名 URL| SeaweedFS
    Attachment -->|签发预签名 URL| SeaweedFS

    style GW fill:#1a73e8,color:#fff
    style Core fill:#e8710a,color:#fff
    style Auth fill:#34a853,color:#fff
    style Logic fill:#9b59b6,color:#fff
    style Attachment fill:#f9ab00,color:#fff
    style DataParsing fill:#4285f4,color:#fff
微服务划分
服务 职责
aim-gateway 对外入口,REST API 代理 + WebSocket 连接管理,JWT 验签
aim-auth 注册/登录、JWT 签发与刷新、多设备会话管理;注册成功后以事务消息发布 UserCreatedEvent
aim-core 消息路由与投递,RocketMQ 消费者集群
aim-logic 用户/好友/群组/Bot 业务逻辑、聚合搜索
aim-attachment 附件上传预签名、元数据管理、下载授权
aim-data-parsing 异步提取附件媒体元数据、生成缩略图

依赖约束:Logic 绝不导入 Core;客户端只与 Gateway 通信。详见 aim-repo-mapping Skill。


技术栈

层次 技术
语言 Go 1.26
微服务框架 go-zero v1.10.1
WebSocket coder/websocket + Protobuf 帧协议
RPC Protobuf / gRPC
消息队列 RocketMQ 5(FIFO topic 按 conversation_id 保序、事务消息、gRPC Proxy)
缓存 Redis Stack
持久化 PostgreSQL(GORM DAO)
文件存储 SeaweedFS(S3 协议)
注册中心 etcd
可观测性 OpenTelemetry + Prometheus + Loki → Grafana

压测

    # 启动压测环境
    cd /home/hpxx/aim/dev-tool && docker compose up -d

    # 500用户注册 + 限速50RPS + 10s渐进加压
    python benchmark.py register --users 500 --rps 50 --ramp-up 10

    # 50用户WS消息压测,每用户500条
    python benchmark.py ws-message --users 50 --messages-per-user 500 --quiet

    # 100用户混合负载60秒
    python benchmark.py mixed --users 100 --duration 60 --rps 200 --output report.json
总体概况
场景 用户数 总请求 成功 失败 成功率 耗时
register 100 100 100 0 100% 40.9s
friend-chain (加好友) 38 对 38 38 0 100% 0.0s
friend-chain (接受) 38 对 38 38 0 100% 0.0s
ws-message 19 对 380 380 0 100% 40.3s
mixed 100 41,094 41,094 0 100% 30.0s
吞吐量
场景 平均 QPS
register 2.4
friend-chain (加好友) 937.9
friend-chain (接受) 1,045.1
ws-message 9.4
mixed 1,368.9
延迟分布 (ms)
场景 Min Avg Max P50 P90 P95 P99
register 82.0 91.8 122.3 90.8 98.5 100.7 122.3
friend-chain (加好友) 6.3 13.7 22.7 13.8 20.4 20.8 22.7
friend-chain (接受) 5.4 10.8 20.7 9.8 16.6 19.5 20.7
ws-message 1,470 2,020 2,270 2,240 2,260 2,260 2,260
mixed 0.4 6.0 18.9 5.3 8.6 9.4 11.2

快速开始

环境准备
  • Go ≥ 1.26
  • Docker + Docker Compose
本地部署
# 启动基础设施 + 业务服务
docker compose --env-file deploy/env/local.env \
  -f deploy/compose/base.yaml \
  -f deploy/compose/dev.yaml \
  up -d --build

# (可选)启动可观测性
docker compose --env-file deploy/env/local.env \
  -f deploy/compose/base.yaml \
  -f deploy/compose/dev.yaml \
  -f deploy/compose/observability.yaml \
  up -d --build

# 本地构建
go mod tidy
go build ./...

# 启动前端页面
cd frontend/ && bun run dev

部署拆分说明见 deploy/README.md。


项目结构

aim/
├── app/
│   ├── auth/rpc/          # 认证服务
│   ├── core/rpc/          # 消息投递服务
│   ├── gateway/api/       # 对外入口(REST + WebSocket)
│   ├── logic/rpc/         # 业务逻辑服务
│   ├── attachment/rpc/    # 附件服务
│   ├── data_parsing/      # 数据解析服务
│   └── shared/            # 进程内共享包
├── bot_sdk/               # AIM Bot Go SDK
├── dev-tool/              # 开发与压测工具 CLI
├── deploy/                # 部署编排与环境配置
├── docs/                  # 客户端开发与协议规范文档
├── shared/proto/          # Protobuf 协议定义
├── skills/                # 领域 Skill 文档
├── .githooks/             # Git pre-commit hook(自动格式化)
└── docker-compose.yaml    # 本地兼容入口

---

## API 文档

API 契约定义在 [`app/gateway/api/gateway.api`](app/gateway/api/gateway.api),采用 **Spec-first** 模式。

| 分组          | 前缀                 | 说明                         |
| ------------- | -------------------- | ---------------------------- |
| 认证          | `/api/auth`          | 注册、登录、刷新 Token、注销 |
| 用户          | `/api/users`         | 用户查询、好友申请           |
| 会话          | `/api/conversations` | 会话 CRUD、群管理、历史消息  |
| 好友          | `/api/friends`       | 好友列表、标签管理           |
| 搜索          | `/api/search`        | 聚合搜索                     |
| 附件          | `/api/attachments`   | 上传/下载/查询               |
| Bot OpenAPI   | `/api/bot/v1`        | 第三方 Bot 接口              |
| 用户 Bot 管理 | `/api/user/bots`     | Bot 创建/管理/Token 管理     |

### 开发测试工具

内置 `aim-dev-tool`(Python CLI),支持 REST/WS 调试、并发压测。详见 [aim-dev-tool Skill](skills/aim-dev-tool/SKILL.md)。

---

## 测试与代码质量

```bash
go test ./...                       # 运行全部测试(60 个测试包,103 个测试文件)
go test -coverprofile=coverage.out ./...  # 覆盖率
golangci-lint run                   # 代码检查
goctl api validate                  # API 契约校验
Pre-commit 钩子

项目内置 Git pre-commit hook(位于 .githooks/),提交前自动格式化 Go 代码:

# 在项目根目录执行一次即可激活:
git config core.hooksPath .githooks

钩子使用 gofumpt(优先)/ gofmt(fallback)格式化 staged Go 文件, 并在 go.mod 变更时自动执行 go mod tidy。

开发指南

  • Spec-first:REST 先改 .api,RPC 先改 .proto,再 goctl/protoc 生成
  • Skill 驱动开发:领域知识文档化为 Skill,Agent 渐进式加载
  • 数据模型:使用 GORM DAO;schema 源文件在 app/*/model/migrations,结构体在 model/orm,查询在 model/dao
  • 错误处理:业务错误使用 errorx.NewCodeError
  • 详细约定见 AGENTS.md

未来规划


相关项目

项目 说明
aim-desktop 桌面客户端
echo 官方 RAG 知识库 Bot
bot_sdk Bot SDK 文档

开源协议

本项目基于 MIT 协议开源。

Directories

Path Synopsis
app
attachment/rpc command
attachment/rpc/internal/service
Package service implements the attachment domain: presigned uploads, object verification, download authorization and the transactional attachment.uploaded event.
Package service implements the attachment domain: presigned uploads, object verification, download authorization and the transactional attachment.uploaded event.
auth/rpc command
auth/rpc/internal/svc/svctest
Package svctest builds ServiceContext values for tests without dialing Postgres or Redis.
Package svctest builds ServiceContext values for tests without dialing Postgres or Redis.
auth/rpc/model/dao
Package dao is the GORM data-access layer for the aim_auth database.
Package dao is the GORM data-access layer for the aim_auth database.
auth/rpc/model/orm
Package orm holds GORM model definitions for the aim_auth database.
Package orm holds GORM model definitions for the aim_auth database.
core/rpc command
core/rpc/internal/push
Package push owns core's outbound side: resolving which gateway nodes hold a user's connections and fanning a push out to them.
Package push owns core's outbound side: resolving which gateway nodes hold a user's connections and fanning a push out to them.
data_parsing command
gateway/api command
gateway/api/internal/authctx
Package authctx carries the authenticated caller through an HTTP request.
Package authctx carries the authenticated caller through an HTTP request.
gateway/api/internal/botctx
Package botctx defines the Identity that the gateway BotAuth middleware injects into request context after a successful Bot OpenAPI token check.
Package botctx defines the Identity that the gateway BotAuth middleware injects into request context after a successful Bot OpenAPI token check.
gateway/api/internal/fanout
Package fanout owns best-effort pushes to the connections this gateway node holds; the broker/core path remains the cross-node path.
Package fanout owns best-effort pushes to the connections this gateway node holds; the broker/core path remains the cross-node path.
gateway/api/internal/handler/ws
Package wshandler implements the gateway WebSocket endpoint: upgrade, the per-connection read loop and frame dispatch.
Package wshandler implements the gateway WebSocket endpoint: upgrade, the per-connection read loop and frame dispatch.
gateway/api/internal/httperr
Package httperr owns the gateway's JSON response envelope and the mapping from errors to HTTP status codes.
Package httperr owns the gateway's JSON response envelope and the mapping from errors to HTTP status codes.
gateway/api/internal/membership
Package membership answers "is this caller a member of this conversation?" for gateway handlers.
Package membership answers "is this caller a member of this conversation?" for gateway handlers.
gateway/api/internal/mqs
Package mqs subscribes the gateway to the topics it delivers to clients.
Package mqs subscribes the gateway to the topics it delivers to clients.
gateway/api/internal/pbconv
Package pbconv maps RPC responses onto the gateway REST DTOs so every REST surface serialises the same fields the same way.
Package pbconv maps RPC responses onto the gateway REST DTOs so every REST surface serialises the same fields the same way.
gateway/api/internal/peerprofile
Package peerprofile fills the peer's display fields on friendship DTOs.
Package peerprofile fills the peer's display fields on friendship DTOs.
gateway/api/internal/svc/svctest
Package svctest builds ServiceContext values for tests without dialing external services.
Package svctest builds ServiceContext values for tests without dialing external services.
gateway/api/internal/ws
Package ws provides WebSocket frame codec helpers for the AIM gateway.
Package ws provides WebSocket frame codec helpers for the AIM gateway.
gateway/api/internal/ws/auth
Package wsauth provides JWT token extraction and validation for WebSocket connections.
Package wsauth provides JWT token extraction and validation for WebSocket connections.
logic/rpc command
logic/rpc/internal/service/rbac
Package rbac decides conversation permissions with Casbin.
Package rbac decides conversation permissions with Casbin.
logic/rpc/internal/servicefakes
Package servicefakes provides in-memory implementations of the logic service contracts, shared by the service and RPC-logic test suites so behaviour stays identical wherever a store is faked.
Package servicefakes provides in-memory implementations of the logic service contracts, shared by the service and RPC-logic test suites so behaviour stays identical wherever a store is faked.
logic/rpc/internal/svc/svctest
Package svctest builds ServiceContext values for tests without dialing Postgres, Redis or RocketMQ.
Package svctest builds ServiceContext values for tests without dialing Postgres, Redis or RocketMQ.
logic/rpc/model/dao
Package dao is the GORM data-access layer for the aim_logic database.
Package dao is the GORM data-access layer for the aim_logic database.
logic/rpc/model/orm
Package orm holds GORM model definitions for the aim_logic database.
Package orm holds GORM model definitions for the aim_logic database.
shared/attachmentstore/dao
Package dao is the GORM data-access layer for the aim_attachment database.
Package dao is the GORM data-access layer for the aim_attachment database.
shared/attachmentstore/orm
Package orm holds the GORM models of the aim_attachment database.
Package orm holds the GORM models of the aim_attachment database.
shared/botperm
Package botperm defines action-based permission helpers for Bot OpenAPI.
Package botperm defines action-based permission helpers for Bot OpenAPI.
shared/bottoken
Package bottoken provides generation and hashing primitives for AIM Bot OpenAPI tokens.
Package bottoken provides generation and hashing primitives for AIM Bot OpenAPI tokens.
shared/botwebhook
Package botwebhook is the bot webhook wire contract: the delivery payload plus its HMAC-SHA256 signature.
Package botwebhook is the bot webhook wire contract: the delivery payload plus its HMAC-SHA256 signature.
shared/events
Package events defines the broker payloads exchanged between AIM services.
Package events defines the broker payloads exchanged between AIM services.
shared/gormdb
Package gormdb centralizes GORM connection setup for AIM services.
Package gormdb centralizes GORM connection setup for AIM services.
shared/pgtypes
Package pgtypes holds the small PostgreSQL column types shared by GORM models.
Package pgtypes holds the small PostgreSQL column types shared by GORM models.
shared/quota
Package quota provides a Redis-backed sliding-window rate limiter used by the AIM backends to throttle hot-path operations such as core.Transfer and any future per-(user, conversation) request quotas.
Package quota provides a Redis-backed sliding-window rate limiter used by the AIM backends to throttle hot-path operations such as core.Transfer and any future per-(user, conversation) request quotas.
shared/rocketmq
Package rocketmq centralises AIM's RocketMQ (gRPC proxy protocol) wiring: producer construction, the simple-consumer loop used by every consumer service, and the transactional-message plumbing that replaced the removed outbox poller.
Package rocketmq centralises AIM's RocketMQ (gRPC proxy protocol) wiring: producer construction, the simple-consumer loop used by every consumer service, and the transactional-message plumbing that replaced the removed outbox poller.
shared/user
Package user holds the closed sets stored in the user_info table.
Package user holds the closed sets stored in the user_info table.
Package botsdk provides a Go client and webhook helpers for AIM Bot OpenAPI.
Package botsdk provides a Go client and webhook helpers for AIM Bot OpenAPI.
shared

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL