10Duke Scale C++ SDK
Loading...
Searching...
No Matches
Heartbeat licenses

A checked-out license lease is valid for a limited time. To keep using the license, the application must heartbeat the lease before the lease expires. This page explains when a lease can be heartbeat, how the client behaves when a lease is not yet due, and what is the recommended pattern for heartbeating leases in an application.

See also client concepts, identity-based licensing and license key licensing.

The heartbeat window

Each lease (tenduke::se::licensing::Lease) carries two timestamps, both in epoch seconds, which together define the window in which the lease can be heartbeat:

  • heartbeatNotBeforeEpochS ("hbnbf" claim of the license token): The earliest time when the lease can be heartbeat. The server sets this value on checkout and on every successful heartbeat, and the server rejects heartbeats sent before this time. If the license token has no "hbnbf" claim, the lease can be heartbeat at any time.
  • expiresEpochS ("exp" claim of the license token): The time when the lease expires. A lease that has expired can no longer be heartbeat: The license must be checked out again.

In other words, a lease must be heartbeat after heartbeatNotBeforeEpochS but before expiresEpochS. A lease that was just checked out or just heartbeat is typically not yet due for heartbeat.

How the client handles leases that are not yet due

The heartbeat methods of tenduke::se::licensing::LicensingClient check every lease against heartbeatNotBeforeEpochS before sending anything to the server. How a lease that is not yet due is handled depends on the skipLeasesNotDue setting.

Skipping (default)

By default, leases that are not yet due are skipped:

  • The skipped leases are not sent to the server
  • The skipped leases are returned, unchanged, in tenduke::se::licensing::LicenseHeartbeatResponse::notDue
  • The skipped leases stay in the lease cache with their current lease id
  • The rest of the leases are heartbeat normally
  • If none of the leases is due, no request is sent to the server at all

Skipped leases are not errors: hasErrors() does not consider them. Use hasNotDue() to check if any leases were skipped.

A heartbeat response therefore has three parts, and the application should handle all of them:

Field Contents Lease id Lease cache
leases Successfully heartbeat leases New lease id (oldLeaseId holds the previous one) Updated with the new leases
errors Leases that the server failed to heartbeat - Depending on the error, the lease may be removed (see below)
notDue Leases that were skipped, because they were not due Unchanged Unchanged

Strict mode

If skipping is disabled, a lease that is not yet due causes tenduke::se::licensing::HeartbeatTooSoon to be thrown. The check is done before anything is sent to the server: A single lease that is not yet due cancels the entire batch, and none of the leases is heartbeat.

To use strict mode with the fluent API:

auto heartbeatResponse = tendukeClient->licensing->heartbeatLicenses()
.skipLeasesNotDue(false)
.leases(leases)
.execute();

or, with parameters:

auto heartbeatResponse = tendukeClient->licensing->heartbeatLicenses(
::tenduke::se::licensing::LicenseHeartbeatParameters(arguments, false)
);

Strict mode is useful when the application wants to treat an early heartbeat as a programming error. For most applications, the default skipping behavior is more convenient.

Clock-skew tolerance

The client compares heartbeatNotBeforeEpochS, which is set by the server, with the local clock of the device. To compensate for small clock differences between the device and the server, the client applies a tolerance: A lease is considered due if heartbeatNotBeforeEpochS - tolerance <= now. The default tolerance is 5 seconds (tenduke::se::licensing::DefaultLicensingClient::DEFAULT_HEARTBEAT_TOLERANCE_S).

The tolerance only helps with small differences. If the device clock is significantly off, the client may skip leases that the server would accept (clock behind), or send heartbeats that the server rejects (clock ahead). A heartbeat rejected by the server is reported in errors like any other heartbeat failure.

Preparing the application

Always continue with the leases returned by the latest operation

A successful heartbeat changes the lease id. Heartbeating or releasing a lease with an old lease id fails. The simplest way to always have current leases is to not keep leases in the application at all and read them from the lease cache (tenduke::se::licensing::Leases) when needed:

auto currentLeases = tendukeClient->leases->getAllLeases();

If the application keeps its own copy of the leases, it must combine leases and notDue from the heartbeat response. For example, to release everything after a heartbeat:

auto releaseResponse = tendukeClient->licensing->releaseLicenses()
.leases(heartbeatResponse.leases)
.leases(heartbeatResponse.notDue) // skipped leases keep their lease id
.execute();

Releasing only heartbeatResponse.leases would leave the skipped leases checked out.

Ask the cache which leases are due

The lease cache can tell which leases are due for heartbeat right now:

auto dueLeases = tendukeClient->leases->getLeasesDueForHeartbeat();

The method returns the leases that are within their heartbeat window: The heartbeat window has been reached and the lease has not expired. This is useful, for example, for deciding whether there is anything to heartbeat, for showing the state of the leases in the user interface, or for picking the leases to heartbeat in strict mode.

The cache also tells when the next lease becomes due:

auto nextDueEpochS = tendukeClient->leases->getNextHeartbeatDueEpochS();

This is the earliest heartbeatNotBeforeEpochS of the leases that have not expired, and it is the natural point in time to schedule the next heartbeat. The value is in the past, if some lease is already due. If the cache has no leases that can be heartbeat, the method returns tenduke::se::licensing::Leases::NO_HEARTBEAT_DUE_EPOCH_S_MAGIC.

Note that the cache does not apply the clock-skew tolerance that the licensing client applies, so the client may accept a lease a few seconds before the cache reports it as due.

Don't heartbeat right after checkout

A lease that was just checked out is not due for heartbeat. With the default settings, heartbeating it just returns the lease in notDue, which is harmless but useless. Schedule the first heartbeat based on heartbeatNotBeforeEpochS of the checked-out leases instead (see the recommended patternthe recommended pattern below).

Handle heartbeat errors

Some heartbeat errors mean that the lease can no longer be used, for example when the checkout has expired (licenseCheckoutExpired) or the server no longer knows the lease (leaseIdNotFound). The client removes such leases from the lease cache automatically. The application should react to these errors, typically by checking out the license again or by disabling the licensed functionality.

Handle network failures

Networking failures are reported as exceptions (see errors in client concepts), and the client has no built-in retry logic. If a heartbeat fails because of a temporary network issue, the leases in the cache are unchanged, and the application can retry. The retry must happen before the leases expire.

Metered leases

Metered leases are heartbeat with the same methods, and the same rules apply. Note that the usage quantity given for a skipped lease is not reported to the server:

  • If the application reports absolute quantities (the default, treatAsIncrementalQty = false), nothing is lost: The next heartbeat reports the up-to-date absolute quantity.
  • If the application reports incremental quantities (treatAsIncrementalQty = true), the application must keep track of the usage of skipped leases and add it to the next heartbeat of that lease. Otherwise the usage is lost.

Save the client state

The lease ids change on every successful heartbeat. As recommended in client concepts, serialize the client state after heartbeat, so that the stored state has the current lease ids if the application terminates unexpectedly.

Recommended pattern

The recommended pattern is a single background task that heartbeats all leases in the cache and schedules itself based on the heartbeat window of the leases:

  1. Heartbeat all leases in the lease cache (getAllLeases()). Let the client skip the leases that are not yet due. In strict mode, heartbeat getLeasesDueForHeartbeat() instead.
  2. Handle the response: React to errors (the lease cache has already been updated) and save the client state.
  3. Ask the cache when the next lease becomes due (getNextHeartbeatDueEpochS()).
  4. Sleep until that time and repeat. Stop when the cache is empty.
  5. If the heartbeat fails with a network exception, retry after a delay (for example, with exponential backoff), but only while the leases have not expired.

This pattern has several benefits:

  • Leases are heartbeat as soon as they are due, which leaves as much time as possible for retries before the leases expire
  • The application doesn't poll: It wakes up only when there is something to heartbeat
  • Leases with different heartbeat windows are handled naturally: Each round heartbeats the leases that are due and skips the rest
  • Leases checked out while the task is sleeping are picked up automatically on the next round. If a newly checked out lease may become due before the current wake-up time, wake the task up after the checkout.

Example:

#include <algorithm>
#include <chrono>
#include <cstdint>
#include <thread>
static std::int64_t nowEpochS()
{
return std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
}
void heartbeatLoop(const std::shared_ptr<::tenduke::se::TendukeClient> &tendukeClient)
{
std::int64_t retryDelayS = 5;
while (true) {
auto leases = tendukeClient->leases->getAllLeases();
if (leases.empty()) {
break; // Nothing to heartbeat
}
try {
// Leases not yet due are skipped and returned in `notDue`
auto response = tendukeClient->licensing->heartbeatLicenses()
.leases(leases)
.execute();
if (response.hasErrors()) {
// Handle errors: e.g. check out again or disable licensed functionality.
// Leases that can no longer be used have already been removed from the cache.
}
// Lease ids have changed: Store the state (encrypted with authenticated encryption, see client-concepts.md)
saveState(tendukeClient->serializeState());
retryDelayS = 5;
}
catch (const ::tenduke::net::NetworkingException &e) {
// Temporary network issue: The cache is unchanged, retry later. Stop retrying (and e.g. disable
// the licensed functionality) when the leases have expired.
std::this_thread::sleep_for(std::chrono::seconds(retryDelayS));
retryDelayS = std::min<std::int64_t>(retryDelayS * 2, 300);
continue;
}
// Sleep until the next lease becomes due
auto nextDue = tendukeClient->leases->getNextHeartbeatDueEpochS();
if (nextDue == ::tenduke::se::licensing::Leases::NO_HEARTBEAT_DUE_EPOCH_S_MAGIC) {
break; // Nothing left to heartbeat
}
// Minimum sleep avoids a busy loop if a lease stays due, e.g. when the server keeps rejecting it
auto sleepS = std::max<std::int64_t>(nextDue - nowEpochS(), 10);
std::this_thread::sleep_for(std::chrono::seconds(sleepS));
}
}

In a real application, use a sleep that can be interrupted (for example, a condition variable with a timeout), so that the task can be woken up after a new checkout and stopped cleanly when the application exits. Stop the task before releasing the licenses on application exit.