task-manager-logic 0.1.1 → 0.1.2

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/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "task-manager-logic",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "private": false,
5
- "description": "任务管理实现:状态机、组聚合、任务树存储",
5
+ "description": "Runtime-first TaskSpace transition processors and backend-neutral in-memory owner",
6
6
  "type": "module",
7
7
  "main": "./src/index.ts",
8
8
  "exports": {
9
9
  ".": "./src/index.ts"
10
10
  },
11
11
  "dependencies": {
12
- "task-manager-contract": "0.1.1"
12
+ "task-manager-contract": "0.1.2"
13
13
  },
14
14
  "files": [
15
15
  "src"
package/src/errors.ts ADDED
@@ -0,0 +1,31 @@
1
+ export type TaskManagerErrorCode =
2
+ | 'artifact-conflict'
3
+ | 'claim-expired'
4
+ | 'claim-not-expired'
5
+ | 'claim-token-mismatch'
6
+ | 'command-receipt-mismatch'
7
+ | 'cross-space-identity'
8
+ | 'cyclic-task-forest'
9
+ | 'duplicate-task-identity'
10
+ | 'invalid-commit'
11
+ | 'invalid-task-definition'
12
+ | 'invalid-task-transition'
13
+ | 'lease-out-of-range'
14
+ | 'revision-conflict'
15
+ | 'task-not-found'
16
+ | 'task-not-ready'
17
+ | 'task-space-already-exists'
18
+ | 'task-space-not-found'
19
+ | 'terminal-task-immutable';
20
+
21
+ export class TaskManagerError extends Error {
22
+ readonly name = 'TaskManagerError';
23
+
24
+ constructor(
25
+ readonly code: TaskManagerErrorCode,
26
+ message: string,
27
+ ) {
28
+ super(`[${code}] ${message}`);
29
+ }
30
+ }
31
+
package/src/index.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export * from './errors.js';
1
2
  export * from './statusMachine.js';
2
- export * from './tree.js';
3
- export * from './stores.js';
3
+ export * from './validation.js';
4
+ export * from './memory-owner.js';
5
+ export * from './processors.js';
@@ -0,0 +1,160 @@
1
+ import type {
2
+ TaskArtifactBody,
3
+ TaskArtifactDigest,
4
+ TaskCommandId,
5
+ TaskCommandReceipt,
6
+ TaskHistoryEvent,
7
+ TaskSpaceCommit,
8
+ TaskSpaceCommitResult,
9
+ TaskSpaceId,
10
+ TaskSpaceOwnerPort,
11
+ TaskSpaceSnapshot,
12
+ } from 'task-manager-contract';
13
+ import { TaskManagerError } from './errors.js';
14
+ import { deepImmutableClone } from './validation.js';
15
+
16
+ interface MemoryTaskSpaceState {
17
+ readonly snapshot: TaskSpaceSnapshot;
18
+ readonly history: readonly TaskHistoryEvent[];
19
+ readonly receiptsByCommand: ReadonlyMap<TaskCommandId, TaskCommandReceipt>;
20
+ readonly artifacts: ReadonlyMap<TaskArtifactDigest, TaskArtifactBody>;
21
+ }
22
+
23
+ /** Deterministic effect adapter for tests and embedded single-process use. */
24
+ export class InMemoryTaskSpaceOwner implements TaskSpaceOwnerPort {
25
+ readonly #spaces = new Map<TaskSpaceId, MemoryTaskSpaceState>();
26
+
27
+ async readSnapshot(taskSpaceId: TaskSpaceId): Promise<TaskSpaceSnapshot | undefined> {
28
+ const snapshot = this.#spaces.get(taskSpaceId)?.snapshot;
29
+ return snapshot === undefined ? undefined : deepImmutableClone(snapshot);
30
+ }
31
+
32
+ async readReceiptByCommand(
33
+ taskSpaceId: TaskSpaceId,
34
+ commandId: TaskCommandId,
35
+ ): Promise<TaskCommandReceipt | undefined> {
36
+ const receipt = this.#spaces.get(taskSpaceId)?.receiptsByCommand.get(commandId);
37
+ return receipt === undefined ? undefined : deepImmutableClone(receipt);
38
+ }
39
+
40
+ async readHistory(taskSpaceId: TaskSpaceId): Promise<readonly TaskHistoryEvent[]> {
41
+ return deepImmutableClone(this.#spaces.get(taskSpaceId)?.history ?? []);
42
+ }
43
+
44
+ async readArtifact(
45
+ taskSpaceId: TaskSpaceId,
46
+ digest: TaskArtifactDigest,
47
+ ): Promise<TaskArtifactBody | undefined> {
48
+ const artifact = this.#spaces.get(taskSpaceId)?.artifacts.get(digest);
49
+ return artifact === undefined ? undefined : deepImmutableClone(artifact);
50
+ }
51
+
52
+ async compareAndSwap(commit: TaskSpaceCommit): Promise<TaskSpaceCommitResult> {
53
+ const current = this.#spaces.get(commit.taskSpaceId);
54
+ const replay = current?.receiptsByCommand.get(commit.commandId);
55
+ if (current && replay) {
56
+ return deepImmutableClone({
57
+ kind: 'command-replayed',
58
+ taskSpaceId: commit.taskSpaceId,
59
+ revision: current.snapshot.revision,
60
+ snapshot: current.snapshot,
61
+ receipt: replay,
62
+ });
63
+ }
64
+
65
+ const actualRevision = current?.snapshot.revision ?? null;
66
+ if (actualRevision !== commit.expectedRevision) {
67
+ return {
68
+ kind: 'revision-conflict',
69
+ taskSpaceId: commit.taskSpaceId,
70
+ expectedRevision: commit.expectedRevision,
71
+ actualRevision,
72
+ };
73
+ }
74
+
75
+ const receipt = validateCommit(commit, current);
76
+ const receiptsByCommand = new Map(current?.receiptsByCommand ?? []);
77
+ for (const candidate of commit.receipts) receiptsByCommand.set(candidate.commandId, deepImmutableClone(candidate));
78
+ const artifacts = new Map(current?.artifacts ?? []);
79
+ for (const artifact of commit.artifacts) {
80
+ const prior = artifacts.get(artifact.digest);
81
+ if (prior && !sameArtifact(prior, artifact)) {
82
+ throw new TaskManagerError('artifact-conflict', `digest ${artifact.digest} has conflicting content`);
83
+ }
84
+ artifacts.set(artifact.digest, deepImmutableClone(artifact));
85
+ }
86
+ const next: MemoryTaskSpaceState = {
87
+ snapshot: deepImmutableClone(commit.snapshot),
88
+ history: deepImmutableClone([...(current?.history ?? []), ...commit.events]),
89
+ receiptsByCommand,
90
+ artifacts,
91
+ };
92
+ this.#spaces.set(commit.taskSpaceId, next);
93
+ return deepImmutableClone({
94
+ kind: 'commit-accepted',
95
+ taskSpaceId: commit.taskSpaceId,
96
+ revision: next.snapshot.revision,
97
+ snapshot: next.snapshot,
98
+ receipt,
99
+ });
100
+ }
101
+ }
102
+
103
+ function validateCommit(
104
+ commit: TaskSpaceCommit,
105
+ current: MemoryTaskSpaceState | undefined,
106
+ ): TaskCommandReceipt {
107
+ const expectedNextRevision = commit.expectedRevision === null ? 0 : commit.expectedRevision + 1;
108
+ if (commit.kind !== 'task-space-commit'
109
+ || commit.snapshot.taskSpaceId !== commit.taskSpaceId
110
+ || commit.snapshot.definition.taskSpaceId !== commit.taskSpaceId
111
+ || commit.snapshot.revision !== expectedNextRevision) {
112
+ invalid('commit snapshot identity or revision is inconsistent');
113
+ }
114
+ if (commit.receipts.length !== 1) invalid('one command admission must contain exactly one receipt');
115
+ const receipt = commit.receipts[0];
116
+ if (!receipt || receipt.commandId !== commit.commandId || receipt.taskSpaceId !== commit.taskSpaceId) {
117
+ invalid('commit receipt does not match command identity');
118
+ }
119
+ if (receipt.toRevision !== expectedNextRevision) invalid('receipt toRevision does not match snapshot');
120
+ if (receipt.fromRevision !== (commit.expectedRevision ?? 0)) invalid('receipt fromRevision does not match CAS');
121
+
122
+ const priorHistoryIds = current?.snapshot.historyEventIds ?? [];
123
+ const expectedHistoryIds = [...priorHistoryIds, ...commit.events.map(({ eventId }) => eventId)];
124
+ if (!sameStrings(commit.snapshot.historyEventIds, expectedHistoryIds)) invalid('snapshot history is not append-only');
125
+ const priorReceiptIds = current?.snapshot.issuedReceiptIds ?? [];
126
+ const expectedReceiptIds = [...priorReceiptIds, ...commit.receipts.map(({ receiptId }) => receiptId)];
127
+ if (!sameStrings(commit.snapshot.issuedReceiptIds, expectedReceiptIds)) invalid('snapshot receipt history is not append-only');
128
+
129
+ const seenEvents = new Set(priorHistoryIds);
130
+ for (let index = 0; index < commit.events.length; index += 1) {
131
+ const event = commit.events[index]!;
132
+ if (event.taskSpaceId !== commit.taskSpaceId
133
+ || event.commandId !== commit.commandId
134
+ || event.sequence !== priorHistoryIds.length + index
135
+ || event.fromRevision !== (commit.expectedRevision ?? 0)
136
+ || event.toRevision !== expectedNextRevision
137
+ || seenEvents.has(event.eventId)) {
138
+ invalid(`event ${event.eventId} violates append-only commit identity`);
139
+ }
140
+ seenEvents.add(event.eventId);
141
+ }
142
+ return receipt;
143
+ }
144
+
145
+ function sameStrings(left: readonly string[], right: readonly string[]): boolean {
146
+ return left.length === right.length && left.every((value, index) => value === right[index]);
147
+ }
148
+
149
+ function sameArtifact(left: TaskArtifactBody, right: TaskArtifactBody): boolean {
150
+ return left.digest === right.digest
151
+ && left.mediaType === right.mediaType
152
+ && left.sizeBytes === right.sizeBytes
153
+ && left.encoding === right.encoding
154
+ && left.data === right.data;
155
+ }
156
+
157
+ function invalid(message: string): never {
158
+ throw new TaskManagerError('invalid-commit', message);
159
+ }
160
+