HiAppEvent 模块

1. 模块概述

1.1 功能与目标

https://gitee.com/openharmony/hiviewdfx_hiappevent

1.1.1 主要功能

HiAppEvent是OpenHarmony为应用程序提供的事件打点模块,主要功能包括:

  • 事件记录:为应用提供事件打点接口,用于记录应用运行过程中发生的各类事件
  • 事件分类:支持故障(FAULT)、统计(STATISTIC)、安全(SECURITY)、行为(BEHAVIOR)四种事件类型
  • 事件存储:将事件数据持久化存储到本地文件和数据库
  • 事件订阅:支持通过Watcher和Processor机制订阅和处理事件
  • 配置管理:提供打点功能开关、存储配额等配置能力
  • 用户信息管理:支持用户ID和用户属性的设置与管理
1.1.2 设计目标
  1. 提供轻量级、高性能的事件打点能力
  2. 支持多种编程语言接口(JS/TS、Native C/C++、Cangjie)
  3. 提供灵活的事件订阅和处理机制
  4. 确保事件数据的可靠存储和传输
  5. 支持开发者进行应用运行状态分析
1.1.3 使用场景
  • 应用故障信息记录与分析
  • 应用统计数据采集
  • 安全事件监控
  • 用户行为分析
  • 分布式服务事件追踪

1.2 系统位置

1.2.1 在系统中的位置

HiAppEvent属于OpenHarmony DFX(Design For X)子系统的核心组件,位于系统框架层,为上层应用提供事件打点服务。

┌─────────────────────────────────────────────────────────────┐
│                     应用层 (Application)                      │
│                      JS/TS Application                        │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                     接口层 (Logging API)                      │
│                      HiAppEvent API                           │
│         ┌──────────────┬──────────────┬──────────────┐       │
│         │   JS/NAPI    │   Native/NDK │   Cangjie    │       │
│         └──────────────┴──────────────┴──────────────┘       │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                     库层 (Library)                            │
│                     HiAppEvent lib                            │
│    ┌─────────┬─────────┬─────────┬─────────┬─────────┐      │
│    │  Core   │ Observer│  Cache  │ Cleaner │ Utility │      │
│    └─────────┴─────────┴─────────┴─────────┴─────────┘      │
└─────────────────────────────────────────────────────────────┘
1.2.2 模块角色
  • 核心模块:作为DFX子系统的核心组件,为整个系统提供应用事件打点基础设施
  • 服务提供者:为上层应用和其他系统组件提供事件记录服务
  • 数据中心:负责事件数据的收集、存储和分发
1.2.3 与其他模块的关系
依赖模块 关系描述
ability_runtime 获取应用上下文,注册生命周期回调
bundle_framework 获取应用包信息
c_utils 基础工具类支持
eventhandler 事件处理机制
ffrt 异步任务调度框架
hitrace 分布式追踪支持
hilog 日志记录
hicollie 超时检测
hisysevent 系统事件上报
relational_store 关系型数据库存储
napi JavaScript接口实现
jsoncpp JSON解析支持

1.3 设计思路与模式

1.3.1 设计思路
  1. 分层架构:采用分层设计,将接口层、业务逻辑层、数据存储层分离
  2. 模块化设计:将功能划分为独立模块(Core、Observer、Cache、Cleaner等)
  3. 异步处理:使用FFRT框架实现异步事件写入,避免阻塞主线程
  4. 观察者模式:通过Watcher和Processor机制实现事件的订阅与分发
  5. 单例模式:核心管理类采用单例模式确保全局唯一
1.3.2 设计模式
设计模式 应用场景 实现类
单例模式 配置管理、观察者管理、事件存储 HiAppEventConfigAppEventObserverMgrAppEventStore
观察者模式 事件订阅与通知 AppEventObserverAppEventWatcherAppEventProcessor
工厂模式 创建Processor实例 ModuleLoader
代理模式 Processor代理 AppEventProcessorProxy
策略模式 事件过滤策略 AppEventFilter
建造者模式 参数列表构建 ParamList

1.4 系统框图

┌────────────────────────────────────────────────────────────────────────────┐
│                              HiAppEvent 系统架构                             │
├────────────────────────────────────────────────────────────────────────────┤
│  ┌──────────────────────────────────────────────────────────────────────┐  │
│  │                          应用接口层                                    │  │
│  │  ┌────────────┐  ┌────────────┐  ┌────────────┐  ┌────────────┐     │  │
│  │  │  JS/NAPI   │  │  ETS/ANI   │  │  NDK/C     │  │  Cangjie   │     │  │
│  │  │  Interface │  │  Interface │  │  Interface │  │  Interface │     │  │
│  │  └─────┬──────┘  └─────┬──────┘  └─────┬──────┘  └─────┬──────┘     │  │
│  └────────┼───────────────┼───────────────┼───────────────┼────────────┘  │
│           │               │               │               │                │
│           └───────────────┴───────┬───────┴───────────────┘                │
│                                   ▼                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐  │
│  │                          核心业务层                                    │  │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐                │  │
│  │  │ EventWrite   │  │ EventVerify  │  │ EventConfig  │                │  │
│  │  │ 事件写入      │  │ 事件校验      │  │ 配置管理      │                │  │
│  │  └──────┬───────┘  └──────────────┘  └──────────────┘                │  │
│  │         │                                                             │  │
│  │         ▼                                                             │  │
│  │  ┌──────────────────────────────────────────────────────────┐        │  │
│  │  │              AppEventObserverMgr (观察者管理器)             │        │  │
│  │  │  ┌──────────────┐              ┌──────────────┐          │        │  │
│  │  │  │   Watcher    │              │  Processor   │          │        │  │
│  │  │  │   管理器      │              │   管理器      │          │        │  │
│  │  │  └──────────────┘              └──────────────┘          │        │  │
│  │  └──────────────────────────────────────────────────────────┘        │  │
│  └──────────────────────────────────────────────────────────────────────┘  │
│                                   │                                        │
│                                   ▼                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐  │
│  │                          数据存储层                                    │  │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐                │  │
│  │  │ AppEventStore│  │ File Storage │  │   Cleaner    │                │  │
│  │  │ (RDB数据库)   │  │ (日志文件)    │  │  (清理器)     │                │  │
│  │  └──────────────┘  └──────────────┘  └──────────────┘                │  │
│  └──────────────────────────────────────────────────────────────────────┘  │
└────────────────────────────────────────────────────────────────────────────┘

2. 模块结构

2.1 源文件与头文件

2.1.1 目录结构
hiappevent/
├── frameworks/                          # 框架实现代码
│   ├── native/                          # Native实现
│   │   ├── libhiappevent/              # 核心库
│   │   │   ├── include/                # 头文件
│   │   │   ├── cache/                  # 缓存/存储模块
│   │   │   ├── cleaner/                # 清理模块
│   │   │   ├── observer/               # 观察者模块
│   │   │   ├── utility/                # 工具模块
│   │   │   ├── load/                   # 加载模块
│   │   │   └── dfr/                    # DFR模块
│   │   └── ndk/                        # NDK接口
│   ├── js/napi/                        # JS/NAPI接口
│   ├── ets/ani/                        # ETS/ANI接口
│   └── cj/ffi/                         # Cangjie接口
├── interfaces/                          # 对外接口
│   └── native/
│       ├── inner_api/                  # 内部API
│       └── kits/                       # SDK接口
└── test/                               # 测试代码
2.1.2 核心源文件说明
文件路径 功能描述
hiappevent_base.cpp/h 事件包基础类实现,定义AppEventPack等核心数据结构
hiappevent_write.cpp/h 事件写入功能实现
hiappevent_config.cpp/h 配置管理功能实现(单例模式)
hiappevent_verify.cpp/h 事件参数校验功能
hiappevent_clean.cpp/h 存储空间清理功能
hiappevent_userinfo.cpp/h 用户信息管理功能
hiappevent_c.cpp/h C语言接口封装
2.1.3 Observer模块文件
文件路径 功能描述
app_event_observer.cpp/h 观察者基类定义
app_event_observer_mgr.cpp/h 观察者管理器(单例模式)
app_event_watcher.cpp/h Watcher实现
app_event_processor_proxy.cpp/h Processor代理实现
app_state_callback.cpp/h 应用状态回调
os_event_listener.cpp/h 系统事件监听器
2.1.4 Cache模块文件
文件路径 功能描述
app_event_store.cpp/h 事件存储管理(单例模式)
app_event_dao.cpp/h 事件数据访问对象
app_event_observer_dao.cpp/h 观察者数据访问对象
app_event_mapping_dao.cpp/h 事件-观察者映射数据访问对象
user_id_dao.cpp/h 用户ID数据访问对象
user_property_dao.cpp/h 用户属性数据访问对象

2.2 类、结构体、函数与方法

2.2.1 核心类定义
AppEventPack(事件包类)
class AppEventPack {
public:
    // 构造函数
    AppEventPack() = default;
    AppEventPack(const std::string& name, int type);
    AppEventPack(const std::string& domain, const std::string& name, int type = 0);
    ~AppEventPack() {}

    // 参数添加方法(支持多种类型)
    void AddParam(const std::string& key);
    void AddParam(const std::string& key, bool b);
    void AddParam(const std::string& key, int i);
    void AddParam(const std::string& key, int64_t ll);
    void AddParam(const std::string& key, double d);
    void AddParam(const std::string& key, const std::string& s);
    void AddParam(const std::string& key, const std::vector<T>& values);
    
    // Getter方法
    int64_t GetSeq() const;
    std::string GetDomain() const;
    std::string GetName() const;
    int GetType() const;
    uint64_t GetTime() const;
    std::string GetEventStr() const;
    
    // Setter方法
    void SetSeq(int64_t seq);
    void SetDomain(const std::string& domain);
    void SetName(const std::string& name);
    void SetType(int type);

private:
    int64_t seq_ = 0;           // 事件序列号
    std::string domain_;         // 事件域
    std::string name_;           // 事件名称
    int type_ = 0;              // 事件类型
    uint64_t time_ = 0;         // 时间戳
    std::string timeZone_;       // 时区
    int pid_ = 0;               // 进程ID
    int tid_ = 0;               // 线程ID
    int64_t traceId_ = 0;       // 追踪ID
    std::list<AppEventParam> baseParams_;  // 参数列表
};
HiAppEventConfig(配置管理类 - 单例)
class HiAppEventConfig : public NoCopyable {
public:
    static HiAppEventConfig& GetInstance();
    
    void SetStorageDir(const std::string& dir);
    bool SetConfigurationItem(std::string name, std::string value);
    bool GetDisable();
    uint64_t GetMaxStorageSize();
    std::string GetStorageDir();
    std::string GetRunningId();
    bool IsFreeSizeOverLimit();
    void RefreshFreeSize();

private:
    HiAppEventConfig() {}
    ~HiAppEventConfig() {}
    
    bool disable_ = false;                           // 打点开关
    uint64_t maxStorageSize_ = 10 * 1024 * 1024;    // 最大存储大小(默认10M)
    std::string storageDir_ = "";                    // 存储目录
    std::string runningId_ = "";                     // 运行ID
};
AppEventObserver(观察者基类)
class AppEventObserver {
public:
    AppEventObserver(const std::string& name);
    AppEventObserver(const std::string& name, 
                    const std::vector<AppEventFilter>& filters,
                    TriggerCondition cond);
    virtual ~AppEventObserver() = default;
    
    // 虚函数接口
    virtual void OnEvents(const std::vector<std::shared_ptr<AppEventPack>>& events) {}
    virtual bool VerifyEvent(std::shared_ptr<AppEventPack> event);
    virtual bool IsRealTimeEvent(std::shared_ptr<AppEventPack> event);
    virtual void OnTrigger(const TriggerCondition& triggerCond) {}
    
    // 事件处理
    void ProcessEvent(std::shared_ptr<AppEventPack> event);
    void ProcessTimeout();
    void ProcessStartup();
    void ProcessBackground();
    
    // 属性访问
    std::string GetName();
    int64_t GetSeq();
    void SetSeq(int64_t seq);

private:
    std::string name_;                    // 观察者名称
    int64_t seq_ = 0;                     // 观察者序列号
    std::vector<AppEventFilter> filters_; // 事件过滤器
    TriggerCondition triggerCond_;        // 触发条件
    TriggerCondition currCond_;           // 当前条件
};
AppEventObserverMgr(观察者管理器 - 单例)
class AppEventObserverMgr : public NoCopyable {
public:
    static AppEventObserverMgr& GetInstance();
    
    // Watcher管理
    int64_t AddWatcher(std::shared_ptr<AppEventWatcher> watcher);
    
    // Processor管理
    int64_t AddProcessor(const std::string& name, const ReportConfig& config = {});
    
    // 观察者移除
    int RemoveObserver(int64_t observerSeq);
    int RemoveObserver(const std::string& observerName);
    
    // 事件处理
    void HandleEvents(std::vector<std::shared_ptr<AppEventPack>>& events);
    void HandleTimeout();
    void HandleBackground();
    void HandleClearUp();
    
    // 配置管理
    int SetReportConfig(int64_t observerSeq, const ReportConfig& config);
    int GetReportConfig(int64_t observerSeq, ReportConfig& config);
    
    // 任务提交
    void SubmitTaskToFFRTQueue(std::function<void()>&& task, const std::string& taskName);

private:
    std::unordered_map<int64_t, std::shared_ptr<AppEventWatcher>> watchers_;
    std::unordered_map<int64_t, std::shared_ptr<AppEventProcessorProxy>> processors_;
    std::shared_ptr<ffrt::queue> queue_ = nullptr;
};
2.2.2 核心结构体定义
AppEventParamType(参数类型枚举)
enum AppEventParamType {
    EMPTY = 0,
    BOOL = 1,
    CHAR = 2,
    SHORT = 3,
    INTEGER = 4,
    LONGLONG = 5,
    FLOAT = 6,
    DOUBLE = 7,
    STRING = 8,
    BVECTOR = 9,    // bool数组
    CVECTOR = 10,   // char数组
    SHVECTOR = 11,  // short数组
    IVECTOR = 12,   // int数组
    LLVECTOR = 13,  // long long数组
    FVECTOR = 14,   // float数组
    DVECTOR = 15,   // double数组
    STRVECTOR = 16  // string数组
};
EventType(事件类型枚举)
enum EventType {
    FAULT = 1,      // 故障事件
    STATISTIC = 2,  // 统计事件
    SECURITY = 3,   // 安全事件
    BEHAVIOR = 4    // 行为事件
};
TriggerCondition(触发条件结构体)
struct TriggerCondition {
    int row = 0;           // 事件数量触发
    int size = 0;          // 事件大小触发
    int timeout = 0;       // 定时触发(秒)
    bool onStartup = false;    // 启动时触发
    bool onBackground = false; // 切换到后台时触发
};
AppEventFilter(事件过滤器结构体)
struct AppEventFilter {
    std::string domain;                      // 事件域过滤
    std::unordered_set<std::string> names;   // 事件名称过滤
    uint32_t types = 0;                      // 事件类型过滤(位存储)
    
    bool IsValidEvent(std::shared_ptr<AppEventPack> event) const;
};
ReportConfig(上报配置结构体)
struct ReportConfig {
    std::string name;                                    // 上报名称
    bool debugMode = false;                              // 调试模式
    std::string routeInfo;                               // 服务器位置信息
    std::string appId;                                   // 应用ID
    TriggerCondition triggerCond;                        // 触发条件
    std::unordered_set<std::string> userIdNames;         // 可上报的用户ID名称
    std::unordered_set<std::string> userPropertyNames;   // 可上报的用户属性名称
    std::vector<EventConfig> eventConfigs;               // 事件配置
    int configId = 0;                                    // 配置ID
    std::unordered_map<std::string, std::string> customConfigs; // 自定义配置
};
2.2.3 继承关系

«观察者基类»

AppEventObserver

+OnEvents()

+VerifyEvent()

+ProcessEvent()

«事件监听器»

AppEventWatcher

+GetOsEventsMask()

«事件处理器»

AppEventProcessor

+OnReport()

«处理器代理»

AppEventProcessorProxy

+OnReport()

+GenerateHashCode()

«清理器基类»

AppEventCleaner

+Clean()

«数据库清理器»

AppEventDbCleaner

+Clean()

«日志清理器»

AppEventLogCleaner

+Clean()

2.3 类图

contains

has

manages

manages

uses

1
1
1
1
1
*
1
*
*
1

AppEventPack

-int64_t seq_

-string domain_

-string name_

-int type_

-uint64_t time_

-list<AppEventParam> baseParams_

+AddParam()

+GetEventStr()

+GetDomain()

+GetName()

+GetType()

AppEventParam

-string name

-ParamType type

-ParamValue value

AppEventParamValue

-ParamType type

-Union valueUnion

«Singleton»

AppEventObserverMgr

-map watchers_

-map processors_

-ffrt::queue queue_

+GetInstance()

+AddWatcher()

+AddProcessor()

+HandleEvents()

+RemoveObserver()

«abstract»

AppEventObserver

-string name_

-int64_t seq_

-vector filters_

-TriggerCondition triggerCond_

+OnEvents()

+VerifyEvent()

+ProcessEvent()

+OnTrigger()

AppEventWatcher

-string filtersStr_

+GetOsEventsMask()

+OnEvents()

AppEventProcessorProxy

-shared_ptr processor_

-ReportConfig config_

+OnReport()

+GenerateHashCode()

«Singleton»

AppEventStore

-RdbStore dbStore_

-string dirPath_

+GetInstance()

+InitDbStore()

+InsertEvent()

+QueryEvents()

+DeleteEvent()

AppEventDao

+Insert()

+Query()

+Delete()

«Singleton»

HiAppEventConfig

-bool disable_

-uint64_t maxStorageSize_

-string storageDir_

+GetInstance()

+SetConfigurationItem()

+GetDisable()

+GetMaxStorageSize()

2.4 模块内部依赖框图

┌─────────────────────────────────────────────────────────────────────────────┐
│                         模块内部依赖关系图                                    │
└─────────────────────────────────────────────────────────────────────────────┘

                              ┌─────────────────┐
                              │   应用接口层     │
                              │ (NAPI/NDK/CJ)   │
                              └────────┬────────┘
                                       │
                                       ▼
┌──────────────────────────────────────────────────────────────────────────────┐
│                              Core Layer                                       │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐         │
│  │hiappevent   │  │hiappevent   │  │hiappevent   │  │hiappevent   │         │
│  │  _write     │──│  _verify    │  │  _config    │  │  _clean     │         │
│  └──────┬──────┘  └─────────────┘  └──────┬──────┘  └──────┬──────┘         │
│         │                                  │                 │               │
└─────────┼──────────────────────────────────┼─────────────────┼───────────────┘
          │                                  │                 │
          ▼                                  │                 │
┌──────────────────────────────────────────────────────────────────────────────┐
│                             Observer Layer                                    │
│  ┌─────────────────────────────────────────────────────────────────┐        │
│  │                    AppEventObserverMgr                           │        │
│  │  ┌───────────────┐                    ┌───────────────┐         │        │
│  │  │ AppEventWatcher│                    │AppEventProcessor│        │        │
│  │  └───────┬───────┘                    └───────┬───────┘         │        │
│  │          │                                    │                  │        │
│  │          └──────────────┬─────────────────────┘                  │        │
│  │                         │                                        │        │
│  │                         ▼                                        │        │
│  │              ┌─────────────────────┐                            │        │
│  │              │  AppEventObserver   │                            │        │
│  │              └─────────────────────┘                            │        │
│  └─────────────────────────────────────────────────────────────────┘        │
└────────────────────────────────────────┬─────────────────────────────────────┘
                                         │
                                         ▼
┌──────────────────────────────────────────────────────────────────────────────┐
│                              Cache Layer                                      │
│  ┌─────────────────────────────────────────────────────────────────┐        │
│  │                      AppEventStore                               │        │
│  │  ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌───────────┐ │        │
│  │  │AppEventDao  │ │ObserverDao  │ │MappingDao   │ │UserIdDao  │ │        │
│  │  └─────────────┘ └─────────────┘ └─────────────┘ └───────────┘ │        │
│  └─────────────────────────────────────────────────────────────────┘        │
└────────────────────────────────────────┬─────────────────────────────────────┘
                                         │
                                         ▼
┌──────────────────────────────────────────────────────────────────────────────┐
│                             Cleaner Layer                                     │
│  ┌─────────────────────────────────────────────────────────────────┐        │
│  │  ┌─────────────────────┐        ┌─────────────────────┐        │        │
│  │  │  AppEventDbCleaner  │        │ AppEventLogCleaner  │        │        │
│  │  └─────────────────────┘        └─────────────────────┘        │        │
│  └─────────────────────────────────────────────────────────────────┘        │
└──────────────────────────────────────────────────────────────────────────────┘
                                         │
                                         ▼
┌──────────────────────────────────────────────────────────────────────────────┐
│                             Utility Layer                                     │
│  ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐     │
│  │ file_util │ │ time_util │ │ sql_util  │ │json_util  │ │event_stat │     │
│  └───────────┘ └───────────┘ └───────────┘ └───────────┘ └───────────┘     │
└──────────────────────────────────────────────────────────────────────────────┘

3. 模块间交互

3.1 交互描述

3.1.1 与外部模块的交互
外部模块 交互方式 交互内容
ability_runtime API调用 获取ApplicationContext,注册生命周期回调
relational_store API调用 使用RDB数据库存储事件数据
ffrt API调用 异步任务调度,使用ffrt::queue提交任务
hilog API调用 日志记录
hitrace API调用 获取分布式追踪信息(traceId, spanId等)
napi API调用 JavaScript接口实现
jsoncpp API调用 JSON数据解析和生成
3.1.2 异步处理机制

HiAppEvent采用FFRT(Function Flow Runtime)框架实现异步事件处理:

// 提交事件写入任务
void SubmitWritingTask(std::shared_ptr<AppEventPack> appEventPack, const std::string& taskName)
{
    AppEventObserverMgr::GetInstance().SubmitTaskToFFRTQueue([appEventPack]() {
        WriteEvent(appEventPack);
    }, taskName);
}

// FFRT队列任务提交
void AppEventObserverMgr::SubmitTaskToFFRTQueue(std::function<void()>&& task, const std::string& taskName)
{
    std::lock_guard<std::mutex> lock(queueMutex_);
    if (queue_ == nullptr) {
        return;
    }
    queue_->submit(task, ffrt::task_attr().name(taskName.c_str()));
}
3.1.3 事件驱动机制
  1. 应用生命周期事件:通过AppStateCallback监听应用前后台切换
  2. 定时触发事件:通过ffrt延时任务实现定时触发
  3. 条件触发事件:当事件数量或大小达到阈值时触发
3.1.4 多线程处理
  • 使用std::mutex保护共享数据
  • 使用ffrt::queue实现任务队列
  • 使用std::atomic实现无锁状态标志

3.2 外部依赖框图

┌─────────────────────────────────────────────────────────────────────────────┐
│                           外部依赖关系图                                     │
└─────────────────────────────────────────────────────────────────────────────┘

                    ┌─────────────────────────────────┐
                    │          HiAppEvent             │
                    │         (核心模块)               │
                    └─────────────────┬───────────────┘
                                      │
        ┌─────────────────────────────┼─────────────────────────────┐
        │                             │                             │
        ▼                             ▼                             ▼
┌───────────────┐           ┌───────────────┐           ┌───────────────┐
│ 系统框架依赖   │           │  数据存储依赖  │           │  工具库依赖    │
├───────────────┤           ├───────────────┤           ├───────────────┤
│               │           │               │           │               │
│ ability_      │           │ relational_   │           │ c_utils       │
│ runtime       │           │ store (RDB)   │           │               │
│               │           │               │           │ jsoncpp       │
│ bundle_       │           │ storage_      │           │               │
│ framework     │           │ service       │           │ ffrt          │
│               │           │               │           │               │
│ eventhandler  │           └───────────────┘           │ napi          │
│               │                                       │               │
│ samgr         │                                       └───────────────┘
│               │
│ ipc           │
│               │
│ init          │
└───────────────┘

        ┌─────────────────────────────┐
        │         DFX子系统依赖        │
        ├─────────────────────────────┤
        │                             │
        │  hilog      - 日志记录       │
        │  hitrace    - 分布式追踪     │
        │  hicollie   - 超时检测       │
        │  hisysevent - 系统事件       │
        │                             │
        └─────────────────────────────┘

4. 状态机转换图

4.1 事件处理状态机

4.1.1 状态机模型

HiAppEvent的事件处理涉及多个状态转换,主要包括:

  1. 事件写入状态机
  2. 观察者状态机
  3. 触发条件状态机
4.1.2 状态机树图
┌─────────────────────────────────────────────────────────────────────────────┐
│                           事件处理状态机树图                                  │
└─────────────────────────────────────────────────────────────────────────────┘

                              ┌─────────────┐
                              │   系统初始化  │
                              └──────┬──────┘
                                     │
                    ┌────────────────┼────────────────┐
                    │                │                │
                    ▼                ▼                ▼
            ┌─────────────┐  ┌─────────────┐  ┌─────────────┐
            │ 配置初始化   │  │ 存储初始化   │  │ 观察者初始化 │
            └──────┬──────┘  └──────┬──────┘  └──────┬──────┘
                   │                │                │
                   └────────────────┼────────────────┘
                                    │
                                    ▼
                            ┌─────────────┐
                            │   就绪状态   │
                            └──────┬──────┘
                                   │
                    ┌──────────────┼──────────────┐
                    │              │              │
                    ▼              ▼              ▼
            ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
            │  事件写入    │ │ 事件订阅    │ │  配置修改   │
            │  处理流程    │ │ 处理流程    │ │  处理流程   │
            └─────────────┘ └─────────────┘ └─────────────┘

4.2 状态机切换规则

4.2.1 事件写入状态转换

初始化

事件请求

校验成功

校验失败

写入成功

写入失败

通知完成

返回错误

返回错误

Idle

等待事件

Verifying

参数校验

Writing

写入存储

Error1

Notifying

通知观察者

Error2

4.2.2 观察者状态转换

初始化

添加观察者

接收事件

定时超时

应用后台

条件满足

条件满足

条件满足

条件未满足

条件未满足

条件未满足

回调完成/重置条件

移除观察者

Unregistered

Registered

等待事件

Processing

Timeout

Background

Triggered

执行OnTrigger

重置条件

4.2.3 触发条件状态转换

初始化

事件数量增加

事件大小增加

定时器触发

row >= 阈值

row < 阈值

size >= 阈值

size < 阈值

超时到达

未超时

触发OnTrigger

重置完成

NotSatisfied

等待条件变化

RowCheck

SizeCheck

TimeoutCheck

Satisfied

准备触发回调

Reset

重置row/size/timeout

4.3 状态转移条件说明

状态转换 触发条件 转移动作
空闲→校验中 收到事件写入请求 开始参数校验
校验中→写入中 校验成功 执行事件写入
校验中→错误 校验失败 返回错误码
写入中→通知观察者 写入成功 通知所有匹配的观察者
未注册→已注册 调用AddWatcher/AddProcessor 注册观察者到管理器
已注册→触发回调 触发条件满足 调用OnTrigger/OnEvents
条件未满足→条件满足 row/size/timeout任一满足 准备触发回调

5. 接口设计

5.1 公共接口

5.1.1 Native C接口(NDK)
事件写入接口
接口名称 返回值 描述
OH_HiAppEvent_Write(domain, name, type, list) int 执行事件打点
OH_HiAppEvent_CreateParamList() ParamList 创建参数列表
OH_HiAppEvent_DestroyParamList(list) void 销毁参数列表
OH_HiAppEvent_AddBoolParam(list, name, value) ParamList 添加bool参数
OH_HiAppEvent_AddInt32Param(list, name, value) ParamList 添加int32参数
OH_HiAppEvent_AddInt64Param(list, name, value) ParamList 添加int64参数
OH_HiAppEvent_AddDoubleParam(list, name, value) ParamList 添加double参数
OH_HiAppEvent_AddStringParam(list, name, value) ParamList 添加string参数
OH_HiAppEvent_Add*ArrayParam(...) ParamList 添加数组类型参数
配置接口
接口名称 返回值 描述
OH_HiAppEvent_Configure(name, value) bool 配置打点功能
OH_HiAppEvent_CreateConfig() HiAppEvent_Config* 创建配置对象
OH_HiAppEvent_DestroyConfig(config) void 销毁配置对象
OH_HiAppEvent_SetConfigItem(config, name, value) int 设置配置项
OH_HiAppEvent_SetEventConfig(name, config) int 设置事件配置
Watcher接口
接口名称 返回值 描述
OH_HiAppEvent_CreateWatcher(name) HiAppEvent_Watcher* 创建Watcher
OH_HiAppEvent_DestroyWatcher(watcher) void 销毁Watcher
OH_HiAppEvent_SetTriggerCondition(watcher, row, size, timeout) int 设置触发条件
OH_HiAppEvent_SetAppEventFilter(watcher, domain, types, names, len) int 设置事件过滤器
OH_HiAppEvent_SetWatcherOnTrigger(watcher, callback) int 设置触发回调
OH_HiAppEvent_SetWatcherOnReceive(watcher, callback) int 设置接收回调
OH_HiAppEvent_AddWatcher(watcher) int 添加Watcher
OH_HiAppEvent_RemoveWatcher(watcher) int 移除Watcher
OH_HiAppEvent_TakeWatcherData(watcher, num, callback) int 获取Watcher数据
Processor接口
接口名称 返回值 描述
OH_HiAppEvent_CreateProcessor(name) HiAppEvent_Processor* 创建Processor
OH_HiAppEvent_DestroyProcessor(processor) void 销毁Processor
OH_HiAppEvent_SetReportRoute(processor, appId, routeInfo) int 设置上报路由
OH_HiAppEvent_SetReportPolicy(processor, period, batch, start, bg) int 设置上报策略
OH_HiAppEvent_SetReportEvent(processor, domain, name, realtime) int 设置上报事件
OH_HiAppEvent_AddProcessor(processor) int64_t 添加Processor
OH_HiAppEvent_RemoveProcessor(processorId) int 移除Processor
数据清理接口
接口名称 返回值 描述
OH_HiAppEvent_ClearData() void 清除所有本地事件数据
5.1.2 错误码定义
typedef enum {
    HIAPPEVENT_SUCCESS = 0,                    // 操作成功
    HIAPPEVENT_INVALID_PARAM_VALUE_LENGTH = 4, // 参数值长度无效
    HIAPPEVENT_PROCESSOR_IS_NULL = -7,         // Processor为空
    HIAPPEVENT_PROCESSOR_NOT_FOUND = -8,       // Processor未找到
    HIAPPEVENT_INVALID_PARAM_VALUE = -9,       // 参数值无效
    HIAPPEVENT_EVENT_CONFIG_IS_NULL = -10,     // 事件配置为空
    HIAPPEVENT_OPERATE_FAILED = -100,          // 操作失败
    HIAPPEVENT_INVALID_UID = -200              // 无效UID
} HiAppEvent_ErrorCode;
5.1.3 内部API(Inner API)
namespace OHOS::HiviewDFX::HiAppEvent {

// 事件类
class Event {
public:
    Event(const std::string& domain, const std::string& name, EventType type);
    
    void AddParam(const std::string& key, bool value);
    void AddParam(const std::string& key, int32_t value);
    void AddParam(const std::string& key, int64_t value);
    void AddParam(const std::string& key, double value);
    void AddParam(const std::string& key, const std::string& value);
    void AddParam(const std::string& key, const std::vector<T>& value);
};

// 事件写入函数
int Write(const Event& event);

// Processor管理
class AppEventProcessorMgr {
public:
    static int RegisterProcessor(const std::string& name, 
                                 std::shared_ptr<AppEventProcessor> processor);
    static int UnregisterProcessor(const std::string& name);
};

}

5.2 数据交换接口

5.2.1 事件数据结构
// C接口事件信息结构
typedef struct HiAppEvent_AppEventInfo {
    const char* domain;      // 事件域
    const char* name;        // 事件名称
    enum EventType type;     // 事件类型
    const char* params;      // JSON格式参数字符串
} HiAppEvent_AppEventInfo;

// C接口事件组结构
typedef struct HiAppEvent_AppEventGroup {
    const char* name;                              // 事件组名称
    const struct HiAppEvent_AppEventInfo* appEventInfos;  // 事件数组
    uint32_t infoLen;                              // 数组长度
} HiAppEvent_AppEventGroup;
5.2.2 回调函数类型
// 事件接收回调
typedef void (*OH_HiAppEvent_OnReceive)(
    const char* domain, 
    const struct HiAppEvent_AppEventGroup* appEventGroups, 
    uint32_t groupLen);

// 触发条件回调
typedef void (*OH_HiAppEvent_OnTrigger)(int row, int size);

// 数据获取回调
typedef void (*OH_HiAppEvent_OnTake)(const char* const *events, uint32_t eventLen);
5.2.3 Processor接口
class AppEventProcessor {
public:
    virtual int OnReport(
        int64_t processorSeq,
        const std::vector<UserId>& userIds,
        const std::vector<UserProperty>& userProperties,
        const std::vector<AppEventInfo>& events) = 0;
        
    virtual int ValidateUserId(const UserId& userId) = 0;
    virtual int ValidateUserProperty(const UserProperty& userProperty) = 0;
    virtual int ValidateEvent(const AppEventInfo& event) = 0;
};

5.3 接口调用时序图

5.3.1 事件写入时序图
Store Observer Core NAPI/NDK Application Store Observer Core NAPI/NDK Application 异步执行 alt [实时事件] OH_HiAppEvent_Write() VerifyAppEvent() 验证结果 SubmitWritingTask() 返回结果 WriteEvent() InsertEvent() eventSeq HandleEvents() ProcessEvent() OnEvents() 处理完成
5.3.2 Watcher注册时序图
Watcher Store ObserverMgr NAPI/NDK Application Watcher Store ObserverMgr NAPI/NDK Application CreateWatcher() watcher ptr SetTriggerCond() SetAppEventFilter() SetWatcherOnReceive() AddWatcher() AddWatcher() QueryObserverSeq() seq InsertObserver() observerSeq Add to watchers_ observerSeq 返回结果
5.3.3 触发条件回调时序图
Application Observer ObserverMgr FFRT Application Observer ObserverMgr FFRT 检查触发条件 alt [条件满足] 延时30s后再次触发 alt [有超时条件] HandleTimeout() ProcessTimeout() OnTrigger() 回调返回 ResetCurrCondition() 处理完成 HasTimeoutCond()? true/false SendTimeoutTask()

附录

A. 配置项说明

配置项 类型 默认值 描述
DISABLE string “false” 打点功能开关
MAX_STORAGE string “10M” 最大存储空间

B. 事件类型说明

类型 描述 使用场景
FAULT 1 故障事件 应用崩溃、异常等
STATISTIC 2 统计事件 数据统计、计数等
SECURITY 3 安全事件 安全相关操作记录
BEHAVIOR 4 行为事件 用户行为记录
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐