Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 21 additions & 12 deletions apps/cron/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,27 @@ async function sampleActiveTunnels() {

let totalCount = 0;

let cursor = "0";
do {
const [nextCursor, keys] = await redis.scan(
cursor,
"MATCH",
"tunnel:online:*",
"COUNT",
1000,
);
cursor = nextCursor;
totalCount += keys.length;
} while (cursor !== "0");
// Use global counter for O(1) lookup instead of O(n) SCAN
const countStr = await redis.get("tunnel:global:online_count");
if (countStr !== null) {
totalCount = parseInt(countStr, 10) || 0;
} else {
// Fallback: counter doesn't exist yet, use SCAN (only happens on first run)
let cursor = "0";
do {
const [nextCursor, keys] = await redis.scan(
cursor,
"MATCH",
"tunnel:online:*",
"COUNT",
1000,
);
cursor = nextCursor;
totalCount += keys.length;
} while (cursor !== "0");
// Initialize the counter for future runs
await redis.set("tunnel:global:online_count", totalCount.toString());
}

console.log("Active tunnels:", totalCount);

Expand Down
5 changes: 5 additions & 0 deletions apps/tunnel/src/core/TunnelRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export class TunnelRouter {
private readonly heartbeatIntervalMs: number;
private readonly requestTimeoutMs: number;
private heartbeatTimer?: NodeJS.Timeout;
private static readonly GLOBAL_ONLINE_COUNT_KEY = "tunnel:global:online_count";

constructor(options: TunnelRouterOptions = {}) {
this.redis = options.redis;
Expand Down Expand Up @@ -117,6 +118,8 @@ export class TunnelRouter {
if (this.redis) {
try {
await this.redis.del(this.redisKey(tunnelId));
// Decrement global online count
await this.redis.decr(TunnelRouter.GLOBAL_ONLINE_COUNT_KEY);
if (metadata?.organizationId && metadata?.dbTunnelId) {
// Remove from online set and delete last_seen
await this.redis.srem(
Expand Down Expand Up @@ -298,6 +301,8 @@ export class TunnelRouter {
"NX",
);
if (result === "OK") {
// Increment global online count
await this.redis.incr(TunnelRouter.GLOBAL_ONLINE_COUNT_KEY);
// Add to org's online tunnels set using dbTunnelId
if (metadata?.organizationId && metadata?.dbTunnelId) {
await this.redis.sadd(
Expand Down