@hadoku/service-kernel 0.1.129 → 0.1.131

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.
@@ -87,6 +87,11 @@ export declare function createEdgeAuth(config: EdgeAuthConfig): EdgeAuth;
87
87
  * header is trustworthy in the first place.
88
88
  */
89
89
  export declare function tierOf(req: Request): string;
90
+ /**
91
+ * The caller's tier exactly as the edge named it — `member` stays `member`. For telemetry and
92
+ * anything else that reports who someone is; a gate reads `tierOf`.
93
+ */
94
+ export declare function edgeTierOf(req: Request): string;
90
95
  /** The caller's userId as the edge stamped it; null when the edge named nobody. */
91
96
  export declare function callerIdOf(req: Request): string | null;
92
97
  export declare function userIdOf(req: Request): string;
@@ -134,6 +134,14 @@ export function tierOf(req) {
134
134
  const tier = typeof t === 'string' && t !== '' ? t : 'public';
135
135
  return tier === 'member' ? 'friend' : tier;
136
136
  }
137
+ /**
138
+ * The caller's tier exactly as the edge named it — `member` stays `member`. For telemetry and
139
+ * anything else that reports who someone is; a gate reads `tierOf`.
140
+ */
141
+ export function edgeTierOf(req) {
142
+ const t = req.headers['x-hadoku-tier'];
143
+ return typeof t === 'string' && t !== '' ? t : 'public';
144
+ }
137
145
  /** The caller's userId as the edge stamped it; null when the edge named nobody. */
138
146
  export function callerIdOf(req) {
139
147
  const u = req.headers['x-user-id'];
@@ -1,2 +1,2 @@
1
1
  export { attachClientEvents, malformedFacts, type ClientEventsOptions, type PageEventSchema } from './client-events.js';
2
- export { attachUsage, MAX_BATCHES_PER_MINUTE, USAGE_TOP, USAGE_WINDOW_MS, type UsageCounter, type UsageEntry, type UsageOptions, type UsageSchema, } from './usage.js';
2
+ export { attachUsage, MAX_BATCHES_PER_MINUTE, USAGE_TOP, USAGE_TRAIL_MAX, USAGE_WINDOW_MS, placed, type UsageCounter, type UsageEntry, type UsageOptions, type UsageSchema, } from './usage.js';
@@ -1,2 +1,2 @@
1
1
  export { attachClientEvents, malformedFacts } from "./client-events.js";
2
- export { attachUsage, MAX_BATCHES_PER_MINUTE, USAGE_TOP, USAGE_WINDOW_MS, } from "./usage.js";
2
+ export { attachUsage, MAX_BATCHES_PER_MINUTE, USAGE_TOP, USAGE_TRAIL_MAX, USAGE_WINDOW_MS, placed, } from "./usage.js";
@@ -1,8 +1,18 @@
1
1
  /**
2
- * A browser relay for usage batches: which screens were shown and which controls pressed, counted
3
- * here and posted to telemetry as one `usage` event per window — how often, by how many people,
4
- * by tier. Nothing per click is kept, and nothing is answered but 204. The schema, the mount path
5
- * and the caller's tier/id are all parameters — this module knows no game's usage shape.
2
+ * A browser relay for usage batches: which screens were shown and which controls pressed, posted
3
+ * to telemetry once per window as
4
+ *
5
+ * - one `usage` event for everyone: how often each (screen, control) was used, by how many
6
+ * people, by tier;
7
+ * - one `usage-user` event per person active in the window: who (userId, name, tier as the edge
8
+ * named it) and their own ordered trail, a line per view or press (`06:41:02 click room pick`),
9
+ * each placed at its receipt time less the page's own `sentAt - at`, so a wrong browser clock
10
+ * still orders and times it right. A trail longer than `trailMax` keeps its first lines and
11
+ * says how many it dropped.
12
+ *
13
+ * Entries are screen names and `data-testid`s with ids stripped, never anything a person typed.
14
+ * Nothing is answered but 204. The schema, the mount path and the caller's tier/id/name are all
15
+ * parameters — this module knows no game's usage shape.
6
16
  *
7
17
  * A caller sending more than `maxBatchesPerMinute` is a client bug or a script; the rest of that
8
18
  * minute is dropped and counted as `dropped`, so the event says so.
@@ -14,13 +24,18 @@ export declare const USAGE_WINDOW_MS: number;
14
24
  export declare const MAX_BATCHES_PER_MINUTE = 10;
15
25
  /** How many (kind, screen, target) rows one event lists, busiest first. */
16
26
  export declare const USAGE_TOP = 60;
27
+ /** The most lines one person's `usage-user` trail keeps per window. */
28
+ export declare const USAGE_TRAIL_MAX = 500;
17
29
  export interface UsageEntry {
18
30
  kind: string;
19
31
  screen: string;
20
32
  target?: string;
33
+ /** The page's clock when it happened; read only against the batch's `sentAt`. */
34
+ at?: number;
21
35
  }
22
36
  export interface UsageSchema<T extends {
23
37
  entries: readonly UsageEntry[];
38
+ sentAt?: number;
24
39
  }> {
25
40
  safeParse(body: unknown): {
26
41
  success: true;
@@ -31,17 +46,22 @@ export interface UsageSchema<T extends {
31
46
  }
32
47
  export interface UsageOptions<T extends {
33
48
  entries: readonly UsageEntry[];
49
+ sentAt?: number;
34
50
  }> {
35
51
  schema: UsageSchema<T>;
36
52
  /** The mount path under `api`, e.g. `/api/<path>`. */
37
53
  path: string;
54
+ /** The tier as the edge named it — reported as is, so it must not be an app's own remapping. */
38
55
  tierOf: (req: Request) => string;
39
56
  userIdOf: (req: Request) => string;
57
+ /** The caller's display name, when the edge gave one. */
58
+ nameOf?: (req: Request) => string | null;
40
59
  report?: Report;
41
60
  now?: () => number;
42
61
  windowMs?: number;
43
62
  maxBatchesPerMinute?: number;
44
63
  top?: number;
64
+ trailMax?: number;
45
65
  }
46
66
  export interface UsageCounter {
47
67
  /** Post the window counted so far, if anything arrived, and start a new one. */
@@ -50,4 +70,11 @@ export interface UsageCounter {
50
70
  }
51
71
  export declare function attachUsage<T extends {
52
72
  entries: readonly UsageEntry[];
73
+ sentAt?: number;
53
74
  }>(api: Router, opts: UsageOptions<T>): UsageCounter;
75
+ /**
76
+ * When an entry happened on this server's clock: its receipt less how long before the batch left
77
+ * the page it was made, by the page's own clock. Never after receipt; an entry from a tab that
78
+ * predates `at`/`sentAt` is placed at receipt.
79
+ */
80
+ export declare function placed(received: number, sentAt: number | undefined, at: number | undefined): number;
@@ -5,11 +5,14 @@ export const USAGE_WINDOW_MS = 5 * 60_000;
5
5
  export const MAX_BATCHES_PER_MINUTE = 10;
6
6
  /** How many (kind, screen, target) rows one event lists, busiest first. */
7
7
  export const USAGE_TOP = 60;
8
+ /** The most lines one person's `usage-user` trail keeps per window. */
9
+ export const USAGE_TRAIL_MAX = 500;
8
10
  export function attachUsage(api, opts) {
9
11
  const report = opts.report ?? defaultReport;
10
12
  const now = opts.now ?? Date.now;
11
13
  const maxBatchesPerMinute = opts.maxBatchesPerMinute ?? MAX_BATCHES_PER_MINUTE;
12
14
  const top = opts.top ?? USAGE_TOP;
15
+ const trailMax = opts.trailMax ?? USAGE_TRAIL_MAX;
13
16
  let counts = new Map();
14
17
  let users = new Map();
15
18
  let batches = 0;
@@ -35,10 +38,23 @@ export function attachUsage(api, opts) {
35
38
  return res.status(204).end();
36
39
  }
37
40
  batches += 1;
38
- users.set(userId, opts.tierOf(req));
39
- for (const e of parsed.data.entries) {
41
+ const received = now();
42
+ const person = users.get(userId) ?? { tier: '', name: null, views: 0, clicks: 0, trail: [], dropped: 0 };
43
+ person.tier = opts.tierOf(req);
44
+ person.name = opts.nameOf?.(req) ?? person.name;
45
+ users.set(userId, person);
46
+ const { entries, sentAt } = parsed.data;
47
+ for (const e of entries) {
40
48
  const key = `${e.kind} ${e.screen}${e.target === undefined ? '' : ` ${e.target}`}`;
41
49
  counts.set(key, (counts.get(key) ?? 0) + 1);
50
+ if (e.kind === 'view')
51
+ person.views += 1;
52
+ else if (e.kind === 'click')
53
+ person.clicks += 1;
54
+ if (person.trail.length >= trailMax)
55
+ person.dropped += 1;
56
+ else
57
+ person.trail.push({ at: placed(received, sentAt, e.at), line: key });
42
58
  }
43
59
  return res.status(204).end();
44
60
  });
@@ -50,7 +66,7 @@ export function attachUsage(api, opts) {
50
66
  if (batches === 0 && dropped === 0)
51
67
  return;
52
68
  const tiers = {};
53
- for (const tier of users.values())
69
+ for (const { tier } of users.values())
54
70
  tiers[tier] = (tiers[tier] ?? 0) + 1;
55
71
  const rows = [...counts].sort((a, b) => b[1] - a[1]);
56
72
  report('usage', {
@@ -64,6 +80,19 @@ export function attachUsage(api, opts) {
64
80
  clicks: rows.filter(([k]) => k.startsWith('click ')).reduce((n, [, c]) => n + c, 0),
65
81
  top: Object.fromEntries(rows.slice(0, top)),
66
82
  });
83
+ for (const [userId, p] of users) {
84
+ report('usage-user', {
85
+ from: new Date(start).toISOString(),
86
+ minutes: Math.round((windowStart - start) / 60_000),
87
+ userId,
88
+ name: p.name,
89
+ tier: p.tier,
90
+ views: p.views,
91
+ clicks: p.clicks,
92
+ trail: p.trail.sort((a, b) => a.at - b.at).map(({ at, line }) => `${clock(at)} ${line}`),
93
+ ...(p.dropped > 0 ? { trailDropped: p.dropped } : {}),
94
+ });
95
+ }
67
96
  counts = new Map();
68
97
  users = new Map();
69
98
  batches = 0;
@@ -73,3 +102,17 @@ export function attachUsage(api, opts) {
73
102
  timer.unref();
74
103
  return { flush, stop: () => clearInterval(timer) };
75
104
  }
105
+ /**
106
+ * When an entry happened on this server's clock: its receipt less how long before the batch left
107
+ * the page it was made, by the page's own clock. Never after receipt; an entry from a tab that
108
+ * predates `at`/`sentAt` is placed at receipt.
109
+ */
110
+ export function placed(received, sentAt, at) {
111
+ if (sentAt === undefined || at === undefined)
112
+ return received;
113
+ return received - Math.max(0, sentAt - at);
114
+ }
115
+ /** `HH:MM:SS` in UTC; the event's `from` carries the date. */
116
+ function clock(ms) {
117
+ return new Date(ms).toISOString().slice(11, 19);
118
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/service-kernel",
3
- "version": "0.1.129",
4
- "gitHead": "e5f8a3ad2185e6524f982af947e6850dcf19134d",
3
+ "version": "0.1.131",
4
+ "gitHead": "f1d05adb733a43c0e239197bb1a656eb5575c999",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "The server parts any game keeps: edge auth and the tier gate, base path and bundle check, health and the busy probe, lifecycle, the JSON logger, the state directory, telemetry and capacity, per-caller limits, the browser relays, the erase registry, and createGameServer, which boots a game from its config and plugins. Knows no game; the app binds its service id, prefix and env names. MIT; imports only node built-ins, express, socket.io and @wolffm/*.",