@travetto/context 5.0.16 → 6.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,52 +17,88 @@ This module provides a wrapper around node's [async_hooks](https://nodejs.org/ap
17
17
 
18
18
  The most common way of utilizing the context, is via the [WithAsyncContext](https://github.com/travetto/travetto/tree/main/module/context/src/decorator.ts#L7) decorator. The decorator requires the class it's being used in, to have a [AsyncContext](https://github.com/travetto/travetto/tree/main/module/context/src/service.ts#L12) member, as it is the source of the contextual information.
19
19
 
20
- The decorator will load the context on invocation, and will keep the context active during the entire asynchronous call chain.
20
+ The decorator will load the context on invocation, and will keep the context active during the entire asynchronous call chain.
21
+
22
+ **NOTE:** while access context properties directly is supported, it is recommended to use [AsyncContextValue](https://github.com/travetto/travetto/tree/main/module/context/src/value.ts#L16) instead.
21
23
 
22
24
  **Code: Usage of context within a service**
23
25
  ```typescript
24
26
  import { AsyncContext, WithAsyncContext } from '@travetto/context';
27
+ import { Inject } from '@travetto/di';
28
+
29
+ const NAME = Symbol.for('My Custom name symbol');
25
30
 
26
31
  export class ContextAwareService {
27
32
 
28
- constructor(public context: AsyncContext) { }
33
+ @Inject()
34
+ context: AsyncContext;
29
35
 
30
36
  @WithAsyncContext()
31
37
  async complexOperator(name: string) {
32
- this.context.set({ name });
38
+ this.context.set(NAME, name);
33
39
  await this.additionalOp('extra');
34
40
  await this.finalOp();
35
41
  }
36
42
 
37
43
  async additionalOp(additional: string) {
38
- const { name } = this.context.get();
39
- this.context.set({ name: `${name} ${additional}` });
44
+ const name = this.context.get(NAME);
45
+ this.context.set(NAME, `${name} ${additional}`);
40
46
  }
41
47
 
42
48
  async finalOp() {
43
- const { name } = this.context.get();
49
+ const name = this.context.get(NAME);
44
50
  // Use name
45
51
  return name;
46
52
  }
47
53
  }
48
54
  ```
49
55
 
50
- The decorator also allows for a priming of the contextual information. This is generally useful for system generated operations that are not initiated by a user.
56
+ ## AsyncContextValue
57
+ Within the framework that is a need to access context values, in a type safe fashion. Additionally, we have the requirement to keep the data accesses isolated from other operations. To this end, [AsyncContextValue](https://github.com/travetto/travetto/tree/main/module/context/src/value.ts#L16) was created to support this use case. This class represents the ability to define a simple read/write contract for a given context field. It also provides some supplemental functionality, e.g., the ability to suppress errors if a context is not initialized.
51
58
 
52
- **Code: Usage of context within a service**
59
+ **Code: Source for AsyncContextValue**
53
60
  ```typescript
54
- import { AsyncContext, WithAsyncContext } from '@travetto/context';
61
+ export class AsyncContextValue<T = unknown> {
62
+ constructor(source: StorageSource, config?: ContextConfig);
63
+ /**
64
+ * Get value
65
+ */
66
+ get(): T | undefined;
67
+ /**
68
+ * Set value
69
+ */
70
+ set(value: T | undefined): void;
71
+ }
72
+ ```
55
73
 
56
- export class SystemInitiatedContext {
74
+ **Code: Usage of context value within a service**
75
+ ```typescript
76
+ import { AsyncContext, AsyncContextValue, WithAsyncContext } from '@travetto/context';
77
+ import { Inject } from '@travetto/di';
78
+
79
+ export class ContextValueService {
80
+
81
+ @Inject()
82
+ context: AsyncContext;
57
83
 
58
- constructor(public context: AsyncContext) { }
84
+ #name = new AsyncContextValue<string>(this);
59
85
 
60
- @WithAsyncContext({
61
- user: 'system',
62
- uid: 20
63
- })
64
- async runJob(name: string) {
65
- console.log('Running', { user: this.context.get().user, jobName: name });
86
+ @WithAsyncContext()
87
+ async complexOperator(name: string) {
88
+ this.#name.set(name);
89
+ await this.additionalOp('extra');
90
+ await this.finalOp();
91
+ }
92
+
93
+ async additionalOp(additional: string) {
94
+ const name = this.#name.get();
95
+ this.#name.set(`${name} ${additional}`);
96
+ }
97
+
98
+ async finalOp() {
99
+ const name = this.#name.get();
100
+ // Use name
101
+ return name;
66
102
  }
67
103
  }
68
104
  ```
package/__index__.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './src/service';
2
+ export * from './src/value';
2
3
  export * from './src/decorator';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@travetto/context",
3
- "version": "5.0.16",
3
+ "version": "6.0.0-rc.0",
4
4
  "description": "Async-aware state management, maintaining context across asynchronous calls.",
5
5
  "keywords": [
6
6
  "async-hooks",
@@ -26,10 +26,10 @@
26
26
  "directory": "module/context"
27
27
  },
28
28
  "dependencies": {
29
- "@travetto/di": "^5.0.16"
29
+ "@travetto/di": "^6.0.0-rc.0"
30
30
  },
31
31
  "peerDependencies": {
32
- "@travetto/test": "^5.0.18"
32
+ "@travetto/test": "^6.0.0-rc.0"
33
33
  },
34
34
  "peerDependenciesMeta": {
35
35
  "@travetto/test": {
package/src/decorator.ts CHANGED
@@ -4,7 +4,7 @@ import { AsyncContext } from './service';
4
4
  /**
5
5
  * Allows running a function while providing an async context
6
6
  */
7
- export function WithAsyncContext(data?: Record<string, unknown>) {
7
+ export function WithAsyncContext() {
8
8
  return function <T extends { context: AsyncContext }>(
9
9
  target: T,
10
10
  prop: string,
@@ -12,7 +12,7 @@ export function WithAsyncContext(data?: Record<string, unknown>) {
12
12
  ): typeof descriptor {
13
13
  const og = descriptor.value!;
14
14
  descriptor.value = function (...args: unknown[]): ReturnType<typeof og> {
15
- return this.context.run(og.bind(this, ...args), structuredClone(data ?? {}));
15
+ return this.context.run(og.bind(this, ...args));
16
16
  };
17
17
 
18
18
  Object.defineProperty(descriptor.value, 'name', { value: og.name });
package/src/service.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
 
3
3
  import { Injectable } from '@travetto/di';
4
- import { AppError, castTo } from '@travetto/runtime';
4
+ import { AppError, AsyncQueue, castTo } from '@travetto/runtime';
5
5
 
6
6
  type Ctx<T = unknown> = Record<string | symbol, T>;
7
7
 
@@ -11,89 +11,72 @@ type Ctx<T = unknown> = Record<string | symbol, T>;
11
11
  @Injectable()
12
12
  export class AsyncContext {
13
13
 
14
- alStorage = new AsyncLocalStorage<{ value?: Ctx }>();
15
- active = 0;
14
+ storage = new AsyncLocalStorage<Ctx>();
16
15
 
17
16
  constructor() {
18
17
  this.run = this.run.bind(this);
19
18
  this.iterate = this.iterate.bind(this);
20
19
  }
21
20
 
22
- #store<T = unknown>(setAs?: Ctx<T> | null): Ctx<T> {
23
- const val = this.alStorage.getStore();
24
- if (!val) {
21
+ #get<T = unknown>(): Ctx<T> {
22
+ const store = this.storage.getStore();
23
+ if (!store) {
25
24
  throw new AppError('Context is not initialized');
26
25
  }
27
- if (setAs) {
28
- val.value = setAs;
29
- } else if (!val.value) {
30
- val.value = {};
31
- }
32
- return castTo(val.value);
26
+ return castTo(store);
33
27
  }
34
28
 
35
29
  /**
36
- * Get entire context or a portion by key
30
+ * Are we in an active context
37
31
  */
38
- get<T = unknown>(key: string | symbol): T;
39
- get(): Ctx;
40
- get<T>(key?: string | symbol): Ctx | T {
41
- const root = this.#store<T>();
42
- if (key) {
43
- return root[key];
44
- } else {
45
- return root;
46
- }
32
+ get active(): boolean {
33
+ return this.storage.getStore() !== undefined;
47
34
  }
48
35
 
49
36
  /**
50
- * Set entire context or a portion by key
37
+ * Get context field by key
51
38
  */
52
- set(key: string | symbol, val: unknown): void;
53
- set(val: Ctx): void;
54
- set(keyOrVal: string | symbol | Ctx, valWithKey?: unknown): void {
55
- if (typeof keyOrVal === 'string' || typeof keyOrVal === 'symbol') {
56
- this.get()[keyOrVal] = valWithKey;
57
- } else {
58
- this.#store(keyOrVal);
59
- }
39
+ get<T = unknown>(key: string | symbol): T | undefined {
40
+ return this.#get<T>()[key];
41
+ }
42
+
43
+ /**
44
+ * Set context field by key
45
+ */
46
+ set<T = unknown>(key: string | symbol, val: T | undefined): void {
47
+ this.#get()[key] = val;
48
+ }
49
+
50
+ /**
51
+ * Get entire context
52
+ * @private
53
+ */
54
+ copy<T = unknown>(): Ctx<T> {
55
+ return structuredClone(this.#get<T>());
60
56
  }
61
57
 
62
58
  /**
63
59
  * Run an async function and ensure the context is available during execution
64
60
  */
65
61
  async run<T = unknown>(fn: () => Promise<T> | T, init: Ctx = {}): Promise<T> {
66
- if (this.alStorage.getStore()) {
67
- init = { ...this.#store(), ...init };
68
- }
69
- this.active += 1;
70
- this.alStorage.enterWith({ value: init });
71
- try {
72
- return await fn();
73
- } finally {
74
- delete this.alStorage.getStore()?.value;
75
- if ((this.active -= 1) === 0) {
76
- this.alStorage.disable();
77
- }
78
- }
62
+ return this.storage.run({ ...this.storage.getStore(), ...init }, fn);
79
63
  }
80
64
 
81
65
  /**
82
66
  * Run an async function and ensure the context is available during execution
83
67
  */
84
- async * iterate<T>(fn: () => AsyncGenerator<T>, init: Ctx = {}): AsyncGenerator<T> {
85
- if (this.alStorage.getStore()) {
86
- init = { ...this.#store(), ...init };
87
- }
88
- this.active += 1;
89
- this.alStorage.enterWith({ value: init });
90
- try {
91
- return yield* fn();
92
- } finally {
93
- delete this.alStorage.getStore()?.value;
94
- if ((this.active -= 1) === 0) {
95
- this.alStorage.disable();
68
+ iterate<T>(fn: () => AsyncIterable<T>, init: Ctx = {}): AsyncIterable<T> {
69
+ const out = new AsyncQueue<T>();
70
+ this.storage.run({ ...this.storage.getStore(), ...init }, async () => {
71
+ try {
72
+ for await (const item of fn()) {
73
+ out.add(item);
74
+ }
75
+ out.close();
76
+ } catch (err) {
77
+ out.throw(castTo(err));
96
78
  }
97
- }
79
+ });
80
+ return out;
98
81
  }
99
82
  }
package/src/value.ts ADDED
@@ -0,0 +1,60 @@
1
+ import { AppError, castTo } from '@travetto/runtime';
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+
4
+ type Payload<T> = Record<string | symbol, T | undefined>;
5
+ type Storage<T = unknown> = AsyncLocalStorage<Payload<T>>;
6
+ type Key = string | symbol;
7
+ type StorageSource = Storage | (() => Storage) | { storage: Storage } | { context: { storage: Storage } };
8
+
9
+ type ContextConfig = {
10
+ failIfUnbound?: boolean;
11
+ };
12
+
13
+ /**
14
+ * Async Context Value
15
+ */
16
+ export class AsyncContextValue<T = unknown> {
17
+
18
+ #source: () => Storage<T>;
19
+ #storage?: Storage<T>;
20
+ #key: Key = Symbol();
21
+ #failIfUnbound: boolean;
22
+
23
+ constructor(source: StorageSource, config?: ContextConfig) {
24
+ this.#source = castTo(typeof source === 'function' ?
25
+ source :
26
+ ((): Storage => 'getStore' in source ?
27
+ source :
28
+ ('storage' in source ?
29
+ source.storage :
30
+ source.context.storage
31
+ ))
32
+ );
33
+ this.#failIfUnbound = config?.failIfUnbound ?? true;
34
+ }
35
+
36
+ get #store(): Payload<T> | undefined {
37
+ const store = (this.#storage ??= this.#source()).getStore();
38
+ if (!store && this.#failIfUnbound) {
39
+ throw new AppError('Context not initialized');
40
+ }
41
+ return store;
42
+ }
43
+
44
+ /**
45
+ * Get value
46
+ */
47
+ get(): T | undefined {
48
+ return this.#store?.[this.#key];
49
+ }
50
+
51
+ /**
52
+ * Set value
53
+ */
54
+ set(value: T | undefined): void {
55
+ const store = this.#store;
56
+ if (store) {
57
+ store[this.#key] = value;
58
+ }
59
+ }
60
+ }
@@ -11,11 +11,11 @@ const Init = Symbol();
11
11
  * Allows for defining a common suite context
12
12
  * @param data
13
13
  */
14
- export function WithSuiteContext(data: Record<string, unknown> = {}) {
14
+ export function WithSuiteContext() {
15
15
  return (target: Class): void => {
16
16
  function wrapped(ctx: AsyncContext, og: Function) {
17
17
  return function (this: unknown) {
18
- return ctx.run(og.bind(this), structuredClone(data));
18
+ return ctx.run(og.bind(this));
19
19
  };
20
20
  }
21
21
 
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2020 ArcSine Technologies
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.