From 50e265c5db1b01292da65a48842e2f60ca2339a3 Mon Sep 17 00:00:00 2001 From: turtledreams <62231246+turtledreams@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:29:35 +0900 Subject: [PATCH 1/2] Ask for content right after a content trigger The behavior settings request asks for the content triggers (jt=1). When the app records something they list while the content zone is entered, the SDK sends the queued requests and asks for content, up to 3 times 1 second apart, with a 10 or 60 second gap per trigger kept in storage. The journey trigger events and views go through the same path while the server sends no content triggers, and the enter content zone setting now only decides the entry at init. --- CHANGELOG.md | 6 +- sdk-java/api/sdk-java.txt | 9 + .../sdk/java/internal/ConfigContent.java | 14 + .../java/internal/ConfigurationProvider.java | 8 + .../sdk/java/internal/ContentTriggers.java | 346 +++++++++++++ .../java/internal/ModuleConfiguration.java | 66 ++- .../sdk/java/internal/ModuleContent.java | 477 +++++++++++++++--- .../sdk/java/internal/ModuleCrashes.java | 9 +- .../count/sdk/java/internal/ModuleEvents.java | 184 +++---- .../sdk/java/internal/ModuleRequests.java | 45 +- .../sdk/java/internal/ModuleUserProfile.java | 37 +- .../count/sdk/java/internal/ModuleViews.java | 10 + .../count/sdk/java/internal/SDKStorage.java | 15 + .../sdk/java/internal/StorageProvider.java | 14 + .../ModuleConfigurationContentTests.java | 305 +++++------ .../ModuleConfigurationLimitsTests.java | 33 +- .../ModuleConfigurationNetworkTests.java | 72 --- .../internal/ModuleConfigurationTests.java | 3 +- .../java/internal/ModuleHealthCheckTests.java | 7 + 19 files changed, 1158 insertions(+), 502 deletions(-) create mode 100644 sdk-java/src/main/java/ly/count/sdk/java/internal/ContentTriggers.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 212ebd3e..03f8430d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,8 +32,12 @@ * The consent requirement, applied on the next initialization * SDK internal limits for key length, value size, segmentation value count, stack trace lines per thread, stack trace line length, and breadcrumb count * Listing filters (blacklist/whitelist) for events, segmentation keys, event specific segmentation keys, and user properties, plus a user property cache limit - * Entering, refreshing, and the fetch interval of the content zone, plus Journey Trigger Events and Journey Trigger Views that refresh it + * Entering the content zone at initialization, refreshing it, and its fetch interval, plus Journey Trigger Events and Journey Trigger Views, which ask for content right away while the server sends no content triggers * Dropping requests older than a given age +* Added content triggers. When the application records something that starts a journey or a campaign with content, the SDK sends the queued requests and asks for that content right away, instead of waiting for the content zone timer: + * The triggers are events, the start or the end of a view, a new session, a user property and a recorded exception. + * The server lists them in its SDK behavior settings answer, and they apply while the content zone is entered. + * Call "disableAutoContentTriggers()" on the content config to turn them off. * Added "setSdkBehaviorSettings(String)" init config method for providing SDK behavior settings at initialization. * Added "disableSdkBehaviorSettingsUpdates()" init config method for disabling SDK behavior settings requests. * Improved request queue handling with a built-in backoff mechanism which is enabled by default. When the server takes 10 seconds or longer to answer while few requests are queued, the SDK pauses sending for 60 seconds. diff --git a/sdk-java/api/sdk-java.txt b/sdk-java/api/sdk-java.txt index 0aec5f02..9bea4013 100644 --- a/sdk-java/api/sdk-java.txt +++ b/sdk-java/api/sdk-java.txt @@ -394,9 +394,11 @@ package ly.count.sdk.java.internal { public class ConfigContent { ctor public ConfigContent(ly.count.sdk.java.Config!); + method public ly.count.sdk.java.Config! disableAutoContentTriggers(); method public ly.count.sdk.java.Config! setContentUrlHandler(ly.count.sdk.java.internal.ContentUrlHandler!); method public ly.count.sdk.java.Config! setGlobalContentCallback(ly.count.sdk.java.internal.ContentCallback!); method public ly.count.sdk.java.Config! setZoneTimerInterval(int); + field protected boolean autoContentTriggersDisabled; field protected ly.count.sdk.java.internal.ContentUrlHandler! contentUrlHandler; field protected ly.count.sdk.java.internal.ContentCallback! globalContentCallback; field protected int zoneTimerInterval; @@ -419,6 +421,7 @@ package ly.count.sdk.java.internal { method public double getBOMRQPercentage(); method public int getBOMRequestAge(); method public boolean getConsentRequired(); + method public ly.count.sdk.java.internal.ContentTriggers? getContentTriggers(); method public boolean getContentZoneEnabled(); method public int getContentZoneTimerInterval(); method public boolean getCrashReportingEnabled(); @@ -827,6 +830,7 @@ package ly.count.sdk.java.internal { method public double getBOMRQPercentage(); method public int getBOMRequestAge(); method public boolean getConsentRequired(); + method public ly.count.sdk.java.internal.ContentTriggers? getContentTriggers(); method public boolean getContentZoneEnabled(); method public int getContentZoneTimerInterval(); method public boolean getCrashReportingEnabled(); @@ -1248,6 +1252,7 @@ package ly.count.sdk.java.internal { public class SDKStorage implements ly.count.sdk.java.internal.StorageProvider { ctor protected SDKStorage(); + method public String! getContentTriggerGaps(); method public String! getDeviceID(); method public String! getDeviceIdType(); method public String! getHealthCheckState(); @@ -1258,6 +1263,7 @@ package ly.count.sdk.java.internal { method public ly.count.sdk.java.internal.SDKStorage! init(ly.count.sdk.java.internal.InternalConfig!); method public boolean isCountlyStorageEmpty(); method protected String! readEventQueue(); + method public void setContentTriggerGaps(String!); method public void setDeviceID(String!); method public void setDeviceIdType(String!); method public void setHealthCheckState(String!); @@ -1281,6 +1287,7 @@ package ly.count.sdk.java.internal { field protected static final String FILE_NAME_PREFIX = "[CLY]"; field protected static final String FILE_NAME_SEPARATOR = "_"; field protected static final String JSON_FILE_NAME = "countly_store.json"; + field protected static final String key_content_trigger_gaps = "CONTENT_TRIGGER_GAPS"; field protected static final String key_device_id = "did"; field protected static final String key_device_id_type = "did_t"; field protected static final String key_health_check = "HEALTH_CHECK"; @@ -1365,6 +1372,7 @@ package ly.count.sdk.java.internal { } public interface StorageProvider { + method public String! getContentTriggerGaps(); method public String! getDeviceID(); method public String! getDeviceIdType(); method public String! getHealthCheckState(); @@ -1373,6 +1381,7 @@ package ly.count.sdk.java.internal { method public String! getServerConfig(); method public void incrementAutomaticCrashCount(); method public boolean isCountlyStorageEmpty(); + method public void setContentTriggerGaps(String!); method public void setDeviceID(String!); method public void setDeviceIdType(String!); method public void setHealthCheckState(String!); diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ConfigContent.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ConfigContent.java index d13fb210..3f443e92 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ConfigContent.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ConfigContent.java @@ -16,6 +16,7 @@ public class ConfigContent { protected int zoneTimerInterval = DEFAULT_ZONE_TIMER_INTERVAL; protected ContentCallback globalContentCallback = null; protected ContentUrlHandler contentUrlHandler = null; + protected boolean autoContentTriggersDisabled = false; public ConfigContent(Config config) { this.config = config; @@ -63,4 +64,17 @@ public synchronized Config setGlobalContentCallback(ContentCallback callback) { this.globalContentCallback = callback; return config; } + + /** + * Turn off the content triggers: the SDK does not ask the server for them and does not follow + * the ones it has, so content comes only with the content zone timer, as before. The journey + * trigger events and views of the SDK behavior settings still apply. + * + * @return the same config object for convenient linking + * @apiNote This is an EXPERIMENTAL feature, and it can have breaking changes + */ + public synchronized Config disableAutoContentTriggers() { + this.autoContentTriggersDisabled = true; + return config; + } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ConfigurationProvider.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ConfigurationProvider.java index 9845a302..970aac01 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ConfigurationProvider.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ConfigurationProvider.java @@ -297,6 +297,14 @@ public interface ConfigurationProvider { */ @Nonnull Set getJourneyTriggerViews(); + /** + * Key {@code jt}, next to the settings. + * + * @return the content triggers the server sent, {@code null} when it sent none or an invalid + * value, or when content triggers are turned off, so the journey trigger events and views apply + */ + @Nullable ContentTriggers getContentTriggers(); + /** * Whether a request body may be sent gzip-compressed now: the developer turned request * compression on, the current server said in its SDK behavior settings answer that it reads diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ContentTriggers.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ContentTriggers.java new file mode 100644 index 00000000..9268537f --- /dev/null +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ContentTriggers.java @@ -0,0 +1,346 @@ +package ly.count.sdk.java.internal; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * The content triggers ("jt") the server sends next to the SDK behavior settings ("c"): what the SDK records that makes + * it send what it holds and ask for content right away, instead of waiting for the content zone timer. + *

+ * "jt": {"e": ["purchase", "[CLY]_session"], "v": ["Checkout"], "p": ["custom.plan"]} + *

+ * "e" holds event keys, and the keys of what the SDK records besides events, "v" holds view names and "p" holds user + * properties. A list the server leaves out is an empty one. + */ +final class ContentTriggers { + static final String KEY_SESSION = "[CLY]_session"; + static final String KEY_USER_PROPERTIES = "[CLY]_property_update"; + static final String KEY_CRASH = "[CLY]_crash"; + static final String KEY_CONSENT = "[CLY]_consent"; + + /** Least time before the same trigger starts another round, for a listed event key, view name or user property */ + static final long GAP_SPECIFIC_MS = 10_000; + /** Least time before the same trigger starts another round, for any view, any user property or any error */ + static final long GAP_NON_SPECIFIC_MS = 60_000; + + private static final String LIST_KEYS = "e"; + private static final String LIST_VIEWS = "v"; + private static final String LIST_PROPERTIES = "p"; + private static final String GAP_KEY_VIEW_PREFIX = "v:"; + private static final String GAP_KEY_PROPERTY_PREFIX = "p:"; + private static final String GAP_KEY_VIEW_END_SUFFIX = ":end"; + + @Nonnull final Set keys; + @Nonnull final Set views; + @Nonnull final Set properties; + + private ContentTriggers(@Nonnull Set keys, @Nonnull Set views, @Nonnull Set properties) { + this.keys = Collections.unmodifiableSet(keys); + this.views = Collections.unmodifiableSet(views); + this.properties = Collections.unmodifiableSet(properties); + } + + /** + * Reads the "jt" value of a behavior settings answer + * + * @param value the "jt" value, null when the answer has none + * @param L logger + * @return the content triggers, or null when the answer has none or has an invalid value, so that the journey + * trigger events and views apply + */ + @Nullable + static ContentTriggers parse(@Nullable Object value, @Nonnull Log L) { + if (value == null) { + return null; + } + if (!(value instanceof JSONObject)) { + L.w("[ContentTriggers] parse, content triggers (jt) must be an object, ignoring them: [" + value + "]"); + return null; + } + JSONObject object = (JSONObject) value; + return new ContentTriggers(readList(object, LIST_KEYS, L), readList(object, LIST_VIEWS, L), readList(object, LIST_PROPERTIES, L)); + } + + /** + * Reads one list of the "jt" object: its non-empty strings + * + * @param object the "jt" object + * @param name list name, "e", "v" or "p" + * @param L logger + * @return the values, empty when the list is missing or is not an array + */ + @Nonnull + private static Set readList(@Nonnull JSONObject object, @Nonnull String name, @Nonnull Log L) { + Set values = new HashSet<>(); + if (!object.has(name)) { + return values; + } + JSONArray array = object.optJSONArray(name); + if (array == null) { + L.w("[ContentTriggers] readList, content triggers (jt) list [" + name + "] must be an array, ignoring it"); + return values; + } + for (int i = 0; i < array.length(); i++) { + Object item = array.opt(i); + if (item instanceof String && !((String) item).isEmpty()) { + values.add((String) item); + } + } + return values; + } + + /** + * Something the SDK recorded, as content triggers compare it + */ + static final class Trigger { + @Nonnull final String key; + @Nullable final String viewName; + final boolean viewEnd; + @Nullable final List properties; + final boolean customEvent; + + private Trigger(@Nonnull String key, @Nullable String viewName, boolean viewEnd, @Nullable List properties, boolean customEvent) { + this.key = key; + this.viewName = viewName; + this.viewEnd = viewEnd; + this.properties = properties; + this.customEvent = customEvent; + } + + /** + * @param key the event key, as the app passed it + * @param customEvent true for an event of the app, false for one the SDK records itself + * @return the trigger of a recorded event + */ + @Nonnull + static Trigger event(@Nonnull String key, boolean customEvent) { + return new Trigger(key, null, false, null, customEvent); + } + + /** + * @param viewName the view name, as the app passed it + * @param viewEnd false for the event recorded when the view starts, true for the one recorded when it ends + * @return the trigger of a recorded view event + */ + @Nonnull + static Trigger view(@Nonnull String viewName, boolean viewEnd) { + return new Trigger(ModuleViews.KEY_VIEW_EVENT, viewName, viewEnd, null, false); + } + + /** + * @param properties the user properties the request sends: a user detail ("email"), or "custom." and the key + * of a custom property + * @return the trigger of sent user properties + */ + @Nonnull + static Trigger userProperties(@Nonnull List properties) { + return new Trigger(KEY_USER_PROPERTIES, null, false, properties, false); + } + + /** + * @param key one of {@link #KEY_SESSION}, {@link #KEY_CRASH} or {@link #KEY_CONSENT} + * @return the trigger of what the SDK records besides events + */ + @Nonnull + static Trigger of(@Nonnull String key) { + return new Trigger(key, null, false, null, false); + } + + /** + * @param other another trigger + * @return true when both stand for the same thing recorded + */ + boolean sameAs(@Nonnull Trigger other) { + return key.equals(other.key) && viewEnd == other.viewEnd && customEvent == other.customEvent + && (viewName == null ? other.viewName == null : viewName.equals(other.viewName)) + && (properties == null ? other.properties == null : properties.equals(other.properties)); + } + + /** + * @return true for a view event + */ + boolean isView() { + return ModuleViews.KEY_VIEW_EVENT.equals(key); + } + + /** + * @return what a gap key of a view event ends with: nothing for the event recorded when the view starts, and + * a suffix for the one recorded when it ends, so that each has its own gap + */ + @Nonnull String gapKeySuffix() { + return isView() && viewEnd ? GAP_KEY_VIEW_END_SUFFIX : ""; + } + + @Nonnull @Override public String toString() { + return key + (viewName != null ? " [" + viewName + (viewEnd ? ", end" : ", start") + "]" : "") + (properties != null ? " " + properties : ""); + } + } + + /** + * A recorded trigger that starts a round: the triggers its gap is kept for, and the gap + */ + static final class Match { + @Nonnull final List gapKeys; + final long gapMs; + + Match(@Nonnull List gapKeys, long gapMs) { + this.gapKeys = gapKeys; + this.gapMs = gapMs; + } + } + + /** + * Whether what was recorded is a content trigger. When the server sent content triggers, only they decide, and + * only while the app wants the content zone. Otherwise (an older server, or disableAutoContentTriggers) a custom + * event key in the journey trigger events and a view name in the journey trigger views decide, also while the app + * doesn't want the content zone. + * + * @param contentTriggers the content triggers in use, null when there are none + * @param zoneWanted true after the app or the "ecz" setting entered the content zone, until it is exited + * @param journeyTriggerEvents the journey trigger events ("jte") + * @param journeyTriggerViews the journey trigger views ("jtv") + * @param trigger what was recorded + * @return the match, or null when it is not a content trigger + */ + @Nullable + static Match match(@Nullable ContentTriggers contentTriggers, boolean zoneWanted, @Nonnull Set journeyTriggerEvents, @Nonnull Set journeyTriggerViews, + @Nonnull Trigger trigger) { + if (contentTriggers != null) { + return zoneWanted ? contentTriggers.matchLists(trigger) : null; + } + return matchJourneyTriggers(journeyTriggerEvents, journeyTriggerViews, trigger); + } + + /** + * The match against these content triggers: a listed view name, then listed user properties, then a listed key + * + * @param trigger what was recorded + * @return the match, or null when none of the lists has it + */ + @Nullable + private Match matchLists(@Nonnull Trigger trigger) { + if (trigger.isView() && trigger.viewName != null && views.contains(trigger.viewName)) { + return viewMatch(trigger); + } + List propertyGapKeys = listedPropertyGapKeys(trigger); + if (!propertyGapKeys.isEmpty()) { + return new Match(propertyGapKeys, GAP_SPECIFIC_MS); + } + if (!keys.contains(trigger.key)) { + return null; + } + boolean nonSpecific = trigger.isView() || KEY_USER_PROPERTIES.equals(trigger.key) || KEY_CRASH.equals(trigger.key); + return new Match(Collections.singletonList(trigger.key + trigger.gapKeySuffix()), nonSpecific ? GAP_NON_SPECIFIC_MS : GAP_SPECIFIC_MS); + } + + /** + * @param trigger what was recorded + * @return the gap keys of the sent user properties that the "p" list has, empty for any other trigger + */ + @Nonnull + private List listedPropertyGapKeys(@Nonnull Trigger trigger) { + List gapKeys = new ArrayList<>(); + if (KEY_USER_PROPERTIES.equals(trigger.key) && trigger.properties != null) { + for (String property : trigger.properties) { + if (properties.contains(property)) { + gapKeys.add(GAP_KEY_PROPERTY_PREFIX + property); + } + } + } + return gapKeys; + } + + /** + * The match against the deprecated journey trigger events and views: custom events, and both events of a view + * + * @param journeyTriggerEvents the journey trigger events ("jte") + * @param journeyTriggerViews the journey trigger views ("jtv") + * @param trigger what was recorded + * @return the match, or null when it is not a journey trigger + */ + @Nullable + private static Match matchJourneyTriggers(@Nonnull Set journeyTriggerEvents, @Nonnull Set journeyTriggerViews, @Nonnull Trigger trigger) { + if (trigger.isView()) { + return trigger.viewName != null && journeyTriggerViews.contains(trigger.viewName) ? viewMatch(trigger) : null; + } + return trigger.customEvent && journeyTriggerEvents.contains(trigger.key) ? new Match(Collections.singletonList(trigger.key), GAP_SPECIFIC_MS) : null; + } + + /** + * @param trigger a view event with a listed name + * @return the match of that view event, with a gap of its own for the start and for the end of the view + */ + @Nonnull + private static Match viewMatch(@Nonnull Trigger trigger) { + return new Match(Collections.singletonList(GAP_KEY_VIEW_PREFIX + trigger.viewName + trigger.gapKeySuffix()), GAP_SPECIFIC_MS); + } + + /** + * Whether a matched trigger may start a round now. When it may, the time of the round is kept in storage, so the + * gap holds after a restart. Times older than the longest gap are dropped, and a time in the future is ignored. + * + * @param match the matched trigger + * @param storedGaps the stored times, a JSON object of gap key to milliseconds, may be empty + * @param nowMs the current time in milliseconds + * @return the times to store when the trigger may start a round, or null when every one of its triggers is inside its gap + */ + @Nullable + static String claimGap(@Nonnull Match match, @Nonnull String storedGaps, long nowMs) { + JSONObject times; + try { + times = storedGaps.isEmpty() ? new JSONObject() : new JSONObject(storedGaps); + } catch (JSONException e) { + times = new JSONObject(); + } + + boolean allInGap = true; + for (String gapKey : match.gapKeys) { + if (!inGap(times.optLong(gapKey, -1), nowMs, match.gapMs)) { + allInGap = false; + break; + } + } + if (allInGap) { + return null; + } + + JSONObject kept = new JSONObject(); + Iterator storedKeys = times.keys(); + while (storedKeys.hasNext()) { + String gapKey = storedKeys.next(); + long time = times.optLong(gapKey, -1); + if (inGap(time, nowMs, GAP_NON_SPECIFIC_MS)) { + try { + kept.put(gapKey, time); + } catch (JSONException ignored) { + } + } + } + for (String gapKey : match.gapKeys) { + try { + kept.put(gapKey, nowMs); + } catch (JSONException ignored) { + } + } + return kept.toString(); + } + + /** + * @param timeMs time of the trigger's last round, -1 when it has none + * @param nowMs the current time + * @param gapMs the gap + * @return true when the time is inside the gap + */ + private static boolean inGap(long timeMs, long nowMs, long gapMs) { + return timeMs >= 0 && nowMs >= timeMs && nowMs - timeMs < gapMs; + } +} diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleConfiguration.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleConfiguration.java index 0bfd5520..727eb72e 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleConfiguration.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleConfiguration.java @@ -85,6 +85,7 @@ public class ModuleConfiguration extends ModuleBase implements ConfigurationProv static final String keyREventSegmentationWhitelist = "esw"; static final String keyRJourneyTriggerEvents = "jte"; static final String keyRJourneyTriggerViews = "jtv"; + static final String keyRContentTriggers = "jt"; static final String keyLGEnabled = "e"; static final String keyLGId = "i"; @@ -170,6 +171,17 @@ public class ModuleConfiguration extends ModuleBase implements ConfigurationProv volatile Set currentVJourneyTriggerEvents = Collections.emptySet(); volatile Set currentVJourneyTriggerViews = Collections.emptySet(); volatile LogGatheringDirective currentVLogGathering = LogGatheringDirective.UNDECIDED; + final AtomicReference currentVContentTriggers = new AtomicReference<>(null); + /** + * Whether the SDK neither asks for the content triggers nor follows them, from + * {@link ConfigContent#disableAutoContentTriggers()}. + */ + boolean autoContentTriggersDisabled = false; + /** + * Whether settings were stored or provided at init. Without them the first settings answer of + * the run decides whether the content zone is entered. + */ + boolean behaviorSettingsStoredAtInit = false; /** * Runs the connection test that a live settings response asks for with its {@code ct} flag. @@ -239,7 +251,8 @@ public void init(InternalConfig config) { boolean backendMode = config.isBackendModeEnabled(); serverConfigRequestsDisabled = backendMode || config.isSdkBehaviorSettingsRequestsDisabled(); requestCompressionEnabled.set(config.isRequestCompressionEnabled()); - L.d("[ModuleConfiguration] init, backend mode:[" + backendMode + "], server config requests disabled:[" + serverConfigRequestsDisabled + "]"); + autoContentTriggersDisabled = config.content.autoContentTriggersDisabled; + L.d("[ModuleConfiguration] init, backend mode:[" + backendMode + "], server config requests disabled:[" + serverConfigRequestsDisabled + "], content triggers disabled:[" + autoContentTriggersDisabled + "]"); seedFromDeveloperConfig(config); developerValues = developerDefaults(config); @@ -265,6 +278,7 @@ public void init(InternalConfig config) { public void initFinished(@Nonnull InternalConfig config) { L.d("[ModuleConfiguration] initFinished"); if (serverConfigRequestsDisabled) { + notifyBehaviorSettingsSettled(false); return; } @@ -324,7 +338,7 @@ void loadConfigFromStorage(@Nullable String sdkBehaviorSettings) { } try { - saveAndStoreDownloadedConfig(new JSONObject(sConfig)); + behaviorSettingsStoredAtInit = saveAndStoreDownloadedConfig(new JSONObject(sConfig)); } catch (JSONException e) { L.w("[ModuleConfiguration] loadConfigFromStorage, failed to parse, " + e); } @@ -472,22 +486,23 @@ private static boolean isFraction(@Nullable Object value) { /** * Validates a configuration and replaces the stored settings with its settings, so a setting it - * does not carry is no longer stored. Only {@code v}, {@code t} and {@code c} are stored, so the - * log gathering directive and the connection test flag never are. An invalid configuration - * leaves the stored settings as they are. + * does not carry is no longer stored. Only {@code v}, {@code t}, {@code c} and the content + * triggers {@code jt} are stored, so the log gathering directive and the connection test flag + * never are. An invalid configuration leaves the stored settings as they are. * * @param config a configuration as the server sends it + * @return whether the configuration was valid and is now stored */ - synchronized void saveAndStoreDownloadedConfig(@Nonnull JSONObject config) { + synchronized boolean saveAndStoreDownloadedConfig(@Nonnull JSONObject config) { L.v("[ModuleConfiguration] saveAndStoreDownloadedConfig"); if (!validateServerConfig(config)) { L.w("[ModuleConfiguration] saveAndStoreDownloadedConfig, retrieved configuration is not valid, ignoring it"); - return; + return false; } List notStoredTopLevelKeys = new ArrayList<>(); for (String key : config.keySet()) { - if (!keyRVersion.equals(key) && !keyRTimestamp.equals(key) && !keyRConfig.equals(key)) { + if (!keyRVersion.equals(key) && !keyRTimestamp.equals(key) && !keyRConfig.equals(key) && !keyRContentTriggers.equals(key)) { notStoredTopLevelKeys.add(key); } } @@ -497,7 +512,9 @@ synchronized void saveAndStoreDownloadedConfig(@Nonnull JSONObject config) { //validation already removed every value that is not a usable setting, so the settings object is kept as it is latestRetrievedConfiguration = config.optJSONObject(keyRConfig); - internalConfig.storageProvider.setServerConfig(new JSONObject(config, keyRVersion, keyRTimestamp, keyRConfig).toString()); + currentVContentTriggers.set(autoContentTriggersDisabled ? null : ContentTriggers.parse(config.opt(keyRContentTriggers), L)); + internalConfig.storageProvider.setServerConfig(new JSONObject(config, keyRVersion, keyRTimestamp, keyRConfig, keyRContentTriggers).toString()); + return true; } /** @@ -898,12 +915,14 @@ void fetchConfigFromServer(@Nonnull InternalConfig config) { if (config.getDeviceId() == null) { L.d("[ModuleConfiguration] fetchConfigFromServer, fetching the configuration is aborted, there is no device ID yet"); decideLogGatheringOffIfUndecided("no device ID, no server response this run"); + notifyBehaviorSettingsSettled(false); return; } if (config.sdk == null || config.sdk.networking == null) { L.w("[ModuleConfiguration] fetchConfigFromServer, fetching the configuration is aborted, networking is not available"); decideLogGatheringOffIfUndecided("networking is not available, no server response this run"); + notifyBehaviorSettingsSettled(false); return; } @@ -912,6 +931,9 @@ void fetchConfigFromServer(@Nonnull InternalConfig config) { if (requestCompressionEnabled.get()) { params.add("gzip", "1"); } + if (!autoContentTriggersDisabled) { + params.add(keyRContentTriggers, "1"); + } String requestData = params.toString(); Transport transport = config.sdk.networking.getTransport(); final long fetchStartNs = System.nanoTime(); @@ -924,6 +946,7 @@ void fetchConfigFromServer(@Nonnull InternalConfig config) { } catch (Exception e) { L.e("[ModuleConfiguration] fetchConfigFromServer, failed to request the configuration, [" + e + "]"); decideLogGatheringOffIfUndecided("the server config request failed"); + notifyBehaviorSettingsSettled(false); } } @@ -948,6 +971,7 @@ private void onServerConfigResponse(@Nonnull InternalConfig config, @Nullable JS if (response == null) { L.w("[ModuleConfiguration] onServerConfigResponse, not possible to retrieve configuration data, probably due to lack of connection to the server"); decideLogGatheringOffIfUndecided("server config fetch failed"); + notifyBehaviorSettingsSettled(false); return; } @@ -969,19 +993,21 @@ private void onServerConfigResponse(@Nonnull InternalConfig config, @Nullable JS } boolean changed; + boolean applied; synchronized (this) { //checked again under the lock stop() takes, so a response racing stop() never writes the store if (!running) { L.d("[ModuleConfiguration] onServerConfigResponse, the SDK was stopped while the response was read, ignoring it"); return; } - saveAndStoreDownloadedConfig(response); + applied = saveAndStoreDownloadedConfig(response); changed = updateConfigVariables(config, response, requestedAfterDeviceIdChanges == deviceIdChangesWithoutMerge); } if (changed && config.sdk != null) { config.sdk.onSdkConfigurationChanged(config); } + notifyBehaviorSettingsSettled(applied); if (connectionTestRequested) { notifyConnectionTestRequested(fetchLatencyMs); @@ -1350,6 +1376,26 @@ public Set getJourneyTriggerViews() { return currentVJourneyTriggerViews; } + @Override + @Nullable + public ContentTriggers getContentTriggers() { + return currentVContentTriggers.get(); + } + + /** + * Tells the content module that the settings answer of this run arrived and was applied, or + * that none will arrive, so it checks again what was recorded before it. + * + * @param answered whether an answer arrived and was applied + */ + private void notifyBehaviorSettingsSettled(boolean answered) { + SDKCore core = SDKCore.instance; + ModuleContent content = core == null ? null : core.module(ModuleContent.class); + if (content != null) { + content.onBehaviorSettingsSettled(answered); + } + } + /** {@inheritDoc} */ @Nonnull @Override diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleContent.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleContent.java index 90721f7b..d2a1a24f 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleContent.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleContent.java @@ -1,9 +1,16 @@ package ly.count.sdk.java.internal; +import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nonnull; import javax.annotation.Nullable; import ly.count.sdk.java.Countly; @@ -39,6 +46,17 @@ public class ModuleContent extends ModuleBase { */ static final int POST_CLOSE_SKIPPED_TICKS = 2; + /** How often a content trigger round checks whether the requests queued before it are sent. */ + static final long TRIGGER_QUEUE_CHECK_MS = 500; + /** How many checks in a row without a sent request end a round without a content request. */ + static final int TRIGGER_QUEUE_CHECKS = 5; + /** How long a round waits before it asks for content again when nothing was shown. */ + static final long TRIGGER_CONTENT_RETRY_MS = 1000; + /** How many content requests a round sends at most. */ + static final int TRIGGER_CONTENT_REQUESTS = 3; + /** How many triggers recorded before the first settings answer of the run are kept. */ + static final int TRIGGER_EARLY_LIMIT = 50; + Content contentInterface = null; ContentDisplay display = null; CountlyTimer contentTimer = null; @@ -50,16 +68,22 @@ public class ModuleContent extends ModuleBase { private boolean fetching = false; private int waitForDelay = 0; private int generation = 0; - /** - * Whether the active zone was entered because the {@code ecz} setting asked for it, so turning - * that setting off leaves it. Guarded by {@link #contentLock}. - */ - private boolean zoneEnteredBySettings = false; - /** - * The {@code ecz} value this module last acted on, so a settings change acts only when that - * value changed. Guarded by {@link #contentLock}. - */ - private boolean contentZoneEnabledApplied = false; + /** The {@code ecz} value of the settings in use at init, which decides the entry at init. */ + private boolean contentZoneEnabledAtInit = false; + /** Whether the {@code ecz} setting decided to enter the zone, which then happens once a display is registered. */ + private final AtomicBoolean settingsAskForZone = new AtomicBoolean(false); + /** Set after the application or the {@code ecz} setting entered the zone, until the zone is left. */ + private final AtomicBoolean contentZoneWanted = new AtomicBoolean(false); + /** Set after the application left the zone, until it enters it again. */ + private final AtomicBoolean contentZoneExited = new AtomicBoolean(false); + /** Set once the settings answer of this run arrived, or once none will arrive. */ + private final AtomicBoolean behaviorSettingsSettled = new AtomicBoolean(false); + /** Runs the content trigger rounds, one task at a time; the fields below are used only on it. */ + private ScheduledExecutorService triggerExecutor = null; + private boolean triggerRoundRunning = false; + private boolean triggerRoundPending = false; + private int contentTriggerChain = 0; + private final List earlyTriggers = new ArrayList<>(); /** * Set once {@link #stop(InternalConfig, boolean)} starts, after which no zone is entered, so no * zone timer outlives the module. Guarded by {@link #contentLock}. @@ -83,55 +107,40 @@ public void init(InternalConfig config) { startedAt = TimeUtils.uniqueTimestampMs(); synchronized (contentLock) { display = config.sdk.contentDisplay; - contentZoneEnabledApplied = config.getConfigurationProvider().getContentZoneEnabled(); } + // the settings in use at init decide the entry, also when an answer arrives before init ends + contentZoneEnabledAtInit = config.getConfigurationProvider().getContentZoneEnabled(); + triggerExecutor = Executors.newSingleThreadScheduledExecutor(runnable -> { + Thread thread = new Thread(runnable, "Countly-content-triggers"); + thread.setDaemon(true); + return thread; + }); } /** - * Enters the content zone when the {@code ecz} setting asks for it. While no display is - * registered the zone is entered once one is. + * Enters the content zone when the {@code ecz} setting of the settings in use at init asks for + * it. While no display is registered the zone is entered once one is. * * @param config configuration of the running SDK */ @Override protected void initFinished(InternalConfig config) { super.initFinished(config); - if (config.getConfigurationProvider().getContentZoneEnabled()) { + if (contentZoneEnabledAtInit) { enterContentZoneForSettings("initFinished"); } } /** - * Applies the content settings a server response changed. A changed {@code czi} restarts the - * timer of an active zone. A changed {@code ecz} enters the zone when it turned on, and when it - * turned off leaves the zone only if this setting entered it: a zone entered through - * {@link Content#enterContentZone()} is left to the application. + * Applies the content settings a server response changed: a changed {@code czi} restarts the + * timer of an active zone. A changed {@code ecz} takes effect at the next init, it never enters + * or leaves the zone of a running SDK. * * @param config configuration of the running SDK */ @Override protected void onSdkConfigurationChanged(InternalConfig config) { - ConfigurationProvider configProvider = config.getConfigurationProvider(); - boolean contentZoneEnabled = configProvider.getContentZoneEnabled(); - boolean contentZoneSettingChanged; - synchronized (contentLock) { - contentZoneSettingChanged = contentZoneEnabled != contentZoneEnabledApplied; - contentZoneEnabledApplied = contentZoneEnabled; - } - - restartZoneTimerIfIntervalChanged(configProvider.getContentZoneTimerInterval()); - - if (!contentZoneSettingChanged) { - return; - } - - if (contentZoneEnabled) { - enterContentZoneForSettings("onSdkConfigurationChanged"); - } else if (exitContentZoneInternal(true, true)) { - L.i("[ModuleContent] onSdkConfigurationChanged, the SDK behavior settings turned the content zone off, left the zone they had entered"); - } else { - L.d("[ModuleContent] onSdkConfigurationChanged, the SDK behavior settings turned the content zone off, no zone they entered is active"); - } + restartZoneTimerIfIntervalChanged(config.getConfigurationProvider().getContentZoneTimerInterval()); } /** @@ -140,6 +149,7 @@ protected void onSdkConfigurationChanged(InternalConfig config) { * @param caller the calling method, for the log */ private void enterContentZoneForSettings(@Nonnull String caller) { + settingsAskForZone.set(true); boolean hasDisplay; synchronized (contentLock) { hasDisplay = display != null; @@ -151,7 +161,7 @@ private void enterContentZoneForSettings(@Nonnull String caller) { } L.d("[ModuleContent] " + caller + ", entering the content zone as the SDK behavior settings ask"); - enterContentZoneInternal(true); + enterContentZoneInternal(); } /** @@ -194,7 +204,13 @@ public void stop(InternalConfig config, boolean clear) { synchronized (contentLock) { stopped = true; } + ScheduledExecutorService executor = triggerExecutor; + triggerExecutor = null; + if (executor != null) { + executor.shutdownNow(); + } super.stop(config, clear); + contentZoneWanted.set(false); exitContentZoneInternal(); display = null; contentInterface = null; @@ -217,6 +233,7 @@ protected void deviceIdChanged(String oldDeviceId, boolean withMerge) { } L.i("[ModuleContent] deviceIdChanged, the device ID changed without merge, leaving the content zone"); + contentZoneWanted.set(false); exitContentZoneInternal(); } @@ -228,24 +245,16 @@ void setContentDisplayInternal(ContentDisplay contentDisplay) { zoneInactive = !zoneActive; } - if (contentDisplay != null && zoneInactive && internalConfig.getConfigurationProvider().getContentZoneEnabled()) { + if (contentDisplay != null && zoneInactive && settingsAskForZone.get()) { enterContentZoneForSettings("setContentDisplayInternal"); } } - void enterContentZoneInternal() { - enterContentZoneInternal(false); - } - /** * Enters the content zone, fetching every {@code czi} seconds. Entering a zone that is already - * active does nothing, except that a call made for the application keeps a zone the settings - * entered active until the application leaves it. - * - * @param bySettings {@code true} when the {@code ecz} setting asks for the zone, {@code false} - * when the application does + * active does nothing. */ - private void enterContentZoneInternal(boolean bySettings) { + void enterContentZoneInternal() { if (display == null) { L.w("[ModuleContent] enterContentZoneInternal, no content display is registered, ignoring the call"); return; @@ -263,13 +272,10 @@ private void enterContentZoneInternal(boolean bySettings) { return; } + contentZoneWanted.set(true); + contentZoneExited.set(false); if (zoneActive) { - if (!bySettings && zoneEnteredBySettings) { - zoneEnteredBySettings = false; - L.d("[ModuleContent] enterContentZoneInternal, already in the content zone the SDK behavior settings entered, it now stays until it is left through exitContentZone"); - } else { - L.d("[ModuleContent] enterContentZoneInternal, already in a content zone, ignoring the call"); - } + L.d("[ModuleContent] enterContentZoneInternal, already in a content zone, ignoring the call"); return; } @@ -278,7 +284,6 @@ private void enterContentZoneInternal(boolean bySettings) { contentShown = false; fetching = false; waitForDelay = 0; - zoneEnteredBySettings = bySettings; // Any fetch left in flight from a previous zone belongs to an older generation and is // discarded when it completes. generation++; @@ -315,11 +320,13 @@ void exitContentZoneInternal() { } /** - * @param awaitTimerTermination must be {@code false} when called from the zone timer's own - * tick, because a task cannot wait for itself to finish + * Leaves the content zone because the application asked for it. Content triggers then ask for + * nothing until the application enters the zone again. */ - private void exitContentZoneInternal(boolean awaitTimerTermination) { - exitContentZoneInternal(awaitTimerTermination, false); + void exitContentZoneByApp() { + contentZoneWanted.set(false); + contentZoneExited.set(true); + exitContentZoneInternal(); } /** @@ -327,23 +334,15 @@ private void exitContentZoneInternal(boolean awaitTimerTermination) { * * @param awaitTimerTermination must be {@code false} when called from the zone timer's own * tick, because a task cannot wait for itself to finish - * @param onlyIfEnteredBySettings {@code true} to leave only an active zone the {@code ecz} - * setting entered - * @return whether the zone was left */ - private boolean exitContentZoneInternal(boolean awaitTimerTermination, boolean onlyIfEnteredBySettings) { + private void exitContentZoneInternal(boolean awaitTimerTermination) { CountlyTimer timerToStop; synchronized (contentLock) { - if (onlyIfEnteredBySettings && !(zoneActive && zoneEnteredBySettings)) { - return false; - } - zoneActive = false; shouldFetch = false; contentShown = false; fetching = false; waitForDelay = 0; - zoneEnteredBySettings = false; generation++; timerToStop = contentTimer; @@ -356,13 +355,11 @@ private boolean exitContentZoneInternal(boolean awaitTimerTermination, boolean o } L.i("[ModuleContent] exitContentZoneInternal, left the content zone"); - return true; } /** - * Flushes the event queue and enters the content zone again, keeping who entered it. Called by - * the application and when the server accepted a journey trigger; ignored while the - * {@code rcz} setting forbids refreshing and while a content block is on screen. + * Flushes the event queue and enters the content zone again. Called by the application; ignored + * while the {@code rcz} setting forbids refreshing and while a content block is on screen. */ void refreshContentZoneInternal() { if (!internalConfig.getConfigurationProvider().getRefreshContentZoneEnabled()) { @@ -370,13 +367,11 @@ void refreshContentZoneInternal() { return; } - boolean enteredBySettings; synchronized (contentLock) { if (contentShown) { L.d("[ModuleContent] refreshContentZoneInternal, a content block is on screen, ignoring the call"); return; } - enteredBySettings = zoneActive && zoneEnteredBySettings; } // Push whatever is queued out first, so the trigger the developer just recorded has a @@ -384,7 +379,296 @@ void refreshContentZoneInternal() { flushEventQueue(); exitContentZoneInternal(); - enterContentZoneInternal(enteredBySettings); + enterContentZoneInternal(); + } + + /** + * Something the SDK recorded that can be a content trigger. A match, outside its gap, sends the + * queued requests and then asks for content. + * + * @param trigger what was recorded + */ + void onContentTrigger(@Nonnull ContentTriggers.Trigger trigger) { + // once the settings of this run are in, what matches nothing is dropped here + if (behaviorSettingsSettled.get() && matchOf(trigger) == null) { + return; + } + runOnTriggerExecutor(() -> handleContentTrigger(trigger), 0); + } + + /** + * The settings answer of this run arrived and was applied, or none will arrive. + * + * @param answered whether an answer arrived and was applied + */ + void onBehaviorSettingsSettled(boolean answered) { + runOnTriggerExecutor(() -> settleEarlyTriggers(answered), 0); + } + + /** + * @param trigger what was recorded + * @return the match of what was recorded with the triggers in use, {@code null} for none + */ + private ContentTriggers.Match matchOf(@Nonnull ContentTriggers.Trigger trigger) { + ConfigurationProvider configProvider = internalConfig.getConfigurationProvider(); + return ContentTriggers.match(configProvider.getContentTriggers(), contentZoneWanted.get(), configProvider.getJourneyTriggerEvents(), configProvider.getJourneyTriggerViews(), trigger); + } + + /** + * Runs a task of the content trigger rounds on their thread, unless the module stopped. + * + * @param task the task + * @param delayMs how long to wait first, in milliseconds + */ + private void runOnTriggerExecutor(@Nonnull Runnable task, long delayMs) { + ScheduledExecutorService executor = triggerExecutor; + if (executor == null) { + return; + } + try { + executor.schedule(() -> { + try { + task.run(); + } catch (RuntimeException e) { + L.e("[ModuleContent] runOnTriggerExecutor, a content trigger task failed, [" + e + "]"); + } + }, delayMs, TimeUnit.MILLISECONDS); + } catch (RejectedExecutionException e) { + L.d("[ModuleContent] runOnTriggerExecutor, the module is stopping, the task is dropped"); + } + } + + /** + * Trigger thread only. Starts a round for a content trigger outside its gap, when content can be + * shown. A trigger during a running round only makes one more round follow it. + * + * @param trigger what was recorded + */ + private void handleContentTrigger(@Nonnull ContentTriggers.Trigger trigger) { + ContentTriggers.Match match = matchOf(trigger); + if (match == null) { + rememberEarlyTrigger(trigger); + return; + } + + if (!contentCanBeShown()) { + L.d("[ModuleContent] handleContentTrigger, [" + trigger + "] is a content trigger, but content can not be shown now, so it is not asked for"); + return; + } + + String storedGaps = internalConfig.storageProvider.getContentTriggerGaps(); + String gaps = ContentTriggers.claimGap(match, storedGaps == null ? "" : storedGaps, TimeUtils.uniqueTimestampMs()); + if (gaps == null) { + L.d("[ModuleContent] handleContentTrigger, [" + trigger + "] started a round less than [" + match.gapMs / 1000 + "] seconds ago"); + return; + } + internalConfig.storageProvider.setContentTriggerGaps(gaps); + + if (triggerRoundRunning) { + L.d("[ModuleContent] handleContentTrigger, [" + trigger + "] matched while a round is running, one more round follows it"); + triggerRoundPending = true; + return; + } + + L.d("[ModuleContent] handleContentTrigger, [" + trigger + "] matched, sending the queued requests and asking for content"); + startTriggerRound(); + } + + /** + * @return whether content can be shown now: the application did not leave the content zone, a + * display is registered and the content consent is given + */ + private boolean contentCanBeShown() { + SDKCore core = SDKCore.instance; + return !contentZoneExited.get() && display != null && core != null && core.hasConsentForFeature(CoreFeature.Content); + } + + /** + * Trigger thread only. Keeps what was recorded before the settings answer of this run arrived. + * + * @param trigger what was recorded + */ + private void rememberEarlyTrigger(@Nonnull ContentTriggers.Trigger trigger) { + if (behaviorSettingsSettled.get() || earlyTriggers.size() >= TRIGGER_EARLY_LIMIT) { + return; + } + for (ContentTriggers.Trigger early : earlyTriggers) { + if (early.sameAs(trigger)) { + return; + } + } + earlyTriggers.add(trigger); + } + + /** + * Trigger thread only. Ends the wait for the settings answer of this run. When the answer + * arrived and no settings were stored at init, its {@code ecz} decides the content zone entry, + * and the first remembered trigger it lists starts a round. + * + * @param answered whether an answer arrived and was applied + */ + private void settleEarlyTriggers(boolean answered) { + boolean firstAnswer = answered && !behaviorSettingsSettled.get(); + behaviorSettingsSettled.set(true); + if (!firstAnswer) { + earlyTriggers.clear(); + return; + } + List early = new ArrayList<>(earlyTriggers); + earlyTriggers.clear(); + + SDKCore core = SDKCore.instance; + ModuleConfiguration configuration = core == null ? null : core.module(ModuleConfiguration.class); + if (configuration != null && !configuration.behaviorSettingsStoredAtInit && configuration.getContentZoneEnabled() && !contentZoneWanted.get() && !contentZoneExited.get()) { + enterContentZoneForSettings("settleEarlyTriggers"); + } + + for (ContentTriggers.Trigger trigger : early) { + if (matchOf(trigger) != null) { + L.d("[ModuleContent] settleEarlyTriggers, [" + trigger + "] was recorded before the behavior settings arrived"); + handleContentTrigger(trigger); + return; + } + } + } + + /** + * Trigger thread only. Moves the recorded events into the request queue, sends the queue, and + * asks for content once the requests queued until now are sent. + */ + private void startTriggerRound() { + triggerRoundRunning = true; + triggerRoundPending = false; + + SDKCore core = SDKCore.instance; + ModuleEvents events = core == null ? null : core.module(ModuleEvents.class); + if (events == null) { + waitForQueueOfRound(); + return; + } + events.moveEventsToRequestQueue(() -> runOnTriggerExecutor(this::waitForQueueOfRound, 0)); + } + + /** + * Trigger thread only. Sends the queue and starts checking whether the requests queued until + * now are sent. + */ + private void waitForQueueOfRound() { + List queued = Storage.list(internalConfig, Request.getStoragePrefix()); + if (queued.isEmpty()) { + requestTriggeredContent(++contentTriggerChain, 1); + endTriggerRound(); + return; + } + + long lastQueued = Collections.max(queued); + sendQueue(); + int chain = contentTriggerChain; + runOnTriggerExecutor(() -> waitForTriggerQueue(lastQueued, queued.size(), 0, chain), TRIGGER_QUEUE_CHECK_MS); + } + + /** + * Trigger thread only. Checks whether the requests queued when the round started are sent, and + * asks for content once they are. When none of them is sent for {@link #TRIGGER_QUEUE_CHECKS} + * checks in a row, the round ends without a content request, and the content zone timer picks + * the content up. + * + * @param lastQueued storage ID of the last request queued when the round started + * @param previousRemaining how many of them were left at the previous check + * @param checksWithoutProgress checks in a row that found none of them sent + * @param chain the chain of content requests when the round started + */ + private void waitForTriggerQueue(long lastQueued, int previousRemaining, int checksWithoutProgress, int chain) { + int remaining = 0; + for (Long id : Storage.list(internalConfig, Request.getStoragePrefix())) { + if (id <= lastQueued) { + remaining++; + } + } + + if (remaining == 0) { + requestTriggeredContent(++contentTriggerChain, 1); + endTriggerRound(); + return; + } + + int withoutProgress = remaining < previousRemaining ? 0 : checksWithoutProgress + 1; + if (withoutProgress >= TRIGGER_QUEUE_CHECKS) { + L.d("[ModuleContent] waitForTriggerQueue, the queued requests could not be sent in time, the round ends without a content request"); + endTriggerRound(); + return; + } + + sendQueue(); + int left = remaining; + runOnTriggerExecutor(() -> waitForTriggerQueue(lastQueued, left, withoutProgress, chain), TRIGGER_QUEUE_CHECK_MS); + } + + /** + * Has the networking send the next queued request, unless one is on its way. + */ + private void sendQueue() { + SDKCore core = SDKCore.instance; + if (core != null && core.networking != null) { + core.networking.check(internalConfig); + } + } + + /** + * Trigger thread only. Sends a content request of a round. When it shows nothing, it is sent + * again {@link #TRIGGER_CONTENT_RETRY_MS} later, up to {@link #TRIGGER_CONTENT_REQUESTS} + * requests, as the server may still be processing what triggered it. A newer round's content + * request stops the ones left of an older round. + * + * @param chain the chain this request belongs to + * @param attempt the number of this content request in its round, from 1 + */ + private void requestTriggeredContent(int chain, int attempt) { + if (chain != contentTriggerChain) { + return; + } + + boolean zoneNeeded = internalConfig.getConfigurationProvider().getContentTriggers() != null; + if (!contentCanBeShown() || zoneNeeded && !contentZoneWanted.get()) { + L.d("[ModuleContent] requestTriggeredContent, the content zone is not wanted now, no content request is sent"); + return; + } + + Runnable retry = () -> { + if (attempt < TRIGGER_CONTENT_REQUESTS) { + runOnTriggerExecutor(() -> requestTriggeredContent(chain, attempt + 1), TRIGGER_CONTENT_RETRY_MS); + } + }; + + int currentGeneration; + synchronized (contentLock) { + if (contentShown) { + L.d("[ModuleContent] requestTriggeredContent, content is already shown, no content request is sent"); + return; + } + if (fetching) { + L.d("[ModuleContent] requestTriggeredContent, a content request is already on its way"); + retry.run(); + return; + } + fetching = true; + currentGeneration = generation; + } + + L.d("[ModuleContent] requestTriggeredContent, sending content request [" + attempt + "] of [" + TRIGGER_CONTENT_REQUESTS + "]"); + fetchContents(null, currentGeneration, retry); + } + + /** + * Trigger thread only. Ends the queue part of a round, and starts the round a trigger during it + * asked for. + */ + private void endTriggerRound() { + triggerRoundRunning = false; + if (triggerRoundPending) { + triggerRoundPending = false; + runOnTriggerExecutor(this::startTriggerRound, 0); + } } void previewContentInternal(String contentId) { @@ -409,7 +693,7 @@ void previewContentInternal(String contentId) { } L.i("[ModuleContent] previewContentInternal, previewing content:[" + contentId + "]"); - fetchContents(contentId, currentGeneration); + fetchContents(contentId, currentGeneration, null); } void recordContentEventsInternal(String eventsJson) { @@ -507,6 +791,7 @@ private void zoneTimerTick() { if (!SDKCore.instance.hasConsentForFeature(CoreFeature.Content)) { L.d("[ModuleContent] onZoneTimerTick, content consent was removed, leaving the content zone"); + contentZoneWanted.set(false); exitContentZoneInternal(false); return; } @@ -527,10 +812,18 @@ private void zoneTimerTick() { currentGeneration = generation; } - fetchContents(null, currentGeneration); + fetchContents(null, currentGeneration, null); } - private void fetchContents(String contentId, int fetchGeneration) { + /** + * Asks the server for content and shows what it answers with. + * + * @param contentId the content to preview, {@code null} for the content the server picks + * @param fetchGeneration the zone generation this request belongs to + * @param onNothingShown called when the request shows nothing: no content, a failed request, or + * an answer without content to show; {@code null} for nothing to call + */ + private void fetchContents(String contentId, int fetchGeneration, @Nullable Runnable onNothingShown) { try { ContentDisplay currentDisplay; synchronized (contentLock) { @@ -540,6 +833,7 @@ private void fetchContents(String contentId, int fetchGeneration) { if (currentDisplay == null) { L.w("[ModuleContent] fetchContents, the content display went away, aborting the fetch"); clearFetching(fetchGeneration); + runIfSet(onNothingShown); return; } @@ -555,14 +849,25 @@ private void fetchContents(String contentId, int fetchGeneration) { internalConfig.immediateRequestGenerator.createImmediateRequestMaker() .doWork(requestData, "/o/sdk/content?", transport, false, networkingIsEnabled, - response -> onContentFetched(response, fetchGeneration), L); + response -> onContentFetched(response, fetchGeneration, onNothingShown), L); } catch (Throwable t) { L.e("[ModuleContent] fetchContents, failed to request content, [" + t + "]"); clearFetching(fetchGeneration); + runIfSet(onNothingShown); + } + } + + /** + * @param task the task to run, {@code null} for none + */ + private static void runIfSet(@Nullable Runnable task) { + if (task != null) { + task.run(); } } - private void onContentFetched(JSONObject response, int fetchGeneration) { + private void onContentFetched(JSONObject response, int fetchGeneration, @Nullable Runnable onNothingShown) { + boolean shown = false; try { ContentData content = ContentParser.parse(response, L); if (content == null) { @@ -595,10 +900,14 @@ private void onContentFetched(JSONObject response, int fetchGeneration) { shouldFetch = false; } } + shown = true; } catch (Throwable t) { L.e("[ModuleContent] onContentFetched, the content display failed to show the content, [" + t + "]"); } finally { clearFetching(fetchGeneration); + if (!shown) { + runIfSet(onNothingShown); + } } } @@ -719,7 +1028,7 @@ public void exitContentZone() { } synchronized (Countly.instance()) { L.i("[Content] exitContentZone, leaving the content zone"); - exitContentZoneInternal(); + exitContentZoneByApp(); } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleCrashes.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleCrashes.java index 8cd21157..72a0c028 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleCrashes.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleCrashes.java @@ -228,7 +228,14 @@ protected boolean recordExceptionInternal(Throwable t, boolean handled, Map journeyTriggerRequestIds = ConcurrentHashMap.newKeySet(); /** * The thread ending the timed events and the view of the previous device ID during a device ID * change without merge; its sends wait, so those events go out in one request under that ID. @@ -60,52 +54,6 @@ public Boolean onRequest(Request request) { return true; } - /** - * Refreshes the content zone once the server accepted a request that carries a journey trigger. - * The first attempt to send such a request settles it: when it fails, neither it nor its retry - * refreshes anything. A request dropped from the queue unsent settles it the same way. - * - * @param request the request that was sent - * @param response the response body, {@code null} when none could be read - * @param responseCode the response code, {@link Transport#NO_RESPONSE_CODE} when no response arrived - */ - @Override - public void onRequestCompleted(Request request, String response, int responseCode) { - if (request == null || !journeyTriggerRequestIds.remove(request.storageId())) { - return; - } - - if (!Transport.isSuccessfulResponse(responseCode, response)) { - L.d("[ModuleEvents] onRequestCompleted, the request [" + request.storageId() + "] carrying a journey trigger failed with code [" + responseCode + "], the content zone is not refreshed"); - return; - } - - SDKCore core = SDKCore.instance; - ModuleContent content = core == null ? null : core.module(ModuleContent.class); - if (content == null) { - L.d("[ModuleEvents] onRequestCompleted, the server accepted the request [" + request.storageId() + "] carrying a journey trigger, there is no content zone to refresh"); - return; - } - - L.d("[ModuleEvents] onRequestCompleted, the server accepted the request [" + request.storageId() + "] carrying a journey trigger, refreshing the content zone"); - content.refreshContentZoneInternal(); - } - - /** - * Settles the journey triggers carried by requests that were removed from the queue unread, - * which leaves their owner unknown and untold. No response will ever arrive for them, and none - * of them refreshes the content zone. - * - * @param requestIds storage IDs of the removed requests - */ - void onRequestsDroppedUnread(@Nonnull Collection requestIds) { - for (Long requestId : requestIds) { - if (journeyTriggerRequestIds.remove(requestId)) { - L.d("[ModuleEvents] onRequestsDroppedUnread, the request [" + requestId + "] carrying a journey trigger was dropped from the queue without being sent, the content zone is not refreshed"); - } - } - } - @Override public void deviceIdChanged(String oldDeviceId, boolean withMerge) { super.deviceIdChanged(oldDeviceId, withMerge); @@ -140,7 +88,6 @@ public void deviceIdChanged(String oldDeviceId, boolean withMerge) { @Override public void stop(InternalConfig config, final boolean clear) { super.stop(config, clear); - journeyTriggerRequestIds.clear(); if (clear) { eventQueue.clear(); timedEvents.clear(); @@ -152,46 +99,49 @@ public void stop(InternalConfig config, final boolean clear) { * * @param deviceId the device ID the events belong to, {@code null} for the current one */ - private void addEventsToRequestQ(@Nullable String deviceId) { - addEventsToRequestQ(deviceId, false); + private synchronized void addEventsToRequestQ(@Nullable String deviceId) { + L.d("[ModuleEvents] addEventsToRequestQ"); + + if (eventQueue.getEQ().isEmpty()) { + L.d("[ModuleEvents] addEventsToRequestQ, eventQueueMemoryCache is empty, skipping"); + return; + } + + Request request = eventsRequest(deviceId); + eventQueue.clear(); + ModuleRequests.pushAsync(internalConfig, request); } /** - * Moves every queued event into one request. + * Moves every queued event into one request, for a content trigger round, which sends the + * request queue once this request is stored. * - * @param deviceId the device ID the events belong to, {@code null} for the current one - * @param journeyTrigger whether the events include a journey trigger, whose request refreshes - * the content zone once the server accepts it + * @param onStored called once the request is stored, or right away when no event is queued */ - private synchronized void addEventsToRequestQ(@Nullable String deviceId, boolean journeyTrigger) { - L.d("[ModuleEvents] addEventsToRequestQ"); - + synchronized void moveEventsToRequestQueue(@Nonnull Runnable onStored) { if (eventQueue.getEQ().isEmpty()) { - L.d("[ModuleEvents] addEventsToRequestQ, eventQueueMemoryCache is empty, skipping"); + onStored.run(); return; } + Request request = eventsRequest(null); + eventQueue.clear(); + ModuleRequests.pushAsync(internalConfig, request, false, stored -> onStored.run()); + } + + /** + * @param deviceId the device ID the events belong to, {@code null} for the current one + * @return a request with every queued event + */ + @Nonnull + private Request eventsRequest(@Nullable String deviceId) { Request request = new Request(); if (deviceId != null) { request.params.add("device_id", deviceId); } request.params.arr("events").put(eventQueue.getEQ()).add(); request.own(ModuleEvents.class); - - eventQueue.clear(); - if (!journeyTrigger) { - ModuleRequests.pushAsync(internalConfig, request); - return; - } - - final Long requestId = request.storageId(); - journeyTriggerRequestIds.add(requestId); - L.d("[ModuleEvents] addEventsToRequestQ, the request [" + requestId + "] carries a journey trigger, the content zone is refreshed once the server accepts it"); - ModuleRequests.pushAsync(internalConfig, request, false, stored -> { - if (!Boolean.TRUE.equals(stored)) { - journeyTriggerRequestIds.remove(requestId); - } - }); + return request; } /** @@ -237,7 +187,7 @@ protected void recordEventInternal(String key, int count, Double sum, Double dur segmentation = filteredCustomEventSegmentation(key, segmentation, configProvider); } - boolean journeyTrigger = isJourneyTrigger(key, isCustomEvent, segmentation, configProvider); + String keyAsGiven = key; L.d("[ModuleEvents] recordEventInternal, Recording event with key: [" + key + "] and provided event ID of:[" + eventIdOverride + "] and segmentation with:[" + (segmentation == null ? "null" : segmentation.size()) + "] keys"); @@ -272,7 +222,39 @@ protected void recordEventInternal(String key, int count, Double sum, Double dur this.previousEventId = eventId; } - addEventToQueue(new EventImpl(key, count, sum, dur, segmentation, L, eventId, pvid, cvid, previousEventIdToSend), journeyTrigger); + addEventToQueue(new EventImpl(key, count, sum, dur, segmentation, L, eventId, pvid, cvid, previousEventIdToSend)); + notifyContentTrigger(keyAsGiven, eventId, segmentation); + } + + /** + * Tells the content module about a recorded event, which can be a content trigger: a view event + * by its name, and any other event by its key, both as the app passed them, before the limits + * cut them. + * + * @param keyAsGiven the event key as the app passed it + * @param eventId the ID of the event, which is the view ID for a view event + * @param segmentation the segmentation of the event, {@code null} for none + */ + private void notifyContentTrigger(@Nonnull String keyAsGiven, @Nonnull String eventId, @Nullable Map segmentation) { + SDKCore core = SDKCore.instance; + ModuleContent content = core == null ? null : core.module(ModuleContent.class); + if (content == null) { + return; + } + + if (!ModuleViews.KEY_VIEW_EVENT.equals(keyAsGiven)) { + content.onContentTrigger(ContentTriggers.Trigger.event(keyAsGiven, !keyAsGiven.startsWith("[CLY]_"))); + return; + } + + ModuleViews views = core.module(ModuleViews.class); + String viewName = views == null ? null : views.viewNameFor(eventId); + if (viewName == null && segmentation != null && segmentation.get(ModuleViews.KEY_NAME) instanceof String) { + viewName = (String) segmentation.get(ModuleViews.KEY_NAME); + } + if (viewName != null) { + content.onContentTrigger(ContentTriggers.Trigger.view(viewName, segmentation == null || !segmentation.containsKey(ModuleViews.KEY_VISIT))); + } } /** @@ -297,61 +279,29 @@ private Map filteredCustomEventSegmentation(@Nonnull String key, } /** - * Whether an event is a journey trigger of the SDK behavior settings: a custom event whose key - * is in {@code jte}, or a view event whose name is in {@code jtv}. - * - * @param key the key of the event, as it was passed - * @param isCustomEvent whether the key is not one of {@link #INTERNAL_EVENT_KEYS} - * @param segmentation the segmentation of the event, {@code null} for none - * @param configProvider the settings in effect - * @return {@code true} for a journey trigger - */ - private static boolean isJourneyTrigger(@Nonnull String key, boolean isCustomEvent, @Nullable Map segmentation, @Nonnull ConfigurationProvider configProvider) { - if (isCustomEvent) { - return configProvider.getJourneyTriggerEvents().contains(key); - } - - if (!ModuleViews.KEY_VIEW_EVENT.equals(key) || segmentation == null) { - return false; - } - - Object viewName = segmentation.get(ModuleViews.KEY_NAME); - return viewName != null && configProvider.getJourneyTriggerViews().contains(viewName); - } - - /** - * Adds an event to the event queue and sends the queue when it is full or holds a journey trigger. + * Adds an event to the event queue and sends the queue when it is full. * * @param event the event - * @param journeyTrigger whether the event is a journey trigger */ - private void addEventToQueue(@Nonnull EventImpl event, boolean journeyTrigger) { + private void addEventToQueue(@Nonnull EventImpl event) { L.d("[ModuleEvents] addEventToQueue"); eventQueue.addEvent(event); - if (journeyTrigger) { - L.d("[ModuleEvents] addEventToQueue, event [" + event.key + "] is a journey trigger, sending the event queue now"); - } - checkEventQueueToSend(journeyTrigger, journeyTrigger); - } - - void checkEventQueueToSend(boolean forceSend) { - checkEventQueueToSend(forceSend, false); + checkEventQueueToSend(false); } /** * Sends the queued events when asked to or when the queue reached its threshold. * * @param forceSend whether to send whatever is queued - * @param journeyTrigger whether the queue holds a journey trigger */ - private void checkEventQueueToSend(boolean forceSend, boolean journeyTrigger) { + void checkEventQueueToSend(boolean forceSend) { if (Thread.currentThread() == threadEndingEventsOfThePreviousDeviceId) { L.d("[ModuleEvents] checkEventQueueToSend, the events of the previous device ID are being ended, they are sent together under that ID"); return; } L.d("[ModuleEvents] queue size:[" + eventQueue.eqSize() + "] || forceSend: " + forceSend); if (forceSend || eventQueue.eqSize() >= internalConfig.getConfigurationProvider().getEventQueueSizeThreshold()) { - addEventsToRequestQ(null, journeyTrigger); + addEventsToRequestQ(null); } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleRequests.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleRequests.java index a6255704..4a15604e 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleRequests.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleRequests.java @@ -73,7 +73,25 @@ private static Request sessionRequest(InternalConfig config, SessionImpl session public static Future sessionBegin(InternalConfig config, SessionImpl session) { Request request = sessionRequest(config, session, "begin_session", 1L); - return request.isEmpty() ? null : pushAsync(config, request); + return request.isEmpty() ? null : pushAsync(config, request, false, stored -> notifyContentTrigger(config, stored, ContentTriggers.Trigger.of(ContentTriggers.KEY_SESSION))); + } + + /** + * Tells the content module about something recorded that can be a content trigger, once its + * request is stored, so a round it starts sends that request before it asks for content. + * + * @param config configuration of the running SDK + * @param stored whether the request was stored + * @param trigger what was recorded + */ + static void notifyContentTrigger(@Nonnull InternalConfig config, @Nullable Boolean stored, @Nonnull ContentTriggers.Trigger trigger) { + if (!Boolean.TRUE.equals(stored) || config.sdk == null) { + return; + } + ModuleContent content = config.sdk.module(ModuleContent.class); + if (content != null) { + content.onContentTrigger(trigger); + } } public static Future sessionUpdate(InternalConfig config, SessionImpl session, Long seconds) { @@ -385,7 +403,6 @@ static int dropOldestRequestsOverQueueLimit(@Nonnull InternalConfig config) { config.getLogger().e("[ModuleRequests] dropOldestRequestsOverQueueLimit, failed to keep the request queue within its size, [" + e + "]"); } - settleJourneyTriggersOf(config, droppedIds); return droppedIds.size(); } @@ -437,30 +454,6 @@ static int removeQueuedRequests(@Nonnull InternalConfig config, @Nullable Predic return 0; } - settleJourneyTriggersOf(config, removedIds); return removedIds.size(); } - - /** - * Tells the events module which requests were dropped unread, so a journey trigger one of them - * carried stops waiting for a response. Only a set of IDs is touched, which is safe on the - * storage thread. - * - * @param config configuration of the running SDK - * @param droppedIds storage IDs of the dropped requests - */ - private static void settleJourneyTriggersOf(@Nonnull InternalConfig config, @Nonnull List droppedIds) { - if (droppedIds.isEmpty() || config.sdk == null) { - return; - } - - try { - ModuleEvents events = config.sdk.module(ModuleEvents.class); - if (events != null) { - events.onRequestsDroppedUnread(droppedIds); - } - } catch (Exception e) { - config.getLogger().e("[ModuleRequests] settleJourneyTriggersOf, failed to settle the journey triggers of the dropped requests, [" + e + "]"); - } - } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleUserProfile.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleUserProfile.java index 796b5c63..57856aae 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleUserProfile.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleUserProfile.java @@ -459,10 +459,45 @@ protected void saveInternal() { events.checkEventQueueToSend(true); } - ModuleRequests.pushAsync(internalConfig, new Request(generatedParams)); + ModuleRequests.pushAsync(internalConfig, new Request(generatedParams), false, + stored -> ModuleRequests.notifyContentTrigger(internalConfig, stored, ContentTriggers.Trigger.userProperties(sentPropertyNames(generatedParams)))); clearInternal(); } + /** + * The user properties a user details request sends, as content triggers name them: a user detail + * ("email"), or "custom." and the key of a custom property. + * + * @param params the parameters of the request + * @return the property names + */ + @Nonnull + static List sentPropertyNames(@Nonnull Params params) { + List names = new ArrayList<>(); + String details = params.get("user_details"); + if (details != null) { + try { + JSONObject json = new JSONObject(details); + for (String key : json.keySet()) { + JSONObject custom = "custom".equals(key) ? json.optJSONObject(key) : null; + if (custom == null) { + names.add(key); + continue; + } + for (String customKey : custom.keySet()) { + names.add("custom." + customKey); + } + } + } catch (JSONException ignored) { + // a request without readable user details sends no property names + } + } + if ((params.has(PICTURE_BYTES) || params.has(PredefinedUserPropertyKeys.PICTURE_PATH)) && !names.contains("picture")) { + names.add("picture"); + } + return names; + } + protected void clearInternal() { L.d("[ModuleUserProfile] clearInternal"); diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleViews.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleViews.java index 165528a7..ffddccfe 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleViews.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleViews.java @@ -235,6 +235,16 @@ private void autoCloseRequiredViews(boolean closeAllViews, Map c return currentViewData.viewID; } + /** + * @param viewId the ID of a started view, which is also the ID of its view events + * @return the name the app passed for the view, {@code null} when no started view has the ID + */ + @Nullable + String viewNameFor(@Nullable String viewId) { + ViewData vd = viewId == null ? null : viewDataMap.get(viewId); + return vd == null ? null : vd.viewName; + } + protected void setFirstViewInternal(boolean firstView) { this.firstView = firstView; } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/SDKStorage.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/SDKStorage.java index 45f0531b..883d142a 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/SDKStorage.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/SDKStorage.java @@ -36,6 +36,7 @@ public class SDKStorage implements StorageProvider { protected static final String key_server_config = "sc"; protected static final String key_health_check = "HEALTH_CHECK"; protected static final String key_health_check_automatic_crashes = "HEALTH_CHECK_AUTOMATIC_CRASHES"; + protected static final String key_content_trigger_gaps = "CONTENT_TRIGGER_GAPS"; private JsonFileStorage jsonFileStorage; @@ -436,6 +437,20 @@ public void setHealthCheckState(String state) { } } + @Override + public String getContentTriggerGaps() { + JsonFileStorage storage = jsonFileStorage; + return storage == null ? null : storage.getString(key_content_trigger_gaps); + } + + @Override + public void setContentTriggerGaps(String gaps) { + JsonFileStorage storage = jsonFileStorage; + if (storage != null) { + storage.addAndSave(key_content_trigger_gaps, gaps == null ? "" : gaps); + } + } + @Override public void incrementAutomaticCrashCount() { JsonFileStorage storage = jsonFileStorage; diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/StorageProvider.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/StorageProvider.java index e0308a40..4b82010b 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/StorageProvider.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/StorageProvider.java @@ -98,6 +98,20 @@ public interface StorageProvider { */ void setHealthCheckState(String state); + /** + * Read when each content trigger last asked for content. + * + * @return a JSON object of trigger to time in milliseconds, {@code null} or empty when none is stored + */ + String getContentTriggerGaps(); + + /** + * Store when each content trigger last asked for content, so its gap holds after a restart. + * + * @param gaps a JSON object of trigger to time in milliseconds, empty to clear them + */ + void setContentTriggerGaps(String gaps); + /** * Add one automatically detected crash to the count the next start reports in the health check. * Written right away, without the health check counters, as it runs while the crash is reported. diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationContentTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationContentTests.java index b04fd278..999dcecb 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationContentTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationContentTests.java @@ -84,67 +84,39 @@ public void afterTest() { // region scenarios /** - * {@code ecz} enters the content zone once a display is registered, and turning it off leaves - * only a zone it entered. + * {@code ecz} decides only whether the SDK enters the content zone at init. *

- * Verifies that the response of the fetch made at init, applied before the content module - * finished its init, enters nothing while no display is registered; that registering one enters - * the zone, which a refresh keeps as the settings' zone; that turning the setting off leaves that - * zone and turning it on enters again; that a zone the application entered, or claimed by entering - * while the settings' zone ran, survives the setting turning off; that a response which leaves the - * setting as it is changes nothing, so a zone the application left stays left; that registering a - * display again enters; and that the stored setting enters again after a restart. + * Verifies that on a first start the first answer decides, and the zone is entered once a display + * is registered; that a later answer turning the setting off does not leave the zone; that after + * the application left the zone a later answer turning it on does not enter it; and that at the + * next init the stored setting enters the zone once a display is registered. */ @Test - public void contentZoneEnabled_entersOnceADisplayIsRegistered_andTurningItOffLeavesOnlyTheZoneItEntered() { + public void contentZoneEnabled_decidesOnlyTheEntryAtInit() throws InterruptedException { server.settings.respondWith(new ServerConfigBuilder().contentZone(true)); init(contentConfig()); holdTheZoneTimer(); - Assert.assertTrue(provider().getContentZoneEnabled()); - Assert.assertEquals(2, logsContaining("it is entered once a content display is registered")); + awaitLogs("it is entered once a content display is registered", 1); assertZoneIsInactive(0); - Countly.instance().content().setContentDisplay(display); assertZoneFetches(1); - Countly.instance().content().refreshContentZone(); - assertZoneFetches(2); push(new ServerConfigBuilder().contentZone(false)); - assertZoneIsInactive(2); - push(new ServerConfigBuilder().contentZone(true)); - assertZoneFetches(3); + assertZoneFetches(2); - Countly.instance().content().enterContentZone(); - push(new ServerConfigBuilder().contentZone(false)); - assertZoneFetches(4); - push(new ServerConfigBuilder().eventQueueSize(5)); - assertZoneFetches(5); Countly.instance().content().exitContentZone(); - assertZoneIsInactive(5); - - Countly.instance().content().enterContentZone(); - push(new ServerConfigBuilder().contentZone(true)); - push(new ServerConfigBuilder().contentZone(false)); - assertZoneFetches(6); - Countly.instance().content().exitContentZone(); - + assertZoneIsInactive(2); push(new ServerConfigBuilder().contentZone(true)); - assertZoneFetches(7); - Countly.instance().content().exitContentZone(); - push(new ServerConfigBuilder().contentZone(true).eventQueueSize(6)); - assertZoneIsInactive(7); - - Countly.instance().content().setContentDisplay(display); - assertZoneFetches(8); + assertZoneIsInactive(2); Countly.instance().stop(); server.settings.pending(); init(contentConfig()); holdTheZoneTimer(); - assertZoneIsInactive(8); + assertZoneIsInactive(2); Countly.instance().content().setContentDisplay(display); - assertZoneFetches(9); + assertZoneFetches(3); } /** @@ -193,172 +165,139 @@ public void contentZoneInterval_isReadWhenTheZoneIsEntered_andAChangeRestartsThe } /** - * {@code jte} and {@code jtv} send the whole event queue as soon as a trigger is recorded. - *

- * Verifies on disk, with networking off, that events that are not triggers wait for the queue - * threshold, an internal event listed in {@code jte} included, that a custom trigger sends them all - * with it, that each later trigger gets its own request and each such request waits for its - * response, that both the start and the end of a trigger view send the queue, and that a trigger - * filtered out by {@code eb} or a trigger view while view tracking is off sends nothing. + * The settings request asks for the content triggers with {@code jt=1}, and they are stored with + * the settings, unless {@code disableAutoContentTriggers} is set. */ @Test - public void journeyTriggers_sendTheWholeEventQueueRightAway_eachTriggerInItsOwnRequest() { - server.settings.respondWith(journeyTriggerSettings()); - init(contentConfig().enableFeatures(Config.Feature.Views)); + public void contentTriggers_areAskedForAndStored_unlessTurnedOff() { + server.settings.respondWith(new ServerConfigBuilder().topLevelKey("jt", triggers("e", "purchase"))); + init(contentConfig()); - Countly.instance().events().recordEvent("regular"); - Countly.instance().events().recordEvent("[CLY]_star_rating"); - Countly.instance().views().startView("home"); - Assert.assertEquals(0, TestUtils.getCurrentRQ().length); - TestUtils.validateEQSize(3); - - Countly.instance().events().recordEvent("purchase", TestUtils.map("item", "book")); - TestUtils.letTheClockCatchUp(); - TestUtils.validateEQSize(0); - Assert.assertEquals(1, TestUtils.getCurrentRQ().length); - List sent = TestUtils.readEventsFromRequest(0, TestUtils.DEVICE_ID); - Assert.assertEquals(4, sent.size()); - Assert.assertEquals("regular", sent.get(0).key); - Assert.assertEquals("[CLY]_star_rating", sent.get(1).key); - Assert.assertEquals(ModuleViews.KEY_VIEW_EVENT, sent.get(2).key); - Assert.assertEquals("purchase", sent.get(3).key); - Assert.assertEquals("book", sent.get(3).segmentation.get("item")); + Assert.assertEquals("1", server.settings.requests.get(0).get("jt")); + Assert.assertTrue(provider().getContentTriggers().keys.contains("purchase")); + Assert.assertTrue(SDKCore.instance.config.storageProvider.getServerConfig().contains("\"jt\"")); + Countly.instance().halt(); - Countly.instance().events().recordEvent("purchase"); - TestUtils.letTheClockCatchUp(); - Assert.assertEquals(2, TestUtils.getCurrentRQ().length); - Assert.assertEquals(1, TestUtils.readEventsFromRequest(1, TestUtils.DEVICE_ID).size()); + TestUtils.createCleanTestState(); + server = new SettingsAndContentServer(); + server.settings.respondWith(new ServerConfigBuilder().topLevelKey("jt", triggers("e", "purchase"))); + Config config = contentConfig(); + config.content.disableAutoContentTriggers(); + init(config); - Countly.instance().views().startView("checkout"); - TestUtils.letTheClockCatchUp(); - Countly.instance().views().stopViewWithName("checkout"); - TestUtils.letTheClockCatchUp(); - Assert.assertEquals(4, TestUtils.getCurrentRQ().length); - List checkoutStart = TestUtils.readEventsFromRequest(2, TestUtils.DEVICE_ID); - List checkoutEnd = TestUtils.readEventsFromRequest(3, TestUtils.DEVICE_ID); - Assert.assertEquals("checkout", checkoutStart.get(0).segmentation.get(ModuleViews.KEY_NAME)); - Assert.assertEquals("1", checkoutStart.get(0).segmentation.get(ModuleViews.KEY_VISIT)); - Assert.assertEquals("checkout", checkoutEnd.get(0).segmentation.get(ModuleViews.KEY_NAME)); - Assert.assertNull(checkoutEnd.get(0).segmentation.get(ModuleViews.KEY_VISIT)); - Assert.assertEquals(storedRequestIds(), SDKCore.instance.module(ModuleEvents.class).journeyTriggerRequestIds); - - Countly.instance().views().startView("profile"); - push(journeyTriggerSettings().eventFilterList(names("purchase"), false)); - Countly.instance().events().recordEvent("purchase"); - push(journeyTriggerSettings().viewTracking(false)); - Assert.assertNull(Countly.instance().views().startView("checkout")); - Assert.assertEquals(4, TestUtils.getCurrentRQ().length); - TestUtils.validateEQSize(1); - Assert.assertEquals(4, SDKCore.instance.module(ModuleEvents.class).journeyTriggerRequestIds.size()); + Assert.assertNull(server.settings.requests.get(0).get("jt")); + Assert.assertNull(provider().getContentTriggers()); } /** - * A {@code jte} trigger refreshes the content zone once the server accepts the request carrying it. + * A listed event, while the content zone is wanted, sends the queued requests and then asks for + * content, up to three times while there is none; the same event asks again only after its gap. *

- * Verifies against a local server that the zone is entered only after the request carrying the - * trigger and the events queued before it was accepted; that while a content block is on screen - * the refresh is ignored; that a rejected request refreshes nothing, and neither does its retry - * once accepted; and that an attempt that got no response settles it the same way. + * Verifies against a local server that every recorded event goes out with the trigger, that the + * request queue is empty when the first content request goes out, that three content requests + * follow, and that the same event inside its gap starts no round. */ @Test - public void journeyTriggerEvent_refreshesTheZoneOnlyWhenTheServerAcceptsItsRequest() throws Exception { + public void contentTriggers_aListedEventSendsTheQueueThenAsksForContent() throws Exception { startQueueServer(); - server.settings.respondWith(new ServerConfigBuilder().journeyTriggerEvents(names("purchase"))); + server.settings.respondWith(new ServerConfigBuilder().topLevelKey("jt", triggers("e", "purchase"))); init(networkedContentConfig()); holdTheZoneTimer(); Countly.instance().content().setContentDisplay(display); - assertZoneIsInactive(0); + Countly.instance().content().enterContentZone(); Countly.instance().events().recordEvent("regular"); - TestUtils.validateEQSize(1); Countly.instance().events().recordEvent("purchase"); - awaitZoneFetch(1); - Assert.assertEquals(1, queueServer.eventRequests().size()); + awaitContentRequests(3); Assert.assertEquals("[\"regular\",\"purchase\"]", eventKeys(queueServer.eventRequests().get(0)).toString()); - awaitEmptyQueue(); + Assert.assertEquals(Integer.valueOf(0), server.queuedRequestsAtFetch.get(0)); - server.contentResponse = CONTENT_RESPONSE; - assertZoneFetches(2); - Assert.assertEquals(1, display.presented.size()); Countly.instance().events().recordEvent("purchase"); - awaitLogs("a content block is on screen, ignoring the call", 1); - display.lastCallback.onClosed(new HashMap<>()); - Countly.instance().content().exitContentZone(); - server.contentResponse = NO_CONTENT_RESPONSE; - awaitEmptyQueue(); - assertZoneIsInactive(2); + awaitLogs("started a round less than [10] seconds ago", 1); + Thread.sleep(1500); + Assert.assertEquals(3, server.contentFetches.size()); + } - queueServer.mode = QueueServer.REJECT; - Countly.instance().events().recordEvent("purchase"); - awaitLogs("carrying a journey trigger failed with code [500]", 1); - Assert.assertEquals(1, queuedRequestCount()); - assertZoneIsInactive(2); - queueServer.mode = QueueServer.ACCEPT; - awaitEmptyQueue(); - assertZoneIsInactive(2); + /** + * Content triggers apply only while the content zone is wanted, and an answer with content + * triggers, even an empty one, makes the SDK ignore the journey trigger events. + */ + @Test + public void contentTriggers_needTheContentZone_andHideTheJourneyTriggerEvents() throws Exception { + startQueueServer(); + server.settings.respondWith(new ServerConfigBuilder().journeyTriggerEvents(names("legacy")).topLevelKey("jt", triggers("e", "purchase"))); + init(networkedContentConfig()); + holdTheZoneTimer(); + Countly.instance().content().setContentDisplay(display); - queueServer.mode = QueueServer.DROP; Countly.instance().events().recordEvent("purchase"); - awaitLogs("carrying a journey trigger failed with code [" + Transport.NO_RESPONSE_CODE + "]", 1); - assertZoneIsInactive(2); - queueServer.mode = QueueServer.ACCEPT; - awaitEmptyQueue(); - assertZoneIsInactive(2); - Assert.assertEquals(2, logsContaining("carrying a journey trigger, refreshing the content zone")); - Assert.assertTrue(SDKCore.instance.module(ModuleEvents.class).journeyTriggerRequestIds.isEmpty()); + Countly.instance().events().recordEvent("legacy"); + Thread.sleep(2500); + Assert.assertEquals(0, server.contentFetches.size()); + + push(new ServerConfigBuilder().journeyTriggerEvents(names("legacy")).topLevelKey("jt", new JSONObject())); + Countly.instance().content().enterContentZone(); + int zoneFetches = server.contentFetches.size(); + Countly.instance().events().recordEvent("legacy"); + Thread.sleep(2500); + Assert.assertEquals(zoneFetches, server.contentFetches.size()); } /** - * A {@code jtv} trigger refreshes the zone like an event does, it never triggers while view - * tracking is off, and {@code rcz} off ignores every refresh. - *

- * Verifies against a local server that with refreshing forbidden the application's refresh is - * ignored before it sends the queued events and the refresh of an accepted trigger is ignored too; - * that with view tracking off a trigger view is not recorded, so nothing is sent; and that with - * both allowed a trigger view sends the queue and enters the zone once the server accepted it. + * Without content triggers, the journey trigger events and views ask for content directly, also + * outside the content zone and while {@code rcz} is off: an event of the app whose key is listed, + * and a listed view when it starts and again when it ends, each with its own gap. */ @Test - public void journeyTriggerView_refreshesLikeAnEvent_neverWhileViewTrackingIsOff_andRczOffIgnoresEveryRefresh() throws Exception { + public void journeyTriggers_askForContentDirectly_forEventsOfTheAppAndBothEventsOfAView() throws Exception { startQueueServer(); - server.settings.respondWith(new ServerConfigBuilder() - .journeyTriggerViews(names("checkout")) - .journeyTriggerEvents(names("purchase")) - .refreshContentZone(false)); + server.settings.respondWith(new ServerConfigBuilder().refreshContentZone(false) + .journeyTriggerEvents(names("purchase", "[CLY]_star_rating")) + .journeyTriggerViews(names("checkout"))); init(networkedContentConfig()); holdTheZoneTimer(); Countly.instance().content().setContentDisplay(display); - Countly.instance().views().startView("home"); - Countly.instance().content().refreshContentZone(); - TestUtils.validateEQSize(1); - Assert.assertEquals(1, logsContaining("refreshing the content zone is disabled by the SDK behavior settings")); - assertZoneIsInactive(0); + Countly.instance().events().recordEvent("[CLY]_star_rating"); + Thread.sleep(2000); + Assert.assertEquals(0, server.contentFetches.size()); Countly.instance().events().recordEvent("purchase"); - awaitLogs("refreshing the content zone is disabled by the SDK behavior settings", 2); - awaitEmptyQueue(); - assertZoneIsInactive(0); - Assert.assertEquals("[\"[CLY]_view\",\"purchase\"]", eventKeys(queueServer.eventRequests().get(0)).toString()); - - push(new ServerConfigBuilder().refreshContentZone(true).viewTracking(false) - .journeyTriggerViews(names("checkout")) - .journeyTriggerEvents(names("purchase"))); - Assert.assertNull(Countly.instance().views().startView("checkout")); - TestUtils.validateEQSize(0); - Assert.assertEquals(0, queuedRequestCount()); - assertZoneIsInactive(0); + awaitContentRequests(3); - push(new ServerConfigBuilder().viewTracking(true) - .journeyTriggerViews(names("checkout")) - .journeyTriggerEvents(names("purchase"))); Countly.instance().views().startView("checkout"); - awaitZoneFetch(1); - List> eventRequests = queueServer.eventRequests(); - Assert.assertEquals(2, eventRequests.size()); - JSONObject view = new JSONArray(eventRequests.get(1).get("events")).getJSONObject(0); - Assert.assertEquals(ModuleViews.KEY_VIEW_EVENT, view.getString("key")); - Assert.assertEquals("checkout", view.getJSONObject("segmentation").getString(ModuleViews.KEY_NAME)); - awaitEmptyQueue(); + awaitContentRequests(6); + Countly.instance().views().stopViewWithName("checkout"); + awaitContentRequests(9); + } + + /** + * What was recorded before the first settings answer of the run is checked again when it + * arrives, and a listed one starts a round; a session, a user property and a handled exception + * are triggers too. + */ + @Test + public void contentTriggers_earlyTriggerAndTheOtherTriggerKinds() throws Exception { + startQueueServer(); + server.settings.pending(); + init(networkedContentConfig().enableFeatures(Config.Feature.CrashReporting, Config.Feature.UserProfiles)); + holdTheZoneTimer(); + Countly.instance().content().setContentDisplay(display); + Countly.instance().content().enterContentZone(); + + Countly.instance().events().recordEvent("purchase"); + Thread.sleep(1000); + Assert.assertEquals(0, server.contentFetches.size()); + JSONObject listed = triggers("e", "purchase", "[CLY]_crash").put("p", new JSONArray().put("custom.plan")); + push(new ServerConfigBuilder().topLevelKey("jt", listed)); + awaitContentRequests(3); + + Countly.instance().userProfile().setProperty("plan", "pro"); + Countly.instance().userProfile().save(); + awaitContentRequests(6); + + Countly.instance().crashes().recordHandledException(new IllegalStateException("content trigger")); + awaitContentRequests(9); } /** @@ -429,12 +368,28 @@ protected void onSdkConfigurationChanged(InternalConfig config) { * * @return a builder holding those settings */ - private static ServerConfigBuilder journeyTriggerSettings() { - return new ServerConfigBuilder() - .journeyTriggerEvents(names("purchase", "[CLY]_star_rating")) - .journeyTriggerViews(names("checkout")) - .eventQueueSize(100) - .networking(false); + /** + * @param list the list of the content triggers, "e", "v" or "p" + * @param names the names in it + * @return content triggers with that one list + */ + private static JSONObject triggers(String list, String... names) { + JSONArray array = new JSONArray(); + for (String name : names) { + array.put(name); + } + return new JSONObject().put(list, array); + } + + /** + * Waits until the content requests reached the expected count, then that no more follow at once. + * + * @param expected the expected count of content requests + */ + private void awaitContentRequests(int expected) throws InterruptedException { + Assert.assertTrue("only [" + server.contentFetches.size() + "] content requests, logs: " + logs, waitFor(() -> server.contentFetches.size() >= expected)); + Thread.sleep(300); + Assert.assertEquals(expected, server.contentFetches.size()); } /** @@ -446,6 +401,7 @@ private static ServerConfigBuilder journeyTriggerSettings() { private static final class SettingsAndContentServer implements ImmediateRequestGenerator { final ModuleConfigurationTests.ServerConfigResponder settings = new ModuleConfigurationTests.ServerConfigResponder(); final List contentFetches = new CopyOnWriteArrayList<>(); + final List queuedRequestsAtFetch = new CopyOnWriteArrayList<>(); volatile String contentResponse = NO_CONTENT_RESPONSE; /** @@ -465,6 +421,7 @@ public ImmediateRequestI createImmediateRequestMaker() { callback.callback(null); return; } + queuedRequestsAtFetch.add(queuedRequestCount()); contentFetches.add(requestData); callback.callback(new JSONObject(contentResponse)); }; diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationLimitsTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationLimitsTests.java index 88853b8b..0b6860d5 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationLimitsTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationLimitsTests.java @@ -69,12 +69,10 @@ public void afterTest() { // region scenarios /** - * {@code lkl}, {@code lvs} and {@code lsv} cut custom events after the listing filters and the - * journey trigger match, which see the full key, while an internal event only gets the string - * values of its widget result cut. + * {@code lkl}, {@code lvs} and {@code lsv} cut custom events after the listing filters, which see + * the full key, while an internal event only gets the string values of its widget result cut. *

- * Verifies on the wire that a journey trigger listed by its full key sends the queue at once, that - * its key is cut to 5 characters, that a segmentation key blacklisted by its full name and an + * Verifies on the wire, once the queue is sent, that the key of an event is cut to 5 characters, that a segmentation key blacklisted by its full name and an * entry of an unsupported type are removed before the entry limit counts while a key blacklisted * only by its truncated form is kept, that of two keys cut to the same key the one that sorts last * keeps its value, that string values are cut to 6 characters, that past 2 entries the keys that @@ -84,11 +82,10 @@ public void afterTest() { * result keeps every key and entry and the values the SDK adds, only its own strings being cut. */ @Test - public void customEvents_areCutAfterTheFiltersAndTheJourneyTriggerSawTheFullKey_andInternalEventsOnlyGetWidgetValuesCut() { + public void customEvents_areCutAfterTheFilters_andInternalEventsOnlyGetWidgetValuesCut() { server.respondWith(smallLimits() .eventFilterList(names("purchase_completed", "timed_checkout", "check"), true) - .segmentationFilterList(names("internal_notes", "payme"), false) - .journeyTriggerEvents(names("purchase_completed"))); + .segmentationFilterList(names("internal_notes", "payme"), false)); init(configWithWarnings().enableFeatures(Config.Feature.Events, Config.Feature.Feedback).setEventQueueSizeToSend(100)); Map segmentation = new HashMap<>(); @@ -100,7 +97,7 @@ public void customEvents_areCutAfterTheFiltersAndTheJourneyTriggerSawTheFullKey_ segmentation.put("zz_note", "dropped_by_the_entry_limit"); Map callers = Collections.unmodifiableMap(new HashMap<>(segmentation)); Countly.instance().events().recordEvent("purchase_completed", callers, 2, 9.99); - TestUtils.letTheClockCatchUp(); + sendEventQueue(); List sent = sentEvents(); Assert.assertEquals(keysOf(sent).toString(), 1, sent.size()); @@ -148,12 +145,12 @@ public void customEvents_areCutAfterTheFiltersAndTheJourneyTriggerSawTheFullKey_ * reserved key is removed so an end event never carries {@code visit}, that an entry of an * unsupported type takes no place under the entry limit, that past 2 entries the keys that sort * last are dropped while {@code name}, {@code visit}, {@code start} and - * {@code segment} stay with their values uncut, that a journey trigger view matches the name as - * sent, and that a view started under a long name is still stopped by that name. + * {@code segment} stay with their values uncut, and that a view started under a long name is still + * stopped by that name. */ @Test public void views_nameAndSegmentationAreCut_whileTheKeysTheSdkAddsAreNeitherCutNorCounted() { - server.respondWith(smallLimits().journeyTriggerViews(names("Setti"))); + server.respondWith(smallLimits()); init(configWithWarnings().enableFeatures(Config.Feature.Events, Config.Feature.Views).setEventQueueSizeToSend(100)); String platform = SDKCore.instance.config.getSdkPlatform(); Countly.instance().views().setGlobalViewSegmentation(TestUtils.map("global_key", "global_value")); @@ -162,7 +159,7 @@ public void views_nameAndSegmentationAreCut_whileTheKeysTheSdkAddsAreNeitherCutN TestUtils.letTheClockCatchUp(); Countly.instance().views().addSegmentationToViewWithID(viewId, TestUtils.map("added_key", "added_value", "bb_second", 2)); Countly.instance().views().stopViewWithID(viewId, TestUtils.map("visitor_type", "new_visitor", "cc_third", "third_value", "aa_unsupported", new int[] { 1 })); - TestUtils.letTheClockCatchUp(); + sendEventQueue(); List sent = sentEvents(); Assert.assertEquals(keysOf(sent).toString(), 2, sent.size()); @@ -185,7 +182,7 @@ public void views_nameAndSegmentationAreCut_whileTheKeysTheSdkAddsAreNeitherCutN Assert.assertEquals("1", queued.get(1).segmentation.get(ModuleViews.KEY_VISIT)); assertEvent(queued.get(2), ModuleViews.KEY_VIEW_EVENT, TestUtils.map("globa", "global", ModuleViews.KEY_NAME, "Profi", ModuleViews.KEY_SEGMENT, platform)); - Assert.assertEquals(2, TestUtils.getCurrentRQ().length); + Assert.assertEquals(1, TestUtils.getCurrentRQ().length); } /** @@ -647,6 +644,14 @@ private int warningsContaining(String text) { * * @return the events */ + /** + * Moves the queued events into a request and waits until it is stored. + */ + private static void sendEventQueue() { + SDKCore.instance.module(ModuleEvents.class).checkEventQueueToSend(true); + TestUtils.letTheClockCatchUp(); + } + private static List sentEvents() { List events = new ArrayList<>(); int requestCount = TestUtils.getCurrentRQ().length; diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationNetworkTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationNetworkTests.java index 2ae7b0eb..92db25d2 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationNetworkTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationNetworkTests.java @@ -366,78 +366,6 @@ public void requestDropAge_dropsTheStoredRequestsOlderThanIt_unsent_andZeroDrops Assert.assertEquals(0, logsContaining(DROPPED_UNSENT)); } - /** - * A journey trigger whose request is dropped for its age is settled, while a later trigger still - * refreshes the content zone. - *

- * Verifies against a local server that a trigger request recorded while networking is off and - * aged past {@code dort} on disk is dropped unsent once networking is back on, that its owner is - * told with {@link Transport#NO_RESPONSE_CODE}, which leaves no pending trigger and the zone - * inactive, and that a fresh trigger is then sent, accepted and enters the zone. - */ - @Test - public void requestDropAge_settlesTheJourneyTriggerOfADroppedRequest_andALaterTriggerStillRefreshes() throws Exception { - startQueueServer(); - server.settings.failing(); - init(networkedConfig().enableFeatures(Config.Feature.Content).setEventQueueSizeToSend(100) - .setSdkBehaviorSettings(new ServerConfigBuilder().networking(false).journeyTriggerEvents(names("purchase")).dropOldRequestTime(1).build())); - holdTheZoneTimer(); - Countly.instance().content().setContentDisplay(new FakeDisplay()); - assertZoneIsInactive(0); - - Countly.instance().events().recordEvent("purchase"); - TestUtils.letTheClockCatchUp(); - Assert.assertEquals(1, TestUtils.getCurrentRQ().length); - Set pending = SDKCore.instance.module(ModuleEvents.class).journeyTriggerRequestIds; - Assert.assertEquals(storedRequestIds(), pending); - Assert.assertEquals(1, pending.size()); - ageStoredRequests(2 * HOUR_MS); - - push(new ServerConfigBuilder().networking(true).journeyTriggerEvents(names("purchase")).dropOldRequestTime(1)); - Assert.assertTrue("the aged request was never dropped, logs: " + logs, waitNudging(() -> queuedRequestCount() == 0)); - Assert.assertEquals(1, logsContaining(DROPPED_UNSENT)); - awaitLogs("carrying a journey trigger failed with code [" + Transport.NO_RESPONSE_CODE + "], the content zone is not refreshed", 1); - Assert.assertTrue(pending.isEmpty()); - Assert.assertTrue(queueServer.received.isEmpty()); - assertZoneIsInactive(0); - - Countly.instance().events().recordEvent("purchase"); - awaitZoneFetch(1); - Assert.assertEquals(Collections.singletonList("purchase"), receivedEventKeys()); - Assert.assertTrue(pending.isEmpty()); - Assert.assertEquals(1, logsContaining(DROPPED_UNSENT)); - } - - /** - * The request queue trim settles the journey triggers of the requests it drops unread. - *

- * Verifies on disk, with networking off and {@code rqs} 2, that each journey trigger waits for - * its own request, and that a third trigger, whose request drops the oldest one, leaves waiting - * only the triggers of the two requests still queued. - */ - @Test - public void requestQueueTrim_settlesTheJourneyTriggersOfTheRequestsItDrops() { - server.settings.respondWith(new ServerConfigBuilder().networking(false).requestQueueSize(2).journeyTriggerEvents(names("purchase"))); - init(TestUtils.getConfigSdkBehaviorSettings() - .enableFeatures(Config.Feature.Events) - .setEventQueueSizeToSend(100) - .setLogListener((message, level) -> logs.add(message))); - Set pending = SDKCore.instance.module(ModuleEvents.class).journeyTriggerRequestIds; - - recordEvents("purchase", "purchase"); - Assert.assertEquals(2, TestUtils.getCurrentRQ().length); - Set firstTwo = storedRequestIds(); - Assert.assertEquals(firstTwo, pending); - long oldest = Collections.min(firstTwo); - - recordEvents("purchase"); - Assert.assertEquals(2, TestUtils.getCurrentRQ().length); - Set lastTwo = storedRequestIds(); - Assert.assertFalse(lastTwo.contains(oldest)); - Assert.assertEquals(lastTwo, pending); - Assert.assertEquals(1, logsContaining("the request [" + oldest + "] carrying a journey trigger was dropped from the queue without being sent")); - } - // endregion // region helpers diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationTests.java index 318abc3c..11ae5911 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationTests.java @@ -44,7 +44,7 @@ @RunWith(JUnit4.class) public class ModuleConfigurationTests { - private static final Set TOP_LEVEL_KEYS = names("v", "t", "c", "lg", "ct", "gzip"); + private static final Set TOP_LEVEL_KEYS = names("v", "t", "c", "lg", "ct", "gzip", "jt"); private ServerConfigResponder server; @@ -708,7 +708,6 @@ public void journeyTrigger_endedByADeviceIdChange_isSentUnderThePreviousDeviceId Assert.assertEquals(2, events.size()); Assert.assertEquals("old_user_event", events.get(0).key); Assert.assertEquals("checkout", events.get(1).key); - Assert.assertTrue(SDKCore.instance.module(ModuleEvents.class).journeyTriggerRequestIds.isEmpty()); } /** diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleHealthCheckTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleHealthCheckTests.java index 51d79d88..aca1aab1 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleHealthCheckTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleHealthCheckTests.java @@ -99,6 +99,13 @@ static class MemoryStorage implements StorageProvider { healthCheckState = state; } + @Override public String getContentTriggerGaps() { + return null; + } + + @Override public void setContentTriggerGaps(String gaps) { + } + @Override public void incrementAutomaticCrashCount() { automaticCrashes++; } From 89b06b410ae8f94834a8c4dc9e859bcf8daffe0f Mon Sep 17 00:00:00 2001 From: turtledreams <62231246+turtledreams@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:37:07 +0900 Subject: [PATCH 2/2] Keep the content trigger flags visible to other threads The flags read at init are atomic, the match comment is shorter, and the new tests declare the exceptions they throw. --- .../ly/count/sdk/java/internal/ContentTriggers.java | 11 ++--------- .../count/sdk/java/internal/ModuleConfiguration.java | 10 +++++----- .../ly/count/sdk/java/internal/ModuleContent.java | 6 +++--- .../internal/ModuleConfigurationContentTests.java | 8 ++++---- 4 files changed, 14 insertions(+), 21 deletions(-) diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ContentTriggers.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ContentTriggers.java index 9268537f..47d35a7d 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ContentTriggers.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ContentTriggers.java @@ -199,16 +199,9 @@ static final class Match { } /** - * Whether what was recorded is a content trigger. When the server sent content triggers, only they decide, and - * only while the app wants the content zone. Otherwise (an older server, or disableAutoContentTriggers) a custom - * event key in the journey trigger events and a view name in the journey trigger views decide, also while the app - * doesn't want the content zone. + * Whether what was recorded is a content trigger: the content triggers decide while the zone is wanted, else the + * journey trigger events ("jte") and views ("jtv") decide. * - * @param contentTriggers the content triggers in use, null when there are none - * @param zoneWanted true after the app or the "ecz" setting entered the content zone, until it is exited - * @param journeyTriggerEvents the journey trigger events ("jte") - * @param journeyTriggerViews the journey trigger views ("jtv") - * @param trigger what was recorded * @return the match, or null when it is not a content trigger */ @Nullable diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleConfiguration.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleConfiguration.java index 727eb72e..c9e78c3d 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleConfiguration.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleConfiguration.java @@ -176,7 +176,7 @@ public class ModuleConfiguration extends ModuleBase implements ConfigurationProv * Whether the SDK neither asks for the content triggers nor follows them, from * {@link ConfigContent#disableAutoContentTriggers()}. */ - boolean autoContentTriggersDisabled = false; + final AtomicBoolean autoContentTriggersDisabled = new AtomicBoolean(false); /** * Whether settings were stored or provided at init. Without them the first settings answer of * the run decides whether the content zone is entered. @@ -251,8 +251,8 @@ public void init(InternalConfig config) { boolean backendMode = config.isBackendModeEnabled(); serverConfigRequestsDisabled = backendMode || config.isSdkBehaviorSettingsRequestsDisabled(); requestCompressionEnabled.set(config.isRequestCompressionEnabled()); - autoContentTriggersDisabled = config.content.autoContentTriggersDisabled; - L.d("[ModuleConfiguration] init, backend mode:[" + backendMode + "], server config requests disabled:[" + serverConfigRequestsDisabled + "], content triggers disabled:[" + autoContentTriggersDisabled + "]"); + autoContentTriggersDisabled.set(config.content.autoContentTriggersDisabled); + L.d("[ModuleConfiguration] init, backend mode:[" + backendMode + "], server config requests disabled:[" + serverConfigRequestsDisabled + "], content triggers disabled:[" + autoContentTriggersDisabled.get() + "]"); seedFromDeveloperConfig(config); developerValues = developerDefaults(config); @@ -512,7 +512,7 @@ synchronized boolean saveAndStoreDownloadedConfig(@Nonnull JSONObject config) { //validation already removed every value that is not a usable setting, so the settings object is kept as it is latestRetrievedConfiguration = config.optJSONObject(keyRConfig); - currentVContentTriggers.set(autoContentTriggersDisabled ? null : ContentTriggers.parse(config.opt(keyRContentTriggers), L)); + currentVContentTriggers.set(autoContentTriggersDisabled.get() ? null : ContentTriggers.parse(config.opt(keyRContentTriggers), L)); internalConfig.storageProvider.setServerConfig(new JSONObject(config, keyRVersion, keyRTimestamp, keyRConfig, keyRContentTriggers).toString()); return true; } @@ -931,7 +931,7 @@ void fetchConfigFromServer(@Nonnull InternalConfig config) { if (requestCompressionEnabled.get()) { params.add("gzip", "1"); } - if (!autoContentTriggersDisabled) { + if (!autoContentTriggersDisabled.get()) { params.add(keyRContentTriggers, "1"); } String requestData = params.toString(); diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleContent.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleContent.java index d2a1a24f..0992e028 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleContent.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleContent.java @@ -69,7 +69,7 @@ public class ModuleContent extends ModuleBase { private int waitForDelay = 0; private int generation = 0; /** The {@code ecz} value of the settings in use at init, which decides the entry at init. */ - private boolean contentZoneEnabledAtInit = false; + private final AtomicBoolean contentZoneEnabledAtInit = new AtomicBoolean(false); /** Whether the {@code ecz} setting decided to enter the zone, which then happens once a display is registered. */ private final AtomicBoolean settingsAskForZone = new AtomicBoolean(false); /** Set after the application or the {@code ecz} setting entered the zone, until the zone is left. */ @@ -109,7 +109,7 @@ public void init(InternalConfig config) { display = config.sdk.contentDisplay; } // the settings in use at init decide the entry, also when an answer arrives before init ends - contentZoneEnabledAtInit = config.getConfigurationProvider().getContentZoneEnabled(); + contentZoneEnabledAtInit.set(config.getConfigurationProvider().getContentZoneEnabled()); triggerExecutor = Executors.newSingleThreadScheduledExecutor(runnable -> { Thread thread = new Thread(runnable, "Countly-content-triggers"); thread.setDaemon(true); @@ -126,7 +126,7 @@ public void init(InternalConfig config) { @Override protected void initFinished(InternalConfig config) { super.initFinished(config); - if (contentZoneEnabledAtInit) { + if (contentZoneEnabledAtInit.get()) { enterContentZoneForSettings("initFinished"); } } diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationContentTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationContentTests.java index 999dcecb..8e8f8340 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationContentTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationContentTests.java @@ -198,7 +198,7 @@ public void contentTriggers_areAskedForAndStored_unlessTurnedOff() { * follow, and that the same event inside its gap starts no round. */ @Test - public void contentTriggers_aListedEventSendsTheQueueThenAsksForContent() throws Exception { + public void contentTriggers_aListedEventSendsTheQueueThenAsksForContent() throws IOException, InterruptedException { startQueueServer(); server.settings.respondWith(new ServerConfigBuilder().topLevelKey("jt", triggers("e", "purchase"))); init(networkedContentConfig()); @@ -223,7 +223,7 @@ public void contentTriggers_aListedEventSendsTheQueueThenAsksForContent() throws * triggers, even an empty one, makes the SDK ignore the journey trigger events. */ @Test - public void contentTriggers_needTheContentZone_andHideTheJourneyTriggerEvents() throws Exception { + public void contentTriggers_needTheContentZone_andHideTheJourneyTriggerEvents() throws IOException, InterruptedException { startQueueServer(); server.settings.respondWith(new ServerConfigBuilder().journeyTriggerEvents(names("legacy")).topLevelKey("jt", triggers("e", "purchase"))); init(networkedContentConfig()); @@ -249,7 +249,7 @@ public void contentTriggers_needTheContentZone_andHideTheJourneyTriggerEvents() * and a listed view when it starts and again when it ends, each with its own gap. */ @Test - public void journeyTriggers_askForContentDirectly_forEventsOfTheAppAndBothEventsOfAView() throws Exception { + public void journeyTriggers_askForContentDirectly_forEventsOfTheAppAndBothEventsOfAView() throws IOException, InterruptedException { startQueueServer(); server.settings.respondWith(new ServerConfigBuilder().refreshContentZone(false) .journeyTriggerEvents(names("purchase", "[CLY]_star_rating")) @@ -277,7 +277,7 @@ public void journeyTriggers_askForContentDirectly_forEventsOfTheAppAndBothEvents * are triggers too. */ @Test - public void contentTriggers_earlyTriggerAndTheOtherTriggerKinds() throws Exception { + public void contentTriggers_earlyTriggerAndTheOtherTriggerKinds() throws IOException, InterruptedException { startQueueServer(); server.settings.pending(); init(networkedContentConfig().enableFeatures(Config.Feature.CrashReporting, Config.Feature.UserProfiles));