This commit is contained in:
2026-05-01 01:53:14 +08:00
69 changed files with 7346 additions and 759 deletions

2
server-rs/Cargo.lock generated
View File

@@ -84,6 +84,7 @@ dependencies = [
"module-combat",
"module-custom-world",
"module-inventory",
"module-match3d",
"module-npc",
"module-puzzle",
"module-runtime",
@@ -2668,6 +2669,7 @@ dependencies = [
"module-combat",
"module-custom-world",
"module-inventory",
"module-match3d",
"module-npc",
"module-puzzle",
"module-runtime",

View File

@@ -19,6 +19,7 @@ module-big-fish = { path = "../module-big-fish" }
module-combat = { path = "../module-combat" }
module-custom-world = { path = "../module-custom-world" }
module-inventory = { path = "../module-inventory" }
module-match3d = { path = "../module-match3d" }
module-npc = { path = "../module-npc" }
module-puzzle = { path = "../module-puzzle" }
module-runtime = { path = "../module-runtime" }
@@ -54,4 +55,4 @@ tower = { version = "0.5", features = ["util"] }
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=lld"] # Ubuntu 22+ 自带 lld
rustflags = ["-C", "link-arg=-fuse-ld=lld"] # Ubuntu 22+ 自带 lld

View File

@@ -11,7 +11,7 @@ use axum::{
header::{AUTHORIZATION, CONTENT_TYPE},
},
middleware::Next,
response::{Html, Response},
response::Response,
};
use reqwest::Client;
use serde::Deserialize;
@@ -76,6 +76,9 @@ const DATABASE_OVERVIEW_TABLES: &[&str] = &[
"asset_object",
"asset_entity_binding",
];
// SpacetimeDB 2.x 的 schema HTTP API 要求显式传入 BSATN JSON 版本。
// 后台总览只读取表名,固定使用当前 CLI 2.1.0 兼容的版本参数即可。
const SPACETIME_SCHEMA_VERSION_QUERY: &str = "version=9";
#[derive(Clone, Debug)]
pub struct AuthenticatedAdmin {
@@ -100,17 +103,6 @@ struct SpacetimeSchemaTable {
name: Option<String>,
}
#[derive(Debug, Deserialize)]
struct SpacetimeSqlRow {
#[serde(flatten)]
columns: serde_json::Map<String, Value>,
}
#[derive(Debug, Deserialize)]
struct SpacetimeSqlResponse {
rows: Option<Vec<SpacetimeSqlRow>>,
}
impl AuthenticatedAdmin {
pub fn new(session: AdminSessionPayload) -> Self {
Self { session }
@@ -121,10 +113,6 @@ impl AuthenticatedAdmin {
}
}
pub async fn admin_console_page() -> Html<&'static str> {
Html(ADMIN_CONSOLE_HTML)
}
pub async fn admin_login(
State(state): State<AppState>,
Extension(request_context): Extension<RequestContext>,
@@ -287,7 +275,7 @@ async fn fetch_database_overview(state: &AppState) -> AdminDatabaseOverviewPaylo
let schema = fetch_spacetime_json::<SpacetimeSchemaResponse>(
&client,
&format!("{server_root}/v1/database/{database}/schema"),
&build_spacetime_schema_url(server_root, database),
token,
)
.await
@@ -353,6 +341,10 @@ async fn fetch_database_overview(state: &AppState) -> AdminDatabaseOverviewPaylo
}
}
fn build_spacetime_schema_url(server_root: &str, database: &str) -> String {
format!("{server_root}/v1/database/{database}/schema?{SPACETIME_SCHEMA_VERSION_QUERY}")
}
async fn fetch_spacetime_json<T>(
client: &Client,
url: &str,
@@ -409,17 +401,63 @@ async fn fetch_spacetime_sql_count(
}
let payload = response
.json::<SpacetimeSqlResponse>()
.json::<Value>()
.await
.map_err(|error| format!("SQL 响应解析失败:{error}"))?;
let row = payload
.rows
.and_then(|rows| rows.into_iter().next())
.ok_or_else(|| "SQL 结果为空".to_string())?;
extract_sql_count(row.columns)
parse_spacetime_sql_count_response(payload)
}
fn extract_sql_count(columns: serde_json::Map<String, Value>) -> Result<u64, String> {
fn parse_spacetime_sql_count_response(payload: Value) -> Result<u64, String> {
match payload {
// SpacetimeDB 2.x /sql 返回 statement result 数组,每个 result 内含 schema 与 rows。
Value::Array(statements) => {
let statement = statements
.into_iter()
.next()
.ok_or_else(|| "SQL 结果为空".to_string())?;
extract_sql_count_from_statement(statement)
}
// 保留兼容旧对象形状,便于本地/远端 API 小版本差异时仍能读取计数。
Value::Object(statement) => extract_sql_count_from_statement(Value::Object(statement)),
_ => Err("SQL 响应格式非法".to_string()),
}
}
fn extract_sql_count_from_statement(statement: Value) -> Result<u64, String> {
let Value::Object(mut statement) = statement else {
return Err("SQL statement 结果格式非法".to_string());
};
let schema = statement.remove("schema");
let rows = statement
.remove("rows")
.ok_or_else(|| "SQL 响应缺少 rows 字段".to_string())?;
extract_sql_count_from_rows(rows, schema.as_ref())
}
fn extract_sql_count_from_rows(rows: Value, schema: Option<&Value>) -> Result<u64, String> {
let Value::Array(rows) = rows else {
return Err("SQL rows 字段格式非法".to_string());
};
let row = rows.first().ok_or_else(|| "SQL 结果为空".to_string())?;
extract_sql_count_from_row(row, schema)
}
fn extract_sql_count_from_row(row: &Value, schema: Option<&Value>) -> Result<u64, String> {
match row {
Value::Object(columns) => extract_sql_count(columns),
Value::Array(values) => {
let count_index = schema.and_then(find_sql_count_column_index).unwrap_or(0);
values
.get(count_index)
.ok_or_else(|| "SQL 结果缺少 count 字段".to_string())
.and_then(parse_count_value)
}
value => parse_count_value(value),
}
}
fn extract_sql_count(columns: &serde_json::Map<String, Value>) -> Result<u64, String> {
for key in ["row_count", "count", "COUNT(*)"] {
if let Some(value) = columns.get(key) {
return parse_count_value(value);
@@ -432,6 +470,25 @@ fn extract_sql_count(columns: serde_json::Map<String, Value>) -> Result<u64, Str
.and_then(parse_count_value)
}
fn find_sql_count_column_index(schema: &Value) -> Option<usize> {
let elements = schema.get("elements")?.as_array()?;
elements.iter().position(|element| {
element
.get("name")
.and_then(extract_sql_schema_name)
.map(|name| matches!(name, "row_count" | "count" | "COUNT(*)"))
.unwrap_or(false)
})
}
fn extract_sql_schema_name(value: &Value) -> Option<&str> {
match value {
Value::String(text) => Some(text.as_str()),
Value::Object(object) => object.get("some").and_then(Value::as_str),
_ => None,
}
}
fn parse_count_value(value: &Value) -> Result<u64, String> {
match value {
Value::Number(number) => number
@@ -602,520 +659,14 @@ fn build_admin_session_payload(session: crate::state::AdminSession) -> AdminSess
}
}
// 首版后台页面内嵌在 api-server避免新增独立前端工程与静态资源发布链。
static ADMIN_CONSOLE_HTML: &str = r#"<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Genarrative 管理后台</title>
<style>
:root {
--bg: linear-gradient(180deg, #f4efe5 0%, #e7ddd0 100%);
--panel: rgba(255, 249, 240, 0.92);
--panel-strong: #fffaf2;
--line: rgba(90, 61, 41, 0.14);
--text: #2f241d;
--muted: #7b6657;
--accent: #b45a2f;
--accent-strong: #8f431f;
--ok: #2c7a54;
--danger: #a63f2f;
--shadow: 0 20px 50px rgba(70, 41, 19, 0.12);
--radius: 20px;
--font: "Microsoft YaHei", "PingFang SC", "Segoe UI", sans-serif;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: var(--font);
color: var(--text);
background: var(--bg);
min-height: 100vh;
}
.shell {
max-width: 1180px;
margin: 0 auto;
padding: 20px 16px 40px;
}
.hero {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
margin-bottom: 18px;
}
.hero h1 {
margin: 0;
font-size: 28px;
line-height: 1.1;
letter-spacing: 0.02em;
}
.hero p {
margin: 10px 0 0;
color: var(--muted);
font-size: 14px;
}
.status-chip {
padding: 10px 14px;
border-radius: 999px;
background: rgba(180, 90, 47, 0.1);
color: var(--accent-strong);
font-size: 13px;
white-space: nowrap;
}
.grid {
display: grid;
grid-template-columns: 340px minmax(0, 1fr);
gap: 16px;
}
.panel {
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.panel-head {
padding: 18px 18px 0;
}
.panel-head h2 {
margin: 0;
font-size: 18px;
}
.panel-head p {
margin: 8px 0 0;
color: var(--muted);
font-size: 13px;
}
.panel-body {
padding: 18px;
}
.form {
display: grid;
gap: 12px;
}
label {
display: grid;
gap: 6px;
font-size: 13px;
color: var(--muted);
}
input, textarea, select {
width: 100%;
border: 1px solid rgba(78, 53, 37, 0.12);
border-radius: 14px;
background: var(--panel-strong);
color: var(--text);
font: inherit;
padding: 12px 14px;
outline: none;
}
textarea {
min-height: 140px;
resize: vertical;
}
.btn-row {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
button {
border: none;
border-radius: 14px;
padding: 11px 16px;
background: var(--accent);
color: #fff8f2;
font: inherit;
cursor: pointer;
}
button.secondary {
background: rgba(180, 90, 47, 0.14);
color: var(--accent-strong);
}
button:disabled {
opacity: 0.6;
cursor: wait;
}
.stack {
display: grid;
gap: 16px;
}
.metrics {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 12px;
}
.metric {
padding: 14px;
border-radius: 16px;
border: 1px solid var(--line);
background: rgba(255,255,255,0.45);
}
.metric .k {
font-size: 12px;
color: var(--muted);
}
.metric .v {
margin-top: 8px;
font-size: 18px;
font-weight: 700;
}
.data-grid {
display: grid;
gap: 10px;
}
.row {
display: grid;
grid-template-columns: 160px 1fr;
gap: 10px;
font-size: 13px;
align-items: start;
padding: 10px 0;
border-bottom: 1px solid rgba(78, 53, 37, 0.08);
}
.row:last-child {
border-bottom: none;
}
.row .k {
color: var(--muted);
}
.table-list {
display: grid;
gap: 10px;
max-height: 420px;
overflow: auto;
padding-right: 4px;
}
.table-item {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 12px 14px;
border-radius: 14px;
background: rgba(255,255,255,0.52);
border: 1px solid rgba(78, 53, 37, 0.08);
align-items: center;
}
.table-item small {
color: var(--muted);
display: block;
margin-top: 4px;
}
.count {
font-weight: 700;
white-space: nowrap;
}
.count.err {
color: var(--danger);
font-weight: 600;
}
.result-panel {
border-radius: 16px;
border: 1px solid var(--line);
background: rgba(255,255,255,0.55);
padding: 14px;
display: grid;
gap: 10px;
}
pre {
margin: 0;
white-space: pre-wrap;
word-break: break-word;
font-size: 12px;
line-height: 1.5;
background: rgba(47, 36, 29, 0.06);
border-radius: 14px;
padding: 12px;
overflow: auto;
}
.hint {
font-size: 12px;
color: var(--muted);
}
.err-text { color: var(--danger); }
.ok-text { color: var(--ok); }
@media (max-width: 900px) {
.grid { grid-template-columns: 1fr; }
.hero { flex-direction: column; }
.row { grid-template-columns: 1fr; gap: 4px; }
}
</style>
</head>
<body>
<div class="shell">
<div class="hero">
<div>
<h1>Genarrative 管理后台</h1>
<p>查看服务状态、数据库概览,并对当前 API 做受控调试。</p>
</div>
<div id="admin-status" class="status-chip">未登录</div>
</div>
<div class="grid">
<div class="stack">
<section class="panel">
<div class="panel-head">
<h2>管理员登录</h2>
<p>使用配置的后台账号进入管理域。</p>
</div>
<div class="panel-body">
<form id="login-form" class="form">
<label>用户名
<input id="login-username" name="username" autocomplete="username" />
</label>
<label>密码
<input id="login-password" name="password" type="password" autocomplete="current-password" />
</label>
<div class="btn-row">
<button id="login-submit" type="submit">登录后台</button>
<button id="login-clear" class="secondary" type="button">清空令牌</button>
</div>
<div id="login-message" class="hint"></div>
</form>
</div>
</section>
<section class="panel">
<div class="panel-head">
<h2>API 调试</h2>
<p>对当前服务做同源受控请求。</p>
</div>
<div class="panel-body">
<form id="debug-form" class="form">
<label>方法
<select id="debug-method">
<option>GET</option>
<option>POST</option>
<option>PUT</option>
<option>DELETE</option>
<option>PATCH</option>
</select>
</label>
<label>路径
<input id="debug-path" value="/healthz" />
</label>
<label>附加请求头JSON 数组)
<textarea id="debug-headers">[]</textarea>
</label>
<label>请求体
<textarea id="debug-body"></textarea>
</label>
<div class="btn-row">
<button id="debug-submit" type="submit">发送调试请求</button>
</div>
</form>
</div>
</section>
</div>
<div class="stack">
<section class="panel">
<div class="panel-head">
<h2>数据库概览</h2>
<p>读取当前服务配置和 SpacetimeDB 数据库真相。</p>
</div>
<div class="panel-body">
<div class="btn-row" style="margin-bottom:14px;">
<button id="refresh-overview" type="button">刷新概览</button>
</div>
<div id="overview-metrics" class="metrics"></div>
<div id="overview-detail" class="data-grid" style="margin-top:14px;"></div>
<div id="overview-errors" class="hint err-text" style="margin-top:10px;"></div>
<div id="overview-tables" class="table-list" style="margin-top:14px;"></div>
</div>
</section>
<section class="panel">
<div class="panel-head">
<h2>调试结果</h2>
<p>返回状态、响应头和内容预览。</p>
</div>
<div class="panel-body">
<div id="debug-result" class="result-panel">
<div class="hint">尚未执行调试请求。</div>
</div>
</div>
</section>
</div>
</div>
</div>
<script>
const TOKEN_KEY = 'genarrative_admin_token';
const statusEl = document.getElementById('admin-status');
const loginMessageEl = document.getElementById('login-message');
const overviewMetricsEl = document.getElementById('overview-metrics');
const overviewDetailEl = document.getElementById('overview-detail');
const overviewTablesEl = document.getElementById('overview-tables');
const overviewErrorsEl = document.getElementById('overview-errors');
const debugResultEl = document.getElementById('debug-result');
function getToken() {
return window.localStorage.getItem(TOKEN_KEY) || '';
}
function setToken(token) {
if (!token) {
window.localStorage.removeItem(TOKEN_KEY);
return;
}
window.localStorage.setItem(TOKEN_KEY, token);
}
function setStatus(text, ok) {
statusEl.textContent = text;
statusEl.style.background = ok ? 'rgba(44,122,84,0.12)' : 'rgba(180,90,47,0.1)';
statusEl.style.color = ok ? '#2c7a54' : '#8f431f';
}
async function request(path, options = {}) {
const headers = new Headers(options.headers || {});
const token = getToken();
if (token) {
headers.set('authorization', `Bearer ${token}`);
}
if (options.json !== undefined) {
headers.set('content-type', 'application/json');
options.body = JSON.stringify(options.json);
}
const response = await fetch(path, { ...options, headers });
const text = await response.text();
let data = null;
try { data = text ? JSON.parse(text) : null; } catch (_) {}
if (!response.ok) {
const message = data?.error?.message || data?.message || text || `HTTP ${response.status}`;
throw new Error(message);
}
return data?.data ?? data;
}
function renderOverview(overview) {
const service = overview.service || {};
const database = overview.database || {};
const stats = Array.isArray(database.tableStats) ? database.tableStats : [];
overviewMetricsEl.innerHTML = `
<div class="metric"><div class="k">后台状态</div><div class="v">${service.adminEnabled ? '已启用' : '未启用'}</div></div>
<div class="metric"><div class="k">服务监听</div><div class="v">${service.bindHost || '-'}:${service.bindPort || '-'}</div></div>
<div class="metric"><div class="k">SpacetimeDB</div><div class="v">${service.spacetimeDatabase || '-'}</div></div>
<div class="metric"><div class="k">统计表数</div><div class="v">${stats.length}</div></div>
`;
overviewDetailEl.innerHTML = `
<div class="row"><div class="k">JWT Issuer</div><div>${service.jwtIssuer || '-'}</div></div>
<div class="row"><div class="k">Spacetime 服务</div><div>${service.spacetimeServerUrl || '-'}</div></div>
<div class="row"><div class="k">数据库 Identity</div><div>${database.databaseIdentity || '-'}</div></div>
<div class="row"><div class="k">Owner Identity</div><div>${database.ownerIdentity || '-'}</div></div>
<div class="row"><div class="k">Host Type</div><div>${database.hostType || '-'}</div></div>
<div class="row"><div class="k">Schema 表数量</div><div>${(database.schemaTableNames || []).length}</div></div>
`;
overviewTablesEl.innerHTML = stats.map((item) => `
<div class="table-item">
<div>
<strong>${item.tableName}</strong>
${item.errorMessage ? `<small class="err-text">${item.errorMessage}</small>` : ''}
</div>
<div class="count ${item.errorMessage ? 'err' : ''}">${item.rowCount ?? '失败'}</div>
</div>
`).join('');
overviewErrorsEl.textContent = (database.fetchErrors || []).join(' | ');
}
function renderDebugResult(result) {
const headerText = (result.headers || []).map((item) => `${item.name}: ${item.value}`).join('\n');
debugResultEl.innerHTML = `
<div><strong>状态:</strong><span class="${result.status < 400 ? 'ok-text' : 'err-text'}">${result.status} ${result.statusText}</span></div>
<div><strong>响应头</strong><pre>${headerText || '(无)'}</pre></div>
<div><strong>响应体预览</strong><pre>${result.bodyText || '(空)'}</pre></div>
<div><strong>响应 JSON</strong><pre>${result.bodyJson ? JSON.stringify(result.bodyJson, null, 2) : '(不是 JSON)'}</pre></div>
`;
}
async function loadMe() {
const token = getToken();
if (!token) {
setStatus('未登录', false);
return;
}
try {
const result = await request('/admin/api/me');
setStatus(`管理员:${result.admin.displayName}`, true);
} catch (error) {
setToken('');
setStatus('未登录', false);
}
}
async function loadOverview() {
try {
const overview = await request('/admin/api/overview');
renderOverview(overview);
} catch (error) {
overviewMetricsEl.innerHTML = '';
overviewDetailEl.innerHTML = '';
overviewTablesEl.innerHTML = '';
overviewErrorsEl.textContent = error.message;
}
}
document.getElementById('login-form').addEventListener('submit', async (event) => {
event.preventDefault();
loginMessageEl.textContent = '正在登录...';
try {
const result = await request('/admin/api/login', {
method: 'POST',
json: {
username: document.getElementById('login-username').value,
password: document.getElementById('login-password').value,
},
});
setToken(result.token);
loginMessageEl.textContent = '登录成功';
await loadMe();
await loadOverview();
} catch (error) {
loginMessageEl.textContent = error.message;
}
});
document.getElementById('login-clear').addEventListener('click', () => {
setToken('');
setStatus('未登录', false);
loginMessageEl.textContent = '已清空本地令牌';
});
document.getElementById('refresh-overview').addEventListener('click', async () => {
await loadOverview();
});
document.getElementById('debug-form').addEventListener('submit', async (event) => {
event.preventDefault();
debugResultEl.innerHTML = '<div class="hint">正在请求...</div>';
try {
const headers = JSON.parse(document.getElementById('debug-headers').value || '[]');
const result = await request('/admin/api/debug/http', {
method: 'POST',
json: {
method: document.getElementById('debug-method').value,
path: document.getElementById('debug-path').value,
headers,
body: document.getElementById('debug-body').value,
},
});
renderDebugResult(result);
} catch (error) {
debugResultEl.innerHTML = `<div class="err-text">${error.message}</div>`;
}
});
loadMe().then(loadOverview);
</script>
</body>
</html>"#;
#[cfg(test)]
mod tests {
use super::{build_body_preview, build_debug_base_url, normalize_debug_path, trim_preview};
use super::{
build_body_preview, build_debug_base_url, build_spacetime_schema_url, normalize_debug_path,
parse_spacetime_sql_count_response, trim_preview,
};
use axum::{http::StatusCode, response::IntoResponse};
use serde_json::json;
#[test]
fn normalize_debug_path_rejects_absolute_url() {
@@ -1161,6 +712,91 @@ mod tests {
assert_eq!(trim_preview(&text).chars().count(), 4000);
}
#[test]
fn build_spacetime_schema_url_includes_required_version_query() {
let url = build_spacetime_schema_url("http://127.0.0.1:3101", "xushi-p4wfr");
assert_eq!(
url,
"http://127.0.0.1:3101/v1/database/xushi-p4wfr/schema?version=9"
);
}
#[test]
fn parse_spacetime_sql_count_response_accepts_statement_array_rows() {
let payload = json!([
{
"schema": {
"elements": [
{
"name": {
"some": "row_count"
},
"algebraic_type": {
"U64": []
}
}
]
},
"rows": [[7]],
"total_duration_micros": 116,
"stats": {
"rows_inserted": 0,
"rows_deleted": 0,
"rows_updated": 0
}
}
]);
let count =
parse_spacetime_sql_count_response(payload).expect("statement array should parse");
assert_eq!(count, 7);
}
#[test]
fn parse_spacetime_sql_count_response_uses_schema_column_index() {
let payload = json!([
{
"schema": {
"elements": [
{
"name": {
"some": "table_name"
}
},
{
"name": {
"some": "row_count"
}
}
]
},
"rows": [["runtime_setting", "12"]]
}
]);
let count =
parse_spacetime_sql_count_response(payload).expect("schema column index should parse");
assert_eq!(count, 12);
}
#[test]
fn parse_spacetime_sql_count_response_keeps_object_row_compatibility() {
let payload = json!({
"rows": [
{
"row_count": "3"
}
]
});
let count = parse_spacetime_sql_count_response(payload).expect("object row should parse");
assert_eq!(count, 3);
}
#[test]
fn build_body_preview_handles_utf8() {
let preview = build_body_preview("后台测试".as_bytes());

View File

@@ -13,10 +13,7 @@ use tower_http::{
use tracing::{Level, Span, error, info, info_span, warn};
use crate::{
admin::{
admin_console_page, admin_debug_http, admin_login, admin_me, admin_overview,
require_admin_auth,
},
admin::{admin_debug_http, admin_login, admin_me, admin_overview, require_admin_auth},
ai_tasks::{
append_ai_text_chunk, attach_ai_result_reference, cancel_ai_task, complete_ai_stage,
complete_ai_task, create_ai_task, fail_ai_task, start_ai_task, start_ai_task_stage,
@@ -78,6 +75,13 @@ use crate::{
login_options::auth_login_options,
logout::logout,
logout_all::logout_all,
match3d::{
click_match3d_item, create_match3d_agent_session, delete_match3d_work,
execute_match3d_agent_action, finish_match3d_time_up, get_match3d_agent_session,
get_match3d_run, get_match3d_work_detail, get_match3d_works, list_match3d_gallery,
publish_match3d_work, put_match3d_work, restart_match3d_run, start_match3d_run,
stop_match3d_run, stream_match3d_agent_message, submit_match3d_agent_message,
},
password_entry::password_entry,
password_management::{change_password, reset_password},
phone_auth::{phone_login, send_phone_code},
@@ -105,10 +109,10 @@ use crate::{
},
runtime_inventory::get_runtime_inventory_state,
runtime_profile::{
admin_disable_profile_redeem_code, admin_upsert_profile_redeem_code,
create_profile_recharge_order, get_profile_dashboard, get_profile_play_stats,
get_profile_recharge_center, get_profile_referral_invite_center, get_profile_wallet_ledger,
redeem_profile_referral_invite_code, redeem_profile_reward_code,
admin_disable_profile_redeem_code, admin_upsert_profile_invite_code,
admin_upsert_profile_redeem_code, create_profile_recharge_order, get_profile_dashboard,
get_profile_play_stats, get_profile_recharge_center, get_profile_referral_invite_center,
get_profile_wallet_ledger, redeem_profile_referral_invite_code, redeem_profile_reward_code,
},
runtime_save::{
delete_runtime_snapshot, get_runtime_snapshot, list_profile_save_archives,
@@ -135,7 +139,6 @@ pub fn build_router(state: AppState) -> Router {
let slow_request_threshold_ms = state.config.slow_request_threshold_ms;
Router::new()
.route("/admin", get(admin_console_page))
.route("/admin/api/login", post(admin_login))
.route(
"/admin/api/me",
@@ -172,6 +175,13 @@ pub fn build_router(state: AppState) -> Router {
require_admin_auth,
)),
)
.route(
"/admin/api/profile/invite-codes",
post(admin_upsert_profile_invite_code).route_layer(middleware::from_fn_with_state(
state.clone(),
require_admin_auth,
)),
)
.route(
"/healthz",
get(|Extension(request_context): Extension<_>| async move {
@@ -702,6 +712,116 @@ pub fn build_router(state: AppState) -> Router {
require_bearer_auth,
)),
)
.route(
"/api/creation/match3d/sessions",
post(create_match3d_agent_session).route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route(
"/api/creation/match3d/sessions/{session_id}",
get(get_match3d_agent_session).route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route(
"/api/creation/match3d/sessions/{session_id}/messages",
post(submit_match3d_agent_message).route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route(
"/api/creation/match3d/sessions/{session_id}/messages/stream",
post(stream_match3d_agent_message).route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route(
"/api/creation/match3d/sessions/{session_id}/actions",
post(execute_match3d_agent_action).route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route(
"/api/creation/match3d/sessions/{session_id}/compile",
post(execute_match3d_agent_action).route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route(
"/api/creation/match3d/works",
get(get_match3d_works).route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route(
"/api/creation/match3d/works/{profile_id}",
get(get_match3d_work_detail)
.patch(put_match3d_work)
.put(put_match3d_work)
.delete(delete_match3d_work)
.route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route(
"/api/creation/match3d/works/{profile_id}/publish",
post(publish_match3d_work).route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route("/api/runtime/match3d/gallery", get(list_match3d_gallery))
.route(
"/api/runtime/match3d/works/{profile_id}/runs",
post(start_match3d_run).route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route(
"/api/runtime/match3d/runs/{run_id}",
get(get_match3d_run).route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route(
"/api/runtime/match3d/runs/{run_id}/click",
post(click_match3d_item).route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route(
"/api/runtime/match3d/runs/{run_id}/stop",
post(stop_match3d_run).route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route(
"/api/runtime/match3d/runs/{run_id}/restart",
post(restart_match3d_run).route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route(
"/api/runtime/match3d/runs/{run_id}/time-up",
post(finish_match3d_time_up).route_layer(middleware::from_fn_with_state(
state.clone(),
require_bearer_auth,
)),
)
.route(
"/api/runtime/puzzle/agent/sessions",
post(create_puzzle_agent_session)
@@ -1993,6 +2113,8 @@ mod tests {
payload["user"]["phoneNumberMasked"],
Value::String("138****8000".to_string())
);
assert_eq!(payload["created"], Value::Bool(true));
assert!(payload["referral"].is_null());
}
#[tokio::test]
@@ -2099,6 +2221,175 @@ mod tests {
serde_json::from_slice(&second_body).expect("second login payload should be json");
assert_eq!(first_payload["user"]["id"], second_payload["user"]["id"]);
assert_eq!(first_payload["created"], Value::Bool(true));
assert_eq!(second_payload["created"], Value::Bool(false));
assert!(second_payload["referral"].is_null());
}
#[tokio::test]
async fn phone_login_invite_code_failure_does_not_block_created_user() {
let config = AppConfig {
sms_auth_enabled: true,
..AppConfig::default()
};
let app = build_router(AppState::new(config).expect("state should build"));
let send_code_response = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/auth/phone/send-code")
.header("content-type", "application/json")
.body(Body::from(
serde_json::json!({
"phone": "13600136000",
"scene": "login"
})
.to_string(),
))
.expect("send code request should build"),
)
.await
.expect("send code request should succeed");
assert_eq!(send_code_response.status(), StatusCode::OK);
let login_response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/auth/phone/login")
.header("content-type", "application/json")
.body(Body::from(
serde_json::json!({
"phone": "13600136000",
"code": "123456",
"inviteCode": "SPRING2026"
})
.to_string(),
))
.expect("login request should build"),
)
.await
.expect("login request should succeed");
assert_eq!(login_response.status(), StatusCode::OK);
let body = login_response
.into_body()
.collect()
.await
.expect("login body should collect")
.to_bytes();
let payload: Value = serde_json::from_slice(&body).expect("login payload should be json");
assert!(payload["token"].as_str().is_some());
assert_eq!(payload["created"], Value::Bool(true));
assert_eq!(payload["referral"]["ok"], Value::Bool(false));
assert_eq!(
payload["referral"]["message"],
Value::String("邀请码无效,已继续注册".to_string())
);
}
#[tokio::test]
async fn phone_login_existing_user_ignores_invite_code() {
let config = AppConfig {
sms_auth_enabled: true,
..AppConfig::default()
};
let app = build_router(AppState::new(config).expect("state should build"));
let first_send_code_response = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/auth/phone/send-code")
.header("content-type", "application/json")
.body(Body::from(
serde_json::json!({
"phone": "13500135000",
"scene": "login"
})
.to_string(),
))
.expect("send code request should build"),
)
.await
.expect("send code request should succeed");
assert_eq!(first_send_code_response.status(), StatusCode::OK);
let first_login_response = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/auth/phone/login")
.header("content-type", "application/json")
.body(Body::from(
serde_json::json!({
"phone": "13500135000",
"code": "123456"
})
.to_string(),
))
.expect("first login request should build"),
)
.await
.expect("first login request should succeed");
assert_eq!(first_login_response.status(), StatusCode::OK);
let second_send_code_response = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/auth/phone/send-code")
.header("content-type", "application/json")
.body(Body::from(
serde_json::json!({
"phone": "13500135000",
"scene": "login"
})
.to_string(),
))
.expect("send code request should build"),
)
.await
.expect("send code request should succeed");
assert_eq!(second_send_code_response.status(), StatusCode::OK);
let second_login_response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/auth/phone/login")
.header("content-type", "application/json")
.body(Body::from(
serde_json::json!({
"phone": "13500135000",
"code": "123456",
"inviteCode": "SPRING2026"
})
.to_string(),
))
.expect("second login request should build"),
)
.await
.expect("second login request should succeed");
assert_eq!(second_login_response.status(), StatusCode::OK);
let body = second_login_response
.into_body()
.collect()
.await
.expect("second login body should collect")
.to_bytes();
let payload: Value =
serde_json::from_slice(&body).expect("second login payload should be json");
assert_eq!(payload["created"], Value::Bool(false));
assert!(payload["referral"].is_null());
}
#[tokio::test]
@@ -3314,6 +3605,23 @@ mod tests {
);
}
#[tokio::test]
async fn admin_page_route_is_not_mounted() {
let app = build_router(AppState::new(AppConfig::default()).expect("state should build"));
let response = app
.oneshot(
Request::builder()
.uri("/admin")
.body(Body::empty())
.expect("admin page request should build"),
)
.await
.expect("admin page request should succeed");
assert_eq!(response.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn admin_login_returns_token_when_configured() {
let mut config = AppConfig::default();

View File

@@ -40,6 +40,7 @@ mod llm_model_routing;
mod login_options;
mod logout;
mod logout_all;
mod match3d;
mod password_entry;
mod password_management;
mod phone_auth;

File diff suppressed because it is too large Load Diff

View File

@@ -9,7 +9,8 @@ use module_auth::{
};
use serde_json::json;
use shared_contracts::auth::{
PhoneLoginRequest, PhoneLoginResponse, PhoneSendCodeRequest, PhoneSendCodeResponse,
PhoneLoginReferralResponse, PhoneLoginRequest, PhoneLoginResponse, PhoneSendCodeRequest,
PhoneSendCodeResponse,
};
use time::OffsetDateTime;
use tracing::{info, warn};
@@ -110,6 +111,7 @@ pub async fn phone_login(
AppError::from_status(StatusCode::BAD_REQUEST).with_message("手机号登录暂未启用")
);
}
let invite_code = payload.invite_code.clone();
let result = match state
.phone_auth_service()
.login(
@@ -146,6 +148,18 @@ pub async fn phone_login(
return Err(map_phone_auth_error(error));
}
};
let created = result.created;
let referral = if created {
bind_referral_invite_code_on_registration(
&state,
&request_context,
result.user.id.clone(),
invite_code,
)
.await
} else {
None
};
let session_client = resolve_session_client_context(&headers);
let signed_session = create_auth_session(
&state,
@@ -174,11 +188,55 @@ pub async fn phone_login(
PhoneLoginResponse {
token: signed_session.access_token,
user: map_auth_user_payload(result.user),
created,
referral,
},
),
))
}
async fn bind_referral_invite_code_on_registration(
state: &AppState,
request_context: &RequestContext,
user_id: String,
invite_code: Option<String>,
) -> Option<PhoneLoginReferralResponse> {
let invite_code = invite_code
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())?;
let updated_at_micros = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000;
match state
.spacetime_client()
.redeem_profile_referral_invite_code(user_id, invite_code, updated_at_micros as i64)
.await
{
Ok(record) => Some(PhoneLoginReferralResponse {
ok: true,
message: Some("邀请码已绑定".to_string()),
invitee_reward_granted: record.invitee_reward_granted,
inviter_reward_granted: record.inviter_reward_granted,
invitee_balance_after: Some(record.invitee_balance_after),
inviter_balance_after: Some(record.inviter_balance_after),
}),
Err(error) => {
warn!(
request_id = request_context.request_id(),
operation = request_context.operation(),
error = %error,
"注册邀请码绑定失败,登录流程继续"
);
Some(PhoneLoginReferralResponse {
ok: false,
message: Some("邀请码无效,已继续注册".to_string()),
invitee_reward_granted: false,
inviter_reward_granted: false,
invitee_balance_after: None,
inviter_balance_after: None,
})
}
}
}
fn map_phone_auth_scene(raw_scene: Option<&str>) -> Result<PhoneAuthScene, AppError> {
match raw_scene.unwrap_or("login").trim() {
"login" => Ok(PhoneAuthScene::Login),

View File

@@ -5,18 +5,18 @@ use axum::{
response::Response,
};
use module_runtime::{
PROFILE_RECHARGE_PAYMENT_CHANNEL_MOCK, RuntimeProfileMembershipBenefitRecord,
RuntimeProfileRechargeCenterRecord, RuntimeProfileRechargeOrderRecord,
RuntimeProfileRechargeProductRecord, RuntimeProfileRedeemCodeMode,
RuntimeProfileRedeemCodeRecord, RuntimeProfileRewardCodeRedeemRecord,
RuntimeProfileWalletLedgerSourceType, RuntimeReferralInviteCenterRecord,
RuntimeReferralRedeemRecord,
PROFILE_RECHARGE_PAYMENT_CHANNEL_MOCK, RuntimeProfileInviteCodeRecord,
RuntimeProfileMembershipBenefitRecord, RuntimeProfileRechargeCenterRecord,
RuntimeProfileRechargeOrderRecord, RuntimeProfileRechargeProductRecord,
RuntimeProfileRedeemCodeMode, RuntimeProfileRedeemCodeRecord,
RuntimeProfileRewardCodeRedeemRecord, RuntimeProfileWalletLedgerSourceType,
RuntimeReferralInviteCenterRecord,
};
use serde_json::{Value, json};
use shared_contracts::runtime::{
AdminDisableProfileRedeemCodeRequest, AdminUpsertProfileRedeemCodeRequest,
CreateProfileRechargeOrderRequest, CreateProfileRechargeOrderResponse,
PROFILE_WALLET_LEDGER_SOURCE_TYPE_ASSET_OPERATION_CONSUME,
AdminDisableProfileRedeemCodeRequest, AdminUpsertProfileInviteCodeRequest,
AdminUpsertProfileRedeemCodeRequest, CreateProfileRechargeOrderRequest,
CreateProfileRechargeOrderResponse, PROFILE_WALLET_LEDGER_SOURCE_TYPE_ASSET_OPERATION_CONSUME,
PROFILE_WALLET_LEDGER_SOURCE_TYPE_ASSET_OPERATION_REFUND,
PROFILE_WALLET_LEDGER_SOURCE_TYPE_INVITE_INVITEE_REWARD,
PROFILE_WALLET_LEDGER_SOURCE_TYPE_INVITE_INVITER_REWARD,
@@ -24,13 +24,12 @@ use shared_contracts::runtime::{
PROFILE_WALLET_LEDGER_SOURCE_TYPE_PUZZLE_AUTHOR_INCENTIVE_CLAIM,
PROFILE_WALLET_LEDGER_SOURCE_TYPE_REDEEM_CODE_REWARD,
PROFILE_WALLET_LEDGER_SOURCE_TYPE_SNAPSHOT_SYNC, ProfileDashboardSummaryResponse,
ProfileMembershipBenefitResponse, ProfileMembershipResponse, ProfilePlayStatsResponse,
ProfilePlayedWorkSummaryResponse, ProfileRechargeCenterResponse, ProfileRechargeOrderResponse,
ProfileRechargeProductResponse, ProfileRedeemCodeAdminResponse,
ProfileInviteCodeAdminResponse, ProfileMembershipBenefitResponse, ProfileMembershipResponse,
ProfilePlayStatsResponse, ProfilePlayedWorkSummaryResponse, ProfileRechargeCenterResponse,
ProfileRechargeOrderResponse, ProfileRechargeProductResponse, ProfileRedeemCodeAdminResponse,
ProfileReferralInviteCenterResponse, ProfileWalletLedgerEntryResponse,
ProfileWalletLedgerResponse, RedeemProfileReferralInviteCodeRequest,
RedeemProfileReferralInviteCodeResponse, RedeemProfileRewardCodeRequest,
RedeemProfileRewardCodeResponse,
RedeemProfileRewardCodeRequest, RedeemProfileRewardCodeResponse,
};
use spacetime_client::SpacetimeClientError;
use time::OffsetDateTime;
@@ -217,27 +216,14 @@ pub async fn get_profile_referral_invite_center(
}
pub async fn redeem_profile_referral_invite_code(
State(state): State<AppState>,
State(_state): State<AppState>,
Extension(request_context): Extension<RequestContext>,
Extension(authenticated): Extension<AuthenticatedAccessToken>,
Json(payload): Json<RedeemProfileReferralInviteCodeRequest>,
Extension(_authenticated): Extension<AuthenticatedAccessToken>,
Json(_payload): Json<RedeemProfileReferralInviteCodeRequest>,
) -> Result<Json<Value>, Response> {
let user_id = authenticated.claims().user_id().to_string();
let updated_at_micros = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000;
let record = state
.spacetime_client()
.redeem_profile_referral_invite_code(user_id, payload.invite_code, updated_at_micros as i64)
.await
.map_err(|error| {
runtime_profile_error_response(
&request_context,
map_runtime_profile_client_error(error),
)
})?;
Ok(json_success_body(
Some(&request_context),
build_redeem_profile_referral_invite_code_response(record),
Err(runtime_profile_error_response(
&request_context,
AppError::from_status(StatusCode::BAD_REQUEST).with_message("邀请码仅注册时填写"),
))
}
@@ -334,6 +320,37 @@ pub async fn admin_disable_profile_redeem_code(
))
}
pub async fn admin_upsert_profile_invite_code(
State(state): State<AppState>,
Extension(request_context): Extension<RequestContext>,
Extension(admin): Extension<AuthenticatedAdmin>,
Json(payload): Json<AdminUpsertProfileInviteCodeRequest>,
) -> Result<Json<Value>, Response> {
let metadata_json = normalize_admin_invite_code_metadata(payload.metadata)
.map_err(|error| runtime_profile_error_response(&request_context, error))?;
let updated_at_micros = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000;
let record = state
.spacetime_client()
.admin_upsert_profile_invite_code(
admin.session().username.clone(),
payload.invite_code,
metadata_json,
updated_at_micros as i64,
)
.await
.map_err(|error| {
runtime_profile_error_response(
&request_context,
map_runtime_profile_client_error(error),
)
})?;
Ok(json_success_body(
Some(&request_context),
build_profile_invite_code_admin_response(record),
))
}
pub async fn get_profile_play_stats(
State(state): State<AppState>,
Extension(request_context): Extension<RequestContext>,
@@ -490,18 +507,6 @@ fn build_profile_referral_invite_center_response(
}
}
fn build_redeem_profile_referral_invite_code_response(
record: RuntimeReferralRedeemRecord,
) -> RedeemProfileReferralInviteCodeResponse {
RedeemProfileReferralInviteCodeResponse {
center: build_profile_referral_invite_center_response(record.center),
invitee_reward_granted: record.invitee_reward_granted,
inviter_reward_granted: record.inviter_reward_granted,
invitee_balance_after: record.invitee_balance_after,
inviter_balance_after: record.inviter_balance_after,
}
}
fn build_redeem_profile_reward_code_response(
record: RuntimeProfileRewardCodeRedeemRecord,
) -> RedeemProfileRewardCodeResponse {
@@ -519,6 +524,30 @@ fn build_redeem_profile_reward_code_response(
}
}
fn normalize_admin_invite_code_metadata(metadata: Option<Value>) -> Result<String, AppError> {
let metadata = match metadata {
Some(Value::Null) | None => json!({}),
Some(value) if value.is_object() => value,
Some(_) => {
return Err(AppError::from_status(StatusCode::BAD_REQUEST)
.with_message("邀请码 metadata 必须是 JSON 对象")
.with_details(json!({ "field": "metadata" })));
}
};
let metadata_json = serde_json::to_string(&metadata).map_err(|error| {
AppError::from_status(StatusCode::BAD_REQUEST)
.with_message(format!("邀请码 metadata 序列化失败:{error}"))
.with_details(json!({ "field": "metadata" }))
})?;
if metadata_json.len() > 4096 {
return Err(AppError::from_status(StatusCode::BAD_REQUEST)
.with_message("邀请码 metadata 不能超过 4096 bytes")
.with_details(json!({ "field": "metadata" })));
}
Ok(metadata_json)
}
fn parse_profile_redeem_code_mode(raw: &str) -> Result<RuntimeProfileRedeemCodeMode, String> {
match raw.trim().to_ascii_lowercase().as_str() {
"public" => Ok(RuntimeProfileRedeemCodeMode::Public),
@@ -528,6 +557,20 @@ fn parse_profile_redeem_code_mode(raw: &str) -> Result<RuntimeProfileRedeemCodeM
}
}
fn build_profile_invite_code_admin_response(
record: RuntimeProfileInviteCodeRecord,
) -> ProfileInviteCodeAdminResponse {
let metadata =
serde_json::from_str::<Value>(&record.metadata_json).unwrap_or_else(|_| json!({}));
ProfileInviteCodeAdminResponse {
user_id: record.user_id,
invite_code: record.invite_code,
metadata,
created_at: record.created_at,
updated_at: record.updated_at,
}
}
fn build_profile_redeem_code_admin_response(
record: RuntimeProfileRedeemCodeRecord,
) -> ProfileRedeemCodeAdminResponse {
@@ -549,7 +592,7 @@ fn build_profile_redeem_code_admin_response(
mod tests {
use module_runtime::RuntimeProfileWalletLedgerSourceType;
use super::format_profile_wallet_ledger_source_type;
use super::{format_profile_wallet_ledger_source_type, normalize_admin_invite_code_metadata};
use axum::{
body::Body,
@@ -715,6 +758,60 @@ mod tests {
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn profile_referral_redeem_code_rejects_authenticated_manual_fill() {
let state = seed_authenticated_state().await;
let token = issue_access_token(&state);
let app = build_router(state);
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/profile/referrals/redeem-code")
.header("authorization", format!("Bearer {token}"))
.header("content-type", "application/json")
.body(Body::from(r#"{"inviteCode":"SY12345678"}"#))
.expect("request should build"),
)
.await
.expect("request should succeed");
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let body = response
.into_body()
.collect()
.await
.expect("body should collect")
.to_bytes();
let payload: Value =
serde_json::from_slice(&body).expect("response body should be valid json");
assert_eq!(
payload["error"]["message"],
Value::String("邀请码仅注册时填写".to_string())
);
}
#[test]
fn admin_invite_code_metadata_accepts_only_json_object() {
assert_eq!(
normalize_admin_invite_code_metadata(None).expect("empty metadata should default"),
"{}"
);
assert_eq!(
normalize_admin_invite_code_metadata(Some(serde_json::json!({
"channel": "spring",
"source": "banner"
})))
.expect("object metadata should serialize"),
r#"{"channel":"spring","source":"banner"}"#
);
let error = normalize_admin_invite_code_metadata(Some(serde_json::json!("spring")))
.expect_err("non-object metadata should reject");
assert_eq!(error.message(), "邀请码 metadata 必须是 JSON 对象");
}
#[tokio::test]
async fn profile_dashboard_compat_route_matches_main_route_error_shape() {
assert_compat_route_matches_main_route_error_shape(

View File

@@ -17,6 +17,8 @@ pub const MAX_BROWSE_HISTORY_BATCH_SIZE: usize = 100;
pub const PROFILE_WALLET_LEDGER_LIST_LIMIT: usize = 50;
pub const PROFILE_REFERRAL_REWARD_POINTS: u64 = 30;
pub const PROFILE_REFERRAL_DAILY_INVITER_REWARD_LIMIT: u32 = 10;
pub const PROFILE_INVITE_CODE_METADATA_DEFAULT_JSON: &str = "{}";
const PROFILE_INVITE_CODE_METADATA_MAX_BYTES: usize = 4096;
pub const SAVE_SNAPSHOT_VERSION: u32 = 2;
pub const DEFAULT_SAVE_ARCHIVE_SUMMARY_TEXT: &str = "继续推进上一次保存的故事。";
pub const PROFILE_RECHARGE_PAYMENT_CHANNEL_MOCK: &str = "mock";
@@ -503,6 +505,33 @@ pub struct RuntimeProfileRedeemCodeAdminProcedureResult {
pub error_message: Option<String>,
}
#[cfg_attr(feature = "spacetime-types", derive(SpacetimeType))]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RuntimeProfileInviteCodeAdminUpsertInput {
pub admin_user_id: String,
pub invite_code: String,
pub metadata_json: String,
pub updated_at_micros: i64,
}
#[cfg_attr(feature = "spacetime-types", derive(SpacetimeType))]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RuntimeProfileInviteCodeSnapshot {
pub user_id: String,
pub invite_code: String,
pub metadata_json: String,
pub created_at_micros: i64,
pub updated_at_micros: i64,
}
#[cfg_attr(feature = "spacetime-types", derive(SpacetimeType))]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RuntimeProfileInviteCodeAdminProcedureResult {
pub ok: bool,
pub record: Option<RuntimeProfileInviteCodeSnapshot>,
pub error_message: Option<String>,
}
#[cfg_attr(feature = "spacetime-types", derive(SpacetimeType))]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RuntimeReferralInviteCenterSnapshot {
@@ -616,6 +645,7 @@ pub enum RuntimeProfileFieldError {
MissingLedgerId,
InvalidWalletAmount,
MissingInviteCode,
InvalidInviteCodeMetadata,
MissingRedeemCode,
InvalidRedeemCodeReward,
InvalidRedeemCodeMaxUses,
@@ -917,6 +947,17 @@ pub struct RuntimeProfileRedeemCodeRecord {
pub updated_at_micros: i64,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RuntimeProfileInviteCodeRecord {
pub user_id: String,
pub invite_code: String,
pub metadata_json: String,
pub created_at: String,
pub created_at_micros: i64,
pub updated_at: String,
pub updated_at_micros: i64,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RuntimeReferralInviteCenterRecord {
pub user_id: String,
@@ -1142,6 +1183,25 @@ pub fn build_runtime_profile_redeem_code_admin_disable_input(
})
}
pub fn build_runtime_profile_invite_code_admin_upsert_input(
admin_user_id: String,
invite_code: String,
metadata_json: String,
updated_at_micros: i64,
) -> Result<RuntimeProfileInviteCodeAdminUpsertInput, RuntimeProfileFieldError> {
let admin_user_id = normalize_runtime_profile_user_id(admin_user_id)?;
let invite_code =
normalize_invite_code(invite_code).ok_or(RuntimeProfileFieldError::MissingInviteCode)?;
let metadata_json = normalize_invite_code_metadata_json(metadata_json)?;
Ok(RuntimeProfileInviteCodeAdminUpsertInput {
admin_user_id,
invite_code,
metadata_json,
updated_at_micros,
})
}
pub fn build_runtime_profile_play_stats_get_input(
user_id: String,
) -> Result<RuntimeProfilePlayStatsGetInput, RuntimeProfileFieldError> {
@@ -1524,6 +1584,20 @@ pub fn build_runtime_profile_redeem_code_record(
}
}
pub fn build_runtime_profile_invite_code_record(
snapshot: RuntimeProfileInviteCodeSnapshot,
) -> RuntimeProfileInviteCodeRecord {
RuntimeProfileInviteCodeRecord {
user_id: snapshot.user_id,
invite_code: snapshot.invite_code,
metadata_json: snapshot.metadata_json,
created_at: format_utc_micros(snapshot.created_at_micros),
created_at_micros: snapshot.created_at_micros,
updated_at: format_utc_micros(snapshot.updated_at_micros),
updated_at_micros: snapshot.updated_at_micros,
}
}
pub fn build_runtime_profile_played_world_record(
snapshot: RuntimeProfilePlayedWorldSnapshot,
) -> RuntimeProfilePlayedWorldRecord {
@@ -1949,6 +2023,25 @@ pub fn normalize_invite_code(value: String) -> Option<String> {
}
}
pub fn normalize_invite_code_metadata_json(
value: String,
) -> Result<String, RuntimeProfileFieldError> {
let trimmed = value.trim();
if trimmed.is_empty() {
return Ok(PROFILE_INVITE_CODE_METADATA_DEFAULT_JSON.to_string());
}
if trimmed.len() > PROFILE_INVITE_CODE_METADATA_MAX_BYTES {
return Err(RuntimeProfileFieldError::InvalidInviteCodeMetadata);
}
let parsed = serde_json::from_str::<Value>(trimmed)
.map_err(|_| RuntimeProfileFieldError::InvalidInviteCodeMetadata)?;
if !parsed.is_object() {
return Err(RuntimeProfileFieldError::InvalidInviteCodeMetadata);
}
serde_json::to_string(&parsed).map_err(|_| RuntimeProfileFieldError::InvalidInviteCodeMetadata)
}
pub fn normalize_redeem_code(value: String) -> Option<String> {
normalize_invite_code(value)
}
@@ -1960,6 +2053,9 @@ impl std::fmt::Display for RuntimeProfileFieldError {
Self::MissingLedgerId => f.write_str("profile.wallet_ledger_id 不能为空"),
Self::InvalidWalletAmount => f.write_str("profile.wallet_amount 必须大于 0"),
Self::MissingInviteCode => f.write_str("referral.invite_code 不能为空"),
Self::InvalidInviteCodeMetadata => {
f.write_str("邀请码 metadata 必须是 JSON 对象且不超过 4096 bytes")
}
Self::MissingRedeemCode => f.write_str("兑换码不能为空"),
Self::InvalidRedeemCodeReward => f.write_str("兑换码奖励无效"),
Self::InvalidRedeemCodeMaxUses => f.write_str("兑换次数必须大于 0"),
@@ -2204,6 +2300,41 @@ mod tests {
);
}
#[test]
fn invite_code_metadata_defaults_to_empty_object() {
assert_eq!(
normalize_invite_code_metadata_json(" ".to_string()).expect("blank metadata defaults"),
"{}"
);
}
#[test]
fn invite_code_metadata_requires_json_object() {
assert_eq!(
normalize_invite_code_metadata_json("[]".to_string()).expect_err("array rejects"),
RuntimeProfileFieldError::InvalidInviteCodeMetadata
);
assert_eq!(
normalize_invite_code_metadata_json("{bad".to_string()).expect_err("bad json rejects"),
RuntimeProfileFieldError::InvalidInviteCodeMetadata
);
}
#[test]
fn build_admin_invite_code_input_normalizes_code_and_compacts_metadata() {
let input = build_runtime_profile_invite_code_admin_upsert_input(
" admin-user ".to_string(),
" spring-2026 ".to_string(),
r#"{ "channel": "spring", "batch": 1 }"#.to_string(),
1_776_000_000_000_000,
)
.expect("admin invite input should build");
assert_eq!(input.admin_user_id, "admin-user");
assert_eq!(input.invite_code, "SPRING2026");
assert_eq!(input.metadata_json, r#"{"batch":1,"channel":"spring"}"#);
}
#[test]
fn profile_dashboard_record_formats_optional_timestamp() {
let record = build_runtime_profile_dashboard_record(RuntimeProfileDashboardSnapshot {

View File

@@ -164,6 +164,8 @@ pub struct PhoneSendCodeResponse {
pub struct PhoneLoginRequest {
pub phone: String,
pub code: String,
#[serde(default)]
pub invite_code: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
@@ -171,6 +173,19 @@ pub struct PhoneLoginRequest {
pub struct PhoneLoginResponse {
pub token: String,
pub user: AuthUserPayload,
pub created: bool,
pub referral: Option<PhoneLoginReferralResponse>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PhoneLoginReferralResponse {
pub ok: bool,
pub message: Option<String>,
pub invitee_reward_granted: bool,
pub inviter_reward_granted: bool,
pub invitee_balance_after: Option<u64>,
pub inviter_balance_after: Option<u64>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]

View File

@@ -55,8 +55,11 @@ pub struct Match3DCreatorConfigResponse {
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Match3DResultDraftResponse {
pub profile_id: String,
pub game_name: String,
pub theme_text: String,
#[serde(default)]
pub summary_text: Option<String>,
pub summary: String,
pub tags: Vec<String>,
#[serde(default)]
@@ -65,10 +68,28 @@ pub struct Match3DResultDraftResponse {
pub reference_image_src: Option<String>,
pub clear_count: u32,
pub difficulty: u32,
pub total_item_count: u32,
pub publish_ready: bool,
pub blockers: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Match3DAnchorItemResponse {
pub key: String,
pub label: String,
pub value: String,
pub status: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Match3DAnchorPackResponse {
pub theme: Match3DAnchorItemResponse,
pub clear_count: Match3DAnchorItemResponse,
pub difficulty: Match3DAnchorItemResponse,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Match3DAgentMessageResponse {
@@ -86,6 +107,7 @@ pub struct Match3DAgentSessionSnapshotResponse {
pub current_turn: u32,
pub progress_percent: u32,
pub stage: String,
pub anchor_pack: Match3DAnchorPackResponse,
#[serde(default)]
pub config: Option<Match3DCreatorConfigResponse>,
#[serde(default)]

View File

@@ -4,6 +4,8 @@ use serde::{Deserialize, Serialize};
#[serde(rename_all = "camelCase")]
pub struct PutMatch3DWorkRequest {
pub game_name: String,
#[serde(default)]
pub theme_text: Option<String>,
pub summary: String,
pub tags: Vec<String>,
#[serde(default)]
@@ -74,6 +76,7 @@ mod tests {
fn match3d_work_request_uses_camel_case() {
let payload = serde_json::to_value(PutMatch3DWorkRequest {
game_name: "水果抓大鹅".to_string(),
theme_text: Some("水果".to_string()),
summary: "水果主题".to_string(),
tags: vec!["水果".to_string()],
cover_image_src: None,

View File

@@ -298,6 +298,14 @@ pub struct AdminUpsertProfileRedeemCodeRequest {
pub allowed_public_user_codes: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AdminUpsertProfileInviteCodeRequest {
pub invite_code: String,
#[serde(default)]
pub metadata: Option<serde_json::Value>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AdminDisableProfileRedeemCodeRequest {
@@ -319,6 +327,16 @@ pub struct ProfileRedeemCodeAdminResponse {
pub updated_at: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProfileInviteCodeAdminResponse {
pub user_id: String,
pub invite_code: String,
pub metadata: serde_json::Value,
pub created_at: String,
pub updated_at: String,
}
fn default_true() -> bool {
true
}

View File

@@ -11,6 +11,7 @@ module-big-fish = { path = "../module-big-fish" }
module-combat = { path = "../module-combat" }
module-custom-world = { path = "../module-custom-world" }
module-inventory = { path = "../module-inventory" }
module-match3d = { path = "../module-match3d" }
module-npc = { path = "../module-npc" }
module-puzzle = { path = "../module-puzzle" }
module-runtime = { path = "../module-runtime" }

View File

@@ -32,6 +32,14 @@ pub use mapper::{
PuzzleAgentSessionRecord, PuzzleAgentSuggestedActionRecord, PuzzleAnchorItemRecord,
PuzzleAnchorPackRecord, PuzzleBoardRecord, PuzzleCellPositionRecord, PuzzleCreatorIntentRecord,
PuzzleDraftLevelRecord, PuzzleFormDraftRecord, PuzzleFormDraftSaveRecordInput,
Match3DAgentMessageFinalizeRecordInput, Match3DAgentMessageRecord,
Match3DAgentMessageSubmitRecordInput, Match3DAgentSessionCreateRecordInput,
Match3DAgentSessionRecord, Match3DAnchorItemRecord, Match3DAnchorPackRecord,
Match3DClickConfirmationRecord, Match3DCompileDraftRecordInput, Match3DCreatorConfigRecord,
Match3DItemSnapshotRecord, Match3DResultDraftRecord, Match3DRunClickRecordInput,
Match3DRunRecord, Match3DRunRestartRecordInput, Match3DRunStartRecordInput,
Match3DRunStopRecordInput, Match3DRunTimeUpRecordInput, Match3DTraySlotRecord,
Match3DWorkProfileRecord, Match3DWorkUpdateRecordInput,
PuzzleGeneratedImageCandidateRecord, PuzzleGeneratedImagesSaveRecordInput,
PuzzleLeaderboardEntryRecord, PuzzleLeaderboardSubmitRecordInput, PuzzleMergedGroupRecord,
PuzzlePieceStateRecord, PuzzlePublishRecordInput, PuzzleRecommendedNextWorkRecord,
@@ -51,6 +59,7 @@ pub mod big_fish;
pub mod combat;
pub mod custom_world;
pub mod inventory;
pub mod match3d;
pub mod npc;
pub mod puzzle;
pub mod runtime;
@@ -124,7 +133,7 @@ use module_puzzle::{
};
use module_runtime::{
RuntimeBrowseHistoryRecord, RuntimePlatformTheme as DomainRuntimePlatformTheme,
RuntimeProfileDashboardRecord, RuntimeProfilePlayStatsRecord,
RuntimeProfileDashboardRecord, RuntimeProfileInviteCodeRecord, RuntimeProfilePlayStatsRecord,
RuntimeProfileRechargeCenterRecord, RuntimeProfileRechargeOrderRecord,
RuntimeProfileRedeemCodeMode as DomainRuntimeProfileRedeemCodeMode,
RuntimeProfileRedeemCodeRecord, RuntimeProfileRewardCodeRedeemRecord,
@@ -133,7 +142,8 @@ use module_runtime::{
RuntimeSnapshotRecord, build_runtime_browse_history_clear_input,
build_runtime_browse_history_list_input, build_runtime_browse_history_record,
build_runtime_browse_history_sync_input, build_runtime_profile_dashboard_get_input,
build_runtime_profile_dashboard_record, build_runtime_profile_play_stats_get_input,
build_runtime_profile_dashboard_record, build_runtime_profile_invite_code_admin_upsert_input,
build_runtime_profile_invite_code_record, build_runtime_profile_play_stats_get_input,
build_runtime_profile_play_stats_record, build_runtime_profile_recharge_center_get_input,
build_runtime_profile_recharge_center_record,
build_runtime_profile_recharge_order_create_input,

View File

@@ -203,6 +203,19 @@ impl From<module_runtime::RuntimeProfileRedeemCodeAdminDisableInput>
}
}
impl From<module_runtime::RuntimeProfileInviteCodeAdminUpsertInput>
for RuntimeProfileInviteCodeAdminUpsertInput
{
fn from(input: module_runtime::RuntimeProfileInviteCodeAdminUpsertInput) -> Self {
Self {
admin_user_id: input.admin_user_id,
invite_code: input.invite_code,
metadata_json: input.metadata_json,
updated_at_micros: input.updated_at_micros,
}
}
}
impl From<module_runtime::RuntimeReferralInviteCenterGetInput>
for RuntimeReferralInviteCenterGetInput
{
@@ -886,6 +899,26 @@ pub(crate) fn map_runtime_profile_redeem_code_admin_procedure_result(
))
}
pub(crate) fn map_runtime_profile_invite_code_admin_procedure_result(
result: RuntimeProfileInviteCodeAdminProcedureResult,
) -> Result<RuntimeProfileInviteCodeRecord, SpacetimeClientError> {
if !result.ok {
return Err(SpacetimeClientError::Procedure(
result
.error_message
.unwrap_or_else(|| "SpacetimeDB procedure 返回未知错误".to_string()),
));
}
let snapshot = result.record.ok_or_else(|| {
SpacetimeClientError::Procedure("SpacetimeDB procedure 未返回 invite code 快照".to_string())
})?;
Ok(build_runtime_profile_invite_code_record(
map_runtime_profile_invite_code_snapshot(snapshot),
))
}
pub(crate) fn map_runtime_profile_play_stats_procedure_result(
result: RuntimeProfilePlayStatsProcedureResult,
) -> Result<RuntimeProfilePlayStatsRecord, SpacetimeClientError> {
@@ -1388,6 +1421,132 @@ pub(crate) fn map_big_fish_works_procedure_result(
.collect())
}
pub(crate) fn map_match3d_agent_session_procedure_result(
result: Match3DAgentSessionProcedureResult,
) -> Result<Match3DAgentSessionRecord, SpacetimeClientError> {
if !result.ok {
return Err(SpacetimeClientError::Procedure(
result
.error_message
.unwrap_or_else(|| "SpacetimeDB procedure 返回未知错误".to_string()),
));
}
let session_json = result.session_json.ok_or_else(|| {
SpacetimeClientError::Procedure(
"SpacetimeDB procedure 未返回 match3d agent session 快照".to_string(),
)
})?;
let session =
serde_json::from_str::<Match3DAgentSessionJsonRecord>(&session_json).map_err(|error| {
SpacetimeClientError::Runtime(format!("match3d session_json 非法: {error}"))
})?;
Ok(map_match3d_agent_session_snapshot(session))
}
pub(crate) fn map_match3d_work_procedure_result(
result: Match3DWorkProcedureResult,
) -> Result<Match3DWorkProfileRecord, SpacetimeClientError> {
if !result.ok {
return Err(SpacetimeClientError::Procedure(
result
.error_message
.unwrap_or_else(|| "SpacetimeDB procedure 返回未知错误".to_string()),
));
}
let work_json = result.work_json.ok_or_else(|| {
SpacetimeClientError::Procedure(
"SpacetimeDB procedure 未返回 match3d work 快照".to_string(),
)
})?;
let work = serde_json::from_str::<Match3DWorkJsonRecord>(&work_json).map_err(|error| {
SpacetimeClientError::Runtime(format!("match3d work_json 非法: {error}"))
})?;
Ok(map_match3d_work_snapshot(work))
}
pub(crate) fn map_match3d_works_procedure_result(
result: Match3DWorksProcedureResult,
) -> Result<Vec<Match3DWorkProfileRecord>, SpacetimeClientError> {
if !result.ok {
return Err(SpacetimeClientError::Procedure(
result
.error_message
.unwrap_or_else(|| "SpacetimeDB procedure 返回未知错误".to_string()),
));
}
let items_json = result.items_json.ok_or_else(|| {
SpacetimeClientError::Procedure(
"SpacetimeDB procedure 未返回 match3d works 快照".to_string(),
)
})?;
let items =
serde_json::from_str::<Vec<Match3DWorkJsonRecord>>(&items_json).map_err(|error| {
SpacetimeClientError::Runtime(format!("match3d works items_json 非法: {error}"))
})?;
Ok(items.into_iter().map(map_match3d_work_snapshot).collect())
}
pub(crate) fn map_match3d_run_procedure_result(
result: Match3DRunProcedureResult,
) -> Result<Match3DRunRecord, SpacetimeClientError> {
if !result.ok {
return Err(SpacetimeClientError::Procedure(
result
.error_message
.unwrap_or_else(|| "SpacetimeDB procedure 返回未知错误".to_string()),
));
}
let run_json = result.run_json.ok_or_else(|| {
SpacetimeClientError::Procedure("SpacetimeDB procedure 未返回 match3d run 快照".to_string())
})?;
map_match3d_run_json(run_json)
}
pub(crate) fn map_match3d_click_item_procedure_result(
result: Match3DClickItemProcedureResult,
) -> Result<Match3DClickConfirmationRecord, SpacetimeClientError> {
if !result.ok {
return Err(SpacetimeClientError::Procedure(
result
.error_message
.unwrap_or_else(|| "SpacetimeDB procedure 返回未知错误".to_string()),
));
}
let run_json = result.run_json.ok_or_else(|| {
SpacetimeClientError::Procedure(
"SpacetimeDB procedure 未返回 match3d click run 快照".to_string(),
)
})?;
let run = map_match3d_run_json(run_json)?;
let accepted = result.status == "Accepted";
let accepted_item_instance_id = result.accepted_item_instance_id.clone();
let entered_slot_index = accepted_item_instance_id.as_deref().and_then(|item_id| {
run.items
.iter()
.find(|item| item.item_instance_id == item_id)
.and_then(|item| item.tray_slot_index)
});
Ok(Match3DClickConfirmationRecord {
status: result.status.clone(),
accepted,
reject_reason: if accepted { None } else { Some(result.status) },
accepted_item_instance_id,
entered_slot_index,
cleared_item_instance_ids: result.cleared_item_instance_ids,
failure_reason: result.failure_reason,
run,
})
}
pub(crate) fn map_story_session_procedure_result(
result: StorySessionProcedureResult,
) -> Result<StorySessionResultRecord, SpacetimeClientError> {
@@ -1784,6 +1943,18 @@ pub(crate) fn map_runtime_profile_redeem_code_snapshot(
}
}
pub(crate) fn map_runtime_profile_invite_code_snapshot(
snapshot: RuntimeProfileInviteCodeSnapshot,
) -> module_runtime::RuntimeProfileInviteCodeSnapshot {
module_runtime::RuntimeProfileInviteCodeSnapshot {
user_id: snapshot.user_id,
invite_code: snapshot.invite_code,
metadata_json: snapshot.metadata_json,
created_at_micros: snapshot.created_at_micros,
updated_at_micros: snapshot.updated_at_micros,
}
}
pub(crate) fn map_runtime_profile_played_world_snapshot(
snapshot: RuntimeProfilePlayedWorldSnapshot,
) -> module_runtime::RuntimeProfilePlayedWorldSnapshot {
@@ -2363,6 +2534,236 @@ pub(crate) fn map_puzzle_agent_message_snapshot(
}
}
fn map_match3d_agent_session_snapshot(
snapshot: Match3DAgentSessionJsonRecord,
) -> Match3DAgentSessionRecord {
let config = map_match3d_creator_config(snapshot.config);
Match3DAgentSessionRecord {
session_id: snapshot.session_id,
current_turn: snapshot.current_turn,
progress_percent: snapshot.progress_percent,
stage: normalize_match3d_stage(&snapshot.stage).to_string(),
anchor_pack: build_match3d_anchor_pack(&config),
draft: snapshot
.draft
.map(|draft| map_match3d_result_draft(draft, config.reference_image_src.clone())),
config: Some(config),
messages: snapshot
.messages
.into_iter()
.map(map_match3d_agent_message_snapshot)
.collect(),
last_assistant_reply: empty_string_to_none(snapshot.last_assistant_reply),
published_profile_id: snapshot.published_profile_id,
updated_at: format_timestamp_micros(snapshot.updated_at_micros),
}
}
fn map_match3d_creator_config(
snapshot: Match3DCreatorConfigJsonRecord,
) -> Match3DCreatorConfigRecord {
Match3DCreatorConfigRecord {
theme_text: snapshot.theme_text,
reference_image_src: snapshot.reference_image_src,
clear_count: snapshot.clear_count,
difficulty: snapshot.difficulty,
}
}
fn map_match3d_result_draft(
snapshot: Match3DDraftJsonRecord,
reference_image_src: Option<String>,
) -> Match3DResultDraftRecord {
Match3DResultDraftRecord {
profile_id: snapshot.profile_id,
game_name: snapshot.game_name,
theme_text: snapshot.theme_text,
summary_text: snapshot.summary_text,
tags: snapshot.tags,
cover_image_src: None,
reference_image_src,
clear_count: snapshot.clear_count,
difficulty: snapshot.difficulty,
total_item_count: snapshot.clear_count.saturating_mul(3),
publish_ready: false,
blockers: Vec::new(),
}
}
fn map_match3d_agent_message_snapshot(
snapshot: Match3DAgentMessageJsonRecord,
) -> Match3DAgentMessageRecord {
Match3DAgentMessageRecord {
message_id: snapshot.message_id,
role: snapshot.role,
kind: normalize_match3d_message_kind(&snapshot.kind).to_string(),
text: snapshot.text,
created_at: format_timestamp_micros(snapshot.created_at_micros),
}
}
fn map_match3d_work_snapshot(snapshot: Match3DWorkJsonRecord) -> Match3DWorkProfileRecord {
let config = map_match3d_creator_config(snapshot.config);
Match3DWorkProfileRecord {
work_id: snapshot.profile_id.clone(),
profile_id: snapshot.profile_id,
owner_user_id: snapshot.owner_user_id,
source_session_id: empty_string_to_none(snapshot.source_session_id),
author_display_name: snapshot.author_display_name,
game_name: snapshot.game_name,
theme_text: snapshot.theme_text,
summary: snapshot.summary_text,
tags: snapshot.tags,
cover_image_src: empty_string_to_none(snapshot.cover_image_src),
cover_asset_id: empty_string_to_none(snapshot.cover_asset_id),
reference_image_src: config.reference_image_src,
clear_count: snapshot.clear_count,
difficulty: snapshot.difficulty,
publication_status: normalize_match3d_publication_status(&snapshot.publication_status)
.to_string(),
play_count: snapshot.play_count,
updated_at: format_timestamp_micros(snapshot.updated_at_micros),
published_at: snapshot.published_at_micros.map(format_timestamp_micros),
publish_ready: snapshot.publish_ready,
}
}
fn map_match3d_run_json(run_json: String) -> Result<Match3DRunRecord, SpacetimeClientError> {
let run = serde_json::from_str::<Match3DRunJsonRecord>(&run_json).map_err(|error| {
SpacetimeClientError::Runtime(format!("match3d run_json 非法: {error}"))
})?;
Ok(map_match3d_run_snapshot(run))
}
fn map_match3d_run_snapshot(snapshot: Match3DRunJsonRecord) -> Match3DRunRecord {
let tray_slots = snapshot
.tray_slots
.into_iter()
.map(map_match3d_tray_slot_snapshot)
.collect::<Vec<_>>();
let items = snapshot
.items
.into_iter()
.map(|item| {
let tray_slot_index = tray_slots
.iter()
.find(|slot| {
slot.item_instance_id.as_deref() == Some(item.item_instance_id.as_str())
})
.map(|slot| slot.slot_index);
map_match3d_item_snapshot(item, tray_slot_index)
})
.collect();
Match3DRunRecord {
run_id: snapshot.run_id,
profile_id: snapshot.profile_id,
owner_user_id: String::new(),
status: snapshot.status,
snapshot_version: u64::from(snapshot.snapshot_version),
started_at_ms: i64_to_u64_ms(snapshot.started_at_ms),
duration_limit_ms: i64_to_u64_ms(snapshot.duration_limit_ms),
server_now_ms: Some(i64_to_u64_ms(snapshot.server_now_ms)),
remaining_ms: i64_to_u64_ms(snapshot.remaining_ms),
clear_count: snapshot.clear_count,
total_item_count: snapshot.total_item_count,
cleared_item_count: snapshot.cleared_item_count,
items,
tray_slots,
failure_reason: snapshot.failure_reason,
last_confirmed_action_id: None,
}
}
fn map_match3d_item_snapshot(
snapshot: Match3DItemJsonRecord,
tray_slot_index: Option<u32>,
) -> Match3DItemSnapshotRecord {
Match3DItemSnapshotRecord {
item_instance_id: snapshot.item_instance_id,
item_type_id: snapshot.item_type_id,
visual_key: snapshot.visual_key,
x: snapshot.x,
y: snapshot.y,
radius: snapshot.radius,
layer: snapshot.layer,
state: snapshot.state,
clickable: snapshot.clickable,
tray_slot_index,
}
}
fn map_match3d_tray_slot_snapshot(snapshot: Match3DTraySlotJsonRecord) -> Match3DTraySlotRecord {
Match3DTraySlotRecord {
slot_index: snapshot.slot_index,
item_instance_id: snapshot.item_instance_id,
item_type_id: snapshot.item_type_id,
visual_key: snapshot.visual_key,
}
}
fn build_match3d_anchor_pack(config: &Match3DCreatorConfigRecord) -> Match3DAnchorPackRecord {
let clear_count = config.clear_count.to_string();
let difficulty = config.difficulty.to_string();
Match3DAnchorPackRecord {
theme: build_match3d_anchor_item("theme", "题材主题", config.theme_text.as_str()),
clear_count: build_match3d_anchor_item("clearCount", "需要消除次数", clear_count.as_str()),
difficulty: build_match3d_anchor_item("difficulty", "难度", difficulty.as_str()),
}
}
fn build_match3d_anchor_item(key: &str, label: &str, value: &str) -> Match3DAnchorItemRecord {
Match3DAnchorItemRecord {
key: key.to_string(),
label: label.to_string(),
value: value.to_string(),
status: if value.trim().is_empty() {
"missing"
} else {
"confirmed"
}
.to_string(),
}
}
fn normalize_match3d_stage(value: &str) -> &str {
match value {
"Collecting" | "collecting" | "collecting_config" => "collecting_config",
"ReadyToCompile" | "ready_to_compile" => "ready_to_compile",
"DraftCompiled" | "draft_compiled" | "draft_ready" => "draft_ready",
"Published" | "published" => "published",
_ => value,
}
}
fn normalize_match3d_publication_status(value: &str) -> &str {
match value {
"Draft" | "draft" => "draft",
"Published" | "published" => "published",
_ => value,
}
}
fn normalize_match3d_message_kind(value: &str) -> &str {
match value {
"text" => "chat",
_ => value,
}
}
fn empty_string_to_none(value: String) -> Option<String> {
let trimmed = value.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
fn i64_to_u64_ms(value: i64) -> u64 {
value.max(0) as u64
}
pub(crate) fn map_puzzle_suggested_action(
snapshot: DomainPuzzleAgentSuggestedAction,
) -> PuzzleAgentSuggestedActionRecord {
@@ -2493,9 +2894,9 @@ fn map_puzzle_recommended_next_work(
pub(crate) fn map_puzzle_runtime_level_snapshot(
snapshot: DomainPuzzleRuntimeLevelSnapshot,
) -> PuzzleRuntimeLevelRecord {
// 中文注释:历史 run_json 可能缺 started_at_ms领域 serde 会回填为 0API 层继续补成 1避免前端计时器拿到无效开局时间。
let started_at_ms = if snapshot.started_at_ms == 0 {
1
// 中文注释:旧 run_json 没有计时字段时只补一个可用开始时间,其余限时字段保持旧默认值。
current_unix_millis_for_legacy_puzzle_snapshot()
} else {
snapshot.started_at_ms
};
@@ -2530,6 +2931,13 @@ pub(crate) fn map_puzzle_runtime_level_snapshot(
}
}
fn current_unix_millis_for_legacy_puzzle_snapshot() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
.unwrap_or(1)
}
pub(crate) fn map_puzzle_leaderboard_entry(
snapshot: module_puzzle::PuzzleLeaderboardEntry,
) -> PuzzleLeaderboardEntryRecord {
@@ -4574,6 +4982,367 @@ pub struct BigFishWorkRemixRecordInput {
pub remixed_at_micros: i64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DAgentSessionCreateRecordInput {
pub session_id: String,
pub owner_user_id: String,
pub seed_text: String,
pub welcome_message_id: String,
pub welcome_message_text: String,
pub config_json: Option<String>,
pub created_at_micros: i64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DAgentMessageSubmitRecordInput {
pub session_id: String,
pub owner_user_id: String,
pub user_message_id: String,
pub user_message_text: String,
pub submitted_at_micros: i64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DAgentMessageFinalizeRecordInput {
pub session_id: String,
pub owner_user_id: String,
pub assistant_message_id: Option<String>,
pub assistant_reply_text: Option<String>,
pub config_json: Option<String>,
pub progress_percent: u32,
pub stage: String,
pub updated_at_micros: i64,
pub error_message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DCompileDraftRecordInput {
pub session_id: String,
pub owner_user_id: String,
pub profile_id: String,
pub author_display_name: String,
pub game_name: Option<String>,
pub summary_text: Option<String>,
pub tags_json: Option<String>,
pub cover_image_src: Option<String>,
pub cover_asset_id: Option<String>,
pub compiled_at_micros: i64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DWorkUpdateRecordInput {
pub profile_id: String,
pub owner_user_id: String,
pub game_name: String,
pub theme_text: String,
pub summary_text: String,
pub tags_json: String,
pub cover_image_src: String,
pub cover_asset_id: String,
pub clear_count: u32,
pub difficulty: u32,
pub updated_at_micros: i64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DRunStartRecordInput {
pub run_id: String,
pub owner_user_id: String,
pub profile_id: String,
pub started_at_ms: i64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DRunClickRecordInput {
pub run_id: String,
pub owner_user_id: String,
pub item_instance_id: String,
pub client_snapshot_version: u32,
pub client_event_id: String,
pub clicked_at_ms: i64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DRunStopRecordInput {
pub run_id: String,
pub owner_user_id: String,
pub stopped_at_ms: i64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DRunRestartRecordInput {
pub source_run_id: String,
pub next_run_id: String,
pub owner_user_id: String,
pub restarted_at_ms: i64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DRunTimeUpRecordInput {
pub run_id: String,
pub owner_user_id: String,
pub finished_at_ms: i64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DAnchorItemRecord {
pub key: String,
pub label: String,
pub value: String,
pub status: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DAnchorPackRecord {
pub theme: Match3DAnchorItemRecord,
pub clear_count: Match3DAnchorItemRecord,
pub difficulty: Match3DAnchorItemRecord,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DCreatorConfigRecord {
pub theme_text: String,
pub reference_image_src: Option<String>,
pub clear_count: u32,
pub difficulty: u32,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DResultDraftRecord {
pub profile_id: String,
pub game_name: String,
pub theme_text: String,
pub summary_text: String,
pub tags: Vec<String>,
pub cover_image_src: Option<String>,
pub reference_image_src: Option<String>,
pub clear_count: u32,
pub difficulty: u32,
pub total_item_count: u32,
pub publish_ready: bool,
pub blockers: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DAgentMessageRecord {
pub message_id: String,
pub role: String,
pub kind: String,
pub text: String,
pub created_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DAgentSessionRecord {
pub session_id: String,
pub current_turn: u32,
pub progress_percent: u32,
pub stage: String,
pub anchor_pack: Match3DAnchorPackRecord,
pub config: Option<Match3DCreatorConfigRecord>,
pub draft: Option<Match3DResultDraftRecord>,
pub messages: Vec<Match3DAgentMessageRecord>,
pub last_assistant_reply: Option<String>,
pub published_profile_id: Option<String>,
pub updated_at: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DWorkProfileRecord {
pub work_id: String,
pub profile_id: String,
pub owner_user_id: String,
pub source_session_id: Option<String>,
pub author_display_name: String,
pub game_name: String,
pub theme_text: String,
pub summary: String,
pub tags: Vec<String>,
pub cover_image_src: Option<String>,
pub cover_asset_id: Option<String>,
pub reference_image_src: Option<String>,
pub clear_count: u32,
pub difficulty: u32,
pub publication_status: String,
pub play_count: u32,
pub updated_at: String,
pub published_at: Option<String>,
pub publish_ready: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Match3DItemSnapshotRecord {
pub item_instance_id: String,
pub item_type_id: String,
pub visual_key: String,
pub x: f32,
pub y: f32,
pub radius: f32,
pub layer: u32,
pub state: String,
pub clickable: bool,
pub tray_slot_index: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match3DTraySlotRecord {
pub slot_index: u32,
pub item_instance_id: Option<String>,
pub item_type_id: Option<String>,
pub visual_key: Option<String>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Match3DRunRecord {
pub run_id: String,
pub profile_id: String,
pub owner_user_id: String,
pub status: String,
pub snapshot_version: u64,
pub started_at_ms: u64,
pub duration_limit_ms: u64,
pub server_now_ms: Option<u64>,
pub remaining_ms: u64,
pub clear_count: u32,
pub total_item_count: u32,
pub cleared_item_count: u32,
pub items: Vec<Match3DItemSnapshotRecord>,
pub tray_slots: Vec<Match3DTraySlotRecord>,
pub failure_reason: Option<String>,
pub last_confirmed_action_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Match3DClickConfirmationRecord {
pub status: String,
pub accepted: bool,
pub reject_reason: Option<String>,
pub accepted_item_instance_id: Option<String>,
pub entered_slot_index: Option<u32>,
pub cleared_item_instance_ids: Vec<String>,
pub failure_reason: Option<String>,
pub run: Match3DRunRecord,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct Match3DCreatorConfigJsonRecord {
theme_text: String,
reference_image_src: Option<String>,
clear_count: u32,
difficulty: u32,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct Match3DAgentMessageJsonRecord {
message_id: String,
#[allow(dead_code)]
session_id: String,
role: String,
kind: String,
text: String,
created_at_micros: i64,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct Match3DDraftJsonRecord {
profile_id: String,
game_name: String,
theme_text: String,
summary_text: String,
tags: Vec<String>,
clear_count: u32,
difficulty: u32,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct Match3DAgentSessionJsonRecord {
session_id: String,
#[allow(dead_code)]
owner_user_id: String,
#[allow(dead_code)]
seed_text: String,
current_turn: u32,
progress_percent: u32,
stage: String,
config: Match3DCreatorConfigJsonRecord,
draft: Option<Match3DDraftJsonRecord>,
messages: Vec<Match3DAgentMessageJsonRecord>,
last_assistant_reply: String,
published_profile_id: Option<String>,
#[allow(dead_code)]
created_at_micros: i64,
updated_at_micros: i64,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct Match3DWorkJsonRecord {
profile_id: String,
owner_user_id: String,
source_session_id: String,
author_display_name: String,
game_name: String,
theme_text: String,
summary_text: String,
tags: Vec<String>,
cover_image_src: String,
cover_asset_id: String,
clear_count: u32,
difficulty: u32,
config: Match3DCreatorConfigJsonRecord,
publication_status: String,
publish_ready: bool,
play_count: u32,
updated_at_micros: i64,
published_at_micros: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct Match3DItemJsonRecord {
item_instance_id: String,
item_type_id: String,
visual_key: String,
x: f32,
y: f32,
radius: f32,
layer: u32,
state: String,
clickable: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct Match3DTraySlotJsonRecord {
slot_index: u32,
item_instance_id: Option<String>,
item_type_id: Option<String>,
visual_key: Option<String>,
}
#[derive(Clone, Debug, PartialEq, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct Match3DRunJsonRecord {
run_id: String,
profile_id: String,
status: String,
snapshot_version: u32,
started_at_ms: i64,
duration_limit_ms: i64,
server_now_ms: i64,
remaining_ms: i64,
clear_count: u32,
total_item_count: u32,
cleared_item_count: u32,
tray_slots: Vec<Match3DTraySlotJsonRecord>,
items: Vec<Match3DItemJsonRecord>,
failure_reason: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PuzzleAnchorItemRecord {
pub key: String,

View File

@@ -0,0 +1,466 @@
use super::*;
use crate::mapper::*;
impl SpacetimeClient {
pub async fn create_match3d_agent_session(
&self,
input: Match3DAgentSessionCreateRecordInput,
) -> Result<Match3DAgentSessionRecord, SpacetimeClientError> {
let procedure_input = Match3DAgentSessionCreateInput {
session_id: input.session_id,
owner_user_id: input.owner_user_id,
seed_text: input.seed_text,
welcome_message_id: input.welcome_message_id,
welcome_message_text: input.welcome_message_text,
config_json: input.config_json,
created_at_micros: input.created_at_micros,
};
self.call_after_connect(move |connection, sender| {
connection.procedures().create_match_3_d_agent_session_then(
procedure_input,
move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_agent_session_procedure_result);
send_once(&sender, mapped);
},
);
})
.await
}
pub async fn get_match3d_agent_session(
&self,
session_id: String,
owner_user_id: String,
) -> Result<Match3DAgentSessionRecord, SpacetimeClientError> {
let procedure_input = Match3DAgentSessionGetInput {
session_id,
owner_user_id,
};
self.call_after_connect(move |connection, sender| {
connection.procedures().get_match_3_d_agent_session_then(
procedure_input,
move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_agent_session_procedure_result);
send_once(&sender, mapped);
},
);
})
.await
}
pub async fn submit_match3d_agent_message(
&self,
input: Match3DAgentMessageSubmitRecordInput,
) -> Result<Match3DAgentSessionRecord, SpacetimeClientError> {
let procedure_input = Match3DAgentMessageSubmitInput {
session_id: input.session_id,
owner_user_id: input.owner_user_id,
user_message_id: input.user_message_id,
user_message_text: input.user_message_text,
submitted_at_micros: input.submitted_at_micros,
};
self.call_after_connect(move |connection, sender| {
connection.procedures().submit_match_3_d_agent_message_then(
procedure_input,
move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_agent_session_procedure_result);
send_once(&sender, mapped);
},
);
})
.await
}
pub async fn finalize_match3d_agent_message(
&self,
input: Match3DAgentMessageFinalizeRecordInput,
) -> Result<Match3DAgentSessionRecord, SpacetimeClientError> {
let procedure_input = Match3DAgentMessageFinalizeInput {
session_id: input.session_id,
owner_user_id: input.owner_user_id,
assistant_message_id: input.assistant_message_id,
assistant_reply_text: input.assistant_reply_text,
config_json: input.config_json,
progress_percent: input.progress_percent,
stage: input.stage,
updated_at_micros: input.updated_at_micros,
error_message: input.error_message,
};
self.call_after_connect(move |connection, sender| {
connection
.procedures()
.finalize_match_3_d_agent_message_turn_then(procedure_input, move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_agent_session_procedure_result);
send_once(&sender, mapped);
});
})
.await
}
pub async fn compile_match3d_draft(
&self,
input: Match3DCompileDraftRecordInput,
) -> Result<Match3DAgentSessionRecord, SpacetimeClientError> {
let procedure_input = Match3DDraftCompileInput {
session_id: input.session_id,
owner_user_id: input.owner_user_id,
profile_id: input.profile_id,
author_display_name: input.author_display_name,
game_name: input.game_name,
summary_text: input.summary_text,
tags_json: input.tags_json,
cover_image_src: input.cover_image_src,
cover_asset_id: input.cover_asset_id,
compiled_at_micros: input.compiled_at_micros,
};
self.call_after_connect(move |connection, sender| {
connection.procedures().compile_match_3_d_draft_then(
procedure_input,
move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_agent_session_procedure_result);
send_once(&sender, mapped);
},
);
})
.await
}
pub async fn update_match3d_work(
&self,
input: Match3DWorkUpdateRecordInput,
) -> Result<Match3DWorkProfileRecord, SpacetimeClientError> {
let procedure_input = Match3DWorkUpdateInput {
profile_id: input.profile_id,
owner_user_id: input.owner_user_id,
game_name: input.game_name,
theme_text: input.theme_text,
summary_text: input.summary_text,
tags_json: input.tags_json,
cover_image_src: input.cover_image_src,
cover_asset_id: input.cover_asset_id,
clear_count: input.clear_count,
difficulty: input.difficulty,
updated_at_micros: input.updated_at_micros,
};
self.call_after_connect(move |connection, sender| {
connection.procedures().update_match_3_d_work_then(
procedure_input,
move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_work_procedure_result);
send_once(&sender, mapped);
},
);
})
.await
}
pub async fn publish_match3d_work(
&self,
profile_id: String,
owner_user_id: String,
published_at_micros: i64,
) -> Result<Match3DWorkProfileRecord, SpacetimeClientError> {
let procedure_input = Match3DWorkPublishInput {
profile_id,
owner_user_id,
published_at_micros,
};
self.call_after_connect(move |connection, sender| {
connection.procedures().publish_match_3_d_work_then(
procedure_input,
move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_work_procedure_result);
send_once(&sender, mapped);
},
);
})
.await
}
pub async fn list_match3d_works(
&self,
owner_user_id: String,
) -> Result<Vec<Match3DWorkProfileRecord>, SpacetimeClientError> {
self.list_match3d_works_with_input(Match3DWorksListInput {
owner_user_id,
published_only: false,
})
.await
}
pub async fn list_match3d_gallery(
&self,
) -> Result<Vec<Match3DWorkProfileRecord>, SpacetimeClientError> {
self.list_match3d_works_with_input(Match3DWorksListInput {
// 中文注释:公开广场读取只依赖 published_onlyowner_user_id 保持非空便于兼容校验。
owner_user_id: "match3d-public-gallery".to_string(),
published_only: true,
})
.await
}
async fn list_match3d_works_with_input(
&self,
procedure_input: Match3DWorksListInput,
) -> Result<Vec<Match3DWorkProfileRecord>, SpacetimeClientError> {
self.call_after_connect(move |connection, sender| {
connection
.procedures()
.list_match_3_d_works_then(procedure_input, move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_works_procedure_result);
send_once(&sender, mapped);
});
})
.await
}
pub async fn get_match3d_work_detail(
&self,
profile_id: String,
owner_user_id: String,
) -> Result<Match3DWorkProfileRecord, SpacetimeClientError> {
let procedure_input = Match3DWorkGetInput {
profile_id,
owner_user_id,
};
self.call_after_connect(move |connection, sender| {
connection.procedures().get_match_3_d_work_detail_then(
procedure_input,
move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_work_procedure_result);
send_once(&sender, mapped);
},
);
})
.await
}
pub async fn delete_match3d_work(
&self,
profile_id: String,
owner_user_id: String,
) -> Result<Vec<Match3DWorkProfileRecord>, SpacetimeClientError> {
let procedure_input = Match3DWorkDeleteInput {
profile_id,
owner_user_id,
};
self.call_after_connect(move |connection, sender| {
connection.procedures().delete_match_3_d_work_then(
procedure_input,
move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_works_procedure_result);
send_once(&sender, mapped);
},
);
})
.await
}
pub async fn start_match3d_run(
&self,
input: Match3DRunStartRecordInput,
) -> Result<Match3DRunRecord, SpacetimeClientError> {
let owner_user_id = input.owner_user_id.clone();
let procedure_input = Match3DRunStartInput {
run_id: input.run_id,
owner_user_id: input.owner_user_id,
profile_id: input.profile_id,
started_at_ms: input.started_at_ms,
};
self.call_after_connect(move |connection, sender| {
connection
.procedures()
.start_match_3_d_run_then(procedure_input, move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_run_procedure_result)
.map(|mut run| {
run.owner_user_id = owner_user_id;
run
});
send_once(&sender, mapped);
});
})
.await
}
pub async fn get_match3d_run(
&self,
run_id: String,
owner_user_id: String,
) -> Result<Match3DRunRecord, SpacetimeClientError> {
let procedure_owner_user_id = owner_user_id.clone();
let procedure_input = Match3DRunGetInput {
run_id,
owner_user_id,
};
self.call_after_connect(move |connection, sender| {
connection
.procedures()
.get_match_3_d_run_then(procedure_input, move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_run_procedure_result)
.map(|mut run| {
run.owner_user_id = procedure_owner_user_id;
run
});
send_once(&sender, mapped);
});
})
.await
}
pub async fn click_match3d_item(
&self,
input: Match3DRunClickRecordInput,
) -> Result<Match3DClickConfirmationRecord, SpacetimeClientError> {
let owner_user_id = input.owner_user_id.clone();
let client_event_id = input.client_event_id.clone();
let procedure_input = Match3DRunClickInput {
run_id: input.run_id,
owner_user_id: input.owner_user_id,
item_instance_id: input.item_instance_id,
client_snapshot_version: input.client_snapshot_version,
client_event_id: input.client_event_id,
clicked_at_ms: input.clicked_at_ms,
};
self.call_after_connect(move |connection, sender| {
connection
.procedures()
.click_match_3_d_item_then(procedure_input, move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_click_item_procedure_result)
.map(|mut confirmation| {
confirmation.run.owner_user_id = owner_user_id;
if confirmation.accepted {
confirmation.run.last_confirmed_action_id = Some(client_event_id);
}
confirmation
});
send_once(&sender, mapped);
});
})
.await
}
pub async fn stop_match3d_run(
&self,
input: Match3DRunStopRecordInput,
) -> Result<Match3DRunRecord, SpacetimeClientError> {
let owner_user_id = input.owner_user_id.clone();
let procedure_input = Match3DRunStopInput {
run_id: input.run_id,
owner_user_id: input.owner_user_id,
stopped_at_ms: input.stopped_at_ms,
};
self.call_after_connect(move |connection, sender| {
connection
.procedures()
.stop_match_3_d_run_then(procedure_input, move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_run_procedure_result)
.map(|mut run| {
run.owner_user_id = owner_user_id;
run
});
send_once(&sender, mapped);
});
})
.await
}
pub async fn restart_match3d_run(
&self,
input: Match3DRunRestartRecordInput,
) -> Result<Match3DRunRecord, SpacetimeClientError> {
let owner_user_id = input.owner_user_id.clone();
let procedure_input = Match3DRunRestartInput {
source_run_id: input.source_run_id,
next_run_id: input.next_run_id,
owner_user_id: input.owner_user_id,
restarted_at_ms: input.restarted_at_ms,
};
self.call_after_connect(move |connection, sender| {
connection.procedures().restart_match_3_d_run_then(
procedure_input,
move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_run_procedure_result)
.map(|mut run| {
run.owner_user_id = owner_user_id;
run
});
send_once(&sender, mapped);
},
);
})
.await
}
pub async fn finish_match3d_time_up(
&self,
input: Match3DRunTimeUpRecordInput,
) -> Result<Match3DRunRecord, SpacetimeClientError> {
let owner_user_id = input.owner_user_id.clone();
let procedure_input = Match3DRunTimeUpInput {
run_id: input.run_id,
owner_user_id: input.owner_user_id,
finished_at_ms: input.finished_at_ms,
};
self.call_after_connect(move |connection, sender| {
connection.procedures().finish_match_3_d_time_up_then(
procedure_input,
move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_match3d_run_procedure_result)
.map(|mut run| {
run.owner_user_id = owner_user_id;
run
});
send_once(&sender, mapped);
},
);
})
.await
}
}

View File

@@ -0,0 +1,59 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
use super::runtime_profile_invite_code_admin_procedure_result_type::RuntimeProfileInviteCodeAdminProcedureResult;
use super::runtime_profile_invite_code_admin_upsert_input_type::RuntimeProfileInviteCodeAdminUpsertInput;
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
struct AdminUpsertProfileInviteCodeArgs {
pub input: RuntimeProfileInviteCodeAdminUpsertInput,
}
impl __sdk::InModule for AdminUpsertProfileInviteCodeArgs {
type Module = super::RemoteModule;
}
#[allow(non_camel_case_types)]
/// Extension trait for access to the procedure `admin_upsert_profile_invite_code`.
///
/// Implemented for [`super::RemoteProcedures`].
pub trait admin_upsert_profile_invite_code {
fn admin_upsert_profile_invite_code(&self, input: RuntimeProfileInviteCodeAdminUpsertInput) {
self.admin_upsert_profile_invite_code_then(input, |_, _| {});
}
fn admin_upsert_profile_invite_code_then(
&self,
input: RuntimeProfileInviteCodeAdminUpsertInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<RuntimeProfileInviteCodeAdminProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
);
}
impl admin_upsert_profile_invite_code for super::RemoteProcedures {
fn admin_upsert_profile_invite_code_then(
&self,
input: RuntimeProfileInviteCodeAdminUpsertInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<RuntimeProfileInviteCodeAdminProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
) {
self.imp
.invoke_procedure_with_callback::<_, RuntimeProfileInviteCodeAdminProcedureResult>(
"admin_upsert_profile_invite_code",
AdminUpsertProfileInviteCodeArgs { input },
__callback,
);
}
}

View File

@@ -335,6 +335,9 @@ pub mod runtime_platform_theme_type;
pub mod runtime_profile_dashboard_get_input_type;
pub mod runtime_profile_dashboard_procedure_result_type;
pub mod runtime_profile_dashboard_snapshot_type;
pub mod runtime_profile_invite_code_admin_procedure_result_type;
pub mod runtime_profile_invite_code_admin_upsert_input_type;
pub mod runtime_profile_invite_code_snapshot_type;
pub mod runtime_profile_membership_benefit_snapshot_type;
pub mod runtime_profile_membership_snapshot_type;
pub mod runtime_profile_membership_status_type;
@@ -431,6 +434,7 @@ pub mod upsert_custom_world_profile_reducer;
pub mod upsert_npc_state_reducer;
pub mod custom_world_gallery_entry_table;
pub mod admin_disable_profile_redeem_code_procedure;
pub mod admin_upsert_profile_invite_code_procedure;
pub mod admin_upsert_profile_redeem_code_procedure;
pub mod advance_puzzle_next_level_procedure;
pub mod append_ai_text_chunk_and_return_procedure;
@@ -895,6 +899,9 @@ pub use runtime_platform_theme_type::RuntimePlatformTheme;
pub use runtime_profile_dashboard_get_input_type::RuntimeProfileDashboardGetInput;
pub use runtime_profile_dashboard_procedure_result_type::RuntimeProfileDashboardProcedureResult;
pub use runtime_profile_dashboard_snapshot_type::RuntimeProfileDashboardSnapshot;
pub use runtime_profile_invite_code_admin_procedure_result_type::RuntimeProfileInviteCodeAdminProcedureResult;
pub use runtime_profile_invite_code_admin_upsert_input_type::RuntimeProfileInviteCodeAdminUpsertInput;
pub use runtime_profile_invite_code_snapshot_type::RuntimeProfileInviteCodeSnapshot;
pub use runtime_profile_membership_benefit_snapshot_type::RuntimeProfileMembershipBenefitSnapshot;
pub use runtime_profile_membership_snapshot_type::RuntimeProfileMembershipSnapshot;
pub use runtime_profile_membership_status_type::RuntimeProfileMembershipStatus;
@@ -991,6 +998,7 @@ pub use upsert_chapter_progression_reducer::upsert_chapter_progression;
pub use upsert_custom_world_profile_reducer::upsert_custom_world_profile;
pub use upsert_npc_state_reducer::upsert_npc_state;
pub use admin_disable_profile_redeem_code_procedure::admin_disable_profile_redeem_code;
pub use admin_upsert_profile_invite_code_procedure::admin_upsert_profile_invite_code;
pub use admin_upsert_profile_redeem_code_procedure::admin_upsert_profile_redeem_code;
pub use advance_puzzle_next_level_procedure::advance_puzzle_next_level;
pub use append_ai_text_chunk_and_return_procedure::append_ai_text_chunk_and_return;

View File

@@ -15,6 +15,7 @@ use spacetimedb_sdk::__codegen::{
pub struct ProfileInviteCode {
pub user_id: String,
pub invite_code: String,
pub metadata_json: String,
pub created_at: __sdk::Timestamp,
pub updated_at: __sdk::Timestamp,
}
@@ -31,6 +32,7 @@ impl __sdk::InModule for ProfileInviteCode {
pub struct ProfileInviteCodeCols {
pub user_id: __sdk::__query_builder::Col<ProfileInviteCode, String>,
pub invite_code: __sdk::__query_builder::Col<ProfileInviteCode, String>,
pub metadata_json: __sdk::__query_builder::Col<ProfileInviteCode, String>,
pub created_at: __sdk::__query_builder::Col<ProfileInviteCode, __sdk::Timestamp>,
pub updated_at: __sdk::__query_builder::Col<ProfileInviteCode, __sdk::Timestamp>,
}
@@ -41,6 +43,7 @@ impl __sdk::__query_builder::HasCols for ProfileInviteCode {
ProfileInviteCodeCols {
user_id: __sdk::__query_builder::Col::new(table_name, "user_id"),
invite_code: __sdk::__query_builder::Col::new(table_name, "invite_code"),
metadata_json: __sdk::__query_builder::Col::new(table_name, "metadata_json"),
created_at: __sdk::__query_builder::Col::new(table_name, "created_at"),
updated_at: __sdk::__query_builder::Col::new(table_name, "updated_at"),

View File

@@ -0,0 +1,19 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
use super::runtime_profile_invite_code_snapshot_type::RuntimeProfileInviteCodeSnapshot;
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub struct RuntimeProfileInviteCodeAdminProcedureResult {
pub ok: bool,
pub record: Option<RuntimeProfileInviteCodeSnapshot>,
pub error_message: Option<String>,
}
impl __sdk::InModule for RuntimeProfileInviteCodeAdminProcedureResult {
type Module = super::RemoteModule;
}

View File

@@ -0,0 +1,18 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub struct RuntimeProfileInviteCodeAdminUpsertInput {
pub admin_user_id: String,
pub invite_code: String,
pub metadata_json: String,
pub updated_at_micros: i64,
}
impl __sdk::InModule for RuntimeProfileInviteCodeAdminUpsertInput {
type Module = super::RemoteModule;
}

View File

@@ -0,0 +1,19 @@
// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
#![allow(unused, clippy::all)]
use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws};
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub struct RuntimeProfileInviteCodeSnapshot {
pub user_id: String,
pub invite_code: String,
pub metadata_json: String,
pub created_at_micros: i64,
pub updated_at_micros: i64,
}
impl __sdk::InModule for RuntimeProfileInviteCodeSnapshot {
type Module = super::RemoteModule;
}

View File

@@ -346,6 +346,35 @@ impl SpacetimeClient {
.await
}
pub async fn admin_upsert_profile_invite_code(
&self,
admin_user_id: String,
invite_code: String,
metadata_json: String,
updated_at_micros: i64,
) -> Result<RuntimeProfileInviteCodeRecord, SpacetimeClientError> {
let procedure_input = build_runtime_profile_invite_code_admin_upsert_input(
admin_user_id,
invite_code,
metadata_json,
updated_at_micros,
)
.map_err(|error| SpacetimeClientError::Runtime(error.to_string()))?
.into();
self.call_after_connect(move |connection, sender| {
connection
.procedures()
.admin_upsert_profile_invite_code_then(procedure_input, move |_, result| {
let mapped = result
.map_err(|error| SpacetimeClientError::Procedure(error.to_string()))
.and_then(map_runtime_profile_invite_code_admin_procedure_result);
send_once(&sender, mapped);
});
})
.await
}
pub async fn get_profile_play_stats(
&self,
user_id: String,

View File

@@ -1102,6 +1102,14 @@ fn normalize_migration_row(table_name: &str, value: &serde_json::Value) -> serde
.or_insert(serde_json::Value::Null);
}
}
if table_name == "profile_invite_code" {
if let Some(object) = next_value.as_object_mut() {
// 中文注释:邀请码 metadata 晚于邀请表加入,旧迁移包按空对象兼容。
object
.entry("metadata_json".to_string())
.or_insert_with(|| serde_json::Value::String("{}".to_string()));
}
}
if table_name == "big_fish_creation_session" {
if let Some(object) = next_value.as_object_mut() {
// 中文注释:旧迁移包没有公开游玩次数字段,导入时按新建作品默认 0 兼容。

View File

@@ -70,6 +70,7 @@ pub struct ProfileInviteCode {
pub(crate) user_id: String,
#[unique]
pub(crate) invite_code: String,
pub(crate) metadata_json: String,
pub(crate) created_at: Timestamp,
pub(crate) updated_at: Timestamp,
}
@@ -568,6 +569,25 @@ pub fn admin_disable_profile_redeem_code(
}
}
#[spacetimedb::procedure]
pub fn admin_upsert_profile_invite_code(
ctx: &mut ProcedureContext,
input: RuntimeProfileInviteCodeAdminUpsertInput,
) -> RuntimeProfileInviteCodeAdminProcedureResult {
match ctx.try_with_tx(|tx| admin_upsert_profile_invite_code_record(tx, input.clone())) {
Ok(record) => RuntimeProfileInviteCodeAdminProcedureResult {
ok: true,
record: Some(record),
error_message: None,
},
Err(message) => RuntimeProfileInviteCodeAdminProcedureResult {
ok: false,
record: None,
error_message: Some(message),
},
}
}
pub(crate) fn list_profile_save_archive_rows(
ctx: &ReducerContext,
input: RuntimeProfileSaveArchiveListInput,
@@ -1658,10 +1678,14 @@ fn redeem_profile_referral_invite_code_record(
),
bound_at,
)?;
let today_inviter_reward_count =
count_today_profile_referral_inviter_rewards(ctx, &inviter_code.user_id, bound_at);
let inviter_reward_granted =
today_inviter_reward_count < PROFILE_REFERRAL_DAILY_INVITER_REWARD_LIMIT;
let is_admin_invite_code = is_admin_profile_invite_code_user_id(&inviter_code.user_id);
let today_inviter_reward_count = if is_admin_invite_code {
0
} else {
count_today_profile_referral_inviter_rewards(ctx, &inviter_code.user_id, bound_at)
};
let inviter_reward_granted = !is_admin_invite_code
&& today_inviter_reward_count < PROFILE_REFERRAL_DAILY_INVITER_REWARD_LIMIT;
let inviter_balance_after = if inviter_reward_granted {
apply_profile_wallet_delta(
ctx,
@@ -1877,6 +1901,56 @@ fn admin_disable_profile_redeem_code_record(
Ok(build_profile_redeem_code_snapshot_from_row(&inserted))
}
fn admin_upsert_profile_invite_code_record(
ctx: &ReducerContext,
input: RuntimeProfileInviteCodeAdminUpsertInput,
) -> Result<RuntimeProfileInviteCodeSnapshot, String> {
let validated_input = build_runtime_profile_invite_code_admin_upsert_input(
input.admin_user_id,
input.invite_code,
input.metadata_json,
input.updated_at_micros,
)
.map_err(|error| error.to_string())?;
let updated_at = Timestamp::from_micros_since_unix_epoch(validated_input.updated_at_micros);
let user_id = build_admin_profile_invite_code_user_id(
&validated_input.admin_user_id,
&validated_input.invite_code,
);
if let Some(existing) = ctx
.db
.profile_invite_code()
.invite_code()
.find(&validated_input.invite_code)
{
if existing.user_id != user_id {
return Err("邀请码已被其他用户占用".to_string());
}
ctx.db
.profile_invite_code()
.user_id()
.delete(&existing.user_id);
let inserted = ctx.db.profile_invite_code().insert(ProfileInviteCode {
user_id,
invite_code: validated_input.invite_code,
metadata_json: validated_input.metadata_json,
created_at: existing.created_at,
updated_at,
});
return Ok(build_profile_invite_code_snapshot_from_row(&inserted));
}
let inserted = ctx.db.profile_invite_code().insert(ProfileInviteCode {
user_id,
invite_code: validated_input.invite_code,
metadata_json: validated_input.metadata_json,
created_at: updated_at,
updated_at,
});
Ok(build_profile_invite_code_snapshot_from_row(&inserted))
}
fn build_profile_referral_invite_center_snapshot(
ctx: &ReducerContext,
user_id: &str,
@@ -1949,6 +2023,7 @@ fn ensure_profile_invite_code(ctx: &ReducerContext, user_id: &str) -> ProfileInv
ctx.db.profile_invite_code().insert(ProfileInviteCode {
user_id: user_id.to_string(),
invite_code,
metadata_json: PROFILE_INVITE_CODE_METADATA_DEFAULT_JSON.to_string(),
created_at: ctx.timestamp,
updated_at: ctx.timestamp,
})
@@ -1980,6 +2055,14 @@ fn count_today_profile_referral_inviter_rewards(
.count() as u32
}
fn is_admin_profile_invite_code_user_id(user_id: &str) -> bool {
user_id.starts_with("admin:")
}
fn build_admin_profile_invite_code_user_id(admin_user_id: &str, invite_code: &str) -> String {
format!("admin:{}:{}", admin_user_id, invite_code)
}
fn profile_wallet_balance(ctx: &ReducerContext, user_id: &str) -> u64 {
ctx.db
.profile_dashboard_state()
@@ -2348,6 +2431,18 @@ fn build_profile_redeem_code_snapshot_from_row(
}
}
fn build_profile_invite_code_snapshot_from_row(
row: &ProfileInviteCode,
) -> RuntimeProfileInviteCodeSnapshot {
RuntimeProfileInviteCodeSnapshot {
user_id: row.user_id.clone(),
invite_code: row.invite_code.clone(),
metadata_json: row.metadata_json.clone(),
created_at_micros: row.created_at.to_micros_since_unix_epoch(),
updated_at_micros: row.updated_at.to_micros_since_unix_epoch(),
}
}
fn build_profile_wallet_ledger_snapshot_from_row(
row: &ProfileWalletLedger,
) -> RuntimeProfileWalletLedgerEntrySnapshot {