2025-01-18 23:52:44 +01:00
# @push.rocks/smartcontext
A module to enrich logs with context, featuring async log contexts and scope management.
2018-03-08 23:49:26 +01:00
2025-01-19 11:15:46 +01:00
Special thanks to Ilias Bhallil for his awesome simple-async-context library.
2024-04-14 13:39:41 +02:00
## Install
2025-01-19 00:27:06 +01:00
Make sure you have Node.js and npm installed, then run:
2025-01-18 23:52:44 +01:00
```bash
npm install @push .rocks/smartcontext
2024-04-14 13:39:41 +02:00
```
2025-01-19 00:27:06 +01:00
This will install the library and its dependencies into your local `node_modules` folder.
2018-03-08 23:49:26 +01:00
## Usage
2020-07-20 11:57:20 +00:00
2025-01-19 00:29:00 +01:00
The `@push.rocks/smartcontext` module provides an efficient way to enrich your code (often for logging) with contextual information. It uses asynchronous context management to support hierarchical scopes—particularly helpful in complex or nested asynchronous operations in Node.js.
2025-01-18 23:52:44 +01:00
2025-01-19 00:29:00 +01:00
### Basic Setup
2025-01-18 23:52:44 +01:00
```typescript
2025-01-19 00:27:06 +01:00
import { AsyncContext } from '@push .rocks/smartcontext';
2018-03-03 14:11:27 +01:00
2025-01-19 00:27:06 +01:00
const asyncContext = new AsyncContext();
2025-01-18 23:52:44 +01:00
2025-01-19 00:29:00 +01:00
// The parent store is always accessible through `asyncContext.store`
2025-01-19 00:27:06 +01:00
asyncContext.store.add('username', 'john_doe');
console.log(asyncContext.store.get('username')); // 'john_doe'
2018-03-03 14:11:27 +01:00
```
2024-04-14 13:39:41 +02:00
2025-01-19 00:29:00 +01:00
### `runScoped`
2025-01-18 23:52:44 +01:00
2025-01-19 00:29:00 +01:00
When you call `asyncContext.runScoped(async () => { ... })` , the library automatically creates a **child** `AsyncStore` . Inside that scoped function, `asyncContext.store` refers to the child store. Any data you add or delete there is isolated from the parent store. However, you can still read parent data if it hasn’ t been overridden.
2018-03-03 14:11:27 +01:00
```typescript
2025-01-19 00:27:06 +01:00
await asyncContext.runScoped(async () => {
2025-01-19 00:29:00 +01:00
// Inside this callback, `asyncContext.store` is a *child* store
asyncContext.store.add('transactionId', 'txn_abc123');
console.log(asyncContext.store.get('transactionId')); // 'txn_abc123'
2025-01-18 23:52:44 +01:00
2025-01-19 00:29:00 +01:00
// We can also see parent data like 'username'
2025-01-19 00:27:06 +01:00
console.log(asyncContext.store.get('username')); // 'john_doe'
2025-01-18 23:52:44 +01:00
});
2025-01-19 00:29:00 +01:00
// Outside `runScoped` , asyncContext.store reverts to the parent store
console.log(asyncContext.store.get('transactionId')); // undefined
2025-01-19 00:27:06 +01:00
```
2025-01-18 23:52:44 +01:00
2025-01-19 00:29:00 +01:00
### Isolating Data
2025-01-18 23:52:44 +01:00
2025-01-19 00:29:00 +01:00
Because each call to `runScoped` returns control to the parent store afterward, any keys added in a child scope disappear once the scope completes (unless you explicitly move them to the parent). This mechanism keeps data from leaking between scopes.
2025-01-18 23:52:44 +01:00
```typescript
2025-01-19 00:29:00 +01:00
// Parent store
asyncContext.store.add('someParentKey', 'parentValue');
2025-01-18 23:52:44 +01:00
2025-01-19 00:29:00 +01:00
// Child scope
2025-01-19 00:27:06 +01:00
await asyncContext.runScoped(async () => {
2025-01-19 00:29:00 +01:00
asyncContext.store.add('scopedKey', 'childValue');
console.log(asyncContext.store.get('scopedKey')); // 'childValue'
2025-01-19 00:27:06 +01:00
});
2018-03-03 14:11:27 +01:00
2025-01-19 00:29:00 +01:00
// Outside, the child key is gone
console.log(asyncContext.store.get('scopedKey')); // undefined
2025-01-18 23:52:44 +01:00
```
2018-03-03 14:11:27 +01:00
2025-01-19 00:29:00 +01:00
### Deleting Data
If the child deletes a key that exists in the parent, it will only remove it from the child’ s view of the store. Once the scope completes, the parent store is unaffected.
2024-04-14 13:39:41 +02:00
```typescript
2025-01-19 00:29:00 +01:00
asyncContext.store.add('deletableKey', 'originalValue');
2025-01-18 23:52:44 +01:00
2025-01-19 00:27:06 +01:00
await asyncContext.runScoped(async () => {
2025-01-19 00:29:00 +01:00
console.log(asyncContext.store.get('deletableKey')); // 'originalValue'
asyncContext.store.delete('deletableKey');
console.log(asyncContext.store.get('deletableKey')); // undefined in child
2018-03-03 14:11:27 +01:00
});
2025-01-18 23:52:44 +01:00
2025-01-19 00:29:00 +01:00
console.log(asyncContext.store.get('deletableKey')); // 'originalValue' remains in parent
2025-01-18 23:52:44 +01:00
```
2025-01-19 00:29:00 +01:00
### Parallel or Sequential Scopes
You can call `runScoped` multiple times, whether sequentially or in parallel (with `Promise.all` ). Each invocation creates its own isolated child store, preventing data collisions across asynchronous tasks.
2025-01-18 23:52:44 +01:00
```typescript
2025-01-19 00:27:06 +01:00
await asyncContext.runScoped(async () => {
2025-01-19 00:29:00 +01:00
asyncContext.store.add('childKey1', 'childValue1');
console.log(asyncContext.store.get('childKey1')); // 'childValue1'
});
2024-04-14 13:39:41 +02:00
2025-01-19 00:29:00 +01:00
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey2', 'childValue2');
console.log(asyncContext.store.get('childKey2')); // 'childValue2'
2025-01-19 00:27:06 +01:00
});
2025-01-19 00:29:00 +01:00
// Both keys were added in separate scopes, so they won't exist in the parent
console.log(asyncContext.store.get('childKey1')); // undefined
console.log(asyncContext.store.get('childKey2')); // undefined
2025-01-18 23:52:44 +01:00
```
2025-01-19 00:29:00 +01:00
### Testing Example
The following is a complete test script (using [tapbundle ](https://www.npmjs.com/package/@push.rocks/tapbundle )) demonstrating how child stores inherit data from the parent but remain isolated. After each scoped block, new child keys vanish, and any parent keys deleted inside the child remain intact in the parent.
2025-01-18 23:52:44 +01:00
```typescript
2025-01-19 00:27:06 +01:00
import { tap, expect } from '@push .rocks/tapbundle';
2025-01-19 00:29:00 +01:00
import { AsyncContext } from '../ts/logcontext.classes.asynccontext.js';
2025-01-18 23:52:44 +01:00
2025-01-19 00:27:06 +01:00
const asyncContext = new AsyncContext();
2025-01-18 23:52:44 +01:00
2025-01-19 00:29:00 +01:00
tap.test('should run a scoped function and add data to a child store', async () => {
// Add some default data to the parent store
2025-01-19 00:27:06 +01:00
asyncContext.store.add('parentKey', 'parentValue');
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
2025-01-18 23:52:44 +01:00
2025-01-19 00:29:00 +01:00
// Now run a child scope, add some data, and check that parent data is still accessible
2025-01-19 00:27:06 +01:00
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey', 'childValue');
2025-01-19 00:29:00 +01:00
// Child sees its own data
2025-01-19 00:27:06 +01:00
expect(asyncContext.store.get('childKey')).toEqual('childValue');
2025-01-19 00:29:00 +01:00
// Child also sees parent data
2025-01-19 00:27:06 +01:00
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
2025-01-18 23:52:44 +01:00
});
2025-01-19 00:27:06 +01:00
});
2024-04-14 13:39:41 +02:00
2025-01-19 00:29:00 +01:00
tap.test('should not contaminate the parent store with child-only data', async () => {
// Create a new child scope
2025-01-19 00:27:06 +01:00
await asyncContext.runScoped(async () => {
asyncContext.store.add('temporaryKey', 'temporaryValue');
expect(asyncContext.store.get('temporaryKey')).toEqual('temporaryValue');
2025-01-18 23:52:44 +01:00
});
2025-01-19 00:29:00 +01:00
// After scope finishes, 'temporaryKey' won't exist in the parent
2025-01-19 00:27:06 +01:00
expect(asyncContext.store.get('temporaryKey')).toBeUndefined();
});
2025-01-19 00:29:00 +01:00
tap.test('should allow adding data in multiple scopes independently', async () => {
// Add data in the first scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey1', 'childValue1');
expect(asyncContext.store.get('childKey1')).toEqual('childValue1');
});
// Add data in the second scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey2', 'childValue2');
expect(asyncContext.store.get('childKey2')).toEqual('childValue2');
});
// Neither childKey1 nor childKey2 should exist in the parent store
expect(asyncContext.store.get('childKey1')).toBeUndefined();
expect(asyncContext.store.get('childKey2')).toBeUndefined();
});
tap.test('should allow deleting data in a child store without removing it from the parent store', async () => {
// Ensure parent has some data
asyncContext.store.add('deletableKey', 'iShouldStayInParent');
await asyncContext.runScoped(async () => {
// Child sees the parent's data
expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
// Delete it in the child
asyncContext.store.delete('deletableKey');
// Child no longer sees it
expect(asyncContext.store.get('deletableKey')).toBeUndefined();
});
// Parent still has it
expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
});
2025-01-19 00:27:06 +01:00
2025-01-19 00:29:00 +01:00
tap.test('should allow multiple child scopes to share the same parent store data', async () => {
// Add a key to the parent store
asyncContext.store.add('sharedKey', 'sharedValue');
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
// First child scope
await asyncContext.runScoped(async () => {
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
});
// Second child scope
await asyncContext.runScoped(async () => {
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
});
});
export default tap.start();
2024-04-14 13:39:41 +02:00
```
2025-01-19 00:29:00 +01:00
With this updated `runScoped` design, there’ s no need to explicitly instantiate or manage child stores. The context automatically switches from the parent store to the child store while within the callback, then reverts back to the parent store afterwards. This structure makes it easy to:
2024-04-14 13:39:41 +02:00
2025-01-19 00:29:00 +01:00
- Keep each async operation’ s state isolated
- Preserve read-access to parent context data
- Avoid overwriting or polluting other operations’ data
2024-04-14 13:39:41 +02:00
2025-01-19 00:29:00 +01:00
This pattern works particularly well for logging or any scenario where you need to pass metadata through deeply nested async calls without manually juggling that data everywhere in your code.
2024-04-14 13:39:41 +02:00
## License and Legal Information
2025-01-19 00:27:06 +01:00
This repository is under the [MIT License ](./license ). Please note that the MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as necessary for reasonable use in describing the origin of the work.
2024-04-14 13:39:41 +02:00
### Trademarks
2025-01-19 00:27:06 +01:00
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Usage must be approved in writing by Task Venture Capital GmbH.
2024-04-14 13:39:41 +02:00
### Company Information
2020-07-20 11:57:20 +00:00
2024-04-14 13:39:41 +02:00
Task Venture Capital GmbH
2025-01-19 00:27:06 +01:00
Registered at District Court Bremen HRB 35230 HB, Germany
2020-07-20 11:57:20 +00:00
2025-01-19 00:27:06 +01:00
For any legal inquiries, please contact us at hello@task .vc. By using this repository, you acknowledge that you have read this section and agree to comply with its terms.