15 Commits

Author SHA1 Message Date
0657770c5d 1.0.17 2025-08-26 19:42:20 +00:00
a698d6cd35 fix(package): Update dependency scopes/versions, fix imports and scripts, add pnpm workspace, remove GitLab CI 2025-08-26 19:42:20 +00:00
428f159ff7 update description 2024-05-29 14:11:59 +02:00
abfa1e1c70 update tsconfig 2024-04-14 17:23:41 +02:00
57c2e33a6c update npmextra.json: githost 2024-04-01 21:34:01 +02:00
b0fa7931a8 update npmextra.json: githost 2024-04-01 19:57:45 +02:00
53d9f8bce1 update npmextra.json: githost 2024-03-30 21:46:42 +01:00
6e7205d788 switch to new org scheme 2023-07-11 00:17:21 +02:00
c57d76376d switch to new org scheme 2023-07-10 02:42:23 +02:00
b6c4ef568a 1.0.16 2023-01-08 09:18:41 +01:00
c7682e4cc5 fix(core): update 2023-01-08 09:18:41 +01:00
677b07a176 1.0.15 2022-06-26 20:36:23 +02:00
0e11d0e760 fix(core): update 2022-06-26 20:36:22 +02:00
1f80df6ec2 1.0.14 2021-04-21 19:52:53 +00:00
05997ef1cf fix(core): update 2021-04-21 19:52:53 +00:00
21 changed files with 9000 additions and 1876 deletions

4
.gitignore vendored
View File

@@ -15,8 +15,6 @@ node_modules/
# builds # builds
dist/ dist/
dist_web/ dist_*/
dist_serve/
dist_ts_web/
# custom # custom

View File

@@ -1,126 +0,0 @@
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: '$CI_BUILD_STAGE'
stages:
- security
- test
- release
- metadata
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
tags:
- lossless
- docker
- notpriv
snyk:
image: registry.gitlab.com/hosttoday/ht-docker-node:snyk
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command snyk test
tags:
- lossless
- docker
- notpriv
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- lossless
- docker
- priv
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- lossless
- docker
- notpriv
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- lossless
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
script:
- npmci command npm install -g tslint typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

68
.serena/project.yml Normal file
View File

@@ -0,0 +1,68 @@
# language of the project (csharp, python, rust, java, typescript, go, cpp, or ruby)
# * For C, use cpp
# * For JavaScript, use typescript
# Special requirements:
# * csharp: Requires the presence of a .sln file in the project folder.
language: typescript
# whether to use the project's gitignore file to ignore files
# Added on 2025-04-07
ignore_all_files_in_gitignore: true
# list of additional paths to ignore
# same syntax as gitignore, so you can use * and **
# Was previously called `ignored_dirs`, please update your config if you are using that.
# Added (renamed) on 2025-04-07
ignored_paths: []
# whether the project is in read-only mode
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
# Added on 2025-04-18
read_only: false
# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
# Below is the complete list of tools for convenience.
# To make sure you have the latest list of tools, and to view their descriptions,
# execute `uv run scripts/print_tool_overview.py`.
#
# * `activate_project`: Activates a project by name.
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
# * `create_text_file`: Creates/overwrites a file in the project directory.
# * `delete_lines`: Deletes a range of lines within a file.
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
# * `execute_shell_command`: Executes a shell command.
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
# * `initial_instructions`: Gets the initial instructions for the current project.
# Should only be used in settings where the system prompt cannot be set,
# e.g. in clients you have no control over, like Claude Desktop.
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
# * `insert_at_line`: Inserts content at a given line in a file.
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
# * `list_memories`: Lists memories in Serena's project-specific memory store.
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
# * `read_file`: Reads a file within the project directory.
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
# * `remove_project`: Removes a project from the Serena configuration.
# * `replace_lines`: Replaces a range of lines within a file with new content.
# * `replace_symbol_body`: Replaces the full definition of a symbol.
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
# * `search_for_pattern`: Performs a search for a pattern in the project.
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
# * `switch_modes`: Activates modes by providing a list of their names
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
excluded_tools: []
# initial prompt for the project. It will always be given to the LLM upon activating the project
# (contrary to the memories, which are loaded on demand).
initial_prompt: ""
project_name: "smartcache"

24
.vscode/launch.json vendored
View File

@@ -2,28 +2,10 @@
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"name": "current file", "command": "npm test",
"type": "node", "name": "Run npm test",
"request": "launch", "request": "launch",
"args": [ "type": "node-terminal"
"${relativeFile}"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "test.ts",
"type": "node",
"request": "launch",
"args": [
"test/test.ts"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
} }
] ]
} }

View File

@@ -15,7 +15,7 @@
"properties": { "properties": {
"projectType": { "projectType": {
"type": "string", "type": "string",
"enum": ["website", "element", "service", "npm"] "enum": ["website", "element", "service", "npm", "wcc"]
} }
} }
} }

94
changelog.md Normal file
View File

@@ -0,0 +1,94 @@
# Changelog
## 2025-08-26 - 1.0.17 - fix(package)
Update dependency scopes/versions, fix imports and scripts, add pnpm workspace, remove GitLab CI
- Normalized package scopes to include dot notation (e.g. @push.rocks/*) and updated internal import paths in TypeScript files
- Updated runtime dependencies: @push.rocks/smartdelay -> ^3.0.5, @push.rocks/smartpromise -> ^4.2.3 (other @push.rocks/* deps kept/validated)
- Switched dev tooling packages to @git.zone/* namespace and bumped @git.zone/tstest version
- Adjusted npm scripts: more verbose test command and changed build target to use tsfolders
- Added pnpm-workspace.yaml and packageManager entry in package.json
- Removed .gitlab-ci.yml CI configuration
## 2024-05-29 - 1.0.16 - chore
Project metadata and TypeScript configuration updates.
- Update package description.
- Update tsconfig for TypeScript configuration.
- Update npmextra.json (githost) entries.
- Switch to new organization scheme (org restructuring).
## 2023-01-08 - 1.0.15 - fix(core)
Core fixes and maintenance.
- Apply core updates and fixes.
## 2022-06-26 - 1.0.14 - fix(core)
Core fixes and maintenance.
- Apply core updates and fixes.
## 2021-04-21 - 1.0.13 - fix(core)
Core fixes and maintenance.
- Apply core updates and fixes.
## 2020-02-03 - 1.0.12 - fix(core)
Core fixes and maintenance.
- Apply core updates and fixes.
## 2019-10-23 - 1.0.11 - fix(core)
Core fixes and maintenance.
- Apply core updates and fixes.
## 2018-12-02 - 1.0.10 - fix(core)
Core fixes and maintenance.
- Apply core updates and fixes.
## 2018-12-02 - 1.0.9 - test
Test updates.
- Update and improve tests.
## 2018-09-07 - 1.0.8 - fix(core)
Core fixes and maintenance.
- Apply core updates and fixes.
## 2018-08-21 - 1.0.7 - fix
Remove obsolete logging.
- Remove obsolete console.log statements.
## 2018-08-19 - 1.0.6 - ci
Continuous integration cleanup.
- Remove obsolete build dependencies from CI/build configuration.
## 2018-08-19 - 1.0.5 - dependencies
Dependency updates.
- Update project dependencies.
## 2018-07-13 - 1.0.4 - package
Package metadata fixes.
- Fix package name in metadata.
## 2018-07-12 - 1.0.3 - meta
Tag-only release.
- No code changes recorded for this tag (tagging/release bookkeeping only).
## 2018-07-12 - 1.0.2 - package
Project setup.
- Fix project/package setup issues.
## 2018-07-12 - 1.0.1 - init
Initial release.
- Initial project release and base setup.

View File

@@ -6,12 +6,27 @@
"gitzone": { "gitzone": {
"projectType": "npm", "projectType": "npm",
"module": { "module": {
"githost": "gitlab.com", "githost": "code.foss.global",
"gitscope": "pushrocks", "gitscope": "push.rocks",
"gitrepo": "smartcache", "gitrepo": "smartcache",
"shortDescription": "cache things in smart ways", "description": "A module for caching asynchronous function results with smart time and hash-based invalidation strategies.",
"npmPackagename": "@pushrocks/smartcache", "npmPackagename": "@push.rocks/smartcache",
"license": "MIT" "license": "MIT",
} "keywords": [
"caching",
"asynchronous",
"time-based invalidation",
"hash-based identification",
"smart caching",
"node.js",
"performance optimization",
"typescript",
"delay handling",
"error management"
]
}
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
} }
} }

1635
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,41 +1,62 @@
{ {
"name": "@pushrocks/smartcache", "name": "@push.rocks/smartcache",
"version": "1.0.13", "version": "1.0.17",
"private": false, "private": false,
"description": "cache things in smart ways", "description": "A module for caching asynchronous function results with smart time and hash-based invalidation strategies.",
"main": "dist/index.js", "main": "dist_ts/index.js",
"typings": "dist/index.d.ts", "typings": "dist_ts/index.d.ts",
"author": "Lossless GmbH", "author": "Lossless GmbH",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"test": "(tstest test/)", "test": "(tstest test/ --verbose --logfile --timeout 60)",
"build": "(tsbuild)" "build": "(tsbuild tsfolders)",
"buildDocs": "tsdoc"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.17", "@git.zone/tsbuild": "^2.1.63",
"@gitzone/tsrun": "^1.2.8", "@git.zone/tsrun": "^1.2.37",
"@gitzone/tstest": "^1.0.28", "@git.zone/tstest": "^2.3.5",
"@pushrocks/tapbundle": "^3.2.0", "@types/node": "^18.0.0"
"@types/node": "^13.7.0",
"tslint": "^6.0.0",
"tslint-config-prettier": "^1.18.0"
}, },
"dependencies": { "dependencies": {
"@pushrocks/smartdelay": "^2.0.6", "@push.rocks/smartdelay": "^3.0.5",
"@pushrocks/smarterror": "^2.0.1", "@push.rocks/smarterror": "^2.0.1",
"@pushrocks/smarthash": "^2.1.6", "@push.rocks/smarthash": "^3.0.1",
"@pushrocks/smartpromise": "^3.0.6", "@push.rocks/smartpromise": "^4.2.3",
"@pushrocks/smarttime": "^3.0.12" "@push.rocks/smarttime": "^4.0.1"
}, },
"files": [ "files": [
"ts/**/*", "ts/**/*",
"ts_web/**/*", "ts_web/**/*",
"dist/**/*", "dist/**/*",
"dist_web/**/*", "dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*", "dist_ts_web/**/*",
"assets/**/*", "assets/**/*",
"cli.js", "cli.js",
"npmextra.json", "npmextra.json",
"readme.md" "readme.md"
] ],
"browserslist": [
"last 1 chrome versions"
],
"type": "module",
"keywords": [
"caching",
"asynchronous",
"time-based invalidation",
"hash-based identification",
"smart caching",
"node.js",
"performance optimization",
"typescript",
"delay handling",
"error management"
],
"homepage": "https://code.foss.global/push.rocks/smartcache",
"repository": {
"type": "git",
"url": "https://code.foss.global/push.rocks/smartcache.git"
},
"packageManager": "pnpm@10.14.0+sha512.ad27a79641b49c3e481a16a805baa71817a04bbe06a38d17e60e2eaee83f6a146c6a688125f5792e48dd5ba30e7da52a5cda4c3992b9ccf333f9ce223af84748"
} }

8388
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

4
pnpm-workspace.yaml Normal file
View File

@@ -0,0 +1,4 @@
onlyBuiltDependencies:
- esbuild
- mongodb-memory-server
- puppeteer

1
readme.hints.md Normal file
View File

@@ -0,0 +1 @@

348
readme.md
View File

@@ -1,31 +1,335 @@
# @pushrocks/smartcache # @push.rocks/smartcache 🚀
cache things in smart ways **Smart time-based caching for async functions** - Because waiting is overrated!
## Availabililty and Links ## 🌟 What is SmartCache?
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartcache)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smartcache)
* [github.com (source mirror)](https://github.com/pushrocks/smartcache)
* [docs (typedoc)](https://pushrocks.gitlab.io/smartcache/)
## Status for master `@push.rocks/smartcache` is a powerful TypeScript caching library that intelligently caches the results of asynchronous functions. It automatically detects identical function calls based on the call stack, preventing redundant computations and dramatically improving performance. Perfect for expensive API calls, complex calculations, or any async operation you don't want to repeat unnecessarily!
[![pipeline status](https://gitlab.com/pushrocks/smartcache/badges/master/pipeline.svg)](https://gitlab.com/pushrocks/smartcache/commits/master)
[![coverage report](https://gitlab.com/pushrocks/smartcache/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smartcache/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/@pushrocks/smartcache.svg)](https://www.npmjs.com/package/@pushrocks/smartcache)
[![Known Vulnerabilities](https://snyk.io/test/npm/@pushrocks/smartcache/badge.svg)](https://snyk.io/test/npm/@pushrocks/smartcache)
[![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://prettier.io/)
## Usage ### ✨ Key Features
- 🎯 **Automatic cache identification** - Uses smart hashing to detect identical function calls
- ⏱️ **Time-based expiration** - Set custom cache durations for each cached operation
- 🔄 **Concurrent request handling** - Multiple simultaneous requests for the same data only trigger one actual call
- 🎭 **Zero configuration** - Works out of the box with sensible defaults
- 📦 **Lightweight** - Minimal dependencies, maximum performance
- 🔒 **Type-safe** - Full TypeScript support with proper typing
## Contribution ## 📦 Installation
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :) Get started in seconds:
For further information read the linked docs at the top of this readme. ```bash
# Using npm
npm install @push.rocks/smartcache --save
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh) # Using pnpm (recommended)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy) pnpm add @push.rocks/smartcache
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com) # Using yarn
yarn add @push.rocks/smartcache
```
## 🎮 Quick Start
```typescript
import { SmartCache } from '@push.rocks/smartcache';
// Create a cache instance
const cache = new SmartCache();
// Your expensive async function
async function fetchUserData(userId: string) {
console.log(`Fetching user ${userId} from API...`);
const response = await fetch(`/api/users/${userId}`);
return response.json();
}
// Wrap it with caching - subsequent calls within 5 seconds return cached result
async function getCachedUserData(userId: string) {
return cache.cacheReturn(
() => fetchUserData(userId),
5000 // Cache for 5 seconds
);
}
// First call - hits the API
const user1 = await getCachedUserData('123'); // Logs: "Fetching user 123 from API..."
// Second call within 5 seconds - returns cached result instantly!
const user2 = await getCachedUserData('123'); // No log, returns cached data
```
## 🚀 Advanced Usage
### Automatic Call Stack Detection
SmartCache uses intelligent call stack analysis to automatically identify unique function calls. This means you don't need to manually specify cache keys!
```typescript
const cache = new SmartCache();
// These will be automatically cached separately based on their call location
async function getData() {
// First location in code
const result1 = await cache.cacheReturn(async () => {
return await fetch('/api/data1').then(r => r.json());
}, 10000);
// Second location in code - different cache entry!
const result2 = await cache.cacheReturn(async () => {
return await fetch('/api/data2').then(r => r.json());
}, 10000);
return { result1, result2 };
}
```
### Concurrent Request Handling
SmartCache brilliantly handles concurrent requests - if multiple requests come in for the same cached operation before the first one completes, they all wait for and share the same result:
```typescript
const cache = new SmartCache();
async function expensiveOperation() {
console.log('Starting expensive operation...');
await new Promise(resolve => setTimeout(resolve, 2000));
return { data: 'valuable result' };
}
// Fire off 5 concurrent requests
const promises = Array(5).fill(null).map(() =>
cache.cacheReturn(expensiveOperation, 60000)
);
// Only ONE "Starting expensive operation..." log appears!
// All 5 requests get the same result
const results = await Promise.all(promises);
```
### Dynamic Cache Durations
Adjust cache duration based on your data's characteristics:
```typescript
const cache = new SmartCache();
async function getDataWithVariableCache(dataType: string) {
// Critical data - short cache
if (dataType === 'critical') {
return cache.cacheReturn(fetchCriticalData, 1000); // 1 second
}
// Static data - long cache
if (dataType === 'static') {
return cache.cacheReturn(fetchStaticData, 3600000); // 1 hour
}
// Default - moderate cache
return cache.cacheReturn(fetchNormalData, 60000); // 1 minute
}
```
### Cache Different Function Results
Each function call location gets its own cache entry:
```typescript
const cache = new SmartCache();
class DataService {
async getUserPosts(userId: string) {
// Cached separately from getUserProfile
return cache.cacheReturn(
async () => {
const response = await fetch(`/api/users/${userId}/posts`);
return response.json();
},
30000 // Cache for 30 seconds
);
}
async getUserProfile(userId: string) {
// Different cache entry than getUserPosts
return cache.cacheReturn(
async () => {
const response = await fetch(`/api/users/${userId}/profile`);
return response.json();
},
60000 // Cache for 60 seconds
);
}
}
```
## 🎯 Real-World Examples
### API Rate Limiting Helper
Prevent hitting rate limits by caching API responses:
```typescript
const cache = new SmartCache();
class GitHubService {
async getRepoInfo(owner: string, repo: string) {
return cache.cacheReturn(
async () => {
const response = await fetch(
`https://api.github.com/repos/${owner}/${repo}`,
{ headers: { 'Authorization': `token ${process.env.GITHUB_TOKEN}` } }
);
return response.json();
},
300000 // Cache for 5 minutes - respect API limits
);
}
}
```
### Database Query Optimization
Cache expensive database queries:
```typescript
const cache = new SmartCache();
class DatabaseService {
async getTopProducts(category: string) {
return cache.cacheReturn(
async () => {
// Expensive aggregation query
const products = await db.products.aggregate([
{ $match: { category } },
{ $group: { _id: '$productId', totalSales: { $sum: '$sales' } } },
{ $sort: { totalSales: -1 } },
{ $limit: 10 }
]);
return products;
},
120000 // Cache for 2 minutes - data doesn't change often
);
}
}
```
### Computed Values Cache
Cache expensive computations:
```typescript
const cache = new SmartCache();
class AnalyticsService {
async calculateMetrics(data: number[]) {
return cache.cacheReturn(
async () => {
console.log('Running expensive calculation...');
// Simulate expensive computation
const result = {
mean: data.reduce((a, b) => a + b, 0) / data.length,
median: this.calculateMedian(data),
standardDeviation: this.calculateStdDev(data),
percentiles: this.calculatePercentiles(data)
};
return result;
},
600000 // Cache for 10 minutes
);
}
private calculateMedian(data: number[]) { /* ... */ }
private calculateStdDev(data: number[]) { /* ... */ }
private calculatePercentiles(data: number[]) { /* ... */ }
}
```
## 📊 Performance Benefits
SmartCache can dramatically improve your application's performance:
- 🚀 **Reduce API calls** by up to 90% for frequently accessed data
-**Instant responses** for cached data (sub-millisecond)
- 📉 **Lower server costs** by reducing redundant computations
- 🛡️ **Protect against thundering herd** problems
- 🔄 **Automatic cleanup** - expired cache entries are removed automatically
## 🏗️ Architecture & How It Works
SmartCache uses a sophisticated approach to caching:
1. **Call Stack Hashing**: When you call `cacheReturn`, SmartCache captures the call stack and generates a SHA-256 hash
2. **Cache Lookup**: It checks if a valid cached result exists for this hash
3. **Concurrent Protection**: If a request is in-flight, new requests wait for the same result
4. **Automatic Expiration**: Each cache entry has a timer that automatically removes it when expired
5. **Memory Efficient**: Only stores what's actively being used, expired entries are cleaned up
## 💡 Best Practices
### ✅ Do's
- **Cache expensive operations** - API calls, database queries, complex calculations
- **Use appropriate durations** - Match cache time to your data's update frequency
- **Cache at the right level** - Cache complete results, not partial data
- **Monitor memory usage** - Be mindful when caching large objects
### ❌ Don'ts
- **Don't cache user-specific sensitive data** without careful consideration
- **Don't use excessive cache durations** for frequently changing data
- **Don't cache massive objects** that could cause memory issues
- **Don't rely on cache** for critical data consistency
## 🎓 Pro Tips
1. **Layer your caching**: Use SmartCache alongside CDN and database caching for maximum effect
2. **Cache warming**: Pre-populate cache with frequently accessed data on startup
3. **Metrics tracking**: Monitor cache hit rates to optimize cache durations
4. **Error handling**: Always handle potential errors in cached functions
```typescript
const cache = new SmartCache();
// Good - with error handling
async function getResilientData() {
return cache.cacheReturn(
async () => {
try {
const response = await fetch('/api/data');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
} catch (error) {
console.error('Failed to fetch data:', error);
// Return fallback or rethrow based on your needs
throw error;
}
},
30000
);
}
```
## 🤝 Support & Community
- 🐛 **Found a bug?** [Open an issue](https://code.foss.global/push.rocks/smartcache/issues)
- 💡 **Have a feature request?** [Start a discussion](https://code.foss.global/push.rocks/smartcache/issues)
- 📖 **Need help?** Check our [comprehensive documentation](https://code.foss.global/push.rocks/smartcache)
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@@ -1,35 +1,38 @@
import { expect, tap } from '@pushrocks/tapbundle'; import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartcache from '../ts/index'; import * as smartcache from '../ts/index.js';
import * as smartdelay from '@pushrocks/smartdelay';
let smartcacheInstance: smartcache.SmartCache; let smartcacheInstance: smartcache.SmartCache;
tap.test('should create a valid instance of SmartCache', async () => { tap.test('should create a valid instance of SmartCache', async () => {
smartcacheInstance = new smartcache.SmartCache(); smartcacheInstance = new smartcache.SmartCache();
expect(smartcacheInstance).to.be.instanceof(smartcache.SmartCache); expect(smartcacheInstance).toBeInstanceOf(smartcache.SmartCache);
}); });
tap.test('try to get async responses', async () => { tap.test('try to get async responses', async (toolsArg) => {
let response1Counter = 0;
const getResponse = async () => { const getResponse = async () => {
const response = await smartcacheInstance const response = await smartcacheInstance
.cacheReturn(async () => { .cacheReturn(async () => {
console.log('function 1 ran'); console.log('function 1 ran');
response1Counter++;
return 'hello'; return 'hello';
}, 1000) }, 1000)
.catch(err => { .catch((err) => {
console.log(err); console.log(err);
}); });
console.log('response is:'); console.log('response is:');
console.log(response); console.log(response);
}; };
let response2Counter = 0;
const getResponse2 = async () => { const getResponse2 = async () => {
const response = await smartcacheInstance const response = await smartcacheInstance
.cacheReturn(async () => { .cacheReturn(async () => {
console.log('function 2 ran'); console.log('function 2 ran');
response2Counter++;
return 'hello there!'; return 'hello there!';
}, 1000) }, 1000)
.catch(err => { .catch((err) => {
console.log(err); console.log(err);
}); });
console.log('response is:'); console.log('response is:');
@@ -40,12 +43,12 @@ tap.test('try to get async responses', async () => {
await getResponse(); await getResponse();
await getResponse2(); await getResponse2();
await getResponse2(); await getResponse2();
await smartdelay.delayFor(2000).then(async () => { await toolsArg.delayFor(500);
await getResponse(); await getResponse();
await toolsArg.delayFor(2000);
await getResponse2(); await getResponse2();
}); });
});
tap.start({ tap.start({
throwOnError: true throwOnError: true,
}); });

8
ts/00_commitinfo_data.ts Normal file
View File

@@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartcache',
version: '1.0.17',
description: 'A module for caching asynchronous function results with smart time and hash-based invalidation strategies.'
}

View File

@@ -1 +1 @@
export * from './smartcache.classes.smartcache'; export * from './smartcache.classes.smartcache.js';

View File

@@ -1,5 +1,5 @@
import * as plugins from './smartcache.plugins'; import * as plugins from './smartcache.plugins.js';
import { SmartError } from '@pushrocks/smarterror'; import { SmartError } from '@push.rocks/smarterror';
export interface ICacheMap { export interface ICacheMap {
[key: string]: { [key: string]: {
@@ -12,7 +12,7 @@ export interface ICacheMap {
export class CacheManager { export class CacheManager {
private _cacheMap: ICacheMap = {}; private _cacheMap: ICacheMap = {};
cacheExists(identifierArg): boolean { cacheExists(identifierArg: string): boolean {
if (this._cacheMap[identifierArg]) { if (this._cacheMap[identifierArg]) {
return true; return true;
} }
@@ -36,7 +36,7 @@ export class CacheManager {
this._cacheMap[identifierArg] = { this._cacheMap[identifierArg] = {
timer: new plugins.smarttime.Timer(validForArg), timer: new plugins.smarttime.Timer(validForArg),
cachedDeferred: new plugins.smartpromise.Deferred(), cachedDeferred: new plugins.smartpromise.Deferred(),
cachedObject: null cachedObject: null,
}; };
this._cacheMap[identifierArg].timer.start(); this._cacheMap[identifierArg].timer.start();
this._cacheMap[identifierArg].timer.completed.then(() => { this._cacheMap[identifierArg].timer.completed.then(() => {

View File

@@ -1,11 +1,13 @@
import * as plugins from './smartcache.plugins'; import * as plugins from './smartcache.plugins.js';
import { CacheManager } from './smartcache.classes.cachemanager'; import { CacheManager } from './smartcache.classes.cachemanager.js';
export class SmartCache { export class SmartCache {
private _cacheManager = new CacheManager(); private _cacheManager = new CacheManager();
async cacheReturn(asyncCachedFuncArg: () => Promise<any>, cacheDuration: number = 5000) { async cacheReturn(asyncCachedFuncArg: () => Promise<any>, cacheDuration: number = 5000) {
const callStack: string = new plugins.smarterror.SmartError('Cache Creation Point').cleanFullStack.split('\n')[2]; const callStack: string = new plugins.smarterror.SmartError(
'Cache Creation Point'
).cleanFullStack.split('\n')[2];
const callHash = plugins.smarthash.sha256FromStringSync(callStack); const callHash = plugins.smarthash.sha256FromStringSync(callStack);
// console.log(callHash); // console.log(callHash);

View File

@@ -1,7 +1,7 @@
import * as smartdelay from '@pushrocks/smartdelay'; import * as smartdelay from '@push.rocks/smartdelay';
import * as smarterror from '@pushrocks/smarterror'; import * as smarterror from '@push.rocks/smarterror';
import * as smartpromise from '@pushrocks/smartpromise'; import * as smartpromise from '@push.rocks/smartpromise';
import * as smarttime from '@pushrocks/smarttime'; import * as smarttime from '@push.rocks/smarttime';
import * as smarthash from '@pushrocks/smarthash'; import * as smarthash from '@push.rocks/smarthash';
export { smarterror, smartdelay, smartpromise, smarttime, smarthash }; export { smarterror, smartdelay, smartpromise, smarttime, smarthash };

14
tsconfig.json Normal file
View File

@@ -0,0 +1,14 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

View File

@@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}