Loading files
be66d9be7This file is pinned to the selected release. Download the original to open it in your design tool.
/**
* Presence / remote-usage daily tracking — write path for `UserDailyPresence`,
* `UserDailyRemoteUsage`, `UserDailyDevicePresence` and `MachineDailyPresence`
* (prisma/schema.prisma). Separate model family and separate module from the opt-in `Analytics*`
* telemetry in analyticsIngest.ts: these signals are derived directly from the web-ws/device-ws/
* adapter-ws relays (src/lib/webWs.ts, src/lib/deviceWs.ts, src/lib/adapterWs.ts), not from a
* collector upload.
*
* Unlike analyticsIngest.ts, none of these rows need last-write-wins ordering (there's no
* client-supplied revision to defend against), so each touch is a plain atomic `upsert` on the
* day's unique key — no separate create-then-swallow-P2002 step that could drop a concurrent
* write's `lastSeenAt`/counter increment.
*
* All entry points are meant to be called fire-and-forget from the hot path (connection open,
* periodic re-seed, p2p_offer) — callers must not await them inline.
*/
import { prisma } from './prisma.js'
import { utcDayKey, utcDayStart } from '../types/analytics.js'
/**
* Mark a user online for the UTC day containing `now`. Call once on connect
* (`isNewConnection: true`, bumps `connections`) and again whenever a day-boundary check on an
* open connection finds the day has changed (`isNewConnection: false`, just touches `lastSeenAt`).
*
* `connections` counts connections OPENED on that day: a touch that is the first write of a new
* UTC day but is not a connect (a session spanning midnight) creates the row with `connections: 0`,
* so summing the column across days never double-counts one long session. Same rule for every
* `touch*OnlineDay` below.
*/
export async function touchUserOnlineDay(
userId: string,
now: Date,
opts: { isNewConnection: boolean },
): Promise<void> {
const dayUtc = utcDayStart(now)
await prisma.userDailyPresence.upsert({
where: { userId_dayUtc: { userId, dayUtc } },
create: { userId, dayUtc, connections: opts.isNewConnection ? 1 : 0, firstSeenAt: now, lastSeenAt: now },
update: {
lastSeenAt: now,
...(opts.isNewConnection ? { connections: { increment: 1 } } : {}),
},
})
}
/**
* Record that a user actually established a remote p2p connection (a `p2p_offer` frame passed
* through the relay) to `machineId` on the UTC day containing `now`.
*/
export async function recordRemoteUsage(userId: string, machineId: string, now: Date): Promise<void> {
const dayUtc = utcDayStart(now)
await prisma.userDailyRemoteUsage.upsert({
where: { userId_machineId_dayUtc: { userId, machineId, dayUtc } },
create: { userId, machineId, dayUtc, sessions: 1, firstSeenAt: now, lastSeenAt: now },
update: { lastSeenAt: now, sessions: { increment: 1 } },
})
}
/**
* Mark a user's device online for the UTC day containing `now`, mirroring `touchUserOnlineDay`
* for the device-ws relay (src/lib/deviceWs.ts) instead of web-ws.
*/
export async function touchDeviceOnlineDay(
userId: string,
deviceId: string,
now: Date,
opts: { isNewConnection: boolean },
): Promise<void> {
const dayUtc = utcDayStart(now)
await prisma.userDailyDevicePresence.upsert({
where: { userId_deviceId_dayUtc: { userId, deviceId, dayUtc } },
create: { userId, deviceId, dayUtc, connections: opts.isNewConnection ? 1 : 0, firstSeenAt: now, lastSeenAt: now },
update: {
lastSeenAt: now,
...(opts.isNewConnection ? { connections: { increment: 1 } } : {}),
},
})
}
/**
* Mark a machine's `harness` daemon online for the UTC day containing `now`, mirroring
* `touchUserOnlineDay` for the adapter-ws relay (src/lib/adapterWs.ts). `userId` is the owner at
* connect time, denormalized so per-user rollups need no join through `machines`.
*/
export async function touchMachineOnlineDay(
userId: string,
machineId: string,
now: Date,
opts: { isNewConnection: boolean },
): Promise<void> {
const dayUtc = utcDayStart(now)
await prisma.machineDailyPresence.upsert({
where: { machineId_dayUtc: { machineId, dayUtc } },
create: { machineId, userId, dayUtc, connections: opts.isNewConnection ? 1 : 0, firstSeenAt: now, lastSeenAt: now },
update: {
lastSeenAt: now,
...(opts.isNewConnection ? { connections: { increment: 1 } } : {}),
},
})
}
/** Last SUCCESSFUL presence write for one open socket — `dayKey` null until the first one lands. */
export interface PresenceWriteState { dayKey: string | null; wroteAt: number }
/**
* Whether a heartbeat on an open socket should write presence now: yes when nothing has been
* written yet, when the UTC day rolled over since the last write (so the new day gets its row),
* or when the last write is at least `minIntervalMs` old. Lets a caller ride an existing
* high-frequency tick (15s node heartbeat) without writing Mongo at that rate.
*/
export function presenceWriteDue(last: PresenceWriteState, now: Date, minIntervalMs: number): boolean {
if (last.dayKey === null) return true
if (utcDayKey(now) !== last.dayKey) return true
return now.getTime() - last.wroteAt >= minIntervalMs
}