UBA Backend API Contract
This document organizes the UBA external/internal API contracts based on the actual Protobuf definitions (backend/api/protos/), serving as the authoritative reference for secondary development and SDK integration.
Interface contract first: all APIs are defined in
.protofiles, with Go / TypeScript / OpenAPI code generated via buf. See Code Generation Pipeline for details.
1. Proto Layering
api/protos/
├── uba/service/v1/ # UBA domain messages + gRPC service contracts (implemented by Core)
│ ├── analytics.proto # Analytics aggregations
│ ├── behavior_event.proto# Behavior events
│ ├── report.proto # Report service (implemented by Collector)
│ ├── session.proto / event_path.proto
│ ├── risk_event.proto / risk_rule.proto
│ ├── application.proto / event_schema.proto / object.proto
│ ├── tag_definition.proto / user_tag.proto / id_mapping.proto
│ ├── user_behavior_profile.proto / webhook.proto
│ ├── common.proto / uba_error.proto
├── admin/service/v1/ # Admin console HTTP gateway (forwarding implemented by Admin, i_ prefix)
│ ├── i_analytics.proto / i_behavior_event.proto / i_application.proto
│ ├── i_session.proto / i_event_path.proto / i_event_schema.proto
│ ├── i_risk_event.proto / i_risk_rule.proto / i_webhook.proto
│ ├── i_tag_definition.proto / i_user_tag.proto / i_id_mapping.proto
│ ├── i_user.proto / i_role.proto / i_permission*.proto / i_menu.proto
│ ├── i_authentication.proto / i_login_policy.proto / i_tenant.proto
│ ├── i_dict_*.proto / i_language.proto / i_file*.proto / i_task.proto
│ ├── i_internal_message*.proto / i_org_unit.proto / i_position.proto
│ └── i_*_audit_log.proto / i_admin_portal.proto
└── <other domains>/ # authentication / permission / dict / identity ...
Only
admin/service/v1/*.protogenerates the frontend TypeScript client (seeinputs.pathsinapi/buf.admin.typescript.gen.yaml).
2. Report Service (Collector)
ReportService (uba/service/v1/report.proto)
| RPC | Description |
|---|---|
PostReport(PostReportRequest) returns (PostReportResponse) | Unified reporting interface, supports mixed reporting of behavior/risk events |
HTTP Endpoint
POST /uba/v1/report
Authentication
appId+appSecretare placed in the request body (not headers); no Authorization token.- Authentication failure returns
401; the SDK does not retry.
Request Body Structure (camelCase, protojson encoding)
{
"appId": "your_app_id",
"appSecret": "your_app_secret",
"clientInfo": { "userAgent": "...", "referer": "..." },
"events": [
{
"eventType": "BEHAVIOR", // BEHAVIOR | RISK
"eventId": "uuid", // auto-generated by the SDK, unique
"eventName": "click", // required
"eventTime": "RFC3339", // auto-completed by the SDK
"deviceId": "...", // persisted by the SDK, stable per device
"sessionId": "...", // session level
"platform": "web", // detected by the SDK
"userId": 1001, // carried automatically after identify
"properties": { "button": "buy" },
"behavior": { "objectType": "button", "objectId": "btn_buy" }
}
]
}
tenantIdis not reported; the server authoritatively identifies and overrides it based on appId, ensuring multi-tenant isolation.
Event Types (oneof payload of the events element)
| Type | Fields | Triggering API |
|---|---|---|
Behavior event (BEHAVIOR) | behavior + properties | SDK track / trackBehavior |
Risk event (RISK) | risk (riskType / riskLevel / riskScore / description) | SDK trackRisk |
Response Conventions
- HTTP
200may still contain partial failures: when the response body hasfailedCount > 0or a non-emptyerrorsByType, the SDK logs a warning. - Error codes:
400validation failure,401authentication failure (no retry),500server error (retry). - Error bodies follow the Kratos error envelope format.
3. Analytics Aggregation Service
AnalyticsService (uba/service/v1/analytics.proto)
A total of 25 analysis model RPCs (grouped by scenario, corresponding to lines 11-83 of the proto):
| Scenario | RPC | Purpose |
|---|---|---|
| Basic aggregations | EventTrend | Event volume trend (time bucketing) |
GroupBy | Dimension group aggregation (whitelisted dimensions + metrics) | |
ActiveUsers | DAU / WAU / MAU (daily-level true values via HLL rolling windows) | |
| Conversion & paths | Funnel | Funnel analysis (multi-step conversion) |
Retention | Cohort retention matrix | |
PathSankey | Top conversion paths (Sankey diagram) | |
BehaviorSequence | Behavior sequence analysis | |
| In-depth user insights | Attribution | Attribution analysis (first-touch/last-touch) |
Distribution | Distribution analysis (duration bucketing + percentiles) | |
Segmentation | User segmentation / targeting | |
Click | Click heatmaps | |
Interval | Interval time analysis | |
| Lifecycle | Lifecycle | User lifecycle |
Churn | Churn and win-back analysis | |
NewVsOld | New vs. returning user comparison | |
Matrix | Matrix / quadrant analysis | |
| Revenue & value | Revenue | Revenue analysis (ARPU/ARPPU/GMV) |
WhaleTier | Paying-user tiers (whale users) | |
LTV | Historical lifetime value | |
| Sessions & anomalies | SessionAnalysis | Session analysis (bounce rate/depth/percentiles) |
Anomaly | Year-over-year / month-over-month, anomaly detection | |
| Game-specific | LevelAnalysis | Level / numeric balance analysis |
ServerRetention | Merged-server retention (by server) | |
OnlineStats | Concurrent online PCU / ACU | |
Economy | Economy system / token flows |
Common Messages
AnalyticsGranularityenum:UNSPECIFIED=0,HOUR=1,DAY=2,WEEK=3,MONTH=4.TimeRange:start_ms(inclusive),end_ms(inclusive), Unix milliseconds. When omitted, the default is end = now and start = 7 days ago.TimeSeriesPoint:timestamp(ms),value(double).
Request Essentials
The request messages (*Request) of the 25 models follow unified conventions:
- Common fields:
time_range(TimeRange), optionalapp_id(used in the repository as atenant_idisolation predicate;0/absent means all tenants). Time-series models also carrygranularity(AnalyticsGranularity). - Filter fields:
event_name/platform/dimensionetc. are carried according to each model's semantics.GroupBy'sdimensionuses a whitelist:platform/channel/country/app_version/event_name/event_category/os/network(game models additionally supportserver_id/leveletc.). - Model-specific parameters: e.g.
FunnelRequest.steps(repeated string, ≥2),RetentionRequest.retention_type(ACTIVE/EVENT) +max_offset_days,GroupByRequest.metric(COUNT/UNIQUE_USER/SUM_AMOUNT), etc.
For the complete field-by-field definitions of the 25 models, consult
backend/api/protos/uba/service/v1/analytics.proto(request/response messages with full field comments), or the Swagger docs generated by runningmake openapi.
Admin HTTP Endpoints (admin/service/v1/i_analytics.proto)
All are POST with body: "*", forwarded to Core gRPC; the path convention is uniformly POST /admin/v1/analytics/<kebab-case method name>:
| Method | HTTP Path |
|---|---|
EventTrend | POST /admin/v1/analytics/event-trend |
Funnel | POST /admin/v1/analytics/funnel |
Retention | POST /admin/v1/analytics/retention |
GroupBy | POST /admin/v1/analytics/group-by |
ActiveUsers | POST /admin/v1/analytics/active-users |
Attribution | POST /admin/v1/analytics/attribution |
Distribution | POST /admin/v1/analytics/distribution |
BehaviorSequence | POST /admin/v1/analytics/behavior-sequence |
Segmentation | POST /admin/v1/analytics/segmentation |
Click | POST /admin/v1/analytics/click |
Lifecycle | POST /admin/v1/analytics/lifecycle |
Churn | POST /admin/v1/analytics/churn |
Interval | POST /admin/v1/analytics/interval |
Matrix | POST /admin/v1/analytics/matrix |
Revenue | POST /admin/v1/analytics/revenue |
SessionAnalysis | POST /admin/v1/analytics/session-analysis |
Anomaly | POST /admin/v1/analytics/anomaly |
NewVsOld | POST /admin/v1/analytics/new-vs-old |
PathSankey | POST /admin/v1/analytics/path-sankey |
LevelAnalysis | POST /admin/v1/analytics/level-analysis |
WhaleTier | POST /admin/v1/analytics/whale-tier |
LTV | POST /admin/v1/analytics/ltv |
ServerRetention | POST /admin/v1/analytics/server-retention |
OnlineStats | POST /admin/v1/analytics/online-stats |
Economy | POST /admin/v1/analytics/economy |
⚠️ Known limitation:
ActiveUsers'swau/maualready output true values at the daily level based on HLL rolling windows; only HOUR granularity degrades to equal DAU due to the lack of hourly state. See Appendix for details.
4. Behavior Event Service
BehaviorEventService (uba/service/v1/behavior_event.proto)
| RPC | Description |
|---|---|
Create(BehaviorEvent) returns (Empty) | Insert a single event |
BatchCreate(BatchCreateBehaviorEventRequest) returns (Empty) | Batch insert |
List(PagingRequest) returns (ListBehaviorEventResponse) | Paginated query |
Get(GetBehaviorEventRequest) returns (BehaviorEvent) | Query a single event |
Full Set of BehaviorEvent Fields (corresponds to events_fact)
| Field | Type | Group |
|---|---|---|
event_id, tenant_id | string / uint32 | Routing/identity |
user_id, device_id, account_id, global_user_id | uint32 / string | Subject (Who) |
event_time, event_ts, server_time | Timestamp / int64 | Time |
event_category, event_name, event_action | string | Behavior (What) |
object_type, object_id, object_name | string | Object |
session_id, session_seq | string / uint32 | Session context |
platform, os, app_version, channel | string | Environment |
ip, ip_city, country, network, geo, user_agent, referer | string | Network/location |
context | map<string,string> | Business context |
duration_ms, amount, quantity, score, metrics | uint32/string/int32/map | Metrics |
properties | map<string,string> | Extended properties |
op_result, error_code, risk_level, trace_id | string | Enterprise/operations |
click_x, click_y, element_xpath, page_url, viewport_width | uint32 / string | Heatmap (filled by autotrack) |
server_id, level | string / uint32 | Game-specific dimensions (server ID / player level) |
created_at, updated_at | Timestamp | Timestamps |
5. CRUD Services Overview
The following services all provide standard CRUD (List/Count/Get/Create/Update/Delete, some with BatchCreate), forwarded one-to-one by the Admin layer:
| Domain | Core service / proto | Admin proto |
|---|---|---|
| Sessions | SessionService / session.proto | i_session.proto |
| User paths | EventPathService / event_path.proto | i_event_path.proto |
| Event schemas | EventSchemaService / event_schema.proto | i_event_schema.proto |
| Behavior objects | ObjectService / object.proto | i_object.proto |
| UBA apps | ApplicationService / application.proto | i_application.proto |
| Risk events | RiskEventService / risk_event.proto | i_risk_event.proto |
| Risk rules | RiskRuleService / risk_rule.proto | i_risk_rule.proto |
| Webhooks | WebhookService / webhook.proto | i_webhook.proto |
| Tag definitions | TagDefinitionService / tag_definition.proto | i_tag_definition.proto |
| User tags | UserTagService / user_tag.proto | i_user_tag.proto |
| ID mapping | IdMappingService / id_mapping.proto | i_id_mapping.proto |
| User behavior profiles | UserBehaviorProfileService / user_behavior_profile.proto | i_user_behavior_profile.proto |
| Users / user profiles | UserService etc. | i_user.proto / i_user_profile.proto |
| Tenants/organizations/positions | TenantService / OrgUnitService / PositionService | i_tenant.proto / i_org_unit.proto / i_position.proto |
| Roles/permissions/menus | RoleService / PermissionService / MenuService | i_role.proto / i_permission*.proto / i_menu.proto |
| Dictionaries/languages | DictTypeService / DictEntryService / LanguageService | i_dict_*.proto / i_language.proto |
| Authentication/login policy | AuthenticationService / LoginPolicyService | i_authentication.proto / i_login_policy.proto |
| Files | FileService / FileTransferService | i_file.proto / i_file_transfer.proto |
| Internal messages | InternalMessageService (+ Category/Recipient) | i_internal_message*.proto |
| Tasks | TaskService | i_task.proto |
| Audit logs (6 types) | *AuditLogService / PolicyEvaluationLogService | i_*_audit_log.proto etc. |
| API metadata | ApiService | i_api.proto |
For the complete request/response message definitions, consult the corresponding
.protofiles directly inbackend/api/protos/, or the Swagger docs generated by runningmake openapi.
6. Getting Interactive Documentation
cd backend
make openapi # generate OpenAPI / Swagger (based on admin / collector protos)
After starting the Admin / Collector services (enable_swagger: true), visit each service's Swagger UI to browse and try out the APIs.
