server(themes): make counter increment faster

This commit is contained in:
Abdullah Atta
2026-01-03 14:38:45 +05:00
parent 603b7da9e6
commit 4bace10bab
2 changed files with 13 additions and 18 deletions

View File

@@ -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;
});
}

View File

@@ -28,6 +28,7 @@ type WorkersKVRESTConfig = {
export class KVCounter {
private readonly client: Cloudflare;
private readonly mutex: Mutex;
private installs: Record<string, string[]> = {};
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<T>(
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)
});
}