From 4bace10bab31cf810f3d9a87de796cbfa6f165e2 Mon Sep 17 00:00:00 2001 From: Abdullah Atta Date: Sat, 3 Jan 2026 14:38:45 +0500 Subject: [PATCH] server(themes): make counter increment faster --- servers/themes/src/counter/fs.ts | 5 +++-- servers/themes/src/counter/kv.ts | 26 ++++++++++---------------- 2 files changed, 13 insertions(+), 18 deletions(-) diff --git a/servers/themes/src/counter/fs.ts b/servers/themes/src/counter/fs.ts index 0003036eb..e06ab0e0a 100644 --- a/servers/themes/src/counter/fs.ts +++ b/servers/themes/src/counter/fs.ts @@ -30,12 +30,13 @@ export class FsCounter { } async increment(key: string, uid: string) { - await this.mutex.runExclusive(async () => { + return await this.mutex.runExclusive(async () => { const counts = await this.all(); counts[key] = counts[key] || []; - if (counts[key].includes(uid)) return; + if (counts[key].includes(uid)) return counts[key].length; counts[key].push(uid); await this.save(counts); + return counts[key].length; }); } diff --git a/servers/themes/src/counter/kv.ts b/servers/themes/src/counter/kv.ts index 9b30759c6..467ef7fd1 100644 --- a/servers/themes/src/counter/kv.ts +++ b/servers/themes/src/counter/kv.ts @@ -28,6 +28,7 @@ type WorkersKVRESTConfig = { export class KVCounter { private readonly client: Cloudflare; private readonly mutex: Mutex; + private installs: Record = {}; constructor(private readonly config: WorkersKVRESTConfig) { this.mutex = new Mutex(); this.client = new Cloudflare({ @@ -36,15 +37,12 @@ export class KVCounter { } async increment(key: string, uid: string) { - await this.mutex.runExclusive(async () => { - const installs = await readMulti(this.client, this.config, [key]); - const existing = installs[key] || []; - await write( - this.client, - this.config, - key, - Array.from(new Set([...existing, uid])) - ); + return await this.mutex.runExclusive(async () => { + const existing = this.installs[key] || []; + const installsSet = Array.from(new Set([...existing, uid])); + await write(this.client, this.config, key, installsSet); + this.installs[key] = installsSet; + return installsSet.length; }); } @@ -54,6 +52,7 @@ export class KVCounter { for (const [key, value] of Object.entries(installs)) { result[key] = value.length; } + this.installs = installs; return result; } } @@ -87,13 +86,8 @@ function write( key: string, data: T ) { - return client.kv.namespaces.bulkUpdate(config.namespaceId, { + return client.kv.namespaces.values.update(config.namespaceId, key + "_test", { account_id: config.cfAccountId, - body: [ - { - key, - value: JSON.stringify(data) - } - ] + value: JSON.stringify(data) }); }