"description":"A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.",
@ -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:
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:
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:
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:
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.
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
awaitasyncContext.runScoped(async()=>{
asyncContext.store.add('layer1',true);
awaitasyncContext.runScoped(async()=>{
asyncContext.store.add('layer2',true);
// This store sees data from both layer1 and layer2
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:
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:
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:
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`.
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:
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
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.
description:'A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.'
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.