@obzerver/server 0.17.3 → 0.18.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/queries.js CHANGED
@@ -925,38 +925,103 @@ export function outbound(db, w) {
925
925
  }).sort((a, b) => b.calls - a.calls);
926
926
  }
927
927
  // ------------------------------------------------------------------ users
928
+ /** The email domain of a user id, the tenant's fallback when the app sets none. */
929
+ const domainOf = (u) => (u && u.includes('@') ? u.slice(u.lastIndexOf('@') + 1).toLowerCase() : null);
930
+ /**
931
+ * Users in the window, busiest first. Each has its tenant: the one the app set (`getTenantId`, `setTenant`,
932
+ * the OTLP `tenant.id` attribute), or else the email domain, marked `guessed`. With `groupBy: 'tenant'`,
933
+ * the same numbers per tenant ('customer' is the name before 0.18).
934
+ */
928
935
  export function users(db, w, { groupBy } = {}) {
929
936
  const s = scope(w);
930
- const list = db.all(`SELECT user_id, COUNT(*) calls, SUM(failed) failed, AVG(duration) avg, MAX(ts) last, MIN(ts) first, COUNT(DISTINCT name) ops
937
+ if (groupBy === 'tenant' || groupBy === 'customer') {
938
+ // Requests with a tenant count for it, with or without a user; the rest go to the user's email domain.
939
+ const rows = db.all(`SELECT COALESCE(tenant_id, CASE WHEN instr(user_id, '@') > 0 THEN lower(substr(user_id, instr(user_id, '@') + 1)) END) tenant,
940
+ tenant_id IS NULL guessed, COUNT(DISTINCT user_id) users, COUNT(*) calls, SUM(failed) failed, MAX(ts) last
941
+ FROM traces INDEXED BY traces_window WHERE kind IN ('http', 'job') AND (user_id IS NOT NULL OR tenant_id IS NOT NULL) AND ${s.sql}
942
+ GROUP BY 1, 2 ORDER BY calls DESC LIMIT 500`, ...s.args);
943
+ return rows.map((r) => ({ tenant: r.tenant ?? '(no tenant)', guessed: !!r.guessed, users: r.users, calls: r.calls, failed: r.failed, lastSeen: r.last, failureRate: round((r.failed / r.calls) * 100) }));
944
+ }
945
+ return db.all(`SELECT user_id, COUNT(*) calls, SUM(failed) failed, AVG(duration) avg, MAX(ts) last, MIN(ts) first, COUNT(DISTINCT name) ops,
946
+ MAX(tenant_id) tenant, COUNT(DISTINCT tenant_id) tenants
931
947
  FROM traces WHERE user_id IS NOT NULL AND ${s.sql} GROUP BY user_id ORDER BY calls DESC LIMIT 500`, ...s.args)
932
- .map((r) => ({ userId: r.user_id, calls: r.calls, failed: r.failed, failureRate: round((r.failed / r.calls) * 100), avg: round(r.avg), lastSeen: r.last, firstSeen: r.first, operations: r.ops }));
933
- if (groupBy !== 'customer')
934
- return list;
935
- return [...group(list, (u) => (u.userId.includes('@') ? u.userId.split('@')[1] : '(no domain)')).entries()].map(([customer, us]) => {
936
- const calls = sum(us.map((u) => u.calls));
937
- const failed = sum(us.map((u) => u.failed));
938
- return { customer, users: us.length, calls, failed, lastSeen: maxOf(us.map((u) => u.lastSeen)), failureRate: round((failed / calls) * 100) };
939
- }).sort((a, b) => b.calls - a.calls);
948
+ .map((r) => ({
949
+ userId: r.user_id, calls: r.calls, failed: r.failed, failureRate: round((r.failed / r.calls) * 100), avg: round(r.avg), lastSeen: r.last, firstSeen: r.first, operations: r.ops,
950
+ tenant: r.tenant ?? domainOf(r.user_id), tenantGuessed: !r.tenant && !!domainOf(r.user_id), tenants: r.tenants,
951
+ }));
952
+ }
953
+ /** A user's tenants in the window, busiest first; the email domain (guessed) when the app set none. */
954
+ function tenantsOf(db, w, id) {
955
+ const s = scope(w);
956
+ const set = db.all(`SELECT tenant_id t FROM traces WHERE user_id = ? AND tenant_id IS NOT NULL AND ${s.sql} GROUP BY tenant_id ORDER BY COUNT(*) DESC`, id, ...s.args).map((r) => r.t);
957
+ if (set.length)
958
+ return { tenants: set, tenantGuessed: false };
959
+ const d = domainOf(id);
960
+ return { tenants: d ? [d] : [], tenantGuessed: !!d };
961
+ }
962
+ /** The tenants behind a set of errors: the ones the app set, else the users' email domains. */
963
+ export function tenantsOfErrors(rows) {
964
+ return [...new Set(rows.map((r) => r.tenant_id ?? domainOf(r.user_id)).filter((t) => !!t))];
965
+ }
966
+ /** A gap longer than this between two actions starts a new session. */
967
+ export const SESSION_GAP = 30 * 60e3;
968
+ /** Sessions the user page replays; the rest are on the sessions page. */
969
+ export const REPLAY_SESSIONS = 4;
970
+ /** Every session of a user in the window, oldest first, numbered from 1. */
971
+ function sessionsOf(db, w, id) {
972
+ const s = scope(w);
973
+ const rows = db.all(`SELECT ts, failed FROM traces WHERE user_id = ? AND ${s.sql} ORDER BY ts`, id, ...s.args);
974
+ const out = [];
975
+ for (const r of rows) {
976
+ const cur = out[out.length - 1];
977
+ if (cur && r.ts - cur.end <= SESSION_GAP) {
978
+ cur.end = r.ts;
979
+ cur.actions++;
980
+ cur.failed += r.failed ? 1 : 0;
981
+ }
982
+ else
983
+ out.push({ n: out.length + 1, start: r.ts, end: r.ts, actions: 1, failed: r.failed ? 1 : 0 });
984
+ }
985
+ return out;
986
+ }
987
+ function actionsBetween(db, w, id, from, to, limit = 1000) {
988
+ const s = scope({ ...w, from: Math.max(w.from, from), to: Math.min(w.to, to) });
989
+ return db.all(`SELECT id, ts, name, kind, status, duration, failed, error_message, trace_id FROM traces WHERE user_id = ? AND ${s.sql} ORDER BY ts DESC LIMIT ${limit}`, id, ...s.args);
990
+ }
991
+ /** Newest session first, each with its actions newest first. */
992
+ function withActions(db, w, id, list) {
993
+ return list.map((x) => ({ ...x, items: actionsBetween(db, w, id, x.start, x.end) }));
940
994
  }
941
995
  export function user(db, w, id) {
942
996
  const s = scope(w);
943
- const actions = db.all(`SELECT id, ts, name, kind, status, duration, failed, error_message, trace_id FROM traces WHERE user_id = ? AND ${s.sql} ORDER BY ts DESC LIMIT 300`, id, ...s.args);
997
+ const all = sessionsOf(db, w, id);
944
998
  const ops = db.all(`SELECT name, COUNT(*) calls, SUM(failed) failed, AVG(duration) avg FROM traces WHERE user_id = ? AND ${s.sql} GROUP BY name ORDER BY calls DESC`, id, ...s.args);
945
999
  const errors = db.all(`SELECT fingerprint, class, MAX(message) message, COUNT(*) n FROM errors WHERE user_id = ? AND ${s.sql} GROUP BY fingerprint ORDER BY n DESC`, id, ...s.args);
946
- // Paths: consecutive action transitions within 30 minutes.
947
- const chron = [...actions].reverse();
1000
+ // Last seen anywhere, not only in this window.
1001
+ const last = db.get(`SELECT MAX(ts) ts FROM traces WHERE user_id = ?${scopeBase(w).sql}`, id, ...scopeBase(w).args).ts;
1002
+ // Paths: consecutive action transitions within a session, over the newest 300 actions.
1003
+ const chron = actionsBetween(db, w, id, w.from, w.to, 300).reverse();
948
1004
  const paths = new Map();
949
1005
  for (let i = 1; i < chron.length; i++) {
950
- if (chron[i].ts - chron[i - 1].ts > 30 * 60e3)
1006
+ if (chron[i].ts - chron[i - 1].ts > SESSION_GAP)
951
1007
  continue;
952
1008
  const k = `${chron[i - 1].name} → ${chron[i].name}`;
953
1009
  paths.set(k, (paths.get(k) || 0) + 1);
954
1010
  }
955
1011
  return {
956
- userId: id, actions, operations: ops.map((o) => ({ ...o, avg: round(o.avg) })), errors,
1012
+ userId: id, lastSeen: last, sessionCount: all.length, ...tenantsOf(db, w, id),
1013
+ actionCount: sum(all.map((x) => x.actions)), failedCount: sum(all.map((x) => x.failed)),
1014
+ sessions: withActions(db, w, id, all.slice(-REPLAY_SESSIONS).reverse()),
1015
+ operations: ops.map((o) => ({ ...o, avg: round(o.avg) })), errors,
957
1016
  paths: [...paths.entries()].map(([path, n]) => ({ path, n })).sort((a, b) => b.n - a.n).slice(0, 15),
958
1017
  };
959
1018
  }
1019
+ /** All of a user's sessions in the window, newest first; with `n`, also the actions of session `n`. */
1020
+ export function userSessions(db, w, id, n) {
1021
+ const all = sessionsOf(db, w, id);
1022
+ const pick = n ? all.find((x) => x.n === n) : undefined;
1023
+ return { userId: id, sessions: [...all].reverse(), session: pick ? withActions(db, w, id, [pick])[0] : null };
1024
+ }
960
1025
  // ------------------------------------------------------------------ runtime & metrics
961
1026
  export function runtime(db, w) {
962
1027
  const s = scope(w);