cursedbelt-server 4.56.0 → 4.58.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/dist/server/engagement/actions.d.ts +85 -3
- package/dist/server/engagement/actions.js +93 -11
- package/dist/server/engagement/api.d.ts +2 -1
- package/dist/server/engagement/api.js +9 -10
- package/dist/server/engagement/d1.d.ts +3 -0
- package/dist/server/engagement/d1.js +36 -10
- package/dist/server/engagement/store.d.ts +7 -3
- package/dist/server/engagement/store.js +22 -7
- package/dist/server/engagement/visits.d.ts +37 -0
- package/dist/server/engagement/visits.js +28 -0
- package/dist/server/youtube/ytdlp.d.ts +9 -0
- package/dist/server/youtube/ytdlp.js +16 -5
- package/docs/engagement.md +14 -0
- package/package.json +2 -2
- package/src/server/engagement/actions.ts +109 -12
- package/src/server/engagement/api.ts +8 -9
- package/src/server/engagement/d1.spec.ts +60 -1
- package/src/server/engagement/d1.ts +34 -9
- package/src/server/engagement/engagement.spec.ts +41 -0
- package/src/server/engagement/store.ts +20 -7
- package/src/server/engagement/visits.ts +53 -0
- package/src/server/youtube/ytdlp.spec.ts +13 -0
- package/src/server/youtube/ytdlp.ts +23 -6
|
@@ -1,20 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Feature ACTIONS — what somebody DID on a page, beside where they were (task 3470).
|
|
3
|
+
*
|
|
4
|
+
* A place-view answers "which pages do they open". The owner's question goes one step further:
|
|
5
|
+
* *"what features they use and ignore … and know which users to ask first when I am planning to
|
|
6
|
+
* add or delete a feature"*. A page is not a feature — music's library page holds play, search,
|
|
7
|
+
* rate and download — so this records a declared ACTION NAME per (account, place).
|
|
8
|
+
*
|
|
9
|
+
* ── The privacy contract is the places' contract, unchanged ─────────────────
|
|
10
|
+
* The action is a NAME from the app's own `routes.manifest.json` `actions` list
|
|
11
|
+
* (`policy.ts:resolveAction`); the place is resolved against the same manifest as a view. There is
|
|
12
|
+
* no field for a value — `search`, never the query; `play`, never the track — so nothing a person
|
|
13
|
+
* typed or chose can reach a row. The account is the session's subject, never the body's.
|
|
14
|
+
*
|
|
15
|
+
* ── Counts and clocks, two grains ───────────────────────────────────────────
|
|
16
|
+
* engagement_actions (user, place, action) → uses, first, last. LIFETIME, never trimmed:
|
|
17
|
+
* it is the row that answers "who uses this most, and when did they last",
|
|
18
|
+
* and trimming it would make a feature's old regulars vanish.
|
|
19
|
+
* engagement_action_days (user, place, action, day) → uses. Trimmed with the view days, for
|
|
20
|
+
* "used this month" against "used once, long ago".
|
|
21
|
+
* No event log, no sequence: an action does not touch the sessionization clock or dwell.
|
|
22
|
+
*
|
|
23
|
+
* 🔴 Its own DDL, not appended to `ENGAGEMENT_DDL`: an app whose schema is generated from that list
|
|
24
|
+
* (music, family, desk, arch) would otherwise go red on the version bump alone. An app opts in by
|
|
25
|
+
* declaring `actions` and applying {@link ENGAGEMENT_ACTION_DDL}; the Bun store always creates both.
|
|
26
|
+
*
|
|
27
|
+
* ── One POST, many actions (task 4034) ──────────────────────────────────────
|
|
28
|
+
* The browser queues actions and sends them together after a few seconds of quiet, and at
|
|
29
|
+
* `pagehide` (`cursedbelt/react/engagement-beacon`), so a feature the owner adds to the record
|
|
30
|
+
* costs no extra request per click. The door reads either body: `{ place, action }`, one action
|
|
31
|
+
* as before, which is what the client still sends when its queue holds one, so an older server
|
|
32
|
+
* reads it; or `{ actions: [{ place, action, at }…] }`. A batch over {@link MAX_ACTION_BATCH} is
|
|
33
|
+
* cut, and the cut is counted in the reply and in the log. `at` is the browser's clock, so it
|
|
34
|
+
* is clamped to the last {@link MAX_ACTION_AGE_MS} and never ahead of the server's. It only
|
|
35
|
+
* picks the DAY a use counts on. Repeats fold before the write ({@link tallyActions}): ten plays
|
|
36
|
+
* on one page are one upsert of `uses + 10`.
|
|
37
|
+
*
|
|
38
|
+
* Pure and Worker-safe: the Bun store and the D1 recorder both write through
|
|
39
|
+
* {@link actionStatements}, so there is one write, not two that agree.
|
|
40
|
+
*/
|
|
41
|
+
import { type ActionRef, type PlaceRef } from "./policy.js";
|
|
42
|
+
/** The most actions one POST records; the rest are cut and counted. The client sends no more. */
|
|
43
|
+
export declare const MAX_ACTION_BATCH = 100;
|
|
44
|
+
/** How far back a batched action's own clock may place it. The client holds one for 30 s at most. */
|
|
45
|
+
export declare const MAX_ACTION_AGE_MS: number;
|
|
1
46
|
export declare const ENGAGEMENT_ACTION_DDL: readonly string[];
|
|
2
47
|
/** One resolved action, ready to count. `place` and `action` have been through the allowlists. */
|
|
3
48
|
export interface ActionUse {
|
|
4
49
|
userKey: string;
|
|
5
50
|
place: string;
|
|
6
51
|
action: string;
|
|
52
|
+
/** When it happened; with `uses` > 1, the LAST of them. */
|
|
7
53
|
ts: number;
|
|
54
|
+
/** How many uses this row counts. A batch folds repeats into one row ({@link tallyActions}); default 1. */
|
|
55
|
+
uses?: number;
|
|
56
|
+
/** The first of them, when `uses` > 1; default `ts`. */
|
|
57
|
+
firstTs?: number;
|
|
8
58
|
}
|
|
9
|
-
/** The two upserts one action is — run them together (a transaction, or one D1 batch). */
|
|
59
|
+
/** The two upserts one action (or one tally of them) is — run them together (a transaction, or one D1 batch). */
|
|
10
60
|
export declare function actionStatements(use: ActionUse): Array<{
|
|
11
61
|
sql: string;
|
|
12
62
|
params: (string | number)[];
|
|
13
63
|
}>;
|
|
14
|
-
/**
|
|
15
|
-
export
|
|
64
|
+
/** One action as the browser claimed it: two NAMES, and its clock already clamped to the server's. */
|
|
65
|
+
export interface ClaimedAction {
|
|
16
66
|
place: string;
|
|
17
67
|
action: string;
|
|
68
|
+
at: number;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Read the claimed actions out of a request body: `{ place, action }` (one, at `now`) or
|
|
72
|
+
* `{ actions: [{ place, action, at? }…] }`. Every one must carry two strings, or the whole body is a
|
|
73
|
+
* 400, as a single one is. Past {@link MAX_ACTION_BATCH} they are cut, and `cut` says how many.
|
|
74
|
+
*/
|
|
75
|
+
export declare function claimedActions(body: unknown, now: number): {
|
|
76
|
+
actions: ClaimedAction[];
|
|
77
|
+
cut: number;
|
|
78
|
+
batch: boolean;
|
|
79
|
+
} | {
|
|
80
|
+
error: string;
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* Fold resolved uses into one row per (place, action, day), so a batch is a handful of upserts
|
|
84
|
+
* however many clicks it carries. The order of first appearance is kept.
|
|
85
|
+
*/
|
|
86
|
+
export declare function tallyActions(uses: readonly ActionUse[]): ActionUse[];
|
|
87
|
+
/**
|
|
88
|
+
* The action door's whole answer to one body — what to write and what to say back — so the Bun
|
|
89
|
+
* recorder and the D1 one cannot drift. One action replies as it always has; a batch replies with
|
|
90
|
+
* how many it recorded, how many of those were bucketed as `other`, and how many it cut.
|
|
91
|
+
*/
|
|
92
|
+
export declare function actionDoor(body: unknown, door: {
|
|
93
|
+
userKey: string;
|
|
94
|
+
now: number;
|
|
95
|
+
places: readonly PlaceRef[];
|
|
96
|
+
actions: readonly ActionRef[];
|
|
97
|
+
}): {
|
|
98
|
+
uses: ActionUse[];
|
|
99
|
+
reply: Record<string, unknown>;
|
|
18
100
|
} | {
|
|
19
101
|
error: string;
|
|
20
102
|
};
|
|
@@ -24,39 +24,121 @@
|
|
|
24
24
|
* (music, family, desk, arch) would otherwise go red on the version bump alone. An app opts in by
|
|
25
25
|
* declaring `actions` and applying {@link ENGAGEMENT_ACTION_DDL}; the Bun store always creates both.
|
|
26
26
|
*
|
|
27
|
+
* ── One POST, many actions (task 4034) ──────────────────────────────────────
|
|
28
|
+
* The browser queues actions and sends them together after a few seconds of quiet, and at
|
|
29
|
+
* `pagehide` (`cursedbelt/react/engagement-beacon`), so a feature the owner adds to the record
|
|
30
|
+
* costs no extra request per click. The door reads either body: `{ place, action }`, one action
|
|
31
|
+
* as before, which is what the client still sends when its queue holds one, so an older server
|
|
32
|
+
* reads it; or `{ actions: [{ place, action, at }…] }`. A batch over {@link MAX_ACTION_BATCH} is
|
|
33
|
+
* cut, and the cut is counted in the reply and in the log. `at` is the browser's clock, so it
|
|
34
|
+
* is clamped to the last {@link MAX_ACTION_AGE_MS} and never ahead of the server's. It only
|
|
35
|
+
* picks the DAY a use counts on. Repeats fold before the write ({@link tallyActions}): ten plays
|
|
36
|
+
* on one page are one upsert of `uses + 10`.
|
|
37
|
+
*
|
|
27
38
|
* Pure and Worker-safe: the Bun store and the D1 recorder both write through
|
|
28
39
|
* {@link actionStatements}, so there is one write, not two that agree.
|
|
29
40
|
*/
|
|
30
|
-
import { dayKey } from "./policy.js";
|
|
41
|
+
import { dayKey, OTHER_PLACE, resolveAction, resolvePlace } from "./policy.js";
|
|
42
|
+
/** The most actions one POST records; the rest are cut and counted. The client sends no more. */
|
|
43
|
+
export const MAX_ACTION_BATCH = 100;
|
|
44
|
+
/** How far back a batched action's own clock may place it. The client holds one for 30 s at most. */
|
|
45
|
+
export const MAX_ACTION_AGE_MS = 10 * 60 * 1000;
|
|
31
46
|
export const ENGAGEMENT_ACTION_DDL = [
|
|
32
47
|
"CREATE TABLE IF NOT EXISTS engagement_actions ( user_key TEXT NOT NULL, place TEXT NOT NULL, action TEXT NOT NULL, uses INTEGER NOT NULL DEFAULT 0, first_ts INTEGER NOT NULL, last_ts INTEGER NOT NULL, PRIMARY KEY (user_key, place, action) )",
|
|
33
48
|
"CREATE TABLE IF NOT EXISTS engagement_action_days ( user_key TEXT NOT NULL, place TEXT NOT NULL, action TEXT NOT NULL, day TEXT NOT NULL, uses INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (user_key, place, action, day) )",
|
|
34
49
|
"CREATE INDEX IF NOT EXISTS idx_engagement_action_days_day ON engagement_action_days (day)",
|
|
35
50
|
];
|
|
36
|
-
/** The two upserts one action is — run them together (a transaction, or one D1 batch). */
|
|
51
|
+
/** The two upserts one action (or one tally of them) is — run them together (a transaction, or one D1 batch). */
|
|
37
52
|
export function actionStatements(use) {
|
|
38
53
|
const { userKey, place, action, ts } = use;
|
|
54
|
+
const uses = use.uses ?? 1;
|
|
39
55
|
return [
|
|
40
56
|
{
|
|
57
|
+
// MIN/MAX, not "the newest wins": a batch's clock can sit behind a use the door recorded since.
|
|
41
58
|
sql: `INSERT INTO engagement_actions (user_key, place, action, uses, first_ts, last_ts)
|
|
42
|
-
VALUES (?, ?, ?,
|
|
43
|
-
ON CONFLICT(user_key, place, action) DO UPDATE SET uses = uses +
|
|
44
|
-
|
|
59
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
60
|
+
ON CONFLICT(user_key, place, action) DO UPDATE SET uses = uses + excluded.uses,
|
|
61
|
+
first_ts = MIN(first_ts, excluded.first_ts), last_ts = MAX(last_ts, excluded.last_ts)`,
|
|
62
|
+
params: [userKey, place, action, uses, use.firstTs ?? ts, ts],
|
|
45
63
|
},
|
|
46
64
|
{
|
|
47
65
|
sql: `INSERT INTO engagement_action_days (user_key, place, action, day, uses)
|
|
48
|
-
VALUES (?, ?, ?, ?,
|
|
49
|
-
ON CONFLICT(user_key, place, action, day) DO UPDATE SET uses = uses +
|
|
50
|
-
params: [userKey, place, action, dayKey(ts)],
|
|
66
|
+
VALUES (?, ?, ?, ?, ?)
|
|
67
|
+
ON CONFLICT(user_key, place, action, day) DO UPDATE SET uses = uses + excluded.uses`,
|
|
68
|
+
params: [userKey, place, action, dayKey(ts), uses],
|
|
51
69
|
},
|
|
52
70
|
];
|
|
53
71
|
}
|
|
54
|
-
/**
|
|
55
|
-
|
|
72
|
+
/**
|
|
73
|
+
* Read the claimed actions out of a request body: `{ place, action }` (one, at `now`) or
|
|
74
|
+
* `{ actions: [{ place, action, at? }…] }`. Every one must carry two strings, or the whole body is a
|
|
75
|
+
* 400, as a single one is. Past {@link MAX_ACTION_BATCH} they are cut, and `cut` says how many.
|
|
76
|
+
*/
|
|
77
|
+
export function claimedActions(body, now) {
|
|
78
|
+
const list = body?.actions;
|
|
79
|
+
if (list === undefined) {
|
|
80
|
+
const one = claimedOne(body, now);
|
|
81
|
+
return "error" in one ? one : { actions: [one], cut: 0, batch: false };
|
|
82
|
+
}
|
|
83
|
+
if (!Array.isArray(list))
|
|
84
|
+
return { error: "actions must be an array" };
|
|
85
|
+
const actions = [];
|
|
86
|
+
for (const item of list.slice(0, MAX_ACTION_BATCH)) {
|
|
87
|
+
const one = claimedOne(item, now);
|
|
88
|
+
if ("error" in one)
|
|
89
|
+
return { error: `actions[${actions.length}]: ${one.error}` };
|
|
90
|
+
actions.push(one);
|
|
91
|
+
}
|
|
92
|
+
return { actions, cut: Math.max(0, list.length - MAX_ACTION_BATCH), batch: true };
|
|
93
|
+
}
|
|
94
|
+
function claimedOne(body, now) {
|
|
56
95
|
const b = body;
|
|
57
96
|
if (typeof b?.action !== "string")
|
|
58
97
|
return { error: "action must be a string" };
|
|
59
98
|
if (typeof b.place !== "string")
|
|
60
99
|
return { error: "place must be a string" };
|
|
61
|
-
|
|
100
|
+
const at = typeof b.at === "number" && Number.isFinite(b.at) ? Math.min(now, Math.max(now - MAX_ACTION_AGE_MS, b.at)) : now;
|
|
101
|
+
return { place: b.place, action: b.action, at };
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Fold resolved uses into one row per (place, action, day), so a batch is a handful of upserts
|
|
105
|
+
* however many clicks it carries. The order of first appearance is kept.
|
|
106
|
+
*/
|
|
107
|
+
export function tallyActions(uses) {
|
|
108
|
+
const rows = new Map();
|
|
109
|
+
for (const u of uses) {
|
|
110
|
+
const key = `${u.userKey}\u0000${u.place}\u0000${u.action}\u0000${dayKey(u.ts)}`;
|
|
111
|
+
const row = rows.get(key);
|
|
112
|
+
const n = u.uses ?? 1;
|
|
113
|
+
const first = u.firstTs ?? u.ts;
|
|
114
|
+
if (!row)
|
|
115
|
+
rows.set(key, { ...u, uses: n, firstTs: first });
|
|
116
|
+
else
|
|
117
|
+
rows.set(key, { ...row, uses: (row.uses ?? 1) + n, firstTs: Math.min(row.firstTs ?? row.ts, first), ts: Math.max(row.ts, u.ts) });
|
|
118
|
+
}
|
|
119
|
+
return [...rows.values()];
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* The action door's whole answer to one body — what to write and what to say back — so the Bun
|
|
123
|
+
* recorder and the D1 one cannot drift. One action replies as it always has; a batch replies with
|
|
124
|
+
* how many it recorded, how many of those were bucketed as `other`, and how many it cut.
|
|
125
|
+
*/
|
|
126
|
+
export function actionDoor(body, door) {
|
|
127
|
+
const claimed = claimedActions(body, door.now);
|
|
128
|
+
if ("error" in claimed)
|
|
129
|
+
return claimed;
|
|
130
|
+
const resolved = claimed.actions.map((a) => ({
|
|
131
|
+
userKey: door.userKey,
|
|
132
|
+
place: resolvePlace(a.place, door.places),
|
|
133
|
+
action: resolveAction(a.action, door.actions),
|
|
134
|
+
ts: a.at,
|
|
135
|
+
}));
|
|
136
|
+
const bucketed = resolved.filter((u) => u.place === OTHER_PLACE || u.action === OTHER_PLACE).length;
|
|
137
|
+
if (claimed.cut > 0)
|
|
138
|
+
console.warn(`engagement: cut ${claimed.cut} action(s) past the batch cap of ${MAX_ACTION_BATCH}`);
|
|
139
|
+
const [one] = resolved;
|
|
140
|
+
const reply = !claimed.batch && one
|
|
141
|
+
? { ok: true, place: one.place, action: one.action, bucketed: bucketed > 0 }
|
|
142
|
+
: { ok: true, recorded: resolved.length, bucketed, cut: claimed.cut };
|
|
143
|
+
return { uses: tallyActions(resolved), reply };
|
|
62
144
|
}
|
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
* POST /api/engagement/view → the beacon. SESSION-gated; the user id comes
|
|
5
5
|
* from the session, never from the body.
|
|
6
6
|
* POST /api/engagement/action → a feature used on a page — `{ place, action }`, both
|
|
7
|
-
* NAMES resolved against the manifest (`actions.ts`)
|
|
7
|
+
* NAMES resolved against the manifest (`actions.ts`), or a
|
|
8
|
+
* batch of them, `{ actions: [{ place, action, at }…] }`.
|
|
8
9
|
* Mounted only for an app that passes `actions`.
|
|
9
10
|
*
|
|
10
11
|
* 🔴 **There is no HTTP read surface, on purpose** (task `113`/`268`, 2026-09-22).
|
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
* POST /api/engagement/view → the beacon. SESSION-gated; the user id comes
|
|
5
5
|
* from the session, never from the body.
|
|
6
6
|
* POST /api/engagement/action → a feature used on a page — `{ place, action }`, both
|
|
7
|
-
* NAMES resolved against the manifest (`actions.ts`)
|
|
7
|
+
* NAMES resolved against the manifest (`actions.ts`), or a
|
|
8
|
+
* batch of them, `{ actions: [{ place, action, at }…] }`.
|
|
8
9
|
* Mounted only for an app that passes `actions`.
|
|
9
10
|
*
|
|
10
11
|
* 🔴 **There is no HTTP read surface, on purpose** (task `113`/`268`, 2026-09-22).
|
|
@@ -33,8 +34,8 @@
|
|
|
33
34
|
* rule and its reason: `docs/engagement.md` §2 in this package.
|
|
34
35
|
*/
|
|
35
36
|
import { Hono } from "hono";
|
|
36
|
-
import {
|
|
37
|
-
import { OTHER_PLACE,
|
|
37
|
+
import { actionDoor } from "./actions.js";
|
|
38
|
+
import { OTHER_PLACE, resolvePlace } from "./policy.js";
|
|
38
39
|
import { returnCurve, summarize } from "./summary.js";
|
|
39
40
|
/** The recorder half — session-gated, mounted at `/api/engagement`. */
|
|
40
41
|
export function createEngagementRecorder(options) {
|
|
@@ -78,13 +79,11 @@ export function createEngagementRecorder(options) {
|
|
|
78
79
|
catch {
|
|
79
80
|
return c.json({ error: "expected a json body" }, 400);
|
|
80
81
|
}
|
|
81
|
-
const
|
|
82
|
-
if ("error" in
|
|
83
|
-
return c.json({ error:
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
options.store.recordAction({ userKey, place, action, ts: now() });
|
|
87
|
-
return c.json({ ok: true, place, action, bucketed: place === OTHER_PLACE || action === OTHER_PLACE });
|
|
82
|
+
const door = actionDoor(body, { userKey, now: now(), places: options.places, actions });
|
|
83
|
+
if ("error" in door)
|
|
84
|
+
return c.json({ error: door.error }, 400);
|
|
85
|
+
options.store.recordActions(door.uses);
|
|
86
|
+
return c.json(door.reply);
|
|
88
87
|
});
|
|
89
88
|
}
|
|
90
89
|
return app;
|
|
@@ -58,6 +58,8 @@ export declare function recordViewD1(db: D1LikeDatabase, input: {
|
|
|
58
58
|
}>;
|
|
59
59
|
/** Count one resolved action — the Bun store's `recordAction`, as ONE D1 batch (`./actions.ts`). */
|
|
60
60
|
export declare function recordActionD1(db: D1LikeDatabase, use: ActionUse): Promise<void>;
|
|
61
|
+
/** Count a tally of actions (`tallyActions`) as ONE D1 batch: two statements a row, 200 at the batch cap. */
|
|
62
|
+
export declare function recordActionsD1(db: D1LikeDatabase, uses: readonly ActionUse[]): Promise<void>;
|
|
61
63
|
/**
|
|
62
64
|
* The recorder as the kit's `createEngagementRecorder` mounts it — `POST /view` under
|
|
63
65
|
* `ENGAGEMENT_BASE_PATH` — over D1. Recording only: there is no read surface here, as there is
|
|
@@ -75,4 +77,5 @@ export declare function createD1EngagementRecorder(options: {
|
|
|
75
77
|
now?: () => number;
|
|
76
78
|
}): Hono;
|
|
77
79
|
export { ENGAGEMENT_ACTION_DDL } from "./actions.js";
|
|
80
|
+
export { ENGAGEMENT_SESSION_DDL } from "./visits.js";
|
|
78
81
|
export { actionsFromManifest, placesFromManifest } from "./manifestPlaces.js";
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Hono } from "hono";
|
|
2
|
-
import {
|
|
3
|
-
import { dayKey, foldView, OTHER_PLACE,
|
|
2
|
+
import { actionDoor, actionStatements } from "./actions.js";
|
|
3
|
+
import { dayKey, foldView, OTHER_PLACE, resolvePlace } from "./policy.js";
|
|
4
|
+
import { ENGAGEMENT_SESSION_DDL, visitStatements } from "./visits.js";
|
|
4
5
|
/** The kit store's own tables and indexes, as one-line DDL — see the header. */
|
|
5
6
|
export const ENGAGEMENT_DDL = [
|
|
6
7
|
"CREATE TABLE IF NOT EXISTS engagement_days ( user_key TEXT NOT NULL, place TEXT NOT NULL, day TEXT NOT NULL, views INTEGER NOT NULL DEFAULT 0, active_ms INTEGER NOT NULL DEFAULT 0, sessions INTEGER NOT NULL DEFAULT 0, first_ts INTEGER NOT NULL, last_ts INTEGER NOT NULL, PRIMARY KEY (user_key, place, day) )",
|
|
@@ -49,11 +50,37 @@ export async function recordViewD1(db, input) {
|
|
|
49
50
|
last_ts = excluded.last_ts, last_place = excluded.last_place`)
|
|
50
51
|
.bind(userKey, sessionDelta, ts, ts, place, fold.activeMs));
|
|
51
52
|
await db.batch(statements);
|
|
53
|
+
await recordVisitD1(db, { userKey, ts }, fold);
|
|
52
54
|
return fold;
|
|
53
55
|
}
|
|
56
|
+
/**
|
|
57
|
+
* The view's visit (`visits.ts`), after its batch and never in it, and it never throws: the view is
|
|
58
|
+
* already safe, and a beacon's answer must not depend on this. The first write on a D1 without the
|
|
59
|
+
* table creates it, so a version bump needs no migration in any app and no deploy order.
|
|
60
|
+
*/
|
|
61
|
+
async function recordVisitD1(db, view, fold) {
|
|
62
|
+
const write = () => db.batch(visitStatements(view, fold).map(({ sql, params }) => db.prepare(sql).bind(...params)));
|
|
63
|
+
try {
|
|
64
|
+
await write().catch(async (error) => {
|
|
65
|
+
if (!/no such table/i.test(String(error)))
|
|
66
|
+
throw error;
|
|
67
|
+
await db.batch(ENGAGEMENT_SESSION_DDL.map((ddl) => db.prepare(ddl)));
|
|
68
|
+
await write();
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
console.warn(`[engagement] a visit was not recorded: ${String(error)}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
54
75
|
/** Count one resolved action — the Bun store's `recordAction`, as ONE D1 batch (`./actions.ts`). */
|
|
55
76
|
export async function recordActionD1(db, use) {
|
|
56
|
-
await db
|
|
77
|
+
await recordActionsD1(db, [use]);
|
|
78
|
+
}
|
|
79
|
+
/** Count a tally of actions (`tallyActions`) as ONE D1 batch: two statements a row, 200 at the batch cap. */
|
|
80
|
+
export async function recordActionsD1(db, uses) {
|
|
81
|
+
if (uses.length === 0)
|
|
82
|
+
return;
|
|
83
|
+
await db.batch(uses.flatMap(actionStatements).map(({ sql, params }) => db.prepare(sql).bind(...params)));
|
|
57
84
|
}
|
|
58
85
|
/**
|
|
59
86
|
* The recorder as the kit's `createEngagementRecorder` mounts it — `POST /view` under
|
|
@@ -94,16 +121,15 @@ export function createD1EngagementRecorder(options) {
|
|
|
94
121
|
catch {
|
|
95
122
|
return c.json({ error: "expected a json body" }, 400);
|
|
96
123
|
}
|
|
97
|
-
const
|
|
98
|
-
if ("error" in
|
|
99
|
-
return c.json({ error:
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
await recordActionD1(options.db, { userKey, place, action, ts: now() });
|
|
103
|
-
return c.json({ ok: true, place, action, bucketed: place === OTHER_PLACE || action === OTHER_PLACE });
|
|
124
|
+
const door = actionDoor(body, { userKey, now: now(), places: options.places, actions });
|
|
125
|
+
if ("error" in door)
|
|
126
|
+
return c.json({ error: door.error }, 400);
|
|
127
|
+
await recordActionsD1(options.db, door.uses);
|
|
128
|
+
return c.json(door.reply);
|
|
104
129
|
});
|
|
105
130
|
}
|
|
106
131
|
return app;
|
|
107
132
|
}
|
|
108
133
|
export { ENGAGEMENT_ACTION_DDL } from "./actions.js";
|
|
134
|
+
export { ENGAGEMENT_SESSION_DDL } from "./visits.js";
|
|
109
135
|
export { actionsFromManifest, placesFromManifest } from "./manifestPlaces.js";
|
|
@@ -14,8 +14,10 @@
|
|
|
14
14
|
* One row per (user, place, UTC day). The alternative — a row per view — buys
|
|
15
15
|
* nothing at this fleet's size and costs the one thing worth protecting: an
|
|
16
16
|
* event log is a timeline, and a timeline of a household's private apps is a
|
|
17
|
-
* far more sensitive object than a count. Sequence is exactly the
|
|
18
|
-
* we do not want to be holding, so the schema cannot express it.
|
|
17
|
+
* far more sensitive object than a count. Sequence of PLACES is exactly the
|
|
18
|
+
* information we do not want to be holding, so the schema cannot express it.
|
|
19
|
+
* `engagement_sessions` (`visits.ts`, the owner's ask of 2026-10-30) holds when a
|
|
20
|
+
* visit began and ended and has no place in it.
|
|
19
21
|
*
|
|
20
22
|
* The one place ordering DOES matter is sessionization, and it is resolved at
|
|
21
23
|
* WRITE time against `engagement_users.last_ts` — a single stored clock per
|
|
@@ -73,6 +75,8 @@ export declare class EngagementStore {
|
|
|
73
75
|
* dwell: an action is something done on the page the view already counted.
|
|
74
76
|
*/
|
|
75
77
|
recordAction(use: ActionUse): void;
|
|
78
|
+
/** Count a tally of actions (`tallyActions`) in ONE transaction — what a batched POST writes. */
|
|
79
|
+
recordActions(uses: readonly ActionUse[]): void;
|
|
76
80
|
/** Every (user, place, action) lifetime roll-up, most used first. */
|
|
77
81
|
actions(): EngagementActionUse[];
|
|
78
82
|
/** Every account's roll-up for this app, most recently seen first. */
|
|
@@ -84,7 +88,7 @@ export declare class EngagementStore {
|
|
|
84
88
|
/**
|
|
85
89
|
* Drop daily rows older than the retention window.
|
|
86
90
|
*
|
|
87
|
-
* 🔴 Only the daily grains (`engagement_days`, `engagement_action_days`). The roll-ups are deliberately untouched —
|
|
91
|
+
* 🔴 Only the daily grains (`engagement_days`, `engagement_action_days`) and the visits. The roll-ups are deliberately untouched —
|
|
88
92
|
* see the file header. An agent "completing" this by trimming them too would
|
|
89
93
|
* delete the only record that somebody used to be here, which is the entire
|
|
90
94
|
* drop-off signal.
|
|
@@ -14,8 +14,10 @@
|
|
|
14
14
|
* One row per (user, place, UTC day). The alternative — a row per view — buys
|
|
15
15
|
* nothing at this fleet's size and costs the one thing worth protecting: an
|
|
16
16
|
* event log is a timeline, and a timeline of a household's private apps is a
|
|
17
|
-
* far more sensitive object than a count. Sequence is exactly the
|
|
18
|
-
* we do not want to be holding, so the schema cannot express it.
|
|
17
|
+
* far more sensitive object than a count. Sequence of PLACES is exactly the
|
|
18
|
+
* information we do not want to be holding, so the schema cannot express it.
|
|
19
|
+
* `engagement_sessions` (`visits.ts`, the owner's ask of 2026-10-30) holds when a
|
|
20
|
+
* visit began and ended and has no place in it.
|
|
19
21
|
*
|
|
20
22
|
* The one place ordering DOES matter is sessionization, and it is resolved at
|
|
21
23
|
* WRITE time against `engagement_users.last_ts` — a single stored clock per
|
|
@@ -36,6 +38,7 @@ import { mkdirSync } from "node:fs";
|
|
|
36
38
|
import { dirname, resolve } from "node:path";
|
|
37
39
|
import { actionStatements, ENGAGEMENT_ACTION_DDL } from "./actions.js";
|
|
38
40
|
import { dayKey, foldView } from "./policy.js";
|
|
41
|
+
import { ENGAGEMENT_SESSION_DDL, visitStatements } from "./visits.js";
|
|
39
42
|
/**
|
|
40
43
|
* `bun:sqlite`'s `create: true` creates the FILE, never the directory above it, so a first boot
|
|
41
44
|
* into an empty data dir would throw here. Swallowed on purpose: the open that follows names the
|
|
@@ -114,6 +117,9 @@ export class EngagementStore {
|
|
|
114
117
|
// Feature actions (task 3470) — `actions.ts` says why they are their own two tables.
|
|
115
118
|
for (const ddl of ENGAGEMENT_ACTION_DDL)
|
|
116
119
|
this.handle.run(ddl);
|
|
120
|
+
// Visits (the owner's "at the same time", 2026-10-30) — `visits.ts` says why they are their own table.
|
|
121
|
+
for (const ddl of ENGAGEMENT_SESSION_DDL)
|
|
122
|
+
this.handle.run(ddl);
|
|
117
123
|
}
|
|
118
124
|
/**
|
|
119
125
|
* Record one resolved place-view.
|
|
@@ -162,6 +168,8 @@ export class EngagementStore {
|
|
|
162
168
|
active_ms = active_ms + ?,
|
|
163
169
|
last_ts = excluded.last_ts,
|
|
164
170
|
last_place = excluded.last_place`, [userKey, sessionDelta, ts, ts, place, fold.activeMs]);
|
|
171
|
+
for (const { sql, params } of visitStatements({ userKey, ts }, fold))
|
|
172
|
+
this.handle.run(sql, params);
|
|
165
173
|
// Amortised, exactly as the metrics store trims: a DELETE per beacon would
|
|
166
174
|
// cost more than the beacon, and never trimming lets a long-lived daemon
|
|
167
175
|
// keep every day it has ever served.
|
|
@@ -175,13 +183,19 @@ export class EngagementStore {
|
|
|
175
183
|
* dwell: an action is something done on the page the view already counted.
|
|
176
184
|
*/
|
|
177
185
|
recordAction(use) {
|
|
178
|
-
|
|
186
|
+
this.recordActions([use]);
|
|
187
|
+
}
|
|
188
|
+
/** Count a tally of actions (`tallyActions`) in ONE transaction — what a batched POST writes. */
|
|
189
|
+
recordActions(uses) {
|
|
190
|
+
const last = uses.at(-1);
|
|
191
|
+
if (!last)
|
|
192
|
+
return;
|
|
179
193
|
this.handle.transaction(() => {
|
|
180
|
-
for (const { sql, params } of
|
|
194
|
+
for (const { sql, params } of uses.flatMap(actionStatements))
|
|
181
195
|
this.handle.run(sql, params);
|
|
182
196
|
})();
|
|
183
197
|
if (++this.writes % 256 === 0)
|
|
184
|
-
this.prune(
|
|
198
|
+
this.prune(last.ts);
|
|
185
199
|
}
|
|
186
200
|
/** Every (user, place, action) lifetime roll-up, most used first. */
|
|
187
201
|
actions() {
|
|
@@ -221,7 +235,7 @@ export class EngagementStore {
|
|
|
221
235
|
/**
|
|
222
236
|
* Drop daily rows older than the retention window.
|
|
223
237
|
*
|
|
224
|
-
* 🔴 Only the daily grains (`engagement_days`, `engagement_action_days`). The roll-ups are deliberately untouched —
|
|
238
|
+
* 🔴 Only the daily grains (`engagement_days`, `engagement_action_days`) and the visits. The roll-ups are deliberately untouched —
|
|
225
239
|
* see the file header. An agent "completing" this by trimming them too would
|
|
226
240
|
* delete the only record that somebody used to be here, which is the entire
|
|
227
241
|
* drop-off signal.
|
|
@@ -230,7 +244,8 @@ export class EngagementStore {
|
|
|
230
244
|
const cutoff = dayKey(at - this.retentionDays * 86_400_000);
|
|
231
245
|
// The action DAYS age out with the view days; `engagement_actions` is a roll-up and stays.
|
|
232
246
|
const actionDays = this.handle.run("DELETE FROM engagement_action_days WHERE day < ?", [cutoff]).changes;
|
|
233
|
-
|
|
247
|
+
const visits = this.handle.run("DELETE FROM engagement_sessions WHERE start_ts < ?", [at - this.retentionDays * 86_400_000]).changes;
|
|
248
|
+
return this.handle.run("DELETE FROM engagement_days WHERE day < ?", [cutoff]).changes + actionDays + visits;
|
|
234
249
|
}
|
|
235
250
|
/** Row counts + age bounds, for the retention card. */
|
|
236
251
|
stats() {
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Visits — WHEN a person was in this app, so station can say which apps they used at the same time.
|
|
3
|
+
*
|
|
4
|
+
* The owner, 2026-10-30: *"see a timeline of what apps they went to, for how long, which ones at the
|
|
5
|
+
* same time"*. `engagement_days` answers the first two per DAY; its `first_ts`/`last_ts` span every
|
|
6
|
+
* visit that day, so "more than one app on the same day" can be two visits hours apart.
|
|
7
|
+
*
|
|
8
|
+
* ── What it may hold, and why this much ─────────────────────────────────────
|
|
9
|
+
* `store.ts`'s header refuses a timeline of a household's private apps, and that still holds for
|
|
10
|
+
* everything with a PLACE in it. A row here has no place: a visit's start, end, view count and
|
|
11
|
+
* attention, the least that answers his question, and only for {@link ENGAGEMENT_VISIT_RETENTION_DAYS}.
|
|
12
|
+
* One row per VISIT (the same cut as the sessions count, `policy.ts:foldView`), not per beacon: 264
|
|
13
|
+
* visits across the fleet in the 30 days to 2026-10-30, against "a few thousand a month" as the line.
|
|
14
|
+
*
|
|
15
|
+
* 🔴 Its own DDL, not appended to `ENGAGEMENT_DDL`, for the reason `actions.ts` gives: an app whose
|
|
16
|
+
* schema is generated from that list goes red on the version bump alone. And on a Worker the write is
|
|
17
|
+
* NOT in the view's batch: a D1 missing this table would fail that whole atomic batch and lose the view.
|
|
18
|
+
* `d1.ts` `recordVisitD1` runs it after, creates the table the first time it is missing, and never throws.
|
|
19
|
+
*
|
|
20
|
+
* Pure and Worker-safe: the Bun store and the D1 recorder both write through {@link visitStatements}.
|
|
21
|
+
*/
|
|
22
|
+
import type { ViewFold } from "./policy.js";
|
|
23
|
+
/** As long as the daily grain: a visit is the more sensitive row, so it is never kept longer. */
|
|
24
|
+
export declare const ENGAGEMENT_VISIT_RETENTION_DAYS = 120;
|
|
25
|
+
export declare const ENGAGEMENT_SESSION_DDL: readonly string[];
|
|
26
|
+
/**
|
|
27
|
+
* What one view does to the visits: opens one, trimming the ones past retention, or extends the open
|
|
28
|
+
* one. A view in a visit that began before this table existed updates nothing, and its visit is simply
|
|
29
|
+
* not recorded; the next one is.
|
|
30
|
+
*/
|
|
31
|
+
export declare function visitStatements(view: {
|
|
32
|
+
userKey: string;
|
|
33
|
+
ts: number;
|
|
34
|
+
}, fold: ViewFold): Array<{
|
|
35
|
+
sql: string;
|
|
36
|
+
params: (string | number)[];
|
|
37
|
+
}>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** As long as the daily grain: a visit is the more sensitive row, so it is never kept longer. */
|
|
2
|
+
export const ENGAGEMENT_VISIT_RETENTION_DAYS = 120;
|
|
3
|
+
export const ENGAGEMENT_SESSION_DDL = [
|
|
4
|
+
"CREATE TABLE IF NOT EXISTS engagement_sessions ( user_key TEXT NOT NULL, start_ts INTEGER NOT NULL, end_ts INTEGER NOT NULL, views INTEGER NOT NULL DEFAULT 0, active_ms INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (user_key, start_ts) )",
|
|
5
|
+
"CREATE INDEX IF NOT EXISTS idx_engagement_sessions_start ON engagement_sessions (start_ts)",
|
|
6
|
+
];
|
|
7
|
+
/**
|
|
8
|
+
* What one view does to the visits: opens one, trimming the ones past retention, or extends the open
|
|
9
|
+
* one. A view in a visit that began before this table existed updates nothing, and its visit is simply
|
|
10
|
+
* not recorded; the next one is.
|
|
11
|
+
*/
|
|
12
|
+
export function visitStatements(view, fold) {
|
|
13
|
+
const { userKey, ts } = view;
|
|
14
|
+
if (fold.newSession)
|
|
15
|
+
return [
|
|
16
|
+
// IGNORE: two views in one millisecond are one visit opened twice.
|
|
17
|
+
{ sql: "INSERT OR IGNORE INTO engagement_sessions (user_key, start_ts, end_ts, views, active_ms) VALUES (?, ?, ?, 1, 0)", params: [userKey, ts, ts] },
|
|
18
|
+
{ sql: "DELETE FROM engagement_sessions WHERE start_ts < ?", params: [ts - ENGAGEMENT_VISIT_RETENTION_DAYS * 86_400_000] },
|
|
19
|
+
];
|
|
20
|
+
return [
|
|
21
|
+
{
|
|
22
|
+
// MAX: a device with a wrong clock makes a number boring, never a visit that ends before it began.
|
|
23
|
+
sql: `UPDATE engagement_sessions SET end_ts = MAX(end_ts, ?), views = views + 1, active_ms = active_ms + ?
|
|
24
|
+
WHERE user_key = ? AND start_ts = (SELECT MAX(start_ts) FROM engagement_sessions WHERE user_key = ?)`,
|
|
25
|
+
params: [ts, fold.activeMs, userKey, userKey],
|
|
26
|
+
},
|
|
27
|
+
];
|
|
28
|
+
}
|
|
@@ -54,6 +54,14 @@ export interface YtDownload {
|
|
|
54
54
|
interface YtDlpCallOptions {
|
|
55
55
|
/** A Netscape-format cookie jar yt-dlp reads (`--cookies`). The caller owns and removes it. */
|
|
56
56
|
cookiesFile?: string;
|
|
57
|
+
/**
|
|
58
|
+
* A RESUMABLE download: yt-dlp writes into this directory, which the CALLER owns — made if it is
|
|
59
|
+
* missing, kept with its `.part` files when the download fails, so the next call with the same
|
|
60
|
+
* directory continues where the bytes stopped instead of starting a 25 GB film again. The owner,
|
|
61
|
+
* 2026-10-29: *"if my internet was to go out … my downloads in process could be picked back up
|
|
62
|
+
* where they left off"* (forge task 4010). `dispose` still removes it once the file is had.
|
|
63
|
+
*/
|
|
64
|
+
workDir?: string;
|
|
57
65
|
}
|
|
58
66
|
/**
|
|
59
67
|
* Fetch one video. `target` is a YouTube video id, or a page URL (`https://…`) of any site yt-dlp
|
|
@@ -96,6 +104,7 @@ export declare function ytDlpArgs(target: string, outDir: string, profile: Pick<
|
|
|
96
104
|
cacheDir?: string;
|
|
97
105
|
jsRuntime?: string;
|
|
98
106
|
cookiesFile?: string;
|
|
107
|
+
resumable?: boolean;
|
|
99
108
|
}): string[];
|
|
100
109
|
/** Run a program, handing each stdout line over as it arrives. Injected in tests. */
|
|
101
110
|
export type RunLines = (binary: string, args: string[], onLine: (line: string) => void) => Promise<{
|
|
@@ -19,7 +19,8 @@
|
|
|
19
19
|
* age check) is handed the owner's own cookie jar per call; reading that jar is the app's business.
|
|
20
20
|
*
|
|
21
21
|
* ── The file stays on disk ──────────────────────────────────────────────────────────────
|
|
22
|
-
* A download resolves to a PATH inside a fresh temporary directory
|
|
22
|
+
* A download resolves to a PATH inside a fresh temporary directory — or inside the caller's own
|
|
23
|
+
* `workDir`, which makes it resumable across failures (forge task 4010) — and the caller disposes of
|
|
23
24
|
* it. A 1080p video is gigabytes, and reading it into memory to hand it over would make the
|
|
24
25
|
* agent's footprint the size of the largest video in a playlist. Music, whose files are a few
|
|
25
26
|
* MB, reads the bytes and disposes at once.
|
|
@@ -178,7 +179,9 @@ export function ytDlpArgs(target, outDir, profile, options = {}) {
|
|
|
178
179
|
...(profile.extraArgs ?? []),
|
|
179
180
|
"--max-filesize",
|
|
180
181
|
profile.maxFilesize,
|
|
181
|
-
|
|
182
|
+
// Resumable: keep the `.part` and continue it. Otherwise no `.part` at all — a fresh directory
|
|
183
|
+
// per run has nothing to continue, and a half file there is only litter.
|
|
184
|
+
...(options.resumable ? ["--continue"] : ["--no-part"]),
|
|
182
185
|
"--no-mtime",
|
|
183
186
|
"--no-colors",
|
|
184
187
|
"--newline",
|
|
@@ -189,7 +192,9 @@ export function ytDlpArgs(target, outDir, profile, options = {}) {
|
|
|
189
192
|
"--print",
|
|
190
193
|
`after_move:${INFO_MARK}%()j`,
|
|
191
194
|
"-o",
|
|
192
|
-
|
|
195
|
+
// Resumable runs name the file for the directory, not the site's id: a signed URL resolved
|
|
196
|
+
// afresh on the next try can carry a different id, and a different name is a fresh download.
|
|
197
|
+
join(outDir, options.resumable ? "download.%(ext)s" : "%(id)s.%(ext)s"),
|
|
193
198
|
"--",
|
|
194
199
|
isPageUrl(target) ? target : `https://www.youtube.com/watch?v=${target}`,
|
|
195
200
|
];
|
|
@@ -293,7 +298,10 @@ export function createYtDlp(options) {
|
|
|
293
298
|
};
|
|
294
299
|
/** One yt-dlp run into a fresh directory. Throws a classified error on failure. */
|
|
295
300
|
const attempt = async (target, onProgress, call = {}) => {
|
|
296
|
-
const
|
|
301
|
+
const resumable = call.workDir !== undefined;
|
|
302
|
+
const dir = call.workDir ?? (await mkdtemp(join(options.tmpRoot ?? tmpdir(), "ytdlp-")));
|
|
303
|
+
if (resumable)
|
|
304
|
+
await mkdir(dir, { recursive: true });
|
|
297
305
|
const dispose = () => rm(dir, { recursive: true, force: true });
|
|
298
306
|
try {
|
|
299
307
|
let info = null;
|
|
@@ -301,6 +309,7 @@ export function createYtDlp(options) {
|
|
|
301
309
|
...(options.cacheDir ? { cacheDir: options.cacheDir } : {}),
|
|
302
310
|
...(jsRuntime ? { jsRuntime } : {}),
|
|
303
311
|
...(call.cookiesFile ? { cookiesFile: call.cookiesFile } : {}),
|
|
312
|
+
...(resumable ? { resumable } : {}),
|
|
304
313
|
}), (line) => {
|
|
305
314
|
const fraction = parseYtProgress(line);
|
|
306
315
|
if (fraction !== null)
|
|
@@ -318,7 +327,9 @@ export function createYtDlp(options) {
|
|
|
318
327
|
return { path: found.filepath, extension, info: found, dir, dispose };
|
|
319
328
|
}
|
|
320
329
|
catch (error) {
|
|
321
|
-
|
|
330
|
+
// 🔴 A resumable directory is the caller's, and its `.part` is the whole point: keep it.
|
|
331
|
+
if (!resumable)
|
|
332
|
+
await dispose();
|
|
322
333
|
throw error;
|
|
323
334
|
}
|
|
324
335
|
};
|