diff options
author | Tor Andersson <tor@ccxvii.net> | 2025-04-24 12:48:51 +0200 |
---|---|---|
committer | Tor Andersson <tor@ccxvii.net> | 2025-04-25 16:06:05 +0200 |
commit | ed2361980b455d1825d811670f329cbcf5624927 (patch) | |
tree | a1e620490bf305635c3a0f22a6f695e22c14ff2f | |
parent | 71a98cbbe0657880cfb1d81962786188b009fc5c (diff) | |
download | server-ed2361980b455d1825d811670f329cbcf5624927.tar.gz |
Move docs to Markdown and use markdown renderer in server.
-rw-r--r-- | docs/TODO (renamed from public/docs/TODO) | 0 | ||||
-rw-r--r-- | docs/index.md | 36 | ||||
-rw-r--r-- | docs/module/fuzzer.md | 58 | ||||
-rw-r--r-- | docs/module/guide.md | 45 | ||||
-rw-r--r-- | docs/module/library.md | 123 | ||||
-rw-r--r-- | docs/module/rules.md | 420 | ||||
-rw-r--r-- | docs/module/script.md | 155 | ||||
-rw-r--r-- | docs/overview/architecture.md | 58 | ||||
-rw-r--r-- | docs/overview/database.md | 175 | ||||
-rw-r--r-- | docs/overview/module.md (renamed from public/docs/module.html) | 356 | ||||
-rw-r--r-- | docs/server/install.md | 46 | ||||
-rw-r--r-- | docs/server/production.md | 103 | ||||
-rw-r--r-- | docs/tips.md (renamed from public/docs/tips.html) | 102 | ||||
-rw-r--r-- | docs/tournaments.md (renamed from public/docs/tournaments.html) | 54 | ||||
-rw-r--r-- | package.json | 1 | ||||
-rw-r--r-- | public/docs/architecture.html | 104 | ||||
-rw-r--r-- | public/docs/database.html | 207 | ||||
-rw-r--r-- | public/docs/index.html | 51 | ||||
-rw-r--r-- | public/docs/install.html | 84 | ||||
-rw-r--r-- | public/docs/production.html | 144 | ||||
-rw-r--r-- | public/docs/style.css | 19 | ||||
-rw-r--r-- | server.js | 38 | ||||
-rw-r--r-- | views/about.pug | 4 |
23 files changed, 1493 insertions, 890 deletions
diff --git a/public/docs/TODO b/docs/TODO index 3861872..3861872 100644 --- a/public/docs/TODO +++ b/docs/TODO diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..96c9a7b --- /dev/null +++ b/docs/index.md @@ -0,0 +1,36 @@ +# Documentation + +This is the documentation for the _Rally the Troops_ software and website. +Here you will find information both about how to configure and run your own +server instance and how to create new modules. + +## For players + +* [Tips & Tricks](/docs/tips) +* [Tournaments](/docs/tournaments) + +## For developers + +* [Installing the server](/docs/server/install) +* [Running a public server](/docs/server/production) + +## System overview + +* [Server architecture](/docs/overview/architecture) +* [Database schema](/docs/overview/database) +* [Module architecture](/docs/overview/module) + +## Module implementation + +* [Step by step guide](/docs/module/guide) +* [Rules framework](/docs/module/rules) + * [Script syntax](/docs/module/script) + * [Utility library](/docs/module/library) +* Create the user interface (todo) +* Prepare the art assets (todo) +* [Test with the Fuzzer](/docs/module/fuzzer) + +<!-- +* [Preparing the art assets](/docs/module/assets) +* [How to write the client](/docs/module/play) +--> diff --git a/docs/module/fuzzer.md b/docs/module/fuzzer.md new file mode 100644 index 0000000..d69b992 --- /dev/null +++ b/docs/module/fuzzer.md @@ -0,0 +1,58 @@ +# Fuzzing the Troops! + +We use [Jazzer.js](https://github.com/CodeIntelligenceTesting/jazzer.js/) +as a coverage-guided fuzzer for automatic testing of module rules. + +## What is fuzzing? + +Fuzzing or fuzz testing is an automated software testing technique that +involves providing invalid, unexpected, or random data as inputs to a computer +program. With the fuzzer you can test the rules for any RTT module. It will +play random moves and check for unexpected errors. + +The fuzzer can detect the following types of errors: + +* Any crashes in the rules.js module. +* Dead-end game states where no other actions are available (besides "undo"). +* A game taking an excessive number of steps. This could indicate infinite loops and other logical flaws in the rules. + +Work files are written to the "fuzzer" directory. + +## Running + +Start the fuzzer: + + bash tools/fuzz.sh title [ jazzer options... ] + +This will run jazzer until you stop it or it has found too many errors. + +To keep an eye on the crashes, you can watch the fuzzer/log-title.txt file: + + tail -f fuzzer/log-title.txt + +Each fuzzed title gets its own "fuzzer/corpus-title" sub-directory. +The corpus helps the fuzzer find interesting game states in future runs. + +To create a code coverage report pass the `--cov` option to fuzz.sh. + +## Debug + +When the fuzzer finds a crash, it saves the game state and replay log to a JSON file. +You can import the crashed game state like so: + + node tools/import-game.js fuzzer/dump-title-*.json + +The imported games don't have snapshots. You can recreate them with the patch-game tool. + + node tools/patch-game.js game_id + +## Avoidance + +If your rules have actions or rules you don't want to test, guard the code +or action generation by checking if globalThis.RTT_FUZZER is true. + + if (globalThis.RTT_FUZZER) { + // this code only runs in the fuzzer! + } else { + // this code never runs in the fuzzer! + } diff --git a/docs/module/guide.md b/docs/module/guide.md new file mode 100644 index 0000000..ada195f --- /dev/null +++ b/docs/module/guide.md @@ -0,0 +1,45 @@ +# Module Implementation Guide + +## 0. Secure the rights. + +All games on RTT are published with the right holders written express permission. +It's better to secure the rights before spending a lot of time on an implementation, +in case the publisher says no. +If you have a game in mind that you want to host on RTT, approach Tor to talk +about whether a license may be available. + +## 1. Create a git project. + +TODO + +## 2. Setup the required files. + +TODO + +## 3. Import and prepare the art assets. + +Ask Tor to do this for you! + +## 4. Board representation. + +Design the data representation for the game board state. + +Implement enough of the rules to create and setup the initial board game state. + +Implement enough of the client to display the initial board game state. + +The client doesn't need to be fancy, all we need at this point is to be able to +present the spaces and pieces at their approximate locations to be able to interact with them. +Fine tuning the look & feel comes much later. + +## 5. Implement the sequence of play and core rules. + +Data representation accessors and helper functions. + +Main sequence of play. + +## 6. Implement events and special cases. + +All the hard work. + +## 7. Profit! diff --git a/docs/module/library.md b/docs/module/library.md new file mode 100644 index 0000000..134fae8 --- /dev/null +++ b/docs/module/library.md @@ -0,0 +1,123 @@ +# Utility Library + +The common framework.js file defines many useful functions. + +Some of these are optimized versions of common Javascript functions, +that are simpler and faster because they do less. + +For example array_delete is much faster than Array.splice() because all it does +is remove an item from the array. Splice also creates a new array with the deleted items +and returns it; and since we usually don't need that it's better to use the simpler function +defined here. + +Likewise, array_delete_item is faster than using array.filter. + +## Object functions + + function object_copy(original) + Make a deep copy of an object without cycles. + + +## Array functions + + function array_delete(array, index) + Delete the item at index. + + function array_delete_item(array, item) + Find and delete the first instance of the item. + + function array_insert(array, index, item) + Insert item at the index. + + function array_delete_pair(array, index) + Delete two items at the index. + + function array_insert_pair(array, index, a, b) + Insert two items a and b at the index. + +## Set functions + +Sets can be represented as a sorted array. +To use an array as a set this way, we provide these functions. + + function set_clear(set) + Delete every entry in the set. + + function set_has(set, item) + Check if item exists in the set. + + function set_add(set, item) + Add an item to the set (if it doesn't alerady exist). + + function set_delete(set, item) + Delete an item from the set (if it exists). + + function set_toggle(set, item) + Toggle the presence of an item in the set. + +## Map functions + +Maps (or key/value dictionaries) can also be represented as an array of pairs +sorted on the key value. + + function map_clear(map) + Delete every entry in the map. + + function map_has(map, key) + Check if the map has a value associated with the key. + + function map_get(map, key, missing) + Return the value associated with key; + or missing if the key is not present. + + function map_set(map, key, value) + Set the value for the key. + + function map_delete(map, key) + Delete an entry. + + function map_for_each(map, fun) + Iterate over each entry calling fun(key, value) + +## Group By + +The Object.groupBy function in standard Javascript is implemented here for both +Objects and our "arrays as map" representation. + + function object_group_by(items, callback) + function map_group_by(items, callback) + +## Game functions + +These functions affect the game state. + + function log(s) + +View functions: + + function prompt(s) + function button(action, enabled = true) + function action(action, argument) + +State transitions: + + function call_or_goto(pred, name, env) + function call(name, env) + function goto(name, env) + function end(result) + +Ending a game: + + function finish(result, message) + +## Undo stack handling + + function clear_undo() + function push_undo() + function pop_undo() + +## Random number generator + + function random(range) + function shuffle(list) + diff --git a/docs/module/rules.md b/docs/module/rules.md new file mode 100644 index 0000000..a2135f1 --- /dev/null +++ b/docs/module/rules.md @@ -0,0 +1,420 @@ +# Rules Framework + +The rules.js file contains the logic of the game! + +This is exposed to the system via a handful of exported properties and functions. + +All of the board state is represented as a plain JS object that is passed to +and returned from these functions. + +See the [module overview](/docs/overview/module) for the details. + +## Copy & Paste + +In order to simplify rules creation, there is a shared library of code that +does some of the work and provides a structured approach to handling control +flow through the game. + +A copy of this code can be found in the server repository in +[public/common/framework.js](https://git.rally-the-troops.com/common/server/tree/public/common/framework.js) + +This framework.js file provides implementations of all of the necessary exports, +a game state management system, random number generator, undo handling, and +several other useful functions. + +Include a copy of this file at the end of rules.js to get started! + +> Note: We can't "require" it as a module because it needs access to the rules.js specific scope; +> so unfortunately you'll just have to include a copy of it. + +## Prolog + +The framework uses several global variables that must be defined near the top of the file. + + + var G, L, R, V + +You also need to define the states and procedures tables. + + const S = {} + const P = {} + +The rules need a list of player roles. The index of each role in the array determines their numeric value. + + const ROLES = [ "White", "Black" ] + + // mnemonics for use in the rules + const R_WHITE = 0 + const R_BLACK = 1 + +If there are multiple scenarios, define them in a list: + + const SCENARIOS = [ + "Wars of the Roses", + "Kingmaker", + "Richard III", + ] + +## Globals + +The framework uses four main global variables. + +### R - who are you? + +Whenever the system executes code to handle user actions or populate the user +view object, the R global is set to the index of the corresponding user. You +should rarely need to use this outside of on_view, but when multiple users are +active simultaneously, use R to distinguish between them in the action handlers. + +### G - the (global) game state + +This object contains the full representation of the game. +There are several properties here that are special! + + G.L // local scope (aliased as L below) + G.seed // random number generator state + G.log // game log text + G.undo // undo stack + G.active // currently active role (or roles) + +Add to G any data you need to represent the game board state. + +The G.L, G.seed, G.log, and G.undo properties are automatically managed; you should never need to touch these. + +The G.active is used to indicate whose turn it is to take an action. +It can be set to a single role index, or an array of multiple roles. + + G.active = R_WHITE + G.active = [ R_WHITE, R_BLACK ] + +### L - the (local) game state + +There is a local scope for storing data that is only used by a particular state. +This local scope has reserved properties ("P", "I", and "L") that you must not touch! +These properties are used to track the execution of scripts and where to go next. + +### V - the view object + +The view object that is being generated for the client is held in V during +the execution of the on_view hook and the state prompt functions (see below). + +## Setup + +You must provide the on_setup function to setup the game with the initial board state. + +At the end of the function you must transition to the first game state by invoking call. + + function on_setup(scenario, options) { + G.active = R_WHITE + G.pieces = [ ... ] + call("main") + } + +## View + +The client needs a view object to display the game state. We can't send the +full game object to the client, because that would reveal information that +should be hidden to some or all players. Use the on_view function to populate +the V object with the data that should be presented to the player. + +Use the R object to distinguish who the function is being called for. + + function on_view() { + V.pieces = G.pieces + if (R === R_BRITAIN) + V.hand = G.hand[R_BRITAIN] + if (R === R_FRANCE) + V.hand = G.hand[R_FRANCE] + } + +## The Flow Chart + +--- + +Consider the rules logic as a state machine, or a flow chart. + +At each "box" it pauses and waits for the active player to take an action. Once +an action is taken, the game proceeds along the action "arrow", changing what +needs to be changed (like moving a piece) along the way, before stopping at the +next "box". + +These "boxes" are game states, and the "arrows" are transitions between states. + +In simple games that's all there is to it, but in more complicated games you +sometimes want to share logic at different points in the sequence of play (like +common handling of taking casualties whether it's from a battle or winter +attrition). + +In order to support this, we can recursively "nest" the states. + +--- + +The game is defined by a mix of states, scripts, and functions. + +The basic game flow consists of a set of "procedures" which are +interrupted by "states" that prompt the players to perform actions. + +The game stops at states, prompting the user for input. +When an action is chosen, the transition to another state can happen +in a few different ways: + +End the current state and go back to the previous state or procedure that called this one. + +Call another state or procedure. + +Goto another state or procedure (combination of calling and ending). + +The game holds a stack of states (and their environments). +Each state and procedure runs in its own scope (accessed via the L namespace). +There's also a global scope for the main game data (via the G namespace). + +--- + +## States + +The "states" where we wait for user input are kept in the S table. + +Each state is an object that provides several functions. + + S.place_piece = { + prompt() { + prompt("Select a piece to move.") + for (var s = 0; s < 64; ++s) + if (G.board[s] === 0) + action("space", s) + button("pass") + }, + space(s) { + log("Placed piece at " + s) + G.board[s] = 1 + end() + }, + pass() { + log("Passed") + end() + }, + } + +### S.state.prompt() + +The prompt function is called for each active player to generate a list of +valid actions. + +To show a text prompt to the user: + + prompt("Do something!") + +To generate a valid action use one of the following functions: + + function action(name, value) + +To generate a push button action: + + function button(name) + function button(name, enabled) + +To show an enabled/disabled push button, use a boolean in the second argument: + + button("pass", can_player_pass()) + +It's sometimes helpful to define simple wrapper functions to save on typing and +reduce the risk of introducing typos. + + function action_space(s) { + action("space", s) + } + +> Note: The on_view function should NEVER change any game state! + +### S.state.action() + +When a player chooses a valid action, the function with the action name is +invoked! + +Use the action handler function to perform the necessary changes to the game +state, and transition to the next state using one of the state transition +functions "call", "goto", or "end". + +To add entries to the game log: + + log(ROLES[R] + " did something!") + +Calling log with no arguments inserts a blank line: + + log() + +### S.state._begin() and _resume() and _end() + +These functions are invoked when the state is first entered, when control returns +to the state (from a nested state), and when the state is departed. + +You can use this to do some house-keeping or initialize the L scope. + + S.state.remove_3_pieces = { + _begin() { + L.count = 3 + }, + prompt() { + ... + }, + piece(p) { + remove_piece(p) + if (--L.count === 0) + end() + } + } + + +## State transitions + +When transitioning to another state in an action handler, it must be the last thing you do! + +> You cannot sequence multiple invocations to "call" in a normal function! + +See "procedures" below for a way to string together multiple states. + +### call - enter another state + +To recursively go to another state, use the call() function. + +This will transfer control to the named state or procedure, and once that has +finished, control will come back to the current state. + +The second argument (if present) can be an object with the initial scope. +The L scope for the new state is initialized with this data. + + call("remove_pieces", { count: 3 }) + +### end - return from whence we came + +Calling end() will return control to the calling state/procedure. + +If you pass an argument to end, that will be available to the caller as `L.$`. + +### goto - exit this state to go to the next + +The goto() function is like call() and end() combined. We exit the current state and jump to the next. +Use this to transition to another state when you don't need to return to the current state afterwards. + +## Procedures + +Sometimes state transitions can become complicated. + +In order to make the code to deal with them easier, you can define procedures in the "P" table, + +Procedures defined by the "script" function are executed by the framework. +They can sequence together states and other procedures. + +Calling a state will enter that state, and execution of the caller will resume +where it left off when the called state ends. You can also recursively call other procedures. + + P.hammer_of_the_scots = script (` + for G.year in 1 to 7 { + call deal_cards + for G.round in 1 to 5 { + set G.active [ R_ENGLAND, R_SCOTLAND ] + call choose_cards + call reveal_cards + set G.active G.p1 + call movement_phase + set G.active G.p2 + call movement_phase + set G.active G.p1 + call combat_phase + } + call winter_phase + } + `) + +See [script syntax](script) for the commands available in this simple scripting language. + +### Plain function procedures + +Procedures can also be plain Javascript functions! There is normally no reason +to use a plain procedure over simply calling a function, but if you want them +to be part of a larger script sequence this can make it easier. + +Note that a plain function procedure must transition somewhere else before it +returns, either via "goto" or "end". + +It's also a neat way to define events; to dispatch based on a string. + + S.strategy_phase = { + ... + play_event(c) { + goto(data.events[c].event) + }, + } + + P.the_war_ends_in_1781 = function () { + G.war_ends = 1781 + end() + } + + P.major_campaign = script (` + call activate_general + call activate_general + call activate_general + `) + + +## Ending the game + +To signal the termination of a game, call the finish function. + + function finish(result, message) + +The result must be either the index of the role that won, the string "Draw", +or any other string to indicate that nobody won. + +The message will both be logged and used as the text prompt. + + finish(R_WHITE, "White has won!") + finish("Draw", "It's a tie!") + finish("None", "Nobody won.") + +Calling finish will abort the current scripts and/or states. + +## Random number generator + +There is a pseudo-random number generator included in the framework. + +> Do NOT use Math.random! + +Games must be reproducible for the replay and debugging to work, so +the system initializes the PRNG with a random seed on setup. The random +number generator state is stored in G.seed. + +To generate a new random number between 0 and range: + + function random(range) + +To shuffle an array (for example a deck of cards): + + function shuffle(list) + +## Undo + +Undo is handled by taking snapshots of the game state. Generating the undo +action and handling it is taken care of by the framework. You only need to +create and clear the checkpoints at suitable times. + +Call push_undo at the top of each action you want to be able to undo. + +Don't forget to call clear_undo whenever hidden information is revealed or any +random number is generated. + + function roll_die() { + clear_undo() + return random(6) + 1 + } + +Whenever the active player changes, the undo stack is automatically cleared. + +## Miscellaneous utility functions + +The framework also includes a library of useful functions to work +with sorted sets, maps, etc. + +See the [utility library](library) for how to use these. + diff --git a/docs/module/script.md b/docs/module/script.md new file mode 100644 index 0000000..52d1eb5 --- /dev/null +++ b/docs/module/script.md @@ -0,0 +1,155 @@ +# Script Syntax + +The script function compiles a simple scripting language to a list of +instructions that are executed by the framework. +The argument to the script function is a plain text string, +so use multiline backtick string quotes. + +The script language syntax is very similar to Tcl and is based on space +separated list of "words". + +A word can be any sequential string of non-whitespace characters. +Words can also be "quoted", ( parenthesized ), { bracketed } or [ braced ]. +Any whitespace characters (including line breaks) are permitted within these quoted strings. +Parenthesises, brackets, and braces must be balanced! + +Each line of words is parsed as a command. +The first word defines a command, and the remaining words are arguments to that command. + +Control flow commands can take "blocks" as arguments. These words are parsed +recursively to form further lists of commands. + +Some commands take "expressions" as arguments. +These words are included verbatim as Javascript snippets. + +## Eval + +To run any snippet of Javascript, you can include it verbatim with the eval command. + + eval <expr> + +Example: + + eval { + do_stuff() + } + +## Variables + +The set, incr, and decr commands set, increment, and decrement a variable. +This can be done with the eval command, but using these commands is shorter. + + set <lhs> <expr> + incr <lhs> + decr <lhs> + +Example: + + set G.active P_ROME + set G.active (1 - G.active) + incr G.turn + decr L.count + +## Log + +A shorter way to print a log message to the game log: + + log <expr> + + log "Hello, world!" + +## State transitions + +Use call to invoke another state or procedure (with an optional environment scope). + + call <name> <env> + call <name> + +Use goto to jump to another state or procedure without coming back (a tail call). + + goto <name> <env> + goto <name> + +Use return to exit the current procedure. +This is equivalent to the end function used in states and function procedures. + + return <expr> + return + +Examples: + + call movement { mp: 4 } + goto combat_phase + return L.who + + +## Loops + +Loops come in three flavors: + + while <expr> <block> + for <lhs> in <expr> <block> + for <lhs> in <expr> to <expr> <block> + +A while loop has full control: + + set G.turn 1 + while (G.turn <= 3) { + call turn + incr G.turn + } + +Iterating over a range with for is easiest: + + for G.turn in 1 to 3 { + call turn + } + +Note that the list expression in a for statement is re-evaluated each iteration! + + for G.turn in [1, 2, 3] { + call turn + } + +## Branches + +The if-else command is used for branching code. + + if <expr> <block> else <block> + if <expr> <block> + +Example: + + if (G.month < 12) { + call normal_turn + } else { + call winter_turn + } + +## Return + +Use return (or the end() function in states and function procedures) to +pass information up the call chain. + + S.greeting = { + prompt() { + button("hello") + button("goodbye") + }, + hello() { + end("hello") + }, + goodbye() { + end("goodbye") + }, + } + + P.example = script (` + call greeting + if (L.$ === "hello") { + goto hello_world + } + if (L.$ === "goodbye") { + goto goodbye_cruel_world + } + `) diff --git a/docs/overview/architecture.md b/docs/overview/architecture.md new file mode 100644 index 0000000..6413386 --- /dev/null +++ b/docs/overview/architecture.md @@ -0,0 +1,58 @@ +# Architecture Overview + +The basic architecture of Rally the Troops is a single server process storing all data in an sqlite database. +This server handles both HTTP requests for the "meta-site" and websocket requests for the rules when playing a game. + +## Meta-site + +The meta-site consists of all the web pages showing the login, signup, active game lists, the create a game page, forum, etc. +These pages are all created using PUG templates in the "view" directory. +The "join" page is the most complicated, and also uses javascript and server sent events for live updates. + +## Database + +See the [database overview](/docs/overview/database) for a brief introduction to the tables involved. + +## Client/Server + +When playing a game, the browser (client) connects to the server with a web socket. +The query string indicates which game and role to connect to. + +The game state is stored in a JSON object. A redacted version of this game state is sent to the clients, which then update the game display in real time. +One part of the view object is a list of possible actions a player can take. +When a player clicks on a possible action, a message is sent to the server with this action. +The server then processes the action, updates the game state, and sends out a new view object to all the clients that are connected to the game. + +The client code for connecting to the server, sending actions, and managing the player list, game log, chat, and notes is shared between all modules. +The following files contain the code and styling for the client display: + +* <a href="https://git.rally-the-troops.com/common/server/tree/public/fonts/fonts.css">public/fonts/fonts.css</a> +* <a href="https://git.rally-the-troops.com/common/server/tree/public/common/client.css">public/common/client.css</a> +* <a href="https://git.rally-the-troops.com/common/server/tree/public/common/client.js">public/common/client.js</a> + +## Tools + +The "tools" directory holds a number of other useful scripts for administrating the server and debugging modules. + + bash tools/export-game.sh game_id > file.json + Export full game state to a JSON file. + + node tools/import-game.js file.json + Import a game from an export JSON file. + + node tools/patchgame.js game_id + Patch game state for one game (by replaying the action log). + + node tools/patchgame.js title_id + Patch game state for all active games of one module. + + bash tools/undo.sh game_id + Undo an action by removing the last entry in the replay log and running patchgame.js + + bash tools/showgame.sh game_id + Print game state JSON object for debugging. + +<!-- + bash tools/gencovers.sh + Generate cover images and thumbnails. Requires imagemagick. +--> diff --git a/docs/overview/database.md b/docs/overview/database.md new file mode 100644 index 0000000..db96df1 --- /dev/null +++ b/docs/overview/database.md @@ -0,0 +1,175 @@ +# Database Overview + +The database uses the following schemas, somewhat simplified and redacted to highlight the important bits. + +## Users + +The user table is pretty simple, it just holds the user name and e-mail. + + create table users ( + user_id integer primary key, + name text unique collate nocase, + mail text unique collate nocase + ); + +Passwords are hashed and salted with SHA-256. + + create table user_password ( + user_id integer primary key, + password text, + salt text + ); + +The login session cookie is a 48-bit random number. + + create table logins ( + sid integer primary key, + user_id integer, + expires real -- julianday + ); + +Webhook notification settings are kept in the webhooks table. +The error column keeps any error message such as timeouts or HTTP failure statuses. +It is null if the hook is operational. + + create table webhooks ( + user_id integer primary key, + url text, + format text, + prefix text, + error text + ); + +The contact list keeps track of friends (positive relation) and blacklisted users (negative relation). + + create table contacts ( + me integer, + you integer, + relation integer, + primary key (me, you) + ); + + +## Modules + +The game modules to load are registered in the titles table. The title_id must match the directory name for the module. + + create table titles ( + title_id text primary key, + title_name text, + bgg integer, + is_symmetric boolean + ); + +## Games + +Each game session uses a handful of tables. +The main table holds the status (open/active/finished), setup information (scenario, options), whose turn it is (active), and the final result. + + create table games ( + game_id integer primary key, + status integer, + + title_id text, + scenario text, + options text, + + player_count integer, + join_count integer, + invite_count integer, + user_count integer, + + owner_id integer, + notice text, + pace integer, + is_private boolean, + is_random boolean, + is_match boolean, + + ctime datetime, + mtime datetime, + moves integer, + active text, + result text, + + is_opposed boolean generated as ( user_count = join_count and join_count > 1 ), + is_ready boolean generated as ( player_count = join_count and invite_count = 0 ) + ); + +The players table connects users to the games they play. + + create table players ( + game_id integer, + role text, + user_id integer, + is_invite integer, + is_active boolean, + primary key (game_id, role) + ); + +The game state is represented by a JSON blob. + + create table game_state ( + game_id integer primary key, + state text + ); + +Each action taken in stored in the game_replay log. This is primarily used for +the detailed "Sherlock" replay view, but is also used to patch running games when +fixing bugs. + + create table game_replay ( + game_id integer, + replay_id integer, + role text, + action text, + arguments json, + primary key (game_id, replay_id) + ); + +Whenever who is active changes, we take a snapshot of the game state +so we can provide the coarse turn-by-turn rewind view that is available when +playing. This table is also used when rewinding games. The replay_id syncs each +snapshot with the corresponding action in the game_replay table. + + create table game_snap ( + game_id integer, + snap_id integer, + replay_id integer, + state text, + primary key (game_id, snap_id) + ); + +Game chat is kept in another table, and there's also a table to track whether a +user has any unread in-game chat messages, and one table to track finished but not yet +seen games. + + create table game_chat ( + game_id integer, + chat_id integer, + user_id integer, + time datetime, + message text, + primary key (game_id, chat_id) + ); + + create table unread_chats ( + user_id integer, + game_id integer, + primary key (user_id, game_id) + ); + + create table unseen_games ( + user_id integer, + game_id integer, + primary key (user_id, game_id) + ); + +## Other tables + +There are several other tables to deal with tournaments, password reset tokens, email +notifications, messages, and the forum. + +See the full +[schema.sql](https://git.rally-the-troops.com/common/server/tree/schema.sql) +for more details on these. diff --git a/public/docs/module.html b/docs/overview/module.md index a3a4483..2a12461 100644 --- a/public/docs/module.html +++ b/docs/overview/module.md @@ -1,189 +1,164 @@ -<!doctype html> -<meta name="viewport" content="width=device-width"> -<title>Module Overview</title> -<link rel="stylesheet" href="style.css"> -<body> -<article> - -<h1> -Module Overview -</h1> - -<p> +# Module Overview + A module consists of a directory containing certain mandatory files which are loaded by the server. All the other resources needed for a module are also put in this directory. Note that all of the files in the module will be available on the web. -<p> The module must be put in the server "public" directory, matching the name of title_id. If our example game has the title "My Example Module" and a title_id of "example", the module directory should be "public/example/". -<h2> -Metadata -</h2> +## Two halves make one + +A module consists of two separate parts: + +1. The rules work with actions and their consequences. +2. The client present the game and possible actions to the players. + +The rules run on the server. The client runs in the player's browser. +The rules create a view object that is passed to the client, containing the visible game state +and a list of possible actions. The client presents this to the players, and sends the chosen +actions back to the rules for execution. + + +## Metadata -<p> Each module needs to be registered in the database so that the system can find it. -To do this we usually create a title.sql file that you will run to register the module. +To do this we create a title.sql file that we source to register the module. -<pre> -insert or replace into titles - ( title_id, title_name, bgg ) -values - ( 'example', 'Example', 123 ) -; -</pre> + insert or replace into titles + ( title_id, title_name, bgg ) + values + ( 'example', 'Example', 123 ) + ; -<p> The bgg column should have the <a href="httsp://www.boardgamegeek.com/">boardgamegeek.com</a> game id. -<p> After creating this file, source it into the database and restart the server program. -<pre> -$ sqlite3 db < public/example/title.sql -</pre> + $ sqlite3 db < public/example/title.sql -<h2> -Cover image -</h2> +## Cover image -<p> Each game needs a cover image! Create a file containing the high resolution cover image named cover.png or cover.jpg. After you have created or modified the cover image, run the following script to generate the small cover images and thumbnails that the site uses. -<pre> -$ bash tools/gencovers.sh -</pre> + $ bash tools/gencovers.sh -<p> <i>This script requires ImageMagick (convert), netpbm (pngtopnm), and libjpeg (cjpeg) tools to be installed.</i> -<h2> -About text -</h2> +## About text -<p> The game landing page on the server has a bit of text introducing the game, and links to rules and other reference material. -<p>Put the about text in the about.html file. +Put the about text in the about.html file. -<xmp> -<p> -Dolorum fugiat dolor temporibus. Debitis ea non illo sed -debitis cupiditate ipsum illo. Eos eos molestias illo -quisquam dicta. + <p> + Dolorum fugiat dolor temporibus. Debitis ea non illo sed + debitis cupiditate ipsum illo. Eos eos molestias illo + quisquam dicta. -<ul> -<li> <a href="info/rules.html">Rules</a> -</ul> -</xmp> + <ul> + <li> <a href="info/rules.html">Rules</a> + </ul> -<h2> -Create game options -</h2> +## Options -<p> When creating a game, the scenarios and common options are handled by the system. However, if your game uses custom options these need to be added as form fields. -<p> Add a create.html file to inject form fields into the create game page. -<xmp> -<p> -Player count: -<br> -<select name="players"> - <option value="2">2 Player</option> - <option value="3">3 Player</option> - <option value="4">4 Player</option> -</select> - -<p> -<label> - <input type="checkbox" value="true" name="house_rule"> - House rule -</label> -</xmp> - -<p> + <p> + Player count: + <br> + <select name="players"> + <option value="2">2 Player</option> + <option value="3">3 Player</option> + <option value="4">4 Player</option> + </select> + + <p> + <label> + <input type="checkbox" value="true" name="house_rule"> + House rule + </label> + This file may be empty if your game doesn't have any custom options. -<h2> -Client HTML -</h2> +## Client HTML -<p> The game needs a play.html file using the following template: -<xmp> -<!doctype html> -<html lang="en"> -<head> - <meta name="viewport" content="width=device-width, - height=device-height, - user-scalable=no, - interactive-widget=resizes-content, - viewport-fit=cover"> - <meta name="theme-color" content="#444"> - <meta charset="UTF-8"> - <title> - GAME TITLE - </title> - <link rel="icon" href="favicon.svg"> - <link rel="stylesheet" href="/fonts/fonts.css"> - <link rel="stylesheet" href="/common/client.css"> - <script defer src="/common/client.js"></script> - <script defer src="play.js"></script> - <style> - GAME STYLES - </style> -</head> -<body> - -<header> - <div id="toolbar"> - <details> - <summary><img src="/images/cog.svg"></summary> - <menu> - <li><a href="info/rules.html" target="_blank">Rules</a> - <li class="separator"> - </menu> - </details> - </div> -</header> - -<aside> - <div id="roles"></div> - <div id="log"></div> -</aside> - -<main data-min-zoom="0.5" data-max-zoom="2.0"> - GAME AREA -</main> - -<footer id="status"></footer> - -</body> -</xmp> - -<h2> View Program </h2> - -<p> + <!doctype html> + <html lang="en"> + <head> + <meta name="viewport" content="width=device-width, + height=device-height, + user-scalable=no, + interactive-widget=resizes-content, + viewport-fit=cover"> + <meta name="theme-color" content="#444"> + <meta charset="UTF-8"> + <title> + GAME TITLE + </title> + <link rel="icon" href="favicon.svg"> + <link rel="stylesheet" href="/fonts/fonts.css"> + <link rel="stylesheet" href="/common/client.css"> + <link rel="stylesheet" href="play.css"> + <script defer src="/common/client.js"></script> + <script defer src="play.js"></script> + </head> + <body> + + <header> + <div id="toolbar"> + <details> + <summary><img src="/images/cog.svg"></summary> + <menu> + <li><a href="info/rules.html" target="_blank">Rules</a> + <li class="separator"> + </menu> + </details> + </div> + </header> + + <aside> + <div id="roles"></div> + <div id="log"></div> + </aside> + + <main data-min-zoom="0.5" data-max-zoom="2.0"> + GAME AREA + </main> + + <footer id="status"></footer> + + </body> + +## Client CSS + +Put the game specific stylesheet in play.css. + +If the stylesheet is very small you could also include it inline in play.html. + +## Client Program + As you saw above, the client page references a play.js script which should contain the code for updating the game. This script must provide a couple of functions that are called by the common client code whenever the game state changes. -<h3>The view object</h3> +### The view object -<p> -TODO +The view object is passed from the server rules module to the client! -<h3>Framework globals</h3> +It must contain both some common properties that you shouldn't touch ("log" and +"prompt" and "actions") and all the information you need to display the current +board state. + +### Client script globals -<p> These global variables are provided by the framework for use with your code. <dl> @@ -197,9 +172,8 @@ The value may change if the client is in replay mode. </dl> -<h3>Framework functions</h3> +### Client script functions -<p> These functions are provided to your client code to build the game interface and communicate with the server. <dl> @@ -228,79 +202,113 @@ is legal. </dl> -<h3>function on_update()</h3> +### function on_update() -<p> This function is called whenever the "view" object has updated. It should update the visible game representation and highlight possible actions. -<p> The client code has already updated the prompt message and log when this is called. -<p> The view.actions object contains the list of legal actions to present. -<h3>function on_log(text)</h3> +### function on_prompt(text) + +Optional function to implement custom HTML formatting of the prompt text. +If present, this function must return an HTML _string_. + +### function on_log(text) -<p> Optional function to implement custom HTML formatting of log messages. -If present, this function must return an HTML element representing the given text. +If present, this function must return an HTML _element_ representing the given text. -<h3>function on_reply(what, response)</h3> +### function on_reply(what, response) -<p> This function is invoked with the result of send_query. The what parameter matches the argument to send_query and is used to identify different queries. -<p>See rommel-in-the-desert and wilderness-war for examples of using the query mechanism. +See rommel-in-the-desert and wilderness-war for examples of using the query mechanism. + +## Rules Program -<h2> Rules Program </h2> +The rules.js script is loaded by the server. +Certain properties and functions must be provided by the rules module. -<h3> The game object </h3> +> NOTE: See the [module rules](/docs/module/rules) documentation if you want to +> use the shared rules framework that provides a structured approach to +> implementing game rules. -<p> -TODO... -<h3> exports.scenarios </h3> +### Scenarios -<p> A list of scenarios! If there are no scenarios, it should be a list with one element "Standard". -<h3> exports.roles = function (scenario, options) </h3> + exports.scenarios = [ "Standard" ] + +### Roles + +A list of roles, or a function returning a list of roles. + + exports.roles = [ "White", "Black" ] -<p> -Either a list of roles, or a function returning a list of roles. + exports.roles = function (scenario, options) { + if (scenario === "3P") + return [ "White", "Black", "Red" ] + else + return [ "White", "Black" ] + } -<h3> exports.setup = function (seed, scenario, options) </h3> +### Setup + + exports.setup = function (seed, scenario, options) { + var game = { + seed: seed, + log: [], + undo: [], + active: "White", + } + ... + return game + } -<p> Create the initial game object with a random number seed, scenario, and options object. -<p> The "setup" function takes three parameters provided by the server: the random seed (generated by the server when starting the game), the scenario (a string with the scenario name) and options (a plain javascript object with key/value pairs for the options chosen by the user when creating the game). -<p> The options object is filled in with values from the create.html form fields. -<h3> exports.view = function (game, player) </h3> +### View + + exports.view = function (game, player) { + var view = { + log: game.log, + ... + } + if (game.active === player) { + view.actions = {} + // generate list of actions + } + return view + } -<p> Given a game object, a player role, return the view object that is used by the client to display the game state. This should contain game state known to the player. -<p> -TODO: prompt +### Action -<p> -TODO: actions + exports.action = function (game, player, verb, noun) { + // handle action + return game + } -<h3> exports.action = function (game, player, verb, noun) </h3> - -<p> Perform an action taken by a player. Return a game object representing the new state. It's okay to mutate the input game object. -<h3> exports.query = function (game, player, what) </h3> +### Query + + exports.query = function (game, player, what) { + if (what === "discard") + return game.discard[player] + return null + } -<p> A custom query for information that is normally not presented. For example showing a supply line overview, or a list of cards in a discard pile. diff --git a/docs/server/install.md b/docs/server/install.md new file mode 100644 index 0000000..86359bc --- /dev/null +++ b/docs/server/install.md @@ -0,0 +1,46 @@ +# Getting Started + +The _Rally the Troops_ software is very simple and has minimal dependencies. +All the data is stored in a single SQLite3 database. +The server runs in a single Node process using the Express.js framework. + +To set up an RTT server instance, you will need +the <a href="https://www.sqlite.org/index.html">sqlite3</a> command line tool +and <a href="https://nodejs.org/en">Node</a>. + +## Install the server + +Check out the server repository. + + git clone https://git.rally-the-troops.com/common/server + +In the cloned server directory, install the NPM dependencies: + + npm install + +Initialize the database: + + sqlite3 db < schema.sql + +## Install the modules + +Game modules are found in the "public" directory. +They also need to be registered in the database. + +Check out a game module: + + git clone https://git.rally-the-troops.com/modules/field-cloth-gold \ + public/field-cloth-gold + +Register it in the database: + + sqlite3 db < public/field-cloth-gold/title.sql + +## Start the server + + node server.js + +Open the browser to http://localhost:8080/ and create an account. + +The first account created will have administrator privileges. + diff --git a/docs/server/production.md b/docs/server/production.md new file mode 100644 index 0000000..9882a5a --- /dev/null +++ b/docs/server/production.md @@ -0,0 +1,103 @@ +# Running a public server + +To let other people connect to your server and play games, there are a few other things you will need to set up. + +## Recovering from a crash + +Use <tt>nodemon</tt> to restart the server if it crashes. +This also restarts the server if the software is updated. + + nodemon server.js + +## Database & Backups + +For best performance, you should turn on WAL mode on the database. + + sqlite3 db "pragma journal_mode = wal" + +You will want to backup your database periodically. This is easy to do with a single sqlite command. +Schedule the following command using cron or something similar, and make sure to copy the resulting +backup database to another machine! + + sqlite3 db "vacuum into strftime('backup-%Y%m%d-%H%M.db')" + +## Customize settings + +The server reads its settings from the .env file. + + NODE_ENV=production + + SITE_NAME=Example + SITE_URL=https://example.com + SITE_IMPRINT="This website is operated by ..." + + HTTP_HOST=localhost + HTTP_PORT=8080 + + # Enable mail notifications + MAIL_FROM=Example Notifications <notifications@example.com> + MAIL_HOST=localhost + MAIL_PORT=25 + + # Enable webhooks + WEBHOOKS=1 + + # Enable forum + FORUM=1 + +## Expose the server to the internet + +For simplicity, the server only talks plain HTTP on localhost. +To expose the server to your LAN and/or WAN, either listen to 0.0.0.0 or use a reverse proxy server such as Nginx. +To use SSL (HTTPS) you need a reverse proxy server. + +Here is an example Nginx configuration: + + server { + listen 80; + server_name example.com www.example.com; + return 301 https://$host$request_uri; + } + + server { + listen 443 ssl; + server_name example.com www.example.com; + ssl_certificate /path/to/ssl/certificate/fullchain.cer; + ssl_certificate_key /path/to/ssl/certificate/example.com.key; + root /path/to/server/public; + location / { + try_files $uri @rally; + } + location @rally { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_read_timeout 86400s; + proxy_send_timeout 86400s; + } + } + +## Archive + +Storing all the games ever played requires a lot of space. To keep the size of +the main database down, you can delete and/or archive finished games periodically. + +You can copy the game state and replay data for finished games to a separate archive database. +Below are the tools to archive (and restore) the game state data. +Run the archive and purge scripts as part of the backup cron job. + +Copy game state data of finished games into archive database. + + sqlite3 tools/archive.sql + +Delete game state data of finished games over a certain age. + + sqlite3 tools/purge.sql + +Restore archived game state. + + bash tools/unarchive.sh game_id + diff --git a/public/docs/tips.html b/docs/tips.md index 4fb7248..c0a71c7 100644 --- a/public/docs/tips.html +++ b/docs/tips.md @@ -1,126 +1,80 @@ -<!doctype html> -<meta name="viewport" content="width=device-width"> -<title>Tips & Tricks</title> -<link rel="stylesheet" href="style.css"> <style> img { height: 18px; vertical-align: -3px; } </style> -<body> -<article> -<h1> -Tips & Tricks -</h1> +# Tips & Tricks -<p> +## Shortcuts -<h2> Shortcuts </h2> - -<p> There are several ways to scroll without the scroll bars: -<ul> -<li> The <kbd>←</kbd> <kbd>↑</kbd> <kbd>↓</kbd> <kbd>→</kbd> keys. -<li> <kbd>Shift</kbd> + <kbd>mouse wheel</kbd> to scroll horizontally. -<li> Hold down the middle mouse button and drag. -<li> Two finger scrolling with the touch pad. -<li> Tap and drag using a touch screen. -</ul> +* The <kbd>←</kbd> <kbd>↑</kbd> <kbd>↓</kbd> <kbd>→</kbd> keys. +* <kbd>Shift</kbd> + <kbd>mouse wheel</kbd> to scroll horizontally. +* Hold down the middle mouse button and drag. +* Two finger scrolling with the touch pad. +* Tap and drag using a touch screen. -<p> There are also several ways to change the size of the game area: -<ul> -<li> <kbd>Control</kbd> + <kbd>+</kbd> to zoom in. -<li> <kbd>Control</kbd> + <kbd>-</kbd> to zoom out. -<li> <kbd>Control</kbd> + <kbd>0</kbd> to reset zoom. -<li> <kbd>Control</kbd> + <kbd>mouse wheel</kbd> to zoom in and out. -<li> Pinch gesture with a touchpad. -<li> Pinch gesture on a touch screen. -</ul> +* <kbd>Control</kbd> + <kbd>+</kbd> to zoom in. +* <kbd>Control</kbd> + <kbd>-</kbd> to zoom out. +* <kbd>Control</kbd> + <kbd>0</kbd> to reset zoom. +* <kbd>Control</kbd> + <kbd>mouse wheel</kbd> to zoom in and out. +* Pinch gesture with a touchpad. +* Pinch gesture on a touch screen. -<p> Hold down the <kbd>Shift</kbd> key to see more information. In some games cards and chits will be magnified when mousing over them when holding shift. Other games may reveal the reverse side of pieces. -<p> Open a separate browser tab or window for each side when playing solo. -<h2> Toolbar </h2> +## Toolbar -<p> -The <img src="/images/cog.svg"> menu has links to rules, player aids and other reference material. +The  menu has links to rules, player aids and other reference material. In some games you can also choose between alternative graphics and layout options. The resign option is also present here if available. -<p> -The <img src="/images/scroll-quill.svg"> button toggles the game log and player status displays. +The  button toggles the game log and player status displays. -<p> -The <img src="/images/magnifying-glass.svg"> button shrinks the map to fit your screen. +The  button shrinks the map to fit your screen. -<p> -The <img src="/images/chat-bubble.svg"> button lights up if you have unread chat messages. +The  button lights up if you have unread chat messages. Chat messages can only be seen by players who have joined the game. Use <kbd>Enter</kbd> and <kbd>Escape</kbd> to quickly open and close the chat box. -<p> -The <img src="/images/cycle.svg"> button appears when the game is over. +The  button appears when the game is over. Use this to quickly start a rematch with the same players, or to go to the tournament score page. -<p> -The <img src="/images/earth-africa-europe.svg"> button hides all counters and markers. +The  button hides all counters and markers. Use this if you need to check something on the map that is obscured. -</ul> -<h2> Time Control -</h2> +## Time Control -<p> For everyone's enjoyment, please respect the pace requests! If someone wants a fast game, don't join if you can only play one move per day. -<p> Each player has a clock that ticks down while it's their turn. When the clock runs out, they forfeit the game. Each time a player takes a move, they get some time back on the clock, but there's a limit to how much time you can accumulate. <dl> - <dt> No time control -<dd> -For friendly games without an enforced pace. - -<dt> -Live / Blitz (7+ moves per day) -<dd> -24h +4h/move up to 72h -<dd> - -<dt> -Fast (3+ moves per day) -<dd> -72h +12h/move up to 120h -<dd> - -<dt> -Slow -(1+ move per day) -<dd> -72h +36h/move up to 240h - +<dd> For friendly games without an enforced pace. +<dt> Live / Blitz (7+ moves per day) +<dd> 24h +4h/move up to 72h +<dt> Fast (3+ moves per day) +<dd> 72h +12h/move up to 120h +<dt> Slow (1+ move per day) +<dd> 72h +36h/move up to 240h </dl> -<p> When playing live, let your opponents know if you're going away! If you need to resume a live game another day, schedule a time when you can continue. -<p> Turn on notifications so you can take your turns promptly. If you see that your opponent is online (the dot next to their name is filled in) then stay in the game for a while and perhaps you can play live for a bit. - diff --git a/public/docs/tournaments.html b/docs/tournaments.md index e8f08f8..0db6df5 100644 --- a/public/docs/tournaments.html +++ b/docs/tournaments.md @@ -1,81 +1,57 @@ -<!doctype html> -<meta name="viewport" content="width=device-width"> -<title>Tournaments</title> -<link rel="stylesheet" href="style.css"> -<body> -<article> +# Tournaments -<h1> -Automated Tournaments -</h1> +The automated tournaments are managed by the computer. -<p> -These are the tournaments that are managed by the computer. - -<p> To play in one of these tournaments, simply register and wait. Once enough players have joined, the tournaments will kick off automatically. Make sure you've turned on notifications so you don't miss the start! -<hr> +--- -<h3>Time Control</h3> +### Time Control -<p> All tournament games use time control. -<p> + If you let a tournament game time out, you will not be allowed to join future tournaments! -<h3>Rounds</h3> +### Rounds -<p> Tournaments are round-robin, where each player meets every other player. Everyone plays each side the same number of times. There may be a few exceptions to these rules in 3+ player games at certain player counts, but the system attempts to make the pairings as fair as possible. -<p> With sequential rounds you will only play one game at a time. -<p> With concurrent rounds you will play several games simultaneously; but never the same side in more than one game at a time. -<h3>Points</h3> -<p> +### Points + Victories are worth 2 points; ties and shared victories are worth 1 point. -The -<a href="https://en.wikipedia.org/wiki/Sonneborn%E2%80%93Berger_score">Sonneborn-Berger</a> +The [Sonneborn-Berger](https://en.wikipedia.org/wiki/Sonneborn%E2%80%93Berger_score) score is used to break ties. -<h3>Levels</h3> +### Levels -<p> Some tournaments may have multiple levels. If you win a tournament at one level, you may play in the next level (once for each victory). -<hr> +--- -<h2> -Mini Cup -</h2> +## Mini Cup -<p> This is a small and fast tournament format for casual play. The mini cup starts as soon as the required number of players have entered. You can play any number of mini cups. -<p> The mini cup games use fast (3+ moves/day) time control. -<hr> +--- -<h2> -Championship -</h2> +## Championship -<p> To be done... -<hr> +--- diff --git a/package.json b/package.json index c752c02..98e6b06 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,7 @@ "bufferutil": "^4.0.8", "dotenv": "^16.4.4", "express": "^4.18.2", + "marked": "^15.0.10", "nodemailer": "^6.9.9", "pug": "^3.0.2", "utf-8-validate": "^6.0.3", diff --git a/public/docs/architecture.html b/public/docs/architecture.html deleted file mode 100644 index 4b22f8f..0000000 --- a/public/docs/architecture.html +++ /dev/null @@ -1,104 +0,0 @@ -<!doctype html> -<meta name="viewport" content="width=device-width"> -<title>Architecture Overview</title> -<link rel="stylesheet" href="style.css"> -<body> -<article> - -<h1> -Architecture Overview -</h1> - -<p> -The basic architecture of Rally the Troops is a single server process storing all data in an sqlite database. -This server handles both HTTP requests for the "meta-site" and websocket requests for the rules when playing a game. - -<h2> -Meta-site -</h2> - -<p> -The meta-site consists of all the web pages showing the login, signup, active game lists, the create a game page, forum, etc. -These pages are all created using PUG templates in the "view" directory. -The "join" page is the most complicated, and also uses javascript and server sent events for live updates. - -<h2> -Database -</h2> - -<p> -See the <a href="database.html">database overview</a> for a brief introduction to the tables involved. - -<h2> -Client/Server -</h2> - -<p> -When playing a game, the browser (client) connects to the server with a web socket. -The query string indicates which game and role to connect to. - -<p> -The game state is stored in a JSON object. A redacted version of this game state is sent to the clients, which then update the game display in real time. -One part of the view object is a list of possible actions a player can take. -When a player clicks on a possible action, a message is sent to the server with this action. -The server then processes the action, updates the game state, and sends out a new view object to all the clients that are connected to the game. - -<p> -The client code for connecting to the server, sending actions, and managing the player list, game log, chat, and notes is shared between all modules. -The following files contain the code and styling for the client display: -<ul> -<li> -<a href="https://git.rally-the-troops.com/common/server/tree/public/fonts/fonts.css">public/fonts/fonts.css</a> -<li> -<a href="https://git.rally-the-troops.com/common/server/tree/public/common/client.css">public/common/client.css</a> -<li> -<a href="https://git.rally-the-troops.com/common/server/tree/public/common/client.js">public/common/client.js</a> -</ul> - -<h2> -Tools -</h2> - -<p> -The "tools" directory holds a number of other useful scripts for administrating the server and debugging modules. - -<dl> - -<dt> -<code>bash tools/export-game.sh <i>game_id</i> > <i>file.json</i></code> -<dd> -Export full game state to a JSON file. -<dt> -<code>node tools/import-game.js [title_id=<i>title</i>] <i>file.json</i></code> -<dd> -Import a game from an export JSON file. - -<dt> -<code>node tools/patchgame.js <i>game_id</i></code> -<dd> -Patch game state for one game (by replaying the action log). - -<dt> -<code>node tools/patchgame.js <i>title_id</i></code> -<dd> -Patch game state for all active games of one module. - -<dt> -<code>bash tools/undo.sh <i>game_id</i></code> -<dd> -Undo an action by removing the last entry in the replay log and running patchgame.js - -<!-- -<dt> -<code>bash tools/gencovers.sh</code> -<dd> -Generate cover images and thumbnails. Requires imagemagick. - -<dt> -<code>bash tools/showgame.sh <i>game_id</i></code> -<dd> -Print game state JSON object. - ---> - -</dl> diff --git a/public/docs/database.html b/public/docs/database.html deleted file mode 100644 index 27ae6d9..0000000 --- a/public/docs/database.html +++ /dev/null @@ -1,207 +0,0 @@ -<!doctype html> -<meta name="viewport" content="width=device-width"> -<title>Database Overview</title> -<link rel="stylesheet" href="style.css"> -<body> -<article> - -<h1> -Database Overview -</h1> - -<p> -The database uses the following schemas, somewhat simplified and redacted to highlight the important bits. - -<h2>Users</h2> - -<p> -The user table is pretty simple, it just holds the user account information. -Passwords are hashed and salted with SHA-256. - -<pre> -create table users ( - user_id integer primary key, - name text unique collate nocase, - mail text unique collate nocase, - notify integer, -- email notifications - password text, -- hashed & salted - salt text -); -</pre> - -<p> -The login session cookie is a 48-bit random number. - -<pre> -create table logins ( - sid integer primary key, - user_id integer, - expires real -- julianday -); -</pre> - -<p> -Webhook notification settings are kept in the webhooks table. -The error column keeps any error message such as timeouts or HTTP failure statuses. -It is null if the hook is operational. - -<pre> -create table webhooks ( - user_id integer primary key, - url text, - format text, - prefix text, - error text -); -</pre> - -<p> -The contact list keeps track of friends (positive relation) and blacklisted users (negative relation). - -<pre> -create table contacts ( - me integer, - you integer, - relation integer, - primary key (me, you) -); -</pre> - - -<h2>Modules</h2> - -<p> -The game modules to load are registered in the titles table. The title_id must match the directory name for the module. - -<pre> -create table titles ( - title_id text primary key, - title_name text, - bgg integer, - is_symmetric boolean -); -</pre> - -<h2>Games</h2> - -<p> -Each game session uses a handful of tables. -The main table holds the status (open/active/finished), setup information (scenario, options), whose turn it is (active), and the final result. - -<pre> -create table games ( - game_id integer primary key, - status integer, - - title_id text, - scenario text, - options text, - - player_count integer, - join_count integer, - invite_count integer, - user_count integer, - - owner_id integer, - notice text, - pace integer, - is_private boolean, - is_random boolean, - is_match boolean, - - ctime datetime, - mtime datetime, - moves integer, - active text, - result text, - - is_opposed boolean generated as ( user_count = join_count and join_count > 1 ), - is_ready boolean generated as ( player_count = join_count and invite_count = 0 ) -); -</pre> - -<p> -The players table connects users to the games they play. - -<pre> -create table players ( - game_id integer, - role text, - user_id integer, - is_invite integer, - primary key (game_id, role) -); -</pre> - -<p> -The game state is represented by a JSON blob. - -<pre> -create table game_state ( - game_id integer primary key, - state text -); -</pre> - -<p> -Each action taken in stored in the game_replay log. This is primarily used for -the detailed "Sherlock" replay view, but is also used to patch running games when -fixing bugs. - -<pre> -create table game_replay ( - game_id integer, - replay_id integer, - role text, - action text, - arguments json, - primary key (game_id, replay_id) -); -</pre> - -<p> -Whenever who is active changes, we take a snapshot of the game state -so we can provide the coarse turn-by-turn rewind view that is available when -playing. This table is also used when rewinding games. The replay_id syncs each -snapshot with the corresponding action in the game_replay table. - -<pre> -create table game_snap ( - game_id integer, - snap_id integer, - replay_id integer, - state text, - primary key (game_id, snap_id) -); -</pre> - -<p> -Game chat is kept in another table, and there's also a table to track whether a -user has any unread in-game chat messages. - -<pre> -create table game_chat ( - game_id integer, - chat_id integer, - user_id integer, - time datetime, - message text, - primary key (game_id, chat_id) -); - -create table unread_chats ( - user_id integer, - game_id integer, - primary key (user_id, game_id) -); -</pre> - -<h2>Other tables</h2> - -<p> -There are several other tables to deal with password reset tokens, email -notifications, messages, and the forum. - -See the full -<a href="https://git.rally-the-troops.com/common/server/tree/schema.sql">schema.sql</a> -for more details on these. diff --git a/public/docs/index.html b/public/docs/index.html deleted file mode 100644 index 9adfdbb..0000000 --- a/public/docs/index.html +++ /dev/null @@ -1,51 +0,0 @@ -<!doctype html> -<meta name="viewport" content="width=device-width"> -<title>Documentation</title> -<link rel="stylesheet" href="style.css"> -<body> -<article> - -<h1> -Documentation -</h1> - -<p> -This is the documentation for the <i>Rally the Troops</i> software and website. -Here you will find information both about how to configure and run your own -server instance and how to create new modules. - -<h2>For players</h2> - -<ul> -<li><a href="tips.html">Tips & tricks.</a> -<li><a href="tournaments.html">Tournaments</a> -</ul> - -<h2>For developers</h2> - -<ul> -<li><a href="install.html">Installing the server.</a> -<li><a href="production.html">Running a public server.</a> -</ul> - -<h2>System overview</h2> - -<ul> -<li><a href="architecture.html">Server architecture</a> -<li><a href="database.html">Database schema</a> -<li><a href="module.html">Module architecture</a> -</ul> - -<!-- -<h2>Module implementation guides</h2> - -<ul> -<li><a href="tutorial.html">How to create a module.</a> -<li><a href="rules.html">How to write good rules</a> -<li><a href="client.html">How to write a good client</a> -<li><a href="utils.html">The javascript utility library</a> -<li><a href="events.html">Implementing events using a mini-language</a> -<li><a href="graphics.html">Preparing map, card, and component graphics</a> -<li><a href="fuzzer.html">Using the fuzzer to stress test your rules</a> -</ul> ---> diff --git a/public/docs/install.html b/public/docs/install.html deleted file mode 100644 index 1b1bc2b..0000000 --- a/public/docs/install.html +++ /dev/null @@ -1,84 +0,0 @@ -<!doctype html> -<meta name="viewport" content="width=device-width"> -<title>RTT: Getting Started</title> -<link rel="stylesheet" href="style.css"> -<body> -<article> - -<h1> -Getting Started -</h1> - -<p> -The <i>Rally the Troops</i> software is very simple and has minimal dependencies. -All the data is stored in a single SQLite3 database. -The server runs in a single Node process using the Express.js framework. - -<p> -To run an RTT server instance, you will need -the <a href="https://www.sqlite.org/index.html">sqlite3</a> command line tool -and -<a href="https://nodejs.org/en">Node</a>. - -<h2> -Install the server -</h2> - -<p> -Check out the server repository. - -<pre> -git clone https://git.rally-the-troops.com/common/server -</pre> - -<p> -In the cloned server directory, install the NPM dependencies: - -<pre> -npm install -</pre> - -<p> -Initialize the database: - -<xmp> -sqlite3 db < schema.sql -</xmp> - -<h2> -Install the modules -</h2> - -<p> -Game modules are found in the "public" directory. -They also need to be registered in the database. - -<p> -Check out a game module: - -<pre> -git clone https://git.rally-the-troops.com/modules/field-cloth-gold \ - public/field-cloth-gold -</pre> - -<p> -Register it in the database: - -<xmp> -sqlite3 db < public/field-cloth-gold/title.sql -</xmp> - -<h2> -Start the server -</h2> - -<pre> -node server.js -</pre> - -<p> -Open the browser to <a href="http://localhost:8080/">http://localhost:8080/</a> and create an account. - -<p> -The first account created will have administrator privileges. - diff --git a/public/docs/production.html b/public/docs/production.html deleted file mode 100644 index e737bb6..0000000 --- a/public/docs/production.html +++ /dev/null @@ -1,144 +0,0 @@ -<!doctype html> -<meta name="viewport" content="width=device-width"> -<title>Public Server</title> -<link rel="stylesheet" href="style.css"> -<body> -<article> - -<h1> -Running a public server -</h1> - -<p> -To let other people connect to your server and play games, there are a few other things you will need to set up. - -<h2> -Recovering from a crash -</h2> - -<p> -Use <tt>nodemon</tt> to restart the server if it crashes. -This also restarts the server if the software is updated. - -<pre> -nodemon server.js -</pre> - -<h2> -Database & Backups -</h2> - -<p> -For best performance, you should turn on WAL mode on the database. - -<pre> -sqlite3 db "pragma journal_mode = wal" -</pre> - -<p> -You will want to backup your database periodically. This is easy to do with a single sqlite command. -Schedule the following command using cron or something similar, and make sure to copy the resulting -backup database to another machine! - -<pre> -sqlite3 db "vacuum into strftime('backup-%Y%m%d-%H%M.db')" -</pre> - -<h2> -Customize settings -</h2> - -<p> -The server reads its settings from the .env file. - -<xmp> -NODE_ENV=production - -SITE_NAME=Example -SITE_URL=https://example.com -SITE_IMPRINT="This website is operated by ..." - -HTTP_HOST=localhost -HTTP_PORT=8080 - -# Enable mail notifications -MAIL_FROM=Example Notifications <notifications@example.com> -MAIL_HOST=localhost -MAIL_PORT=25 - -# Enable webhooks -WEBHOOKS=1 - -# Enable forum -FORUM=1 -</xmp> - -<h2> -Expose the server to the internet -</h2> - -<p> -For simplicity, the server only talks plain HTTP on localhost. -To expose the server to your LAN and/or WAN, either listen to 0.0.0.0 or use a reverse proxy server such as Nginx. -To use SSL (HTTPS) you need a reverse proxy server. - -<p> -Here is an example Nginx configuration: - -<pre> -server { - listen 80; - server_name example.com www.example.com; - return 301 https://$host$request_uri; -} - -server { - listen 443 ssl; - server_name example.com www.example.com; - ssl_certificate /path/to/ssl/certificate/fullchain.cer; - ssl_certificate_key /path/to/ssl/certificate/example.com.key; - root /path/to/server/public; - location / { - try_files $uri @rally; - } - location @rally { - proxy_pass http://127.0.0.1:8080; - proxy_http_version 1.1; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection "upgrade"; - proxy_read_timeout 86400s; - proxy_send_timeout 86400s; - } -} -</pre> - -<h2> -Archive -</h2> - -<p> -Storing all the games ever played requires a lot of space. To keep the size of -the main database down, you can delete and/or archive finished games periodically. - -<p> -You can copy the game state and replay data for finished games to a separate archive database. -Below are the tools to archive (and restore) the game state data. -Run the archive and purge scripts as part of the backup cron job. - -<dl> -<dt> -<code>sqlite3 tools/archive.sql</code> -<dd> -Copy game state data of finished games into archive database. -<dt> -<code>sqlite3 tools/purge.sql</code> -<dd> -Delete game state data of finished games over a certain age. -<dt> -<code>bash tools/unarchive.sh <i>game_id</i></code> -<dd> -Restore archived game state. -</dl> - diff --git a/public/docs/style.css b/public/docs/style.css index c387442..49c72c9 100644 --- a/public/docs/style.css +++ b/public/docs/style.css @@ -1,26 +1,23 @@ +h1, h2 { border-bottom: 2px dotted brown } html { background-color: white; color: black; } -xmp, pre { background-color: #fafafa; } -xmp, pre { border: 1px solid gray; } +pre { background-color: #fafafa; } +pre { border: 1px solid gray; } h1, h2, h3 { color: brown; } - -pre.wrap, xmp.wrap { white-space: pre-wrap } - html { margin: 0; padding: 0; line-height: 1.5; } body { padding: 0rem 1rem; margin: 0 auto; max-width: 45rem; } -xmp, pre { min-width: fit-content; } +pre { min-width: fit-content; } h1, h2, h3 { margin: 2rem 0 1rem 0; padding: 0; font-weight: normal; font-family: sans-serif; } h1 { font-size: 1.8rem; } h2 { font-size: 1.4rem; } h3 { font-size: 1.2rem; } -p, ul, ol, dl, figure, blockquote, xmp, pre, table { margin: 1rem 0; font-size: 1rem; } -xmp, pre, tt, code, kbd { font-size: 0.8rem; } +p, ul, ol, dl, figure, pre, table { margin: 1rem 0; font-size: 1rem; } +ul ul, ul ol, ol ol, ol ul { margin: 0 } +blockquote { margins: 1rem 2rem; font-style: italic; } +pre, tt, code, kbd { font-size: 0.8rem; } pre { padding: 1rem; } -xmp { padding: 0rem 1rem 1rem 1rem; } kbd { background-color: whitesmoke; padding: 0px 4px; border: 1px solid #444; } dd { margin-bottom: 0.5rem; } - hr { margin: 2rem 0; border: none; border-top: 2px dotted brown; } - article::after { display: block; margin: 2rem 0; @@ -9,6 +9,7 @@ const { WebSocketServer } = require("ws") const express = require("express") const url = require("url") const sqlite3 = require("better-sqlite3") +const marked = require("marked") require("dotenv").config() @@ -4184,6 +4185,43 @@ wss.on("connection", (socket, req) => { }) /* + * DOCUMENTATION - MARKDOWN + */ + +const docs_prolog = `<!doctype html> +<meta name="viewport" content="width=device-width"> +<link rel="stylesheet" href="/docs/style.css"> +<title>TITLE</title> +<body><article>` + +function render_markdown(path) { + var text = fs.readFileSync(path, "utf-8") + var html = marked.parse(text) + var title = html.match(/<h1>([^>]*)<\/h1>/)?.[1] ?? path + return docs_prolog.replace("TITLE", title) + html +} + +app.get("/docs", function (req, res) { + res.send(render_markdown("docs/index.md")) +}) + +app.get("/docs/:file", function (req, res) { + try { + res.send(render_markdown("docs/" + req.params.file + ".md")) + } catch (err) { + res.status(404).send(err.message) + } +}) + +app.get("/docs/:dir/:file", function (req, res) { + try { + res.send(render_markdown("docs/" + req.params.dir + "/" + req.params.file + ".md")) + } catch (err) { + res.status(404).send(err.message) + } +}) + +/* * HIDDEN EXTRAS */ diff --git a/views/about.pug b/views/about.pug index f2f9964..ee94352 100644 --- a/views/about.pug +++ b/views/about.pug @@ -22,8 +22,8 @@ html h2 About ul - li Read the <a href="/docs/tips.html">Tips & Tricks</a> before playing! - li Read the <a href="/docs/tournaments.html">tournament information</a> before joining a tournament. + li Read the <a href="/docs/tips">Tips & Tricks</a> before playing! + li Read the <a href="/docs/tournaments">tournament information</a> before joining a tournament. li Study the <a href="/docs/">developer documentation</a> if you want to create modules. p. |