Change Log 0.9.0
Version 0.9.0 is a breaking release that changes three fundamental areas of the library:
- Event Bus State Propagation. The Digital Twin State does not travel anymore as a single, complete
DigitalTwinStateon 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). - A new declarative Query System. The request-type based
QueryRequestis replaced by an immutableQueryobject (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. - 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 customAugmentationFunctionHandler, customWldtStorage/QueryManager,LifeCycleListenerimplementations, event bus subscribers of the state events, code that usesQueryRequest.- 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,
STARTEDis notified before the adapters run,observeState/observeEventNotificationsare 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) anddt.state.values.update(only the changed values).dt.state.updateand the complete state on the bus do not exist anymore DigitalTwinStateDescriptionhas a unique id<creationTimestamp>_<numSeq>andDigitalTwinStateValuesalways carries the id of the description it belongs toDigitalTwinStateManagernever returns the complete state —getDigitalTwinStateDescription()andgetDigitalTwinStateValues()replacegetDigitalTwinState()- 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/applyValuesEventreturn whether the event has been applied,applyNextPendingValues()drains the values that arrived before their description), withDigitalTwinStateManager.getDescriptionChanges(event)/getValuesChanges(event)to read the changes carried by an event - Digital Adapter —
onStateUpdateremoved;onStateDescriptionUpdate/onStateValuesUpdateare the abstract state callbacks; content and trigger filters are set withobserveDigitalTwinState(filter[, changeFilter]), typically inonDigitalTwinSync - 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/onStateValuesUpdatereplaceonStateUpdate; the context has description and values; the abstractAugmentationFunctionHandlerapplies the filters of each function and calls two per-function hooks QueryreplacesQueryRequest— built withQuery.on(resourceType), with filters, sorting,limit/offset, aggregations, total count and timeoutWldtStorageis query-driven — the ~60 per-resource getters are replaced by a singleexecute(Query)methodQueryResultalways returns records — typed (QueryResult<T extends StorageRecord>) and built withsuccess(...)/failure(...)- Filters and aggregations — new
filterandaggregationsub-packages, plus an in-memory evaluator used byDefaultWldtStorage - Query timeout — configurable on the
Queryand on theQueryExecutor; expired queries are skipped by theStorageManager observeState/observeEventNotificationsare 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 —
STARTEDis published before the Physical and Digital Adapters are executed, soBOUNDcan 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).
| Area | Change | Impact |
|---|---|---|
| Event Bus | The 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 Bus | The query request event now carries a Query as body (WldtEvent<Query>); EventManager.publishStorageQueryRequest and the augmentation listener callbacks take a Query | Compile; Runtime (ClassCastException) for custom subscribers that read the body |
| State | DigitalTwinStateManager.getDigitalTwinState() is removed; no method of the manager returns the complete DigitalTwinState. Use getDigitalTwinStateDescription() and getDigitalTwinStateValues(). DigitalTwinStateTransaction.getStartDigitalTwinState() / getEndDigitalTwinState() are not public anymore | Compile |
| State | DigitalTwinStateManager.notifyDigitalTwinStateEvent(...) must be called inside a state transaction (it used to need none): it throws WldtDigitalTwinStateEventNotificationException otherwise, and the notification is published at commit time | Runtime |
| State | DigitalTwinStateManager.recordActionInvocation(key) is removed, and the DigitalTwinModel does not record the last invocation automatically anymore: call notifyActionExecuted(actionKey[, instant]) inside a transaction | Compile; Runtime: if the call is missing, the last invocation of the action is never updated |
| State | DigitalTwinStateDescription and DigitalTwinStateValues have a new id field (package-private constructors changed). DigitalTwinStateValues.getDescriptionId() and DigitalTwinStateDescription.getId() | Compile (only code in the package) |
| Life cycle | ShadowingModelListener.onShadowingSync / onShadowingOutOfSync, LifeCycleListener.onSync / onUnSync and AugmentationLifeCycleListener.onSync / onUnSync receive (DigitalTwinStateDescription, DigitalTwinStateValues) instead of a DigitalTwinState | Compile |
| Life cycle | STARTED 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 thread | Runtime |
| Digital Adapter | onStateUpdate(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 DigitalTwinStateDescription | Compile |
| Augmentation | StatefulAugmentationFunction.onStateUpdate(DigitalTwinState) is replaced by the abstract onStateDescriptionUpdate(DigitalTwinStateDescription) and onStateValuesUpdate(DigitalTwinStateValues); the final method handleStateUpdate(DigitalTwinState) is replaced by handleStateDescriptionUpdate(...) / handleStateValuesUpdate(...) | Compile |
| Augmentation | AugmentationFunctionContext: constructors, getDigitalTwinState() / setDigitalTwinState(...) are replaced by (DigitalTwinStateDescription, DigitalTwinStateValues[, QueryResult]), getDigitalTwinStateDescription() / getDigitalTwinStateValues() and the matching setters | Compile |
| Augmentation | The 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) |
| Augmentation | StatefulAugmentationFunction.onQueryResultRefresh(QueryRequest, QueryResult) is now onQueryResultRefresh(Query, QueryResult); same for StatefulAugmentationListener.onStatefulAugmentationFunctionQueryResultRefresh(String, Query) and AugmentationFunctionHandler | Compile |
| Augmentation | AugmentationFunctionContextRequest: the constructor (QueryRequest) is replaced by (Query), and getQueryRequest() / setQueryRequest(...) are renamed getQuery() / setQuery(...) | Compile |
| Augmentation | AugmentationFunctionHandler: the protected field digitalTwinState is removed, use getDigitalTwinStateDescription() / getDigitalTwinStateValues(). observeDigitalTwinEventsNotifications(...) / unObserveDigitalTwinEventsNotifications(...) take a DigitalTwinStateDescription instead of a DigitalTwinState | Compile (custom handlers) |
| Storage | WldtStorage.saveDigitalTwinState(...) and DigitalTwinStateRecord are removed: use saveDigitalTwinStateDescription(description, changes) / saveDigitalTwinStateValues(values, valuesDelta, changes) and the new records | Compile |
| Storage | The 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 delta | Compile (custom storages) |
| Storage | IWldtEventObserverListener.onStateEvent is replaced by onStateDescriptionEvent, onStateValuesEvent and onStateEventNotification | Compile |
| Storage | QueryRequest and QueryRequestType are removed. Use Query | Compile |
| Storage | WldtStorage: all the abstract getters by resource are removed and replaced by abstract QueryResult<?> execute(Query query). Custom storages must implement execute (see below) | Compile |
| Storage | QueryManager / 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 metrics | Compile |
| Storage | QueryExecutor: 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 bus | Compile |
| Storage | QueryResult<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 removed | Compile |
| Storage | The 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) |
| Storage | StorageStats extends StorageRecord; getStateVariationStats() / setStateVariationStats(...) are renamed getStateValuesVariationStats() / setStateValuesVariationStats(...), new getStateDescriptionVariationStats() / setStateDescriptionVariationStats(...); the all-arguments constructor changed | Compile |
| Monitoring | af_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 type | Equivalent query |
|---|---|
TIME_RANGE | where(and(gte(TIMESTAMP, start), lte(TIMESTAMP, end))) |
SAMPLE_RANGE (indices a to b) | offset(a).limit(b - a + 1) |
LAST_VALUE | orderBy(TIMESTAMP, DESC).limit(1) |
COUNT | aggregate(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 changes | Before (0.8.1) | Now (0.9.0) | What to do |
|---|---|---|---|
| Last invocation of an action | Updated by the library when a Digital Action was received | Never updated automatically | Call notifyActionExecuted(actionKey[, instant]) inside a state transaction when the Shadowing Function considers the action executed |
| Notification of a state event | notifyDigitalTwinStateEvent(...) could be called outside a transaction | Throws WldtDigitalTwinStateEventNotificationException outside a transaction; published at commit | Wrap the call in startStateTransaction() / commitStateTransaction() |
| Life cycle order | BOUND could be published before STARTED (race with the adapters) | STARTED is always published before the adapters are executed, then BOUND | Nothing, unless the code relied on the old order |
| Start callback of the adapters | onDigitalTwinStart() / onStart() called while the adapters were already running | Called before the adapters run (before onAdapterStart()); a way to exploit it will be defined in the future | Do not initialize adapter resources there: use onAdapterStart() |
observeState / observeEventNotifications of a function | observeState = false only affected the context of start / stop / execute; observeEventNotifications was ignored | Both are honoured on the push path | Review functions that set them to false |
| Number of values updates | One state update per transaction | A 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 subscribers | Complete state at every update | Description (only on a real structural change) and values delta (possibly with an empty body), two independent topics | Keep a DigitalTwinStateReplica instead of reading the body as the complete state |
| Storage of the state | One complete state record at every update | Description saved at every structural change, complete values saved at every values update, never filtered | Query DIGITAL_TWIN_STATE_DESCRIPTION / DIGITAL_TWIN_STATE_VALUES for counts; read DIGITAL_TWIN_STATE as a DigitalTwinStateHistoryRecord |
| Removal of a property, relationship, action or event | A state update with the new state | A 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 Adapter | storage_write_dt_state_* counted the state writes | They count the values writes; the description writes have their own metrics | Update 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):
| Event | Topic | Published when | Body | Metadata |
|---|---|---|---|---|
| Description update | dt.state.description.update | The 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 DigitalTwinStateDescription | DT_STATE_DESCRIPTION_UPDATE_METADATA_PREVIOUS_DESCRIPTION (previous description), DT_STATE_DESCRIPTION_UPDATE_METADATA_CHANGE_LIST (changes that alter the structure) |
| Values update | dt.state.values.update | The transaction contains at least one change that produces a values update (see Which changes alter what) | A DigitalTwinStateValues delta: only the values that changed | DT_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 statenotifyActionExecuted(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):
| Method | Description |
|---|---|
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) andDigitalTwinStateChangeFilter(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 helpersdescriptionChanges(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
DigitalTwinStateChangeFilterrule 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), queryFilter(conditions of a storage query). - Consequence: a trigger rule with
OPERATION_REMOVEon a property, relationship, action or event never fires a values callback (the removal is delivered byonStateDescriptionUpdate, which is never filtered);OPERATION_REMOVEonRELATIONSHIP_INSTANCEdoes.
Digital Adapter
observeDigitalTwinState(filter[, changeFilter])sets the content and trigger filters (typically inonDigitalTwinSync, where the description is available, so they are active from the first update) andclearStateFilter()removes themonStateDescriptionUpdate(description, descriptionChanges)— at every structural change, always completeonStateValuesUpdate(values, relevantChanges)— the complete values of the local copy (limited by the content filter), only if at least one change passes the filtersgetDigitalTwinStateDescription()/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)andsaveDigitalTwinStateValues(values, valuesDelta, changes)(the complete values, the delta carried by the values event,nullafter 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) andDIGITAL_TWIN_STATE_VALUES(DigitalTwinStateValuesRecord);DIGITAL_TWIN_STATEreturns the complete state as a singleDigitalTwinStateHistoryRecordthat 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_STATEwork on the fields of both description and values (QueryFieldNames.DESCRIPTION_ID,values.propertyValues.<key>,description.<field>, …);limit,offsetandtotalcount the values (the selected rows, before the grouping by description) StorageStats.getStateValuesVariationStats()(renamed fromgetStateVariationStats()) andgetStateDescriptionVariationStats();IWldtEventObserverListenerhasonStateDescriptionEvent,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 filteredStatefulAugmentationFunction.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 updateAugmentationFunctionContext.getDigitalTwinStateDescription()(always complete) andgetDigitalTwinStateValues()(limited by the content filter) in the context of start, stop and execute- The
AugmentationFunctionHandlerkeeps 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)replacesfilterState - The abstract
AugmentationFunctionHandleralso applies the event notification filters (observeEventNotificationsand the event names) before calling the hookonEventNotificationReceived(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 newaf_function_state_description_update_*count the description updates
Which changes alter what
| Change | Description update | Values update |
|---|---|---|
PROPERTY, RELATIONSHIP with OPERATION_ADD / OPERATION_UPDATE | yes | yes (the value / the instances) |
PROPERTY, RELATIONSHIP, ACTION, EVENT with OPERATION_REMOVE | yes | no (the local copies drop the value when they apply the description; no values callback) |
ACTION, EVENT with OPERATION_ADD / OPERATION_UPDATE | yes | no (they carry no value) |
OPERATION_UPDATE_VALUE (property value, last invocation of an action, last notification of an event) | no | yes |
RELATIONSHIP_INSTANCE with OPERATION_ADD / OPERATION_REMOVE | no | yes (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
| Package | Classes |
|---|---|
it.wldt.storage.query.filter | Filter, ComparisonFilter, AndFilter, OrFilter, NotFilter, FilterOperator, FilterVisitor, FilterFactory (eq, gte, and, …) |
it.wldt.storage.query.aggregation | Aggregation, 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_MSis 5000 ms; a new constructorQueryExecutor(digitalTwinId, queryExecutorId, defaultTimeoutMs)customizes it- A query overrides it with
Query.Builder.timeout(long) - Timeouts and errors are reported as failed
QueryResult - The
StorageManagerskips 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
QueryManageris set, theStorageManagernow answers with a failedQueryResultinstead 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 = falsenow stops state updates being pushed to a stateful function (it used to affect only the start / stop / execute context);observeEventNotifications = falsenow stops event notifications being pushed (it was ignored)- The constructor
AugmentationFunctionContextRequest(boolean, boolean, Query)now honours its two flags (it ignored them and always usedtrue) - 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
RuntimeExceptionthrown 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
STARTEDlife cycle event is now published before the Physical and Digital Adapters are executed, soBOUNDcan no longer precedeSTARTED(see Behaviour changes without compile errors). Consequence: the adapters’ start callback (DigitalAdapter.onDigitalTwinStart(),PhysicalAdapter.onStart()) is invoked before the adapter is running (beforeonAdapterStart()) and must not be used to initialize adapter resources; a way to exploit it will be defined in the future DigitalTwinno longer waits in a busywhileloop (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
StorageManageris seeded with the initial description and values when theDigitalTwinis 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:
| Class | Removed constructor | Replacement |
|---|---|---|
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
- Replace the removed constructors listed above with the ones that also set the
contentType. - Digital Adapters: remove
onStateUpdateand implementonStateDescriptionUpdateandonStateValuesUpdate(both abstract). ChangeonDigitalTwinSync/onDigitalTwinUnSyncto(DigitalTwinStateDescription, DigitalTwinStateValues). Replace the use of thedigitalTwinStatefield withgetDigitalTwinStateDescription()/getDigitalTwinStateValues().observeAllDigitalTwinEventsNotificationsnow takes the description. UseobserveDigitalTwinState(filter[, changeFilter])inonDigitalTwinSyncto restrict the values (content filter) and to choose whenonStateValuesUpdateis called (trigger filter). - Shadowing Functions (
DigitalTwinModel): replacegetDigitalTwinState()withgetDigitalTwinStateDescription()/getDigitalTwinStateValues()(for example,getProperties().stream().anyMatch(...)instead ofcontainsProperty(...)). WrapnotifyDigitalTwinStateEvent(...)instartStateTransaction()/commitStateTransaction(). RemoverecordActionInvocation(...)and, if the last invocation of an action matters, callnotifyActionExecuted(...)inside a transaction when the action is executed.onShadowingSync/onShadowingOutOfSynclisteners andLifeCycleListenerimplementations receive description and values. - Augmentation Functions: replace
onStateUpdate(DigitalTwinState)withonStateDescriptionUpdate(DigitalTwinStateDescription)andonStateValuesUpdate(DigitalTwinStateValues); read the context withgetDigitalTwinStateDescription()/getDigitalTwinStateValues(). CustomAugmentationFunctionHandlerimplementations: adopt the new hooks and the(description, values)life cycle callbacks. - Event bus subscribers: replace the subscription to
dt.state.updatewithdt.state.description.updateand/ordt.state.values.update, read the new bodies and metadata, and note that the values body is a delta. Keep aDigitalTwinStateReplicaif 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. - Storage: implement
saveDigitalTwinStateDescription/saveDigitalTwinStateValues(values, valuesDelta, changes)in customWldtStorageclasses (the delta isnullwhen the values are saved after a description removal); replaceDigitalTwinStateRecordwithDigitalTwinStateHistoryRecord(full state: a single record, read it withfirst()and iterategetEntries()),DigitalTwinStateDescriptionRecordorDigitalTwinStateValuesRecord;StorageStats.getStateVariationStats()is renamedgetStateValuesVariationStats();IWldtEventObserverListenerimplementations getonStateDescriptionEvent,onStateValuesEventandonStateEventNotificationinstead ofonStateEvent. Counts of the stored states (DIGITAL_TWIN_STATE) now refer to descriptions: countDIGITAL_TWIN_STATE_VALUESfor the number of stored value snapshots. - Replace every
QueryRequest/QueryRequestTypewith aQuery(see the equivalence table above). - Update the signature of
onQueryResultRefreshin stateful augmentation functions:Queryinstead ofQueryRequest. Build theAugmentationFunctionContextRequestwith aQueryand usegetQuery()/setQuery(...)instead ofgetQueryRequest()/setQueryRequest(...). - Read results through
QueryResult.getItems()/as(Class)instead ofgetResults(), and the total throughgetTotal()(build the query withwithTotal()) instead ofgetTotalResults(); useQueryResult.success(...)/failure(...)instead of the removed constructors and setters, andgetOriginalQuery()instead ofgetOriginalRequest(). - Custom
WldtStorageimplementations: remove the per-resource getters and implementexecute(Query). - Custom
QueryManagerimplementations: adopt the newhandleQuery/getTargetStoragesignatures. - If a function relied on
observeState = false/observeEventNotifications = falsehaving no effect on the push path, review it: those flags are now honoured. - 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.
- Life cycle: if an adapter or a listener relied on
onStart()/onDigitalTwinStart()being called after the adapters were running, move that code toonAdapterStart();STARTEDnow precedesBOUNDalways. - Augmentation:
AugmentationFunctionContextis built with(description, values[, queryResult]);handleStateUpdateis replaced byhandleStateDescriptionUpdate/handleStateValuesUpdate; a customAugmentationFunctionHandlerimplements the two per-function hooksonStateDescriptionUpdate(function, description, changes)/onStateValuesUpdate(function, filteredValues, changes)and must not filter the state anymore; it reads the state withgetDigitalTwinStateDescription()/getDigitalTwinStateValues()instead of the removeddigitalTwinStatefield. - Monitoring: update dashboards and alerts:
storage_write_dt_state_*now count the values writes, addstorage_write_dt_state_description_*for the descriptions. StorageStats: usegetStateValuesVariationStats()/getStateDescriptionVariationStats()and the new constructor.- Augmentation: the content filter of
AugmentationFunctionContextRequestis aDigitalTwinStateFilterset withwithStateFilter(...); a customAugmentationFunctionHandlerreceives inonEventNotificationReceived(functions, notification)only the functions that observe the event notifications and accept the event: remove the code that repeats the filters.DigitalTwinStateFilterUtilsdoes not exist: use the methods of the context request (shouldTrigger,acceptsEventNotification,filterValues). - State classes: the classification of the changes is in
DigitalTwinStateChange(isDescriptionChange(),isValueChange(),descriptionChanges(list),valueChanges(list));DigitalTwinStateValues.applyUpdate(delta)takes only the delta. - Monitoring: the values updates dispatched to a function are
af_function_state_update_*; addaf_function_state_description_update_*for the descriptions. - 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).