MySQL options of the owner kept across starts (#103)

Settings, Service edits Settings/mysql-custom.ini. Every start adds its name = value lines
(outside a section or in [mysqld]) to the rendered my.ini, after the defaults so they
win; the port, addresses, data and log paths, sockets and !include stay managed. Nothing
changes for a server without the file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ДмитрийandClaude Opus 5.5 committed 2026-11-15 20:21:24 +05:00
1 parent f08ae1c76b
commit 20657df203
13 files changed
+211 -2

No files matched your search

@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Your own MySQL settings survive restarts and updates
---
Settings, Service has a MySQL settings box. Its options are added to my.ini at every start of the database; before, my.ini was rewritten and hand edits were lost. Port, addresses and data paths stay managed.
+97 -1
View File
@@ -140,6 +140,7 @@ pub fn prepare(root: &Path, config: &Settings) -> Result<Vec<PathBuf>> {
std::fs::write(root.join(target), text.as_bytes())?;
written.push(root.join(target));
}
let custom = custom_mysql_options(root);
let files: [(&str, String); 3] = [
(
"Core/configs/modules/coa_bugreport.conf",
@@ -150,7 +151,7 @@ pub fn prepare(root: &Path, config: &Settings) -> Result<Vec<PathBuf>> {
(
"mysql/my.ini",
format!(
"[mysqld]\nbasedir=\"{base}/mysql\"\ndatadir=\"{base}/mysql/data\"\nport={mysql_port}\nbind-address=127.0.0.1\nmysqlx=0\ncharacter-set-server=utf8mb4\ncollation-server=utf8mb4_unicode_ci\nmax_allowed_packet=128M\ninnodb_buffer_pool_size=256M\nskip-log-bin\nlog-error=\"{base}/mysql/logs/mysql-error.log\"\npid-file=\"{base}/mysql/mysql.pid\"\n"
"[mysqld]\nbasedir=\"{base}/mysql\"\ndatadir=\"{base}/mysql/data\"\nport={mysql_port}\nbind-address=127.0.0.1\nmysqlx=0\ncharacter-set-server=utf8mb4\ncollation-server=utf8mb4_unicode_ci\nmax_allowed_packet=128M\ninnodb_buffer_pool_size=256M\nskip-log-bin\nlog-error=\"{base}/mysql/logs/mysql-error.log\"\npid-file=\"{base}/mysql/mysql.pid\"\n{custom}"
),
),
(
@@ -168,6 +169,85 @@ pub fn prepare(root: &Path, config: &Settings) -> Result<Vec<PathBuf>> {
Ok(written)
}
/// The owner's file of extra MySQL options; the launcher rewrites `mysql/my.ini` at every start.
pub const CUSTOM_MYSQL: &str = "Settings/mysql-custom.ini";
/// The owner's MySQL options as written, and the lines a start will add to `[mysqld]`.
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomMysql {
pub text: String,
pub applied: String,
}
pub fn read_custom_mysql(root: &Path) -> CustomMysql {
let text = std::fs::read(root.join(CUSTOM_MYSQL))
.map(|b| String::from_utf8_lossy(&b).into_owned())
.unwrap_or_default();
CustomMysql { text, applied: custom_mysql_options(root) }
}
/// Save the owner's MySQL options; they apply at the next start of the database.
pub fn write_custom_mysql(root: &Path, text: &str) -> Result<CustomMysql> {
if text.len() > 16 * 1024 || text.contains(char::from(0)) {
return Err(Error::Invalid("The MySQL options must be plain text of at most 16 KB.".into()));
}
crate::fsx::atomic_write(&root.join(CUSTOM_MYSQL), text.replace("\r\n", "\n").as_bytes())?;
Ok(read_custom_mysql(root))
}
/// Options the server cannot run without, which only the launcher sets.
const MANAGED_MYSQL_OPTIONS: [&str; 10] = [
"basedir",
"datadir",
"port",
"bind-address",
"mysqlx",
"log-error",
"pid-file",
"socket",
"skip-networking",
"defaults-file",
];
/// `name = value` lines of the owner's file (outside any section or in `[mysqld]`), as lines for `[mysqld]`.
/// Comments, other sections, `!include` and the options the launcher manages are left out.
pub fn custom_mysql_options(root: &Path) -> String {
let Ok(bytes) = std::fs::read(root.join(CUSTOM_MYSQL)) else {
return String::new();
};
let text = String::from_utf8_lossy(&bytes);
let mut in_mysqld = true;
let mut out = String::new();
for line in text.trim_start_matches('\u{feff}').lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
continue;
}
if line.starts_with('[') {
in_mysqld = line.eq_ignore_ascii_case("[mysqld]");
continue;
}
if !in_mysqld || line.starts_with('!') {
continue;
}
let name = line
.split('=')
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase()
.replace('_', "-");
let name = name.strip_prefix("loose-").unwrap_or(&name);
if name.is_empty() || MANAGED_MYSQL_OPTIONS.contains(&name) {
continue;
}
out.push_str(line);
out.push('\n');
}
out
}
#[cfg(windows)]
mod sys {
use std::os::windows::ffi::OsStrExt;
@@ -206,6 +286,22 @@ mod tests {
w("Settings/mod_ascension_compat.conf.template", b"Ascension.DbcDir = \"@ASCENSION_DBC@\"\rOld.Mac = 1\r");
}
#[test]
fn the_owners_mysql_options_are_kept_except_the_managed_ones() {
let d = tempfile::tempdir().unwrap();
std::fs::create_dir_all(d.path().join("Settings")).unwrap();
std::fs::write(
d.path().join(CUSTOM_MYSQL),
"\u{feff}# tuning\ninnodb_buffer_pool_size = 2G\nport=3999\nloose_bind_address=0.0.0.0\n!include C:/x.ini\n[client]\nuser=evil\n[mysqld]\nmax_connections=500\nDATADIR=D:/elsewhere\n",
)
.unwrap();
assert_eq!(
custom_mysql_options(d.path()),
"innodb_buffer_pool_size = 2G\nmax_connections=500\n"
);
assert_eq!(custom_mysql_options(&d.path().join("missing")), "");
}
#[test]
fn placeholders_left_outside_comments_are_refused() {
let d = tempfile::tempdir().unwrap();
+23
View File
@@ -1238,6 +1238,27 @@ async fn realm_select(
result
}
#[tauri::command]
async fn mysql_custom(
state: State<'_, AppState>,
id: String,
) -> std::result::Result<coa_core::launcher::render::CustomMysql, UiError> {
let root = path_of(&state, &id)?;
blocking(move || Ok(coa_core::launcher::render::read_custom_mysql(&root))).await
}
/// The owner's own MySQL options (Settings/mysql-custom.ini); they apply at the next start of the database.
#[tauri::command]
async fn mysql_custom_save(
state: State<'_, AppState>,
id: String,
text: String,
) -> std::result::Result<coa_core::launcher::render::CustomMysql, UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || coa_core::launcher::render::write_custom_mysql(&root, &text)).await
}
#[tauri::command]
async fn realm_names(
state: State<'_, AppState>,
@@ -3011,6 +3032,8 @@ pub fn run() {
realm_with_reborn,
realm_names,
realm_rename,
mysql_custom,
mysql_custom_save,
check_database,
repair_server,
module_set_enabled,
+1
View File
@@ -39,6 +39,7 @@ export {};
if(cmd==="pending_update") return null;
if(cmd==="plugin:app|version") return "0.8.2";
if(cmd==="release_history") throw new Error("Offline demo: using bundled notes");
if(cmd==="mysql_custom"||cmd==="mysql_custom_save"){const w=window as any;if(cmd==="mysql_custom_save")w.__my=args.text;const text:string=w.__my??"";const applied=text.split("\n").map((l:string)=>l.trim()).filter((l:string)=>l&&!l.startsWith("#")&&!/^(port|datadir|basedir|bind[-_]address)\b/i.test(l)).map((l:string)=>l+"\n").join("");return {text,applied};}
if(cmd==="realm_names"||cmd==="realm_rename"){const w=window as any;w.__rn=w.__rn??{};const defs:[number,string][]=[[1,"Conquest of Azeroth"],[2,"Wildcard"]];if(cmd==="realm_rename"){await new Promise(r=>setTimeout(r,300));const n=(args.name??"").trim();if(n.length>32||n.includes('"'))throw new Error("The realm name can have at most 32 characters.");if(n)w.__rn[args.realmId]=n;else delete w.__rn[args.realmId];}return defs.map(([id,d])=>({id,name:w.__rn[id]??d,defaultName:d,custom:id in w.__rn}));}
if(cmd==="realm_profiles") return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:simultaneous&&running,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:withReborn&&running};
if(cmd==="realm_simultaneous") { if(running) throw new Error("Stop both realms before changing simultaneous startup."); simultaneous=args.enabled; wildcardCreated ||= simultaneous; return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:false,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:false}; }
+5
View File
@@ -773,6 +773,11 @@ const de: Partial<Record<keyof typeof en, string>> = {
"overview.reportBtn": "Diagnose sammeln und melden",
// Realmlist switcher and modules page
"mysql.title": "MySQL-Einstellungen",
"mysql.hint": "Eigene MySQL-Optionen, eine Zeile name = wert. Sie werden bei jedem Start der Datenbank zu my.ini hinzugefügt und bleiben nach Updates erhalten. Port, Adressen und Datenpfade verwaltet der Manager; hier werden sie ignoriert.",
"mysql.save": "Speichern",
"mysql.saved": "Gespeichert; Server neu starten, um sie anzuwenden.",
"mysql.applied": "Angewandte Optionen: {count}",
"realm.namesTitle": "Realmnamen",
"realm.namesHint": "So heißt der Realm in der Realmliste der Spieler. Ein laufender Server zeigt den Namen sofort, und er bleibt nach Updates erhalten.",
"realm.nameSave": "Speichern",
+5
View File
@@ -57,6 +57,11 @@ const en = {
"remote.hostInstead": "Host my own server",
"welcome.roleSubtitle": "How would you like to play?",
"mysql.title": "MySQL settings",
"mysql.hint": "Your own MySQL options, one name = value per line. They are added to my.ini at every start of the database and stay after updates. The port, addresses and data paths are managed by the Manager and ignored here.",
"mysql.save": "Save",
"mysql.saved": "Saved; restart the server to apply.",
"mysql.applied": "Options applied: {count}",
"realm.namesTitle": "Realm names",
"realm.namesHint": "The name players see in the realm list. A running server shows it at once, and it stays after updates.",
"realm.nameSave": "Save",
+5
View File
@@ -773,6 +773,11 @@ const es: Partial<Record<keyof typeof en, string>> = {
"overview.reportBtn": "Reunir el diagnóstico y avisar",
// Realmlist switcher and modules page
"mysql.title": "Ajustes de MySQL",
"mysql.hint": "Tus propias opciones de MySQL, una línea nombre = valor. Se añaden a my.ini en cada inicio de la base de datos y se mantienen tras las actualizaciones. El puerto, las direcciones y las rutas de datos los gestiona el Manager y aquí se ignoran.",
"mysql.save": "Guardar",
"mysql.saved": "Guardado; reinicia el servidor para aplicarlo.",
"mysql.applied": "Opciones aplicadas: {count}",
"realm.namesTitle": "Nombres de los reinos",
"realm.namesHint": "El nombre que ven los jugadores en la lista de reinos. Un servidor en marcha lo muestra al instante y se mantiene tras las actualizaciones.",
"realm.nameSave": "Guardar",
+5
View File
@@ -773,6 +773,11 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"overview.reportBtn": "Rassembler le diagnostic et signaler",
// Realmlist switcher and modules page
"mysql.title": "Paramètres MySQL",
"mysql.hint": "Vos propres options MySQL, une ligne nom = valeur. Elles sont ajoutées à my.ini à chaque démarrage de la base et restent après les mises à jour. Le port, les adresses et les chemins de données sont gérés par le Manager et ignorés ici.",
"mysql.save": "Enregistrer",
"mysql.saved": "Enregistré ; redémarrez le serveur pour appliquer.",
"mysql.applied": "Options appliquées : {count}",
"realm.namesTitle": "Noms des royaumes",
"realm.namesHint": "Le nom que les joueurs voient dans la liste des royaumes. Un serveur en marche l'affiche aussitôt, et il reste après les mises à jour.",
"realm.nameSave": "Enregistrer",
+5
View File
@@ -60,6 +60,11 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"remote.hostInstead": "Создать свой сервер",
"welcome.roleSubtitle": "Как вы хотите играть?",
"mysql.title": "Настройки MySQL",
"mysql.hint": "Свои параметры MySQL, по одному «имя = значение» в строке. Они добавляются в my.ini при каждом запуске базы и сохраняются после обновлений. Порт, адреса и пути к данным задаёт Manager, здесь они игнорируются.",
"mysql.save": "Сохранить",
"mysql.saved": "Сохранено; перезапустите сервер, чтобы применить.",
"mysql.applied": "Применяется параметров: {count}",
"realm.namesTitle": "Названия реалмов",
"realm.namesHint": "Так реалм называется в списке реалмов у игроков. Работающий сервер показывает новое название сразу, и оно сохраняется после обновлений.",
"realm.nameSave": "Сохранить",
+5
View File
@@ -58,6 +58,11 @@ const zh = {
"remote.hostInstead": "搭建自己的服务器",
"welcome.roleSubtitle": "你想如何游玩?",
"mysql.title": "MySQL 设置",
"mysql.hint": "自定义 MySQL 选项,每行一个“名称 = 值”。每次数据库启动时都会加入 my.ini,更新后也会保留。端口、地址和数据路径由 Manager 管理,此处会被忽略。",
"mysql.save": "保存",
"mysql.saved": "已保存;重启服务器后生效。",
"mysql.applied": "生效的选项:{count}",
"realm.namesTitle": "服务器名称",
"realm.namesHint": "玩家在服务器列表中看到的名称。运行中的服务器会立即显示新名称,更新后也会保留。",
"realm.nameSave": "保存",
+3
View File
@@ -57,6 +57,7 @@ export interface StatusView {
}
export type RealmMode = "coa" | "wildcard" | "reborn";
export interface CustomMysql { text: string; applied: string }
export interface RealmName { id: number; name: string; defaultName: string; custom: boolean }
export interface RealmProfiles { active: RealmMode; wildcard_created: boolean; reborn_created: boolean; reborn_supported: boolean; supported: boolean; recovery_pending: boolean; simultaneous: boolean; secondary_world_port: number | null; secondary_running: boolean; with_reborn: boolean; reborn_world_port: number | null; reborn_running: boolean }
export interface DatabaseCheck {
@@ -487,6 +488,8 @@ export const api = {
realmProfiles: (id: string) => invoke<RealmProfiles>("realm_profiles", { id }),
realmSelect: (id: string, mode: RealmMode, restart: boolean) => invoke<RealmProfiles>("realm_select", { id, mode, restart }),
realmSimultaneous: (id: string, enabled: boolean) => invoke<RealmProfiles>("realm_simultaneous", { id, enabled }),
mysqlCustom: (id: string) => invoke<CustomMysql>("mysql_custom", { id }),
mysqlCustomSave: (id: string, text: string) => invoke<CustomMysql>("mysql_custom_save", { id, text }),
realmNames: (id: string) => invoke<RealmName[]>("realm_names", { id }),
realmRename: (id: string, realmId: number, name: string | null) => invoke<RealmName[]>("realm_rename", { id, realmId, name }),
realmWithReborn: (id: string, enabled: boolean) => invoke<RealmProfiles>("realm_with_reborn", { id, enabled }),
+48
View File
@@ -0,0 +1,48 @@
import { useEffect, useState } from "react";
import { api, asUiError, type CustomMysql } from "@/lib/api";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { useT } from "@/i18n";
/** The owner's own MySQL options (#103): kept in Settings/mysql-custom.ini and added to my.ini at every start. */
export function MySqlSettings({ serverId }: { serverId: string }) {
const t = useT();
const [saved, setSaved] = useState<CustomMysql | null>(null);
const [draft, setDraft] = useState("");
const [busy, setBusy] = useState(false);
const [done, setDone] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
void api.mysqlCustom(serverId).then(v => { if (alive) { setSaved(v); setDraft(v.text); } }).catch(e => { if (alive) setError(asUiError(e).technical); });
return () => { alive = false; };
}, [serverId]);
async function save() {
setBusy(true); setError(null); setDone(false);
try { const v = await api.mysqlCustomSave(serverId, draft); setSaved(v); setDraft(v.text); setDone(true); }
catch (e) { setError(asUiError(e).technical); }
finally { setBusy(false); }
}
const applied = saved?.applied.trim() ? saved.applied.trim().split("\n").length : 0;
return <Card className="mt-6 p-6" aria-busy={busy}>
<h2 className="font-semibold">{t("mysql.title")}</h2>
<p className="mt-1 text-sm text-muted">{t("mysql.hint")}</p>
<textarea
className="selectable mt-3 h-36 w-full rounded border border-line bg-bg p-3 font-mono text-xs text-ink outline-none focus:border-gold"
spellCheck={false}
placeholder={"innodb_buffer_pool_size = 1G\nmax_connections = 300"}
aria-label={t("mysql.title")}
value={draft}
disabled={busy || !saved}
onChange={e => { setDraft(e.target.value); setDone(false); }}
/>
<div className="mt-3 flex flex-wrap items-center gap-3">
<Button size="sm" disabled={busy || !saved || draft === saved.text} onClick={() => void save()}>{t("mysql.save")}</Button>
<span className="text-xs text-muted">{t("mysql.applied", { count: applied })}{done ? ` · ${t("mysql.saved")}` : ""}</span>
</div>
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
</Card>;
}
+2 -1
View File
@@ -13,6 +13,7 @@ import { ClientCard } from "./ClientCard";
import { GameDataCard } from "./GameDataCard";
import { RealmStartupSettings } from "./RealmStartupSettings";
import { RealmNameSettings } from "./RealmNameSettings";
import { MySqlSettings } from "./MySqlSettings";
import { AutoRestartSettings } from "./AutoRestartSettings";
import { DiagnosticsCard } from "./DiagnosticsCard";
import { RepairCard } from "./RepairCard";
@@ -53,7 +54,7 @@ export function SettingsHome({ serverId, path, onForget }: { serverId: string; s
</div>
<div hidden={section !== "startup"} className="max-w-3xl"><RealmNameSettings serverId={serverId} /><RealmStartupSettings serverId={serverId} /><AutoRestartSettings serverId={serverId} /></div>
<div hidden={section !== "client"} className="max-w-3xl"><ClientCard serverId={serverId} /><GameDataCard serverId={serverId} /></div>
<div hidden={section !== "service"} className="max-w-3xl"><ServerLoggingSettings serverId={serverId} /><DiagnosticsCard serverId={serverId} /><RepairCard serverId={serverId} /><RemoveServerCard serverId={serverId} path={path} onForget={onForget} /></div>
<div hidden={section !== "service"} className="max-w-3xl"><ServerLoggingSettings serverId={serverId} /><MySqlSettings serverId={serverId} /><DiagnosticsCard serverId={serverId} /><RepairCard serverId={serverId} /><RemoveServerCard serverId={serverId} path={path} onForget={onForget} /></div>
<div hidden={section !== "interface"} className="max-w-3xl"><Card className="mt-6 p-6"><h2 className="font-semibold">{t("settings.language")}</h2><p className="mt-1 text-sm text-muted">{t("settings.languageHint")}</p><LanguagePicker className="mt-4" /></Card><WindowSettings /><PublicServerSettings /></div>
</div>;
}