nanoMMO

MMORPG guilds in C++, from MySQL to the nameplate

Our C++ MMORPG gets guilds, kept in MySQL a transaction at a time, with invitations in Redis, a window to found one, the name over your head, a chat for the guild, and a leader who hands it on.

Watch on YouTube

Guilds for our MMORPG, in C++, MySQL and Redis. A guild changes for players other than the one who acts, so it lives in MySQL, a transaction for each change, with a unique key that keeps its name the world's once, whatever its case. A window on G founds one, and its name goes under yours, over your head. Officers and the leader ask players in, with an invitation that waits a minute in Redis (SET NX EX), or until they say no, so another guild can ask, and joining locks the guild's row first, so it can't fill up or end while you join. A chat for the guild alone goes out at once over TCP, in green, and when the leader leaves, the guild goes to whoever's been in it longest, or ends with the last one out. This is episode 66 of a series about building an MMORPG from scratch in C++, with the focus on the engineering around the game.

Topics: Databases, Gameplay

The code

Each step on screen is a tag in the game's repository. The code at the end of the episode is ep066/end.

  1. 2:22ep066/step-1Guilds in MySQLBrowseChanges
  2. 14:24ep066/step-2A guild windowBrowseChanges
  3. 27:55ep066/step-3A name over your headBrowseChanges
  4. 31:55ep066/step-4Asking someone inBrowseChanges
  5. 47:48ep066/step-5The guild's chatBrowseChanges
  6. 55:06ep066/step-6LeavingBrowseChanges

Transcript

Intro

0:00 Hi, and welcome to episode sixty-six, where we're going to give the game guilds, from two tables in MySQL all the way to a name over your head. I think guilds are where an MMO stops being a lot of single players side by side. And for us, a guild is the first thing one player changes for others, so it can't sit in Redis with the rest of a player. Let's start with a quick look at where we'll be by the end.

0:25 By the end of the episode, arthur leads a guild called Iron Wolves, and its window opens on G. Asking gwen in by her name sends her a question, and once she says yes, the guild's name goes under hers, over her head. Then what she says to the guild comes up in green, for its players alone.

0:48 All of this is on the series' website, which links the code on GitHub, open source, and has a page for each episode, with its chapters and the code at each step.

Last time

0:57 A quick reminder of where we left off. Last time, we took a brand-new Ubuntu machine from a git clone to a laptop playing on it, with a doctor script that says what a machine is missing, and one command to install it. The build lost its six hundred warnings, and Redis, MySQL and Consul stopped listening on the network. A refused TLS handshake says what's wrong with the certificate, and what to do, and the steps went on a getting started page.

Today

1:24 Here's the game as it stands, at the end of the last episode. Over each player goes a name and a level, and nothing about who they play with. Pressing G doesn't open anything yet, and the buttons in the corner are for the character, the bag, the map and the menu. The chat has one channel, the world's, so there's no way to talk to a few friends alone, and a line meant for them goes to everyone in Ember, slash g and all.

1:50 So, today we're going to build guilds, one piece at a time. They go in MySQL, in two tables, with a transaction for each change, as a guild changes for players other than the one who acts. Then a window on G, to found one, and the guild's name under yours, over your head. After that, asking someone in, with an invitation that waits a minute in Redis, a chat for the guild alone, and leaving, where the leader's place goes to whoever's been in longest. Right, let's start with the two tables a guild lives in.

Guilds in MySQL

2:23 Each episode's code is a minor version of its own, so the top CMake file moves the project on to zero point sixty-six. Guilds start in the database, with a new Flyway migration, version eleven. I spent a while on where a guild should live. A player's state sits in Redis while they play, and their world saves it, as nobody else changes it. A guild is different: one player's leaving changes another's rank, and a copy of it in Redis could be written back stale, so each change goes straight to MySQL, in a transaction. The guilds table has an id that MySQL counts up for us, the world the guild is in, and its name, up to twenty-four characters, with when it was made. A unique key on the world and the name means a name is taken once per world. The database refuses a second one for us, even when two players found a guild of that name at once, on two instances, which a check in our code could miss. I like the database holding a rule like that, as it's one place to look, and no instance of the world can race past it. The default collation in MySQL compares text without its case, so Iron Wolves and iron wolves are one name, which is what a player would expect. It's easy to forget that the collation does that for us, so it goes in a note above the table: guilds, each in one world, like its characters, and a name taken once per world, whatever its case. A name taken in one world is still free in another, as each world is a game of its own. Who's in which guild goes in guild members, keyed by the player, which is the character's id. With the player as the primary key, a character is in one guild at most, and again it's MySQL that checks it, instead of our code. The rank would be a column called rank, but rank is a word MySQL keeps for its window functions, so the column is grade, a small number: zero for a member, one for an officer and two for the leader. Joined at keeps milliseconds, as we're going to pick a new leader by who joined first, and two players can easily join within a second of each other. An index on the guild and the grade finds a guild's members by rank, which is the order we'll look for a leader in. Two foreign keys finish the table, one for each side. A deleted character takes its row with it, with on delete cascade, and a guild that ends takes its members' rows. Over the table, we write what it holds: who's in which guild, by the character's id, so one guild at most, with the grade for the rank, as rank is a word MySQL keeps. And a deleted character, or an ended guild, takes its rows with it. The rank is something the client shows too, so in our proto file, it gets an enum, which gives the client and the server names for it, where a bare number would mean looking up what a two is. Protobuf's enums start at zero, which is what a field holds when nobody set it, so the least of the ranks, a member, is the one a missing rank falls back to. It goes from the least: member, officer and leader, numbered as the grade column holds them, so the server turns one into the other with a cast. Above the enum goes that order, and that MySQL keeps it as the member's grade.

5:27 The server gets a new header file, guilds, for the guilds and who's in them. We bring in cstdint, for the ids, string and string view, and Abseil's status and status or, as our functions return a result or an error that says why. Then our protocol, for the rank, and the database. Check guild name says whether a guild may be called that. It's a free function, as it needs no database, so a test can call it on its own. The rule is three to twenty-four letters, with single spaces between words, or an invalid argument error that says what's wrong. A membership is the guild a character is in, and their rank there, which is all the server keeps about a player's guild: the guild's id and name, with a rank that starts as a member. Then the class, Guilds, and the reason it's in MySQL. A guild is in one world, as its characters are, and a character is in one guild at most. Unlike a player, whose own world saves them, a guild changes for players other than the one who acts, so it isn't in Redis, and each change is a transaction. Its constructor keeps a reference to the database, like our accounts and characters, and it's explicit, as a single argument would otherwise let a database turn into guilds by accident. Of gives the guild a character is in, or a not found error for none, which is how most players start out. Create founds a new guild in a world, led by the character who founds it. Its errors are worded for a player: invalid argument says what's wrong with the name, and already exists that the name is taken in the world, or that the character is in a guild already. Last, the class keeps its reference to the database, in private, as nothing outside needs it, and the header ends, as ours do, by closing the namespace and the include guard. In guilds, we bring in our header, then cstddef, for size t, string and vector. From Abseil, ascii tells letters apart, numbers reads the text MySQL gives back into numbers, and str cat joins strings. Check guild name starts with the length, three to twenty-four, which fits the column, so MySQL won't cut a name that passes. Then we go through the name, a character at a time. The rule it keeps is words of letters, one space apart, so a name starts and ends with a letter, and two names can't differ by their spaces alone. Otherwise Iron Wolves with two spaces would be a second guild that looks like the first over somebody's head. A space is fine between words: not first, not last, and not right after another space. Anything that isn't a letter, or a space between words, gets an error that says what a name can be. Abseil's ascii is alpha takes an unsigned char, and the cast says so out loud, as a byte of a name in UTF-8 can be over a hundred and twenty-seven, which a signed char holds as a negative number. I decided against letters from other alphabets for now, as two names that look alike in different scripts are a way to pretend to be another guild. Of asks MySQL for the character's guild, joining the two tables, so the guild's id, its name and the member's grade come back in one query. The player's id goes apart from the SQL, as a value for the question mark, like all our queries. Of runs on its own, outside a transaction, as a single select already reads both tables as they were at one moment. No rows means no guild, and the error is already in a player's words. MySQL hands us text, so simple a to i reads the id and the grade back into numbers, and Rank is valid, which protobuf generates for each enum, checks the grade is a rank we know. If any of that fails, it's an internal error, as the table would hold something our code didn't write. Then the name, and the grade cast to a rank. Create takes the world, the founder and the name. The world comes from the server, which knows which world it is, so a client gets no say in it. Create checks the name first, before it touches the database, so a bad name costs no round trip. The membership starts with the name and the leader's rank, in designated initialisers, which name the fields they set. The rest goes in a transaction, as the guild and its leader have to go in together. Over it, we write why: when the character is in a guild already, the second insert fails, the transaction takes the guild back out, and its name stays free for someone else. We insert the guild, and when MySQL refuses it as a duplicate, which our database class turns into already exists, we say there's a guild called that in the world already. Leaning on the unique key, instead of a select that checks first, means two founders at once can't both get through, as the check and the write are a single statement. The guild's id is the insert id MySQL gave it. Then the leader's row, at the leader's grade, which str cat writes as the number two, with a cast to an int to say we mean the number. A duplicate here means the character is in a guild already, as the player is the primary key. A failed transaction is Create's answer, and otherwise the membership. In the server's CMake file, guilds goes into the server's core library, and its test into the server's tests.

10:34 Now, let's pin down the rules MySQL keeps for us with a few tests, as a migration later on could quietly drop a key, and nothing else would notice. We bring in our header, cstdint, memory and string, Abseil's status and status or, and GoogleTest. Then the accounts, the characters, and the test services, which connect to MySQL when a variable says where it is. The first test needs no database at all. Iron Wolves is fine, and so is Ash, at three letters. Io, at two, is too short, and The Wolves of the Iron Hill, at twenty-seven, is too long. Then come the names that are easy to type by accident. Two spaces in the middle are refused, and so is a space at the start, and one at the end, which a player pasting a name could easily leave in. An exclamation mark is refused, as names are letters, and so is a digit, as in Clan seven. I'd sooner find those here than over somebody's head. For the rest, a fixture in an unnamed namespace makes characters in a world of the test's own, named after the test. That way the guilds' names are free whatever ran before. Set up connects to MySQL, and without it, the tests are skipped, with a message that says how to run them. Then it makes an account, named after the test too, and asserts that worked, as nothing after it can go on without one. The account gets three characters: alice, in the test's world, then bob, in that world too, and carol, in another one, for the name in a second world. The test asserts all three were made, and keeps their ids, so the tests can refer to each of them by name. Tear down deletes the test's guilds in both worlds, then the account. An account takes its characters with it, and those take their memberships, but a guild stays until it's deleted. So the guilds need a delete of their own, and that's the note we write over it. Both deletes go through Run, with the worlds and the name as values, and each is expected to work, so a clean-up that fails shows up as a failure of its own. The fixture keeps the database, the test's name, which is its world too, the other world, and the three ids, which start at zero until set up fills them in. The first test with MySQL founds a guild. Before it, Of says alice is in no guild, with not found, which is how the server will tell a player in none from a database that's down. Once she founds Iron Wolves, the membership Create returns has that name, and the leader's rank. Then Of reads it back from the database, with the guild's id from Create, its name, and alice as the leader. That shows Create wrote both rows, and that Of's join finds them. A test that checked Create's answer alone would pass for a Create that wrote nothing. The second test is the one I care about most. Once alice has founded Iron Wolves, bob can't found Iron Wolves all in capitals, in her world, as the collation reads the two as one name. Meanwhile carol can found Iron Wolves in another world. Without carol's half, the test would pass for a server that refused the name in all the worlds. And last, once alice leads Iron Wolves, she can't found a second guild, Stone Bears, as she's in one already. Her refusal takes the Stone Bears guild back out with it, so bob can found Stone Bears straight after. That check at the end is there for Create's transaction, as without the transaction, the guild would have stayed behind, with nobody in it, holding its name for good.

14:00 We build the server's tests at this step, in Docker, and run the guilds' tests against MySQL in Compose, where Flyway runs our new migration first. Grep keeps the line of each test that passes, and the total, and the build takes a while, as the image compiles the game from scratch. A name is the world's once, whatever its case, a character founds one guild at most, and all four pass.

A guild window

14:25 With the tables in place, a player needs a way to found a guild from the game. In our proto file, the input a client sends gets a guild action, field fifteen, sent once, like an item's action, and not with each input. The world the server sends gets the player's guild, field twenty. It comes on its own, over TCP, as they join and as it changes, which is how their bag already comes, as it's rare, and it has to arrive. A guild action is a oneof, which holds one of its fields at a time, and so far there's one, create, with the name of the guild to found, and we'll add to it as we go. A refusal comes back as a line from nobody, which is how our server's notices come. And Guild is the player's guild, and their rank in it, with an empty name for none, which is what protobuf sends for a message nobody filled in. Guild actions are transactions that can wait on each other's locks, so in the database's header file, we add to what Run says about its errors: a lock waited for too long, or a deadlock, comes back as aborted. In the database, MySQL has an error code for each of those two, the lock wait timeout and the deadlock, and they become an aborted error. In Abseil's codes, aborted means the operation was cut short by a conflict with another one, and is worth trying again. That's when another transaction held what this one needed for too long, or the two waited for each other. That's the code Refuse is going to look for, a little further on. Then, as each connection is made, we set the InnoDB lock wait timeout for the session to two seconds. The default in MySQL is fifty, and a world's tick waits for whatever it asks of MySQL, so a statement stuck on a lock for fifty seconds would freeze the whole world with it. Two seconds is still a very long tick, and I'd much sooner give up and tell the player to try again. If MySQL refuses the setting, the new connection is closed and its error returned, like the checks before it. In the server's header file, we bring in set, for the players with news, and our guilds' header. Create takes the guilds as well, between the players and the events, and so does the private constructor. The guilds come in by reference, like the other services, as main owns them, and they outlive the server. Guild handles a player's guild action, and Found founds one. Refuse tells the player why their guild action failed: in the error's words when it's about what they asked, and with try again when it's MySQL. Send guilds goes to each player as they join, and as their guild changes. In private, the server keeps the guilds by reference, and a token bucket for each player's guild actions sits with the others. Members is the guild of each player here who's in one, a map from their id, and guild news is the set of players whose guild we have to send them. In the server, a guild action is a transaction in MySQL, and the tick waits for it, which makes it the slowest thing a player can ask of a world so far. Moving an item is a few comparisons in memory, while this is a round trip to the database, and a lock or two. So each player gets a token bucket for guild actions, like the chat's and the bag's, with a burst of three. The reason is that each guild action is a transaction in MySQL, which the tick waits for, so a player gets three at once, and then one a second. Ten a second, like the bag's, would let one player hold up the tick for everyone else on the server. The server's Create and its constructor take the guilds and keep them, like the players. When an input from a player carries a guild action, it goes to Guild, next to the item's. As a player says hello, we ask MySQL for their guild, and keep it in members, a map we keep for the players on this server. Not found is the usual case, a player in no guild. Anything else gets logged, with the player's id and the status, while they play on without one, as a guild that didn't load shouldn't stop someone playing. Either way, their id goes into guild news, so the first guild message tells them, even when it's none. Above it, we write that it's from MySQL, and that the first guild news brings it, or none. Their token bucket for guild actions goes in with the others, and as they leave, it goes, along with their membership and any news we hadn't sent. Guild returns at once while the world is handing its players over to its next instance, like the bag, so that the next instance reads the guild as it'll stay. A player out of tokens is told they're doing that too fast. Then a switch on which field of the oneof is set, where create goes to Found, and an action with nothing set does nothing. An action from a newer client, which this server doesn't know, arrives with nothing set, so it does nothing too. Found asks the guilds to create one in this world, whose name is the server's. When that fails, Refuse tells the player why, in the chat. Otherwise the player's membership is kept, they go into guild news, and the server logs who founded what. Refuse splits the errors it's given into two kinds. Unavailable, internal and aborted mean MySQL failed us, so we log the details for ourselves, and the player gets That didn't work, try again, as they don't need our SQL. Anything else is about what they asked, such as a name that's taken, and its message goes straight to them, which is why those errors were worded for a player in the first place. Each tick sends the guild news after the quests. For each player with news who's still connected, we build a world message with their guild. An empty guild still says they're in none, which matters for the first one. With a membership, it carries the name and the rank. Either way, it's framed, counted in our metrics, and sent over their TCP session, and then the news is cleared. And in the server's main, the guilds are made from the database, next to the players, and handed to Create.

20:10 Next, a test that a player founds a guild from the game, over the network, like a client would. The server test brings in the guilds' header. Its test player keeps the guild the server last sent, as an optional. It's empty until one has come, which is different from an empty guild, which says the player's in none, so the test can wait for the first message. A world message with a guild in it goes there. The fixture makes the guilds from the test's MySQL, next to the players, and the server it makes takes them, between the players and the events. The fixture's server is the one most tests share, in a world named after the test, with a tick of fifty milliseconds, so the tests run quickly. Tear down deletes the guilds in the test's world, before the accounts. The characters go with their accounts, and the memberships with the characters, but not the guilds. The fixture keeps the guilds with the players. Four of the tests make servers of their own, set up for what they test, and each of those takes the guilds now, as the fixture's does. The test that hands players over makes a second instance of the world, as a handover goes from one instance to the next, here in one process. The bag's test makes a server with gear in it, so that there's something to wear. The quests' test makes one with a guard who gives a quest, and the hits' test one with a skeleton next to the players, to hit, as the hits are what that test is about. None of them founds a guild, but a server can't be made without the guilds now, as each world answers guild actions, so they all pass them along, and nothing else in them changes. A reference can't be left out, so a server made without guilds is a compile error, which is where I'd want to find it. With each server taking the guilds, the new test can found one over the network. The new test starts like the others, with two players, alice and bob, who join over TLS, like two clients. The test waits until both have had their first guild message, and over that, we note that each hears they're in no guild as they join. Then it checks alice's has an empty name. Then alice sends a guild action to found Iron Wolves, with two spaces in it. The notice she gets is the rule about spaces, in the words Check guild name wrote, which shows the server passes the error's message on. With one space, the guild news says she's in Iron Wolves. The test waits on the guild news for that, and on a notice for the refusal, as a success and a refusal come back in different messages, and then it checks she leads it. And when bob asks for iron wolves, in lower case, he's told there's a guild called that in the world already, and his guild is still the empty one from joining, as a refusal sends no guild news. The refusal bob gets starts at the unique key in MySQL, and reaches him in the words Create gave it, as Refuse passes a player's error on.

22:59 On the client, the guild gets a window of its own, in a new header file, guild window. We bring in array, for the name being typed, optional, for an action that's there or not, and our protocol. Rank name gives what a rank is called, Leader, Officer or Member, for the window to show. Guild window is your guild, in a window of its own, which G opens and closes. While you're in none, it has a field for a name to found one with, and once you are, its name and your rank. It's built like the bag window: mutable visible hands the button bar a pointer to whether it's open, visible says whether it is, and toggle flips it. Build draws it while it's open, from the guild the server sent us. It returns what the player asks for, which the server does, or says in the chat why not, and main sends it, as the window doesn't talk to the network. In private, the window keeps whether it's visible, closed to begin with. The name being typed is an array of twenty-five characters, as ImGui's text fields write into a buffer we own: twenty-four letters, and the end. In guild window, we bring in ImGui and our theme, and in the corner, the window is in the game at this step. Rank name is a switch on the rank, with a case for the leader and one for an officer, and anything else is a member, by default, so a rank from a newer server still gets a name. Build takes your guild, as the server last sent it. While the window's closed, it returns nothing, and otherwise the action starts empty. The first time it opens, it goes in the middle across, and four tenths of the way down, centred there by its pivot, a little above the middle of the screen. It's one of our panels, titled Guild, whose close button sets visible to false. It fits what's in it, and its place isn't saved between runs. The fields and buttons are two hundred and eighty points wide, at the interface's scale. Without a guild, a line says you're in no guild, and to found one. Under it, in muted text, goes the rule for a name, so a player knows it before the server has to tell them. The field shows Its name as a hint while it's empty, and its flag, enter returns true, has ImGui tell us when Enter was pressed in it. Named says whether the field has anything in it. Found the guild is the panel's main button, in the fire's colours, across the panel, and disabled until there's a name. A click on it, or Enter, makes a create action with the name, and the field keeps it, in case the server says no. Once you're in a guild, the window shows its name, and your rank under it, muted. In the client's CMake file, guild window goes into the client's core library. In the connection's header file, guild returns our guild, as the server last sent it, where an empty name means none, and the connection keeps it. In the connection, a world message with a guild in it is kept there, like our bag and our quests. We add our guild to the list above of what comes on its own, with nothing of the world in it. Those messages don't go through the parts that build up the world, so a guild message can't wipe out what we know about the players. In the menu's header file, build buttons takes a flag for the guild window too, between the bag and the map. In the menu, the keys' page gets a sixteenth row, G, for your guild, so its array grows to sixteen. And the row of buttons in the bottom right gets one between the bag and the map, with Font Awesome's half shield, and Guild, G, in its tooltip, which flips the window's flag when it's clicked. In the client's main, we bring in the guild window's header, and make one next to the bag window. Escape closes it after the bag, and G opens and closes it while you're not typing, like I for the bag. Each frame, the window is built with the guild the server sent us. An action it returns goes to the server in an input, with what we sent last, so we keep moving as we were. The button bar gets the guild window's flag. And the load bots skip a world message with a guild in it, as we note over it: a bot founds no guild, so it doesn't need to know it's in none. Without that, the message would go into its picture of the world, which it doesn't belong in.

27:11 We run the new server test at this step, against MySQL and Redis in Compose, with the test's world on a port of its own. A guild founded over the network comes back as the player's guild news, and a name taken in lower case is refused, so it passes.

27:26 At this step, arthur is in no guild yet, and the game has a guild window. A shield joins the buttons in the corner, with G in its tooltip, and G opens the window, which says we're in no guild, with the rule for a name under it. Enter in the field sends the name to the server, in a guild action. MySQL takes the guild and its leader in one transaction, and the guild news turns the window into the guild's name, with Leader under it.

A name over your head

27:55 Next, the guild's name over a player's head, so you can tell who plays with whom from across a field. In our proto file, a player gets the name of the guild they're in, field fifteen, which comes with their name. On the wire, the names, the kinds and the levels come once a second, in the world sent in full, and in between, the client keeps the last ones it had, in parts. The weapon goes by the name, as a player can hold none, and protobuf leaves an empty field off the wire, so a missing weapon and a weapon put away look alike. The guild is like the weapon, so over the function, we write that a player with their name has their weapon and guild too, even when they're empty. So when a compact world comes without the name, we keep the guild we had, and a full one without a guild means they've left it. In the server, the full broadcast puts each player's guild next to their name, from their membership, once a second. A compact world clears the name and the rest, and sends none of it, so the guild costs nothing on the ticks in between, which are most of them. In the animator's header file, a figure gets the guild, by its name, or empty for none, and the animator copies it from the player, next to the name. Nameplates are next, and the corner shows them in the game, at this step. A guild gets a colour of its own, a pale, sandy gold, quieter than the names, and a size of eighty-five hundredths of the name's. The top of the plate starts just above the health bar, as before, but it's a variable now, as the guild may take a line under the name. For a player in a guild, its name goes in angle brackets, which is how most other games put a guild under a name. It's measured at its smaller size, and centred over the figure. The top goes up by its height, and it's drawn with a shadow, in the guild's colour. Then the top goes up again by the name's height, and the name and the level go there, so the guild sits between the name and the bar. The old line that worked the top out goes. In the player frame, your guild goes across from your name, on the right, where a target's frame has its level. It's in the bold face, at thirteen points, measured so that it ends at the right edge, and drawn muted, as it matters less than your name.

30:08 Two tests pin that down, one for the client's parts and one for the server. The parts test that keeps names and levels between full worlds gives the first player a guild too, Iron Wolves, and checks it's still there after a compact world, which had no names in it. Then a world with their name, and no weapon or guild, means they've put the weapon away and left the guild, so the guild comes back empty. That's the case a quick version of parts gets wrong, as keeping the old guild would leave a player wearing a guild's name long after they'd left it. In the server test, a new test checks that others see the guild with your name. It reads like the check we'd do by hand, with two clients side by side. First, alice and bob join, and the test waits until bob sees alice, as before that, his world has nobody in it to check. Then alice sends a guild action, to found Iron Wolves. The test runs until bob's world has a player with alice's id, and Iron Wolves as the guild, with ranges any of, which says whether any player matches, given a lambda that checks one. The lambda captures by reference, so it sees bob's world as it is each time it's called. Over that, we write why it waits: the guild comes with her name, in the world sent in full once a second. A second is a long wait in a test, but Run until stops as soon as it's true, so it costs one full world at most.

31:33 With this step's code, a guild gets a line of its own over the heads. This time, arthur leads Iron Wolves, so the guild's name goes under arthur's, over the head, and across from the name in our frame. Then gwen, ahead of us, founds a guild of her own, Stone Bears, and within a second, the next full world brings it, under her name.

Asking someone in

31:56 A guild of one isn't much of a guild, so next, asking someone in. In our proto file, the world gets a guild invite, field twenty-one, which comes on its own, over TCP, like the guild. A guild action can now ask a player in this world to join, by their name, or join the guild that asked, or say no to it, which frees them for another guild to ask. Accept and decline are bools in the oneof, as a oneof needs a field to set, and yes or no needs nothing more than that. A guild invite is the guild's name and who asked, by their name, and it waits a minute for an answer. An invitation runs out after a minute, so I put it in Redis, which deletes a key for us when its time is up, while the guild stays in MySQL. MySQL could do it with an expiry column and a clean-up job, but Redis does that part for us. In the guilds' header file, we bring in chrono, for the invitation's life, and Redis, and the class now says the invitations, which run out, are the part in Redis. A guild holds a hundred characters at most, and an invitation waits sixty seconds for an answer, as a chrono duration, which carries its unit in its type. The constructor takes Redis as well, and loses explicit, as it takes two arguments now. Invite asks a player to join the guild of the one who asks, which an officer or the leader can do. Its errors say that the one who asks is in no guild, or a member, or that a guild asked the player a minute ago at most, and they haven't answered. It returns the guild they're asked to join, for the question. Accept has the player join the guild that asked, as a member. Not found says nobody asked, or it ran out, or the guild is gone, already exists that they're in a guild, and resource exhausted that the guild is full. And Decline has the player say no to the guild that asked, so that another can ask. Last, the class keeps Redis next to the database. In guilds, an unnamed namespace holds Invitation of, which gives the Redis key of a player's invitation: guild invite, a colon, and their character's id. Each player has one invitation at a time, by their character's id, and its value is the guild's id. Invite starts with the guild of the one who asks, and returns Of's error when they're in none. A member gets permission denied, with the reason in words, as officers and the leader are the ones who ask people in. The invitation is a single SET, with two options that do the work for us. N X sets it when there's no key yet, so of two guilds asking at once, from any instance, one wins and the other is told. E X gives the key its life, in seconds, so Redis deletes it after a minute, and nothing of ours has to clean up. When N X finds a key already, Redis answers nil, which our Redis class returns as not found, so that becomes already exists: they've been asked to join a guild. Otherwise Invite returns the guild of the one who asked, which the question names. Accept reads the invitation with GET, and doesn't take it yet. That way, if MySQL fails for a moment, the invitation is still there to try again. And two accepts at once can't both join, as a character is in one guild at most. Nil means nobody asked, or it ran out. Then the guild's id is read back from its value, which Invite wrote as a number, so anything else is an internal error. Joining is a transaction, as its three statements have to see one guild, and the insert at the end has to go in with what the first two found. Its first statement locks the guild's row, with select for update. Each change to a guild is going to lock that row first, so changes to one guild happen one at a time, and the guild can't end or fill up while we join. We write that above it, as any code that changes a guild later has to lock that row first too. A lock on the whole table would have all the guilds queue behind one another, while the row's lock lets two different guilds go ahead side by side. No row means the guild ended since the invitation, and otherwise we keep its name. Then we count its members with count star, which runs while we hold the guild's lock, so nobody can join or leave between the count and our insert. Simple a to i reads the count, and a count that isn't a number is an internal error, as the answer MySQL gives can't be anything else. A guild at a hundred is full, and the error names it, so the player knows which guild turned them away. Without the lock, two players could both count ninety-nine, and both join. Last, the member's row, at the default grade, a member, and a duplicate means they're in a guild already. Anything else from the insert is returned as it is, which ends the transaction with that error, and MySQL undoes the lot. Once the transaction's done, the invitation goes, with DEL, unless MySQL gave up on a lock or went away, which are the two errors worth trying again. By then they've joined, or won't ever with this one, so it's spent, and if deleting it fails, it runs out on its own, so we ignore that error. Taking the invitation first would lose it each time MySQL fails for a moment, and the player told to try again would have nothing left to accept. Decline deletes the invitation, and returns how that went. The server's main hands Redis to the guilds too. In the server's header file, Ask asks the player of that name in, if they're playing in this world, Join has a player say yes, and Tell guild sends each of the guild's players here a line from the server. In the server, we bring in Abseil's match header, for comparing names without their case. The switch sends invite to Ask, and accept to Join, while decline goes straight to Guilds, and an error from it goes to Refuse. Ask starts with nobody found, an id of zero. It looks in this world alone, as they have to be playing here to see the question. Their name starts empty too, until we find them. Then it goes through each copy of the world, which is each land, and each copy of a dungeon, as a player can be in any of them, and looks at each player's name. Names compare without their case, as MySQL compares them, and we keep their id, and their name as they spell it. When nobody of that name is playing in this world, the one who asked gets a notice that says so. We know who's in a guild here from members, so asking someone who's in one already is refused before Guilds goes to MySQL or Redis. Then Guilds sets the invitation, and Refuse says why when it can't. The question is a world message with the invite, the guild's name and the name of the one who asked, sent over the asked player's TCP session. And the one who asked hears that they did, with the name spelled as its player spells it. Join accepts the invitation through Guilds, and Refuse says why when it can't. Otherwise it keeps the new membership, and puts the player in guild news, so their window and their plate change. Then the guild's players on this server hear who joined. Tell guild goes through the members here and notifies the ones in that guild. And the load bots skip the invitation too, as a bot doesn't say yes to a guild that asks it.

39:08 The invitations get tests at both ends, starting with Guilds. The guilds' test brings in str cat, for the Redis keys. Its fixture makes three characters in the test's world now, and one in another. Guilds needs Redis now, for the invitations, so the fixture needs it too. Set up connects to both now, and skips without either, with a message that names both variables, so whoever runs it knows what to set. The new character, dave, goes in the test's world, so there's someone left to ask, and the test asserts all four were made. Tear down deletes each character's invitation from Redis. An invitation could outlive the test by up to a minute. The next run's characters have new ids, so it wouldn't get in their way, but a test shouldn't leave keys behind. The fixture keeps Redis, and dave's id, next to the others, starting at zero like them. The three tests from before make their guilds with Redis too, a line each. The first new test is about the invitation in Redis. In it, alice founds Iron Wolves and asks bob in, and a second ask is refused with already exists while the first one waits, which is N X at work, as the key is there already. Then bob accepts, and joins the guild the invitation pointed at, Iron Wolves, as a member. Accepting again finds nothing, as joining deleted the invitation. And Of agrees he's in alice's guild, by its id, so the row went into MySQL. The second test is about the ranks, and who may ask. Once bob has joined alice's guild, as a member, asking dave in gets permission denied. And dave, in no guild at all, gets not found for asking bob, as he has no guild to ask him into. Both errors come before Redis is touched, so neither leaves an invitation behind. The third test is about a player who's in a guild already, so alice founds Iron Wolves, and bob founds Stone Bears, so he leads it. Then alice asks him into Iron Wolves, which Redis lets her do, but his accept is refused, as the primary key on the player refuses a second row. And afterwards, bob is still in Stone Bears. The fourth test shows what Decline is for. alice founds Iron Wolves, and dave founds Stone Bears. alice asks bob in, so while bob hasn't answered, dave's invitation is refused. Once bob says no, dave can ask, which shows the key has gone, and then bob accepts. He joins Stone Bears, so the invitation his accept read was dave's, and not one left over from alice. In the server test, we bring in map, for the names, and Abseil's ascii, to write a name in capitals. The test player keeps the last invitation it was sent, as an optional, which a world message brings on its own, like the guild, and Read puts it there. Tear down deletes each character's invitation along with the rest of their keys, in the pipeline that's there already, so it's still one round trip to Redis. And as each character is made, the fixture keeps its name, in a map from its id, as asking goes by name. In the test, alice and bob join, each as a test player over TLS, and the test waits until both have had their first guild news, as the other tests do. Then alice founds Iron Wolves, as in the founding test, and the test waits until the news says she's in it. Then she asks bob in, by his name in capitals, which works, as names compare without their case, which we note over it. The test waits until bob has an invitation, and checks it's for Iron Wolves, and from alice, by her name. Then it makes an accept action, for bob to send. Once he's sent it, the test waits until his guild news says he's in Iron Wolves, and then checks he's a member, the rank a new player gets. And alice hears that bob joined, which the test waits for, as a notice comes in a message of its own.

43:05 We run the guilds' tests and the new server test at this step, with MySQL and Redis in Compose. An invitation is one at a time and taken once, members can't ask anyone in, and saying no lets another guild ask. And a player asked by name in capitals joins, so all eight pass.

43:24 On the client, the connection's header file gets Take invite, which hands over the guild that asked us to join since the last time, once, and an optional invite to keep it in until then. In the connection, a world message with an invite in it goes there, next to the guild. Take invite returns it, and empties it, in one go, with std exchange, like the events, so the window hears about each invitation once. In the guild window's header file, the class now has a name to ask someone in by, for an officer or the leader. Invited is how the window hears that a guild asked us to join. It takes the invitation by value, as the window keeps it. Invited keeps it, and the drawing waits for Build. The window asks us about it, shown or hidden, until we answer or the invitation runs out. Keeping it in the window means that a closed window still asks. Build draws that question too, as the first thing it does: the question, if a guild asked, and then the window. As before, the window is drawn while it's open. Its return is as before, an action that the server does, or says why not. Build question is its private half, which draws the question and returns the answer. The guild's name keeps its array, and a player's name to ask in gets one of its own, of seventeen characters, for a name of up to sixteen. Two fields sharing a buffer would carry what was typed in one over into the other. The window keeps the invitation, as an optional, empty while there's none, and when it came, in ImGui's seconds, as a double, which is what ImGui's clock gives. In guild window, we bring in utility, for std move. The client keeps a minute of its own, in seconds, as long as the server keeps an invitation, so the question goes when the invitation has, without the client having to ask about it. Invited moves the invitation in, and keeps ImGui's time. Build starts with the question now, so that it shows while the window's closed, and a closed window returns the question's answer. Named moves up, before the branch, which doesn't change what it does. In a guild, officers and the leader ask players in, by name. Members don't see it at all, as the server would refuse them anyway, and a button that can't work is worse than none. Under a little space, the others get a field for someone playing here, as its hint says, as wide as the rest. It has a buffer of its own, so it starts out empty. Someone says whether that field has a name in it. Ask them in is a plain button this time, as it's not what the window's mostly for. Enter works too, and the field empties once the name has gone, so the next one starts fresh. Build question is the part the corner shows: a guild asking us to join. Without an invitation, or a minute after it came, there's nothing to ask. The question goes in the middle across, three tenths of the way down, each frame, and it can't be moved, as it waits for an answer. It's a panel titled Join a guild, whose close button sets open to false. Its line names who asks, and the guild. Under it, Join, in the fire's colours, makes an accept action, and closes the question. Not now closes the question too, and over it, we write that saying no tells the server, so that another guild can ask, instead of waiting out the minute. So the button sends a decline to the server. Once it's closed, either way, the client drops the invitation. And in the client's main, an invitation that came is handed to the guild window, each frame, before it's built.

46:53 Let's try asking someone in, in the game, at this step, as the leader of Iron Wolves. The window has a field for someone playing here, and a button to ask them in. Asking gwen sets her invitation in Redis, with a minute to live, and sends her the question, over TCP. Once she says yes, MySQL has her in the guild, Iron Wolves hears that she joined, and the next full world puts the guild under her name.

47:21 And from the other side, where gwen leads Stone Bears, and arthur's in no guild. Her invitation comes up as a question above the middle of the screen, with the guild window closed, naming who asks and which guild. Join sends the accept, and the server reads the invitation from Redis, joins arthur to the guild while it holds the guild's row, and then deletes the invitation, as it's spent. So the frame and the plate say Stone Bears now, and the guild hears who joined.

The guild's chat

47:49 Now that people are in guilds, they need a way to talk to the guild alone, as the world's chat goes to everyone in Ember, in all its lands. In our proto file, a channel says who hears a line: the whole world, or the guild of the one who said it. Each line of chat carries its channel, as field three. The world is zero, and protobuf leaves a zero off the wire, so the world's lines cost no more bytes than before, and an older client reads a guild's line as a line like any other. And a guild action can say a line, for the guild alone. I went back and forth on whether this belonged in the guild action or in the chat's own field, and the guild action won, as it keeps all things guild in one place on the server. In the server's header file, Guild say goes to the guild's players in this world, at once, over TCP. In the server, a guild action with a line in it goes to Guild say before the guild's token bucket. Above that, we write why: a line of chat has the chat's own limit, and doesn't touch MySQL, so it shouldn't use up the tokens that guard the database. The switch lists say next to an action with nothing set, as it's handled above, before the bucket. Guild say turns away a player in no guild, with a notice that says so, which is what the slash g of someone without a guild gets. Then it takes from the chat's token bucket, so talking to the guild and to the world share one limit. Too fast gets the chat's own refusal, and the chat's metric counts it as refused, like a world line would be. The line goes through the chat's cleaning, which turns control characters into spaces, trims the ends, and refuses a line that's empty or over two hundred bytes, and a refused line is counted too. A line that's said counts as said, whichever channel it's on. The line has the speaker's name, the cleaned text, and the guild's channel, and the server's log gets it, with the guild's name in square brackets, like a channel in most other games. It's serialized once, for all of them, like the world's chat, and each member here gets a shared pointer to those bytes, over their TCP session, counted in our metrics. The world's chat waits for the end of the tick and goes out in one batch, while this goes at once. A guild is a hundred players at most, so sending straight away is cheap, and it means a guild's line doesn't wait behind the world's.

50:05 On the client, the chat window's header file brings in string view, and declares Guild line, a free function outside the class, so a test can call it without a window. Over it, we write what it gives: what a line typed in the chat says to the guild, when it starts with slash g and a space, even if that's nothing, which the server drops. Or it gives nothing at all, for a line to the world. In the chat window, the corner shows a guild's lines in the game. The guild gets a colour of its own, a soft green, which nothing else in the chat uses, next to the orange of a player's name and the gold of the server's lines. Guild line looks for slash g and a space at the start, with starts with, which string views have had since C++20, and without them, the line is for the world. Otherwise, it's what comes after the command, copied into a string of its own. So slash g and a space, with nothing after them, is still a line for the guild, an empty one the server drops, and doesn't land in the world's chat. I went with a slash command, as most other games use one, and players type it without looking. When the lines are drawn, a guild's line pushes the green as the text colour, for its name and its words, so the whole line stands apart from the world's. Its name goes after Guild, in square brackets, in the bold face, while a world line keeps the name in orange. The words go after it, wrapped, as before, and the colour's popped once they're drawn, so the next line starts clean. And the field's hint says slash g is for your guild, as a player wouldn't guess it otherwise. In the client's main, a line the chat returns goes through Guild line. A line for the guild becomes a guild action with say, carrying the words without the command, and anything else is said to the world, as before. Either way, it goes with what we sent last, so we keep moving as we were. The keys' page gets a seventeenth row: Enter, then slash g and a space, talks to your guild. And the client's tests get a new file, for the chat window's test.

52:07 Testing it starts on the client, where the slash command is read, in a new test file for the chat window, which brings in its header and GoogleTest. The test is a list of lines a player could type. First, a line after slash g goes to the guild, without the command, and a line without it goes to the world. Slash g and a space, alone, gives an empty line for the guild. Over that, we write why: nothing for the guild is still for the guild, not the world, and the server drops it. Then slash go away, which starts with the letters but not the space, goes to the world. That last case is the one I'd get wrong by checking for slash g alone, and a line that starts with a word like go would end up in the guild's chat. In the server test, the test player keeps what players said that it heard, oldest first, apart from the server's notices. A line with a name goes there, while a line from nobody is still a notice, and the test player keeps the heard lines in a vector, next to the notices. The test needs a third player, carol, who's in no guild, so it makes her an account of her own with New account, which tear down deletes with the others. Then alice joins, then bob, each over TLS, as a test player of their own, on the fixture's server, which is the one in the test's world, with a token the fixture made for each. Last of all, carol joins, the one we're going to check didn't hear the guild. The test waits until each of them has had their first guild news. Then alice founds Iron Wolves, and the test waits until she's in it. She asks bob in, by his name, and the test waits until his invitation arrives. Then bob says yes, and the test waits for his guild news. That's all set-up, from the last test, and each step waits for its answer before the next goes, as the next depends on it. Then alice says meet at the Crypt gate, to the guild, and the test runs until bob has heard a line. It's from alice, by her name, it says meet at the Crypt gate, and it's on the guild's channel, so the client would draw it in green. Without the channel check, a server that put the line on the world's channel would pass the rest of this part. After that, alice says hello all to the world, in an input of its own. The test waits until carol has heard something, and then checks she heard one line, and that it's hello all. What alice says reaches carol over one connection, in order, so if the guild's line had reached her, it would have come first, and she'd have heard two. That's how the test checks that something didn't arrive, without waiting a second for nothing.

54:38 For the guild's chat, arthur and gwen are both in Iron Wolves, at this step. A line from gwen to the guild comes in green, after Guild in square brackets. A reply that starts with slash g goes to the server as a guild action, and comes straight back to the guild's players, in green too. A line without it goes to everyone in the world, with arthur's name in orange, at the end of the server's tick.

Leaving

55:06 Last, leaving, which turned out to be the part I had to think about most, as a guild can't be left without a leader. In our proto file, a guild action can leave the guild, a bool like accept, as there's nothing more to say than yes. In the guilds' header file, Left is what leaving did. It holds the guild and its name, so the server can tell the guild. Then who leads it now, by their character's id and name, when the one who left led it, and someone's still in it. And ended says whether they were the last one in it, so it's gone. Leave guild is a free function that takes the database. When the one leaving leads the guild, the one who's been in it longest leads it now, an officer before a member, and the last one out ends it. A not found error says they're in none. It runs in a transaction its caller has begun, which is Leave's own, or a character's deletion. That way a guild keeps a leader, and when a leader's character is deleted, the hand-over and the delete commit together, or neither does. It's outside the class, as Characters, which has a database and no Redis, calls it too. And the class gets Leave, which leaves as Leave guild says, in a transaction, so the server can go through Guilds, as it does for the rest. In guilds, Leave opens the transaction, and runs Leave guild inside it, keeping what it returns, so a guild can't be left half done. Leave guild's answer goes into a status or that Leave declares before the transaction, as the lambda returns a status, and not a Left. A failed transaction is Leave's answer, and otherwise it's what Leave guild returned. Leave guild starts with an empty Left, and runs its statements on the database it's given, in the caller's transaction. It finds the player's guild first, with a plain select, without a lock yet, as we don't know which guild's row to lock until we've read it. A failed select returns its error, as each statement here does. None, or an id that isn't a number, is not found, in a player's words. Reading it without a lock is safe, as we read the member's row again once the guild is locked. Then it locks the guild's row, with select for update, as each change to a guild does. Over it, we write the order: the guild's row first, then the member's, which another transaction may have changed between our first select and our getting the guild's lock. So the member's row is read again, locked this time, and in this guild. Those two locks go in one order, the guild's first, in each change to a guild. If one transaction locked a member first and then the guild, while another locked the guild and then that member, each could hold what the other one waits for. That's a deadlock, and MySQL would roll one of them back. Taking the guild's lock first, everywhere, rules that out. Either select failing returns its error, and either one missing means they're in no guild by now. We keep the guild's name, for the news. Then the member's row is deleted, so they're out of the guild. If they weren't the leader, it returns what it has, and the caller's transaction commits. Otherwise, we pick who leads next, with one more select. It joins players, for the successor's name, and takes the guild's members, ordered by grade, highest first, then by joined at, and then by the player's id, to settle a tie, and limit one keeps the first. It locks that row too, as we're about to change it. The rule in words is the highest rank left, and of those, who joined first. That's why joined at kept milliseconds, back in the migration. I thought about making the leader pick a successor before leaving. But a character can be deleted too, and the guild needs a leader either way, so a rule decides. With nobody left, the guild ends: ended is set, its row is deleted, and its name is free again, while an error there stops it. Otherwise we read the successor's id, and keep their name, for the news the guild hears. And their grade goes up to the leader's, where an error stops it, like each statement before it. Then Leave guild returns Left, and the caller's transaction commits. In characters, we bring in the guilds' header, as Delete now leaves the character's guild as it deletes them. Delete becomes a transaction, with World of, Leave guild and the delete inside it. It's the account's own, which hands on a guild it leads as it goes, in one transaction, so the guild doesn't change unless the character goes. World of checks the character is the account's own first, so a request for someone else's character changes nothing. A not found from Leave guild is fine, as most characters aren't in a guild, and any other error stops the delete, and undoes what Leave guild did. Without this, the foreign key's cascade would delete the leader's row along with the character, and leave the guild without a leader. The delete is as it was, moved into the lambda. In the server's header file, Quit guild has a player leave theirs. In the server, leave goes to Quit guild, and the corner shows a leader leaving, in the game. Quit guild asks Guilds to leave, and Refuse says why when it can't. Then their membership goes, and their guild news says they're in none. The guild's news is who left, and which guild. When there's a successor, it adds who leads it now. If they're playing here, their membership becomes the leader's, and their guild news goes out, so their window changes at once. A successor playing on another instance sees it when they next join, which is good enough for now. Then the guild hears it, and the one who left hears that they left, or that they were the last in it, so it's no more. And in the guild window, Leave the guild goes at the bottom, under a little space, for any rank, as a plain button.

1:00:48 Leaving gets three tests in Guilds and one over the network, as a guild left without a leader would be stuck for good. The fixture keeps the account's id, for deleting a character later on. In the first test, alice founds Iron Wolves. Then a loop goes over bob and dave, in that order, and for each, alice asks them in, and they accept, so bob joins first. When alice leaves, Left says bob leads it now, and over that check, we note that bob joined before dave. It hasn't ended, as two are still in it. Then the database agrees: alice is in no guild, bob is the leader, and dave is still a member. The check on dave catches an update that promoted everyone left, which would still give the guild a leader. The second test has alice found a guild, Iron Wolves, and leave it straight away, alone in it. Left says it ended, which is what tells the server to say so, and leaving again is not found, as she's in none. The last check is that bob can found Iron Wolves straight after, which shows the guild's row went, and its name with it. The third test is the one Characters needed. This time, alice founds Iron Wolves, and bob joins as a member. Then Characters deletes alice, with the account's id, as an account deletes its own characters and nobody else's, and that has to work. Afterwards, bob is the leader, which is the case the foreign key's cascade alone would have got wrong. In the server test, a last test plays it out over the network, with the guild news and the notices. First, alice and bob join, as two players over TLS, and wait for their first guild news, which says they're in none. That first message is how the test knows both have joined the world, and not just connected. Then alice founds Iron Wolves, with a guild action sent like a client's, and the test waits until her news says she's in it. She asks bob in, the test waits for his invitation, and once bob says yes, it waits until he's in the guild, so that he's the one left when alice goes. Then alice sends a leave action, like the button would. The test runs until two things are true: alice's guild news has no name, and bob's says he's the leader, as he's playing on this server, so the news reaches him at once. Last, the test builds the news it expects, word for word: alice left Iron Wolves, and bob leads it now. And it waits until that's the last notice bob heard.

1:03:13 We run the guilds' tests at this step, with the server's test of leaving, against MySQL and Redis in Compose. The guild goes to who joined first, and ends with the last one out, and a deleted leader hands it on, so all eleven pass.

1:03:29 For leaving, gwen leads Iron Wolves this time, and arthur is in it as a member. The window has the guild's name, the rank, and a button to leave. When gwen leaves, the guild goes to arthur, the one still in it. The chat says so, the window turns into the leader's, with the field to ask people in, and the next full world takes the guild from under her name. With arthur the last one out, the guild ends, and its name is free in Ember again.

Wrap-up

1:04:00 So, today, guilds went into MySQL, a transaction for each change, with a unique key that keeps a name the world's once, whatever its case. A window on G founds one, and its name goes under yours, over your head, with the full world each second. Officers and the leader ask players in, with an invitation that waits a minute in Redis, or until a no frees the player for another guild, and joining locks the guild's row first. Slash g talks to the guild alone, in green, and when the leader leaves, the guild goes to whoever's been in longest, or ends with the last one out.

Playing it

1:05:26 Tell me in the comments what you'd want from a guild in a game like this, or what you'd like to see next. And if you want to follow along with the series, subscribe to the channel. I hope you find this useful, and thanks for watching.