Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
traffic.ts7.0 KB · 242 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/**
 * Block F1 — Traffic analytics helpers.
 *
 * Records + rolls up per-repo visit / clone / API hits. We record a row per
 * event (cheap) and aggregate in-memory for the chart. `trackView` and
 * `trackClone` are fire-and-forget — they never throw and never slow the
 * user-facing request.
 */

import { and, eq, gte, sql } from "drizzle-orm";
import { createHash } from "node:crypto";
import { db } from "../db";
import { repoTrafficEvents, repositories, users } from "../db/schema";

export type TrafficKind = "view" | "clone" | "api" | "ui";

export interface TrackArgs {
  repositoryId: string;
  kind: TrafficKind;
  path?: string | null;
  userId?: string | null;
  ip?: string | null;
  userAgent?: string | null;
  referer?: string | null;
}

function hashIp(ip: string | null | undefined): string | null {
  if (!ip) return null;
  return createHash("sha256")
    .update(ip)
    .digest("hex")
    .slice(0, 16); // 64 bits is plenty for uniqueness within a day
}

/**
 * Record a traffic event. Never throws. Returns quickly — callers don't need
 * to await, but may if they want backpressure.
 */
export async function track(args: TrackArgs): Promise<void> {
  try {
    await db.insert(repoTrafficEvents).values({
      repositoryId: args.repositoryId,
      kind: args.kind,
      path: args.path ? args.path.slice(0, 256) : null,
      userId: args.userId || null,
      ipHash: hashIp(args.ip),
      userAgent: args.userAgent ? args.userAgent.slice(0, 128) : null,
      referer: args.referer ? args.referer.slice(0, 256) : null,
    });
  } catch {
    // swallow
  }
}

/**
 * Convenience wrappers. Kept separate so call sites read semantically.
 */
export async function trackView(
  args: Omit<TrackArgs, "kind">
): Promise<void> {
  return track({ ...args, kind: "view" });
}

export async function trackClone(
  args: Omit<TrackArgs, "kind">
): Promise<void> {
  return track({ ...args, kind: "clone" });
}

/**
 * Look up `(owner, repo)` and record a traffic event. Safe to fire-and-forget
 * from request handlers; never throws. Returns void.
 */
export async function trackByName(
  owner: string,
  repo: string,
  kind: TrafficKind,
  meta: Omit<TrackArgs, "kind" | "repositoryId"> = {}
): Promise<void> {
  try {
    const [row] = await db
      .select({ id: repositories.id })
      .from(repositories)
      .innerJoin(users, eq(repositories.ownerId, users.id))
      .where(and(eq(users.username, owner), eq(repositories.name, repo)))
      .limit(1);
    if (!row) return;
    await track({ ...meta, kind, repositoryId: row.id });
  } catch {
    // swallow
  }
}

export interface TrafficSummary {
  totalViews: number;
  totalClones: number;
  uniqueVisitorsApprox: number;
  daily: Array<{ day: string; views: number; clones: number }>;
  topReferers: Array<{ referer: string; n: number }>;
  topPaths: Array<{ path: string; n: number }>;
}

/**
 * Build a 14-day traffic summary for a repo. Approximation for
 * uniqueVisitorsApprox: distinct `ip_hash` over the window.
 */
export async function summarise(
  repositoryId: string,
  windowDays = 14
): Promise<TrafficSummary> {
  const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1000);
  const empty: TrafficSummary = {
    totalViews: 0,
    totalClones: 0,
    uniqueVisitorsApprox: 0,
    daily: [],
    topReferers: [],
    topPaths: [],
  };

  try {
    const rows = await db
      .select({
        day: sql<string>`to_char(date_trunc('day', ${repoTrafficEvents.createdAt}), 'YYYY-MM-DD')`,
        kind: repoTrafficEvents.kind,
        n: sql<number>`count(*)::int`,
      })
      .from(repoTrafficEvents)
      .where(
        and(
          eq(repoTrafficEvents.repositoryId, repositoryId),
          gte(repoTrafficEvents.createdAt, since)
        )
      )
      .groupBy(
        sql`date_trunc('day', ${repoTrafficEvents.createdAt})`,
        repoTrafficEvents.kind
      );

    const dayMap = new Map<string, { views: number; clones: number }>();
    let totalViews = 0;
    let totalClones = 0;
    for (const r of rows) {
      const day = r.day;
      const bucket = dayMap.get(day) || { views: 0, clones: 0 };
      if (r.kind === "view" || r.kind === "ui") {
        bucket.views += Number(r.n);
        totalViews += Number(r.n);
      } else if (r.kind === "clone") {
        bucket.clones += Number(r.n);
        totalClones += Number(r.n);
      }
      dayMap.set(day, bucket);
    }

    const daily = Array.from(dayMap.entries())
      .map(([day, v]) => ({ day, views: v.views, clones: v.clones }))
      .sort((a, b) => a.day.localeCompare(b.day));

    const [uv] = await db
      .select({
        n: sql<number>`count(distinct ${repoTrafficEvents.ipHash})::int`,
      })
      .from(repoTrafficEvents)
      .where(
        and(
          eq(repoTrafficEvents.repositoryId, repositoryId),
          gte(repoTrafficEvents.createdAt, since)
        )
      );

    const refRows = await db
      .select({
        referer: repoTrafficEvents.referer,
        n: sql<number>`count(*)::int`,
      })
      .from(repoTrafficEvents)
      .where(
        and(
          eq(repoTrafficEvents.repositoryId, repositoryId),
          gte(repoTrafficEvents.createdAt, since),
          sql`${repoTrafficEvents.referer} IS NOT NULL AND ${repoTrafficEvents.referer} <> ''`
        )
      )
      .groupBy(repoTrafficEvents.referer)
      .orderBy(sql`count(*) desc`)
      .limit(8);

    const pathRows = await db
      .select({
        path: repoTrafficEvents.path,
        n: sql<number>`count(*)::int`,
      })
      .from(repoTrafficEvents)
      .where(
        and(
          eq(repoTrafficEvents.repositoryId, repositoryId),
          gte(repoTrafficEvents.createdAt, since),
          sql`${repoTrafficEvents.path} IS NOT NULL`
        )
      )
      .groupBy(repoTrafficEvents.path)
      .orderBy(sql`count(*) desc`)
      .limit(8);

    return {
      totalViews,
      totalClones,
      uniqueVisitorsApprox: Number(uv?.n || 0),
      daily,
      topReferers: refRows
        .filter((r) => !!r.referer)
        .map((r) => ({ referer: r.referer as string, n: Number(r.n) })),
      topPaths: pathRows
        .filter((r) => !!r.path)
        .map((r) => ({ path: r.path as string, n: Number(r.n) })),
    };
  } catch {
    return empty;
  }
}

/**
 * Pure helper for unit tests — turn a list of events into the same daily
 * bucket structure as `summarise` without needing a DB.
 */
export function bucketDaily(
  events: Array<{ createdAt: Date | string; kind: string }>
): Array<{ day: string; views: number; clones: number }> {
  const dayMap = new Map<string, { views: number; clones: number }>();
  for (const e of events) {
    const t = typeof e.createdAt === "string" ? new Date(e.createdAt) : e.createdAt;
    const day = t.toISOString().slice(0, 10);
    const bucket = dayMap.get(day) || { views: 0, clones: 0 };
    if (e.kind === "view" || e.kind === "ui") bucket.views++;
    else if (e.kind === "clone") bucket.clones++;
    dayMap.set(day, bucket);
  }
  return Array.from(dayMap.entries())
    .map(([day, v]) => ({ day, ...v }))
    .sort((a, b) => a.day.localeCompare(b.day));
}