@nano133/nanoterra 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +133 -8
- package/ai/SPEC.md +25 -3
- package/dist/admin/adapters/d1.d.ts +1 -0
- package/dist/admin/adapters/d1.js +6 -4
- package/dist/admin/adapters/firestore.d.ts +1 -0
- package/dist/admin/adapters/firestore.js +7 -5
- package/dist/admin/conformance.d.ts +1 -1
- package/dist/admin/conformance.js +13 -5
- package/dist/admin/handler.d.ts +1 -1
- package/dist/admin/handler.js +3 -3
- package/dist/admin/index.d.ts +2 -2
- package/dist/admin/index.js +2 -2
- package/dist/admin/memory.js +3 -1
- package/dist/admin/panel/gameCard.d.ts +1 -1
- package/dist/admin/panel/gameCard.js +56 -6
- package/dist/admin/panel/mount.js +1 -1
- package/dist/admin/panel/overview.d.ts +1 -1
- package/dist/admin/panel/overview.js +4 -2
- package/dist/admin/store.d.ts +2 -1
- package/dist/admin/switches.d.ts +23 -1
- package/dist/admin/switches.js +26 -5
- package/dist/friends/adapters/d1.d.ts +4 -0
- package/dist/friends/adapters/d1.js +131 -0
- package/dist/friends/adapters/firestore.d.ts +49 -0
- package/dist/friends/adapters/firestore.js +163 -0
- package/dist/friends/conformance.d.ts +11 -0
- package/dist/friends/conformance.js +229 -0
- package/dist/friends/handler.d.ts +31 -0
- package/dist/friends/handler.js +139 -0
- package/dist/friends/index.d.ts +8 -0
- package/dist/friends/index.js +12 -0
- package/dist/friends/memory.d.ts +9 -0
- package/dist/friends/memory.js +79 -0
- package/dist/friends/panel/index.d.ts +4 -0
- package/dist/friends/panel/index.js +10 -0
- package/dist/friends/panel/mount.d.ts +38 -0
- package/dist/friends/panel/mount.js +321 -0
- package/dist/friends/panel/window.d.ts +52 -0
- package/dist/friends/panel/window.js +72 -0
- package/dist/friends/rules.d.ts +92 -0
- package/dist/friends/rules.js +180 -0
- package/dist/friends/types.d.ts +58 -0
- package/dist/friends/types.js +24 -0
- package/package.json +11 -4
- package/src/admin/adapters/d1.ts +5 -4
- package/src/admin/adapters/firestore.ts +6 -5
- package/src/admin/conformance.ts +15 -6
- package/src/admin/handler.ts +3 -3
- package/src/admin/index.ts +3 -3
- package/src/admin/memory.ts +2 -1
- package/src/admin/panel/gameCard.ts +52 -6
- package/src/admin/panel/mount.ts +1 -1
- package/src/admin/panel/overview.ts +4 -3
- package/src/admin/panel/style.css +10 -1
- package/src/admin/store.ts +2 -2
- package/src/admin/switches.ts +35 -9
- package/src/friends/adapters/d1.sql +33 -0
- package/src/friends/adapters/d1.ts +146 -0
- package/src/friends/adapters/firestore.ts +197 -0
- package/src/friends/conformance.ts +260 -0
- package/src/friends/handler.ts +144 -0
- package/src/friends/index.ts +17 -0
- package/src/friends/memory.ts +83 -0
- package/src/friends/panel/index.ts +13 -0
- package/src/friends/panel/mount.ts +346 -0
- package/src/friends/panel/style.css +303 -0
- package/src/friends/panel/window.ts +79 -0
- package/src/friends/rules.ts +196 -0
- package/src/friends/types.ts +57 -0
package/src/admin/store.ts
CHANGED
|
@@ -48,13 +48,13 @@ export type AdminLogin = { at: number; country: string | null; browser: string }
|
|
|
48
48
|
export const ADMIN_LOGINS_SHOWN = 10;
|
|
49
49
|
|
|
50
50
|
/**
|
|
51
|
-
* The game's database, as the handler needs it. An adapter writes ONLY what these calls say: the
|
|
51
|
+
* The game's database, as the handler needs it. An adapter writes ONLY what these calls say: the three settings and, when the game turns it on, the deletion of the admin sessions
|
|
52
52
|
* (`signOutEverywhere`). Nothing else.
|
|
53
53
|
* (There is no call that writes a look, a price or an order: the Shelf gives text to copy, and a change of looks is a change of the repository.)
|
|
54
54
|
*/
|
|
55
55
|
export interface AdminStore {
|
|
56
56
|
/** The settings that /admin has saved. A value that is not a known word is ignored by the handler, so an adapter returns what it holds. */
|
|
57
|
-
readSettings(): Promise<{ character?: unknown; signin?: unknown }>;
|
|
57
|
+
readSettings(): Promise<{ character?: unknown; signin?: unknown; friends?: unknown }>;
|
|
58
58
|
/** Saves a checked patch: all of it or none of it. */
|
|
59
59
|
saveSettings(patch: GamePatch, now: number): Promise<void>;
|
|
60
60
|
summary(now: number): Promise<StoreSummary>;
|
package/src/admin/switches.ts
CHANGED
|
@@ -1,46 +1,72 @@
|
|
|
1
|
-
// The
|
|
2
|
-
// draws the card from `SWITCHES`. A switch changes ONLY these
|
|
1
|
+
// The switches of the "Game" card in /admin, and the words that say what each does. The handler checks a press with `parsePatch`; the panel
|
|
2
|
+
// draws the card from `SWITCHES` and `FRIENDS_CHOICES`. A switch changes ONLY these three settings; never a look, a price or an order.
|
|
3
3
|
|
|
4
4
|
/** Which character the player is: Nanoterra's island character (the one the player has there) or the game's own. */
|
|
5
5
|
export type Character = "nanoterra" | "own";
|
|
6
6
|
/** How the game signs a Nanoterra player in: the code exchange, a signed ticket (a game with no server), or not at all. */
|
|
7
7
|
export type Signin = "exchange" | "ticket" | "none";
|
|
8
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Which friends list the game shows: Nanoterra's (the nano133 window, "@nano133/nanoterra/friends/panel"), the game's own (its own players and store), or none.
|
|
10
|
+
* A three-way choice, not an On/Off switch.
|
|
11
|
+
*/
|
|
12
|
+
export type Friends = "nanoterra" | "own" | "off";
|
|
13
|
+
/** The game's own words for the switches. `friends` may be left out: it is "nanoterra" then (on by default). */
|
|
14
|
+
export type GameSettings = { character: Character; signin: Signin; friends?: Friends };
|
|
9
15
|
/** What a press can set: sign-in is on ("exchange": a game with a server) or off ("none"). */
|
|
10
|
-
export type GamePatch = { character?: Character; signin?: "exchange" | "none" };
|
|
16
|
+
export type GamePatch = { character?: Character; signin?: "exchange" | "none"; friends?: Friends };
|
|
11
17
|
/** The settings as they are now, and which ones /admin has set (the others still have the game's default). */
|
|
12
|
-
export type GameState =
|
|
18
|
+
export type GameState = { character: Character; signin: Signin; friends: Friends; fromAdmin: { character: boolean; signin: boolean; friends: boolean } };
|
|
13
19
|
|
|
14
20
|
export const isCharacter = (v: unknown): v is Character => v === "nanoterra" || v === "own";
|
|
15
21
|
export const isSigninChoice = (v: unknown): v is "exchange" | "none" => v === "exchange" || v === "none";
|
|
16
22
|
export const isSignin = (v: unknown): v is Signin => v === "exchange" || v === "ticket" || v === "none";
|
|
23
|
+
export const isFriends = (v: unknown): v is Friends => v === "nanoterra" || v === "own" || v === "off";
|
|
24
|
+
/** The friends list a game shows while neither its own words nor /admin say: Nanoterra's. */
|
|
25
|
+
export const DEFAULT_FRIENDS: Friends = "nanoterra";
|
|
17
26
|
/** The sign-in switch is on for any way but "none". */
|
|
18
27
|
export const signinOn = (s: Signin): boolean => s !== "none";
|
|
19
28
|
|
|
20
29
|
/** A request body for a press: only the two known words, at least one. Anything else is refused, with the reason in words. */
|
|
21
30
|
export function parsePatch(body: unknown): { ok: true; patch: GamePatch } | { ok: false; error: string } {
|
|
22
|
-
if (!body || typeof body !== "object" || Array.isArray(body)) return { ok: false, error: 'Send an object with "character" or "
|
|
31
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) return { ok: false, error: 'Send an object with "character", "signin" or "friends".' };
|
|
23
32
|
const patch: GamePatch = {};
|
|
24
33
|
for (const [key, value] of Object.entries(body as Record<string, unknown>)) {
|
|
25
34
|
if (key === "character" && isCharacter(value)) patch.character = value;
|
|
26
35
|
else if (key === "signin" && isSigninChoice(value)) patch.signin = value;
|
|
36
|
+
else if (key === "friends" && isFriends(value)) patch.friends = value;
|
|
37
|
+
else if (key === "friends") return { ok: false, error: '"friends" must be "nanoterra", "own" or "off".' };
|
|
27
38
|
else if (key === "character") return { ok: false, error: '"character" must be "nanoterra" or "own".' };
|
|
28
39
|
else if (key === "signin") return { ok: false, error: '"signin" must be "exchange" or "none".' };
|
|
29
40
|
else return { ok: false, error: `"${key}" is not a game switch.` };
|
|
30
41
|
}
|
|
31
|
-
if (!Object.keys(patch).length) return { ok: false, error: 'Send "character" or "
|
|
42
|
+
if (!Object.keys(patch).length) return { ok: false, error: 'Send "character", "signin" or "friends".' };
|
|
32
43
|
return { ok: true, patch };
|
|
33
44
|
}
|
|
34
45
|
|
|
35
46
|
/** The settings from what the store kept and the game's defaults. A stored value that is not one of the known words is ignored. */
|
|
36
|
-
export function mergeSettings(stored: { character?: unknown; signin?: unknown }, defaults: GameSettings): GameState {
|
|
47
|
+
export function mergeSettings(stored: { character?: unknown; signin?: unknown; friends?: unknown }, defaults: GameSettings): GameState {
|
|
37
48
|
return {
|
|
38
49
|
character: isCharacter(stored.character) ? stored.character : defaults.character,
|
|
39
50
|
signin: isSigninChoice(stored.signin) ? stored.signin : defaults.signin,
|
|
40
|
-
|
|
51
|
+
friends: isFriends(stored.friends) ? stored.friends : isFriends(defaults.friends) ? defaults.friends : DEFAULT_FRIENDS,
|
|
52
|
+
fromAdmin: { character: isCharacter(stored.character), signin: isSigninChoice(stored.signin), friends: isFriends(stored.friends) },
|
|
41
53
|
};
|
|
42
54
|
}
|
|
43
55
|
|
|
56
|
+
/** The friends choice of the card: its title, and for each choice its short name (the card's three keys) and one plain sentence. Nanoterra's is the default. */
|
|
57
|
+
export const FRIENDS_TITLE = "Friends list";
|
|
58
|
+
export const FRIENDS_CHOICES: Record<Friends, { name: string; note: string }> = {
|
|
59
|
+
nanoterra: {
|
|
60
|
+
name: "Nanoterra",
|
|
61
|
+
note: "Nanoterra: a player signed in on nano133 sees their Nanoterra friends in a small nano133 frame in your game, and their friends see that they are playing it. The friends stay on nano133: your game gets none of them.",
|
|
62
|
+
},
|
|
63
|
+
own: {
|
|
64
|
+
name: "The game's own",
|
|
65
|
+
note: "The game's own: a friends list of this game's players, kept in this game's own database. Nanoterra friends do not show.",
|
|
66
|
+
},
|
|
67
|
+
off: { name: "Off", note: "Off: the game shows no friends list." },
|
|
68
|
+
};
|
|
69
|
+
|
|
44
70
|
/** One switch of the card: its title, and one plain sentence for each state. */
|
|
45
71
|
export type SwitchId = "character" | "signin";
|
|
46
72
|
export const SWITCHES: Record<SwitchId, { title: string; on: string; off: string }> = {
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
-- The friends tables of "@nano133/nanoterra/friends/d1". Add this file to the game's migrations (for example migrations/0005_friends.sql) and run
|
|
2
|
+
-- `wrangler d1 migrations apply`. The adapter reads and writes only these three tables.
|
|
3
|
+
|
|
4
|
+
-- One row for each pair of players (a < b): a request, a friendship or a block. `edge` is the opaque id the browser sees.
|
|
5
|
+
CREATE TABLE IF NOT EXISTS friend_edges (
|
|
6
|
+
edge TEXT PRIMARY KEY,
|
|
7
|
+
a TEXT NOT NULL,
|
|
8
|
+
b TEXT NOT NULL,
|
|
9
|
+
from_player TEXT NOT NULL,
|
|
10
|
+
state TEXT NOT NULL CHECK (state IN ('pending', 'friend', 'blocked')),
|
|
11
|
+
blocked_by TEXT NOT NULL DEFAULT '[]',
|
|
12
|
+
at INTEGER NOT NULL,
|
|
13
|
+
invite_from TEXT,
|
|
14
|
+
invite_where TEXT,
|
|
15
|
+
invite_at INTEGER,
|
|
16
|
+
rev INTEGER NOT NULL DEFAULT 1,
|
|
17
|
+
UNIQUE (a, b)
|
|
18
|
+
);
|
|
19
|
+
CREATE INDEX IF NOT EXISTS friend_edges_b ON friend_edges (b);
|
|
20
|
+
|
|
21
|
+
-- Where a player is now, and which tab said so. A row older than two minutes does not count.
|
|
22
|
+
CREATE TABLE IF NOT EXISTS friend_presence (
|
|
23
|
+
player TEXT PRIMARY KEY,
|
|
24
|
+
place TEXT NOT NULL,
|
|
25
|
+
lease TEXT NOT NULL,
|
|
26
|
+
at INTEGER NOT NULL
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
-- A player's "show me online" choice (1 or 0). No row: shown.
|
|
30
|
+
CREATE TABLE IF NOT EXISTS friend_prefs (
|
|
31
|
+
player TEXT PRIMARY KEY,
|
|
32
|
+
show_online INTEGER NOT NULL DEFAULT 1
|
|
33
|
+
);
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// The friends store for a game on Cloudflare D1. The tables are in ./d1.sql (the package ships it: "@nano133/nanoterra/friends/d1.sql"); add it to
|
|
2
|
+
// the game's migrations. It reads and writes ONLY friend_edges, friend_presence and friend_prefs.
|
|
3
|
+
//
|
|
4
|
+
// import { createD1Friends } from "@nano133/nanoterra/friends/d1";
|
|
5
|
+
// const friends = createD1Friends(env.DB);
|
|
6
|
+
//
|
|
7
|
+
// D1 has no transaction that reads and then writes, so each write is ONE statement that holds its own check: a change of an edge says which `rev`
|
|
8
|
+
// it read (a row that changed in between is not written, and the player is asked to try again), and a new edge is written only while both players
|
|
9
|
+
// have room (the count is in the same statement) and the pair has no row yet (UNIQUE (a, b)).
|
|
10
|
+
|
|
11
|
+
import type { D1Like } from "../../admin/adapters/d1.js";
|
|
12
|
+
import { buildRows, checkPulse, pairOf, planAccept, planBlock, planDecline, planInvite, planRemove, planRequest, planUnblock, shownOthers, type EdgeRec, type Plan, type PresenceRec } from "../rules.js";
|
|
13
|
+
import { FRIEND_LIMIT, FRIEND_REQUEST_MS, FriendsError, type FriendView, type FriendsStore, type PlayerDirectory } from "../types.js";
|
|
14
|
+
|
|
15
|
+
export type { D1Like, D1StatementLike } from "../../admin/adapters/d1.js";
|
|
16
|
+
|
|
17
|
+
type Row = { edge: string; a: string; b: string; from_player: string; state: string; blocked_by: string; at: number; invite_from: string | null; invite_where: string | null; invite_at: number | null; rev: number };
|
|
18
|
+
|
|
19
|
+
const COLS = "edge, a, b, from_player, state, blocked_by, at, invite_from, invite_where, invite_at, rev";
|
|
20
|
+
|
|
21
|
+
function recOf(r: Row): EdgeRec {
|
|
22
|
+
let blockedBy: string[] = [];
|
|
23
|
+
try {
|
|
24
|
+
const v: unknown = JSON.parse(r.blocked_by);
|
|
25
|
+
if (Array.isArray(v)) blockedBy = v.filter((x): x is string => typeof x === "string");
|
|
26
|
+
} catch {
|
|
27
|
+
blockedBy = [];
|
|
28
|
+
}
|
|
29
|
+
const state = r.state === "friend" || r.state === "blocked" ? r.state : "pending";
|
|
30
|
+
const invite = typeof r.invite_from === "string" && typeof r.invite_where === "string" && typeof r.invite_at === "number" ? { from: r.invite_from, where: r.invite_where, at: Number(r.invite_at) } : null;
|
|
31
|
+
return { edge: r.edge, a: r.a, b: r.b, from: r.from_player, state, blockedBy, at: Number(r.at), invite, rev: Number(r.rev) };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const CHANGED = "That changed just now. Try again.";
|
|
35
|
+
|
|
36
|
+
export function createD1Friends(db: D1Like): FriendsStore {
|
|
37
|
+
const changes = (res: unknown): number => Number((res as { meta?: { changes?: number } } | undefined)?.meta?.changes ?? 0);
|
|
38
|
+
const byEdge = async (edge: string) => {
|
|
39
|
+
const r = await db.prepare(`SELECT ${COLS} FROM friend_edges WHERE edge = ?`).bind(edge).first<Row>();
|
|
40
|
+
return r ? recOf(r) : null;
|
|
41
|
+
};
|
|
42
|
+
const byPair = async (x: string, y: string) => {
|
|
43
|
+
const [a, b] = pairOf(x, y);
|
|
44
|
+
const r = await db.prepare(`SELECT ${COLS} FROM friend_edges WHERE a = ? AND b = ?`).bind(a, b).first<Row>();
|
|
45
|
+
return r ? recOf(r) : null;
|
|
46
|
+
};
|
|
47
|
+
/** Live edges of a player, as SQL (?1 the player, ?2 the oldest request time that still counts). */
|
|
48
|
+
const LIVE_COUNT = "(SELECT COUNT(*) FROM friend_edges WHERE (a = ?1 OR b = ?1) AND (state != 'pending' OR at > ?2))";
|
|
49
|
+
const liveCount = async (player: string, now: number) => Number((await db.prepare(`SELECT ${LIVE_COUNT} AS n`).bind(player, now - FRIEND_REQUEST_MS).first<{ n: number }>())?.n ?? 0);
|
|
50
|
+
|
|
51
|
+
async function apply(plan: Plan, prev: EdgeRec | null, now: number): Promise<void> {
|
|
52
|
+
if ("none" in plan) return;
|
|
53
|
+
if ("drop" in plan) {
|
|
54
|
+
if (changes(await db.prepare("DELETE FROM friend_edges WHERE edge = ? AND rev = ?").bind(plan.drop.edge, plan.drop.rev).run()) !== 1) throw new FriendsError(409, CHANGED);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const r = plan.put;
|
|
58
|
+
const inv = r.invite;
|
|
59
|
+
if (prev && prev.edge === r.edge) {
|
|
60
|
+
const res = await db
|
|
61
|
+
.prepare("UPDATE friend_edges SET from_player = ?, state = ?, blocked_by = ?, at = ?, invite_from = ?, invite_where = ?, invite_at = ?, rev = ? WHERE edge = ? AND rev = ?")
|
|
62
|
+
.bind(r.from, r.state, JSON.stringify(r.blockedBy), r.at, inv?.from ?? null, inv?.where ?? null, inv?.at ?? null, r.rev, r.edge, prev.rev)
|
|
63
|
+
.run();
|
|
64
|
+
if (changes(res) !== 1) throw new FriendsError(409, CHANGED);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
// A new edge: only while both players have room, in the same statement (the pair's UNIQUE (a, b) refuses a second row).
|
|
68
|
+
const cut = now - FRIEND_REQUEST_MS;
|
|
69
|
+
const other = r.from === r.a ? r.b : r.a;
|
|
70
|
+
const sql =
|
|
71
|
+
`INSERT INTO friend_edges (${COLS}) SELECT ?3, ?4, ?5, ?6, ?7, ?8, ?9, NULL, NULL, NULL, ?10 ` +
|
|
72
|
+
`WHERE (SELECT COUNT(*) FROM friend_edges WHERE (a = ?1 OR b = ?1) AND (state != 'pending' OR at > ?11)) < ?12 ` +
|
|
73
|
+
`AND (SELECT COUNT(*) FROM friend_edges WHERE (a = ?2 OR b = ?2) AND (state != 'pending' OR at > ?11)) < ?12 ` +
|
|
74
|
+
`ON CONFLICT (a, b) DO NOTHING`;
|
|
75
|
+
const res = await db.prepare(sql).bind(r.from, other, r.edge, r.a, r.b, r.from, r.state, JSON.stringify(r.blockedBy), r.at, r.rev, cut, FRIEND_LIMIT).run();
|
|
76
|
+
if (changes(res) !== 1) throw new FriendsError(409, CHANGED);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function onEdge(_player: string, edge: string, plan: (rec: EdgeRec | null) => Plan, now: number) {
|
|
80
|
+
const rec = await byEdge(edge);
|
|
81
|
+
await apply(plan(rec), rec, now);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return {
|
|
85
|
+
async view(player: string, directory: PlayerDirectory, now: number): Promise<FriendView> {
|
|
86
|
+
const recs = (await db.prepare(`SELECT ${COLS} FROM friend_edges WHERE a = ?1 OR b = ?1`).bind(player).all<Row>()).results.map(recOf);
|
|
87
|
+
// The presence and the choice of the player's friends, in one statement each (a friend's id is the other side of a friend edge).
|
|
88
|
+
const OTHER = "CASE WHEN e.a = ?1 THEN e.b ELSE e.a END";
|
|
89
|
+
const pres = (
|
|
90
|
+
await db
|
|
91
|
+
.prepare(`SELECT p.player, p.place, p.lease, p.at FROM friend_edges e JOIN friend_presence p ON p.player = ${OTHER} WHERE (e.a = ?1 OR e.b = ?1) AND e.state = 'friend'`)
|
|
92
|
+
.bind(player)
|
|
93
|
+
.all<{ player: string; place: string; lease: string; at: number }>()
|
|
94
|
+
).results;
|
|
95
|
+
const hidden = (
|
|
96
|
+
await db.prepare(`SELECT f.player FROM friend_edges e JOIN friend_prefs f ON f.player = ${OTHER} WHERE (e.a = ?1 OR e.b = ?1) AND e.state = 'friend' AND f.show_online = 0`).bind(player).all<{ player: string }>()
|
|
97
|
+
).results;
|
|
98
|
+
const me = await db.prepare("SELECT show_online FROM friend_prefs WHERE player = ?").bind(player).first<{ show_online: number }>();
|
|
99
|
+
const names = await directory.names(shownOthers(player, recs, now));
|
|
100
|
+
const presence = new Map<string, PresenceRec>(pres.map((p) => [p.player, { player: p.player, where: p.place, lease: p.lease, at: Number(p.at) }]));
|
|
101
|
+
const shows = new Map<string, boolean>(hidden.map((x) => [x.player, false]));
|
|
102
|
+
return { showOnline: !me || Number(me.show_online) !== 0, people: buildRows(player, recs, now, names, presence, shows) };
|
|
103
|
+
},
|
|
104
|
+
|
|
105
|
+
async request(player, other, now) {
|
|
106
|
+
const rec = await byPair(player, other);
|
|
107
|
+
const plan = await planRequest(player, other, rec, now, async () => ({ mine: await liveCount(player, now), theirs: await liveCount(other, now) }));
|
|
108
|
+
// A request that went stale is still the pair's row: it is changed in place (its count is the one just read).
|
|
109
|
+
await apply(plan, rec, now);
|
|
110
|
+
},
|
|
111
|
+
accept: (player, edge, now) => onEdge(player, edge, (r) => planAccept(player, r, now), now),
|
|
112
|
+
decline: (player, edge) => onEdge(player, edge, (r) => planDecline(player, r, Date.now()), Date.now()),
|
|
113
|
+
remove: (player, edge) => onEdge(player, edge, (r) => planRemove(player, r, Date.now()), Date.now()),
|
|
114
|
+
block: (player, edge, now) => onEdge(player, edge, (r) => planBlock(player, r, now), now),
|
|
115
|
+
unblock: (player, edge, now) => onEdge(player, edge, (r) => planUnblock(player, r, now), now),
|
|
116
|
+
invite: (player, edge, where, now) => onEdge(player, edge, (r) => planInvite(player, r, where, now), now),
|
|
117
|
+
|
|
118
|
+
async pulse(player, where, lease, now) {
|
|
119
|
+
const p = checkPulse(where, lease);
|
|
120
|
+
if (p.where !== null) {
|
|
121
|
+
await db
|
|
122
|
+
.prepare("INSERT INTO friend_presence (player, place, lease, at) VALUES (?, ?, ?, ?) ON CONFLICT (player) DO UPDATE SET place = excluded.place, lease = excluded.lease, at = excluded.at")
|
|
123
|
+
.bind(player, p.where, p.lease, now)
|
|
124
|
+
.run();
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
// Leaving: only the tab that holds the row may clear it (planPulse's rule, in the statement).
|
|
128
|
+
await db.prepare("DELETE FROM friend_presence WHERE player = ? AND lease = ?").bind(player, p.lease).run();
|
|
129
|
+
},
|
|
130
|
+
|
|
131
|
+
async setShowOnline(player, on) {
|
|
132
|
+
const stmts = [db.prepare("INSERT INTO friend_prefs (player, show_online) VALUES (?, ?) ON CONFLICT (player) DO UPDATE SET show_online = excluded.show_online").bind(player, on ? 1 : 0)];
|
|
133
|
+
if (!on) stmts.push(db.prepare("DELETE FROM friend_presence WHERE player = ?").bind(player));
|
|
134
|
+
await db.batch(stmts);
|
|
135
|
+
},
|
|
136
|
+
|
|
137
|
+
async forget(player) {
|
|
138
|
+
const done = await db.batch([
|
|
139
|
+
db.prepare("DELETE FROM friend_edges WHERE a = ?1 OR b = ?1").bind(player),
|
|
140
|
+
db.prepare("DELETE FROM friend_presence WHERE player = ?").bind(player),
|
|
141
|
+
db.prepare("DELETE FROM friend_prefs WHERE player = ?").bind(player),
|
|
142
|
+
]);
|
|
143
|
+
return done.reduce<number>((n, r) => n + changes(r), 0);
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// The friends store for a game on Firestore (the Admin SDK). The package has no Firebase dependency: the adapter uses the small interface below,
|
|
2
|
+
// which the Admin SDK's `Firestore` fits. It reads and writes ONLY its three collections.
|
|
3
|
+
//
|
|
4
|
+
// import { createFirestoreFriends } from "@nano133/nanoterra/friends/firestore";
|
|
5
|
+
// const friends = createFirestoreFriends(getFirestore());
|
|
6
|
+
//
|
|
7
|
+
// The data model (the three collection names can be changed):
|
|
8
|
+
// friend_edges/{pair} { edge, a, b, players: [a, b], from, state, blockedBy, at, invite: { from, where, at } | null, rev }
|
|
9
|
+
// friend_presence/{player} { player, where, lease, at }
|
|
10
|
+
// friend_prefs/{player} { player, showOnline }
|
|
11
|
+
// `{pair}` and `{player}` are SHA-256 hex digests (of "a\u0000b" and of the player's id), so any id makes a valid document id, and a pair has one
|
|
12
|
+
// document: two requests at the same moment meet on it in their transactions. `edge` is a random id; the browser sees only that.
|
|
13
|
+
// Indexes: the single-field indexes Firestore makes by itself are enough (`players` array-contains, `edge` ==).
|
|
14
|
+
|
|
15
|
+
import { buildRows, checkPulse, friendsOf, hasPlayer, liveEdge, pairOf, planAccept, planBlock, planDecline, planInvite, planPulse, planRemove, planRequest, planUnblock, shownOthers, type EdgeRec, type Plan, type PresenceRec } from "../rules.js";
|
|
16
|
+
import { FriendsError, type FriendView, type FriendsStore, type PlayerDirectory } from "../types.js";
|
|
17
|
+
|
|
18
|
+
export type FriendsDocSnap = { exists: boolean; data(): Record<string, unknown> | undefined };
|
|
19
|
+
export interface FriendsDocRef {
|
|
20
|
+
get(): Promise<FriendsDocSnap>;
|
|
21
|
+
}
|
|
22
|
+
export type FriendsQuerySnap = { docs: { id: string; ref: FriendsDocRef; data(): Record<string, unknown> }[] };
|
|
23
|
+
export interface FriendsQuery {
|
|
24
|
+
where(field: string, op: "==" | "array-contains", value: unknown): FriendsQuery;
|
|
25
|
+
limit(n: number): FriendsQuery;
|
|
26
|
+
get(): Promise<FriendsQuerySnap>;
|
|
27
|
+
}
|
|
28
|
+
export interface FriendsCollection extends FriendsQuery {
|
|
29
|
+
doc(id: string): FriendsDocRef;
|
|
30
|
+
}
|
|
31
|
+
/** A transaction: every read before the first write, as Firestore asks. */
|
|
32
|
+
export interface FriendsTransaction {
|
|
33
|
+
get(ref: FriendsDocRef): Promise<FriendsDocSnap>;
|
|
34
|
+
get(query: FriendsQuery): Promise<FriendsQuerySnap>;
|
|
35
|
+
set(ref: FriendsDocRef, data: Record<string, unknown>): unknown;
|
|
36
|
+
delete(ref: FriendsDocRef): unknown;
|
|
37
|
+
}
|
|
38
|
+
export interface FriendsBatch {
|
|
39
|
+
set(ref: FriendsDocRef, data: Record<string, unknown>, options?: { merge?: boolean }): unknown;
|
|
40
|
+
delete(ref: FriendsDocRef): unknown;
|
|
41
|
+
commit(): Promise<unknown>;
|
|
42
|
+
}
|
|
43
|
+
export interface FirestoreFriendsLike {
|
|
44
|
+
collection(name: string): FriendsCollection;
|
|
45
|
+
runTransaction<T>(fn: (tx: FriendsTransaction) => Promise<T>): Promise<T>;
|
|
46
|
+
batch(): FriendsBatch;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** How many edges of one player a read takes at most: the limit, the blocks by others and old requests fit under it. */
|
|
50
|
+
export const FIRESTORE_FRIENDS_SCAN = 1000;
|
|
51
|
+
|
|
52
|
+
async function sha256(text: string): Promise<string> {
|
|
53
|
+
const bytes = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
|
|
54
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const text = (v: unknown, fallback = ""): string => (typeof v === "string" ? v : fallback);
|
|
58
|
+
const num = (v: unknown, fallback = 0): number => (typeof v === "number" && Number.isFinite(v) ? v : fallback);
|
|
59
|
+
|
|
60
|
+
function recOf(d: Record<string, unknown>): EdgeRec {
|
|
61
|
+
const inv = d.invite as Record<string, unknown> | null | undefined;
|
|
62
|
+
const state = d.state === "friend" || d.state === "blocked" ? d.state : "pending";
|
|
63
|
+
return {
|
|
64
|
+
edge: text(d.edge),
|
|
65
|
+
a: text(d.a),
|
|
66
|
+
b: text(d.b),
|
|
67
|
+
from: text(d.from),
|
|
68
|
+
state,
|
|
69
|
+
blockedBy: Array.isArray(d.blockedBy) ? d.blockedBy.filter((x): x is string => typeof x === "string") : [],
|
|
70
|
+
at: num(d.at),
|
|
71
|
+
invite: inv && typeof inv.from === "string" && typeof inv.where === "string" && typeof inv.at === "number" ? { from: inv.from, where: inv.where, at: inv.at } : null,
|
|
72
|
+
rev: num(d.rev),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const dataOf = (r: EdgeRec): Record<string, unknown> => ({ edge: r.edge, a: r.a, b: r.b, players: [r.a, r.b], from: r.from, state: r.state, blockedBy: r.blockedBy, at: r.at, invite: r.invite, rev: r.rev });
|
|
77
|
+
|
|
78
|
+
export function createFirestoreFriends(db: FirestoreFriendsLike, collections: { edges?: string; presence?: string; prefs?: string } = {}): FriendsStore {
|
|
79
|
+
const edges = () => db.collection(collections.edges ?? "friend_edges");
|
|
80
|
+
const presenceCol = () => db.collection(collections.presence ?? "friend_presence");
|
|
81
|
+
const prefsCol = () => db.collection(collections.prefs ?? "friend_prefs");
|
|
82
|
+
const pairRef = async (x: string, y: string) => {
|
|
83
|
+
const [a, b] = pairOf(x, y);
|
|
84
|
+
return edges().doc(await sha256(`${a}\u0000${b}`));
|
|
85
|
+
};
|
|
86
|
+
const playerRef = async (col: FriendsCollection, player: string) => col.doc(await sha256(player));
|
|
87
|
+
const ofPlayer = (player: string) => edges().where("players", "array-contains", player).limit(FIRESTORE_FRIENDS_SCAN);
|
|
88
|
+
|
|
89
|
+
/** Writes a plan in the transaction, on the pair's document. */
|
|
90
|
+
async function write(tx: FriendsTransaction, plan: Plan) {
|
|
91
|
+
if ("none" in plan) return;
|
|
92
|
+
const rec = "put" in plan ? plan.put : plan.drop;
|
|
93
|
+
const ref = await pairRef(rec.a, rec.b);
|
|
94
|
+
if ("put" in plan) tx.set(ref, dataOf(plan.put));
|
|
95
|
+
else tx.delete(ref);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** An operation on an edge the browser named: the edge is found, then read again in the transaction on its pair's document. */
|
|
99
|
+
async function onEdge(player: string, edge: string, plan: (rec: EdgeRec | null) => Plan) {
|
|
100
|
+
const found = await edges().where("edge", "==", edge).limit(2).get();
|
|
101
|
+
const first = found.docs.map((d) => recOf(d.data())).find((r) => hasPlayer(r, player));
|
|
102
|
+
if (!first) {
|
|
103
|
+
plan(null);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
const ref = await pairRef(first.a, first.b);
|
|
107
|
+
await db.runTransaction(async (tx) => {
|
|
108
|
+
const snap = await tx.get(ref);
|
|
109
|
+
const now = snap.exists ? recOf(snap.data() ?? {}) : null;
|
|
110
|
+
// The pair's document holds another edge now (it was removed and asked again): the old edge is gone.
|
|
111
|
+
await write(tx, plan(now && now.edge === edge ? now : null));
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const liveOf = (snap: FriendsQuerySnap, now: number) => snap.docs.map((d) => recOf(d.data())).filter((r) => liveEdge(r, now)).length;
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
async view(player: string, directory: PlayerDirectory, now: number): Promise<FriendView> {
|
|
119
|
+
const recs = (await ofPlayer(player).get()).docs.map((d) => recOf(d.data())).filter((r) => hasPlayer(r, player));
|
|
120
|
+
const friends = friendsOf(player, recs, now);
|
|
121
|
+
const [mePref, pres, prefs, names] = await Promise.all([
|
|
122
|
+
(await playerRef(prefsCol(), player)).get(),
|
|
123
|
+
Promise.all(friends.map(async (f) => (await playerRef(presenceCol(), f)).get())),
|
|
124
|
+
Promise.all(friends.map(async (f) => (await playerRef(prefsCol(), f)).get())),
|
|
125
|
+
directory.names(shownOthers(player, recs, now)),
|
|
126
|
+
]);
|
|
127
|
+
const presence = new Map<string, PresenceRec>();
|
|
128
|
+
pres.forEach((s, i) => {
|
|
129
|
+
const d = s.exists ? s.data() : undefined;
|
|
130
|
+
if (d && d.player === friends[i]) presence.set(friends[i], { player: friends[i], where: text(d.where), lease: text(d.lease), at: num(d.at) });
|
|
131
|
+
});
|
|
132
|
+
const shows = new Map<string, boolean>();
|
|
133
|
+
prefs.forEach((s, i) => {
|
|
134
|
+
const d = s.exists ? s.data() : undefined;
|
|
135
|
+
if (d && d.player === friends[i] && d.showOnline === false) shows.set(friends[i], false);
|
|
136
|
+
});
|
|
137
|
+
const mine = mePref.exists ? mePref.data() : undefined;
|
|
138
|
+
return { showOnline: mine?.showOnline !== false, people: buildRows(player, recs, now, names, presence, shows) };
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
async request(player, other, now) {
|
|
142
|
+
if (player === other) throw new FriendsError(400, "You cannot add yourself.");
|
|
143
|
+
const ref = await pairRef(player, other);
|
|
144
|
+
await db.runTransaction(async (tx) => {
|
|
145
|
+
const snap = await tx.get(ref);
|
|
146
|
+
const rec = snap.exists ? recOf(snap.data() ?? {}) : null;
|
|
147
|
+
// The counts are read in the transaction too (every read before the first write).
|
|
148
|
+
const plan = await planRequest(player, other, rec, now, async () => {
|
|
149
|
+
const [mine, theirs] = await Promise.all([tx.get(ofPlayer(player)), tx.get(ofPlayer(other))]);
|
|
150
|
+
return { mine: liveOf(mine, now), theirs: liveOf(theirs, now) };
|
|
151
|
+
});
|
|
152
|
+
await write(tx, plan);
|
|
153
|
+
});
|
|
154
|
+
},
|
|
155
|
+
accept: (player, edge, now) => onEdge(player, edge, (r) => planAccept(player, r, now)),
|
|
156
|
+
decline: (player, edge) => onEdge(player, edge, (r) => planDecline(player, r, Date.now())),
|
|
157
|
+
remove: (player, edge) => onEdge(player, edge, (r) => planRemove(player, r, Date.now())),
|
|
158
|
+
block: (player, edge, now) => onEdge(player, edge, (r) => planBlock(player, r, now)),
|
|
159
|
+
unblock: (player, edge, now) => onEdge(player, edge, (r) => planUnblock(player, r, now)),
|
|
160
|
+
invite: (player, edge, where, now) => onEdge(player, edge, (r) => planInvite(player, r, where, now)),
|
|
161
|
+
|
|
162
|
+
async pulse(player, where, lease, now) {
|
|
163
|
+
const p = checkPulse(where, lease);
|
|
164
|
+
const ref = await playerRef(presenceCol(), player);
|
|
165
|
+
await db.runTransaction(async (tx) => {
|
|
166
|
+
const snap = await tx.get(ref);
|
|
167
|
+
const d = snap.exists ? snap.data() : undefined;
|
|
168
|
+
const was = d ? { player, where: text(d.where), lease: text(d.lease), at: num(d.at) } : null;
|
|
169
|
+
const plan = planPulse(player, p.where, p.lease, was, now);
|
|
170
|
+
if ("put" in plan) tx.set(ref, { player, where: plan.put.where, lease: plan.put.lease, at: plan.put.at });
|
|
171
|
+
else if ("drop" in plan) tx.delete(ref);
|
|
172
|
+
});
|
|
173
|
+
},
|
|
174
|
+
|
|
175
|
+
async setShowOnline(player, on) {
|
|
176
|
+
const batch = db.batch();
|
|
177
|
+
batch.set(await playerRef(prefsCol(), player), { player, showOnline: Boolean(on) });
|
|
178
|
+
if (!on) batch.delete(await playerRef(presenceCol(), player));
|
|
179
|
+
await batch.commit();
|
|
180
|
+
},
|
|
181
|
+
|
|
182
|
+
async forget(player) {
|
|
183
|
+
const docs = (await ofPlayer(player).get()).docs.filter((d) => hasPlayer(recOf(d.data()), player));
|
|
184
|
+
const [pres, pref] = await Promise.all([(await playerRef(presenceCol(), player)).get(), (await playerRef(prefsCol(), player)).get()]);
|
|
185
|
+
const refs = docs.map((d) => d.ref);
|
|
186
|
+
if (pres.exists) refs.push(await playerRef(presenceCol(), player));
|
|
187
|
+
if (pref.exists) refs.push(await playerRef(prefsCol(), player));
|
|
188
|
+
// A batch holds at most 500 writes.
|
|
189
|
+
for (let i = 0; i < refs.length; i += 400) {
|
|
190
|
+
const batch = db.batch();
|
|
191
|
+
for (const ref of refs.slice(i, i + 400)) batch.delete(ref);
|
|
192
|
+
await batch.commit();
|
|
193
|
+
}
|
|
194
|
+
return refs.length;
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|