@cratis/chronicle 6.61.0 → 6.63.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/ChronicleClient.ts +86 -3
- package/connection/ChronicleConnection.ts +7 -1
- package/connection/ChronicleServices.ts +2 -0
- package/connection/ConnectionLifecycle.ts +42 -1
- package/dist/ChronicleClient.d.ts +28 -1
- package/dist/ChronicleClient.d.ts.map +1 -1
- package/dist/ChronicleClient.js +71 -3
- package/dist/ChronicleClient.js.map +1 -1
- package/dist/connection/ChronicleConnection.d.ts +1 -0
- package/dist/connection/ChronicleConnection.d.ts.map +1 -1
- package/dist/connection/ChronicleConnection.js +6 -2
- package/dist/connection/ChronicleConnection.js.map +1 -1
- package/dist/connection/ChronicleServices.d.ts +2 -1
- package/dist/connection/ChronicleServices.d.ts.map +1 -1
- package/dist/connection/ConnectionLifecycle.d.ts +24 -0
- package/dist/connection/ConnectionLifecycle.d.ts.map +1 -1
- package/dist/connection/ConnectionLifecycle.js +40 -1
- package/dist/connection/ConnectionLifecycle.js.map +1 -1
- package/dist/eventSequences/EventForEventSourceId.d.ts +21 -1
- package/dist/eventSequences/EventForEventSourceId.d.ts.map +1 -1
- package/dist/eventSequences/EventSequence.d.ts +9 -0
- package/dist/eventSequences/EventSequence.d.ts.map +1 -1
- package/dist/eventSequences/EventSequence.js +18 -0
- package/dist/eventSequences/EventSequence.js.map +1 -1
- package/dist/eventSequences/IEventSequence.d.ts +30 -0
- package/dist/eventSequences/IEventSequence.d.ts.map +1 -1
- package/dist/imports/EventImport.d.ts +29 -0
- package/dist/imports/EventImport.d.ts.map +1 -0
- package/dist/imports/EventImport.js +248 -0
- package/dist/imports/EventImport.js.map +1 -0
- package/dist/imports/EventImportSettings.d.ts +32 -0
- package/dist/imports/EventImportSettings.d.ts.map +1 -0
- package/dist/imports/EventImportSettings.js +4 -0
- package/dist/imports/EventImportSettings.js.map +1 -0
- package/dist/imports/IEventImport.d.ts +50 -0
- package/dist/imports/IEventImport.d.ts.map +1 -0
- package/dist/imports/IEventImport.js +4 -0
- package/dist/imports/IEventImport.js.map +1 -0
- package/dist/imports/ImportChunkRefused.d.ts +12 -0
- package/dist/imports/ImportChunkRefused.d.ts.map +1 -0
- package/dist/imports/ImportChunkRefused.js +19 -0
- package/dist/imports/ImportChunkRefused.js.map +1 -0
- package/dist/imports/ImportCouldNotBegin.d.ts +10 -0
- package/dist/imports/ImportCouldNotBegin.d.ts.map +1 -0
- package/dist/imports/ImportCouldNotBegin.js +16 -0
- package/dist/imports/ImportCouldNotBegin.js.map +1 -0
- package/dist/imports/ImportOptions.d.ts +26 -0
- package/dist/imports/ImportOptions.d.ts.map +1 -0
- package/dist/imports/ImportOptions.js +4 -0
- package/dist/imports/ImportOptions.js.map +1 -0
- package/dist/imports/ImportProgress.d.ts +20 -0
- package/dist/imports/ImportProgress.d.ts.map +1 -0
- package/dist/imports/ImportProgress.js +4 -0
- package/dist/imports/ImportProgress.js.map +1 -0
- package/dist/imports/ImportRejection.d.ts +10 -0
- package/dist/imports/ImportRejection.d.ts.map +1 -0
- package/dist/imports/ImportRejection.js +4 -0
- package/dist/imports/ImportRejection.js.map +1 -0
- package/dist/imports/ImportResult.d.ts +30 -0
- package/dist/imports/ImportResult.d.ts.map +1 -0
- package/dist/imports/ImportResult.js +4 -0
- package/dist/imports/ImportResult.js.map +1 -0
- package/dist/imports/ImportState.d.ts +18 -0
- package/dist/imports/ImportState.d.ts.map +1 -0
- package/dist/imports/ImportState.js +21 -0
- package/dist/imports/ImportState.js.map +1 -0
- package/dist/imports/ImportTarget.d.ts +16 -0
- package/dist/imports/ImportTarget.d.ts.map +1 -0
- package/dist/imports/ImportTarget.js +4 -0
- package/dist/imports/ImportTarget.js.map +1 -0
- package/dist/imports/ImportWasAbandoned.d.ts +11 -0
- package/dist/imports/ImportWasAbandoned.d.ts.map +1 -0
- package/dist/imports/ImportWasAbandoned.js +16 -0
- package/dist/imports/ImportWasAbandoned.js.map +1 -0
- package/dist/imports/ImportsNotSupported.d.ts +5 -0
- package/dist/imports/ImportsNotSupported.d.ts.map +1 -0
- package/dist/imports/ImportsNotSupported.js +10 -0
- package/dist/imports/ImportsNotSupported.js.map +1 -0
- package/dist/imports/OnInvalidEvent.d.ts +8 -0
- package/dist/imports/OnInvalidEvent.d.ts.map +1 -0
- package/dist/imports/OnInvalidEvent.js +11 -0
- package/dist/imports/OnInvalidEvent.js.map +1 -0
- package/dist/imports/abortable.d.ts +23 -0
- package/dist/imports/abortable.d.ts.map +1 -0
- package/dist/imports/abortable.js +60 -0
- package/dist/imports/abortable.js.map +1 -0
- package/dist/imports/beginEventImport.d.ts +16 -0
- package/dist/imports/beginEventImport.d.ts.map +1 -0
- package/dist/imports/beginEventImport.js +74 -0
- package/dist/imports/beginEventImport.js.map +1 -0
- package/dist/imports/for_EventImport/given/a_kernel_import_session.d.ts +144 -0
- package/dist/imports/for_EventImport/given/a_kernel_import_session.d.ts.map +1 -0
- package/dist/imports/for_EventImport/given/a_kernel_import_session.js +132 -0
- package/dist/imports/for_EventImport/given/a_kernel_import_session.js.map +1 -0
- package/dist/imports/importEvents.d.ts +13 -0
- package/dist/imports/importEvents.d.ts.map +1 -0
- package/dist/imports/importEvents.js +35 -0
- package/dist/imports/importEvents.js.map +1 -0
- package/dist/imports/index.d.ts +12 -0
- package/dist/imports/index.d.ts.map +1 -0
- package/dist/imports/index.js +9 -0
- package/dist/imports/index.js.map +1 -0
- package/dist/imports/isTransientImportFailure.d.ts +7 -0
- package/dist/imports/isTransientImportFailure.d.ts.map +1 -0
- package/dist/imports/isTransientImportFailure.js +13 -0
- package/dist/imports/isTransientImportFailure.js.map +1 -0
- package/dist/imports/sizeOfImportEvent.d.ts +9 -0
- package/dist/imports/sizeOfImportEvent.d.ts.map +1 -0
- package/dist/imports/sizeOfImportEvent.js +25 -0
- package/dist/imports/sizeOfImportEvent.js.map +1 -0
- package/dist/imports/toImportEvent.d.ts +14 -0
- package/dist/imports/toImportEvent.d.ts.map +1 -0
- package/dist/imports/toImportEvent.js +54 -0
- package/dist/imports/toImportEvent.js.map +1 -0
- package/dist/imports/toImportProgress.d.ts +9 -0
- package/dist/imports/toImportProgress.d.ts.map +1 -0
- package/dist/imports/toImportProgress.js +20 -0
- package/dist/imports/toImportProgress.js.map +1 -0
- package/dist/imports/toImportResult.d.ts +9 -0
- package/dist/imports/toImportResult.d.ts.map +1 -0
- package/dist/imports/toImportResult.js +33 -0
- package/dist/imports/toImportResult.js.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/observation/ObservationReconnectBackoff.d.ts +64 -0
- package/dist/observation/ObservationReconnectBackoff.d.ts.map +1 -0
- package/dist/observation/ObservationReconnectBackoff.js +75 -0
- package/dist/observation/ObservationReconnectBackoff.js.map +1 -0
- package/dist/observation/ObservationStreamOutcome.d.ts +10 -0
- package/dist/observation/ObservationStreamOutcome.d.ts.map +1 -0
- package/dist/observation/ObservationStreamOutcome.js +4 -0
- package/dist/observation/ObservationStreamOutcome.js.map +1 -0
- package/dist/observation/classifyStreamError.d.ts +25 -0
- package/dist/observation/classifyStreamError.d.ts.map +1 -0
- package/dist/observation/classifyStreamError.js +55 -0
- package/dist/observation/classifyStreamError.js.map +1 -0
- package/dist/observation/for_ObservationReconnectBackoff/given/a_backoff.d.ts +13 -0
- package/dist/observation/for_ObservationReconnectBackoff/given/a_backoff.d.ts.map +1 -0
- package/dist/observation/for_ObservationReconnectBackoff/given/a_backoff.js +25 -0
- package/dist/observation/for_ObservationReconnectBackoff/given/a_backoff.js.map +1 -0
- package/dist/observation/for_ObservationReconnectBackoff/given/a_scripted_stream.d.ts +27 -0
- package/dist/observation/for_ObservationReconnectBackoff/given/a_scripted_stream.d.ts.map +1 -0
- package/dist/observation/for_ObservationReconnectBackoff/given/a_scripted_stream.js +36 -0
- package/dist/observation/for_ObservationReconnectBackoff/given/a_scripted_stream.js.map +1 -0
- package/dist/observation/index.d.ts +2 -0
- package/dist/observation/index.d.ts.map +1 -1
- package/dist/observation/index.js +1 -0
- package/dist/observation/index.js.map +1 -1
- package/dist/reactors/Reactors.d.ts +15 -5
- package/dist/reactors/Reactors.d.ts.map +1 -1
- package/dist/reactors/Reactors.js +95 -18
- package/dist/reactors/Reactors.js.map +1 -1
- package/dist/reactors/for_Reactors/when_reconnecting_the_observation_stream/given/a_reactor_whose_stream_ends.d.ts +26 -0
- package/dist/reactors/for_Reactors/when_reconnecting_the_observation_stream/given/a_reactor_whose_stream_ends.d.ts.map +1 -0
- package/dist/reactors/for_Reactors/when_reconnecting_the_observation_stream/given/a_reactor_whose_stream_ends.js +64 -0
- package/dist/reactors/for_Reactors/when_reconnecting_the_observation_stream/given/a_reactor_whose_stream_ends.js.map +1 -0
- package/dist/reducers/Reducers.d.ts +11 -5
- package/dist/reducers/Reducers.d.ts.map +1 -1
- package/dist/reducers/Reducers.js +93 -19
- package/dist/reducers/Reducers.js.map +1 -1
- package/dist/reducers/for_Reducers/when_reconnecting_the_observation_stream/given/a_reducer_whose_stream_ends.d.ts +25 -0
- package/dist/reducers/for_Reducers/when_reconnecting_the_observation_stream/given/a_reducer_whose_stream_ends.d.ts.map +1 -0
- package/dist/reducers/for_Reducers/when_reconnecting_the_observation_stream/given/a_reducer_whose_stream_ends.js +70 -0
- package/dist/reducers/for_Reducers/when_reconnecting_the_observation_stream/given/a_reducer_whose_stream_ends.js.map +1 -0
- package/dist/testing/BatchPartitionOutcome.d.ts +7 -0
- package/dist/testing/BatchPartitionOutcome.d.ts.map +1 -0
- package/dist/testing/BatchPartitionOutcome.js +4 -0
- package/dist/testing/BatchPartitionOutcome.js.map +1 -0
- package/dist/testing/InProcessEventSequence.d.ts +4 -0
- package/dist/testing/InProcessEventSequence.d.ts.map +1 -1
- package/dist/testing/InProcessEventSequence.js +2 -0
- package/dist/testing/InProcessEventSequence.js.map +1 -1
- package/dist/testing/ReactorDeliveryResult.d.ts +2 -0
- package/dist/testing/ReactorDeliveryResult.d.ts.map +1 -1
- package/dist/testing/ReactorScenario.d.ts +46 -10
- package/dist/testing/ReactorScenario.d.ts.map +1 -1
- package/dist/testing/ReactorScenario.js +120 -29
- package/dist/testing/ReactorScenario.js.map +1 -1
- package/dist/testing/deliverToBatchMethods.d.ts +35 -0
- package/dist/testing/deliverToBatchMethods.d.ts.map +1 -0
- package/dist/testing/deliverToBatchMethods.js +55 -0
- package/dist/testing/deliverToBatchMethods.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/eventSequences/EventForEventSourceId.ts +25 -1
- package/eventSequences/EventSequence.ts +28 -0
- package/eventSequences/IEventSequence.ts +33 -0
- package/for_ChronicleClient/when_reconnecting/and_an_observation_stream_lost_its_session.spec.ts +212 -0
- package/imports/EventImport.ts +263 -0
- package/imports/EventImportSettings.ts +46 -0
- package/imports/IEventImport.ts +58 -0
- package/imports/ImportChunkRefused.ts +15 -0
- package/imports/ImportCouldNotBegin.ts +14 -0
- package/imports/ImportOptions.ts +36 -0
- package/imports/ImportProgress.ts +29 -0
- package/imports/ImportRejection.ts +14 -0
- package/imports/ImportResult.ts +43 -0
- package/imports/ImportState.ts +26 -0
- package/imports/ImportTarget.ts +23 -0
- package/imports/ImportWasAbandoned.ts +16 -0
- package/imports/ImportsNotSupported.ts +10 -0
- package/imports/OnInvalidEvent.ts +11 -0
- package/imports/abortable.ts +57 -0
- package/imports/beginEventImport.ts +85 -0
- package/imports/for_EventImport/given/a_kernel_import_session.ts +160 -0
- package/imports/for_EventImport/when_a_chunk_fails.spec.ts +65 -0
- package/imports/for_EventImport/when_abandoning.spec.ts +52 -0
- package/imports/for_EventImport/when_cancelling_with_an_abort_signal.spec.ts +59 -0
- package/imports/for_EventImport/when_completing.spec.ts +71 -0
- package/imports/for_EventImport/when_cutting_events_into_chunks.spec.ts +70 -0
- package/imports/for_EventImport/when_keeping_chunks_in_flight.spec.ts +49 -0
- package/imports/for_beginEventImport/when_reattaching.spec.ts +82 -0
- package/imports/for_beginEventImport/when_the_kernel_does_not_serve_imports.spec.ts +55 -0
- package/imports/for_importEvents/when_importing_in_one_call.spec.ts +99 -0
- package/imports/for_toImportEvent/when_converting_an_event.spec.ts +74 -0
- package/imports/importEvents.ts +44 -0
- package/imports/index.ts +14 -0
- package/imports/isTransientImportFailure.ts +15 -0
- package/imports/sizeOfImportEvent.ts +25 -0
- package/imports/toImportEvent.ts +60 -0
- package/imports/toImportProgress.ts +24 -0
- package/imports/toImportResult.ts +36 -0
- package/index.ts +3 -0
- package/observation/ObservationReconnectBackoff.ts +109 -0
- package/observation/ObservationStreamOutcome.ts +12 -0
- package/observation/classifyStreamError.ts +67 -0
- package/observation/for_ObservationReconnectBackoff/given/a_backoff.ts +29 -0
- package/observation/for_ObservationReconnectBackoff/given/a_scripted_stream.ts +52 -0
- package/observation/for_ObservationReconnectBackoff/when_a_stream_delivered_before_it_ended.spec.ts +23 -0
- package/observation/for_ObservationReconnectBackoff/when_a_stream_stayed_open_before_it_ended.spec.ts +25 -0
- package/observation/for_ObservationReconnectBackoff/when_jittering_the_delay.spec.ts +24 -0
- package/observation/for_ObservationReconnectBackoff/when_streams_keep_ending_without_working.spec.ts +24 -0
- package/observation/for_ObservationReconnectBackoff/when_the_base_delay_is_not_positive.spec.ts +18 -0
- package/observation/for_ObservationReconnectBackoff/when_the_settings_are_not_finite.spec.ts +32 -0
- package/observation/for_ObservationReconnectBackoff/when_using_the_defaults.spec.ts +29 -0
- package/observation/for_classifyStreamError/when_classifying_a_stream_error.spec.ts +36 -0
- package/observation/index.ts +2 -0
- package/package.json +7 -2
- package/projections/for_childrenOrderingSupport/when_detecting_support_in_the_pinned_contracts.spec.ts +1 -1
- package/reactors/Reactors.ts +101 -18
- package/reactors/for_Reactors/when_reconnecting_the_observation_stream/and_a_handler_failed_with_a_lost_session.spec.ts +32 -0
- package/reactors/for_Reactors/when_reconnecting_the_observation_stream/and_a_replaced_stream_fails_late.spec.ts +28 -0
- package/reactors/for_Reactors/when_reconnecting_the_observation_stream/and_a_stream_delivered_before_it_ended.spec.ts +24 -0
- package/reactors/for_Reactors/when_reconnecting_the_observation_stream/and_a_stream_stayed_open_before_it_ended.spec.ts +23 -0
- package/reactors/for_Reactors/when_reconnecting_the_observation_stream/and_it_is_disposed_while_waiting_to_reopen.spec.ts +27 -0
- package/reactors/for_Reactors/when_reconnecting_the_observation_stream/and_streams_keep_ending_without_working.spec.ts +24 -0
- package/reactors/for_Reactors/when_reconnecting_the_observation_stream/and_the_client_reconnected_after_streams_kept_ending.spec.ts +24 -0
- package/reactors/for_Reactors/when_reconnecting_the_observation_stream/and_the_client_reconnected_while_waiting_to_reopen.spec.ts +25 -0
- package/reactors/for_Reactors/when_reconnecting_the_observation_stream/and_the_kernel_lost_the_session.spec.ts +24 -0
- package/reactors/for_Reactors/when_reconnecting_the_observation_stream/given/a_reactor_whose_stream_ends.ts +69 -0
- package/reducers/Reducers.ts +99 -19
- package/reducers/for_Reducers/when_reconnecting_the_observation_stream/and_a_reducer_failed_with_a_lost_session.spec.ts +33 -0
- package/reducers/for_Reducers/when_reconnecting_the_observation_stream/and_a_replaced_stream_fails_late.spec.ts +28 -0
- package/reducers/for_Reducers/when_reconnecting_the_observation_stream/and_a_stream_delivered_before_it_ended.spec.ts +24 -0
- package/reducers/for_Reducers/when_reconnecting_the_observation_stream/and_a_stream_stayed_open_before_it_ended.spec.ts +23 -0
- package/reducers/for_Reducers/when_reconnecting_the_observation_stream/and_it_is_disposed_while_waiting_to_reopen.spec.ts +27 -0
- package/reducers/for_Reducers/when_reconnecting_the_observation_stream/and_streams_keep_ending_without_working.spec.ts +24 -0
- package/reducers/for_Reducers/when_reconnecting_the_observation_stream/and_the_client_reconnected_after_streams_kept_ending.spec.ts +24 -0
- package/reducers/for_Reducers/when_reconnecting_the_observation_stream/and_the_client_reconnected_while_waiting_to_reopen.spec.ts +25 -0
- package/reducers/for_Reducers/when_reconnecting_the_observation_stream/and_the_kernel_lost_the_session.spec.ts +24 -0
- package/reducers/for_Reducers/when_reconnecting_the_observation_stream/given/a_reducer_whose_stream_ends.ts +69 -0
- package/testing/BatchPartitionOutcome.ts +10 -0
- package/testing/InProcessEventSequence.ts +4 -0
- package/testing/ReactorDeliveryResult.ts +2 -0
- package/testing/ReactorScenario.ts +147 -39
- package/testing/deliverToBatchMethods.ts +90 -0
- package/testing/for_ReactorScenario/when_the_reactor_has_a_batch_method.spec.ts +143 -9
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { Guid, JsonSerializer } from '@cratis/fundamentals';
|
|
5
|
+
import type { Identity as ContractsIdentity, ImportEvent } from '@cratis/chronicle.contracts';
|
|
6
|
+
import { resolveEventSubject } from '../compliance/resolveEventSubject.js';
|
|
7
|
+
import { toContractsGuid } from '../connection/Guid.js';
|
|
8
|
+
import { getEventTypeFor } from '../events/eventTypeDecorator.js';
|
|
9
|
+
import { mergeNamedTags } from '../events/mergeNamedTags.js';
|
|
10
|
+
import { mergeTags } from '../events/mergeTags.js';
|
|
11
|
+
import { getTagsFor } from '../events/tagDecorator.js';
|
|
12
|
+
import type { IEventSources } from '../eventSources/IEventSources.js';
|
|
13
|
+
import type { EventForEventSourceId } from '../eventSequences/EventForEventSourceId.js';
|
|
14
|
+
import { resolveBatchRouting } from '../eventSequences/resolveEventSourceRouting.js';
|
|
15
|
+
import type { Identity } from '../identity/Identity.js';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Converts an event to the form an import sends it in, keeping everything the event says about its source.
|
|
19
|
+
* @param event - The {@link EventForEventSourceId}.
|
|
20
|
+
* @param eventSources - The registered event sources, for events routed through a definition.
|
|
21
|
+
* @returns The {@link ImportEvent}.
|
|
22
|
+
* @remarks
|
|
23
|
+
* What the event does not say is left for the kernel to resolve: an omitted occurrence time, subject, route or
|
|
24
|
+
* correlation is not filled in from the importing process.
|
|
25
|
+
*/
|
|
26
|
+
export function toImportEvent(event: EventForEventSourceId, eventSources?: IEventSources): ImportEvent {
|
|
27
|
+
const routing = resolveBatchRouting(eventSources, event);
|
|
28
|
+
const eventType = getEventTypeFor(event.event.constructor as Function);
|
|
29
|
+
return {
|
|
30
|
+
EventSourceId: event.eventSourceId,
|
|
31
|
+
EventSourceType: routing?.sourceType ?? event.eventSourceType ?? '',
|
|
32
|
+
EventStreamType: routing?.streamType ?? event.eventStreamType ?? '',
|
|
33
|
+
EventStreamId: event.eventStreamId ?? '',
|
|
34
|
+
EventType: {
|
|
35
|
+
Id: eventType.id.value,
|
|
36
|
+
Generation: event.generation ?? eventType.generation.value,
|
|
37
|
+
Tombstone: eventType.tombstone
|
|
38
|
+
},
|
|
39
|
+
Content: JsonSerializer.serialize(event.event),
|
|
40
|
+
Tags: mergeTags(getTagsFor(event.event.constructor as Function), event.tags),
|
|
41
|
+
NamedTags: mergeNamedTags(event.namedTags).map(tag => ({ Name: tag.name, Value: tag.value })),
|
|
42
|
+
Occurred: event.occurred === undefined ? undefined : { Value: event.occurred.toISOString() },
|
|
43
|
+
Subject: event.subject ?? resolveEventSubject(event.event) ?? '',
|
|
44
|
+
CorrelationId: event.correlationId === undefined ? undefined : toContractsGuid(Guid.as(event.correlationId)),
|
|
45
|
+
Causation: [],
|
|
46
|
+
CausedBy: event.causedBy === undefined ? undefined : toContractsIdentity(event.causedBy),
|
|
47
|
+
IdempotencyKey: '',
|
|
48
|
+
EventSource: routing?.eventSource ?? '',
|
|
49
|
+
SourceSequenceNumber: event.sourceSequenceNumber === undefined ? 0n : BigInt(event.sourceSequenceNumber)
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function toContractsIdentity(identity: Identity): ContractsIdentity {
|
|
54
|
+
return {
|
|
55
|
+
Subject: identity.subject,
|
|
56
|
+
Name: identity.name,
|
|
57
|
+
UserName: identity.userName,
|
|
58
|
+
OnBehalfOf: identity.onBehalfOf === undefined ? undefined : toContractsIdentity(identity.onBehalfOf)
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import type { ImportProgressResponse } from '@cratis/chronicle.contracts';
|
|
5
|
+
import { fromContractsGuid } from '../connection/Guid.js';
|
|
6
|
+
import type { ImportProgress } from './ImportProgress.js';
|
|
7
|
+
import type { ImportState } from './ImportState.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Converts the progress the kernel reports to {@link ImportProgress}.
|
|
11
|
+
* @param progress - The {@link ImportProgressResponse}.
|
|
12
|
+
* @returns The {@link ImportProgress}.
|
|
13
|
+
*/
|
|
14
|
+
export function toImportProgress(progress: ImportProgressResponse): ImportProgress {
|
|
15
|
+
return {
|
|
16
|
+
importId: fromContractsGuid(progress.ImportId),
|
|
17
|
+
state: progress.State as number as ImportState,
|
|
18
|
+
eventsReceived: Number(progress.EventsReceived),
|
|
19
|
+
eventsStaged: Number(progress.EventsStaged),
|
|
20
|
+
eventsCommitted: Number(progress.EventsCommitted),
|
|
21
|
+
alreadyAppended: Number(progress.AlreadyAppended),
|
|
22
|
+
eventsRejected: Number(progress.RejectedCount)
|
|
23
|
+
};
|
|
24
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import type { ImportProgressResponse } from '@cratis/chronicle.contracts';
|
|
5
|
+
import { fromContractsGuid } from '../connection/Guid.js';
|
|
6
|
+
import { EventSequenceNumber } from '../eventSequences/EventSequenceNumber.js';
|
|
7
|
+
import type { ImportResult } from './ImportResult.js';
|
|
8
|
+
import { ImportState } from './ImportState.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Converts the progress the kernel reports to the {@link ImportResult} it amounts to.
|
|
12
|
+
* @param progress - The {@link ImportProgressResponse}.
|
|
13
|
+
* @returns The {@link ImportResult}.
|
|
14
|
+
*/
|
|
15
|
+
export function toImportResult(progress: ImportProgressResponse): ImportResult {
|
|
16
|
+
const state = progress.State as number as ImportState;
|
|
17
|
+
// Sequence numbers are only meaningful once the import committed something.
|
|
18
|
+
const committed = progress.EventsCommitted > 0n;
|
|
19
|
+
return {
|
|
20
|
+
importId: fromContractsGuid(progress.ImportId),
|
|
21
|
+
state,
|
|
22
|
+
eventsStaged: Number(progress.EventsStaged),
|
|
23
|
+
eventsCommitted: Number(progress.EventsCommitted),
|
|
24
|
+
alreadyAppended: Number(progress.AlreadyAppended),
|
|
25
|
+
firstSequenceNumber: committed ? new EventSequenceNumber(progress.FirstSequenceNumber) : undefined,
|
|
26
|
+
lastSequenceNumber: committed ? new EventSequenceNumber(progress.LastSequenceNumber) : undefined,
|
|
27
|
+
rejectedCount: Number(progress.RejectedCount),
|
|
28
|
+
rejections: (progress.Rejections ?? []).map(rejection => ({
|
|
29
|
+
index: Number(rejection.Index),
|
|
30
|
+
eventType: rejection.EventType,
|
|
31
|
+
reasons: [...rejection.Reasons]
|
|
32
|
+
})),
|
|
33
|
+
failureReason: progress.FailureReason ? progress.FailureReason : undefined,
|
|
34
|
+
isSuccess: state === ImportState.Completed
|
|
35
|
+
};
|
|
36
|
+
}
|
package/index.ts
CHANGED
|
@@ -26,6 +26,7 @@ import * as transactions from './transactions/index.js';
|
|
|
26
26
|
import * as eventStoreSubscriptions from './eventStoreSubscriptions/index.js';
|
|
27
27
|
import * as compliance from './compliance/index.js';
|
|
28
28
|
import * as confidentiality from './confidentiality/index.js';
|
|
29
|
+
import * as imports from './imports/index.js';
|
|
29
30
|
|
|
30
31
|
export { ChronicleClient } from './ChronicleClient.js';
|
|
31
32
|
export { IncompatibleChronicleServer } from './connection/IncompatibleChronicleServer.js';
|
|
@@ -73,6 +74,7 @@ export * from './transactions/index.js';
|
|
|
73
74
|
export * from './eventStoreSubscriptions/index.js';
|
|
74
75
|
export * from './compliance/index.js';
|
|
75
76
|
export * from './confidentiality/index.js';
|
|
77
|
+
export * from './imports/index.js';
|
|
76
78
|
|
|
77
79
|
export {
|
|
78
80
|
events,
|
|
@@ -100,4 +102,5 @@ export {
|
|
|
100
102
|
eventStoreSubscriptions,
|
|
101
103
|
compliance,
|
|
102
104
|
confidentiality,
|
|
105
|
+
imports,
|
|
103
106
|
};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Settings for how a reactor or reducer waits before opening its observation stream again.
|
|
6
|
+
* Every setting is optional; the defaults match the .NET client.
|
|
7
|
+
*/
|
|
8
|
+
export interface ObservationReconnectBackoffOptions {
|
|
9
|
+
/** The wait in milliseconds after a stream that had worked. Defaults to 2 seconds. */
|
|
10
|
+
baseDelayMs?: number;
|
|
11
|
+
|
|
12
|
+
/** The longest wait in milliseconds, however often streams end. Defaults to 60 seconds. */
|
|
13
|
+
maxDelayMs?: number;
|
|
14
|
+
|
|
15
|
+
/** How long in milliseconds a stream must stay open to count as having worked. Defaults to 3 minutes. */
|
|
16
|
+
healthyStreamDurationMs?: number;
|
|
17
|
+
|
|
18
|
+
/** Returns the current time in milliseconds, measuring how long a stream stayed open. Defaults to `performance.now`. */
|
|
19
|
+
now?: () => number;
|
|
20
|
+
|
|
21
|
+
/** Returns a value in [0, 1) choosing where in the upper half of the wait this one lands. Defaults to `Math.random`. */
|
|
22
|
+
nextJitter?: () => number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const finiteOr = (value: number | undefined, fallback: number, isAllowed: (value: number) => boolean): number =>
|
|
26
|
+
value !== undefined && Number.isFinite(value) && isAllowed(value) ? value : fallback;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Decides how long one reactor or reducer waits before opening its observation stream again after it ended.
|
|
30
|
+
*
|
|
31
|
+
* A fixed delay is right for one observer and wrong for many: seventy reactors whose streams fail together
|
|
32
|
+
* come back together, every two seconds, against a kernel that is still busy. So each stream that ends without
|
|
33
|
+
* having worked doubles the wait, up to a ceiling, and every wait lands at random in its upper half so a herd
|
|
34
|
+
* spreads out.
|
|
35
|
+
*
|
|
36
|
+
* The wait starts over once a stream has worked: it delivered something, or it stayed open long enough to have
|
|
37
|
+
* been established. A base delay of zero or less is used as it is.
|
|
38
|
+
*/
|
|
39
|
+
export class ObservationReconnectBackoff {
|
|
40
|
+
/** The default wait after a stream that had worked. */
|
|
41
|
+
static readonly defaultBaseDelayMs = 2_000;
|
|
42
|
+
|
|
43
|
+
/** The default longest wait between attempts. */
|
|
44
|
+
static readonly defaultMaxDelayMs = 60_000;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The default time a stream must stay open to count as having worked.
|
|
48
|
+
*
|
|
49
|
+
* It is longer than the kernel takes to give up establishing a stream: the kernel asks a busy observer again
|
|
50
|
+
* on the same stream, up to four attempts of a thirty-second grain call each, before it fails the stream. A
|
|
51
|
+
* shorter threshold would count every such stream as having worked and start the wait over at the base delay.
|
|
52
|
+
*/
|
|
53
|
+
static readonly defaultHealthyStreamDurationMs = 180_000;
|
|
54
|
+
|
|
55
|
+
private static readonly _maxExponent = 30;
|
|
56
|
+
|
|
57
|
+
private readonly _baseDelayMs: number;
|
|
58
|
+
private readonly _maxDelayMs: number;
|
|
59
|
+
private readonly _healthyStreamDurationMs: number;
|
|
60
|
+
private readonly _now: () => number;
|
|
61
|
+
private readonly _nextJitter: () => number;
|
|
62
|
+
private _streamsEndedWithoutWorking = 0;
|
|
63
|
+
private _streamOpenedAt: number;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Creates a new {@link ObservationReconnectBackoff}.
|
|
67
|
+
* @param options - The settings; anything left out uses its default.
|
|
68
|
+
*/
|
|
69
|
+
constructor(options: ObservationReconnectBackoffOptions = {}) {
|
|
70
|
+
// A wait that is not a finite number would reach setTimeout as about one millisecond: a hot loop.
|
|
71
|
+
this._baseDelayMs = finiteOr(options.baseDelayMs, ObservationReconnectBackoff.defaultBaseDelayMs, () => true);
|
|
72
|
+
this._maxDelayMs = finiteOr(options.maxDelayMs, ObservationReconnectBackoff.defaultMaxDelayMs, value => value > 0);
|
|
73
|
+
this._healthyStreamDurationMs = finiteOr(options.healthyStreamDurationMs,
|
|
74
|
+
ObservationReconnectBackoff.defaultHealthyStreamDurationMs, value => value >= 0);
|
|
75
|
+
this._now = options.now ?? (() => performance.now());
|
|
76
|
+
this._nextJitter = options.nextJitter ?? Math.random;
|
|
77
|
+
this._streamOpenedAt = this._now();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Records that a new observation stream was opened. */
|
|
81
|
+
streamOpened(): void {
|
|
82
|
+
this._streamOpenedAt = this._now();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Records that the open stream delivered something, which proves it was established. */
|
|
86
|
+
streamDelivered(): void {
|
|
87
|
+
this._streamsEndedWithoutWorking = 0;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Gets how long to wait before opening the stream again, now that the open one has ended.
|
|
92
|
+
* @returns The wait in milliseconds.
|
|
93
|
+
*/
|
|
94
|
+
nextDelayMs(): number {
|
|
95
|
+
if (this._baseDelayMs <= 0) {
|
|
96
|
+
return this._baseDelayMs;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (this._now() - this._streamOpenedAt >= this._healthyStreamDurationMs) {
|
|
100
|
+
this._streamsEndedWithoutWorking = 0;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const exponent = Math.min(this._streamsEndedWithoutWorking, ObservationReconnectBackoff._maxExponent);
|
|
104
|
+
this._streamsEndedWithoutWorking++;
|
|
105
|
+
const ceiling = Math.min(this._maxDelayMs, this._baseDelayMs * Math.pow(2, exponent));
|
|
106
|
+
const jitter = 0.5 + 0.5 * Math.min(Math.max(this._nextJitter(), 0), 1);
|
|
107
|
+
return Math.floor(ceiling * jitter);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* How one reactor or reducer observation stream ended, which decides what happens next.
|
|
6
|
+
*
|
|
7
|
+
* - `ended`: the stream ended or failed while it was still the current one; open it again after a backoff.
|
|
8
|
+
* - `sessionLost`: the kernel no longer knows the connection; the whole client reconnects and re-registers it.
|
|
9
|
+
* - `superseded`: a disconnect, a dispose or a newer stream replaced it; nothing to do.
|
|
10
|
+
* - `stopped`: the client cancelled it on purpose; nothing to do.
|
|
11
|
+
*/
|
|
12
|
+
export type ObservationStreamOutcome = 'ended' | 'sessionLost' | 'superseded' | 'stopped';
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
/** What ended a kernel observation stream, deciding how the client recovers. */
|
|
5
|
+
export enum StreamErrorKind {
|
|
6
|
+
/** The stream failed for a reason of its own; it is opened again after a backoff. */
|
|
7
|
+
Failure = 'Failure',
|
|
8
|
+
|
|
9
|
+
/** The client cancelled the stream itself; it is not opened again. */
|
|
10
|
+
Cancelled = 'Cancelled',
|
|
11
|
+
|
|
12
|
+
/** The kernel is stopping or unreachable; the stream is opened again after a backoff. */
|
|
13
|
+
ConnectionLost = 'ConnectionLost',
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The kernel no longer knows this client's connection, for instance after it restarted. Opening the stream again
|
|
17
|
+
* with the same connection id can never work, so the whole client reconnects with a new one.
|
|
18
|
+
*/
|
|
19
|
+
SessionLost = 'SessionLost'
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const CANCELLED = 1;
|
|
23
|
+
const UNAVAILABLE = 14;
|
|
24
|
+
const CLIENT_IS_NOT_CONNECTED = 'ClientIsNotConnected';
|
|
25
|
+
|
|
26
|
+
interface GrpcLikeError {
|
|
27
|
+
code?: unknown;
|
|
28
|
+
details?: unknown;
|
|
29
|
+
message?: unknown;
|
|
30
|
+
name?: unknown;
|
|
31
|
+
cause?: unknown;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const mentionsClientIsNotConnected = (error: GrpcLikeError): boolean =>
|
|
35
|
+
[error.details, error.message].some(text => typeof text === 'string' && text.includes(CLIENT_IS_NOT_CONNECTED));
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Classifies an error that ended a kernel observation stream, looking through wrapping errors.
|
|
39
|
+
*
|
|
40
|
+
* An {@link AggregateError} takes the most serious kind among the errors it wraps, in this order:
|
|
41
|
+
* {@link StreamErrorKind.Failure}, then {@link StreamErrorKind.SessionLost}, then {@link StreamErrorKind.ConnectionLost},
|
|
42
|
+
* then {@link StreamErrorKind.Cancelled}. This matches the .NET client.
|
|
43
|
+
* @param error - The error the stream ended with.
|
|
44
|
+
* @returns The {@link StreamErrorKind} for the error.
|
|
45
|
+
*/
|
|
46
|
+
export function classifyStreamError(error: unknown): StreamErrorKind {
|
|
47
|
+
if (error === null || typeof error !== 'object') {
|
|
48
|
+
return StreamErrorKind.Failure;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (error instanceof AggregateError && error.errors.length > 0) {
|
|
52
|
+
const kinds = error.errors.map(classifyStreamError);
|
|
53
|
+
if (kinds.includes(StreamErrorKind.Failure)) return StreamErrorKind.Failure;
|
|
54
|
+
if (kinds.includes(StreamErrorKind.SessionLost)) return StreamErrorKind.SessionLost;
|
|
55
|
+
return kinds.includes(StreamErrorKind.ConnectionLost) ? StreamErrorKind.ConnectionLost : StreamErrorKind.Cancelled;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const grpcError = error as GrpcLikeError;
|
|
59
|
+
if (grpcError.name === 'AbortError') return StreamErrorKind.Cancelled;
|
|
60
|
+
if (typeof grpcError.code === 'number') {
|
|
61
|
+
if (grpcError.code === CANCELLED) return StreamErrorKind.Cancelled;
|
|
62
|
+
if (grpcError.code === UNAVAILABLE) return StreamErrorKind.ConnectionLost;
|
|
63
|
+
return mentionsClientIsNotConnected(grpcError) ? StreamErrorKind.SessionLost : StreamErrorKind.Failure;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return grpcError.cause !== undefined ? classifyStreamError(grpcError.cause) : StreamErrorKind.Failure;
|
|
67
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { ObservationReconnectBackoff } from '../../ObservationReconnectBackoff.js';
|
|
5
|
+
|
|
6
|
+
/** A backoff with a 2 second base, a 60 second ceiling and a 3 minute healthy threshold, on a clock and jitter the spec controls. */
|
|
7
|
+
export class a_backoff {
|
|
8
|
+
static readonly baseDelayMs = 2_000;
|
|
9
|
+
static readonly maxDelayMs = 60_000;
|
|
10
|
+
static readonly healthyStreamDurationMs = 180_000;
|
|
11
|
+
|
|
12
|
+
now = 0;
|
|
13
|
+
jitter = 0;
|
|
14
|
+
|
|
15
|
+
readonly backoff = new ObservationReconnectBackoff({
|
|
16
|
+
baseDelayMs: a_backoff.baseDelayMs,
|
|
17
|
+
maxDelayMs: a_backoff.maxDelayMs,
|
|
18
|
+
healthyStreamDurationMs: a_backoff.healthyStreamDurationMs,
|
|
19
|
+
now: () => this.now,
|
|
20
|
+
nextJitter: () => this.jitter
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
/** Opens a stream, lets it stay open for a while and ends it, returning the wait before the next one. */
|
|
24
|
+
streamEndsAfter(openForMs: number): number {
|
|
25
|
+
this.backoff.streamOpened();
|
|
26
|
+
this.now += openForMs;
|
|
27
|
+
return this.backoff.nextDelayMs();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
/** How one observation stream behaves: what it delivers, how long it stays open and the error it ends with, if any. */
|
|
5
|
+
export interface StreamScript<T> {
|
|
6
|
+
/** What the stream delivers before it ends. */
|
|
7
|
+
deliver?: T[];
|
|
8
|
+
|
|
9
|
+
/** How long, in milliseconds, the stream stays open after delivering before it ends. */
|
|
10
|
+
openForMs?: number;
|
|
11
|
+
|
|
12
|
+
/** Whether the stream stays open until the client aborts it. */
|
|
13
|
+
untilAborted?: boolean;
|
|
14
|
+
|
|
15
|
+
/** How long, in milliseconds, an aborted stream takes to end, as a slow transport would. */
|
|
16
|
+
endsLateByMs?: number;
|
|
17
|
+
|
|
18
|
+
/** The error the stream ends with. */
|
|
19
|
+
error?: unknown;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Records the observation streams a reactor or reducer opens and plays them by their scripts. */
|
|
23
|
+
export class a_scripted_stream<T> {
|
|
24
|
+
readonly openedAt: number[] = [];
|
|
25
|
+
readonly scripts: StreamScript<T>[] = [];
|
|
26
|
+
open = 0;
|
|
27
|
+
|
|
28
|
+
/** The observe method of the fake kernel connection. */
|
|
29
|
+
readonly observe = (_messages: unknown, options: { signal: AbortSignal }): AsyncGenerator<T> => this.play(options.signal);
|
|
30
|
+
|
|
31
|
+
/** Gets the wait before each stream after the first was opened. */
|
|
32
|
+
get waits(): number[] {
|
|
33
|
+
return this.openedAt.slice(1).map((at, index) => at - this.openedAt[index]);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
private async *play(signal: AbortSignal): AsyncGenerator<T> {
|
|
37
|
+
this.openedAt.push(Date.now());
|
|
38
|
+
this.open++;
|
|
39
|
+
try {
|
|
40
|
+
const script = this.scripts.shift() ?? {};
|
|
41
|
+
for (const delivery of script.deliver ?? []) yield delivery;
|
|
42
|
+
if (script.openForMs) await new Promise(resolve => setTimeout(resolve, script.openForMs));
|
|
43
|
+
if (script.untilAborted) {
|
|
44
|
+
await new Promise<void>(resolve => signal.aborted ? resolve() : signal.addEventListener('abort', () => resolve(), { once: true }));
|
|
45
|
+
if (script.endsLateByMs) await new Promise(resolve => setTimeout(resolve, script.endsLateByMs));
|
|
46
|
+
}
|
|
47
|
+
if (script.error) throw script.error;
|
|
48
|
+
} finally {
|
|
49
|
+
this.open--;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
package/observation/for_ObservationReconnectBackoff/when_a_stream_delivered_before_it_ended.spec.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { beforeEach, chai, describe, it } from 'vitest';
|
|
5
|
+
import { a_backoff } from './given/a_backoff.js';
|
|
6
|
+
|
|
7
|
+
chai.should();
|
|
8
|
+
|
|
9
|
+
describe('when a stream delivered before it ended', () => {
|
|
10
|
+
let context: a_backoff;
|
|
11
|
+
let delay: number;
|
|
12
|
+
|
|
13
|
+
beforeEach(() => {
|
|
14
|
+
context = new a_backoff();
|
|
15
|
+
for (let attempt = 0; attempt < 4; attempt++) context.streamEndsAfter(1_000);
|
|
16
|
+
context.backoff.streamOpened();
|
|
17
|
+
context.backoff.streamDelivered();
|
|
18
|
+
context.now += 1_000;
|
|
19
|
+
delay = context.backoff.nextDelayMs();
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it('should start the wait over at the base delay', () => delay.should.equal(a_backoff.baseDelayMs / 2));
|
|
23
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { beforeEach, chai, describe, it } from 'vitest';
|
|
5
|
+
import { a_backoff } from './given/a_backoff.js';
|
|
6
|
+
|
|
7
|
+
chai.should();
|
|
8
|
+
|
|
9
|
+
describe('when a stream stayed open before it ended', () => {
|
|
10
|
+
let longEnough: number;
|
|
11
|
+
let tooShort: number;
|
|
12
|
+
|
|
13
|
+
beforeEach(() => {
|
|
14
|
+
const healthy = new a_backoff();
|
|
15
|
+
for (let attempt = 0; attempt < 3; attempt++) healthy.streamEndsAfter(1_000);
|
|
16
|
+
longEnough = healthy.streamEndsAfter(a_backoff.healthyStreamDurationMs);
|
|
17
|
+
|
|
18
|
+
const unhealthy = new a_backoff();
|
|
19
|
+
for (let attempt = 0; attempt < 3; attempt++) unhealthy.streamEndsAfter(1_000);
|
|
20
|
+
tooShort = unhealthy.streamEndsAfter(a_backoff.healthyStreamDurationMs - 1);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('should start the wait over at the base delay once it stayed open long enough', () => longEnough.should.equal(a_backoff.baseDelayMs / 2));
|
|
24
|
+
it('should keep backing off when it closed just before counting as having worked', () => tooShort.should.equal(8_000));
|
|
25
|
+
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { beforeEach, chai, describe, it } from 'vitest';
|
|
5
|
+
import { a_backoff } from './given/a_backoff.js';
|
|
6
|
+
|
|
7
|
+
chai.should();
|
|
8
|
+
|
|
9
|
+
describe('when jittering the delay', () => {
|
|
10
|
+
let delays: number[];
|
|
11
|
+
|
|
12
|
+
beforeEach(() => {
|
|
13
|
+
delays = [0, 0.5, -1, 2].map(jitter => {
|
|
14
|
+
const context = new a_backoff();
|
|
15
|
+
context.jitter = jitter;
|
|
16
|
+
return context.streamEndsAfter(0);
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it('should land at half the wait for the lowest jitter', () => delays[0].should.equal(1_000));
|
|
21
|
+
it('should land in the upper half of the wait', () => delays[1].should.equal(1_500));
|
|
22
|
+
it('should clamp a jitter below zero to the lower bound', () => delays[2].should.equal(1_000));
|
|
23
|
+
it('should clamp a jitter above one to the full wait', () => delays[3].should.equal(2_000));
|
|
24
|
+
});
|
package/observation/for_ObservationReconnectBackoff/when_streams_keep_ending_without_working.spec.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { beforeEach, chai, describe, it } from 'vitest';
|
|
5
|
+
import { a_backoff } from './given/a_backoff.js';
|
|
6
|
+
|
|
7
|
+
chai.should();
|
|
8
|
+
|
|
9
|
+
describe('when streams keep ending without working', () => {
|
|
10
|
+
let context: a_backoff;
|
|
11
|
+
let delays: number[];
|
|
12
|
+
|
|
13
|
+
beforeEach(() => {
|
|
14
|
+
context = new a_backoff();
|
|
15
|
+
context.jitter = 0.999999;
|
|
16
|
+
delays = Array.from({ length: 8 }, () => context.streamEndsAfter(1_000));
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('should double the wait each time, starting from the base delay', () =>
|
|
20
|
+
delays.slice(0, 5).map(delay => Math.round(delay / 1_000)).should.deep.equal([2, 4, 8, 16, 32]));
|
|
21
|
+
|
|
22
|
+
it('should never wait longer than the ceiling', () => delays.forEach(delay => delay.should.be.at.most(a_backoff.maxDelayMs)));
|
|
23
|
+
it('should keep waiting close to the ceiling once it is reached', () => delays.slice(5).forEach(delay => delay.should.be.at.least(59_999)));
|
|
24
|
+
});
|
package/observation/for_ObservationReconnectBackoff/when_the_base_delay_is_not_positive.spec.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { beforeEach, chai, describe, it } from 'vitest';
|
|
5
|
+
import { ObservationReconnectBackoff } from '../ObservationReconnectBackoff.js';
|
|
6
|
+
|
|
7
|
+
chai.should();
|
|
8
|
+
|
|
9
|
+
describe('when the base delay is not positive', () => {
|
|
10
|
+
let delays: number[];
|
|
11
|
+
|
|
12
|
+
beforeEach(() => {
|
|
13
|
+
const backoff = new ObservationReconnectBackoff({ baseDelayMs: 0, nextJitter: () => 0.5 });
|
|
14
|
+
delays = [backoff.nextDelayMs(), backoff.nextDelayMs(), backoff.nextDelayMs()];
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it('should use the base delay as it is, without backing off', () => delays.should.deep.equal([0, 0, 0]));
|
|
18
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { beforeEach, chai, describe, it } from 'vitest';
|
|
5
|
+
import { ObservationReconnectBackoff } from '../ObservationReconnectBackoff.js';
|
|
6
|
+
|
|
7
|
+
chai.should();
|
|
8
|
+
|
|
9
|
+
describe('when the settings are not finite', () => {
|
|
10
|
+
let delays: number[];
|
|
11
|
+
|
|
12
|
+
beforeEach(() => {
|
|
13
|
+
let now = 0;
|
|
14
|
+
const backoff = new ObservationReconnectBackoff({
|
|
15
|
+
baseDelayMs: Number.NaN,
|
|
16
|
+
maxDelayMs: -1,
|
|
17
|
+
healthyStreamDurationMs: Number.POSITIVE_INFINITY,
|
|
18
|
+
now: () => now,
|
|
19
|
+
nextJitter: () => 1
|
|
20
|
+
});
|
|
21
|
+
delays = [];
|
|
22
|
+
for (let attempt = 0; attempt < 7; attempt++) {
|
|
23
|
+
backoff.streamOpened();
|
|
24
|
+
delays.push(backoff.nextDelayMs());
|
|
25
|
+
}
|
|
26
|
+
now = ObservationReconnectBackoff.defaultHealthyStreamDurationMs;
|
|
27
|
+
delays.push(backoff.nextDelayMs());
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('should fall back to the default delays', () =>
|
|
31
|
+
delays.should.deep.equal([2_000, 4_000, 8_000, 16_000, 32_000, 60_000, 60_000, 2_000]));
|
|
32
|
+
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { beforeEach, chai, describe, it } from 'vitest';
|
|
5
|
+
import { ObservationReconnectBackoff } from '../ObservationReconnectBackoff.js';
|
|
6
|
+
|
|
7
|
+
chai.should();
|
|
8
|
+
|
|
9
|
+
describe('when using the defaults', () => {
|
|
10
|
+
let delays: number[];
|
|
11
|
+
|
|
12
|
+
beforeEach(() => {
|
|
13
|
+
let now = 0;
|
|
14
|
+
const backoff = new ObservationReconnectBackoff({ now: () => now, nextJitter: () => 0.999999 });
|
|
15
|
+
delays = Array.from({ length: 7 }, () => {
|
|
16
|
+
backoff.streamOpened();
|
|
17
|
+
now += 1_000;
|
|
18
|
+
return backoff.nextDelayMs();
|
|
19
|
+
});
|
|
20
|
+
backoff.streamOpened();
|
|
21
|
+
now += ObservationReconnectBackoff.defaultHealthyStreamDurationMs;
|
|
22
|
+
delays.push(backoff.nextDelayMs());
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('should start at two seconds', () => Math.round(delays[0] / 1_000).should.equal(2));
|
|
26
|
+
it('should never wait longer than a minute', () => delays.forEach(delay => delay.should.be.at.most(60_000)));
|
|
27
|
+
it('should reach a minute while streams keep ending', () => Math.round(delays[6] / 1_000).should.equal(60));
|
|
28
|
+
it('should start over after a stream stayed open for three minutes', () => Math.round(delays[7] / 1_000).should.equal(2));
|
|
29
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { ClientError, Status } from 'nice-grpc';
|
|
5
|
+
import { chai, describe, it } from 'vitest';
|
|
6
|
+
import { classifyStreamError, StreamErrorKind } from '../classifyStreamError.js';
|
|
7
|
+
|
|
8
|
+
chai.should();
|
|
9
|
+
|
|
10
|
+
const sessionLost = () => new ClientError('/Reactors/Observe', Status.UNKNOWN, 'ClientIsNotConnected: connection 42 is not connected');
|
|
11
|
+
const abort = () => Object.assign(new Error('The operation has been aborted'), { name: 'AbortError' });
|
|
12
|
+
|
|
13
|
+
describe('when classifying a stream error', () => {
|
|
14
|
+
const cases: [string, unknown, StreamErrorKind][] = [
|
|
15
|
+
['the kernel no longer knows the connection', sessionLost(), StreamErrorKind.SessionLost],
|
|
16
|
+
['the message names the lost connection', Object.assign(new Error('ClientIsNotConnected'), { code: Status.INTERNAL }), StreamErrorKind.SessionLost],
|
|
17
|
+
['the lost connection is wrapped', new Error('stream failed', { cause: sessionLost() }), StreamErrorKind.SessionLost],
|
|
18
|
+
['every wrapped error lost the session or connection',
|
|
19
|
+
new AggregateError([sessionLost(), new ClientError('/x', Status.UNAVAILABLE, '')]), StreamErrorKind.SessionLost],
|
|
20
|
+
['a wrapped error is a failure of its own',
|
|
21
|
+
new AggregateError([sessionLost(), new ClientError('/x', Status.INTERNAL, 'boom')]), StreamErrorKind.Failure],
|
|
22
|
+
['a wrapped error lost the connection and another was cancelled',
|
|
23
|
+
new AggregateError([new ClientError('/x', Status.CANCELLED, ''), new ClientError('/x', Status.UNAVAILABLE, '')]),
|
|
24
|
+
StreamErrorKind.ConnectionLost],
|
|
25
|
+
['every wrapped error was cancelled', new AggregateError([abort(), new ClientError('/x', Status.CANCELLED, '')]), StreamErrorKind.Cancelled],
|
|
26
|
+
['the kernel is unreachable', new ClientError('/x', Status.UNAVAILABLE, 'ClientIsNotConnected'), StreamErrorKind.ConnectionLost],
|
|
27
|
+
['the call was cancelled', new ClientError('/x', Status.CANCELLED, ''), StreamErrorKind.Cancelled],
|
|
28
|
+
['the client aborted the stream', abort(), StreamErrorKind.Cancelled],
|
|
29
|
+
['the stream failed for another reason', new ClientError('/x', Status.INTERNAL, 'boom'), StreamErrorKind.Failure],
|
|
30
|
+
['the error is not an object', 'boom', StreamErrorKind.Failure]
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
for (const [scenario, error, kind] of cases) {
|
|
34
|
+
it(`should classify as ${kind} when ${scenario}`, () => classifyStreamError(error).should.equal(kind));
|
|
35
|
+
}
|
|
36
|
+
});
|
package/observation/index.ts
CHANGED
|
@@ -25,6 +25,8 @@ export { observes } from './batches/observes.js';
|
|
|
25
25
|
export { batchSize } from './batches/batchSize.js';
|
|
26
26
|
export type { BatchSizeOptions } from './batches/batchSize.js';
|
|
27
27
|
export { EventBatch } from './batches/EventBatch.js';
|
|
28
|
+
export type { BatchOutcome } from './batches/BatchOutcome.js';
|
|
29
|
+
export { BatchOutcomeKind } from './batches/BatchOutcomeKind.js';
|
|
28
30
|
export { EventAndContext } from './batches/EventAndContext.js';
|
|
29
31
|
export { BatchContext } from './batches/BatchContext.js';
|
|
30
32
|
export { ObservationOrigin } from './batches/ObservationOrigin.js';
|