@decaf-ts/core 0.20.0 → 0.21.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.
Files changed (138) hide show
  1. package/lib/cjs/index.cjs +1 -1
  2. package/lib/esm/index.js +1 -1
  3. package/lib/types/auth/constants.d.ts +5 -0
  4. package/lib/types/auth/decorators.d.ts +5 -0
  5. package/lib/types/auth/index.d.ts +2 -0
  6. package/lib/types/fs/FilesystemAdapter.d.ts +70 -0
  7. package/lib/types/fs/FsDispatch.d.ts +7 -0
  8. package/lib/types/fs/helpers.d.ts +17 -0
  9. package/lib/types/fs/index.d.ts +4 -0
  10. package/lib/types/fs/indexStore.d.ts +28 -0
  11. package/lib/types/fs/locks/FilesystemLock.d.ts +13 -0
  12. package/lib/types/fs/locks/FilesystemMultiLock.d.ts +8 -0
  13. package/lib/types/fs/types.d.ts +40 -0
  14. package/lib/types/identity/decorators.d.ts +72 -0
  15. package/lib/types/identity/index.d.ts +6 -0
  16. package/lib/types/index.d.cts +1 -1
  17. package/lib/types/index.d.mts +1 -1
  18. package/lib/types/index.d.ts +34 -0
  19. package/lib/types/interfaces/ContextuallyLogged.d.ts +8 -0
  20. package/lib/types/interfaces/ErrorParser.d.ts +16 -0
  21. package/lib/types/interfaces/Executor.d.ts +16 -0
  22. package/lib/types/interfaces/Observable.d.ts +33 -0
  23. package/lib/types/interfaces/Observer.d.ts +15 -0
  24. package/lib/types/interfaces/Paginatable.d.ts +20 -0
  25. package/lib/types/interfaces/Queriable.d.ts +47 -0
  26. package/lib/types/interfaces/RawExecutor.d.ts +28 -0
  27. package/lib/types/interfaces/SequenceOptions.d.ts +79 -0
  28. package/lib/types/interfaces/index.d.ts +12 -0
  29. package/lib/types/migrations/Migration.d.ts +19 -0
  30. package/lib/types/migrations/MigrationService.d.ts +63 -0
  31. package/lib/types/migrations/MigrationTaskBuilder.d.ts +10 -0
  32. package/lib/types/migrations/MigrationTasks.d.ts +9 -0
  33. package/lib/types/migrations/MigrationVersioning.d.ts +7 -0
  34. package/lib/types/migrations/SemverMigrationVersioning.d.ts +10 -0
  35. package/lib/types/migrations/StandardMigrationVersioning.d.ts +12 -0
  36. package/lib/types/migrations/constants.d.ts +2 -0
  37. package/lib/types/migrations/decorators.d.ts +12 -0
  38. package/lib/types/migrations/index.d.ts +15 -0
  39. package/lib/types/migrations/types.d.ts +46 -0
  40. package/lib/types/model/BaseModel.d.ts +37 -0
  41. package/lib/types/model/SequenceModel.d.ts +32 -0
  42. package/lib/types/model/construction.d.ts +455 -0
  43. package/lib/types/model/decorators.d.ts +237 -0
  44. package/lib/types/model/index.d.ts +11 -0
  45. package/lib/types/model/indexing.d.ts +20 -0
  46. package/lib/types/model/types.d.ts +60 -0
  47. package/lib/types/overrides/Metadata.d.ts +22 -0
  48. package/lib/types/overrides/Model.d.ts +94 -0
  49. package/lib/types/overrides/ModelBuilder.d.ts +31 -0
  50. package/lib/types/overrides/index.d.ts +11 -0
  51. package/lib/types/overrides/injectables.d.ts +10 -0
  52. package/lib/types/overrides/overrides.d.ts +1 -0
  53. package/lib/types/persistence/Adapter.d.ts +469 -0
  54. package/lib/types/persistence/Context.d.ts +16 -0
  55. package/lib/types/persistence/ContextLock.d.ts +18 -0
  56. package/lib/types/persistence/Dispatch.d.ts +128 -0
  57. package/lib/types/persistence/ObserverHandler.d.ts +111 -0
  58. package/lib/types/persistence/Sequence.d.ts +126 -0
  59. package/lib/types/persistence/constants.d.ts +74 -0
  60. package/lib/types/persistence/decorators.d.ts +28 -0
  61. package/lib/types/persistence/errors.d.ts +33 -0
  62. package/lib/types/persistence/event-filters.d.ts +20 -0
  63. package/lib/types/persistence/generators.d.ts +14 -0
  64. package/lib/types/persistence/index.d.ts +18 -0
  65. package/lib/types/persistence/transactions.d.ts +4 -0
  66. package/lib/types/persistence/types.d.ts +86 -0
  67. package/lib/types/query/Condition.d.ts +131 -0
  68. package/lib/types/query/MethodQueryBuilder.d.ts +185 -0
  69. package/lib/types/query/Paginator.d.ts +105 -0
  70. package/lib/types/query/Statement.d.ts +136 -0
  71. package/lib/types/query/constants.d.ts +69 -0
  72. package/lib/types/query/decorators.d.ts +8 -0
  73. package/lib/types/query/errors.d.ts +21 -0
  74. package/lib/types/query/index.d.ts +16 -0
  75. package/lib/types/query/options.d.ts +393 -0
  76. package/lib/types/query/selectors.d.ts +39 -0
  77. package/lib/types/query/types.d.ts +158 -0
  78. package/lib/types/query/utils.d.ts +40 -0
  79. package/lib/types/ram/RamAdapter.d.ts +341 -0
  80. package/lib/types/ram/RamPaginator.d.ts +54 -0
  81. package/lib/types/ram/RamStatement.d.ts +92 -0
  82. package/lib/types/ram/constants.d.ts +8 -0
  83. package/lib/types/ram/handlers.d.ts +24 -0
  84. package/lib/types/ram/index.d.ts +12 -0
  85. package/lib/types/ram/types.d.ts +50 -0
  86. package/lib/types/repository/Repository.d.ts +501 -0
  87. package/lib/types/repository/constants.d.ts +36 -0
  88. package/lib/types/repository/decorators.d.ts +30 -0
  89. package/lib/types/repository/errors.d.ts +19 -0
  90. package/lib/types/repository/index.d.ts +12 -0
  91. package/lib/types/repository/injectables.d.ts +95 -0
  92. package/lib/types/repository/types.d.ts +28 -0
  93. package/lib/types/repository/utils.d.ts +36 -0
  94. package/lib/types/services/ModelService.d.ts +45 -0
  95. package/lib/types/services/PersistenceService.d.ts +17 -0
  96. package/lib/types/services/index.d.ts +8 -0
  97. package/lib/types/services/services.d.ts +96 -0
  98. package/lib/types/tasks/CleanUpTask.d.ts +15 -0
  99. package/lib/types/tasks/TaskContext.d.ts +30 -0
  100. package/lib/types/tasks/TaskEngine.d.ts +97 -0
  101. package/lib/types/tasks/TaskErrors.d.ts +65 -0
  102. package/lib/types/tasks/TaskEventBus.d.ts +17 -0
  103. package/lib/types/tasks/TaskEventService.d.ts +7 -0
  104. package/lib/types/tasks/TaskHandler.d.ts +12 -0
  105. package/lib/types/tasks/TaskHandlerRegistry.d.ts +8 -0
  106. package/lib/types/tasks/TaskService.d.ts +65 -0
  107. package/lib/types/tasks/TaskStateChangeError.d.ts +11 -0
  108. package/lib/types/tasks/TaskTracker.d.ts +47 -0
  109. package/lib/types/tasks/builder.d.ts +72 -0
  110. package/lib/types/tasks/constants.d.ts +31 -0
  111. package/lib/types/tasks/decorators.d.ts +4 -0
  112. package/lib/types/tasks/index.d.ts +23 -0
  113. package/lib/types/tasks/logging.d.ts +31 -0
  114. package/lib/types/tasks/models/TaskBackoffModel.d.ts +9 -0
  115. package/lib/types/tasks/models/TaskErrorModel.d.ts +8 -0
  116. package/lib/types/tasks/models/TaskEventModel.d.ts +11 -0
  117. package/lib/types/tasks/models/TaskIOSerializer.d.ts +33 -0
  118. package/lib/types/tasks/models/TaskLogEntryModel.d.ts +10 -0
  119. package/lib/types/tasks/models/TaskModel.d.ts +43 -0
  120. package/lib/types/tasks/models/TaskStepResultModel.d.ts +9 -0
  121. package/lib/types/tasks/models/TaskStepSpecModel.d.ts +9 -0
  122. package/lib/types/tasks/models/index.d.ts +8 -0
  123. package/lib/types/tasks/types.d.ts +71 -0
  124. package/lib/types/tasks/utils.d.ts +5 -0
  125. package/lib/types/utils/ContextualLoggedClass.d.ts +37 -0
  126. package/lib/types/utils/decorators.d.ts +27 -0
  127. package/lib/types/utils/errors.d.ts +56 -0
  128. package/lib/types/utils/index.d.ts +11 -0
  129. package/lib/types/utils/throttling.d.ts +9 -0
  130. package/lib/types/utils/types.d.ts +23 -0
  131. package/lib/types/utils/utils.d.ts +22 -0
  132. package/lib/types/workers/TaskEngine.d.ts +40 -0
  133. package/lib/types/workers/WorkThreadEnvironment.d.ts +35 -0
  134. package/lib/types/workers/index.d.ts +5 -0
  135. package/lib/types/workers/messages.d.ts +69 -0
  136. package/lib/types/workers/types.d.ts +41 -0
  137. package/lib/types/workers/workerThread.d.ts +1 -0
  138. package/package.json +1 -1
@@ -0,0 +1,65 @@
1
+ import { type ContextualArgs, type ContextualizedArgs, type MaybeContextualArg, type MethodOrOperation } from "../utils/ContextualLoggedClass";
2
+ import { ClientBasedService } from "../services/services";
3
+ import { TaskEngine } from "./TaskEngine";
4
+ import { Adapter } from "../persistence/Adapter";
5
+ import { type AllOperationKeys, type ContextOf, type EventIds, type ObserverFilter } from "../persistence/types";
6
+ import { type PrimaryKeyType } from "@decaf-ts/db-decorators";
7
+ import { OrderDirection } from "../repository/constants";
8
+ import { type Repo } from "../repository/Repository";
9
+ import { TaskModel } from "./models/TaskModel";
10
+ import { type DirectionLimitOffset } from "../query/types";
11
+ import type { Constructor } from "@decaf-ts/decoration";
12
+ import type { Observer } from "../interfaces/Observer";
13
+ import type { ArrayMode } from "../services/ModelService";
14
+ import { TaskEngineConfig } from "./types";
15
+ import { TaskTracker } from "./TaskTracker";
16
+ import { TaskEventModel } from "./models/index";
17
+ import { SelectSelector, WhereOption } from "../query/index";
18
+ export type TaskServiceConfig<A extends Adapter<any, any, any, any>, T extends TaskEngine<A> = TaskEngine<A>, C extends TaskEngineConfig<A> = TaskEngineConfig<A>> = C & {
19
+ engine?: Constructor<T>;
20
+ };
21
+ export declare class TaskService<A extends Adapter<any, any, any, any>> extends ClientBasedService<TaskEngine<A>, TaskEngineConfig<A>> {
22
+ protected get adapter(): A;
23
+ protected get tasks(): Repo<TaskModel>;
24
+ protected get events(): Repo<TaskEventModel>;
25
+ constructor();
26
+ initialize(...args: MaybeContextualArg<ContextOf<A>>): Promise<{
27
+ config: TaskServiceConfig<A, any, any>;
28
+ client: TaskEngine<A>;
29
+ }>;
30
+ push<I, O>(task: TaskModel<I, O>, ...args: MaybeContextualArg<any>): Promise<TaskModel<I, O>>;
31
+ push<I, O>(task: TaskModel<I, O>, track: false, ...args: MaybeContextualArg<any>): Promise<TaskModel<I, O>>;
32
+ push<I, O>(task: TaskModel<I, O>, track: true, ...args: MaybeContextualArg<any>): Promise<{
33
+ task: TaskModel<I, O>;
34
+ tracker: TaskTracker<O>;
35
+ }>;
36
+ track(id: string, ...args: MaybeContextualArg<any>): Promise<{
37
+ task: TaskModel;
38
+ tracker: TaskTracker<any>;
39
+ }>;
40
+ select<S extends readonly SelectSelector<TaskModel>[]>(): WhereOption<TaskModel, TaskModel[]>;
41
+ select<S extends readonly SelectSelector<TaskModel>[]>(selector: readonly [...S]): WhereOption<TaskModel, Pick<TaskModel, S[number]>[]>;
42
+ create(model: TaskModel, ...args: MaybeContextualArg<ContextOf<A>>): Promise<TaskModel>;
43
+ createAll(models: TaskModel[], ...args: MaybeContextualArg<ContextOf<A>>): Promise<TaskModel[]>;
44
+ delete(key: PrimaryKeyType, ...args: MaybeContextualArg<ContextOf<A>>): Promise<TaskModel>;
45
+ deleteAll(keys: PrimaryKeyType[], ...args: MaybeContextualArg<ContextOf<A>>): Promise<TaskModel[]>;
46
+ read(key: PrimaryKeyType, ...args: MaybeContextualArg<ContextOf<A>>): Promise<TaskModel>;
47
+ readAll(keys: PrimaryKeyType[], ...args: MaybeContextualArg<ContextOf<A>>): Promise<TaskModel[]>;
48
+ query<M, R extends ArrayMode = "one">(methodName: string, ...args: MaybeContextualArg<ContextOf<A>>): Promise<R extends "one" ? M : M[]>;
49
+ update(model: TaskModel, ...args: MaybeContextualArg<ContextOf<A>>): Promise<TaskModel>;
50
+ updateAll(models: TaskModel[], ...args: MaybeContextualArg<ContextOf<A>>): Promise<TaskModel[]>;
51
+ listBy(key: keyof TaskModel, order: OrderDirection, ...args: MaybeContextualArg<ContextOf<A>>): Promise<TaskModel<any, any>[]>;
52
+ paginateBy(key: keyof TaskModel, order: OrderDirection, ref: Omit<DirectionLimitOffset, "direction">, ...args: MaybeContextualArg<ContextOf<A>>): Promise<import("..").SerializedPage<TaskModel<any, any>>>;
53
+ findOneBy(key: keyof TaskModel, value: any, ...args: MaybeContextualArg<ContextOf<A>>): Promise<TaskModel<any, any>>;
54
+ findBy(key: keyof TaskModel, value: any, ...args: MaybeContextualArg<ContextOf<A>>): Promise<TaskModel<any, any>[]>;
55
+ findByPaginate(key: keyof TaskModel, value: any, ref: DirectionLimitOffset, ...args: MaybeContextualArg<ContextOf<A>>): Promise<import("..").SerializedPage<TaskModel<any, any>>>;
56
+ statement(name: string, ...args: MaybeContextualArg<ContextOf<A>>): Promise<any>;
57
+ refresh(table: Constructor<any>, event: AllOperationKeys, id: EventIds, ...args: ContextualArgs<ContextOf<A>>): Promise<void>;
58
+ observe(observer: Observer, filter?: ObserverFilter): () => void;
59
+ unObserve(observer: Observer): void;
60
+ updateObservers(model: Constructor, operation: AllOperationKeys, ids: EventIds, ...args: ContextualArgs<ContextOf<A>>): Promise<void>;
61
+ protected logCtx<ARGS extends any[] = any[], METHOD extends MethodOrOperation = MethodOrOperation>(args: MaybeContextualArg<ContextOf<A>, ARGS>, operation: METHOD): ContextualizedArgs<ContextOf<A>, ARGS, METHOD extends string ? true : false>;
62
+ protected logCtx<ARGS extends any[] = any[], METHOD extends MethodOrOperation = MethodOrOperation>(args: MaybeContextualArg<ContextOf<A>, ARGS>, operation: METHOD, allowCreate: false): ContextualizedArgs<ContextOf<A>, ARGS, METHOD extends string ? true : false>;
63
+ protected logCtx<ARGS extends any[] = any[], METHOD extends MethodOrOperation = MethodOrOperation>(args: MaybeContextualArg<ContextOf<A>, ARGS>, operation: METHOD, allowCreate: true): Promise<ContextualizedArgs<ContextOf<A>, ARGS, METHOD extends string ? true : false>>;
64
+ shutdown(...args: MaybeContextualArg<any>): Promise<void>;
65
+ }
@@ -0,0 +1,11 @@
1
+ import { TaskStatus } from "./constants";
2
+ import { TaskErrorModel } from "./models/TaskErrorModel";
3
+ export interface TaskStateChangeRequest {
4
+ status: TaskStatus;
5
+ error?: TaskErrorModel;
6
+ scheduledTo?: Date;
7
+ }
8
+ export declare class TaskStateChangeError extends Error {
9
+ readonly request: TaskStateChangeRequest;
10
+ constructor(request: TaskStateChangeRequest);
11
+ }
@@ -0,0 +1,47 @@
1
+ import { Observer } from "../interfaces/Observer";
2
+ import { TaskEventModel } from "./models/TaskEventModel";
3
+ import { Logger } from "@decaf-ts/logging";
4
+ import { TaskEventType, TaskStatus } from "./constants";
5
+ import { EventPipe, LogPipe, LogPipeOptions } from "./types";
6
+ import { TaskModel } from "./models/TaskModel";
7
+ import { Context } from "../persistence/index";
8
+ import { TaskEventBus } from "./TaskEventBus";
9
+ import { TaskControlError } from "./TaskErrors";
10
+ export declare class TaskTracker<O = any> implements Observer<[TaskEventModel, Context]> {
11
+ protected bus: TaskEventBus;
12
+ private readonly task;
13
+ protected unregistration: () => void;
14
+ protected pipes?: Record<TaskEventType, Set<EventPipe>>;
15
+ private resolved;
16
+ private terminalContext?;
17
+ constructor(bus: TaskEventBus, task: TaskModel);
18
+ resolve(): Promise<O>;
19
+ wait(): Promise<O>;
20
+ attach(log: Logger, opts?: LogPipeOptions): void;
21
+ logs(pipe: LogPipe): void;
22
+ pipe(pipe: EventPipe, type?: TaskEventType): void;
23
+ protected succeed(_result?: O): void;
24
+ protected fail(_error?: TaskControlError): void;
25
+ protected cancel(evt: TaskEventModel): void;
26
+ protected retry(): void;
27
+ protected reschedule(): void;
28
+ onSucceed(handler: EventPipe): () => void;
29
+ onFailure(handler: EventPipe): () => void;
30
+ onCancel(handler: EventPipe): () => void;
31
+ onUpdate(handler: EventPipe): () => void;
32
+ private awaitStatusTerminal;
33
+ private extractOutput;
34
+ private extractError;
35
+ private complete;
36
+ protected isTerminalStatus(status: TaskStatus): boolean;
37
+ protected track(evt: TaskEventModel, ctx: Context): Promise<void>;
38
+ private registerStatusHandler;
39
+ private getTerminalContext;
40
+ private buildTerminalEvent;
41
+ private createTaskControlError;
42
+ private assignNextAction;
43
+ private getNextAction;
44
+ private buildMeta;
45
+ private resolveTerminalState;
46
+ refresh(evt: TaskEventModel, ctx: Context): Promise<void>;
47
+ }
@@ -0,0 +1,72 @@
1
+ import { TaskModel } from "./models/TaskModel";
2
+ import { BackoffStrategy, JitterStrategy, TaskStatus, TaskType } from "./constants";
3
+ import { TaskBackoffModel } from "./models/index";
4
+ import { TaskStepSpecModel } from "./models/TaskStepSpecModel";
5
+ import { Model, ModelArg } from "@decaf-ts/decorator-validation";
6
+ export declare class TaskBackoffBuilder<NESTED extends boolean = false> extends Model {
7
+ baseMs: number;
8
+ jitter: JitterStrategy;
9
+ maxMs: number;
10
+ strategy: BackoffStrategy;
11
+ constructor(arg?: ModelArg<TaskBackoffBuilder>);
12
+ setBaseMs(value: number): this;
13
+ setJitter(value: JitterStrategy): this;
14
+ setMaxMs(value: number): this;
15
+ setStrategy(value: BackoffStrategy): this;
16
+ build(): NESTED extends false ? TaskBackoffModel : TaskBuilder;
17
+ }
18
+ export declare class TaskBuilder extends Model {
19
+ protected classification: string;
20
+ protected name?: string;
21
+ protected status: TaskStatus;
22
+ protected atomicity: TaskType;
23
+ protected backoff: TaskBackoffModel;
24
+ protected input?: any;
25
+ protected lock?: string;
26
+ protected dependencies?: string[];
27
+ protected maxAttempts: number;
28
+ setClassification(value: string): this;
29
+ setName(value: string): this;
30
+ setAtomicity(value: TaskType): this;
31
+ setBackoff<V extends TaskBackoffModel>(value?: TaskBackoffModel): V extends TaskBackoffModel ? this : TaskBackoffBuilder<true>;
32
+ setInput(value: any): this;
33
+ setLock(value?: string): this;
34
+ setDependencies(value?: string[]): this;
35
+ setDependsOn(value?: string[]): this;
36
+ setMaxAttempts(value: number): this;
37
+ constructor(arg?: ModelArg<TaskBuilder>);
38
+ build(): TaskModel<any, any>;
39
+ }
40
+ export declare class TaskStepSpecBuilder {
41
+ protected parent: CompositeTaskBuilder;
42
+ protected step: TaskStepSpecModel;
43
+ constructor(parent: CompositeTaskBuilder, step: TaskStepSpecModel);
44
+ setClassification(value: string): this;
45
+ setName(value?: string): this;
46
+ setInput(value: any): this;
47
+ setLock(value?: string): this;
48
+ setDependsOn(value?: string[]): this;
49
+ addStep(classification: string): TaskStepSpecBuilder;
50
+ addStep(classification: string, input: any): CompositeTaskBuilder;
51
+ addStep(classification: string, name: string, input?: any): CompositeTaskBuilder;
52
+ setSteps(value: TaskStepSpecModel[]): CompositeTaskBuilder;
53
+ build(): CompositeTaskBuilder;
54
+ }
55
+ export declare class CompositeTaskBuilder extends TaskBuilder {
56
+ protected steps?: TaskStepSpecModel[];
57
+ protected stepResults?: TaskStepSpecModel[];
58
+ constructor(arg?: ModelArg<CompositeTaskBuilder>);
59
+ setAtomicity(value: TaskType): this;
60
+ setSteps(value: TaskStepSpecModel[]): this;
61
+ /**
62
+ * Backwards compatible:
63
+ * - addStep(classification, input?)
64
+ * - addStep(classification, name, input?)
65
+ *
66
+ * When called with only `classification`, returns a TaskStepSpecBuilder so
67
+ * callers can configure the step and then `.build()` back to this builder.
68
+ */
69
+ addStep(classification: string): TaskStepSpecBuilder;
70
+ addStep(classification: string, input: any): this;
71
+ addStep(classification: string, name: string, input?: any): this;
72
+ }
@@ -0,0 +1,31 @@
1
+ import { TaskEngineConfig } from "./types";
2
+ export declare enum TaskStatus {
3
+ PENDING = "pending",
4
+ SCHEDULED = "scheduled",
5
+ RUNNING = "running",
6
+ FAILED = "failed",
7
+ SUCCEEDED = "succeeded",
8
+ CANCELED = "canceled",
9
+ WAITING_RETRY = "waiting_retry"
10
+ }
11
+ export declare enum BackoffStrategy {
12
+ EXPONENTIAL = "exponential",
13
+ FIXED = "fixed"
14
+ }
15
+ export declare enum JitterStrategy {
16
+ NONE = "none",
17
+ FULL = "full"
18
+ }
19
+ export declare enum TaskEventType {
20
+ STATUS = "status",
21
+ UPDATE = "update",
22
+ LOG = "log",
23
+ PROGRESS = "progress",
24
+ ALL = "all"
25
+ }
26
+ export declare enum TaskType {
27
+ ATOMIC = "atomic",
28
+ COMPOSITE = "composite"
29
+ }
30
+ export declare const TasksKey = "tasks";
31
+ export declare const DefaultTaskEngineConfig: TaskEngineConfig<any>;
@@ -0,0 +1,4 @@
1
+ export type TaskMetadata = {
2
+ type: string;
3
+ };
4
+ export declare function task(key: string): (target: any, propertyKey?: any, descriptor?: TypedPropertyDescriptor<any>) => any;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @description Exports for the tasks module.
3
+ * @summary This file exports all the necessary components for the tasks functionality, including models, builder, and more.
4
+ * @module core/tasks
5
+ */
6
+ import "../overrides";
7
+ export * from "./models";
8
+ export * from "./builder";
9
+ export * from "./CleanUpTask";
10
+ export * from "./constants";
11
+ export * from "./decorators";
12
+ export * from "./logging";
13
+ export * from "./TaskContext";
14
+ export * from "./TaskEngine";
15
+ export * from "./TaskEventBus";
16
+ export * from "./TaskEventService";
17
+ export * from "./TaskHandler";
18
+ export * from "./TaskHandlerRegistry";
19
+ export * from "./TaskService";
20
+ export * from "./TaskTracker";
21
+ export * from "./types";
22
+ export * from "./utils";
23
+ export * from "./TaskErrors";
@@ -0,0 +1,31 @@
1
+ import { AnyFunction, Logger, LoggingConfig, LogLevel, LogMeta, StringLike } from "@decaf-ts/logging";
2
+ import { EventPipe, LogPipe, LogPipeOptions } from "./types";
3
+ export declare class TaskLogger<LOG extends Logger> implements Logger {
4
+ protected logger: Logger;
5
+ protected bufferSize: number;
6
+ protected maxBufferSize: number;
7
+ protected pipe?: LogPipe | undefined;
8
+ protected history: [LogLevel, string, any][];
9
+ constructor(logger: Logger, bufferSize?: number, maxBufferSize?: number, pipe?: LogPipe | undefined);
10
+ push(level: LogLevel, string: string, meta?: any): void;
11
+ flush<PIPE extends LogPipe>(pipe?: PIPE): PIPE extends LogPipe ? Promise<[LogLevel, string, any][]> : [LogLevel, string, any][];
12
+ readonly root: string[];
13
+ benchmark(msg: StringLike): void;
14
+ clear(): this;
15
+ debug(msg: StringLike, meta?: LogMeta): void;
16
+ error(msg: StringLike | Error, e?: Error | LogMeta, meta?: LogMeta): void;
17
+ for(config: Partial<LoggingConfig>): this;
18
+ for(context: string | {
19
+ new (...args: any[]): any;
20
+ } | AnyFunction | object): this;
21
+ for(method: string | {
22
+ new (...args: any[]): any;
23
+ } | AnyFunction | object | Partial<LoggingConfig>, config?: Partial<LoggingConfig>, ...args: any[]): this;
24
+ info(msg: StringLike, meta?: LogMeta): void;
25
+ setConfig(config: Partial<LoggingConfig>): void;
26
+ silly(msg: StringLike, meta?: LogMeta): void;
27
+ trace(msg: StringLike, meta?: LogMeta): void;
28
+ verbose(msg: StringLike, verbosity?: number | LogMeta, meta?: LogMeta): void;
29
+ warn(msg: StringLike, meta?: LogMeta): void;
30
+ }
31
+ export declare function getLogPipe<LOG extends Logger>(log: LOG, opts?: LogPipeOptions): EventPipe;
@@ -0,0 +1,9 @@
1
+ import { Model, type ModelArg } from "@decaf-ts/decorator-validation";
2
+ import { BackoffStrategy, JitterStrategy } from "../constants";
3
+ export declare class TaskBackoffModel extends Model {
4
+ strategy: BackoffStrategy;
5
+ baseMs: number;
6
+ maxMs: number;
7
+ jitter?: JitterStrategy;
8
+ constructor(arg?: ModelArg<TaskBackoffModel>);
9
+ }
@@ -0,0 +1,8 @@
1
+ import { Model, type ModelArg } from "@decaf-ts/decorator-validation";
2
+ export declare class TaskErrorModel extends Model {
3
+ message: string;
4
+ stack?: string;
5
+ code?: string;
6
+ details?: any;
7
+ constructor(arg?: ModelArg<TaskErrorModel>);
8
+ }
@@ -0,0 +1,11 @@
1
+ import { Model, type ModelArg } from "@decaf-ts/decorator-validation";
2
+ import { TaskEventType } from "../constants";
3
+ export declare class TaskEventModel extends Model {
4
+ id: string;
5
+ uuid: string;
6
+ taskId: string;
7
+ ts: Date;
8
+ classification: TaskEventType;
9
+ payload?: any;
10
+ constructor(arg?: ModelArg<TaskEventModel>);
11
+ }
@@ -0,0 +1,33 @@
1
+ import { JSONSerializer, Model } from "@decaf-ts/decorator-validation";
2
+ export declare class TaskIOSerializer<M extends Model> extends JSONSerializer<M> {
3
+ constructor();
4
+ /**
5
+ * @summary prepares the model for serialization
6
+ * @description returns a shallow copy of the object, containing an enumerable {@link ModelKeys#ANCHOR} property
7
+ * so the object can be recognized upon deserialization
8
+ *
9
+ * @param {any} value
10
+ * @protected
11
+ */
12
+ protected preSerialize(value: any, ...args: any[]): any;
13
+ /**
14
+ * @summary Rebuilds a model from a serialization
15
+ * @param {string} str
16
+ *
17
+ * @throws {Error} If it fails to parse the string, or to build the model
18
+ */
19
+ deserialize(str: string, ...args: any[]): M;
20
+ private serializeValue;
21
+ private serializeModel;
22
+ private serializePlain;
23
+ private getMetadata;
24
+ private rebuildValue;
25
+ private rebuildObject;
26
+ /**
27
+ * @summary Serializes a model
28
+ * @param {T} model
29
+ *
30
+ * @throws {Error} if fails to serialize
31
+ */
32
+ serialize(model: M, ...args: any[]): string;
33
+ }
@@ -0,0 +1,10 @@
1
+ import { LogLevel } from "@decaf-ts/logging";
2
+ import { type ModelArg, Model } from "@decaf-ts/decorator-validation";
3
+ export declare class TaskLogEntryModel extends Model {
4
+ ts: Date;
5
+ level: LogLevel;
6
+ step?: number;
7
+ msg: string;
8
+ meta?: any;
9
+ constructor(arg?: ModelArg<TaskLogEntryModel>);
10
+ }
@@ -0,0 +1,43 @@
1
+ import { Model, type ModelArg } from "@decaf-ts/decorator-validation";
2
+ import { TaskStatus, TaskType } from "../constants";
3
+ import { TaskErrorModel } from "./TaskErrorModel";
4
+ import { TaskBackoffModel } from "./TaskBackoffModel";
5
+ import { TaskStepSpecModel } from "./TaskStepSpecModel";
6
+ import { TaskStepResultModel } from "./TaskStepResultModel";
7
+ import { TaskLogEntryModel } from "./TaskLogEntryModel";
8
+ export declare class TaskModel<INPUT = any, OUTPUT = any> extends Model {
9
+ id: string;
10
+ atomicity: TaskType;
11
+ classification: string;
12
+ name?: string;
13
+ lock?: string;
14
+ status: TaskStatus;
15
+ input?: INPUT;
16
+ output?: OUTPUT;
17
+ error?: TaskErrorModel;
18
+ attempt: number;
19
+ maxAttempts: number;
20
+ backoff: TaskBackoffModel;
21
+ nextRunAt?: Date;
22
+ scheduledTo?: Date;
23
+ dependencies?: string[];
24
+ leaseOwner?: string;
25
+ leaseExpiry?: Date;
26
+ steps?: TaskStepSpecModel[];
27
+ currentStep?: number;
28
+ stepResults?: TaskStepResultModel[];
29
+ logTail?: TaskLogEntryModel[];
30
+ /**
31
+ * @description Creation timestamp for the model
32
+ * @summary Automatically set to the current date and time when the model is created
33
+ */
34
+ createdAt: Date;
35
+ /**
36
+ * @description Last update timestamp for the model
37
+ * @summary Automatically updated to the current date and time whenever the model is modified
38
+ */
39
+ updatedAt: Date;
40
+ createdBy: string;
41
+ updatedBy: string;
42
+ constructor(arg?: ModelArg<TaskModel>);
43
+ }
@@ -0,0 +1,9 @@
1
+ import { Model, type ModelArg } from "@decaf-ts/decorator-validation";
2
+ import { TaskStatus } from "../constants";
3
+ import { TaskErrorModel } from "./TaskErrorModel";
4
+ export declare class TaskStepResultModel extends Model {
5
+ status: TaskStatus;
6
+ output?: any;
7
+ error?: TaskErrorModel;
8
+ constructor(arg?: ModelArg<TaskStepResultModel>);
9
+ }
@@ -0,0 +1,9 @@
1
+ import { Model, type ModelArg } from "@decaf-ts/decorator-validation";
2
+ export declare class TaskStepSpecModel extends Model {
3
+ classification: string;
4
+ name?: string;
5
+ input?: any;
6
+ lock?: string;
7
+ dependsOn?: string[];
8
+ constructor(arg?: ModelArg<TaskStepSpecModel>);
9
+ }
@@ -0,0 +1,8 @@
1
+ export * from "./TaskBackoffModel";
2
+ export * from "./TaskErrorModel";
3
+ export * from "./TaskEventModel";
4
+ export * from "./TaskIOSerializer";
5
+ export * from "./TaskLogEntryModel";
6
+ export * from "./TaskModel";
7
+ export * from "./TaskStepResultModel";
8
+ export * from "./TaskStepSpecModel";
@@ -0,0 +1,71 @@
1
+ import { TaskContext } from "./TaskContext";
2
+ import { TaskLogger } from "./logging";
3
+ import { LogLevel } from "@decaf-ts/logging";
4
+ import { Adapter, ContextFlags } from "../persistence/index";
5
+ import { ConfOf } from "../persistence/types";
6
+ import { TaskEventBus } from "./TaskEventBus";
7
+ import { TaskHandlerRegistry } from "./TaskHandlerRegistry";
8
+ import { TaskEventModel } from "./models/TaskEventModel";
9
+ import { TaskStatus } from "./constants";
10
+ import { TaskErrorModel } from "./models/TaskErrorModel";
11
+ import { TaskStepSpecModel } from "./models/TaskStepSpecModel";
12
+ export interface ITaskHandler<I = any, O = any> {
13
+ type: string;
14
+ run(input: I, ctx: TaskContext): Promise<O>;
15
+ catch?(input: I, error: unknown, ctx: TaskContext): Promise<void>;
16
+ }
17
+ export type TaskDependencySpec = {
18
+ dependencies?: string[];
19
+ };
20
+ export type LogPipeOptions = {
21
+ style: boolean;
22
+ logProgress: boolean;
23
+ logStatus: boolean;
24
+ };
25
+ export type EventPipe = (evt: TaskEventModel, ...args: any[]) => Promise<void>;
26
+ export interface LogPipe {
27
+ (logs: [LogLevel, string, any][]): Promise<void>;
28
+ (entry: [LogLevel, string] | [LogLevel, string, any]): Promise<void>;
29
+ (level: LogLevel, msg: string, meta?: any): Promise<void>;
30
+ }
31
+ export interface TaskFlags<LOG extends TaskLogger<any> = TaskLogger<any>> extends ContextFlags<LOG> {
32
+ taskId: string;
33
+ attempt: number;
34
+ pipe: LogPipe;
35
+ flush: () => Promise<void>;
36
+ progress: (data: any) => Promise<void>;
37
+ heartbeat: () => Promise<void>;
38
+ scheduleCompositeSteps?: (steps: TaskStepSpecModel[]) => Promise<void>;
39
+ resultCache?: Record<string, any>;
40
+ }
41
+ export type TaskEngineConfig<A extends Adapter<any, any, any, any>> = {
42
+ adapter: A;
43
+ overrides?: Partial<ConfOf<A>>;
44
+ bus?: TaskEventBus;
45
+ registry?: TaskHandlerRegistry;
46
+ workerId: string;
47
+ concurrency: number;
48
+ leaseMs: number;
49
+ pollMsIdle: number;
50
+ pollMsBusy: number;
51
+ logTailMax: number;
52
+ streamBufferSize: number;
53
+ maxLoggingBuffer: number;
54
+ loggingBufferTruncation: number;
55
+ gracefulShutdownMsTimeout: number;
56
+ autoShutdown?: TaskEngineAutoShutdownConfig;
57
+ };
58
+ export type TaskProgressPayload = {
59
+ status: TaskStatus | "update";
60
+ currentStep?: number;
61
+ totalSteps?: number;
62
+ output?: any;
63
+ error?: TaskErrorModel;
64
+ nextRunAt?: Date;
65
+ scheduledTo?: Date;
66
+ };
67
+ export interface TaskEngineAutoShutdownConfig {
68
+ enabled?: boolean;
69
+ backoffStepMs?: number;
70
+ maxIdleDelayMs?: number;
71
+ }
@@ -0,0 +1,5 @@
1
+ import { TaskErrorModel } from "./models/TaskErrorModel";
2
+ import { TaskBackoffModel } from "./models/TaskBackoffModel";
3
+ export declare function computeBackoffMs(attempt: number, cfg: TaskBackoffModel): number;
4
+ export declare function serializeError(err: any): TaskErrorModel;
5
+ export declare function sleep(ms: number): Promise<unknown>;
@@ -0,0 +1,37 @@
1
+ import { LoggedClass, Logger } from "@decaf-ts/logging";
2
+ import { BulkCrudOperationKeys, Contextual, OperationKeys } from "@decaf-ts/db-decorators";
3
+ import { Context } from "../persistence/Context";
4
+ import { FlagsOf, LoggerOf } from "../persistence/types";
5
+ import type { Constructor } from "@decaf-ts/decoration";
6
+ import { PersistenceKeys } from "../persistence/index";
7
+ import { PreparedStatementKeys } from "../query/index";
8
+ export type ContextualArgs<C extends Context<any>, ARGS extends any[] = any[]> = [...ARGS, C];
9
+ export type MethodOrOperation = ((...args: any[]) => any) | string | OperationKeys | PersistenceKeys | BulkCrudOperationKeys | PreparedStatementKeys;
10
+ export type MaybeContextualArg<C extends Context<any>, ARGS extends any[] = any[]> = any[] | ContextualArgs<C, ARGS>;
11
+ export type ContextualizedArgs<C extends Context<any>, ARGS extends any[] = any[], EXTEND extends boolean = false> = EXTEND extends true ? {
12
+ ctx: C;
13
+ log: LoggerOf<C>;
14
+ ctxArgs: ContextualArgs<C, ARGS>;
15
+ for: (...any: any[]) => ContextualizedArgs<C, ARGS, false>;
16
+ } : {
17
+ ctx: C;
18
+ log: LoggerOf<C>;
19
+ ctxArgs: ContextualArgs<C, ARGS>;
20
+ };
21
+ export declare abstract class ContextualLoggedClass<C extends Context<any>> extends LoggedClass {
22
+ protected logCtx<CONTEXT extends Context<any> = C, ARGS extends any[] = any[], METHOD extends MethodOrOperation = MethodOrOperation>(args: MaybeContextualArg<CONTEXT, ARGS>, operation: METHOD): ContextualizedArgs<CONTEXT, ARGS, METHOD extends string ? true : false>;
23
+ protected logCtx<CONTEXT extends Context<any> = C, ARGS extends any[] = any[], METHOD extends MethodOrOperation = MethodOrOperation>(args: MaybeContextualArg<CONTEXT, ARGS>, operation: METHOD, allowCreate: false, overrides?: Partial<FlagsOf<CONTEXT>>): ContextualizedArgs<CONTEXT, ARGS, METHOD extends string ? true : false>;
24
+ protected logCtx<CONTEXT extends Context<any> = C, ARGS extends any[] = any[], METHOD extends MethodOrOperation = MethodOrOperation>(args: MaybeContextualArg<CONTEXT, ARGS>, operation: METHOD, allowCreate: true, overrides?: Partial<FlagsOf<CONTEXT>>): Promise<ContextualizedArgs<CONTEXT, ARGS, METHOD extends string ? true : false>>;
25
+ static logFrom<CONTEXT extends Context<any>, A = any | Contextual<CONTEXT>, METHOD extends MethodOrOperation = MethodOrOperation>(obj: A, logger: LoggerOf<any>, ctx: CONTEXT, method?: METHOD | keyof A): Logger;
26
+ static logCtx<CONTEXT extends Context<any>, ARGS extends any[] = any[], METHOD extends MethodOrOperation = MethodOrOperation>(this: any, operation: METHOD, ...args: MaybeContextualArg<CONTEXT, ARGS>): ContextualizedArgs<CONTEXT, ARGS, METHOD extends string ? true : false>;
27
+ }
28
+ export declare abstract class AbsContextual<C extends Context<any>> extends ContextualLoggedClass<C> implements Contextual<C> {
29
+ protected constructor();
30
+ /**
31
+ * @description The context constructor for this adapter
32
+ * @summary Reference to the context class constructor used by this adapter
33
+ */
34
+ private readonly _Context;
35
+ protected get Context(): Constructor<C>;
36
+ context(operation: ((...args: any[]) => any) | OperationKeys.CREATE | OperationKeys.READ | OperationKeys.UPDATE | OperationKeys.DELETE | string, overrides: Partial<FlagsOf<C>>, ...args: MaybeContextualArg<Context<any>, any[]>): Promise<C>;
37
+ }
@@ -0,0 +1,27 @@
1
+ import { Constructor } from "@decaf-ts/decoration";
2
+ import type { ModelConstructor } from "@decaf-ts/decorator-validation";
3
+ import { HttpVerbs } from "./types";
4
+ export declare const create: () => (target: any, _propertyKey?: any, descriptor?: any) => any;
5
+ export declare const read: () => (target: any, _propertyKey?: any, descriptor?: any) => any;
6
+ export declare const update: () => (target: any, _propertyKey?: any, descriptor?: any) => any;
7
+ export declare const del: () => (target: any, _propertyKey?: any, descriptor?: any) => any;
8
+ export declare function service(key?: string | ModelConstructor<any>): (target: any, prop?: any, descriptor?: any) => void;
9
+ export declare function auth(model: string | Constructor): (target: any, propertyKey?: any, descriptor?: TypedPropertyDescriptor<any>) => any;
10
+ /**
11
+ * A decorator function that sets the roles required for authentication and authorization to the model in NestJS.
12
+ *
13
+ * @param roles - An array of role names required for access.
14
+ *
15
+ * @returns - A function that applies the role decorators to the target.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * @model('users')
20
+ * @Roles(['admin'])
21
+ * export class UserModel {
22
+ * //...
23
+ * }
24
+ *
25
+ */
26
+ export declare const roles: (roles: string[]) => (model: any, prop?: any, descriptor?: PropertyDescriptor | number) => void;
27
+ export declare function route(httpMethod: HttpVerbs, path: string): (target: any, propertyKey?: any, descriptor?: TypedPropertyDescriptor<any>) => any;
@@ -0,0 +1,56 @@
1
+ import { BadRequestError, InternalError } from "@decaf-ts/db-decorators";
2
+ /**
3
+ * @description Error thrown when a user is not authorized to perform an action
4
+ * @summary This error is thrown when a user attempts to access a resource or perform an action without proper authentication
5
+ * @param {string|Error} msg - The error message or Error object
6
+ * @class AuthorizationError
7
+ * @category Errors
8
+ * @example
9
+ * ```typescript
10
+ * // Example of throwing an AuthorizationError
11
+ * if (!user.isAuthenticated()) {
12
+ * throw new AuthorizationError('User not authenticated');
13
+ * }
14
+ * ```
15
+ */
16
+ export declare class AuthorizationError extends BadRequestError {
17
+ constructor(msg: string | Error, name?: string, code?: number);
18
+ }
19
+ /**
20
+ * @description Error thrown when a user is forbidden from accessing a resource
21
+ * @summary This error is thrown when an authenticated user attempts to access a resource or perform an action they don't have permission for
22
+ * @param {string|Error} msg - The error message or Error object
23
+ * @return {void}
24
+ * @class ForbiddenError
25
+ * @category Errors
26
+ * @example
27
+ * ```typescript
28
+ * // Example of throwing a ForbiddenError
29
+ * if (!user.hasPermission('admin')) {
30
+ * throw new ForbiddenError('User does not have admin permissions');
31
+ * }
32
+ * ```
33
+ */
34
+ export declare class ForbiddenError extends AuthorizationError {
35
+ constructor(msg: string | Error, name?: string);
36
+ }
37
+ /**
38
+ * @description Error thrown when a connection to a service fails
39
+ * @summary This error is thrown when the application fails to establish a connection to a required service or resource
40
+ * @param {string|Error} msg - The error message or Error object
41
+ * @return {void}
42
+ * @class ConnectionError
43
+ * @category Errors
44
+ * @example
45
+ * ```typescript
46
+ * // Example of throwing a ConnectionError
47
+ * try {
48
+ * await database.connect();
49
+ * } catch (error) {
50
+ * throw new ConnectionError('Failed to connect to database');
51
+ * }
52
+ * ```
53
+ */
54
+ export declare class ConnectionError extends InternalError {
55
+ constructor(msg: string | Error);
56
+ }