Change Log 0.9.0

Version 0.9.0 is a breaking release that changes three fundamental areas of the library:

  1. Event Bus State Propagation. The Digital Twin State does not travel anymore as a single, complete DigitalTwinState on the event bus. It is split into a description (the structure of the state, with a unique id) and values (a delta with only the values that changed), published on two separate topics. Every component that observes the state keeps its own, always up to date, local copy. This drastically reduces what circulates inside the Digital Twin. All the Digital Twins written for previous versions must be migrated (see Migration from 0.8.1).
  2. A new declarative Query System. The request-type based QueryRequest is replaced by an immutable Query object (resource, filter, sorting, paging, aggregation, timeout) that is translated by the storage into its own native language, so only the needed records are returned. The state is stored and queried as description + values.
  3. State Filters. Digital Adapters and Augmentation Functions can choose when they are notified of a values update (trigger filter) and which part of the values they receive (content filter). The description is never filtered. The Storage Manager does not filter: it always saves the description and the complete values.

⚠️ Breaking changes at a glance. Almost every component that touches the Digital Twin State must be updated:

  • Compile errors (code that does not compile anymore): Shadowing Functions (DigitalTwinModel), Digital Adapters, Augmentation Functions and custom AugmentationFunctionHandler, custom WldtStorage / QueryManager, LifeCycleListener implementations, event bus subscribers of the state events, code that uses QueryRequest.
  • Silent behaviour changes (the code still compiles but behaves differently, see Behaviour changes without compile errors): the last invocation of an action is not recorded automatically anymore, STARTED is notified before the adapters run, observeState / observeEventNotifications are now honoured, stored states and their counts have a different meaning, storage metrics changed.

The table Breaking changes lists every change with its impact, and Migration from 0.8.1 gives the steps to follow.

Key updates:

  • Two state topics — dt.state.description.update (the complete new description, published only if the structure really changed) and dt.state.values.update (only the changed values). dt.state.update and the complete state on the bus do not exist anymore
  • DigitalTwinStateDescription has a unique id <creationTimestamp>_<numSeq> and DigitalTwinStateValues always carries the id of the description it belongs to
  • DigitalTwinStateManager never returns the complete state — getDigitalTwinStateDescription() and getDigitalTwinStateValues() replace getDigitalTwinState()
  • Last invocation of actions / last notification of events are values of the state, written inside state transactions (notifyActionExecuted, notifyDigitalTwinStateEvent)
  • Local copy of the state in every observer — new DigitalTwinStateReplica (applyDescriptionEvent / applyValuesEvent return whether the event has been applied, applyNextPendingValues() drains the values that arrived before their description), with DigitalTwinStateManager.getDescriptionChanges(event) / getValuesChanges(event) to read the changes carried by an event
  • Digital Adapter — onStateUpdate removed; onStateDescriptionUpdate / onStateValuesUpdate are the abstract state callbacks; content and trigger filters are set with observeDigitalTwinState(filter[, changeFilter]), typically in onDigitalTwinSync
  • Storage Manager and storages — description and values are saved separately (saveDigitalTwinStateDescription(description, changes) / saveDigitalTwinStateValues(values, valuesDelta, changes)), the complete state is queried as a description with its values (DigitalTwinStateHistoryRecord); the Storage Manager never filters: it always saves the description and the complete values
  • Augmentation Functions — onStateDescriptionUpdate / onStateValuesUpdate replace onStateUpdate; the context has description and values; the abstract AugmentationFunctionHandler applies the filters of each function and calls two per-function hooks
  • Query replaces QueryRequest — built with Query.on(resourceType), with filters, sorting, limit/offset, aggregations, total count and timeout
  • WldtStorage is query-driven — the ~60 per-resource getters are replaced by a single execute(Query) method
  • QueryResult always returns records — typed (QueryResult<T extends StorageRecord>) and built with success(...) / failure(...)
  • Filters and aggregations — new filter and aggregation sub-packages, plus an in-memory evaluator used by DefaultWldtStorage
  • Query timeout — configurable on the Query and on the QueryExecutor; expired queries are skipped by the StorageManager
  • observeState / observeEventNotifications are now honoured on the stateful push path
  • Optional query refresh on every values update for stateful functions (refreshQueryOnStateUpdate)
  • Removal of the constructors deprecated in 0.8.1 (type-only constructors of State and Physical Asset properties and events)
  • Event bus robustness — a failing subscriber no longer stops the delivery of the following events to the same subscriber
  • Life cycle order — STARTED is published before the Physical and Digital Adapters are executed, so BOUND can never precede it (the start callbacks of the adapters are therefore called before the adapters run)
  • Storage monitoring — new metrics for the writes of the state description; storage_write_dt_state_* now count the values writes

Breaking changes

Impact column: Compile = the code that uses it does not compile anymore; Runtime = it compiles but fails or behaves differently at runtime (these are the dangerous ones, see also Behaviour changes without compile errors).

AreaChangeImpact
Event BusThe topic dt.state.update (WldtEventTypes.DT_STATE_UPDATE_MESSAGE_EVENT_TYPE, DigitalTwinStateManager.getStatusUpdatesWldtEventMessageType()) and the metadata DT_STATE_UPDATE_METADATA_PREVIOUS_STATE / DT_STATE_UPDATE_METADATA_CHANGE_LIST are removed. Subscribe to dt.state.description.update and dt.state.values.update (see below)Compile; Runtime for a subscriber that uses the topic as a plain string: it silently receives nothing
Event BusThe query request event now carries a Query as body (WldtEvent<Query>); EventManager.publishStorageQueryRequest and the augmentation listener callbacks take a QueryCompile; Runtime (ClassCastException) for custom subscribers that read the body
StateDigitalTwinStateManager.getDigitalTwinState() is removed; no method of the manager returns the complete DigitalTwinState. Use getDigitalTwinStateDescription() and getDigitalTwinStateValues(). DigitalTwinStateTransaction.getStartDigitalTwinState() / getEndDigitalTwinState() are not public anymoreCompile
StateDigitalTwinStateManager.notifyDigitalTwinStateEvent(...) must be called inside a state transaction (it used to need none): it throws WldtDigitalTwinStateEventNotificationException otherwise, and the notification is published at commit timeRuntime
StateDigitalTwinStateManager.recordActionInvocation(key) is removed, and the DigitalTwinModel does not record the last invocation automatically anymore: call notifyActionExecuted(actionKey[, instant]) inside a transactionCompile; Runtime: if the call is missing, the last invocation of the action is never updated
StateDigitalTwinStateDescription and DigitalTwinStateValues have a new id field (package-private constructors changed). DigitalTwinStateValues.getDescriptionId() and DigitalTwinStateDescription.getId()Compile (only code in the package)
Life cycleShadowingModelListener.onShadowingSync / onShadowingOutOfSync, LifeCycleListener.onSync / onUnSync and AugmentationLifeCycleListener.onSync / onUnSync receive (DigitalTwinStateDescription, DigitalTwinStateValues) instead of a DigitalTwinStateCompile
Life cycleSTARTED is published before the Physical and Digital Adapters are executed. LifeCycleListener.onStart() (hence DigitalAdapter.onDigitalTwinStart(), PhysicalAdapter.onStart(), AugmentationLifeCycleListener.onStart()) is called before onAdapterStart() / the adapter threadRuntime
Digital AdapteronStateUpdate(new, previous, changes) is removed. onStateDescriptionUpdate(description, changes) and onStateValuesUpdate(values, changes) are abstract. onDigitalTwinSync / onDigitalTwinUnSync receive (description, values). The protected field digitalTwinState is replaced by getDigitalTwinStateDescription() / getDigitalTwinStateValues(). observeAllDigitalTwinEventsNotifications / unObserveAll... take a DigitalTwinStateDescriptionCompile
AugmentationStatefulAugmentationFunction.onStateUpdate(DigitalTwinState) is replaced by the abstract onStateDescriptionUpdate(DigitalTwinStateDescription) and onStateValuesUpdate(DigitalTwinStateValues); the final method handleStateUpdate(DigitalTwinState) is replaced by handleStateDescriptionUpdate(...) / handleStateValuesUpdate(...)Compile
AugmentationAugmentationFunctionContext: constructors, getDigitalTwinState() / setDigitalTwinState(...) are replaced by (DigitalTwinStateDescription, DigitalTwinStateValues[, QueryResult]), getDigitalTwinStateDescription() / getDigitalTwinStateValues() and the matching settersCompile
AugmentationThe abstract AugmentationFunctionHandler hook onStateUpdate is replaced by onStateDescriptionUpdate(StatefulAugmentationFunction, DigitalTwinStateDescription, List<DigitalTwinStateChange>) and onStateValuesUpdate(StatefulAugmentationFunction, DigitalTwinStateValues, List<DigitalTwinStateChange>), called once per running function after the handler has applied the filters of the function; onDigitalTwinLifeCycleSync / UnSync receive (description, values)Compile (custom handlers)
AugmentationStatefulAugmentationFunction.onQueryResultRefresh(QueryRequest, QueryResult) is now onQueryResultRefresh(Query, QueryResult); same for StatefulAugmentationListener.onStatefulAugmentationFunctionQueryResultRefresh(String, Query) and AugmentationFunctionHandlerCompile
AugmentationAugmentationFunctionContextRequest: the constructor (QueryRequest) is replaced by (Query), and getQueryRequest() / setQueryRequest(...) are renamed getQuery() / setQuery(...)Compile
AugmentationAugmentationFunctionHandler: the protected field digitalTwinState is removed, use getDigitalTwinStateDescription() / getDigitalTwinStateValues(). observeDigitalTwinEventsNotifications(...) / unObserveDigitalTwinEventsNotifications(...) take a DigitalTwinStateDescription instead of a DigitalTwinStateCompile (custom handlers)
StorageWldtStorage.saveDigitalTwinState(...) and DigitalTwinStateRecord are removed: use saveDigitalTwinStateDescription(description, changes) / saveDigitalTwinStateValues(values, valuesDelta, changes) and the new recordsCompile
StorageThe abstract WldtStorage.saveDigitalTwinStateValues(DigitalTwinStateValues values, DigitalTwinStateValues valuesDelta, List<DigitalTwinStateChange> changes) receives the complete values, the delta carried by the event (null when the save follows a description that removes a resource) and the changes. DefaultWldtStorage ignores the deltaCompile (custom storages)
StorageIWldtEventObserverListener.onStateEvent is replaced by onStateDescriptionEvent, onStateValuesEvent and onStateEventNotificationCompile
StorageQueryRequest and QueryRequestType are removed. Use QueryCompile
StorageWldtStorage: all the abstract getters by resource are removed and replaced by abstract QueryResult<?> execute(Query query). Custom storages must implement execute (see below)Compile
StorageQueryManager / DefaultQueryManager: handleQuery(Query, Map<String, WldtStorage>) and getTargetStorage(Query, Map); the per-resource handle…Query methods are removed. The monitoring metrics (storage_query_*) are updated by the QueryManager base class, so DefaultQueryManager only inherits the default selection and a custom manager that overrides getTargetStorage gets the metricsCompile
StorageQueryExecutor: syncQueryExecute(Query) and asyncQueryExecute(Query, IQueryResultListener); the listener of an asynchronous query runs on a library thread pool (not on the event bus thread) and its exceptions are logged; new close() releases the subscription to the event busCompile
StorageQueryResult<T> is now QueryResult<T extends StorageRecord>; the public constructors are replaced by the factories success(query, items[, total]) and failure(query, errorMessage); getOriginalRequest() is now getOriginalQuery(); getResults() is replaced by getItems() and getTotalResults() by getTotal(), which returns a Long that is null unless the query was built with withTotal(); all the setters are removedCompile
StorageThe query DIGITAL_TWIN_STATE returns a single DigitalTwinStateHistoryRecord (description id → description + values) instead of a list of DigitalTwinStateRecord; counts of the stored states refer to descriptions (count DIGITAL_TWIN_STATE_VALUES for the value snapshots)Compile; Runtime (ClassCastException, different counts)
StorageStorageStats extends StorageRecord; getStateVariationStats() / setStateVariationStats(...) are renamed getStateValuesVariationStats() / setStateValuesVariationStats(...), new getStateDescriptionVariationStats() / setStateDescriptionVariationStats(...); the all-arguments constructor changedCompile
Monitoringaf_function_state_update_* now count the values updates dispatched to a function; the description updates have the new af_function_state_description_update_{exec_time,success_count,error_count}. da_state_update_processing_exec_error_count counts also the failures of the state callbacks. storage_write_dt_state_{success_count,error_count,exec_time} count only the writes of the values; the writes of the description have the new metrics storage_write_dt_state_description_{success_count,error_count,exec_time} (CoreMonitoringUtils.STORAGE_WRITE_DIGITAL_TWIN_STATE_DESCRIPTION_*). The storage metrics registered per storage grow from 18 to 21. da_state_update_processing_* count every state event (description and values)Runtime (dashboards, alerts)

Equivalence with the previous request types

Previous request typeEquivalent query
TIME_RANGEwhere(and(gte(TIMESTAMP, start), lte(TIMESTAMP, end)))
SAMPLE_RANGE (indices a to b)offset(a).limit(b - a + 1)
LAST_VALUEorderBy(TIMESTAMP, DESC).limit(1)
COUNTaggregate(count().as("count"))

Before / after

// 0.8.1 - query
QueryRequest request = new QueryRequest();
request.setResourceType(QueryResourceType.DIGITAL_TWIN_STATE);
request.setRequestType(QueryRequestType.TIME_RANGE);
request.setStartTimestampMs(start);
request.setEndTimestampMs(end);
QueryResult<?> result = queryExecutor.syncQueryExecute(request);

// 0.9.0 - query: the complete state is a single record that maps descriptions to the values stored for them
Query query = Query.on(QueryResourceType.DIGITAL_TWIN_STATE)
        .where(and(gte(QueryFieldNames.TIMESTAMP, start), lte(QueryFieldNames.TIMESTAMP, end)))
        .build();
QueryResult<?> result = queryExecutor.syncQueryExecute(query);
DigitalTwinStateHistoryRecord states = result.as(DigitalTwinStateHistoryRecord.class).first();
for (DigitalTwinStateHistoryEntry entry : states.getEntries().values())
    entry.getValuesList(); // the values stored for entry.getDescription()
// 0.8.1 - Digital Adapter
@Override
protected void onStateUpdate(DigitalTwinState newState, DigitalTwinState previousState, ArrayList<DigitalTwinStateChange> changes) {
    newState.getPropertyList().ifPresent(properties -> properties.forEach(p -> publish(p.getKey(), p.getValue())));
}

// 0.9.0 - Digital Adapter
@Override
protected void onStateDescriptionUpdate(DigitalTwinStateDescription description, List<DigitalTwinStateChange> descriptionChanges) {
    // the structure changed: add/remove what is exposed to the external world
}

@Override
protected void onStateValuesUpdate(DigitalTwinStateValues values, List<DigitalTwinStateChange> relevantChanges) {
    values.getPropertyValues().forEach((key, value) -> publish(key, value));
}

Behaviour changes without compile errors

These changes do not produce compile errors: code written for 0.8.1 builds, but behaves differently. Review each of them.

What changesBefore (0.8.1)Now (0.9.0)What to do
Last invocation of an actionUpdated by the library when a Digital Action was receivedNever updated automaticallyCall notifyActionExecuted(actionKey[, instant]) inside a state transaction when the Shadowing Function considers the action executed
Notification of a state eventnotifyDigitalTwinStateEvent(...) could be called outside a transactionThrows WldtDigitalTwinStateEventNotificationException outside a transaction; published at commitWrap the call in startStateTransaction() / commitStateTransaction()
Life cycle orderBOUND could be published before STARTED (race with the adapters)STARTED is always published before the adapters are executed, then BOUNDNothing, unless the code relied on the old order
Start callback of the adaptersonDigitalTwinStart() / onStart() called while the adapters were already runningCalled before the adapters run (before onAdapterStart()); a way to exploit it will be defined in the futureDo not initialize adapter resources there: use onAdapterStart()
observeState / observeEventNotifications of a functionobserveState = false only affected the context of start / stop / execute; observeEventNotifications was ignoredBoth are honoured on the push pathReview functions that set them to false
Number of values updatesOne state update per transactionA notified event or an executed action adds a values update (the last notification / invocation is a value of the state)Review stateful functions and adapters without filters that react to every update
State events delivered to the subscribersComplete state at every updateDescription (only on a real structural change) and values delta (possibly with an empty body), two independent topicsKeep a DigitalTwinStateReplica instead of reading the body as the complete state
Storage of the stateOne complete state record at every updateDescription saved at every structural change, complete values saved at every values update, never filteredQuery DIGITAL_TWIN_STATE_DESCRIPTION / DIGITAL_TWIN_STATE_VALUES for counts; read DIGITAL_TWIN_STATE as a DigitalTwinStateHistoryRecord
Removal of a property, relationship, action or eventA state update with the new stateA description update only; no values callback (the local copies drop the value)React to removals in onStateDescriptionUpdate
Metrics of the storage and of the Digital Adapterstorage_write_dt_state_* counted the state writesThey count the values writes; the description writes have their own metricsUpdate dashboards and alerts

New: Event Bus State Propagation

The two state events

Every committed state transaction publishes, in this order, up to two events (and then the notifications of the events notified in the transaction):

EventTopicPublished whenBodyMetadata
Description updatedt.state.description.updateThe structure of the state really changed: the new description is compared structurally with the previous one (an update that leaves the structure identical publishes nothing)The complete new DigitalTwinStateDescriptionDT_STATE_DESCRIPTION_UPDATE_METADATA_PREVIOUS_DESCRIPTION (previous description), DT_STATE_DESCRIPTION_UPDATE_METADATA_CHANGE_LIST (changes that alter the structure)
Values updatedt.state.values.updateThe transaction contains at least one change that produces a values update (see Which changes alter what)A DigitalTwinStateValues delta: only the values that changedDT_STATE_VALUES_UPDATE_METADATA_PREVIOUS_VALUES (previous values of the same resources), DT_STATE_VALUES_UPDATE_METADATA_CHANGE_LIST (changes that alter the values)

WldtEventTypes.DT_STATE_DESCRIPTION_UPDATE_MESSAGE_EVENT_TYPE and DT_STATE_VALUES_UPDATE_MESSAGE_EVENT_TYPE (also DigitalTwinStateManager.getStateDescriptionUpdateWldtEventMessageType() / getStateValuesUpdateWldtEventMessageType()) are the topic constants. The topics of the event notifications (dt.state.event.notification.*) are unchanged.

What goes in the values delta:

  • a property added or whose value changed: its new value; a property whose value is unchanged is not in the body (an update with the same value is still in the change list, and the event is published with an empty body and a new evaluation instant)
  • a relationship added or with changed instances: the complete list of the instances of that relationship
  • the last invocation of the actions / last notification of the events triggered in the transaction
  • nothing for a removed property, relationship, action or event: the removal is not a values update, it travels only in the description event; every component that keeps a local copy drops the value when it applies the new description (so no values callback is invoked for a removal)
  • a relationship instance added or removed: the complete, updated list of the instances of that relationship (the description does not change, so this is the only event that carries the removal of an instance)

Description id

DigitalTwinStateDescription.getId() is <creationTimestamp>_<numSeq>: the epoch milliseconds of the creation of the DigitalTwinStateManager followed by a sequence number that starts from 0 (the initial, empty description) and grows every time the structure really changes. A transaction that changes several resources produces one new description. DigitalTwinStateValues.getDescriptionId() is the id of the description the values belong to: DigitalTwinStateManager.getDigitalTwinStateValues() always uses the id of the current description.

Last invocation and last notification are values of the state

The last invocation of each action and the last notification of each event are part of the values and travel in the values update. They are written inside a transaction as a DigitalTwinStateChange with OPERATION_UPDATE_VALUE on an ACTION / EVENT resource (getValueInstant() carries the instant):

  • notifyDigitalTwinStateEvent(notification) — requires a transaction; the notification is published at commit time, after description and values; a rolled back transaction publishes nothing; the event key must be defined in the state
  • notifyActionExecuted(actionKey[, executionInstant]) — new, requires a transaction. The invocation of a Digital Action does not update the timestamp anymore: the Shadowing Function calls this method when it considers the action executed
this.digitalTwinStateManager.startStateTransaction();
this.digitalTwinStateManager.notifyActionExecuted("set-temperature-action-key");
this.digitalTwinStateManager.notifyDigitalTwinStateEvent(new DigitalTwinStateEventNotification<>("overheating", "critical", System.currentTimeMillis()));
this.digitalTwinStateManager.commitStateTransaction();

Local copy of the state: DigitalTwinStateReplica

Digital Adapters, the Storage Manager and the Augmentation Function Handlers keep a complete and never filtered local copy of the description and of the values, initialized at synchronization time (the Storage Manager when the DigitalTwin is created) and updated at every event (DigitalTwinStateReplica, package it.wldt.core.state, available to custom components too). The delta of the values is merged with the complete values (DigitalTwinStateValues.applyUpdate) and a new description realigns the values to its id.

The public API of DigitalTwinStateReplica (all methods are synchronized; the caller holds synchronized (replica) around apply + read when it needs a consistent view):

MethodDescription
seed(description, values) / clear() / isSeeded()Initialize the copy at synchronization time, drop it at un-synchronization, check if it is initialized
boolean applyDescriptionEvent(WldtEvent<?>)Applies a description event: true if applied; false for a description that is not newer than the current one or that belongs to another state. After it the waiting values events must be drained
boolean applyValuesEvent(WldtEvent<?>)Applies a values event: true if applied; false if it is kept waiting for its description, if it is already included in the seeded values, or if it belongs to another state
WldtEvent<?> applyNextPendingValues()Applies the next waiting values event and returns it, null when there is none (or the next one still waits for its description). Call it in a loop after a description event
getDescription() / getValues()The complete local copy (never filtered); getPendingValuesCount() counts the values waiting for their description
DigitalTwinStateManager.getDescriptionChanges(event) / getValuesChanges(event)Static helpers (never null): the changes carried in the metadata of a description / values event
DigitalTwinStateReplica replica = new DigitalTwinStateReplica();
replica.seed(description, values);                    // at synchronization time

synchronized (replica) {
    if (replica.applyValuesEvent(wldtEvent))
        process(replica.getValues(), DigitalTwinStateManager.getValuesChanges(wldtEvent));

    if (replica.applyDescriptionEvent(wldtEvent)) {
        process(replica.getDescription(), DigitalTwinStateManager.getDescriptionChanges(wldtEvent));

        WldtEvent<?> pendingEvent;
        while ((pendingEvent = replica.applyNextPendingValues()) != null)
            process(replica.getValues(), DigitalTwinStateManager.getValuesChanges(pendingEvent));
    }
}

The two topics are delivered independently, so the values of a new description can arrive before the description itself. In that case they are kept in a list, in arrival order: when the description arrives it is applied first, then the waiting values are processed one at a time in the order they arrived (a warning is logged if they wait too long, nothing is discarded). Values that refer to an older description are applied anyway.

Filters

  • The description is never filtered, anywhere: Digital Adapters, the Storage Manager and Augmentation Functions always receive the complete new description at every structural change.
  • DigitalTwinStateFilter (content, by name on properties, actions, events and relationships) and DigitalTwinStateChangeFilter (trigger, by operation, resource type and name) apply only to the values. The values callback is invoked if at least one change passes both; the delivered values are the complete values limited by the content filter. The local copy is always updated, whatever the filters.
  • DigitalTwinStateChange.isDescriptionChange() / isValueChange() (and the static helpers descriptionChanges(list) / valueChanges(list)) classify the changes on the operation first (see Which changes alter what): the trigger of an action or event (OPERATION_UPDATE_VALUE) is a value change only, the removal of a property, relationship, action or event is a description change only.
  • The event names of the content filter also select the event notifications delivered to the Digital Adapter (onEventNotificationReceived) and to the Augmentation Functions: the notifications of the events that the filter does not accept are discarded.
  • A DigitalTwinStateChangeFilter rule is a cross product: inside each criterion (operations, resource types, names) the values are alternatives (OR) and the criteria are AND-ed, so {OPERATION_UPDATE_VALUE} x {PROPERTY_VALUE, EVENT} x {"temperature", "alarm"} accepts any combination of the three sets (the names are not tied to a resource type). A Digital Adapter has one content filter and one rule; an Augmentation Function can have several rules (OR).
  • The four “filters” of the library are unrelated and documented as such: DigitalTwinStateFilter (which values), DigitalTwinStateChangeFilter (which changes trigger), WldtEventFilter (event types of an event bus subscription), query Filter (conditions of a storage query).
  • Consequence: a trigger rule with OPERATION_REMOVE on a property, relationship, action or event never fires a values callback (the removal is delivered by onStateDescriptionUpdate, which is never filtered); OPERATION_REMOVE on RELATIONSHIP_INSTANCE does.

Digital Adapter

  • observeDigitalTwinState(filter[, changeFilter]) sets the content and trigger filters (typically in onDigitalTwinSync, where the description is available, so they are active from the first update) and clearStateFilter() removes them
  • onStateDescriptionUpdate(description, descriptionChanges) — at every structural change, always complete
  • onStateValuesUpdate(values, relevantChanges) — the complete values of the local copy (limited by the content filter), only if at least one change passes the filters
  • getDigitalTwinStateDescription() / getDigitalTwinStateValues() — protected accessors to the complete local copy
  • The state callbacks run on the event bus thread of the adapter while holding the monitor of the local copy: a slow callback, or one that keeps a lock needed by other threads, blocks the arrival of the following state events. A failure of a callback is logged and counted in da_state_update_processing_exec_error_count
  • At un-synchronization the adapter unsubscribes from the state topics and drops its local copy; the next synchronization seeds the copy again and subscribes again

Storage

  • WldtStorage.saveDigitalTwinStateDescription(description, changes) and saveDigitalTwinStateValues(values, valuesDelta, changes) (the complete values, the delta carried by the values event, null after a description removal, and the change list); the Storage Manager always saves the description and saves the complete values of its local copy (with the id of the description and the change list) at every values update, without any filter. After a description that contains a removal it saves the values aligned to the new description too (no values event is published for a removal)
  • The Storage Manager does not filter: every description event saves the description and every values event saves the complete values of the local copy
  • New resources QueryResourceType.DIGITAL_TWIN_STATE_DESCRIPTION (DigitalTwinStateDescriptionRecord) and DIGITAL_TWIN_STATE_VALUES (DigitalTwinStateValuesRecord); DIGITAL_TWIN_STATE returns the complete state as a single DigitalTwinStateHistoryRecord that maps every selected description (by description id) to the values stored for it in the selected interval (getEntries(), getEntry(id), getValuesList(id))
  • Filters, sorting, limits and aggregations on DIGITAL_TWIN_STATE work on the fields of both description and values (QueryFieldNames.DESCRIPTION_ID, values.propertyValues.<key>, description.<field>, …); limit, offset and total count the values (the selected rows, before the grouping by description)
  • StorageStats.getStateValuesVariationStats() (renamed from getStateVariationStats()) and getStateDescriptionVariationStats(); IWldtEventObserverListener has onStateDescriptionEvent, onStateValuesEvent, onStateEventNotification
// The complete state in an interval: one record that maps descriptions to their values
DigitalTwinStateHistoryRecord history = queryExecutor.syncQueryExecute(
        Query.on(QueryResourceType.DIGITAL_TWIN_STATE)
                .where(and(gte(QueryFieldNames.TIMESTAMP, from), lt(QueryFieldNames.TIMESTAMP, to)))
                .build())
        .as(DigitalTwinStateHistoryRecord.class).first();

for (DigitalTwinStateHistoryEntry entry : history.getEntries().values())
    logger.info("{}: {} values", entry.getDescriptionId(), entry.getValuesList().size());

// Average temperature for each description
Query stats = Query.on(QueryResourceType.DIGITAL_TWIN_STATE)
        .aggregate(groupBy(QueryFieldNames.DESCRIPTION_ID), count().as("count"), avg("values.propertyValues.temperature").as("avg"))
        .build();

Augmentation Functions

  • StatefulAugmentationFunction.onStateDescriptionUpdate(DigitalTwinStateDescription) — every structural change, never filtered
  • StatefulAugmentationFunction.onStateValuesUpdate(DigitalTwinStateValues) — the complete values (limited by the content filter), only if at least one change passes the trigger and content filters; without filters it is invoked at every values update
  • AugmentationFunctionContext.getDigitalTwinStateDescription() (always complete) and getDigitalTwinStateValues() (limited by the content filter) in the context of start, stop and execute
  • The AugmentationFunctionHandler keeps a complete, never filtered, local copy of the state; the filters of each function are applied only when the function is notified. AugmentationFunctionContextRequest.filterValues(values) replaces filterState
  • The abstract AugmentationFunctionHandler also applies the event notification filters (observeEventNotifications and the event names) before calling the hook onEventNotificationReceived(functions, notification), that receives only the functions to notify: a custom handler gets them without repeating the code
  • At un-synchronization the handler unsubscribes from the state topics and drops its local copy; the next synchronization seeds it again and subscribes again
  • Metrics of the functions: af_function_state_update_* count the values updates dispatched to a function (as the state updates in the previous versions) and the new af_function_state_description_update_* count the description updates

Which changes alter what

ChangeDescription updateValues update
PROPERTY, RELATIONSHIP with OPERATION_ADD / OPERATION_UPDATEyesyes (the value / the instances)
PROPERTY, RELATIONSHIP, ACTION, EVENT with OPERATION_REMOVEyesno (the local copies drop the value when they apply the description; no values callback)
ACTION, EVENT with OPERATION_ADD / OPERATION_UPDATEyesno (they carry no value)
OPERATION_UPDATE_VALUE (property value, last invocation of an action, last notification of an event)noyes
RELATIONSHIP_INSTANCE with OPERATION_ADD / OPERATION_REMOVEnoyes (the complete list of the instances)

A change is published in the description event only if the structure really changed, so for example updateProperty(...) with an identical structure produces a values update (the property value) but no description update.


New: Query System

Query

Immutable description of a query created with the builder Query.on(resourceType): filter, sorting (SortCriterion), limit / offset, aggregation, withTotal and timeout. refresh() returns a copy with a new requestId, useful to re-run the same query periodically.

Filters and aggregations

PackageClasses
it.wldt.storage.query.filterFilter, ComparisonFilter, AndFilter, OrFilter, NotFilter, FilterOperator, FilterVisitor, FilterFactory (eq, gte, and, …)
it.wldt.storage.query.aggregationAggregation, AggregationGroupBy, AggregationMetric, AggregationFunction, AggregationPart, AggregationFactory (groupBy, count, avg, …)

QueryFieldNames lists the fields usable in filters, sorting and aggregations. The result of an aggregation is an AggregationRecord (package it.wldt.storage.model), holding the group-by values and the computed metrics with typed getters (getString, getLong, getDouble).

FilterVisitor allows a custom storage to translate the filter tree into the native query language of its backend (SQL, MongoDB, …).

Results

QueryResult<T extends StorageRecord> always contains a list of records (getItems()), the optional total number of matches, the status and the error message. Helpers: as(Class), first(), last().

Timeouts

  • QueryExecutor.DEFAULT_QUERY_TIMEOUT_MS is 5000 ms; a new constructor QueryExecutor(digitalTwinId, queryExecutorId, defaultTimeoutMs) customizes it
  • A query overrides it with Query.Builder.timeout(long)
  • Timeouts and errors are reported as failed QueryResult
  • The StorageManager skips queries whose timeout already expired (nobody is waiting for the result), so a backlog of abandoned queries does not delay writes and other queries
  • If no QueryManager is set, the StorageManager now answers with a failed QueryResult instead of leaving the caller waiting

Custom storages

A custom WldtStorage implements execute(Query) and translates the query to its backend, plus saveDigitalTwinStateDescription and saveDigitalTwinStateValues(values, valuesDelta, changes). DefaultWldtStorage delegates to the new InMemoryQueryEvaluator (package it.wldt.storage.query.inmemory), which can also be reused by storages that have no native query engine. For DIGITAL_TWIN_STATE the default storage takes a snapshot of the stored descriptions and values and delegates to InMemoryDigitalTwinStateQuery, that joins every values record with its description in an internal row (so filters, sorting and aggregations are evaluated on one values record at a time) and groups the selected rows in the single DigitalTwinStateHistoryRecord. See the Storage Layer page.


New: State Filters for Augmentation Functions

Until 0.8.1 every dt.state.update was pushed, with the complete state, to every running stateful function. Two optional filters are now available in AugmentationFunctionContextRequest. They are disabled by default: with no filter every values update is delivered with the complete values. They apply only to the values; the description is never filtered.

1. Trigger filter (stateful functions only)

DigitalTwinStateChangeFilter rules decide when a values update is pushed. A rule has optional criteria on operation, resource type and resource name (empty criterion = wildcard, non-empty criteria are AND-ed). The update is pushed if any change of the update matches any rule; if the update carries no change list, it is not pushed.

DigitalTwinStateChangeFilter.onPropertyValueUpdate("temperature", "humidity");
DigitalTwinStateChangeFilter.onResources("near");
DigitalTwinStateChangeFilter.builder()
        .operations(DigitalTwinStateChange.Operation.OPERATION_REMOVE)
        .resourceTypes(DigitalTwinStateChange.ResourceType.RELATIONSHIP_INSTANCE)
        .build();

2. Content filter (stateful and stateless functions)

The DigitalTwinStateFilter set with withStateFilter(...) (the same class used by the Digital Adapters: properties, actions (new), events and relationships, by name) decides what of the values the function receives. Each category is independent: null keeps everything, an empty list removes it. The same filter applies to the values in the context of start / stop / execute (stateless included). The event names also drop the event notifications whose name is not listed.

Configuration

AugmentationFunctionContextRequest request = new AugmentationFunctionContextRequest()
        .withStateChangeFilters(DigitalTwinStateChangeFilter.onPropertyValueUpdate("temperature", "humidity"))
        .withStateFilter(DigitalTwinStateFilter.all()
                .withPropertyNames("temperature", "humidity")
                .withActionNames());      // no action delivered

Fluent methods: withStateChangeFilters and withStateFilter; helpers hasTriggerFilter(), hasContentFilter(), getStateFilter(), shouldTrigger(changes), acceptsEventNotification(notification) and filterValues(values). New classes: DigitalTwinStateChangeFilter and DigitalTwinStateFilter (package it.wldt.core.state, generic, also used by Digital Adapters). The getters getPropertyNameFilter(), getEventNameFilter(), getRelationshipNameFilter() (and the new getActionNameFilter()) are kept and read the content filter.

The filters are applied by the abstract AugmentationFunctionHandler, not by DefaultAugmentationFunctionHandler, so custom handlers get them too. For every running stateful function the library checks observeState, evaluates the trigger and content filters on the changes and delivers the values limited by the content filter. The two protected abstract callbacks of the handler are now per function: onStateDescriptionUpdate(StatefulAugmentationFunction, DigitalTwinStateDescription, List<DigitalTwinStateChange>) and onStateValuesUpdate(StatefulAugmentationFunction, DigitalTwinStateValues, List<DigitalTwinStateChange>) (custom handlers must adapt their signatures).

Behaviour changes to be aware of

  • observeState = false now stops state updates being pushed to a stateful function (it used to affect only the start / stop / execute context); observeEventNotifications = false now stops event notifications being pushed (it was ignored)
  • The constructor AugmentationFunctionContextRequest(boolean, boolean, Query) now honours its two flags (it ignored them and always used true)
  • The name filters were declared but never read by the framework: setting them now has an effect
  • The trigger filter does not apply to event notifications (use the event names of the content filter) nor to stateless functions, which are request-driven
  • Event notifications are now accompanied by a values update (the last notification of the event): a function without filters is notified also for them

Query refresh on values update (opt-in)

AugmentationFunctionContextRequest.setRefreshQueryOnStateUpdate(true) makes the handler execute the function’s query and deliver the result (onQueryResultRefresh) before every values update notified to it. Disabled by default: the query runs synchronously on the handler thread. See the Augmentation Functions page.


Fixes

  • A RuntimeException thrown by an event listener no longer stops the delivery of the following events to the same subscriber: it is logged and the delivery continues (DefaultEventBusStrategy)
  • The STARTED life cycle event is now published before the Physical and Digital Adapters are executed, so BOUND can no longer precede STARTED (see Behaviour changes without compile errors). Consequence: the adapters’ start callback (DigitalAdapter.onDigitalTwinStart(), PhysicalAdapter.onStart()) is invoked before the adapter is running (before onAdapterStart()) and must not be used to initialize adapter resources; a way to exploit it will be defined in the future
  • DigitalTwin no longer waits in a busy while loop (it consumed a CPU core) on the adapter executors at the end of the start of the life cycle: both executors are simply shut down after the adapters have been submitted, and the adapters keep running on their threads
  • The values saved after the removal of a property, relationship, action or event take the evaluation instant of the new description (they used to keep the one of the previous values, often identical to an existing record, so time-range queries placed them in the past)
  • A failure of a state callback of a Digital Adapter is now counted by da_state_update_processing_exec_error_count (it was swallowed before being counted)
  • An exception thrown by the listener of an asynchronous query is now logged (it was lost); the listener no longer blocks the delivery of the query results or the query timeouts
  • At un-synchronization Digital Adapters and Augmentation Function Handlers unsubscribe from the state topics (they kept collecting the values events, without limit, until the next synchronization)
  • The StorageManager is seeded with the initial description and values when the DigitalTwin is created (StorageManager.seedDigitalTwinState) and then follows every state event; it is not re-seeded at synchronization time, so the events still in flight at that moment are not considered already included and are saved

Removed (deprecated in 0.8.1)

The constructors that set only the semantic type, deprecated in 0.8.1, are removed:

ClassRemoved constructorReplacement
DigitalTwinStateProperty<T>(key, value, type)(key, value, type, contentType)
DigitalTwinStateEvent(key, type)(key, type, contentType)
PhysicalAssetProperty<T>(key, type, initialValue)(key, type, contentType, initialValue)
PhysicalAssetEvent(key, type)(key, type, contentType)

Code using them no longer compiles. When creating State resources from a Physical Asset Description, copy getType() and getContentType() (see the 0.8.1 Change Log). Pass null as contentType only if the format is really unknown.


Migration from 0.8.1

  1. Replace the removed constructors listed above with the ones that also set the contentType.
  2. Digital Adapters: remove onStateUpdate and implement onStateDescriptionUpdate and onStateValuesUpdate (both abstract). Change onDigitalTwinSync / onDigitalTwinUnSync to (DigitalTwinStateDescription, DigitalTwinStateValues). Replace the use of the digitalTwinState field with getDigitalTwinStateDescription() / getDigitalTwinStateValues(). observeAllDigitalTwinEventsNotifications now takes the description. Use observeDigitalTwinState(filter[, changeFilter]) in onDigitalTwinSync to restrict the values (content filter) and to choose when onStateValuesUpdate is called (trigger filter).
  3. Shadowing Functions (DigitalTwinModel): replace getDigitalTwinState() with getDigitalTwinStateDescription() / getDigitalTwinStateValues() (for example, getProperties().stream().anyMatch(...) instead of containsProperty(...)). Wrap notifyDigitalTwinStateEvent(...) in startStateTransaction() / commitStateTransaction(). Remove recordActionInvocation(...) and, if the last invocation of an action matters, call notifyActionExecuted(...) inside a transaction when the action is executed. onShadowingSync / onShadowingOutOfSync listeners and LifeCycleListener implementations receive description and values.
  4. Augmentation Functions: replace onStateUpdate(DigitalTwinState) with onStateDescriptionUpdate(DigitalTwinStateDescription) and onStateValuesUpdate(DigitalTwinStateValues); read the context with getDigitalTwinStateDescription() / getDigitalTwinStateValues(). Custom AugmentationFunctionHandler implementations: adopt the new hooks and the (description, values) life cycle callbacks.
  5. Event bus subscribers: replace the subscription to dt.state.update with dt.state.description.update and/or dt.state.values.update, read the new bodies and metadata, and note that the values body is a delta. Keep a DigitalTwinStateReplica if you need the complete state; handle that the description event is published only when the structure changes and that a values update can have an empty body.
  6. Storage: implement saveDigitalTwinStateDescription / saveDigitalTwinStateValues(values, valuesDelta, changes) in custom WldtStorage classes (the delta is null when the values are saved after a description removal); replace DigitalTwinStateRecord with DigitalTwinStateHistoryRecord (full state: a single record, read it with first() and iterate getEntries()), DigitalTwinStateDescriptionRecord or DigitalTwinStateValuesRecord; StorageStats.getStateVariationStats() is renamed getStateValuesVariationStats(); IWldtEventObserverListener implementations get onStateDescriptionEvent, onStateValuesEvent and onStateEventNotification instead of onStateEvent. Counts of the stored states (DIGITAL_TWIN_STATE) now refer to descriptions: count DIGITAL_TWIN_STATE_VALUES for the number of stored value snapshots.
  7. Replace every QueryRequest / QueryRequestType with a Query (see the equivalence table above).
  8. Update the signature of onQueryResultRefresh in stateful augmentation functions: Query instead of QueryRequest. Build the AugmentationFunctionContextRequest with a Query and use getQuery() / setQuery(...) instead of getQueryRequest() / setQueryRequest(...).
  9. Read results through QueryResult.getItems() / as(Class) instead of getResults(), and the total through getTotal() (build the query with withTotal()) instead of getTotalResults(); use QueryResult.success(...) / failure(...) instead of the removed constructors and setters, and getOriginalQuery() instead of getOriginalRequest().
  10. Custom WldtStorage implementations: remove the per-resource getters and implement execute(Query).
  11. Custom QueryManager implementations: adopt the new handleQuery / getTargetStorage signatures.
  12. If a function relied on observeState = false / observeEventNotifications = false having no effect on the push path, review it: those flags are now honoured.
  13. Stateful functions without filters are now notified at every values update, including the ones produced by the notification of an event (last notification): if a function reacts to every update, review how many times it runs.
  14. Life cycle: if an adapter or a listener relied on onStart() / onDigitalTwinStart() being called after the adapters were running, move that code to onAdapterStart(); STARTED now precedes BOUND always.
  15. Augmentation: AugmentationFunctionContext is built with (description, values[, queryResult]); handleStateUpdate is replaced by handleStateDescriptionUpdate / handleStateValuesUpdate; a custom AugmentationFunctionHandler implements the two per-function hooks onStateDescriptionUpdate(function, description, changes) / onStateValuesUpdate(function, filteredValues, changes) and must not filter the state anymore; it reads the state with getDigitalTwinStateDescription() / getDigitalTwinStateValues() instead of the removed digitalTwinState field.
  16. Monitoring: update dashboards and alerts: storage_write_dt_state_* now count the values writes, add storage_write_dt_state_description_* for the descriptions.
  17. StorageStats: use getStateValuesVariationStats() / getStateDescriptionVariationStats() and the new constructor.
  18. Augmentation: the content filter of AugmentationFunctionContextRequest is a DigitalTwinStateFilter set with withStateFilter(...); a custom AugmentationFunctionHandler receives in onEventNotificationReceived(functions, notification) only the functions that observe the event notifications and accept the event: remove the code that repeats the filters. DigitalTwinStateFilterUtils does not exist: use the methods of the context request (shouldTrigger, acceptsEventNotification, filterValues).
  19. State classes: the classification of the changes is in DigitalTwinStateChange (isDescriptionChange(), isValueChange(), descriptionChanges(list), valueChanges(list)); DigitalTwinStateValues.applyUpdate(delta) takes only the delta.
  20. Monitoring: the values updates dispatched to a function are af_function_state_update_*; add af_function_state_description_update_* for the descriptions.
  21. Queries: do not block in a callback with a synchronous query if you want the following events of the component delivered on time; the listener of an asynchronous query can run other queries (it runs on a library thread pool).