@atolis-hq/wake 0.3.97 → 0.3.98

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.
@@ -1,4 +1,5 @@
1
1
  import { ResourceEventType, selectResourceEvent } from '../contracts/events.js';
2
+ import { ResourceCorrelationRole } from '../contracts/vocabulary.js';
2
3
  export const resourceProjection = {
3
4
  name: 'resources',
4
5
  select(event) {
@@ -11,6 +12,10 @@ export const resourceProjection = {
11
12
  const owned = selectResourceEvent(event);
12
13
  if (owned === null)
13
14
  return previous;
15
+ if (isExternalOutcome(owned))
16
+ return projectExternalOutcome(previous, owned);
17
+ if (isCorrelationRetry(owned))
18
+ return projectCorrelationRetry(previous, owned);
14
19
  switch (owned.eventType) {
15
20
  case ResourceEventType.ResourceDiscovered:
16
21
  return {
@@ -35,6 +40,11 @@ export const resourceProjection = {
35
40
  },
36
41
  };
37
42
  case ResourceEventType.WorkCorrelationEstablished:
43
+ return previous === null
44
+ ? previous
45
+ : owned.payload.role === ResourceCorrelationRole.Primary
46
+ ? withoutCorrelationStatus(previous)
47
+ : previous;
38
48
  case ResourceEventType.WorkCorrelationRetracted:
39
49
  case ResourceEventType.IssueCompletionObservationConsumed:
40
50
  case ResourceEventType.IssueCompletionObservationSuperseded:
@@ -44,6 +54,48 @@ export const resourceProjection = {
44
54
  }
45
55
  },
46
56
  };
57
+ function isCorrelationRetry(event) {
58
+ return (event.eventType === ResourceEventType.WorkCorrelationRetryPending ||
59
+ event.eventType === ResourceEventType.WorkCorrelationUnresolvable);
60
+ }
61
+ function isExternalOutcome(event) {
62
+ return (event.eventType === ResourceEventType.ExternalOutcomeObserved ||
63
+ event.eventType === ResourceEventType.ExternalOutcomeReopened ||
64
+ event.eventType === ResourceEventType.ExternalOutcomeConsumed);
65
+ }
66
+ function projectCorrelationRetry(previous, event) {
67
+ switch (event.eventType) {
68
+ case ResourceEventType.WorkCorrelationRetryPending:
69
+ return previous;
70
+ case ResourceEventType.WorkCorrelationUnresolvable:
71
+ return previous === null ? previous : { ...previous, correlationStatus: 'unresolvable' };
72
+ default:
73
+ return assertNever(event);
74
+ }
75
+ }
76
+ function projectExternalOutcome(previous, event) {
77
+ switch (event.eventType) {
78
+ case ResourceEventType.ExternalOutcomeObserved:
79
+ return previous === null ? previous : { ...previous, pendingExternalOutcome: event.payload };
80
+ case ResourceEventType.ExternalOutcomeReopened:
81
+ return previous === null ? previous : withoutPendingExternalOutcome(previous);
82
+ case ResourceEventType.ExternalOutcomeConsumed:
83
+ return previous?.pendingExternalOutcome?.sourceObservationId ===
84
+ event.payload.sourceObservationId
85
+ ? withoutPendingExternalOutcome(previous)
86
+ : previous;
87
+ default:
88
+ return assertNever(event);
89
+ }
90
+ }
91
+ function withoutCorrelationStatus(view) {
92
+ const { correlationStatus: _correlationStatus, ...withoutStatus } = view;
93
+ return withoutStatus;
94
+ }
95
+ function withoutPendingExternalOutcome(view) {
96
+ const { pendingExternalOutcome: _pendingExternalOutcome, ...withoutOutcome } = view;
97
+ return withoutOutcome;
98
+ }
47
99
  export const resourceCorrelationProjection = {
48
100
  name: 'resource-correlations',
49
101
  select(event) {
@@ -55,6 +107,8 @@ export const resourceCorrelationProjection = {
55
107
  const owned = selectResourceEvent(event);
56
108
  if (owned === null)
57
109
  return previous;
110
+ if (!changesCorrelation(owned))
111
+ return previous;
58
112
  switch (owned.eventType) {
59
113
  case ResourceEventType.WorkCorrelationEstablished: {
60
114
  const correlation = {
@@ -70,17 +124,15 @@ export const resourceCorrelationProjection = {
70
124
  }
71
125
  case ResourceEventType.WorkCorrelationRetracted:
72
126
  return previous.filter((value) => value.workItemId !== owned.payload.workItemId);
73
- case ResourceEventType.ResourceDiscovered:
74
- case ResourceEventType.ResourceRevisionObserved:
75
- case ResourceEventType.WorkCorrelationConflicted:
76
- case ResourceEventType.IssueCompletionObservationConsumed:
77
- case ResourceEventType.IssueCompletionObservationSuperseded:
78
- return previous;
79
127
  default:
80
128
  return assertNever(owned);
81
129
  }
82
130
  },
83
131
  };
132
+ function changesCorrelation(event) {
133
+ return (event.eventType === ResourceEventType.WorkCorrelationEstablished ||
134
+ event.eventType === ResourceEventType.WorkCorrelationRetracted);
135
+ }
84
136
  function assertNever(value) {
85
137
  throw new Error(`Unhandled Resource event: ${JSON.stringify(value)}`);
86
138
  }
@@ -1,10 +1,13 @@
1
- import { decodeResourceEvent, selectResourceEvent, } from '../contracts/events.js';
1
+ import { cachedJournalView, } from '../../kernel/index.js';
2
+ import { ResourceEventType, decodeResourceEvent, selectResourceEvent, } from '../contracts/events.js';
2
3
  import { resourceStream } from '../contracts/streams.js';
3
4
  import { foldResource } from '../domain/resource.js';
4
5
  export class ResourceRepository {
5
6
  journal;
7
+ resourceIds;
6
8
  constructor(journal) {
7
9
  this.journal = journal;
10
+ this.resourceIds = cachedJournalView(journal, deriveResourceIds);
8
11
  }
9
12
  async load(resourceId) {
10
13
  const events = await this.journal.readStream(resourceStream(resourceId));
@@ -15,4 +18,15 @@ export class ResourceRepository {
15
18
  const events = await this.journal.append(resourceStream(resourceId), expectedSequence, drafts);
16
19
  return events.map(decodeResourceEvent);
17
20
  }
21
+ async listResourceIds() {
22
+ return this.resourceIds.get();
23
+ }
24
+ }
25
+ function deriveResourceIds(events) {
26
+ return [
27
+ ...new Set(events
28
+ .map(selectResourceEvent)
29
+ .filter((event) => event?.eventType === ResourceEventType.ResourceDiscovered)
30
+ .map((event) => event.stream.id)),
31
+ ];
18
32
  }
@@ -2,6 +2,7 @@ import { createEventDraft, EventSourceKind, } from '../../kernel/index.js';
2
2
  import { ResourceEventType, } from '../contracts/events.js';
3
3
  import { resourceStream } from '../contracts/streams.js';
4
4
  import { ResourceCorrelationProvenance, ResourceCorrelationRole, } from '../contracts/vocabulary.js';
5
+ import { noteMissingPrimaryCorrelation, observeExternalOutcome, pendingExternalOutcomes, retryPendingWorkCorrelations, } from './resource-correlation-retry.js';
5
6
  import { ResourceRepository } from './resource-repository.js';
6
7
  export function createResourceService(journal, lookup) {
7
8
  const repository = new ResourceRepository(journal);
@@ -25,6 +26,13 @@ export function createResourceService(journal, lookup) {
25
26
  workItemId,
26
27
  }));
27
28
  },
29
+ noteMissingPrimaryCorrelation: (resourceId, reason, context) => noteMissingPrimaryCorrelation(repository, resourceId, reason, context),
30
+ retryPendingWorkCorrelations: () => retryPendingWorkCorrelations(repository),
31
+ observeExternalOutcome: (resourceId, observation, context) => observeExternalOutcome(repository, resourceId, observation, context),
32
+ pendingExternalOutcomes: () => pendingExternalOutcomes(repository),
33
+ consumeExternalOutcome: (resourceId, sourceObservationId, context) => appendResourceEvent(repository, resourceId, resourceDraft(resourceId, context, ResourceEventType.ExternalOutcomeConsumed, {
34
+ sourceObservationId,
35
+ })),
28
36
  async consumeIssueCompletion(resourceId, intentEventId, context) {
29
37
  await appendResourceEvent(repository, resourceId, resourceDraft(resourceId, context, ResourceEventType.IssueCompletionObservationConsumed, {
30
38
  intentEventId,
@@ -38,6 +46,14 @@ export function createResourceService(journal, lookup) {
38
46
  };
39
47
  }
40
48
  async function discoverResource(repository, command, context) {
49
+ const existing = (await repository.load(command.resourceId)).resource;
50
+ if (existing !== null) {
51
+ if (command.revision !== undefined && existing.view.revision !== command.revision)
52
+ await appendResourceEvent(repository, command.resourceId, resourceDraft(command.resourceId, context, ResourceEventType.ResourceRevisionObserved, {
53
+ revision: command.revision,
54
+ }));
55
+ return (await repository.load(command.resourceId)).resource.view;
56
+ }
41
57
  await appendResourceEvent(repository, command.resourceId, resourceDraft(command.resourceId, context, ResourceEventType.ResourceDiscovered, {
42
58
  kind: command.kind,
43
59
  externalKey: command.externalKey,
@@ -3,13 +3,18 @@ import { brandedStringSchema, eventEnvelopeSchema, } from '../../kernel/index.js
3
3
  import { workItemId } from '../../work/index.js';
4
4
  import { resourceCapability, resourceId, resourceKind, } from './identifiers.js';
5
5
  import { ResourceStreamKind } from './streams.js';
6
- import { ResourceCorrelationProvenance, ResourceCorrelationRole, } from './vocabulary.js';
6
+ import { ResourceCorrelationProvenance, ResourceCorrelationRole, ResourceExternalOutcome, } from './vocabulary.js';
7
7
  export const ResourceEventType = {
8
8
  ResourceDiscovered: 'resources.resource-discovered',
9
9
  ResourceRevisionObserved: 'resources.resource-revision-observed',
10
10
  WorkCorrelationEstablished: 'resources.work-correlation-established',
11
11
  WorkCorrelationRetracted: 'resources.work-correlation-retracted',
12
12
  WorkCorrelationConflicted: 'resources.work-correlation-conflicted',
13
+ WorkCorrelationRetryPending: 'resources.work-correlation-retry-pending',
14
+ WorkCorrelationUnresolvable: 'resources.work-correlation-unresolvable',
15
+ ExternalOutcomeObserved: 'resources.external-outcome-observed',
16
+ ExternalOutcomeReopened: 'resources.external-outcome-reopened',
17
+ ExternalOutcomeConsumed: 'resources.external-outcome-consumed',
13
18
  IssueCompletionObservationConsumed: 'resources.issue-completion-observation-consumed',
14
19
  IssueCompletionObservationSuperseded: 'resources.issue-completion-observation-superseded',
15
20
  };
@@ -35,6 +40,45 @@ const eventSchema = z.discriminatedUnion('eventType', [
35
40
  })
36
41
  .strict(),
37
42
  }),
43
+ eventEnvelopeSchema.extend({
44
+ eventType: z.literal(ResourceEventType.ExternalOutcomeObserved),
45
+ stream: streamSchema,
46
+ payload: z
47
+ .object({
48
+ sourceObservationId: z.string().min(1),
49
+ outcome: z.enum([ResourceExternalOutcome.Completed, ResourceExternalOutcome.Cancelled]),
50
+ revision: z.string().min(1),
51
+ })
52
+ .strict(),
53
+ }),
54
+ eventEnvelopeSchema.extend({
55
+ eventType: z.literal(ResourceEventType.ExternalOutcomeReopened),
56
+ stream: streamSchema,
57
+ payload: z.object({ revision: z.string().min(1) }).strict(),
58
+ }),
59
+ eventEnvelopeSchema.extend({
60
+ eventType: z.literal(ResourceEventType.ExternalOutcomeConsumed),
61
+ stream: streamSchema,
62
+ payload: z.object({ sourceObservationId: z.string().min(1) }).strict(),
63
+ }),
64
+ eventEnvelopeSchema.extend({
65
+ eventType: z.literal(ResourceEventType.WorkCorrelationRetryPending),
66
+ stream: streamSchema,
67
+ payload: z
68
+ .object({ attemptCount: z.number().int().min(1), lastFailureReason: z.string().min(1) })
69
+ .strict(),
70
+ }),
71
+ eventEnvelopeSchema.extend({
72
+ eventType: z.literal(ResourceEventType.WorkCorrelationUnresolvable),
73
+ stream: streamSchema,
74
+ payload: z
75
+ .object({
76
+ externalKey: z.object({ adapter: z.string(), key: z.string() }).strict(),
77
+ attemptCount: z.number().int().min(1),
78
+ lastFailureReason: z.string().min(1),
79
+ })
80
+ .strict(),
81
+ }),
38
82
  eventEnvelopeSchema.extend({
39
83
  eventType: z.literal(ResourceEventType.ResourceRevisionObserved),
40
84
  stream: streamSchema,
@@ -26,6 +26,10 @@ export const ResourceCorrelationProvenance = defineClosedVocabulary({
26
26
  AgentReported: 'agent-reported',
27
27
  OperatorDeclared: 'operator-declared',
28
28
  });
29
+ export const ResourceExternalOutcome = defineClosedVocabulary({
30
+ Completed: 'completed',
31
+ Cancelled: 'cancelled',
32
+ });
29
33
  class OpenResourceVocabularyRegistry {
30
34
  parse;
31
35
  label;
@@ -1,4 +1,5 @@
1
1
  import { ResourceEventType } from '../contracts/events.js';
2
+ import { ResourceCorrelationRole } from '../contracts/vocabulary.js';
2
3
  export function foldResource(events) {
3
4
  const discovered = events.find((event) => event.eventType === ResourceEventType.ResourceDiscovered);
4
5
  if (discovered === undefined)
@@ -7,7 +8,7 @@ export function foldResource(events) {
7
8
  const active = new Map();
8
9
  for (const event of events)
9
10
  applyResourceEvent(resource, active, event);
10
- return { view: resource, correlations: [...active.values()] };
11
+ return { view: resource, correlations: [...active.values()], events };
11
12
  }
12
13
  function discoveredResource(event) {
13
14
  const revision = event.payload.revision === undefined ? {} : { revision: event.payload.revision };
@@ -22,6 +23,14 @@ function discoveredResource(event) {
22
23
  };
23
24
  }
24
25
  function applyResourceEvent(resource, active, event) {
26
+ if (isExternalOutcome(event)) {
27
+ applyExternalOutcome(resource, event);
28
+ return;
29
+ }
30
+ if (isCorrelationRetry(event)) {
31
+ applyCorrelationRetry(resource, event);
32
+ return;
33
+ }
25
34
  switch (event.eventType) {
26
35
  case ResourceEventType.ResourceDiscovered:
27
36
  break;
@@ -29,6 +38,8 @@ function applyResourceEvent(resource, active, event) {
29
38
  Object.assign(resource, { revision: event.payload.revision });
30
39
  break;
31
40
  case ResourceEventType.WorkCorrelationEstablished:
41
+ if (event.payload.role === ResourceCorrelationRole.Primary)
42
+ delete resource.correlationStatus;
32
43
  active.set(event.payload.workItemId, {
33
44
  resourceId: resource.resourceId,
34
45
  workItemId: event.payload.workItemId,
@@ -56,6 +67,44 @@ function applyResourceEvent(resource, active, event) {
56
67
  assertNever(event);
57
68
  }
58
69
  }
70
+ function isCorrelationRetry(event) {
71
+ return (event.eventType === ResourceEventType.WorkCorrelationRetryPending ||
72
+ event.eventType === ResourceEventType.WorkCorrelationUnresolvable);
73
+ }
74
+ function isExternalOutcome(event) {
75
+ return (event.eventType === ResourceEventType.ExternalOutcomeObserved ||
76
+ event.eventType === ResourceEventType.ExternalOutcomeReopened ||
77
+ event.eventType === ResourceEventType.ExternalOutcomeConsumed);
78
+ }
79
+ function applyCorrelationRetry(resource, event) {
80
+ switch (event.eventType) {
81
+ case ResourceEventType.WorkCorrelationRetryPending:
82
+ return;
83
+ case ResourceEventType.WorkCorrelationUnresolvable:
84
+ Object.assign(resource, { correlationStatus: 'unresolvable' });
85
+ return;
86
+ default:
87
+ return assertNever(event);
88
+ }
89
+ }
90
+ function applyExternalOutcome(resource, event) {
91
+ switch (event.eventType) {
92
+ case ResourceEventType.ExternalOutcomeObserved:
93
+ Object.assign(resource, { pendingExternalOutcome: event.payload });
94
+ return;
95
+ case ResourceEventType.ExternalOutcomeReopened:
96
+ delete resource
97
+ .pendingExternalOutcome;
98
+ return;
99
+ case ResourceEventType.ExternalOutcomeConsumed:
100
+ if (resource.pendingExternalOutcome?.sourceObservationId === event.payload.sourceObservationId)
101
+ delete resource
102
+ .pendingExternalOutcome;
103
+ return;
104
+ default:
105
+ return assertNever(event);
106
+ }
107
+ }
59
108
  function assertNever(value) {
60
109
  throw new Error(`Unhandled Resource event: ${JSON.stringify(value)}`);
61
110
  }