denoland / deploy_feedback

For reporting issues with Deno Deploy
https://deno.com/deploy
74 stars 5 forks source link

Feature request: A way for the backend to know how many read/write units have been used that day. #503

Open JoakimCh opened 1 year ago

JoakimCh commented 1 year ago

This would be a nice way to be able to have better control over spendings.

E.g. for my backend I would want to shut down certain features when I get over the free limit. Or limit the users allowed actions based on how many free units I have left.

I would love to be able to have this control!

ooker777 commented 3 months ago

do you have any solution for this yet?

JoakimCh commented 3 months ago

Nope.

ooker777 commented 3 months ago

I come up with this solution to track the used units via signals:

// signals.ts
import { signal } from "@preact/signals";

export const kvSignal = signal<Deno.Kv>(await Deno.openKv());
export const readUnitSignal = signal<number>(0);
export const writeUnitSignal = signal<number>(0);

Replace the native kv.get and kv.set operations with these:

// kvUtils.ts
import sizeof from "npm:object-sizeof";

export function increaseReadUnit(data: any) {
  const kb = sizeof(data) / 1000;
  readUnitSignal.value += Math.ceil(kb / 4);
}
export function increaseWriteUnit(data: any) {
  const kb = sizeof(data) / 1000;
  writeUnitSignal.value += Math.ceil(kb);
}

export async function kvGet(key: Deno.KvKey) {
  const kv = kvSignal.value;
  const result = await kv.get(key);
  increaseReadUnit(result);
  return result;
}

export async function kvSet(key: Deno.KvKey, value: any) {
  const kv = kvSignal.value;
  await kv.set(key, value);
  increaseWriteUnit(value);
}

It doesn't match the result shown up in the analytic chart on the dashboard unfortunately. Here is the detail of that issue. Nevertheless I hope this gives some food for thought.