fix(core): Improve scope handling in async contexts.
This commit is contained in:
parent
58b189c1c7
commit
9c0b53f373
@ -1,5 +1,11 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-01-19 - 2.1.2 - fix(core)
|
||||
Improve scope handling in async contexts.
|
||||
|
||||
- Modified the handling of scoped stores within `AsyncContext.runScoped` to simplify the API usage.
|
||||
- Refactored tests to verify the context's behavior and isolation between parent and child stores.
|
||||
|
||||
## 2025-01-18 - 2.1.1 - fix(build)
|
||||
Fix tsbuild script to include missing flag
|
||||
|
||||
|
311
readme.md
311
readme.md
@ -4,249 +4,178 @@ A module to enrich logs with context, featuring async log contexts and scope man
|
||||
|
||||
## Install
|
||||
|
||||
To install the `@push.rocks/smartcontext` module, you can use npm. Make sure you have Node.js and npm installed on your system. Navigate to your project directory and run the following command:
|
||||
Make sure you have Node.js and npm installed, then run:
|
||||
|
||||
```bash
|
||||
npm install @push.rocks/smartcontext
|
||||
```
|
||||
|
||||
This command will download and install the module and its dependencies into your project's `node_modules` directory.
|
||||
This will install the library and its dependencies into your local `node_modules` folder.
|
||||
|
||||
## Usage
|
||||
|
||||
The `@push.rocks/smartcontext` module provides an efficient way to enrich your logging with contextual information. It features asynchronous log contexts and scope management, especially useful in complex asynchronous workflows in Node.js applications. This documentation will guide you through its core components: `AsyncContext` and `AsyncStore`.
|
||||
The `@push.rocks/smartcontext` module provides an efficient way to enrich your logging (or any functionality) with contextual information. It uses asynchronous context management to support hierarchical scopes—particularly handy when dealing with complex or nested asynchronous operations in Node.js.
|
||||
|
||||
### Setting Up and Basic Usage
|
||||
|
||||
First, import the necessary classes from the module in your TypeScript application:
|
||||
First, import the necessary classes:
|
||||
|
||||
```typescript
|
||||
import { AsyncContext, AsyncStore } from '@push.rocks/smartcontext';
|
||||
import { AsyncContext } from '@push.rocks/smartcontext';
|
||||
```
|
||||
|
||||
#### Creating a Context
|
||||
|
||||
You can create an `AsyncContext` for managing scope-based data sharing. Each context maintains a top-level `AsyncStore` instance. Let’s create a simple context and store some data:
|
||||
An `AsyncContext` manages a top-level `AsyncStore`. You can attach any data you want to that store. For example:
|
||||
|
||||
```typescript
|
||||
const mainContext = new AsyncContext();
|
||||
const asyncContext = new AsyncContext();
|
||||
|
||||
// Add some data to the store
|
||||
mainContext.store.add('username', 'john_doe');
|
||||
mainContext.store.add('role', 'admin');
|
||||
|
||||
console.log(mainContext.store.get('username')); // Outputs: 'john_doe'
|
||||
console.log(mainContext.store.get('role')); // Outputs: 'admin'
|
||||
// Add data to the top-level store
|
||||
asyncContext.store.add('username', 'john_doe');
|
||||
console.log(asyncContext.store.get('username')); // 'john_doe'
|
||||
```
|
||||
|
||||
This `mainContext` acts as a container for contextual data throughout the lifecycle of your application or a specific code block.
|
||||
### Using `runScoped`
|
||||
|
||||
### Scoping with `runScoped`
|
||||
The `runScoped` method now creates a child store *automatically* and makes that child store accessible via `asyncContext.store` **only** within the passed-in function. Once that scoped function completes, `asyncContext.store` reverts to the original (parent) store.
|
||||
|
||||
The `runScoped` method allows you to run a function within a specific child `AsyncStore` scope. This is vital for isolating child data during asynchronous operations, while still having access to any relevant parent data:
|
||||
#### Example
|
||||
|
||||
```typescript
|
||||
await mainContext.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('transactionId', 'txn_123456');
|
||||
|
||||
console.log(childStore.get('transactionId')); // Outputs: 'txn_123456'
|
||||
// Child store can also access data from the parent context:
|
||||
console.log(childStore.get('username')); // Outputs: 'john_doe'
|
||||
console.log(childStore.get('role')); // Outputs: 'admin'
|
||||
await asyncContext.runScoped(async () => {
|
||||
// While in this scope, asyncContext.store refers to the child store.
|
||||
asyncContext.store.add('transactionId', 'txn_123456');
|
||||
console.log(asyncContext.store.get('transactionId')); // 'txn_123456'
|
||||
|
||||
// Data from the parent store is also accessible in the child
|
||||
console.log(asyncContext.store.get('username')); // 'john_doe'
|
||||
});
|
||||
|
||||
// Outside runScoped, asyncContext.store is the parent store again
|
||||
console.log(asyncContext.store.get('transactionId')); // undefined
|
||||
```
|
||||
|
||||
1. **Child Store Access**: Within the scope, `asyncContext.store` points to a *child* store.
|
||||
2. **Parent Data**: Any keys from the parent are still visible in the child (unless overridden).
|
||||
3. **No Cross-Contamination**: Keys added in the child store don’t persist in the parent after the scope ends.
|
||||
|
||||
### Isolating and Deleting Data
|
||||
|
||||
If you add a key within a `runScoped` block, it stays there unless you intentionally move it to the parent. Also, if you delete a key in the child, it won’t remove it from the parent store:
|
||||
|
||||
```typescript
|
||||
// Parent store has some initial data
|
||||
asyncContext.store.add('deletableKey', 'initialValue');
|
||||
|
||||
await asyncContext.runScoped(async () => {
|
||||
console.log(asyncContext.store.get('deletableKey')); // 'initialValue'
|
||||
asyncContext.store.delete('deletableKey'); // Delete in child
|
||||
console.log(asyncContext.store.get('deletableKey')); // undefined (child only)
|
||||
});
|
||||
|
||||
// Outside scope, parent's data is intact
|
||||
console.log(asyncContext.store.get('deletableKey')); // 'initialValue'
|
||||
```
|
||||
|
||||
### Multiple Scopes
|
||||
|
||||
You can create multiple scopes, each maintaining its own data isolation. That way, concurrent or sequential operations don’t overwrite or “contaminate” each other’s data in the shared context.
|
||||
|
||||
```typescript
|
||||
// Scope 1
|
||||
await asyncContext.runScoped(async () => {
|
||||
asyncContext.store.add('key1', 'value1');
|
||||
console.log(asyncContext.store.get('key1')); // 'value1'
|
||||
});
|
||||
|
||||
// Scope 2
|
||||
await asyncContext.runScoped(async () => {
|
||||
asyncContext.store.add('key2', 'value2');
|
||||
console.log(asyncContext.store.get('key2')); // 'value2'
|
||||
});
|
||||
|
||||
// After both scopes finish, neither key1 nor key2 is visible to the parent
|
||||
console.log(asyncContext.store.get('key1')); // undefined
|
||||
console.log(asyncContext.store.get('key2')); // undefined
|
||||
```
|
||||
|
||||
### Deeper Nesting
|
||||
|
||||
If you nest `runScoped` calls, each subsequent call creates another child store, which inherits from the store that’s currently active. This allows you to build deeper context layers when needed.
|
||||
|
||||
```typescript
|
||||
await asyncContext.runScoped(async () => {
|
||||
asyncContext.store.add('layer1', true);
|
||||
|
||||
await asyncContext.runScoped(async () => {
|
||||
asyncContext.store.add('layer2', true);
|
||||
// This store sees data from both layer1 and layer2
|
||||
console.log(asyncContext.store.get('layer1')); // true
|
||||
console.log(asyncContext.store.get('layer2')); // true
|
||||
});
|
||||
|
||||
// Only layer1 data remains in scope here; layer2 is gone
|
||||
console.log(asyncContext.store.get('layer2')); // undefined
|
||||
});
|
||||
```
|
||||
|
||||
Changes made within this child store do not leak back to the parent unless explicitly intended.
|
||||
### Testing
|
||||
|
||||
#### Isolating Data in Scoped Functions
|
||||
|
||||
Data added within a child scope is only stored locally, unless you decide to propagate it to the parent. Additionally, you can delete data in the child without affecting the parent:
|
||||
Below is a simplified test example using [tapbundle](https://www.npmjs.com/package/@push.rocks/tapbundle). It demonstrates `runScoped()` creating isolated child stores and verifying behavior such as data inheritance and cleanup:
|
||||
|
||||
```typescript
|
||||
await mainContext.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('temporaryData', 'tempValue');
|
||||
console.log(childStore.get('temporaryData')); // Outputs: 'tempValue'
|
||||
|
||||
// Delete data in child scope
|
||||
childStore.delete('temporaryData');
|
||||
console.log(childStore.get('temporaryData')); // Outputs: undefined
|
||||
});
|
||||
```
|
||||
import { tap, expect } from '@push.rocks/tapbundle';
|
||||
import { AsyncContext } from './logcontext.classes.asynccontext.js';
|
||||
|
||||
In this example, `temporaryData` is never propagated to the parent. Once deleted within the scope, it’s gone for that child context.
|
||||
const asyncContext = new AsyncContext();
|
||||
|
||||
### Advanced Usage
|
||||
tap.test('should run scoped and see parent data', async () => {
|
||||
asyncContext.store.add('parentKey', 'parentValue');
|
||||
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
|
||||
|
||||
Below are some patterns to demonstrate more advanced scenarios.
|
||||
|
||||
#### Handling Complex Asynchronous Flows
|
||||
|
||||
Consider a scenario where you process a list of user requests asynchronously, assigning each request its own temporary data:
|
||||
|
||||
```typescript
|
||||
import { AsyncContext } from '@push.rocks/smartcontext';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
async function processUserRequests(users: string[], asyncContext: AsyncContext) {
|
||||
for (const user of users) {
|
||||
await asyncContext.runScoped(async (childStore: AsyncStore) => {
|
||||
// Assign a unique request ID
|
||||
const requestId = uuidv4();
|
||||
childStore.add('currentUser', user);
|
||||
childStore.add('requestId', requestId);
|
||||
|
||||
console.log(`Processing user: ${childStore.get('currentUser')} with Request ID: ${childStore.get('requestId')}`);
|
||||
|
||||
// Simulate an async operation
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
console.log(`Completed processing for user: ${childStore.get('currentUser')}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const mainContext = new AsyncContext();
|
||||
processUserRequests(['alice', 'bob'], mainContext);
|
||||
```
|
||||
|
||||
Each user’s scope remains neatly contained while still sharing any parent data (if present). This is highly beneficial in servers that handle multiple requests or tasks in parallel.
|
||||
|
||||
#### Sharing Data Across Scopes
|
||||
|
||||
Occasionally, you may want the child scope to add or modify data that persists in the parent. By default, `childStore` only extends the parent for lookup; changes remain local to the child. If you need truly shared data, you can write data directly to the parent store as well:
|
||||
|
||||
```typescript
|
||||
const newContext = new AsyncContext();
|
||||
await newContext.runScoped(async (childStore: AsyncStore) => {
|
||||
// This affects only the child store
|
||||
childStore.add('childMessage', 'I am a child.');
|
||||
|
||||
// Directly manipulate the parent store if needed:
|
||||
newContext.store.add('parentMessage', 'I am the parent (updated).');
|
||||
await asyncContext.runScoped(async () => {
|
||||
asyncContext.store.add('childKey', 'childValue');
|
||||
expect(asyncContext.store.get('childKey')).toEqual('childValue');
|
||||
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
|
||||
});
|
||||
});
|
||||
|
||||
// Checking the parent store:
|
||||
console.log(newContext.store.get('parentMessage')); // Outputs: 'I am the parent (updated)'
|
||||
console.log(newContext.store.get('childMessage')); // Outputs: undefined (child-only)
|
||||
```
|
||||
|
||||
This approach helps you maintain clarity on what data belongs to the parent vs. a transient child operation.
|
||||
|
||||
#### Parallel Scopes
|
||||
|
||||
When dealing with parallel asynchronous operations, each scope can be maintained independently. For instance, multiple login operations can be handled by the same parent context yet remain separate at runtime:
|
||||
|
||||
```typescript
|
||||
import { AsyncContext } from '@push.rocks/smartcontext';
|
||||
|
||||
const userContext = new AsyncContext();
|
||||
userContext.store.add('appVersion', '1.2.0');
|
||||
|
||||
async function handleUserLogin(userId: string, context: AsyncContext) {
|
||||
await context.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('sessionUser', userId);
|
||||
|
||||
console.log(`User: ${childStore.get('sessionUser')}, App: ${childStore.get('appVersion')}`);
|
||||
// More processing for the user...
|
||||
tap.test('should isolate new keys within a child scope', async () => {
|
||||
await asyncContext.runScoped(async () => {
|
||||
asyncContext.store.add('temporaryKey', 'temporaryValue');
|
||||
expect(asyncContext.store.get('temporaryKey')).toEqual('temporaryValue');
|
||||
});
|
||||
}
|
||||
// Key won't leak to the parent
|
||||
expect(asyncContext.store.get('temporaryKey')).toBeUndefined();
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
handleUserLogin('user123', userContext),
|
||||
handleUserLogin('user456', userContext),
|
||||
]);
|
||||
// More tests ...
|
||||
|
||||
tap.start();
|
||||
```
|
||||
|
||||
In this example, the `userContext` store data (like `appVersion`) is accessible within each child scope, but each user session remains isolated. The parent’s data is shared and read-only for the children, unless children write specifically to the parent context.
|
||||
### Conclusion
|
||||
|
||||
#### Error Handling and Context-Enriched Logging
|
||||
The updated `runScoped` usage makes child store management more intuitive by dynamically switching `asyncContext.store` to a child store inside the scope, then reverting back to the parent store afterwards. This design ensures:
|
||||
|
||||
By leveraging contextual data, your logs can capture additional diagnostic details automatically:
|
||||
- **Scoped Modifications**: Data added or removed in a child scope stays in that scope.
|
||||
- **Parent Inheritance**: Child scopes still read the parent’s data.
|
||||
- **Easy Syntax**: No need to pass the child store around; simply call `asyncContext.store` within `runScoped`.
|
||||
|
||||
```typescript
|
||||
async function performTaskWithLogging(taskId: string, context: AsyncContext) {
|
||||
try {
|
||||
await context.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('taskId', taskId);
|
||||
// Simulate some failing operation
|
||||
throw new Error('Task failed due to unexpected error');
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(`[Error] Task ID: ${context.store.get('taskId')}, Error: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const loggingContext = new AsyncContext();
|
||||
performTaskWithLogging('task_789', loggingContext);
|
||||
```
|
||||
|
||||
In the example above, we track `taskId` in the context store, ensuring that any error logs or additional logging statements automatically include that identifying information.
|
||||
|
||||
### Managing Contexts Across Modules
|
||||
|
||||
In large applications, you might want different modules to read or update shared context data without tight coupling between modules. One pattern is to define an `AsyncContext` in a root or shared location and pass it as needed:
|
||||
|
||||
```typescript
|
||||
// main.ts
|
||||
import { AsyncContext } from '@push.rocks/smartcontext';
|
||||
import { userModule } from './userModule';
|
||||
import { billingModule } from './billingModule';
|
||||
|
||||
const globalContext = new AsyncContext();
|
||||
globalContext.store.add('appName', 'SmartContextApp');
|
||||
|
||||
userModule(globalContext);
|
||||
billingModule(globalContext);
|
||||
```
|
||||
|
||||
Then, each module file can utilize that shared context:
|
||||
|
||||
```typescript
|
||||
// userModule.ts
|
||||
export async function userModule(context: AsyncContext) {
|
||||
await context.runScoped(async (childStore) => {
|
||||
childStore.add('moduleName', 'UserModule');
|
||||
console.log(`[UserModule] appName: ${childStore.get('appName')}`);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// billingModule.ts
|
||||
export async function billingModule(context: AsyncContext) {
|
||||
await context.runScoped(async (childStore) => {
|
||||
childStore.add('moduleName', 'BillingModule');
|
||||
console.log(`[BillingModule] appName: ${childStore.get('appName')}`);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
This approach keeps the code cleaner and ensures each module has access to shared data while retaining isolation where needed.
|
||||
|
||||
`@push.rocks/smartcontext` equips developers with a sophisticated asynchronous context management system, helping maintain clarity and consistency in logging and context sharing. Here’s a recap of the benefits:
|
||||
|
||||
- **Scoped Data**: Run logical operations within isolated child scopes, reducing contamination of global or parent-level data.
|
||||
- **Asynchronous Safety**: Each asynchronous operation can track its own context, preventing race conditions on shared state.
|
||||
- **Enhanced Logging**: Include relevant contextual data in your logs automatically for easier debugging and tracing.
|
||||
- **Module-Friendly**: Share contexts without introducing deep module interdependencies.
|
||||
|
||||
These features simplify building robust Node.js applications, where concurrency and context tracking can otherwise become unwieldy. Enjoy exploring the breadth of this module’s functionality, and tailor it to meet your project’s unique challenges.
|
||||
With `@push.rocks/smartcontext`, you can maintain clear boundaries between different parts of your asynchronous code. This not only enriches your logging with context but also simplifies tracking data across nested or concurrent operations.
|
||||
|
||||
## 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.
|
||||
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.
|
||||
|
||||
### 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.
|
||||
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.
|
||||
|
||||
### Company Information
|
||||
|
||||
Task Venture Capital GmbH
|
||||
Registered at District Court Bremen HRB 35230 HB, Germany
|
||||
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.
|
||||
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.
|
88
test/test.both.ts
Normal file
88
test/test.both.ts
Normal file
@ -0,0 +1,88 @@
|
||||
import { tap, expect } from '@push.rocks/tapbundle';
|
||||
import { AsyncContext } from '../ts/logcontext.classes.asynccontext.js';
|
||||
import { AsyncStore } from '../ts/logcontext.classes.asyncstore.js';
|
||||
|
||||
/**
|
||||
* This test file demonstrates how to use the AsyncContext and ensures
|
||||
* that runScoped() properly creates child AsyncStore contexts and merges parent data.
|
||||
*/
|
||||
|
||||
const asyncContext = new AsyncContext();
|
||||
|
||||
tap.test('should run a scoped function and add data to a child store', async () => {
|
||||
// add some default data to the parent store
|
||||
asyncContext.store.add('parentKey', 'parentValue');
|
||||
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
|
||||
|
||||
// now run a child scope, add some data, and check that parent's data is still accessible
|
||||
await asyncContext.runScoped(async () => {
|
||||
asyncContext.store.add('childKey', 'childValue');
|
||||
|
||||
// child should see its own data
|
||||
expect(asyncContext.store.get('childKey')).toEqual('childValue');
|
||||
// child should also see parent data
|
||||
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('should not contaminate the parent store with child-only data', async () => {
|
||||
// create a new child scope
|
||||
await asyncContext.runScoped(async () => {
|
||||
asyncContext.store.add('temporaryKey', 'temporaryValue');
|
||||
expect(asyncContext.store.get('temporaryKey')).toEqual('temporaryValue');
|
||||
});
|
||||
// after the child scope finishes, 'temporaryKey' should not exist in the parent
|
||||
expect(asyncContext.store.get('temporaryKey')).toBeUndefined();
|
||||
});
|
||||
|
||||
tap.test('should allow adding data in multiple scopes independently', async () => {
|
||||
// add data in first scope
|
||||
await asyncContext.runScoped(async () => {
|
||||
asyncContext.store.add('childKey1', 'childValue1');
|
||||
expect(asyncContext.store.get('childKey1')).toEqual('childValue1');
|
||||
});
|
||||
|
||||
// add data in 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');
|
||||
// attempt to delete it in the child
|
||||
asyncContext.store.delete('deletableKey');
|
||||
// child no longer sees it
|
||||
expect(asyncContext.store.get('deletableKey')).toBeUndefined();
|
||||
// but parent still has it
|
||||
});
|
||||
expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
|
||||
});
|
||||
|
||||
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();
|
88
test/test.ts
88
test/test.ts
@ -1,88 +0,0 @@
|
||||
import { tap, expect } from '@push.rocks/tapbundle';
|
||||
import { AsyncContext } from '../ts/logcontext.classes.asynccontext.js';
|
||||
import { AsyncStore } from '../ts/logcontext.classes.asyncstore.js';
|
||||
|
||||
/**
|
||||
* This test file demonstrates how to use the AsyncContext and ensures
|
||||
* that runScoped() properly creates child AsyncStore contexts and merges parent data.
|
||||
*/
|
||||
|
||||
const parentContext = new AsyncContext();
|
||||
|
||||
tap.test('should run a scoped function and add data to a child store', async () => {
|
||||
// add some default data to the parent store
|
||||
parentContext.store.add('parentKey', 'parentValue');
|
||||
expect(parentContext.store.get('parentKey')).toEqual('parentValue');
|
||||
|
||||
// now run a child scope, add some data, and check that parent's data is still accessible
|
||||
await parentContext.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('childKey', 'childValue');
|
||||
|
||||
// child should see its own data
|
||||
expect(childStore.get('childKey')).toEqual('childValue');
|
||||
// child should also see parent data
|
||||
expect(childStore.get('parentKey')).toEqual('parentValue');
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('should not contaminate the parent store with child-only data', async () => {
|
||||
// create a new child scope
|
||||
await parentContext.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('temporaryKey', 'temporaryValue');
|
||||
expect(childStore.get('temporaryKey')).toEqual('temporaryValue');
|
||||
});
|
||||
// after the child scope finishes, 'temporaryKey' should not exist in the parent
|
||||
expect(parentContext.store.get('temporaryKey')).toBeUndefined();
|
||||
});
|
||||
|
||||
tap.test('should allow adding data in multiple scopes independently', async () => {
|
||||
// add data in first scope
|
||||
await parentContext.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('childKey1', 'childValue1');
|
||||
expect(childStore.get('childKey1')).toEqual('childValue1');
|
||||
});
|
||||
|
||||
// add data in second scope
|
||||
await parentContext.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('childKey2', 'childValue2');
|
||||
expect(childStore.get('childKey2')).toEqual('childValue2');
|
||||
});
|
||||
|
||||
// neither childKey1 nor childKey2 should exist in the parent store
|
||||
expect(parentContext.store.get('childKey1')).toBeUndefined();
|
||||
expect(parentContext.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
|
||||
parentContext.store.add('deletableKey', 'iShouldStayInParent');
|
||||
|
||||
await parentContext.runScoped(async (childStore: AsyncStore) => {
|
||||
// child sees the parent's data
|
||||
expect(childStore.get('deletableKey')).toEqual('iShouldStayInParent');
|
||||
// attempt to delete it in the child
|
||||
childStore.delete('deletableKey');
|
||||
// child no longer sees it
|
||||
expect(childStore.get('deletableKey')).toBeUndefined();
|
||||
// but parent still has it
|
||||
expect(parentContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('should allow multiple child scopes to share the same parent store data', async () => {
|
||||
// add a key to the parent store
|
||||
parentContext.store.add('sharedKey', 'sharedValue');
|
||||
expect(parentContext.store.get('sharedKey')).toEqual('sharedValue');
|
||||
|
||||
// first child scope
|
||||
await parentContext.runScoped(async (firstChild: AsyncStore) => {
|
||||
expect(firstChild.get('sharedKey')).toEqual('sharedValue');
|
||||
});
|
||||
|
||||
// second child scope
|
||||
await parentContext.runScoped(async (secondChild: AsyncStore) => {
|
||||
expect(secondChild.get('sharedKey')).toEqual('sharedValue');
|
||||
});
|
||||
});
|
||||
|
||||
tap.start();
|
@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartcontext',
|
||||
version: '2.1.1',
|
||||
version: '2.1.2',
|
||||
description: 'A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.'
|
||||
}
|
||||
|
@ -2,12 +2,18 @@ import * as plugins from './logcontext.plugins.js';
|
||||
import { AsyncStore } from './logcontext.classes.asyncstore.js';
|
||||
|
||||
export class AsyncContext {
|
||||
private context = new plugins.simpleAsyncContext.AsyncContext.Variable<AsyncStore>();
|
||||
public store = new AsyncStore();
|
||||
public runScoped(functionArg: (storeArg: AsyncStore) => Promise<void>) {
|
||||
this.context.run(this.store, async () => {
|
||||
const childStore = new AsyncStore(this.store);
|
||||
functionArg(childStore)
|
||||
private _context = new plugins.simpleAsyncContext.AsyncContext.Variable<AsyncStore>();
|
||||
private _store = new AsyncStore();
|
||||
get store() {
|
||||
return this._context.get() || this._store;
|
||||
}
|
||||
set store(value: AsyncStore) {
|
||||
this._store = value;
|
||||
}
|
||||
public async runScoped(functionArg: () => Promise<void>) {
|
||||
const childStore = new AsyncStore(this.store);
|
||||
await this._context.run(childStore, async () => {
|
||||
await functionArg()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user