All files / json-crdt-server/src/services/blocks util.ts

100% Statements 16/16
100% Branches 6/6
100% Functions 3/3
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24        7x 7x   7x 7x   1329x     106x 1332x 140x 140x 140x 1x 1x 1x 1x    
import type * as fs from 'fs';
 
type Promises = (typeof fs)['promises'];
 
const KILOBYTE = 1024;
const MEGABYTE = KILOBYTE * KILOBYTE;
 
export const storageSpaceReclaimDecision =
  (
    promises: Pick<Promises, 'statfs'>,
    isGoodTime: () => boolean = () => Math.random() < 0.1,
    threshold: number = 300 * MEGABYTE,
  ) =>
  async () => {
    if (!isGoodTime()) return 0;
    const stats = await promises.statfs('/');
    const availableBytes = stats.bavail * stats.bsize;
    if (availableBytes > threshold) return 0;
    const avgDocSize = 30 * KILOBYTE;
    const blocksToDelete = Math.ceil((threshold - availableBytes) / avgDocSize);
    const blocksToDeleteClamped = Math.min(100, blocksToDelete);
    return blocksToDeleteClamped;
  };