Merge pull request 'feat(sidecar): make the sidecar installable — CLI, --print-config, anchored data paths' (#24) from feat/installable-cli into main
Reviewed-on: #24 Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
This commit is contained in:
@@ -39,6 +39,15 @@ cp sidecar.toml.example sidecar.toml # then edit
|
||||
cargo run --release
|
||||
```
|
||||
|
||||
Deploying it rather than developing on it: `--config <PATH>` names the config file (as does
|
||||
`$UOLINK_CONFIG`), and `--print-config` prints the resolved settings — **including the auth token
|
||||
the website needs** — as JSON, provisioning the config file on first run. That is the supported way
|
||||
to read the token back; it is not meant to be scraped from the log.
|
||||
|
||||
```bash
|
||||
uo-link-sidecar --print-config --config /etc/runicgateway/sidecar.toml
|
||||
```
|
||||
|
||||
`.gitea/workflows/release.yml` cross-compiles Linux + Windows binaries and cuts a Gitea release on
|
||||
every merge to `main` (conventional-commit versioning). See [`sidecar/README.md`](sidecar/README.md)
|
||||
for configuration and the wire protocol.
|
||||
|
||||
@@ -18,9 +18,61 @@ RUST_LOG=debug cargo run # see every event, incl. pong heartbeats
|
||||
|
||||
On first run it writes `sidecar.toml` with a generated auth token and logs the path. Binds the shard listener (`127.0.0.1:7788`) and the web server (`127.0.0.1:8080`) from that file, then waits for the shard to connect.
|
||||
|
||||
## Command line
|
||||
|
||||
Four flags. Everything else is configuration, and configuration lives in the file.
|
||||
|
||||
```
|
||||
uo-link-sidecar [--print-config] [--config <PATH>] [-V|--version] [-h|--help]
|
||||
```
|
||||
|
||||
| Flag | What |
|
||||
|------|------|
|
||||
| `--print-config` | Resolve the configuration, print it as JSON on stdout, exit. |
|
||||
| `--config <PATH>` | Path to `sidecar.toml`. Outranks `$UOLINK_CONFIG`; default `./sidecar.toml`. |
|
||||
| `-V`, `--version` | `uo-link-sidecar <ver> (protocol <n>)`. |
|
||||
| `-h`, `--help` | Usage. |
|
||||
|
||||
An unrecognized argument is an error (exit `2`), not something to ignore — a typo'd flag would otherwise start a sidecar that is not the one you asked for.
|
||||
|
||||
### `--print-config`
|
||||
|
||||
The non-interactive way to read the sidecar's own settings back, so an installer or a diagnostic never has to scrape the startup log or parse TOML:
|
||||
|
||||
```console
|
||||
$ uo-link-sidecar --print-config --config /etc/runicgateway/sidecar.toml
|
||||
{
|
||||
"component": "uo-link-sidecar",
|
||||
"config_created": false,
|
||||
"config_path": "/etc/runicgateway/sidecar.toml",
|
||||
"protocol": 3,
|
||||
"shard": { "bind": "127.0.0.1:7788" },
|
||||
"store": { "path": "/var/lib/runicgateway/uo-link.db" },
|
||||
"token_generated": false,
|
||||
"version": "0.1.0",
|
||||
"web": {
|
||||
"auth_required": true,
|
||||
"auth_token": "c0f04ace66a937edff407d9dc25d5d8a967b0300e3306f11",
|
||||
"bind": "127.0.0.1:8080",
|
||||
"ws_path": "/ws"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- **It contains the auth token in clear text.** That is the point — those values go straight into Admin → Shard — but it means the output is a secret: don't pipe it into a log or a CI artifact.
|
||||
- **It performs first-run setup**, exactly as a normal start would: a missing config file is written and a blank token is generated and saved. So `--print-config` on a fresh host provisions the sidecar *and* tells you its token in one step. `config_created` and `token_generated` report whether this run did either, which is how a re-run distinguishes "read an existing install" from "provisioned a new one".
|
||||
- Paths are the **resolved absolute** ones, not what the file literally says.
|
||||
- Nothing else is written to stdout — the log subscriber is not started in this mode, so the JSON is the entire output.
|
||||
|
||||
## Configuration & auth
|
||||
|
||||
All runtime settings live in `sidecar.toml` (path overridable with `$UOLINK_CONFIG`) — **nothing is compiled into the binary**. See `sidecar.toml.example`. Environment variables override the file: `UOLINK_SHARD_BIND`, `UOLINK_WEB_BIND`, `UOLINK_WEB_TOKEN`, `UOLINK_DB_PATH`.
|
||||
All runtime settings live in `sidecar.toml` (path overridable with `--config` or `$UOLINK_CONFIG`) — **nothing is compiled into the binary**. See `sidecar.toml.example`. Environment variables override the file: `UOLINK_SHARD_BIND`, `UOLINK_WEB_BIND`, `UOLINK_WEB_TOKEN`, `UOLINK_DB_PATH`.
|
||||
|
||||
### Where the data goes
|
||||
|
||||
A **relative** `[store].path` resolves against the directory holding `sidecar.toml`, not the process's working directory. Under `cargo run` those are the same thing, so nothing changes for development; for an installed service they are emphatically not. A unit that pins `UOLINK_CONFIG=/etc/runicgateway/sidecar.toml` and leaves the default `uo-link.db` gets `/etc/runicgateway/uo-link.db` — beside its config, deterministically — instead of a database wherever the service manager happened to set CWD (`%SystemRoot%\System32`, or a silently redirected VirtualStore copy under `C:\Program Files\`).
|
||||
|
||||
Absolute paths are used as written, and the parent directory is created if it does not exist, so a service can name `/var/lib/runicgateway/uo-link.db` on a host where nothing has created that directory yet. Paths are handed to SQLite as filesystem paths rather than being formatted into a `sqlite://` URL, so a `%`, `#`, `?` or space in the path means what it looks like.
|
||||
|
||||
The website authenticates to the sidecar with a shared token, presented as:
|
||||
|
||||
@@ -56,7 +108,7 @@ Bump `PROTOCOL_VERSION` in `main.rs` whenever an event or endpoint's shape chang
|
||||
```json
|
||||
{
|
||||
"status": "ok", // "ok" when plugin connected and DB reachable, else "degraded"
|
||||
"protocol": 1,
|
||||
"protocol": 3,
|
||||
"plugin_connected": true, // is the shard link up?
|
||||
"database": "ok",
|
||||
"uptime": "3d 12h",
|
||||
@@ -101,7 +153,9 @@ A shard `*.error` reply maps to HTTP 404 (unknown/not-found) or 400 (bad request
|
||||
- **`shard.rs`** — `serve()` binds the listener and accepts shard connections in a loop. Each connection splits into read/write halves: the read half parses newline-JSON into `ShardEvent { kind, value }` and forwards them; the write half drains an mpsc of command lines. `ShardHandle::send` posts a command to whichever shard is currently connected, and **drops with a warning if none is** — a website query during a shard outage should fail fast and retry, not queue behind a reconnect. Live *events* that must survive an outage are buffered by the shard, not here.
|
||||
- **`web.rs`** — the website-facing HTTP surface (axum). `AppState` holds the `broadcast::Sender<String>`; each `/ws` client subscribes and forwards every event as a text frame. A client that lags past the broadcast buffer is warned and kept live (it just misses events) rather than stalling the others. This side *may* be exposed beyond loopback — it is the gatekeeper, so add auth when you do.
|
||||
- **`rpc.rs`** — request/reply correlation over the one shard socket. A REST call registers a pending entry under a correlation id, sends the command, and awaits the reply (10 s timeout). The event loop routes any incoming line whose id is pending back to the waiter; everything else flows on as a live event. Recognizes three correlation fields, matching what the plugin echoes: `reqId` (queries), `code` (link), `id` (town-crier).
|
||||
- **`store.rs`** — SQLite (`sqlx`). Three tables: `events` (the full live stream, append-only), `links` (account ↔ website user, mirrored from `link.ok`), `profiles` (last-known character sheet, cached from `char.profile`). History and economy read here instead of the shard; `pong` is dropped as ephemeral chatter. DB file defaults to `uo-link.db` (`DB_PATH` in `main.rs`), gitignored.
|
||||
- **`store.rs`** — SQLite (`sqlx`). Three tables: `events` (the full live stream, append-only), `links` (account ↔ website user, mirrored from `link.ok`), `profiles` (last-known character sheet, cached from `char.profile`). History and economy read here instead of the shard; `pong` is dropped as ephemeral chatter. The DB file is `[store].path` (default `uo-link.db` beside the config), gitignored.
|
||||
- **`config.rs`** — resolves the config file, applies the environment overrides, guarantees an auth token, anchors relative paths, and renders the `--print-config` document.
|
||||
- **`cli.rs`** — the four flags above. Hand-rolled; no argument-parsing dependency.
|
||||
- **`main.rs`** — wires it together: the shard event loop first tries to route each line as an RPC reply; if it isn't one, the line is a live event — logged, persisted, and broadcast to WS.
|
||||
|
||||
## Wire protocol
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
# uo-link sidecar configuration — example.
|
||||
#
|
||||
# The sidecar reads `sidecar.toml` (override the path with $UOLINK_CONFIG). If that file
|
||||
# is absent on first run, one is generated automatically with a random auth_token, so you
|
||||
# normally do not create this by hand — just start the sidecar and edit the file it writes.
|
||||
# Nothing here is compiled into the binary.
|
||||
# The sidecar reads `sidecar.toml` (override the path with --config or $UOLINK_CONFIG).
|
||||
# If that file is absent on first run, one is generated automatically with a random
|
||||
# auth_token, so you normally do not create this by hand — just start the sidecar and edit
|
||||
# the file it writes. Nothing here is compiled into the binary.
|
||||
#
|
||||
# Environment variables override the file:
|
||||
# UOLINK_SHARD_BIND, UOLINK_WEB_BIND, UOLINK_WEB_TOKEN, UOLINK_DB_PATH
|
||||
#
|
||||
# Read the resolved settings back without starting the sidecar (JSON, includes the token):
|
||||
# uo-link-sidecar --print-config --config /etc/runicgateway/sidecar.toml
|
||||
|
||||
[shard]
|
||||
# Loopback address the shard dials out to. Keep this on localhost — the game must not
|
||||
@@ -27,4 +30,9 @@ bind = "127.0.0.1:8080"
|
||||
auth_token = "replace-with-a-long-random-secret"
|
||||
|
||||
[store]
|
||||
# A RELATIVE path resolves against the directory holding this file, not the working
|
||||
# directory of the process — so a service pinned to /etc/runicgateway/sidecar.toml keeps
|
||||
# its database beside its config no matter what CWD the service manager picked. Give an
|
||||
# absolute path (or set UOLINK_DB_PATH) to put the data somewhere else, e.g.
|
||||
# /var/lib/runicgateway/uo-link.db or C:\ProgramData\RunicGateway\uo-link.db.
|
||||
path = "uo-link.db"
|
||||
|
||||
172
sidecar/src/cli.rs
Normal file
172
sidecar/src/cli.rs
Normal file
@@ -0,0 +1,172 @@
|
||||
//! Command-line surface.
|
||||
//!
|
||||
//! The sidecar is configured by file and environment (see [`crate::config`]); this is deliberately
|
||||
//! not a second configuration mechanism. It exists so the binary can be *driven by an installer*
|
||||
//! rather than only by a human reading its logs:
|
||||
//!
|
||||
//! - `--print-config` resolves the configuration exactly as a normal start would — including
|
||||
//! generating the auth token on first run — and prints it as JSON on stdout. That is the
|
||||
//! supported way to obtain the token for the website's Admin → Shard form. Before this existed,
|
||||
//! the only way to read it back was to scrape the startup log or parse `sidecar.toml`.
|
||||
//! - `--config <PATH>` names the config file without having to export `UOLINK_CONFIG`, so a
|
||||
//! diagnostic run can point at an installed config from any working directory.
|
||||
//!
|
||||
//! Hand-rolled rather than pulled from a crate: four flags, no subcommands, no completions. A
|
||||
//! dependency here would be larger than the code it replaced.
|
||||
|
||||
/// What this invocation should do. Everything except `Run` prints and exits.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
/// Normal operation: bind the shard listener and the web server.
|
||||
Run,
|
||||
/// Resolve config, print it as JSON, exit.
|
||||
PrintConfig,
|
||||
Help,
|
||||
Version,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Cli {
|
||||
pub mode: Mode,
|
||||
/// `--config <PATH>`, which outranks `$UOLINK_CONFIG`.
|
||||
pub config: Option<String>,
|
||||
}
|
||||
|
||||
pub const USAGE: &str = "\
|
||||
uo-link sidecar — bridges a ServUO shard to the Runic Gateway website.
|
||||
|
||||
Usage: uo-link-sidecar [OPTIONS]
|
||||
|
||||
Options:
|
||||
--print-config Resolve the configuration, print it as JSON, and exit.
|
||||
Runs first-run setup like a normal start does: if the
|
||||
config file is missing it is written, and a blank auth
|
||||
token is generated and saved. The JSON CONTAINS THE
|
||||
AUTH TOKEN in clear text.
|
||||
--config <PATH> Path to sidecar.toml. Overrides $UOLINK_CONFIG;
|
||||
defaults to ./sidecar.toml.
|
||||
-V, --version Print the sidecar and protocol versions and exit.
|
||||
-h, --help Print this help and exit.
|
||||
|
||||
Configuration lives in sidecar.toml; environment variables override the file:
|
||||
UOLINK_CONFIG, UOLINK_SHARD_BIND, UOLINK_WEB_BIND, UOLINK_WEB_TOKEN,
|
||||
UOLINK_DB_PATH
|
||||
";
|
||||
|
||||
/// Parses arguments **without** the program name.
|
||||
///
|
||||
/// Returns the message to print on stderr when the arguments are unusable; the caller exits `2`.
|
||||
pub fn parse<I: IntoIterator<Item = String>>(args: I) -> Result<Cli, String> {
|
||||
let mut mode = Mode::Run;
|
||||
let mut config = None;
|
||||
let mut it = args.into_iter();
|
||||
|
||||
while let Some(arg) = it.next() {
|
||||
match arg.as_str() {
|
||||
"--print-config" => mode = Mode::PrintConfig,
|
||||
"-h" | "--help" => {
|
||||
return Ok(Cli {
|
||||
mode: Mode::Help,
|
||||
config,
|
||||
})
|
||||
}
|
||||
"-V" | "--version" => {
|
||||
return Ok(Cli {
|
||||
mode: Mode::Version,
|
||||
config,
|
||||
})
|
||||
}
|
||||
"--config" => {
|
||||
// `--config` with nothing after it would otherwise silently fall through and start
|
||||
// the sidecar against the default config — the opposite of what was asked for.
|
||||
let path = it
|
||||
.next()
|
||||
.ok_or_else(|| "--config requires a path".to_string())?;
|
||||
config = Some(path);
|
||||
}
|
||||
_ => match arg.strip_prefix("--config=") {
|
||||
Some("") => return Err("--config requires a path".into()),
|
||||
Some(path) => config = Some(path.to_string()),
|
||||
None => return Err(format!("unrecognized argument: {arg}")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Cli { mode, config })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse_str(args: &[&str]) -> Result<Cli, String> {
|
||||
parse(args.iter().map(|s| s.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_arguments_runs_the_sidecar() {
|
||||
let cli = parse_str(&[]).unwrap();
|
||||
assert_eq!(cli.mode, Mode::Run);
|
||||
assert_eq!(cli.config, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_config_is_recognized() {
|
||||
assert_eq!(
|
||||
parse_str(&["--print-config"]).unwrap().mode,
|
||||
Mode::PrintConfig
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_accepts_both_spellings() {
|
||||
let spaced = parse_str(&["--config", "/etc/runicgateway/sidecar.toml"]).unwrap();
|
||||
let equals = parse_str(&["--config=/etc/runicgateway/sidecar.toml"]).unwrap();
|
||||
assert_eq!(
|
||||
spaced.config.as_deref(),
|
||||
Some("/etc/runicgateway/sidecar.toml")
|
||||
);
|
||||
assert_eq!(spaced, equals);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_combines_with_print_config() {
|
||||
let cli = parse_str(&["--config", "c.toml", "--print-config"]).unwrap();
|
||||
assert_eq!(cli.mode, Mode::PrintConfig);
|
||||
assert_eq!(cli.config.as_deref(), Some("c.toml"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_is_never_swallowed_as_a_flag() {
|
||||
// `--config --print-config` takes the next token as the path, wrong as that path is. The
|
||||
// alternative — treating it as a missing value — guesses at intent.
|
||||
let cli = parse_str(&["--config", "--print-config"]).unwrap();
|
||||
assert_eq!(cli.mode, Mode::Run);
|
||||
assert_eq!(cli.config.as_deref(), Some("--print-config"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_without_a_value_is_an_error() {
|
||||
assert!(parse_str(&["--config"]).is_err());
|
||||
assert!(parse_str(&["--config="]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_arguments_are_rejected() {
|
||||
// Silently ignoring a typo'd flag would start a sidecar that is not what was asked for.
|
||||
let err = parse_str(&["--pirnt-config"]).unwrap_err();
|
||||
assert!(err.contains("--pirnt-config"), "{err}");
|
||||
assert!(parse_str(&["/etc/runicgateway/sidecar.toml"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_and_version_win_immediately() {
|
||||
assert_eq!(parse_str(&["--help", "--bogus"]).unwrap().mode, Mode::Help);
|
||||
assert_eq!(parse_str(&["-h"]).unwrap().mode, Mode::Help);
|
||||
assert_eq!(
|
||||
parse_str(&["--version", "--bogus"]).unwrap().mode,
|
||||
Mode::Version
|
||||
);
|
||||
assert_eq!(parse_str(&["-V"]).unwrap().mode, Mode::Version);
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,26 @@
|
||||
//! first run, if the file is absent, a default one is written with a freshly generated auth token,
|
||||
//! so the sidecar is secured out of the box and the operator just copies the token to the website.
|
||||
//!
|
||||
//! File path: `$UOLINK_CONFIG`, else `sidecar.toml` in the working directory.
|
||||
//! File path: `--config <PATH>`, else `$UOLINK_CONFIG`, else `sidecar.toml` in the working
|
||||
//! directory.
|
||||
//!
|
||||
//! **Paths are anchored to the config file, not the working directory.** A relative
|
||||
//! `[store].path` resolves against the directory holding `sidecar.toml`. A service started with
|
||||
//! `UOLINK_CONFIG=/etc/runicgateway/sidecar.toml` therefore keeps its database beside its config
|
||||
//! instead of wherever the service manager happened to set the working directory — which on
|
||||
//! Windows can be `%SystemRoot%\System32` or, under `C:\Program Files\`, a silently redirected
|
||||
//! VirtualStore copy. The values reported by `--print-config` are the resolved absolute ones.
|
||||
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use tracing::info;
|
||||
|
||||
use crate::PROTOCOL_VERSION;
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub struct Config {
|
||||
#[serde(default)]
|
||||
@@ -33,8 +44,8 @@ pub struct ShardCfg {
|
||||
pub struct WebCfg {
|
||||
#[serde(default = "default_web_bind")]
|
||||
pub bind: String,
|
||||
/// Shared secret the website must present. Empty means the web surface is unauthenticated —
|
||||
/// only acceptable when `bind` is loopback; refused otherwise (see `Config::validate`).
|
||||
/// Shared secret the website must present. Never empty in practice — `Config::load` generates
|
||||
/// and persists one when it finds none, so the web surface is authenticated from first boot.
|
||||
#[serde(default)]
|
||||
pub auth_token: String,
|
||||
}
|
||||
@@ -45,6 +56,20 @@ pub struct StoreCfg {
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// A loaded configuration plus what loading it *did* — an installer re-running the binary needs to
|
||||
/// distinguish "read an existing install" from "provisioned a new one", and it cannot tell from the
|
||||
/// values alone.
|
||||
#[derive(Debug)]
|
||||
pub struct Loaded {
|
||||
pub cfg: Config,
|
||||
/// Absolute path of the config file that was read or written.
|
||||
pub path: PathBuf,
|
||||
/// The config file did not exist and was created by this run.
|
||||
pub config_created: bool,
|
||||
/// No usable token was configured, so one was generated and saved.
|
||||
pub token_generated: bool,
|
||||
}
|
||||
|
||||
fn default_shard_bind() -> String {
|
||||
"127.0.0.1:7788".into()
|
||||
}
|
||||
@@ -79,9 +104,20 @@ impl Default for StoreCfg {
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn load() -> anyhow::Result<Self> {
|
||||
let path = env::var("UOLINK_CONFIG").unwrap_or_else(|_| "sidecar.toml".into());
|
||||
let existed = Path::new(&path).exists();
|
||||
/// Which config file this invocation will use: `--config`, else `$UOLINK_CONFIG`, else
|
||||
/// `sidecar.toml` beside the working directory. Always returned absolute, so every later
|
||||
/// message names a path the operator can act on.
|
||||
pub fn resolve_path(cli_override: Option<&str>) -> PathBuf {
|
||||
let raw = cli_override
|
||||
.map(str::to_string)
|
||||
.or_else(|| env::var("UOLINK_CONFIG").ok())
|
||||
.unwrap_or_else(|| "sidecar.toml".into());
|
||||
absolutize(PathBuf::from(raw))
|
||||
}
|
||||
|
||||
pub fn load(cli_override: Option<&str>) -> anyhow::Result<Loaded> {
|
||||
let path = Self::resolve_path(cli_override);
|
||||
let existed = path.exists();
|
||||
|
||||
let mut cfg: Config = if existed {
|
||||
let text = fs::read_to_string(&path)?;
|
||||
@@ -95,12 +131,16 @@ impl Config {
|
||||
// Authentication is always on. A blank token is never allowed — if none is set (fresh
|
||||
// install, or someone cleared it), generate one, save it, and continue. This keeps setup
|
||||
// effortless while making it impossible to accidentally run with auth off.
|
||||
if cfg.web.auth_token.trim().is_empty() {
|
||||
let token_generated = cfg.web.auth_token.trim().is_empty();
|
||||
if token_generated {
|
||||
let token = generate_token();
|
||||
|
||||
if existed {
|
||||
persist_token(&path, &token)?;
|
||||
} else {
|
||||
// The parent may not exist yet when an installer points at a fresh
|
||||
// /etc/runicgateway; failing here would mean "run me again after mkdir".
|
||||
create_parent_dir(&path)?;
|
||||
fs::write(&path, default_file(&token))?;
|
||||
}
|
||||
|
||||
@@ -108,10 +148,17 @@ impl Config {
|
||||
|
||||
info!("No auth token configured.");
|
||||
info!("Generated new token: {}", token);
|
||||
info!("Saved to {}. Authentication is on.", path);
|
||||
info!("Saved to {}. Authentication is on.", path.display());
|
||||
}
|
||||
|
||||
Ok(cfg)
|
||||
cfg.anchor_store_path(&path);
|
||||
|
||||
Ok(Loaded {
|
||||
cfg,
|
||||
path,
|
||||
config_created: !existed,
|
||||
token_generated,
|
||||
})
|
||||
}
|
||||
|
||||
/// Environment overrides, so a deployment can set secrets without editing the file.
|
||||
@@ -130,15 +177,102 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves `[store].path` against the config file's directory (see the module docs). Absolute
|
||||
/// paths and SQLite's non-filesystem spellings are left exactly as written.
|
||||
fn anchor_store_path(&mut self, config_path: &Path) {
|
||||
if is_sqlite_special(&self.store.path) {
|
||||
return;
|
||||
}
|
||||
let raw = PathBuf::from(&self.store.path);
|
||||
let anchored = if raw.is_absolute() {
|
||||
raw
|
||||
} else {
|
||||
config_dir(config_path).join(raw)
|
||||
};
|
||||
self.store.path = absolutize(anchored).to_string_lossy().into_owned();
|
||||
}
|
||||
|
||||
pub fn auth_required(&self) -> bool {
|
||||
// Always true now — load() guarantees a non-empty token.
|
||||
!self.web.auth_token.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// The `--print-config` document: everything an installer needs to register this sidecar with a
|
||||
/// website, in one non-interactive read.
|
||||
///
|
||||
/// **This includes the auth token in clear text**, which is the point — §2.4 of the installer plan
|
||||
/// calls the manual token hunt the largest "I installed it and nothing happened" failure mode. The
|
||||
/// caller prints it to stdout and starts no log subscriber, so the document is the whole output.
|
||||
pub fn describe(loaded: &Loaded) -> serde_json::Value {
|
||||
json!({
|
||||
"component": "uo-link-sidecar",
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"protocol": PROTOCOL_VERSION,
|
||||
"config_path": loaded.path.to_string_lossy(),
|
||||
"config_created": loaded.config_created,
|
||||
"token_generated": loaded.token_generated,
|
||||
"shard": { "bind": loaded.cfg.shard.bind },
|
||||
"web": {
|
||||
"bind": loaded.cfg.web.bind,
|
||||
"ws_path": crate::web::WS_PATH,
|
||||
"auth_required": loaded.cfg.auth_required(),
|
||||
"auth_token": loaded.cfg.web.auth_token,
|
||||
},
|
||||
"store": { "path": loaded.cfg.store.path },
|
||||
})
|
||||
}
|
||||
|
||||
/// Directory holding the config file. A bare `sidecar.toml` has no parent component, which would
|
||||
/// join into an empty base — treat it as the current directory.
|
||||
fn config_dir(config_path: &Path) -> PathBuf {
|
||||
match config_path.parent() {
|
||||
Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
|
||||
_ => PathBuf::from("."),
|
||||
}
|
||||
}
|
||||
|
||||
/// Prefixes the working directory onto a relative path, then drops the `.` components that
|
||||
/// joining leaves behind — cosmetic, but these paths are printed and pasted into service units.
|
||||
fn absolutize(p: PathBuf) -> PathBuf {
|
||||
let joined = if p.is_absolute() {
|
||||
p
|
||||
} else {
|
||||
match env::current_dir() {
|
||||
Ok(cwd) => cwd.join(p),
|
||||
Err(_) => p,
|
||||
}
|
||||
};
|
||||
let cleaned: PathBuf = joined
|
||||
.components()
|
||||
.filter(|c| !matches!(c, Component::CurDir))
|
||||
.collect();
|
||||
if cleaned.as_os_str().is_empty() {
|
||||
joined
|
||||
} else {
|
||||
cleaned
|
||||
}
|
||||
}
|
||||
|
||||
/// `:memory:` and `file:` URIs are instructions to SQLite, not paths on disk. Anchoring them to a
|
||||
/// directory would turn a working in-memory store into an attempt to create a file called
|
||||
/// `:memory:` — which Windows cannot even name.
|
||||
fn is_sqlite_special(path: &str) -> bool {
|
||||
path == ":memory:" || path.starts_with("file:")
|
||||
}
|
||||
|
||||
fn create_parent_dir(path: &Path) -> anyhow::Result<()> {
|
||||
if let Some(dir) = path.parent() {
|
||||
if !dir.as_os_str().is_empty() && !dir.exists() {
|
||||
fs::create_dir_all(dir)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rewrites the `auth_token` line in an existing config file, preserving everything else. Falls
|
||||
/// back to inserting it under `[web]`, or appending a `[web]` section, if the key is absent.
|
||||
fn persist_token(path: &str, token: &str) -> anyhow::Result<()> {
|
||||
fn persist_token(path: &Path, token: &str) -> anyhow::Result<()> {
|
||||
let text = fs::read_to_string(path)?;
|
||||
let line = format!("auth_token = \"{token}\"");
|
||||
|
||||
@@ -213,10 +347,269 @@ bind = "127.0.0.1:8080"
|
||||
# WebSocket: add ?token=<token> to the connect URL
|
||||
# Authentication is always on: if this is left blank, the sidecar generates a new
|
||||
# token here on startup. Rotate by changing this value and restarting.
|
||||
# Read it back without starting the sidecar: uo-link-sidecar --print-config
|
||||
auth_token = "{token}"
|
||||
|
||||
[store]
|
||||
# Relative paths resolve against the directory holding THIS FILE, not the working
|
||||
# directory of the process.
|
||||
path = "uo-link.db"
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A unique scratch directory. `std::env::temp_dir()` plus the test name keeps the cases
|
||||
/// independent under the default parallel test runner.
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let dir = env::temp_dir().join(format!("uo-link-cfg-test-{name}"));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).expect("create scratch dir");
|
||||
dir
|
||||
}
|
||||
|
||||
/// `Config::load` consults the process environment, and a developer may have `UOLINK_*` set
|
||||
/// for a local shard. Mutating shared env state from a test thread is worse than skipping, so
|
||||
/// the two cases that exercise the full load path bail out instead of failing spuriously.
|
||||
fn env_overrides_present() -> bool {
|
||||
[
|
||||
"UOLINK_SHARD_BIND",
|
||||
"UOLINK_WEB_BIND",
|
||||
"UOLINK_WEB_TOKEN",
|
||||
"UOLINK_DB_PATH",
|
||||
]
|
||||
.iter()
|
||||
.any(|k| env::var_os(k).is_some())
|
||||
}
|
||||
|
||||
fn cfg_with_store(path: &str) -> Config {
|
||||
Config {
|
||||
store: StoreCfg { path: path.into() },
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_store_path_anchors_to_the_config_directory() {
|
||||
// The working-directory trap: the service pins UOLINK_CONFIG but the service manager
|
||||
// decides the CWD, so a relative db path must not follow the CWD.
|
||||
let mut cfg = cfg_with_store("uo-link.db");
|
||||
let config_path = if cfg!(windows) {
|
||||
PathBuf::from(r"C:\ProgramData\RunicGateway\sidecar.toml")
|
||||
} else {
|
||||
PathBuf::from("/etc/runicgateway/sidecar.toml")
|
||||
};
|
||||
cfg.anchor_store_path(&config_path);
|
||||
|
||||
let expected = config_path.parent().unwrap().join("uo-link.db");
|
||||
assert_eq!(Path::new(&cfg.store.path), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_store_path_is_left_alone() {
|
||||
let absolute = if cfg!(windows) {
|
||||
r"C:\ProgramData\RunicGateway\uo-link.db"
|
||||
} else {
|
||||
"/var/lib/runicgateway/uo-link.db"
|
||||
};
|
||||
let mut cfg = cfg_with_store(absolute);
|
||||
cfg.anchor_store_path(Path::new("/etc/runicgateway/sidecar.toml"));
|
||||
assert_eq!(cfg.store.path, absolute);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_config_filename_anchors_to_the_working_directory() {
|
||||
// `cargo run` in the crate root: config dir and CWD are the same, so the historical
|
||||
// behavior (db beside the binary's CWD) is preserved exactly.
|
||||
let mut cfg = cfg_with_store("uo-link.db");
|
||||
cfg.anchor_store_path(Path::new("sidecar.toml"));
|
||||
assert_eq!(
|
||||
Path::new(&cfg.store.path),
|
||||
env::current_dir().unwrap().join("uo-link.db")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlite_special_paths_are_not_anchored() {
|
||||
for special in [":memory:", "file:cache?mode=memory"] {
|
||||
let mut cfg = cfg_with_store(special);
|
||||
cfg.anchor_store_path(Path::new("/etc/runicgateway/sidecar.toml"));
|
||||
assert_eq!(cfg.store.path, special);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_path_prefers_the_cli_override() {
|
||||
// Absolute in, absolute out — and unchanged, so the operator sees the path they passed.
|
||||
let explicit = if cfg!(windows) {
|
||||
r"C:\tmp\custom.toml"
|
||||
} else {
|
||||
"/tmp/custom.toml"
|
||||
};
|
||||
assert_eq!(
|
||||
Config::resolve_path(Some(explicit)),
|
||||
PathBuf::from(explicit)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_path_makes_a_relative_override_absolute() {
|
||||
let resolved = Config::resolve_path(Some("./conf/sidecar.toml"));
|
||||
assert!(resolved.is_absolute(), "{}", resolved.display());
|
||||
assert_eq!(
|
||||
resolved,
|
||||
env::current_dir()
|
||||
.unwrap()
|
||||
.join("conf")
|
||||
.join("sidecar.toml")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persist_token_replaces_an_existing_key() {
|
||||
let dir = scratch("replace");
|
||||
let path = dir.join("sidecar.toml");
|
||||
fs::write(
|
||||
&path,
|
||||
"[web]\nbind = \"127.0.0.1:8080\"\nauth_token = \"\"\n\n[store]\npath = \"x.db\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
persist_token(&path, "deadbeef").unwrap();
|
||||
|
||||
let out = fs::read_to_string(&path).unwrap();
|
||||
assert!(out.contains("auth_token = \"deadbeef\""), "{out}");
|
||||
assert_eq!(out.matches("auth_token").count(), 1, "{out}");
|
||||
// Everything else survives — the file is the operator's, not ours to rewrite.
|
||||
assert!(out.contains("bind = \"127.0.0.1:8080\""), "{out}");
|
||||
assert!(out.contains("path = \"x.db\""), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persist_token_inserts_under_an_existing_web_section() {
|
||||
let dir = scratch("insert");
|
||||
let path = dir.join("sidecar.toml");
|
||||
fs::write(&path, "[web]\nbind = \"127.0.0.1:8080\"\n").unwrap();
|
||||
|
||||
persist_token(&path, "deadbeef").unwrap();
|
||||
|
||||
let out = fs::read_to_string(&path).unwrap();
|
||||
let web = out.find("[web]").unwrap();
|
||||
let token = out.find("auth_token").unwrap();
|
||||
assert!(token > web, "token must land inside [web]: {out}");
|
||||
assert!(out.contains("auth_token = \"deadbeef\""), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persist_token_appends_a_web_section_when_there_is_none() {
|
||||
let dir = scratch("append");
|
||||
let path = dir.join("sidecar.toml");
|
||||
fs::write(&path, "[shard]\nbind = \"127.0.0.1:7788\"\n").unwrap();
|
||||
|
||||
persist_token(&path, "deadbeef").unwrap();
|
||||
|
||||
let out = fs::read_to_string(&path).unwrap();
|
||||
assert!(out.contains("[shard]"), "{out}");
|
||||
assert!(out.contains("[web]\nauth_token = \"deadbeef\""), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generated_config_round_trips_through_the_parser() {
|
||||
// The template is a format! string, so a stray brace or a bad key would only ever surface
|
||||
// on someone's first run.
|
||||
let cfg: Config = toml::from_str(&default_file("deadbeef")).expect("template parses");
|
||||
assert_eq!(cfg.web.auth_token, "deadbeef");
|
||||
assert_eq!(cfg.shard.bind, "127.0.0.1:7788");
|
||||
assert_eq!(cfg.web.bind, "127.0.0.1:8080");
|
||||
assert_eq!(cfg.store.path, "uo-link.db");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_tokens_are_random_and_hex() {
|
||||
let (a, b) = (generate_token(), generate_token());
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(a.len(), 48);
|
||||
assert!(a.chars().all(|c| c.is_ascii_hexdigit()), "{a}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn describe_reports_the_resolved_configuration() {
|
||||
let loaded = Loaded {
|
||||
cfg: Config {
|
||||
shard: ShardCfg {
|
||||
bind: "127.0.0.1:7788".into(),
|
||||
},
|
||||
web: WebCfg {
|
||||
bind: "0.0.0.0:8080".into(),
|
||||
auth_token: "deadbeef".into(),
|
||||
},
|
||||
store: StoreCfg {
|
||||
path: "/var/lib/runicgateway/uo-link.db".into(),
|
||||
},
|
||||
},
|
||||
path: PathBuf::from("/etc/runicgateway/sidecar.toml"),
|
||||
config_created: true,
|
||||
token_generated: true,
|
||||
};
|
||||
|
||||
let doc = describe(&loaded);
|
||||
|
||||
assert_eq!(doc["component"], "uo-link-sidecar");
|
||||
assert_eq!(doc["version"], env!("CARGO_PKG_VERSION"));
|
||||
assert_eq!(doc["protocol"], PROTOCOL_VERSION);
|
||||
assert_eq!(doc["config_path"], "/etc/runicgateway/sidecar.toml");
|
||||
assert_eq!(doc["config_created"], true);
|
||||
assert_eq!(doc["token_generated"], true);
|
||||
assert_eq!(doc["shard"]["bind"], "127.0.0.1:7788");
|
||||
assert_eq!(doc["web"]["bind"], "0.0.0.0:8080");
|
||||
assert_eq!(doc["web"]["ws_path"], "/ws");
|
||||
assert_eq!(doc["web"]["auth_required"], true);
|
||||
assert_eq!(doc["web"]["auth_token"], "deadbeef");
|
||||
assert_eq!(doc["store"]["path"], "/var/lib/runicgateway/uo-link.db");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_provisions_a_missing_config_and_reports_it() {
|
||||
if env_overrides_present() {
|
||||
return;
|
||||
}
|
||||
let dir = scratch("provision");
|
||||
let path = dir.join("sidecar.toml");
|
||||
|
||||
let loaded = Config::load(Some(path.to_str().unwrap())).unwrap();
|
||||
|
||||
assert!(loaded.config_created);
|
||||
assert!(loaded.token_generated);
|
||||
assert!(
|
||||
path.exists(),
|
||||
"the config file must be written, not just held in memory"
|
||||
);
|
||||
assert!(!loaded.cfg.web.auth_token.is_empty());
|
||||
// The db lands beside the config, whatever the working directory is.
|
||||
assert_eq!(Path::new(&loaded.cfg.store.path), dir.join("uo-link.db"));
|
||||
|
||||
// Second run: same token, and nothing reported as new.
|
||||
let again = Config::load(Some(path.to_str().unwrap())).unwrap();
|
||||
assert!(!again.config_created);
|
||||
assert!(!again.token_generated);
|
||||
assert_eq!(again.cfg.web.auth_token, loaded.cfg.web.auth_token);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_creates_the_config_directory() {
|
||||
if env_overrides_present() {
|
||||
return;
|
||||
}
|
||||
// An installer pointing at a fresh /etc/runicgateway should not have to mkdir first.
|
||||
let dir = scratch("mkdir").join("nested").join("deeper");
|
||||
let path = dir.join("sidecar.toml");
|
||||
|
||||
let loaded = Config::load(Some(path.to_str().unwrap())).unwrap();
|
||||
|
||||
assert!(path.exists(), "{}", path.display());
|
||||
assert!(loaded.config_created);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Terminates the loopback link to the ServUO shard and exposes a website-facing HTTP surface. So
|
||||
//! far: the shard link (bidirectional) and a WebSocket live feed. REST queries and SQLite come next.
|
||||
|
||||
mod cli;
|
||||
mod config;
|
||||
mod rpc;
|
||||
mod shard;
|
||||
@@ -33,13 +34,48 @@ pub const PROTOCOL_VERSION: u32 = 3;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let args = match cli::parse(std::env::args().skip(1)) {
|
||||
Ok(args) => args,
|
||||
Err(msg) => {
|
||||
eprintln!("uo-link-sidecar: {msg}\n\n{}", cli::USAGE);
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
|
||||
match args.mode {
|
||||
cli::Mode::Help => {
|
||||
print!("{}", cli::USAGE);
|
||||
return Ok(());
|
||||
}
|
||||
cli::Mode::Version => {
|
||||
println!(
|
||||
"uo-link-sidecar {} (protocol {})",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
PROTOCOL_VERSION
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
// Tracing stays uninitialized here on purpose: the subscriber writes to stdout, and stdout
|
||||
// is the document. Config::load's messages are dropped rather than interleaved into JSON
|
||||
// an installer is about to parse — everything they would have said is in the document.
|
||||
cli::Mode::PrintConfig => {
|
||||
let loaded = config::Config::load(args.config.as_deref())?;
|
||||
println!("{:#}", config::describe(&loaded));
|
||||
return Ok(());
|
||||
}
|
||||
cli::Mode::Run => {}
|
||||
}
|
||||
|
||||
init_tracing();
|
||||
info!("uo-link sidecar starting");
|
||||
|
||||
let cfg = config::Config::load()?;
|
||||
let loaded = config::Config::load(args.config.as_deref())?;
|
||||
let cfg = loaded.cfg;
|
||||
info!(
|
||||
config = %loaded.path.display(),
|
||||
shard = %cfg.shard.bind,
|
||||
web = %cfg.web.bind,
|
||||
db = %cfg.store.path,
|
||||
auth = cfg.auth_required(),
|
||||
"configuration loaded"
|
||||
);
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! instead of round-tripping the shard. Links and profiles are written from the REST reply paths
|
||||
//! (`link.ok`, `char.profile`), which are RPC replies and never hit the broadcast stream.
|
||||
|
||||
use std::str::FromStr;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::Value;
|
||||
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
|
||||
@@ -20,9 +20,24 @@ pub struct Store {
|
||||
|
||||
impl Store {
|
||||
/// Opens (creating if absent) the SQLite database and ensures the schema exists.
|
||||
///
|
||||
/// `path` is a filesystem path, handed to sqlx as one. It is deliberately **not** formatted
|
||||
/// into a `sqlite://` URL first: that spelling is parsed as a URL, so it percent-decodes the
|
||||
/// path and splits it on `?`. Under an installed layout the path is absolute and chosen by the
|
||||
/// operator — `C:\ProgramData\RunicGateway\uo-link.db`, or something under a home directory
|
||||
/// with a `%` or `#` in it — and a URL round-trip silently opens a *different* file.
|
||||
pub async fn open(path: &str) -> anyhow::Result<Self> {
|
||||
let opts =
|
||||
SqliteConnectOptions::from_str(&format!("sqlite://{path}"))?.create_if_missing(true);
|
||||
// A service unit can name a data directory that does not exist yet; creating it here means
|
||||
// one less way for a fresh install to fail on first start.
|
||||
if let Some(dir) = Path::new(path).parent() {
|
||||
if !dir.as_os_str().is_empty() && !dir.exists() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
}
|
||||
|
||||
let opts = SqliteConnectOptions::new()
|
||||
.filename(path)
|
||||
.create_if_missing(true);
|
||||
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(4)
|
||||
|
||||
@@ -43,10 +43,14 @@ pub struct AppState {
|
||||
pub last_event: Arc<AtomicI64>,
|
||||
}
|
||||
|
||||
/// Path of the live-feed WebSocket. Named because `--print-config` reports it: an installer builds
|
||||
/// the website's WS URL from `web.bind` plus this, and neither side should be hardcoding it twice.
|
||||
pub const WS_PATH: &str = "/ws";
|
||||
|
||||
pub async fn serve(addr: &str, state: AppState) -> anyhow::Result<()> {
|
||||
// Everything except /health is behind the auth check.
|
||||
let protected = Router::new()
|
||||
.route("/ws", get(ws_upgrade))
|
||||
.route(WS_PATH, get(ws_upgrade))
|
||||
// Queries (shard reply correlated by reqId).
|
||||
.route("/char/:account/:slot", get(char_by_slot))
|
||||
.route("/char/serial/:serial", get(char_by_serial))
|
||||
|
||||
Reference in New Issue
Block a user