-
-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add gameplay lifecycle telemetry and admin analytics #153
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tuxerrante
wants to merge
2
commits into
main
Choose a base branch
from
feat/gameplay-lifecycle-telemetry
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,15 +1,168 @@ | ||
| import type { GameplayAnalytics, GameplayDifficultyAnalytics, GameplayScenarioAnalytics, GameplayLifecycleState } from "../../../../shared/types/gameplay"; | ||
| import type { Difficulty } from "../../../../shared/types/game"; | ||
| import type { IMetricsStore, GameplayRecord } from "./types"; | ||
|
|
||
| const records: GameplayRecord[] = []; | ||
|
|
||
| function sessionKey(record: GameplayRecord): string { | ||
| return record.sessionToken ?? record.id ?? crypto.randomUUID(); | ||
| } | ||
|
|
||
| function roundAverage(values: number[]): number | null { | ||
| if (values.length === 0) return null; | ||
| const total = values.reduce((sum, value) => sum + value, 0); | ||
| return Math.round((total / values.length) * 100) / 100; | ||
| } | ||
|
|
||
| function toRate(part: number, total: number): number { | ||
| if (total === 0) return 0; | ||
| return Math.round((part / total) * 10000) / 100; | ||
| } | ||
|
|
||
| function latestSessionRecords(): GameplayRecord[] { | ||
| const latest = new Map<string, GameplayRecord>(); | ||
| const sorted = [...records].sort((a, b) => { | ||
| const aTime = a.createdAt?.getTime() ?? 0; | ||
| const bTime = b.createdAt?.getTime() ?? 0; | ||
| return aTime - bTime; | ||
| }); | ||
|
|
||
| for (const record of sorted) { | ||
| latest.set(sessionKey(record), record); | ||
| } | ||
|
|
||
| return [...latest.values()]; | ||
| } | ||
|
|
||
| function countStates(items: GameplayRecord[]) { | ||
| const states: Record<GameplayLifecycleState, number> = { | ||
| started: 0, | ||
| completed: 0, | ||
| abandoned: 0, | ||
| }; | ||
|
|
||
| for (const item of items) { | ||
| const state = item.lifecycleState ?? "completed"; | ||
| states[state] += 1; | ||
| } | ||
|
|
||
| return states; | ||
| } | ||
|
|
||
| export class JsonMetricsStore implements IMetricsStore { | ||
| async recordGameplay(data: GameplayRecord): Promise<void> { | ||
| const record: GameplayRecord = { | ||
| ...data, | ||
| id: data.id ?? crypto.randomUUID(), | ||
| lifecycleState: data.lifecycleState ?? "completed", | ||
| commandCount: data.commandCount ?? data.commandsExecuted?.length ?? 0, | ||
| commandsExecuted: data.commandsExecuted ?? [], | ||
| scoringEvents: data.scoringEvents ?? [], | ||
| chatMessageCount: data.chatMessageCount ?? 0, | ||
| aiPromptTokens: data.aiPromptTokens ?? 0, | ||
| aiCompletionTokens: data.aiCompletionTokens ?? 0, | ||
| completed: data.completed ?? data.lifecycleState === "completed", | ||
| metadata: data.metadata ?? {}, | ||
| createdAt: data.createdAt ?? new Date(), | ||
| }; | ||
|
|
||
| records.push(record); | ||
|
|
||
| console.log( | ||
| `[metrics] gameplay recorded (in-memory only): session=${data.sessionToken ?? "unknown"} ` + | ||
| `nickname=${data.nickname ?? "unknown"} difficulty=${data.difficulty ?? "unknown"}` | ||
| `[metrics] gameplay recorded (in-memory only): session=${record.sessionToken ?? "unknown"} ` + | ||
| `state=${record.lifecycleState} difficulty=${record.difficulty ?? "unknown"}` | ||
| ); | ||
| } | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| async getPlayerHistory(_nickname: string): Promise<GameplayRecord[]> { | ||
| return []; | ||
| async getPlayerHistory(nickname: string): Promise<GameplayRecord[]> { | ||
| return records | ||
| .filter((record) => record.nickname === nickname) | ||
| .sort((a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0)); | ||
| } | ||
|
|
||
| async getGameplayAnalytics(): Promise<GameplayAnalytics> { | ||
| const latest = latestSessionRecords(); | ||
| const completed = latest.filter((record) => record.lifecycleState === "completed"); | ||
| const summaryStates = countStates(latest); | ||
|
|
||
| const byDifficulty = (["easy", "medium", "hard"] as Difficulty[]) | ||
| .map((difficulty): GameplayDifficultyAnalytics => { | ||
| const scoped = latest.filter((record) => record.difficulty === difficulty); | ||
| const scopedStates = countStates(scoped); | ||
| return { | ||
| difficulty, | ||
| totalSessions: scoped.length, | ||
| completedSessions: scopedStates.completed, | ||
| abandonedSessions: scopedStates.abandoned, | ||
| inProgressSessions: scopedStates.started, | ||
| completionRate: toRate(scopedStates.completed, scoped.length), | ||
| }; | ||
| }) | ||
| .filter((bucket) => bucket.totalSessions > 0); | ||
|
|
||
| const scenarioMap = new Map<string, GameplayRecord[]>(); | ||
| for (const record of latest) { | ||
| const key = `${record.difficulty ?? "unknown"}::${record.scenarioTitle ?? "Unknown Scenario"}`; | ||
| const existing = scenarioMap.get(key) ?? []; | ||
| existing.push(record); | ||
| scenarioMap.set(key, existing); | ||
| } | ||
|
|
||
| const byScenario = [...scenarioMap.entries()] | ||
| .map(([key, scoped]): GameplayScenarioAnalytics => { | ||
| const [difficulty, scenarioTitle] = key.split("::"); | ||
| const scopedStates = countStates(scoped); | ||
| return { | ||
| difficulty: difficulty === "unknown" ? undefined : (difficulty as Difficulty), | ||
| scenarioTitle, | ||
| totalSessions: scoped.length, | ||
| completedSessions: scopedStates.completed, | ||
| abandonedSessions: scopedStates.abandoned, | ||
| inProgressSessions: scopedStates.started, | ||
| completionRate: toRate(scopedStates.completed, scoped.length), | ||
| }; | ||
| }) | ||
| .sort((a, b) => b.totalSessions - a.totalSessions || a.scenarioTitle.localeCompare(b.scenarioTitle)); | ||
|
|
||
| return { | ||
| summary: { | ||
| totalSessions: latest.length, | ||
| completedSessions: summaryStates.completed, | ||
| abandonedSessions: summaryStates.abandoned, | ||
| inProgressSessions: summaryStates.started, | ||
| completionRate: toRate(summaryStates.completed, latest.length), | ||
| abandonmentRate: toRate(summaryStates.abandoned, latest.length), | ||
| avgCompletionDurationMs: roundAverage( | ||
| completed.map((record) => record.durationMs).filter((value): value is number => typeof value === "number"), | ||
| ), | ||
| avgCompletionCommandCount: roundAverage( | ||
| completed.map((record) => record.commandCount).filter((value): value is number => typeof value === "number"), | ||
| ), | ||
| avgCompletionChatMessageCount: roundAverage( | ||
| completed.map((record) => record.chatMessageCount).filter((value): value is number => typeof value === "number"), | ||
| ), | ||
| avgCompletionScoreTotal: roundAverage( | ||
| completed.map((record) => record.scoreTotal).filter((value): value is number => typeof value === "number"), | ||
| ), | ||
| }, | ||
| byDifficulty, | ||
| byScenario, | ||
| recentSessions: latest | ||
| .sort((a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0)) | ||
| .slice(0, 20) | ||
| .map((record) => ({ | ||
| sessionToken: record.sessionToken, | ||
| lifecycleState: record.lifecycleState ?? "completed", | ||
| nickname: record.nickname, | ||
| difficulty: record.difficulty, | ||
| scenarioTitle: record.scenarioTitle, | ||
| commandCount: record.commandCount, | ||
| chatMessageCount: record.chatMessageCount, | ||
| durationMs: record.durationMs, | ||
| scoreTotal: record.scoreTotal, | ||
| grade: record.grade, | ||
| createdAt: (record.createdAt ?? new Date(0)).toISOString(), | ||
| })), | ||
| }; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
64 changes: 64 additions & 0 deletions
64
backend/src/lib/storage/migrations/002_gameplay_lifecycle_events.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| IF COL_LENGTH('gameplay_metrics', 'lifecycle_state') IS NULL | ||
| BEGIN | ||
| ALTER TABLE gameplay_metrics | ||
| ADD lifecycle_state VARCHAR(16) NOT NULL | ||
| CONSTRAINT df_gameplay_metrics_lifecycle_state DEFAULT 'completed'; | ||
| END; | ||
|
|
||
| IF COL_LENGTH('gameplay_metrics', 'command_count') IS NULL | ||
| BEGIN | ||
| ALTER TABLE gameplay_metrics | ||
| ADD command_count INT NOT NULL | ||
| CONSTRAINT df_gameplay_metrics_command_count DEFAULT 0; | ||
| END; | ||
|
|
||
| IF COL_LENGTH('gameplay_metrics', 'score_total') IS NULL | ||
| BEGIN | ||
| ALTER TABLE gameplay_metrics | ||
| ADD score_total INT NULL; | ||
| END; | ||
|
|
||
| IF COL_LENGTH('gameplay_metrics', 'grade') IS NULL | ||
| BEGIN | ||
| ALTER TABLE gameplay_metrics | ||
| ADD grade VARCHAR(5) NULL; | ||
| END; | ||
|
|
||
| IF NOT EXISTS ( | ||
| SELECT * | ||
| FROM sys.check_constraints | ||
| WHERE name = 'ck_gameplay_metrics_lifecycle_state' | ||
| ) | ||
| BEGIN | ||
| EXEC(' | ||
| ALTER TABLE gameplay_metrics | ||
| ADD CONSTRAINT ck_gameplay_metrics_lifecycle_state | ||
| CHECK (lifecycle_state IN (''started'', ''completed'', ''abandoned'')) | ||
| '); | ||
| END; | ||
|
|
||
| IF NOT EXISTS ( | ||
| SELECT * | ||
| FROM sys.indexes | ||
| WHERE name = 'idx_metrics_session_created' | ||
| AND object_id = OBJECT_ID('gameplay_metrics') | ||
| ) | ||
| BEGIN | ||
| EXEC(' | ||
| CREATE INDEX idx_metrics_session_created | ||
| ON gameplay_metrics (session_token, created_at) | ||
| '); | ||
| END; | ||
|
|
||
| IF NOT EXISTS ( | ||
| SELECT * | ||
| FROM sys.indexes | ||
| WHERE name = 'idx_metrics_lifecycle_state' | ||
| AND object_id = OBJECT_ID('gameplay_metrics') | ||
| ) | ||
| BEGIN | ||
| EXEC(' | ||
| CREATE INDEX idx_metrics_lifecycle_state | ||
| ON gameplay_metrics (lifecycle_state, created_at) | ||
| '); | ||
| END; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The JSON metrics backend keeps all
GameplayRecords in a process-globalrecordsarray with no cap/TTL. In long-running json-backend deployments (or dev sessions), this can grow without bound and increase memory usage over time. Consider adding a retention limit (e.g., keep last N records) and/or TTL-based cleanup.