package -> pkg
This commit is contained in:
146
pkg/server/src/api.ts
Normal file
146
pkg/server/src/api.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
import { Elysia, t } from "elysia";
|
||||
import {
|
||||
getSimplePlayerView,
|
||||
SimpleAction,
|
||||
SimpleConfiguration,
|
||||
SimpleGameState,
|
||||
} from "@games/shared/games/simple";
|
||||
import { human } from "./human";
|
||||
import dayjs from "dayjs";
|
||||
import db from "./db";
|
||||
import { liveTable, WsOut, WsIn } from "./table";
|
||||
import { Human } from "@prisma/client";
|
||||
import { combine } from "kefir";
|
||||
|
||||
const api = new Elysia({ prefix: "/api" })
|
||||
.post("/whoami", async ({ cookie: { token } }) => {
|
||||
let human: Human | null;
|
||||
if (
|
||||
token.value == null ||
|
||||
(human = await db.human.findUnique({
|
||||
where: {
|
||||
token: token.value,
|
||||
},
|
||||
})) == null
|
||||
) {
|
||||
human = await db.human.create({
|
||||
data: {},
|
||||
});
|
||||
token.set({
|
||||
value: human.token,
|
||||
expires: dayjs().add(1, "year").toDate(),
|
||||
httpOnly: true,
|
||||
});
|
||||
}
|
||||
|
||||
return human.key;
|
||||
})
|
||||
.use(human)
|
||||
.post(
|
||||
"/setName",
|
||||
({ body: { name }, humanKey }) =>
|
||||
db.human.update({
|
||||
where: {
|
||||
key: humanKey,
|
||||
},
|
||||
data: {
|
||||
name,
|
||||
},
|
||||
}),
|
||||
{
|
||||
body: t.Object({
|
||||
name: t.String(),
|
||||
}),
|
||||
}
|
||||
)
|
||||
.get("/profile", ({ humanKey, query: { otherHumanKey } }) =>
|
||||
db.human
|
||||
.findFirst({ where: { key: otherHumanKey ?? humanKey } })
|
||||
.then((human) => {
|
||||
if (human == null) {
|
||||
return null;
|
||||
}
|
||||
const { token, ...safeProfile } = human;
|
||||
return safeProfile;
|
||||
})
|
||||
)
|
||||
.get("/games", () => [{ key: "simple", name: "simple" }])
|
||||
.ws("/ws/:tableKey", {
|
||||
async open({
|
||||
data: {
|
||||
params: { tableKey },
|
||||
humanKey,
|
||||
},
|
||||
send,
|
||||
}) {
|
||||
const table = liveTable<
|
||||
SimpleConfiguration,
|
||||
SimpleGameState,
|
||||
SimpleAction
|
||||
>(tableKey);
|
||||
|
||||
table.inputs.connectionChanges.emit({
|
||||
humanKey,
|
||||
presence: "joined",
|
||||
});
|
||||
|
||||
table.outputs.playersPresent.onValue((players) =>
|
||||
send({ players })
|
||||
);
|
||||
|
||||
table.outputs.playersReady
|
||||
.skipDuplicates()
|
||||
.onValue((readys) => send({ playersReady: readys }));
|
||||
|
||||
combine(
|
||||
[table.outputs.gameState],
|
||||
[table.outputs.gameConfig],
|
||||
(state, config) =>
|
||||
state &&
|
||||
config &&
|
||||
getSimplePlayerView(config, state, humanKey)
|
||||
)
|
||||
.toProperty()
|
||||
.onValue((view) => send({ view }));
|
||||
},
|
||||
|
||||
response: WsOut,
|
||||
body: WsIn,
|
||||
|
||||
message(
|
||||
{
|
||||
data: {
|
||||
humanKey,
|
||||
params: { tableKey },
|
||||
},
|
||||
},
|
||||
body
|
||||
) {
|
||||
const {
|
||||
inputs: { readys, actions, quits },
|
||||
} = liveTable(tableKey);
|
||||
|
||||
if ("ready" in body) {
|
||||
readys.emit({ humanKey, ...body });
|
||||
} else if ("action" in body) {
|
||||
actions.emit({ humanKey, ...body.action });
|
||||
} else if ("quit" in body) {
|
||||
quits.emit({ humanKey });
|
||||
}
|
||||
},
|
||||
|
||||
async close({
|
||||
data: {
|
||||
params: { tableKey },
|
||||
humanKey,
|
||||
},
|
||||
}) {
|
||||
liveTable(tableKey).inputs.connectionChanges.emit({
|
||||
humanKey,
|
||||
presence: "left",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export default api;
|
||||
export type Api = typeof api;
|
||||
5
pkg/server/src/db.ts
Normal file
5
pkg/server/src/db.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
"use server";
|
||||
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
export default new PrismaClient();
|
||||
13
pkg/server/src/human.ts
Normal file
13
pkg/server/src/human.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import Elysia from "elysia";
|
||||
import db from "./db";
|
||||
|
||||
export const human = new Elysia({ name: "human" })
|
||||
.derive(async ({ cookie: { token }, status }) => {
|
||||
const humanKey = await db.human
|
||||
.findUnique({
|
||||
where: { token: token.value },
|
||||
})
|
||||
.then((human) => human?.key);
|
||||
return humanKey != null ? { humanKey } : status(401);
|
||||
})
|
||||
.as("scoped");
|
||||
33
pkg/server/src/index.ts
Normal file
33
pkg/server/src/index.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { cors } from "@elysiajs/cors";
|
||||
import { staticPlugin } from "@elysiajs/static";
|
||||
import { Elysia, env } from "elysia";
|
||||
import api from "./api";
|
||||
|
||||
const port = env.PORT || 5001;
|
||||
|
||||
const app = new Elysia()
|
||||
.use(
|
||||
cors({
|
||||
origin: ["http://localhost:3000", "https://games.drm.dev"],
|
||||
})
|
||||
)
|
||||
// .onRequest(({ request }) => {
|
||||
// console.log(request.method, request.url);
|
||||
// })
|
||||
.onError(({ error }) => {
|
||||
console.error(error);
|
||||
return error;
|
||||
})
|
||||
.get("/ping", () => "pong")
|
||||
.use(api)
|
||||
.get("/*", () => Bun.file("./public/index.html"))
|
||||
.use(
|
||||
staticPlugin({
|
||||
assets: "public",
|
||||
prefix: "/",
|
||||
alwaysStatic: true,
|
||||
})
|
||||
)
|
||||
.listen(port);
|
||||
|
||||
console.log("server started on", port);
|
||||
29
pkg/server/src/kefir-extension.ts
Normal file
29
pkg/server/src/kefir-extension.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { merge, Observable } from "kefir";
|
||||
|
||||
export const transform = <
|
||||
T,
|
||||
Mutations extends [Observable<any, any>, (prev: T, evt: any) => T][]
|
||||
>(
|
||||
initValue: T,
|
||||
...mutations: Mutations
|
||||
): Observable<T, unknown> =>
|
||||
merge(
|
||||
mutations.map(([source, mutation]) =>
|
||||
source.map((event) => ({ event, mutation }))
|
||||
)
|
||||
).scan((prev, { event, mutation }) => mutation(prev, event), initValue);
|
||||
|
||||
export const partition =
|
||||
<C extends readonly [...string[]], T, E>(
|
||||
classes: C,
|
||||
partitionFn: (v: T) => C[number]
|
||||
) =>
|
||||
(obs: Observable<T, E>) => {
|
||||
const assigned = obs.map((obj) => ({ obj, cls: partitionFn(obj) }));
|
||||
return Object.fromEntries(
|
||||
classes.map((C) => [
|
||||
C,
|
||||
assigned.filter(({ cls }) => cls == C).map(({ obj }) => obj),
|
||||
])
|
||||
);
|
||||
};
|
||||
0
pkg/server/src/logging.ts
Normal file
0
pkg/server/src/logging.ts
Normal file
202
pkg/server/src/table.ts
Normal file
202
pkg/server/src/table.ts
Normal file
@@ -0,0 +1,202 @@
|
||||
import { t } from "elysia";
|
||||
import { combine, pool, Property } from "kefir";
|
||||
import Bus, { type Bus as TBus } from "kefir-bus";
|
||||
import {
|
||||
newSimpleGameState,
|
||||
resolveSimpleAction,
|
||||
SimpleAction,
|
||||
SimpleConfiguration,
|
||||
SimpleGameState,
|
||||
} from "@games/shared/games/simple";
|
||||
import { transform } from "./kefir-extension";
|
||||
|
||||
export const WsOut = t.Object({
|
||||
players: t.Optional(t.Array(t.String())),
|
||||
playersReady: t.Optional(t.Nullable(t.Record(t.String(), t.Boolean()))),
|
||||
view: t.Optional(t.Any()),
|
||||
});
|
||||
export type TWsOut = typeof WsOut.static;
|
||||
export const WsIn = t.Union([
|
||||
t.Object({ ready: t.Boolean() }),
|
||||
t.Object({ action: t.Any() }),
|
||||
t.Object({ quit: t.Literal(true) }),
|
||||
]);
|
||||
export type TWsIn = typeof WsIn.static;
|
||||
|
||||
type Attributed = { humanKey: string };
|
||||
type TablePayload<GameConfig, GameState, GameAction> = {
|
||||
inputs: {
|
||||
connectionChanges: TBus<
|
||||
Attributed & { presence: "joined" | "left" },
|
||||
never
|
||||
>;
|
||||
|
||||
readys: TBus<Attributed & { ready: boolean }, any>;
|
||||
actions: TBus<Attributed & GameAction, any>;
|
||||
quits: TBus<Attributed, any>;
|
||||
};
|
||||
outputs: {
|
||||
playersPresent: Property<string[], any>;
|
||||
playersReady: Property<{ [key: string]: boolean } | null, any>;
|
||||
gameConfig: Property<GameConfig | null, any>;
|
||||
gameState: Property<GameState | null, any>;
|
||||
};
|
||||
};
|
||||
|
||||
const tables: {
|
||||
[key: string]: TablePayload<unknown, unknown, unknown>;
|
||||
} = {};
|
||||
|
||||
export const liveTable = <GameConfig, GameState, GameAction>(key: string) => {
|
||||
if (!(key in tables)) {
|
||||
const inputs: TablePayload<
|
||||
GameConfig,
|
||||
GameState,
|
||||
GameAction
|
||||
>["inputs"] = {
|
||||
connectionChanges: Bus(),
|
||||
readys: Bus(),
|
||||
actions: Bus(),
|
||||
quits: Bus(),
|
||||
};
|
||||
const { connectionChanges, readys, actions, quits } = inputs;
|
||||
quits.log("quits");
|
||||
// =======
|
||||
|
||||
const playersPresent = connectionChanges
|
||||
.scan((prev, evt) => {
|
||||
if (evt.presence == "left" && prev[evt.humanKey] == 1) {
|
||||
const { [evt.humanKey]: _, ...rest } = prev;
|
||||
return rest;
|
||||
}
|
||||
return {
|
||||
...prev,
|
||||
[evt.humanKey]:
|
||||
(prev[evt.humanKey] ?? 0) +
|
||||
(evt.presence == "joined" ? 1 : -1),
|
||||
};
|
||||
}, {} as { [key: string]: number })
|
||||
.map((counts) => Object.keys(counts))
|
||||
.toProperty();
|
||||
|
||||
const gameEnds = quits.map((_) => null);
|
||||
|
||||
const gameStarts = pool<null, any>();
|
||||
const playersReady = transform(
|
||||
null as { [key: string]: boolean } | null,
|
||||
[
|
||||
playersPresent,
|
||||
(prev, players: string[]) =>
|
||||
Object.fromEntries(
|
||||
players.map((p) => [p, prev?.[p] ?? false])
|
||||
),
|
||||
],
|
||||
[
|
||||
readys,
|
||||
(prev, evt: { humanKey: string; ready: boolean }) =>
|
||||
prev?.[evt.humanKey] != null
|
||||
? { ...prev, [evt.humanKey]: evt.ready }
|
||||
: prev,
|
||||
],
|
||||
[gameStarts, () => null],
|
||||
[
|
||||
combine([gameEnds], [playersPresent], (_, players) => players),
|
||||
(_, players: string[]) =>
|
||||
Object.fromEntries(players.map((p) => [p, false])),
|
||||
]
|
||||
)
|
||||
.toProperty()
|
||||
.log("playersReady");
|
||||
|
||||
gameStarts.plug(
|
||||
playersReady
|
||||
.filter(
|
||||
(pr) =>
|
||||
Object.values(pr ?? {}).length > 0 &&
|
||||
Object.values(pr!).every((ready) => ready)
|
||||
)
|
||||
.map((_) => null)
|
||||
.log("gameStarts")
|
||||
);
|
||||
|
||||
const gameConfigPool = pool<
|
||||
{
|
||||
game: string;
|
||||
players: string[];
|
||||
},
|
||||
never
|
||||
>();
|
||||
|
||||
const gameConfig = gameConfigPool.toProperty();
|
||||
|
||||
const gameState = transform(
|
||||
null as SimpleGameState | null,
|
||||
[
|
||||
combine([gameStarts], [gameConfigPool], (_, config) => config),
|
||||
(prev, startConfig: SimpleConfiguration) =>
|
||||
prev == null ? newSimpleGameState(startConfig) : prev,
|
||||
],
|
||||
[
|
||||
combine([actions], [gameConfigPool], (action, config) => ({
|
||||
action,
|
||||
config,
|
||||
})),
|
||||
(
|
||||
prev,
|
||||
evt: {
|
||||
action: Attributed & SimpleAction;
|
||||
config: SimpleConfiguration;
|
||||
}
|
||||
) =>
|
||||
prev != null
|
||||
? resolveSimpleAction({
|
||||
config: evt.config,
|
||||
state: prev,
|
||||
action: evt.action,
|
||||
humanKey: evt.action.humanKey,
|
||||
})
|
||||
: prev,
|
||||
],
|
||||
[quits, () => null]
|
||||
).toProperty();
|
||||
gameState
|
||||
.map((state) => JSON.stringify(state).substring(0, 10))
|
||||
.log("gameState");
|
||||
|
||||
const gameIsActive = gameState
|
||||
.map((gs) => gs != null)
|
||||
.skipDuplicates()
|
||||
.toProperty()
|
||||
.log("gameIsActive");
|
||||
|
||||
gameConfigPool.plug(
|
||||
playersPresent
|
||||
.filterBy(gameIsActive.map((active) => !active))
|
||||
.map((players) => ({
|
||||
game: "simple",
|
||||
players,
|
||||
}))
|
||||
);
|
||||
|
||||
tables[key] = {
|
||||
inputs,
|
||||
outputs: {
|
||||
playersPresent,
|
||||
playersReady: playersReady.toProperty(),
|
||||
gameConfig: gameConfig as Property<unknown, any>,
|
||||
gameState: gameState as Property<unknown, any>,
|
||||
},
|
||||
};
|
||||
|
||||
// cleanup
|
||||
tables[key].outputs.playersPresent
|
||||
.debounce(30000, { immediate: false })
|
||||
.filter((players) => players.length === 0)
|
||||
.skip(1)
|
||||
.onValue((_) => {
|
||||
console.log("DELETING LIVE TABLE");
|
||||
delete tables[key];
|
||||
});
|
||||
}
|
||||
return tables[key] as TablePayload<GameConfig, GameState, GameAction>;
|
||||
};
|
||||
Reference in New Issue
Block a user