partitionService is a mock, so an unstubbed getAllServiceIds() returns an
empty set and the known-id tests also passed through the fail-open branch.
Assert that a live member is accepted without consulting getAllServiceIds,
so the tests fail if the isKnownServiceId check is broken.
The recently-seen grace period and fails-open-on-unknown-topology paths
of isUnknownService were only tested for pushNotificationToCore. Mirror
those tests for pushNotificationToRuleEngine and pushNotificationToTransport
so a regression scoped to those service types doesn't slip through.
- Use the new isKnownServiceId() instead of getAllServiceIds().contains(),
avoiding two collection allocations on the common (live member) path.
- Reuse SetCache instead of a hand-rolled Caffeine cache for
recentlySeenServices.
- Drop pushNotificationToTransport's null/empty serviceId guard, now
redundant with isUnknownService() treating null/empty as unknown.
- Track skipped-due-to-unknown-service notifications in a counter and
surface it via the existing periodic stats log, since the point of
this guard is to catch a leak that was previously invisible.
getAllServiceIds() rebuilds two HashSets just to test membership of a
single id - PartitionService#isKnownServiceId scans the live service
lists directly instead, for the hot path in DefaultTbClusterService's
per-notification unknown-service guard. SetCache.boundedBySize() adds
an LRU-by-size variant alongside the existing TTL-based constructor.
The clusterService field is typed as the TbClusterService interface, which
does not declare onServiceListChanged (it is a concrete-class @EventListener).
Cast to DefaultTbClusterService in the recently-seen test so it compiles.
Make the unknown-service-id skip a lenient safety net rather than a
precise gatekeeper. A service id is treated as known if it is either a
current member (PartitionService.getAllServiceIds) OR a recently seen one.
The recently-seen set is a bounded (1024) LRU cache fed from
ServiceListChangedEvent, so a node that is briefly absent from the live
snapshot - discovery-propagation lag, rolling restart, transient
scale-down - still receives its notifications instead of having them
dropped; genuine non-delivery to a node that is actually gone is already
handled by the caller-side RPC/REST timeout. An id gone for good ages out
via LRU eviction and the guard tightens again.
The live-snapshot check stays authoritative for current members (discovery
events are change-only, so a pure recently-seen cache would go cold in a
quiet cluster); recently-seen only widens 'known', it never adds a new
drop. Adds a test for the offline-but-recently-seen path.
Follow the existing pushNotificationToTransport convention: a deliberate
skip to a non-member service id now completes the callback as a no-op
success instead of onFailure, so callers don't treat an intentional skip
as a delivery error. Aligns all three skip paths (core, rule engine,
transport) on one contract.
- Extend the unknown-service-id orphan-topic guard to pushNotificationToTransport
- Make HashPartitionService.currentOtherServices volatile (now read on the
per-notification path, written under the synchronized recalculatePartitions)
- Lower the per-skip log from warn to debug to avoid noise when stale service
ids appear in message metadata during normal operation
- Add tests for the transport guard (unknown skipped, known sent)
Per-service notification topics (<notifications-topic>.<serviceId>) are
auto-created by the Kafka producer on first send. pushNotificationToCore and
pushNotificationToRuleEngine forwarded the target service id as-is. That id may
come from message metadata (e.g. the originServiceId of RPC reply and
integration-downlink flows), so an id that does not belong to the cluster
created an orphan notification topic that no node ever consumes and that is
never cleaned up, growing the topic count without bound.
Validate the target service id against current cluster membership
(PartitionService.getAllServiceIds) before sending; when the id is not a known
TB_CORE / TB_RULE_ENGINE service, skip the push and report delivery failure on
the callback (the message was not delivered, so onFailure is the correct signal
and it also lets a waiting caller complete). The check fails open while the
cluster topology is not yet known (empty membership, e.g. right after startup)
so legitimate notifications are never dropped.
With the entity partitioning strategy, DummyTask.getEntityId() returns a new
random id per task, so the 200 tasks spread over many partitions and run in
parallel. 200 x 50 ms tasks could all finish within the fixed Thread.sleep(500),
so the cancel found nothing left to discard (discardedCount == 0).
Use 30 s tasks (60 s task timeout) so tasks are always in flight when the job
is cancelled, whatever the partitioning strategy, and cancel as soon as the job
is RUNNING. Cancellation interrupts running tasks (TaskProcessor.cancelRunningTasks),
so the test still finishes quickly. One test body covers both strategies.
The server accepts the WebSocket handshake and closes the session right
away when it rejects a pre-verification token in afterConnectionEstablished.
Java-WebSocket's connectBlocking() releases its latch on both open and close
and then returns engine.isOpen(), so it returns false when the client reads
the close frame before the caller checks the state. The asserted connect in
buildAndConnectWebSocketClient then failed.
The test now connects without asserting the connect result, waits for the
close, and asserts the server close code (1011), so it still proves the
token was rejected.
The rule engine stats report runs on a schedule. On its first report for
a tenant it creates a QUEUE_STATS entity, whose SaveEntityEvent becomes
an ADDED sendNotificationMsgToEdge call. When that tick fell between
Mockito.reset and verify, testFindTenantAssets and
testFindAssetTypesByTenantId saw one extra invocation (179 vs 178, 4 vs 3).
Count only entity ids that have an edge event type, which is the same
filter DefaultTbClusterService applies before sending to an edge.
AlarmRuleState included its back-reference to the parent AlarmCalculatedFieldState
in the Lombok-generated hashCode/toString, and the parent includes its rule states,
causing infinite recursion. It surfaced when TenantActor logged a skipped
CalculatedFieldStateRestoreMsg during partition rebalancing, flooding logs with
StackOverflowError traces.
Exclude the parent reference from hashCode/equals/toString and log only the
restore message id instead of the whole state.
* Remove IoT Hub Dashboard item type
The IoT Hub no longer has Dashboard items, so drop the DASHBOARD item type
from the platform: install/update/checksum/delete handling and the
DashboardInstalledItemDescriptor on the backend, and the item type, the
/iot-hub/dashboards page and route, deep links, translations and styles in
the UI. Dashboards created by device packages and solution templates are
not affected.
* Keep DashboardInstalledItemDescriptor for existing installed items
Installed-item rows with a DASHBOARD descriptor may still exist on
instances that were connected to the QA Hub. Without the subtype Jackson
fails on such a row and the whole Installed items page breaks, so keep the
descriptor and the delete branch to let those rows be read and removed.
* Revert "Keep DashboardInstalledItemDescriptor for existing installed items"
This reverts commit 61246776fa. A DASHBOARD installed-item row can only
exist on instances connected to the QA Hub; production and official
releases never had Dashboard items, so the legacy descriptor is not kept.
The enrollment now collects its license key from the portal when the grant is
done, and keeps it in tb_cluster.license_secret. A claim that has nothing to
hand over yet leaves the flow for the next poll; a refused claim ends the flow
registered without a key; a transport failure is left to the existing backoff.
Addresses review feedback on the activity-state guard:
- sessionEdgeEventChecks is keyed by edgeId, so a stale disconnect callback
cancelled the check scheduled by the session that replaced it. The loop only
reschedules from inside the task, so the connected edge stopped receiving
downlinks with nothing to restart it. Cancel only when no live session holds
the edge on this node.
- Document that the EDGE_CONNECTION notification is raised from inside
pushRuleEngineMessage on this branch and is therefore suppressed together
with the DISCONNECT_EVENT.
- Pin the LAST_DISCONNECT_TIME write and the zombie compare-and-remove with
tests, both of which were previously unguarded by the suite.
Follow-ups from review of the activity-state guard:
1. The guard only covered a reconnect landing on a different node. If the
replacement lands on this node while the stale callback is still tearing its
own session down, isOwnedByAnotherNode sees this node's own service id and the
stale active=false is written anyway - the exact state the guard exists to
prevent. Add the local-session check, matching the eviction guard which
already tests for a newer local session.
2. LAST_DISCONNECT_TIME and the DISCONNECT_EVENT push ran unconditionally. The
timestamp would contradict the live session's lastConnectTime, and the event
payload is {"active": false, ...} with SERVER_SCOPE in its metadata - exactly
what a Save Attributes node persists, so a rule chain wiring Disconnect Event
to Save Attributes writes active=false straight back and re-creates the
dropped-event behaviour through the rule engine. Both now sit inside the same
guard. scheduleDisconnectNotification stays outside: it re-verifies liveness
itself before firing.
3. The eviction guard only checked cache ownership, so a replacement on this node
would have its claim evicted by the stale callback. It now also requires that
no live session holds the edge.
4. cleanupZombieSessions removed by edge id unconditionally after destroy(),
which is not instantaneous. If the edge reconnected in that gap the live
session was dropped from 'sessions' while remaining in 'sessionsById', so it
was never torn down but every downlink lookup silently no-opped. Use a
compare-and-remove. removeFunc becomes a Consumer, since its return value was
already discarded.
5. Document that the guard narrows rather than closes the race - the attribute is
last-writer-wins across nodes - and that the dead-owner fallback does not
cover a node restarting under the same service id.
Tests: cover the same-node replacement, the DISCONNECT_EVENT suppression and its
positive counterpart, and pin the onEdgeConnect ownership publish order with an
InOrder assertion, which nothing held before. The rule-engine stubs in the
suppression tests are lenient on purpose: without them the push could never fire
and the never() assertions would pass vacuously.
onEdgeDisconnect persisted active=false based only on this node's in-memory
session map. When an edge drops and reconnects to a different TB-Core node, the
new node sets active=true while the old node writes active=false whenever it
finally notices its dead stream. If the stale write lands last, the edge stays
marked inactive while its gRPC session is alive.
That flag is not only a status indicator: saveEdgeEvent() consults it before
queueing any server-to-edge event, and actions that are not on the offline
allowlist - device and entity-group assignments among them - are dropped
outright rather than queued. A stale active=false therefore makes assignments
silently never reach the edge, with a full "Sync Edge" as the only recovery.
- Guard the write with the cluster-wide service-id cache, skipping it only when
another node is the recorded owner and that node is still a live TB_CORE
service. An absent entry means ownership is unknown, not claimed elsewhere, so
that case still persists the inactive state; and a node that died without
evicting its claim cannot leave the edge marked active forever.
- Publish the ownership claim before writing active=true in onEdgeConnect, so a
disconnect callback on the node the edge just left cannot read a stale owner.
- Only evict the service-id cache entry when it still points at this node.
A stale callback would otherwise wipe the live owner's claim and defeat the
guard above for any later disconnect.
- Remove the session atomically in onEdgeDisconnect. get() and remove() were not
atomic, so a session replaced between the two was dropped from the map, torn
down and marked inactive by the stale callback even though it was the live one.
LAST_DISCONNECT_TIME and the rule-engine DISCONNECT_EVENT are intentionally left
unguarded - they are accurate statements about this session, and the timestamps
are the main diagnostic signal for flapping edges.
Backport of thingsboard/thingsboard#16155 to lts-4.2, which has no disconnect
notification debounce and therefore none of the ownership helpers the 4.3 change
builds on; they are introduced here.
license:format prepends the header it expects without recognising the
block comment the files were created with, so both new files carried the
license twice. They now have only the two SPDX lines, the same as every
other file that this repository shares with CE.
license:format prepends the header it expects without recognising the
block comment the files were created with, so both new files carried the
license twice. They now have only the two SPDX lines, the same as every
other file that this repository shares with CE.
The base switched every header to the SPDX form yesterday, so the files
this branch adds were the only ones left with the old block comment and
license:check failed on them once the base was merged in.
The base switched every header to the SPDX form yesterday, so the files
this branch adds were the only ones left with the old block comment and
license:check failed on them once the base was merged in.