CodeSampleX

Пример

toad-cache 3.7.4: LruHitStatistics

Проверенный пример — npm toad-cache 3.7.4: LruHitStatistics. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден.

sha256:2aef6a26ca487b0c994c22767825a9247f1113e2f1f73ff74a728d6a0989faae

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-11-28

Кейс

HOW
Цель
verify toad-cache.LruHitStatistics in pkg:npm/toad-cache@3.7.4
Пакеты
Символы
  • toad-cache.LruHitStatistics
Окружение
node 22.23.2
Создан
2026-11-28T00:03:13Z

Контракт

  1. require('toad-cache').LruHitStatistics is exported in CJS as an alias of LruObjectHitStatistics
  2. new LruHitStatistics() requires a non-empty cacheId (throws 'Cache id is mandatory') and validates non-negative integer max and ttlInMsecs
  3. passing a shared HitStatisticsRecord shares the same statistics object across cache.getStatistics() and record.getStatistics() keyed by cacheId and YYYY-MM-DD
  4. set, get, LRU eviction at max capacity, delete, and clear update sets, hits, falsyHits, emptyHits, misses, evictions, invalidateOne, invalidateAll, and cacheSize
  5. expired entries on get() when ttlInMsecs > 0 return undefined, remove the entry, increment expirations, and do not increment invalidateOne or misses

Файлы

  • PROMPT.md
  • csx.json
  • index.cjs
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.cjs

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify toad-cache.LruHitStatistics in pkg:npm/toad-cache@3.7.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/toad-cache@3.7.4
Demonstrate these symbols/APIs:
  - toad-cache.LruHitStatistics
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:f29662680e3f0c2279a21865ce7695a31ceb5a5549029a9bf939c946475fb599","constraints":{"executionContext":"node"},"contract":["require('toad-cache').LruHitStatistics is exported in CJS as an alias of LruObjectHitStatistics","new LruHitStatistics() requires a non-empty cacheId (throws 'Cache id is mandatory') and validates non-negative integer max and ttlInMsecs","passing a shared HitStatisticsRecord shares the same statistics object across cache.getStatistics() and record.getStatistics() keyed by cacheId and YYYY-MM-DD","set, get, LRU eviction at max capacity, delete, and clear update sets, hits, falsyHits, emptyHits, misses, evictions, invalidateOne, invalidateAll, and cacheSize","expired entries on get() when ttlInMsecs \u003e 0 return undefined, remove the entry, increment expirations, and do not increment invalidateOne or misses"],"goal":"verify toad-cache.LruHitStatistics in pkg:npm/toad-cache@3.7.4","kind":"HOW","packages":["pkg:npm/toad-cache@3.7.4"],"schemaVersion":1,"symbols":["toad-cache.LruHitStatistics"]},"contractCommand":["node","test/contract.cjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/toad-cache@3.7.4"],"schemaVersion":1,"subject":"pkg:npm/toad-cache@3.7.4","symbols":["toad-cache.LruHitStatistics"],"verifierAdapter":"node-typescript@1"}
index.cjs
'use strict';

const { LruHitStatistics, HitStatisticsRecord } = require('toad-cache');

function createTrackedCache({
  max = 1000,
  ttlInMsecs = 0,
  cacheId = 'items',
  record = new HitStatisticsRecord(),
  statisticTtlInHours = 24,
} = {}) {
  const cache = new LruHitStatistics(
    max,
    ttlInMsecs,
    cacheId,
    record,
    statisticTtlInHours
  );
  return { cache, record };
}

function getLatestStatsEntry(cache, cacheId) {
  const allStats = cache.getStatistics();
  const cacheStats = allStats[cacheId];
  const timestamps = Object.keys(cacheStats);
  return cacheStats[timestamps[timestamps.length - 1]];
}

module.exports = {
  createTrackedCache,
  getLatestStatsEntry,
};
package-lock.json
{
  "name": "toad-cache-lru-hit-statistics-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "toad-cache-lru-hit-statistics-sample",
      "version": "1.0.0",
      "dependencies": {
        "toad-cache": "3.7.4"
      }
    },
    "node_modules/toad-cache": {
      "version": "3.7.4",
      "resolved": "https://registry.npmjs.org/toad-cache/-/toad-cache-3.7.4.tgz",
      "integrity": "sha512-m1TdR/rvT7kgGJZhspNtXdsdYk0fddFpJJFlG5s+UkPFo6lkLoZ3YLOaovPYjq1R75NP5JfeTlSHaOsE09peCg==",
      "license": "MIT",
      "engines": {
        "node": ">=20"
      }
    }
  }
}
package.json
{
  "name": "toad-cache-lru-hit-statistics-sample",
  "version": "1.0.0",
  "private": true,
  "description": "Minimal offline contract sample verifying toad-cache.LruHitStatistics",
  "main": "index.cjs",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "toad-cache": "3.7.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify toad-cache.LruHitStatistics in pkg:npm/toad-cache@3.7.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/toad-cache@3.7.4"
  ],
  "symbols": [
    "toad-cache.LruHitStatistics"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.cjs
'use strict';

const assert = require('node:assert/strict');
const {
  LruHitStatistics,
  LruObjectHitStatistics,
  HitStatisticsRecord,
} = require('toad-cache');
const { createTrackedCache, getLatestStatsEntry } = require('../index.cjs');

// 1. Export identity and constructor validation
assert.strictEqual(LruHitStatistics, LruObjectHitStatistics);

assert.throws(
  () => new LruHitStatistics(10, 0),
  { message: 'Cache id is mandatory' }
);
assert.throws(
  () => new LruHitStatistics(10, 0, ''),
  { message: 'Cache id is mandatory' }
);
assert.throws(
  () => new LruHitStatistics(-1, 0, 'bad-max'),
  { message: 'Invalid max value' }
);
assert.throws(
  () => new LruHitStatistics(10, -1, 'bad-ttl'),
  { message: 'Invalid ttl value' }
);

const defaultCache = new LruHitStatistics(undefined, undefined, 'defaults');
assert.strictEqual(defaultCache.max, 1000);
assert.strictEqual(defaultCache.ttl, 0);

// 2. Shared HitStatisticsRecord, LRU eviction, hit/falsy/empty/miss/invalidation counters
const sharedRecord = new HitStatisticsRecord();
const { cache } = createTrackedCache({
  max: 2,
  ttlInMsecs: 0,
  cacheId: 'primary',
  record: sharedRecord,
  statisticTtlInHours: 24,
});

assert.strictEqual(cache.getStatistics(), sharedRecord.getStatistics());

// Miss on empty cache
assert.strictEqual(cache.get('missing'), undefined);

// Populate to capacity (max = 2)
cache.set('k1', 'value-1');
cache.set('k2', 0);

// Hit k1 (truthy) -> bumps k1 as most recently used; k2 becomes LRU
assert.strictEqual(cache.get('k1'), 'value-1');

// Hit k2 (falsy, non-empty) -> bumps k2; k1 becomes LRU
assert.strictEqual(cache.get('k2'), 0);

// Inserting k3 evicts k1 (LRU)
cache.set('k3', '');
assert.strictEqual(cache.size, 2);
assert.strictEqual(cache.get('k1'), undefined); // miss

// Hit k3 (empty string -> hit + falsyHit + emptyHit)
assert.strictEqual(cache.get('k3'), '');

// Replace existing key with null and read it (emptyHit + falsyHit + hit)
cache.set('k3', null);
assert.strictEqual(cache.get('k3'), null);

// Delete missing key does not increment invalidateOne; deleting existing key does
cache.delete('never-existed');
cache.delete('k2');
assert.strictEqual(cache.size, 1);

let stats = getLatestStatsEntry(cache, 'primary');
assert.deepStrictEqual(stats, {
  cacheSize: 1,
  hits: 4,
  falsyHits: 3,
  emptyHits: 2,
  misses: 2,
  expirations: 0,
  evictions: 1,
  invalidateOne: 1,
  invalidateAll: 0,
  sets: 4,
});

// Clear cache increments invalidateAll and zeroes cacheSize
cache.clear();
assert.strictEqual(cache.size, 0);
stats = getLatestStatsEntry(cache, 'primary');
assert.strictEqual(stats.invalidateAll, 1);
assert.strictEqual(stats.cacheSize, 0);

// 3. TTL expiration tracking (deterministic clock via Date.now)
const realDateNow = Date.now;
let now = 1_700_000_000_000;
Date.now = () => now;
try {
  const { cache: ttlCache } = createTrackedCache({
    max: 5,
    ttlInMsecs: 100,
    cacheId: 'ttl-cache',
    record: sharedRecord,
  });

  ttlCache.set('ephemeral', 'fresh');
  assert.strictEqual(ttlCache.get('ephemeral'), 'fresh');

  now += 150;
  assert.strictEqual(ttlCache.get('ephemeral'), undefined);

  const ttlStats = getLatestStatsEntry(ttlCache, 'ttl-cache');
  assert.deepStrictEqual(ttlStats, {
    cacheSize: 0,
    hits: 1,
    falsyHits: 0,
    emptyHits: 0,
    misses: 0,
    expirations: 1,
    evictions: 0,
    invalidateOne: 0,
    invalidateAll: 0,
    sets: 1,
  });
} finally {
  Date.now = realDateNow;
}

// Verify both caches are recorded under the shared HitStatisticsRecord
const combined = sharedRecord.getStatistics();
assert.ok(Object.hasOwn(combined, 'primary'));
assert.ok(Object.hasOwn(combined, 'ttl-cache'));

console.log('toad-cache.LruHitStatistics contract passed');

Исходный сидер

аноним