diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..01eda9268 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @turtledreams @arifBurakDemiray diff --git a/.github/dependabot.yml b/.github/dependabot.yml index edf452cf5..3de5b3dc0 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -26,6 +26,12 @@ updates: target-branch: staging schedule: interval: monthly + # CodeQL's init and analyze steps must run the same version or the analyze + # step fails, so their updates come in one PR. + groups: + codeql: + patterns: + - "github/codeql-action*" labels: - dependencies - ci diff --git a/.github/release-contract/java-ui.json b/.github/release-contract/java-ui.json new file mode 100644 index 000000000..7caab10da --- /dev/null +++ b/.github/release-contract/java-ui.json @@ -0,0 +1,14 @@ +{ + "schema": 1, + "coordinates": "ly.count.sdk:java-ui", + "pomDependencies": [ + "ly.count.sdk:java:26.8.0:compile", + "org.json:json:20260814:runtime", + "org.openjfx:javafx-controls:21.0.5:runtime", + "org.openjfx:javafx-web:21.0.5:runtime" + ], + "moduleVariantAttributes": { + "org.gradle.jvm.version": 17 + }, + "maxClassFileMajor": 61 +} diff --git a/.github/release-contract/java.json b/.github/release-contract/java.json new file mode 100644 index 000000000..91eeeb28c --- /dev/null +++ b/.github/release-contract/java.json @@ -0,0 +1,12 @@ +{ + "schema": 1, + "coordinates": "ly.count.sdk:java", + "pomDependencies": [ + "com.google.code.findbugs:jsr305:3.0.2:runtime", + "org.json:json:20260814:runtime" + ], + "moduleVariantAttributes": { + "org.gradle.jvm.version": 8 + }, + "maxClassFileMajor": 52 +} diff --git a/.github/release/.gitignore b/.github/release/.gitignore new file mode 100644 index 000000000..4dd207434 --- /dev/null +++ b/.github/release/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +consumers/maven/target/ diff --git a/.github/release/checks.py b/.github/release/checks.py new file mode 100644 index 000000000..3de8799f7 --- /dev/null +++ b/.github/release/checks.py @@ -0,0 +1,42 @@ +"""Checks before a release: the tag commit's release branch, its required status checks and the publish environment.""" + +import subprocess + + +def is_ancestor(commit, ref, repo_root, runner=subprocess.run): + """Whether the commit is the ref or one of its ancestors.""" + return runner(["git", "-C", str(repo_root), "merge-base", "--is-ancestor", commit, ref], capture_output=True).returncode == 0 + + +def branch_problems(commit, branch, repo_root, runner=subprocess.run): + """Problems unless the commit is an ancestor of origin/.""" + return [] if is_ancestor(commit, f"origin/{branch}", repo_root, runner) else [f"{commit} is not on origin/{branch}; the tag must point to that branch"] + + +def missing_checks(check_runs, required): + """Required check names that did not succeed on the commit, from the GitHub check-runs API response: a name without + any run, or with any run that did not succeed or has not finished. A commit can carry several runs of one check, + for example one from the push to the release branch and one from a pull request whose head it is, which tests a + merge with another branch; each of them must have passed.""" + problems = [] + for name in required: + conclusions = [run.get("conclusion") for run in check_runs.get("check_runs", []) if run["name"] == name] + if not conclusions or any(conclusion != "success" for conclusion in conclusions): + problems.append(name) + return problems + + +def environment_problems(environment): + """Problems unless the deployment environment, as the GitHub environments API returns it, makes a reviewer approve + the publish job and limits deployments to selected branches and tags. GitHub creates an environment a job names on + first use with neither rule, and once the signing and upload secrets are added to it the job would publish + unattended. Releases run on tags, which a protected-branches-only policy would refuse after the build, so only + selected rules count.""" + name = environment.get("name") + rules = environment.get("protection_rules") or [] + problems = [] + if not any(rule.get("type") == "required_reviewers" and rule.get("reviewers") for rule in rules): + problems.append(f"environment {name} does not require a reviewer to approve the publish job") + if not (environment.get("deployment_branch_policy") or {}).get("custom_branch_policies"): + problems.append(f"environment {name} does not limit deployments to selected branches and tags") + return problems diff --git a/.github/release/config.json b/.github/release/config.json new file mode 100644 index 000000000..d7bc32b7e --- /dev/null +++ b/.github/release/config.json @@ -0,0 +1,32 @@ +{ + "repository": "Countly/countly-sdk-java", + "publicBaseUrl": { "production": "https://maven.countly.com/", "test": "https://maven-test.countly.com/" }, + "centralBaseUrl": "https://repo1.maven.org/maven2/", + "publishedModules": ":sdk-java,:sdk-java-ui", + "platformSpecificGroups": ["org.openjfx"], + "requiredChecks": ["Build and Test", "Test on ubuntu-latest", "Test on windows-latest", "OSV scan (all modules)", "Analyze (java)"], + "tagRules": [ + { "tag": "{version}", "branch": "staging", "artifacts": ["java"] }, + { "tag": "ui-{version}", "branch": "staging", "artifacts": ["java-ui"] } + ], + "artifacts": { + "java": { + "group": "ly.count.sdk", "artifact": "java", "module": ":sdk-java", + "contract": ".github/release-contract/java.json", "consumerJava": 8, + "versionSources": [ + { "file": "gradle.properties", "regex": "^VERSION_NAME=(.+)$" }, + { "file": "build.gradle", "regex": "ext\\.CLY_VERSION = \"([^\"]+)\"" }, + { "file": "sdk-java/src/main/java/ly/count/sdk/java/Config.java", "regex": "protected String sdkVersion = \"([^\"]+)\"" } + ], + "changelog": "CHANGELOG.md" + }, + "java-ui": { + "group": "ly.count.sdk", "artifact": "java-ui", "module": ":sdk-java-ui", + "contract": ".github/release-contract/java-ui.json", "consumerJava": 17, + "versionSources": [ + { "file": "sdk-java-ui/gradle.properties", "regex": "^VERSION_NAME=(.+)$" } + ], + "changelog": "sdk-java-ui/CHANGELOG.md" + } + } +} diff --git a/.github/release/consumers.py b/.github/release/consumers.py new file mode 100644 index 000000000..6b269c872 --- /dev/null +++ b/.github/release/consumers.py @@ -0,0 +1,60 @@ +"""Commands for the clean projects in .github/release/consumers that build against a staged release.""" + +import re +from pathlib import Path + +GRADLE_PROJECT = ".github/release/consumers/gradle" +MAVEN_POM = ".github/release/consumers/maven/pom.xml" +GRADLE_FLAGS = ["--no-daemon", "--no-configuration-cache", "--stacktrace"] +PROBE_CLASS = "ly.count.consumer.Probe" +REPOSITORY_ID = "countly" +# Maven 3.9 records the repository as "countly=", Maven 3.10 as "countly-=". A hex-only suffix +# keeps the "countly-public" repository out. +STAGED_SOURCE = re.compile(rf"{REPOSITORY_ID}(-[0-9a-f]+)?=") + + +def gradle_command(gradlew, repository, public_repository, plan, artifact): + """Builds the Gradle consumer against one artifact of the plan and installs it with its runtime classpath. Only the + plan's artifacts come from the staging folder; any other Countly package they need, such as the core SDK of a UI + release, comes from the public repository or Maven Central, as it does for an integrator.""" + staged = ",".join(item.coordinates for item in plan.artifacts) + return [ + gradlew, "-p", GRADLE_PROJECT, *GRADLE_FLAGS, "clean", "installDist", + f"-PcountlyRepository={repository}", f"-PcountlyPublicRepository={public_repository}", f"-PcountlyStaged={staged}", + f"-PcountlyDependency={artifact.coordinates}:{plan.version}", + f"-PcountlyRelease={artifact.consumer_java}", f"-PcountlyProbe={artifact.artifact}", + ] + + +def maven_command(mvn, repository, public_repository, artifact, version, local_repository): + """Compiles the Maven consumer against one artifact version, with an empty local repository so nothing is reused. + Maven looks in the staging folder first, then in the public repository, then on Maven Central.""" + return [ + mvn, "-B", "-f", MAVEN_POM, "clean", "compile", + f"-Dcountly.repository={repository}", f"-Dcountly.publicRepository={public_repository}", + f"-Dcountly.artifact={artifact.artifact}", f"-Dcountly.version={version}", + f"-Dcountly.release={artifact.consumer_java}", f"-Dmaven.repo.local={local_repository}", + ] + + +def smoke_command(java_home, repo_root): + """Runs the probe the Gradle consumer installed, on the given Java runtime, with the installed runtime classpath.""" + java = Path(java_home) / "bin" / "java" + classpath = Path(repo_root) / GRADLE_PROJECT / "build/install/countly-consumer/lib/*" + return [str(java), "-cp", str(classpath), PROBE_CLASS] + + +def maven_source_problems(local_repository, plan, consumed): + """Problems when Maven did not take the consumed artifact, and every other artifact of the plan it downloaded, from + the staged release; Maven records the source repository of every downloaded file in _remote.repositories.""" + problems = [] + for artifact in plan.artifacts: + record = Path(local_repository) / artifact.folder(plan.version) / "_remote.repositories" + if not record.is_file(): + if artifact == consumed: + problems.append(f"Maven did not download {artifact.coordinates}:{plan.version}") + continue + sources = [line.split(">", 1)[1] for line in record.read_text(encoding="utf-8").splitlines() if ">" in line and not line.startswith("#")] + if not sources or any(not STAGED_SOURCE.fullmatch(source) for source in sources): + problems.append(f"Maven resolved {artifact.coordinates}:{plan.version} from another repository than the staged release") + return problems diff --git a/.github/release/consumers/gradle/build.gradle b/.github/release/consumers/gradle/build.gradle new file mode 100644 index 000000000..e9075b4fe --- /dev/null +++ b/.github/release/consumers/gradle/build.gradle @@ -0,0 +1,20 @@ +plugins { + id 'java' + id 'application' +} + +def probe = findProperty('countlyProbe') + +sourceSets.main.java.srcDirs = ["../probes/${probe}"] + +tasks.withType(JavaCompile).configureEach { + options.release = Integer.parseInt(findProperty('countlyRelease')) +} + +dependencies { + implementation findProperty('countlyDependency') +} + +application { + mainClass = 'ly.count.consumer.Probe' +} diff --git a/.github/release/consumers/gradle/settings.gradle b/.github/release/consumers/gradle/settings.gradle new file mode 100644 index 000000000..aeac43f85 --- /dev/null +++ b/.github/release/consumers/gradle/settings.gradle @@ -0,0 +1,27 @@ +def countlyRepository = gradle.startParameter.projectProperties['countlyRepository'] +def countlyPublicRepository = gradle.startParameter.projectProperties['countlyPublicRepository'] +def countlyStaged = gradle.startParameter.projectProperties['countlyStaged'].split(',') + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + exclusiveContent { + forRepository { + maven { url = countlyRepository } + } + filter { + countlyStaged.each { coordinates -> + def (group, name) = coordinates.split(':') + includeModule(group, name) + } + } + } + mavenCentral() + maven { + url = countlyPublicRepository + content { includeGroupByRegex 'ly\\.count\\..*' } + } + } +} + +rootProject.name = 'countly-consumer' diff --git a/.github/release/consumers/maven/pom.xml b/.github/release/consumers/maven/pom.xml new file mode 100644 index 000000000..66e339ad1 --- /dev/null +++ b/.github/release/consumers/maven/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + ly.count.consumer + countly-consumer + 1 + + + UTF-8 + ${countly.release} + + + + + countly + ${countly.repository} + + + countly-public + ${countly.publicRepository} + + + + + + ly.count.sdk + ${countly.artifact} + ${countly.version} + + + + + ${project.basedir}/../probes/${countly.artifact} + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.0 + + + + diff --git a/.github/release/consumers/probes/java-ui/ly/count/consumer/Probe.java b/.github/release/consumers/probes/java-ui/ly/count/consumer/Probe.java new file mode 100644 index 000000000..b4ea458b1 --- /dev/null +++ b/.github/release/consumers/probes/java-ui/ly/count/consumer/Probe.java @@ -0,0 +1,18 @@ +package ly.count.consumer; + +import ly.count.sdk.java.ui.CountlyWebView; +import ly.count.sdk.java.ui.JavaFxContentDisplay; + +/** + * Compiles against the UI artifact the way an integrator would. + */ +public class Probe { + /** + * Reads a setting of the UI artifact and names its content display class. + * + * @param args unused + */ + public static void main(String[] args) { + System.out.println("widgets within app " + CountlyWebView.isShowingWidgetsWithinApp() + ", display " + JavaFxContentDisplay.class.getName()); + } +} diff --git a/.github/release/consumers/probes/java/ly/count/consumer/Probe.java b/.github/release/consumers/probes/java/ly/count/consumer/Probe.java new file mode 100644 index 000000000..792838993 --- /dev/null +++ b/.github/release/consumers/probes/java/ly/count/consumer/Probe.java @@ -0,0 +1,20 @@ +package ly.count.consumer; + +import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; + +/** + * Loads the core SDK the way an integrator would, without contacting a server. + */ +public class Probe { + /** + * Creates a configuration and reads the shared instance; a class the runtime cannot load stops here. + * + * @param args unused + */ + public static void main(String[] args) { + Config config = new Config("https://consumer.invalid", "consumer-probe"); + System.out.println("Countly " + config.getSdkVersion() + " loaded on Java " + System.getProperty("java.version") + + ", instance " + Countly.instance().getClass().getName() + ", initialized " + Countly.isInitialized()); + } +} diff --git a/.github/release/contract.py b/.github/release/contract.py new file mode 100644 index 000000000..4dc3e2ab4 --- /dev/null +++ b/.github/release/contract.py @@ -0,0 +1,113 @@ +"""Compares what a staged artifact promises integrators with its committed contract file.""" + +import io +import json +import zipfile +import xml.etree.ElementTree as ElementTree +from pathlib import Path + +POM_NAMESPACE = {"m": "http://maven.apache.org/POM/4.0.0"} +JVM_VERSION = "org.gradle.jvm.version" + + +def _child(element, tag, default=""): + return (element.findtext(f"m:{tag}", default, POM_NAMESPACE) or default).strip() + + +def pom_dependencies(pom): + """Sorted group:artifact:version:scope strings of the POM's direct dependencies.""" + root = ElementTree.fromstring(pom) + return sorted( + f"{_child(d, 'groupId')}:{_child(d, 'artifactId')}:{_child(d, 'version')}:{_child(d, 'scope', 'compile')}" + for d in root.findall("m:dependencies/m:dependency", POM_NAMESPACE) + ) + + +def module_variants(module): + """Library variants (not sources or javadoc) of a Gradle module file.""" + return [variant for variant in json.loads(module).get("variants", []) if variant.get("attributes", {}).get("org.gradle.category") == "library"] + + +def module_dependencies(module): + """Sorted group:module:version strings declared by the library variants of a Gradle module file.""" + found = set() + for variant in module_variants(module): + for dependency in variant.get("dependencies", []): + version = dependency.get("version", {}) + number = version.get("requires") or version.get("strictly") or version.get("prefers") or "" + found.add(f"{dependency['group']}:{dependency['module']}:{number}") + return sorted(found) + + +def max_class_major(jar): + """Highest class-file major version in a jar (52 is Java 8), ignoring multi-release folders.""" + highest = 0 + with zipfile.ZipFile(io.BytesIO(jar)) as archive: + for name in archive.namelist(): + if name.endswith(".class") and not name.startswith("META-INF/versions/"): + head = archive.read(name)[:8] + if len(head) == 8 and head[:4] == b"\xca\xfe\xba\xbe": + highest = max(highest, (head[6] << 8) | head[7]) + return highest + + +def _common(variants, key): + """The attribute value all variants share (None when absent), or a note that they differ.""" + values = {json.dumps(variant.get("attributes", {}).get(key)) for variant in variants} + if len(values) == 1: + return json.loads(values.pop()) + return None if not values else "differs between variants" + + +def actual_contract(staging_dir, artifact, version): + """The contract the staged files of one artifact version fulfil, in the shape of the contract files (schema 1).""" + folder = Path(staging_dir) / artifact.folder(version) + base = artifact.base_name(version) + return { + "schema": 1, + "coordinates": artifact.coordinates, + "pomDependencies": pom_dependencies((folder / f"{base}.pom").read_bytes()), + "moduleVariantAttributes": {JVM_VERSION: _common(module_variants((folder / f"{base}.module").read_bytes()), JVM_VERSION)}, + "maxClassFileMajor": max_class_major((folder / f"{base}.jar").read_bytes()), + } + + +def compare(expected, actual): + """Differences between the committed contract and the staged artifact, as readable problems.""" + problems = [] + if expected["coordinates"] != actual["coordinates"]: + problems.append(f"coordinates are {actual['coordinates']}, the contract says {expected['coordinates']}") + if expected["pomDependencies"] != actual["pomDependencies"]: + problems.append(f"POM dependencies are {actual['pomDependencies']}, the contract says {expected['pomDependencies']}") + for key, value in expected.get("moduleVariantAttributes", {}).items(): + found = actual["moduleVariantAttributes"].get(key) + if found != value: + problems.append(f"{key} is {found}, the contract says {value}") + if actual["maxClassFileMajor"] > expected["maxClassFileMajor"]: + problems.append(f"class files reach major version {actual['maxClassFileMajor']}, the contract allows {expected['maxClassFileMajor']}") + return problems + + +def module_dependency_problems(staging_dir, artifact, version): + """Problems when the .module declares other dependencies than the POM; Gradle builds read the .module, Maven builds the POM.""" + folder = Path(staging_dir) / artifact.folder(version) + base = artifact.base_name(version) + in_module = module_dependencies((folder / f"{base}.module").read_bytes()) + in_pom = sorted(entry.rsplit(":", 1)[0] for entry in pom_dependencies((folder / f"{base}.pom").read_bytes())) + return [] if in_module == in_pom else [f"the .module declares {in_module} but the POM declares {in_pom}"] + + +def _shown(value): + return "absent" if value is None else str(value) + + +def summary_rows(expected, actual): + """(property, contract, built) rows for the job summary table.""" + def listing(values): + return ", ".join(values) if values else "none" + + return [ + ("POM dependencies", listing(expected["pomDependencies"]), listing(actual["pomDependencies"])), + (JVM_VERSION, _shown(expected.get("moduleVariantAttributes", {}).get(JVM_VERSION)), _shown(actual["moduleVariantAttributes"].get(JVM_VERSION))), + ("highest class file version", f"at most {expected['maxClassFileMajor']}", str(actual["maxClassFileMajor"])), + ] diff --git a/.github/release/countly-sdk-signing.asc b/.github/release/countly-sdk-signing.asc new file mode 100644 index 000000000..3d024de9d --- /dev/null +++ b/.github/release/countly-sdk-signing.asc @@ -0,0 +1,54 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- +Comment: Hostname: +Version: Hockeypuck 2.2 + +xsFNBGCBvh0BEADYg3FP0080Vx4RfDvWkC7TfqhhypIR3yBOrIomLLLatsWAnSLO +wOm0HyfldcgrAEK8pm+i2G65QorLKep4nmL5UQ44CU+iEeiEW5obP3Wdw4teA+ra +DNTQ221i8tVQcGYVQwWY1pS0Zkh6ZrEjuSZysm5klABAk1qdh640FB7jX6WUPh28 +vRO4HRC5bSOaL5INyV/tSOhemHqhw1WI8euWFMjIaOAWrI7sMqGl4doxSdSWz04P +JyarHOlwwQxt/PRFWWF+Vkm/ByuAYpp4/yYvUHJBohwwjV+CS2Ouq4rfMfpx1Y67 +1nv7ihiE4rAnmy2QQS0R8DvVWEfesfRldkb7k4XxNbKuOBTvfUozZx9yiNIq3HhI +5qtni/rVadgtZRre051rfJDXFFajEL1bLWPvJFasH1S3BM6n6BmALdkQ9mKvAh3w +mcxWCzmlK89d+QKRXvdq5t6+PTkoOcvWhLiRF0QUwE0SW8yYUQRXMQuIta7mZFvU +P3urgM075fdO90GgZYrFyaUiGFXlBEhM3pZ41ohywVnXJIbP8AcY7xvCb2B2sBfq +75IVye4lH9dC7GZeVUODU1MiHPZ6IHuxfM9ZgUgP2ZzQrbZUHS3JnWx22FIaeatz +LNIXeoorf+Y8Plc6CaLargGWgNQtZJ9jiPKtUDrzza9cZvjOS69LJnuOJQARAQAB +zStBcnR1cnMgS2FkaWtpcyAoQW5kcm9pZCBTREspIDxha2FAY291bnQubHk+wsGO +BBMBCAA4FiEE/I2w3iNKJzukXlYvuMg6B5pbvQwFAmCBvh0CGwMFCwkIBwIGFQoJ +CAsCBBYCAwECHgECF4AACgkQuMg6B5pbvQz+gBAAzDEQGN8PLsGCT9rh9489LFSq +HUtODrHYE2RQPA1eA9IrYpX6jOWsgQ+qomI0aZoVO1PJZ7uLDUFFa4h//+jGDVcL +8xtKPmknGl+ercg6wqPDt/q3NKi5BvD4klHgzxarKasq65Mhcn1izyi9n3lvNza/ +4xezW7NGU6EiIrEH9Rp1r5wxy3+axS7TLlJar+wdUc/U1OkoPuoar+2xK8peRJRb +pI5KGcvZo6XodNRJK5e+L1MWVvQsJM8kknO+9k6NmKS+R6F9mjqcO0OOYoVulPK8 +DwKFYieyNq3SKSpvzDof66eTeaV3JQOnukj7pgRvaUmNOzbsGCTIG4tdK/2VlgmQ +AWPZCJvipW8zFWDxsTiOq6SnmOG0cQ1zYRYvg91lNrsFOROpvSKfmWcOlTi0xlkU +A6lTPXJ/8+c1aFHRB7SoBF9FAjNTXXjhGRraTH5scyW76exOmLDmMloQSrUvIOBk +qiEJl4NiYrYIcMHxy3P9x1TiZSmwjDRbkPDF2+WVuxlXuz844NTnrErpXlphWC2z +LDo5n+uO2BWkh0Acp+CBRg1P0naZUHcbX2kyXCePvhemsB4WVBp596KzfWj0JN8k +iLL5+oM2JJ9TnE0LxepvaFYxi2E5F9qOLtzKhqS/ENrL7tPqnGk2yJY9X/5eh2qV +uEttgau92EdSsNZomS/OwU0EYIG+HQEQALypyd4svykhkPgf1cuoTn/bQFBKZt06 +fkxfy/A5btcXuzPjJxc8kIpBHC4TM8wwtYOBjqrgqPcaEqlWfDpF8DjsnGEFyjC/ +xSPy7DO8huQHYiQhqk8di270Uaqh+sMCKPn9Y2qVB6aPdTTO269nL4gJhRuwyqpd +KUc20jVLFV2BkyYWY9gZiXIgvfdYoX7brJJAZJmggK/5D+eZLv7oO3j8doJiMPAY +tIJghgTwvxAHPG5ANmbB50ie8TzjER2zGpYFFi5byXR1RrwIXh0DN3YRnJln3xyT +kzbUIukSXdlEt1tglmDHFGNiDxYKmwNSthdtuVExfYE521j2XEW5fHHYcKAVI9gN +9vA3Ut/xU8ycK8baFesLIeXe1ycc1PytLJA8T7yUT7FPmh0xdL9KNM1lrCJtHT/Z +jdFcjdTavE7TGwDN9apHyqgZxvAmcuzjGhfexmoJ7arIWMaDehA52jajuUFLiUqR +Rum6XzihS24RN5E+5hEztmdNKwh/14KJsEK5d+/ZMm8hJa0jFHd0kPXRUfKLb2cX +H/XADBbzUZ6fqtp6rBVJUJOcuQ3DYt4W4Ejov+d/UxGbt3PxUSbX8DOlEs0l2ckf +lqAkBuOuU+63zTXdNnYsg+NAmZ6mtDbjCYTmE8sOugVjGwRslP7ckZRxvMRNFSUU +KfokrCn72ArRABEBAAHCwXYEGAEIACAWIQT8jbDeI0onO6ReVi+4yDoHmlu9DAUC +YIG+HQIbDAAKCRC4yDoHmlu9DCs5D/sGHF8dcgI929Hrv2zy0KiSjlw7+Eft1Z8Z +NABEoB0ZZwnIb2KD7O4CYcPDTuF/AKGZlxa8nrHplY8YLMHba+u1OFxfCMrNaf3X +f+VESPTEJB18+myw3IeMO2CCNwsh6z0rika6HYZLy2d8G3tiF224gPvBwvOpbAYd +EW4gFPFUP34k96ToL7MEYfHi1TMvfzKg7Ggw8qUbfrbsTK20/3YdkZaIzvsWqcVT +tIjycMPq7+I7j+Bii1pOUkQIB1iQB4ijITm5WswYiy74KMK6D0juPqXBY9m6LQ37 +5cTq9/7/1xGXB+JFi3xLEl/Vccfe5dnlWaZyt4SzRYl9uu5CtO7Yh3rQrbjqb298 +LxkqbHEm1wWMp1vPWa35v15t5hNCzh2HIkH6S+xMUgE9ZhCfNNkJrZtZpzSw6Uyn +vtqdymMTIxF5NA/zj6wwiSlGEkRA5dFeO1B140aRRHsBEBpYTGpFLJRxG2mhNmt3 +o6fiasg8fgMtcvawSR6BkqcN9iDMkDlMMJetaSmS8ITyAv5cAaUa1/grYw4s6LvV +QgkXuFsVkCX9biffcAYibRYhXt+jHwP5QwTvFgfuijiQBRna1HwUWYhDwtz5mjZ2 +WKfeJCvcxVveJd31Oqdip3eSJ9QQA0CTBL0QyNL+ZL1KVQAqlptRQKGFk0V4tK3/ +csSJEAExRA== +=THAH +-----END PGP PUBLIC KEY BLOCK----- diff --git a/.github/release/index.py b/.github/release/index.py new file mode 100644 index 000000000..ab714f413 --- /dev/null +++ b/.github/release/index.py @@ -0,0 +1,73 @@ +"""Rewrites maven-metadata.xml of an artifact from the complete version folders in the bucket.""" + +import hashlib +import re +import tempfile +from pathlib import Path +from xml.sax.saxutils import escape + +from layout import CHECKSUM_ALGORITHMS +from plan import FINAL_VERSION + +METADATA_CACHE = "public, max-age=60, must-revalidate" + + +def complete_versions(keys, group_path, artifact_name): + """Versions whose folder holds the POM; the POM is always uploaded last, so its presence means complete.""" + prefix = f"{group_path}/{artifact_name}/" + versions = set() + for key in keys: + if key.startswith(prefix): + parts = key[len(prefix):].split("/") + if len(parts) == 2 and parts[1] == f"{artifact_name}-{parts[0]}.pom": + versions.add(parts[0]) + return versions + + +def listed_versions(versions): + """Versions that belong in the index, in ascending numeric order: final versions only, so release candidates and + any folder the release workflow cannot produce stay unlisted.""" + final = [version for version in versions if re.fullmatch(FINAL_VERSION, version, re.ASCII)] + return sorted(final, key=lambda version: tuple(int(part) for part in version.split("."))) + + +def render(group, artifact_name, versions, now): + """maven-metadata.xml for ascending versions; latest and release are the highest version.""" + highest = escape(versions[-1]) + return "\n".join([ + '', + "", + f" {escape(group)}", + f" {escape(artifact_name)}", + " ", + f" {highest}", + f" {highest}", + " ", + *[f" {escape(version)}" for version in versions], + " ", + f" {now.strftime('%Y%m%d%H%M%S')}", + " ", + "", + "", + ]) + + +def rewrite_index(bucket, group, artifact_name, now, log=print): + """Rewrites the index from the bucket: the four checksum files first, the body last. Returns the listed versions.""" + group_path = group.replace(".", "/") + versions = listed_versions(complete_versions(bucket.list_keys(f"{group_path}/{artifact_name}/"), group_path, artifact_name)) + if not versions: + log(f"no listed version of {group}:{artifact_name}; index left unchanged") + return [] + body = render(group, artifact_name, versions, now).encode("utf-8") + key = f"{group_path}/{artifact_name}/maven-metadata.xml" + with tempfile.TemporaryDirectory() as folder: + for suffix, algorithm in CHECKSUM_ALGORITHMS: + sidecar = Path(folder) / f"maven-metadata.xml.{suffix}" + sidecar.write_bytes(hashlib.new(algorithm, body).hexdigest().encode("ascii")) + bucket.put_file(f"{key}.{suffix}", sidecar, "text/plain; charset=utf-8", METADATA_CACHE, create_only=False) + main = Path(folder) / "maven-metadata.xml" + main.write_bytes(body) + bucket.put_file(key, main, "application/xml", METADATA_CACHE, create_only=False) + log(f"index {key}: {len(versions)} versions, latest {versions[-1]}") + return versions diff --git a/.github/release/layout.py b/.github/release/layout.py new file mode 100644 index 000000000..34d8ccb3e --- /dev/null +++ b/.github/release/layout.py @@ -0,0 +1,64 @@ +"""Expected files of a release in the staging folder, and checksum helpers.""" + +import hashlib +from pathlib import Path + +CHECKSUM_ALGORITHMS = (("md5", "md5"), ("sha1", "sha1"), ("sha256", "sha256"), ("sha512", "sha512")) +CHECKSUM_SUFFIXES = tuple("." + suffix for suffix, _ in CHECKSUM_ALGORITHMS) + + +def primary_files(artifact, version): + """Primary file names of one artifact version, before checksums and signatures.""" + base = artifact.base_name(version) + return [f"{base}.jar", f"{base}.pom", f"{base}.module", f"{base}-sources.jar", f"{base}-javadoc.jar", f"{base}-cyclonedx.json"] + + +def expected_files(artifact, version): + """Every file name expected in the version folder: the primary files and their four checksums.""" + return sorted(name + suffix for name in primary_files(artifact, version) for suffix in ("",) + CHECKSUM_SUFFIXES) + + +def is_checksum(name): + """True for .md5, .sha1, .sha256 and .sha512 files.""" + return name.endswith(CHECKSUM_SUFFIXES) + + +def write_checksums(path): + """Writes path.md5, .sha1, .sha256 and .sha512 as lowercase hex without a file name, like Maven Central.""" + data = Path(path).read_bytes() + for suffix, algorithm in CHECKSUM_ALGORITHMS: + Path(f"{path}.{suffix}").write_bytes(hashlib.new(algorithm, data).hexdigest().encode("ascii")) + + +def remove_index_files(staging_dir): + """Deletes the maven-metadata.xml files Gradle writes; the publish job writes the real index.""" + for path in Path(staging_dir).rglob("maven-metadata.xml*"): + path.unlink() + + +def check_staging(staging_dir, plan): + """Problems with the staging folder: missing or unexpected files for the tag's artifacts, wrong checksums.""" + root = Path(staging_dir) + problems = [] + expected_paths = set() + for artifact in plan.artifacts: + relative = artifact.folder(plan.version) + folder = root / relative + expected = expected_files(artifact, plan.version) + expected_paths.update(f"{relative}/{name}" for name in expected) + present = sorted(path.name for path in folder.iterdir()) if folder.is_dir() else [] + problems += [f"missing {relative}/{name}" for name in expected if name not in present] + problems += [f"unexpected {relative}/{name}" for name in present if name not in expected] + for name in primary_files(artifact, plan.version): + path = folder / name + if not path.is_file(): + continue + data = path.read_bytes() + for suffix, algorithm in CHECKSUM_ALGORITHMS: + sidecar = folder / f"{name}.{suffix}" + if sidecar.is_file() and sidecar.read_bytes().decode("ascii").strip() != hashlib.new(algorithm, data).hexdigest(): + problems.append(f"wrong checksum {relative}/{name}.{suffix}") + for path in root.rglob("*"): + if path.is_file() and path.relative_to(root).as_posix() not in expected_paths: + problems.append(f"unexpected {path.relative_to(root).as_posix()}") + return sorted(set(problems)) diff --git a/.github/release/manifest.py b/.github/release/manifest.py new file mode 100644 index 000000000..a4d4b97cf --- /dev/null +++ b/.github/release/manifest.py @@ -0,0 +1,28 @@ +"""The list of staged files with sizes and hashes, handed from the build job to the publish and verify jobs.""" + +import hashlib +from pathlib import Path + + +def build_manifest(staging_dir, tag, commit): + """Lists every staged file with its size and sha256.""" + root = Path(staging_dir) + files = [] + for path in sorted(p for p in root.rglob("*") if p.is_file()): + data = path.read_bytes() + files.append({"path": path.relative_to(root).as_posix(), "size": len(data), "sha256": hashlib.sha256(data).hexdigest()}) + return {"tag": tag, "commit": commit, "files": files} + + +def verify_manifest(staging_dir, manifest): + """Problems when the staging folder differs from the manifest: missing, unexpected or changed files.""" + root = Path(staging_dir) + listed = {entry["path"]: entry for entry in manifest["files"]} + present = {path.relative_to(root).as_posix() for path in root.rglob("*") if path.is_file()} + problems = [f"missing {path}" for path in sorted(set(listed) - present)] + problems += [f"unexpected {path}" for path in sorted(present - set(listed))] + for path in sorted(set(listed) & present): + data = (root / path).read_bytes() + if len(data) != listed[path]["size"] or hashlib.sha256(data).hexdigest() != listed[path]["sha256"]: + problems.append(f"changed {path}") + return problems diff --git a/.github/release/pending.py b/.github/release/pending.py new file mode 100644 index 000000000..883ce73a7 --- /dev/null +++ b/.github/release/pending.py @@ -0,0 +1,55 @@ +"""What a release PR from staging into master releases: one GitHub release per tag rule of staging whose version has +no tag yet, on the PR's head commit, once the merge is checked to hold exactly that commit.""" + +import subprocess +from dataclasses import dataclass + +import checks +import sources +from plan import checkout_tags, plan_for_tag + + +@dataclass(frozen=True) +class PendingRelease: + """One GitHub release the merge creates.""" + + tag: str + prerelease: bool + latest: bool + notes: str + + def to_json(self): + """Serializable form, written to pending.json for the workflow; the notes go to a file of their own.""" + return {"tag": self.tag, "prerelease": self.prerelease, "latest": self.latest} + + +def merge_problems(head, merge, repo_root, runner=subprocess.run): + """Problems unless the merge commit contains the PR's head commit and holds exactly its tree, so the commit the + releases are tagged on is what master holds.""" + if not checks.is_ancestor(head, merge, repo_root, runner): + return [f"{merge} does not contain {head}; merge the release PR with a merge commit, not a squash or a rebase"] + trees = runner(["git", "-C", str(repo_root), "rev-parse", f"{head}^{{tree}}", f"{merge}^{{tree}}"], capture_output=True, text=True, check=True).stdout.split() + if trees[0] != trees[1]: + return ["master holds changes staging lacks; merge master into staging, then update the release PR"] + return [] + + +def existing_tags(repo_root, runner=subprocess.run): + """The tags of the checkout.""" + return set(runner(["git", "-C", str(repo_root), "tag", "--list"], capture_output=True, text=True, check=True).stdout.split()) + + +def pending_releases(config, repo_root, branch, tags): + """The releases the checkout makes from the branch, in tag rule order, and the problems that must stop all of them. + A tag that exists is skipped; every other one needs its version sources and changelog ready. Only a final release of + the plain version tag is marked latest. Raises PlanError when a version is unreadable.""" + releases = [] + problems = [] + for tag in checkout_tags(config, repo_root, branch): + if tag in tags: + continue + plan = plan_for_tag(config, tag) + notes, notes_problems = sources.release_notes(repo_root, plan, config) + problems += sources.check_version_sources(repo_root, plan, config) + notes_problems + releases.append(PendingRelease(tag, plan.prerelease, tag == plan.version and not plan.prerelease, notes)) + return releases, list(dict.fromkeys(problems)) diff --git a/.github/release/plan.py b/.github/release/plan.py new file mode 100644 index 000000000..1281f45ed --- /dev/null +++ b/.github/release/plan.py @@ -0,0 +1,118 @@ +"""Maps a release tag to what it publishes, using the repository's .github/release/config.json.""" + +import json +import re +from dataclasses import dataclass +from pathlib import Path +from typing import Optional, Tuple + +FINAL_VERSION = r"\d+\.\d+\.\d+" +RELEASE_VERSION = FINAL_VERSION + r"(?:-rc\d+)?" +RC_PATTERN = re.compile(r"-rc\d+$") +CONFIG_PATH = Path(__file__).resolve().parent / "config.json" + + +class PlanError(Exception): + """A tag or repository state that must stop the release.""" + + +@dataclass(frozen=True) +class Artifact: + """One Maven artifact of the repository and the Gradle module that builds it.""" + + key: str + group: str + artifact: str + module: str + contract: Optional[str] + consumer_java: int + + @property + def group_path(self): + """Group as a folder path, e.g. ly/count/sdk.""" + return self.group.replace(".", "/") + + @property + def coordinates(self): + """group:artifact.""" + return f"{self.group}:{self.artifact}" + + @property + def module_dir(self): + """Folder of the Gradle module, e.g. sdk-java-ui for :sdk-java-ui.""" + return self.module.lstrip(":").replace(":", "/") + + def folder(self, version): + """Repository folder of one version, e.g. ly/count/sdk/java/26.8.1.""" + return f"{self.group_path}/{self.artifact}/{version}" + + def base_name(self, version): + """File name stem of one version, e.g. java-26.8.1.""" + return f"{self.artifact}-{version}" + + +@dataclass(frozen=True) +class Plan: + """What one tag publishes.""" + + tag: str + version: str + listed: bool + prerelease: bool + branch: str + artifacts: Tuple[Artifact, ...] + + @property + def modules(self): + """Gradle modules to build, in order, without duplicates.""" + return list(dict.fromkeys(artifact.module for artifact in self.artifacts)) + + def to_json(self): + """Serializable form, handed between workflow jobs as plan.json.""" + return {"tag": self.tag, "version": self.version, "listed": self.listed, "prerelease": self.prerelease, "branch": self.branch, "artifacts": [artifact.key for artifact in self.artifacts]} + + +def load_config(path=CONFIG_PATH): + """Reads config.json.""" + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def artifact_from_config(config, key): + """Builds the Artifact described by config['artifacts'][key].""" + spec = config["artifacts"][key] + return Artifact(key, spec["group"], spec["artifact"], spec["module"], spec.get("contract"), spec["consumerJava"]) + + +def plan_for_tag(config, tag): + """Maps a tag to its plan; raises PlanError for a tag outside the repository's grammar (ASCII digits only).""" + for rule in config["tagRules"]: + prefix, suffix = rule["tag"].split("{version}") + match = re.fullmatch(f"{re.escape(prefix)}(?P{RELEASE_VERSION}){re.escape(suffix)}", tag, re.ASCII) + if match: + version = match.group("version") + prerelease = bool(RC_PATTERN.search(version)) + artifacts = tuple(artifact_from_config(config, key) for key in rule["artifacts"]) + return Plan(tag, version, not prerelease, prerelease, rule["branch"], artifacts) + raise PlanError(f'"{tag}" is not a release tag of {config["repository"]}') + + +def checkout_tags(config, repo_root, branch): + """Tags the checkout would be released as from the branch: one per tag rule of that branch, carrying the version + held by the first version source of the rule's first artifact. Raises PlanError when that version is unreadable.""" + tags = [] + for rule in config["tagRules"]: + if rule["branch"] != branch: + continue + source = config["artifacts"][rule["artifacts"][0]]["versionSources"][0] + path = Path(repo_root) / source["file"] + match = re.search(source["regex"], path.read_text(encoding="utf-8"), re.MULTILINE) if path.is_file() else None + if match is None: + raise PlanError(f"{source['file']}: no version found") + tags.append(rule["tag"].format(version=match.group(1).strip())) + return tags + + +def plan_from_json(config, data): + """Rebuilds a plan written by Plan.to_json.""" + artifacts = tuple(artifact_from_config(config, key) for key in data["artifacts"]) + return Plan(data["tag"], data["version"], data["listed"], data["prerelease"], data["branch"], artifacts) diff --git a/.github/release/release.py b/.github/release/release.py new file mode 100644 index 000000000..57246b50a --- /dev/null +++ b/.github/release/release.py @@ -0,0 +1,448 @@ +#!/usr/bin/env python3 +"""Entry point of .github/workflows/release.yml: one subcommand per workflow step.""" + +import argparse +import datetime +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import checks +import consumers +import contract +import index +import layout +import manifest as manifest_module +import pending +import sbom +import sign +import sources +import upload +import verify +from plan import PlanError, checkout_tags, load_config, plan_for_tag, plan_from_json +from s3 import R2Bucket + +HERE = Path(__file__).resolve().parent +REPO_ROOT = HERE.parents[1] +PUBLIC_KEY = HERE / "countly-sdk-signing.asc" +RELEASE_KEY_FINGERPRINT = "FC8DB0DE234A273BA45E562FB8C83A079A5BBD0C" +TARGETS = ["production", "test"] + + +def summary(lines): + """Prints lines and appends them to the job summary when running in GitHub Actions.""" + for line in lines: + print(line) + path = os.environ.get("GITHUB_STEP_SUMMARY") + if path: + with open(path, "a", encoding="utf-8") as handle: + handle.write("\n".join(lines) + "\n") + + +def outputs(values): + """Writes step outputs when running in GitHub Actions.""" + path = os.environ.get("GITHUB_OUTPUT") + if path: + with open(path, "a", encoding="utf-8") as handle: + for key, value in values.items(): + handle.write(f"{key}={value}\n") + + +def finish(problems, title): + """Reports problems as error annotations and exits with 1 when there are any; reports success otherwise.""" + if problems: + for problem in problems: + print(f"::error::{problem}") + summary([f"### {title}: failed"] + [f"- {problem}" for problem in problems]) + sys.exit(1) + summary([f"### {title}: passed"]) + + +def read_plan(path): + """Loads config.json and the plan written by the plan step.""" + config = load_config() + return config, plan_from_json(config, json.loads(Path(path).read_text(encoding="utf-8"))) + + +def bucket_from_env(): + """The R2 bucket named by the R2_BUCKET and R2_ACCOUNT_ID variables.""" + return R2Bucket(os.environ["R2_BUCKET"], os.environ["R2_ACCOUNT_ID"]) + + +def staged_file(staging, artifact, version, suffix): + """Path of one staged file of an artifact version, e.g. suffix '.jar' or '-cyclonedx.json'.""" + return Path(staging) / artifact.folder(version) / f"{artifact.base_name(version)}{suffix}" + + +def cmd_plan(args): + """Maps the tag to a plan, writes plan.json and the step outputs, and checks the GitHub release type.""" + config = load_config() + try: + plan = plan_for_tag(config, args.tag) + except PlanError as error: + finish([str(error)], "Tag") + return + Path(args.out).write_bytes(json.dumps(plan.to_json(), indent=2).encode("utf-8")) + outputs({ + "environment": "maven-release" if args.target == "production" else "maven-test", + "check_tasks": " ".join(f"{module}:check" for module in plan.modules), + "publish_tasks": " ".join(f"{module}:publishAllPublicationsToReleaseStagingRepository {module}:cyclonedxDirectBom" for module in plan.modules), + "published_modules": config["publishedModules"], + }) + state = "listed" if plan.listed else "release candidate, not listed" + lines = [f"### Plan for {plan.tag}", f"- version {plan.version} ({state})", f"- branch {plan.branch}", f"- target {args.target}"] + if args.commit: + lines.append(f"- commit {args.commit}") + summary(lines + [f"- {artifact.coordinates}" for artifact in plan.artifacts]) + problems = [] + if args.target == "production": + if args.prerelease not in ("true", "false"): + problems.append("a production release needs a published GitHub release for this tag") + elif (args.prerelease == "true") != plan.prerelease: + problems.append("a tag ending in -rcN must be published as a GitHub pre-release, and a pre-release needs such a tag") + finish(problems, "GitHub release") + + +def cmd_checkout_tags(args): + """Writes the tags the checkout would be released as from --branch, as the JSON list the release checks run on.""" + try: + tags = checkout_tags(load_config(), REPO_ROOT, args.branch) + except PlanError as error: + finish([str(error)], "Checkout tags") + return + outputs({"tags": json.dumps(tags)}) + summary([f"### Tags {args.branch} would release"] + [f"- {tag}" for tag in tags or ["none"]]) + + +def cmd_pending(args): + """Lists the GitHub releases a release PR from staging into master creates and writes their notes, after checking + the merge; fails on anything that would stop one of them, so nothing is created.""" + config = load_config() + problems = pending.merge_problems(args.head, args.merge, REPO_ROOT) + releases = [] + if not problems: + try: + releases, problems = pending.pending_releases(config, REPO_ROOT, args.branch, pending.existing_tags(REPO_ROOT)) + except (PlanError, OSError) as error: + problems = [str(error)] + if not problems: + notes = Path(args.notes) + notes.mkdir(parents=True, exist_ok=True) + for release in releases: + (notes / f"{release.tag}.md").write_bytes(release.notes.encode("utf-8")) + Path(args.out).write_bytes(json.dumps({"releases": [release.to_json() for release in releases]}, indent=2).encode("utf-8")) + lines = [f"- {release.tag}{' (pre-release)' if release.prerelease else ''}" for release in releases] + summary(["### Releases of this merge"] + (lines or ["- none, every version is tagged already"])) + finish(problems, "Release plan") + + +def cmd_check_branch(args): + """The tag commit must be on the plan's release branch.""" + _, plan = read_plan(args.plan) + finish(checks.branch_problems(args.commit, plan.branch, REPO_ROOT), "Release branch") + + +def cmd_check_sources(args): + """Version numbers and changelog headings must match the tag.""" + config, plan = read_plan(args.plan) + finish(sources.check_version_sources(REPO_ROOT, plan, config), "Version numbers") + + +def cmd_check_absent(args): + """The version must exist neither in the target repository nor, for production, on Maven Central.""" + config, plan = read_plan(args.plan) + base = config["publicBaseUrl"][args.target] + problems = [] + for artifact in plan.artifacts: + pom = f"{artifact.folder(plan.version)}/{artifact.base_name(plan.version)}.pom" + if verify.fetch(f"{base}{pom}?nocache={args.nocache}") is not None: + problems.append(f"{artifact.coordinates}:{plan.version} is already on {base}") + if args.target == "production" and verify.fetch(f"{config['centralBaseUrl']}{pom}") is not None: + problems.append(f"{artifact.coordinates}:{plan.version} is already on Maven Central") + finish(problems, "Not published yet") + + +def cmd_check_required(args): + """The required status checks must have succeeded on the tag commit.""" + config = load_config() + runs = json.loads(Path(args.check_runs).read_text(encoding="utf-8")) + finish([f"required check '{name}' did not succeed on the tag commit" for name in checks.missing_checks(runs, config["requiredChecks"])], "Required checks") + + +def cmd_check_environment(args): + """The environment of the publish job must make a reviewer approve it and limit which refs deploy to it.""" + environment = json.loads(Path(args.environment).read_text(encoding="utf-8")) + finish(checks.environment_problems(environment), "Publish environment") + + +def cmd_stage(args): + """Removes Gradle's indexes, places the SBOMs, checks the file set and writes the manifest.""" + config, plan = read_plan(args.plan) + staging = Path(args.staging) + layout.remove_index_files(staging) + timestamp = subprocess.run(["git", "-C", str(REPO_ROOT), "show", "-s", "--format=%cI", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() + problems = [] + lines = [] + modules = {artifact.module: artifact for artifact in plan.artifacts} + for artifact in plan.artifacts: + source = REPO_ROOT / artifact.module_dir / "build/reports/cyclonedx-direct/bom.json" + if not source.is_file(): + problems.append(f"no SBOM at {artifact.module_dir}/build/reports/cyclonedx-direct/bom.json") + continue + try: + placed = sbom.place_sbom(source, staging, artifact, plan.version, timestamp, config["publicBaseUrl"][args.target], modules, config["platformSpecificGroups"]) + except sbom.SbomError as error: + problems.append(str(error)) + continue + lines.append(f"- SBOM of {artifact.coordinates}: {len(json.loads(placed.read_bytes()).get('components', []))} components") + problems += layout.check_staging(staging, plan) + if not problems: + data = manifest_module.build_manifest(staging, plan.tag, args.commit) + Path(args.manifest).write_bytes(json.dumps(data, indent=2).encode("utf-8")) + lines += [f"- {len(data['files'])} files staged", "", "
Staged files", ""] + lines += [f" {entry['path']}" for entry in data["files"]] + ["", "
"] + summary(lines) + finish(problems, "Staging") + + +def cmd_validate_sbom(args): + """Validates every staged SBOM against the CycloneDX 1.6 schema with the CycloneDX CLI.""" + _, plan = read_plan(args.plan) + env = dict(os.environ, DOTNET_SYSTEM_GLOBALIZATION_INVARIANT="1") + problems = [] + for artifact in plan.artifacts: + path = staged_file(args.staging, artifact, plan.version, "-cyclonedx.json") + result = subprocess.run([args.cli, "validate", "--input-file", str(path), "--input-format", "json", "--input-version", "v1_6", "--fail-on-errors"], env=env) + if result.returncode != 0: + problems.append(f"{path.name} is not a valid CycloneDX 1.6 document") + finish(problems, "SBOM schema") + + +def cmd_contract(args): + """Compares each staged artifact with its contract file and writes the comparison table; --capture prints the actual contracts instead.""" + _, plan = read_plan(args.plan) + problems = [] + lines = [] + for artifact in plan.artifacts: + if not artifact.contract: + continue + actual = contract.actual_contract(args.staging, artifact, plan.version) + if args.capture: + print(json.dumps(actual, indent=2)) + continue + expected = json.loads((REPO_ROOT / artifact.contract).read_text(encoding="utf-8")) + found = contract.compare(expected, actual) + contract.module_dependency_problems(args.staging, artifact, plan.version) + problems += [f"{artifact.coordinates}: {problem}" for problem in found] + lines += [f"#### {artifact.coordinates}", "", "| Property | Contract | Built |", "|---|---|---|"] + lines += [f"| {name} | {wanted} | {built} |" for name, wanted, built in contract.summary_rows(expected, actual)] + [""] + if not args.capture: + summary(lines) + finish(problems, "Contract") + + +def cmd_verify_manifest(args): + """The downloaded staging folder must be exactly what the build job produced.""" + data = json.loads(Path(args.manifest).read_text(encoding="utf-8")) + finish(manifest_module.verify_manifest(args.staging, data), "Manifest") + + +def cmd_sign(args): + """Signs every staged file with the key of the target held in GNUPGHOME and checks every signature. Production + must use the release key; a dry run must use its own key. The public key the signatures verify against is written + to --public-key-out for the verify job: the committed release key, or the dry-run key exported from the keyring.""" + homedir = os.environ["GNUPGHOME"] + production = args.target == "production" + try: + fingerprint = sign.signing_fingerprint(homedir, RELEASE_KEY_FINGERPRINT, production) + except sign.SigningError as error: + finish([str(error)], "Signing key") + if production: + shutil.copyfile(PUBLIC_KEY, args.public_key_out) + else: + sign.export_public_key(homedir, fingerprint, args.public_key_out) + signed = sign.sign_staging(args.staging, homedir, os.environ["SIGNING_KEY_PASSPHRASE"], fingerprint) + finish(verify.verify_signatures(args.staging, Path(args.public_key_out)), f"Signing ({len(signed)} files with {fingerprint})") + + +def cmd_upload(args): + """Uploads the signed staging folder create-only.""" + _, plan = read_plan(args.plan) + try: + upload.upload_release(bucket_from_env(), args.staging, plan) + except upload.UploadError as error: + finish([str(error), "this version number is burned; release the next patch version"], "Upload") + finish([], "Upload") + + +def cmd_index(args): + """Rewrites maven-metadata.xml of the plan's artifacts, or of every artifact of this repository with --all.""" + config = load_config() + if args.all: + targets = [(spec["group"], spec["artifact"]) for spec in config["artifacts"].values()] + else: + _, plan = read_plan(args.plan) + targets = [(artifact.group, artifact.artifact) for artifact in plan.artifacts] + bucket = bucket_from_env() + now = datetime.datetime.now(datetime.timezone.utc) + for group, name in targets: + index.rewrite_index(bucket, group, name, now) + finish([], "Version index") + + +def cmd_verify_public(args): + """Downloads the release from the public address and checks files, index and signatures.""" + config, plan = read_plan(args.plan) + data = json.loads(Path(args.manifest).read_text(encoding="utf-8")) + problems = verify.verify_public(data, plan, config["publicBaseUrl"][args.target], args.nocache, args.work) + if not problems: + problems = verify.verify_signatures(args.work, Path(args.public_key)) + finish(problems, "Public files") + + +def cmd_consumer(args): + """Builds a clean Gradle project and a clean Maven project against every artifact of the staging folder, used as a + local repository, and runs the Java 8 artifacts on a Java 8 runtime, so a release that a clean project cannot build + with stops before the approval. Countly packages outside the release come from the target's public repository.""" + config, plan = read_plan(args.plan) + repository = Path(args.staging).resolve().as_uri() + public_repository = config["publicBaseUrl"][args.target].rstrip("/") + gradlew = str(REPO_ROOT / ("gradlew.bat" if os.name == "nt" else "gradlew")) + problems = [] + lines = [] + for artifact in plan.artifacts: + name = f"{artifact.coordinates}:{plan.version}" + if subprocess.run(consumers.gradle_command(gradlew, repository, public_repository, plan, artifact), cwd=REPO_ROOT).returncode != 0: + problems.append(f"a clean Gradle project could not build with {name}") + elif artifact.consumer_java == 8: + smoke = subprocess.run(consumers.smoke_command(args.java8_home, REPO_ROOT), cwd=REPO_ROOT, capture_output=True, text=True) + print(smoke.stdout + smoke.stderr) + if smoke.returncode != 0: + problems.append(f"{name} did not load on the Java 8 runtime") + else: + lines.append(f"- Java 8 run of {artifact.coordinates}: {smoke.stdout.strip()}") + local_repository = Path(args.work) / f"m2-{artifact.artifact}" + shutil.rmtree(local_repository, ignore_errors=True) + if subprocess.run(consumers.maven_command(args.mvn, repository, public_repository, artifact, plan.version, local_repository.resolve()), cwd=REPO_ROOT).returncode != 0: + problems.append(f"a clean Maven project could not build with {name}") + else: + problems += consumers.maven_source_problems(local_repository, plan, artifact) + summary(lines) + finish(problems, "Consumer builds") + + +def main(argv=None): + """Parses the subcommand and runs it.""" + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + + command = commands.add_parser("plan") + command.add_argument("--tag", required=True) + command.add_argument("--target", choices=TARGETS, required=True) + command.add_argument("--prerelease", default="unknown") + command.add_argument("--commit", default="") + command.add_argument("--out", required=True) + command.set_defaults(func=cmd_plan) + + command = commands.add_parser("checkout-tags") + command.add_argument("--branch", required=True) + command.set_defaults(func=cmd_checkout_tags) + + command = commands.add_parser("pending") + command.add_argument("--head", required=True) + command.add_argument("--merge", required=True) + command.add_argument("--branch", required=True) + command.add_argument("--out", required=True) + command.add_argument("--notes", required=True) + command.set_defaults(func=cmd_pending) + + command = commands.add_parser("check-branch") + command.add_argument("--plan", required=True) + command.add_argument("--commit", required=True) + command.set_defaults(func=cmd_check_branch) + + command = commands.add_parser("check-sources") + command.add_argument("--plan", required=True) + command.set_defaults(func=cmd_check_sources) + + command = commands.add_parser("check-absent") + command.add_argument("--plan", required=True) + command.add_argument("--target", choices=TARGETS, required=True) + command.add_argument("--nocache", required=True) + command.set_defaults(func=cmd_check_absent) + + command = commands.add_parser("check-required") + command.add_argument("--check-runs", required=True) + command.set_defaults(func=cmd_check_required) + + command = commands.add_parser("check-environment") + command.add_argument("--environment", required=True) + command.set_defaults(func=cmd_check_environment) + + command = commands.add_parser("stage") + command.add_argument("--plan", required=True) + command.add_argument("--staging", required=True) + command.add_argument("--commit", required=True) + command.add_argument("--target", choices=TARGETS, required=True) + command.add_argument("--manifest", required=True) + command.set_defaults(func=cmd_stage) + + command = commands.add_parser("validate-sbom") + command.add_argument("--plan", required=True) + command.add_argument("--staging", required=True) + command.add_argument("--cli", required=True) + command.set_defaults(func=cmd_validate_sbom) + + command = commands.add_parser("contract") + command.add_argument("--plan", required=True) + command.add_argument("--staging", required=True) + command.add_argument("--capture", action="store_true") + command.set_defaults(func=cmd_contract) + + command = commands.add_parser("verify-manifest") + command.add_argument("--manifest", required=True) + command.add_argument("--staging", required=True) + command.set_defaults(func=cmd_verify_manifest) + + command = commands.add_parser("sign") + command.add_argument("--staging", required=True) + command.add_argument("--target", choices=TARGETS, required=True) + command.add_argument("--public-key-out", required=True) + command.set_defaults(func=cmd_sign) + + command = commands.add_parser("upload") + command.add_argument("--plan", required=True) + command.add_argument("--staging", required=True) + command.set_defaults(func=cmd_upload) + + command = commands.add_parser("index") + command.add_argument("--plan") + command.add_argument("--all", action="store_true") + command.set_defaults(func=cmd_index) + + command = commands.add_parser("verify-public") + command.add_argument("--plan", required=True) + command.add_argument("--manifest", required=True) + command.add_argument("--target", choices=TARGETS, required=True) + command.add_argument("--nocache", required=True) + command.add_argument("--work", required=True) + command.add_argument("--public-key", default=str(PUBLIC_KEY)) + command.set_defaults(func=cmd_verify_public) + + command = commands.add_parser("consumer") + command.add_argument("--plan", required=True) + command.add_argument("--staging", required=True) + command.add_argument("--target", choices=TARGETS, required=True) + command.add_argument("--java8-home", required=True) + command.add_argument("--mvn", default="mvn") + command.add_argument("--work", required=True) + command.set_defaults(func=cmd_consumer) + + args = parser.parse_args(argv) + args.func(args) + + +if __name__ == "__main__": + main() diff --git a/.github/release/s3.py b/.github/release/s3.py new file mode 100644 index 000000000..064fe2fa6 --- /dev/null +++ b/.github/release/s3.py @@ -0,0 +1,54 @@ +"""Minimal R2 access through the AWS CLI (S3 API), so the release job needs no Python packages.""" + +import json +import os +import subprocess + + +class S3Error(Exception): + """An S3 call failed for a reason other than 'not found' or 'already exists'.""" + + +class R2Bucket: + """One R2 bucket, reached with `aws s3api` at the account's R2 endpoint using the AWS_* credentials in the environment.""" + + def __init__(self, bucket, account_id, runner=subprocess.run): + self.bucket = bucket + self.endpoint = f"https://{account_id}.r2.cloudflarestorage.com" + self.runner = runner + + def _aws(self, *args): + env = dict(os.environ, AWS_DEFAULT_REGION="auto", AWS_REQUEST_CHECKSUM_CALCULATION="when_required", AWS_RESPONSE_CHECKSUM_VALIDATION="when_required") + command = ["aws", "s3api", *args, "--bucket", self.bucket, "--endpoint-url", self.endpoint, "--output", "json"] + return self.runner(command, capture_output=True, text=True, env=env) + + def head(self, key): + """Returns {'etag': MD5 hex, 'size': bytes} or None when the key does not exist.""" + result = self._aws("head-object", "--key", key) + if result.returncode == 0: + data = json.loads(result.stdout) + return {"etag": data["ETag"].strip('"'), "size": int(data["ContentLength"])} + if "Not Found" in result.stderr or "(404)" in result.stderr: + return None + raise S3Error(result.stderr.strip()) + + def put_file(self, key, path, content_type, cache_control, create_only): + """Uploads a file in one request; with create_only an existing key is never overwritten and 'exists' is returned.""" + args = ["put-object", "--key", key, "--body", str(path), "--content-type", content_type, "--cache-control", cache_control] + if create_only: + args += ["--if-none-match", "*"] + result = self._aws(*args) + if result.returncode == 0: + return "created" + if create_only and ("PreconditionFailed" in result.stderr or "(412)" in result.stderr): + return "exists" + raise S3Error(result.stderr.strip()) + + def list_keys(self, prefix): + """Every key under the prefix (the CLI follows continuation tokens itself).""" + result = self._aws("list-objects-v2", "--prefix", prefix) + if result.returncode != 0: + raise S3Error(result.stderr.strip()) + if not result.stdout.strip(): + return [] + return [item["Key"] for item in json.loads(result.stdout).get("Contents") or []] diff --git a/.github/release/sbom.py b/.github/release/sbom.py new file mode 100644 index 000000000..9c71e3618 --- /dev/null +++ b/.github/release/sbom.py @@ -0,0 +1,64 @@ +"""Turns the CycloneDX plugin's per-project SBOM into the published component list of one artifact.""" + +import json +from pathlib import Path +from urllib.parse import parse_qs, quote, urlsplit + +from layout import write_checksums + + +def purl(artifact, version, public_base_url): + """Package URL of a published Countly artifact, naming the Countly repository.""" + repository = quote(public_base_url.rstrip("/"), safe="") + return f"pkg:maven/{artifact.group}/{artifact.artifact}@{version}?repository_url={repository}&type=jar" + + +class SbomError(Exception): + """The plugin's SBOM names a module of this build that is not published.""" + + +def _project_path(component): + """Gradle project path of a component the plugin wrote for a module of this build, or None.""" + return parse_qs(urlsplit(component.get("purl", "")).query).get("project_path", [None])[0] + + +def normalize(bom, artifact, version, timestamp, public_base_url, modules=None, platform_groups=()): + """Sets the published coordinates, the licence and a fixed timestamp, and drops the random serial number. Components + the plugin wrote for other modules of this build (java-ui depends on java) get the coordinates those modules are + published under in the same release; `modules` maps a Gradle project path to its published artifact. Components of + `platform_groups` lose their hashes: those groups publish one file per operating system (JavaFX), so the hashes of + the file the build machine resolved match no file the named package stands for.""" + metadata = bom.setdefault("metadata", {}) + old_ref = metadata.get("component", {}).get("bom-ref") + ref = purl(artifact, version, public_base_url) + metadata["component"] = {"type": "library", "bom-ref": ref, "group": artifact.group, "name": artifact.artifact, "version": version, "purl": ref, "licenses": [{"license": {"id": "MIT"}}]} + metadata["timestamp"] = timestamp + bom.pop("serialNumber", None) + renamed = {} if old_ref is None else {old_ref: ref} + for component in bom.get("components", []): + if component.get("group") in platform_groups: + component.pop("hashes", None) + path = _project_path(component) + if path is None: + continue + published = (modules or {}).get(path) + if published is None: + raise SbomError(f"the SBOM of {artifact.coordinates} names the module {path}, which is not published") + new_ref = purl(published, version, public_base_url) + renamed[component.get("bom-ref")] = new_ref + component.update({"bom-ref": new_ref, "group": published.group, "name": published.artifact, "version": version, "purl": new_ref}) + for dependency in bom.get("dependencies", []): + dependency["ref"] = renamed.get(dependency.get("ref"), dependency.get("ref")) + if "dependsOn" in dependency: + dependency["dependsOn"] = [renamed.get(entry, entry) for entry in dependency["dependsOn"]] + return bom + + +def place_sbom(bom_path, staging_dir, artifact, version, timestamp, public_base_url, modules=None, platform_groups=()): + """Writes the published SBOM and its checksums into the staging folder and returns its path.""" + bom = normalize(json.loads(Path(bom_path).read_text(encoding="utf-8")), artifact, version, timestamp, public_base_url, modules, platform_groups) + target = Path(staging_dir) / artifact.folder(version) / f"{artifact.base_name(version)}-cyclonedx.json" + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes((json.dumps(bom, indent=2) + "\n").encode("utf-8")) + write_checksums(target) + return target diff --git a/.github/release/sign.py b/.github/release/sign.py new file mode 100644 index 000000000..822a7dec2 --- /dev/null +++ b/.github/release/sign.py @@ -0,0 +1,55 @@ +"""Signs the staged files with the key of the target: the release key for production, the dry-run key for tests.""" + +import subprocess +from pathlib import Path + +from layout import is_checksum + + +class SigningError(Exception): + """The keyring holds the wrong signing key for the target.""" + + +def primary_secret_fingerprints(homedir, runner=subprocess.run): + """Fingerprints of the primary secret keys in the keyring, without their subkeys.""" + listing = runner(["gpg", "--homedir", str(homedir), "--batch", "--with-colons", "--list-secret-keys"], capture_output=True, text=True, check=True).stdout + lines = listing.splitlines() + return [line.split(":")[9] for index, line in enumerate(lines) if line.startswith("fpr:") and index > 0 and lines[index - 1].startswith("sec:")] + + +def signing_fingerprint(homedir, release_fingerprint, production, runner=subprocess.run): + """The key to sign with. Production requires the release key. A dry run requires exactly one other key and + refuses the release key, so the release key never has to leave the production environment.""" + fingerprints = primary_secret_fingerprints(homedir, runner) + if production: + if release_fingerprint not in fingerprints: + raise SigningError(f"the imported signing key is not {release_fingerprint}") + return release_fingerprint + if release_fingerprint in fingerprints: + raise SigningError("a dry run must not use the release key; the maven-test environment needs its own dry-run key") + if len(fingerprints) != 1: + raise SigningError(f"a dry run needs exactly one signing key in the keyring, found {len(fingerprints)}") + return fingerprints[0] + + +def export_public_key(homedir, fingerprint, path, runner=subprocess.run): + """Writes the ASCII-armoured public key of the fingerprint to path.""" + armored = runner(["gpg", "--homedir", str(homedir), "--batch", "--armor", "--export", fingerprint], capture_output=True, text=True, check=True).stdout + Path(path).write_bytes(armored.encode("ascii")) + + +def files_to_sign(staging_dir): + """Every staged file except checksum files and existing signatures.""" + return sorted(path for path in Path(staging_dir).rglob("*") if path.is_file() and not is_checksum(path.name) and not path.name.endswith(".asc")) + + +def sign_staging(staging_dir, homedir, passphrase, fingerprint, runner=subprocess.run): + """Writes one ASCII-armoured detached signature, made by exactly the given key, next to every file to sign; returns the signed files.""" + signed = files_to_sign(staging_dir) + for path in signed: + runner( + ["gpg", "--homedir", str(homedir), "--batch", "--yes", "--pinentry-mode", "loopback", "--passphrase-fd", "0", + "--local-user", f"{fingerprint}!", "--armor", "--detach-sign", "--output", f"{path}.asc", str(path)], + input=passphrase, text=True, capture_output=True, check=True, + ) + return signed diff --git a/.github/release/sources.py b/.github/release/sources.py new file mode 100644 index 000000000..f28b31214 --- /dev/null +++ b/.github/release/sources.py @@ -0,0 +1,78 @@ +"""Checks that every version source of the tag's artifacts carries the tag's version, and reads the release notes from +the changelogs.""" + +import re +from pathlib import Path + +PLACEHOLDER = "XX.XX.XX" + + +def check_version_sources(repo_root, plan, config): + """Returns problems; empty when every version source and, for final releases, every changelog heading matches, with + no '## XX.XX.XX' heading left.""" + problems = [] + root = Path(repo_root) + for artifact in plan.artifacts: + spec = config["artifacts"][artifact.key] + for source in spec["versionSources"]: + path = root / source["file"] + if not path.is_file(): + problems.append(f"{source['file']} does not exist") + continue + match = re.search(source["regex"], path.read_text(encoding="utf-8"), re.MULTILINE) + if match is None: + problems.append(f"{source['file']}: no version found") + elif match.group(1).strip() != plan.version: + problems.append(f"{source['file']}: version is {match.group(1).strip()}, the tag says {plan.version}") + changelog = spec.get("changelog") + if changelog and not plan.prerelease: + path = root / changelog + if not path.is_file(): + problems.append(f"{changelog} does not exist") + continue + text = path.read_text(encoding="utf-8") + if changelog_section(text, plan.version) is None: + problems.append(f"{changelog}: no '## {plan.version}' heading") + if changelog_section(text, PLACEHOLDER) is not None: + problems.append(f"{changelog}: still has a '## {PLACEHOLDER}' heading; move its lines under '## {plan.version}'") + return list(dict.fromkeys(problems)) + + +def release_notes(repo_root, plan, config): + """The notes of the plan's GitHub release, the changelog section of its version for each of its artifacts; a + pre-release takes the '## XX.XX.XX' section when there is one. Returns the notes and the problems that leave a + changelog without them.""" + notes = "" + problems = [] + for artifact in plan.artifacts: + changelog = config["artifacts"][artifact.key].get("changelog") + if not changelog: + continue + path = Path(repo_root) / changelog + if not path.is_file(): + problems.append(f"{changelog} does not exist") + continue + text = path.read_text(encoding="utf-8") + section = (changelog_section(text, PLACEHOLDER) if plan.prerelease else None) or changelog_section(text, plan.version) + if section is None: + problems.append(f"{changelog}: no '## {plan.version}' heading") + notes += section or "" + return notes, problems + + +def changelog_section(text, heading): + """The lines under the '## ' heading of a changelog, up to the next '## ' heading outside a fenced code + block, without the blank lines around them; None when the changelog has no such heading.""" + lines = text.splitlines() + start = next((index for index, line in enumerate(lines) if re.fullmatch(rf"## {re.escape(heading)}\s*", line)), None) + if start is None: + return None + section = [] + fenced = False + for line in lines[start + 1:]: + if line.lstrip().startswith("```"): + fenced = not fenced + elif not fenced and line.startswith("## "): + break + section.append(line) + return "\n".join(section).strip("\n") + "\n" diff --git a/.github/release/tests/__init__.py b/.github/release/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/.github/release/tests/builders.py b/.github/release/tests/builders.py new file mode 100644 index 000000000..bf6b5dc25 --- /dev/null +++ b/.github/release/tests/builders.py @@ -0,0 +1,59 @@ +"""Builders for staged artifacts: class files, jars, POMs and Gradle module files.""" + +import io +import json +import zipfile +from pathlib import Path + +from layout import primary_files, write_checksums + + +def class_bytes(major): + """A minimal class-file header with the given major version.""" + return b"\xca\xfe\xba\xbe" + (0).to_bytes(2, "big") + major.to_bytes(2, "big") + b"\x00" * 8 + + +def jar_bytes(majors): + """A jar holding one class file per major version.""" + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as archive: + for number, major in enumerate(majors): + archive.writestr(f"ly/count/C{number}.class", class_bytes(major)) + return buffer.getvalue() + + +def pom_bytes(dependencies): + """A POM with the given group:artifact:version:scope dependencies.""" + entries = "".join( + f"{g}{a}{v}{s}" + for g, a, v, s in (dependency.split(":") for dependency in dependencies) + ) + return f'4.0.0{entries}'.encode("utf-8") + + +def module_bytes(jvm_version=None, dependencies=()): + """A Gradle module file with a runtime library variant (optionally with org.gradle.jvm.version and group:module:version dependencies) and a sources variant.""" + attributes = {"org.gradle.category": "library", "org.gradle.usage": "java-runtime"} + if jvm_version is not None: + attributes["org.gradle.jvm.version"] = jvm_version + declared = [] + for dependency in dependencies: + group, module, version = dependency.split(":") + declared.append({"group": group, "module": module, "version": {"requires": version}}) + variants = [{"name": "runtime", "attributes": attributes, "dependencies": declared}, {"name": "sources", "attributes": {"org.gradle.category": "documentation"}}] + return json.dumps({"formatVersion": "1.1", "variants": variants}).encode("utf-8") + + +def write_artifact(staging, artifact, version, main=None, pom=None, module=None): + """Writes a complete staged artifact version (primary files plus four checksums each) and returns its folder.""" + folder = Path(staging) / artifact.folder(version) + folder.mkdir(parents=True, exist_ok=True) + base = artifact.base_name(version) + contents = {name: f"content of {name}".encode("utf-8") for name in primary_files(artifact, version)} + contents[f"{base}.jar"] = main if main is not None else jar_bytes([52]) + contents[f"{base}.module"] = module if module is not None else module_bytes() + contents[f"{base}.pom"] = pom if pom is not None else pom_bytes([]) + for name, data in contents.items(): + (folder / name).write_bytes(data) + write_checksums(folder / name) + return folder diff --git a/.github/release/tests/support.py b/.github/release/tests/support.py new file mode 100644 index 000000000..837d03b60 --- /dev/null +++ b/.github/release/tests/support.py @@ -0,0 +1,77 @@ +"""Shared test helpers: the repository configuration, fake checkouts and in-memory stand-ins for R2 and the web.""" + +import hashlib +from pathlib import Path + +from plan import load_config + +BUILD_GRADLE = 'allprojects {\n ext.CLY_VERSION = "{version}"\n ext.POWERMOCK_VERSION = "1.7.4"\n}\n' +CONFIG_JAVA = 'public class Config {\n protected String sdkVersion = "{version}";\n}\n' + + +def repository_config(): + """The real config.json of this repository.""" + return load_config(Path(__file__).resolve().parents[1] / "config.json") + + +def write_file(root, relative, text): + """Writes a file of a fake checkout.""" + path = Path(root) / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(text.encode("utf-8")) + + +def write_core(root, properties_version, gradle_version, java_version, changelog): + """Writes the three version sources of the core SDK and its changelog into a fake checkout.""" + write_file(root, "gradle.properties", f"VERSION_NAME={properties_version}\nGROUP=ly.count.sdk\n") + write_file(root, "build.gradle", BUILD_GRADLE.replace("{version}", gradle_version)) + write_file(root, "sdk-java/src/main/java/ly/count/sdk/java/Config.java", CONFIG_JAVA.replace("{version}", java_version)) + write_file(root, "CHANGELOG.md", changelog) + + +def write_ui(root, version, changelog): + """Writes the version source of the UI package and its changelog into a fake checkout.""" + write_file(root, "sdk-java-ui/gradle.properties", f"POM_ARTIFACT_ID=java-ui\nVERSION_NAME={version}\n") + write_file(root, "sdk-java-ui/CHANGELOG.md", changelog) + + +class FakeBucket: + """In-memory stand-in for s3.R2Bucket with MD5 ETags; `fail_on` makes one upload fail like a lost connection.""" + + def __init__(self, fail_on=None): + self.objects = {} + self.calls = [] + self.fail_on = fail_on + + def head(self, key): + """Returns {'etag', 'size'} or None.""" + if key not in self.objects: + return None + data = self.objects[key][0] + return {"etag": hashlib.md5(data).hexdigest(), "size": len(data)} + + def put_file(self, key, path, content_type, cache_control, create_only): + """Stores a file; with create_only an existing key is left alone and 'exists' is returned.""" + if key == self.fail_on: + raise RuntimeError(f"connection lost while uploading {key}") + self.calls.append(key) + if create_only and key in self.objects: + return "exists" + self.objects[key] = (Path(path).read_bytes(), content_type, cache_control) + return "created" + + def list_keys(self, prefix): + """Keys starting with the prefix, sorted.""" + return sorted(key for key in self.objects if key.startswith(prefix)) + + +class FakeWeb: + """Serves a dict of URL to bytes (ignoring ?nocache=...); anything else is a 404 (None).""" + + def __init__(self, pages=None): + self.pages = dict(pages or {}) + self.requests = [] + + def __call__(self, url): + self.requests.append(url) + return self.pages.get(url.split("?nocache=")[0]) diff --git a/.github/release/tests/test_checks.py b/.github/release/tests/test_checks.py new file mode 100644 index 000000000..bcf80519f --- /dev/null +++ b/.github/release/tests/test_checks.py @@ -0,0 +1,65 @@ +import subprocess +import unittest + +from checks import branch_problems, environment_problems, missing_checks + +COMMIT = "c" * 40 +REVIEWERS = {"type": "required_reviewers", "reviewers": [{"type": "User", "reviewer": {"login": "releaser"}}]} +TAG_POLICY = {"protected_branches": False, "custom_branch_policies": True} + + +class ChecksTest(unittest.TestCase): + def test_reports_missing_and_failed_checks(self): + runs = {"check_runs": [{"name": "Build and Test", "conclusion": "success"}, {"name": "Analyze (java)", "conclusion": "failure"}]} + required = ["Build and Test", "Analyze (java)", "OSV scan (all modules)"] + self.assertEqual(missing_checks(runs, required), ["Analyze (java)", "OSV scan (all modules)"]) + + def test_every_run_of_a_required_check_must_succeed(self): + runs = {"check_runs": [ + {"name": "Build and Test", "conclusion": "failure"}, + {"name": "Build and Test", "conclusion": "success"}, + {"name": "Analyze (java)", "conclusion": "success"}, + {"name": "Analyze (java)", "conclusion": None}, + {"name": "OSV scan (all modules)", "conclusion": "success"}, + {"name": "OSV scan (all modules)", "conclusion": "success"}, + ]} + required = ["Build and Test", "Analyze (java)", "OSV scan (all modules)"] + self.assertEqual(missing_checks(runs, required), ["Build and Test", "Analyze (java)"]) + + def test_tag_commit_must_be_on_the_release_branch(self): + calls = [] + + def on_branch(args, **kwargs): + calls.append(args) + return subprocess.CompletedProcess(args, 0) + + def elsewhere(args, **kwargs): + return subprocess.CompletedProcess(args, 1) + + self.assertEqual(branch_problems(COMMIT, "staging", "/repo", runner=on_branch), []) + self.assertEqual(calls[0], ["git", "-C", "/repo", "merge-base", "--is-ancestor", COMMIT, "origin/staging"]) + self.assertEqual(branch_problems(COMMIT, "master", "/repo", runner=elsewhere), [f"{COMMIT} is not on origin/master; the tag must point to that branch"]) + + def test_publish_environment_needs_a_reviewer_and_a_deployment_policy(self): + """An environment GitHub created on first use, without rules, fails on both counts.""" + protected = {"name": "maven-release", "protection_rules": [REVIEWERS, {"type": "branch_policy"}], "deployment_branch_policy": TAG_POLICY} + self.assertEqual(environment_problems(protected), []) + created_on_first_use = {"name": "maven-release", "protection_rules": [], "deployment_branch_policy": None} + self.assertEqual(environment_problems(created_on_first_use), [ + "environment maven-release does not require a reviewer to approve the publish job", + "environment maven-release does not limit deployments to selected branches and tags", + ]) + + def test_protected_branches_only_does_not_count_as_a_tag_rule(self): + """A release runs on a tag, which a protected-branches-only policy refuses after the build.""" + environment = {"name": "maven-release", "protection_rules": [REVIEWERS], "deployment_branch_policy": {"protected_branches": True, "custom_branch_policies": False}} + self.assertEqual(environment_problems(environment), ["environment maven-release does not limit deployments to selected branches and tags"]) + + def test_a_reviewer_rule_without_reviewers_does_not_count(self): + """A reviewer rule whose list is empty, or a wait timer alone, approves nothing.""" + environment = {"name": "maven-release", "protection_rules": [{"type": "required_reviewers", "reviewers": []}, {"type": "wait_timer", "wait_timer": 5}], "deployment_branch_policy": TAG_POLICY} + self.assertEqual(environment_problems(environment), ["environment maven-release does not require a reviewer to approve the publish job"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/tests/test_consumers.py b/.github/release/tests/test_consumers.py new file mode 100644 index 000000000..c50680bfb --- /dev/null +++ b/.github/release/tests/test_consumers.py @@ -0,0 +1,73 @@ +import tempfile +import unittest +from pathlib import Path + +from consumers import gradle_command, maven_command, maven_source_problems, smoke_command +from plan import plan_for_tag +from tests.support import repository_config + +PUBLIC = "https://maven.countly.com" + + +class ConsumersTest(unittest.TestCase): + def setUp(self): + config = repository_config() + self.core_plan = plan_for_tag(config, "26.9.0") + self.ui_plan = plan_for_tag(config, "ui-26.8.1") + self.java = self.core_plan.artifacts[0] + self.ui = self.ui_plan.artifacts[0] + + def test_gradle_takes_only_the_staged_artifacts_from_the_staging_folder(self): + command = gradle_command("/repo/gradlew", "file:///staging", PUBLIC, self.ui_plan, self.ui) + self.assertEqual(command[:3], ["/repo/gradlew", "-p", ".github/release/consumers/gradle"]) + for part in ["installDist", "-PcountlyRepository=file:///staging", f"-PcountlyPublicRepository={PUBLIC}", "-PcountlyStaged=ly.count.sdk:java-ui", "-PcountlyDependency=ly.count.sdk:java-ui:26.8.1", "-PcountlyRelease=17", "-PcountlyProbe=java-ui"]: + self.assertIn(part, command) + core = gradle_command("/repo/gradlew", "file:///staging", PUBLIC, self.core_plan, self.java) + for part in ["-PcountlyStaged=ly.count.sdk:java", "-PcountlyDependency=ly.count.sdk:java:26.9.0", "-PcountlyRelease=8"]: + self.assertIn(part, core) + + def test_maven_uses_an_empty_local_repository_and_the_public_repository(self): + command = maven_command("mvn", "file:///staging", PUBLIC, self.java, "26.9.0", "/work/m2-java") + self.assertEqual(command[:4], ["mvn", "-B", "-f", ".github/release/consumers/maven/pom.xml"]) + for part in [f"-Dcountly.publicRepository={PUBLIC}", "-Dcountly.artifact=java", "-Dcountly.version=26.9.0", "-Dcountly.release=8", "-Dmaven.repo.local=/work/m2-java"]: + self.assertIn(part, command) + + def test_smoke_run_uses_the_given_runtime_and_the_installed_classpath(self): + command = smoke_command("/jdk8", "/repo") + self.assertEqual(Path(command[0]), Path("/jdk8/bin/java")) + self.assertEqual(Path(command[2]), Path("/repo/.github/release/consumers/gradle/build/install/countly-consumer/lib/*")) + self.assertEqual(command[3], "ly.count.consumer.Probe") + + def write_record(self, local, artifact, version, text): + """Writes Maven's download record for one artifact version into the local repository.""" + folder = Path(local) / artifact.folder(version) + folder.mkdir(parents=True, exist_ok=True) + (folder / "_remote.repositories").write_text(text, encoding="utf-8") + + def test_maven_must_resolve_the_release_from_the_staged_folder(self): + local = tempfile.mkdtemp() + self.assertEqual(maven_source_problems(local, self.core_plan, self.java), ["Maven did not download ly.count.sdk:java:26.9.0"]) + self.write_record(local, self.java, "26.9.0", "#NOTE: This is a Maven Resolver internal implementation file\njava-26.9.0.jar>countly=\njava-26.9.0.pom>countly=\n") + self.assertEqual(maven_source_problems(local, self.core_plan, self.java), []) + self.write_record(local, self.ui, "26.8.1", "java-ui-26.8.1.jar>central=\njava-ui-26.8.1.pom>countly=\n") + self.assertEqual(maven_source_problems(local, self.ui_plan, self.ui), ["Maven resolved ly.count.sdk:java-ui:26.8.1 from another repository than the staged release"]) + + def test_maven_3_10_records_the_staged_folder_with_a_hash_of_its_url(self): + """Maven 3.10 writes the repository ID followed by a hash of its URL; the public repository must still fail.""" + local = tempfile.mkdtemp() + staged = "countly-58d9892363928677300153295cdc58687f00b301=" + self.write_record(local, self.java, "26.9.0", f"java-26.9.0.jar>{staged}\njava-26.9.0.pom>{staged}\n") + self.assertEqual(maven_source_problems(local, self.core_plan, self.java), []) + public = "countly-public-0c2d4b3f1e8a7c6d5b4a3f2e1d0c9b8a7f6e5d4c=" + self.write_record(local, self.java, "26.9.0", f"java-26.9.0.jar>{public}\njava-26.9.0.pom>{staged}\n") + self.assertEqual(maven_source_problems(local, self.core_plan, self.java), ["Maven resolved ly.count.sdk:java:26.9.0 from another repository than the staged release"]) + + def test_the_core_of_a_ui_release_may_come_from_anywhere(self): + local = tempfile.mkdtemp() + self.write_record(local, self.ui, "26.8.1", "java-ui-26.8.1.jar>countly=\njava-ui-26.8.1.pom>countly=\n") + self.write_record(local, self.java, "26.8.0", "java-26.8.0.jar>central=\njava-26.8.0.pom>central=\n") + self.assertEqual(maven_source_problems(local, self.ui_plan, self.ui), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/tests/test_contract.py b/.github/release/tests/test_contract.py new file mode 100644 index 000000000..7a82f9e07 --- /dev/null +++ b/.github/release/tests/test_contract.py @@ -0,0 +1,71 @@ +import tempfile +import unittest +from pathlib import Path + +from contract import actual_contract, compare, max_class_major, module_dependency_problems, summary_rows +from plan import plan_for_tag +from tests.builders import jar_bytes, module_bytes, pom_bytes, write_artifact +from tests.support import repository_config + +JSON = "org.json:json:20250517" +JSR305 = "com.google.code.findbugs:jsr305:3.0.2" +JAVA_CONTRACT = { + "schema": 1, + "coordinates": "ly.count.sdk:java", + "pomDependencies": [JSR305 + ":runtime", JSON + ":runtime"], + "moduleVariantAttributes": {"org.gradle.jvm.version": 8}, + "maxClassFileMajor": 52, +} + + +class ContractTest(unittest.TestCase): + def setUp(self): + self.config = repository_config() + self.staging = Path(tempfile.mkdtemp()) + self.java = plan_for_tag(self.config, "26.8.1").artifacts[0] + + def stage_java(self, majors=(52,), jvm_version=8, pom_dependencies=(JSON + ":runtime", JSR305 + ":runtime"), module_dependencies=(JSON, JSR305)): + """Stages java 26.8.1 with the given contents and returns the contract it actually fulfils.""" + write_artifact(self.staging, self.java, "26.8.1", main=jar_bytes(list(majors)), pom=pom_bytes(list(pom_dependencies)), module=module_bytes(jvm_version, module_dependencies)) + return actual_contract(self.staging, self.java, "26.8.1") + + def test_actual_contract_has_the_contract_file_shape(self): + self.assertEqual(self.stage_java(), JAVA_CONTRACT) + + def test_matching_contract(self): + self.assertEqual(compare(JAVA_CONTRACT, self.stage_java()), []) + self.assertEqual(module_dependency_problems(self.staging, self.java, "26.8.1"), []) + + def test_regressions_are_reported(self): + actual = self.stage_java(majors=(52, 61), jvm_version=17, pom_dependencies=[JSON + ":compile"]) + problems = compare(JAVA_CONTRACT, actual) + joined = "\n".join(problems) + self.assertEqual(len(problems), 3, joined) + for fragment in ["POM dependencies", "org.gradle.jvm.version is 17", "major version 61"]: + self.assertIn(fragment, joined) + + def test_dependency_only_in_the_module_file_is_reported(self): + self.stage_java(module_dependencies=(JSON, JSR305, "org.slf4j:slf4j-api:2.0.17")) + self.assertEqual(module_dependency_problems(self.staging, self.java, "26.8.1"), [ + f"the .module declares ['{JSR305}', '{JSON}', 'org.slf4j:slf4j-api:2.0.17'] but the POM declares ['{JSR305}', '{JSON}']", + ]) + + def test_the_core_version_of_the_ui_is_compared_exactly(self): + ui = plan_for_tag(self.config, "ui-26.8.1").artifacts[0] + contract = {"schema": 1, "coordinates": "ly.count.sdk:java-ui", "pomDependencies": ["ly.count.sdk:java:26.8.0:compile", JSON + ":runtime"], "moduleVariantAttributes": {"org.gradle.jvm.version": 17}, "maxClassFileMajor": 61} + write_artifact(self.staging, ui, "26.8.1", main=jar_bytes([61]), pom=pom_bytes(["ly.count.sdk:java:26.8.1:compile", JSON + ":runtime"]), module=module_bytes(17, ["ly.count.sdk:java:26.8.1", JSON])) + actual = actual_contract(self.staging, ui, "26.8.1") + self.assertEqual(actual["pomDependencies"], ["ly.count.sdk:java:26.8.1:compile", JSON + ":runtime"]) + self.assertEqual(compare(contract, actual), [f"POM dependencies are ['ly.count.sdk:java:26.8.1:compile', '{JSON}:runtime'], the contract says ['ly.count.sdk:java:26.8.0:compile', '{JSON}:runtime']"]) + + def test_highest_class_version_wins(self): + self.assertEqual(max_class_major(jar_bytes([52, 50])), 52) + + def test_summary_rows(self): + rows = summary_rows(JAVA_CONTRACT, self.stage_java()) + self.assertIn(("org.gradle.jvm.version", "8", "8"), rows) + self.assertIn(("highest class file version", "at most 52", "52"), rows) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/tests/test_index.py b/.github/release/tests/test_index.py new file mode 100644 index 000000000..a0540928b --- /dev/null +++ b/.github/release/tests/test_index.py @@ -0,0 +1,69 @@ +import datetime +import hashlib +import unittest + +from index import METADATA_CACHE, complete_versions, listed_versions, render, rewrite_index +from tests.support import FakeBucket +from upload import IMMUTABLE + +NOW = datetime.datetime(2026, 10, 27, 10, 15, 0) + + +def quiet(line): + """Swallows log lines.""" + + +class IndexTest(unittest.TestCase): + def test_complete_versions_need_a_pom(self): + keys = [ + "ly/count/sdk/java/26.8.1/java-26.8.1.pom", + "ly/count/sdk/java/26.8.1/java-26.8.1.jar", + "ly/count/sdk/java/26.9.0/java-26.9.0.jar", + "ly/count/sdk/java/maven-metadata.xml", + "ly/count/sdk/java-ui/26.8.1/java-ui-26.8.1.pom", + ] + self.assertEqual(complete_versions(keys, "ly/count/sdk", "java"), {"26.8.1"}) + + def test_only_final_versions_are_listed_in_numeric_order(self): + folders = {"26.1.10", "26.2.0-rc1", "26.1.6-rc2", "26.1.6", "26.10.0", "26.9.1", "19.09-sdk2-rc", "21.11.0-RC1", "26.3.0-hotfix"} + self.assertEqual(listed_versions(folders), ["26.1.6", "26.1.10", "26.9.1", "26.10.0"]) + + def test_render(self): + self.assertEqual(render("ly.count.sdk", "java", ["26.1.10", "26.2.0"], NOW), "\n".join([ + '', + "", + " ly.count.sdk", + " java", + " ", + " 26.2.0", + " 26.2.0", + " ", + " 26.1.10", + " 26.2.0", + " ", + " 20261027101500", + " ", + "", + "", + ])) + + def test_rewrite_writes_checksums_first_and_the_body_last(self): + bucket = FakeBucket() + for version in ["26.1.6", "26.2.0", "26.2.0-rc1"]: + bucket.objects[f"ly/count/sdk/java/{version}/java-{version}.pom"] = (b"pom", "application/xml", IMMUTABLE) + self.assertEqual(rewrite_index(bucket, "ly.count.sdk", "java", NOW, log=quiet), ["26.1.6", "26.2.0"]) + self.assertEqual(bucket.calls, [f"ly/count/sdk/java/maven-metadata.xml.{suffix}" for suffix in ["md5", "sha1", "sha256", "sha512"]] + ["ly/count/sdk/java/maven-metadata.xml"]) + body, kind, cache = bucket.objects["ly/count/sdk/java/maven-metadata.xml"] + self.assertEqual((kind, cache), ("application/xml", METADATA_CACHE)) + self.assertEqual(bucket.objects["ly/count/sdk/java/maven-metadata.xml.sha1"][0], hashlib.sha1(body).hexdigest().encode("ascii")) + self.assertIn(b"26.2.0", body) + + def test_no_listed_version_writes_nothing(self): + bucket = FakeBucket() + bucket.objects["ly/count/sdk/java/26.2.0-rc1/java-26.2.0-rc1.pom"] = (b"pom", "application/xml", IMMUTABLE) + self.assertEqual(rewrite_index(bucket, "ly.count.sdk", "java", NOW, log=quiet), []) + self.assertEqual(bucket.calls, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/tests/test_layout.py b/.github/release/tests/test_layout.py new file mode 100644 index 000000000..1264e0e12 --- /dev/null +++ b/.github/release/tests/test_layout.py @@ -0,0 +1,68 @@ +import tempfile +import unittest +from pathlib import Path + +from layout import check_staging, expected_files, primary_files, remove_index_files, write_checksums +from plan import plan_for_tag +from tests.builders import write_artifact +from tests.support import repository_config + + +class LayoutTest(unittest.TestCase): + def setUp(self): + self.config = repository_config() + self.staging = Path(tempfile.mkdtemp()) + self.plan = plan_for_tag(self.config, "26.8.1") + self.ui_plan = plan_for_tag(self.config, "ui-26.8.1") + + def test_expected_files_of_a_jar(self): + ui = self.ui_plan.artifacts[0] + self.assertEqual(primary_files(ui, "26.8.1"), ["java-ui-26.8.1.jar", "java-ui-26.8.1.pom", "java-ui-26.8.1.module", "java-ui-26.8.1-sources.jar", "java-ui-26.8.1-javadoc.jar", "java-ui-26.8.1-cyclonedx.json"]) + self.assertEqual(len(expected_files(ui, "26.8.1")), 30) + + def test_checksums_are_plain_hex(self): + path = self.staging / "a.txt" + path.write_bytes(b"abc") + write_checksums(path) + self.assertEqual((self.staging / "a.txt.md5").read_bytes(), b"900150983cd24fb0d6963f7d28e17f72") + self.assertEqual((self.staging / "a.txt.sha1").read_bytes(), b"a9993e364706816aba3e25717850c26c9cd0d89d") + + def test_complete_staging_passes(self): + for plan in (self.plan, self.ui_plan): + with self.subTest(tag=plan.tag): + staging = Path(tempfile.mkdtemp()) + for artifact in plan.artifacts: + write_artifact(staging, artifact, plan.version) + self.assertEqual(check_staging(staging, plan), []) + + def test_a_tag_stages_only_its_own_artifact(self): + write_artifact(self.staging, self.ui_plan.artifacts[0], self.ui_plan.version) + write_artifact(self.staging, self.plan.artifacts[0], self.plan.version) + problems = check_staging(self.staging, self.ui_plan) + self.assertEqual(len(problems), 30) + self.assertIn("unexpected ly/count/sdk/java/26.8.1/java-26.8.1.jar", problems) + + def test_missing_unexpected_and_wrong_files_are_reported(self): + folder = write_artifact(self.staging, self.plan.artifacts[0], self.plan.version) + (folder / "java-26.8.1-javadoc.jar").unlink() + (folder / "notes.txt").write_bytes(b"x") + (folder / "java-26.8.1.pom.sha1").write_bytes(b"0" * 40) + (self.staging / "ly/count/sdk/other").mkdir(parents=True) + (self.staging / "ly/count/sdk/other/x.jar").write_bytes(b"x") + self.assertEqual(check_staging(self.staging, self.plan), [ + "missing ly/count/sdk/java/26.8.1/java-26.8.1-javadoc.jar", + "unexpected ly/count/sdk/java/26.8.1/notes.txt", + "unexpected ly/count/sdk/other/x.jar", + "wrong checksum ly/count/sdk/java/26.8.1/java-26.8.1.pom.sha1", + ]) + + def test_index_files_are_removed(self): + path = self.staging / "ly/count/sdk/java/maven-metadata.xml.sha1" + path.parent.mkdir(parents=True) + path.write_bytes(b"x") + remove_index_files(self.staging) + self.assertFalse(path.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/tests/test_manifest.py b/.github/release/tests/test_manifest.py new file mode 100644 index 000000000..144786170 --- /dev/null +++ b/.github/release/tests/test_manifest.py @@ -0,0 +1,23 @@ +import hashlib +import tempfile +import unittest +from pathlib import Path + +from manifest import build_manifest, verify_manifest + + +class ManifestTest(unittest.TestCase): + def test_round_trip_and_changes(self): + staging = Path(tempfile.mkdtemp()) + (staging / "a").mkdir() + (staging / "a/x.pom").write_bytes(b"one") + manifest = build_manifest(staging, "26.2.0", "c" * 40) + self.assertEqual(manifest, {"tag": "26.2.0", "commit": "c" * 40, "files": [{"path": "a/x.pom", "size": 3, "sha256": hashlib.sha256(b"one").hexdigest()}]}) + self.assertEqual(verify_manifest(staging, manifest), []) + (staging / "a/x.pom").write_bytes(b"two") + (staging / "a/y.pom").write_bytes(b"new") + self.assertEqual(verify_manifest(staging, manifest), ["unexpected a/y.pom", "changed a/x.pom"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/tests/test_pending.py b/.github/release/tests/test_pending.py new file mode 100644 index 000000000..8bf2bd512 --- /dev/null +++ b/.github/release/tests/test_pending.py @@ -0,0 +1,86 @@ +import subprocess +import tempfile +import unittest +from pathlib import Path + +from pending import merge_problems, pending_releases +from plan import PlanError +from tests.support import repository_config, write_core, write_ui + +HEAD = "a" * 40 +MERGE = "b" * 40 +RELEASED = {"26.8.0", "ui-26.8.0"} + + +def git_runner(contains_head, trees): + """A stand-in for subprocess.run answering the two git questions of merge_problems: whether the merge contains the + head, and the tree of each commit.""" + def run(args, **kwargs): + if "merge-base" in args: + return subprocess.CompletedProcess(args, 0 if contains_head else 1) + return subprocess.CompletedProcess(args, 0, stdout="".join(trees[arg.split("^")[0]] + "\n" for arg in args[-2:])) + return run + + +class PendingTest(unittest.TestCase): + def setUp(self): + self.config = repository_config() + self.root = Path(tempfile.mkdtemp()) + + def checkout(self, core, ui, changelog, ui_changelog, gradle=None): + """Writes the version sources and the changelogs of the core and the UI.""" + write_core(self.root, core, gradle or core, core, changelog) + write_ui(self.root, ui, ui_changelog) + + def test_new_versions_are_released_core_first_with_their_changelog_sections_and_only_the_core_is_latest(self): + self.checkout("26.9.0", "26.9.0", "## 26.9.0\n\n* Core change.\n with a second line\n\n## 26.8.0\n* Old.\n", "## 26.9.0\n* UI change.\n") + releases, problems = pending_releases(self.config, self.root, "staging", RELEASED) + self.assertEqual(problems, []) + self.assertEqual([(release.tag, release.latest, release.prerelease) for release in releases], [("26.9.0", True, False), ("ui-26.9.0", False, False)]) + self.assertEqual([release.notes for release in releases], ["* Core change.\n with a second line\n", "* UI change.\n"]) + self.assertEqual(releases[1].to_json(), {"tag": "ui-26.9.0", "prerelease": False, "latest": False}) + + def test_tagged_versions_are_skipped_so_an_unchanged_ui_or_a_repeated_merge_releases_nothing_more(self): + self.checkout("26.9.0", "26.8.0", "## 26.9.0\n* Core change.\n", "## 26.8.0\n* Old UI.\n") + releases, problems = pending_releases(self.config, self.root, "staging", RELEASED) + self.assertEqual(([release.tag for release in releases], problems), (["26.9.0"], [])) + self.assertEqual(pending_releases(self.config, self.root, "staging", RELEASED | {"26.9.0"}), ([], [])) + + def test_a_changelog_or_a_version_source_not_ready_is_reported_for_every_release(self): + self.checkout("26.9.0", "26.9.0", "## XX.XX.XX\n* Still waiting.\n\n## 26.9.0\n* Core change.\n", "## 26.8.0\n", gradle="26.8.0") + _, problems = pending_releases(self.config, self.root, "staging", RELEASED) + self.assertEqual(problems, [ + "build.gradle: version is 26.8.0, the tag says 26.9.0", + "CHANGELOG.md: still has a '## XX.XX.XX' heading; move its lines under '## 26.9.0'", + "sdk-java-ui/CHANGELOG.md: no '## 26.9.0' heading", + ]) + + def test_a_release_candidate_is_a_prerelease_never_latest_with_the_placeholder_section_as_notes(self): + self.checkout("26.9.0-rc1", "26.8.0", "## XX.XX.XX\n* Coming soon.\n\n## 26.8.0\n* Old.\n", "## 26.8.0\n") + releases, problems = pending_releases(self.config, self.root, "staging", RELEASED) + self.assertEqual(problems, []) + self.assertEqual([(release.tag, release.latest, release.prerelease, release.notes) for release in releases], [("26.9.0-rc1", False, True, "* Coming soon.\n")]) + + def test_a_release_candidate_falls_back_to_its_version_section_and_needs_one_of_them(self): + self.checkout("26.9.0-rc1", "26.8.0", "## 26.9.0-rc1\n* Ready early.\n", "## 26.8.0\n") + releases, problems = pending_releases(self.config, self.root, "staging", RELEASED) + self.assertEqual(([release.notes for release in releases], problems), (["* Ready early.\n"], [])) + self.checkout("26.9.0-rc1", "26.8.0", "## 26.8.0\n* Old.\n", "## 26.8.0\n") + _, problems = pending_releases(self.config, self.root, "staging", RELEASED) + self.assertEqual(problems, ["CHANGELOG.md: no '## 26.9.0-rc1' heading"]) + + def test_a_version_outside_the_tag_grammar_stops_the_plan(self): + self.checkout("XX.XX.XX", "26.8.0", "## XX.XX.XX\n", "## 26.8.0\n") + with self.assertRaises(PlanError): + pending_releases(self.config, self.root, "staging", RELEASED) + + def test_the_merge_must_contain_the_head_and_hold_exactly_its_tree(self): + self.assertEqual(merge_problems(HEAD, MERGE, "/repo", runner=git_runner(True, {HEAD: "tree", MERGE: "tree"})), []) + self.assertEqual(merge_problems(HEAD, MERGE, "/repo", runner=git_runner(False, {})), + [f"{MERGE} does not contain {HEAD}; merge the release PR with a merge commit, not a squash or a rebase"]) + self.assertEqual(merge_problems(HEAD, MERGE, "/repo", runner=git_runner(True, {HEAD: "tree", MERGE: "other"})), + ["master holds changes staging lacks; merge master into staging, then update the release PR"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/tests/test_plan.py b/.github/release/tests/test_plan.py new file mode 100644 index 000000000..9ca31e6e2 --- /dev/null +++ b/.github/release/tests/test_plan.py @@ -0,0 +1,83 @@ +import tempfile +import unittest +from pathlib import Path + +from plan import PlanError, checkout_tags, plan_for_tag, plan_from_json +from tests.support import repository_config + +JAVA = ["ly.count.sdk:java"] +UI = ["ly.count.sdk:java-ui"] + + +class PlanTest(unittest.TestCase): + def setUp(self): + self.config = repository_config() + + def test_tags(self): + cases = [ + ("26.8.1", JAVA, "26.8.1", True), + ("26.8.1-rc1", JAVA, "26.8.1-rc1", False), + ("0.0.1", JAVA, "0.0.1", True), + ("ui-26.8.1", UI, "26.8.1", True), + ("ui-26.8.1-rc1", UI, "26.8.1-rc1", False), + ("ui-0.0.1", UI, "0.0.1", True), + ] + for tag, artifacts, version, listed in cases: + with self.subTest(tag=tag): + plan = plan_for_tag(self.config, tag) + self.assertEqual(plan.branch, "staging") + self.assertEqual([artifact.coordinates for artifact in plan.artifacts], artifacts) + self.assertEqual(plan.version, version) + self.assertEqual(plan.listed, listed) + self.assertEqual(plan.prerelease, not listed) + + def test_refused_tags(self): + refused = [ + "v26.8.1", "26.8", "26.8.1-RC1", "26.8.1-rc.1", " 26.8.1", "26.8.1-nw", "native-26.8.1", "plugin-26.8.1", + "26.8.1/../x", "java-26.8.1", "٢٦.8.1", "ui-26.8", "ui-v26.8.1", "UI-26.8.1", "ui26.8.1", + "java-ui-26.8.1", "26.8.1-ui", "ui-ui-26.8.1", + ] + for tag in refused: + with self.subTest(tag=tag): + with self.assertRaises(PlanError): + plan_for_tag(self.config, tag) + + def test_modules_and_round_trip(self): + core = plan_for_tag(self.config, "26.8.1") + ui = plan_for_tag(self.config, "ui-26.8.1") + self.assertEqual(core.modules, [":sdk-java"]) + self.assertEqual(ui.modules, [":sdk-java-ui"]) + self.assertEqual(ui.artifacts[0].module_dir, "sdk-java-ui") + self.assertEqual(ui.artifacts[0].folder("26.8.1"), "ly/count/sdk/java-ui/26.8.1") + for plan in (core, ui): + self.assertEqual(plan_from_json(self.config, plan.to_json()), plan) + + def test_artifact_details(self): + java = plan_for_tag(self.config, "26.8.1").artifacts[0] + ui = plan_for_tag(self.config, "ui-26.8.1").artifacts[0] + self.assertEqual((java.contract, java.consumer_java), (".github/release-contract/java.json", 8)) + self.assertEqual((ui.contract, ui.consumer_java), (".github/release-contract/java-ui.json", 17)) + + def test_checkout_tags_follow_each_version_file(self): + root = Path(tempfile.mkdtemp()) + (root / "gradle.properties").write_bytes(b"VERSION_NAME=26.9.0-rc1\r\nGROUP=ly.count.sdk\r\n") + (root / "sdk-java-ui").mkdir() + (root / "sdk-java-ui/gradle.properties").write_bytes(b"POM_ARTIFACT_ID=java-ui\r\nVERSION_NAME=26.8.0\r\n") + self.assertEqual(checkout_tags(self.config, root, "staging"), ["26.9.0-rc1", "ui-26.8.0"]) + self.assertEqual(checkout_tags(self.config, root, "master"), []) + + def test_checkout_tags_need_a_readable_version(self): + root = Path(tempfile.mkdtemp()) + with self.assertRaises(PlanError): + checkout_tags(self.config, root, "staging") + (root / "gradle.properties").write_bytes(b"VERSION_NAME=26.9.0\n") + with self.assertRaises(PlanError): + checkout_tags(self.config, root, "staging") + (root / "sdk-java-ui").mkdir() + (root / "sdk-java-ui/gradle.properties").write_bytes(b"POM_ARTIFACT_ID=java-ui\n") + with self.assertRaises(PlanError): + checkout_tags(self.config, root, "staging") + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/tests/test_release_cli.py b/.github/release/tests/test_release_cli.py new file mode 100644 index 000000000..29852036d --- /dev/null +++ b/.github/release/tests/test_release_cli.py @@ -0,0 +1,114 @@ +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from tests.support import write_core, write_ui + +RELEASE = Path(__file__).resolve().parents[1] / "release.py" + + +def run_cli(*args, output="", script=RELEASE): + """Runs release.py like the workflow does; GitHub's step output file is written only when `output` names one.""" + env = dict(os.environ, GITHUB_OUTPUT=output, GITHUB_STEP_SUMMARY="") + return subprocess.run([sys.executable, str(script), *args], capture_output=True, text=True, env=env) + + +class ReleaseCliTest(unittest.TestCase): + def setUp(self): + self.folder = Path(tempfile.mkdtemp()) + + def test_plan_writes_plan_json_and_the_task_lists(self): + cases = [ + ("26.8.1", ["java"], ":sdk-java:check", ":sdk-java:publishAllPublicationsToReleaseStagingRepository :sdk-java:cyclonedxDirectBom"), + ("ui-26.8.1", ["java-ui"], ":sdk-java-ui:check", ":sdk-java-ui:publishAllPublicationsToReleaseStagingRepository :sdk-java-ui:cyclonedxDirectBom"), + ] + for tag, artifacts, check_tasks, publish_tasks in cases: + with self.subTest(tag=tag): + out = self.folder / "plan.json" + output = self.folder / "output" + output.write_bytes(b"") + result = run_cli("plan", "--tag", tag, "--target", "test", "--out", str(out), output=str(output)) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(json.loads(out.read_text(encoding="utf-8"))["artifacts"], artifacts) + lines = dict(line.split("=", 1) for line in output.read_text(encoding="utf-8").splitlines()) + self.assertEqual(lines["environment"], "maven-test") + self.assertEqual(lines["check_tasks"], check_tasks) + self.assertEqual(lines["publish_tasks"], publish_tasks) + self.assertEqual(lines["published_modules"], ":sdk-java,:sdk-java-ui") + + def test_plan_refuses_an_unknown_tag(self): + result = run_cli("plan", "--tag", "v1", "--target", "test", "--out", str(self.folder / "plan.json")) + self.assertEqual(result.returncode, 1) + self.assertIn("::error::", result.stdout) + + def test_checkout_tags_are_a_json_list_the_matrix_can_read(self): + output = self.folder / "output" + output.write_bytes(b"") + result = run_cli("checkout-tags", "--branch", "staging", output=str(output)) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + line = output.read_text(encoding="utf-8").strip() + self.assertTrue(line.startswith("tags="), line) + tags = json.loads(line[len("tags="):]) + self.assertEqual(len(tags), 2) + self.assertTrue(tags[1].startswith("ui-"), tags) + + def test_a_branch_without_releases_gets_the_empty_list_the_workflow_skips_on(self): + output = self.folder / "output" + output.write_bytes(b"") + result = run_cli("checkout-tags", "--branch", "master", output=str(output)) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(output.read_text(encoding="utf-8").strip(), "tags=[]") + + def test_pending_creates_nothing_when_the_merge_does_not_contain_the_head(self): + out = self.folder / "pending.json" + result = run_cli("pending", "--head", "0" * 40, "--merge", "HEAD", "--branch", "staging", "--out", str(out), "--notes", str(self.folder / "notes")) + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("::error::", result.stdout) + self.assertFalse(out.exists()) + + def test_pending_writes_the_untagged_releases_and_their_notes_for_the_workflow(self): + """Runs a copy of the release tools in a throwaway repository whose core version has no tag yet.""" + repo = self.folder / "repo" + shutil.copytree(RELEASE.parent, repo / ".github/release", ignore=shutil.ignore_patterns("tests", "__pycache__")) + write_core(repo, "26.9.0", "26.9.0", "26.9.0", "## 26.9.0\n* Core change.\n\n## 26.8.0\n* Old.\n") + write_ui(repo, "26.8.0", "## 26.8.0\n* Old UI.\n") + git = ["git", "-C", str(repo), "-c", "user.name=Release test", "-c", "user.email=release@example.com", "-c", "commit.gpgsign=false", "-c", "tag.gpgSign=false"] + subprocess.run(["git", "init", "-q", str(repo)], check=True) + subprocess.run(git + ["add", "-A"], check=True) + subprocess.run(git + ["commit", "-q", "-m", "Release 26.9.0"], check=True) + subprocess.run(git + ["tag", "ui-26.8.0"], check=True) + out = self.folder / "pending.json" + notes = self.folder / "notes" + result = run_cli("pending", "--head", "HEAD", "--merge", "HEAD", "--branch", "staging", "--out", str(out), "--notes", str(notes), script=repo / ".github/release/release.py") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(json.loads(out.read_text(encoding="utf-8")), {"releases": [{"tag": "26.9.0", "prerelease": False, "latest": True}]}) + self.assertEqual(sorted(path.name for path in notes.iterdir()), ["26.9.0.md"]) + self.assertEqual((notes / "26.9.0.md").read_text(encoding="utf-8"), "* Core change.\n") + + def test_prerelease_flag_must_match(self): + cases = [("26.8.1", "true", 1), ("26.8.1-rc1", "false", 1), ("26.8.1", "unknown", 1), ("26.8.1-rc1", "true", 0), ("26.8.1", "false", 0)] + for tag, prerelease, code in cases: + with self.subTest(tag=tag, prerelease=prerelease): + result = run_cli("plan", "--tag", tag, "--target", "production", "--prerelease", prerelease, "--out", str(self.folder / "plan.json")) + self.assertEqual(result.returncode, code, result.stdout) + + def test_check_environment_reads_the_api_answer_and_fails_an_unprotected_environment(self): + """The workflow saves the environments API answer and passes its path; an unprotected environment fails the step.""" + protected = {"name": "maven-release", "protection_rules": [{"type": "required_reviewers", "reviewers": [{"type": "User"}]}], + "deployment_branch_policy": {"protected_branches": False, "custom_branch_policies": True}} + unprotected = {"name": "maven-release", "protection_rules": [], "deployment_branch_policy": None} + for environment, code in ((protected, 0), (unprotected, 1)): + with self.subTest(code=code): + path = self.folder / "environment.json" + path.write_text(json.dumps(environment), encoding="utf-8") + result = run_cli("check-environment", "--environment", str(path)) + self.assertEqual(result.returncode, code, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/tests/test_s3.py b/.github/release/tests/test_s3.py new file mode 100644 index 000000000..1967aed2d --- /dev/null +++ b/.github/release/tests/test_s3.py @@ -0,0 +1,51 @@ +import subprocess +import unittest + +from s3 import R2Bucket, S3Error + + +class RecordingRunner: + """Stands in for subprocess.run and replays one prepared result.""" + + def __init__(self, returncode=0, stdout="", stderr=""): + self.result = (returncode, stdout, stderr) + self.calls = [] + + def __call__(self, args, **kwargs): + self.calls.append((args, kwargs)) + return subprocess.CompletedProcess(args, *self.result) + + +class R2BucketTest(unittest.TestCase): + def test_create_only_put_uses_if_none_match_and_the_r2_endpoint(self): + runner = RecordingRunner() + bucket = R2Bucket("countly-maven", "abc123", runner=runner) + self.assertEqual(bucket.put_file("a/b.pom", "/tmp/b.pom", "application/xml", "public, max-age=60", create_only=True), "created") + args, kwargs = runner.calls[0] + self.assertEqual(args[:3], ["aws", "s3api", "put-object"]) + self.assertIn("--if-none-match", args) + self.assertEqual(args[args.index("--endpoint-url") + 1], "https://abc123.r2.cloudflarestorage.com") + self.assertEqual(kwargs["env"]["AWS_DEFAULT_REGION"], "auto") + self.assertEqual(kwargs["env"]["AWS_REQUEST_CHECKSUM_CALCULATION"], "when_required") + + def test_existing_key_and_missing_key(self): + exists = R2Bucket("b", "a", runner=RecordingRunner(254, "", "An error occurred (PreconditionFailed) when calling the PutObject operation")) + self.assertEqual(exists.put_file("k", "/tmp/f", "t", "c", create_only=True), "exists") + missing = R2Bucket("b", "a", runner=RecordingRunner(254, "", "An error occurred (404) when calling the HeadObject operation: Not Found")) + self.assertIsNone(missing.head("k")) + + def test_other_errors_raise(self): + broken = R2Bucket("b", "a", runner=RecordingRunner(255, "", "An error occurred (AccessDenied)")) + with self.assertRaises(S3Error): + broken.put_file("k", "/tmp/f", "t", "c", create_only=True) + + def test_head_and_list(self): + head = R2Bucket("b", "a", runner=RecordingRunner(0, '{"ETag": "\\"0cc175b9c0f1b6a831c399e269772661\\"", "ContentLength": 1}')) + self.assertEqual(head.head("k"), {"etag": "0cc175b9c0f1b6a831c399e269772661", "size": 1}) + listing = R2Bucket("b", "a", runner=RecordingRunner(0, '{"Contents": [{"Key": "x/1"}, {"Key": "x/2"}]}')) + self.assertEqual(listing.list_keys("x/"), ["x/1", "x/2"]) + self.assertEqual(R2Bucket("b", "a", runner=RecordingRunner(0, "")).list_keys("x/"), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/tests/test_sbom.py b/.github/release/tests/test_sbom.py new file mode 100644 index 000000000..5b8840890 --- /dev/null +++ b/.github/release/tests/test_sbom.py @@ -0,0 +1,80 @@ +import copy +import json +import tempfile +import unittest +from pathlib import Path + +from plan import plan_for_tag +from sbom import SbomError, normalize, place_sbom +from tests.support import repository_config + +PLUGIN_BOM = { + "bomFormat": "CycloneDX", + "specVersion": "1.6", + "serialNumber": "urn:uuid:random", + "metadata": { + "timestamp": "2026-10-01T00:00:00Z", + "component": {"type": "application", "bom-ref": "pkg:maven/ly.count.sdk/sdk-java-ui@26.8.1?type=jar", "group": "ly.count.sdk", "name": "sdk-java-ui", "version": "26.8.1"}, + "tools": {"components": [{"type": "application", "name": "cyclonedx-gradle-plugin"}]}, + }, + "components": [{"type": "library", "bom-ref": "pkg:maven/org.json/json@20250517?type=jar", "name": "json"}], + "dependencies": [{"ref": "pkg:maven/ly.count.sdk/sdk-java-ui@26.8.1?type=jar", "dependsOn": ["pkg:maven/org.json/json@20250517?type=jar"]}], +} + + +class SbomTest(unittest.TestCase): + def setUp(self): + self.config = repository_config() + self.java = plan_for_tag(self.config, "26.8.1").artifacts[0] + self.ui = plan_for_tag(self.config, "ui-26.8.1").artifacts[0] + + def test_normalize_sets_the_published_coordinates(self): + bom = normalize(copy.deepcopy(PLUGIN_BOM), self.ui, "26.8.1", "2026-10-27T10:15:00+03:00", "https://maven.countly.com/") + ref = "pkg:maven/ly.count.sdk/java-ui@26.8.1?repository_url=https%3A%2F%2Fmaven.countly.com&type=jar" + self.assertEqual(bom["metadata"]["component"], {"type": "library", "bom-ref": ref, "group": "ly.count.sdk", "name": "java-ui", "version": "26.8.1", "purl": ref, "licenses": [{"license": {"id": "MIT"}}]}) + self.assertEqual(bom["metadata"]["timestamp"], "2026-10-27T10:15:00+03:00") + self.assertNotIn("serialNumber", bom) + self.assertEqual(bom["dependencies"][0]["ref"], ref) + + def test_other_modules_of_the_build_get_their_published_coordinates(self): + core = "pkg:maven/countly-sdk-java/sdk-java@unspecified?project_path=%3Asdk-java" + bom = copy.deepcopy(PLUGIN_BOM) + bom["components"].append({"type": "library", "bom-ref": core, "group": "countly-sdk-java", "name": "sdk-java", "version": "unspecified", "purl": core}) + bom["dependencies"][0]["dependsOn"].append(core) + bom["dependencies"].append({"ref": core, "dependsOn": ["pkg:maven/org.json/json@20250517?type=jar"]}) + normalize(bom, self.ui, "26.8.1", "t", "https://maven.countly.com/", {":sdk-java": self.java, ":sdk-java-ui": self.ui}) + java_ref = "pkg:maven/ly.count.sdk/java@26.8.1?repository_url=https%3A%2F%2Fmaven.countly.com&type=jar" + self.assertEqual(bom["components"][-1], {"type": "library", "bom-ref": java_ref, "group": "ly.count.sdk", "name": "java", "version": "26.8.1", "purl": java_ref}) + self.assertIn(java_ref, bom["dependencies"][0]["dependsOn"]) + self.assertEqual(bom["dependencies"][-1]["ref"], java_ref) + self.assertNotIn("project_path", json.dumps(bom)) + + def test_platform_specific_components_carry_no_hashes(self): + bom = copy.deepcopy(PLUGIN_BOM) + hashes = [{"alg": "SHA-256", "content": "c689de189abaa839eaf628d4b34aa176f6661e0d62ca918cb4af7544172e6a60"}] + bom["components"][0]["hashes"] = copy.deepcopy(hashes) + bom["components"].append({"type": "library", "bom-ref": "pkg:maven/org.openjfx/javafx-controls@21.0.5?type=jar", "group": "org.openjfx", "name": "javafx-controls", "version": "21.0.5", "hashes": copy.deepcopy(hashes), "purl": "pkg:maven/org.openjfx/javafx-controls@21.0.5?type=jar"}) + normalize(bom, self.ui, "26.8.1", "t", "https://maven.countly.com/", platform_groups=["org.openjfx"]) + self.assertEqual(bom["components"][0]["hashes"], hashes) + self.assertNotIn("hashes", bom["components"][1]) + self.assertEqual(bom["components"][1]["purl"], "pkg:maven/org.openjfx/javafx-controls@21.0.5?type=jar") + + def test_an_unpublished_module_stops_the_release(self): + bom = copy.deepcopy(PLUGIN_BOM) + bom["components"].append({"bom-ref": "x", "purl": "pkg:maven/x/app-java@unspecified?project_path=%3Aapp-java"}) + with self.assertRaises(SbomError): + normalize(bom, self.ui, "26.8.1", "t", "https://maven.countly.com/", {":sdk-java": self.java}) + + def test_place_sbom_writes_the_file_and_its_checksums(self): + staging = Path(tempfile.mkdtemp()) + source = staging / "bom.json" + source.write_bytes(json.dumps(PLUGIN_BOM).encode("utf-8")) + target = place_sbom(source, staging, self.java, "26.8.1", "t", "https://maven.countly.com/") + self.assertEqual(target, staging / "ly/count/sdk/java/26.8.1/java-26.8.1-cyclonedx.json") + self.assertEqual(json.loads(target.read_bytes())["metadata"]["component"]["name"], "java") + for suffix in [".md5", ".sha1", ".sha256", ".sha512"]: + self.assertTrue(Path(f"{target}{suffix}").is_file()) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/tests/test_sign.py b/.github/release/tests/test_sign.py new file mode 100644 index 000000000..f580c58e0 --- /dev/null +++ b/.github/release/tests/test_sign.py @@ -0,0 +1,74 @@ +import subprocess +import tempfile +import unittest +from pathlib import Path + +from sign import SigningError, export_public_key, sign_staging, signing_fingerprint + +RELEASE = "FC8DB0DE234A273BA45E562FB8C83A079A5BBD0C" +DRY_RUN = "1111111111111111111111111111111111111111" +OTHER = "2222222222222222222222222222222222222222" +SUBKEY = "9999999999999999999999999999999999999999" + + +def keyring(*fingerprints): + """A fake gpg whose secret keyring holds one primary key, with an encryption subkey, per fingerprint.""" + listing = "".join( + f"sec:u:4096:1:{fp[-16:]}:1:::u:::scESC:\nfpr:::::::::{fp}:\ngrp:::::::::{'A' * 40}:\n" + f"ssb:u:4096:1:{SUBKEY[-16:]}:1::::::e:\nfpr:::::::::{SUBKEY}:\n" + for fp in fingerprints + ) + + def fake_gpg(args, **kwargs): + return subprocess.CompletedProcess(args, 0, listing, "") + return fake_gpg + + +class SignTest(unittest.TestCase): + def test_signs_everything_but_checksums_with_the_chosen_key(self): + staging = Path(tempfile.mkdtemp()) + (staging / "a").mkdir() + for name in ["x.pom", "x.pom.sha1", "x.jar", "x.jar.md5"]: + (staging / "a" / name).write_bytes(b"x") + calls = [] + + def fake_gpg(args, **kwargs): + calls.append((args, kwargs.get("input"))) + Path(args[args.index("--output") + 1]).write_bytes(b"signature") + return subprocess.CompletedProcess(args, 0, "", "") + + signed = sign_staging(staging, "/tmp/gnupg", "secret", RELEASE, runner=fake_gpg) + self.assertEqual([path.name for path in signed], ["x.jar", "x.pom"]) + self.assertTrue((staging / "a/x.pom.asc").is_file()) + self.assertFalse((staging / "a/x.pom.sha1.asc").exists()) + self.assertTrue(all(passphrase == "secret" and "--passphrase-fd" in args for args, passphrase in calls)) + self.assertTrue(all(args[args.index("--local-user") + 1] == RELEASE + "!" for args, _ in calls)) + + def test_production_needs_the_release_key(self): + self.assertEqual(signing_fingerprint("/tmp/gnupg", RELEASE, production=True, runner=keyring(RELEASE)), RELEASE) + with self.assertRaises(SigningError): + signing_fingerprint("/tmp/gnupg", RELEASE, production=True, runner=keyring(OTHER)) + + def test_dry_run_refuses_the_release_key_and_needs_exactly_one_key(self): + self.assertEqual(signing_fingerprint("/tmp/gnupg", RELEASE, production=False, runner=keyring(DRY_RUN)), DRY_RUN) + for fingerprints in [(RELEASE,), (DRY_RUN, OTHER), ()]: + with self.subTest(fingerprints=fingerprints): + with self.assertRaises(SigningError): + signing_fingerprint("/tmp/gnupg", RELEASE, production=False, runner=keyring(*fingerprints)) + + def test_exports_the_public_key(self): + target = Path(tempfile.mkdtemp()) / "key.asc" + calls = [] + + def fake_gpg(args, **kwargs): + calls.append(args) + return subprocess.CompletedProcess(args, 0, "-----BEGIN PGP PUBLIC KEY BLOCK-----\nabc\n", "") + + export_public_key("/tmp/gnupg", DRY_RUN, target, runner=fake_gpg) + self.assertTrue(target.read_bytes().startswith(b"-----BEGIN PGP PUBLIC KEY BLOCK-----")) + self.assertIn("--export", calls[0]) + self.assertEqual(calls[0][-1], DRY_RUN) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/tests/test_sources.py b/.github/release/tests/test_sources.py new file mode 100644 index 000000000..b8b37b826 --- /dev/null +++ b/.github/release/tests/test_sources.py @@ -0,0 +1,84 @@ +import re +import tempfile +import unittest +from pathlib import Path + +from plan import plan_for_tag +from sources import changelog_section, check_version_sources +from tests.support import repository_config, write_core, write_file + + +class SourcesTest(unittest.TestCase): + def setUp(self): + self.config = repository_config() + self.root = Path(tempfile.mkdtemp()) + + def write(self, relative, text): + """Writes a file of the fake checkout.""" + write_file(self.root, relative, text) + + def write_sdk(self, properties_version, gradle_version, java_version, changelog): + """Writes the three version sources and the changelog.""" + write_core(self.root, properties_version, gradle_version, java_version, changelog) + + def test_matching_sources(self): + self.write_sdk("26.8.1", "26.8.1", "26.8.1", "## 26.8.1\n* Fixed things.\n") + self.assertEqual(check_version_sources(self.root, plan_for_tag(self.config, "26.8.1"), self.config), []) + + def test_mismatches_are_reported_once(self): + self.write_sdk("26.8.1", "26.8.0", "26.8.2", "## XX.XX.XX\n") + problems = check_version_sources(self.root, plan_for_tag(self.config, "26.8.1"), self.config) + self.assertEqual(problems, [ + "build.gradle: version is 26.8.0, the tag says 26.8.1", + "sdk-java/src/main/java/ly/count/sdk/java/Config.java: version is 26.8.2, the tag says 26.8.1", + "CHANGELOG.md: no '## 26.8.1' heading", + "CHANGELOG.md: still has a '## XX.XX.XX' heading; move its lines under '## 26.8.1'", + ]) + + def test_candidates_need_no_changelog_heading(self): + self.write_sdk("26.8.1-rc1", "26.8.1-rc1", "26.8.1-rc1", "## XX.XX.XX\n") + self.assertEqual(check_version_sources(self.root, plan_for_tag(self.config, "26.8.1-rc1"), self.config), []) + + def test_windows_line_endings_are_accepted(self): + self.write_sdk("26.8.1\r", "26.8.1", "26.8.1", "## 26.8.1\r\n") + self.assertEqual(check_version_sources(self.root, plan_for_tag(self.config, "26.8.1"), self.config), []) + + def test_ui_uses_its_own_version_and_changelog(self): + self.write_sdk("26.9.0", "26.9.0", "26.9.0", "## 26.9.0\n") + self.write("sdk-java-ui/gradle.properties", "POM_ARTIFACT_ID=java-ui\nVERSION_NAME=26.8.1\n") + self.write("sdk-java-ui/CHANGELOG.md", "## 26.8.1\n* Fixed the survey card.\n") + self.assertEqual(check_version_sources(self.root, plan_for_tag(self.config, "ui-26.8.1"), self.config), []) + self.assertEqual(check_version_sources(self.root, plan_for_tag(self.config, "26.9.0"), self.config), []) + + def test_ui_mismatches_are_reported(self): + self.write("sdk-java-ui/gradle.properties", "POM_ARTIFACT_ID=java-ui\nVERSION_NAME=26.8.0\n") + self.write("sdk-java-ui/CHANGELOG.md", "## 26.8.0\n") + self.assertEqual(check_version_sources(self.root, plan_for_tag(self.config, "ui-26.8.1"), self.config), [ + "sdk-java-ui/gradle.properties: version is 26.8.0, the tag says 26.8.1", + "sdk-java-ui/CHANGELOG.md: no '## 26.8.1' heading", + ]) + + def test_a_changelog_section_ends_at_the_next_heading_and_keeps_its_lines(self): + text = "## XX.XX.XX\n\n* New.\n ```groovy\n code\n ```\n\n## 26.8.0\n* Old.\n" + self.assertEqual(changelog_section(text, "XX.XX.XX"), "* New.\n ```groovy\n code\n ```\n") + self.assertEqual(changelog_section(text, "26.8.0"), "* Old.\n") + self.assertIsNone(changelog_section(text, "26.9.0")) + fenced = "## 26.9.0\r\n* Add the repository:\r\n```markdown\r\n## Not a release\r\n```\r\n## 26.8.0\r\n" + self.assertEqual(changelog_section(fenced, "26.9.0"), "* Add the repository:\n```markdown\n## Not a release\n```\n") + + def test_a_missing_changelog_is_reported(self): + self.write_sdk("26.9.0", "26.9.0", "26.9.0", "") + (self.root / "CHANGELOG.md").unlink() + self.assertEqual(check_version_sources(self.root, plan_for_tag(self.config, "26.9.0"), self.config), ["CHANGELOG.md does not exist"]) + + def test_every_version_source_is_found_in_this_checkout(self): + root = Path(__file__).resolve().parents[3] + for spec in self.config["artifacts"].values(): + for source in spec["versionSources"]: + with self.subTest(file=source["file"]): + text = (root / source["file"]).read_text(encoding="utf-8") + self.assertIsNotNone(re.search(source["regex"], text, re.MULTILINE)) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/tests/test_upload.py b/.github/release/tests/test_upload.py new file mode 100644 index 000000000..df6673464 --- /dev/null +++ b/.github/release/tests/test_upload.py @@ -0,0 +1,80 @@ +import datetime +import tempfile +import unittest +from pathlib import Path + +from index import rewrite_index +from plan import plan_for_tag +from tests.builders import write_artifact +from tests.support import FakeBucket, repository_config +from upload import IMMUTABLE, UploadError, content_type, upload_order, upload_release + +POM = "ly/count/sdk/java/26.8.1/java-26.8.1.pom" +JAR = "ly/count/sdk/java/26.8.1/java-26.8.1.jar" + + +def quiet(line): + """Swallows log lines.""" + + +class UploadTest(unittest.TestCase): + def setUp(self): + self.config = repository_config() + self.staging = Path(tempfile.mkdtemp()) + self.plan = plan_for_tag(self.config, "26.8.1") + + def stage(self): + """Stages the artifact of the tag and returns its folder.""" + return write_artifact(self.staging, self.plan.artifacts[0], self.plan.version) + + def test_pom_family_goes_last(self): + names = ["a.pom", "a.pom.asc", "a.pom.sha1", "a.jar", "a.jar.sha1", "a.module"] + self.assertEqual(upload_order(names, "a.pom"), ["a.jar", "a.jar.sha1", "a.module", "a.pom.asc", "a.pom.sha1", "a.pom"]) + + def test_upload_creates_then_skips_identical_files(self): + self.stage() + bucket = FakeBucket() + upload_release(bucket, self.staging, self.plan, log=quiet) + stored = dict(bucket.objects) + self.assertEqual(bucket.calls[-1], POM) + self.assertEqual(len(bucket.calls), 30) + self.assertEqual(stored[POM][2], IMMUTABLE) + self.assertEqual(stored[JAR][1], "application/java-archive") + upload_release(bucket, self.staging, self.plan, log=quiet) + self.assertEqual(bucket.objects, stored) + + def test_rerun_keeps_signatures_from_the_first_attempt(self): + folder = self.stage() + signature = folder / "java-26.8.1.pom.asc" + signature.write_bytes(b"first attempt") + bucket = FakeBucket() + upload_release(bucket, self.staging, self.plan, log=quiet) + signature.write_bytes(b"second attempt") + upload_release(bucket, self.staging, self.plan, log=quiet) + self.assertEqual(bucket.objects[POM + ".asc"][0], b"first attempt") + + def test_different_bytes_stop_the_upload(self): + folder = self.stage() + bucket = FakeBucket() + upload_release(bucket, self.staging, self.plan, log=quiet) + (folder / "java-26.8.1.module").write_bytes(b"rebuilt") + with self.assertRaises(UploadError): + upload_release(bucket, self.staging, self.plan, log=quiet) + + def test_interrupted_upload_is_never_listed(self): + self.stage() + bucket = FakeBucket(fail_on=POM) + with self.assertRaises(RuntimeError): + upload_release(bucket, self.staging, self.plan, log=quiet) + self.assertIn(JAR, bucket.objects) + self.assertEqual(rewrite_index(bucket, "ly.count.sdk", "java", datetime.datetime(2026, 10, 27), log=quiet), []) + + def test_content_types(self): + cases = [("a.pom", "application/xml"), ("a.pom.sha1", "text/plain; charset=utf-8"), ("a.jar.asc", "application/pgp-signature"), ("a.module", "application/json"), ("a-cyclonedx.json", "application/json"), ("a.jar", "application/java-archive"), ("a.bin", "application/octet-stream")] + for name, kind in cases: + with self.subTest(name=name): + self.assertEqual(content_type(name), kind) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/tests/test_verify.py b/.github/release/tests/test_verify.py new file mode 100644 index 000000000..62aef12f8 --- /dev/null +++ b/.github/release/tests/test_verify.py @@ -0,0 +1,70 @@ +import hashlib +import subprocess +import tempfile +import unittest +from pathlib import Path + +from plan import plan_for_tag +from tests.support import FakeWeb, repository_config +from verify import verify_public, verify_signatures + +BASE = "https://maven.test/" +POM = "ly/count/sdk/java/26.8.1/java-26.8.1.pom" + + +class VerifyTest(unittest.TestCase): + def setUp(self): + self.config = repository_config() + self.plan = plan_for_tag(self.config, "26.8.1") + self.work = Path(tempfile.mkdtemp()) + self.manifest = {"tag": "26.8.1", "commit": "c" * 40, "files": [ + {"path": POM, "size": 3, "sha256": hashlib.sha256(b"pom").hexdigest()}, + {"path": POM + ".sha1", "size": 4, "sha256": hashlib.sha256(b"sha1").hexdigest()}, + ]} + self.web = FakeWeb({ + BASE + POM: b"pom", + BASE + POM + ".sha1": b"sha1", + BASE + POM + ".asc": b"signature", + BASE + "ly/count/sdk/java/maven-metadata.xml": b"26.8.1", + }) + + def test_published_release_passes_and_keeps_the_signatures(self): + self.assertEqual(verify_public(self.manifest, self.plan, BASE, "1", self.work, fetcher=self.web), []) + self.assertEqual((self.work / (POM + ".asc")).read_bytes(), b"signature") + self.assertTrue(all("?nocache=1" in url for url in self.web.requests)) + + def test_problems_are_reported(self): + self.web.pages[BASE + POM] = b"changed" + del self.web.pages[BASE + POM + ".asc"] + self.web.pages[BASE + "ly/count/sdk/java/maven-metadata.xml"] = b"26.8.0" + self.assertEqual(verify_public(self.manifest, self.plan, BASE, "1", self.work, fetcher=self.web), [ + f"changed {POM}", + f"missing {POM}.asc", + "ly.count.sdk:java index does not list 26.8.1", + ]) + + def test_a_ui_release_checks_only_the_ui_index(self): + plan = plan_for_tag(self.config, "ui-26.8.1") + web = FakeWeb({BASE + "ly/count/sdk/java-ui/maven-metadata.xml": b"26.8.1"}) + self.assertEqual(verify_public({"files": []}, plan, BASE, "1", self.work, fetcher=web), []) + self.assertEqual(web.requests, [BASE + "ly/count/sdk/java-ui/maven-metadata.xml?nocache=1"]) + + def test_candidate_must_stay_unlisted(self): + plan = plan_for_tag(self.config, "26.8.1-rc1") + web = FakeWeb({BASE + "ly/count/sdk/java/maven-metadata.xml": b"26.8.1-rc1"}) + self.assertEqual(verify_public({"files": []}, plan, BASE, "1", self.work, fetcher=web), ["ly.count.sdk:java index lists the release candidate 26.8.1-rc1"]) + + def test_bad_signatures_are_reported(self): + (self.work / "a").mkdir() + for name in ["x.pom", "x.pom.asc", "y.pom", "y.pom.asc"]: + (self.work / "a" / name).write_bytes(b"x") + + def fake_gpg(args, **kwargs): + bad = "--verify" in args and args[-1].endswith("y.pom") + return subprocess.CompletedProcess(args, 1 if bad else 0, b"", b"") + + self.assertEqual(verify_signatures(self.work, Path("key.asc"), runner=fake_gpg), ["bad signature a/y.pom.asc"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/upload.py b/.github/release/upload.py new file mode 100644 index 000000000..4bfb96824 --- /dev/null +++ b/.github/release/upload.py @@ -0,0 +1,59 @@ +"""Uploads a signed release create-only, in an order that keeps the repository consistent at every moment.""" + +import hashlib +from pathlib import Path + +IMMUTABLE = "public, max-age=31536000, immutable" +CONTENT_TYPES = ( + ((".md5", ".sha1", ".sha256", ".sha512"), "text/plain; charset=utf-8"), + ((".asc",), "application/pgp-signature"), + ((".pom", ".xml"), "application/xml"), + ((".jar",), "application/java-archive"), + ((".module", ".json"), "application/json"), +) + + +class UploadError(Exception): + """A stored object differs from the file that should be uploaded; the version number is burned.""" + + +def content_type(name): + """Content type of a repository file, chosen by its extension.""" + for suffixes, kind in CONTENT_TYPES: + if name.endswith(suffixes): + return kind + return "application/octet-stream" + + +def upload_order(names, pom_name): + """Every file except the POM family first, then the POM's checksums and signature, the POM itself last.""" + family = sorted(name for name in names if name.startswith(pom_name) and name != pom_name) + others = sorted(name for name in names if not name.startswith(pom_name)) + return others + family + ([pom_name] if pom_name in names else []) + + +def upload_folder(bucket, local_folder, remote_folder, pom_name, log=print): + """Uploads one version folder create-only. An identical stored file is skipped; a signature stored by an earlier + attempt is kept; any other difference raises UploadError.""" + names = sorted(path.name for path in Path(local_folder).iterdir() if path.is_file()) + for name in upload_order(names, pom_name): + path = Path(local_folder) / name + key = f"{remote_folder}/{name}" + if bucket.put_file(key, path, content_type(name), IMMUTABLE, create_only=True) == "created": + log(f"created {key}") + continue + stored = bucket.head(key) + if stored is not None and stored["etag"] == hashlib.md5(path.read_bytes()).hexdigest(): + log(f"identical {key}") + elif stored is not None and name.endswith(".asc"): + # Re-signing gives other bytes (a signature carries its creation time); the verify job checks the stored one. + log(f"kept the signature stored earlier {key}") + else: + raise UploadError(f"{key} already exists with different content") + + +def upload_release(bucket, staging_dir, plan, log=print): + """Uploads every artifact version folder of the plan.""" + for artifact in plan.artifacts: + folder = artifact.folder(plan.version) + upload_folder(bucket, Path(staging_dir) / folder, folder, f"{artifact.base_name(plan.version)}.pom", log) diff --git a/.github/release/verify.py b/.github/release/verify.py new file mode 100644 index 000000000..4fa860b1e --- /dev/null +++ b/.github/release/verify.py @@ -0,0 +1,65 @@ +"""Checks a release from the public address, the way a customer's build sees it.""" + +import hashlib +import subprocess +import tempfile +import urllib.error +import urllib.request +from pathlib import Path + +from layout import is_checksum + + +def fetch(url, timeout=60): + """Downloads a URL; returns None for 404 and raises for any other error.""" + request = urllib.request.Request(url, headers={"User-Agent": "countly-sdk-release"}) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + return response.read() + except urllib.error.HTTPError as error: + if error.code == 404: + return None + raise + + +def verify_public(manifest, plan, base_url, nocache, work_dir, fetcher=fetch): + """Problems found when downloading the release: missing or changed files, missing signatures, wrong index. Downloaded files and signatures are kept in work_dir.""" + problems = [] + base = base_url.rstrip("/") + "/" + for entry in manifest["files"]: + body = fetcher(f"{base}{entry['path']}?nocache={nocache}") + if body is None: + problems.append(f"missing {entry['path']}") + continue + if hashlib.sha256(body).hexdigest() != entry["sha256"]: + problems.append(f"changed {entry['path']}") + if is_checksum(entry["path"]): + continue + signature = fetcher(f"{base}{entry['path']}.asc?nocache={nocache}") + if signature is None: + problems.append(f"missing {entry['path']}.asc") + continue + target = Path(work_dir) / entry["path"] + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(body) + Path(f"{target}.asc").write_bytes(signature) + for artifact in plan.artifacts: + index = fetcher(f"{base}{artifact.group_path}/{artifact.artifact}/maven-metadata.xml?nocache={nocache}") + listed = index is not None and f"{plan.version}".encode("utf-8") in index + if plan.listed and not listed: + problems.append(f"{artifact.coordinates} index does not list {plan.version}") + if not plan.listed and listed: + problems.append(f"{artifact.coordinates} index lists the release candidate {plan.version}") + return problems + + +def verify_signatures(work_dir, public_key, runner=subprocess.run): + """Checks every signature under work_dir against the given public key only; returns problems.""" + home = tempfile.mkdtemp() + runner(["gpg", "--homedir", home, "--batch", "--import", str(public_key)], capture_output=True, check=True) + problems = [] + for signature in sorted(Path(work_dir).rglob("*.asc")): + result = runner(["gpg", "--homedir", home, "--batch", "--verify", str(signature), str(signature.with_suffix(""))], capture_output=True) + if result.returncode != 0: + problems.append(f"bad signature {signature.relative_to(work_dir).as_posix()}") + return problems diff --git a/.github/scripts/ci_report.py b/.github/scripts/ci_report.py new file mode 100644 index 000000000..2fbb31a89 --- /dev/null +++ b/.github/scripts/ci_report.py @@ -0,0 +1,187 @@ +"""Rebuilds the one CI report comment of the pull request whose head commit a finished workflow run tested.""" + +import io +import json +import os +import re +import subprocess +import sys +import zipfile +from datetime import datetime, timezone + +MARKER = "" +FRAGMENT_PREFIX = "ci-report-" +FRAGMENT_FILE = "report.md" +MAX_FRAGMENT_BYTES = 65536 +MAX_SUMMARY_CHARS = 200 +MAX_DETAILS_CHARS = 12000 +MAX_BODY_CHARS = 60000 +MAX_CELL_SUMMARIES = 3 +# a summary that reports a failure, which opens its section when the run failed +FAILING = re.compile( + r"\b([1-9][0-9]* (failed|new findings?|of [0-9]+ scenarios differ)|has a blocking vulnerability)\b") +ICONS = { + "success": "✅ passed", + "failure": "❌ failed", + "cancelled": "⚪ cancelled", + "timed_out": "⌛ timed out", + "skipped": "⏭️ skipped", + "neutral": "➖ neutral", + "action_required": "⚠️ action required", + "stale": "⚪ stale", + "startup_failure": "❌ did not start", +} +ORDER = {"failure": 0, "startup_failure": 0, "timed_out": 0, "action_required": 1, "running": 2, "cancelled": 3} + + +def gh(*args, raw=False): + """Runs gh with the given arguments and returns its output, parsed as JSON unless raw.""" + out = subprocess.run(["gh", *args], check=True, capture_output=True).stdout + return out if raw else json.loads(out or b"null") + + +def paged(path): + """Returns every page of a list endpoint, merged, for endpoints that answer with a list or with one keyed list.""" + pages = gh("api", "--paginate", "--slurp", path) + items = [] + for page in pages: + if isinstance(page, list): + items.extend(page) + else: + items.extend(next(value for value in page.values() if isinstance(value, list))) + return items + + +def pull_requests(repo, sha): + """Returns the numbers of the open pull requests whose head is the given commit.""" + return [pr["number"] for pr in paged(f"repos/{repo}/pulls?state=open&per_page=100") if pr["head"]["sha"] == sha] + + +def latest_runs(repo, sha, own_name): + """Returns the newest pull request run of each workflow for the commit, leaving out this report's own workflow.""" + runs = {} + for run in paged(f"repos/{repo}/actions/runs?head_sha={sha}&event=pull_request&per_page=100"): + if run["name"] == own_name: + continue + kept = runs.get(run["name"]) + if kept is None or (run["created_at"], run["id"]) > (kept["created_at"], kept["id"]): + runs[run["name"]] = run + return list(runs.values()) + + +def defused(text): + """Returns untrusted Markdown that cannot mention anyone, close the report's sections or fake its marker.""" + text = text.replace(MARKER, "") + text = re.sub(r"@(?=[A-Za-z0-9])", "@​", text) + # a fragment's own collapsible sections become bold headings, since they would close the report's section + text = re.sub(r"]*>\s*]*>(.*?)", r"**\1**", text, flags=re.IGNORECASE | re.DOTALL) + text = re.sub(r"", "", text, flags=re.IGNORECASE) + return re.sub(r"<(/?)(details|summary)", r"<\1\2", text, flags=re.IGNORECASE) + + +def fragments(repo, run): + """Returns the report fragments the run uploaded, each as a dict with key, title, summary and details.""" + found = [] + for artifact in paged(f"repos/{repo}/actions/runs/{run['id']}/artifacts?per_page=100"): + if not artifact["name"].startswith(FRAGMENT_PREFIX) or artifact.get("expired"): + continue + zipped = gh("api", f"repos/{repo}/actions/artifacts/{artifact['id']}/zip", raw=True) + archive = zipfile.ZipFile(io.BytesIO(zipped)) + if FRAGMENT_FILE not in archive.namelist(): + continue + key = artifact["name"][len(FRAGMENT_PREFIX):] + data = archive.read(FRAGMENT_FILE)[:MAX_FRAGMENT_BYTES].decode("utf-8", "replace") + lines = defused(data).replace("\r\n", "\n").split("\n") + title = lines[0].strip() or key + summary = (lines[1].strip() if len(lines) > 1 else "")[:MAX_SUMMARY_CHARS] + details = "\n".join(lines[2:]).strip() + if len(details) > MAX_DETAILS_CHARS: + details = details[:MAX_DETAILS_CHARS] + "\n\n…cut here; the run's job summary has the rest." + found.append({"key": key, "title": title, "summary": summary, "details": details}) + return sorted(found, key=lambda fragment: fragment["key"]) + + +def failing_jobs(repo, run): + """Returns the names of the run's jobs that did not succeed or get skipped.""" + jobs = paged(f"repos/{repo}/actions/runs/{run['id']}/jobs?per_page=100") + return [job["name"] for job in jobs if job.get("conclusion") not in (None, "success", "skipped", "neutral")] + + +def state(run): + """Returns the run's conclusion, or "running" while it has none.""" + return run["conclusion"] if run["status"] == "completed" and run["conclusion"] else "running" + + +def label(run, fragment): + """Returns the fragment's title, or nothing when the title only repeats its workflow's name.""" + return "" if fragment["title"].casefold() == run["name"].casefold() else fragment["title"] + + +def joined(*parts): + """Returns the non-empty parts joined by a colon.""" + return ": ".join(part for part in parts if part) + + +def body(repo, sha, runs): + """Returns the comment: a table with one row per workflow, then a collapsible section per fragment.""" + rows, sections = [], [] + for run in sorted(runs, key=lambda run: (ORDER.get(state(run), 4), run["name"].lower())): + result = state(run) + found = fragments(repo, run) if result != "running" else [] + parts = [joined(label(run, fragment), fragment["summary"]) for fragment in found if fragment["summary"]] + if len(parts) > MAX_CELL_SUMMARIES: + parts = parts[:MAX_CELL_SUMMARIES] + [f"{len(parts) - MAX_CELL_SUMMARIES} more below"] + failed = failing_jobs(repo, run) if result in ("failure", "timed_out") else [] + if failed: + parts.insert(0, "Failed: " + ", ".join(failed)) + summary = "; ".join(parts) + icon = "⏳ running" if result == "running" else ICONS.get(result, result) + cell = summary.replace("|", "\\|") + rows.append(f"| [{run['name']}]({run['html_url']}) | {icon} | {cell} |") + for fragment in found: + opened = " open" if result in ("failure", "timed_out") and FAILING.search(fragment["summary"]) else "" + heading = joined(run["name"], label(run, fragment)) + if fragment["summary"]: + heading += f", {fragment['summary']}" + details = fragment["details"] or "No details." + sections.append(f"\n{heading}\n\n{details}\n\n\n") + when = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") + head = [MARKER, "### CI report", "", "| Check | Result | Summary |", "| --- | --- | --- |", *rows, ""] + tail = [f"For {sha[:7]}, updated {when}. Each check's run page has its full log."] + text = "\n".join(head + sections + tail) + while len(text) > MAX_BODY_CHARS and sections: + sections.pop() + text = "\n".join(head + sections + ["…more sections did not fit in one comment.", ""] + tail) + return text + + +def publish(repo, number, text): + """Updates the pull request's report comment, or posts it when there is none yet.""" + comments = paged(f"repos/{repo}/issues/{number}/comments?per_page=100") + mine = [comment for comment in comments + if comment["user"]["login"] == "github-actions[bot]" and comment["body"].startswith(MARKER)] + if mine: + gh("api", "--method", "PATCH", f"repos/{repo}/issues/comments/{mine[-1]['id']}", "-f", f"body={text}") + else: + gh("api", "--method", "POST", f"repos/{repo}/issues/{number}/comments", "-f", f"body={text}") + + +def main(): + """Rebuilds the report for the commit in HEAD_SHA, or prints it when DRY_RUN is set.""" + repo, sha = os.environ["REPO"], os.environ["HEAD_SHA"] + numbers = [int(os.environ["PR"])] if os.environ.get("PR") else pull_requests(repo, sha) + if not numbers: + print(f"No open pull request has {sha} as its head, so there is nothing to report on.") + return 0 + text = body(repo, sha, latest_runs(repo, sha, os.environ.get("OWN_WORKFLOW", "CI report"))) + if os.environ.get("DRY_RUN"): + print(text) + return 0 + for number in numbers: + publish(repo, number, text) + print(f"Updated the CI report of #{number}.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/public-api.init.gradle b/.github/scripts/public-api.init.gradle new file mode 100644 index 000000000..203377c44 --- /dev/null +++ b/.github/scripts/public-api.init.gradle @@ -0,0 +1,42 @@ +// Applies metalava to the modules listed in -DapiModules (for example :sdk,:sdk-native) and points each module's +// signature file at <-DapiDir>/.txt: `metalavaGenerateSignature` writes the module's public API +// there, and `metalavaCheckCompatibility` checks the module's code against the signature found there. +// Only .github/workflows/public_api.yml applies it, through --init-script, so no build file changes. +def apiModules = (System.getProperty('apiModules') ?: '').tokenize(',') as Set +def apiDir = System.getProperty('apiDir') + +rootProject { + // On the root build script classpath the plugin shares a class loader with the Android Gradle Plugin it calls. + buildscript { + repositories { + gradlePluginPortal { + content { + includeGroup 'me.tylerbwong.gradle.metalava' + } + } + } + dependencies { + classpath 'me.tylerbwong.gradle.metalava:plugin:0.5.1' + } + } +} + +allprojects { project -> + if (!apiModules.contains(project.path)) { + return + } + if (!apiDir) { + throw new org.gradle.api.GradleException('Pass -DapiDir= to choose where the API signatures live.') + } + ['java-library', 'com.android.library'].each { pluginId -> + project.pluginManager.withPlugin(pluginId) { + project.pluginManager.apply('me.tylerbwong.gradle.metalava') + project.metalava { + filename.set(new File(apiDir, "${project.name}.txt").absolutePath) + enforceCheck.set(false) + // Public methods that return package-private types are lint findings, not compatibility breaks. + arguments.addAll('--hide', 'ReferencesHidden,HiddenTypeParameter') + } + } + } +} diff --git a/.github/scripts/public_api.py b/.github/scripts/public_api.py new file mode 100644 index 000000000..3019d5d73 --- /dev/null +++ b/.github/scripts/public_api.py @@ -0,0 +1,142 @@ +"""Keeps the metalava compatibility errors that touch the public API integrators can reach.""" +import argparse +import glob +import os +import re +import sys + +ERROR = re.compile(r"^(?P\S+?\.txt):(?P\d+): error: (?P.*)$") +PACKAGE = re.compile(r"^package (?P[\w.]+) \{$") +CLASS = re.compile(r"^ (?:@\S+\s+)*(?:(?:public|protected|static|final|abstract|sealed)\s+)*" + r"(?:class|interface|enum|@interface)\s+(?P[\w.$]+)") +REFERENCE = re.compile(r"\bly\.count(?:\.[A-Za-z_$][\w$]*)+") +ANSI = re.compile(r"\x1b\[[0-9;]*m") + + +def _in_package(name, package): + """Returns whether the class name, nested or not, is declared directly in package and not in a subpackage.""" + return name.startswith(f"{package}.") and name[len(package) + 1:][:1].isupper() + + +class Signature: + """One metalava signature file: its class blocks and the classes each class's signature names.""" + + def __init__(self, path): + """Parses the signature file at path.""" + self.blocks = [] + self.references = {} + self.headers = {} + self.members = {} + package, current, start = None, None, 0 + with open(path, encoding="utf-8") as handle: + lines = handle.read().splitlines() + for number, text in enumerate(lines, start=1): + package_match, class_match = PACKAGE.match(text), CLASS.match(text) + if package_match: + package = package_match.group("name") + elif class_match and package: + current, start = f"{package}.{class_match.group('name')}", number + self.references[current] = set(REFERENCE.findall(text)) + self.headers[current] = text.strip() + self.members[current] = [] + elif current and text == " }": + self.blocks.append((start, number, current)) + current = None + elif current: + self.references[current].update(REFERENCE.findall(text)) + if text.strip(): + self.members[current].append(text.strip()) + + def class_at(self, line): + """Returns the class whose block contains line, or None for a line outside every class.""" + for start, end, name in self.blocks: + if start <= line <= end: + return name + return None + + +def reachable(signatures, root_packages): + """Returns the root package classes, the classes their signatures name, transitively, and nested classes.""" + references = {} + for signature in signatures: + for name, named in signature.references.items(): + references.setdefault(name, set()).update(named) + classes = set(references) + pending = [name for name in classes if any(_in_package(name, root) for root in root_packages)] + found = set() + while pending: + name = pending.pop() + if name in found: + continue + found.add(name) + pending.extend(other for other in classes if other.startswith(f"{name}.")) + pending.extend(reference for reference in references.get(name, ()) if reference in classes) + return found + + +def added(base_dir, head_dir, root_packages): + """Returns "class: declaration" lines for the public API the head signatures add to the base ones.""" + heads = {os.path.basename(path): Signature(path) for path in sorted(glob.glob(os.path.join(head_dir, "*.txt")))} + public = reachable(heads.values(), root_packages) + lines = [] + for name, head in heads.items(): + base_path = os.path.join(base_dir, name) + if not os.path.exists(base_path): + lines.append(f"{name[:-len('.txt')]}: a new module, all of its public API is new") + continue + base = Signature(base_path) + for owner in sorted(cls for cls in head.members if cls in public): + known = set(base.members.get(owner, ())) + if owner not in base.members: + lines.append(f"{owner}: {head.headers[owner]}") + lines.extend(f"{owner}: {member}" for member in head.members[owner] if member not in known) + return lines + + +def main(): + """Reads a metalava check log and prints the compatibility errors that touch reachable public API.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root-package", action="append", required=True, + help="a package whose classes are public API; repeat it for each root package") + parser.add_argument("--signatures", required=True, + help="every module's base signatures: one module's public API can name another's classes") + parser.add_argument("--module-dir", + help="the module's directory: metalava names this pull request's signature relative to it") + parser.add_argument("--added", metavar="HEAD_DIR", + help="print what the head signatures in this directory add to --signatures") + parser.add_argument("log", nargs="?", help="the metalava compatibility check log") + arguments = parser.parse_args() + if arguments.added: + for line in added(arguments.signatures, arguments.added, set(arguments.root_package)): + print(line) + return + if not arguments.module_dir or not arguments.log: + parser.error("--module-dir and the log are needed unless --added is given") + base = [Signature(path) for path in sorted(glob.glob(os.path.join(arguments.signatures, "*.txt")))] + if not base: + sys.exit(f"No base signatures in {arguments.signatures}.") + public = reachable(base, set(arguments.root_package)) + signatures = {} + found = 0 + with open(arguments.log, encoding="utf-8", errors="replace") as handle: + for raw in handle: + match = ERROR.match(ANSI.sub("", raw.strip())) + if not match: + continue + found += 1 + path = os.path.join(arguments.module_dir, match.group("path")) + message = match.group("message") + if path not in signatures: + signatures[path] = Signature(path) + owner = signatures[path].class_at(int(match.group("line"))) + if owner is None or owner in public: + print(message) + else: + # A class that is public only so other SDK packages can call it is not integrator API. + print(f"Ignored, {owner} is not reachable from the public API: {message}", file=sys.stderr) + if found == 0: + sys.exit("No metalava error lines found in the log.") + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/public_api_record.sh b/.github/scripts/public_api_record.sh new file mode 100644 index 000000000..88f5c9508 --- /dev/null +++ b/.github/scripts/public_api_record.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# Compares the public API this run extracted with the record committed in the repository. On a difference it lists the +# changed lines in the job summary, copies the extracted API to $RUNNER_TEMP/public-api-record/ under the record's path, +# for the workflow to upload, and fails: a deliberate change is committed together with a changelog line. +# $@ pairs "=" +set -euo pipefail +out="$RUNNER_TEMP/public-api-record" +status=0 +current="$RUNNER_TEMP/public-api-current.txt" +recorded="$RUNNER_TEMP/public-api-recorded.txt" +for pair in "$@"; do + extracted=${pair%%=*} + record=${pair#*=} + # Line endings do not count: .NET writes CRLF on Windows, and a Windows checkout can give the record CRLF too. + tr -d '\r' < "$extracted" > "$current" + if [ -f "$record" ] && tr -d '\r' < "$record" | cmp -s - "$current"; then + echo "The public API is the one $record records." + continue + fi + status=1 + mkdir -p "$out/$(dirname "$record")" + cp "$current" "$out/$record" + { + printf '### The public API differs from %s\n\n' "$record" + printf "Commit \`%s\` from the \`public-api-record\` artifact of this run, with a changelog line for the change.\n\n" "$record" + if [ -f "$record" ]; then + printf '```diff\n' + tr -d '\r' < "$record" > "$recorded" + diff -u "$recorded" "$current" | tail -n +3 | head -n 300 || true + printf '```\n\n' + else + printf 'There is no record yet.\n\n' + fi + } >> "$GITHUB_STEP_SUMMARY" + echo "::error title=Public API record::The public API differs from $record. Commit the file from this run's public-api-record artifact and add a changelog line." +done +exit "$status" diff --git a/.github/scripts/public_api_report.sh b/.github/scripts/public_api_report.sh new file mode 100644 index 000000000..6c32e49ad --- /dev/null +++ b/.github/scripts/public_api_report.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Writes the report of a pull request's public API changes to the job summary, to the step output "report", which +# the workflow's comment job posts on the pull request, and to $RUNNER_TEMP/ci-report-public-api/report.md, the +# fragment the CI report comment shows. The comment and the fragment list at most 200 lines per section. +# $1 a file with one removed or changed declaration per line +# $2 a file with one declaration per line that the pull request adds to the public API +set -euo pipefail +breaking=$1 +added=$2 +marker='' + +# Prints a section titled $1 and explained by $2 with the lines of file $3, at most $4 of them when $4 is not 0. +section() { + local count + count=$(grep -c . "$3" || true) + [ "$count" -gt 0 ] || return 0 + printf '**%s: %s.** %s\n\n```\n' "$1" "$count" "$2" + if [ "$4" -gt 0 ]; then + head -n "$4" "$3" + else + cat "$3" + fi + printf '```\n' + if [ "$4" -gt 0 ] && [ "$count" -gt "$4" ]; then + printf '\n%s more in the job summary.\n' "$((count - $4))" + fi + printf '\n' +} + +# Prints the whole report, with at most $1 lines per section when $1 is not 0. +report() { + printf '%s\n### Public API changes\n\n' "$marker" + if ! grep -q . "$breaking" && ! grep -q . "$added"; then + printf 'No public API change.\n' + return + fi + section 'Removed or changed' 'Each needs a CHANGELOG entry that marks it as a breaking change.' "$breaking" "$1" + section 'Added' 'Check that each one is meant to be public.' "$added" "$1" +} + +report 0 >> "$GITHUB_STEP_SUMMARY" +delimiter="EOF_$(od -An -N8 -tx1 /dev/urandom | tr -d ' \n')" +{ + echo "report<<$delimiter" + report 200 + echo "$delimiter" +} >> "$GITHUB_OUTPUT" + +removed=$(grep -c . "$breaking" || true) +new=$(grep -c . "$added" || true) +summary='No public API change' +if [ "$removed" -gt 0 ] || [ "$new" -gt 0 ]; then + summary="$removed removed or changed, $new added" +fi +mkdir -p "$RUNNER_TEMP/ci-report-public-api" +{ + printf 'Public API\n%s\n' "$summary" + report 200 | tail -n +3 +} > "$RUNNER_TEMP/ci-report-public-api/report.md" diff --git a/.github/scripts/sarif_summary.py b/.github/scripts/sarif_summary.py new file mode 100644 index 000000000..a741a429b --- /dev/null +++ b/.github/scripts/sarif_summary.py @@ -0,0 +1,150 @@ +"""Summarizes SARIF static analysis results as Markdown and, given the base's results, fails on new findings.""" +import argparse +import collections +import json +import pathlib +import re +import sys +import urllib.parse +import urllib.request + +MAX_LISTED = 50 +GATED_LEVELS = ("error", "warning") +Finding = collections.namedtuple("Finding", "rule level description path line column message") + + +def sarif_files(arguments): + """Returns the SARIF files named by the arguments, expanding directories.""" + files = [] + for argument in arguments: + path = pathlib.Path(argument) + files.extend(sorted(path.rglob("*.sarif")) if path.is_dir() else [path] if path.is_file() else []) + return files + + +def relative_path(uri, root): + """Returns the path of a SARIF artifact URI, relative to root when it lies inside it.""" + parsed = urllib.parse.urlparse(uri) + path = urllib.request.url2pathname(parsed.path) if parsed.scheme == "file" else urllib.parse.unquote(uri) + try: + return (root / path).resolve().relative_to(root.resolve()).as_posix() + except (ValueError, OSError): + return pathlib.PurePath(path).as_posix() + + +def artifact_uri(location, base_ids): + """Returns the artifact URI of a SARIF location, resolved against its uriBaseId when the run defines it.""" + uri = location.get("uri", "") + base = base_ids.get(location.get("uriBaseId"), {}).get("uri") + return urllib.parse.urljoin(base, uri) if base else uri + + +def findings(files, root): + """Yields every distinct finding in the SARIF files, with paths relative to root.""" + seen = set() + for file in files: + for run in json.loads(file.read_text(encoding="utf-8-sig")).get("runs", []): + rules = {rule.get("id"): rule for rule in run.get("tool", {}).get("driver", {}).get("rules", [])} + base_ids = run.get("originalUriBaseIds", {}) + for result in run.get("results", []): + rule_id = result.get("ruleId") or result.get("rule", {}).get("id", "unknown") + rule = rules.get(rule_id, {}) + physical = (result.get("locations") or [{}])[0].get("physicalLocation", {}) + finding = Finding( + rule_id, + result.get("level") or rule.get("defaultConfiguration", {}).get("level", "warning"), + rule.get("shortDescription", {}).get("text") + or rule.get("fullDescription", {}).get("text") or rule.get("helpUri", ""), + relative_path(artifact_uri(physical.get("artifactLocation", {}), base_ids), root), + physical.get("region", {}).get("startLine"), + physical.get("region", {}).get("startColumn"), + (result.get("message", {}).get("text") or "").split("\n")[0], + ) + # The same finding in a shared header is reported once per source file that includes it. + if finding not in seen: + seen.add(finding) + yield finding + + +def fingerprint(finding): + """Returns what identifies a finding across commits: rule, file and message, with numbers masked.""" + return finding.rule, finding.path, re.sub(r"\d+", "#", finding.message) + + +def cell(text): + """Escapes text for a Markdown table cell.""" + return str(text).replace("|", "\\|").replace("\n", " ")[:160] + + +def where(finding): + """Returns 'path:line', or the path alone when the finding has no line.""" + return f"{finding.path}:{finding.line}" if finding.line else finding.path + + +def print_summary(title, rows): + """Prints the findings per rule and level, then the first findings with their location.""" + print(f"### {title}: {len(rows)} finding{'s' if len(rows) != 1 else ''}\n") + if not rows: + return + counts = collections.Counter((row.rule, row.level, row.description) for row in rows) + print("| Rule | Level | Count | Description |\n|---|---|---|---|") + for (rule, level, description), count in sorted(counts.items(), key=lambda item: (-item[1], item[0])): + print(f"| {cell(rule)} | {level} | {count} | {cell(description)} |") + print(f"\n
First {min(MAX_LISTED, len(rows))} findings\n") + print("| Location | Rule | Message |\n|---|---|---|") + for row in sorted(rows, key=lambda row: (row.path, row.line or 0))[:MAX_LISTED]: + print(f"| {cell(where(row))} | {cell(row.rule)} | {cell(row.message)} |") + print("\n
\n") + + +def print_new(title, rows, base_rows): + """Prints the findings that outnumber the base's findings with the same fingerprint; returns the gated count.""" + base_counts = collections.Counter(fingerprint(row) for row in base_rows) + groups = collections.defaultdict(list) + for row in rows: + groups[fingerprint(row)].append(row) + new = {key: group for key, group in groups.items() if len(group) > base_counts[key]} + added = sum(len(group) - base_counts[key] for key, group in new.items()) + gated = sum(len(group) - base_counts[key] for key, group in new.items() if group[0].level in GATED_LEVELS) + print(f"### New compared with the base branch: {added}\n") + if not new: + print("No finding that the base branch does not have.\n") + return 0 + print("| Location | Rule | Level | Message | Base | Head |\n|---|---|---|---|---|---|") + for key, group in sorted(new.items()): + locations = ", ".join(where(row) for row in group[:5]) + (", ..." if len(group) > 5 else "") + print(f"| {cell(locations)} | {cell(key[0])} | {group[0].level} | {cell(group[0].message)} " + f"| {base_counts[key]} | {len(group)} |") + print() + if gated: + print(f"::error title={title}::{gated} new finding{'s' if gated != 1 else ''} at " + f"{' or '.join(GATED_LEVELS)} level: fix or suppress them, the job summary lists them.", file=sys.stderr) + return gated + + +def load(title, paths, root): + """Returns the findings of the SARIF files under paths, failing when there is no SARIF at all.""" + files = sarif_files(paths) + if not files: + # An analyzer that silently wrote nothing must not read as a clean result. + sys.exit(f"::error title={title}::No SARIF file found in {' '.join(paths)}") + return list(findings(files, root)) + + +def main(): + """Prints the summary; with --base, also the new findings, and exits with 1 when any is gated.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("title", help="the analyzer's name, used as the heading") + parser.add_argument("sarif", nargs="+", help="SARIF files or directories of the working directory's analysis") + parser.add_argument("--base", nargs="+", help="SARIF files or directories of the pull request base's analysis") + parser.add_argument("--base-root", default=".", help="the base checkout, which the base's paths are relative to") + arguments = parser.parse_args() + rows = load(arguments.title, arguments.sarif, pathlib.Path.cwd()) + print_summary(arguments.title, rows) + if arguments.base and print_new(arguments.title, rows, + load(arguments.title, arguments.base, pathlib.Path(arguments.base_root))): + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/spotbugs.init.gradle b/.github/scripts/spotbugs.init.gradle new file mode 100644 index 000000000..1b6532233 --- /dev/null +++ b/.github/scripts/spotbugs.init.gradle @@ -0,0 +1,43 @@ +// Applies SpotBugs to the modules listed in -DspotbugsModules (for example :sdk-java,:sdk-java-ui) and writes each +// analysis as SARIF to <-DspotbugsDir>/-.sarif. Findings never fail the build. +// Only .github/workflows/static_analysis.yml applies it, through --init-script, so no build file changes. +def spotbugsModules = (System.getProperty('spotbugsModules') ?: '').tokenize(',') as Set +def spotbugsDir = System.getProperty('spotbugsDir') + +rootProject { + buildscript { + repositories { + gradlePluginPortal { + content { + includeGroup 'com.github.spotbugs.snom' + } + } + } + dependencies { + classpath 'com.github.spotbugs.snom:spotbugs-gradle-plugin:6.5.13' + } + } +} + +allprojects { project -> + if (!spotbugsModules.contains(project.path)) { + return + } + if (!spotbugsDir) { + throw new org.gradle.api.GradleException('Pass -DspotbugsDir= to choose where the reports go.') + } + project.pluginManager.withPlugin('java') { + project.pluginManager.apply('com.github.spotbugs') + project.spotbugs { + ignoreFailures.set(true) + } + project.tasks.matching { it.name.startsWith('spotbugs') }.configureEach { task -> + task.reports { + create('sarif') { + required.set(true) + outputLocation.set(new File(spotbugsDir, "${project.name}-${task.name}.sarif")) + } + } + } + } +} diff --git a/.github/workflows/api-changelog.yml b/.github/workflows/api-changelog.yml new file mode 100644 index 000000000..c827151aa --- /dev/null +++ b/.github/workflows/api-changelog.yml @@ -0,0 +1,53 @@ +name: Public API changelog + +# A pull request that changes or removes a record of the public API, or of the requests the SDK sends, must also change +# the CHANGELOG.md that API_FILES pairs it with, so that the release notes tell integrators about every such change. A +# record the pull request adds needs no line. A path ending in "/" stands for every file under it. The API and request +# checks keep each record in step with the SDK. +on: + pull_request: + branches: [master, staging] + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + pull-requests: read # to list the files the pull request changes + +jobs: + changelog: + name: A public API or request change comes with a CHANGELOG line + runs-on: ubuntu-24.04 + steps: + - name: Check the files the pull request changes + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + PR: ${{ github.event.pull_request.number }} + API_FILES: sdk-java/api/sdk-java.txt=CHANGELOG.md sdk-java-ui/api/sdk-java-ui.txt=sdk-java-ui/CHANGELOG.md sdk-java/api/requests/=CHANGELOG.md + run: | + changed=$(gh api "repos/$REPO/pulls/$PR/files" --paginate --jq '.[] | select(.status != "added") | .filename') + changes() { + case "$1" in + */) printf '%s\n' "$changed" | awk -v prefix="$1" 'index($0, prefix) == 1 { found = 1 } END { exit !found }' ;; + *) printf '%s\n' "$changed" | grep -qxF "$1" ;; + esac + } + recorded_changed=no + for pair in $API_FILES; do + record=${pair%%=*} + changelog=${pair#*=} + if changes "$record"; then + recorded_changed=yes + if ! changes "$changelog"; then + echo "::error::This pull request changes $record, which records the public API or the requests the SDK sends, but not $changelog. Add a line that tells integrators what changed." + exit 1 + fi + fi + done + if [ "$recorded_changed" = yes ]; then + echo "The recorded public API or requests change, and the CHANGELOG changes with them." + else + echo "This pull request changes neither the recorded public API nor the recorded requests." + fi diff --git a/.github/workflows/ci-report.yml b/.github/workflows/ci-report.yml new file mode 100644 index 000000000..04a25f9dd --- /dev/null +++ b/.github/workflows/ci-report.yml @@ -0,0 +1,52 @@ +name: CI report + +# Keeps one comment on each pull request with the result of every workflow that ran for its head commit, a table +# first, then one collapsible section per report fragment (an artifact named ci-report- holding report.md: a +# title line, a summary line, then the details). It runs from the default branch after each listed workflow, so a +# fork's pull request gets its report too: nothing from the pull request is checked out or run, and the fragments +# are read as untrusted text. +on: # zizmor: ignore[dangerous-triggers] the job reads the pull request's artifacts as text and never runs its code + workflow_run: + workflows: + - "Code Coverage" + - "CodeQL" + - "Cross Platform Tests" + - "Dependency Security Scan" + - "Java Gradle Build and Test" + - "Public API changelog" + - "Public API changes" + - "Release on merge" + - "Release tools" + - "Static analysis" + - "Validate Gradle Wrapper Checksum" + types: [completed] + +permissions: {} + +concurrency: + group: ci-report-${{ github.event.workflow_run.head_sha }} + cancel-in-progress: false + +jobs: + report: + name: Update the CI report + if: github.event.workflow_run.event == 'pull_request' + runs-on: ubuntu-24.04 + permissions: + actions: read + contents: read + pull-requests: write + steps: + - name: Check out the report script + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + sparse-checkout: .github/scripts/ci_report.py + sparse-checkout-cone-mode: false + + - name: Rebuild the report comment + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + run: python3 .github/scripts/ci_report.py diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 000000000..6048d6314 --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,55 @@ +name: "CodeQL" + +on: + push: + branches: [master, staging] + pull_request: + branches: [master, staging] + schedule: + - cron: '18 18 * * 1' + +permissions: {} + +jobs: + analyze: + name: Analyze (java) + runs-on: ubuntu-24.04 + permissions: + actions: read + contents: read + security-events: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Initialize CodeQL + uses: github/codeql-action/init@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0 + with: + languages: java + # Without a build the scan needs no JDK or display, so the check a release requires cannot fail for build reasons. + build-mode: none + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0 + with: + category: "/language:java" + + actions: + name: Analyze (actions) + runs-on: ubuntu-24.04 + permissions: + actions: read + contents: read + security-events: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Initialize CodeQL + uses: github/codeql-action/init@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0 + with: + languages: actions + build-mode: none + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0 + with: + category: "/language:actions" diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 56b735667..96569c1f1 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -37,20 +37,20 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: # The changed-file list is computed by diffing against the base branch, which needs # more than the default single commit. fetch-depth: 0 - name: Set up JDK 17 - uses: actions/setup-java@v6 + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 with: java-version: '17' distribution: 'corretto' - name: Set up Gradle - uses: gradle/actions/setup-gradle@v6 + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 # The task deliberately lets tests fail so a flake cannot block the report. The report # itself carries the failure count, and gradle.yml is what actually gates on tests. @@ -104,7 +104,7 @@ jobs: # pull-requests: write. - name: Comment the report on the pull request if: always() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository - uses: actions/github-script@v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: script: | const fs = require('fs'); @@ -144,9 +144,46 @@ jobs: }); } + - name: Write the CI report fragment + if: ${{ !cancelled() }} + env: + OUTCOME: ${{ steps.report.outcome }} + run: | + dir="$RUNNER_TEMP/ci-report-coverage" + mkdir -p "$dir" + if [ ! -f coverage-report.md ]; then + printf 'Coverage\nSee details\nThe coverage step did not produce a report (outcome: %s). See the workflow logs.\n' "$OUTCOME" > "$dir/report.md" + exit 0 + fi + # The report has no overall figure, only one per module in its first table. + modules=$(awk -F'|' ' + /^[|]---/ { table = 1; next } + table && !/^[|]/ { exit } + table { + module = $2; gsub(/[^A-Za-z0-9._-]/, "", module) + cell = $3; sub(/^ +/, "", cell); sub(/ *[(].*$/, "", cell); sub(/ +$/, "", cell) + if (cell !~ /^([0-9.]+%|n\/a|no report)$/) { out = ""; exit } + out = out (out == "" ? "" : ", ") cell " (" module ")" + } + END { print out }' coverage-report.md) + summary='See details' + if [ -n "$modules" ]; then + summary="Line coverage $modules" + fi + # The CI report section has its own title, so the report's heading is dropped. + { printf 'Coverage\n%s\n' "$summary"; awk 'NR > 1 || !/^#/' coverage-report.md; } > "$dir/report.md" + + - name: Upload the CI report fragment + if: ${{ !cancelled() }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ci-report-coverage + path: ${{ runner.temp }}/ci-report-coverage + if-no-files-found: ignore + - name: Upload the coverage reports if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: coverage-reports path: | diff --git a/.github/workflows/cross-platform-tests.yml b/.github/workflows/cross-platform-tests.yml index 034b03b9d..71c6dbb48 100644 --- a/.github/workflows/cross-platform-tests.yml +++ b/.github/workflows/cross-platform-tests.yml @@ -34,16 +34,16 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Set up JDK 17 - uses: actions/setup-java@v6 + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 with: java-version: '17' distribution: 'corretto' - name: Set up Gradle - uses: gradle/actions/setup-gradle@v6 + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 # bash on both platforms so one command works everywhere; Git Bash ships on the Windows runner. - name: Run the core SDK tests @@ -56,9 +56,14 @@ jobs: # # Deliberately without -Dcountly.ui.pageLoadTests: that enables the one class showing a # transparent stage, which segfaults the JVM everywhere it has been tried. + # + # testUiWithLocalCore (see sdk-java-ui/build.gradle) runs the UI on this checkout's core. The + # release of a ui- tag still tests it against the released core it names. - name: Run the JavaFX UI tests if: always() shell: bash + env: + ORG_GRADLE_PROJECT_testUiWithLocalCore: 'true' run: | if [ "$RUNNER_OS" = "Linux" ]; then sudo apt-get update -qq && sudo apt-get install -y -qq xvfb @@ -69,7 +74,7 @@ jobs: - name: Upload test results if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: test-results-${{ matrix.os }} path: | diff --git a/.github/workflows/dependency-security.yml b/.github/workflows/dependency-security.yml index e171c855b..70a3f8d17 100644 --- a/.github/workflows/dependency-security.yml +++ b/.github/workflows/dependency-security.yml @@ -36,20 +36,20 @@ jobs: pull-requests: write steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 # NOTE: JDK 17, not the JDK 8 used by gradle.yml. settings.gradle only includes # :app-javafx on Java 11+, so a JDK 8 run would silently skip that module's # dependencies -- exactly the blind spot that let a known org.json CVE sit in the demo # modules after sdk-java had been fixed. - name: Set up JDK 17 - uses: actions/setup-java@v6 + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 with: java-version: '17' distribution: 'corretto' - name: Set up Gradle - uses: gradle/actions/setup-gradle@v6 + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 - name: Resolve dependencies for every module run: | @@ -79,7 +79,7 @@ jobs: # instead of adding a new one on every push. - name: Comment scan result on the pull request if: always() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository - uses: actions/github-script@v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: script: | const fs = require('fs'); @@ -126,9 +126,35 @@ jobs: }); } + - name: Write the CI report fragment + if: ${{ !cancelled() }} + env: + OUTCOME: ${{ steps.osv.outcome }} + run: | + dir="$RUNNER_TEMP/ci-report-dependency-scan" + mkdir -p "$dir" + if [ ! -f osv-report.md ]; then + printf 'Dependency scan\nNo report\nThe scan step did not produce a report (outcome: %s). See the workflow logs.\n' "$OUTCOME" > "$dir/report.md" + exit 0 + fi + summary='No blocking vulnerability' + if [ "$OUTCOME" != success ]; then + summary='A dependency has a blocking vulnerability' + fi + # The CI report section has its own title, so the report's heading is dropped. + { printf 'Dependency scan\n%s\n' "$summary"; awk 'NR > 1 || !/^#/' osv-report.md; } > "$dir/report.md" + + - name: Upload the CI report fragment + if: ${{ !cancelled() }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ci-report-dependency-scan + path: ${{ runner.temp }}/ci-report-dependency-scan + if-no-files-found: ignore + - name: Upload dependency list if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: resolved-dependencies path: | @@ -149,13 +175,13 @@ jobs: permissions: contents: write steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v6 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 with: java-version: '17' distribution: 'corretto' - name: Submit resolved dependency graph to GitHub - uses: gradle/actions/dependency-submission@v6 + uses: gradle/actions/dependency-submission@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 dependency-review: name: Review dependency changes @@ -173,9 +199,9 @@ jobs: contents: read pull-requests: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Fail the PR on newly introduced vulnerable dependencies - uses: actions/dependency-review-action@v5 + uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0 with: fail-on-severity: low comment-summary-in-pr: on-failure diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index 0b34e5646..3452137a2 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -21,19 +21,24 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Set up JDK 8 - uses: actions/setup-java@v6 + # Gradle 9 runs only on Java 17+, so 17 is listed last and becomes JAVA_HOME. The SDK's + # tests still run on Java 8, its floor, through the toolchain sdk-java/build.gradle selects. + - name: Set up JDK 8 and 17 + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 with: - java-version: '8' + java-version: | + 8 + 17 distribution: 'corretto' - name: Build and Test with Gradle - run: ./gradlew build + run: ./gradlew build -PtestJavaVersion=8 -Porg.gradle.java.installations.fromEnv=JAVA_HOME_8_X64 - name: Publish Test Results - uses: EnricoMi/publish-unit-test-result-action@v2 + id: test-results + uses: EnricoMi/publish-unit-test-result-action@da5b7be67623cd59bbbd1a0ce4f022050a55605f # v2.26.0 if: always() with: check_name: "Unit Test Results :rocket:" @@ -41,3 +46,23 @@ jobs: files: | sdk-java/build/test-results/**/*.xml + - name: Write the CI report fragment + if: ${{ !cancelled() && steps.test-results.outputs.json != '' }} + env: + TEST_RESULTS: ${{ steps.test-results.outputs.json }} + run: | + dir="$RUNNER_TEMP/ci-report-unit-tests" + mkdir -p "$dir" + jq -r '"Unit tests", + "\(.stats.tests_succ) passed, \(.stats.tests_fail + .stats.tests_error) failed, \(.stats.tests_skip) skipped", + if .check_url then "The [check run](\(.check_url)) lists every test and each failure." else empty end' \ + <<< "$TEST_RESULTS" > "$dir/report.md" + + - name: Upload the CI report fragment + if: ${{ !cancelled() }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ci-report-unit-tests + path: ${{ runner.temp }}/ci-report-unit-tests + if-no-files-found: ignore + diff --git a/.github/workflows/public_api.yml b/.github/workflows/public_api.yml new file mode 100644 index 000000000..ec1e9635b --- /dev/null +++ b/.github/workflows/public_api.yml @@ -0,0 +1,160 @@ +name: Public API changes + +on: + pull_request: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + api: + name: Breaking changes + outputs: + report: ${{ steps.report.outputs.report }} + runs-on: ubuntu-24.04 + env: + # Each module is paired with the changelog that records its breaking changes. + API_MODULES: ":sdk-java=CHANGELOG.md,:sdk-java-ui=sdk-java-ui/CHANGELOG.md" + steps: + - name: Checkout SDK code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 2 + persist-credentials: false + + - name: Set up Java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: corretto + java-version: 17 + + # The first parent of the pull request's merge commit is the base branch it merges into. + # A module the base branch does not have yet has no API to break, so it is left out. + - name: Write the public API of the base branch + run: | + git worktree add "$RUNNER_TEMP/base" HEAD^1 + cd "$RUNNER_TEMP/base" + IFS=, read -ra entries <<< "$API_MODULES" + modules=() + for entry in "${entries[@]}"; do + module="${entry%%=*}" + if [ -d "${module#:}" ]; then + modules+=("$module") + fi + done + ./gradlew --init-script "$GITHUB_WORKSPACE/.github/scripts/public-api.init.gradle" \ + -DapiModules="$(IFS=,; echo "${modules[*]}")" -DapiDir="$RUNNER_TEMP/api" \ + "${modules[@]/%/:metalavaGenerateSignature}" + + - name: Compare the public API with the base branch + id: compare + run: | + : > "$RUNNER_TEMP/breaking.txt" + : > "$RUNNER_TEMP/changelogs.txt" + IFS=, read -ra entries <<< "$API_MODULES" + for entry in "${entries[@]}"; do + module="${entry%%=*}" + if [ ! -f "$RUNNER_TEMP/api/${module#:}.txt" ]; then + continue + fi + if ./gradlew --init-script .github/scripts/public-api.init.gradle \ + -DapiModules="$module" -DapiDir="$RUNNER_TEMP/api" \ + "$module:metalavaCheckCompatibility" > "$RUNNER_TEMP/check.log" 2>&1; then + continue + fi + if ! grep -q 'Found compatibility problems' "$RUNNER_TEMP/check.log"; then + cat "$RUNNER_TEMP/check.log" + echo "::error::Could not compare the public API of $module with the base branch." + exit 1 + fi + python3 .github/scripts/public_api.py --root-package ly.count.sdk.java --root-package ly.count.sdk.java.ui \ + --signatures "$RUNNER_TEMP/api" --module-dir "${module#:}" "$RUNNER_TEMP/check.log" > "$RUNNER_TEMP/module.txt" + if [ -s "$RUNNER_TEMP/module.txt" ]; then + cat "$RUNNER_TEMP/module.txt" >> "$RUNNER_TEMP/breaking.txt" + echo "${entry#*=}" >> "$RUNNER_TEMP/changelogs.txt" + fi + done + # The head's own signatures, beside the base's, give what this pull request adds to the public API. + modules=() + for entry in "${entries[@]}"; do + modules+=("${entry%%=*}") + done + ./gradlew --init-script .github/scripts/public-api.init.gradle -DapiModules="$(IFS=,; echo "${modules[*]}")" \ + -DapiDir="$RUNNER_TEMP/api-head" "${modules[@]/%/:metalavaGenerateSignature}" + python3 .github/scripts/public_api.py --root-package ly.count.sdk.java --root-package ly.count.sdk.java.ui \ + --signatures "$RUNNER_TEMP/api" --added "$RUNNER_TEMP/api-head" > "$RUNNER_TEMP/added.txt" + + - name: Report the public API changes + id: report + run: bash .github/scripts/public_api_report.sh "$RUNNER_TEMP/breaking.txt" "$RUNNER_TEMP/added.txt" + + - name: Upload the CI report fragment + if: ${{ !cancelled() && steps.report.outcome == 'success' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ci-report-public-api + path: ${{ runner.temp }}/ci-report-public-api + if-no-files-found: ignore + + - name: Require a changelog entry for breaking changes + run: | + if [ ! -s "$RUNNER_TEMP/breaking.txt" ]; then + exit 0 + fi + missing="" + while read -r changelog; do + if git diff --quiet HEAD^1 HEAD -- "$changelog"; then + missing="$missing $changelog" + fi + done < <(sort -u "$RUNNER_TEMP/changelogs.txt") + if [ -n "$missing" ]; then + echo "::error title=Breaking API change::This pull request breaks the public API without an entry in:$missing. The job summary lists each break." + exit 1 + fi + echo "::warning title=Breaking API change::This pull request breaks the public API. Check that the changelog marks it as a breaking change." + + # The committed record keeps every change to the public API visible in the pull request's diff. + - name: Compare the public API with its record + id: record + if: ${{ !cancelled() && steps.compare.outcome == 'success' }} + run: > + bash .github/scripts/public_api_record.sh + "$RUNNER_TEMP/api-head/sdk-java.txt=sdk-java/api/sdk-java.txt" "$RUNNER_TEMP/api-head/sdk-java-ui.txt=sdk-java-ui/api/sdk-java-ui.txt" + + - name: Upload the new record + if: ${{ !cancelled() && steps.record.outcome == 'failure' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: public-api-record + path: ${{ runner.temp }}/public-api-record + + comment: + name: Comment the public API changes + needs: api + # A fork's or Dependabot's pull request only gets a read-only token, so its report stays in the job summary. + if: >- + always() && needs.api.outputs.report != '' && + github.event.pull_request.head.repo.full_name == github.repository && + github.event.pull_request.user.login != 'dependabot[bot]' + runs-on: ubuntu-24.04 + permissions: + pull-requests: write + steps: + - name: Post or update the comment + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + PR: ${{ github.event.pull_request.number }} + REPORT: ${{ needs.api.outputs.report }} + run: | + id=$(gh api --paginate "repos/$REPO/issues/$PR/comments" --jq \ + '.[] | select(.user.login == "github-actions[bot]" and (.body | startswith(""))) | .id' | tail -n 1) + if [ -n "$id" ]; then + gh api --method PATCH "repos/$REPO/issues/comments/$id" -f "body=$REPORT" > /dev/null + elif ! grep -qx 'No public API change.' <<< "$REPORT"; then + gh api --method POST "repos/$REPO/issues/$PR/comments" -f "body=$REPORT" > /dev/null + fi diff --git a/.github/workflows/publishing.yml b/.github/workflows/publishing.yml deleted file mode 100644 index e5a1dfe3f..000000000 --- a/.github/workflows/publishing.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Publish the Java SDK -on: - workflow_dispatch: - inputs: - deploy: - description: 'Deploy?' - required: true - type: boolean -jobs: - build: - name: Build and Test - if: ${{ inputs.deploy }} - runs-on: ubuntu-latest - - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Set up JDK 8 - uses: actions/setup-java@v6 - with: - java-version: '8' - distribution: 'corretto' - - - name: Build and Test with Gradle - run: ./gradlew build - - - name: Publish SDK Library to Maven Central - run: ./gradlew publishAllPublicationsToMavenCentralRepository --no-configuration-cache - env: - ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_USERNAME }} - ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_PASSWORD }} - ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_KEY }} - ORG_GRADLE_PROJECT_signingInMemoryKeyId: ${{ secrets.GPG_KEY_ID }} - ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.GPG_KEY_PASSWORD }} diff --git a/.github/workflows/release-on-merge.yml b/.github/workflows/release-on-merge.yml new file mode 100644 index 000000000..b6103e3ac --- /dev/null +++ b/.github/workflows/release-on-merge.yml @@ -0,0 +1,84 @@ +name: Release on merge + +on: + pull_request: + types: [opened, reopened, synchronize, edited, labeled, unlabeled, closed] + branches: [master] + +permissions: {} + +jobs: + check: + name: Release plan + if: >- + github.event.action != 'closed' + && contains(github.event.pull_request.labels.*.name, 'release') + && github.event.pull_request.head.ref == 'staging' + && github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + - name: Plan the releases of the merge + env: + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: python3 .github/release/release.py pending --head "$HEAD_SHA" --merge "$GITHUB_SHA" --branch staging --out pending.json --notes notes + - name: Releasing on merge is off + if: vars.RELEASE_ON_MERGE != 'true' + run: | + echo "::warning::The RELEASE_ON_MERGE variable is not true, so merging this PR creates no release; publish the GitHub release by hand." + echo "- Releasing on merge is off: merging creates no release." >> "$GITHUB_STEP_SUMMARY" + + release: + name: Create the releases + if: >- + github.event.action == 'closed' + && github.event.pull_request.merged + && contains(github.event.pull_request.labels.*.name, 'release') + && github.event.pull_request.head.ref == 'staging' + && github.event.pull_request.head.repo.full_name == github.repository + && vars.RELEASE_ON_MERGE == 'true' + runs-on: ubuntu-24.04 + concurrency: + group: release-on-merge + cancel-in-progress: false + permissions: + contents: write + actions: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.merge_commit_sha }} + fetch-depth: 0 + persist-credentials: false + - name: Plan the releases of the merge + env: + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + MERGE_SHA: ${{ github.event.pull_request.merge_commit_sha }} + run: python3 .github/release/release.py pending --head "$HEAD_SHA" --merge "$MERGE_SHA" --branch staging --out pending.json --notes notes + # A release created with this job's token starts no workflow, so each publish is dispatched on its tag. + - name: Create each GitHub release and start its publish + id: create + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + MERGED_BY: ${{ github.event.pull_request.merged_by.login }} + run: | + jq -r '.releases[] | [.tag, .latest, .prerelease] | @tsv' pending.json | while IFS=$'\t' read -r tag latest prerelease; do + gh release create "$tag" --target "$HEAD_SHA" --title "$tag" --notes-file "notes/$tag.md" --latest="$latest" --prerelease="$prerelease" + gh workflow run release.yml --ref "$tag" -f target=production -f requested_by="$MERGED_BY" + echo "- $tag: GitHub release created, publish started" >> "$GITHUB_STEP_SUMMARY" + done + - name: Recovery + if: failure() && steps.create.outcome == 'failure' + run: | + { + echo "### Some releases may be incomplete" + echo "A GitHub release listed above without its publish has to be published by hand: run the Release workflow on its tag with target production." + echo "A release that is not listed was not created; create it as a GitHub release on the PR's head commit, which starts its publish." + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/release-tools.yml b/.github/workflows/release-tools.yml new file mode 100644 index 000000000..b43897f5c --- /dev/null +++ b/.github/workflows/release-tools.yml @@ -0,0 +1,88 @@ +name: Release tools + +on: + pull_request: + push: + branches: [master, staging] + +permissions: + contents: read + +jobs: + test: + name: Release tools tests + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Unit tests + working-directory: .github/release + run: python3 -m unittest discover -s tests -t . -v + + lint: + name: Release workflow lint + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: actionlint + run: | + curl -sSfL -o "$RUNNER_TEMP/actionlint.tar.gz" https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz + echo "8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 $RUNNER_TEMP/actionlint.tar.gz" | sha256sum -c - + tar -xzf "$RUNNER_TEMP/actionlint.tar.gz" -C "$RUNNER_TEMP" actionlint + # actionlint 1.7.12 predates the concurrency queue key GitHub added in May 2026 (rhysd/actionlint#654). + "$RUNNER_TEMP/actionlint" -ignore 'unexpected key "queue" for "concurrency" section' .github/workflows/release.yml .github/workflows/release-tools.yml .github/workflows/release-on-merge.yml + - name: zizmor + run: | + curl -sSfL -o "$RUNNER_TEMP/zizmor.tar.gz" https://github.com/zizmorcore/zizmor/releases/download/v1.30.1/zizmor-x86_64-unknown-linux-gnu.tar.gz + echo "e65324f4430c2717591937edcec90ccbefaf14c174f8ec9415e03ca875b46e1a $RUNNER_TEMP/zizmor.tar.gz" | sha256sum -c - + tar -xzf "$RUNNER_TEMP/zizmor.tar.gz" -C "$RUNNER_TEMP" zizmor + # The informational findings are expansions of the plan's Gradle task lists, which come from config.json in the same checkout. + "$RUNNER_TEMP/zizmor" --offline --min-severity low .github/workflows/release.yml .github/workflows/release-tools.yml .github/workflows/release-on-merge.yml + + tags: + name: Tags this branch releases + runs-on: ubuntu-24.04 + outputs: + tags: ${{ steps.tags.outputs.tags }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Read the version files + id: tags + env: + BRANCH: ${{ github.base_ref || github.ref_name }} + run: python3 .github/release/release.py checkout-tags --branch "$BRANCH" + + checks: + name: Release checks (${{ matrix.tag }}) + needs: tags + if: needs.tags.outputs.tags != '[]' + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + tag: ${{ fromJSON(needs.tags.outputs.tags) }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + with: + distribution: corretto + java-version: '17' + - uses: gradle/actions/setup-gradle@3f5f9adaf7d9fecd50b5935e54106014257a94e6 # v6.4.0 + - name: Plan + id: plan + env: + TAG: ${{ matrix.tag }} + run: python3 .github/release/release.py plan --tag "$TAG" --target test --out plan.json + - name: Publish into the staging folder + run: ./gradlew --no-configuration-cache ${{ steps.plan.outputs.publish_tasks }} -PRELEASE_SIGNING_ENABLED=false + - name: Stage the release and check its files + run: python3 .github/release/release.py stage --plan plan.json --staging build/release-staging --commit "$GITHUB_SHA" --target test --manifest release-manifest.json + - name: Check what the release promises integrators + run: python3 .github/release/release.py contract --plan plan.json --staging build/release-staging diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 49951badf..d18033cff 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -10,6 +10,10 @@ on: type: choice options: [production, test] default: production + requested_by: + description: "who the announcement names as publishing the release; the one starting the run when empty" + type: string + default: "" permissions: {} @@ -29,11 +33,13 @@ jobs: permissions: contents: read checks: read + actions: read outputs: environment: ${{ steps.plan.outputs.environment }} check_tasks: ${{ steps.plan.outputs.check_tasks }} publish_tasks: ${{ steps.plan.outputs.publish_tasks }} published_modules: ${{ steps.plan.outputs.published_modules }} + prerelease: ${{ steps.release.outputs.prerelease }} steps: - name: Only tags can be released if: github.ref_type != 'tag' @@ -55,6 +61,17 @@ jobs: - name: Plan id: plan run: python3 .github/release/release.py plan --tag "$TAG" --target "$TARGET" --commit "$GITHUB_SHA" --prerelease "${{ steps.release.outputs.prerelease || 'unknown' }}" --out plan.json + - name: The publish environment requires approval + if: env.TARGET == 'production' + env: + GH_TOKEN: ${{ github.token }} + ENVIRONMENT: ${{ steps.plan.outputs.environment }} + run: | + if ! gh api "repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT" > environment.json; then + echo "::error::Could not read the $ENVIRONMENT environment (the error above says why); it has to exist with required reviewers and selected tag deployment rules before releasing." + exit 1 + fi + python3 .github/release/release.py check-environment --environment environment.json - name: The tag commit is on the release branch if: env.TARGET == 'production' run: python3 .github/release/release.py check-branch --plan plan.json --commit "$GITHUB_SHA" @@ -88,7 +105,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: plan - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 @@ -121,7 +138,7 @@ jobs: - name: Check what the release promises integrators run: python3 .github/release/release.py contract --plan plan.json --staging build/release-staging - name: Clean projects build against the staged release - run: python3 .github/release/release.py consumer --plan plan.json --staging build/release-staging --java8-home "$JAVA_HOME_8_X64" --work "$RUNNER_TEMP/consumers" + run: python3 .github/release/release.py consumer --plan plan.json --staging build/release-staging --target "$TARGET" --java8-home "$JAVA_HOME_8_X64" --work "$RUNNER_TEMP/consumers" - name: Scan the published dependencies env: OSV_FAIL_ON: high @@ -149,10 +166,10 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: plan - - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: staged-release - name: The files are exactly what the build produced @@ -200,13 +217,13 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: plan - - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: staged-release - - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: signing-public-key - name: Files, signatures and index @@ -214,31 +231,46 @@ jobs: announce: name: Announce - needs: verify - if: github.event_name == 'release' && !github.event.release.prerelease + needs: [plan, verify] + if: needs.plan.outputs.prerelease == 'false' runs-on: ubuntu-24.04 - permissions: {} + permissions: + contents: read + env: + RELEASE_URL: ${{ github.server_url }}/${{ github.repository }}/releases/tag/${{ github.ref_name }} steps: + - name: Read the release notes + id: release + env: + GH_TOKEN: ${{ github.token }} + run: | + delimiter="EOF_$(openssl rand -hex 16)" + { + echo "body<<$delimiter" + gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json body --jq .body + echo "$delimiter" + } >> "$GITHUB_OUTPUT" - name: Slack - uses: slackapi/slack-github-action@007b2c3c751a190b6f0f040e47ed024deaa72844 # v1.23.0 + uses: slackapi/slack-github-action@dcb1066f776dd043e64d0e8ba94ca15cc7e1875d # v4.0.0 with: + errors: true + webhook: ${{ secrets.SLACK_RELEASE }} + webhook-type: webhook-trigger payload: | { "repository": "${{ github.repository }}", - "tag_name": "${{ github.event.release.tag_name }}", - "actor": "${{ github.actor }}", - "body": ${{ toJSON(github.event.release.body) }}, - "html_url": "${{ github.event.release.html_url }}" + "tag_name": "${{ env.TAG }}", + "actor": ${{ toJSON(inputs.requested_by || github.actor) }}, + "body": ${{ toJSON(steps.release.outputs.body) }}, + "html_url": "${{ env.RELEASE_URL }}" } - env: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_RELEASE }} - name: Discord uses: sarisia/actions-status-discord@eb045afee445dc055c18d3d90bd0f244fd062708 # v1.16.0 with: webhook: ${{ secrets.DISCORD_WEBHOOK_URL }} nodetail: true - title: New ${{ github.repository }} version ${{ github.event.release.tag_name }} published by ${{ github.actor }} + title: New ${{ github.repository }} version ${{ env.TAG }} published by ${{ inputs.requested_by || github.actor }} description: | - Release URL: ${{ github.event.release.html_url }} - Click [here](https://github.com/Countly/countly-server/blob/master/CHANGELOG.md) to view the change log. - `${{ github.event.release.body }}` + Release URL: ${{ env.RELEASE_URL }} + Click [here](${{ github.server_url }}/${{ github.repository }}/blob/${{ env.TAG }}/CHANGELOG.md) to view the change log. + `${{ steps.release.outputs.body }}` diff --git a/.github/workflows/release_notice.yml b/.github/workflows/release_notice.yml deleted file mode 100644 index 336863e5d..000000000 --- a/.github/workflows/release_notice.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: Release Notice -on: - release: - types: [published] - workflow_dispatch: -jobs: - build: - runs-on: ubuntu-latest - steps: - # To check the github context - - name: Dump Github context - env: - GITHUB_CONTEXT: ${{ toJSON(github) }} - run: echo "$GITHUB_CONTEXT" - - name: Send custom JSON data to Slack workflow - id: slack - uses: slackapi/slack-github-action@v4.0.0 - with: - webhook: ${{ secrets.SLACK_RELEASE }} - webhook-type: webhook-trigger - # This data can be any valid JSON from a previous step in the GitHub Action - payload: | - { - "repository": "${{ github.repository }}", - "tag_name": "${{ github.event.release.tag_name }}", - "actor": "${{ github.actor }}", - "body": ${{ toJSON(github.event.release.body) }}, - "html_url": "${{ github.event.release.html_url }}" - } - - name: Send custom JSON data to Discord - uses: sarisia/actions-status-discord@v1.16.0 - with: - webhook: ${{ secrets.DISCORD_WEBHOOK_URL }} - nodetail: true - title: New ${{ github.repository }} version ${{ github.event.release.tag_name }} published by ${{ github.actor }} - description: | - Release URL: ${{ github.event.release.html_url }} - Click [here](https://github.com/Countly/countly-server/blob/master/CHANGELOG.md) to view the change log. - `${{ github.event.release.body }}` diff --git a/.github/workflows/static_analysis.yml b/.github/workflows/static_analysis.yml new file mode 100644 index 000000000..b5be68ba4 --- /dev/null +++ b/.github/workflows/static_analysis.yml @@ -0,0 +1,91 @@ +name: Static analysis + +on: + pull_request: + push: + branches: + - master + - staging + workflow_dispatch: + +permissions: + contents: read + +jobs: + spotbugs: + name: SpotBugs + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 2 + persist-credentials: false + + # JDK 17 rather than the SDK's Java 8 floor: settings.gradle only includes :sdk-java-ui on Java 11+. + - name: Set up JDK 17 + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + java-version: '17' + distribution: 'corretto' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + + # On pull requests the base branch is analyzed too, so that only findings it lacks can fail the job. + - name: Analyze the published modules + run: | + # Runs SpotBugs on the published modules that the checkout in $1 has, writing SARIF to $2. + analyze() { + modules=() + for module in :sdk-java :sdk-java-ui; do + if [ -d "$1/${module#:}" ]; then + modules+=("$module") + fi + done + (cd "$1" && ./gradlew --no-configuration-cache --init-script "$GITHUB_WORKSPACE/.github/scripts/spotbugs.init.gradle" \ + -DspotbugsModules="$(IFS=,; echo "${modules[*]}")" "-DspotbugsDir=$2" "${modules[@]/%/:spotbugsMain}") + } + analyze "$GITHUB_WORKSPACE" "$RUNNER_TEMP/sarif" + if [ "$GITHUB_EVENT_NAME" = pull_request ]; then + # The first parent of the pull request's merge commit is the base branch it merges into. + git worktree add "$RUNNER_TEMP/base" HEAD^1 + analyze "$RUNNER_TEMP/base" "$RUNNER_TEMP/sarif-base" + fi + + # Every finding goes to the job summary; a new one at warning or error level fails the job. + - name: Summarize the findings + run: | + # The default shell has no pipefail, and without it tee would hide the summary's exit code. + set -o pipefail + base=() + if [ -d "$RUNNER_TEMP/sarif-base" ]; then + base=(--base "$RUNNER_TEMP/sarif-base" --base-root "$RUNNER_TEMP/base") + fi + python3 .github/scripts/sarif_summary.py SpotBugs "$RUNNER_TEMP/sarif" "${base[@]}" | tee -a "$GITHUB_STEP_SUMMARY" "$RUNNER_TEMP/static-analysis.md" + + - name: Write the CI report fragment + if: ${{ !cancelled() }} + run: | + [ -s "$RUNNER_TEMP/static-analysis.md" ] || exit 0 + new=$(sed -n 's/^### New compared with the base branch: \([0-9][0-9]*\)$/\1/p' "$RUNNER_TEMP/static-analysis.md") + case "$new" in + '') summary=$(sed -n '1s/^### //p' "$RUNNER_TEMP/static-analysis.md") ;; + 0) summary="No new findings" ;; + 1) summary="1 new finding" ;; + *) summary="$new new findings" ;; + esac + mkdir -p "$RUNNER_TEMP/ci-report-static-analysis" + { + printf 'Static analysis\n%s\n' "$summary" + cat "$RUNNER_TEMP/static-analysis.md" + } > "$RUNNER_TEMP/ci-report-static-analysis/report.md" + + - name: Upload the CI report fragment + if: ${{ !cancelled() }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ci-report-static-analysis + path: ${{ runner.temp }}/ci-report-static-analysis + if-no-files-found: ignore diff --git a/.github/workflows/validate_gradle.yml b/.github/workflows/validate_gradle.yml index 7f9cf22c8..6486a47c5 100644 --- a/.github/workflows/validate_gradle.yml +++ b/.github/workflows/validate_gradle.yml @@ -10,10 +10,13 @@ on: - master - staging +permissions: + contents: read + jobs: validation: name: "Validate Gradle Wrapper SHA-256 checksum" runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: gradle/wrapper-validation-action@v3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: gradle/actions/wrapper-validation@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 diff --git a/CHANGELOG.md b/CHANGELOG.md index f088611b1..3aba5104f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,78 @@ +## 26.12.0 +* !! Major breaking change !! New versions of `ly.count.sdk:java` and `ly.count.sdk:java-ui` are published at `https://maven.countly.com` instead of Maven Central. Add the repository once. + Gradle, next to `mavenCentral()` in `dependencyResolutionManagement` of `settings.gradle` (or in `allprojects` of the root `build.gradle` in older projects): + ```groovy + maven { + url = 'https://maven.countly.com' + content { includeGroupByRegex 'ly\\.count\\..*' } + } + ``` + Maven, in `pom.xml`: + ```xml + + + countly + https://maven.countly.com + true + false + + + ``` + Versions released before this one stay available on Maven Central. The files are signed with the same key as before (`FC8DB0DE234A273BA45E562FB8C83A079A5BBD0C`). +* ! Minor breaking change ! `ly.count.sdk:java-ui` now has its own version numbers and is released only when it changes; see its own [CHANGELOG](sdk-java-ui/CHANGELOG.md). Use the latest version of each package instead of one shared number. +* ! Minor breaking change ! SDK behavior settings are now enabled by default. The SDK fetches them from the server at initialization and every few hours, so changes made in SDK Manager > SDK Configuration on your server affect SDK behavior directly. They are not used in backend mode. +* ! Minor breaking change ! The feature interfaces of "Countly.instance()" ("events()", "views()", "crashes()", "location()", "userProfile()", "remoteConfig()", "feedback()", "content()" and "deviceId()") no longer return null. + Before initialization, while the consent of a feature is not given, or when a feature is not enabled, they return an interface that ignores calls until the feature runs and passes an error to the callbacks of the calls it ignores. + An interface you keep sends its calls to the feature once it runs. Use "Countly.isTracking" to check whether a feature runs. + +* Added the health check feature. The SDK now sends a health check request once after each initialization, except in backend mode. +* Added support for SDK behavior settings that let the server control the SDK: + * Switches for tracking, networking, sessions, views, custom events, crash reporting, automatic crash reporting, location, and console logging + * The event queue size, request queue size, session update interval, and settings refresh interval + * 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 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. +* Added "disableBackoffMechanism()" init config method to disable the backoff behavior. +* Added "enableRequestCompression()" init config method. Request bodies between 1 KB and 1 MB are then sent gzip-compressed, once the server's SDK behavior settings answer says it reads them. It does not apply in backend mode, which does not use the SDK behavior settings. +* Added support for server requested SDK log gathering. When the server asks for it, the SDK uploads its own internal log lines, even if logging is disabled. While consent is required, a line is uploaded only while the consent of the feature it belongs to is given. +* Added support for the SDK connection test. When the server asks for it, the SDK checks that it can reach every endpoint it depends on and reports the results. +* Added "setMaxKeyLength(int)" init config method to limit the length of event keys, view names, segmentation keys and custom user property keys. Longer keys are truncated. There is no limit by default, and the key length limit of the SDK behavior settings overrides it. +* Added "disableHealthCheck()" init config method to turn off the health check request. +* Added "changeServerUrl(String)" to "Countly.instance()" to change the server URL after init. +* Added "changeAppKey(String)" to "Countly.instance()" to change the app key after init. +* Added "flushQueues()", "replaceAllAppKeysInQueueWithCurrentAppKey()", "removeDifferentAppKeysFromQueue()" and "attemptToSendStoredRequests()" to "Countly.instance()" to manage the request queue. +* The deprecated "event", "timedEvent", "view" and "addCrashReport" calls of the session interface, and "record" and "endAndRecord" of a legacy event, now log a warning that names the call to use instead. +* Failed requests are now logged at debug level, and wrong uses of the session, event, view and crash methods at warning level instead of error level. + +* Mitigated an issue where saving the SDK storage while remote config values were changing could empty the storage file. +* Mitigated an issue where a storage file cut short by a stopped process made initialization fail. +* Mitigated an issue where a request recorded while the SDK was finishing a send could wait until the next request or session update before it was sent. + +* Mitigated an issue where requests, sessions or crashes created close together could get the same storage ID, so some of them were lost. +* Mitigated an issue where removing the consent of one feature also stopped the other features and deleted their queued events, unsent crashes and remote config values, after which the device ID and user profile interfaces could throw. +* Mitigated an issue where, while consent was required, unhandled crashes were not recorded if the crash reporting consent was given after initialization. +* Mitigated an issue where removing the location consent did not erase the location on the server. +* Mitigated an issue where an error in one feature during a timer tick stopped the SDK timer, and with it session updates and event sending. +* Mitigated an issue where verbose logs showed the values of custom network request headers. Only the number of headers is logged now. +* Mitigated an issue where a fresh initialization logged an error for storage files that did not exist yet. +* Mitigated an issue where a crash breadcrumb added while a crash was being recorded on another thread could be lost. +* Mitigated an issue where backend mode requests carried no device ID type, so the server did not count the users recorded in backend mode as identified. +* Mitigated an issue where a backend mode direct request sent a key twice when the given map contained a key the SDK also sets. The value in the map now replaces the SDK's value, as documented. +* Mitigated an issue where a backend mode direct request changed the given map, and failed with an unmodifiable map. +* Mitigated an issue where "onConsent" and "onConsentRemoval" threw a NullPointerException when one of the given features was null. +* Mitigated an issue where the session update timer logged an error every minute for a session that was created but not begun. + +* Updated JSON library version from "20250517" to "20260814". + ## 26.8.0 * Added support for the Content feature, accessible through the "Countly.instance().content()" interface: * "enterContentZone" / "exitContentZone" for starting and stopping periodic content fetching diff --git a/app-java/build.gradle b/app-java/build.gradle index 1de384cec..bc19c7481 100644 --- a/app-java/build.gradle +++ b/app-java/build.gradle @@ -16,4 +16,6 @@ dependencies { //implementation "ly.count.sdk:java:${CLY_VERSION}" } -mainClassName = 'ly.count.java.demo.ReproduceIssue264' +application { + mainClass = 'ly.count.java.demo.ReproduceIssue264' +} diff --git a/app-javafx/build.gradle b/app-javafx/build.gradle index c6613abfb..5322a9a6b 100644 --- a/app-javafx/build.gradle +++ b/app-javafx/build.gradle @@ -29,6 +29,15 @@ dependencies { implementation 'org.json:json:20260814' } +// sdk-java-ui depends on a released ly.count.sdk:java. The demo runs everything on +// the local sdk-java module instead, so two copies of the core never meet on its +// classpath. +configurations.configureEach { + resolutionStrategy.dependencySubstitution { + substitute module('ly.count.sdk:java') using project(':sdk-java') + } +} + application { mainClass = 'ly.count.javafx.demo.Main' } diff --git a/app-javafx/src/main/java/ly/count/javafx/demo/AppContext.java b/app-javafx/src/main/java/ly/count/javafx/demo/AppContext.java index fd70e38e2..ba9d5834e 100644 --- a/app-javafx/src/main/java/ly/count/javafx/demo/AppContext.java +++ b/app-javafx/src/main/java/ly/count/javafx/demo/AppContext.java @@ -13,7 +13,7 @@ public final class AppContext { // flows, so our raw feedback HTTP call (used to recover the wv field // for URL construction) identifies the same client. public static final String SDK_NAME = "java-native"; - public static final String SDK_VERSION = "26.8.0"; + public static final String SDK_VERSION = "26.12.0"; public static final String PLATFORM = "desktop"; // Populated from the Init tab once the user initializes the SDK; the diff --git a/build.gradle b/build.gradle index b8f1479b3..c797c2f2e 100644 --- a/build.gradle +++ b/build.gradle @@ -4,6 +4,10 @@ buildscript { repositories { google() mavenCentral() + // CycloneDX publishes its Gradle plugin 3.x only on the Gradle Plugin Portal. + gradlePluginPortal { + content { includeGroup 'org.cyclonedx' } + } } dependencies { // The publish plugin is loaded here, once, and only when a publish task is requested. Loading it @@ -13,12 +17,31 @@ buildscript { if (gradle.startParameter.taskNames.any { it.toLowerCase().contains("publish") }) { // This requires minimum java 11 to work classpath 'com.vanniktech:gradle-maven-publish-plugin:0.28.0' + classpath 'org.cyclonedx:cyclonedx-gradle-plugin:3.5.1' + } + } +} + +// Publishing modules: the local staging repository release.yml uploads from, and the SBOM of the published runtime classpath. +subprojects { + plugins.withId('com.vanniktech.maven.publish') { + publishing { + repositories { + maven { + name = 'releaseStaging' + url = rootProject.file('build/release-staging') + } + } + } + apply plugin: 'org.cyclonedx.bom' + tasks.named('cyclonedxDirectBom').configure { + includeConfigs = ['runtimeClasspath'] } } } allprojects { - ext.CLY_VERSION = "26.8.0" + ext.CLY_VERSION = "26.12.0" ext.POWERMOCK_VERSION = "1.7.4" ext.JACOCO_VERSION = "0.8.13" @@ -35,6 +58,11 @@ allprojects { repositories { google() mavenCentral() + // Core SDK releases published after the move from Maven Central, which sdk-java-ui can depend on. + maven { + url = 'https://maven.countly.com' + content { includeGroupByRegex 'ly\\.count\\..*' } + } } } @@ -129,7 +157,7 @@ ext.countFailedTests = { module -> int failed = 0 resultsDir.listFiles({ file -> file.name.endsWith('.xml') } as FileFilter)?.each { file -> try { - def suite = new XmlParser(false, false).parse(file) + def suite = new groovy.xml.XmlParser(false, false).parse(file) failed += (suite.@failures as int) + (suite.@errors as int) } catch (Exception ignored) { // An unreadable result file is not worth failing the summary over. @@ -145,7 +173,7 @@ ext.countFailedTests = { module -> * build depend on the network, so external entities are switched off. */ ext.readCounters = { File report -> - def parser = new XmlParser(false, false) + def parser = new groovy.xml.XmlParser(false, false) parser.setFeature('http://apache.org/xml/features/disallow-doctype-decl', false) parser.setFeature('http://apache.org/xml/features/nonvalidating/load-external-dtd', false) diff --git a/gradle.properties b/gradle.properties index a5a8126c6..a01e56b67 100644 --- a/gradle.properties +++ b/gradle.properties @@ -18,7 +18,7 @@ # org.gradle.parallel=true # RELEASE FIELD SECTION -VERSION_NAME=26.8.0 +VERSION_NAME=26.12.0 GROUP=ly.count.sdk POM_URL=https://github.com/Countly/countly-sdk-java diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 1b33c55ba..9fa7f2882 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 4f5eb9dcc..2a66ec2c7 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.5-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew index 23d15a936..249efbb03 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright © 2015-2021 the original authors. +# Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ ############################################################################## # -# Gradle start up script for POSIX generated by Gradle. +# gradlew start up script for POSIX generated by Gradle. # # Important for running: # @@ -29,7 +29,7 @@ # bash, then to run this script, type that shell name before the whole # command line, like: # -# ksh Gradle +# ksh gradlew # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: @@ -57,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -114,7 +114,6 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH="\\\"\\\"" # Determine the Java command to use to start the JVM. @@ -172,7 +171,6 @@ fi # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) @@ -212,7 +210,6 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" diff --git a/gradlew.bat b/gradlew.bat index 5eed7ee84..03754c4c3 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -19,12 +19,39 @@ @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem -@rem Gradle startup script for Windows +@rem gradlew startup script for Windows @rem @rem ########################################################################## -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @@ -45,13 +72,14 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. -goto fail +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% @@ -59,36 +87,26 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. -goto fail +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel :execute @rem Setup the command line -set CLASSPATH= -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/sdk-java-ui/CHANGELOG.md b/sdk-java-ui/CHANGELOG.md new file mode 100644 index 000000000..13e91192d --- /dev/null +++ b/sdk-java-ui/CHANGELOG.md @@ -0,0 +1,10 @@ +## 26.12.0 +* !! Major breaking change !! New versions of `ly.count.sdk:java-ui` are published at `https://maven.countly.com` instead of Maven Central. Add the repository once, as shown in the Java SDK's [CHANGELOG](../CHANGELOG.md), and keep `mavenCentral()`: JavaFX, the JSON library and Java SDK versions up to 26.8.0 still come from there. + Versions released before this one stay available on Maven Central. The files are signed with the same key as before (`FC8DB0DE234A273BA45E562FB8C83A079A5BBD0C`). +* ! Minor breaking change ! `ly.count.sdk:java-ui` now has its own version numbers and is released only when it changes, so its version no longer follows the core SDK `ly.count.sdk:java`. + It names the core version it needs, currently 26.8.0; if your project also declares `ly.count.sdk:java`, use that version or a newer one. + +* Updated JSON library version from "20250517" to "20260814". + +## 26.8.0 +* First release, together with the Java SDK 26.8.0. See the Java SDK's [CHANGELOG](../CHANGELOG.md) for what it displays. diff --git a/sdk-java-ui/api/sdk-java-ui.txt b/sdk-java-ui/api/sdk-java-ui.txt new file mode 100644 index 000000000..e34128f7e --- /dev/null +++ b/sdk-java-ui/api/sdk-java-ui.txt @@ -0,0 +1,100 @@ +// Signature format: 4.0 +package ly.count.sdk.java.ui { + + public class ContentJsBridge { + method public void post(String!); + } + + public final class CountlyWebView { + method public static void disableContentZone(); + method public static void enableContentZone(); + method public static void enableContentZone(javafx.stage.Window!); + method public static boolean isShowingWidgetsWithinApp(); + method public static void presentFeedbackWidget(javafx.stage.Window!, ly.count.sdk.java.internal.CountlyFeedbackWidget!, Runnable!); + method public static void presentNPS(javafx.stage.Window!); + method public static void presentNPS(javafx.stage.Window!, String!); + method public static void presentNPS(javafx.stage.Window!, String!, Runnable!); + method public static void presentRating(javafx.stage.Window!); + method public static void presentRating(javafx.stage.Window!, String!); + method public static void presentRating(javafx.stage.Window!, String!, Runnable!); + method public static void presentSurvey(javafx.stage.Window!); + method public static void presentSurvey(javafx.stage.Window!, String!); + method public static void presentSurvey(javafx.stage.Window!, String!, Runnable!); + method public static void setOverlayCornerRadius(double); + method public static void setShowWidgetsWithinApp(boolean); + method public static void setWebViewDiagnosticsEnabled(boolean); + } + + public class FeedbackWidgetPresenter implements ly.count.sdk.java.ui.WidgetWebHost.Listener { + ctor public FeedbackWidgetPresenter(ly.count.sdk.java.ui.WidgetWebHost!, ly.count.sdk.java.internal.ModuleFeedback.Feedback!, Runnable!); + method public void onCardFollowing(int, int); + method public void onCardMeasured(int, int); + method public void onContentOverflow(int); + method public void onLoadFailed(); + method public void onNavigationStarting(String!); + method public void onPageLoaded(); + method public void onSizeNotReported(int, int); + method public void onWidgetMessage(String!); + method public void refreshPlacement(); + method public void start(ly.count.sdk.java.internal.CountlyFeedbackWidget!); + } + + public class JavaFxContentDisplay implements ly.count.sdk.java.internal.ContentDisplay { + ctor public JavaFxContentDisplay(); + ctor public JavaFxContentDisplay(javafx.stage.Window!); + method public ly.count.sdk.java.internal.ContentScreen! getScreen(); + method public void present(ly.count.sdk.java.internal.ContentData!, ly.count.sdk.java.internal.ContentCloseCallback!); + } + + public class WidgetJsBridge { + method public void cardChanged(String!); + method public void post(String!); + } + + public class WidgetMessageParser { + method public static ly.count.sdk.java.internal.WidgetAction! parse(String!); + } + + public class WidgetPlacement { + method public static ly.count.sdk.java.internal.ContentPlacement! following(ly.count.sdk.java.internal.ContentPlacement!, ly.count.sdk.java.ui.WidgetSurface!, ly.count.sdk.java.internal.ContentPlacement!, ly.count.sdk.java.ui.WidgetSurface!, ly.count.sdk.java.ui.WidgetSurface!); + method public static ly.count.sdk.java.internal.ContentPlacement! rescale(ly.count.sdk.java.internal.ContentPlacement!, ly.count.sdk.java.ui.WidgetSurface!, ly.count.sdk.java.ui.WidgetSurface!); + method public static ly.count.sdk.java.internal.ContentPlacement! resolve(ly.count.sdk.java.internal.ContentPlacement!, ly.count.sdk.java.ui.WidgetSurface!); + method public static ly.count.sdk.java.internal.ContentPlacement! resolve(ly.count.sdk.java.internal.WidgetAction!, ly.count.sdk.java.ui.WidgetSurface!); + } + + public class WidgetSurface { + ctor public WidgetSurface(int, int, int, int); + method public boolean isLandscape(); + method public boolean sameAs(ly.count.sdk.java.ui.WidgetSurface!); + method public boolean sameSizeAs(ly.count.sdk.java.ui.WidgetSurface!); + method public String toString(); + field public final int height; + field public final int width; + field public final int x; + field public final int y; + } + + public interface WidgetWebHost { + method public void closeHost(); + method public void followGeometry(ly.count.sdk.java.internal.ContentPlacement!); + method public ly.count.sdk.java.ui.WidgetSurface! getSurface(); + method public void navigate(String!); + method public void placeAndShow(ly.count.sdk.java.internal.ContentPlacement!); + method public void reportSurfaceSize(int, int); + method public void setListener(ly.count.sdk.java.ui.WidgetWebHost.Listener!); + method public void setSurface(ly.count.sdk.java.ui.WidgetSurface!); + } + + public static interface WidgetWebHost.Listener { + method public void onCardFollowing(int, int); + method public void onCardMeasured(int, int); + method public void onContentOverflow(int); + method public void onLoadFailed(); + method public void onNavigationStarting(String!); + method public void onPageLoaded(); + method public void onSizeNotReported(int, int); + method public void onWidgetMessage(String!); + } + +} + diff --git a/sdk-java-ui/build.gradle b/sdk-java-ui/build.gradle index 6f11bc4f2..00f2e6ac8 100644 --- a/sdk-java-ui/build.gradle +++ b/sdk-java-ui/build.gradle @@ -59,8 +59,11 @@ javafx { dependencies { // 'api' so a consumer of this artifact also gets the core SDK, whose types - // appear in this package's public signatures. - api project(':sdk-java') + // appear in this package's public signatures. A released core, not the sdk-java + // project: this artifact is released on its own, so what it is built and tested + // against is exactly what its POM tells integrators to use. Raise it only to a + // core version that is already published. + api 'ly.count.sdk:java:26.8.0' implementation 'org.json:json:20260814' @@ -68,6 +71,18 @@ dependencies { testImplementation 'org.mockito:mockito-core:4.11.0' } +// -PtestUiWithLocalCore=true builds and tests this module's source against the sdk-java project +// instead of the released core above. This module uses the core's internal classes, so a core +// change that breaks it fails CI before the core is released. It does not test the released +// java-ui jar on a newer core. +if (findProperty('testUiWithLocalCore') == 'true') { + configurations.configureEach { + resolutionStrategy.dependencySubstitution { + substitute module('ly.count.sdk:java') using project(':sdk-java') + } + } +} + // Coverage. Reports land in build/reports/jacoco/test/ (HTML to read, XML for tooling). // "./gradlew coverage" from the repo root runs this and prints a summary. apply plugin: 'jacoco' diff --git a/sdk-java-ui/gradle.properties b/sdk-java-ui/gradle.properties index 980570f36..4aa279ddd 100644 --- a/sdk-java-ui/gradle.properties +++ b/sdk-java-ui/gradle.properties @@ -1,5 +1,7 @@ #RELEASE FIELDS POM_ARTIFACT_ID=java-ui +# Released on its own with tags ui-X.Y.Z, so it overrides the root VERSION_NAME of the core SDK. +VERSION_NAME=26.12.0 POM_NAME=Countly Java SDK UI POM_DESCRIPTION=JavaFX user interface for the Countly Java SDK, displaying feedback widgets and content diff --git a/sdk-java/api/requests/consent.json b/sdk-java/api/requests/consent.json new file mode 100644 index 000000000..0b8e2bd70 --- /dev/null +++ b/sdk-java/api/requests/consent.json @@ -0,0 +1,65 @@ +[ + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "begin_session": "1", + "device_id": "parity-device-001", + "dow": "", + "hour": "", + "metrics": { + "_app_version": "", + "_device": "", + "_locale": "", + "_os": "", + "_os_version": "", + "_resolution": "" + }, + "sdk_name": "java-native", + "sdk_version": "", + "session_id": "", + "timestamp": "", + "tz": "" + } + }, + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "device_id": "parity-device-001", + "dow": "", + "events": [ + { + "count": 1, + "cvid": "", + "dow": "", + "hour": "", + "id": "", + "key": "consented", + "timestamp": "" + } + ], + "hour": "", + "sdk_name": "java-native", + "sdk_version": "", + "timestamp": "", + "tz": "" + } + }, + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "device_id": "parity-device-001", + "dow": "", + "end_session": "1", + "hour": "", + "sdk_name": "java-native", + "sdk_version": "", + "session_duration": "", + "session_id": "", + "timestamp": "", + "tz": "" + } + } +] diff --git a/sdk-java/api/requests/crash.json b/sdk-java/api/requests/crash.json new file mode 100644 index 000000000..b1a2a71c9 --- /dev/null +++ b/sdk-java/api/requests/crash.json @@ -0,0 +1,40 @@ +[ + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "crash": { + "_app_version": "1.0", + "_bat": "", + "_cpu": "", + "_custom": { + "tier": "gold" + }, + "_device": "", + "_disk_current": "", + "_disk_total": "", + "_error": "", + "_logs": "breadcrumb one", + "_manufacture": "", + "_muted": "", + "_nonfatal": true, + "_online": "", + "_opengl": "", + "_orientation": "", + "_os": "", + "_os_version": "", + "_ram_current": "", + "_ram_total": "", + "_resolution": "", + "_run": "" + }, + "device_id": "parity-device-001", + "dow": "", + "hour": "", + "sdk_name": "java-native", + "sdk_version": "", + "timestamp": "", + "tz": "" + } + } +] diff --git a/sdk-java/api/requests/device-id.json b/sdk-java/api/requests/device-id.json new file mode 100644 index 000000000..a19eceab0 --- /dev/null +++ b/sdk-java/api/requests/device-id.json @@ -0,0 +1,142 @@ +[ + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "begin_session": "1", + "device_id": "parity-device-001", + "dow": "", + "hour": "", + "metrics": { + "_app_version": "", + "_device": "", + "_locale": "", + "_os": "", + "_os_version": "", + "_resolution": "" + }, + "sdk_name": "java-native", + "sdk_version": "", + "session_id": "", + "timestamp": "", + "tz": "" + } + }, + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "device_id": "parity-device-002", + "dow": "", + "hour": "", + "old_device_id": "parity-device-001", + "sdk_name": "java-native", + "sdk_version": "", + "timestamp": "", + "tz": "" + } + }, + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "device_id": "parity-device-002", + "dow": "", + "events": [ + { + "count": 1, + "cvid": "", + "dow": "", + "hour": "", + "id": "", + "key": "after_merge", + "timestamp": "" + } + ], + "hour": "", + "sdk_name": "java-native", + "sdk_version": "", + "timestamp": "", + "tz": "" + } + }, + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "device_id": "parity-device-002", + "dow": "", + "end_session": "1", + "hour": "", + "sdk_name": "java-native", + "sdk_version": "", + "session_duration": "", + "session_id": "", + "timestamp": "", + "tz": "" + } + }, + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "begin_session": "1", + "device_id": "parity-device-003", + "dow": "", + "hour": "", + "metrics": { + "_app_version": "", + "_device": "", + "_locale": "", + "_os": "", + "_os_version": "", + "_resolution": "" + }, + "sdk_name": "java-native", + "sdk_version": "", + "session_id": "", + "timestamp": "", + "tz": "" + } + }, + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "device_id": "parity-device-003", + "dow": "", + "end_session": "1", + "hour": "", + "sdk_name": "java-native", + "sdk_version": "", + "session_id": "", + "timestamp": "", + "tz": "" + } + }, + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "device_id": "parity-device-003", + "dow": "", + "events": [ + { + "count": 1, + "cvid": "", + "dow": "", + "hour": "", + "id": "", + "key": "after_new_id", + "peid": "", + "timestamp": "" + } + ], + "hour": "", + "sdk_name": "java-native", + "sdk_version": "", + "timestamp": "", + "tz": "" + } + } +] diff --git a/sdk-java/api/requests/parity.json b/sdk-java/api/requests/parity.json new file mode 100644 index 000000000..5afcf7f66 --- /dev/null +++ b/sdk-java/api/requests/parity.json @@ -0,0 +1,115 @@ +[ + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "begin_session": "1", + "device_id": "parity-device-001", + "dow": "", + "hour": "", + "metrics": { + "_app_version": "", + "_device": "", + "_locale": "", + "_os": "", + "_os_version": "", + "_resolution": "" + }, + "sdk_name": "java-native", + "sdk_version": "", + "session_id": "", + "timestamp": "", + "tz": "" + } + }, + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "device_id": "parity-device-001", + "dow": "", + "events": [ + { + "count": 2, + "cvid": "", + "dow": "", + "dur": 5, + "hour": "", + "id": "", + "key": "purchase", + "segmentation": { + "hashirama": -2147483647, + "itachi": 1.7976931348623157E+308, + "kakaski": 4.9E-324, + "nar": "uto", + "sakura": false, + "sasuke": 2147483647 + }, + "sum": 9.99, + "timestamp": "" + } + ], + "hour": "", + "sdk_name": "java-native", + "sdk_version": "", + "timestamp": "", + "tz": "" + } + }, + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "device_id": "parity-device-001", + "dow": "", + "hour": "", + "sdk_name": "java-native", + "sdk_version": "", + "timestamp": "", + "tz": "", + "user_details": { + "byear": 1980, + "custom": { + "age": 30, + "tier": "gold" + }, + "email": "john@example.com", + "gender": "M", + "name": "John Doe", + "organization": "Countly", + "phone": "1234567890", + "username": "john_d" + } + } + }, + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "device_id": "parity-device-001", + "dow": "", + "hour": "", + "sdk_name": "java-native", + "sdk_version": "", + "session_duration": "", + "session_id": "", + "timestamp": "", + "tz": "" + } + }, + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "device_id": "parity-device-001", + "dow": "", + "end_session": "1", + "hour": "", + "sdk_name": "java-native", + "sdk_version": "", + "session_id": "", + "timestamp": "", + "tz": "" + } + } +] diff --git a/sdk-java/api/requests/views.json b/sdk-java/api/requests/views.json new file mode 100644 index 000000000..51e9300c3 --- /dev/null +++ b/sdk-java/api/requests/views.json @@ -0,0 +1,104 @@ +[ + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "begin_session": "1", + "device_id": "parity-device-001", + "dow": "", + "hour": "", + "metrics": { + "_app_version": "", + "_device": "", + "_locale": "", + "_os": "", + "_os_version": "", + "_resolution": "" + }, + "sdk_name": "java-native", + "sdk_version": "", + "session_id": "", + "timestamp": "", + "tz": "" + } + }, + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "device_id": "parity-device-001", + "dow": "", + "end_session": "1", + "hour": "", + "sdk_name": "java-native", + "sdk_version": "", + "session_id": "", + "timestamp": "", + "tz": "" + } + }, + { + "path": "/i", + "params": { + "app_key": "parity-app-key", + "device_id": "parity-device-001", + "dow": "", + "events": [ + { + "count": 1, + "dow": "", + "dur": "", + "hour": "", + "id": "", + "key": "[CLY]_view", + "pvid": "", + "segmentation": { + "name": "Home", + "segment": "", + "source": "scenario", + "start": "1", + "visit": "1" + }, + "sum": 0, + "timestamp": "" + }, + { + "count": 1, + "dow": "", + "dur": "", + "hour": "", + "id": "", + "key": "[CLY]_view", + "pvid": "", + "segmentation": { + "name": "Home", + "segment": "" + }, + "sum": 0, + "timestamp": "" + }, + { + "count": 1, + "dow": "", + "dur": "", + "hour": "", + "id": "", + "key": "[CLY]_view", + "pvid": "", + "segmentation": { + "name": "Settings", + "segment": "", + "visit": "1" + }, + "sum": 0, + "timestamp": "" + } + ], + "hour": "", + "sdk_name": "java-native", + "sdk_version": "", + "timestamp": "", + "tz": "" + } + } +] diff --git a/sdk-java/api/sdk-java.txt b/sdk-java/api/sdk-java.txt new file mode 100644 index 000000000..9bea4013f --- /dev/null +++ b/sdk-java/api/sdk-java.txt @@ -0,0 +1,1569 @@ +// Signature format: 4.0 +package ly.count.sdk.java { + + public class Config { + ctor @Deprecated public Config(String!, String!); + ctor public Config(String!, String!, File!); + method public ly.count.sdk.java.Config! addCertificatePin(String!); + method public ly.count.sdk.java.Config! addCustomNetworkRequestHeaders(Map!); + method public ly.count.sdk.java.Config! addPublicKeyPin(String!); + method @Deprecated public ly.count.sdk.java.Config! disableANRCrashReporting(); + method public ly.count.sdk.java.Config! disableAutoSendUserProperties(); + method public ly.count.sdk.java.Config! disableBackoffMechanism(); + method public ly.count.sdk.java.Config! disableFeatures(ly.count.sdk.java.Config.Feature!...!); + method public ly.count.sdk.java.Config! disableHealthCheck(); + method public ly.count.sdk.java.Config! disableLocation(); + method public ly.count.sdk.java.Config! disableSdkBehaviorSettingsUpdates(); + method @Deprecated public ly.count.sdk.java.Config! disableTestMode(); + method public ly.count.sdk.java.Config! disableUnhandledCrashReporting(); + method public ly.count.sdk.java.Config! disableUpdateRequests(); + method public ly.count.sdk.java.Config! enableBackendMode(); + method public ly.count.sdk.java.Config! enableFeatures(ly.count.sdk.java.Config.Feature!...!); + method public ly.count.sdk.java.Config! enableForcedHTTPPost(); + method public ly.count.sdk.java.Config! enableParameterTamperingProtection(String!); + method public ly.count.sdk.java.Config! enableRemoteConfigAutomaticTriggers(); + method public ly.count.sdk.java.Config! enableRemoteConfigValueCaching(); + method public ly.count.sdk.java.Config! enableRequestCompression(); + method @Deprecated public ly.count.sdk.java.Config! enableTestMode(); + method @Deprecated public ly.count.sdk.java.Config! enableUsePOST(); + method public ly.count.sdk.java.Config! enrollABOnRCDownload(); + method @Deprecated public String! getApplicationName(); + method public String! getApplicationVersion(); + method public Set! getCertificatePins(); + method public String! getCrashProcessorClass(); + method @Deprecated public int getCrashReportingANRCheckingPeriod(); + method public String! getCustomDeviceId(); + method public Map! getCustomNetworkRequestHeaders(); + method public int getDeviceIdStrategy(); + method public ly.count.sdk.java.Config.DeviceIdStrategy! getDeviceIdStrategyEnum(); + method @Deprecated public int getEventsBufferSize(); + method public Set! getFeatures(); + method public int getFeaturesMap(); + method public ly.count.sdk.java.internal.LogCallback! getLogListener(); + method public ly.count.sdk.java.Config.LoggingLevel! getLoggingLevel(); + method @Deprecated public String! getLoggingTag(); + method @Deprecated public Class! getModuleOverride(int); + method @Deprecated public Class! getModuleOverride(ly.count.sdk.java.Config.Feature!); + method public int getNetworkConnectionTimeout(); + method public int getNetworkImportantRequestCooldown(); + method public int getNetworkReadTimeout(); + method public int getNetworkRequestCooldown(); + method public String! getParameterTamperingProtectionSalt(); + method public Set! getPublicKeyPins(); + method public int getRequestQueueMaxSize(); + method @Deprecated public String! getSdkName(); + method public String! getSdkPlatform(); + method @Deprecated public String! getSdkVersion(); + method public int getSendUpdateEachSeconds(); + method public String! getServerAppKey(); + method public URL! getServerURL(); + method public boolean isBackendModeEnabled(); + method @Deprecated public boolean isDeviceIdFallbackAllowed(); + method public boolean isFeatureEnabled(int); + method public boolean isFeatureEnabled(ly.count.sdk.java.Config.Feature!); + method public boolean isHTTPPostForced(); + method @Deprecated public boolean isTestModeEnabled(); + method @Deprecated protected ly.count.sdk.java.Config! overrideModule(Integer!, Class!); + method public ly.count.sdk.java.Config! remoteConfigRegisterGlobalCallback(ly.count.sdk.java.internal.RCDownloadCallback!); + method public boolean requiresConsent(); + method @Deprecated public ly.count.sdk.java.Config! setApplicationName(String!); + method public ly.count.sdk.java.Config! setApplicationVersion(String!); + method public ly.count.sdk.java.Config! setCrashProcessorClass(Class!); + method @Deprecated public ly.count.sdk.java.Config! setCrashReportingANRCheckingPeriod(int); + method public ly.count.sdk.java.Config! setCustomDeviceId(String!); + method @Deprecated public ly.count.sdk.java.Config! setDeviceIdFallbackAllowed(boolean); + method public ly.count.sdk.java.Config! setDeviceIdStrategy(ly.count.sdk.java.Config.DeviceIdStrategy!); + method public ly.count.sdk.java.Config! setDeviceIdStrategy(ly.count.sdk.java.Config.DeviceIdStrategy!, String!); + method public ly.count.sdk.java.Config! setEventQueueSizeToSend(int); + method @Deprecated public ly.count.sdk.java.Config! setEventsBufferSize(int); + method public ly.count.sdk.java.Config! setFeatures(ly.count.sdk.java.Config.Feature!...!); + method public ly.count.sdk.java.Config! setLocation(String!, String!, String!, String!); + method public ly.count.sdk.java.Config! setLogListener(ly.count.sdk.java.internal.LogCallback!); + method public ly.count.sdk.java.Config! setLoggingLevel(ly.count.sdk.java.Config.LoggingLevel!); + method @Deprecated public ly.count.sdk.java.Config! setLoggingTag(String!); + method public ly.count.sdk.java.Config! setMaxBreadcrumbCount(int); + method public ly.count.sdk.java.Config! setMaxKeyLength(int); + method public ly.count.sdk.java.Config! setMetricOverride(Map!); + method public ly.count.sdk.java.Config! setNetworkConnectTimeout(int); + method public ly.count.sdk.java.Config! setNetworkImportantRequestCooldown(int); + method public ly.count.sdk.java.Config! setNetworkReadTimeout(int); + method public ly.count.sdk.java.Config! setNetworkRequestCooldown(int); + method public ly.count.sdk.java.Config! setRequestQueueMaxSize(int); + method public ly.count.sdk.java.Config! setRequiresConsent(boolean); + method public ly.count.sdk.java.Config! setSdkBehaviorSettings(String!); + method @Deprecated public ly.count.sdk.java.Config! setSdkName(String!); + method public ly.count.sdk.java.Config! setSdkPlatform(String!); + method @Deprecated public ly.count.sdk.java.Config! setSdkVersion(String!); + method @Deprecated public ly.count.sdk.java.Config! setSendUpdateEachSeconds(int); + method public ly.count.sdk.java.Config! setUpdateSessionTimerDelay(int); + method @Deprecated public ly.count.sdk.java.Config! setUsePOST(boolean); + field protected String! applicationVersion; + field protected boolean autoSendUserProperties; + field protected boolean backoffMechanismEnabled; + field protected Set! certificatePins; + field protected String! city; + field protected ly.count.sdk.java.internal.Log! configLog; + field public ly.count.sdk.java.internal.ConfigContent! content; + field protected String! country; + field protected String! crashProcessorClass; + field protected String! customDeviceId; + field protected Map! customNetworkRequestHeaders; + field protected int deviceIdStrategy; + field protected boolean enableAutoEnrollFlag; + field protected boolean enableBackendMode; + field protected boolean enableRemoteConfigAutomaticDownloadTriggers; + field protected boolean enableRemoteConfigValueCaching; + field protected int eventQueueThreshold; + field protected int features; + field protected boolean forceHTTPPost; + field protected boolean healthCheckEnabled; + field protected String! ip; + field protected String! location; + field protected boolean locationEnabled; + field protected ly.count.sdk.java.internal.LogCallback! logListener; + field protected ly.count.sdk.java.Config.LoggingLevel! loggingLevel; + field protected int maxBreadcrumbCount; + field protected int maxKeyLength; + field protected final Map! metricOverride; + field protected Map!>! moduleOverrides; + field protected int networkConnectionTimeout; + field protected int networkImportantRequestCooldown; + field protected int networkReadTimeout; + field protected int networkRequestCooldown; + field protected Set! publicKeyPins; + field protected List! remoteConfigGlobalCallbacks; + field protected boolean requestCompressionEnabled; + field protected int requestQueueMaxSize; + field protected boolean requiresConsent; + field protected String! salt; + field protected String! sdkBehaviorSettings; + field protected boolean sdkBehaviorSettingsRequestsDisabled; + field protected String! sdkName; + field protected String! sdkPlatform; + field protected File! sdkStorageRootDirectory; + field protected String! sdkVersion; + field protected int sendUpdateEachSeconds; + field protected volatile String! serverAppKey; + field protected volatile URL! serverURL; + field protected boolean unhandledCrashReportingEnabled; + field public ly.count.sdk.java.internal.ConfigViews! views; + } + + public static final class Config.DID { + ctor public Config.DID(int, String!); + method public boolean equals(Object?); + method public int hashCode(); + method public String toString(); + field public static final int STRATEGY_CUSTOM = 10; // 0xa + field public static final int STRATEGY_UUID = 0; // 0x0 + field public String! id; + field public int strategy; + } + + public enum Config.DeviceIdStrategy { + method public static ly.count.sdk.java.Config.DeviceIdStrategy! fromIndex(int); + method public int getIndex(); + enum_constant public static final ly.count.sdk.java.Config.DeviceIdStrategy CUSTOM_ID; + enum_constant public static final ly.count.sdk.java.Config.DeviceIdStrategy UUID; + } + + public enum Config.Feature { + method public static ly.count.sdk.java.Config.Feature! byIndex(int); + method public int getIndex(); + enum_constant public static final ly.count.sdk.java.Config.Feature Content; + enum_constant public static final ly.count.sdk.java.Config.Feature CrashReporting; + enum_constant public static final ly.count.sdk.java.Config.Feature Events; + enum_constant public static final ly.count.sdk.java.Config.Feature Feedback; + enum_constant public static final ly.count.sdk.java.Config.Feature Location; + enum_constant public static final ly.count.sdk.java.Config.Feature RemoteConfig; + enum_constant public static final ly.count.sdk.java.Config.Feature Sessions; + enum_constant public static final ly.count.sdk.java.Config.Feature UserProfiles; + enum_constant public static final ly.count.sdk.java.Config.Feature Views; + } + + public enum Config.LoggingLevel { + method public int getLevel(); + method public boolean prints(ly.count.sdk.java.Config.LoggingLevel!); + enum_constant public static final ly.count.sdk.java.Config.LoggingLevel DEBUG; + enum_constant public static final ly.count.sdk.java.Config.LoggingLevel ERROR; + enum_constant public static final ly.count.sdk.java.Config.LoggingLevel INFO; + enum_constant public static final ly.count.sdk.java.Config.LoggingLevel OFF; + enum_constant public static final ly.count.sdk.java.Config.LoggingLevel VERBOSE; + enum_constant public static final ly.count.sdk.java.Config.LoggingLevel WARN; + } + + public class Countly implements ly.count.sdk.java.Usage { + ctor public Countly(); + ctor protected Countly(ly.count.sdk.java.internal.SDKCore!, ly.count.sdk.java.internal.Log!); + method public ly.count.sdk.java.Usage! addCrashReport(Throwable!, boolean); + method public ly.count.sdk.java.Usage! addCrashReport(Throwable!, boolean, String!, Map!, String!...!); + method public ly.count.sdk.java.Usage! addLocation(double, double); + method public ly.count.sdk.java.Usage! addParam(String!, Object!); + method public static ly.count.sdk.java.Usage! api(); + method public void attemptToSendStoredRequests(); + method public ly.count.sdk.java.internal.ModuleBackendMode.BackendMode! backendM(); + method @Deprecated public static ly.count.sdk.java.internal.ModuleBackendMode.BackendMode! backendMode(); + method public void changeAppKey(String!); + method @Deprecated public ly.count.sdk.java.Usage! changeDeviceIdWithMerge(String!); + method @Deprecated public ly.count.sdk.java.Usage! changeDeviceIdWithoutMerge(String!); + method public void changeServerUrl(String!); + method public ly.count.sdk.java.internal.ModuleContent.Content! content(); + method public ly.count.sdk.java.internal.ModuleCrashes.Crashes! crashes(); + method public ly.count.sdk.java.internal.ModuleDeviceIdCore.DeviceId! deviceId(); + method @Deprecated public ly.count.sdk.java.Event! event(String!); + method public ly.count.sdk.java.internal.ModuleEvents.Events! events(); + method public ly.count.sdk.java.internal.ModuleFeedback.Feedback! feedback(); + method public void flushQueues(); + method @Deprecated public String! getDeviceId(); + method public ly.count.sdk.java.internal.DeviceIdType! getDeviceIdType(); + method public void halt(); + method @Deprecated public static void init(File!, ly.count.sdk.java.Config!); + method public void init(ly.count.sdk.java.Config!); + method public static ly.count.sdk.java.Countly! instance(); + method public static boolean isInitialized(); + method public static boolean isTracking(ly.count.sdk.java.Config.Feature!); + method public ly.count.sdk.java.internal.ModuleLocation.Location! location(); + method public ly.count.sdk.java.Usage! login(String!); + method public ly.count.sdk.java.Usage! logout(); + method public static void onConsent(ly.count.sdk.java.Config.Feature!...!); + method public static void onConsentRemoval(ly.count.sdk.java.Config.Feature!...!); + method public ly.count.sdk.java.internal.ModuleRemoteConfig.RemoteConfig! remoteConfig(); + method public void removeDifferentAppKeysFromQueue(); + method public void replaceAllAppKeysInQueueWithCurrentAppKey(); + method public static ly.count.sdk.java.Session! session(); + method public void stop(); + method @Deprecated public static void stop(boolean); + method @Deprecated public ly.count.sdk.java.Event! timedEvent(String!); + method public ly.count.sdk.java.User! user(); + method public ly.count.sdk.java.internal.ModuleUserProfile.UserProfile! userProfile(); + method @Deprecated public ly.count.sdk.java.View! view(String!); + method @Deprecated public ly.count.sdk.java.View! view(String!, boolean); + method public ly.count.sdk.java.internal.ModuleViews.Views! views(); + field protected ly.count.sdk.java.internal.Log! L; + field public static final ly.count.sdk.java.internal.Device! device; + field protected ly.count.sdk.java.internal.SDKCore! sdk; + } + + public interface Crash { + method public ly.count.sdk.java.Crash! addException(Exception!); + method public ly.count.sdk.java.Crash! addThrowable(Throwable!); + method public ly.count.sdk.java.Crash! addTraces(Thread!, Map!); + method public List! getLogs(); + method public String! getName(); + method public Map! getSegments(); + method public Throwable! getThrowable(); + method public Map! getTraces(); + method public boolean isFatal(); + method public ly.count.sdk.java.Crash! setFatal(boolean); + method public ly.count.sdk.java.Crash! setLogs(String![]!); + method public ly.count.sdk.java.Crash! setName(String!); + method public ly.count.sdk.java.Crash! setSegments(Map!); + } + + public interface CrashProcessor { + method public ly.count.sdk.java.Crash! process(ly.count.sdk.java.Crash!); + } + + @Deprecated public interface Event { + method @Deprecated public ly.count.sdk.java.Event! addSegment(String, String); + method @Deprecated public ly.count.sdk.java.Event! addSegments(String!...); + method @Deprecated public void endAndRecord(); + method @Deprecated public boolean isInvalid(); + method @Deprecated public void record(); + method @Deprecated public ly.count.sdk.java.Event! setCount(int); + method @Deprecated public ly.count.sdk.java.Event! setDuration(double); + method @Deprecated public ly.count.sdk.java.Event! setSegmentation(Map); + method @Deprecated public ly.count.sdk.java.Event! setSum(double); + } + + public class PredefinedUserPropertyKeys { + ctor public PredefinedUserPropertyKeys(); + field public static final String BIRTH_YEAR = "byear"; + field public static final String EMAIL = "email"; + field public static final String GENDER = "gender"; + field public static final String NAME = "name"; + field public static final String ORGANIZATION = "organization"; + field public static final String PHONE = "phone"; + field public static final String PICTURE = "picture"; + field public static final String PICTURE_PATH = "picturePath"; + field public static final String USERNAME = "username"; + } + + public interface Session extends ly.count.sdk.java.Usage { + method public ly.count.sdk.java.Session! begin(); + method public void end(); + method public Long! getBegan(); + method public Long! getEnded(); + method public Long! getId(); + method public boolean isActive(); + method public ly.count.sdk.java.Session! update(); + } + + public interface Usage { + method @Deprecated public ly.count.sdk.java.Usage! addCrashReport(Throwable!, boolean); + method @Deprecated public ly.count.sdk.java.Usage! addCrashReport(Throwable!, boolean, String!, Map!, String!...!); + method @Deprecated public ly.count.sdk.java.Usage! addLocation(double, double); + method public ly.count.sdk.java.Usage! addParam(String!, Object!); + method @Deprecated public ly.count.sdk.java.Usage! changeDeviceIdWithMerge(String!); + method @Deprecated public ly.count.sdk.java.Usage! changeDeviceIdWithoutMerge(String!); + method @Deprecated public ly.count.sdk.java.Event! event(String!); + method @Deprecated public String! getDeviceId(); + method @Deprecated public ly.count.sdk.java.Usage! login(String!); + method @Deprecated public ly.count.sdk.java.Usage! logout(); + method @Deprecated public ly.count.sdk.java.Event! timedEvent(String!); + method public ly.count.sdk.java.User! user(); + method @Deprecated public ly.count.sdk.java.View! view(String!); + method @Deprecated public ly.count.sdk.java.View! view(String!, boolean); + } + + public abstract class User { + ctor public User(); + method public abstract Integer! birthyear(); + method public abstract String! city(); + method public abstract String! country(); + method public abstract Map! custom(); + method public abstract ly.count.sdk.java.UserEditor! edit(); + method public abstract String! email(); + method public abstract ly.count.sdk.java.User.Gender! gender(); + method public abstract String! locale(); + method public abstract String! location(); + method public abstract String! name(); + method public abstract String! org(); + method public abstract String! phone(); + method public abstract byte[]! picture(); + method public abstract String! picturePath(); + method public abstract String! username(); + } + + public enum User.Gender { + method public static ly.count.sdk.java.User.Gender! fromString(String!); + method public String toString(); + enum_constant public static final ly.count.sdk.java.User.Gender FEMALE; + enum_constant public static final ly.count.sdk.java.User.Gender MALE; + } + + @Deprecated public interface UserEditor { + method @Deprecated public ly.count.sdk.java.UserEditor! addToCohort(String!); + method @Deprecated public ly.count.sdk.java.User! commit(); + method @Deprecated public ly.count.sdk.java.UserEditor! inc(String!, int); + method @Deprecated public ly.count.sdk.java.UserEditor! max(String!, double); + method @Deprecated public ly.count.sdk.java.UserEditor! min(String!, double); + method @Deprecated public ly.count.sdk.java.UserEditor! mul(String!, double); + method @Deprecated public ly.count.sdk.java.UserEditor! optOutFromLocationServices(); + method @Deprecated public ly.count.sdk.java.UserEditor! pull(String!, Object!); + method @Deprecated public ly.count.sdk.java.UserEditor! push(String!, Object!); + method @Deprecated public ly.count.sdk.java.UserEditor! pushUnique(String!, Object!); + method @Deprecated public ly.count.sdk.java.UserEditor! removeFromCohort(String!); + method @Deprecated public ly.count.sdk.java.UserEditor! set(String!, Object!); + method @Deprecated public ly.count.sdk.java.UserEditor! setBirthyear(int); + method @Deprecated public ly.count.sdk.java.UserEditor! setBirthyear(String!); + method @Deprecated public ly.count.sdk.java.UserEditor! setCity(String!); + method @Deprecated public ly.count.sdk.java.UserEditor! setCountry(String!); + method @Deprecated public ly.count.sdk.java.UserEditor! setCustom(String!, Object!); + method @Deprecated public ly.count.sdk.java.UserEditor! setEmail(String!); + method @Deprecated public ly.count.sdk.java.UserEditor! setGender(Object!); + method @Deprecated public ly.count.sdk.java.UserEditor! setLocale(String!); + method @Deprecated public ly.count.sdk.java.UserEditor! setLocation(double, double); + method @Deprecated public ly.count.sdk.java.UserEditor! setLocation(String!); + method @Deprecated public ly.count.sdk.java.UserEditor! setName(String!); + method @Deprecated public ly.count.sdk.java.UserEditor! setOnce(String!, Object!); + method @Deprecated public ly.count.sdk.java.UserEditor! setOrg(String!); + method @Deprecated public ly.count.sdk.java.UserEditor! setPhone(String!); + method @Deprecated public ly.count.sdk.java.UserEditor! setPicture(byte[]!); + method @Deprecated public ly.count.sdk.java.UserEditor! setPicturePath(String!); + method @Deprecated public ly.count.sdk.java.UserEditor! setUsername(String!); + } + + public interface View { + method @Deprecated public void start(boolean); + method @Deprecated public void stop(boolean); + } + +} + +package ly.count.sdk.java.internal { + + public interface Byteable { + method public boolean restore(byte[]!, ly.count.sdk.java.internal.Log!); + method public byte[]! store(ly.count.sdk.java.internal.Log!); + } + + public interface CallbackOnFinish { + method public void onFinished(T, String!); + } + + 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; + } + + public class ConfigViews { + ctor public ConfigViews(ly.count.sdk.java.Config!); + method public ly.count.sdk.java.Config! setGlobalViewSegmentation(Map!); + field protected Map! globalViewSegmentation; + } + + public interface ConfigurationProvider { + method public default void blockRequestCompression(); + method public boolean getAutomaticCrashReportingEnabled(); + method public boolean getAutomaticSessionTrackingEnabled(); + method public boolean getAutomaticViewTrackingEnabled(); + method public int getBOMAcceptedTimeoutSeconds(); + method public int getBOMDuration(); + method public boolean getBOMEnabled(); + 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(); + method public boolean getCustomEventTrackingEnabled(); + method public ly.count.sdk.java.internal.ConfigurationProvider.FilterList!> getEventFilterList(); + method public int getEventQueueSizeThreshold(); + method public ly.count.sdk.java.internal.ConfigurationProvider.FilterList!>!> getEventSegmentationFilterList(); + method public Set getJourneyTriggerEvents(); + method public Set getJourneyTriggerViews(); + method public boolean getLocationTrackingEnabled(); + method public int getLogGatheringBatchSize(); + method public String? getLogGatheringId(); + method public String getLogGatheringLevels(); + method public ly.count.sdk.java.internal.ConfigurationProvider.LogGatheringState getLogGatheringState(); + method public boolean getLoggingEnabled(); + method public int getMaxBreadcrumbCount(); + method public int getMaxKeyLength(); + method public int getMaxSegmentationValues(); + method public int getMaxStackTraceLineLength(); + method public int getMaxStackTraceLinesPerThread(); + method public int getMaxValueSize(); + method public boolean getNetworkingEnabled(); + method public boolean getRefreshContentZoneEnabled(); + method public int getRequestDropAgeHours(); + method public int getRequestQueueMaxSize(); + method public ly.count.sdk.java.internal.ConfigurationProvider.FilterList!> getSegmentationFilterList(); + method public int getServerConfigUpdateInterval(); + method public boolean getSessionTrackingEnabled(); + method public int getSessionUpdateInterval(); + method public boolean getTrackingEnabled(); + method public int getUserPropertyCacheLimit(); + method public ly.count.sdk.java.internal.ConfigurationProvider.FilterList!> getUserPropertyFilterList(); + method public boolean getViewTrackingEnabled(); + method public default boolean isRequestCompressionAllowed(); + method public boolean isRequestQueueMaxSizeFromBehaviorSettings(); + } + + public static final class ConfigurationProvider.FilterList { + method public T getFilterList(); + method public boolean isWhitelist(); + method public String toString(); + } + + public enum ConfigurationProvider.LogGatheringState { + enum_constant public static final ly.count.sdk.java.internal.ConfigurationProvider.LogGatheringState GATHERING; + enum_constant public static final ly.count.sdk.java.internal.ConfigurationProvider.LogGatheringState NOT_GATHERING; + enum_constant public static final ly.count.sdk.java.internal.ConfigurationProvider.LogGatheringState UNDECIDED; + } + + public interface ContentCallback { + method public void onContentCallback(ly.count.sdk.java.internal.ContentStatus!, Map!); + } + + public interface ContentCloseCallback { + method public void onClosed(Map!); + } + + public class ContentData { + ctor public ContentData(String!, ly.count.sdk.java.internal.ContentPlacement!, ly.count.sdk.java.internal.ContentPlacement!); + method public ly.count.sdk.java.internal.ContentPlacement! placementFor(boolean); + method public String toString(); + field public final ly.count.sdk.java.internal.ContentPlacement! landscape; + field public final ly.count.sdk.java.internal.ContentPlacement! portrait; + field public final String! url; + } + + public interface ContentDisplay { + method public ly.count.sdk.java.internal.ContentScreen! getScreen(); + method public void present(ly.count.sdk.java.internal.ContentData!, ly.count.sdk.java.internal.ContentCloseCallback!); + } + + public class ContentPlacement { + ctor public ContentPlacement(int, int, int, int); + method public String toString(); + field public final int height; + field public final int width; + field public final int x; + field public final int y; + } + + public class ContentScreen { + ctor public ContentScreen(int, int); + method public String toString(); + field public final int height; + field public final int width; + } + + public enum ContentStatus { + enum_constant public static final ly.count.sdk.java.internal.ContentStatus CLOSED; + enum_constant public static final ly.count.sdk.java.internal.ContentStatus COMPLETED; + } + + public interface ContentUrlHandler { + method public boolean onContentUrl(String!); + } + + public enum CoreFeature { + method public ly.count.sdk.java.internal.ModuleBaseCreator! getCreator(); + method public int getIndex(); + enum_constant public static final ly.count.sdk.java.internal.CoreFeature BackendMode; + enum_constant public static final ly.count.sdk.java.internal.CoreFeature Content; + enum_constant public static final ly.count.sdk.java.internal.CoreFeature CrashReporting; + enum_constant public static final ly.count.sdk.java.internal.CoreFeature DeviceId; + enum_constant public static final ly.count.sdk.java.internal.CoreFeature Events; + enum_constant public static final ly.count.sdk.java.internal.CoreFeature Feedback; + enum_constant public static final ly.count.sdk.java.internal.CoreFeature Location; + enum_constant public static final ly.count.sdk.java.internal.CoreFeature Logs; + enum_constant public static final ly.count.sdk.java.internal.CoreFeature RemoteConfig; + enum_constant public static final ly.count.sdk.java.internal.CoreFeature Requests; + enum_constant public static final ly.count.sdk.java.internal.CoreFeature Sessions; + enum_constant public static final ly.count.sdk.java.internal.CoreFeature TestDummy; + enum_constant public static final ly.count.sdk.java.internal.CoreFeature UserProfiles; + enum_constant public static final ly.count.sdk.java.internal.CoreFeature Views; + } + + public class CountlyFeedbackWidget { + ctor public CountlyFeedbackWidget(); + method public boolean equals(Object?); + method public int hashCode(); + field public String! name; + field public String! position; + field public String![]! tags; + field public ly.count.sdk.java.internal.FeedbackWidgetType! type; + field public String! widgetId; + } + + public class CountlyTimer { + ctor protected CountlyTimer(ly.count.sdk.java.internal.Log!); + method protected void startTimer(long, long, Runnable!); + method protected void startTimer(long, Runnable!); + method protected void stopTimer(); + method protected void stopTimer(boolean); + field protected static int TIMER_DELAY_MS; + } + + public class CrashImpl implements ly.count.sdk.java.Crash ly.count.sdk.java.internal.Storable { + ctor protected CrashImpl(Long!, ly.count.sdk.java.internal.Log!); + ctor protected CrashImpl(ly.count.sdk.java.internal.Log!); + method protected ly.count.sdk.java.internal.CrashImpl! add(String!, Object!); + method public ly.count.sdk.java.internal.CrashImpl! addException(Exception!); + method protected ly.count.sdk.java.internal.CrashImpl! addSegments(Map!); + method public ly.count.sdk.java.internal.CrashImpl! addThrowable(Throwable!); + method public ly.count.sdk.java.internal.CrashImpl! addTraces(Thread!, Map!); + method public org.json.JSONObject! getData(); + method public String! getJSON(); + method public List! getLogs(); + method public String! getName(); + method public Map! getSegments(); + method public static String! getStoragePrefix(); + method public Throwable! getThrowable(); + method public Map! getTraces(); + method public boolean isFatal(); + method public ly.count.sdk.java.internal.CrashImpl! putMetrics(Long!); + method public boolean restore(byte[]!, ly.count.sdk.java.internal.Log!); + method public ly.count.sdk.java.internal.CrashImpl! setFatal(boolean); + method public void setId(Long!); + method public ly.count.sdk.java.internal.CrashImpl! setLogs(String![]!); + method public ly.count.sdk.java.internal.CrashImpl! setName(String!); + method public ly.count.sdk.java.internal.CrashImpl! setSegments(Map!); + method public Long! storageId(); + method public String! storagePrefix(); + method public byte[]! store(ly.count.sdk.java.internal.Log!); + method public String toString(); + } + + public class DefaultNetworking implements ly.count.sdk.java.internal.Networking { + ctor public DefaultNetworking(); + method public boolean check(ly.count.sdk.java.internal.InternalConfig!); + method public ly.count.sdk.java.internal.Transport! getTransport(); + method public void init(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.IStorageForRequestQueue!); + method public boolean isSending(); + method public void stop(ly.count.sdk.java.internal.InternalConfig!); + method protected ly.count.sdk.java.internal.Tasks.Task! submit(ly.count.sdk.java.internal.InternalConfig!, boolean); + } + + public class Device { + ctor protected Device(); + method public ly.count.sdk.java.internal.Params! buildMetrics(); + method public String! getAppVersion(); + method public Float! getBatteryLevel(); + method public String! getCpu(); + method public String! getDevice(); + method public Long! getDiskAvailable(); + method public Long! getDiskTotal(); + method public String! getLocale(); + method public String! getManufacturer(); + method public String! getOS(); + method public String! getOSVersion(); + method public String! getOpenGL(); + method public String! getOrientation(); + method public Long! getRAMAvailable(); + method public Long! getRAMTotal(); + method public String! getResolution(); + method public int getTimezoneOffset(); + method public Boolean! isMuted(); + method public Boolean! isOnline(); + method public ly.count.sdk.java.internal.Device! setAppVersion(String!); + method public ly.count.sdk.java.internal.Device! setBatteryLevel(Float!); + method public ly.count.sdk.java.internal.Device! setCpu(String!); + method public ly.count.sdk.java.internal.Device! setDevice(String!); + method public void setLog(ly.count.sdk.java.internal.Log!); + method public ly.count.sdk.java.internal.Device! setManufacturer(String!); + method public ly.count.sdk.java.internal.Device setMetricOverride(Map?); + method public ly.count.sdk.java.internal.Device! setMuted(Boolean!); + method public ly.count.sdk.java.internal.Device! setOnline(Boolean!); + method public ly.count.sdk.java.internal.Device! setOpenGL(String!); + method public ly.count.sdk.java.internal.Device! setOrientation(String!); + method public ly.count.sdk.java.internal.Device! setResolution(String!); + field protected static final Long BYTES_IN_MB; + field protected static final Double MS_IN_SECOND; + field protected static final Double NS_IN_MS; + field protected static final Double NS_IN_SECOND; + field public static ly.count.sdk.java.internal.Device! dev; + } + + public interface DeviceIdGenerator { + method public String! generate(ly.count.sdk.java.internal.InternalConfig!); + } + + public enum DeviceIdType { + method public static ly.count.sdk.java.internal.DeviceIdType! fromInt(int, ly.count.sdk.java.internal.Log!); + method public static int toInt(String!); + enum_constant public static final ly.count.sdk.java.internal.DeviceIdType DEVELOPER_SUPPLIED; + enum_constant public static final ly.count.sdk.java.internal.DeviceIdType SDK_GENERATED; + field public final int index; + } + + public class EventQueue { + ctor protected EventQueue(); + ctor protected EventQueue(ly.count.sdk.java.internal.Log, int); + method public void clear(); + method protected int eqSize(); + method protected List! getEQ(); + field protected final Object! lockEQ; + } + + public class FeedbackWidgetSelector { + method public static ly.count.sdk.java.internal.CountlyFeedbackWidget! select(List!, ly.count.sdk.java.internal.FeedbackWidgetType!, String!); + } + + public enum FeedbackWidgetType { + enum_constant public static final ly.count.sdk.java.internal.FeedbackWidgetType nps; + enum_constant public static final ly.count.sdk.java.internal.FeedbackWidgetType rating; + enum_constant public static final ly.count.sdk.java.internal.FeedbackWidgetType survey; + } + + public class HealthCheckCounter { + ctor public HealthCheckCounter(ly.count.sdk.java.internal.StorageProvider, ly.count.sdk.java.internal.Log, Predicate); + } + + public interface IStorageForRequestQueue { + method public ly.count.sdk.java.internal.Request! getNextRequest(); + method public Integer! remaningRequests(); + method public Boolean! removeRequest(ly.count.sdk.java.internal.Request!); + } + + public interface IdGenerator { + method public String generateId(); + } + + public interface ImmediateRequestGenerator { + method public ly.count.sdk.java.internal.ImmediateRequestI! createImmediateRequestMaker(); + } + + public interface ImmediateRequestI { + method public void doWork(String!, String!, ly.count.sdk.java.internal.Transport!, boolean, boolean, ly.count.sdk.java.internal.ImmediateRequestMaker.InternalImmediateRequestCallback!, ly.count.sdk.java.internal.Log!); + } + + public class InternalConfig extends ly.count.sdk.java.Config { + ctor public InternalConfig(); + ctor public InternalConfig(ly.count.sdk.java.Config!); + ctor public InternalConfig(String!, String!); + method public ly.count.sdk.java.Config.DID! getDeviceId(); + method public int getFeatures1(); + method public Map! getMetricOverride(); + method public Set! getModuleOverrides(); + method public boolean getNetworkingEnabled(); + method public List! getRemoteConfigGlobalCallbackList(); + method protected String! getSDKNameInternal(); + method public String! getSdkBehaviorSettings(); + method public static String! getStoragePrefix(); + method public boolean isAutoEnrollFlagEnabled(); + method public boolean isDefaultNetworking(); + method public boolean isRemoteConfigAutomaticDownloadTriggersEnabled(); + method public boolean isRemoteConfigValueCachingEnabled(); + method public boolean isSdkBehaviorSettingsRequestsDisabled(); + method public boolean isTemporaryIdEnabled(); + method public boolean removeDeviceId(ly.count.sdk.java.Config.DID!); + method public boolean removeDeviceId(String!); + method public void setDefaultNetworking(boolean); + method public ly.count.sdk.java.Config.DID! setDeviceId(ly.count.sdk.java.Config.DID!); + method public void setFrom(ly.count.sdk.java.Config!); + method public void setLogger(ly.count.sdk.java.internal.Log!); + method public static Long! storageId(); + field protected ly.count.sdk.java.internal.IdGenerator! eventIdGenerator; + field public ly.count.sdk.java.internal.SDKCore! sdk; + field public ly.count.sdk.java.internal.StorageProvider! storageProvider; + field protected ly.count.sdk.java.internal.IdGenerator! viewIdGenerator; + field protected ly.count.sdk.java.internal.ViewIdProvider! viewIdProvider; + } + + public interface JSONable { + method public String! toJSON(ly.count.sdk.java.internal.Log!); + } + + public class JsonFileStorage { + ctor public JsonFileStorage(File, ly.count.sdk.java.internal.Log); + method public void add(String, Object); + method public void addAndSave(String, Object); + method public void clear(); + method public void clearAndSave(); + method public void delete(String); + method public void deleteAndSave(String); + method public Object! get(String); + method public int getInt(String, int); + method public org.json.JSONObject! getJsonObj(String, org.json.JSONObject!); + method public String! getString(String); + method public String! getString(String, String!); + method public void save(); + method public int size(); + } + + public class Log { + ctor public Log(ly.count.sdk.java.Config.LoggingLevel!, ly.count.sdk.java.internal.LogCallback!); + method public void d(String!); + method public void e(String!); + method public void i(String!); + method public void recordLogCode(String); + method public void recordLogCode(String, int); + method public void recordLogCode(String, String); + method public static void recordLogCodeWhileNotInitialized(String); + method public void recordUsage(String, String); + method public void v(String!); + method public void w(String!); + } + + public interface LogCallback { + method public void LogHappened(String!, ly.count.sdk.java.Config.LoggingLevel!); + } + + public class MigrationHelper { + ctor protected MigrationHelper(ly.count.sdk.java.internal.Log!); + method protected void applyMigrations(Map!); + method protected boolean migration_DeleteConfigFile_01(Map!); + method protected boolean migration_UserImplFile_02(Map!); + method protected void setupMigrations(ly.count.sdk.java.internal.StorageProvider!); + field protected int currentDataModelVersion; + field protected ly.count.sdk.java.internal.Log! logger; + } + + public class ModuleBackendMode extends ly.count.sdk.java.internal.ModuleBase { + ctor public ModuleBackendMode(); + method public void disableModule(); + method public void recordExceptionInternal(String!, String!, String!, Map!, Map!, Long!); + method protected Map! removeInvalidDataFromSegments(Map!); + field protected boolean disabledModule; + field protected int eventQSize; + field protected final Map! eventQueues; + field protected ly.count.sdk.java.internal.InternalConfig! internalConfig; + } + + public class ModuleBackendMode.BackendMode { + ctor public ModuleBackendMode.BackendMode(); + method protected ly.count.sdk.java.internal.ModuleBase! getModule(); + method public int getQueueSize(); + method public void recordDirectRequest(String!, Map!, Long!); + method public void recordEvent(String!, String!, int, Double!, Double!, Map!, Long!); + method public void recordException(String!, String!, String!, Map!, Map!, Long!); + method public void recordException(String!, Throwable!, Map!, Map!, Long!); + method public void recordUserProperties(String!, Map!, Long!); + method public void recordView(String!, String!, Map!, Long!); + method public void sessionBegin(String!, Map!, Map!, Long!); + method public void sessionEnd(String!, double, Long!); + method public void sessionUpdate(String!, double, Long!); + } + + public abstract class ModuleBase { + ctor public ModuleBase(); + method protected void deviceIdChanged(String!, boolean); + method public void init(ly.count.sdk.java.internal.InternalConfig!); + method protected void initFinished(ly.count.sdk.java.internal.InternalConfig!); + method public boolean isActive(); + method public Boolean! onRequest(ly.count.sdk.java.internal.Request!); + method public void onRequestCompleted(ly.count.sdk.java.internal.Request!, String!, int); + method protected void onSdkConfigurationChanged(ly.count.sdk.java.internal.InternalConfig!); + method public void onSessionBegan(ly.count.sdk.java.Session!, ly.count.sdk.java.internal.InternalConfig!); + method public void onSessionEnded(ly.count.sdk.java.Session!, ly.count.sdk.java.internal.InternalConfig!); + method protected void onTimer(); + method public void setActive(boolean); + method public void stop(ly.count.sdk.java.internal.InternalConfig!, boolean); + field protected ly.count.sdk.java.internal.Log! L; + } + + public interface ModuleBaseCreator { + method public ly.count.sdk.java.internal.ModuleBase! create(); + } + + public class ModuleConfiguration extends ly.count.sdk.java.internal.ModuleBase implements ly.count.sdk.java.internal.ConfigurationProvider { + ctor public ModuleConfiguration(); + method public boolean getAutomaticCrashReportingEnabled(); + method public boolean getAutomaticSessionTrackingEnabled(); + method public boolean getAutomaticViewTrackingEnabled(); + method public int getBOMAcceptedTimeoutSeconds(); + method public int getBOMDuration(); + method public boolean getBOMEnabled(); + 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(); + method public boolean getCustomEventTrackingEnabled(); + method public ly.count.sdk.java.internal.ConfigurationProvider.FilterList!> getEventFilterList(); + method public int getEventQueueSizeThreshold(); + method public ly.count.sdk.java.internal.ConfigurationProvider.FilterList!>!> getEventSegmentationFilterList(); + method public Set getJourneyTriggerEvents(); + method public Set getJourneyTriggerViews(); + method public boolean getLocationTrackingEnabled(); + method public int getLogGatheringBatchSize(); + method public String? getLogGatheringId(); + method public String getLogGatheringLevels(); + method public ly.count.sdk.java.internal.ConfigurationProvider.LogGatheringState getLogGatheringState(); + method public boolean getLoggingEnabled(); + method public int getMaxBreadcrumbCount(); + method public int getMaxKeyLength(); + method public int getMaxSegmentationValues(); + method public int getMaxStackTraceLineLength(); + method public int getMaxStackTraceLinesPerThread(); + method public int getMaxValueSize(); + method public boolean getNetworkingEnabled(); + method public boolean getRefreshContentZoneEnabled(); + method public int getRequestDropAgeHours(); + method public int getRequestQueueMaxSize(); + method public ly.count.sdk.java.internal.ConfigurationProvider.FilterList!> getSegmentationFilterList(); + method public int getServerConfigUpdateInterval(); + method public boolean getSessionTrackingEnabled(); + method public int getSessionUpdateInterval(); + method public boolean getTrackingEnabled(); + method public int getUserPropertyCacheLimit(); + method public ly.count.sdk.java.internal.ConfigurationProvider.FilterList!> getUserPropertyFilterList(); + method public boolean getViewTrackingEnabled(); + method public void initFinished(ly.count.sdk.java.internal.InternalConfig); + method public boolean isRequestQueueMaxSizeFromBehaviorSettings(); + } + + public class ModuleContent extends ly.count.sdk.java.internal.ModuleBase { + } + + public class ModuleContent.Content { + ctor public ModuleContent.Content(); + method public void enterContentZone(); + method public void exitContentZone(); + method public void previewContent(String?); + method public void recordContentEvents(String?); + method public void refreshContentZone(); + method public void setContentDisplay(ly.count.sdk.java.internal.ContentDisplay?); + } + + public class ModuleCrashes extends ly.count.sdk.java.internal.ModuleBase { + ctor public ModuleCrashes(); + method protected void addBreadcrumbInternal(String!); + method public void initFinished(ly.count.sdk.java.internal.InternalConfig!); + method public ly.count.sdk.java.internal.CrashImpl! onCrash(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.CrashImpl!); + method protected boolean recordExceptionInternal(Throwable!, boolean, Map!, String!); + field protected ly.count.sdk.java.internal.InternalConfig! config; + field protected ly.count.sdk.java.CrashProcessor! crashProcessor; + field protected final List! logs; + field protected long started; + } + + public class ModuleCrashes.Crashes { + ctor public ModuleCrashes.Crashes(); + method public void addCrashBreadcrumb(String!); + method public void recordHandledException(Throwable!); + method public void recordHandledException(Throwable!, Map!); + method public void recordUnhandledException(Throwable!); + method public void recordUnhandledException(Throwable!, Map!); + } + + public class ModuleDeviceIdCore extends ly.count.sdk.java.internal.ModuleBase { + ctor public ModuleDeviceIdCore(); + method protected ly.count.sdk.java.Config.DID! acquireId(); + method protected void changeDeviceIdInternal(String!, ly.count.sdk.java.internal.DeviceIdType!, boolean); + method public void deviceIdChanged(String!, boolean); + method protected String! getIDInternal(); + method protected ly.count.sdk.java.internal.DeviceIdType! getTypeInternal(); + method public void init(ly.count.sdk.java.internal.InternalConfig!); + method public void initFinished(ly.count.sdk.java.internal.InternalConfig!); + method public void login(String!); + method public void logout(); + field protected ly.count.sdk.java.internal.ModuleDeviceIdCore.DeviceId! deviceIdInterface; + } + + public class ModuleDeviceIdCore.DeviceId { + ctor public ModuleDeviceIdCore.DeviceId(); + method public void changeWithMerge(String!); + method public void changeWithoutMerge(String!); + method public String! getID(); + method public ly.count.sdk.java.internal.DeviceIdType! getType(); + method public void setID(String!); + } + + public class ModuleEvents extends ly.count.sdk.java.internal.ModuleBase { + ctor public ModuleEvents(); + method public void deviceIdChanged(String!, boolean); + method protected void recordEventInternal(String!, int, Double!, Double!, Map!, String!); + field protected ly.count.sdk.java.internal.EventQueue! eventQueue; + field protected ly.count.sdk.java.internal.ModuleEvents.Events! eventsInterface; + } + + public class ModuleEvents.Events { + ctor public ModuleEvents.Events(); + method public boolean cancelEvent(String!); + method public boolean endEvent(String!); + method public boolean endEvent(String!, Map!, int, Double!); + method public void recordEvent(String!); + method public void recordEvent(String!, int); + method public void recordEvent(String!, int, Double!); + method public void recordEvent(String!, Map!); + method public void recordEvent(String!, Map!, int); + method public void recordEvent(String!, Map!, int, Double!); + method public void recordEvent(String!, Map!, int, Double!, Double!); + method public boolean startEvent(String!); + } + + public class ModuleFeedback extends ly.count.sdk.java.internal.ModuleBase { + } + + public class ModuleFeedback.Feedback { + ctor public ModuleFeedback.Feedback(); + method public String! constructFeedbackWidgetUrl(ly.count.sdk.java.internal.CountlyFeedbackWidget?); + method public String! constructFeedbackWidgetUrl(ly.count.sdk.java.internal.CountlyFeedbackWidget?, int, int); + method public void getAvailableFeedbackWidgets(ly.count.sdk.java.internal.CallbackOnFinish!>?); + method public void getFeedbackWidgetData(ly.count.sdk.java.internal.CountlyFeedbackWidget?, ly.count.sdk.java.internal.CallbackOnFinish?); + method public void reportFeedbackWidgetManually(ly.count.sdk.java.internal.CountlyFeedbackWidget?, org.json.JSONObject?, Map?); + } + + public class ModuleHealthCheck extends ly.count.sdk.java.internal.ModuleBase { + ctor public ModuleHealthCheck(); + } + + public class ModuleLocation extends ly.count.sdk.java.internal.ModuleBase { + method public void initFinished(ly.count.sdk.java.internal.InternalConfig); + method protected void saveLocationToParamsLegacy(ly.count.sdk.java.internal.Params!); + method protected void setLocationLegacy(Object?, Object?, Object?); + } + + public class ModuleLocation.Location { + ctor public ModuleLocation.Location(); + method public void disableLocation(); + method public void setLocation(String?, String?, String?, String?); + } + + public class ModuleRemoteConfig extends ly.count.sdk.java.internal.ModuleBase { + method public void initFinished(ly.count.sdk.java.internal.InternalConfig); + } + + public class ModuleRemoteConfig.RemoteConfig { + ctor public ModuleRemoteConfig.RemoteConfig(); + method public void clearAll(); + method public void downloadAllKeys(ly.count.sdk.java.internal.RCDownloadCallback?); + method public void downloadOmittingKeys(String![]?, ly.count.sdk.java.internal.RCDownloadCallback?); + method public void downloadSpecificKeys(String![]?, ly.count.sdk.java.internal.RCDownloadCallback?); + method public void enrollIntoABTestsForKeys(String![]?); + method public void exitABTestsForKeys(String![]?); + method public Map getAllValuesAndEnroll(); + method public ly.count.sdk.java.internal.RCData getValue(String?); + method public ly.count.sdk.java.internal.RCData getValueAndEnroll(String?); + method public Map getValues(); + method public void registerDownloadCallback(ly.count.sdk.java.internal.RCDownloadCallback?); + method public void removeDownloadCallback(ly.count.sdk.java.internal.RCDownloadCallback?); + } + + public class ModuleRequests extends ly.count.sdk.java.internal.ModuleBase { + ctor public ModuleRequests(); + method public static Future! changeId(ly.count.sdk.java.internal.InternalConfig!, String!); + method public void initFinished(ly.count.sdk.java.internal.InternalConfig!); + method public static void injectParams(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.ModuleRequests.ParamsInjector!); + method public static Future! location(ly.count.sdk.java.internal.InternalConfig!, double, double); + method public static ly.count.sdk.java.internal.Request! nonSessionRequest(ly.count.sdk.java.internal.InternalConfig!); + method public static ly.count.sdk.java.internal.Params! prepareRequiredParams(ly.count.sdk.java.internal.InternalConfig!); + method public static String! prepareRequiredParamsAsString(ly.count.sdk.java.internal.InternalConfig!, Object!...!); + method public static Future! pushAsync(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.Request!); + method public static Future! pushAsync(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.Request!, boolean, ly.count.sdk.java.internal.Tasks.Callback!); + method public static Future! sessionBegin(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.SessionImpl!); + method public static Future! sessionEnd(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.SessionImpl!, Long!, String!, ly.count.sdk.java.internal.Tasks.Callback!); + method public static Future! sessionUpdate(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.SessionImpl!, Long!); + } + + public static interface ModuleRequests.ParamsInjector { + method public void call(ly.count.sdk.java.internal.Params!); + } + + public class ModuleSessions extends ly.count.sdk.java.internal.ModuleBase { + ctor public ModuleSessions(); + method public void deviceIdChanged(String!, boolean); + method public void forgetSession(); + method public ly.count.sdk.java.internal.SessionImpl! getSession(); + method public void initFinished(ly.count.sdk.java.internal.InternalConfig!); + method public ly.count.sdk.java.internal.SessionImpl! session(ly.count.sdk.java.internal.InternalConfig!, Long!); + method public ly.count.sdk.java.internal.TimedEvents! timedEvents(); + } + + public class ModuleUserProfile extends ly.count.sdk.java.internal.ModuleBase { + method protected void clearInternal(); + method public void deviceIdChanged(String!, boolean); + method public void initFinished(ly.count.sdk.java.internal.InternalConfig!); + method protected void saveInternal(); + method protected void setPropertiesInternal(Map); + } + + public class ModuleUserProfile.UserProfile { + ctor public ModuleUserProfile.UserProfile(); + method public void clear(); + method public void increment(String!); + method public void incrementBy(String!, int); + method public void multiply(String!, double); + method public void pull(String!, Object!); + method public void push(String!, Object!); + method public void pushUnique(String!, Object!); + method public void save(); + method public void saveMax(String!, double); + method public void saveMin(String!, double); + method public void setOnce(String!, Object!); + method public void setProperties(Map!); + method public void setProperty(String!, Object!); + } + + public class ModuleViews extends ly.count.sdk.java.internal.ModuleBase implements ly.count.sdk.java.internal.ViewIdProvider { + method public void deviceIdChanged(String!, boolean); + method public String getCurrentViewId(); + method public String getPreviousViewId(); + method protected void setFirstViewInternal(boolean); + method public void updateGlobalViewSegmentationInternal(Map); + } + + public class ModuleViews.Views { + ctor public ModuleViews.Views(); + method public void addSegmentationToViewWithID(String, Map?); + method public void addSegmentationToViewWithName(String, Map?); + method public void pauseViewWithID(String); + method public void resumeViewWithID(String); + method public void setGlobalViewSegmentation(Map?); + method public String! startAutoStoppedView(String); + method public String! startAutoStoppedView(String, Map?); + method public String? startView(String); + method public String? startView(String, Map?); + method public void stopAllViews(Map?); + method public void stopViewWithID(String); + method public void stopViewWithID(String, Map?); + method public void stopViewWithName(String); + method public void stopViewWithName(String, Map?); + method public void updateGlobalViewSegmentation(Map?); + } + + public interface Networking { + method public boolean check(ly.count.sdk.java.internal.InternalConfig!); + method public ly.count.sdk.java.internal.Transport! getTransport(); + method public void init(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.IStorageForRequestQueue!); + method public boolean isSending(); + method public void stop(ly.count.sdk.java.internal.InternalConfig!); + } + + public class Params { + ctor public Params(); + ctor public Params(Object!...!); + ctor public Params(String!); + method public ly.count.sdk.java.internal.Params! add(ly.count.sdk.java.internal.Params!); + method public ly.count.sdk.java.internal.Params! add(Object!...!); + method public ly.count.sdk.java.internal.Params! add(String!); + method public ly.count.sdk.java.internal.Params! add(String!, Object!); + method public ly.count.sdk.java.internal.Params.Arr! arr(String!); + method public void clear(); + method public boolean equals(Object?); + method public String! get(String!); + method public boolean has(String!); + method public int hashCode(); + method public int length(); + method public Map! map(); + method public ly.count.sdk.java.internal.Params.Obj! obj(String!); + method public String! remove(String!); + method public String toString(); + } + + public static final class Params.Arr { + method public ly.count.sdk.java.internal.Params! add(); + method public ly.count.sdk.java.internal.Params.Arr! put(Collection!); + method public ly.count.sdk.java.internal.Params.Arr! put(ly.count.sdk.java.internal.JSONable!); + } + + public static final class Params.Obj { + method public ly.count.sdk.java.internal.Params! add(); + method public ly.count.sdk.java.internal.Params.Obj! put(String!, Object!); + } + + public class RCData { + ctor public RCData(Object!, boolean); + field public boolean isCurrentUsersData; + field public Object! value; + } + + public interface RCDownloadCallback { + method public void callback(ly.count.sdk.java.internal.RequestResult!, String!, boolean, Map!); + } + + public class RemoteConfigValueStore { + ctor protected RemoteConfigValueStore(org.json.JSONObject, boolean, ly.count.sdk.java.internal.Log); + method protected void cacheClearValues(); + method protected Map getAllValues(); + method protected ly.count.sdk.java.internal.RCData getValue(String); + method protected void mergeValues(Map, boolean); + field protected ly.count.sdk.java.internal.Log! L; + field protected static final int cacheValCached = 0; // 0x0 + field protected static final int cacheValFresh = 1; // 0x1 + field protected static final String keyCacheFlag = "c"; + field protected static final String keyValue = "v"; + field protected org.json.JSONObject! values; + field protected boolean valuesCanBeCached; + } + + public class Request implements ly.count.sdk.java.internal.Storable { + ctor public Request(Long!); + ctor public Request(Object!...!); + method public ly.count.sdk.java.internal.Request! endpoint(String!); + method public boolean equals(Object?); + method public static String! getStoragePrefix(); + method public int hashCode(); + method public ly.count.sdk.java.internal.Request! own(Class!); + method public Class! owner(); + method public boolean restore(byte[]!, ly.count.sdk.java.internal.Log!); + method public void setId(Long!); + method public Long! storageId(); + method public String! storagePrefix(); + method public byte[]! store(ly.count.sdk.java.internal.Log!); + method public String toString(); + field public static final String ENDPOINT = "endpoint"; + field public static final String MODULE = "module"; + field public ly.count.sdk.java.internal.Params! params; + } + + public enum RequestResult { + enum_constant public static final ly.count.sdk.java.internal.RequestResult Error; + enum_constant public static final ly.count.sdk.java.internal.RequestResult NetworkIssue; + enum_constant public static final ly.count.sdk.java.internal.RequestResult Success; + } + + public class SDKCore { + ctor public SDKCore(); + method public void attemptToSendStoredRequests(); + method protected void buildModules(ly.count.sdk.java.internal.InternalConfig!, int); + method public void changeAppKey(String?); + method @Deprecated public void changeDeviceIdWithMerge(ly.count.sdk.java.internal.InternalConfig!, String!); + method @Deprecated public void changeDeviceIdWithoutMerge(ly.count.sdk.java.internal.InternalConfig!, String!); + method public void changeServerUrl(String?); + method public ly.count.sdk.java.internal.InternalConfig! config(); + method public ly.count.sdk.java.internal.ModuleContent.Content! content(); + method public static ly.count.sdk.java.internal.ContentUrlHandler! contentUrlHandler(); + method public ly.count.sdk.java.internal.ModuleCrashes.Crashes! crashes(); + method public ly.count.sdk.java.internal.ModuleDeviceIdCore.DeviceId! deviceId(); + method public static boolean enabled(int); + method public static boolean enabled(ly.count.sdk.java.internal.CoreFeature!); + method public ly.count.sdk.java.internal.ModuleEvents.Events! events(); + method public ly.count.sdk.java.internal.ModuleFeedback.Feedback! feedback(); + method public void flushQueues(); + method public ly.count.sdk.java.internal.SessionImpl! getSession(); + method public void halt(); + method public boolean hasConsentForFeature(ly.count.sdk.java.internal.CoreFeature!); + method public void init(ly.count.sdk.java.internal.InternalConfig!); + method public Boolean! isRequestReady(ly.count.sdk.java.internal.Request!); + method public boolean isTracking(Integer!); + method public ly.count.sdk.java.internal.ModuleLocation.Location! location(); + method public static ly.count.sdk.java.internal.Log! logger(); + method public void login(String!); + method public void logout(); + method public T module(Class!); + method protected ly.count.sdk.java.internal.ModuleBase! module(ly.count.sdk.java.internal.CoreFeature!); + method public void notifyModulesDeviceIdChanged(String?, boolean); + method public void onConsent(int); + method public void onConsentRemoval(ly.count.sdk.java.internal.InternalConfig!, int); + method public void onRequest(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.Request!); + method public void onRequestCompleted(ly.count.sdk.java.internal.Request!, String!, int, Class!); + method public ly.count.sdk.java.internal.SessionImpl! onSessionBegan(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.SessionImpl!); + method public ly.count.sdk.java.internal.SessionImpl! onSessionEnded(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.SessionImpl!); + method public void onSignal(ly.count.sdk.java.internal.InternalConfig!, int); + method public void onSignal(ly.count.sdk.java.internal.InternalConfig!, int, String!); + method protected void prepareMappings(); + method protected void recover(ly.count.sdk.java.internal.InternalConfig!); + method protected static void registerDefaultModuleMappings(); + method public ly.count.sdk.java.internal.ModuleRemoteConfig.RemoteConfig! remoteConfig(); + method public void removeDifferentAppKeysFromQueue(); + method public void replaceAllAppKeysInQueueWithCurrentAppKey(); + method public static File! sdkStorageDirectory(); + method public ly.count.sdk.java.internal.SessionImpl! session(Long!); + method protected void setDeviceIdFromStorageIfExist(ly.count.sdk.java.internal.InternalConfig!); + method @Deprecated public void stop(boolean); + method public ly.count.sdk.java.internal.UserImpl! user(); + method public ly.count.sdk.java.internal.ModuleUserProfile.UserProfile! userProfile(); + method public ly.count.sdk.java.internal.ModuleViews.Views! views(); + field protected ly.count.sdk.java.internal.Log! L; + field public ly.count.sdk.java.internal.InternalConfig! config; + field protected volatile int consents; + field public static final ly.count.sdk.java.internal.ModuleContent.Content! dormantContent; + field public static final ly.count.sdk.java.internal.ModuleCrashes.Crashes! dormantCrashes; + field public static final ly.count.sdk.java.internal.ModuleDeviceIdCore.DeviceId! dormantDeviceId; + field public static final ly.count.sdk.java.internal.ModuleEvents.Events! dormantEvents; + field public static final ly.count.sdk.java.internal.ModuleFeedback.Feedback! dormantFeedback; + field public static final ly.count.sdk.java.internal.ModuleLocation.Location! dormantLocation; + field public static final ly.count.sdk.java.internal.ModuleRemoteConfig.RemoteConfig! dormantRemoteConfig; + field public static final ly.count.sdk.java.internal.ModuleUserProfile.UserProfile! dormantUserProfile; + field public static final ly.count.sdk.java.internal.ModuleViews.Views! dormantViews; + field protected static ly.count.sdk.java.internal.SDKCore! instance; + field protected final Object! lockBRQStorage; + field protected final Map! modules; + field protected ly.count.sdk.java.internal.Networking! networking; + field protected Queue! requestQueueMemory; + field protected final ly.count.sdk.java.internal.SDKStorage! sdkStorage; + field protected static ly.count.sdk.java.internal.ModuleBase! testDummyModule; + } + + public enum SDKCore.Signal { + method public int getIndex(); + enum_constant public static final ly.count.sdk.java.internal.SDKCore.Signal Crash; + enum_constant public static final ly.count.sdk.java.internal.SDKCore.Signal DID; + enum_constant public static final ly.count.sdk.java.internal.SDKCore.Signal Ping; + enum_constant public static final ly.count.sdk.java.internal.SDKCore.Signal Start; + } + + 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(); + method public Integer! getMigrationVersion(); + method public org.json.JSONObject! getRemoteConfigValues(); + method public String! getServerConfig(); + method public void incrementAutomaticCrashCount(); + 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!); + method public void setMigrationVersion(Integer!); + method public void setRemoteConfigValues(org.json.JSONObject!); + method public void setServerConfig(String!); + method public void stop(ly.count.sdk.java.internal.InternalConfig!, boolean); + method public List! storableList(ly.count.sdk.java.internal.InternalConfig!, String!, int); + method public Boolean! storablePop(ly.count.sdk.java.internal.InternalConfig!, T); + method public int storablePurge(ly.count.sdk.java.internal.InternalConfig!, String!); + method public Boolean! storableRead(ly.count.sdk.java.internal.InternalConfig!, T); + method public byte[]! storableReadBytes(ly.count.sdk.java.internal.InternalConfig!, String!); + method public byte[]! storableReadBytes(ly.count.sdk.java.internal.InternalConfig!, String!, Long!); + method public Map.Entry! storableReadBytesOneOf(ly.count.sdk.java.internal.InternalConfig!, T, boolean); + method public Boolean! storableRemove(ly.count.sdk.java.internal.InternalConfig!, T); + method public Boolean! storableWrite(ly.count.sdk.java.internal.InternalConfig!, String!, Long!, byte[]!); + method public Boolean! storableWrite(ly.count.sdk.java.internal.InternalConfig!, T); + method protected void storeEventQueue(String!); + method public int takeAutomaticCrashCount(); + field protected static final String EVENT_QUEUE_FILE_NAME = "event_queue"; + 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"; + field protected static final String key_health_check_automatic_crashes = "HEALTH_CHECK_AUTOMATIC_CRASHES"; + field protected static final String key_migration_version = "dv"; + field protected static final String key_remote_config = "rc"; + field protected static final String key_server_config = "sc"; + } + + public class SessionImpl implements ly.count.sdk.java.Session ly.count.sdk.java.internal.Storable { + ctor protected SessionImpl(ly.count.sdk.java.internal.InternalConfig!); + ctor public SessionImpl(ly.count.sdk.java.internal.InternalConfig!, Long!); + method public ly.count.sdk.java.Session! addCrashReport(Throwable!, boolean); + method public ly.count.sdk.java.Session! addCrashReport(Throwable!, boolean, String!, Map!, String!...!); + method public ly.count.sdk.java.Session! addLocation(double, double); + method public ly.count.sdk.java.Session! addParam(String!, Object!); + method public ly.count.sdk.java.Session! begin(); + method @Deprecated public ly.count.sdk.java.Usage! changeDeviceIdWithMerge(String!); + method @Deprecated public ly.count.sdk.java.Usage! changeDeviceIdWithoutMerge(String!); + method public void end(); + method public boolean equals(Object?); + method public ly.count.sdk.java.Event! event(String!); + method public Long! getBegan(); + method @Deprecated public String! getDeviceId(); + method public Long! getEnded(); + method public Long! getId(); + method public static String! getStoragePrefix(); + method public int hashCode(); + method public boolean isActive(); + method public ly.count.sdk.java.Usage! login(String!); + method public ly.count.sdk.java.Usage! logout(); + method @Deprecated public void recordEvent(ly.count.sdk.java.Event!); + method public boolean restore(byte[]!, ly.count.sdk.java.internal.Log!); + method public void setId(Long!); + method public Long! storageId(); + method public String! storagePrefix(); + method public byte[]! store(ly.count.sdk.java.internal.Log!); + method @Deprecated public ly.count.sdk.java.Event! timedEvent(String!); + method @Deprecated protected ly.count.sdk.java.internal.TimedEvents! timedEvents(); + method public String toString(); + method public ly.count.sdk.java.Session! update(); + method public ly.count.sdk.java.User! user(); + method @Deprecated public ly.count.sdk.java.View! view(String!); + method @Deprecated public ly.count.sdk.java.View! view(String!, boolean); + field protected ly.count.sdk.java.internal.Log! L; + field protected Long! began; + field protected ly.count.sdk.java.View! currentView; + field protected Long! ended; + field protected final List! events; + field protected Long! id; + field protected final ly.count.sdk.java.internal.Params! params; + field protected boolean startView; + field protected Long! updated; + } + + public interface Storable extends ly.count.sdk.java.internal.Byteable { + method public void setId(Long!); + method public Long! storageId(); + method public String! storagePrefix(); + } + + public class Storage { + ctor public Storage(); + method public static void await(ly.count.sdk.java.internal.Log!); + method public static List! list(ly.count.sdk.java.internal.InternalConfig!, String!); + method public static List! list(ly.count.sdk.java.internal.InternalConfig!, String!, int); + method public static Future!>! listAsync(ly.count.sdk.java.internal.InternalConfig!, String!, int); + method public static String! name(ly.count.sdk.java.internal.Storable!); + method public static T pop(ly.count.sdk.java.internal.InternalConfig!, T); + method public static Future! popAsync(ly.count.sdk.java.internal.InternalConfig!, T); + method public static boolean push(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.Storable!); + method public static Future! pushAsync(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.Storable!); + method public static Future! pushAsync(ly.count.sdk.java.internal.InternalConfig!, ly.count.sdk.java.internal.Storable!, ly.count.sdk.java.internal.Tasks.Callback!); + method public static T read(ly.count.sdk.java.internal.InternalConfig!, T); + method public static Future! readAsync(ly.count.sdk.java.internal.InternalConfig!, T); + method public static Future! readAsync(ly.count.sdk.java.internal.InternalConfig!, T, ly.count.sdk.java.internal.Tasks.Callback!); + method public static T readOne(ly.count.sdk.java.internal.InternalConfig!, T, boolean); + method public static Future! readOneAsync(ly.count.sdk.java.internal.InternalConfig!, T, boolean); + method public static Boolean! remove(ly.count.sdk.java.internal.InternalConfig!, T); + method public static Future! removeAsync(ly.count.sdk.java.internal.InternalConfig!, T, ly.count.sdk.java.internal.Tasks.Callback!); + method public static void stop(); + } + + public interface StorageProvider { + method public String! getContentTriggerGaps(); + method public String! getDeviceID(); + method public String! getDeviceIdType(); + method public String! getHealthCheckState(); + method public Integer! getMigrationVersion(); + method public org.json.JSONObject! getRemoteConfigValues(); + 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!); + method public void setMigrationVersion(Integer!); + method public void setRemoteConfigValues(org.json.JSONObject!); + method public void setServerConfig(String!); + method public int takeAutomaticCrashCount(); + } + + public class Tasks { + ctor public Tasks(String!, ly.count.sdk.java.internal.Log!); + method public Future! run(ly.count.sdk.java.internal.Tasks.Task!); + field public static final Long ID_LIST; + field public static final Long ID_STRICT; + } + + public static interface Tasks.Callback { + method public void call(T); + } + + public abstract static class Tasks.Task { + method public abstract T call(); + } + + public class TimeUtils { + ctor public TimeUtils(); + method public static int currentDayOfWeek(); + method public static int currentHour(); + method public static ly.count.sdk.java.internal.TimeUtils.Instant! getCurrentInstant(); + method protected static ly.count.sdk.java.internal.TimeUtils.Instant! getCurrentInstant(long); + method public static ly.count.sdk.java.internal.TimeUtils.Instant! getCurrentInstantUnique(); + method public static long nsToMs(long); + method public static long nsToSec(long); + method public static long secToMs(long); + method public static long secToNs(long); + method public static long timestampMs(); + method public static long uniqueStorageId(); + method public static long uniqueTimestampMs(); + method public static long uniqueTimestampS(); + field protected static final long MS_IN_SECOND = 1000L; // 0x3e8L + field protected static final Double NS_IN_MS; + field protected static final Double NS_IN_SECOND; + } + + public static class TimeUtils.Instant { + field public final int dow; + field public final int hour; + field public final long timestamp; + field public final int tz; + } + + public interface Transformer { + method public byte[]! doTheJob(Long!, byte[]!); + } + + public class Transport { + ctor public Transport(); + method public void checkClientTrusted(X509Certificate![]!, String!); + method public void checkServerTrusted(X509Certificate![]!, String!); + method public X509Certificate![]! getAcceptedIssuers(); + method public void init(ly.count.sdk.java.internal.InternalConfig!); + method public HttpURLConnection! openConnection(String!, String!, boolean); + method public ly.count.sdk.java.internal.Tasks.Task! send(ly.count.sdk.java.internal.Request!); + } + + public class UserEditorImpl implements ly.count.sdk.java.UserEditor { + method public ly.count.sdk.java.UserEditor! addToCohort(String!); + method public ly.count.sdk.java.User! commit(); + method public ly.count.sdk.java.UserEditor! inc(String!, int); + method public ly.count.sdk.java.UserEditor! max(String!, double); + method public ly.count.sdk.java.UserEditor! min(String!, double); + method public ly.count.sdk.java.UserEditor! mul(String!, double); + method public ly.count.sdk.java.UserEditor! optOutFromLocationServices(); + method public ly.count.sdk.java.UserEditor! pull(String!, Object!); + method public ly.count.sdk.java.UserEditor! push(String!, Object!); + method public ly.count.sdk.java.UserEditor! pushUnique(String!, Object!); + method public ly.count.sdk.java.UserEditor! removeFromCohort(String!); + method public ly.count.sdk.java.UserEditor! set(String!, Object!); + method public ly.count.sdk.java.UserEditor! setBirthyear(int); + method public ly.count.sdk.java.UserEditor! setBirthyear(String!); + method public ly.count.sdk.java.UserEditor! setCity(String!); + method public ly.count.sdk.java.UserEditor! setCountry(String!); + method public ly.count.sdk.java.UserEditor! setCustom(String!, Object!); + method public ly.count.sdk.java.UserEditor! setEmail(String!); + method public ly.count.sdk.java.UserEditor! setGender(Object!); + method public ly.count.sdk.java.UserEditor! setLocale(String!); + method public ly.count.sdk.java.UserEditor! setLocation(double, double); + method public ly.count.sdk.java.UserEditor! setLocation(String!); + method public ly.count.sdk.java.UserEditor! setName(String!); + method public ly.count.sdk.java.UserEditor! setOnce(String!, Object!); + method public ly.count.sdk.java.UserEditor! setOrg(String!); + method public ly.count.sdk.java.UserEditor! setPhone(String!); + method public ly.count.sdk.java.UserEditor! setPicture(byte[]!); + method public ly.count.sdk.java.UserEditor! setPicturePath(String!); + method public ly.count.sdk.java.UserEditor! setUsername(String!); + } + + public class UserImpl extends ly.count.sdk.java.User { + ctor public UserImpl(ly.count.sdk.java.internal.InternalConfig!); + method public Integer! birthyear(); + method public String! city(); + method public String! country(); + method public Map! custom(); + method public ly.count.sdk.java.UserEditor! edit(); + method public String! email(); + method public ly.count.sdk.java.User.Gender! gender(); + method public String! id(); + method public String! locale(); + method public String! location(); + method public String! name(); + method public String! org(); + method public String! phone(); + method public byte[]! picture(); + method public String! picturePath(); + method public String toString(); + method public String! username(); + } + + public class Utils { + ctor public Utils(); + method public static boolean contains(String!, String!); + method public static String! digestHex(String!, String!, ly.count.sdk.java.internal.Log!); + method public static Map! fixSegmentKeysAndValues(int, int, Map!, ly.count.sdk.java.internal.Log!); + method public static String! hex(byte[]!); + method public static boolean isEmptyOrNull(String!); + method public static boolean isEqual(Object!, Object!); + method public static boolean isNotEmpty(String!); + method public static boolean isNotEqual(Object!, Object!); + method public static boolean isValidDataType(Object!); + method public static boolean isValidURL(String!); + method public static String! join(Collection!, String!); + method public static String! readFileContent(File!, ly.count.sdk.java.internal.Log!); + method public static byte[]! readStream(InputStream!, ly.count.sdk.java.internal.Log!); + method public static List! reflectiveGetDeclaredFields(Class!, boolean); + method public static List! reflectiveGetDeclaredFields(List!, Class!, boolean); + method public static void removeInvalidDataFromSegments(Map!, ly.count.sdk.java.internal.Log!); + method public static String! safeRandomVal(); + method public static String! trimKey(int, String!, ly.count.sdk.java.internal.Log!); + method public static String! trimValue(int, String!, String!, ly.count.sdk.java.internal.Log!); + method public static String![]! trimValues(int, String![]!, ly.count.sdk.java.internal.Log!); + method public static String! urldecode(String!); + method public static String! urlencode(String!, ly.count.sdk.java.internal.Log!); + method protected static String! urlencode(String!, ly.count.sdk.java.internal.Log!, String!); + field public static final char[]! BASE_16; + field public static final String CRLF = "\r\n"; + field public static final String UTF8 = "UTF-8"; + } + + public static class Utils.Base64 { + ctor public Utils.Base64(); + method public static byte[]! decode(String!, ly.count.sdk.java.internal.Log!); + method public static String! decodeToString(String!, ly.count.sdk.java.internal.Log!); + method public static String! encode(byte[]!); + method public static String! encode(String!); + } + + public interface ViewIdProvider { + method public String getCurrentViewId(); + method public String getPreviousViewId(); + } + + public class WidgetAction { + ctor public WidgetAction(); + method public ly.count.sdk.java.internal.ContentPlacement! resizeFor(boolean); + field public boolean close; + field public String! eventPayload; + field public boolean hasResize; + field public boolean isActionEvent; + field public boolean isExternalLink; + field public boolean isSdkSignal; + field public boolean isWidgetCommand; + field public ly.count.sdk.java.internal.ContentPlacement! landscape; + field public String! link; + field public ly.count.sdk.java.internal.ContentPlacement! portrait; + field public Map! queryParams; + } + + public class WidgetActionParser { + method public static ly.count.sdk.java.internal.WidgetAction! parse(String!, ly.count.sdk.java.internal.Log!); + field public static final String ACTION_HOST = "countly_action_event"; + field public static final String! ACTION_URL_START = "https://countly_action_event"; + } + +} + diff --git a/sdk-java/build.gradle b/sdk-java/build.gradle index fc64a858f..02391c4cc 100644 --- a/sdk-java/build.gradle +++ b/sdk-java/build.gradle @@ -10,6 +10,23 @@ java { targetCompatibility = JavaVersion.VERSION_1_8 } +// javac 8 has no --release flag; on a newer JDK it also stops the use of Java 9+ APIs, which the target alone allows. +if (JavaVersion.current().isJava9Compatible()) { + tasks.withType(JavaCompile).configureEach { + options.release = 8 + } +} + +// Gradle itself needs Java 17, so CI passes -PtestJavaVersion=8 to run the tests on the SDK's Java 8 floor. +def testJavaVersion = findProperty('testJavaVersion') +if (testJavaVersion) { + tasks.named('test') { + javaLauncher = javaToolchains.launcherFor { + languageVersion = JavaLanguageVersion.of(testJavaVersion.toString()) + } + } +} + dependencies { implementation 'org.json:json:20260814' implementation 'com.google.code.findbugs:jsr305:3.0.2' diff --git a/sdk-java/src/main/java/ly/count/sdk/java/Config.java b/sdk-java/src/main/java/ly/count/sdk/java/Config.java index 56275a98f..e0b712bba 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/Config.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/Config.java @@ -29,12 +29,12 @@ public class Config { /** * URL of Countly server */ - protected URL serverURL; + protected volatile URL serverURL; /** * Application key of Countly server */ - protected String serverAppKey; + protected volatile String serverAppKey; /** * Set of Countly SDK features enabled @@ -69,7 +69,7 @@ public class Config { /** * Countly SDK version to be sent in HTTP requests */ - protected String sdkVersion = "26.8.0"; + protected String sdkVersion = "26.12.0"; /** * Countly SDK version to be sent in HTTP requests @@ -226,6 +226,11 @@ public class Config { */ protected int maxBreadcrumbCount = 100; + /** + * Maximum length of the keys the SDK records, no limit by default. + */ + protected int maxKeyLength = Integer.MAX_VALUE; + /** * Enable automatic crash reporting for unhandled exceptions. */ @@ -253,6 +258,37 @@ public class Config { protected boolean locationEnabled = true; protected boolean autoSendUserProperties = true; + /** + * Seed value for the SDK behavior settings. Used on first init only, + * when no settings have yet been persisted; subsequent inits use the + * value pulled from storage. + */ + protected String sdkBehaviorSettings = null; + + /** + * If {@code true}, the SDK skips the periodic {@code /o/sdk?method=sc} + * fetch. The seed JSON from {@link #setSdkBehaviorSettings(String)} (or + * a previously-persisted snapshot) is still applied. + */ + protected boolean sdkBehaviorSettingsRequestsDisabled = false; + + /** + * Whether request bodies are sent gzip-compressed, once the server's SDK behavior settings + * answer says it reads them. + */ + protected boolean requestCompressionEnabled = false; + + /** + * Whether the backoff mechanism may hold the request queue back after the server answered + * slowly. The SDK behavior settings can override it. + */ + protected boolean backoffMechanismEnabled = true; + + /** + * Whether the SDK sends its health check after init. + */ + protected boolean healthCheckEnabled = true; + // TODO: storage limits & configuration // protected int maxRequestsStored = 0; // protected int storageDirectory = ""; @@ -302,6 +338,26 @@ public Config setMaxBreadcrumbCount(int maxBreadcrumbCount) { return this; } + /** + * Set the maximum length of the keys the SDK records: event keys, view names, segmentation keys, + * custom user property keys, and the keys of custom user property modifiers. Longer keys are + * truncated to this length. There is no limit by default. The key length limit of the SDK behavior + * settings overrides this value. + * + * @param maxKeyLength the maximum key length, at least 1 + * @return {@code this} instance for method chaining + */ + public Config setMaxKeyLength(int maxKeyLength) { + if (maxKeyLength < 1) { + if (configLog != null) { + configLog.e("[Config] maxKeyLength cannot be less than 1"); + } + } else { + this.maxKeyLength = maxKeyLength; + } + return this; + } + /** * Disable automatic crash reporting for unhandled exceptions. * @@ -1508,4 +1564,77 @@ public Config disableAutoSendUserProperties() { this.autoSendUserProperties = false; return this; } + + /** + * Provide an initial SDK behavior settings payload to apply at init time, + * before the first {@code /o/sdk?method=sc} fetch returns. The value is + * the same JSON shape the Countly server emits: {@code {"v":1,"t":, + * "c":{...}}}. The seed is only used when nothing has been persisted yet, + * and it stands in for the server's settings: the first answer from the + * server replaces it, so a setting the answer does not carry goes back to + * this configuration. A {@code "cr":true} here can be lifted by that answer; + * use {@link #setRequiresConsent(boolean)} for a requirement that must hold. + * + * @param sdkBehaviorSettings serialized config JSON, or {@code null} for none + * @return {@code this} instance for method chaining + */ + public Config setSdkBehaviorSettings(String sdkBehaviorSettings) { + this.sdkBehaviorSettings = sdkBehaviorSettings; + return this; + } + + /** + * Disable the periodic SDK behavior settings fetch from the server. Any + * seed JSON or previously-persisted snapshot is still applied at init. + * + * @return {@code this} instance for method chaining + */ + public Config disableSdkBehaviorSettingsUpdates() { + this.sdkBehaviorSettingsRequestsDisabled = true; + return this; + } + + /** + * Compress request bodies between 1 KB and 1 MB with gzip before sending them. The SDK + * compresses only after the server's SDK behavior settings answer said it reads compressed + * bodies, so older servers keep getting plain requests. It needs the SDK behavior settings + * updates, which backend mode and {@link #disableSdkBehaviorSettingsUpdates()} turn off. A + * compressed request that the server, or something in front of it, answers without accepting + * it stops compression until the next SDK behavior settings answer says again that the server + * reads compressed bodies. + * + * @return {@code this} instance for method chaining + */ + public Config enableRequestCompression() { + this.requestCompressionEnabled = true; + return this; + } + + /** + * Disable the backoff mechanism. While it is on, a request the server takes long to answer + * makes the SDK wait before it sends the next queued request, which gives a busy server room + * to recover. It never waits while many requests are queued or after an old request. The SDK + * behavior settings can still turn it on or off. + * + * @return {@code this} instance for method chaining + */ + public Config disableBackoffMechanism() { + this.backoffMechanismEnabled = false; + return this; + } + + /** + * Disable the SDK health check. Once after init the SDK sends the server a short report about + * its own state: how many warnings and errors it logged, the last request the server refused, + * how often it had to wait for a slow server, how often its session, event, view and crash + * methods were called, and which known problems occurred. It carries no data the app recorded. + * The server shows it in the SDK Manager. With this option the report is not sent; the SDK + * keeps counting, as before. + * + * @return {@code this} instance for method chaining + */ + public Config disableHealthCheck() { + this.healthCheckEnabled = false; + return this; + } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/Countly.java b/sdk-java/src/main/java/ly/count/sdk/java/Countly.java index 86486768d..0a0e1dba3 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/Countly.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/Countly.java @@ -1,7 +1,9 @@ package ly.count.sdk.java; import java.io.File; +import java.util.Arrays; import java.util.Map; +import java.util.function.Consumer; import ly.count.sdk.java.internal.Device; import ly.count.sdk.java.internal.DeviceIdType; import ly.count.sdk.java.internal.InternalConfig; @@ -84,7 +86,6 @@ public void init(final Config config) { } Log L = new Log(internalConfig.loggingLevel, internalConfig.logListener); - internalConfig.setLogger(L); if (directory == null) { L.e("[Countly] File cannot be null"); @@ -101,16 +102,20 @@ public void init(final Config config) { } if (isInitialized()) { - L.e("[Countly] Countly shouldn't be initialized twice. Please either use Countly.isInitialized() to check status or call Countly.stop() before second Countly.init(). Calling 'init' the second time will now do nothing"); + Log running = cly.L != null ? cly.L : L; + running.w("[Countly] Countly shouldn't be initialized twice. Please either use Countly.isInitialized() to check status or call Countly.stop() before second Countly.init(). Calling 'init' the second time will now do nothing"); + running.recordLogCode("w110"); return; } + internalConfig.setLogger(L); if (internalConfig.enableBackendMode) { internalConfig.sdkName = "java-native-backend"; } if (internalConfig.requestQueueMaxSize < 1) { - L.e("[Countly] init: Request queue max size can not be less than 1."); + L.w("[Countly] init: Request queue max size can not be less than 1."); + L.recordLogCode("w121"); internalConfig.requestQueueMaxSize = 1; } @@ -211,9 +216,7 @@ public static boolean isTracking(Config.Feature feature) { */ public static Session session() { if (!isInitialized()) { - if (cly.L != null) { - cly.L.e("[Countly] SDK is not initialized yet."); - } + Log.recordLogCodeWhileNotInitialized("w101"); return null; } @@ -237,9 +240,7 @@ public static ModuleBackendMode.BackendMode backendMode() { */ public ModuleBackendMode.BackendMode backendM() { if (!isInitialized()) { - if (cly.L != null) { - cly.L.e("[Countly] SDK is not initialized yet."); - } + Log.recordLogCodeWhileNotInitialized("w101"); return null; } else { ModuleBackendMode mbm = cly.sdk.module(ModuleBackendMode.class); @@ -353,19 +354,44 @@ public Usage changeDeviceIdWithoutMerge(String id) { */ public static void onConsent(Config.Feature... features) { if (!isInitialized()) { + Log.recordLogCodeWhileNotInitialized("w101"); + } else { if (cly.L != null) { - cly.L.e("[Countly] SDK is not initialized yet."); + cly.L.i("[Countly] onConsent: features = " + Arrays.toString(features)); } - } else { + cly.sdk.onConsent(consentFeatureIndexes("onConsent", features)); + } + } + + /** + * The feature bits a consent call names. A call that names no feature, or a {@code null} + * feature, is reported as log code w402; such a name is ignored. + * + * @param call the consent call, for the log + * @param features the features the call names + * @return the bits of the named features + */ + private static int consentFeatureIndexes(String call, Config.Feature... features) { + int ftrs = 0; + if (features == null || features.length == 0) { if (cly.L != null) { - cly.L.e("[Countly] onConsent: features = " + features); + cly.L.w("[Countly] " + call + ", no feature is given, the call does nothing"); + cly.L.recordLogCode("w402"); } - int ftrs = 0; - for (Config.Feature f : features) { - ftrs = ftrs | f.getIndex(); + return ftrs; + } + + for (Config.Feature f : features) { + if (f == null) { + if (cly.L != null) { + cly.L.w("[Countly] " + call + ", a 'null' feature is given, it is ignored"); + cly.L.recordLogCode("w402"); + } + continue; } - cly.sdk.onConsent(ftrs); + ftrs = ftrs | f.getIndex(); } + return ftrs; } /** @@ -377,33 +403,108 @@ public static void onConsent(Config.Feature... features) { */ public static void onConsentRemoval(Config.Feature... features) { if (cly.L != null) { - cly.L.e("[Countly] onConsentRemoval: features = " + features); + cly.L.i("[Countly] onConsentRemoval: features = " + Arrays.toString(features)); } if (!isInitialized()) { - if (cly.L != null) { - cly.L.e("[Countly] onConsentRemoval: SDK is not initialized yet."); - } + Log.recordLogCodeWhileNotInitialized("w101"); } else { - int ftrs = 0; - for (Config.Feature f : features) { - ftrs = ftrs | f.getIndex(); - } - cly.sdk.onConsentRemoval(cly.sdk.config, ftrs); + cly.sdk.onConsentRemoval(cly.sdk.config, consentFeatureIndexes("onConsentRemoval", features)); } } + /** + * Changes the server URL while the SDK runs. Every later request goes to the new URL, queued + * ones included; a request being sent finishes at the old one. The app key, salt and custom + * request headers stay. Then the SDK requests its behavior settings from the new server, and + * remote config when it downloads automatically. Kept in memory only: the next initialization + * uses the URL of the configuration again. An invalid URL is ignored with an error log. + * + * @param serverUrl an absolute http or https URL with a host, https only while certificate or + * public key pins are set; trailing "/" characters are removed + */ + public void changeServerUrl(String serverUrl) { + callIfInitialized("changeServerUrl, serverUrl:[" + serverUrl + "]", sdk -> sdk.changeServerUrl(serverUrl)); + } + + /** + * Changes the app key while the SDK runs, so the SDK reports to another app. First, under the + * old key, the running views are stopped, the queued events and pending user profile changes + * are stored as requests, and a running session is ended, then begun again under the new key. + * Queued requests keep their key: see {@link #replaceAllAppKeysInQueueWithCurrentAppKey()} and + * {@link #removeDifferentAppKeysFromQueue()}. Then the SDK requests the behavior settings of + * the new app, and its remote config when remote config downloads automatically; the remote + * config values of the old app are cleared, or marked as cached with value caching. Kept in + * memory only: the next initialization uses the key of the configuration again. An invalid key + * is ignored with an error log. The key in use is ignored, and so is any call in backend mode. + * + * @param appKey the new app key, neither empty nor "YOUR_APP_KEY" + */ + public void changeAppKey(String appKey) { + callIfInitialized("changeAppKey, appKey:[" + appKey + "]", sdk -> sdk.changeAppKey(appKey)); + } + + /** + * Clears the request queue and the event queue: all pending data is discarded. Started timed + * events, running views, pending user profile changes and the health check counters are kept, + * and a request that is being sent is not stopped. Ignored in backend mode. + */ + public void flushQueues() { + callIfInitialized("flushQueues", SDKCore::flushQueues); + } + + /** + * Replaces the app key of every queued request with the current app key, so requests queued + * under another key are sent to the current app. Ignored in backend mode. + */ + public void replaceAllAppKeysInQueueWithCurrentAppKey() { + callIfInitialized("replaceAllAppKeysInQueueWithCurrentAppKey", SDKCore::replaceAllAppKeysInQueueWithCurrentAppKey); + } + + /** + * Removes every queued request whose app key differs from the current app key, so it is never + * sent. Ignored in backend mode. + */ + public void removeDifferentAppKeysFromQueue() { + callIfInitialized("removeDifferentAppKeysFromQueue", SDKCore::removeDifferentAppKeysFromQueue); + } + + /** + * Packs the queued events into a request and starts sending the request queue right away, + * without waiting for the next timer tick. During a backoff pause, or while the SDK behavior + * settings turn networking off, sending waits as usual. + */ + public void attemptToSendStoredRequests() { + callIfInitialized("attemptToSendStoredRequests", SDKCore::attemptToSendStoredRequests); + } + + /** + * Logs a call at info level and runs it on the SDK, or only records log code w101 before init. + * + * @param logLine the call and its arguments, as logged + * @param call the call on the SDK + */ + private static void callIfInitialized(String logLine, Consumer call) { + if (!isInitialized()) { + Log.recordLogCodeWhileNotInitialized("w101"); + return; + } + if (cly.L != null) { + cly.L.i("[Countly] " + logLine); + } + call.accept(cly.sdk); + } + /** * Feedback interface to use feedback widgets nps,rating and forms. * And do manual reporting of feedbacks. * - * @return {@link ModuleFeedback.Feedback} instance. + * @return {@link ModuleFeedback.Feedback} instance, never {@code null}: before init, or while the feature does not + * run, as its consent is not given or it is not enabled, one that ignores calls until it runs */ public ModuleFeedback.Feedback feedback() { if (!isInitialized()) { - if (L != null) { - L.e("[Countly] SDK is not initialized yet."); - } - return null; + Log.recordLogCodeWhileNotInitialized("w101"); + return SDKCore.dormantFeedback; } return sdk.feedback(); } @@ -413,15 +514,14 @@ public ModuleFeedback.Feedback feedback() { * content block. A {@link ly.count.sdk.java.internal.ContentDisplay} has to be registered * before a content zone can be entered; the "ly.count.sdk:java-ui" artifact ships a JavaFX one. * - * @return {@link ModuleContent.Content} instance. + * @return {@link ModuleContent.Content} instance, never {@code null}: before init, or while the feature does not + * run, as its consent is not given or it is not enabled, one that ignores calls until it runs * @apiNote This is an EXPERIMENTAL feature, and it can have breaking changes */ public ModuleContent.Content content() { if (!isInitialized()) { - if (L != null) { - L.e("[Countly] content, SDK is not initialized yet."); - } - return null; + Log.recordLogCodeWhileNotInitialized("w101"); + return SDKCore.dormantContent; } return sdk.content(); } @@ -429,14 +529,13 @@ public ModuleContent.Content content() { /** * RemoteConfig interface to use remote config feature. * - * @return {@link ModuleRemoteConfig.RemoteConfig} instance. + * @return {@link ModuleRemoteConfig.RemoteConfig} instance, never {@code null}: before init, or while the feature does not + * run, as its consent is not given or it is not enabled, one that ignores calls until it runs */ public ModuleRemoteConfig.RemoteConfig remoteConfig() { if (!isInitialized()) { - if (L != null) { - L.e("[Countly] remoteConfig, SDK is not initialized yet."); - } - return null; + Log.recordLogCodeWhileNotInitialized("w101"); + return SDKCore.dormantRemoteConfig; } return sdk.remoteConfig(); } @@ -444,14 +543,13 @@ public ModuleRemoteConfig.RemoteConfig remoteConfig() { /** * DeviceId interface to use device id functionalities. * - * @return {@link ModuleDeviceIdCore.DeviceId} instance. + * @return {@link ModuleDeviceIdCore.DeviceId} instance, never {@code null}: before init, or while the feature does not + * run, as its consent is not given or it is not enabled, one that ignores calls until it runs */ public ModuleDeviceIdCore.DeviceId deviceId() { if (!isInitialized()) { - if (L != null) { - L.e("[Countly] SDK is not initialized yet."); - } - return null; + Log.recordLogCodeWhileNotInitialized("w101"); + return SDKCore.dormantDeviceId; } return sdk.deviceId(); } @@ -472,14 +570,13 @@ public Event event(String key) { /** * Event module calls * - * @return event module otherwise null if SDK is not initialized + * @return {@link ModuleEvents.Events} instance, never {@code null}: before init, or while the feature does not + * run, as its consent is not given or it is not enabled, one that ignores calls until it runs */ public ModuleEvents.Events events() { if (!isInitialized()) { - if (L != null) { - L.e("[Countly] SDK is not initialized yet."); - } - return null; + Log.recordLogCodeWhileNotInitialized("w101"); + return SDKCore.dormantEvents; } return sdk.events(); } @@ -487,14 +584,13 @@ public ModuleEvents.Events events() { /** * Crash module calls * - * @return crash module otherwise null if SDK is not initialized + * @return {@link ModuleCrashes.Crashes} instance, never {@code null}: before init, or while the feature does not + * run, as its consent is not given or it is not enabled, one that ignores calls until it runs */ public ModuleCrashes.Crashes crashes() { if (!isInitialized()) { - if (L != null) { - L.e("[Countly] SDK is not initialized yet."); - } - return null; + Log.recordLogCodeWhileNotInitialized("w101"); + return SDKCore.dormantCrashes; } return sdk.crashes(); } @@ -502,14 +598,13 @@ public ModuleCrashes.Crashes crashes() { /** * Views interface to use views feature. * - * @return {@link ModuleViews.Views} instance. + * @return {@link ModuleViews.Views} instance, never {@code null}: before init, or while the feature does not + * run, as its consent is not given or it is not enabled, one that ignores calls until it runs */ public ModuleViews.Views views() { if (!isInitialized()) { - if (L != null) { - L.e("[Countly] SDK is not initialized yet."); - } - return null; + Log.recordLogCodeWhileNotInitialized("w101"); + return SDKCore.dormantViews; } return sdk.views(); } @@ -530,14 +625,13 @@ public Event timedEvent(String key) { /** * UserProfile interface to use user profile feature. * - * @return {@link ModuleUserProfile.UserProfile} instance. + * @return {@link ModuleUserProfile.UserProfile} instance, never {@code null}: before init, or while the feature does not + * run, as its consent is not given or it is not enabled, one that ignores calls until it runs */ public ModuleUserProfile.UserProfile userProfile() { if (!isInitialized()) { - if (L != null) { - L.e("[Countly] userProfile, SDK is not initialized yet."); - } - return null; + Log.recordLogCodeWhileNotInitialized("w101"); + return SDKCore.dormantUserProfile; } return sdk.userProfile(); } @@ -545,15 +639,13 @@ public ModuleUserProfile.UserProfile userProfile() { /** * Location interface to use location feature. * - * @return {@link ModuleLocation.Location} instance. + * @return {@link ModuleLocation.Location} instance, never {@code null}: before init, or while the feature does not + * run, as its consent is not given or it is not enabled, one that ignores calls until it runs */ public ModuleLocation.Location location() { if (!isInitialized()) { - // L is null before init, so this has to be guarded like every sibling accessor. - if (L != null) { - L.e("Countly.sharedInstance().init must be called before accessing location"); - } - return null; + Log.recordLogCodeWhileNotInitialized("w101"); + return SDKCore.dormantLocation; } return sdk.location(); @@ -574,25 +666,25 @@ public User user() { @Override public Usage addParam(String key, Object value) { - L.d("[Countly] addParam: key = " + key + " value = " + value); + L.d("[Countly] addParam: key = " + key); return ((Session) sdk.session(null)).addParam(key, value); } @Override public Usage addCrashReport(Throwable t, boolean fatal) { - L.d("[Countly] addCrashReport: t = " + t + " fatal = " + fatal); + L.d("[Countly] addCrashReport: fatal = " + fatal); return ((Session) sdk.session(null)).addCrashReport(t, fatal); } @Override public Usage addCrashReport(Throwable t, boolean fatal, String name, Map segments, String... logs) { - L.d("[Countly] addCrashReport: t = " + t + " fatal = " + fatal + " name = " + name + " segments = " + segments + " logs = " + logs); + L.d("[Countly] addCrashReport: fatal = " + fatal); return ((Session) sdk.session(null)).addCrashReport(t, fatal, name, segments, logs); } @Override public Usage addLocation(double latitude, double longitude) { - L.d("[Countly] addLocation: latitude = " + latitude + " longitude = " + longitude); + L.d("[Countly] addLocation"); return ((Session) sdk.session(null)).addLocation(latitude, longitude); } @@ -603,7 +695,7 @@ public Usage addLocation(double latitude, double longitude) { */ @Override public View view(String name, boolean start) { - L.d("[Countly] view: name = " + name + " start = " + start); + L.d("[Countly] view: start = " + start); return ((Session) sdk.session(null)).view(name, start); } @@ -614,7 +706,7 @@ public View view(String name, boolean start) { */ @Override public View view(String name) { - L.d("[Countly] view: name = " + name); + L.d("[Countly] view"); return ((Session) sdk.session(null)).view(name); } } 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 d13fb2103..3f443e923 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 new file mode 100644 index 000000000..970aac01a --- /dev/null +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ConfigurationProvider.java @@ -0,0 +1,452 @@ +package ly.count.sdk.java.internal; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * The SDK behavior settings in effect, the server side configuration served by + * {@code /o/sdk?method=sc}. Every value starts from the developer configuration and is overridden, + * in increasing order of precedence, by the settings provided at init (used only while nothing is + * stored), by the settings stored from an earlier run and by the latest server response. + *

+ * {@link ModuleConfiguration} implements it for the running SDK. Reach it through + * {@link InternalConfig#getConfigurationProvider()}, which never returns {@code null}. A server + * response can change any value on the thread that delivered it, so read a value where it is used + * instead of keeping a copy of it. + */ +public interface ConfigurationProvider { + + /** + * Key {@code networking}. + * + * @return whether requests may be sent at all, the queued ones and the immediate ones + */ + boolean getNetworkingEnabled(); + + /** + * Key {@code tracking}. + * + * @return whether anything new may be recorded + */ + boolean getTrackingEnabled(); + + /** + * Key {@code st}. + * + * @return whether sessions may be tracked + */ + boolean getSessionTrackingEnabled(); + + /** + * Key {@code vt}. + * + * @return whether views may be tracked + */ + boolean getViewTrackingEnabled(); + + /** + * Key {@code cet}. + * + * @return whether custom events, the ones whose key is not one of {@link ModuleEvents#INTERNAL_EVENT_KEYS}, may be recorded + */ + boolean getCustomEventTrackingEnabled(); + + /** + * Key {@code ecz}. + * + * @return whether the SDK should be in the content zone + */ + boolean getContentZoneEnabled(); + + /** + * Key {@code crt}. + * + * @return whether crashes may be recorded + */ + boolean getCrashReportingEnabled(); + + /** + * Key {@code ast}. This SDK has no automatic session tracking, so the value is only exposed. + * + * @return whether sessions should be tracked automatically + */ + boolean getAutomaticSessionTrackingEnabled(); + + /** + * Key {@code avt}. This SDK has no automatic view tracking, so the value is only exposed. + * + * @return whether views should be tracked automatically + */ + boolean getAutomaticViewTrackingEnabled(); + + /** + * Key {@code acr}. + * + * @return whether unhandled exceptions should be reported automatically + */ + boolean getAutomaticCrashReportingEnabled(); + + /** + * Key {@code lt}. + * + * @return whether location may be tracked + */ + boolean getLocationTrackingEnabled(); + + /** + * Key {@code rcz}. + * + * @return whether the content zone may be refreshed + */ + boolean getRefreshContentZoneEnabled(); + + /** + * Key {@code bom}. + * + * @return whether the backoff mechanism is on + */ + boolean getBOMEnabled(); + + /** + * Key {@code log}. + * + * @return whether the SDK should print its logs + */ + boolean getLoggingEnabled(); + + /** + * Key {@code cr}. The SDK applies it when it initializes, so a value that arrives later takes + * effect on the next init and can differ from {@link InternalConfig#requiresConsent()} until then. + * + * @return whether consent is required before anything is recorded + */ + boolean getConsentRequired(); + + /** + * Key {@code scui}. + * + * @return hours between two fetches of the settings + */ + int getServerConfigUpdateInterval(); + + /** + * Key {@code rqs}. + * + * @return the maximum number of queued requests + */ + int getRequestQueueMaxSize(); + + /** + * Whether {@link #getRequestQueueMaxSize()} comes from the settings, provided, stored or + * received, rather than from the developer configuration. + * + * @return {@code true} when the settings set the request queue size + */ + boolean isRequestQueueMaxSizeFromBehaviorSettings(); + + /** + * Key {@code eqs}. + * + * @return how many events are held before they are sent + */ + int getEventQueueSizeThreshold(); + + /** + * Key {@code sui}. + * + * @return seconds between two ticks of the SDK timer, which sends session updates and queued events + */ + int getSessionUpdateInterval(); + + /** + * Key {@code lkl}. + * + * @return the maximum length of a key, {@link Integer#MAX_VALUE} for no limit + */ + int getMaxKeyLength(); + + /** + * Key {@code lvs}. + * + * @return the maximum length of a value, {@link Integer#MAX_VALUE} for no limit + */ + int getMaxValueSize(); + + /** + * Key {@code lsv}. + * + * @return the maximum number of segmentation entries, {@link Integer#MAX_VALUE} for no limit + */ + int getMaxSegmentationValues(); + + /** + * Key {@code lbc}. + * + * @return the maximum number of breadcrumbs kept for a crash + */ + int getMaxBreadcrumbCount(); + + /** + * Key {@code ltlpt}. + * + * @return the maximum number of stack trace lines per thread, {@link Integer#MAX_VALUE} for no limit + */ + int getMaxStackTraceLinesPerThread(); + + /** + * Key {@code ltl}. + * + * @return the maximum length of a stack trace line, {@link Integer#MAX_VALUE} for no limit + */ + int getMaxStackTraceLineLength(); + + /** + * Key {@code upcl}. + * + * @return the maximum number of custom user properties cached before they are sent, + * {@link Integer#MAX_VALUE} for no limit + */ + int getUserPropertyCacheLimit(); + + /** + * Key {@code bom_at}. + * + * @return seconds a request may take before the backoff mechanism counts it as slow + */ + int getBOMAcceptedTimeoutSeconds(); + + /** + * Key {@code bom_rqp}. + * + * @return the share of the request queue, in (0, 1), above which the backoff mechanism stays off + */ + double getBOMRQPercentage(); + + /** + * Key {@code bom_ra}. + * + * @return the age, in hours, above which a request is too old for the backoff mechanism to delay it + */ + int getBOMRequestAge(); + + /** + * Key {@code bom_d}. + * + * @return seconds the backoff mechanism holds the request queue back + */ + int getBOMDuration(); + + /** + * Key {@code dort}. + * + * @return the age, in hours, above which a queued request is dropped, {@code 0} to keep every request + */ + int getRequestDropAgeHours(); + + /** + * Key {@code czi}. + * + * @return seconds between two content fetches while in the content zone + */ + int getContentZoneTimerInterval(); + + /** + * Keys {@code eb} and {@code ew}. + * + * @return the filter for custom event keys, never {@code null} + */ + @Nonnull FilterList> getEventFilterList(); + + /** + * Keys {@code upb} and {@code upw}. + * + * @return the filter for custom user property keys, never {@code null} + */ + @Nonnull FilterList> getUserPropertyFilterList(); + + /** + * Keys {@code sb} and {@code sw}. + * + * @return the filter for custom event segmentation keys, never {@code null} + */ + @Nonnull FilterList> getSegmentationFilterList(); + + /** + * Keys {@code esb} and {@code esw}. + * + * @return the segmentation key filter of each custom event key, never {@code null} + */ + @Nonnull FilterList>> getEventSegmentationFilterList(); + + /** + * Key {@code jte}. + * + * @return the custom event keys that trigger a journey, never {@code null} and never modifiable + */ + @Nonnull Set getJourneyTriggerEvents(); + + /** + * Key {@code jtv}. + * + * @return the view names that trigger a journey, never {@code null} and never modifiable + */ + @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 + * compressed bodies, and no compressed request was refused since that answer. + * + * @return {@code true} when a request body may be compressed + */ + default boolean isRequestCompressionAllowed() { + return false; + } + + /** + * Stops request compression until the next SDK behavior settings answer says that the server + * reads compressed bodies, or the SDK starts again; called after the server, or something in + * front of it, answered a compressed request without accepting it. + */ + default void blockRequestCompression() { + } + + /** + * The decision of the {@code lg} directive, which sits next to {@code c} in a live response. + * + * @return whether this device gathers its SDK logs for the server + */ + @Nonnull LogGatheringState getLogGatheringState(); + + /** + * The gather id every uploaded log batch has to carry. + * + * @return the id, {@code null} unless {@link #getLogGatheringState()} is {@link LogGatheringState#GATHERING} + */ + @Nullable String getLogGatheringId(); + + /** + * The log levels to gather, as level characters: e error, w warning, i info, d debug, v verbose. + * + * @return a non empty subset of {@code ewidv} + */ + @Nonnull String getLogGatheringLevels(); + + /** + * How many log lines to hold before a batch is uploaded. + * + * @return the batch size, within [10, 500] + */ + int getLogGatheringBatchSize(); + + /** + * Whether this device gathers its SDK logs for the server. + */ + enum LogGatheringState { + /** + * No live response has decided yet: only stored or provided settings were seen. + */ + UNDECIDED, + /** + * A live response enabled gathering and carried a usable gather id. + */ + GATHERING, + /** + * A live response, a failed fetch or disabled settings requests decided against gathering. + */ + NOT_GATHERING + } + + /** + * An immutable listing filter: names that are the only ones allowed, a whitelist, or the ones + * rejected, a blacklist. An empty blacklist allows everything. + * + * @param the names, as a set or as a set per event key + */ + final class FilterList { + static final FilterList> NO_NAMES = new FilterList<>(Collections.emptySet(), false); + static final FilterList>> NO_NAMES_PER_EVENT = new FilterList<>(Collections.>emptyMap(), false); + + private final T names; + private final boolean isWhitelist; + + /** + * Wraps names that are already immutable. + * + * @param names the names + * @param isWhitelist {@code true} when only the names are allowed, {@code false} when they are rejected + */ + private FilterList(@Nonnull T names, boolean isWhitelist) { + this.names = names; + this.isWhitelist = isWhitelist; + } + + /** + * Builds a filter over an immutable copy of the given names. + * + * @param names the names, kept in the given order + * @param isWhitelist {@code true} when only the names are allowed, {@code false} when they are rejected + * @return the filter + */ + static FilterList> ofNames(@Nonnull Set names, boolean isWhitelist) { + return new FilterList<>(Collections.unmodifiableSet(new LinkedHashSet<>(names)), isWhitelist); + } + + /** + * Builds a filter over an immutable copy of the given names of each event key. + * + * @param namesPerEvent the names of each event key, kept in the given order + * @param isWhitelist {@code true} when only the names are allowed, {@code false} when they are rejected + * @return the filter + */ + static FilterList>> ofNamesPerEvent(@Nonnull Map> namesPerEvent, boolean isWhitelist) { + Map> copy = new LinkedHashMap<>(); + for (Map.Entry> entry : namesPerEvent.entrySet()) { + copy.put(entry.getKey(), Collections.unmodifiableSet(new LinkedHashSet<>(entry.getValue()))); + } + return new FilterList<>(Collections.unmodifiableMap(copy), isWhitelist); + } + + /** + * The names of the filter. + * + * @return the names, never modifiable + */ + @Nonnull + public T getFilterList() { + return names; + } + + /** + * Whether the names are the only ones allowed. + * + * @return {@code true} for a whitelist, {@code false} for a blacklist + */ + public boolean isWhitelist() { + return isWhitelist; + } + + /** + * Describes the filter for logs. + * + * @return the kind of the filter followed by its names + */ + @Override + public String toString() { + return (isWhitelist ? "whitelist " : "blacklist ") + names; + } + } +} 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 000000000..47d35a7dc --- /dev/null +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ContentTriggers.java @@ -0,0 +1,339 @@ +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: the content triggers decide while the zone is wanted, else the + * journey trigger events ("jte") and views ("jtv") decide. + * + * @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/CountlyTimer.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/CountlyTimer.java index f2dd22058..a79481d79 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/CountlyTimer.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/CountlyTimer.java @@ -8,6 +8,7 @@ public class CountlyTimer { private final Log L; private ScheduledExecutorService timerService; + private volatile long timerDelaySeconds = -1; protected static int TIMER_DELAY_MS = 0; // for testing purposes protected CountlyTimer(Log logger) { @@ -53,6 +54,7 @@ protected void startTimer(long timerDelay, Runnable runnable) { */ protected void startTimer(long timerDelay, long initialDelayMs, Runnable runnable) { L.i("[CountlyTimer] startTimer, Starting global timer timerDelay: [" + timerDelay + "] initialDelayMs: [" + initialDelayMs + "]"); + timerDelaySeconds = timerDelay; long delay = timerDelay * 1000; if (delay < 1000) { @@ -66,6 +68,22 @@ protected void startTimer(long timerDelay, long initialDelayMs, Runnable runnabl startTime = 0; } - timerService.scheduleWithFixedDelay(runnable, startTime, delay, TimeUnit.MILLISECONDS); + timerService.scheduleWithFixedDelay(() -> { + try { + runnable.run(); + } catch (Throwable t) { + //a fixed delay schedule ends for good once a run throws + L.e("[CountlyTimer] a timer run failed, [" + t + "]"); + } + }, startTime, delay, TimeUnit.MILLISECONDS); + } + + /** + * The interval this timer was last started with, as it was requested. + * + * @return the interval in seconds, {@code -1} while the timer was never started + */ + long getTimerDelaySeconds() { + return timerDelaySeconds; } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/CrashImpl.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/CrashImpl.java index 72e6003ec..20665634f 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/CrashImpl.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/CrashImpl.java @@ -6,9 +6,11 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import javax.annotation.Nonnull; import ly.count.sdk.java.Crash; import org.json.JSONException; import org.json.JSONObject; @@ -23,9 +25,13 @@ public class CrashImpl implements Crash, Storable { private final JSONObject data; private Throwable throwable; private Map traces; + private Thread tracesMainThread; + //whether "_error" holds the dump of addTraces rather than the stack trace of a throwable + private boolean errorIsTraceDump = false; + private String[] logs; protected CrashImpl(Log logger) { - this(TimeUtils.uniqueTimestampMs(), logger); + this(TimeUtils.uniqueStorageId(), logger); } protected CrashImpl(Long id, Log logger) { @@ -38,6 +44,7 @@ protected CrashImpl(Long id, Log logger) { @Override public CrashImpl addThrowable(Throwable throwable) { this.throwable = throwable; + this.errorIsTraceDump = false; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); @@ -57,31 +64,58 @@ public CrashImpl addTraces(Thread main, Map traces) return this; } else { this.traces = traces; + String dump = printAllTraces(main, traces, Integer.MAX_VALUE, "[CrashImpl] addTraces"); + this.tracesMainThread = main; + this.errorIsTraceDump = true; + return add("_type", "anr").add("_error", dump); + } + } - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); + /** + * Prints the stack traces of every thread, the main thread first. + * + * @param main the main thread, {@code null} for none + * @param threadTraces the stack trace of each thread + * @param maxLinesPerThread how many of the top lines of each thread to print at most + * @param tag the caller, for the log of a thread that has more lines + * @return the printed stack traces + */ + private String printAllTraces(Thread main, @Nonnull Map threadTraces, int maxLinesPerThread, @Nonnull String tag) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); - if (main != null && traces.containsKey(main)) { - pw.println("Thread [main]:"); - printTraces(pw, null, traces.get(main)); - pw.append("\n\n"); - } + if (main != null && threadTraces.containsKey(main)) { + pw.println("Thread [main]:"); + printTraces(pw, main, true, threadTraces.get(main), maxLinesPerThread, tag); + pw.append("\n\n"); + } - for (Thread thread : traces.keySet()) { - if (thread != main) { - printTraces(pw, thread, traces.get(thread)); - pw.append("\n\n"); - } + for (Thread thread : threadTraces.keySet()) { + if (thread != main) { + printTraces(pw, thread, false, threadTraces.get(thread), maxLinesPerThread, tag); + pw.append("\n\n"); } - return add("_type", "anr").add("_error", sw.toString()); } + return sw.toString(); } - private void printTraces(PrintWriter pw, Thread thread, StackTraceElement[] traces) { - if (thread != null) { + /** + * Prints the stack trace of one thread, under a header naming the thread unless it is the main one. + * + * @param pw where to print + * @param thread the thread + * @param mainThread whether it is the main thread, whose header is printed by the caller + * @param traces the stack trace of the thread + * @param maxLines how many of the top lines to print at most + * @param tag the caller, for the log when lines are left out + */ + private void printTraces(PrintWriter pw, Thread thread, boolean mainThread, StackTraceElement[] traces, int maxLines, @Nonnull String tag) { + if (!mainThread && thread != null) { pw.append("Thread [").append(thread.getName()).append("]:\n"); } - for (StackTraceElement el : traces) { + int lines = UtilsInternalLimits.stackTraceLinesToKeep(traces.length, maxLines, thread == null ? null : thread.getName(), L, tag); + for (int i = 0; i < lines; i++) { + StackTraceElement el = traces[i]; pw.append("\tat ").append(el == null ? "<>" : el.toString()).append("\n"); } } @@ -111,11 +145,90 @@ protected CrashImpl addSegments(Map segments) { @Override public CrashImpl setLogs(String[] logs) { if (logs != null && logs.length > 0) { + this.logs = logs.clone(); return add("_logs", Utils.join(Arrays.asList(logs), "\n")); } return this; } + /** + * Applies the SDK internal limits of the SDK behavior settings to what this crash sends: the lines + * per thread of a dump made by {@link #addTraces(Thread, Map)}, the length of every stack trace + * line, the keys, string values and number of the custom segments and the length of every + * breadcrumb. The stack trace of a throwable keeps all its lines. Nothing changes while no limit + * is exceeded. + * + * @param limits the settings in effect + * @param tag the caller, for the log + */ + void applyInternalLimits(@Nonnull ConfigurationProvider limits, @Nonnull String tag) { + int maxLinesPerThread = limits.getMaxStackTraceLinesPerThread(); + if (errorIsTraceDump && traceDumpExceeds(maxLinesPerThread)) { + add("_error", printAllTraces(tracesMainThread, traces, maxLinesPerThread, tag)); + } + + String error = data.optString("_error", null); + if (error != null) { + String truncatedError = UtilsInternalLimits.truncateStackTraceLines(error, limits.getMaxStackTraceLineLength(), L, tag); + if (truncatedError.length() != error.length()) { + add("_error", truncatedError); + } + } + + JSONObject custom = data.optJSONObject("_custom"); + if (custom != null) { + Map segments = new LinkedHashMap<>(); + for (String key : custom.keySet()) { + segments.put(key, custom.opt(key)); + } + Map limitedSegments = UtilsInternalLimits.applySegmentationLimits(segments, limits, L, tag); + if (!segments.equals(limitedSegments)) { + add("_custom", new JSONObject(limitedSegments)); + } + } + + applyValueSizeLimitToLogs(limits.getMaxValueSize(), tag); + } + + /** + * Whether a thread of the dump made by {@link #addTraces(Thread, Map)} has more stack trace lines + * than a limit. + * + * @param maxLinesPerThread the limit + * @return {@code true} when a thread has more lines + */ + private boolean traceDumpExceeds(int maxLinesPerThread) { + for (StackTraceElement[] threadTraces : traces.values()) { + if (threadTraces != null && threadTraces.length > maxLinesPerThread) { + return true; + } + } + return false; + } + + /** + * Cuts every breadcrumb given to {@link #setLogs(String[])} to the value size limit. + * + * @param maxValueSize the limit + * @param tag the caller, for the log + */ + private void applyValueSizeLimitToLogs(int maxValueSize, @Nonnull String tag) { + if (logs == null) { + return; + } + + String[] truncatedLogs = new String[logs.length]; + boolean truncated = false; + for (int i = 0; i < logs.length; i++) { + truncatedLogs[i] = UtilsInternalLimits.truncateValue(logs[i], maxValueSize, L, tag); + truncated |= logs[i] != null && truncatedLogs[i].length() != logs[i].length(); + } + + if (truncated) { + setLogs(truncatedLogs); + } + } + @Override public Throwable getThrowable() { return throwable; diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/DefaultNetworking.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/DefaultNetworking.java index 085775c30..f6eade49d 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/DefaultNetworking.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/DefaultNetworking.java @@ -1,20 +1,58 @@ package ly.count.sdk.java.internal; +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.AtomicLong; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + public class DefaultNetworking implements Networking { + /** + * Name of the thread that ends a backoff of the request queue. + */ + static final String BACKOFF_THREAD_NAME = "network-backoff"; + private static final String TIMESTAMP_PARAM = "timestamp"; + private static final long MS_IN_HOUR = 60L * 60L * 1000L; + private Log L = null; private Transport transport; - private Tasks tasks; - private boolean shutdown; + //package-private so tests can wait until a sent request was handled + Tasks tasks; + private volatile boolean shutdown; + private volatile boolean backedOff; + + private final Object recheckLock = new Object(); + //a check asked for while a task ran, which a drain that found the queue empty would otherwise lose: + //null for none, else whether every check asked for came from the log gathering's own transport work + private Boolean pendingRecheck = null; + private boolean backendMode; + private ScheduledExecutorService backoffScheduler; IStorageForRequestQueue storageForRequestQueue; + /** + * Prepares the transport, the thread requests are sent on and the scheduler that ends a + * backoff, which starts its daemon thread only when a first backoff is scheduled. + * + * @param config configuration of the SDK being initialized + * @param storageForRequestQueue the request queue to drain + */ @Override public void init(InternalConfig config, IStorageForRequestQueue storageForRequestQueue) { L = config.getLogger(); shutdown = false; + backedOff = false; + backendMode = config.isBackendModeEnabled(); transport = new Transport(); transport.init(config); tasks = new Tasks("network", L); + backoffScheduler = Executors.newSingleThreadScheduledExecutor(runnable -> { + Thread thread = new Thread(runnable, BACKOFF_THREAD_NAME); + thread.setDaemon(true); + return thread; + }); this.storageForRequestQueue = storageForRequestQueue; } @@ -23,54 +61,419 @@ public boolean isSending() { return tasks.isRunning(); } + /** + * Starts draining the request queue unless the SDK stopped, there is no device ID yet or the + * backoff mechanism holds the queue back. While a request is being handled the check is kept + * for when the drain ends without handing a request over. A drain started from a thread marked + * as doing the log gathering's own transport work, which queued or sent a batch of gathered log + * lines, keeps that mark until it read the request to send. + * + * @param config configuration of the running SDK + * @return whether a request is being handled + */ @Override public boolean check(InternalConfig config) { - L.d("[Networking] [check] state: shutdown [" + shutdown + "], tasks running [" + tasks.isRunning() + "], net running [" + tasks.isRunning() + "], device id [" + config.getDeviceId() + "]"); - if (!shutdown && !tasks.isRunning() && config.getDeviceId() != null) { - tasks.run(submit(config)); + L.d("[Networking] [check] state: shutdown [" + shutdown + "], backed off [" + backedOff + "], tasks running [" + tasks.isRunning() + "], net running [" + tasks.isRunning() + "], device id [" + config.getDeviceId() + "]"); + if (!shutdown && !backedOff && config.getDeviceId() != null) { + boolean ownTransportWork = L.isOwnTransportWork(); + boolean drainNow; + //decided under the lock the end of a drain takes, so a check kept for that end is never kept too late + synchronized (recheckLock) { + drainNow = !tasks.isRunning(); + if (!drainNow) { + pendingRecheck = pendingRecheck == null ? ownTransportWork : pendingRecheck && ownTransportWork; + } + } + if (drainNow) { + drain(config, ownTransportWork); + } } return tasks.isRunning(); } - protected Tasks.Task submit(final InternalConfig config) { + /** + * Starts a queue drain. When it ends without handing a request over for sending, failing + * included, it checks again if a check was asked for meanwhile, as a request stored just after the drain read the + * queue would otherwise wait for the next check. A drain that hands a request over is followed + * by the check of that send, so one request is handled at a time. + * + * @param config configuration of the running SDK + * @param followsOwnTransportWork whether the log gathering's own transport work started the drain + */ + private void drain(@Nonnull InternalConfig config, boolean followsOwnTransportWork) { + synchronized (recheckLock) { + pendingRecheck = null; + } + final Tasks.Task drain = submit(config, followsOwnTransportWork); + tasks.run(new Tasks.Task(drain.id) { + /** + * Runs the drain, a failure counting as a drain that handed nothing over. + */ + @Override + public Boolean call() { + try { + return drain.call(); + } catch (Exception e) { + L.e("[Networking] drain, failed to handle the next request, [" + e + "]"); + return false; + } + } + }, handedOver -> { + if (!Boolean.TRUE.equals(handedOver)) { + recheckIfRequested(config); + } + }); + } + + /** + * Runs a check kept while a task ran, marked as the log gathering's own transport work when + * every thread that asked for it was. + * + * @param config configuration of the running SDK + */ + private void recheckIfRequested(@Nonnull InternalConfig config) { + Boolean followsOwnTransportWork; + synchronized (recheckLock) { + followsOwnTransportWork = pendingRecheck; + pendingRecheck = null; + } + if (followsOwnTransportWork == null) { + return; + } + + L.setOwnTransportWork(followsOwnTransportWork); + try { + check(config); + } finally { + L.setOwnTransportWork(false); + } + } + + /** + * Sends the oldest queued request, unless networking is off or the backoff mechanism holds the + * queue back. Queued requests older than the request drop age are dropped first, unsent. Once + * the server accepts the request the next one follows, unless the server answered so slowly + * that the backoff mechanism holds the queue back. + * + * @param config configuration of the running SDK + * @param followsOwnTransportWork whether the log gathering's own transport work started the + * drain, which then keeps the thread marked while the drain checks whether it may run and + * reads the request, so a drain that follows an upload does not report on it + * @return the task, resolving to whether a request was handed over for sending or removed + */ + protected Tasks.Task submit(final InternalConfig config, final boolean followsOwnTransportWork) { return new Tasks.Task(Tasks.ID_STRICT) { @Override public Boolean call() throws Exception { - final Request request = storageForRequestQueue.getNextRequest(); - if (request == null) { - return false; - } else { - L.d("[Networking] Preparing request: " + request); - final Boolean check = SDKCore.instance.isRequestReady(request); - if (check == null) { - L.d("[Networking] Request is not ready yet: " + request); + L.setOwnTransportWork(followsOwnTransportWork); + try { + if (!config.getNetworkingEnabled()) { + L.d("[Networking] submit, networking disabled by SDK behavior settings; skipping queue drain"); return false; - } else if (check.equals(Boolean.FALSE)) { - L.d("[Networking] Request won't be ready, removing: " + request); - Storage.remove(config, request); - return true; - } else { - if (request.params.has("rr")) { - request.params.remove("rr"); - } - request.params.add("rr", storageForRequestQueue.remaningRequests()); - tasks.run(transport.send(request), result -> { - L.d("[Networking] Request " + request.storageId() + " sent?: " + result); - if (result) { - storageForRequestQueue.removeRequest(request); - check(config); - } - }); - return true; } + if (backedOff) { + L.d("[Networking] submit, the backoff mechanism holds the request queue back; skipping queue drain"); + return false; + } + } finally { + L.setOwnTransportWork(false); + } + final Request request = nextRequestWithinDropAge(config, followsOwnTransportWork); + if (request == null) { + return false; + } + + boolean uploadsGatheredLogs = request.params.has(Log.keySdkLogs); + L.setOwnTransportWork(uploadsGatheredLogs); + try { + return prepareAndSend(config, request, uploadsGatheredLogs); + } finally { + L.setOwnTransportWork(false); } } }; } + /** + * Hands a queued request to the transport once its owner says it is ready, or removes it when + * its owner says it never will be. While the request carries a batch of gathered log lines, the + * thread is marked as doing their transport work, also while the send completes, so nothing + * logged about the upload is gathered, and once it is sent the logger may queue its next batch. + * + * @param config configuration of the running SDK + * @param request the oldest queued request + * @param uploadsGatheredLogs whether the request carries a batch of gathered log lines + * @return whether the request was handed over for sending or removed + */ + private boolean prepareAndSend(final InternalConfig config, final Request request, final boolean uploadsGatheredLogs) { + L.d("[Networking] Preparing request: " + request); + final Boolean check = SDKCore.instance.isRequestReady(request); + if (check == null) { + L.d("[Networking] Request is not ready yet: " + request); + return false; + } else if (check.equals(Boolean.FALSE)) { + L.d("[Networking] Request won't be ready, removing: " + request); + Storage.remove(config, request); + return true; + } + + if (request.params.has("rr")) { + request.params.remove("rr"); + } + request.params.add("rr", storageForRequestQueue.remaningRequests()); + final AtomicLong responseTimeMs = new AtomicLong(-1L); + tasks.run(transport.send(request, responseTimeMs::set), result -> { + L.setOwnTransportWork(uploadsGatheredLogs); + try { + L.d("[Networking] Request " + request.storageId() + " sent?: " + result + ", response time [" + responseTimeMs.get() + "] ms"); + if (result) { + storageForRequestQueue.removeRequest(request); + if (uploadsGatheredLogs) { + L.onLogBatchSent(); + } + if (!backendMode && responseTimeMs.get() >= 0 && responseTimeMs.get() < config.getConfigurationProvider().getBOMAcceptedTimeoutSeconds() * 1000L) { + L.logConsecutiveBackoffRequest(); + } + if (!backOffIfTheServerIsSlow(config, request, responseTimeMs.get())) { + check(config); + } + } + } finally { + L.setOwnTransportWork(false); + } + }); + return true; + } + + /** + * Reads the oldest queued request, first dropping, unsent, every queued request older than the + * request drop age of the SDK behavior settings. + * + * @param config configuration of the running SDK + * @param followsOwnTransportWork whether the log gathering's own transport work started the drain + * @return the request to send next, {@code null} when the queue is empty or a request could not be dropped + */ + @Nullable + private Request nextRequestWithinDropAge(@Nonnull InternalConfig config, boolean followsOwnTransportWork) { + Request request = readNextRequest(followsOwnTransportWork); + while (request != null && isOlderThanDropAge(config, request)) { + if (!dropWithoutSending(config, request)) { + return null; + } + request = readNextRequest(followsOwnTransportWork); + } + return request; + } + + /** + * Reads the oldest queued request. While the log gathering's own transport work started the + * drain, the thread is marked during the read, so the read it logs is not gathered, while a + * request dropped meanwhile is still reported. + * + * @param followsOwnTransportWork whether the log gathering's own transport work started the drain + * @return the request, {@code null} when the queue is empty + */ + @Nullable + private Request readNextRequest(boolean followsOwnTransportWork) { + L.setOwnTransportWork(followsOwnTransportWork); + try { + return storageForRequestQueue.getNextRequest(); + } finally { + L.setOwnTransportWork(false); + } + } + + /** + * Whether a queued request is older than the request drop age of the SDK behavior settings, a + * drop age of {@code 0} keeping every request. Never in backend mode, where the settings are + * inert and a request carries the time the application recorded it at. + * + * @param config configuration of the running SDK + * @param request the queued request + * @return {@code true} when the request has to be dropped without being sent + */ + private boolean isOlderThanDropAge(@Nonnull InternalConfig config, @Nonnull Request request) { + if (backendMode) { + return false; + } + + int dropAgeHours = config.getConfigurationProvider().getRequestDropAgeHours(); + return dropAgeHours > 0 && requestAgeMs(request) > dropAgeHours * MS_IN_HOUR; + } + + /** + * Removes a queued request without sending it, then tells the module that owns it, with a + * {@code null} response and {@link Transport#NO_RESPONSE_CODE}, so nothing keeps waiting for + * its response. + * + * @param config configuration of the running SDK + * @param request the request to drop + * @return whether the request was removed + */ + private boolean dropWithoutSending(@Nonnull InternalConfig config, @Nonnull Request request) { + L.w("[Networking] dropWithoutSending, request [" + request.storageId() + "] is older than the request drop age of [" + config.getConfigurationProvider().getRequestDropAgeHours() + "] hours set by the SDK behavior settings, dropping it without sending"); + L.recordLogCode("w330"); + if (!Boolean.TRUE.equals(storageForRequestQueue.removeRequest(request))) { + L.e("[Networking] dropWithoutSending, failed to remove request [" + request.storageId() + "], the queue drain stops here"); + return false; + } + if (request.params.has(Log.keySdkLogs)) { + L.onLogBatchSent(); + } + + Class requestOwner = request.owner(); + SDKCore core = SDKCore.instance; + if (requestOwner != null && core != null) { + try { + core.onRequestCompleted(request, null, Transport.NO_RESPONSE_CODE, requestOwner); + } catch (Exception e) { + L.e("[Networking] dropWithoutSending, failed to tell the owner of request [" + request.storageId() + "] that it was dropped, [" + e + "]"); + } + } + return true; + } + + /** + * How long ago a request was recorded, read from its {@code timestamp} parameter, or from its + * storage ID, which is taken from the clock when the request is created, when it has none. + * + * @param request the request + * @return the age in milliseconds, negative for a request dated in the future + */ + private long requestAgeMs(@Nonnull Request request) { + Long recordedAtMs = request.storageId(); + String timestamp = request.params == null ? null : request.params.get(TIMESTAMP_PARAM); + if (timestamp != null) { + try { + recordedAtMs = Long.parseLong(timestamp); + } catch (NumberFormatException e) { + L.w("[Networking] requestAgeMs, request [" + request.storageId() + "] has a timestamp that is not a number [" + timestamp + "], dating it by its storage ID"); + } + } + + long nowMs = System.currentTimeMillis(); + return recordedAtMs == null ? 0L : nowMs - recordedAtMs; + } + + /** + * Holds the request queue back for the backoff duration of the SDK behavior settings when the + * backoff mechanism is on and the server answered slowly: the response took at least the + * accepted timeout, the request is not older than the backoff request age, and the requests + * still queued are at most the given share of the request queue size. Never in backend mode, + * where the settings are inert. + * + * @param config configuration of the running SDK + * @param request the request the server just accepted, already removed from the queue + * @param responseTimeMs how long the server took to answer it, in milliseconds + * @return whether the queue is now held back + */ + private boolean backOffIfTheServerIsSlow(@Nonnull InternalConfig config, @Nonnull Request request, long responseTimeMs) { + if (backendMode) { + return false; + } + + ConfigurationProvider provider = config.getConfigurationProvider(); + if (!provider.getBOMEnabled() || responseTimeMs < provider.getBOMAcceptedTimeoutSeconds() * 1000L) { + return false; + } + + if (requestAgeMs(request) > provider.getBOMRequestAge() * MS_IN_HOUR) { + L.v("[Networking] backOffIfTheServerIsSlow, the server took [" + responseTimeMs + "] ms to answer request [" + request.storageId() + "], but the request is older than [" + provider.getBOMRequestAge() + "] hours, not backing off"); + return false; + } + + int queuedRequests = queuedRequestCount(); + if (queuedRequests < 0) { + return false; + } + + double queueShare = provider.getRequestQueueMaxSize() * provider.getBOMRQPercentage(); + if (queuedRequests > queueShare) { + L.v("[Networking] backOffIfTheServerIsSlow, the server took [" + responseTimeMs + "] ms to answer request [" + request.storageId() + "], but [" + queuedRequests + "] requests remain queued, more than [" + queueShare + "], not backing off"); + return false; + } + + int durationSeconds = provider.getBOMDuration(); + if (!startBackoff(config, durationSeconds)) { + return false; + } + L.w("[Networking] backOffIfTheServerIsSlow, the server took [" + responseTimeMs + "] ms to answer request [" + request.storageId() + "] and [" + queuedRequests + "] requests remain queued, holding the request queue back for [" + durationSeconds + "] seconds"); + L.logBackoffRequest(); + return true; + } + + /** + * How many requests the queue holds. + * + * @return the number of queued requests, {@code -1} when they could not be counted + */ + private int queuedRequestCount() { + try { + Integer remaining = storageForRequestQueue.remaningRequests(); + return remaining == null ? -1 : remaining + 1; + } catch (RuntimeException e) { + L.w("[Networking] queuedRequestCount, failed to count the queued requests, not backing off, [" + e + "]"); + return -1; + } + } + + /** + * Holds the request queue back for the given time, after which it drains again. + * + * @param config configuration of the running SDK + * @param durationSeconds how long to hold the queue back + * @return whether the queue is held back, {@code false} when the SDK is stopping + */ + private boolean startBackoff(@Nonnull final InternalConfig config, int durationSeconds) { + backedOff = true; + try { + backoffScheduler.schedule(() -> endBackoff(config), durationSeconds, TimeUnit.SECONDS); + return true; + } catch (RejectedExecutionException e) { + backedOff = false; + L.d("[Networking] startBackoff, the SDK is stopping, the request queue is not held back"); + return false; + } + } + + /** + * Ends a backoff and lets the request queue drain again, unless the SDK stopped meanwhile. + * + * @param config configuration of the running SDK + */ + private void endBackoff(@Nonnull InternalConfig config) { + backedOff = false; + if (shutdown) { + return; + } + + L.d("[Networking] endBackoff, the backoff is over, the request queue drains again"); + try { + check(config); + } catch (RuntimeException e) { + L.w("[Networking] endBackoff, failed to restart the request queue drain, [" + e + "]"); + } + } + + /** + * Stops sending. A backoff that is still running never ends in a drain, and a request that is + * being sent may finish. + * + * @param config configuration of the SDK being stopped + */ @Override public void stop(InternalConfig config) { shutdown = true; + if (backoffScheduler != null) { + backoffScheduler.shutdownNow(); + try { + if (!backoffScheduler.awaitTermination(1, TimeUnit.SECONDS)) { + L.w("[Networking] stop, the backoff scheduler did not stop in time"); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } tasks.shutdown(); } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/EventImpl.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/EventImpl.java index 211628f56..b0913d623 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/EventImpl.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/EventImpl.java @@ -102,6 +102,16 @@ public void record() { return; } + L.w("[EventImpl] record, this function is deprecated, use 'events().recordEvent' instead"); + L.recordLogCode("w120"); + L.recordUsage(HealthCheckCounter.AREA_EVENTS, "record:d"); + recordInternal(); + } + + /** + * Hands the event to its recorder once. + */ + private void recordInternal() { if (recorder != null && !invalid) { invalid = true; recorder.recordEvent(this); @@ -117,8 +127,11 @@ public void endAndRecord() { return; } + L.w("[EventImpl] endAndRecord, this function is deprecated, use 'events().endEvent' instead"); + L.recordLogCode("w120"); + L.recordUsage(HealthCheckCounter.AREA_EVENTS, "endAndRecord:d"); setDuration((TimeUtils.timestampMs() - timestamp) / 1000); - record(); + recordInternal(); } @Override diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/HealthCheckCounter.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/HealthCheckCounter.java new file mode 100644 index 000000000..f88391822 --- /dev/null +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/HealthCheckCounter.java @@ -0,0 +1,492 @@ +package ly.count.sdk.java.internal; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.function.Predicate; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * The counters of the SDK health check: warnings and errors logged, the last failed request, + * backoffs, method usage ("fu") and log codes ("lc"), kept since the last health check the server + * accepted. Logs at debug level only, as every warning and error the SDK logs is counted here. + */ +public class HealthCheckCounter { + static final int COUNT_CAP = 65535; + static final int MAX_ERROR_MESSAGE_LENGTH = 1000; + + static final String KEY_LOG_ERROR = "LErr"; + static final String KEY_LOG_WARNING = "LWar"; + static final String KEY_STATUS_CODE = "RStatC"; + static final String KEY_ERROR_MESSAGE = "REMsg"; + static final String KEY_BACKOFF_REQUEST = "BReq"; + static final String KEY_CONSECUTIVE_BACKOFF_REQUEST = "CBReq"; + static final String KEY_METHOD_USAGE = "MU"; + static final String KEY_LOG_CODES = "LC"; + + static final String REQUEST_KEY_ERROR_COUNT = "el"; + static final String REQUEST_KEY_WARNING_COUNT = "wl"; + static final String REQUEST_KEY_STATUS_CODE = "sc"; + static final String REQUEST_KEY_ERROR_MESSAGE = "em"; + static final String REQUEST_KEY_BACKOFF_REQUEST = "bom"; + static final String REQUEST_KEY_CONSECUTIVE_BACKOFF_REQUEST = "cbom"; + static final String REQUEST_KEY_METHOD_USAGE = "fu"; + static final String REQUEST_KEY_LOG_CODES = "lc"; + + static final String AREA_SESSIONS = "sessions"; + static final String AREA_EVENTS = "events"; + static final String AREA_VIEWS = "views"; + static final String AREA_CRASHES = "crashes"; + + long countLogWarning = 0; + long countLogError = 0; + int statusCode = -1; + String errorMessage = ""; + long countBackoffRequest = 0; + int consecutiveBackoffRequest = 0; + private int consecutiveBackoffRequestCounter = 0; + final Map> methodUsage = new HashMap<>(); + final Map logCodes = new HashMap<>(); + + private volatile boolean recordingStoppedForCrash = false; + private final StorageProvider storageProvider; + private final Log L; + private final Predicate consentGiven; + + /** + * Creates the counters from the state a previous run stored, and adds the automatically + * detected crashes that run counted to "crashes" / "record:a". + * + * @param storageProvider the storage the state is kept in + * @param logger the SDK logger, used at debug level only + * @param consentGiven whether a feature has consent now, {@code true} for every feature while no consent is required + */ + public HealthCheckCounter(@Nonnull StorageProvider storageProvider, @Nonnull Log logger, @Nonnull Predicate consentGiven) { + this.storageProvider = storageProvider; + this.L = logger; + this.consentGiven = consentGiven; + + setupInitialCounters(storageProvider.getHealthCheckState()); + + int automaticCrashes = storageProvider.takeAutomaticCrashCount(); + if (automaticCrashes > 0) { + synchronized (this) { + addUsage(AREA_CRASHES, "record:a", automaticCrashes); + } + saveState(); + } + } + + /** + * Adds the counters a previous run stored to the current ones. A stored state that is not valid + * JSON is reset and reported as log code e503. An entry of the wrong type is skipped. + * + * @param initialState the stored state, {@code null} or empty when nothing was stored + */ + void setupInitialCounters(@Nullable String initialState) { + if (initialState == null || initialState.isEmpty()) { + return; + } + + JSONObject stored; + try { + stored = new JSONObject(initialState); + } catch (JSONException e) { + clearAndSave(); + synchronized (this) { + addLogCode("e503", 1); + } + L.d("[HealthCheckCounter] setupInitialCounters, the stored health check state could not be read and is reset, [" + e + "]"); + return; + } + + synchronized (this) { + countLogWarning += optLong(stored, KEY_LOG_WARNING); + countLogError += optLong(stored, KEY_LOG_ERROR); + if (statusCode == -1 && stored.opt(KEY_STATUS_CODE) instanceof Number) { + statusCode = ((Number) stored.opt(KEY_STATUS_CODE)).intValue(); + } + if (errorMessage.isEmpty() && stored.opt(KEY_ERROR_MESSAGE) instanceof String) { + errorMessage = (String) stored.opt(KEY_ERROR_MESSAGE); + } + countBackoffRequest += optLong(stored, KEY_BACKOFF_REQUEST); + consecutiveBackoffRequest = (int) Math.max(consecutiveBackoffRequest, optLong(stored, KEY_CONSECUTIVE_BACKOFF_REQUEST)); + + JSONObject storedUsage = stored.optJSONObject(KEY_METHOD_USAGE); + if (storedUsage != null) { + Iterator areas = storedUsage.keys(); + while (areas.hasNext()) { + String area = areas.next(); + JSONObject methods = storedUsage.optJSONObject(area); + if (methods == null) { + continue; + } + Iterator methodNames = methods.keys(); + while (methodNames.hasNext()) { + String method = methodNames.next(); + if (methods.opt(method) instanceof Number) { + addUsage(area, method, ((Number) methods.opt(method)).intValue()); + } + } + } + } + + JSONObject storedCodes = stored.optJSONObject(KEY_LOG_CODES); + if (storedCodes != null) { + Iterator codes = storedCodes.keys(); + while (codes.hasNext()) { + String code = codes.next(); + if (storedCodes.opt(code) instanceof Number) { + addLogCode(code, ((Number) storedCodes.opt(code)).intValue()); + } + } + } + } + + L.d("[HealthCheckCounter] setupInitialCounters, loaded the stored health check state [" + stored + "]"); + } + + private static long optLong(@Nonnull JSONObject json, @Nonnull String key) { + Object value = json.opt(key); + return value instanceof Number ? Math.max(0, ((Number) value).longValue()) : 0; + } + + /** + * Counts one warning the SDK logged. + */ + void logWarning() { + synchronized (this) { + countLogWarning++; + } + } + + /** + * Counts one error the SDK logged. + */ + void logError() { + synchronized (this) { + countLogError++; + } + } + + /** + * Keeps the answer of the server to a queued request it did not accept. Only the most recent + * one is kept. + * + * @param statusCode the HTTP status code, ignored unless above 0 and below 1000 + * @param errorResponse the body of the answer, cut to 1000 characters + */ + void logFailedNetworkRequest(int statusCode, @Nullable String errorResponse) { + if (statusCode <= 0 || statusCode >= 1000) { + return; + } + + String response = errorResponse == null ? "" : errorResponse; + synchronized (this) { + this.statusCode = statusCode; + this.errorMessage = response.length() > MAX_ERROR_MESSAGE_LENGTH ? response.substring(0, MAX_ERROR_MESSAGE_LENGTH) : response; + } + } + + /** + * Counts a backoff of the request queue and extends the current run of backoffs in a row. The + * longest run ("cbom") is raised right away, so no save has to end the run to keep it. Records + * log code w320, and w321 when the backoff continues a run. The run is kept in memory only, so + * a restart ends it. + */ + void logBackoffRequest() { + synchronized (this) { + boolean continuesRun = consecutiveBackoffRequestCounter > 0; + countBackoffRequest++; + consecutiveBackoffRequestCounter++; + consecutiveBackoffRequest = Math.max(consecutiveBackoffRequest, consecutiveBackoffRequestCounter); + + if (!recordingStoppedForCrash) { + addLogCode("w320", 1); + if (continuesRun) { + addLogCode("w321", 1); + } + } + } + } + + /** + * Ends the current run of backoffs in a row, when a queued request was answered in time. The + * longest run is already kept by {@link #logBackoffRequest()}. + */ + void logConsecutiveBackoffRequest() { + synchronized (this) { + consecutiveBackoffRequestCounter = 0; + } + } + + /** + * Counts one call of a method for the "fu" map, under its feature area and method name. A call + * the SDK made by itself carries ":a", a deprecated method ":d". Nothing is counted while consent + * is required and the feature of the area has no consent, or while an automatic crash is reported. + * + * @param area the feature area: "sessions", "events", "views" or "crashes" + * @param method the method name with its modifiers + */ + void recordUsage(@Nullable String area, @Nullable String method) { + if (area == null || method == null || area.isEmpty() || method.isEmpty() || recordingStoppedForCrash) { + return; + } + + if (!hasConsentForUsageArea(area)) { + return; + } + + synchronized (this) { + addUsage(area, method, 1); + } + } + + /** + * Counts occurrences of a log code for the "lc" map, a level letter and three digits such as "w740". + * + * @param code the log code + * @param count how many times the condition occurred + */ + void recordLogCode(@Nullable String code, int count) { + if (code == null || code.isEmpty() || count <= 0 || recordingStoppedForCrash) { + return; + } + + synchronized (this) { + addLogCode(code, count); + } + } + + /** + * Counts one occurrence of a log code that a public method of a feature area records. Like + * {@link #recordUsage(String, String)}, nothing is counted while consent is required and the + * feature of the area has no consent. + * + * @param code the log code + * @param area the feature area of the method that recorded it + */ + void recordLogCode(@Nullable String code, @Nullable String area) { + if (!hasConsentForUsageArea(area)) { + return; + } + + recordLogCode(code, 1); + } + + /** + * Makes method usage and log codes ignore their calls while an automatically detected crash is + * reported, so the report never counts into these maps. + */ + void stopRecordingForCrash() { + recordingStoppedForCrash = true; + } + + /** + * Lets method usage and log codes count again after an automatically detected crash was + * reported. A Java process outlives a crashed thread, so counting goes on once the report is stored. + */ + void resumeRecordingAfterCrash() { + recordingStoppedForCrash = false; + } + + /** + * Whether calls of a method usage area are counted: the feature behind it has consent, or no + * consent is required. An unknown area is never counted. + * + * @param area the method usage area + * @return {@code true} when calls of the area are counted + */ + boolean hasConsentForUsageArea(@Nullable String area) { + if (area == null) { + return false; + } + + switch (area) { + case AREA_SESSIONS: + return consentGiven.test(CoreFeature.Sessions); + case AREA_EVENTS: + return consentGiven.test(CoreFeature.Events); + case AREA_VIEWS: + return consentGiven.test(CoreFeature.Views); + case AREA_CRASHES: + return consentGiven.test(CoreFeature.CrashReporting); + default: + return false; + } + } + + /** + * Adds to the count of a method, up to the cap a health check reports. Call while holding this + * object's lock. + */ + private void addUsage(@Nonnull String area, @Nonnull String method, int count) { + if (count <= 0) { + return; + } + + Map methods = methodUsage.computeIfAbsent(area, key -> new HashMap<>()); + Integer current = methods.get(method); + methods.put(method, (int) Math.min((long) (current == null ? 0 : current) + count, COUNT_CAP)); + } + + /** + * Adds to the count of a log code, up to the cap a health check reports. Call while holding this + * object's lock. + */ + private void addLogCode(@Nonnull String code, int count) { + if (count <= 0) { + return; + } + + Integer current = logCodes.get(code); + logCodes.put(code, (int) Math.min((long) (current == null ? 0 : current) + count, COUNT_CAP)); + } + + /** + * Resets every counter to its default and clears the stored state. + */ + void clearAndSave() { + synchronized (this) { + countLogWarning = 0; + countLogError = 0; + statusCode = -1; + errorMessage = ""; + countBackoffRequest = 0; + consecutiveBackoffRequest = 0; + consecutiveBackoffRequestCounter = 0; + methodUsage.clear(); + logCodes.clear(); + } + storageProvider.setHealthCheckState(""); + } + + /** + * Stores the counters. The current run of backoffs in a row goes on, as "cbom" already holds + * the longest run. The storage is written outside this object's lock, since writing can log. + */ + void saveState() { + String state; + synchronized (this) { + JSONObject json = new JSONObject(); + json.put(KEY_LOG_WARNING, countLogWarning); + json.put(KEY_LOG_ERROR, countLogError); + json.put(KEY_STATUS_CODE, statusCode); + json.put(KEY_ERROR_MESSAGE, errorMessage); + json.put(KEY_BACKOFF_REQUEST, countBackoffRequest); + json.put(KEY_CONSECUTIVE_BACKOFF_REQUEST, consecutiveBackoffRequest); + json.put(KEY_METHOD_USAGE, usageToJson()); + json.put(KEY_LOG_CODES, new JSONObject(logCodes)); + state = json.toString(); + } + + storageProvider.setHealthCheckState(state); + } + + /** + * The method usage counts as a JSON object. Call while holding this object's lock. + */ + @Nonnull + private JSONObject usageToJson() { + JSONObject usage = new JSONObject(); + for (Map.Entry> area : methodUsage.entrySet()) { + usage.put(area.getKey(), new JSONObject(area.getValue())); + } + return usage; + } + + /** + * The health check parameter as it is sent, taken from the current counters. "fu" and "lc" are + * always present, empty when nothing was counted, so the server can tell an SDK that reports + * them from one that does not. + * + * @return a copy of the counters that later counting does not change + */ + @Nonnull + JSONObject snapshot() { + JSONObject json = new JSONObject(); + synchronized (this) { + json.put(REQUEST_KEY_ERROR_COUNT, countLogError); + json.put(REQUEST_KEY_WARNING_COUNT, countLogWarning); + json.put(REQUEST_KEY_STATUS_CODE, statusCode); + json.put(REQUEST_KEY_ERROR_MESSAGE, errorMessage); + json.put(REQUEST_KEY_BACKOFF_REQUEST, countBackoffRequest); + json.put(REQUEST_KEY_CONSECUTIVE_BACKOFF_REQUEST, consecutiveBackoffRequest); + json.put(REQUEST_KEY_METHOD_USAGE, usageToJson()); + json.put(REQUEST_KEY_LOG_CODES, new JSONObject(logCodes)); + } + return json; + } + + /** + * Takes away what a health check the server accepted reported, so what was counted while it was + * on its way is reported next time. The last failed request and the longest backoff run are + * cleared only when they did not change since. Stores what is left. + * + * @param sent the snapshot the delivered health check was built from + */ + void clearSentValues(@Nonnull JSONObject sent) { + synchronized (this) { + countLogError = Math.max(0, countLogError - sent.optLong(REQUEST_KEY_ERROR_COUNT, 0)); + countLogWarning = Math.max(0, countLogWarning - sent.optLong(REQUEST_KEY_WARNING_COUNT, 0)); + countBackoffRequest = Math.max(0, countBackoffRequest - sent.optLong(REQUEST_KEY_BACKOFF_REQUEST, 0)); + + if (consecutiveBackoffRequest == sent.optInt(REQUEST_KEY_CONSECUTIVE_BACKOFF_REQUEST, -1)) { + consecutiveBackoffRequest = 0; + } + + if (statusCode == sent.optInt(REQUEST_KEY_STATUS_CODE, -2) && errorMessage.equals(sent.optString(REQUEST_KEY_ERROR_MESSAGE, ""))) { + statusCode = -1; + errorMessage = ""; + } + + JSONObject sentUsage = sent.optJSONObject(REQUEST_KEY_METHOD_USAGE); + if (sentUsage != null) { + Iterator areas = sentUsage.keys(); + while (areas.hasNext()) { + String area = areas.next(); + JSONObject sentMethods = sentUsage.optJSONObject(area); + Map counted = methodUsage.get(area); + if (sentMethods == null || counted == null) { + continue; + } + Iterator methods = sentMethods.keys(); + while (methods.hasNext()) { + String method = methods.next(); + subtract(counted, method, sentMethods.optInt(method, 0)); + } + if (counted.isEmpty()) { + methodUsage.remove(area); + } + } + } + + JSONObject sentCodes = sent.optJSONObject(REQUEST_KEY_LOG_CODES); + if (sentCodes != null) { + Iterator codes = sentCodes.keys(); + while (codes.hasNext()) { + String code = codes.next(); + subtract(logCodes, code, sentCodes.optInt(code, 0)); + } + } + } + + saveState(); + } + + /** + * Takes a reported amount away from a count, removing the count when nothing is left. + */ + private static void subtract(@Nonnull Map counts, @Nonnull String key, int reported) { + Integer current = counts.get(key); + int left = (current == null ? 0 : current) - reported; + if (left > 0) { + counts.put(key, left); + } else { + counts.remove(key); + } + } +} diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ImmediateRequestMaker.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ImmediateRequestMaker.java index 36683c06a..e9f065f23 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ImmediateRequestMaker.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ImmediateRequestMaker.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.net.HttpURLConnection; import java.util.concurrent.CompletableFuture; +import org.json.JSONException; import org.json.JSONObject; /** @@ -69,7 +70,7 @@ private JSONObject doInBackground(String requestData, String customEndpoint, Tra try { connection = cp.connection(request); } catch (IOException e) { - L.e("[ImmediateRequestMaker] IOException while preparing remote config update request :[" + e + "]"); + L.d("[ImmediateRequestMaker] IOException while preparing remote config update request :[" + e + "]"); return null; } //connecting @@ -79,7 +80,7 @@ private JSONObject doInBackground(String requestData, String customEndpoint, Tra String receivedBuffer = cp.response(connection); if (receivedBuffer == null) { - L.e("[ImmediateRequestMaker] Encountered problem while making a immediate server request, received result was null"); + L.d("[ImmediateRequestMaker] Encountered problem while making a immediate server request, received result was null"); return null; } @@ -92,11 +93,15 @@ private JSONObject doInBackground(String requestData, String customEndpoint, Tra } return new JSONObject(receivedBuffer); } else { - L.e("[ImmediateRequestMaker] Encountered problem while making a immediate server request, :[" + receivedBuffer + "]"); + L.d("[ImmediateRequestMaker] Encountered problem while making a immediate server request, :[" + receivedBuffer + "]"); + cp.blockCompressionIfCompressed(connection); return null; } + } catch (JSONException | StringIndexOutOfBoundsException e) { + L.d("[ImmediateRequestMaker] Received an answer that is empty or not JSON while making a immediate server request, [" + e.getMessage() + "]"); + cp.blockCompressionIfCompressed(connection); } catch (Exception e) { - L.e("[ImmediateRequestMaker] Received exception while making a immediate server request " + e.getMessage()); + L.d("[ImmediateRequestMaker] Received exception while making a immediate server request " + e.getMessage()); } finally { if (connection != null) { connection.disconnect(); diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/InternalConfig.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/InternalConfig.java index d446315de..721ccf64b 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/InternalConfig.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/InternalConfig.java @@ -2,11 +2,13 @@ import java.io.File; import java.lang.reflect.Field; +import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import javax.annotation.Nonnull; import ly.count.sdk.java.Config; /** @@ -32,6 +34,11 @@ public class InternalConfig extends Config { protected IdGenerator viewIdGenerator; protected IdGenerator eventIdGenerator; protected ViewIdProvider viewIdProvider; + /** + * The SDK behavior settings of the running SDK, registered by {@link ModuleConfiguration} when it + * initializes. Read it through {@link #getConfigurationProvider()}. + */ + volatile ConfigurationProvider configProvider; /** * Shouldn't be used! @@ -144,13 +151,65 @@ public void setDefaultNetworking(boolean defaultNetworking) { } /** - * This feature is not yet implemented - * and always return true + * The SDK behavior settings in effect. While no {@link ModuleConfiguration} is registered on + * this configuration, as for a module built on its own in a test, the settings come from this + * configuration alone. * - * @return true + * @return the settings, never {@code null} + */ + @Nonnull + ConfigurationProvider getConfigurationProvider() { + ConfigurationProvider provider = configProvider; + if (provider != null) { + return provider; + } + return ModuleConfiguration.developerDefaults(this); + } + + /** + * Whether the SDK is currently allowed to perform network requests, the {@code networking} + * switch of the SDK behavior settings. + * + * @return {@code true} if networking is allowed */ public boolean getNetworkingEnabled() { - return true; + return getConfigurationProvider().getNetworkingEnabled(); + } + + public String getSdkBehaviorSettings() { + return sdkBehaviorSettings; + } + + public boolean isSdkBehaviorSettingsRequestsDisabled() { + return sdkBehaviorSettingsRequestsDisabled; + } + + /** + * Whether the developer turned request compression on, see {@link Config#enableRequestCompression()}. + * + * @return {@code true} after {@link Config#enableRequestCompression()} + */ + boolean isRequestCompressionEnabled() { + return requestCompressionEnabled; + } + + /** + * Whether the SDK sends its health check, see {@link Config#disableHealthCheck()}. + * + * @return {@code true} unless the health check was disabled + */ + boolean isHealthCheckEnabled() { + return healthCheckEnabled; + } + + /** + * Whether the developer left the backoff mechanism on, the value the {@code bom} setting of the + * SDK behavior settings starts from. + * + * @return {@code false} after {@link Config#disableBackoffMechanism()} + */ + boolean isBackoffMechanismEnabled() { + return backoffMechanismEnabled; } /** @@ -189,6 +248,24 @@ public void setLogger(Log logger) { this.configLog = logger; } + /** + * Replaces the server URL every later request is sent to, in this configuration only. + * + * @param serverURL the new server URL + */ + void setServerURL(@Nonnull URL serverURL) { + this.serverURL = serverURL; + } + + /** + * Replaces the app key every later request carries, in this configuration only. + * + * @param serverAppKey the new app key + */ + void setServerAppKey(@Nonnull String serverAppKey) { + this.serverAppKey = serverAppKey; + } + File getSdkStorageRootDirectory() { return sdkStorageRootDirectory; } @@ -205,6 +282,15 @@ int getMaxBreadcrumbCount() { return maxBreadcrumbCount; } + /** + * The key length limit the developer set. + * + * @return the limit, {@link Integer#MAX_VALUE} when none is set + */ + int getMaxKeyLength() { + return maxKeyLength; + } + String[] getLocationParams() { return new String[] { country, city, location, ip }; } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/JsonFileStorage.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/JsonFileStorage.java index 9fb214eaa..e823d540f 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/JsonFileStorage.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/JsonFileStorage.java @@ -3,8 +3,12 @@ import java.io.BufferedWriter; import java.io.File; import java.io.IOException; +import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.Files; +import java.nio.file.StandardCopyOption; import javax.annotation.Nonnull; +import org.json.JSONArray; +import org.json.JSONException; import org.json.JSONObject; public class JsonFileStorage { @@ -21,9 +25,22 @@ public class JsonFileStorage { public JsonFileStorage(@Nonnull final File file, @Nonnull Log logger) { this.logger = logger; this.file = file; + deleteLeftoverTemporaryFile(); this.json = readJsonFile(file); } + /** + * Deletes the temporary file of a save that was stopped before its move. The json file still + * holds the previous save then, and a leftover file would be taken for other stored SDK data. + */ + private void deleteLeftoverTemporaryFile() { + try { + Files.deleteIfExists(temporaryFileOf(file).toPath()); + } catch (IOException e) { + logger.w("[JsonFileStorage] deleteLeftoverTemporaryFile, Failed to delete the temporary file, reason: [" + e + "]"); + } + } + /** * If key exists changes its value, otherwise adds new key-value pair * Null key or value is not allowed @@ -32,21 +49,61 @@ public JsonFileStorage(@Nonnull final File file, @Nonnull Log logger) { * @param key to set * @param value to add */ - public void add(@Nonnull final String key, @Nonnull Object value) { + public synchronized void add(@Nonnull final String key, @Nonnull Object value) { logger.i("[JsonFileStorage] add, Adding key: [" + key + "], value: [" + value + "]"); json.put(key, value); } /** - * Saves changes to the disk/db/memory + * Saves changes to the disk/db/memory. The data is written next to the file and then moved over + * it, so a process stopped while saving leaves the previous file whole. When the data cannot be + * serialized, the file keeps what it had. */ - public void save() { + public synchronized void save() { logger.i("[JsonFileStorage] save, Saving json file: [" + file.getAbsolutePath() + "]"); - try (BufferedWriter writer = Files.newBufferedWriter(file.toPath())) { - writer.write(json.toString()); + // toString returns null instead of throwing, so a failed serialization has to be caught before anything is written + String content = json.toString(); + if (content == null) { + logger.e("[JsonFileStorage] save, Failed to serialize the data, the json file is left as it is: [" + file.getAbsolutePath() + "]"); + logger.recordLogCode("e501"); + return; + } + + File temporary = temporaryFileOf(file); + try { + try (BufferedWriter writer = Files.newBufferedWriter(temporary.toPath())) { + writer.write(content); + } + replaceFile(temporary, file); } catch (IOException e) { logger.e("[JsonFileStorage] save, Failed to save json file, reason: [" + e.getMessage() + "]"); + logger.recordLogCode("e501"); + } + } + + /** + * The file a save writes before moving it over the json file. + * + * @param file the json file + * @return the temporary file next to it + */ + static File temporaryFileOf(@Nonnull File file) { + return new File(file.getAbsolutePath() + ".tmp"); + } + + /** + * Moves a file over another, atomically where the file system supports it. + * + * @param source the file to move + * @param target the file it replaces + * @throws IOException when the move fails + */ + private static void replaceFile(@Nonnull File source, @Nonnull File target) throws IOException { + try { + Files.move(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (AtomicMoveNotSupportedException e) { + Files.move(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING); } } @@ -57,7 +114,7 @@ public void save() { * * @param key to remove */ - public void delete(@Nonnull final String key) { + public synchronized void delete(@Nonnull final String key) { if (!json.has(key)) { logger.v("[JsonFileStorage] delete, Nothing to delete"); } @@ -71,7 +128,7 @@ public void delete(@Nonnull final String key) { * @param key to set * @param value to add */ - public void addAndSave(@Nonnull final String key, @Nonnull Object value) { + public synchronized void addAndSave(@Nonnull final String key, @Nonnull Object value) { add(key, value); save(); } @@ -82,7 +139,7 @@ public void addAndSave(@Nonnull final String key, @Nonnull Object value) { * * @param key to remove */ - public void deleteAndSave(@Nonnull final String key) { + public synchronized void deleteAndSave(@Nonnull final String key) { delete(key); save(); } @@ -94,19 +151,53 @@ public void deleteAndSave(@Nonnull final String key) { * @param key to get * @return value */ - public Object get(@Nonnull final String key) { + public synchronized Object get(@Nonnull final String key) { return json.opt(key); } /** - * Returns JSONObject value for the key + * Returns a copy of the JSONObject value for the key. Changing the copy changes nothing stored: + * hand it back through {@link #add(String, Object)} to store it, so another thread that saves + * never serializes an object while it is being changed. * * @param key to get * @param defaultValue to return if key not found - * @return value, if key not found returns defaultValue + * @return a deep copy of the value, if key not found returns defaultValue + */ + public synchronized JSONObject getJsonObj(@Nonnull final String key, final JSONObject defaultValue) { + JSONObject value = json.optJSONObject(key, null); + if (value == null) { + return defaultValue; + } + return (JSONObject) deepCopy(value); + } + + /** + * Copies a JSON value, every nested object and array included, keeping every other value as it is. + * + * @param value the value to copy + * @return the copy, or the value itself when it holds nothing that can change */ - public JSONObject getJsonObj(@Nonnull final String key, final JSONObject defaultValue) { - return json.optJSONObject(key, defaultValue); + private static Object deepCopy(final Object value) { + if (value instanceof JSONObject) { + JSONObject source = (JSONObject) value; + JSONObject copy = new JSONObject(); + for (String key : source.keySet()) { + copy.put(key, deepCopy(source.opt(key))); + } + return copy; + } + + if (value instanceof JSONArray) { + JSONArray source = (JSONArray) value; + JSONArray copy = new JSONArray(); + for (int i = 0; i < source.length(); i++) { + copy.put(deepCopy(source.opt(i))); + } + return copy; + } + + return value; } /** @@ -115,7 +206,7 @@ public JSONObject getJsonObj(@Nonnull final String key, final JSONObject default * @param key to get * @return value, if key not found returns null */ - public String getString(@Nonnull final String key) { + public synchronized String getString(@Nonnull final String key) { return getString(key, null); } @@ -126,7 +217,7 @@ public String getString(@Nonnull final String key) { * @param defaultValue to return if key not found * @return value, if key not found returns defaultValue */ - public String getString(@Nonnull final String key, final String defaultValue) { + public synchronized String getString(@Nonnull final String key, final String defaultValue) { return json.optString(key, defaultValue); } @@ -137,21 +228,21 @@ public String getString(@Nonnull final String key, final String defaultValue) { * @param defaultValue to return if key not found * @return value, if key not found returns defaultValue */ - public int getInt(@Nonnull final String key, final int defaultValue) { + public synchronized int getInt(@Nonnull final String key, final int defaultValue) { return json.optInt(key, defaultValue); } /** * Clears all data */ - public void clear() { + public synchronized void clear() { json.clear(); } /** * Clears all data and saves changes to the disk/db/memory */ - public void clearAndSave() { + public synchronized void clearAndSave() { clear(); save(); } @@ -161,7 +252,7 @@ public void clearAndSave() { * * @return number of key-value pairs */ - public int size() { + public synchronized int size() { return json.length(); } @@ -182,6 +273,9 @@ private JSONObject readJsonFile(@Nonnull final File file) { } catch (IOException e) { logger.e("[JsonFileStorage] readJsonFile, Failed to read json file, reason: [" + e.getMessage() + "]"); return new JSONObject(); + } catch (JSONException e) { + logger.e("[JsonFileStorage] readJsonFile, The json file is not valid json, starting with empty storage that replaces it on the next save: [" + file.getAbsolutePath() + "], reason: [" + e.getMessage() + "]"); + return new JSONObject(); } } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/Log.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/Log.java index 2fd4a8f7b..8429c687c 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/Log.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/Log.java @@ -1,24 +1,193 @@ package ly.count.sdk.java.internal; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.IntSupplier; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import ly.count.sdk.java.Config; +import ly.count.sdk.java.internal.ConfigurationProvider.LogGatheringState; +import org.json.JSONObject; /** * Logging module. Exposes static functions for simplicity, thus can be used only from some point * in time when {@link Config} is created and {@link ModuleBase}s are up. + *

+ * The logger also gathers the SDK's own lines for the server when the {@code lg} directive of the + * SDK behavior settings asks for them, and uploads them as the {@code sdk_logs} parameter of + * requests of their own, shaped {@code {"i":gatherId,"d":dropped,"l":[{"t":ms,"l":"e","m":message}]}}. + * Every level is captured, whatever is printed. Capture starts with the first line, into a + * provisional buffer, since the init lines are the ones worth having: a live directive adopts the + * buffer filtered to its levels, or drops it. Nothing of it is ever stored. A line whose consent + * is not given when it is logged waits apart until it is, see {@link #logLineConsentFeatures(String)}. */ public class Log { + static final String keySdkLogs = "sdk_logs"; + //a line that carries an uploaded batch is never gathered, or each batch would nest the previous one + static final String transportMarker = keySdkLogs + "="; + + static final String keyBatchGatherId = "i"; + static final String keyBatchDroppedCount = "d"; + static final String keyBatchLines = "l"; + static final String keyLineTimestamp = "t"; + static final String keyLineLevel = "l"; + static final String keyLineMessage = "m"; + + //the server keeps at most this many characters of a message + static final int maxMessageLength = 4096; + //a ceiling on the characters held, since the line ceiling alone does not bound the memory + static final int gatheredCharCeiling = 128 * 1024; + static final String DELIVERY_THREAD_NAME = "Countly-LogDelivery"; + + //the longest bracketed name a line starts with, so finding it never scans a long line to its end + private static final int maxLogLineNameLength = 64; + //the consent a line of no feature needs, as it can quote any feature's data, such as a whole request + static final int UNATTRIBUTED_LINE_CONSENT = CoreFeature.Events.getIndex() | CoreFeature.UserProfiles.getIndex(); + + /** + * The consent a gathered line needs while consent is required, by the name its message starts + * with in brackets, as in {@code "[ModuleEvents] ..."}: the features any one of whose consent + * lets the line go. A line of any other name needs {@link #UNATTRIBUTED_LINE_CONSENT}. + */ + private static final Map logLineConsent; + + static { + Map consent = new HashMap<>(); + mapLogLineConsent(consent, CoreFeature.Events, "ModuleEvents", "Events", "EventImpl", "EventQueue", "TimedEvents"); + mapLogLineConsent(consent, CoreFeature.Sessions, "ModuleSessions", "SessionImpl"); + mapLogLineConsent(consent, CoreFeature.Views, "ModuleViews", "Views", "ViewImpl", "View"); + mapLogLineConsent(consent, CoreFeature.CrashReporting, "ModuleCrash", "Crashes", "CrashImpl"); + mapLogLineConsent(consent, CoreFeature.Location, "ModuleLocation", "Location"); + mapLogLineConsent(consent, CoreFeature.UserProfiles, "ModuleUserProfile", "UserProfile", "UserEditorImpl"); + mapLogLineConsent(consent, CoreFeature.RemoteConfig, "ModuleRemoteConfig", "RemoteConfig", "RemoteConfigValueStore"); + mapLogLineConsent(consent, CoreFeature.Feedback, "ModuleFeedback", "Feedback"); + mapLogLineConsent(consent, CoreFeature.Content, "ModuleContent", "Content", "ContentParser", "ContentRequestBuilder", "WidgetActionParser"); + logLineConsent = Collections.unmodifiableMap(consent); + } + private final LogCallback logListener; private final Config.LoggingLevel loggingLevel; + //the lowest level printed: the developer level unless the SDK behavior settings override it + private volatile Config.LoggingLevel printLevel; + + //guards the buffer and the directive mirror; nothing is logged and nothing is called out while it is held + private final Object logBufferLock = new Object(); + //held while batches are taken and queued, so ending the gathering waits for a delivery in flight + private final Object logDeliveryLock = new Object(); + private final Object logDeliveryExecutorLock = new Object(); + + private final ArrayDeque gatheredLines = new ArrayDeque<>(); + int droppedLogLineCount = 0; + int gatheredChars = 0; + //lines whose consent was not given when they were logged, kept out of every batch until it is + private final ArrayDeque linesAwaitingConsent = new ArrayDeque<>(); + int awaitingConsentChars = 0; + //orders the lines of both lists, as the millisecond timestamps of a burst do not + private long nextLineSequence = 0; + //the last batch of a gather the server stopped, taken under the lock and queued outside it + private LogBatch pendingTailBatch = null; + + //the directive mirror, so capturing a line never reads the settings; the state alone is read without the lock + volatile LogGatheringState logGatheringState = LogGatheringState.UNDECIDED; + String logGatherId = null; + String logGatherLevels = ModuleConfiguration.logGatheringAllLevels; + int logGatherBatchSize = ModuleConfiguration.logGatheringDefaultBatchSize; + private volatile boolean logGatheringEnded = false; + + private final ThreadLocal ownTransportWork = new ThreadLocal<>(); + private final AtomicBoolean logDeliveryPending = new AtomicBoolean(false); + private final AtomicBoolean partialLogDeliveryRequested = new AtomicBoolean(false); + //the storage IDs of the batches this logger queued, until the request queue no longer holds them + private final Set queuedLogBatchIds = ConcurrentHashMap.newKeySet(); + //a delivery left lines for the batch waiting in the request queue, so the send of that batch resumes it + private final AtomicBoolean logDeliveryAwaitsSentBatch = new AtomicBoolean(false); + volatile ExecutorService logDeliveryExecutor = null; + private volatile boolean sdkInitFinished = false; + + private volatile ConfigurationProvider configProvider = null; + private volatile IntSupplier givenConsents = null; + private volatile LogBatchQueue logBatchQueue = null; + + //guards the counts kept until the health check counter exists and the handover to it + private final Object healthCountLock = new Object(); + private volatile HealthCheckCounter healthCheckCounter = null; + private long warningsBeforeHealthCheck = 0; + private long errorsBeforeHealthCheck = 0; + private final Map logCodesBeforeHealthCheck = new HashMap<>(); + //log codes recorded while no SDK runs, such as calls made before init, handed to the next counter + private static final Map logCodesWhileNotInitialized = new HashMap<>(); + + /** + * The request queue as the log gathering uses it: one request per batch of gathered log lines. + */ + interface LogBatchQueue { + /** + * Queues the batch. + * + * @param payload the {@code sdk_logs} value + * @return the storage ID of the request carrying the batch, {@code null} when the queue refused it + */ + @Nullable + Long queueLogBatch(@Nonnull String payload); + + /** + * Whether a request still waits in the queue, until it is sent or dropped. + * + * @param requestId the storage ID {@link #queueLogBatch(String)} returned + * @return {@code true} while the request waits + */ + boolean isQueued(@Nonnull Long requestId); + } public Log(Config.LoggingLevel loggingLevel, LogCallback logListener) { if (loggingLevel == null) { throw new NullPointerException("Logging level can't null."); } this.loggingLevel = loggingLevel; + this.printLevel = loggingLevel; this.logListener = logListener; } + /** + * Applies the {@code log} switch of the SDK behavior settings to what is printed. Switched off, + * nothing is printed. Switched on, the developer level is printed, or every level when the + * developer level is {@link Config.LoggingLevel#OFF}. The log listener receives every line either way. + * + * @param loggingEnabled the resolved {@code log} switch + */ + void setLoggingEnabled(boolean loggingEnabled) { + if (!loggingEnabled) { + printLevel = Config.LoggingLevel.OFF; + } else if (loggingLevel == Config.LoggingLevel.OFF) { + printLevel = Config.LoggingLevel.VERBOSE; + } else { + printLevel = loggingLevel; + } + } + + /** + * The lowest level printed, which the SDK behavior settings can change. + * + * @return the level, {@link Config.LoggingLevel#OFF} while nothing is printed + */ + Config.LoggingLevel getPrintLevel() { + return printLevel; + } + /** * {@link Config.LoggingLevel} level logging * @@ -27,6 +196,7 @@ public Log(Config.LoggingLevel loggingLevel, LogCallback logListener) { public void d(String logMessage) { print("[DEBUG] [Countly]\t" + logMessage, Config.LoggingLevel.DEBUG); informListener(logMessage, Config.LoggingLevel.DEBUG); + captureLogLine(logMessage, 'd'); } /** @@ -37,6 +207,7 @@ public void d(String logMessage) { public void i(String logMessage) { print("[INFO] [Countly]\t" + logMessage, Config.LoggingLevel.INFO); informListener(logMessage, Config.LoggingLevel.INFO); + captureLogLine(logMessage, 'i'); } /** @@ -45,8 +216,10 @@ public void i(String logMessage) { * @param logMessage string to log */ public void w(String logMessage) { + countWarning(); print("[WARN] [Countly]\t" + logMessage, Config.LoggingLevel.WARN); informListener(logMessage, Config.LoggingLevel.WARN); + captureLogLine(logMessage, 'w'); } /** @@ -55,8 +228,219 @@ public void w(String logMessage) { * @param logMessage string to log */ public void e(String logMessage) { + countError(); print("[ERROR] [Countly]\t" + logMessage, Config.LoggingLevel.ERROR); informListener(logMessage, Config.LoggingLevel.ERROR); + captureLogLine(logMessage, 'e'); + } + + /** + * Counts a warning for the health check, whether or not it is printed. Kept here until the + * health check counter exists. + */ + private void countWarning() { + HealthCheckCounter counter = healthCheckCounter; + if (counter != null) { + counter.logWarning(); + return; + } + synchronized (healthCountLock) { + counter = healthCheckCounter; + if (counter == null) { + warningsBeforeHealthCheck++; + return; + } + } + counter.logWarning(); + } + + /** + * Counts an error for the health check, whether or not it is printed. Kept here until the + * health check counter exists. + */ + private void countError() { + HealthCheckCounter counter = healthCheckCounter; + if (counter != null) { + counter.logError(); + return; + } + synchronized (healthCountLock) { + counter = healthCheckCounter; + if (counter == null) { + errorsBeforeHealthCheck++; + return; + } + } + counter.logError(); + } + + /** + * Hands the health check counter to the logger, with the warnings, errors and log codes counted + * before it existed, including the codes recorded while no SDK ran. {@code null} detaches it, + * after which counts are kept here again. + * + * @param counter the counter, {@code null} for none + */ + void setHealthCheckCounter(@Nullable HealthCheckCounter counter) { + long warnings; + long errors; + Map codes = new HashMap<>(); + synchronized (healthCountLock) { + healthCheckCounter = counter; + if (counter == null) { + return; + } + warnings = warningsBeforeHealthCheck; + errors = errorsBeforeHealthCheck; + warningsBeforeHealthCheck = 0; + errorsBeforeHealthCheck = 0; + codes.putAll(logCodesBeforeHealthCheck); + logCodesBeforeHealthCheck.clear(); + } + synchronized (logCodesWhileNotInitialized) { + for (Map.Entry entry : logCodesWhileNotInitialized.entrySet()) { + codes.merge(entry.getKey(), entry.getValue(), Integer::sum); + } + logCodesWhileNotInitialized.clear(); + } + + for (long a = 0; a < warnings; a++) { + counter.logWarning(); + } + for (long a = 0; a < errors; a++) { + counter.logError(); + } + for (Map.Entry entry : codes.entrySet()) { + counter.recordLogCode(entry.getKey(), entry.getValue()); + } + } + + /** + * Records a health check log code, such as "w740", next to the log line of its condition. A + * code recorded before the health check counter exists is kept until it does. + * + * @param code the log code + */ + public void recordLogCode(@Nonnull String code) { + recordLogCode(code, 1); + } + + /** + * Records several occurrences of a health check log code at once, for a condition several + * items met together, such as requests dropped from the queue in one go. + * + * @param code the log code + * @param count how many times the condition occurred + */ + public void recordLogCode(@Nonnull String code, int count) { + if (count <= 0) { + return; + } + HealthCheckCounter counter = healthCheckCounter; + if (counter == null) { + synchronized (healthCountLock) { + counter = healthCheckCounter; + if (counter == null) { + logCodesBeforeHealthCheck.merge(code, count, Integer::sum); + return; + } + } + } + counter.recordLogCode(code, count); + } + + /** + * Records a health check log code that a public method of a feature area records, so it is + * ignored while that feature has no consent. Ignored before the health check counter exists, + * as no consent is known then. + * + * @param code the log code + * @param area the feature area: "sessions", "events", "views" or "crashes" + */ + public void recordLogCode(@Nonnull String code, @Nonnull String area) { + HealthCheckCounter counter = healthCheckCounter; + if (counter != null) { + counter.recordLogCode(code, area); + } + } + + /** + * Counts one call of a method for the health check method usage, under its feature area. A call + * the SDK made by itself carries ":a", a deprecated method ":d". + * + * @param area the feature area: "sessions", "events", "views" or "crashes" + * @param method the method name with its modifiers + */ + public void recordUsage(@Nonnull String area, @Nonnull String method) { + HealthCheckCounter counter = healthCheckCounter; + if (counter != null) { + counter.recordUsage(area, method); + } + } + + /** + * Keeps the answer of the server to a queued request it did not accept for the health check. + * + * @param statusCode the HTTP status code + * @param response the body of the answer + */ + void logFailedNetworkRequest(int statusCode, @Nullable String response) { + HealthCheckCounter counter = healthCheckCounter; + if (counter != null) { + counter.logFailedNetworkRequest(statusCode, response); + } + } + + /** + * Counts a backoff of the request queue for the health check. + */ + void logBackoffRequest() { + HealthCheckCounter counter = healthCheckCounter; + if (counter != null) { + counter.logBackoffRequest(); + } + } + + /** + * Ends the run of backoffs in a row of the health check, as a queued request was answered in time. + */ + void logConsecutiveBackoffRequest() { + HealthCheckCounter counter = healthCheckCounter; + if (counter != null) { + counter.logConsecutiveBackoffRequest(); + } + } + + /** + * Stops method usage and log codes from counting while an automatically detected crash is reported. + */ + void stopHealthCheckRecordingForCrash() { + HealthCheckCounter counter = healthCheckCounter; + if (counter != null) { + counter.stopRecordingForCrash(); + } + } + + /** + * Lets method usage and log codes count again once an automatically detected crash was reported. + */ + void resumeHealthCheckRecordingAfterCrash() { + HealthCheckCounter counter = healthCheckCounter; + if (counter != null) { + counter.resumeRecordingAfterCrash(); + } + } + + /** + * Records a health check log code while no SDK runs, for a call made before init or after the + * SDK stopped, which no logger can print. The next SDK that starts reports it. + * + * @param code the log code + */ + public static void recordLogCodeWhileNotInitialized(@Nonnull String code) { + synchronized (logCodesWhileNotInitialized) { + logCodesWhileNotInitialized.merge(code, 1, (current, added) -> Math.min(current + added, HealthCheckCounter.COUNT_CAP)); + } } /** @@ -67,10 +451,11 @@ public void e(String logMessage) { public void v(String logMessage) { print("[VERBOSE] [Countly]\t" + logMessage, Config.LoggingLevel.VERBOSE); informListener(logMessage, Config.LoggingLevel.VERBOSE); + captureLogLine(logMessage, 'v'); } private void print(String msg, Config.LoggingLevel level) { - if (level != null && loggingLevel.prints(level)) { + if (level != null && printLevel.prints(level)) { System.out.println(msg); } } @@ -80,4 +465,975 @@ private void informListener(String msg, Config.LoggingLevel level) { logListener.LogHappened(msg, level); } } + + /** + * Hands the logger what it needs to act on the log gathering directive, lets the lines logged + * so far whose consent is given join the gather, then applies the directive in effect. Setters + * rather than constructor parameters, as the logger exists before any of them. + * + * @param configProvider the SDK behavior settings, which hold the directive + * @param givenConsents the {@link CoreFeature} indexes whose consent is given, every bit while + * no consent is required; read inside log calls, so it must never log + * @param logBatchQueue queues one batch as a request of its own + */ + void setLogGatheringProviders(@Nonnull ConfigurationProvider configProvider, @Nonnull IntSupplier givenConsents, @Nonnull LogBatchQueue logBatchQueue) { + v("[Log] setLogGatheringProviders, held lines:[" + heldLogLineCount() + "], awaiting consent:[" + awaitingConsentLineCount() + "]"); + this.givenConsents = givenConsents; + this.logBatchQueue = logBatchQueue; + this.configProvider = configProvider; + releaseConsentedLogLines(); + applyLogGatheringDirective("init"); + } + + /** + * Applies the directive the settings hold to what is held. An armed directive adopts the held + * lines filtered to its levels, and a new gather id drops the lines of the previous gather. A + * decision against gathering stops the capture: the lines a running gather held are queued once, + * with its id, and the lines held while undecided are dropped. Called after every decision, and + * ignored once the gathering ended. + * + * @param source what decided, for the log line only + */ + void applyLogGatheringDirective(@Nonnull String source) { + if (logGatheringEnded) { + return; + } + + ConfigurationProvider provider = configProvider; + if (provider == null) { + v("[Log] applyLogGatheringDirective, no configuration provider yet, source:[" + source + "]"); + return; + } + + LogGatheringState state = provider.getLogGatheringState(); + String gatherId = provider.getLogGatheringId(); + String levels = provider.getLogGatheringLevels(); + int batchSize = provider.getLogGatheringBatchSize(); + + if (!adoptLogGatheringDirective(state, gatherId, levels, batchSize)) { + return; + } + + d("[Log] applyLogGatheringDirective, source:[" + source + "], state:[" + state + "], id:[" + gatherId + "], levels:[" + levels + "], batch size:[" + batchSize + "], held lines:[" + heldLogLineCount() + "]"); + + if (state != LogGatheringState.GATHERING) { + shutdownLogDeliveryAfterTail(); + return; + } + + ensureLogDeliveryExecutor(); + scheduleLogDelivery(false); + } + + /** + * Lets the lines held during init go out, as the request queue is usable from here on. + */ + void onSdkInitFinished() { + sdkInitFinished = true; + if (isGatheringLogs()) { + d("[Log] onSdkInitFinished, uploading the lines gathered during init"); + scheduleLogDelivery(true); + } + } + + /** + * Uploads what is held, on a timer tick, so a buffer that never fills a batch still goes out. + */ + void flushGatheredLogs() { + if (isGatheringLogs() && heldLogLineCount() > 0) { + scheduleLogDelivery(true); + } + } + + /** + * Tells the logger that a request carrying a log batch left the request queue, sent or dropped + * unsent. One batch waits in the queue at a time, so while nothing is sent the lines stay in the + * capped buffer instead of filling the queue; a delivery that left lines behind for the waiting + * batch resumes now, a partial batch included. Called by the networking, on a thread marked as + * doing this feature's own transport work, and never logs. + */ + void onLogBatchSent() { + if (logDeliveryAwaitsSentBatch.compareAndSet(true, false) && isGatheringLogs()) { + scheduleLogDelivery(true); + } + } + + /** + * Stops the gather before the device ID changes without merge: queues every held line on the + * calling thread, past the one waiting batch, so each request carries the current device ID, + * then drops the lines still waiting for their consent and stops the capture, so nothing the + * next user does is gathered for the current gather. A later live directive can arm it again. + */ + void stopLogGatheringForDeviceIdChange() { + queueHeldLinesAndStop("stopLogGatheringForDeviceIdChange", true, false); + d("[Log] stopLogGatheringForDeviceIdChange, log gathering stopped before the device ID change"); + } + + /** + * Drops the held lines whose consent is no longer given, as after a consent was removed, the + * last lines of a stopped gather included, so nothing gathered for a feature goes out once its + * consent is withdrawn. They are counted as dropped. + */ + void dropLinesWithoutConsent() { + IntSupplier consents = givenConsents; + if (consents == null) { + return; + } + int given = consents.getAsInt(); + + synchronized (logBufferLock) { + Iterator iterator = gatheredLines.iterator(); + while (iterator.hasNext()) { + LogLine line = iterator.next(); + if (!isConsentGiven(line.consentFeatures, given)) { + iterator.remove(); + gatheredChars -= line.message.length(); + droppedLogLineCount++; + } + } + + LogBatch tail = pendingTailBatch; + if (tail != null) { + List kept = new ArrayList<>(tail.lines.size()); + for (LogLine line : tail.lines) { + if (isConsentGiven(line.consentFeatures, given)) { + kept.add(line); + } + } + pendingTailBatch = kept.isEmpty() ? null : new LogBatch(tail.gatherId, tail.dropped + tail.lines.size() - kept.size(), kept); + } + } + } + + /** + * Moves the lines whose consent is given by now out of the waiting list into the buffer, in + * capture order with the lines already there, and asks for a delivery when a full batch is + * held. Called when the providers are set and whenever consent is given. + */ + void releaseConsentedLogLines() { + IntSupplier consents = givenConsents; + if (consents == null) { + return; + } + int given = consents.getAsInt(); + + boolean fullBatch; + synchronized (logBufferLock) { + List released = new ArrayList<>(); + Iterator iterator = linesAwaitingConsent.iterator(); + while (iterator.hasNext()) { + LogLine line = iterator.next(); + if (isConsentGiven(line.consentFeatures, given)) { + iterator.remove(); + awaitingConsentChars -= line.message.length(); + released.add(line); + } + } + if (!released.isEmpty()) { + mergeIntoBufferLocked(released); + } + fullBatch = isGatheringLogs() && gatheredLines.size() >= logGatherBatchSize; + } + + if (fullBatch) { + scheduleLogDelivery(false); + } + } + + /** + * Marks the calling thread as doing this feature's own transport work, so nothing it logs + * meanwhile is gathered, or every upload would report on itself. + * + * @param transporting {@code true} to mark the thread, {@code false} to clear the mark + */ + void setOwnTransportWork(boolean transporting) { + if (transporting) { + ownTransportWork.set(Boolean.TRUE); + } else { + ownTransportWork.remove(); + } + } + + /** + * Whether the calling thread is marked as doing this feature's own transport work. + * + * @return {@code true} while the thread is marked + */ + boolean isOwnTransportWork() { + return Boolean.TRUE.equals(ownTransportWork.get()); + } + + /** + * Ends log gathering for good, as the SDK that owns this logger stops. A stop that keeps the SDK + * data queues what is held first, as far as tracking and consent allow, since nothing held + * outlives the SDK; a stop that clears the data discards it. Waits for a delivery in flight, so + * no batch of this logger is queued afterwards, and releases the delivery thread. Lines logged + * afterwards, by threads that outlive the SDK, are neither captured nor queued. + * + * @param queueHeldLines {@code true} to queue the held lines first, {@code false} to discard them + */ + void endLogGathering(boolean queueHeldLines) { + queueHeldLinesAndStop("endLogGathering", queueHeldLines, true); + configProvider = null; + givenConsents = null; + logBatchQueue = null; + v("[Log] endLogGathering, log gathering ended"); + } + + /** + * Queues what is held on the calling thread when asked, the held lines and then the last batch + * of a gather the server stopped, so each request carries the current device ID, then stops the + * capture and drops what is left, lines waiting for their consent included. Waits for a + * delivery in flight first, and releases the delivery thread in the same step as the stop, so a + * directive applied meanwhile either runs before it or starts a delivery thread of its own. + * + * @param caller the caller, for the log lines + * @param queueHeldLines {@code true} to queue what is held first, {@code false} to drop it + * @param endForGood {@code true} when the SDK stops, so nothing is gathered again, {@code false} + * when a later live directive may arm a gather again + */ + private void queueHeldLinesAndStop(@Nonnull String caller, boolean queueHeldLines, boolean endForGood) { + ExecutorService executor = null; + Boolean previousMark = ownTransportWork.get(); + setOwnTransportWork(true); + try { + synchronized (logDeliveryLock) { + try { + LogBatchQueue queue = logBatchQueue; + if (queueHeldLines && queue != null) { + if (isGatheringLogs()) { + int heldLines = heldLogLineCount(); + d("[Log] " + caller + ", queueing the [" + heldLines + "] held lines"); + deliverHeldLogBatches(heldLines, false); + } + LogBatch tail = takePendingTailBatch(); + if (tail != null) { + queueTail(queue, tail); + } + } + } catch (RuntimeException e) { + e("[Log] " + caller + ", failed to queue the held lines, [" + e + "]"); + } finally { + synchronized (logBufferLock) { + if (!logGatheringEnded) { + logGatheringEnded = endForGood; + logGatheringState = LogGatheringState.NOT_GATHERING; + logGatherId = null; + logGatherLevels = ModuleConfiguration.logGatheringAllLevels; + logGatherBatchSize = ModuleConfiguration.logGatheringDefaultBatchSize; + pendingTailBatch = null; + clearBufferLocked(); + executor = takeLogDeliveryExecutor(); + } + } + } + } + } finally { + setOwnTransportWork(Boolean.TRUE.equals(previousMark)); + } + + if (executor != null) { + v("[Log] " + caller + ", stopping the log batch delivery executor"); + executor.shutdown(); + } + } + + /** + * Whether lines are still held for the server, which is true until something decides against + * gathering. + * + * @return {@code true} while lines are captured + */ + boolean isCapturingLogs() { + return logGatheringState != LogGatheringState.NOT_GATHERING; + } + + /** + * Whether a live directive armed the gathering. + * + * @return {@code true} while gathering + */ + boolean isGatheringLogs() { + return logGatheringState == LogGatheringState.GATHERING; + } + + /** + * How many lines are held. + * + * @return the number of lines in the buffer + */ + int heldLogLineCount() { + synchronized (logBufferLock) { + return gatheredLines.size(); + } + } + + /** + * How many lines wait for their consent, outside the buffer. + * + * @return the number of waiting lines + */ + int awaitingConsentLineCount() { + synchronized (logBufferLock) { + return linesAwaitingConsent.size(); + } + } + + /** + * Holds a line for the server: every level while nothing is decided, the directive's levels + * while gathering, nothing while not gathering. Lines that carry an uploaded batch and lines of a + * thread doing this feature's own transport work are skipped. A line whose consent is not given + * waits apart until it is. A full batch is handed to the delivery thread. + * + * @param message the line as logged + * @param level the level character: e, w, i, d or v + */ + private void captureLogLine(@Nullable String message, char level) { + if (logGatheringState == LogGatheringState.NOT_GATHERING) { + return; + } + if (Boolean.TRUE.equals(ownTransportWork.get())) { + return; + } + String msg = message == null ? "" : message; + if (msg.contains(transportMarker)) { + return; + } + + int consentFeatures = logLineConsentFeatures(msg); + boolean consentGiven = isConsentGiven(consentFeatures); + boolean batchIsFull = false; + synchronized (logBufferLock) { + LogGatheringState state = logGatheringState; + if (state == LogGatheringState.NOT_GATHERING) { + return; + } + boolean gathering = state == LogGatheringState.GATHERING; + //while nothing is decided the wanted levels are unknown, so every level is held and filtered on adoption + if (gathering && logGatherLevels.indexOf(level) < 0) { + return; + } + + LogLine line = new LogLine(nextLineSequence++, System.currentTimeMillis(), level, trimLogMessage(msg), consentFeatures); + if (consentGiven) { + gatheredLines.addLast(line); + gatheredChars += line.message.length(); + trimBufferLocked(); + batchIsFull = gathering && gatheredLines.size() >= logGatherBatchSize; + } else { + linesAwaitingConsent.addLast(line); + awaitingConsentChars += line.message.length(); + trimAwaitingConsentLocked(); + } + } + + if (batchIsFull && !logDeliveryAwaitsSentBatch.get()) { + scheduleLogDelivery(false); + } else if (!consentGiven && isConsentGiven(consentFeatures)) { + //given since it was read above, possibly right after the release that would have moved this line + releaseConsentedLogLines(); + } + } + + /** + * Whether a line needing the given consent may join the gather now. Says no until the + * providers are set, so the lines logged before that wait. + * + * @param consentFeatures what {@link #logLineConsentFeatures(String)} returned for the line + * @return {@code true} when the line may join the gather + */ + private boolean isConsentGiven(int consentFeatures) { + IntSupplier consents = givenConsents; + return consents != null && isConsentGiven(consentFeatures, consents.getAsInt()); + } + + /** + * Whether a line needing the given consent may join the gather. + * + * @param consentFeatures the features any one of whose consent lets the line go, 0 for + * {@link #UNATTRIBUTED_LINE_CONSENT} + * @param given the {@link CoreFeature} indexes whose consent is given + * @return {@code true} when the line may join the gather + */ + static boolean isConsentGiven(int consentFeatures, int given) { + if (consentFeatures == 0) { + return (given & UNATTRIBUTED_LINE_CONSENT) == UNATTRIBUTED_LINE_CONSENT; + } + return (given & consentFeatures) != 0; + } + + /** + * Finds the consent a log line needs from the name it starts with in brackets, up to the + * closing bracket or a comma. + * + * @param message the line as logged + * @return the {@link CoreFeature} indexes any one of whose consent lets the line go, 0 for a + * line that needs {@link #UNATTRIBUTED_LINE_CONSENT} + */ + static int logLineConsentFeatures(@Nonnull String message) { + if (message.isEmpty() || message.charAt(0) != '[') { + return 0; + } + int limit = Math.min(message.length(), maxLogLineNameLength + 2); + int end = 1; + while (end < limit && message.charAt(end) != ']' && message.charAt(end) != ',') { + end++; + } + if (end == 1 || end == limit) { + return 0; + } + Integer features = logLineConsent.get(message.substring(1, end)); + return features == null ? 0 : features; + } + + /** + * Maps the bracketed names a feature's log lines start with to the consent of that feature. + * + * @param consent the map to fill + * @param feature the feature whose consent the lines need + * @param names the names, without the brackets + */ + private static void mapLogLineConsent(@Nonnull Map consent, @Nonnull CoreFeature feature, @Nonnull String... names) { + for (String name : names) { + consent.put(name, feature.getIndex()); + } + } + + /** + * Mirrors a directive and applies it to what is held. + * + * @param newState the decision + * @param newGatherId the gather id, {@code null} unless gathering + * @param newLevels the level characters to gather + * @param newBatchSize how many lines make a batch + * @return whether anything changed + */ + private boolean adoptLogGatheringDirective(@Nonnull LogGatheringState newState, @Nullable String newGatherId, @Nonnull String newLevels, int newBatchSize) { + synchronized (logBufferLock) { + if (logGatheringEnded) { + return false; + } + + boolean changed = logGatheringState != newState + || !Objects.equals(logGatherId, newGatherId) + || !logGatherLevels.equals(newLevels) + || logGatherBatchSize != newBatchSize; + if (!changed) { + return false; + } + + boolean wasGathering = logGatheringState == LogGatheringState.GATHERING; + String previousGatherId = logGatherId; + + logGatherId = newGatherId; + logGatherLevels = newLevels; + logGatherBatchSize = newBatchSize; + logGatheringState = newState; + + switch (newState) { + case NOT_GATHERING: + //the server accepts the last lines of a stopped gather under its id; lines held while undecided are dropped + if (wasGathering && previousGatherId != null && !gatheredLines.isEmpty()) { + pendingTailBatch = new LogBatch(previousGatherId, droppedLogLineCount, new ArrayList<>(gatheredLines)); + } + clearBufferLocked(); + break; + case GATHERING: + if (wasGathering && previousGatherId != null && !previousGatherId.equals(newGatherId)) { + //the held lines belong to the previous gather and never go out under another id + clearBufferLocked(); + } else { + filterBufferLocked(); + trimBufferLocked(); + } + break; + case UNDECIDED: + default: + break; + } + return true; + } + } + + /** + * Asks the delivery thread to queue what is held, never the calling thread, which may hold a + * lock of its own. A delivery already waiting to run takes the request over. Never logs, as it + * runs from the capture of a line. + * + * @param includePartialBatch whether a batch that is not full goes out too + */ + private void scheduleLogDelivery(boolean includePartialBatch) { + if (!sdkInitFinished) { + return; + } + if (includePartialBatch) { + partialLogDeliveryRequested.set(true); + } + if (!logDeliveryPending.compareAndSet(false, true)) { + return; + } + + ExecutorService executor = logDeliveryExecutor; + if (executor == null) { + logDeliveryPending.set(false); + return; + } + + try { + executor.execute(this::runLogDelivery); + } catch (RejectedExecutionException e) { + logDeliveryPending.set(false); + } + } + + /** + * Runs one delivery on the delivery thread: every full batch, and when asked also what is held + * beyond them, up to what was held when the delivery started. + */ + private void runLogDelivery() { + logDeliveryPending.set(false); + boolean includePartialBatch = partialLogDeliveryRequested.getAndSet(false); + try { + synchronized (logDeliveryLock) { + if (logGatheringEnded) { + return; + } + deliverHeldLogBatches(includePartialBatch ? heldLogLineCount() : 0, true); + } + } catch (RuntimeException e) { + e("[Log] runLogDelivery, failed to upload the gathered log lines, [" + e + "]"); + } + } + + /** + * Queues the held lines batch by batch, oldest first, until nothing is left to queue or the + * queue refuses a batch: every full batch, and within the given budget also a batch that is not + * full. Holds everything while tracking is off. The buffer holds only lines whose consent was + * given. The caller holds the delivery lock and has marked its thread. + * + * @param partialLineBudget how many lines may still go out in batches that are not full + * @param oneBatchAtATime whether to queue nothing while a batch this logger queued waits in the + * request queue, and at most one batch otherwise + */ + private void deliverHeldLogBatches(int partialLineBudget, boolean oneBatchAtATime) { + LogBatchQueue queue = logBatchQueue; + ConfigurationProvider provider = configProvider; + if (queue == null || provider == null) { + return; + } + + int budget = partialLineBudget; + while (true) { + if (!provider.getTrackingEnabled()) { + d("[Log] deliverHeldLogBatches, tracking is disabled, keeping the gathered lines buffered"); + return; + } + if (oneBatchAtATime) { + if (forgetLogBatchesNoLongerQueued(queue) > 0) { + if (hasLinesToDeliver(budget > 0)) { + logDeliveryAwaitsSentBatch.set(true); + d("[Log] deliverHeldLogBatches, a log batch is still waiting in the request queue, delivering the rest once it is sent"); + } + return; + } + //no batch waits any more, as when the queue dropped it unsent, so a resume asked for earlier is moot + logDeliveryAwaitsSentBatch.set(false); + } + + LogBatch batch = takeLogBatch(budget > 0); + if (batch == null) { + return; + } + budget -= batch.lines.size(); + + String payload = buildLogBatchPayload(batch.gatherId, batch.dropped, batch.lines); + d("[Log] deliverHeldLogBatches, uploading a gathered log batch of [" + batch.lines.size() + "] lines, [" + payload.length() + "] characters"); + if (!queueLogBatch(queue, payload)) { + d("[Log] deliverHeldLogBatches, the request queue refused the batch, keeping its lines buffered"); + restoreLogBatch(batch); + return; + } + } + } + + /** + * Hands one batch to the request queue and keeps the storage ID of its request, so the next + * batch waits while the queue holds it. + * + * @param queue the request queue + * @param payload the batch + * @return whether the queue took the batch + */ + private boolean queueLogBatch(@Nonnull LogBatchQueue queue, @Nonnull String payload) { + Long requestId = queue.queueLogBatch(payload); + if (requestId == null) { + return false; + } + queuedLogBatchIds.add(requestId); + return true; + } + + /** + * Forgets the batches the request queue no longer holds, sent or dropped, which also covers a + * request dropped without a send, as when the queue is over its size. + * + * @param queue the request queue + * @return how many batches of this logger the queue still holds + */ + private int forgetLogBatchesNoLongerQueued(@Nonnull LogBatchQueue queue) { + queuedLogBatchIds.removeIf(requestId -> !queue.isQueued(requestId)); + return queuedLogBatchIds.size(); + } + + /** + * Whether a delivery would queue anything now. + * + * @param includePartialBatch whether a batch that is not full counts + * @return {@code true} when a batch could be taken + */ + private boolean hasLinesToDeliver(boolean includePartialBatch) { + synchronized (logBufferLock) { + return canTakeLogBatchLocked(includePartialBatch); + } + } + + /** + * Whether a batch can be taken out of the buffer. The caller holds the buffer lock. + * + * @param includePartialBatch whether a batch that is not full counts + * @return {@code true} when a batch can be taken + */ + private boolean canTakeLogBatchLocked(boolean includePartialBatch) { + if (logGatheringState != LogGatheringState.GATHERING || logGatherId == null || gatheredLines.isEmpty()) { + return false; + } + return includePartialBatch || gatheredLines.size() >= logGatherBatchSize; + } + + /** + * Queues the last batch of a gather the server stopped, once, from the delivery thread, as the + * decision that stopped the gather may hold a lock the request queue needs. + */ + private void queueTailBatch() { + synchronized (logDeliveryLock) { + LogBatch tail = takePendingTailBatch(); + LogBatchQueue queue = logBatchQueue; + if (tail == null || queue == null || !sdkInitFinished || logGatheringEnded) { + return; + } + try { + queueTail(queue, tail); + } catch (RuntimeException e) { + e("[Log] queueTailBatch, failed to upload the last batch, [" + e + "]"); + } + } + } + + /** + * Takes the last batch of a gather the server stopped, if one waits. + * + * @return the batch, {@code null} for none + */ + @Nullable + private LogBatch takePendingTailBatch() { + synchronized (logBufferLock) { + LogBatch tail = pendingTailBatch; + pendingTailBatch = null; + return tail; + } + } + + /** + * Queues the last batch of a stopped gather, with its id. Its lines are gone if the queue + * refuses it. The caller holds the delivery lock. + * + * @param queue the request queue + * @param tail the batch + */ + private void queueTail(@Nonnull LogBatchQueue queue, @Nonnull LogBatch tail) { + d("[Log] queueTail, uploading the last [" + tail.lines.size() + "] lines of the stopped gather"); + if (!queueLogBatch(queue, buildLogBatchPayload(tail.gatherId, tail.dropped, tail.lines))) { + d("[Log] queueTail, the request queue refused the last batch, its lines are dropped"); + } + } + + /** + * Takes up to one batch of the oldest lines out of the buffer, with the lines dropped since the + * last batch, which are reported once, with the batch that follows the loss. + * + * @param includePartialBatch whether a batch that is not full may be taken + * @return the batch, {@code null} when there is nothing to take + */ + @Nullable + private LogBatch takeLogBatch(boolean includePartialBatch) { + synchronized (logBufferLock) { + if (!canTakeLogBatchLocked(includePartialBatch)) { + return null; + } + + int count = Math.min(logGatherBatchSize, gatheredLines.size()); + List taken = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + LogLine line = gatheredLines.removeFirst(); + gatheredChars -= line.message.length(); + taken.add(line); + } + + LogBatch batch = new LogBatch(logGatherId, droppedLogLineCount, taken); + droppedLogLineCount = 0; + return batch; + } + } + + /** + * Puts a batch the queue refused back at the front of the buffer, oldest first, with its drop + * count, unless its gather ended meanwhile. + * + * @param batch the refused batch + */ + private void restoreLogBatch(@Nonnull LogBatch batch) { + synchronized (logBufferLock) { + if (logGatheringState != LogGatheringState.GATHERING || !batch.gatherId.equals(logGatherId)) { + return; + } + + for (int i = batch.lines.size() - 1; i >= 0; i--) { + LogLine line = batch.lines.get(i); + if (logGatherLevels.indexOf(line.level) > -1) { + gatheredLines.addFirst(line); + gatheredChars += line.message.length(); + } + } + droppedLogLineCount += batch.dropped; + trimBufferLocked(); + } + } + + /** + * Creates the delivery thread's executor unless it exists or the gathering ended. The thread is + * a daemon, and it is marked as doing transport work for its whole life. + */ + private void ensureLogDeliveryExecutor() { + synchronized (logDeliveryExecutorLock) { + if (logGatheringEnded || logDeliveryExecutor != null) { + return; + } + logDeliveryExecutor = Executors.newSingleThreadExecutor(runnable -> { + Thread thread = new Thread(() -> { + setOwnTransportWork(true); + runnable.run(); + }, DELIVERY_THREAD_NAME); + thread.setDaemon(true); + return thread; + }); + } + v("[Log] ensureLogDeliveryExecutor, created the log batch delivery executor"); + } + + /** + * Releases the delivery thread once it queued the last batch of a gather the server stopped, + * if there is one. The batch is queued on the delivery thread, behind any delivery already + * waiting there, which finds nothing to do once the gathering is off. + */ + private void shutdownLogDeliveryAfterTail() { + ExecutorService executor = takeLogDeliveryExecutor(); + if (executor == null) { + takePendingTailBatch(); + return; + } + + try { + executor.execute(this::queueTailBatch); + } catch (RejectedExecutionException e) { + takePendingTailBatch(); + } + v("[Log] shutdownLogDeliveryAfterTail, stopping the log batch delivery executor"); + executor.shutdown(); + } + + /** + * Takes the delivery thread's executor away, so no delivery is scheduled on it any more. + * + * @return the executor, {@code null} when there was none + */ + @Nullable + private ExecutorService takeLogDeliveryExecutor() { + synchronized (logDeliveryExecutorLock) { + ExecutorService executor = logDeliveryExecutor; + logDeliveryExecutor = null; + return executor; + } + } + + /** + * Enforces both buffer ceilings by dropping the oldest lines, counting them into {@code d}. + */ + private void trimBufferLocked() { + while (gatheredLines.size() > ModuleConfiguration.logGatheringMaxBufferedLines + || (gatheredChars > gatheredCharCeiling && gatheredLines.size() > 1)) { + gatheredChars -= gatheredLines.removeFirst().message.length(); + droppedLogLineCount++; + } + } + + /** + * Enforces both ceilings on the lines waiting for their consent by dropping the oldest. They + * are not counted into {@code d}, as a line waiting for its consent has not joined the gather. + */ + private void trimAwaitingConsentLocked() { + while (linesAwaitingConsent.size() > ModuleConfiguration.logGatheringMaxBufferedLines + || (awaitingConsentChars > gatheredCharCeiling && linesAwaitingConsent.size() > 1)) { + awaitingConsentChars -= linesAwaitingConsent.removeFirst().message.length(); + } + } + + /** + * Adds lines whose consent was given to the buffer, which stays in capture order. + * + * @param released the lines, in capture order + */ + private void mergeIntoBufferLocked(@Nonnull List released) { + List merged = new ArrayList<>(gatheredLines); + merged.addAll(released); + merged.sort(Comparator.comparingLong(line -> line.sequence)); + for (LogLine line : released) { + gatheredChars += line.message.length(); + } + + gatheredLines.clear(); + gatheredLines.addAll(merged); + trimBufferLocked(); + } + + /** + * Drops the lines of levels the directive does not ask for, held or waiting for their consent. + * They are not counted as dropped, as they were never wanted. + */ + private void filterBufferLocked() { + Iterator iterator = gatheredLines.iterator(); + while (iterator.hasNext()) { + LogLine line = iterator.next(); + if (logGatherLevels.indexOf(line.level) < 0) { + gatheredChars -= line.message.length(); + iterator.remove(); + } + } + + Iterator awaiting = linesAwaitingConsent.iterator(); + while (awaiting.hasNext()) { + LogLine line = awaiting.next(); + if (logGatherLevels.indexOf(line.level) < 0) { + awaitingConsentChars -= line.message.length(); + awaiting.remove(); + } + } + } + + /** + * Empties the buffer and the lines waiting for their consent, and forgets the drop count. + */ + private void clearBufferLocked() { + gatheredLines.clear(); + gatheredChars = 0; + linesAwaitingConsent.clear(); + awaitingConsentChars = 0; + droppedLogLineCount = 0; + } + + /** + * Builds the {@code sdk_logs} value of one batch, its keys always in the same order. + * + * @param gatherId the gather id the directive named, which the server requires + * @param dropped how many lines were dropped since the last batch + * @param lines the lines, oldest first + * @return the JSON text + */ + @Nonnull + static String buildLogBatchPayload(@Nonnull String gatherId, int dropped, @Nonnull List lines) { + StringBuilder payload = new StringBuilder(64 + lines.size() * 96); + payload.append("{\"").append(keyBatchGatherId).append("\":").append(JSONObject.quote(gatherId)) + .append(",\"").append(keyBatchDroppedCount).append("\":").append(dropped) + .append(",\"").append(keyBatchLines).append("\":["); + for (int i = 0; i < lines.size(); i++) { + LogLine line = lines.get(i); + if (i > 0) { + payload.append(','); + } + payload.append("{\"").append(keyLineTimestamp).append("\":").append(line.timestamp) + .append(",\"").append(keyLineLevel).append("\":\"").append(line.level) + .append("\",\"").append(keyLineMessage).append("\":").append(JSONObject.quote(line.message)) + .append('}'); + } + return payload.append("]}").toString(); + } + + /** + * Cuts a message to what the server keeps, never between the two halves of a surrogate pair. + * + * @param message the message + * @return the message, at most {@value #maxMessageLength} characters long + */ + @Nonnull + static String trimLogMessage(@Nonnull String message) { + if (message.length() <= maxMessageLength) { + return message; + } + + int end = maxMessageLength; + if (Character.isHighSurrogate(message.charAt(end - 1))) { + end--; + } + return message.substring(0, end); + } + + /** + * One captured line. + */ + static final class LogLine { + final long sequence; + final long timestamp; + final char level; + final String message; + final int consentFeatures; + + /** + * Holds one line. + * + * @param sequence its place in capture order + * @param timestamp when it was logged, in milliseconds + * @param level the level character + * @param message the message, already cut + * @param consentFeatures the {@link CoreFeature} indexes any one of whose consent lets the + * line go, 0 for {@link #UNATTRIBUTED_LINE_CONSENT} + */ + LogLine(long sequence, long timestamp, char level, @Nonnull String message, int consentFeatures) { + this.sequence = sequence; + this.timestamp = timestamp; + this.level = level; + this.message = message; + this.consentFeatures = consentFeatures; + } + } + + /** + * One batch taken out of the buffer, kept whole so a refused batch can be put back. + */ + private static final class LogBatch { + final String gatherId; + final int dropped; + final List lines; + + /** + * Holds one batch. + * + * @param gatherId the gather id the batch is uploaded with + * @param dropped how many lines were dropped before it + * @param lines the lines, oldest first + */ + LogBatch(@Nonnull String gatherId, int dropped, @Nonnull List lines) { + this.gatherId = gatherId; + this.dropped = dropped; + this.lines = lines; + } + } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBackendMode.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBackendMode.java index 2dfc65d49..6404a73bc 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBackendMode.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBackendMode.java @@ -26,6 +26,8 @@ public class ModuleBackendMode extends ModuleBase { final String[] userPredefinedKeys = { "name", "username", "email", "organization", "phone", "gender", "byear" }; + static final String[] DIRECT_REQUEST_PROTECTED_KEYS = { "checksum", "checksum256", "sdk_name", "sdk_version" }; + @Override public void init(InternalConfig config) { super.init(config); @@ -79,7 +81,7 @@ private void recordEventInternal(String deviceID, String key, int count, Double eventQueues.get(deviceID).put(jsonObject); ++eventQSize; - if (eventQSize >= internalConfig.getEventsBufferSize()) { + if (eventQSize >= internalConfig.getConfigurationProvider().getEventQueueSizeThreshold()) { addEventsToRequestQ(); } } @@ -97,7 +99,7 @@ private void sessionBeginInternal(String deviceID, Map metrics, JSONObject metricsJson = new JSONObject(metrics); request.params.add("metrics", metricsJson); - ModuleRequests.addRequiredParametersToParams(internalConfig, request.params); + addRequiredParameters(request); if (location != null) { for (Map.Entry entry : location.entrySet()) { @@ -120,7 +122,7 @@ private void sessionUpdateInternal(String deviceID, Double duration, Long timest Request request = new Request(); request.params.add("device_id", deviceID); request.params.add("session_duration", duration); - ModuleRequests.addRequiredParametersToParams(internalConfig, request.params); + addRequiredParameters(request); addTimeInfoIntoRequest(request, timestamp); addRequestToRequestQ(request); @@ -141,7 +143,7 @@ private void sessionEndInternal(String deviceID, double duration, Long timestamp request.params.add("device_id", deviceID); request.params.add("end_session", 1); request.params.add("session_duration", duration); - ModuleRequests.addRequiredParametersToParams(internalConfig, request.params); + addRequiredParameters(request); addTimeInfoIntoRequest(request, timestamp); addRequestToRequestQ(request); @@ -171,7 +173,7 @@ public void recordExceptionInternal(String deviceID, String message, String stac Request request = new Request(); request.params.add("device_id", deviceID); request.params.add("crash", crash); - ModuleRequests.addRequiredParametersToParams(internalConfig, request.params); + addRequiredParameters(request); addTimeInfoIntoRequest(request, timestamp); @@ -214,7 +216,7 @@ private void recordUserPropertiesInternal(String deviceID, Map u request.params.add("device_id", deviceID); request.params.add("user_details", properties); - ModuleRequests.addRequiredParametersToParams(internalConfig, request.params); + addRequiredParameters(request); addTimeInfoIntoRequest(request, timestamp); addRequestToRequestQ(request); @@ -231,18 +233,15 @@ void recordDirectRequestInternal(String deviceID, Map requestDat request.params.add("device_id", deviceID); request.params.add("dr", "1"); addTimeInfoIntoRequest(request, timestamp); - - //remove checksum, will add before sending request to server - requestData.remove("checksum"); - requestData.remove("checksum256"); - requestData.remove("sdk_name"); - requestData.remove("sdk_version"); + addRequiredParameters(request); for (Map.Entry item : requestData.entrySet()) { - request.params.add(item.getKey(), item.getValue()); + if (!Arrays.asList(DIRECT_REQUEST_PROTECTED_KEYS).contains(item.getKey())) { + request.params.remove(item.getKey()); + request.params.add(item.getKey(), item.getValue()); + } } - ModuleRequests.addRequiredParametersToParams(internalConfig, request.params); addRequestToRequestQ(request); } @@ -274,6 +273,17 @@ private JSONObject buildEventJSONObject(String key, int count, Double sum, Doubl return jsonObject; } + /** + * Adds the parameters every backend mode request carries: the common ones and the device ID type + * "developer supplied" (t=0), because every backend mode call provides its device ID. + * + * @param request the request to add the parameters to + */ + private void addRequiredParameters(Request request) { + ModuleRequests.addRequiredParametersToParams(internalConfig, request.params); + request.params.add("t", 0); + } + private void addTimeInfoIntoRequest(Request request, Long timestamp) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(timestamp); @@ -298,14 +308,14 @@ private synchronized void addEventsAgainstDeviceIdToRequestQ(String deviceID) { Request request = new Request(); request.params.add("device_id", deviceID); request.params.add("events", events); - ModuleRequests.addRequiredParametersToParams(internalConfig, request.params); + addRequiredParameters(request); addTimeInfoIntoRequest(request, System.currentTimeMillis()); request.own(ModuleBackendMode.class); addRequestToRequestQ(request); } - private synchronized void addEventsToRequestQ() { + synchronized void addEventsToRequestQ() { L.d("[BackendMode] addEventsToRequestQ"); for (String s : eventQueues.keySet()) { @@ -319,7 +329,7 @@ private synchronized void addEventsToRequestQ() { private void addRequestToRequestQ(Request request) { synchronized (SDKCore.instance.lockBRQStorage) { L.d("[BackendMode] addRequestToRequestQ"); - if (internalConfig.getRequestQueueMaxSize() == SDKCore.instance.requestQueueMemory.size()) { + if (internalConfig.getConfigurationProvider().getRequestQueueMaxSize() == SDKCore.instance.requestQueueMemory.size()) { L.d("[BackendMode] addRequestToRequestQ: In Memory request queue is full, dropping oldest request: " + request.params.toString()); SDKCore.instance.requestQueueMemory.remove(); } @@ -599,7 +609,8 @@ public void recordUserProperties(String deviceID, Map userProper } /** - * Record a direct request. + * Record a direct request. A value in the map replaces the base request's value of the same key, + * except sdk_name, sdk_version, checksum and checksum256, so each key is sent once. The given map is not changed. * * @param deviceID device id, cannot be null or empty * @param requestData a map contains request data, it can not be null or empty diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBase.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBase.java index 0b676ace4..a6c786cbf 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBase.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBase.java @@ -1,5 +1,7 @@ package ly.count.sdk.java.internal; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import ly.count.sdk.java.Session; /** @@ -13,6 +15,9 @@ * */ public abstract class ModuleBase { + //what a call through an interface while its module does not run hands to its callback + static final String NOT_RUNNING_ERROR = "The feature does not run, as its consent is not given or it is not enabled"; + private boolean active = false; protected Log L = null; @@ -47,6 +52,27 @@ public void init(InternalConfig config) { public void stop(InternalConfig config, boolean clear) { } + /** + * The instance of this module that the SDK runs, which every call through an interface of this + * module goes to: this one, or the running one when the interface was handed out before that + * started or kept from an instance that stopped. A call while none runs, as before init or while + * the consent of the feature is not given, is ignored and logged. + * + * @param call the call, starting with the bracketed name of the interface, for the log line + * @param the module type + * @return the running instance, {@code null} while none runs + */ + @SuppressWarnings("unchecked") + @Nullable + M runningInstance(@Nonnull String call) { + SDKCore core = SDKCore.instance; + ModuleBase running = core == null ? null : core.module(getClass()); + if (running == null && core != null && core.L != null) { + core.L.w(call + ", the feature does not run, as its consent is not given or it is not enabled, ignoring the call"); + } + return (M) running; + } + /** * A method to be used by the module itself to determine if {@link #init(InternalConfig)} initialized it * and haven't been stopped yet by {@link #stop(InternalConfig, boolean)}. @@ -95,9 +121,16 @@ public Boolean onRequest(Request request) { } /** - * Called when the request is executed. + * Called when the request is executed, only on the owning module ({@link Request#own(Class)}), + * once for every attempt to send it, on the networking thread. A request dropped unsent for + * being older than the request drop age gets a call too, with a {@code null} response and + * {@link Transport#NO_RESPONSE_CODE}. * Gives the module the ability to respond to the response received * Request identification should be done through the Request ID + * + * @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 */ public void onRequestCompleted(Request request, String response, int responseCode) { @@ -124,4 +157,17 @@ protected void initFinished(InternalConfig config) { protected void deviceIdChanged(String oldDeviceId, boolean withMerge) { } + + /** + * Called when a server response changed the SDK behavior settings while the SDK runs, after + * the SDK applied what it owns: the logger, the timer interval and the request queue. Read the + * new values through {@link InternalConfig#getConfigurationProvider()}. Runs on the thread that + * delivered the response, which is usually not the thread that initialized the SDK, and can run + * after {@link #init(InternalConfig)} but before {@link #initFinished(InternalConfig)} when the + * response of the fetch made at init arrives that early. + * + * @param config configuration of the running SDK + */ + protected void onSdkConfigurationChanged(InternalConfig config) { + } } 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 new file mode 100644 index 000000000..c9e78c3d4 --- /dev/null +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleConfiguration.java @@ -0,0 +1,1425 @@ +package ly.count.sdk.java.internal; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import ly.count.sdk.java.Config; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Resolves, stores and serves the SDK behavior settings, the server side configuration served by + * {@code /o/sdk?method=sc}. + *

+ * Every setting starts from the developer configuration and is overridden by the settings provided + * at init (only while nothing is stored), by the stored settings and by every later server response. + * Each accepted response replaces the stored settings as a whole, so a setting the server stops + * sending goes back to the developer configuration, or to the SDK default when it sets none. + * {@link SDKCore} runs {@link #init(InternalConfig)}, which does the resolve, before it starts the + * global timer and builds the other modules; {@link #initFinished(InternalConfig)} fetches the + * settings and starts the refresh timer. In backend mode the module stays inert and serves the + * developer configuration. + *

+ * Resolved values are published through volatile fields and immutable snapshots, so a reader on any + * thread sees consistent values while a response is applied on the thread that delivered it. + */ +public class ModuleConfiguration extends ModuleBase implements ConfigurationProvider { + + static final String keyRTimestamp = "t"; + static final String keyRVersion = "v"; + static final String keyRConfig = "c"; + static final String keyRLogGathering = "lg"; + static final String keyRConnectionTest = "ct"; + //top level key, a sibling of 'c', read from a live response and never stored + static final String keyRGzip = "gzip"; + + static final String keyRTracking = "tracking"; + static final String keyRNetworking = "networking"; + static final String keyRReqQueueSize = "rqs"; + static final String keyREventQueueSize = "eqs"; + static final String keyRLogging = "log"; + static final String keyRSessionUpdateInterval = "sui"; + static final String keyRSessionTracking = "st"; + static final String keyRViewTracking = "vt"; + static final String keyRLocationTracking = "lt"; + static final String keyRRefreshContentZone = "rcz"; + static final String keyRLimitKeyLength = "lkl"; + static final String keyRLimitValueSize = "lvs"; + static final String keyRLimitSegValues = "lsv"; + static final String keyRLimitBreadcrumb = "lbc"; + static final String keyRLimitTraceLine = "ltlpt"; + static final String keyRLimitTraceLength = "ltl"; + static final String keyRCustomEventTracking = "cet"; + static final String keyREnterContentZone = "ecz"; + static final String keyRContentZoneInterval = "czi"; + static final String keyRConsentRequired = "cr"; + static final String keyRDropOldRequestTime = "dort"; + static final String keyRCrashReporting = "crt"; + static final String keyRAutomaticSessionTracking = "ast"; + static final String keyRAutomaticViewTracking = "avt"; + static final String keyRAutomaticCrashReporting = "acr"; + static final String keyRServerConfigUpdateInterval = "scui"; + static final String keyRBackoffMechanism = "bom"; + static final String keyRBOMAcceptedTimeout = "bom_at"; + static final String keyRBOMRQPercentage = "bom_rqp"; + static final String keyRBOMRequestAge = "bom_ra"; + static final String keyRBOMDuration = "bom_d"; + static final String keyRUserPropertyCacheLimit = "upcl"; + static final String keyREventBlacklist = "eb"; + static final String keyRUserPropertyBlacklist = "upb"; + static final String keyRSegmentationBlacklist = "sb"; + static final String keyREventSegmentationBlacklist = "esb"; + static final String keyREventWhitelist = "ew"; + static final String keyRUserPropertyWhitelist = "upw"; + static final String keyRSegmentationWhitelist = "sw"; + 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"; + static final String keyLGLevels = "l"; + static final String keyLGBatchSize = "b"; + + static final String logGatheringAllLevels = "ewidv"; + static final int logGatheringDefaultBatchSize = 100; + static final int logGatheringMinBatchSize = 10; + //the log buffer ceiling, so also the largest batch the server may ask for: a bigger batch would never fill + static final int logGatheringMaxBufferedLines = 500; + + static final int DEFAULT_SERVER_CONFIG_UPDATE_INTERVAL_HOURS = 4; + static final int DEFAULT_BOM_ACCEPTED_TIMEOUT_SECONDS = 10; + static final double DEFAULT_BOM_RQ_PERCENTAGE = 0.5; + static final int DEFAULT_BOM_REQUEST_AGE_HOURS = 24; + static final int DEFAULT_BOM_DURATION_SECONDS = 60; + static final int MIN_CONTENT_ZONE_INTERVAL = 16; + static final int NO_LIMIT = Integer.MAX_VALUE; + + //the settings of the last accepted configuration; guarded by this + JSONObject latestRetrievedConfiguration = null; + + //what each setting goes back to when the stored settings do not carry it, read from the developer configuration at init + private ConfigurationProvider developerValues = null; + + //guarded by this + CountlyTimer serverConfigUpdateTimer = null; + + private boolean serverConfigRequestsDisabled = false; + private volatile boolean running = false; + + private final AtomicBoolean requestCompressionEnabled = new AtomicBoolean(false); + final AtomicReference gzipAcceptingServerUrl = new AtomicReference<>(null); + final AtomicBoolean requestCompressionBlocked = new AtomicBoolean(false); + /** + * How many times the device ID changed without merge, written under this module's lock, so a + * response requested before such a change can tell its gather was armed for the previous user. + */ + private volatile int deviceIdChangesWithoutMerge = 0; + volatile ConnectionTestListener connectionTestListener = null; + + //resolved values; the constant seeds are here, the ones read from the developer configuration are in seedFromDeveloperConfig + volatile boolean currentVTracking = true; + volatile boolean currentVNetworking = true; + volatile boolean currentVSessionTracking = true; + volatile boolean currentVViewTracking = true; + volatile boolean currentVCustomEventTracking = true; + volatile boolean currentVContentZone = false; + volatile boolean currentVCrashReporting = true; + volatile boolean currentVAutomaticSessionTracking = false; + volatile boolean currentVAutomaticViewTracking = false; + volatile boolean currentVAutomaticCrashReporting = true; + volatile boolean currentVLocationTracking = true; + volatile boolean currentVRefreshContentZone = true; + volatile boolean currentVBackoffMechanism = true; + volatile boolean currentVLoggingEnabled = false; + volatile boolean currentVRequiresConsent = false; + + volatile int currentVServerConfigUpdateInterval = DEFAULT_SERVER_CONFIG_UPDATE_INTERVAL_HOURS; + volatile int currentVRequestQueueMaxSize = 1000; + volatile boolean currentVRequestQueueMaxSizeFromBehaviorSettings = false; + volatile int currentVEventQueueSizeThreshold = 10; + volatile int currentVSessionUpdateInterval = 60; + volatile int currentVMaxKeyLength = NO_LIMIT; + volatile int currentVMaxValueSize = NO_LIMIT; + volatile int currentVMaxSegmentationValues = NO_LIMIT; + volatile int currentVMaxBreadcrumbCount = 100; + volatile int currentVMaxStackTraceLinesPerThread = NO_LIMIT; + volatile int currentVMaxStackTraceLineLength = NO_LIMIT; + volatile int currentVUserPropertyCacheLimit = NO_LIMIT; + volatile int currentVBOMAcceptedTimeoutSeconds = DEFAULT_BOM_ACCEPTED_TIMEOUT_SECONDS; + volatile double currentVBOMRQPercentage = DEFAULT_BOM_RQ_PERCENTAGE; + volatile int currentVBOMRequestAge = DEFAULT_BOM_REQUEST_AGE_HOURS; + volatile int currentVBOMDuration = DEFAULT_BOM_DURATION_SECONDS; + volatile int currentVDropAgeHours = 0; + volatile int currentVZoneTimerInterval = ConfigContent.DEFAULT_ZONE_TIMER_INTERVAL; + + volatile FilterList> currentVEventFilterList = FilterList.NO_NAMES; + volatile FilterList> currentVUserPropertyFilterList = FilterList.NO_NAMES; + volatile FilterList> currentVSegmentationFilterList = FilterList.NO_NAMES; + volatile FilterList>> currentVEventSegmentationFilterList = FilterList.NO_NAMES_PER_EVENT; + 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()}. + */ + 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. + */ + boolean behaviorSettingsStoredAtInit = false; + + /** + * Runs the connection test that a live settings response asks for with its {@code ct} flag. + */ + interface ConnectionTestListener { + /** + * Called on the thread that delivered the response, after the settings in it were applied. + * + * @param fetchLatencyMs how long the settings request took, from sending it to its response, in milliseconds + */ + void onConnectionTestRequested(long fetchLatencyMs); + } + + /** + * One decision of the log gathering directive, published as a whole so a reader never sees the + * state of one directive next to the gather id of another. + */ + static final class LogGatheringDirective { + static final LogGatheringDirective UNDECIDED = new LogGatheringDirective(LogGatheringState.UNDECIDED, null, logGatheringAllLevels, logGatheringDefaultBatchSize); + static final LogGatheringDirective NOT_GATHERING = new LogGatheringDirective(LogGatheringState.NOT_GATHERING, null, logGatheringAllLevels, logGatheringDefaultBatchSize); + + final LogGatheringState state; + final String gatherId; + final String levels; + final int batchSize; + + /** + * Holds one decision. + * + * @param state what was decided + * @param gatherId the gather id, {@code null} unless gathering + * @param levels the level characters to gather + * @param batchSize how many lines make a batch + */ + LogGatheringDirective(@Nonnull LogGatheringState state, @Nullable String gatherId, @Nonnull String levels, int batchSize) { + this.state = state; + this.gatherId = gatherId; + this.levels = levels; + this.batchSize = batchSize; + } + } + + /** + * Builds a provider that serves the developer configuration alone, for code that reads the + * settings while no configuration module is registered on that configuration. + * + * @param config the developer configuration to serve + * @return a provider that never changes + */ + @Nonnull + static ConfigurationProvider developerDefaults(@Nonnull InternalConfig config) { + ModuleConfiguration defaults = new ModuleConfiguration(); + defaults.seedFromDeveloperConfig(config); + return defaults; + } + + /** + * Seeds every setting from the developer configuration and resolves the provided and the stored + * settings over it, then registers this module as the provider of the configuration. In backend + * mode nothing is loaded and the developer configuration stays in effect. + * + * @param config configuration of the SDK being initialized + */ + @Override + public void init(InternalConfig config) { + super.init(config); + boolean backendMode = config.isBackendModeEnabled(); + serverConfigRequestsDisabled = backendMode || config.isSdkBehaviorSettingsRequestsDisabled(); + requestCompressionEnabled.set(config.isRequestCompressionEnabled()); + 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); + + if (backendMode) { + L.d("[ModuleConfiguration] init, backend mode is enabled, SDK behavior settings are not applied"); + } else { + loadConfigFromStorage(config.getSdkBehaviorSettings()); + } + + updateConfigVariables(config, null, true); + running = true; + config.configProvider = this; + } + + /** + * Fetches the settings from the server and starts the refresh timer, unless settings requests + * are disabled or backend mode is on. + * + * @param config configuration of the running SDK + */ + @Override + public void initFinished(@Nonnull InternalConfig config) { + L.d("[ModuleConfiguration] initFinished"); + if (serverConfigRequestsDisabled) { + notifyBehaviorSettingsSettled(false); + return; + } + + fetchConfigFromServer(config); + startServerConfigUpdateTimer(); + } + + /** + * Stops the refresh timer; a response that arrives afterwards is ignored. + * + * @param config configuration of the SDK being stopped + * @param clear whether the SDK clears its data, which removes the stored settings with it + */ + @Override + public void stop(InternalConfig config, boolean clear) { + super.stop(config, clear); + running = false; + stopServerConfigUpdateTimer(); + } + + /** + * Sets the resolved values that come from the developer configuration. + * + * @param config the developer configuration + */ + private void seedFromDeveloperConfig(@Nonnull InternalConfig config) { + currentVLoggingEnabled = config.getLoggingLevel() != null && config.getLoggingLevel() != Config.LoggingLevel.OFF; + currentVRequiresConsent = config.requiresConsent(); + currentVAutomaticCrashReporting = config.isUnhandledCrashReportingEnabled(); + currentVBackoffMechanism = config.isBackoffMechanismEnabled(); + currentVRequestQueueMaxSize = config.getRequestQueueMaxSize(); + currentVEventQueueSizeThreshold = config.getEventsBufferSize(); + currentVSessionUpdateInterval = config.getSendUpdateEachSeconds(); + currentVMaxBreadcrumbCount = config.getMaxBreadcrumbCount(); + currentVMaxKeyLength = config.getMaxKeyLength(); + currentVZoneTimerInterval = config.content.zoneTimerInterval; + } + + /** + * Loads the stored settings, or the provided ones when nothing is stored yet, which stores them. + * + * @param sdkBehaviorSettings the settings the developer provided, {@code null} for none + */ + void loadConfigFromStorage(@Nullable String sdkBehaviorSettings) { + String sConfig = internalConfig.storageProvider.getServerConfig(); + + if (Utils.isEmptyOrNull(sConfig) && !Utils.isEmptyOrNull(sdkBehaviorSettings)) { + L.d("[ModuleConfiguration] loadConfigFromStorage, nothing is stored, using the provided settings"); + sConfig = sdkBehaviorSettings; + } + + L.v("[ModuleConfiguration] loadConfigFromStorage, [" + sConfig + "]"); + + if (Utils.isEmptyOrNull(sConfig)) { + L.d("[ModuleConfiguration] loadConfigFromStorage, no configuration is stored or provided"); + return; + } + + try { + behaviorSettingsStoredAtInit = saveAndStoreDownloadedConfig(new JSONObject(sConfig)); + } catch (JSONException e) { + L.w("[ModuleConfiguration] loadConfigFromStorage, failed to parse, " + e); + } + } + + /** + * Requires {@code v}, {@code t} and an object {@code c}, then removes the settings this SDK does + * not support. Other top level keys are allowed; they are never stored. + * + * @param config a configuration as the server sends it, its settings object is changed in place + * @return whether the configuration can be stored + */ + boolean validateServerConfig(@Nonnull JSONObject config) { + L.v("[ModuleConfiguration] validateServerConfig"); + if (!config.has(keyRVersion)) { + L.w("[ModuleConfiguration] validateServerConfig, retrieved configuration has no 'v' field, it is ignored"); + return false; + } + if (!config.has(keyRTimestamp)) { + L.w("[ModuleConfiguration] validateServerConfig, retrieved configuration has no 't' field, it is ignored"); + return false; + } + if (!config.has(keyRConfig)) { + L.w("[ModuleConfiguration] validateServerConfig, retrieved configuration has no 'c' field, it is ignored"); + return false; + } + + JSONObject newInner = config.optJSONObject(keyRConfig); + if (newInner == null) { + L.w("[ModuleConfiguration] validateServerConfig, retrieved configuration has a 'c' that is not an object, it is ignored"); + return false; + } + + removeUnsupportedKeys(newInner); + return true; + } + + /** + * Removes every setting whose key is unknown or whose value has the wrong type or range. + * + * @param newInner the settings object, changed in place + */ + private void removeUnsupportedKeys(@Nonnull JSONObject newInner) { + Iterator keys = newInner.keys(); + while (keys.hasNext()) { + String key = keys.next(); + Object value = newInner.opt(key); + boolean isValid; + + switch (key) { + case keyRNetworking: + case keyRTracking: + case keyRSessionTracking: + case keyRCrashReporting: + case keyRAutomaticSessionTracking: + case keyRAutomaticViewTracking: + case keyRAutomaticCrashReporting: + case keyRViewTracking: + case keyRCustomEventTracking: + case keyRLocationTracking: + case keyREnterContentZone: + case keyRRefreshContentZone: + case keyRBackoffMechanism: + case keyRLogging: + case keyRConsentRequired: + isValid = value instanceof Boolean; + break; + case keyRServerConfigUpdateInterval: + case keyRBOMAcceptedTimeout: + case keyRBOMRequestAge: + case keyRBOMDuration: + case keyRReqQueueSize: + case keyREventQueueSize: + case keyRSessionUpdateInterval: + case keyRLimitKeyLength: + case keyRLimitValueSize: + case keyRLimitSegValues: + case keyRLimitBreadcrumb: + case keyRLimitTraceLine: + case keyRLimitTraceLength: + case keyRUserPropertyCacheLimit: + isValid = isIntAtLeast(value, 1); + break; + case keyRDropOldRequestTime: + isValid = isIntAtLeast(value, 0); + break; + case keyRContentZoneInterval: + isValid = isIntAtLeast(value, MIN_CONTENT_ZONE_INTERVAL); + break; + case keyRBOMRQPercentage: + isValid = isFraction(value); + break; + case keyREventBlacklist: + case keyRSegmentationBlacklist: + case keyRUserPropertyBlacklist: + case keyREventWhitelist: + case keyRSegmentationWhitelist: + case keyRUserPropertyWhitelist: + case keyRJourneyTriggerEvents: + case keyRJourneyTriggerViews: + isValid = value instanceof JSONArray; + break; + case keyREventSegmentationBlacklist: + case keyREventSegmentationWhitelist: + isValid = value instanceof JSONObject; + break; + default: + L.w("[ModuleConfiguration] removeUnsupportedKeys, unknown key [" + key + "], removing it, value: [" + value + "]"); + keys.remove(); + continue; + } + + if (!isValid) { + L.w("[ModuleConfiguration] removeUnsupportedKeys, invalid value for key [" + key + "], removing it, value: [" + value + "]"); + keys.remove(); + } + } + } + + /** + * Whether a setting value is an integer of at least the given value. + * + * @param value the value as parsed from JSON + * @param minimum the smallest valid value + * @return {@code true} for a valid value + */ + private static boolean isIntAtLeast(@Nullable Object value, int minimum) { + return value instanceof Integer && (Integer) value >= minimum; + } + + /** + * Whether a setting value is a number strictly between 0 and 1. Decimals are parsed as + * {@link java.math.BigDecimal}, so any {@link Number} is accepted. + * + * @param value the value as parsed from JSON + * @return {@code true} for a valid value + */ + private static boolean isFraction(@Nullable Object value) { + if (!(value instanceof Number)) { + return false; + } + double fraction = ((Number) value).doubleValue(); + return fraction > 0.0 && fraction < 1.0; + } + + /** + * 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}, {@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 boolean saveAndStoreDownloadedConfig(@Nonnull JSONObject config) { + L.v("[ModuleConfiguration] saveAndStoreDownloadedConfig"); + if (!validateServerConfig(config)) { + L.w("[ModuleConfiguration] saveAndStoreDownloadedConfig, retrieved configuration is not valid, ignoring it"); + return false; + } + + List notStoredTopLevelKeys = new ArrayList<>(); + for (String key : config.keySet()) { + if (!keyRVersion.equals(key) && !keyRTimestamp.equals(key) && !keyRConfig.equals(key) && !keyRContentTriggers.equals(key)) { + notStoredTopLevelKeys.add(key); + } + } + if (!notStoredTopLevelKeys.isEmpty()) { + L.d("[ModuleConfiguration] saveAndStoreDownloadedConfig, top level keys that are not stored: " + notStoredTopLevelKeys); + } + + //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.get() ? null : ContentTriggers.parse(config.opt(keyRContentTriggers), L)); + internalConfig.storageProvider.setServerConfig(new JSONObject(config, keyRVersion, keyRTimestamp, keyRConfig, keyRContentTriggers).toString()); + return true; + } + + /** + * Applies the stored settings to the resolved values, decides the log gathering directive of a + * live response requested since the last device ID change without merge and has the logger apply + * it, and restarts the refresh timer when its interval changed. A response requested before that + * change leaves the directive as it is, as its gather was armed for the previous user. + * + * @param config configuration of the running SDK + * @param serverResponse the live response being applied, {@code null} at init, where only stored or provided settings exist + * @param forCurrentDeviceId whether the response was requested since the last device ID change without merge + * @return whether a resolved value changed + */ + synchronized boolean updateConfigVariables(@Nonnull InternalConfig config, @Nullable JSONObject serverResponse, boolean forCurrentDeviceId) { + L.v("[ModuleConfiguration] updateConfigVariables, from server response:[" + (serverResponse != null) + "]"); + + if (forCurrentDeviceId) { + //read off the live response itself, so it applies even when its settings object was rejected + readLogGatheringDirective(serverResponse); + L.applyLogGatheringDirective(serverResponse == null ? "init" : "server response"); + } else { + L.d("[ModuleConfiguration] updateConfigVariables, the response was requested for a previous device ID, its log gathering directive is ignored"); + } + + if (latestRetrievedConfiguration == null) { + return false; + } + + StringBuilder sb = new StringBuilder(); + boolean previousRequiresConsent = currentVRequiresConsent; + ConfigurationProvider developer = developerValues; + + currentVNetworking = extractBoolean(keyRNetworking, sb, currentVNetworking, developer.getNetworkingEnabled()); + currentVTracking = extractBoolean(keyRTracking, sb, currentVTracking, developer.getTrackingEnabled()); + currentVSessionTracking = extractBoolean(keyRSessionTracking, sb, currentVSessionTracking, developer.getSessionTrackingEnabled()); + currentVCrashReporting = extractBoolean(keyRCrashReporting, sb, currentVCrashReporting, developer.getCrashReportingEnabled()); + currentVAutomaticSessionTracking = extractBoolean(keyRAutomaticSessionTracking, sb, currentVAutomaticSessionTracking, developer.getAutomaticSessionTrackingEnabled()); + currentVAutomaticViewTracking = extractBoolean(keyRAutomaticViewTracking, sb, currentVAutomaticViewTracking, developer.getAutomaticViewTrackingEnabled()); + currentVAutomaticCrashReporting = extractBoolean(keyRAutomaticCrashReporting, sb, currentVAutomaticCrashReporting, developer.getAutomaticCrashReportingEnabled()); + currentVViewTracking = extractBoolean(keyRViewTracking, sb, currentVViewTracking, developer.getViewTrackingEnabled()); + currentVCustomEventTracking = extractBoolean(keyRCustomEventTracking, sb, currentVCustomEventTracking, developer.getCustomEventTrackingEnabled()); + currentVLocationTracking = extractBoolean(keyRLocationTracking, sb, currentVLocationTracking, developer.getLocationTrackingEnabled()); + currentVContentZone = extractBoolean(keyREnterContentZone, sb, currentVContentZone, developer.getContentZoneEnabled()); + currentVRefreshContentZone = extractBoolean(keyRRefreshContentZone, sb, currentVRefreshContentZone, developer.getRefreshContentZoneEnabled()); + currentVBackoffMechanism = extractBoolean(keyRBackoffMechanism, sb, currentVBackoffMechanism, developer.getBOMEnabled()); + currentVLoggingEnabled = extractBoolean(keyRLogging, sb, currentVLoggingEnabled, developer.getLoggingEnabled()); + //the settings can turn the consent requirement on, never off when the developer turned it on + currentVRequiresConsent = developer.getConsentRequired() || extractBoolean(keyRConsentRequired, sb, currentVRequiresConsent, false); + + currentVServerConfigUpdateInterval = extractInt(keyRServerConfigUpdateInterval, sb, currentVServerConfigUpdateInterval, developer.getServerConfigUpdateInterval()); + currentVRequestQueueMaxSize = extractInt(keyRReqQueueSize, sb, currentVRequestQueueMaxSize, developer.getRequestQueueMaxSize()); + currentVEventQueueSizeThreshold = extractInt(keyREventQueueSize, sb, currentVEventQueueSizeThreshold, developer.getEventQueueSizeThreshold()); + currentVSessionUpdateInterval = extractInt(keyRSessionUpdateInterval, sb, currentVSessionUpdateInterval, developer.getSessionUpdateInterval()); + currentVMaxKeyLength = extractInt(keyRLimitKeyLength, sb, currentVMaxKeyLength, developer.getMaxKeyLength()); + currentVMaxValueSize = extractInt(keyRLimitValueSize, sb, currentVMaxValueSize, developer.getMaxValueSize()); + currentVMaxSegmentationValues = extractInt(keyRLimitSegValues, sb, currentVMaxSegmentationValues, developer.getMaxSegmentationValues()); + currentVMaxBreadcrumbCount = extractInt(keyRLimitBreadcrumb, sb, currentVMaxBreadcrumbCount, developer.getMaxBreadcrumbCount()); + currentVMaxStackTraceLinesPerThread = extractInt(keyRLimitTraceLine, sb, currentVMaxStackTraceLinesPerThread, developer.getMaxStackTraceLinesPerThread()); + currentVMaxStackTraceLineLength = extractInt(keyRLimitTraceLength, sb, currentVMaxStackTraceLineLength, developer.getMaxStackTraceLineLength()); + currentVUserPropertyCacheLimit = extractInt(keyRUserPropertyCacheLimit, sb, currentVUserPropertyCacheLimit, developer.getUserPropertyCacheLimit()); + currentVBOMAcceptedTimeoutSeconds = extractInt(keyRBOMAcceptedTimeout, sb, currentVBOMAcceptedTimeoutSeconds, developer.getBOMAcceptedTimeoutSeconds()); + currentVBOMRQPercentage = extractFraction(keyRBOMRQPercentage, sb, currentVBOMRQPercentage, developer.getBOMRQPercentage()); + currentVBOMRequestAge = extractInt(keyRBOMRequestAge, sb, currentVBOMRequestAge, developer.getBOMRequestAge()); + currentVBOMDuration = extractInt(keyRBOMDuration, sb, currentVBOMDuration, developer.getBOMDuration()); + currentVDropAgeHours = extractInt(keyRDropOldRequestTime, sb, currentVDropAgeHours, developer.getRequestDropAgeHours()); + currentVZoneTimerInterval = extractInt(keyRContentZoneInterval, sb, currentVZoneTimerInterval, developer.getContentZoneTimerInterval()); + currentVRequestQueueMaxSizeFromBehaviorSettings = latestRetrievedConfiguration.has(keyRReqQueueSize); + + updateListingFilters(); + + if (serverResponse != null && previousRequiresConsent != currentVRequiresConsent) { + L.d("[ModuleConfiguration] updateConfigVariables, consent requirement changed to [" + currentVRequiresConsent + "], it applies on the next init, the running SDK keeps [" + config.requiresConsent() + "]"); + } + + if (serverConfigUpdateTimer != null && serverConfigUpdateTimer.getTimerDelaySeconds() != serverConfigUpdateIntervalSeconds()) { + startServerConfigUpdateTimer(); + } + + String updatedValues = sb.toString(); + if (updatedValues.isEmpty()) { + return false; + } + + L.i("[ModuleConfiguration] updateConfigVariables, SDK configuration has changed, new values: [" + updatedValues + "]"); + return true; + } + + /** + * Resolves a switch from the stored settings. Validation keeps only usable values, so a stored + * value is used as it is. + * + * @param key the settings key + * @param changedValues where a change is described + * @param currentValue the value in effect + * @param fallbackValue the developer's value, or the SDK default when the developer sets none + * @return the stored value, or the fallback value when none is stored + */ + private boolean extractBoolean(@Nonnull String key, @Nonnull StringBuilder changedValues, boolean currentValue, boolean fallbackValue) { + Object value = latestRetrievedConfiguration.opt(key); + return noteChange(key, changedValues, currentValue, value instanceof Boolean ? (Boolean) value : fallbackValue); + } + + /** + * Resolves an integer from the stored settings. Validation keeps only usable values, so a + * stored value is used as it is. + * + * @param key the settings key + * @param changedValues where a change is described + * @param currentValue the value in effect + * @param fallbackValue the developer's value, or the SDK default when the developer sets none + * @return the stored value, or the fallback value when none is stored + */ + private int extractInt(@Nonnull String key, @Nonnull StringBuilder changedValues, int currentValue, int fallbackValue) { + Object value = latestRetrievedConfiguration.opt(key); + return noteChange(key, changedValues, currentValue, value instanceof Integer ? (Integer) value : fallbackValue); + } + + /** + * Resolves a fraction from the stored settings. Validation keeps only usable values, so a + * stored value is used as it is. + * + * @param key the settings key + * @param changedValues where a change is described + * @param currentValue the value in effect + * @param fallbackValue the SDK default + * @return the stored value, or the fallback value when none is stored + */ + private double extractFraction(@Nonnull String key, @Nonnull StringBuilder changedValues, double currentValue, double fallbackValue) { + Object value = latestRetrievedConfiguration.opt(key); + return noteChange(key, changedValues, currentValue, value instanceof Number ? ((Number) value).doubleValue() : fallbackValue); + } + + /** + * Describes a resolved value that differs from the value in effect. + * + * @param key the settings key + * @param changedValues where a change is described + * @param currentValue the value in effect + * @param resolvedValue the value just resolved + * @param the type of the value + * @return the resolved value + */ + private static T noteChange(@Nonnull String key, @Nonnull StringBuilder changedValues, @Nonnull T currentValue, @Nonnull T resolvedValue) { + if (!resolvedValue.equals(currentValue)) { + changedValues.append(key).append(":[").append(resolvedValue).append("], "); + } + return resolvedValue; + } + + /** + * Rebuilds the listing filters and the journey trigger sets from the stored settings and + * publishes each as a new immutable snapshot. A filter the stored settings do not hold is an + * empty blacklist, which allows everything. + */ + private void updateListingFilters() { + currentVEventFilterList = namesFilterOf(keyREventBlacklist, keyREventWhitelist); + currentVUserPropertyFilterList = namesFilterOf(keyRUserPropertyBlacklist, keyRUserPropertyWhitelist); + currentVSegmentationFilterList = namesFilterOf(keyRSegmentationBlacklist, keyRSegmentationWhitelist); + currentVEventSegmentationFilterList = namesPerEventFilterOf(keyREventSegmentationBlacklist, keyREventSegmentationWhitelist); + currentVJourneyTriggerEvents = Collections.unmodifiableSet(namesOf(latestRetrievedConfiguration.optJSONArray(keyRJourneyTriggerEvents))); + currentVJourneyTriggerViews = Collections.unmodifiableSet(namesOf(latestRetrievedConfiguration.optJSONArray(keyRJourneyTriggerViews))); + + L.d("[ModuleConfiguration] updateListingFilters, event filter:[" + currentVEventFilterList + + "], user property filter:[" + currentVUserPropertyFilterList + + "], segmentation filter:[" + currentVSegmentationFilterList + + "], event segmentation filter:[" + currentVEventSegmentationFilterList + + "], journey trigger events:" + currentVJourneyTriggerEvents + + ", journey trigger views:" + currentVJourneyTriggerViews); + } + + /** + * Builds a names filter from the stored settings, the blacklist winning when both are stored. + * + * @param blacklistKey the settings key of the blacklist + * @param whitelistKey the settings key of the whitelist + * @return the filter + */ + @Nonnull + private FilterList> namesFilterOf(@Nonnull String blacklistKey, @Nonnull String whitelistKey) { + JSONArray blacklist = latestRetrievedConfiguration.optJSONArray(blacklistKey); + if (blacklist != null) { + return FilterList.ofNames(namesOf(blacklist), false); + } + + JSONArray whitelist = latestRetrievedConfiguration.optJSONArray(whitelistKey); + if (whitelist != null) { + return FilterList.ofNames(namesOf(whitelist), true); + } + + return FilterList.NO_NAMES; + } + + /** + * Builds a names per event filter from the stored settings, the blacklist winning when both are stored. + * + * @param blacklistKey the settings key of the blacklist + * @param whitelistKey the settings key of the whitelist + * @return the filter + */ + @Nonnull + private FilterList>> namesPerEventFilterOf(@Nonnull String blacklistKey, @Nonnull String whitelistKey) { + JSONObject blacklist = latestRetrievedConfiguration.optJSONObject(blacklistKey); + if (blacklist != null) { + return FilterList.ofNamesPerEvent(namesPerEventOf(blacklist), false); + } + + JSONObject whitelist = latestRetrievedConfiguration.optJSONObject(whitelistKey); + if (whitelist != null) { + return FilterList.ofNamesPerEvent(namesPerEventOf(whitelist), true); + } + + return FilterList.NO_NAMES_PER_EVENT; + } + + /** + * Reads the names of a JSON array, skipping nulls and turning other values into strings. + * + * @param jsonArray the array, {@code null} for none + * @return the names in array order + */ + @Nonnull + private static Set namesOf(@Nullable JSONArray jsonArray) { + Set names = new LinkedHashSet<>(); + if (jsonArray == null) { + return names; + } + + for (int i = 0; i < jsonArray.length(); i++) { + String item = jsonArray.optString(i, null); + if (item != null) { + names.add(item); + } + } + return names; + } + + /** + * Reads the names of each event key of a JSON object, skipping keys whose value is not an array. + * + * @param jsonObject the object of arrays + * @return the names of each event key + */ + @Nonnull + private static Map> namesPerEventOf(@Nonnull JSONObject jsonObject) { + Map> namesPerEvent = new LinkedHashMap<>(); + for (String key : jsonObject.keySet()) { + JSONArray jsonArray = jsonObject.optJSONArray(key); + if (jsonArray != null) { + namesPerEvent.put(key, namesOf(jsonArray)); + } + } + return namesPerEvent; + } + + /** + * Decides the log gathering state from the top level {@code lg} directive, shaped + * {@code {"e":false}} or {@code {"e":true,"i":id,"l":"ewidv","b":100}}. Only a live response + * decides: without one the state stays as it is, while disabled settings requests, a response + * without a usable directive and a directive with {@code e} not {@code true} decide off. + * + * @param serverResponse the live response, {@code null} at init + */ + private synchronized void readLogGatheringDirective(@Nullable JSONObject serverResponse) { + if (serverConfigRequestsDisabled) { + //without settings requests no directive can ever arrive, so nothing can ever be gathered + L.d("[ModuleConfiguration] readLogGatheringDirective, SDK behavior settings requests are disabled, log gathering can never be armed"); + setLogGatheringOff(); + return; + } + + if (serverResponse == null) { + L.d("[ModuleConfiguration] readLogGatheringDirective, not a server response, log gathering stays undecided"); + return; + } + + JSONObject directive = serverResponse.optJSONObject(keyRLogGathering); + if (directive == null) { + L.d("[ModuleConfiguration] readLogGatheringDirective, server response had no usable '" + keyRLogGathering + "', log gathering is off"); + setLogGatheringOff(); + return; + } + + if (!Boolean.TRUE.equals(directive.opt(keyLGEnabled))) { + L.d("[ModuleConfiguration] readLogGatheringDirective, directive says log gathering is off"); + setLogGatheringOff(); + return; + } + + Object gatherIdRaw = directive.opt(keyLGId); + String gatherId = gatherIdRaw instanceof String ? ((String) gatherIdRaw).trim() : ""; + if (gatherId.isEmpty()) { + //without the id the server rejects every uploaded batch + L.d("[ModuleConfiguration] readLogGatheringDirective, directive enables log gathering but carries no usable '" + keyLGId + "', log gathering is off"); + setLogGatheringOff(); + return; + } + + LogGatheringDirective gathering = new LogGatheringDirective(LogGatheringState.GATHERING, gatherId, + sanitizeLogGatheringLevels(directive.opt(keyLGLevels)), sanitizeLogGatheringBatchSize(directive.opt(keyLGBatchSize))); + currentVLogGathering = gathering; + L.d("[ModuleConfiguration] readLogGatheringDirective, log gathering is on, id:[" + gathering.gatherId + "], levels:[" + gathering.levels + "], batch size:[" + gathering.batchSize + "]"); + } + + /** + * Decides against log gathering when nothing decided yet, for a run where no response can arrive, + * and has the logger apply the decision. + * + * @param reason why no response can arrive + */ + private synchronized void decideLogGatheringOffIfUndecided(@Nonnull String reason) { + if (currentVLogGathering.state == LogGatheringState.UNDECIDED) { + L.d("[ModuleConfiguration] decideLogGatheringOffIfUndecided, " + reason + ", log gathering is off"); + setLogGatheringOff(); + L.applyLogGatheringDirective(reason); + } + } + + /** + * Publishes the decision against log gathering, which also drops any previous gather id. + */ + private void setLogGatheringOff() { + currentVLogGathering = LogGatheringDirective.NOT_GATHERING; + } + + /** + * Stops log gathering before the device ID changes without merge: decides the directive off, + * then has the logger queue what it holds under the current device ID and stop, so nothing the + * next user does is gathered until a live response for the new device ID arms a gather. + */ + void stopLogGatheringForDeviceIdChange() { + synchronized (this) { + deviceIdChangesWithoutMerge++; + setLogGatheringOff(); + } + L.stopLogGatheringForDeviceIdChange(); + } + + /** + * Keeps only the level characters this SDK knows, lower cased, in the order the server sent them + * and without duplicates. Falls back to every level when nothing usable is left. + * + * @param levelsRaw the {@code l} value of the directive + * @return the level characters to gather + */ + @Nonnull + private String sanitizeLogGatheringLevels(@Nullable Object levelsRaw) { + if (!(levelsRaw instanceof String)) { + return logGatheringAllLevels; + } + + String levels = (String) levelsRaw; + StringBuilder filtered = new StringBuilder(); + for (int i = 0; i < levels.length(); i++) { + char level = Character.toLowerCase(levels.charAt(i)); + if (logGatheringAllLevels.indexOf(level) > -1 && filtered.indexOf(String.valueOf(level)) < 0) { + filtered.append(level); + } + } + + if (filtered.length() == 0) { + L.d("[ModuleConfiguration] sanitizeLogGatheringLevels, no usable level in [" + levels + "], falling back to [" + logGatheringAllLevels + "]"); + return logGatheringAllLevels; + } + + return filtered.toString(); + } + + /** + * Clamps the batch size into [{@value #logGatheringMinBatchSize}, {@value #logGatheringMaxBufferedLines}], + * falling back to {@value #logGatheringDefaultBatchSize} when it is missing or not a number. + * + * @param batchSizeRaw the {@code b} value of the directive + * @return the batch size + */ + private static int sanitizeLogGatheringBatchSize(@Nullable Object batchSizeRaw) { + if (!(batchSizeRaw instanceof Number)) { + return logGatheringDefaultBatchSize; + } + + int batchSize = ((Number) batchSizeRaw).intValue(); + return Math.min(logGatheringMaxBufferedLines, Math.max(logGatheringMinBatchSize, batchSize)); + } + + /** + * Requests the settings from the server and applies the response. Skipped when settings + * requests are disabled, in backend mode and while there is no device ID. The request is sent + * even while the settings forbid networking, as the next response is the only way to allow it again. + * + * @param config configuration of the running SDK + */ + void fetchConfigFromServer(@Nonnull InternalConfig config) { + L.v("[ModuleConfiguration] fetchConfigFromServer"); + if (!running || serverConfigRequestsDisabled) { + L.v("[ModuleConfiguration] fetchConfigFromServer, fetching the configuration is aborted, server config requests are disabled or the SDK is stopped"); + return; + } + + 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; + } + + try { + Params params = ModuleRequests.prepareRequiredParams(config).add("method", "sc"); + if (requestCompressionEnabled.get()) { + params.add("gzip", "1"); + } + if (!autoContentTriggersDisabled.get()) { + params.add(keyRContentTriggers, "1"); + } + String requestData = params.toString(); + Transport transport = config.sdk.networking.getTransport(); + final long fetchStartNs = System.nanoTime(); + final int requestedAfterDeviceIdChanges = deviceIdChangesWithoutMerge; + final String requestedAppKey = config.getServerAppKey(); + final String requestedServerUrl = config.getServerURL().toString(); + + config.immediateRequestGenerator.createImmediateRequestMaker().doWork(requestData, "/o/sdk?", transport, false, true, + response -> onServerConfigResponse(config, response, fetchStartNs, requestedAfterDeviceIdChanges, requestedAppKey, requestedServerUrl), L); + } catch (Exception e) { + L.e("[ModuleConfiguration] fetchConfigFromServer, failed to request the configuration, [" + e + "]"); + decideLogGatheringOffIfUndecided("the server config request failed"); + notifyBehaviorSettingsSettled(false); + } + } + + /** + * Handles the response of a settings request: strips the connection test flag, stores and + * applies the settings, and tells the SDK when a resolved value changed. + * + * @param config configuration of the running SDK + * @param response the response, {@code null} when the request failed + * @param fetchStartNs {@link System#nanoTime()} just before the request was made + * @param requestedAfterDeviceIdChanges how many device ID changes without merge happened before the request was made + * @param requestedAppKey the app key the request was made with + * @param requestedServerUrl the server URL the request was made to + */ + private void onServerConfigResponse(@Nonnull InternalConfig config, @Nullable JSONObject response, long fetchStartNs, int requestedAfterDeviceIdChanges, + @Nullable String requestedAppKey, @Nonnull String requestedServerUrl) { + if (!running) { + L.d("[ModuleConfiguration] onServerConfigResponse, the SDK was stopped before the response arrived, ignoring it"); + return; + } + + 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; + } + + if (Utils.isNotEqual(requestedAppKey, config.getServerAppKey()) || !requestedServerUrl.equals(config.getServerURL().toString())) { + L.d("[ModuleConfiguration] onServerConfigResponse, the app key or the server URL changed after the request was made, ignoring its response"); + return; + } + + L.d("[ModuleConfiguration] onServerConfigResponse, retrieved configuration response: [" + response + "]"); + long fetchLatencyMs = (System.nanoTime() - fetchStartNs) / 1_000_000L; + boolean connectionTestRequested = extractConnectionTestFlag(response); + boolean gzipAccepted = extractGzipFlag(response); + if (requestCompressionEnabled.get()) { + gzipAcceptingServerUrl.set(gzipAccepted ? requestedServerUrl : null); + if (gzipAccepted && requestCompressionBlocked.compareAndSet(true, false)) { + L.i("[ModuleConfiguration] onServerConfigResponse, a behavior settings answer says that the server reads compressed bodies, requests are compressed again"); + } + L.d("[ModuleConfiguration] onServerConfigResponse, the server " + (gzipAccepted ? "reads" : "does not say it reads") + " compressed request bodies"); + } + + 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; + } + applied = saveAndStoreDownloadedConfig(response); + changed = updateConfigVariables(config, response, requestedAfterDeviceIdChanges == deviceIdChangesWithoutMerge); + } + + if (changed && config.sdk != null) { + config.sdk.onSdkConfigurationChanged(config); + } + notifyBehaviorSettingsSettled(applied); + + if (connectionTestRequested) { + notifyConnectionTestRequested(fetchLatencyMs); + } + } + + /** + * Reads and removes the {@code gzip} flag of a live response, so it is never stored: only an + * answer that carries {@code true} says that the server reads compressed request bodies. + * + * @param serverConfigResponse the live response, changed in place + * @return {@code true} only when the response had {@code "gzip": true} + */ + static boolean extractGzipFlag(@Nullable JSONObject serverConfigResponse) { + if (serverConfigResponse == null || !serverConfigResponse.has(keyRGzip)) { + return false; + } + + return Boolean.TRUE.equals(serverConfigResponse.remove(keyRGzip)); + } + + /** + * Reads and removes the {@code ct} flag of a live response, so it is never stored and can never + * come back from storage. Booleans and numbers count by value; a string counts unless it is + * empty, {@code "0"} or {@code "false"}; any other value that is not null counts. + * + * @param serverConfigResponse the live response, changed in place + * @return whether the response asks for a connection test + */ + static boolean extractConnectionTestFlag(@Nullable JSONObject serverConfigResponse) { + if (serverConfigResponse == null || !serverConfigResponse.has(keyRConnectionTest)) { + return false; + } + + Object value = serverConfigResponse.remove(keyRConnectionTest); + if (value == null || JSONObject.NULL.equals(value)) { + return false; + } + if (value instanceof Boolean) { + return (Boolean) value; + } + if (value instanceof Number) { + return ((Number) value).doubleValue() != 0; + } + if (value instanceof String) { + String s = ((String) value).trim(); + return !s.isEmpty() && !"0".equals(s) && !"false".equalsIgnoreCase(s); + } + return true; + } + + /** + * Hands a requested connection test to the registered listener. + * + * @param fetchLatencyMs how long the settings request took, in milliseconds + */ + private void notifyConnectionTestRequested(long fetchLatencyMs) { + ConnectionTestListener listener = connectionTestListener; + if (listener == null) { + L.d("[ModuleConfiguration] notifyConnectionTestRequested, the server asked for a connection test, nothing is registered to run it"); + return; + } + + try { + listener.onConnectionTestRequested(fetchLatencyMs); + } catch (Exception e) { + L.e("[ModuleConfiguration] notifyConnectionTestRequested, the connection test listener failed, [" + e + "]"); + } + } + + /** + * Registers what runs the connection test a live settings response can ask for. + * + * @param listener called with the latency of the settings request, {@code null} to unregister + */ + void setConnectionTestListener(@Nullable ConnectionTestListener listener) { + connectionTestListener = listener; + } + + /** + * The refresh interval in the unit of the timer. + * + * @return seconds between two settings fetches + */ + private long serverConfigUpdateIntervalSeconds() { + return (long) currentVServerConfigUpdateInterval * 60L * 60L; + } + + /** + * Starts the timer that fetches the settings every {@code scui} hours, replacing a running one. + * Never waits for the replaced timer, as this also runs from that timer's own task. + */ + private synchronized void startServerConfigUpdateTimer() { + if (serverConfigUpdateTimer != null) { + serverConfigUpdateTimer.stopTimer(false); + } + + L.d("[ModuleConfiguration] startServerConfigUpdateTimer, fetching the configuration every [" + currentVServerConfigUpdateInterval + "] hours"); + final InternalConfig config = internalConfig; + serverConfigUpdateTimer = new CountlyTimer(L); + serverConfigUpdateTimer.startTimer(serverConfigUpdateIntervalSeconds(), () -> fetchConfigFromServer(config)); + } + + /** + * Stops the refresh timer, if it runs. + */ + private synchronized void stopServerConfigUpdateTimer() { + if (serverConfigUpdateTimer != null) { + serverConfigUpdateTimer.stopTimer(false); + serverConfigUpdateTimer = null; + } + } + + /** {@inheritDoc} */ + @Override + public boolean isRequestCompressionAllowed() { + String acceptingUrl = gzipAcceptingServerUrl.get(); + InternalConfig config = internalConfig; + return requestCompressionEnabled.get() && !requestCompressionBlocked.get() && acceptingUrl != null && config != null + && acceptingUrl.equals(config.getServerURL().toString()); + } + + @Override + public void blockRequestCompression() { + if (requestCompressionBlocked.compareAndSet(false, true)) { + L.i("[ModuleConfiguration] blockRequestCompression, a compressed request was refused, requests are sent uncompressed until a behavior settings answer says that the server reads compressed bodies, or the SDK starts again"); + } + } + + @Override + public boolean getNetworkingEnabled() { + return currentVNetworking; + } + + /** {@inheritDoc} */ + @Override + public boolean getTrackingEnabled() { + return currentVTracking; + } + + /** {@inheritDoc} */ + @Override + public boolean getSessionTrackingEnabled() { + return currentVSessionTracking; + } + + /** {@inheritDoc} */ + @Override + public boolean getViewTrackingEnabled() { + return currentVViewTracking; + } + + /** {@inheritDoc} */ + @Override + public boolean getCustomEventTrackingEnabled() { + return currentVCustomEventTracking; + } + + /** {@inheritDoc} */ + @Override + public boolean getContentZoneEnabled() { + return currentVContentZone; + } + + /** {@inheritDoc} */ + @Override + public boolean getCrashReportingEnabled() { + return currentVCrashReporting; + } + + /** {@inheritDoc} */ + @Override + public boolean getAutomaticSessionTrackingEnabled() { + return currentVAutomaticSessionTracking; + } + + /** {@inheritDoc} */ + @Override + public boolean getAutomaticViewTrackingEnabled() { + return currentVAutomaticViewTracking; + } + + /** {@inheritDoc} */ + @Override + public boolean getAutomaticCrashReportingEnabled() { + return currentVAutomaticCrashReporting; + } + + /** {@inheritDoc} */ + @Override + public boolean getLocationTrackingEnabled() { + return currentVLocationTracking; + } + + /** {@inheritDoc} */ + @Override + public boolean getRefreshContentZoneEnabled() { + return currentVRefreshContentZone; + } + + /** {@inheritDoc} */ + @Override + public boolean getBOMEnabled() { + return currentVBackoffMechanism; + } + + /** {@inheritDoc} */ + @Override + public boolean getLoggingEnabled() { + return currentVLoggingEnabled; + } + + /** {@inheritDoc} */ + @Override + public boolean getConsentRequired() { + return currentVRequiresConsent; + } + + /** {@inheritDoc} */ + @Override + public int getServerConfigUpdateInterval() { + return currentVServerConfigUpdateInterval; + } + + /** {@inheritDoc} */ + @Override + public int getRequestQueueMaxSize() { + return currentVRequestQueueMaxSize; + } + + /** {@inheritDoc} */ + @Override + public boolean isRequestQueueMaxSizeFromBehaviorSettings() { + return currentVRequestQueueMaxSizeFromBehaviorSettings; + } + + /** {@inheritDoc} */ + @Override + public int getEventQueueSizeThreshold() { + return currentVEventQueueSizeThreshold; + } + + /** {@inheritDoc} */ + @Override + public int getSessionUpdateInterval() { + return currentVSessionUpdateInterval; + } + + /** {@inheritDoc} */ + @Override + public int getMaxKeyLength() { + return currentVMaxKeyLength; + } + + /** {@inheritDoc} */ + @Override + public int getMaxValueSize() { + return currentVMaxValueSize; + } + + /** {@inheritDoc} */ + @Override + public int getMaxSegmentationValues() { + return currentVMaxSegmentationValues; + } + + /** {@inheritDoc} */ + @Override + public int getMaxBreadcrumbCount() { + return currentVMaxBreadcrumbCount; + } + + /** {@inheritDoc} */ + @Override + public int getMaxStackTraceLinesPerThread() { + return currentVMaxStackTraceLinesPerThread; + } + + /** {@inheritDoc} */ + @Override + public int getMaxStackTraceLineLength() { + return currentVMaxStackTraceLineLength; + } + + /** {@inheritDoc} */ + @Override + public int getUserPropertyCacheLimit() { + return currentVUserPropertyCacheLimit; + } + + /** {@inheritDoc} */ + @Override + public int getBOMAcceptedTimeoutSeconds() { + return currentVBOMAcceptedTimeoutSeconds; + } + + /** {@inheritDoc} */ + @Override + public double getBOMRQPercentage() { + return currentVBOMRQPercentage; + } + + /** {@inheritDoc} */ + @Override + public int getBOMRequestAge() { + return currentVBOMRequestAge; + } + + /** {@inheritDoc} */ + @Override + public int getBOMDuration() { + return currentVBOMDuration; + } + + /** {@inheritDoc} */ + @Override + public int getRequestDropAgeHours() { + return currentVDropAgeHours; + } + + /** {@inheritDoc} */ + @Override + public int getContentZoneTimerInterval() { + return currentVZoneTimerInterval; + } + + /** {@inheritDoc} */ + @Nonnull + @Override + public FilterList> getEventFilterList() { + return currentVEventFilterList; + } + + /** {@inheritDoc} */ + @Nonnull + @Override + public FilterList> getUserPropertyFilterList() { + return currentVUserPropertyFilterList; + } + + /** {@inheritDoc} */ + @Nonnull + @Override + public FilterList> getSegmentationFilterList() { + return currentVSegmentationFilterList; + } + + /** {@inheritDoc} */ + @Nonnull + @Override + public FilterList>> getEventSegmentationFilterList() { + return currentVEventSegmentationFilterList; + } + + /** {@inheritDoc} */ + @Nonnull + @Override + public Set getJourneyTriggerEvents() { + return currentVJourneyTriggerEvents; + } + + /** {@inheritDoc} */ + @Nonnull + @Override + 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 + public LogGatheringState getLogGatheringState() { + return currentVLogGathering.state; + } + + /** {@inheritDoc} */ + @Nullable + @Override + public String getLogGatheringId() { + return currentVLogGathering.gatherId; + } + + /** {@inheritDoc} */ + @Nonnull + @Override + public String getLogGatheringLevels() { + return currentVLogGathering.levels; + } + + /** {@inheritDoc} */ + @Override + public int getLogGatheringBatchSize() { + return currentVLogGathering.batchSize; + } +} diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleConnectionTest.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleConnectionTest.java new file mode 100644 index 000000000..79b7370f6 --- /dev/null +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleConnectionTest.java @@ -0,0 +1,603 @@ +package ly.count.sdk.java.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.SocketTimeoutException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Runs the connection test a live SDK behavior settings response asks for with its top level + * {@code ct} flag: one battery of parameterless GET probes against every endpoint the SDK depends + * on, graded row by row and queued as one {@code ct_results} report. The feature keys, their order + * and the {@code e} strings are the ones every Countly SDK reports, so the dashboard can group the + * results. + *

+ * The module is built for every SDK, whatever its features and consent, and listens to + * {@link ModuleConfiguration}, which reads the flag. One battery runs at a time, on a daemon thread + * of its own, and none while the settings switch networking off. Probes go straight to the server, + * past the request queue, so neither the backoff mechanism nor the request drop age can hold them + * back, while the report is an ordinary queued request. Nothing about the test is ever stored, so a + * response that asks again runs the battery again. + */ +class ModuleConnectionTest extends ModuleBase implements ModuleConfiguration.ConnectionTestListener { + static final String keyResults = "ct_results"; + static final String THREAD_NAME = "Countly-ConnectionTest"; + + static final int DEFAULT_PER_REQUEST_TIMEOUT_MS = 10_000; + static final long BATTERY_CAP_EXTRA_MS = 30_000; + static final int MAX_ROWS = 32; + static final int MAX_REPORT_BYTES = 8 * 1024; + static final int MAX_ERROR_LENGTH = 256; + + static final String errorTimeout = "timeout"; + static final String errorTransport = "transport error"; + static final String errorRedirected = "redirected"; + static final String errorNotRun = "not run: battery cap"; + //the qualifier of a success graded from an opaque browser probe: never produced here, but it always survives the size cap + static final String errorOpaque = "opaque"; + + /** + * The feature rows in report order. The row without paths is {@code sc}, measured from the + * settings request that asked for the test. + */ + static final ProbeRow[] ROWS = { + new ProbeRow("core", true, "/o/ping"), + new ProbeRow("core-write", false, "/i"), + new ProbeRow("sc", false), + new ProbeRow("rc", false, "/o/sdk?method=rc"), + new ProbeRow("ab", false, "/o/sdk?method=ab_fetch_variants"), + new ProbeRow("feedback", false, "/o/sdk?method=feedback"), + new ProbeRow("feedback-widget", false, "/o/surveys/nps/widget", "/o/surveys/survey/widget", "/o/feedback/widget"), + new ProbeRow("feedback-submit", false, "/i/feedback/inputs"), + new ProbeRow("content", false, "/o/sdk/content"), + new ProbeRow("feedback-page", false, "/feedback/nps", "/feedback/survey", "/feedback/rating"), + new ProbeRow("feedback-assets", true, "/surveys/images/ct-probe.png", "/star-rating/images/ct-probe.png"), + new ProbeRow("content-page", false, "/_external/content/"), + }; + + final AtomicBoolean batteryRunning = new AtomicBoolean(false); + volatile boolean halted = false; + //taken by stop() to set halted and by the battery to check it and queue the report, so a stopped SDK never gets one + private final Object reportLock = new Object(); + private volatile ModuleConfiguration listenedConfiguration = null; + + //package-private so tests can shrink the deadlines and take the network out + volatile int perRequestTimeoutMs = DEFAULT_PER_REQUEST_TIMEOUT_MS; + volatile long batteryCapExtraMs = BATTERY_CAP_EXTRA_MS; + volatile ProbeTransport transport = new HttpProbeTransport(); + + /** + * One feature row of the battery. + */ + static final class ProbeRow { + final String feature; + /** + * Whether only a 2xx counts as reached: {@code core} and {@code feedback-assets} have no + * legitimate 4xx answer, so anything else is a fault there. + */ + final boolean requiresSuccessStatus; + final String[] paths; + + /** + * Describes one row. + * + * @param feature the feature key, reported as {@code f} + * @param requiresSuccessStatus whether only a 2xx counts as reached + * @param paths the paths to probe, relative to the server URL; none for the {@code sc} row + */ + ProbeRow(@Nonnull String feature, boolean requiresSuccessStatus, @Nonnull String... paths) { + this.feature = feature; + this.requiresSuccessStatus = requiresSuccessStatus; + this.paths = paths.clone(); + } + } + + /** + * What one probe observed, before it is graded. + */ + static final class ProbeOutcome { + /** + * The HTTP status, {@code 0} when none could be read. + */ + int status; + /** + * From issuing the request to reading the whole response, or to the failure. + */ + long ms; + /** + * {@link #errorTimeout} or {@link #errorTransport} while the status is {@code 0}, otherwise {@code null}. + */ + String failure; + } + + /** + * One graded row of the report. + */ + static final class ResultRow { + final String feature; + boolean ok; + int status; + long ms; + String error; + int pathCount; + + /** + * Starts a row that reached nothing yet. + * + * @param feature the feature key + */ + ResultRow(@Nonnull String feature) { + this.feature = feature; + } + } + + /** + * Issues one probe. Tests replace it to take the network out. + */ + interface ProbeTransport { + /** + * Sends one bare GET and reads its status. + * + * @param url the probe URL + * @param timeoutMs the connect and the read timeout, in milliseconds + * @param transport the transport of the queued requests, whose pinning and custom request + * headers the probe reuses, {@code null} when the SDK runs without one + * @return what the probe observed + */ + @Nonnull + ProbeOutcome probe(@Nonnull String url, int timeoutMs, @Nullable Transport transport); + } + + /** + * Starts listening to the configuration module of the SDK for connection test requests. + * + * @param config configuration of the SDK being initialized + */ + @Override + public void init(InternalConfig config) { + super.init(config); + ModuleConfiguration configuration = config.sdk == null ? null : config.sdk.module(ModuleConfiguration.class); + if (configuration == null) { + L.d("[ModuleConnectionTest] init, no configuration module runs, a connection test can never be requested"); + return; + } + + configuration.setConnectionTestListener(this); + listenedConfiguration = configuration; + L.v("[ModuleConnectionTest] init, listening for connection test requests"); + } + + /** + * Stops listening for connection test requests. A running battery ends at its next row and + * never queues its report. + * + * @param config configuration of the SDK being stopped + * @param clear whether the SDK clears its data + */ + @Override + public void stop(InternalConfig config, boolean clear) { + super.stop(config, clear); + synchronized (reportLock) { + halted = true; + } + + ModuleConfiguration configuration = listenedConfiguration; + listenedConfiguration = null; + if (configuration != null) { + configuration.setConnectionTestListener(null); + } + + if (batteryRunning.get()) { + L.d("[ModuleConnectionTest] stop, the running battery ends at its next row and queues no report"); + } + } + + /** + * Runs the battery a live settings response asked for. + * + * @param fetchLatencyMs how long the settings request took, in milliseconds + */ + @Override + public void onConnectionTestRequested(long fetchLatencyMs) { + startBattery(fetchLatencyMs); + } + + /** + * Starts one battery on a daemon thread of its own, unless the SDK stopped, the settings switch + * networking off or a battery is already running. + * + * @param scLatencyMs latency of the settings request that asked for the test, in milliseconds, + * negative when unknown + */ + void startBattery(final long scLatencyMs) { + if (halted) { + L.d("[ModuleConnectionTest] startBattery, the SDK is stopped, ignoring the request"); + return; + } + + if (!internalConfig.getConfigurationProvider().getNetworkingEnabled()) { + L.d("[ModuleConnectionTest] startBattery, networking is disabled by the SDK behavior settings, ignoring the request"); + return; + } + + if (!batteryRunning.compareAndSet(false, true)) { + L.d("[ModuleConnectionTest] startBattery, a battery is already running, ignoring the request"); + return; + } + + L.i("[ModuleConnectionTest] startBattery, the server asked for a connection test, running the probe battery"); + Thread worker = new Thread(() -> { + try { + runBatteryAndReport(scLatencyMs); + } catch (Throwable t) { + L.e("[ModuleConnectionTest] startBattery, the battery failed, [" + t + "]"); + } finally { + batteryRunning.set(false); + } + }, THREAD_NAME); + worker.setDaemon(true); + + try { + worker.start(); + } catch (Throwable t) { + batteryRunning.set(false); + L.e("[ModuleConnectionTest] startBattery, failed to start the battery thread, [" + t + "]"); + } + } + + /** + * Runs the battery and queues its report as a request of its own, unless the SDK stopped + * meanwhile. + * + * @param scLatencyMs latency of the settings request that asked for the test, in milliseconds, + * negative when unknown + */ + void runBatteryAndReport(long scLatencyMs) { + List rows = runBattery(scLatencyMs); + String report = buildReport(rows); + + synchronized (reportLock) { + if (halted) { + L.d("[ModuleConnectionTest] runBatteryAndReport, the SDK stopped during the battery, dropping the report"); + return; + } + + L.d("[ModuleConnectionTest] runBatteryAndReport, queueing the report [" + report + "]"); + Request request = ModuleRequests.nonSessionRequest(internalConfig); + request.params.add(keyResults, report); + ModuleRequests.pushAsync(internalConfig, request); + } + } + + /** + * Probes the rows in report order, one request at a time. A row the battery cap is reached + * before is reported as not run, and a stop ends the battery before the next row. + * + * @param scLatencyMs latency of the settings request that asked for the test, in milliseconds, + * negative when unknown, which leaves the {@code sc} row out + * @return the graded rows in report order + */ + @Nonnull + List runBattery(long scLatencyMs) { + String serverUrl = internalConfig.getServerURL().toString(); + Transport sdkTransport = sdkTransport(); + ProbeTransport probeTransport = transport; + int timeoutMs = perRequestTimeoutMs; + + int requestCount = 0; + for (ProbeRow row : ROWS) { + requestCount += row.paths.length; + } + long capMs = (long) requestCount * timeoutMs + batteryCapExtraMs; + long batteryStartNs = System.nanoTime(); + + List results = new ArrayList<>(ROWS.length); + for (ProbeRow row : ROWS) { + if (halted) { + L.d("[ModuleConnectionTest] runBattery, the SDK stopped, ending the battery before [" + row.feature + "]"); + break; + } + + if (row.paths.length == 0) { + if (scLatencyMs >= 0) { + //the settings request was answered, or no test would have been asked for + ResultRow sc = new ResultRow(row.feature); + sc.ok = true; + sc.status = HttpURLConnection.HTTP_OK; + sc.ms = scLatencyMs; + results.add(sc); + } + continue; + } + + long elapsedMs = (System.nanoTime() - batteryStartNs) / 1_000_000L; + if (elapsedMs > capMs) { + ResultRow notRun = new ResultRow(row.feature); + notRun.error = errorNotRun; + results.add(notRun); + continue; + } + + results.add(probeRow(row, serverUrl, probeTransport, sdkTransport, timeoutMs)); + } + + L.d("[ModuleConnectionTest] runBattery, [" + results.size() + "] rows graded against [" + serverUrl + "]"); + return results; + } + + /** + * Probes every path of a row and combines them into one row: reached only when every path was, + * the status and the reason of the first failing path, or the first status when none failed, the + * latencies summed and the number of paths. + * + * @param row the row + * @param serverUrl the configured server URL + * @param probeTransport what issues the probes + * @param sdkTransport the transport of the queued requests, {@code null} when there is none + * @param timeoutMs the per request timeout, in milliseconds + * @return the graded row + */ + @Nonnull + ResultRow probeRow(@Nonnull ProbeRow row, @Nonnull String serverUrl, @Nonnull ProbeTransport probeTransport, @Nullable Transport sdkTransport, int timeoutMs) { + ResultRow result = new ResultRow(row.feature); + result.ok = true; + result.pathCount = row.paths.length; + + for (int i = 0; i < row.paths.length; i++) { + String url = buildProbeUrl(serverUrl, row.paths[i]); + ProbeOutcome outcome = probeTransport.probe(url, timeoutMs, sdkTransport); + result.ms += outcome.ms; + + String failure = grade(outcome, row.requiresSuccessStatus); + L.v("[ModuleConnectionTest] probeRow, [" + row.feature + "] " + url + " -> status:[" + outcome.status + "] ms:[" + outcome.ms + "] failure:[" + failure + "]"); + + if (i == 0) { + result.status = outcome.status; + } + + if (failure != null && result.ok) { + result.ok = false; + result.status = outcome.status; + result.error = failure; + } + } + + return result; + } + + /** + * Grades one probe by whether the Countly application answered it: a 2xx did, and so did a + * 4xx other than 403 on a row that has a legitimate 4xx answer. No status, a redirect, a 403, a + * 5xx and anything else did not. + * + * @param outcome what the probe observed + * @param requiresSuccessStatus whether only a 2xx counts as reached on this row + * @return {@code null} when the application answered, otherwise the {@code e} reason + */ + @Nullable + static String grade(@Nonnull ProbeOutcome outcome, boolean requiresSuccessStatus) { + int status = outcome.status; + if (status <= 0) { + return outcome.failure != null ? outcome.failure : errorTransport; + } + if (status >= 200 && status < 300) { + return null; + } + if (status >= 300 && status < 400) { + return errorRedirected; + } + if (!requiresSuccessStatus && status >= 400 && status < 500 && status != HttpURLConnection.HTTP_FORBIDDEN) { + return null; + } + return "HTTP " + status; + } + + /** + * Resolves a path against the configured server URL, keeping any path prefix, with exactly one + * {@code /} at the join, then appends the probe marker and a cache buster. + * + * @param serverUrl the configured server URL + * @param path the path, which may carry a query + * @return the probe URL + */ + @Nonnull + static String buildProbeUrl(@Nonnull String serverUrl, @Nonnull String path) { + String base = serverUrl; + while (base.endsWith("/")) { + base = base.substring(0, base.length() - 1); + } + String joined = path.startsWith("/") ? base + path : base + "/" + path; + String separator = joined.contains("?") ? "&" : "?"; + return joined + separator + "ct=1&_=" + System.currentTimeMillis(); + } + + /** + * Builds the report: the device time, the SDK identity and the rows, within the caps of + * {@value #MAX_ROWS} rows and {@value #MAX_REPORT_BYTES} bytes of UTF-8. Over the size cap every + * {@code e} except {@link #errorOpaque} is dropped first, then rows from the end. + * + * @param rows the graded rows in report order + * @return the report as JSON text + */ + @Nonnull + String buildReport(@Nonnull List rows) { + JSONObject report = new JSONObject(); + JSONArray results = new JSONArray(); + try { + report.put("ts", System.currentTimeMillis()); + JSONObject sdk = new JSONObject(); + sdk.put("name", internalConfig.getSdkName()); + sdk.put("version", internalConfig.getSdkVersion()); + report.put("sdk", sdk); + report.put("results", results); + + int rowLimit = Math.min(rows.size(), MAX_ROWS); + for (int i = 0; i < rowLimit; i++) { + results.put(rowToJson(rows.get(i))); + } + + if (utf8Length(report.toString()) > MAX_REPORT_BYTES) { + L.w("[ModuleConnectionTest] buildReport, the report is over the size cap, dropping the error details"); + for (int i = 0; i < results.length(); i++) { + JSONObject row = results.getJSONObject(i); + if (!errorOpaque.equals(row.optString("e"))) { + row.remove("e"); + } + } + } + + while (utf8Length(report.toString()) > MAX_REPORT_BYTES && results.length() > 0) { + L.w("[ModuleConnectionTest] buildReport, the report is still over the size cap, dropping its last row"); + results.remove(results.length() - 1); + } + } catch (JSONException e) { + L.w("[ModuleConnectionTest] buildReport, failed to build the report, [" + e + "]"); + } + + return report.toString(); + } + + /** + * Serializes one row, its {@code e} cut at {@value #MAX_ERROR_LENGTH} characters and its path + * count only when it probed more than one path. + * + * @param row the graded row + * @return the row as the report carries it + */ + @Nonnull + static JSONObject rowToJson(@Nonnull ResultRow row) { + JSONObject json = new JSONObject(); + json.put("f", row.feature); + json.put("ok", row.ok); + json.put("st", row.status); + json.put("ms", row.ms); + if (row.error != null) { + String error = row.error; + if (error.length() > MAX_ERROR_LENGTH) { + error = error.substring(0, MAX_ERROR_LENGTH); + } + json.put("e", error); + } + if (row.pathCount > 1) { + json.put("n", row.pathCount); + } + return json; + } + + /** + * The size of a text in UTF-8. + * + * @param value the text + * @return its length in bytes + */ + static int utf8Length(@Nonnull String value) { + return value.getBytes(StandardCharsets.UTF_8).length; + } + + /** + * The transport the queued requests go through, whose pinning and custom request headers the + * probes reuse. + * + * @return the transport, {@code null} when the SDK runs without its default networking + */ + @Nullable + private Transport sdkTransport() { + SDKCore sdk = internalConfig.sdk; + Networking networking = sdk == null ? null : sdk.networking; + return networking == null ? null : networking.getTransport(); + } + + /** + * Probes with a bare GET opened by {@link Transport#openProbeConnection(String, int)}. + */ + static final class HttpProbeTransport implements ProbeTransport { + //only the status matters, but the body is read so 'ms' covers the whole response, up to this much of it + static final int MAX_DRAIN_BYTES = 64 * 1024; + + /** + * Sends the probe and reads its status and its body, mapping a timeout to + * {@link #errorTimeout} and any other failure to {@link #errorTransport}. + * + * @param url the probe URL + * @param timeoutMs the connect and the read timeout, in milliseconds + * @param transport the transport whose pinning and custom request headers the probe reuses, + * {@code null} for a plain connection + * @return what the probe observed + */ + @Nonnull + @Override + public ProbeOutcome probe(@Nonnull String url, int timeoutMs, @Nullable Transport transport) { + ProbeOutcome outcome = new ProbeOutcome(); + long startNs = System.nanoTime(); + HttpURLConnection connection = null; + try { + connection = transport == null ? Transport.openBareGetConnection(url, timeoutMs) : transport.openProbeConnection(url, timeoutMs); + int status = connection.getResponseCode(); + if (status > 0) { + outcome.status = status; + drain(connection); + } else { + //not an HTTP answer + outcome.failure = errorTransport; + } + } catch (SocketTimeoutException e) { + outcome.status = 0; + outcome.failure = errorTimeout; + } catch (Exception e) { + outcome.status = 0; + outcome.failure = errorTransport; + } finally { + if (connection != null) { + connection.disconnect(); + } + outcome.ms = (System.nanoTime() - startNs) / 1_000_000L; + } + return outcome; + } + + /** + * Reads the body, up to {@link #MAX_DRAIN_BYTES}, and discards it. + * + * @param connection the answered connection + */ + private static void drain(@Nonnull HttpURLConnection connection) { + try (InputStream stream = bodyStream(connection)) { + if (stream == null) { + return; + } + byte[] buffer = new byte[4096]; + int total = 0; + int read; + while (total < MAX_DRAIN_BYTES && (read = stream.read(buffer)) != -1) { + total += read; + } + } catch (IOException ignored) { + //the status is already read, a failed body read changes nothing + } + } + + /** + * The body of the answer, which is the error stream for a failing status. + * + * @param connection the answered connection + * @return the body, {@code null} when there is none + */ + @Nullable + private static InputStream bodyStream(@Nonnull HttpURLConnection connection) { + try { + return connection.getInputStream(); + } catch (IOException e) { + return connection.getErrorStream(); + } + } + } +} 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 c60d04d98..0992e0283 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,17 @@ 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; import org.json.JSONArray; @@ -38,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; @@ -49,8 +68,27 @@ public class ModuleContent extends ModuleBase { private boolean fetching = false; private int waitForDelay = 0; private int generation = 0; - - private int zoneTimerInterval = ConfigContent.DEFAULT_ZONE_TIMER_INTERVAL; + /** The {@code ecz} value of the settings in use at init, which decides the entry at init. */ + 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. */ + 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}. + */ + private boolean stopped = false; /** When the SDK came up, which is what {@link #START_DELAY_MS} is measured from. */ private long startedAt = 0; @@ -64,10 +102,89 @@ public void init(InternalConfig config) { super.init(config); L.v("[ModuleContent] Initializing"); - zoneTimerInterval = config.content.zoneTimerInterval; globalContentCallback = config.content.globalContentCallback; contentInterface = new Content(); startedAt = TimeUtils.uniqueTimestampMs(); + synchronized (contentLock) { + display = config.sdk.contentDisplay; + } + // the settings in use at init decide the entry, also when an answer arrives before init ends + contentZoneEnabledAtInit.set(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 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 (contentZoneEnabledAtInit.get()) { + 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} 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) { + restartZoneTimerIfIntervalChanged(config.getConfigurationProvider().getContentZoneTimerInterval()); + } + + /** + * Enters the content zone because the {@code ecz} setting asks for it, once a display is registered. + * + * @param caller the calling method, for the log + */ + private void enterContentZoneForSettings(@Nonnull String caller) { + settingsAskForZone.set(true); + boolean hasDisplay; + synchronized (contentLock) { + hasDisplay = display != null; + } + + if (!hasDisplay) { + L.d("[ModuleContent] " + caller + ", the SDK behavior settings ask for the content zone, it is entered once a content display is registered"); + return; + } + + L.d("[ModuleContent] " + caller + ", entering the content zone as the SDK behavior settings ask"); + enterContentZoneInternal(); + } + + /** + * Restarts the timer of an active zone when the fetch interval changed, keeping the zone as it + * is. The next fetch comes as soon as the start delay allows. + * + * @param intervalSeconds the fetch interval now in effect + */ + private void restartZoneTimerIfIntervalChanged(int intervalSeconds) { + CountlyTimer timerToStop; + synchronized (contentLock) { + if (!zoneActive || contentTimer == null || contentTimer.getTimerDelaySeconds() == intervalSeconds) { + return; + } + + L.d("[ModuleContent] restartZoneTimerIfIntervalChanged, the fetch interval changed from [" + contentTimer.getTimerDelaySeconds() + "] to [" + intervalSeconds + "] seconds, restarting the zone timer"); + timerToStop = contentTimer; + contentTimer = new CountlyTimer(L); + contentTimer.startTimer(intervalSeconds, firstFetchDelay(), this::onZoneTimerTick); + } + + // Not awaited: the zone stays active, so a tick of the replaced timer that is still running is harmless. + timerToStop.stopTimer(false); } @Override @@ -75,9 +192,25 @@ public Boolean onRequest(Request request) { return true; } + /** + * Leaves the content zone for good: from here on no zone is entered, not even by a settings + * change that arrives while the SDK stops. + * + * @param config configuration of the SDK being stopped + * @param clear whether the SDK clears its data + */ @Override 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; @@ -100,16 +233,27 @@ 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(); } void setContentDisplayInternal(ContentDisplay contentDisplay) { L.d("[ModuleContent] setContentDisplayInternal, display set:[" + (contentDisplay != null) + "]"); + boolean zoneInactive; synchronized (contentLock) { display = contentDisplay; + zoneInactive = !zoneActive; + } + + if (contentDisplay != null && zoneInactive && settingsAskForZone.get()) { + enterContentZoneForSettings("setContentDisplayInternal"); } } + /** + * Enters the content zone, fetching every {@code czi} seconds. Entering a zone that is already + * active does nothing. + */ void enterContentZoneInternal() { if (display == null) { L.w("[ModuleContent] enterContentZoneInternal, no content display is registered, ignoring the call"); @@ -121,7 +265,15 @@ void enterContentZoneInternal() { return; } + int zoneTimerInterval = internalConfig.getConfigurationProvider().getContentZoneTimerInterval(); synchronized (contentLock) { + if (stopped) { + L.d("[ModuleContent] enterContentZoneInternal, the module is stopped, ignoring the call"); + return; + } + + contentZoneWanted.set(true); + contentZoneExited.set(false); if (zoneActive) { L.d("[ModuleContent] enterContentZoneInternal, already in a content zone, ignoring the call"); return; @@ -168,6 +320,18 @@ void exitContentZoneInternal() { } /** + * Leaves the content zone because the application asked for it. Content triggers then ask for + * nothing until the application enters the zone again. + */ + void exitContentZoneByApp() { + contentZoneWanted.set(false); + contentZoneExited.set(true); + exitContentZoneInternal(); + } + + /** + * Leaves the content zone. + * * @param awaitTimerTermination must be {@code false} when called from the zone timer's own * tick, because a task cannot wait for itself to finish */ @@ -193,7 +357,16 @@ private void exitContentZoneInternal(boolean awaitTimerTermination) { L.i("[ModuleContent] exitContentZoneInternal, left the content zone"); } + /** + * 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()) { + L.d("[ModuleContent] refreshContentZoneInternal, refreshing the content zone is disabled by the SDK behavior settings, ignoring the call"); + return; + } + synchronized (contentLock) { if (contentShown) { L.d("[ModuleContent] refreshContentZoneInternal, a content block is on screen, ignoring the call"); @@ -209,6 +382,295 @@ void refreshContentZoneInternal() { 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) { if (display == null) { L.w("[ModuleContent] previewContentInternal, no content display is registered, ignoring the call"); @@ -231,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) { @@ -240,11 +702,13 @@ void recordContentEventsInternal(String eventsJson) { return; } - ModuleEvents.Events events = SDKCore.instance == null ? null : SDKCore.instance.events(); - if (events == null) { + SDKCore core = SDKCore.instance; + ModuleEvents eventsModule = core == null ? null : core.runningModule(CoreFeature.Events, ModuleEvents.class); + if (eventsModule == null) { L.w("[ModuleContent] recordContentEventsInternal, events are not available, content events are dropped"); return; } + ModuleEvents.Events events = eventsModule.eventsInterface; boolean recorded = false; try { @@ -327,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; } @@ -347,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) { @@ -360,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; } @@ -375,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); } } - private void onContentFetched(JSONObject response, int fetchGeneration) { + /** + * @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, @Nullable Runnable onNothingShown) { + boolean shown = false; try { ContentData content = ContentParser.parse(response, L); if (content == null) { @@ -415,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); + } } } @@ -466,25 +955,57 @@ private void clearFetching(int fetchGeneration) { */ public class Content { + /** + * The interface a call goes to: this one while its module runs, the running module's when + * this one was handed out before that started or kept from one that stopped, and + * {@code null} while the feature does not run. + * + * @param call the call, for the log line + * @return the interface, {@code null} for none + */ + private Content target(String call) { + ModuleContent running = runningInstance(call); + return running == null ? null : running.contentInterface; + } + /** * Register the display that draws content blocks. Required before entering a content zone. - * Pass {@code null} to unregister. + * Pass {@code null} to unregister. While the SDK behavior settings ask for the content zone, + * registering a display enters it. A display registered before the content consent is given + * is used once it is. * * @param contentDisplay the display to draw content with * @apiNote This is an EXPERIMENTAL feature, and it can have breaking changes */ public void setContentDisplay(@Nullable ContentDisplay contentDisplay) { synchronized (Countly.instance()) { - setContentDisplayInternal(contentDisplay); + SDKCore core = SDKCore.instance; + if (core == null) { + return; + } + core.contentDisplay = contentDisplay; + ModuleContent running = core.module(ModuleContent.class); + if (running != null) { + running.setContentDisplayInternal(contentDisplay); + } } } /** * Start asking the server for content to show. Ignored while already in a content zone. + * Once this is called, the zone stays even when the SDK behavior settings turn the content + * zone off. * * @apiNote This is an EXPERIMENTAL feature, and it can have breaking changes */ public void enterContentZone() { + Content target = target("[Content] enterContentZone"); + if (target != this) { + if (target != null) { + target.enterContentZone(); + } + return; + } synchronized (Countly.instance()) { L.i("[Content] enterContentZone, entering the content zone"); enterContentZoneInternal(); @@ -498,19 +1019,34 @@ public void enterContentZone() { * @apiNote This is an EXPERIMENTAL feature, and it can have breaking changes */ public void exitContentZone() { + Content target = target("[Content] exitContentZone"); + if (target != this) { + if (target != null) { + target.exitContentZone(); + } + return; + } synchronized (Countly.instance()) { L.i("[Content] exitContentZone, leaving the content zone"); - exitContentZoneInternal(); + exitContentZoneByApp(); } } /** * Re-enter the content zone right away, after flushing the event queue. Use it when a - * trigger condition just changed. Ignored while a content block is on screen. + * trigger condition just changed. Ignored while a content block is on screen and while the + * SDK behavior settings do not allow refreshing the content zone. * * @apiNote This is an EXPERIMENTAL feature, and it can have breaking changes */ public void refreshContentZone() { + Content target = target("[Content] refreshContentZone"); + if (target != this) { + if (target != null) { + target.refreshContentZone(); + } + return; + } synchronized (Countly.instance()) { L.i("[Content] refreshContentZone, refreshing the content zone"); refreshContentZoneInternal(); @@ -525,6 +1061,13 @@ public void refreshContentZone() { * @apiNote This is an EXPERIMENTAL feature, and it can have breaking changes */ public void previewContent(@Nullable String contentId) { + Content target = target("[Content] previewContent"); + if (target != this) { + if (target != null) { + target.previewContent(contentId); + } + return; + } synchronized (Countly.instance()) { L.i("[Content] previewContent, previewing content:[" + contentId + "]"); if (Utils.isEmptyOrNull(contentId)) { @@ -544,6 +1087,13 @@ public void previewContent(@Nullable String contentId) { * @apiNote This is an EXPERIMENTAL feature, and it can have breaking changes */ public void recordContentEvents(@Nullable String eventsJson) { + Content target = target("[Content] recordContentEvents"); + if (target != this) { + if (target != null) { + target.recordContentEvents(eventsJson); + } + return; + } synchronized (Countly.instance()) { L.d("[Content] recordContentEvents, recording the events of a content block"); recordContentEventsInternal(eventsJson); 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 2dbfb15ad..72a0c0280 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 @@ -3,6 +3,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import ly.count.sdk.java.Countly; import ly.count.sdk.java.Crash; import ly.count.sdk.java.CrashProcessor; @@ -17,9 +19,16 @@ public class ModuleCrashes extends ModuleBase { private boolean crashed = false; protected InternalConfig config; + private final Object crashHandlerLock = new Object(); + //guarded by crashHandlerLock private Thread.UncaughtExceptionHandler previousHandler = null; + //guarded by crashHandlerLock + private Thread.UncaughtExceptionHandler installedHandler = null; + //written under crashHandlerLock + private volatile boolean stopped = false; protected CrashProcessor crashProcessor = null; - protected List logs = new ArrayList<>(); + //guarded by itself, as breadcrumbs are added on any thread and taken on the crash handler thread + protected final List logs = new ArrayList<>(); Crashes crashInterface; @@ -41,55 +50,175 @@ public void init(InternalConfig config) { @Override public void stop(InternalConfig config, boolean clear) { try { - if (previousHandler != null) { - Thread.setDefaultUncaughtExceptionHandler(previousHandler); - } + restoreUncaughtExceptionHandler(); if (clear) { config.sdk.sdkStorage.storablePurge(config, CrashImpl.getStoragePrefix()); } } catch (Throwable t) { L.e("[ModuleCrash] Exception while stopping crash reporting" + t); } - logs.clear(); + synchronized (logs) { + logs.clear(); + } crashInterface = null; } @Override public void initFinished(final InternalConfig config) { - previousHandler = Thread.getDefaultUncaughtExceptionHandler(); + installUncaughtExceptionHandlerIfEnabled("initFinished"); + started = System.nanoTime(); + } + + /** + * Installs the uncaught exception handler when a server response enabled automatic crash + * reporting and it is not installed yet. + * + * @param config configuration of the running SDK + */ + @Override + protected void onSdkConfigurationChanged(InternalConfig config) { + installUncaughtExceptionHandlerIfEnabled("onSdkConfigurationChanged"); + } - if (internalConfig.sdk.hasConsentForFeature(CoreFeature.CrashReporting) && config.isUnhandledCrashReportingEnabled()) { - registerUncaughtExceptionHandler(); + /** + * Installs the uncaught exception handler once, while crash reporting has consent and the SDK + * behavior settings enable both crash reporting and automatic crash reporting. An installed + * handler stays until the module stops and checks both settings again for every crash. + * + * @param caller the calling function, for the log + */ + private void installUncaughtExceptionHandlerIfEnabled(@Nonnull String caller) { + if (stopped) { + return; } - started = System.nanoTime(); + if (!isAutomaticCrashReportingEnabled()) { + L.d("[ModuleCrash] " + caller + ", automatic crash reporting is disabled, the uncaught exception handler is not installed"); + return; + } + + if (!internalConfig.sdk.hasConsentForFeature(CoreFeature.CrashReporting)) { + L.d("[ModuleCrash] " + caller + ", crash reporting has no consent, the uncaught exception handler is not installed"); + return; + } + + boolean installed = false; + synchronized (crashHandlerLock) { + if (installedHandler == null && !stopped) { + previousHandler = Thread.getDefaultUncaughtExceptionHandler(); + installedHandler = createUncaughtExceptionHandler(previousHandler); + Thread.setDefaultUncaughtExceptionHandler(installedHandler); + installed = true; + } + } + + if (installed) { + L.d("[ModuleCrash] " + caller + ", installed the uncaught exception handler"); + } + } + + /** + * Whether the SDK behavior settings enable both crash reporting and automatic crash reporting. + * + * @return {@code true} when unhandled crashes may be recorded + */ + private boolean isAutomaticCrashReportingEnabled() { + ConfigurationProvider configProvider = internalConfig.getConfigurationProvider(); + return configProvider.getCrashReportingEnabled() && configProvider.getAutomaticCrashReportingEnabled(); } - private void registerUncaughtExceptionHandler() { - final Thread.UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler(); - Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> { + /** + * Builds the handler that records an unhandled crash, while the module runs and the SDK behavior + * settings enable automatic crash reporting, and then always hands the crash to the handler it replaced. + * While the crash is reported, the health check counts no method usage and no log codes; the + * crash itself is counted as a stored number that the health check of the next start reports. + * + * @param previous the handler to hand every crash to, {@code null} for none + * @return the handler + */ + @Nonnull + private Thread.UncaughtExceptionHandler createUncaughtExceptionHandler(@Nullable final Thread.UncaughtExceptionHandler previous) { + return (thread, throwable) -> { // needed since following UncaughtExceptionHandler can keep reference to this one crashed = true; - if (isActive()) { - recordExceptionInternal(throwable, false, null, null); + try { + if (isActive() && !stopped && isAutomaticCrashReportingEnabled()) { + L.stopHealthCheckRecordingForCrash(); + try { + if (recordExceptionInternal(throwable, false, null, null)) { + internalConfig.storageProvider.incrementAutomaticCrashCount(); + } + } finally { + L.resumeHealthCheckRecordingAfterCrash(); + } + } + } catch (Throwable recordFailure) { + L.e("[ModuleCrash] uncaughtException, failed to record the crash, [" + recordFailure + "]"); + } finally { + if (previous != null) { + previous.uncaughtException(thread, throwable); + } } + }; + } - if (handler != null) { - handler.uncaughtException(thread, throwable); + /** + * Stops the installed handler from recording and puts back the handler it replaced, if it is + * still the default one. A handler installed over it keeps it in the chain, where it only hands + * crashes on. + */ + private void restoreUncaughtExceptionHandler() { + String outcome = null; + synchronized (crashHandlerLock) { + stopped = true; + if (installedHandler != null) { + if (Thread.getDefaultUncaughtExceptionHandler() == installedHandler) { + Thread.setDefaultUncaughtExceptionHandler(previousHandler); + outcome = "restored the uncaught exception handler it replaced"; + } else { + outcome = "another uncaught exception handler was installed over this one, which stays in the chain and only hands crashes on"; + } + installedHandler = null; + previousHandler = null; } - }); + } + + if (outcome != null) { + L.d("[ModuleCrash] stop, " + outcome); + } } - protected void recordExceptionInternal(Throwable t, boolean handled, Map segments, String legacyCrashName) { + /** + * Records a crash, unless the SDK behavior settings turn crash reporting off, backend mode is + * on, or there is no throwable. + * + * @param t the throwable + * @param handled whether the app handled it + * @param segments custom segmentation, {@code null} for none + * @param legacyCrashName the name of the deprecated crash report call, {@code null} for none + * @return whether the crash was stored for sending + */ + protected boolean recordExceptionInternal(Throwable t, boolean handled, Map segments, String legacyCrashName) { + ConfigurationProvider configProvider = internalConfig.getConfigurationProvider(); + if (!configProvider.getTrackingEnabled()) { + L.w("[ModuleCrash] recordExceptionInternal, tracking disabled by SDK behavior settings; ignoring"); + L.recordLogCode("w505", HealthCheckCounter.AREA_CRASHES); + return false; + } + if (!configProvider.getCrashReportingEnabled()) { + L.d("[ModuleCrash] recordExceptionInternal, crash reporting disabled by SDK behavior settings; ignoring"); + return false; + } if (config.isBackendModeEnabled()) { L.w("[ModuleCrash] recordExceptionInternal, Skipping crash, backend mode is enabled!"); - return; + return false; } if (t == null) { - L.e("[ModuleCrash] recordExceptionInternal, Throwable cannot be null"); - return; + L.w("[ModuleCrash] recordExceptionInternal, Throwable cannot be null"); + L.recordLogCode("w700", HealthCheckCounter.AREA_CRASHES); + return false; } CrashImpl crash = new CrashImpl(L).addThrowable(t).setFatal(!handled).addSegments(segments); @@ -99,7 +228,14 @@ protected void recordExceptionInternal(Throwable t, boolean handled, Map= config.getMaxBreadcrumbCount()) { - logs.remove(0); - } + ConfigurationProvider configProvider = internalConfig.getConfigurationProvider(); + String breadcrumb = UtilsInternalLimits.truncateValue(record, configProvider.getMaxValueSize(), L, "[ModuleCrash] addBreadcrumbInternal"); - logs.add(record); + int maxBreadcrumbCount = configProvider.getMaxBreadcrumbCount(); + synchronized (logs) { + //a loop, as the limit can shrink while breadcrumbs are kept + while (!logs.isEmpty() && logs.size() >= maxBreadcrumbCount) { + logs.remove(0); + } + + logs.add(breadcrumb); + } } public class Crashes { + /** + * The interface a call goes to: this one while its module runs, the running module's when + * this one was handed out before that started or kept from one that stopped, and + * {@code null} while the feature does not run. + * + * @param call the call, for the log line + * @return the interface, {@code null} for none + */ + private Crashes target(String call) { + ModuleCrashes running = runningInstance(call); + return running == null ? null : running.crashInterface; + } + /** * Add crash breadcrumb like log record to the log that will be sent together with crash report * * @param record String a bread crumb for the crash report */ public void addCrashBreadcrumb(String record) { + Crashes target = target("[Crashes] addCrashBreadcrumb"); + if (target != this) { + if (target != null) { + target.addCrashBreadcrumb(record); + } + return; + } synchronized (Countly.instance()) { L.i("[Crashes] Adding crash breadcrumb"); + L.recordUsage(HealthCheckCounter.AREA_CRASHES, "log"); addBreadcrumbInternal(record); } } @@ -175,7 +346,15 @@ public void addCrashBreadcrumb(String record) { * @param exception Throwable to log */ public void recordHandledException(Throwable exception) { + Crashes target = target("[Crashes] recordHandledException"); + if (target != this) { + if (target != null) { + target.recordHandledException(exception); + } + return; + } synchronized (Countly.instance()) { + L.recordUsage(HealthCheckCounter.AREA_CRASHES, "record"); recordExceptionInternal(exception, true, null, null); } } @@ -186,7 +365,15 @@ public void recordHandledException(Throwable exception) { * @param exception Throwable to log */ public void recordUnhandledException(Throwable exception) { + Crashes target = target("[Crashes] recordUnhandledException"); + if (target != this) { + if (target != null) { + target.recordUnhandledException(exception); + } + return; + } synchronized (Countly.instance()) { + L.recordUsage(HealthCheckCounter.AREA_CRASHES, "record"); recordExceptionInternal(exception, false, null, null); } } @@ -197,7 +384,15 @@ public void recordUnhandledException(Throwable exception) { * @param exception Throwable to log */ public void recordHandledException(final Throwable exception, final Map customSegmentation) { + Crashes target = target("[Crashes] recordHandledException"); + if (target != this) { + if (target != null) { + target.recordHandledException(exception, customSegmentation); + } + return; + } synchronized (Countly.instance()) { + L.recordUsage(HealthCheckCounter.AREA_CRASHES, "record"); recordExceptionInternal(exception, true, customSegmentation, null); } } @@ -208,7 +403,15 @@ public void recordHandledException(final Throwable exception, final Map customSegmentation) { + Crashes target = target("[Crashes] recordUnhandledException"); + if (target != this) { + if (target != null) { + target.recordUnhandledException(exception, customSegmentation); + } + return; + } synchronized (Countly.instance()) { + L.recordUsage(HealthCheckCounter.AREA_CRASHES, "record"); recordExceptionInternal(exception, false, customSegmentation, null); } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleDeviceIdCore.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleDeviceIdCore.java index e77f93c54..32919aad1 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleDeviceIdCore.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleDeviceIdCore.java @@ -141,14 +141,19 @@ public void logout() { protected void changeDeviceIdInternal(String id, DeviceIdType type, boolean withMerge) { if (Utils.isEmptyOrNull(id)) { L.w("[ModuleDeviceIdCore] changeDeviceId, Empty id passed to changeDeviceId method"); + L.recordLogCode("w601"); return; } final Config.DID old = internalConfig.getDeviceId(); if (old.id.equals(id)) { - L.w("[ModuleDeviceIdCore] changeDeviceId, Same id passed to changeDeviceId method, ignoring"); + L.d("[ModuleDeviceIdCore] changeDeviceId, Same id passed to changeDeviceId method, ignoring"); return; } + if (!withMerge) { + stopLogGatheringForDeviceIdChange(); + } + internalConfig.storageProvider.setDeviceIdType(type.name()); internalConfig.storageProvider.setDeviceID(id); internalConfig.setDeviceId(new Config.DID(type.index, id)); @@ -156,6 +161,18 @@ protected void changeDeviceIdInternal(String id, DeviceIdType type, boolean with SDKCore.instance.notifyModulesDeviceIdChanged(old.id, withMerge); } + /** + * Has the gathered SDK log lines of the current user queued under the current device ID and + * the gather stopped, as the device ID is about to change without merge. + */ + private void stopLogGatheringForDeviceIdChange() { + SDKCore core = SDKCore.instance; + ModuleConfiguration configuration = core == null ? null : core.module(ModuleConfiguration.class); + if (configuration != null) { + configuration.stopLogGatheringForDeviceIdChange(); + } + } + /** * Gets id of the strategy supplied. In case strategy is not available, returns a fallback strategy. * In case strategy is available but id cannot be acquired right now, returns null. @@ -198,11 +215,12 @@ protected Config.DID acquireId() { private void setIDInternal(String newDeviceID) { if (Utils.isEmptyOrNull(newDeviceID)) { L.w("[ModuleDeviceIdCore] setID, Empty id passed to setID method"); + L.recordLogCode("w601"); return; } if (getIDInternal().equals(newDeviceID)) { - L.w("[ModuleDeviceIdCore] setID, Same id passed to setID method, ignoring"); + L.d("[ModuleDeviceIdCore] setID, Same id passed to setID method, ignoring"); return; } @@ -237,12 +255,32 @@ protected String getIDInternal() { public class DeviceId { + /** + * The interface a call goes to: this one while its module runs, the running module's when + * this one was handed out before that started or kept from one that stopped, and + * {@code null} while the feature does not run. + * + * @param call the call, for the log line + * @return the interface, {@code null} for none + */ + private DeviceId target(String call) { + ModuleDeviceIdCore running = runningInstance(call); + return running == null ? null : running.deviceIdInterface; + } + /** * Returns current device id. * * @return device id string */ public String getID() { + DeviceId target = target("[DeviceId] getID"); + if (target != this) { + if (target == null) { + return null; + } + return target.getID(); + } synchronized (Countly.instance()) { return getIDInternal(); } @@ -255,6 +293,13 @@ public String getID() { * @param newDeviceID device id to set */ public void setID(String newDeviceID) { + DeviceId target = target("[DeviceId] setID"); + if (target != this) { + if (target != null) { + target.setID(newDeviceID); + } + return; + } synchronized (Countly.instance()) { setIDInternal(newDeviceID); } @@ -266,6 +311,13 @@ public void setID(String newDeviceID) { * @return device id type */ public DeviceIdType getType() { + DeviceId target = target("[DeviceId] getType"); + if (target != this) { + if (target == null) { + return null; + } + return target.getType(); + } synchronized (Countly.instance()) { return getTypeInternal(); } @@ -277,6 +329,13 @@ public DeviceIdType getType() { * @param id new device id string, cannot be empty */ public void changeWithMerge(String id) { + DeviceId target = target("[DeviceId] changeWithMerge"); + if (target != this) { + if (target != null) { + target.changeWithMerge(id); + } + return; + } synchronized (Countly.instance()) { changeDeviceIdInternal(id, DeviceIdType.DEVELOPER_SUPPLIED, true); } @@ -288,6 +347,13 @@ public void changeWithMerge(String id) { * @param id new device id string, cannot be empty */ public void changeWithoutMerge(String id) { + DeviceId target = target("[DeviceId] changeWithoutMerge"); + if (target != this) { + if (target != null) { + target.changeWithoutMerge(id); + } + return; + } synchronized (Countly.instance()) { changeDeviceIdInternal(id, DeviceIdType.DEVELOPER_SUPPLIED, false); } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleEvents.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleEvents.java index 1e48a875f..7de779058 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleEvents.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleEvents.java @@ -1,18 +1,37 @@ package ly.count.sdk.java.internal; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import ly.count.sdk.java.Countly; import ly.count.sdk.java.Session; import ly.count.sdk.java.View; public class ModuleEvents extends ModuleBase { + /** + * The keys of the events the SDK records itself, which the custom event settings of the SDK + * behavior settings do not apply to. Any other key is a custom event, one starting with + * {@code [CLY]_} too. + */ + static final Set INTERNAL_EVENT_KEYS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + ModuleViews.KEY_VIEW_EVENT, FeedbackWidgetType.nps.eventKey, FeedbackWidgetType.survey.eventKey, FeedbackWidgetType.rating.eventKey))); + protected EventQueue eventQueue = null; final Map timedEvents = new ConcurrentHashMap<>(); protected Events eventsInterface = null; - ViewIdProvider viewIdProvider = null; IdGenerator idGenerator = null; String previousEventId = null; + /** + * 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. + */ + private volatile Thread threadEndingEventsOfThePreviousDeviceId = null; @Override public void init(InternalConfig config) { @@ -25,12 +44,6 @@ public void init(InternalConfig config) { idGenerator = config.eventIdGenerator; } - @Override - public void initFinished(InternalConfig config) { - super.initFinished(config); - viewIdProvider = config.viewIdProvider; - } - @Override protected void onTimer() { addEventsToRequestQ(null); @@ -46,20 +59,26 @@ public void deviceIdChanged(String oldDeviceId, boolean withMerge) { super.deviceIdChanged(oldDeviceId, withMerge); L.d("[ModuleEvents] deviceIdChanged: oldDeviceId = " + oldDeviceId + ", withMerge = " + withMerge); if (!withMerge) { - for (Map.Entry timedEventEntry : timedEvents.entrySet()) { - L.d("[ModuleEvents] deviceIdChanged, Ending timed event: [" + timedEventEntry.getKey() + "]"); - endEventInternal(timedEventEntry.getKey(), timedEventEntry.getValue().segmentation, timedEventEntry.getValue().count, timedEventEntry.getValue().sum); - } + //the new device ID is already set, so the events ended here are sent below under the old one, never on their own + threadEndingEventsOfThePreviousDeviceId = Thread.currentThread(); + try { + for (Map.Entry timedEventEntry : timedEvents.entrySet()) { + L.d("[ModuleEvents] deviceIdChanged, Ending timed event: [" + timedEventEntry.getKey() + "]"); + endEventInternal(timedEventEntry.getKey(), timedEventEntry.getValue().segmentation, timedEventEntry.getValue().count, timedEventEntry.getValue().sum); + } - // this part is to end and record the current view if exists - Session session = Countly.session(); - if (session != null && session.isActive()) { - View currentView = ((SessionImpl) session).currentView; - if (currentView != null) { - currentView.stop(true); - } else { - Storage.pushAsync(internalConfig, (SessionImpl) Countly.session()); + // this part is to end and record the current view if exists + Session session = Countly.session(); + if (session != null && session.isActive()) { + View currentView = ((SessionImpl) session).currentView; + if (currentView != null) { + currentView.stop(true); + } else { + Storage.pushAsync(internalConfig, (SessionImpl) Countly.session()); + } } + } finally { + threadEndingEventsOfThePreviousDeviceId = null; } addEventsToRequestQ(oldDeviceId); @@ -75,7 +94,12 @@ public void stop(InternalConfig config, final boolean clear) { } } - private synchronized void addEventsToRequestQ(String deviceId) { + /** + * Moves every queued event into one request. + * + * @param deviceId the device ID the events belong to, {@code null} for the current one + */ + private synchronized void addEventsToRequestQ(@Nullable String deviceId) { L.d("[ModuleEvents] addEventsToRequestQ"); if (eventQueue.getEQ().isEmpty()) { @@ -83,36 +107,99 @@ private synchronized void addEventsToRequestQ(String deviceId) { return; } + Request request = eventsRequest(deviceId); + eventQueue.clear(); + ModuleRequests.pushAsync(internalConfig, request); + } + + /** + * Moves every queued event into one request, for a content trigger round, which sends the + * request queue once this request is stored. + * + * @param onStored called once the request is stored, or right away when no event is queued + */ + synchronized void moveEventsToRequestQueue(@Nonnull Runnable onStored) { + if (eventQueue.getEQ().isEmpty()) { + 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); + return request; + } + /** + * Drops the queued events, unsent; timed events are kept. Takes the lock of moving the queued + * events into a request, so a request they were already moved into is queued first. + */ + synchronized void clearEventQueue() { eventQueue.clear(); - ModuleRequests.pushAsync(internalConfig, request); } protected void recordEventInternal(String key, int count, Double sum, Double dur, Map segmentation, String eventIdOverride) { + ConfigurationProvider configProvider = internalConfig.getConfigurationProvider(); + if (!configProvider.getTrackingEnabled()) { + L.w("[ModuleEvents] recordEventInternal, tracking is disabled by the SDK behavior settings, event [" + key + "] will not be recorded"); + L.recordLogCode("w505", HealthCheckCounter.AREA_EVENTS); + return; + } + if (count <= 0) { L.w("[ModuleEvents] recordEventInternal, Count can't be less than 1, ignoring this event."); + L.recordLogCode("w750", HealthCheckCounter.AREA_EVENTS); return; } if (key == null || key.isEmpty()) { L.w("[ModuleEvents] recordEventInternal, Key can't be null or empty, ignoring this event."); + L.recordLogCode("w701", HealthCheckCounter.AREA_EVENTS); return; } + boolean isCustomEvent = !INTERNAL_EVENT_KEYS.contains(key); + if (isCustomEvent) { + if (!configProvider.getCustomEventTrackingEnabled()) { + L.d("[ModuleEvents] recordEventInternal, custom event tracking is disabled by the SDK behavior settings, event [" + key + "] will not be recorded"); + return; + } + + if (!UtilsListingFilters.applyEventFilter(key, configProvider)) { + L.w("[ModuleEvents] recordEventInternal, event [" + key + "] is filtered out by the event filter of the SDK behavior settings, it will not be recorded"); + return; + } + + segmentation = filteredCustomEventSegmentation(key, 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"); Utils.removeInvalidDataFromSegments(segmentation, L); - if (internalConfig.isAutoSendUserProperties() && internalConfig.sdk.userProfile() != null) { - internalConfig.sdk.module(ModuleUserProfile.class).saveInternal(); + if (isCustomEvent) { + key = UtilsInternalLimits.truncateKey(key, configProvider.getMaxKeyLength(), L, "[ModuleEvents] recordEventInternal"); + segmentation = UtilsInternalLimits.applySegmentationLimits(segmentation, configProvider, L, "[ModuleEvents] recordEventInternal"); } + ModuleUserProfile.saveIfSentAutomatically(internalConfig); + String eventId, pvid = null, cvid = null; if (Utils.isEmptyOrNull(eventIdOverride)) { L.d("[ModuleEvents] recordEventInternal, Generating new event id because it was null or empty"); @@ -121,6 +208,7 @@ protected void recordEventInternal(String key, int count, Double sum, Double dur eventId = eventIdOverride; } + ViewIdProvider viewIdProvider = internalConfig.viewIdProvider; if (key.equals(ModuleViews.KEY_VIEW_EVENT)) { pvid = viewIdProvider.getPreviousViewId(); } else { @@ -135,27 +223,97 @@ protected void recordEventInternal(String key, int count, Double sum, Double dur } addEventToQueue(new EventImpl(key, count, sum, dur, segmentation, L, eventId, pvid, cvid, previousEventIdToSend)); + notifyContentTrigger(keyAsGiven, eventId, segmentation); } - private void addEventToQueue(EventImpl event) { + /** + * 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))); + } + } + + /** + * Applies the segmentation filter and then the segmentation filter of this event to the + * segmentation of a custom event. The filters work on a copy, as the map belongs to the caller. + * + * @param key the key of the custom event + * @param segmentation the segmentation the caller passed, {@code null} for none + * @param configProvider the settings in effect + * @return the filtered copy, {@code null} when there was no segmentation + */ + @Nullable + private Map filteredCustomEventSegmentation(@Nonnull String key, @Nullable Map segmentation, @Nonnull ConfigurationProvider configProvider) { + if (segmentation == null) { + return null; + } + + Map filtered = new HashMap<>(segmentation); + UtilsListingFilters.applySegmentationFilter(filtered, configProvider, L); + UtilsListingFilters.applyEventSegmentationFilter(key, filtered, configProvider, L); + return filtered; + } + + /** + * Adds an event to the event queue and sends the queue when it is full. + * + * @param event the event + */ + private void addEventToQueue(@Nonnull EventImpl event) { L.d("[ModuleEvents] addEventToQueue"); eventQueue.addEvent(event); checkEventQueueToSend(false); } + /** + * Sends the queued events when asked to or when the queue reached its threshold. + * + * @param forceSend whether to send whatever is queued + */ 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.getEventsBufferSize()) { + if (forceSend || eventQueue.eqSize() >= internalConfig.getConfigurationProvider().getEventQueueSizeThreshold()) { addEventsToRequestQ(null); } } boolean startEventInternal(final String key) { if (key == null || key.isEmpty()) { - L.e("[ModuleEvents] Can't start event with a null or empty key"); + L.w("[ModuleEvents] Can't start event with a null or empty key"); + L.recordLogCode("w700", HealthCheckCounter.AREA_EVENTS); return false; } if (timedEvents.containsKey(key)) { + L.w("[ModuleEvents] startEventInternal, a timed event with the key [" + key + "] is already running, the call is ignored"); + L.recordLogCode("w722", HealthCheckCounter.AREA_EVENTS); return false; } @@ -177,19 +335,22 @@ boolean endEventInternal(final String key, final Map segmentatio L.d("[ModuleEvents] Ending event: [" + key + "]"); if (key == null || key.isEmpty()) { - L.e("[ModuleEvents] Can't end event with a null or empty key"); + L.w("[ModuleEvents] Can't end event with a null or empty key"); + L.recordLogCode("w700", HealthCheckCounter.AREA_EVENTS); return false; } EventImpl event = timedEvents.remove(key); if (event == null) { - L.w("endEventInternal, No timed event with the name [" + key + "] is started, nothing to end. Will ignore call."); + L.w("[ModuleEvents] endEventInternal, No timed event with the name [" + key + "] is started, nothing to end. Will ignore call."); + L.recordLogCode("w720", HealthCheckCounter.AREA_EVENTS); return false; } if (count < 1) { - L.e("endEventInternal, Countly event count should be greater than zero [" + count + "]. Changing value to 1"); + L.w("[ModuleEvents] endEventInternal, Countly event count should be greater than zero [" + count + "]. Changing value to 1"); + L.recordLogCode("w750", HealthCheckCounter.AREA_EVENTS); count = 1; } @@ -204,17 +365,37 @@ boolean endEventInternal(final String key, final Map segmentatio boolean cancelEventInternal(final String key) { if (key == null || key.isEmpty()) { - L.e("[ModuleEvents] Can't cancel event with a null or empty key"); + L.w("[ModuleEvents] Can't cancel event with a null or empty key"); + L.recordLogCode("w700", HealthCheckCounter.AREA_EVENTS); return false; } EventImpl event = timedEvents.remove(key); - return event != null; + if (event == null) { + L.w("[ModuleEvents] cancelEventInternal, no timed event with the key [" + key + "] is running, the call is ignored"); + L.recordLogCode("w721", HealthCheckCounter.AREA_EVENTS); + return false; + } + + return true; } public class Events { + /** + * The interface a call goes to: this one while its module runs, the running module's when + * this one was handed out before that started or kept from one that stopped, and + * {@code null} while the feature does not run. + * + * @param call the call, for the log line + * @return the interface, {@code null} for none + */ + private Events target(String call) { + ModuleEvents running = runningInstance(call); + return running == null ? null : running.eventsInterface; + } + /** * Record an event. * @@ -225,7 +406,15 @@ public class Events { * @param segmentation additional segmentation data that you want to set, leave null if you don't want to add anything */ public void recordEvent(String key, Map segmentation, int count, Double sum, Double dur) { + Events target = target("[Events] recordEvent"); + if (target != this) { + if (target != null) { + target.recordEvent(key, segmentation, count, sum, dur); + } + return; + } L.i("[Events] recordEvent: key = " + key + ", count = " + count + ", sum = " + sum + ", segmentation = " + segmentation + ", dur = " + dur); + L.recordUsage(HealthCheckCounter.AREA_EVENTS, "record"); recordEventInternal(key, count, sum, dur, segmentation, null); } @@ -305,7 +494,12 @@ public void recordEvent(String key, int count, Double sum) { * @return true if no event with this key existed before and event is started, false otherwise */ public boolean startEvent(final String key) { + Events target = target("[Events] startEvent"); + if (target != this) { + return target != null && target.startEvent(key); + } L.i("[Events] startEvent: key = " + key); + L.recordUsage(HealthCheckCounter.AREA_EVENTS, "start"); return startEventInternal(key); } @@ -316,7 +510,12 @@ public boolean startEvent(final String key) { * @return true if event with this key has been previously started, false otherwise */ public boolean endEvent(final String key) { + Events target = target("[Events] endEvent"); + if (target != this) { + return target != null && target.endEvent(key); + } L.i("[Events] endEvent: key = " + key); + L.recordUsage(HealthCheckCounter.AREA_EVENTS, "end"); return endEventInternal(key, null, 1, null); } @@ -332,7 +531,12 @@ public boolean endEvent(final String key) { * @throws IllegalArgumentException if key is null or empty, count is less than 1, or if segmentation contains null or empty keys or values */ public boolean endEvent(final String key, final Map segmentation, final int count, final Double sum) { + Events target = target("[Events] endEvent"); + if (target != this) { + return target != null && target.endEvent(key, segmentation, count, sum); + } L.i("[Events] endEvent: key = " + key + ", segmentation = " + segmentation + ", count = " + count + ", sum = " + sum); + L.recordUsage(HealthCheckCounter.AREA_EVENTS, "end"); return endEventInternal(key, segmentation, count, sum); } @@ -342,7 +546,12 @@ public boolean endEvent(final String key, final Map segmentation * @return true if event with this key has been previously started, false otherwise **/ public boolean cancelEvent(final String key) { + Events target = target("[Events] cancelEvent"); + if (target != this) { + return target != null && target.cancelEvent(key); + } L.i("[Events] cancelEvent: key = " + key); + L.recordUsage(HealthCheckCounter.AREA_EVENTS, "cancel"); return cancelEventInternal(key); } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleFeedback.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleFeedback.java index d088a5262..f6702c0b4 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleFeedback.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleFeedback.java @@ -263,7 +263,8 @@ private void reportFeedbackWidgetManuallyInternal(CountlyFeedbackWidget widgetIn } else { //widget was filled out //merge given segmentation - segm.putAll(widgetResult); + int maxValueSize = internalConfig.getConfigurationProvider().getMaxValueSize(); + segm.putAll(UtilsInternalLimits.truncateStringValues(widgetResult, maxValueSize, L, "[ModuleFeedback] reportFeedbackWidgetManuallyInternal")); } Countly.instance().events().recordEvent(widgetInfo.type.eventKey, segm); @@ -373,12 +374,34 @@ private String constructFeedbackWidgetUrlInternal(CountlyFeedbackWidget widgetIn public class Feedback { + /** + * The interface a call goes to: this one while its module runs, the running module's when + * this one was handed out before that started or kept from one that stopped, and + * {@code null} while the feature does not run. + * + * @param call the call, for the log line + * @return the interface, {@code null} for none + */ + private Feedback target(String call) { + ModuleFeedback running = runningInstance(call); + return running == null ? null : running.feedbackInterface; + } + /** * Get a list of available feedback widgets for this device ID * * @param callback retrieve widget list callback */ public void getAvailableFeedbackWidgets(@Nullable CallbackOnFinish> callback) { + Feedback target = target("[Feedback] getAvailableFeedbackWidgets"); + if (target != this) { + if (target != null) { + target.getAvailableFeedbackWidgets(callback); + } else if (callback != null) { + callback.onFinished(null, NOT_RUNNING_ERROR); + } + return; + } synchronized (Countly.instance()) { L.i("[Feedback] getAvailableFeedbackWidgets, Trying to retrieve feedback widget list"); @@ -392,6 +415,13 @@ public void getAvailableFeedbackWidgets(@Nullable CallbackOnFinish callback) { + Feedback target = target("[Feedback] getFeedbackWidgetData"); + if (target != this) { + if (target != null) { + target.getFeedbackWidgetData(widgetInfo, callback); + } else if (callback != null) { + callback.onFinished(null, NOT_RUNNING_ERROR); + } + return; + } synchronized (Countly.instance()) { L.i("[Feedback] getFeedbackWidgetData, Trying to retrieve feedback widget data"); @@ -447,6 +493,13 @@ public void getFeedbackWidgetData(@Nullable CountlyFeedbackWidget widgetInfo, @N * @param widgetResult widget result */ public void reportFeedbackWidgetManually(@Nullable CountlyFeedbackWidget widgetInfo, @Nullable JSONObject widgetData, @Nullable Map widgetResult) { + Feedback target = target("[Feedback] reportFeedbackWidgetManually"); + if (target != this) { + if (target != null) { + target.reportFeedbackWidgetManually(widgetInfo, widgetData, widgetResult); + } + return; + } synchronized (Countly.instance()) { L.i("[Feedback] reportFeedbackWidgetManually, Trying to report feedback widget manually"); diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleHealthCheck.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleHealthCheck.java new file mode 100644 index 000000000..d47ee0a67 --- /dev/null +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleHealthCheck.java @@ -0,0 +1,194 @@ +package ly.count.sdk.java.internal; + +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import ly.count.sdk.java.Session; +import org.json.JSONObject; + +/** + * Sends the SDK health check once per initialization, as an immediate request to {@code /i}, and + * stores the health check counters on the update timer, at the end of a session and when the SDK + * stops. Logs at debug level only, as every warning and error the SDK logs is counted. + */ +public class ModuleHealthCheck extends ModuleBase { + static final String ENDPOINT = "/i?"; + static final String KEY_HEALTH_CHECK = "hc"; + static final String KEY_METRICS = "metrics"; + static final String KEY_APP_VERSION = "_app_version"; + + private final AtomicBoolean healthCheckSent = new AtomicBoolean(false); + @Nullable HealthCheckCounter counter; + + @Override + public void init(InternalConfig config) { + super.init(config); + counter = config.sdk == null ? null : config.sdk.healthCheckCounter; + L.v("[ModuleHealthCheck] init, health check enabled:[" + config.isHealthCheckEnabled() + "]"); + } + + @Override + protected void initFinished(InternalConfig config) { + sendHealthCheck(); + } + + @Override + protected void onTimer() { + HealthCheckCounter current = counter; + if (current != null) { + current.saveState(); + } + } + + @Override + public void onSessionEnded(Session session, InternalConfig config) { + HealthCheckCounter current = counter; + if (current != null) { + current.saveState(); + } + } + + /** + * Stores the counters when the SDK stops and keeps its data. When it clears its data, the + * stored state goes with it. + * + * @param config configuration of the SDK being stopped + * @param clear whether the SDK clears its data + */ + @Override + public void stop(InternalConfig config, boolean clear) { + HealthCheckCounter current = counter; + if (current != null && !clear) { + current.saveState(); + } + counter = null; + } + + /** + * Sends the health check, unless it is disabled, offline mode is on, the SDK behavior settings + * turned networking off, or it was sent already in this initialization. The request carries + * the base request parameters, the app version as metrics while the sessions consent allows + * metrics, and a snapshot of the counters. Only what the snapshot reported is taken away from + * the counters, and only once the server accepted it: a 2xx answer with a JSON object that has + * a "result". Otherwise the counters wait for the next initialization. + */ + void sendHealthCheck() { + L.v("[ModuleHealthCheck] sendHealthCheck, preparing the health check"); + + if (!internalConfig.isHealthCheckEnabled()) { + L.d("[ModuleHealthCheck] sendHealthCheck, the health check is disabled, nothing is sent"); + return; + } + + if (internalConfig.isTemporaryIdEnabled()) { + L.d("[ModuleHealthCheck] sendHealthCheck, offline mode is on, nothing is sent"); + return; + } + + if (!internalConfig.getNetworkingEnabled()) { + L.d("[ModuleHealthCheck] sendHealthCheck, networking is disabled by the SDK behavior settings, the counters wait for the next initialization"); + return; + } + + final HealthCheckCounter current = counter; + SDKCore core = internalConfig.sdk; + Networking networking = core == null ? null : core.networking; + if (current == null || networking == null || networking.getTransport() == null) { + L.d("[ModuleHealthCheck] sendHealthCheck, the SDK has no counters or no networking, nothing is sent"); + return; + } + + if (!healthCheckSent.compareAndSet(false, true)) { + L.d("[ModuleHealthCheck] sendHealthCheck, the health check was already sent in this initialization"); + return; + } + + final JSONObject snapshot = current.snapshot(); + Params params = ModuleRequests.prepareRequiredParams(internalConfig); + String metrics = healthCheckMetrics(); + if (metrics != null) { + params.add(KEY_METRICS, metrics); + } + params.add(KEY_HEALTH_CHECK, snapshot.toString()); + + L.d("[ModuleHealthCheck] sendHealthCheck, sending the health check [" + snapshot + "]"); + internalConfig.immediateRequestGenerator.createImmediateRequestMaker().doWork(params.toString(), ENDPOINT, networking.getTransport(), false, true, response -> { + if (response == null || !response.has("result")) { + L.d("[ModuleHealthCheck] sendHealthCheck, the server did not accept the health check, the counters are kept for the next initialization, response:[" + response + "]"); + return; + } + + if (counter != current) { + L.d("[ModuleHealthCheck] sendHealthCheck, the SDK stopped before the answer arrived, the counters are left as they are"); + return; + } + + L.d("[ModuleHealthCheck] sendHealthCheck, the server accepted the health check"); + current.clearSentValues(snapshot); + }, L); + } + + /** + * The metrics of the health check: only the app version, the overridden value when the + * developer set one. Sent only while the sessions consent allows metrics, as for a session + * start, since this SDK has no consent of its own for metrics. + * + * @return the metrics as JSON text, {@code null} when there is no app version or no consent + */ + @Nullable + String healthCheckMetrics() { + SDKCore core = internalConfig.sdk; + if (core == null || !core.hasConsentForFeature(CoreFeature.Sessions)) { + return null; + } + + String appVersion = internalConfig.getApplicationVersion(); + Map overrides = internalConfig.getMetricOverride(); + if (overrides != null && !Utils.isEmptyOrNull(overrides.get(KEY_APP_VERSION))) { + appVersion = overrides.get(KEY_APP_VERSION); + } + + if (Utils.isEmptyOrNull(appVersion)) { + return null; + } + + return new JSONObject().put(KEY_APP_VERSION, appVersion).toString(); + } + + /** + * Whether the health check was sent in this initialization. + * + * @return {@code true} once it was sent + */ + boolean isHealthCheckSent() { + return healthCheckSent.get(); + } + + /** + * The counters this module sends, for the tests. + * + * @return the counters, {@code null} once the module stopped + */ + @Nullable + HealthCheckCounter counter() { + return counter; + } + + /** + * Creates the counters of a starting SDK, unless it runs in backend mode, where no health + * check is sent. + * + * @param config configuration of the starting SDK + * @param storageProvider where the counters are stored + * @param core the starting SDK, which tells which feature has consent + * @return the counters, {@code null} in backend mode + */ + @Nullable + static HealthCheckCounter createCounter(@Nonnull InternalConfig config, @Nonnull StorageProvider storageProvider, @Nonnull SDKCore core) { + if (config.isBackendModeEnabled()) { + return null; + } + return new HealthCheckCounter(storageProvider, config.getLogger(), core::hasConsentForUsageArea); + } +} diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleLocation.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleLocation.java index c81b2adba..6f49fd4cc 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleLocation.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleLocation.java @@ -3,6 +3,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import ly.count.sdk.java.Countly; +import org.json.JSONObject; public class ModuleLocation extends ModuleBase { boolean locationDisabled = false; @@ -28,23 +29,63 @@ public void init(InternalConfig internalConfig) { void disableLocationInternal() { L.d("[ModuleLocation] Calling 'disableLocationInternal'"); + clearLocation(); + sendLocation(); + } + + /** + * Forgets the location and marks it disabled, so the next location request erases it. + */ + private void clearLocation() { country = null; city = null; location = null; ip = null; locationDisabled = true; - sendLocation(); + } + + /** + * Queues a request carrying the location as it is now. + */ + private void pushLocation() { + ModuleRequests.pushAsync(internalConfig, new Request(prepareLocationParams()), true, null); + } + + /** + * Clears the location and erases it on the server right away, without waiting for a session to + * begin, as when the location consent is removed. + */ + void eraseLocation() { + L.d("[ModuleLocation] eraseLocation"); + clearLocation(); + pushLocation(); } void sendLocation() { L.d("[ModuleLocation] Calling 'sendLocation'"); SessionImpl session = internalConfig.sdk.getSession(); - if (session == null || session.getBegan() != null) { - ModuleRequests.pushAsync(internalConfig, new Request(prepareLocationParams()), true, null); + if (session == null || session.getBegan() != null || !isLocationSentWithSessionBegin()) { + pushLocation(); } // else case, values are added to the session begin request } + /** + * Whether a session that has not begun yet sends the location with its begin request, which the + * SDK behavior settings allow only while both session tracking and location tracking are enabled. + * + * @return {@code true} when the location can wait for the begin request + */ + private boolean isLocationSentWithSessionBegin() { + ConfigurationProvider configProvider = internalConfig.getConfigurationProvider(); + return configProvider.getSessionTrackingEnabled() && configProvider.getLocationTrackingEnabled(); + } + void setLocationInternal(@Nullable String countryCode, @Nullable String cityName, @Nullable String gpsCoordinates, @Nullable String ipAddress) { + ConfigurationProvider configProvider = internalConfig.getConfigurationProvider(); + if (!configProvider.getTrackingEnabled() || !configProvider.getLocationTrackingEnabled()) { + L.d("[ModuleLocation] setLocationInternal, location tracking disabled by SDK behavior settings; ignoring"); + return; + } L.d("[ModuleLocation] setLocationInternal, Setting location parameters, cc[" + countryCode + "] cy[" + city + "] gps[" + gpsCoordinates + "] ip[" + ipAddress + "]"); if (countryCode != null ^ city != null) { @@ -96,8 +137,10 @@ public void stop(InternalConfig internalConfig, boolean clear) { @Override public void initFinished(@Nonnull InternalConfig config) { if (config.isLocationDisabled()) { - //disable location if needed - disableLocationInternal(); + //disable location if needed, unless a settings response during init already did and sent the erase request + if (!locationDisabled) { + disableLocationInternal(); + } } else { //if we are not disabling location, check for other set values String[] locParams = config.getLocationParams(); // country, city, location, ip @@ -107,14 +150,35 @@ public void initFinished(@Nonnull InternalConfig config) { } } + /** + * Disables location when a server response turned location tracking off, which erases the + * location stored on the server as {@link Location#disableLocation()} does, and drops the + * location values held for the next user details request. + * + * @param config configuration of the running SDK + */ + @Override + protected void onSdkConfigurationChanged(InternalConfig config) { + synchronized (Countly.instance()) { + if (config.getConfigurationProvider().getLocationTrackingEnabled()) { + return; + } + dropDisallowedLegacyValues(); + if (!locationDisabled) { + L.d("[ModuleLocation] onSdkConfigurationChanged, location tracking was disabled by the SDK behavior settings, disabling location"); + disableLocationInternal(); + } + } + } + protected void saveLocationToParamsLegacy(Params params) { - if (countryLegacy != null) { + if (isLegacyValueAllowed(countryLegacy)) { params.add("country_code", countryLegacy); } - if (cityLegacy != null) { + if (isLegacyValueAllowed(cityLegacy)) { params.add("city", cityLegacy); } - if (locationLegacy != null) { + if (isLegacyValueAllowed(locationLegacy)) { params.add("location", locationLegacy); } countryLegacy = null; @@ -124,23 +188,79 @@ protected void saveLocationToParamsLegacy(Params params) { protected void setLocationLegacy(@Nullable Object countryCode, @Nullable Object city, @Nullable Object gpsCoordinates) { L.d("[Location] setLocationLegacy, calling legacy calls to send locations"); - if (countryCode != null) { + if (isLegacyValueAllowed(countryCode)) { countryLegacy = countryCode.toString(); } - if (city != null) { + if (isLegacyValueAllowed(city)) { cityLegacy = city.toString(); } - if (gpsCoordinates != null) { + if (isLegacyValueAllowed(gpsCoordinates)) { locationLegacy = gpsCoordinates.toString(); } } + /** + * Drops the held deprecated location values that may not be sent while location tracking is off, + * so a value set before the SDK behavior settings turned location tracking off is not sent after + * they turn it on again. + */ + private void dropDisallowedLegacyValues() { + if (!isLegacyValueAllowed(countryLegacy)) { + countryLegacy = null; + } + if (!isLegacyValueAllowed(cityLegacy)) { + cityLegacy = null; + } + if (!isLegacyValueAllowed(locationLegacy)) { + locationLegacy = null; + } + } + + /** + * Whether a deprecated location value can be held and sent with the user details. While the SDK + * behavior settings disable location tracking, only the JSON null that opts out of location + * services can, as it erases a location instead of tracking one. + * + * @param value the value, or {@code null} when none is set + * @return {@code true} when the value is set and can be sent + */ + private boolean isLegacyValueAllowed(@Nullable Object value) { + if (value == null) { + return false; + } + if (JSONObject.NULL.toString().equals(value.toString()) || internalConfig.getConfigurationProvider().getLocationTrackingEnabled()) { + return true; + } + L.d("[ModuleLocation] isLegacyValueAllowed, location tracking disabled by SDK behavior settings; dropping the location value"); + return false; + } + public class Location { + /** + * The interface a call goes to: this one while its module runs, the running module's when + * this one was handed out before that started or kept from one that stopped, and + * {@code null} while the feature does not run. + * + * @param call the call, for the log line + * @return the interface, {@code null} for none + */ + private Location target(String call) { + ModuleLocation running = runningInstance(call); + return running == null ? null : running.locationInterface; + } + /** * Disable sending of location data. Erases server side saved location information */ public void disableLocation() { + Location target = target("[Location] disableLocation"); + if (target != this) { + if (target != null) { + target.disableLocation(); + } + return; + } synchronized (Countly.instance()) { L.i("[Location] Calling 'disableLocation'"); @@ -159,6 +279,13 @@ public void disableLocation() { * @param ipAddress ipAddress like "192.168.88.33" */ public void setLocation(@Nullable String countryCode, @Nullable String city, @Nullable String gpsCoordinates, @Nullable String ipAddress) { + Location target = target("[Location] setLocation"); + if (target != this) { + if (target != null) { + target.setLocation(countryCode, city, gpsCoordinates, ipAddress); + } + return; + } synchronized (Countly.instance()) { L.i("[Location] Calling 'setLocation'"); diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleRemoteConfig.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleRemoteConfig.java index 41abe3a76..32a27e68d 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleRemoteConfig.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleRemoteConfig.java @@ -1,8 +1,6 @@ package ly.count.sdk.java.internal; -import java.util.ArrayList; import java.util.Arrays; -import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Nonnull; @@ -18,7 +16,6 @@ public class ModuleRemoteConfig extends ModuleBase { // if set to true we should add 'oi=1' to our RC download call boolean autoEnrollEnabled; boolean remoteConfigValuesShouldBeCached = false; - List downloadCallbacks = new ArrayList<>(2); ModuleRemoteConfig() { } @@ -36,7 +33,6 @@ public void init(final InternalConfig config) { remoteConfigValuesShouldBeCached = config.isRemoteConfigValueCachingEnabled(); autoEnrollEnabled = config.isAutoEnrollFlagEnabled(); - downloadCallbacks.addAll(config.getRemoteConfigGlobalCallbackList()); remoteConfigInterface = new RemoteConfig(); } @@ -78,6 +74,8 @@ void updateRemoteConfigValues(@Nullable final String[] keysOnly, @Nullable final Transport transport = internalConfig.sdk.networking.getTransport(); final boolean networkingIsEnabled = internalConfig.getNetworkingEnabled(); + final String requestedAppKey = internalConfig.getServerAppKey(); + final String requestedServerUrl = internalConfig.getServerURL().toString(); internalConfig.immediateRequestGenerator.createImmediateRequestMaker().doWork(requestData, "/o/sdk?", transport, false, networkingIsEnabled, checkResponse -> { L.d("[ModuleRemoteConfig] updateRemoteConfigValues, Processing remote config received response, received response is null:[" + (checkResponse == null) + "]"); @@ -86,6 +84,12 @@ void updateRemoteConfigValues(@Nullable final String[] keysOnly, @Nullable final return; } + if (Utils.isNotEqual(requestedAppKey, internalConfig.getServerAppKey()) || !requestedServerUrl.equals(internalConfig.getServerURL().toString())) { + L.d("[ModuleRemoteConfig] updateRemoteConfigValues, the app key or the server URL changed after the request was made, ignoring its response"); + notifyDownloadCallbacks(devProvidedCallback, RequestResult.Error, "The app key or the server URL changed before the response arrived", fullUpdate, null); + return; + } + String error = null; Map newRC = downloadedValuesIntoMap(checkResponse); @@ -242,7 +246,10 @@ private void saveRCValues(@Nonnull final RemoteConfigValueStore rcvs) { internalConfig.storageProvider.setRemoteConfigValues(rcvs.values); } - private void cacheOrClearRCValuesIfNeeded() { + /** + * Clears the stored remote config values, or marks them as cached with value caching. + */ + void cacheOrClearRCValuesIfNeeded() { L.v("[ModuleRemoteConfig] cacheOrClearRCValuesIfNeeded, cache-clearing values"); RemoteConfigValueStore rcvs = getRemoteConfigValueStoreInternal(); @@ -251,14 +258,19 @@ private void cacheOrClearRCValuesIfNeeded() { } private void notifyDownloadCallbacks(final RCDownloadCallback devProvidedCallback, RequestResult requestResult, String message, boolean fullUpdate, Map downloadedValues) { - downloadCallbacks.forEach(callback -> callback.callback(requestResult, message, fullUpdate, downloadedValues)); + internalConfig.sdk.remoteConfigDownloadCallbacks.forEach(callback -> callback.callback(requestResult, message, fullUpdate, downloadedValues)); if (devProvidedCallback != null) { devProvidedCallback.callback(requestResult, message, fullUpdate, downloadedValues); } } - private void rcAutomaticDownloadTrigger(final boolean cacheClearOldValues) { + /** + * Downloads every remote config value when automatic download triggers are enabled. + * + * @param cacheClearOldValues whether the stored values are first cleared, or marked as cached with value caching + */ + void rcAutomaticDownloadTrigger(final boolean cacheClearOldValues) { if (cacheClearOldValues) { cacheOrClearRCValuesIfNeeded(); } @@ -309,6 +321,19 @@ public void stop(InternalConfig config, final boolean clear) { public class RemoteConfig { + /** + * The interface a call goes to: this one while its module runs, the running module's when + * this one was handed out before that started or kept from one that stopped, and + * {@code null} while the feature does not run. + * + * @param call the call, for the log line + * @return the interface, {@code null} for none + */ + private RemoteConfig target(String call) { + ModuleRemoteConfig running = runningInstance(call); + return running == null ? null : running.remoteConfigInterface; + } + /** * Manual remote config call that will initiate a download of all except the given remote config keys. * If no keys are provided then it will download all available RC values @@ -317,6 +342,15 @@ public class RemoteConfig { * @param callback This is called when the operation concludes */ public void downloadOmittingKeys(@Nullable String[] keysToOmit, @Nullable final RCDownloadCallback callback) { + RemoteConfig target = target("[RemoteConfig] downloadOmittingKeys"); + if (target != this) { + if (target != null) { + target.downloadOmittingKeys(keysToOmit, callback); + } else if (callback != null) { + callback.callback(RequestResult.Error, NOT_RUNNING_ERROR, keysToOmit == null || keysToOmit.length == 0, null); + } + return; + } synchronized (Countly.instance()) { L.i("[RemoteConfig] downloadOmittingKeys"); @@ -336,6 +370,15 @@ public void downloadOmittingKeys(@Nullable String[] keysToOmit, @Nullable final * @param callback This is called when the operation concludes */ public void downloadSpecificKeys(@Nullable String[] keysToInclude, @Nullable final RCDownloadCallback callback) { + RemoteConfig target = target("[RemoteConfig] downloadSpecificKeys"); + if (target != this) { + if (target != null) { + target.downloadSpecificKeys(keysToInclude, callback); + } else if (callback != null) { + callback.callback(RequestResult.Error, NOT_RUNNING_ERROR, keysToInclude == null || keysToInclude.length == 0, null); + } + return; + } synchronized (Countly.instance()) { L.i("[RemoteConfig] downloadSpecificKeys"); @@ -353,6 +396,15 @@ public void downloadSpecificKeys(@Nullable String[] keysToInclude, @Nullable fin * @param callback This is called when the operation concludes */ public void downloadAllKeys(@Nullable RCDownloadCallback callback) { + RemoteConfig target = target("[RemoteConfig] downloadAllKeys"); + if (target != this) { + if (target != null) { + target.downloadAllKeys(callback); + } else if (callback != null) { + callback.callback(RequestResult.Error, NOT_RUNNING_ERROR, true, null); + } + return; + } synchronized (Countly.instance()) { L.i("[RemoteConfig] downloadAllKeys"); updateRemoteConfigValues(null, null, callback); @@ -365,6 +417,13 @@ public void downloadAllKeys(@Nullable RCDownloadCallback callback) { * @return The available RC values */ public @Nonnull Map getValues() { + RemoteConfig target = target("[RemoteConfig] getValues"); + if (target != this) { + if (target == null) { + return new ConcurrentHashMap<>(); + } + return target.getValues(); + } synchronized (Countly.instance()) { L.i("[RemoteConfig] getValues"); return getRemoteConfigValueStoreInternal().getAllValues(); @@ -377,6 +436,13 @@ public void downloadAllKeys(@Nullable RCDownloadCallback callback) { * @return The available RC values */ public @Nonnull Map getAllValuesAndEnroll() { + RemoteConfig target = target("[RemoteConfig] getAllValuesAndEnroll"); + if (target != this) { + if (target == null) { + return new ConcurrentHashMap<>(); + } + return target.getAllValuesAndEnroll(); + } synchronized (Countly.instance()) { L.i("[RemoteConfig] getAllValuesAndEnroll"); Map values = getRemoteConfigValueStoreInternal().getAllValues(); @@ -399,6 +465,13 @@ public void downloadAllKeys(@Nullable RCDownloadCallback callback) { * @return The returned value. If no value existed for the key then the inner object (value) will be returned as "null" */ public @Nonnull RCData getValue(final @Nullable String key) { + RemoteConfig target = target("[RemoteConfig] getValue"); + if (target != this) { + if (target == null) { + return new RCData(null, true); + } + return target.getValue(key); + } synchronized (Countly.instance()) { L.i("[RemoteConfig] getValue, key:[" + key + "]"); @@ -418,6 +491,13 @@ public void downloadAllKeys(@Nullable RCDownloadCallback callback) { * @return The returned value. If no value existed for the key then the inner object will be returned as "null" */ public @Nonnull RCData getValueAndEnroll(@Nullable String key) { + RemoteConfig target = target("[RemoteConfig] getValueAndEnroll"); + if (target != this) { + if (target == null) { + return new RCData(null, true); + } + return target.getValueAndEnroll(key); + } synchronized (Countly.instance()) { L.i("[RemoteConfig] getValueAndEnroll, key:[" + key + "]"); @@ -443,6 +523,13 @@ public void downloadAllKeys(@Nullable RCDownloadCallback callback) { * @param keys - String array of keys (parameters) */ public void enrollIntoABTestsForKeys(@Nullable String[] keys) { + RemoteConfig target = target("[RemoteConfig] enrollIntoABTestsForKeys"); + if (target != this) { + if (target != null) { + target.enrollIntoABTestsForKeys(keys); + } + return; + } synchronized (Countly.instance()) { L.i("[RemoteConfig] enrollIntoABTestsForKeys"); if (keys == null || keys.length == 0) { @@ -459,6 +546,13 @@ public void enrollIntoABTestsForKeys(@Nullable String[] keys) { * @param keys - String array of keys (parameters) */ public void exitABTestsForKeys(@Nullable String[] keys) { + RemoteConfig target = target("[RemoteConfig] exitABTestsForKeys"); + if (target != this) { + if (target != null) { + target.exitABTestsForKeys(keys); + } + return; + } synchronized (Countly.instance()) { L.i("[RemoteConfig] exitABTestsForKeys"); if (keys == null) { @@ -469,18 +563,23 @@ public void exitABTestsForKeys(@Nullable String[] keys) { } /** - * Register a global callback for when download operations have finished + * Register a global callback for when download operations have finished. It is kept while + * remote config does not run, as before its consent is given, and called once it does. * * @param callback The callback that should be added */ public void registerDownloadCallback(@Nullable final RCDownloadCallback callback) { synchronized (Countly.instance()) { - L.i("[RemoteConfig] registerDownloadCallback"); + SDKCore core = SDKCore.instance; + if (core == null) { + return; + } + core.L.i("[RemoteConfig] registerDownloadCallback"); if (callback == null) { - L.w("[RemoteConfig] registerDownloadCallback, passed callback is null"); + core.L.w("[RemoteConfig] registerDownloadCallback, passed callback is null"); return; } - downloadCallbacks.add(callback); + core.remoteConfigDownloadCallbacks.add(callback); } } @@ -491,12 +590,16 @@ public void registerDownloadCallback(@Nullable final RCDownloadCallback callback */ public void removeDownloadCallback(@Nullable final RCDownloadCallback callback) { synchronized (Countly.instance()) { - L.i("[RemoteConfig] removeDownloadCallback"); + SDKCore core = SDKCore.instance; + if (core == null) { + return; + } + core.L.i("[RemoteConfig] removeDownloadCallback"); if (callback == null) { - L.w("[RemoteConfig] removeDownloadCallback, passed callback is null"); + core.L.w("[RemoteConfig] removeDownloadCallback, passed callback is null"); return; } - downloadCallbacks.remove(callback); + core.remoteConfigDownloadCallbacks.remove(callback); } } @@ -504,6 +607,13 @@ public void removeDownloadCallback(@Nullable final RCDownloadCallback callback) * Clear all stored remote config values. */ public void clearAll() { + RemoteConfig target = target("[RemoteConfig] clearAll"); + if (target != this) { + if (target != null) { + target.clearAll(); + } + return; + } synchronized (Countly.instance()) { L.i("[RemoteConfig] clearAll"); clearValueStoreInternal(); 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 5ea633c1f..4a15604e8 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 @@ -1,7 +1,17 @@ package ly.count.sdk.java.internal; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import java.util.Map; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; /** * Centralized place for all requests construction & handling. @@ -9,6 +19,9 @@ public class ModuleRequests extends ModuleBase { + //how long queueing a log batch waits for the storage, which never answers once it is shut down + static final long SDK_LOGS_STORE_TIMEOUT_MS = 10_000L; + private static Params metrics; public interface ParamsInjector { @@ -60,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) { @@ -99,6 +130,11 @@ public static Future location(InternalConfig config, double latitude, d return null; } + if (!config.getConfigurationProvider().getLocationTrackingEnabled()) { + config.getLogger().d("[ModuleRequests] location, location tracking is disabled by the SDK behavior settings, the location is not sent"); + return null; + } + Request request = sessionRequest(config, null, null, null); request.params.add("location", latitude + "," + longitude); return pushAsync(config, request); @@ -113,10 +149,6 @@ public static Request nonSessionRequest(InternalConfig config) { return sessionRequest(config, null, null, null); } - public static Request nonSessionRequest(InternalConfig config, Long timestamp) { - return new Request(timestamp); - } - public static void injectParams(InternalConfig config, ParamsInjector injector) { SessionImpl session = SDKCore.instance.getSession(); if (session == null) { @@ -195,21 +227,39 @@ public static Future pushAsync(InternalConfig config, Request request) } /** - * Common store-request logic: store & send a ping to the service. + * Common store-request logic: store & send a ping to the service. While the SDK behavior + * settings set the request queue size, storing a request drops the oldest ones the queue holds + * over that size. While the request carries a batch of gathered log lines, the storage thread is + * marked as doing their transport work until the callback returned, so nothing logged about + * queueing the batch is gathered. * * @param config InternalConfig to run in * @param request Request to store * @param noControl do not check empty validity of the request - * @param callback Callback (nullable) to call when storing is done, called in {@link Storage} {@link Thread} + * @param callback Callback (nullable) to call when storing is done, called in {@link Storage} {@link Thread}, + * or on the calling thread with {@code false} when the request is not stored * @return {@link Future} which resolves to {@code} true if stored successfully, false otherwise */ public static Future pushAsync(final InternalConfig config, final Request request, final boolean noControl, final Tasks.Callback callback) { config.getLogger().d("New request " + request.storageId() + ": " + request); + if (!config.getConfigurationProvider().getTrackingEnabled()) { + config.getLogger().w("[ModuleRequests] pushAsync, tracking disabled by SDK behavior settings; dropping request"); + config.getLogger().recordLogCode("w505"); + if (callback != null) { + try { + callback.call(false); + } catch (Exception e) { + config.getLogger().e("[ModuleRequests] Exception in a callback " + e); + } + } + return null; + } + if (!noControl && request.isEmpty()) { if (callback != null) { try { - callback.call(null); + callback.call(false); } catch (Exception e) { config.getLogger().e("[ModuleRequests] Exception in a callback " + e); } @@ -220,11 +270,190 @@ public static Future pushAsync(final InternalConfig config, final Reque addRequiredTimeParametersToParams(request.params); addRequiredParametersToParams(config, request.params); + final boolean uploadsGatheredLogs = request.params.has(Log.keySdkLogs); return Storage.pushAsync(config, request, param -> { - SDKCore.instance.onRequest(config, request); - if (callback != null) { - callback.call(param); + Log logger = config.getLogger(); + boolean markedBefore = logger.isOwnTransportWork(); + logger.setOwnTransportWork(markedBefore || uploadsGatheredLogs); + try { + if (Boolean.TRUE.equals(param)) { + dropOldestRequestsOverQueueLimit(config); + } + SDKCore.instance.onRequest(config, request); + if (callback != null) { + callback.call(param); + } + } finally { + logger.setOwnTransportWork(markedBefore); } }); } + + /** + * Stores a request as it is, without the checks of {@link #pushAsync(InternalConfig, Request, boolean, Tasks.Callback)}, + * then drops the oldest requests the queue holds over the request queue size of the SDK behavior + * settings. Waits until both are done. + * + * @param config configuration of the running SDK + * @param request the request, with every parameter it is sent with + * @return whether the request was stored + */ + static boolean pushWithinQueueLimit(@Nonnull final InternalConfig config, @Nonnull final Request request) { + try { + return Boolean.TRUE.equals(Storage.pushAsync(config, request, stored -> { + if (Boolean.TRUE.equals(stored)) { + dropOldestRequestsOverQueueLimit(config); + } + }).get()); + } catch (InterruptedException | ExecutionException e) { + config.getLogger().e("[ModuleRequests] pushWithinQueueLimit, failed to store request " + request.storageId() + ", [" + e + "]"); + return false; + } + } + + /** + * Queues one batch of gathered SDK log lines as a request of its own, the batch as its + * {@code sdk_logs} parameter next to the required ones, through the checks of + * {@link #pushAsync(InternalConfig, Request)}, and waits until it is stored. When the wait times + * out or is interrupted, the store is cancelled, as a store left queued would still write the + * request after its lines were kept for another batch. + * + * @param config configuration of the running SDK + * @param payload the batch, as JSON text + * @return the storage ID of the stored request, {@code null} when it was refused, as while + * tracking is off, could not be stored or its store was cancelled + */ + @Nullable + static Long pushSdkLogs(@Nonnull InternalConfig config, @Nonnull String payload) { + Request request = nonSessionRequest(config); + request.params.add(Log.keySdkLogs, payload); + Future stored = null; + boolean queued; + try { + stored = pushAsync(config, request); + queued = stored != null && Boolean.TRUE.equals(stored.get(SDK_LOGS_STORE_TIMEOUT_MS, TimeUnit.MILLISECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + config.getLogger().w("[ModuleRequests] pushSdkLogs, interrupted while storing request " + request.storageId()); + queued = !cancelStore(config, request, stored); + } catch (TimeoutException e) { + config.getLogger().w("[ModuleRequests] pushSdkLogs, storing request " + request.storageId() + " took over [" + SDK_LOGS_STORE_TIMEOUT_MS + "] ms"); + queued = !cancelStore(config, request, stored); + } catch (ExecutionException | RuntimeException e) { + config.getLogger().w("[ModuleRequests] pushSdkLogs, failed to store request " + request.storageId() + ", [" + e + "]"); + queued = false; + } + return queued ? request.storageId() : null; + } + + /** + * Cancels the store of a log batch whose caller stopped waiting for it. A store that cannot be + * cancelled has already completed, so its batch counts as queued. + * + * @param config configuration of the running SDK + * @param request the request carrying the batch + * @param stored the store + * @return whether the store was cancelled, so its batch is not queued + */ + private static boolean cancelStore(@Nonnull InternalConfig config, @Nonnull Request request, @Nonnull Future stored) { + if (stored.cancel(false)) { + config.getLogger().w("[ModuleRequests] cancelStore, cancelled storing request " + request.storageId() + ", its batch is not queued"); + return true; + } + + config.getLogger().w("[ModuleRequests] cancelStore, storing request " + request.storageId() + " completed before it could be cancelled, its batch counts as queued"); + return false; + } + + /** + * Drops the oldest stored requests while the queue holds more than the request queue size of the + * SDK behavior settings. Without a size from the settings the queue has no limit. Must run on the + * storage thread, as it works on the stored files directly. The files are removed unread, so + * their owners are not told; the journey triggers they carried are settled instead. + * + * @param config configuration of the running SDK + * @return how many requests were dropped + */ + static int dropOldestRequestsOverQueueLimit(@Nonnull InternalConfig config) { + ConfigurationProvider configProvider = config.getConfigurationProvider(); + if (!configProvider.isRequestQueueMaxSizeFromBehaviorSettings()) { + return 0; + } + + List droppedIds = new ArrayList<>(); + try { + int maxSize = configProvider.getRequestQueueMaxSize(); + List requestIds = config.sdk.sdkStorage.storableList(config, Request.getStoragePrefix(), 0); + int overflow = requestIds.size() - maxSize; + if (overflow <= 0) { + return 0; + } + + Collections.sort(requestIds); + for (int i = 0; i < overflow; i++) { + Long requestId = requestIds.get(i); + if (Boolean.TRUE.equals(config.sdk.sdkStorage.storableRemove(config, new Request(requestId)))) { + droppedIds.add(requestId); + } + } + + config.getLogger().w("[ModuleRequests] dropOldestRequestsOverQueueLimit, the request queue went over its size of [" + maxSize + "] set by the SDK behavior settings, dropped the [" + droppedIds.size() + "] oldest requests"); + config.getLogger().recordLogCode("w310", droppedIds.size()); + } catch (Exception e) { + config.getLogger().e("[ModuleRequests] dropOldestRequestsOverQueueLimit, failed to keep the request queue within its size, [" + e + "]"); + } + + return droppedIds.size(); + } + + /** + * Sets the current app key on every queued request that carries another one, or none, as one + * storage task. The checksum is computed when a request is sent, so it matches the new key. + * + * @param config configuration of the running SDK + * @return how many requests were changed + */ + static int replaceAppKeysInQueue(@Nonnull InternalConfig config) { + final String appKey = config.getServerAppKey(); + final AtomicInteger replaced = new AtomicInteger(); + Storage.transform(config, Request.getStoragePrefix(), (id, data) -> { + Request request = new Request(id); + if (!request.restore(data, config.getLogger()) || appKey.equals(request.params.get("app_key"))) { + return null; + } + request.params.remove("app_key"); + request.params.add("app_key", appKey); + replaced.incrementAndGet(); + return request.store(config.getLogger()); + }); + return replaced.get(); + } + + /** + * Removes the queued requests a filter selects, unsent, in one storage task, so no other storage + * work interleaves. A request being sent finishes, then the network removes it by its storage + * ID, so no other request is lost. Settles the journey triggers the removed requests carried. + * + * @param config configuration of the running SDK + * @param filter selects a request to remove, {@code null} to remove every request without reading it + * @return how many requests were removed + */ + static int removeQueuedRequests(@Nonnull InternalConfig config, @Nullable Predicate filter) { + List removedIds = Storage.runAndWait(config, () -> { + List removed = new ArrayList<>(); + for (Long id : config.sdk.sdkStorage.storableList(config, Request.getStoragePrefix(), 0)) { + Request request = new Request(id); + boolean selected = filter == null || (Boolean.TRUE.equals(config.sdk.sdkStorage.storableRead(config, request)) && filter.test(request)); + if (selected && Boolean.TRUE.equals(config.sdk.sdkStorage.storableRemove(config, request))) { + removed.add(id); + } + } + return removed; + }); + if (removedIds == null) { + return 0; + } + + return removedIds.size(); + } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleSessions.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleSessions.java index 58977e5c1..be3139ff0 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleSessions.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleSessions.java @@ -39,9 +39,15 @@ public void initFinished(final InternalConfig config) { @Override protected void onTimer() { - if (!internalConfig.isBackendModeEnabled() && isActive() && getSession() != null) { + ConfigurationProvider configProvider = internalConfig.getConfigurationProvider(); + if (!configProvider.getTrackingEnabled() || !configProvider.getSessionTrackingEnabled()) { + L.d("[ModuleSessions] onTimer, session tracking disabled by SDK behavior settings; skipping update"); + return; + } + SessionImpl running = getSession(); + if (!internalConfig.isBackendModeEnabled() && isActive() && running != null && running.isActive()) { L.i("[ModuleSessions] onTimer, updating session"); - getSession().update(); + running.updateAutomatically(); } } @@ -68,11 +74,11 @@ public void deviceIdChanged(String oldDeviceId, boolean withMerge) { L.d("[ModuleSessions] deviceIdChanged, " + deviceId + ", old " + oldDeviceId); if (!withMerge && session != null && session.isActive()) { L.d("[ModuleSessions] deviceIdChanged, Ending session because device id was unset from [" + oldDeviceId + "]"); - session.end(null, null, oldDeviceId); + session.endAutomatically(null, null, oldDeviceId); } if (deviceId != null && oldDeviceId != null && (session == null || !session.isActive()) && !withMerge) { - session(internalConfig, null).begin(); + session(internalConfig, null).beginAutomatically(); } } 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 41aeb5da0..57856aae0 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 @@ -1,10 +1,18 @@ package ly.count.sdk.java.internal; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Set; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import ly.count.sdk.java.Countly; import ly.count.sdk.java.PredefinedUserPropertyKeys; import ly.count.sdk.java.User; @@ -15,6 +23,14 @@ public class ModuleUserProfile extends ModuleBase { static final String CUSTOM_KEY = "custom"; boolean isSynced = true; static final String PICTURE_BYTES = "[CLY]_picture_bytes"; + /** + * The keys of {@link PredefinedUserPropertyKeys}, which neither the user property filter nor the + * user property cache limit of the SDK behavior settings apply to. + */ + static final Set PREDEFINED_KEYS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + PredefinedUserPropertyKeys.NAME, PredefinedUserPropertyKeys.USERNAME, PredefinedUserPropertyKeys.EMAIL, + PredefinedUserPropertyKeys.ORGANIZATION, PredefinedUserPropertyKeys.PHONE, PredefinedUserPropertyKeys.PICTURE, + PredefinedUserPropertyKeys.PICTURE_PATH, PredefinedUserPropertyKeys.GENDER, PredefinedUserPropertyKeys.BIRTH_YEAR))); UserProfile userProfileInterface; private final Map sets; private final List ops; @@ -68,7 +84,7 @@ enum Op { } ModuleUserProfile() { - sets = new HashMap<>(); // keys should be nullable + sets = new LinkedHashMap<>(); // keys should be nullable, insertion order decides what the cache limit drops ops = new ArrayList<>(); } @@ -91,12 +107,23 @@ private Object optString(String key, Object value) { /** * Transforming changes in "sets" into a json contained in "changes" + *

+ * The SDK internal limits of the SDK behavior settings in effect apply here: string values of + * predefined properties, the picture excepted, are cut to the value size limit, and custom + * properties get the key length, value size and segmentation entry limits, the entry limit + * counting sets only, never modifications. * * @param changes JSONObject to store changes * @param params Params to store changes * @throws JSONException if something goes wrong */ void perform(JSONObject changes, Params params) throws JSONException { + ConfigurationProvider limits = internalConfig.getConfigurationProvider(); + int maxValueSize = limits.getMaxValueSize(); + Map customSets = supportedCustomSets(); + Map limitedCustomSets = UtilsInternalLimits.applySegmentationLimits(customSets, limits, L, "[ModuleUserProfile] perform"); + boolean customSetsLimited = !customSets.equals(limitedCustomSets); + for (String key : sets.keySet()) { Object value = sets.get(key); switch (key) { @@ -105,7 +132,7 @@ void perform(JSONObject changes, Params params) throws JSONException { case PredefinedUserPropertyKeys.EMAIL: case PredefinedUserPropertyKeys.ORGANIZATION: case PredefinedUserPropertyKeys.PHONE: - changes.put(key, optString(key, value)); + changes.put(key, optString(key, UtilsInternalLimits.truncateIfString(value, maxValueSize, L, "[ModuleUserProfile] perform"))); break; case PredefinedUserPropertyKeys.PICTURE: if (value == null) { @@ -137,6 +164,7 @@ void perform(JSONObject changes, Params params) throws JSONException { } break; case PredefinedUserPropertyKeys.GENDER: + value = UtilsInternalLimits.truncateIfString(value, maxValueSize, L, "[ModuleUserProfile] perform"); if (value == null || value instanceof User.Gender) { changes.put(PredefinedUserPropertyKeys.GENDER, value == null ? JSONObject.NULL : value.toString()); } else if (value instanceof String) { @@ -151,6 +179,7 @@ void perform(JSONObject changes, Params params) throws JSONException { } break; case PredefinedUserPropertyKeys.BIRTH_YEAR: + value = UtilsInternalLimits.truncateIfString(value, maxValueSize, L, "[ModuleUserProfile] perform"); if (value == null || value instanceof Integer) { changes.put(PredefinedUserPropertyKeys.BIRTH_YEAR, value == null ? JSONObject.NULL : value); } else if (value instanceof String) { @@ -164,25 +193,69 @@ void perform(JSONObject changes, Params params) throws JSONException { } break; default: - performCustomUpdate(key, value, changes); + if (!customSetsLimited || !customSets.containsKey(key)) { + performCustomUpdate(key, value, changes); + } break; } } - applyOps(changes); + if (customSetsLimited) { + for (Map.Entry entry : limitedCustomSets.entrySet()) { + performCustomUpdate(entry.getKey(), entry.getValue(), changes); + } + } + + applyOps(changes, limits); + } + + /** + * The pending sets of custom properties that {@link #performCustomUpdate} sends, the ones with a + * value of a supported type, in the order they were first set. + * + * @return the custom properties to send + */ + private Map supportedCustomSets() { + Map customSets = new LinkedHashMap<>(); + for (Map.Entry entry : sets.entrySet()) { + if (!isPredefinedKey(entry.getKey()) && isSupportedCustomValue(entry.getValue())) { + customSets.put(entry.getKey(), entry.getValue()); + } + } + return customSets; + } + + /** + * Whether a custom property can be sent with a value, which has to be of a supported type. + * + * @param value the value + * @return {@code true} for a supported type, {@code false} for any other type and for {@code null} + */ + private static boolean isSupportedCustomValue(@Nullable Object value) { + return value instanceof String || value instanceof Integer || value instanceof Float || value instanceof Double || value instanceof Boolean || value instanceof Object[]; } - private void applyOps(final JSONObject changes) throws JSONException { + /** + * Applies the pending modifications to the custom properties of the changes, with their keys cut + * to the key length limit and their string values cut to the value size limit. + * + * @param changes the changes to send + * @param limits the SDK behavior settings in effect + * @throws JSONException if a modification cannot be written + */ + private void applyOps(final JSONObject changes, @Nonnull ConfigurationProvider limits) throws JSONException { if (!ops.isEmpty() && !changes.has(CUSTOM_KEY)) { changes.put(CUSTOM_KEY, new JSONObject()); } for (OpParams opParam : ops) { - opParam.op.valueTransformer.apply(changes.getJSONObject(CUSTOM_KEY), opParam.key, opParam.value); + String key = UtilsInternalLimits.truncateKey(opParam.key, limits.getMaxKeyLength(), L, "[ModuleUserProfile] applyOps"); + Object value = UtilsInternalLimits.truncateIfString(opParam.value, limits.getMaxValueSize(), L, "[ModuleUserProfile] applyOps"); + opParam.op.valueTransformer.apply(changes.getJSONObject(CUSTOM_KEY), key, value); } } private void performCustomUpdate(final String key, final Object value, final JSONObject changes) throws JSONException { - if (value == null || value instanceof String || value instanceof Integer || value instanceof Float || value instanceof Double || value instanceof Boolean || value instanceof Object[]) { + if (value == null || isSupportedCustomValue(value)) { if (!changes.has(CUSTOM_KEY)) { changes.put(CUSTOM_KEY, new JSONObject()); } @@ -234,7 +307,14 @@ private void modifyCustomData(String key, Object value, Op mod) { L.w("[ModuleUserProfile] modifyCustomData, value is null, thus nothing to modify"); return; } + + if (!UtilsListingFilters.applyUserPropertyFilter(key, internalConfig.getConfigurationProvider())) { + L.w("[ModuleUserProfile] modifyCustomData, key [" + key + "] is filtered out by the user property filter of the SDK behavior settings, ignoring the modification"); + return; + } + ops.add(new OpParams(key, value, mod)); + applyCacheLimitToModifications(); isSynced = false; } @@ -250,14 +330,122 @@ protected void setPropertiesInternal(@Nonnull Map data) { return; } - sets.putAll(data); + ConfigurationProvider configProvider = internalConfig.getConfigurationProvider(); + Map accepted = new LinkedHashMap<>(); + for (Map.Entry entry : data.entrySet()) { + String key = entry.getKey(); + if (!isPredefinedKey(key) && !UtilsListingFilters.applyUserPropertyFilter(key, configProvider)) { + L.w("[ModuleUserProfile] setPropertiesInternal, key [" + key + "] is filtered out by the user property filter of the SDK behavior settings, it will not be set"); + continue; + } + accepted.put(key, entry.getValue()); + } + + if (accepted.isEmpty()) { + return; + } + + sets.putAll(accepted); + applyCacheLimitToCustomProperties(); isSynced = false; } + /** + * Whether a user property key is one of {@link PredefinedUserPropertyKeys}. + * + * @param key the key + * @return {@code true} for a predefined key + */ + private static boolean isPredefinedKey(@Nullable String key) { + return PREDEFINED_KEYS.contains(key); + } + + /** + * Keeps the pending custom properties within the user property cache limit of the SDK behavior + * settings by dropping the oldest ones. Predefined properties are not counted. + */ + private void applyCacheLimitToCustomProperties() { + int cacheLimit = internalConfig.getConfigurationProvider().getUserPropertyCacheLimit(); + if (sets.size() <= cacheLimit) { + return; + } + + int customCount = 0; + for (String key : sets.keySet()) { + if (!isPredefinedKey(key)) { + customCount++; + } + } + + int overflow = customCount - cacheLimit; + if (overflow <= 0) { + return; + } + + List dropped = new ArrayList<>(overflow); + Iterator keys = sets.keySet().iterator(); + while (keys.hasNext() && dropped.size() < overflow) { + String key = keys.next(); + if (!isPredefinedKey(key)) { + keys.remove(); + dropped.add(key); + } + } + + L.w("[ModuleUserProfile] applyCacheLimitToCustomProperties, [" + customCount + "] custom user properties are pending, over the cache limit of [" + cacheLimit + "] set by the SDK behavior settings, dropped the oldest ones: " + dropped); + } + + /** + * Keeps the keys with pending modifications within the user property cache limit of the SDK + * behavior settings by dropping every modification of the oldest keys. + */ + private void applyCacheLimitToModifications() { + int cacheLimit = internalConfig.getConfigurationProvider().getUserPropertyCacheLimit(); + if (ops.size() <= cacheLimit) { + return; + } + + Set modifiedKeys = new LinkedHashSet<>(); + for (OpParams op : ops) { + modifiedKeys.add(op.key); + } + + int overflow = modifiedKeys.size() - cacheLimit; + if (overflow <= 0) { + return; + } + + Set dropped = new LinkedHashSet<>(); + Iterator keys = modifiedKeys.iterator(); + while (dropped.size() < overflow) { + dropped.add(keys.next()); + } + ops.removeIf(op -> dropped.contains(op.key)); + + L.w("[ModuleUserProfile] applyCacheLimitToModifications, [" + modifiedKeys.size() + "] custom user properties have pending modifications, over the cache limit of [" + cacheLimit + "] set by the SDK behavior settings, dropped the modifications of the oldest ones: " + dropped); + } + + /** + * Sends the user properties set so far when the SDK sends them automatically, which it does + * before every session and event request. + * + * @param config the configuration of the running SDK + */ + static void saveIfSentAutomatically(@Nonnull InternalConfig config) { + if (!config.isAutoSendUserProperties()) { + return; + } + ModuleUserProfile module = config.sdk.module(ModuleUserProfile.class); + if (module != null) { + module.saveInternal(); + } + } + protected void saveInternal() { Params generatedParams = prepareRequestParamsForUserProfile(); - if (internalConfig.sdk.location() != null) { - internalConfig.sdk.module(ModuleLocation.class).saveLocationToParamsLegacy(generatedParams); + ModuleLocation location = internalConfig.sdk.runningModule(CoreFeature.Location, ModuleLocation.class); + if (location != null) { + location.saveLocationToParamsLegacy(generatedParams); } L.d("[ModuleUserProfile] saveInternal, generated params [" + generatedParams + "]"); @@ -266,14 +454,50 @@ protected void saveInternal() { return; } - if (internalConfig.isAutoSendUserProperties() && internalConfig.sdk.events() != null) { - internalConfig.sdk.module(ModuleEvents.class).checkEventQueueToSend(true); + ModuleEvents events = internalConfig.sdk.runningModule(CoreFeature.Events, ModuleEvents.class); + if (internalConfig.isAutoSendUserProperties() && events != null) { + 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"); @@ -316,12 +540,32 @@ public void deviceIdChanged(String oldDeviceId, boolean withMerge) { public class UserProfile { + /** + * The interface a call goes to: this one while its module runs, the running module's when + * this one was handed out before that started or kept from one that stopped, and + * {@code null} while the feature does not run. + * + * @param call the call, for the log line + * @return the interface, {@code null} for none + */ + private UserProfile target(String call) { + ModuleUserProfile running = runningInstance(call); + return running == null ? null : running.userProfileInterface; + } + /** * Increment custom property value by 1. * * @param key String with property name to increment */ public void increment(String key) { + UserProfile target = target("[UserProfile] increment"); + if (target != this) { + if (target != null) { + target.increment(key); + } + return; + } synchronized (Countly.instance()) { modifyCustomData(key, 1, Op.INC); } @@ -334,6 +578,13 @@ public void increment(String key) { * @param value int value by which to increment */ public void incrementBy(String key, int value) { + UserProfile target = target("[UserProfile] incrementBy"); + if (target != this) { + if (target != null) { + target.incrementBy(key, value); + } + return; + } synchronized (Countly.instance()) { modifyCustomData(key, value, Op.INC); } @@ -346,6 +597,13 @@ public void incrementBy(String key, int value) { * @param value int value by which to multiply */ public void multiply(String key, double value) { + UserProfile target = target("[UserProfile] multiply"); + if (target != this) { + if (target != null) { + target.multiply(key, value); + } + return; + } synchronized (Countly.instance()) { modifyCustomData(key, value, Op.MUL); } @@ -358,6 +616,13 @@ public void multiply(String key, double value) { * @param value int value to check for max */ public void saveMax(String key, double value) { + UserProfile target = target("[UserProfile] saveMax"); + if (target != this) { + if (target != null) { + target.saveMax(key, value); + } + return; + } synchronized (Countly.instance()) { modifyCustomData(key, value, Op.MAX); } @@ -370,6 +635,13 @@ public void saveMax(String key, double value) { * @param value int value to check for min */ public void saveMin(String key, double value) { + UserProfile target = target("[UserProfile] saveMin"); + if (target != this) { + if (target != null) { + target.saveMin(key, value); + } + return; + } synchronized (Countly.instance()) { modifyCustomData(key, value, Op.MIN); } @@ -382,6 +654,13 @@ public void saveMin(String key, double value) { * @param value String value to set */ public void setOnce(String key, Object value) { + UserProfile target = target("[UserProfile] setOnce"); + if (target != this) { + if (target != null) { + target.setOnce(key, value); + } + return; + } synchronized (Countly.instance()) { modifyCustomData(key, value, Op.SET_ONCE); } @@ -395,6 +674,13 @@ public void setOnce(String key, Object value) { * @param value String with value to add to array */ public void push(String key, Object value) { + UserProfile target = target("[UserProfile] push"); + if (target != this) { + if (target != null) { + target.push(key, value); + } + return; + } synchronized (Countly.instance()) { modifyCustomData(key, value, Op.PUSH); } @@ -408,6 +694,13 @@ public void push(String key, Object value) { * @param value String with value to add to array */ public void pushUnique(String key, Object value) { + UserProfile target = target("[UserProfile] pushUnique"); + if (target != this) { + if (target != null) { + target.pushUnique(key, value); + } + return; + } synchronized (Countly.instance()) { modifyCustomData(key, value, Op.PUSH_UNIQUE); } @@ -421,6 +714,13 @@ public void pushUnique(String key, Object value) { * @param value String with value to remove from array */ public void pull(String key, Object value) { + UserProfile target = target("[UserProfile] pull"); + if (target != this) { + if (target != null) { + target.pull(key, value); + } + return; + } synchronized (Countly.instance()) { modifyCustomData(key, value, Op.PULL); } @@ -433,6 +733,13 @@ public void pull(String key, Object value) { * @param value the value for the user property to be set. The value should be the allowed data type. */ public void setProperty(String key, Object value) { + UserProfile target = target("[UserProfile] setProperty"); + if (target != this) { + if (target != null) { + target.setProperty(key, value); + } + return; + } synchronized (Countly.instance()) { L.i("[UserProfile] Calling 'setProperty'"); @@ -450,6 +757,13 @@ public void setProperty(String key, Object value) { * @param data Map of user properties to set */ public void setProperties(Map data) { + UserProfile target = target("[UserProfile] setProperties"); + if (target != this) { + if (target != null) { + target.setProperties(data); + } + return; + } synchronized (Countly.instance()) { L.i("[UserProfile] Calling 'setProperties'"); @@ -465,6 +779,13 @@ public void setProperties(Map data) { * Send provided values to server */ public void save() { + UserProfile target = target("[UserProfile] save"); + if (target != this) { + if (target != null) { + target.save(); + } + return; + } synchronized (Countly.instance()) { L.i("[UserProfile] Calling 'save'"); saveInternal(); @@ -475,6 +796,13 @@ public void save() { * Clear queued operations / modifications */ public void clear() { + UserProfile target = target("[UserProfile] clear"); + if (target != this) { + if (target != null) { + target.clear(); + } + return; + } synchronized (Countly.instance()) { L.i("[UserProfile] Calling 'clear'"); 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 dd176c3ee..ffddccfec 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 @@ -61,6 +61,9 @@ public void deviceIdChanged(String oldDeviceId, boolean withMerge) { @Override public void stop(InternalConfig config, boolean clear) { + if (config.viewIdProvider == this) { + config.viewIdProvider = SDKCore.NO_VIEW_IDS; + } viewsInterface = null; viewDataMap.clear(); if (globalViewSegmentation != null) { @@ -106,6 +109,7 @@ public void updateGlobalViewSegmentationInternal(@Nonnull Map se } private Map createViewEventSegmentation(@Nonnull ViewData vd, boolean firstView, boolean visit, Map customViewSegmentation) { + ConfigurationProvider limits = internalConfig.getConfigurationProvider(); Map viewSegmentation = new ConcurrentHashMap<>(); viewSegmentation.putAll(globalViewSegmentation); viewSegmentation.putAll(vd.viewSegmentation); @@ -114,7 +118,9 @@ private Map createViewEventSegmentation(@Nonnull ViewData vd, bo viewSegmentation.putAll(customViewSegmentation); } - viewSegmentation.put(KEY_NAME, vd.viewName); + viewSegmentation = applyInternalLimits(viewSegmentation, limits); + + viewSegmentation.put(KEY_NAME, UtilsInternalLimits.truncateKey(vd.viewName, limits.getMaxKeyLength(), L, "[ModuleViews] createViewEventSegmentation")); if (visit) { viewSegmentation.put(KEY_VISIT, KEY_VISIT_VALUE); } @@ -125,6 +131,30 @@ private Map createViewEventSegmentation(@Nonnull ViewData vd, bo return viewSegmentation; } + /** + * Applies the key length, value size and segmentation entry limits of the SDK behavior settings + * to the segmentation of a view event, before the SDK adds its own keys, which are neither cut + * nor counted. A key cut to one of the reserved keys is removed, and entries of unsupported + * types are removed before the entry limit counts, so they take no place under it. + * + * @param viewSegmentation the merged segmentation, which this module owns and may change + * @param limits the settings in effect + * @return the segmentation within the limits + */ + private Map applyInternalLimits(@Nonnull Map viewSegmentation, @Nonnull ConfigurationProvider limits) { + Map truncated = UtilsInternalLimits.truncateSegmentationKeysAndValues(viewSegmentation, limits.getMaxKeyLength(), limits.getMaxValueSize(), L, "[ModuleViews] createViewEventSegmentation"); + for (String reservedKey : reservedSegmentationKeysViews) { + if (truncated.remove(reservedKey) != null) { + L.w("[ModuleViews] createViewEventSegmentation, a key truncated to the reserved key [" + reservedKey + "] is removed"); + } + } + + if (truncated.size() > limits.getMaxSegmentationValues()) { + Utils.removeInvalidDataFromSegments(truncated, L); + } + return UtilsInternalLimits.limitSegmentationEntries(truncated, limits.getMaxSegmentationValues(), L, "[ModuleViews] createViewEventSegmentation"); + } + private void autoCloseRequiredViews(boolean closeAllViews, Map customViewSegmentation) { L.d("[ModuleViews] autoCloseRequiredViews"); List viewsToRemove = new ArrayList<>(); @@ -155,9 +185,20 @@ private void autoCloseRequiredViews(boolean closeAllViews, Map c * @return Returns link to Countly for call chaining */ @Nullable String startViewInternal(@Nullable String viewName, @Nullable Map customViewSegmentation, boolean viewShouldBeAutomaticallyStopped) { + ConfigurationProvider configProvider = internalConfig.getConfigurationProvider(); + if (!configProvider.getTrackingEnabled()) { + L.w("[ModuleViews] startViewInternal, tracking disabled by SDK behavior settings; ignoring"); + L.recordLogCode("w505", HealthCheckCounter.AREA_VIEWS); + return null; + } + if (!configProvider.getViewTrackingEnabled()) { + L.d("[ModuleViews] startViewInternal, view tracking disabled by SDK behavior settings; ignoring"); + return null; + } if (viewName == null || viewName.isEmpty()) { - L.e("[ModuleViews] startViewInternal, Trying to record view with null or empty view name, ignoring request"); + L.w("[ModuleViews] startViewInternal, Trying to record view with null or empty view name, ignoring request"); + L.recordLogCode("w710", HealthCheckCounter.AREA_VIEWS); return null; } @@ -194,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; } @@ -208,6 +259,10 @@ void stopViewWithNameInternal(@Nullable String viewName, @Nullable Map customViewSegmentation) { + if (!isViewTrackingEnabled("stopViewWithIDInternal")) { + return; + } + ViewData vd = validateViewID(viewID, "stopViewWithIDInternal"); if (vd == null) { return; @@ -252,6 +307,10 @@ private void recordViewEndEvent(ViewData vd, @Nullable Map filte } void pauseViewWithIDInternal(String viewID) { + if (!isViewTrackingEnabled("pauseViewWithIDInternal")) { + return; + } + ViewData vd = validateViewID(viewID, "pauseViewWithIDInternal"); if (vd == null) { return; @@ -261,6 +320,7 @@ void pauseViewWithIDInternal(String viewID) { if (vd.viewStartTimeSeconds == 0) { L.w("[ModuleViews] pauseViewWithIDInternal, pausing a view that is already paused. ID:[" + viewID + "], name:[" + vd.viewName + "]"); + L.recordLogCode("w731", HealthCheckCounter.AREA_VIEWS); return; } @@ -270,6 +330,10 @@ void pauseViewWithIDInternal(String viewID) { } void resumeViewWithIDInternal(String viewID) { + if (!isViewTrackingEnabled("resumeViewWithIDInternal")) { + return; + } + ViewData vd = validateViewID(viewID, "resumeViewWithIDInternal"); if (vd == null) { return; @@ -279,6 +343,7 @@ void resumeViewWithIDInternal(String viewID) { if (vd.viewStartTimeSeconds > 0) { L.w("[ModuleViews] resumeViewWithIDInternal, resuming a view that is already running. ID:[" + viewID + "], name:[" + vd.viewName + "]"); + L.recordLogCode("w731", HealthCheckCounter.AREA_VIEWS); return; } @@ -287,18 +352,39 @@ void resumeViewWithIDInternal(String viewID) { void stopAllViewsInternal(Map viewSegmentation) { L.d("[ModuleViews] stopAllViewsInternal"); + if (!isViewTrackingEnabled("stopAllViewsInternal")) { + return; + } autoCloseRequiredViews(true, viewSegmentation); } + /** + * Whether the SDK behavior settings allow view tracking. While they do not, stopping, pausing + * and resuming views is ignored, so every view keeps its state until view tracking is allowed again. + * + * @param function the ignored call, for the log + * @return {@code true} when view tracking is enabled + */ + private boolean isViewTrackingEnabled(@Nonnull String function) { + if (internalConfig.getConfigurationProvider().getViewTrackingEnabled()) { + return true; + } + + L.d("[ModuleViews] " + function + ", view tracking is disabled by the SDK behavior settings, ignoring the call"); + return false; + } + private ViewData validateViewID(String viewID, String function) { if (viewID == null || viewID.isEmpty()) { - L.e("[ModuleViews] validateViewID, " + function + ", Trying to process view with null or empty view ID, ignoring request"); + L.w("[ModuleViews] validateViewID, " + function + ", Trying to process view with null or empty view ID, ignoring request"); + L.recordLogCode("w700", HealthCheckCounter.AREA_VIEWS); return null; } if (!viewDataMap.containsKey(viewID)) { L.w("[ModuleViews] validateViewID, " + function + ", there is no view with the provided view id"); + L.recordLogCode("w730", HealthCheckCounter.AREA_VIEWS); return null; } @@ -312,7 +398,8 @@ private ViewData validateViewID(String viewID, String function) { private String validateViewWithName(String viewName, String function) { if (viewName == null || viewName.isEmpty()) { - L.e("[ModuleViews] " + function + ", Trying to process the view with null or empty view name, ignoring request"); + L.w("[ModuleViews] " + function + ", Trying to process the view with null or empty view name, ignoring request"); + L.recordLogCode("w700", HealthCheckCounter.AREA_VIEWS); return null; } @@ -326,7 +413,8 @@ private String validateViewWithName(String viewName, String function) { } if (viewID == null) { - L.e("[ModuleViews] " + function + ", No view entry found with the provided name :[" + viewName + "]"); + L.w("[ModuleViews] " + function + ", No view entry found with the provided name :[" + viewName + "]"); + L.recordLogCode("w730", HealthCheckCounter.AREA_VIEWS); } return viewID; @@ -347,7 +435,8 @@ private void addSegmentationToViewWithIDInternal(String viewID, Map viewSegmentation) { + Views target = target("[Views] startAutoStoppedView"); + if (target != this) { + if (target == null) { + return null; + } + return target.startAutoStoppedView(viewName, viewSegmentation); + } synchronized (Countly.instance()) { L.i("[Views] Calling startAutoStoppedView [" + viewName + "] sg[" + viewSegmentation + "]"); + L.recordUsage(HealthCheckCounter.AREA_VIEWS, "startAuto"); return startViewInternal(viewName, viewSegmentation, true); } } @@ -402,8 +519,16 @@ public String startAutoStoppedView(@Nonnull String viewName, @Nullable Map viewSegmentation) { + Views target = target("[Views] startView"); + if (target != this) { + if (target == null) { + return null; + } + return target.startView(viewName, viewSegmentation); + } synchronized (Countly.instance()) { L.i("[Views] Calling startView vn[" + viewName + "] sg[" + viewSegmentation + "]"); + L.recordUsage(HealthCheckCounter.AREA_VIEWS, "start"); return startViewInternal(viewName, viewSegmentation, false); } } @@ -428,8 +561,16 @@ public String startAutoStoppedView(@Nonnull String viewName, @Nullable Map - view segmentation */ public void stopViewWithName(@Nonnull String viewName, @Nullable Map viewSegmentation) { + Views target = target("[Views] stopViewWithName"); + if (target != this) { + if (target != null) { + target.stopViewWithName(viewName, viewSegmentation); + } + return; + } synchronized (Countly.instance()) { L.i("[Views] Calling stopViewWithName vn[" + viewName + "] sg[" + viewSegmentation + "]"); + L.recordUsage(HealthCheckCounter.AREA_VIEWS, "stop"); stopViewWithNameInternal(viewName, viewSegmentation); } } @@ -453,8 +602,16 @@ public void stopViewWithName(@Nonnull String viewName, @Nullable Map - view segmentation */ public void stopViewWithID(@Nonnull String viewID, @Nullable Map viewSegmentation) { + Views target = target("[Views] stopViewWithID"); + if (target != this) { + if (target != null) { + target.stopViewWithID(viewID, viewSegmentation); + } + return; + } synchronized (Countly.instance()) { L.i("[Views] Calling stopViewWithID vi[" + viewID + "] sg[" + viewSegmentation + "]"); + L.recordUsage(HealthCheckCounter.AREA_VIEWS, "stop"); stopViewWithIDInternal(viewID, viewSegmentation); } } @@ -478,8 +643,16 @@ public void stopViewWithID(@Nonnull String viewID, @Nullable Map * @param viewID String - view ID */ public void pauseViewWithID(@Nonnull String viewID) { + Views target = target("[Views] pauseViewWithID"); + if (target != this) { + if (target != null) { + target.pauseViewWithID(viewID); + } + return; + } synchronized (Countly.instance()) { L.i("[Views] Calling pauseViewWithID vi[" + viewID + "]"); + L.recordUsage(HealthCheckCounter.AREA_VIEWS, "pause"); pauseViewWithIDInternal(viewID); } } @@ -490,8 +663,16 @@ public void pauseViewWithID(@Nonnull String viewID) { * @param viewID String - view ID */ public void resumeViewWithID(@Nonnull String viewID) { + Views target = target("[Views] resumeViewWithID"); + if (target != this) { + if (target != null) { + target.resumeViewWithID(viewID); + } + return; + } synchronized (Countly.instance()) { L.i("[Views] Calling resumeViewWithID vi[" + viewID + "]"); + L.recordUsage(HealthCheckCounter.AREA_VIEWS, "resume"); resumeViewWithIDInternal(viewID); } } @@ -502,8 +683,16 @@ public void resumeViewWithID(@Nonnull String viewID) { * @param viewSegmentation Map - view segmentation */ public void stopAllViews(@Nullable Map viewSegmentation) { + Views target = target("[Views] stopAllViews"); + if (target != this) { + if (target != null) { + target.stopAllViews(viewSegmentation); + } + return; + } synchronized (Countly.instance()) { L.i("[Views] Calling stopAllViews sg[" + viewSegmentation + "]"); + L.recordUsage(HealthCheckCounter.AREA_VIEWS, "stopAll"); stopAllViewsInternal(viewSegmentation); } } @@ -515,6 +704,13 @@ public void stopAllViews(@Nullable Map viewSegmentation) { * @param viewSegmentation Map */ public void addSegmentationToViewWithName(@Nonnull String viewName, @Nullable Map viewSegmentation) { + Views target = target("[Views] addSegmentationToViewWithName"); + if (target != this) { + if (target != null) { + target.addSegmentationToViewWithName(viewName, viewSegmentation); + } + return; + } synchronized (Countly.instance()) { L.i("[Views] Calling addSegmentationToViewWithName vn[" + viewName + "] sg[" + viewSegmentation + "]"); addSegmentationToViewWithNameInternal(viewName, viewSegmentation); @@ -528,6 +724,13 @@ public void addSegmentationToViewWithName(@Nonnull String viewName, @Nullable Ma * @param viewSegmentation Map */ public void addSegmentationToViewWithID(@Nonnull String viewId, @Nullable Map viewSegmentation) { + Views target = target("[Views] addSegmentationToViewWithID"); + if (target != this) { + if (target != null) { + target.addSegmentationToViewWithID(viewId, viewSegmentation); + } + return; + } synchronized (Countly.instance()) { L.i("[Views] Calling addSegmentationToViewWithID vi[" + viewId + "] sg[" + viewSegmentation + "]"); addSegmentationToViewWithIDInternal(viewId, viewSegmentation); @@ -540,6 +743,13 @@ public void addSegmentationToViewWithID(@Nonnull String viewId, @Nullable Map - global view segmentation */ public void setGlobalViewSegmentation(@Nullable Map segmentation) { + Views target = target("[Views] setGlobalViewSegmentation"); + if (target != this) { + if (target != null) { + target.setGlobalViewSegmentation(segmentation); + } + return; + } synchronized (Countly.instance()) { L.i("[Views] Calling setGlobalViewSegmentation sg[" + (segmentation == null ? null : segmentation.size()) + "]"); @@ -553,11 +763,19 @@ public void setGlobalViewSegmentation(@Nullable Map segmentation * @param segmentation Map - global view segmentation */ public void updateGlobalViewSegmentation(@Nullable Map segmentation) { + Views target = target("[Views] updateGlobalViewSegmentation"); + if (target != this) { + if (target != null) { + target.updateGlobalViewSegmentation(segmentation); + } + return; + } synchronized (Countly.instance()) { L.i("[Views] Calling updateGlobalViewSegmentation sg[" + (segmentation == null ? null : segmentation.size()) + "]"); if (segmentation == null) { L.w("[View] When updating segmentation values, they can't be 'null'."); + L.recordLogCode("w700", HealthCheckCounter.AREA_VIEWS); return; } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/Request.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/Request.java index 0d32332bc..2ca0fa64a 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/Request.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/Request.java @@ -25,10 +25,10 @@ public class Request implements Storable { public Params params; /** - * Create request from params with current time as id. + * Create request from params with a new storage id based on the current time. */ public Request(Object... params) { - this.id = TimeUtils.uniqueTimestampMs(); + this.id = TimeUtils.uniqueStorageId(); this.params = new Params(params); } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/SDKCore.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/SDKCore.java index 3c8aa1938..68fbbea39 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/SDKCore.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/SDKCore.java @@ -1,19 +1,31 @@ package ly.count.sdk.java.internal; import java.io.File; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Queue; -import java.util.TreeMap; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentSkipListMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Function; import javax.annotation.Nonnull; import javax.annotation.Nullable; import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; public class SDKCore { + /** + * The app key placeholder of the integration samples, never a key of a real app. + */ + private static final String PLACEHOLDER_APP_KEY = "YOUR_APP_KEY"; + protected static SDKCore instance; protected final SDKStorage sdkStorage; private UserImpl user; @@ -21,23 +33,81 @@ public class SDKCore { protected Networking networking; protected Queue requestQueueMemory = null; protected final Object lockBRQStorage = new Object(); - private CountlyTimer countlyTimer; + private final Object lockTimer = new Object(); + //guarded by lockTimer for writes + volatile CountlyTimer countlyTimer; + private ModuleConfiguration moduleConfiguration; protected Log L = null; + //the health check counters, null in backend mode + volatile HealthCheckCounter healthCheckCounter = null; protected static ModuleBase testDummyModule = null;//set during testing when trying to check the SDK's lifecycle /** * Currently enabled features with consents */ - protected int consents = 0; + protected volatile int consents = 0; /** * Selected by config map of module mappings */ private static final Map> moduleMappings = new ConcurrentHashMap<>(); - // TreeMap to keep modules sorted by their feature indexes + /** + * The view IDs events carry while no views module runs. + */ + static final ViewIdProvider NO_VIEW_IDS = new ViewIdProvider() { + /** + * No view runs, so there is no current view ID. + */ + @Nonnull public String getCurrentViewId() { + return ""; + } + + /** + * No view runs, so there is no previous view ID. + */ + @Nonnull public String getPreviousViewId() { + return ""; + } + }; + + /** + * Interfaces of module instances the SDK never runs, handed out in place of the interface of a + * feature that does not run: before init, while its consent is not given, or when it is not + * enabled, so a caller never gets {@code null}. Like every module interface, each sends its + * calls to the module of its feature once that runs and ignores them until then. + */ + public static final ModuleEvents.Events dormantEvents = new ModuleEvents().new Events(); + public static final ModuleFeedback.Feedback dormantFeedback = new ModuleFeedback().new Feedback(); + public static final ModuleContent.Content dormantContent = new ModuleContent().new Content(); + public static final ModuleCrashes.Crashes dormantCrashes = new ModuleCrashes().new Crashes(); + public static final ModuleViews.Views dormantViews = new ModuleViews().new Views(); + public static final ModuleDeviceIdCore.DeviceId dormantDeviceId = new ModuleDeviceIdCore().new DeviceId(); + public static final ModuleRemoteConfig.RemoteConfig dormantRemoteConfig = new ModuleRemoteConfig().new RemoteConfig(); + public static final ModuleUserProfile.UserProfile dormantUserProfile = new ModuleUserProfile().new UserProfile(); + public static final ModuleLocation.Location dormantLocation = new ModuleLocation().new Location(); + + /** + * The remote config download callbacks, those of the configuration and those registered through + * the remote config interface, kept beyond the module, so one built when the consent is given, + * or given again, calls them too. + */ + final List remoteConfigDownloadCallbacks = new CopyOnWriteArrayList<>(); + + /** + * The display registered through the content interface, kept beyond the module, so one built + * when the consent is given, or given again, draws with it. + */ + volatile ContentDisplay contentDisplay = null; + + // sorted by feature index, and safe to iterate while a consent change adds or removes a module protected final Map modules; + /** + * Set once {@link #stop(boolean)} starts, after which no settings change reaches the modules. + */ + private volatile boolean stopping = false; + public enum Signal { DID(1), Crash(2), @@ -56,7 +126,7 @@ public int getIndex() { } public SDKCore() { - this.modules = new TreeMap<>(); + this.modules = new ConcurrentSkipListMap<>(); instance = this; sdkStorage = new SDKStorage(); } @@ -88,7 +158,15 @@ public boolean isTracking(Integer feat) { } private void onTimer() { - modules.forEach((feature, module) -> module.onTimer()); + modules.forEach((feature, module) -> { + try { + module.onTimer(); + } catch (Throwable t) { + //one failing module does not hold back the others on the same tick + L.e("[SDKCore] onTimer, " + module.getClass().getSimpleName() + " failed on a tick, [" + t + "]"); + } + }); + L.flushGatheredLogs(); } /** @@ -101,12 +179,20 @@ public void stop(final boolean clear) { if (instance == null) { return; } + stopping = true; if (networking != null) { networking.stop(config); } - countlyTimer.stopTimer(); + CountlyTimer timerToStop; + synchronized (lockTimer) { + timerToStop = countlyTimer; + countlyTimer = null; + } + if (timerToStop != null) { + timerToStop.stopTimer(); + } L.i("[SDKCore] Stopping Countly SDK" + (clear ? " and clearing all data" : "")); @@ -121,9 +207,13 @@ public void stop(final boolean clear) { modules.clear(); moduleMappings.clear(); + L.setHealthCheckCounter(null); + healthCheckCounter = null; + L.endLogGathering(!clear); sdkStorage.stop(config, clear);//from original super class user = null; + moduleConfiguration = null; config = null; instance = null; } @@ -156,16 +246,17 @@ public void onConsent(final int consent) { if (addingConsent(consent, CoreFeature.Sessions)) { SessionImpl session = module(ModuleSessions.class).getSession(); - if (session != null) { - session.end(); + if (session != null && session.isActive()) { + session.endAutomatically(null, null, null); } consents = consents | (consent & config.getFeatures1()); - module(ModuleSessions.class).session(config, null).begin(); + module(ModuleSessions.class).session(config, null).beginAutomatically(); } consents = consents | (consent & config.getFeatures1()); + L.releaseConsentedLogLines(); for (CoreFeature feature : moduleMappings.keySet()) { ModuleBase existing = module(moduleMappings.get(feature)); @@ -176,6 +267,7 @@ public void onConsent(final int consent) { } else { module.init(config); module.initFinished(config); + module.setActive(true); modules.put(feature.getIndex(), module); } } @@ -195,20 +287,27 @@ public void onConsentRemoval(final InternalConfig config, int noConsent) { if (removingConsent(noConsent, CoreFeature.Sessions)) { SessionImpl session = module(ModuleSessions.class).getSession(); - if (session != null) { - session.end(); + if (session != null && session.isActive()) { + session.endAutomatically(null, null, null); } } if (removingConsent(noConsent, CoreFeature.Location)) { - user().edit().optOutFromLocationServices(); + ModuleLocation location = module(ModuleLocation.class); + if (location != null) { + location.eraseLocation(); + } } consents = consents & ~noConsent; + L.dropLinesWithoutConsent(); for (CoreFeature feature : moduleMappings.keySet()) { + if (feature == CoreFeature.Sessions || (noConsent & feature.getIndex()) == 0) { + continue; + } ModuleBase existing = module(moduleMappings.get(feature)); - if (feature.getIndex() != CoreFeature.Sessions.getIndex() && existing != null) { + if (existing != null) { existing.stop(config, true); modules.remove(feature.getIndex()); } @@ -256,6 +355,10 @@ protected void buildModules(InternalConfig config, int features) throws IllegalA // standard required internal features modules.put(-3, new ModuleDeviceIdCore()); modules.put(-2, new ModuleRequests()); + if (moduleConfiguration != null) { + modules.put(-1, moduleConfiguration); + } + modules.put(0, new ModuleConnectionTest()); modules.put(CoreFeature.Sessions.getIndex(), new ModuleSessions()); modules.put(CoreFeature.UserProfiles.getIndex(), new ModuleUserProfile()); @@ -282,6 +385,11 @@ protected void buildModules(InternalConfig config, int features) throws IllegalA } modules.put(CoreFeature.BackendMode.getIndex(), new ModuleBackendMode()); + //last, so the health check sent at the end of init counts what the other modules logged while starting + if (healthCheckCounter != null) { + modules.put(Integer.MAX_VALUE, new ModuleHealthCheck()); + } + // dummy module for tests if any if (testDummyModule != null) { modules.put(CoreFeature.TestDummy.getIndex(), testDummyModule); @@ -397,6 +505,8 @@ public void init(final InternalConfig givenConfig) { config.sdk = this; sdkStorage.init(config); config.storageProvider = sdkStorage; + healthCheckCounter = ModuleHealthCheck.createCounter(config, sdkStorage, this); + L.setHealthCheckCounter(healthCheckCounter); if (config.immediateRequestGenerator == null) { config.immediateRequestGenerator = ImmediateRequestMaker::new; @@ -405,10 +515,6 @@ public void init(final InternalConfig givenConfig) { //setup module mapping prepareMappings(); - //create internal timer - countlyTimer = new CountlyTimer(L); - countlyTimer.startTimer(config.getSendUpdateEachSeconds(), this::onTimer); - //setup and perform migrations MigrationHelper migrationHelper = new MigrationHelper(L); migrationHelper.setupMigrations(config.storageProvider); @@ -418,7 +524,20 @@ public void init(final InternalConfig givenConfig) { setDeviceIdFromStorageIfExist(config); + //resolve the SDK behavior settings before anything reads them + moduleConfiguration = new ModuleConfiguration(); + moduleConfiguration.init(config); + applyLoggingSetting(config, moduleConfiguration); + applyConsentRequirementAtInit(config, moduleConfiguration.getConsentRequired()); + L.setLogGatheringProviders(moduleConfiguration, this::givenLogLineConsents, gatheredLogBatchQueue); + + //create internal timer + synchronized (lockTimer) { + startTimer(moduleConfiguration.getSessionUpdateInterval()); + } + requestQueueMemory = new ArrayDeque<>(config.getRequestQueueMaxSize()); + remoteConfigDownloadCallbacks.addAll(config.getRemoteConfigGlobalCallbackList()); if (config.viewIdGenerator == null) { config.viewIdGenerator = Utils::safeRandomVal; @@ -429,15 +548,7 @@ public void init(final InternalConfig givenConfig) { } if (config.viewIdProvider == null) { - config.viewIdProvider = new ViewIdProvider() { - @Nonnull public String getCurrentViewId() { - return ""; - } - - @Nonnull public String getPreviousViewId() { - return ""; - } - }; + config.viewIdProvider = NO_VIEW_IDS; } // ModuleSessions is always enabled, even without consent @@ -449,7 +560,9 @@ public void init(final InternalConfig givenConfig) { modules.forEach((feature, module) -> { try { - module.init(config); + if (module != moduleConfiguration) { + module.init(config); + } module.setActive(true); } catch (IllegalArgumentException | IllegalStateException e) { L.e("[SDKCore] Error during module initialization" + e); @@ -528,6 +641,144 @@ private void checkNetworking(InternalConfig config) { private void initFinished(final InternalConfig config) { modules.forEach((feature, module) -> module.initFinished(config)); checkNetworking(config); + L.onSdkInitFinished(); + } + + /** + * The features whose consent lets a gathered log line go: every feature while no consent is + * required, otherwise the ones consent was given for. Read inside log calls, so it never logs. + * + * @return the {@link CoreFeature} indexes, every bit while no consent is required + */ + private int givenLogLineConsents() { + InternalConfig current = config; + if (current == null) { + return 0; + } + if (!current.requiresConsent()) { + return ~0; + } + int given = consents; + //a feature the app never enabled holds no data and can never get consent, so it holds no line back + return given == 0 ? 0 : given | (~current.getFeatures1() & Log.UNATTRIBUTED_LINE_CONSENT); + } + + /** + * The request queue as the log gathering uses it: one request per batch of gathered log lines, + * waiting until it is sent or dropped. + */ + private final Log.LogBatchQueue gatheredLogBatchQueue = new Log.LogBatchQueue() { + /** + * Stores the batch as a request of its own, unless the SDK stopped. + */ + @Nullable + @Override + public Long queueLogBatch(@Nonnull String payload) { + InternalConfig current = config; + return current == null ? null : ModuleRequests.pushSdkLogs(current, payload); + } + + /** + * Whether the request file is still stored, which it is until the request is sent or dropped. + */ + @Override + public boolean isQueued(@Nonnull Long requestId) { + InternalConfig current = config; + return current != null && sdkStorage.storableExists(current, Request.getStoragePrefix(), requestId); + } + }; + + /** + * Makes the consent requirement the SDK behavior settings resolved the one every module reads + * through {@link InternalConfig#requiresConsent()}. It is applied here, before the modules are + * built, and only here: a value that arrives later takes effect on the next init. + * + * @param config configuration of the SDK being initialized + * @param consentRequired the resolved consent requirement + */ + private void applyConsentRequirementAtInit(@Nonnull InternalConfig config, boolean consentRequired) { + if (consentRequired != config.requiresConsent()) { + L.i("[SDKCore] applyConsentRequirementAtInit, SDK behavior settings set the consent requirement to [" + consentRequired + "]"); + config.setRequiresConsent(consentRequired); + } + } + + /** + * Starts the global timer, replacing the running one. The caller holds {@link #lockTimer}. + * + * @param intervalSeconds seconds between two ticks + */ + private void startTimer(int intervalSeconds) { + countlyTimer = new CountlyTimer(L); + countlyTimer.startTimer(intervalSeconds, this::onTimer); + } + + /** + * Restarts the global timer when its interval differs from the given one. Never waits for the + * replaced timer, as a settings change can be applied from a timer task. + * + * @param intervalSeconds the session update interval now in effect + */ + private void restartTimerIfIntervalChanged(int intervalSeconds) { + synchronized (lockTimer) { + CountlyTimer runningTimer = countlyTimer; + if (runningTimer == null || runningTimer.getTimerDelaySeconds() == intervalSeconds) { + return; + } + + L.d("[SDKCore] restartTimerIfIntervalChanged, session update interval changed from [" + runningTimer.getTimerDelaySeconds() + "] to [" + intervalSeconds + "] seconds, restarting the timer"); + runningTimer.stopTimer(false); + startTimer(intervalSeconds); + } + } + + /** + * Applies the {@code log} switch of the SDK behavior settings to what the SDK logger prints. + * + * @param config configuration whose logger prints + * @param provider the settings in effect + */ + private void applyLoggingSetting(@Nonnull InternalConfig config, @Nonnull ConfigurationProvider provider) { + Log logger = config.getLogger(); + if (logger == null) { + return; + } + + logger.setLoggingEnabled(provider.getLoggingEnabled()); + logger.d("[SDKCore] applyLoggingSetting, logging enabled:[" + provider.getLoggingEnabled() + "], printing from level:[" + logger.getPrintLevel() + "]"); + } + + /** + * Applies SDK behavior settings that a server response changed while the SDK runs: sets what the + * logger prints, restarts the global timer when the session update interval changed, lets the + * request queue drain when networking is allowed, then notifies every module, each on its own. + * A change that arrives once the SDK started stopping is ignored, as its modules are being stopped. + * + * @param changedConfig configuration whose settings changed + */ + void onSdkConfigurationChanged(@Nonnull InternalConfig changedConfig) { + if (stopping || config == null || config != changedConfig) { + L.d("[SDKCore] onSdkConfigurationChanged, the SDK is stopping or was stopped before the change arrived, ignoring it"); + return; + } + + L.i("[SDKCore] onSdkConfigurationChanged"); + ConfigurationProvider provider = changedConfig.getConfigurationProvider(); + applyLoggingSetting(changedConfig, provider); + restartTimerIfIntervalChanged(provider.getSessionUpdateInterval()); + + if (provider.getNetworkingEnabled()) { + checkNetworking(changedConfig); + } + + List modulesToNotify = new ArrayList<>(modules.values()); + for (ModuleBase module : modulesToNotify) { + try { + module.onSdkConfigurationChanged(changedConfig); + } catch (Exception e) { + L.e("[SDKCore] onSdkConfigurationChanged, " + module.getClass().getSimpleName() + " failed to apply the change, [" + e + "]"); + } + } } public UserImpl user() { @@ -538,6 +789,202 @@ public InternalConfig config() { return config; } + /** + * Switches to a valid server URL in memory, then sends the request queue and catches up the new + * server, see {@link Countly#changeServerUrl(String)}. + * + * @param serverUrl the new server URL, ignored with log code e102 when it is not valid + */ + public void changeServerUrl(@Nullable String serverUrl) { + URL url = validServerUrl(serverUrl); + if (url == null) { + L.recordLogCode("e102"); + return; + } + + config.setServerURL(url); + L.i("[SDKCore] changeServerUrl, requests are sent to [" + url + "] from now on"); + checkNetworking(config); + catchUpAfterChange(false); + } + + /** + * Parses a server URL the SDK can send to, logging an error when it cannot. + * + * @param serverUrl the URL as given + * @return the URL without trailing "/" characters, {@code null} when it is not valid + */ + @Nullable + private URL validServerUrl(@Nullable String serverUrl) { + URL url; + try { + url = new URL(serverUrl == null ? "" : serverUrl.replaceAll("/+$", "")); + url.toURI(); + } catch (MalformedURLException | URISyntaxException e) { + url = null; + } + + if (url == null || !("http".equals(url.getProtocol()) || "https".equals(url.getProtocol())) || Utils.isEmptyOrNull(url.getHost())) { + L.e("[SDKCore] changeServerUrl, [" + serverUrl + "] is not an absolute http or https URL with a host, the server URL stays [" + config.getServerURL() + "]"); + return null; + } + + Set keyPins = config.getPublicKeyPins(); + Set certificatePins = config.getCertificatePins(); + boolean pinned = (keyPins != null && !keyPins.isEmpty()) || (certificatePins != null && !certificatePins.isEmpty()); + if (pinned && !"https".equals(url.getProtocol())) { + L.e("[SDKCore] changeServerUrl, certificate or public key pins are set, so [" + serverUrl + "] must use https, the server URL stays [" + config.getServerURL() + "]"); + return null; + } + return url; + } + + /** + * Closes what belongs to the old app under the old key, switches the key in memory, begins a + * session again if one was running and catches up the new app, see + * {@link Countly#changeAppKey(String)}. + * + * @param appKey the new app key, ignored with log code e103 when it is empty or "YOUR_APP_KEY" + */ + public void changeAppKey(@Nullable String appKey) { + if (ignoredInBackendMode("changeAppKey")) { + return; + } + if (Utils.isEmptyOrNull(appKey) || PLACEHOLDER_APP_KEY.equals(appKey)) { + L.e("[SDKCore] changeAppKey, [" + appKey + "] is not a valid app key, the app key stays the same"); + L.recordLogCode("e103"); + return; + } + if (appKey.equals(config.getServerAppKey())) { + L.d("[SDKCore] changeAppKey, the given app key is already in use, ignoring the call"); + return; + } + + //the lock of the views, user profile and device ID calls, so none of them runs between closing and switching + synchronized (Countly.instance()) { + ModuleViews views = module(ModuleViews.class); + if (views != null) { + views.stopAllViewsInternal(null); + } + ModuleEvents events = runningModule(CoreFeature.Events, ModuleEvents.class); + if (events != null) { + events.checkEventQueueToSend(true); + } + ModuleUserProfile.saveIfSentAutomatically(config); + SessionImpl session = getSession(); + boolean sessionWasRunning = session != null && session.isActive(); + if (sessionWasRunning) { + session.endAutomatically(null, null, null); + } + + config.setServerAppKey(appKey); + L.i("[SDKCore] changeAppKey, new requests carry the new app key from now on"); + + if (sessionWasRunning) { + session(null).beginAutomatically(); + } + } + catchUpAfterChange(true); + } + + /** + * Catches up a server or app that knows nothing of this device yet: requests the SDK behavior + * settings, keeping the stored ones until the answer arrives, and, as at init, downloads remote + * config when it downloads automatically, except in temporary device ID mode. + * + * @param appKeyChanged whether the stored remote config values belong to the old app, so they + * are cleared, or marked as cached with value caching + */ + private void catchUpAfterChange(boolean appKeyChanged) { + ModuleConfiguration configuration = moduleConfiguration; + if (configuration != null) { + configuration.fetchConfigFromServer(config); + } + ModuleRemoteConfig remoteConfig = runningModule(CoreFeature.RemoteConfig, ModuleRemoteConfig.class); + if (remoteConfig == null) { + return; + } + if (appKeyChanged) { + remoteConfig.cacheOrClearRCValuesIfNeeded(); + } + if (!config.isTemporaryIdEnabled()) { + remoteConfig.rcAutomaticDownloadTrigger(false); + } + } + + /** + * Drops the queued events and every queued request, unsent, see {@link Countly#flushQueues()}. + */ + public void flushQueues() { + if (ignoredInBackendMode("flushQueues")) { + return; + } + ModuleEvents events = module(ModuleEvents.class); + if (events != null) { + events.clearEventQueue(); + } else { + //events stored by an earlier run, which the events module restores once it runs + sdkStorage.storeEventQueue(""); + } + int removed = ModuleRequests.removeQueuedRequests(config, null); + L.i("[SDKCore] flushQueues, cleared the event queue and removed [" + removed + "] queued requests"); + } + + /** + * Sets the current app key on every queued request, so the requests queued under another key + * go to the current app. + */ + public void replaceAllAppKeysInQueueWithCurrentAppKey() { + if (ignoredInBackendMode("replaceAllAppKeysInQueueWithCurrentAppKey")) { + return; + } + int replaced = ModuleRequests.replaceAppKeysInQueue(config); + L.i("[SDKCore] replaceAllAppKeysInQueueWithCurrentAppKey, [" + replaced + "] queued requests now carry the current app key"); + } + + /** + * Removes, unsent, every queued request whose app key is not the current one. + */ + public void removeDifferentAppKeysFromQueue() { + if (ignoredInBackendMode("removeDifferentAppKeysFromQueue")) { + return; + } + String appKey = config.getServerAppKey(); + int removed = ModuleRequests.removeQueuedRequests(config, request -> !appKey.equals(request.params.get("app_key"))); + L.i("[SDKCore] removeDifferentAppKeysFromQueue, removed [" + removed + "] queued requests with another app key"); + } + + /** + * Moves the queued events, those of backend mode included, into requests and starts sending + * the request queue now, see {@link Countly#attemptToSendStoredRequests()}. + */ + public void attemptToSendStoredRequests() { + ModuleEvents events = runningModule(CoreFeature.Events, ModuleEvents.class); + if (events != null) { + events.checkEventQueueToSend(true); + } + ModuleBackendMode backendMode = module(ModuleBackendMode.class); + if (config.isBackendModeEnabled() && backendMode != null) { + backendMode.addEventsToRequestQ(); + } + checkNetworking(config); + } + + /** + * Whether a call is ignored as backend mode is enabled, where the application sets the app key + * of each request, so the queue holds requests of other apps on purpose. + * + * @param call the call, for the log line + * @return {@code true} when backend mode is enabled + */ + private boolean ignoredInBackendMode(@Nonnull String call) { + if (!config.isBackendModeEnabled()) { + return false; + } + L.w("[SDKCore] " + call + ", backend mode is enabled, where requests carry the app key the application sets, ignoring the call"); + return true; + } + public void notifyModulesDeviceIdChanged(@Nullable String old, final boolean withMerge) { L.d("[SDKCore] notifyModulesDeviceIdChanged, newDeviceId:[" + config.getDeviceId() + "], oldDeviceId:[ " + old + "]"); Config.DID id = config.getDeviceId(); @@ -628,6 +1075,24 @@ public static boolean enabled(CoreFeature feature) { return enabled(feature.getIndex()); } + /** + * Whether calls of a feature are counted in the health check method usage: the feature has + * consent, or no consent is required. Reads only this instance, so it is safe while the SDK stops. + * + * @param feature the feature behind a method usage area + * @return {@code true} when its calls are counted + */ + boolean hasConsentForUsageArea(@Nonnull CoreFeature feature) { + InternalConfig current = config; + if (current == null) { + return false; + } + if (!current.requiresConsent()) { + return true; + } + return (consents & feature.getIndex()) == feature.getIndex(); + } + public boolean hasConsentForFeature(CoreFeature feature) { if (!instance.config.requiresConsent()) { //if no consent required, return true @@ -642,8 +1107,8 @@ public Boolean isRequestReady(Request request) { if (cls == null) { return true; } else { + // The owner stays on the request: Transport.send reads it to hand over the response, then removes it before sending ModuleBase module = module(cls); - request.params.remove(Request.MODULE); if (module == null) { return true; } else { @@ -655,17 +1120,23 @@ public Boolean isRequestReady(Request request) { /** * After a network request has been finished * propagate that response to the module - * that owns the request + * that owns the request. Neither looking the owner up nor the owner failing to handle the + * response ever fails the send. * * @param request the request that was sent, used to identify the request */ public void onRequestCompleted(Request request, String response, int responseCode, Class requestOwner) { - if (requestOwner != null) { - ModuleBase module = module(requestOwner); + if (requestOwner == null) { + return; + } + try { + ModuleBase module = module(requestOwner); if (module != null) { module.onRequestCompleted(request, response, responseCode); } + } catch (Exception e) { + L.e("[SDKCore] onRequestCompleted, " + requestOwner.getSimpleName() + " failed to handle the response of request [" + (request == null ? null : request.storageId()) + "], [" + e + "]"); } } @@ -713,7 +1184,8 @@ private boolean processCrash(InternalConfig config, Long id) { crash = Storage.read(config, crash); if (crash == null) { - L.e("Cannot read crash from storage, skipping"); + L.w("[SDKCore] processCrash, Cannot read crash from storage, skipping"); + L.recordLogCode("w504"); return false; } @@ -723,7 +1195,7 @@ private boolean processCrash(InternalConfig config, Long id) { ModuleRequests.addRequiredParametersToParams(config, request.params); ModuleRequests.addRequiredTimeParametersToParams(request.params); - if (Storage.push(config, request)) { + if (ModuleRequests.pushWithinQueueLimit(config, request)) { L.i("[SDKCore] Added request " + request.storageId() + " instead of crash " + crash.storageId()); checkNetworking(config); Boolean success = Storage.remove(config, crash); @@ -749,113 +1221,120 @@ TimedEvents timedEvents() { return ((ModuleSessions) module(CoreFeature.Sessions)).timedEvents(); } + /** + * The events interface: the running module's, or one that ignores calls until the events feature runs, as its consent is not given or it is not enabled. + * + * @return the interface, never {@code null} + */ public ModuleEvents.Events events() { - if (!hasConsentForFeature(CoreFeature.Events)) { - L.v("[SDKCore] events, Events feature has no consent, returning null"); - return null; - } - - ModuleEvents module = module(ModuleEvents.class); - if (module == null) { - return null; - } - - return module.eventsInterface; + return runningInterface(CoreFeature.Events, ModuleEvents.class, module -> module.eventsInterface, dormantEvents); } + /** + * The feedback interface: the running module's, or one that ignores calls until the feedback feature runs, as its consent is not given or it is not enabled. + * + * @return the interface, never {@code null} + */ public ModuleFeedback.Feedback feedback() { - - if (!hasConsentForFeature(CoreFeature.Feedback)) { - L.v("[SDKCore] feedback, Feedback feature has no consent, returning null"); - return null; - } - - ModuleFeedback module = module(ModuleFeedback.class); - if (module == null) { - // Consent is not the only gate: the feature may simply never have been enabled, - // in which case the module was never built and there is nothing to hand back. - L.v("[SDKCore] feedback, feedback feature was not enabled, returning null"); - return null; - } - - return module.feedbackInterface; + return runningInterface(CoreFeature.Feedback, ModuleFeedback.class, module -> module.feedbackInterface, dormantFeedback); } + /** + * The content interface: the running module's, or one that ignores calls until the content feature runs, as its consent is not given or it is not enabled. + * + * @return the interface, never {@code null} + */ public ModuleContent.Content content() { - if (!hasConsentForFeature(CoreFeature.Content)) { - L.v("[SDKCore] content, Content feature has no consent, returning null"); - return null; - } - - ModuleContent module = module(ModuleContent.class); - if (module == null) { - return null; - } - - return module.contentInterface; + return runningInterface(CoreFeature.Content, ModuleContent.class, module -> module.contentInterface, dormantContent); } + /** + * The crashes interface: the running module's, or one that ignores calls until crash reporting runs, as its consent is not given or it is not enabled. + * + * @return the interface, never {@code null} + */ public ModuleCrashes.Crashes crashes() { - if (!hasConsentForFeature(CoreFeature.CrashReporting)) { - L.v("[SDKCore] crash, Crash Reporting feature has no consent, returning null"); - return null; - } - - ModuleCrashes module = module(ModuleCrashes.class); - if (module == null) { - // Consent is not the only gate: the feature may simply never have been enabled, - // in which case the module was never built and there is nothing to hand back. - L.v("[SDKCore] crashes, crashes feature was not enabled, returning null"); - return null; - } - - return module.crashInterface; + return runningInterface(CoreFeature.CrashReporting, ModuleCrashes.class, module -> module.crashInterface, dormantCrashes); } + /** + * The views interface: the running module's, or one that ignores calls until the views feature runs, as its consent is not given or it is not enabled. + * + * @return the interface, never {@code null} + */ public ModuleViews.Views views() { - ModuleViews module = module(ModuleViews.class); - if (module == null) { - L.v("[SDKCore] views, Views feature has no consent, returning null"); - return null; - } - - return module.viewsInterface; + return runningInterface(null, ModuleViews.class, module -> module.viewsInterface, dormantViews); } + /** + * The device ID interface: the running module's, or one that ignores calls until the device ID module runs. + * + * @return the interface, never {@code null} + */ public ModuleDeviceIdCore.DeviceId deviceId() { - return module(ModuleDeviceIdCore.class).deviceIdInterface; + return runningInterface(null, ModuleDeviceIdCore.class, module -> module.deviceIdInterface, dormantDeviceId); } + /** + * The remote config interface: the running module's, or one that ignores calls until remote config runs, as its consent is not given or it is not enabled. + * + * @return the interface, never {@code null} + */ public ModuleRemoteConfig.RemoteConfig remoteConfig() { - if (!hasConsentForFeature(CoreFeature.RemoteConfig)) { - L.v("[SDKCore] remoteConfig, RemoteConfig feature has no consent, returning null"); - return null; - } - - ModuleRemoteConfig module = module(ModuleRemoteConfig.class); - if (module == null) { - // Consent is not the only gate: the feature may simply never have been enabled, - // in which case the module was never built and there is nothing to hand back. - L.v("[SDKCore] remoteConfig, remoteConfig feature was not enabled, returning null"); - return null; - } - - return module.remoteConfigInterface; + return runningInterface(CoreFeature.RemoteConfig, ModuleRemoteConfig.class, module -> module.remoteConfigInterface, dormantRemoteConfig); } + /** + * The user profile interface: the running module's, or one that ignores calls until the user profile module runs. + * + * @return the interface, never {@code null} + */ public ModuleUserProfile.UserProfile userProfile() { - return module(ModuleUserProfile.class).userProfileInterface; + return runningInterface(null, ModuleUserProfile.class, module -> module.userProfileInterface, dormantUserProfile); } + /** + * The location interface: the running module's, or one that ignores calls until the location feature runs, as its consent is not given or it is not enabled. + * + * @return the interface, never {@code null} + */ public ModuleLocation.Location location() { - if (!hasConsentForFeature(CoreFeature.Location)) { - L.v("[SDKCore] location, Location feature has no consent, returning null"); - return null; - } - ModuleLocation module = module(ModuleLocation.class); - if (module == null) { - return null; + return runningInterface(CoreFeature.Location, ModuleLocation.class, module -> module.locationInterface, dormantLocation); + } + + /** + * The interface of a running module, or the one handed out while it does not run, whose calls + * go to the module once it runs and are ignored until then. + * + * @param consent the feature whose consent the module needs, {@code null} when it needs none + * @param moduleClass the class of the module + * @param interfaceOf reads the interface of a module + * @param dormant the interface handed out while the module does not run + * @param the module type + * @param the interface type + * @return the interface, never {@code null} + */ + private I runningInterface(@Nullable CoreFeature consent, @Nonnull Class moduleClass, @Nonnull Function interfaceOf, @Nonnull I dormant) { + M module = consent == null ? module(moduleClass) : runningModule(consent, moduleClass); + I running = module == null ? null : interfaceOf.apply(module); + if (running == null) { + L.v("[SDKCore] runningInterface, " + moduleClass.getSimpleName() + " does not run, handing out an interface that ignores calls until it does"); + return dormant; } - return module.locationInterface; + return running; + } + + /** + * The module of a feature while it runs: it was built and the feature's consent is given. + * + * @param feature the feature + * @param moduleClass the class of its module + * @param the module type + * @return the module, {@code null} while it does not run + */ + @Nullable + M runningModule(@Nonnull CoreFeature feature, @Nonnull Class moduleClass) { + M module = module(moduleClass); + return module != null && hasConsentForFeature(feature) ? module : null; } } 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 4575608ed..883d142ab 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 @@ -33,6 +33,10 @@ public class SDKStorage implements StorageProvider { protected static final String key_device_id_type = "did_t"; protected static final String key_remote_config = "rc"; protected static final String key_migration_version = "dv"; + 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; @@ -119,7 +123,8 @@ public Boolean storableWrite(ly.count.sdk.java.internal.InternalConfig config, S stream.close(); return true; } catch (IOException e) { - L.w("[SDKStorage] Cannot write data to " + filename + " " + e); + L.e("[SDKStorage] Cannot write data to " + filename + " " + e); + L.recordLogCode("e501"); } finally { if (stream != null) { try { @@ -170,6 +175,11 @@ private FileOutputStream openFileAsOutputStream(ly.count.sdk.java.internal.Inter } public byte[] storableReadBytes(InternalConfig config, String filename) { + //every storable starts without a file, so a missing one is no error + if (!new File(createFileFullPath(config, filename)).exists()) { + return null; + } + ByteArrayOutputStream buffer = null; FileInputStream stream = null; @@ -188,6 +198,7 @@ public byte[] storableReadBytes(InternalConfig config, String filename) { return buffer.toByteArray(); } catch (FileNotFoundException e) { + L.e("[SDKStorage] Error while opening file " + filename + " " + e); return null; } catch (IOException e) { L.e("[SDKStorage] Error while reading file " + filename + " " + e); @@ -276,6 +287,18 @@ private String[] getFileList(InternalConfig config, Predicate fileValidati return fileNames.toArray(ret); } + /** + * Whether the file of a storable exists, as a stored request does until it is sent or dropped. + * + * @param config configuration of the running SDK + * @param prefix the storage prefix of the storable + * @param id the storage ID of the storable + * @return {@code true} while the file exists + */ + boolean storableExists(InternalConfig config, String prefix, Long id) { + return new File(createFileFullPath(config, getName(prefix, id.toString()))).exists(); + } + public List storableList(InternalConfig config, String prefix, int slice) { if (Utils.isEmptyOrNull(prefix)) { L.e("[SDKStorage] Cannot get list of ids without prefix"); @@ -386,6 +409,73 @@ public void setMigrationVersion(Integer migrationVersion) { jsonFileStorage.addAndSave(key_migration_version, migrationVersion); } + @Override + public void setServerConfig(String config) { + if (config == null) { + jsonFileStorage.deleteAndSave(key_server_config); + } else { + jsonFileStorage.addAndSave(key_server_config, config); + } + } + + @Override + public String getServerConfig() { + return jsonFileStorage.getString(key_server_config); + } + + @Override + public String getHealthCheckState() { + JsonFileStorage storage = jsonFileStorage; + return storage == null ? null : storage.getString(key_health_check); + } + + @Override + public void setHealthCheckState(String state) { + JsonFileStorage storage = jsonFileStorage; + if (storage != null) { + storage.addAndSave(key_health_check, state == null ? "" : 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; + if (storage != null) { + synchronized (storage) { + storage.addAndSave(key_health_check_automatic_crashes, storage.getInt(key_health_check_automatic_crashes, 0) + 1); + } + } + } + + @Override + public int takeAutomaticCrashCount() { + JsonFileStorage storage = jsonFileStorage; + if (storage == null) { + return 0; + } + synchronized (storage) { + int count = storage.getInt(key_health_check_automatic_crashes, 0); + if (count != 0) { + storage.deleteAndSave(key_health_check_automatic_crashes); + } + return Math.max(count, 0); + } + } + @Override public boolean isCountlyStorageEmpty() { String[] files = getCountlyFileList(config); diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/SessionImpl.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/SessionImpl.java index 295bbe7b4..49c549efb 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/SessionImpl.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/SessionImpl.java @@ -71,11 +71,11 @@ public class SessionImpl implements Session, Storable, EventImpl.EventRecorder { private boolean pushOnChange = true; /** - * Create session with current time as id. + * Create session with a new storage id based on the current time. */ protected SessionImpl(final InternalConfig config) { L = config.getLogger(); - this.id = TimeUtils.uniqueTimestampMs(); + this.id = TimeUtils.uniqueStorageId(); this.config = config; } @@ -85,7 +85,7 @@ protected SessionImpl(final InternalConfig config) { public SessionImpl(final InternalConfig config, Long id) { L = config.getLogger(); this.config = config; - this.id = id == null ? TimeUtils.uniqueTimestampMs() : id; + this.id = id == null ? TimeUtils.uniqueStorageId() : id; if (SDKCore.instance != null) { this.consents = SDKCore.instance.consents; } @@ -99,34 +99,53 @@ public Session begin() { } L.d("[SessionImpl] begin"); + L.recordUsage(HealthCheckCounter.AREA_SESSIONS, "begin"); begin(null); return this; } + /** + * Begins the session on the SDK's own behalf, counted as "begin:a" in the health check. + */ + void beginAutomatically() { + if (config.isBackendModeEnabled()) { + L.w("[SessionImpl] beginAutomatically: Skipping session begin, backend mode is enabled!"); + return; + } + + L.d("[SessionImpl] beginAutomatically"); + L.recordUsage(HealthCheckCounter.AREA_SESSIONS, "begin:a"); + begin(null); + } + Future begin(Long now) { if (SDKCore.instance == null) { - L.e("[SessionImpl] Countly is not initialized"); + L.w("[SessionImpl] Countly is not initialized"); + Log.recordLogCodeWhileNotInitialized("w101"); + return null; + } else if (!isSessionTrackingEnabled("begin")) { return null; } else if (began != null) { - L.e("[SessionImpl] Session already began"); + L.w("[SessionImpl] Session already began"); + L.recordLogCode("w760", HealthCheckCounter.AREA_SESSIONS); return null; } else if (ended != null) { - L.e("[SessionImpl] Session already ended"); + L.w("[SessionImpl] Session already ended"); + L.recordLogCode("w760", HealthCheckCounter.AREA_SESSIONS); return null; } else { began = now == null ? System.nanoTime() : now; } this.consents = SDKCore.instance.consents; - if (config.isAutoSendUserProperties() && config.sdk.userProfile() != null) { - config.sdk.module(ModuleUserProfile.class).saveInternal(); - } + ModuleUserProfile.saveIfSentAutomatically(config); if (pushOnChange) { Storage.pushAsync(config, this); } - if (hasConsent(CoreFeature.Location) && config.sdk.module(ModuleLocation.class) != null) { - params.add(config.sdk.module(ModuleLocation.class).prepareLocationParams()); + ModuleLocation locationModule = config.sdk.module(ModuleLocation.class); + if (hasConsent(CoreFeature.Location) && locationModule != null && config.getConfigurationProvider().getLocationTrackingEnabled()) { + params.add(locationModule.prepareLocationParams()); } Future ret = ModuleRequests.sessionBegin(config, this); @@ -143,26 +162,44 @@ public Session update() { } L.d("[SessionImpl] update"); + L.recordUsage(HealthCheckCounter.AREA_SESSIONS, "update"); update(null); return this; } + /** + * Updates the running session on the SDK's own behalf, from the update timer, counted as + * "update:a" in the health check. A session that does not run is left alone. + */ + void updateAutomatically() { + if (config.isBackendModeEnabled() || !isActive()) { + return; + } + + L.d("[SessionImpl] updateAutomatically"); + L.recordUsage(HealthCheckCounter.AREA_SESSIONS, "update:a"); + update(null); + } + Future update(Long now) { if (SDKCore.instance == null) { - L.e("[SessionImpl] Countly is not initialized"); + L.w("[SessionImpl] Countly is not initialized"); + Log.recordLogCodeWhileNotInitialized("w101"); + return null; + } else if (!isSessionTrackingEnabled("update")) { return null; } else if (began == null) { - L.e("[SessionImpl] Session is not began to update it"); + L.w("[SessionImpl] Session is not began to update it"); + L.recordLogCode("w760", HealthCheckCounter.AREA_SESSIONS); return null; } else if (ended != null) { - L.e("[SessionImpl] Session is already ended to update it"); + L.w("[SessionImpl] Session is already ended to update it"); + L.recordLogCode("w760", HealthCheckCounter.AREA_SESSIONS); return null; } this.consents = SDKCore.instance.consents; - if (config.isAutoSendUserProperties() && config.sdk.userProfile() != null) { - config.sdk.module(ModuleUserProfile.class).saveInternal(); - } + ModuleUserProfile.saveIfSentAutomatically(config); Long duration = updateDuration(now); @@ -181,26 +218,49 @@ public void end() { } L.d("[SessionImpl] end"); + L.recordUsage(HealthCheckCounter.AREA_SESSIONS, "end"); end(null, null, null); } + /** + * Ends the session on the SDK's own behalf, counted as "end:a" in the health check. + * + * @param now the time the session ends at, {@code null} for now + * @param callback called once the end request is handled, {@code null} for none + * @param did the device ID the session belongs to, {@code null} for the current one + * @return the end request, {@code null} when nothing was sent + */ + Future endAutomatically(Long now, final Tasks.Callback callback, String did) { + if (config.isBackendModeEnabled()) { + L.w("[SessionImpl] endAutomatically: Skipping session end, backend mode is enabled!"); + return null; + } + + L.d("[SessionImpl] endAutomatically"); + L.recordUsage(HealthCheckCounter.AREA_SESSIONS, "end:a"); + return end(now, callback, did); + } + Future end(Long now, final Tasks.Callback callback, String did) { if (SDKCore.instance == null) { - L.e("[SessionImpl] Countly is not initialized"); + L.w("[SessionImpl] Countly is not initialized"); + Log.recordLogCodeWhileNotInitialized("w101"); + return null; + } else if (!isSessionTrackingEnabled("end")) { return null; } else if (began == null) { - L.e("[SessionImpl] Session is not began to end it"); + L.w("[SessionImpl] Session is not began to end it"); + L.recordLogCode("w760", HealthCheckCounter.AREA_SESSIONS); return null; } else if (ended != null) { - L.e("[SessionImpl] Session already ended"); + L.w("[SessionImpl] Session already ended"); + L.recordLogCode("w760", HealthCheckCounter.AREA_SESSIONS); return null; } ended = now == null ? System.nanoTime() : now; this.consents = SDKCore.instance.consents; - if (config.isAutoSendUserProperties() && config.sdk.userProfile() != null) { - config.sdk.module(ModuleUserProfile.class).saveInternal(); - } + ModuleUserProfile.saveIfSentAutomatically(config); if (currentView != null) { currentView.stop(true); @@ -222,18 +282,30 @@ Future end(Long now, final Tasks.Callback callback, String did return ret; } + /** + * Ends a session left on disk by an earlier run, or removes it when there is nothing to end. + * While session tracking is disabled by the SDK behavior settings, no session request may be + * sent, so an unended session is removed without an end request: keeping it would end it on a + * later run with a stale duration. + * + * @param config configuration of the SDK being initialized + * @return whether the session was ended or removed, {@code null} when it is left as it is + */ Boolean recover(InternalConfig config) { Log L = config.getLogger(); if ((System.currentTimeMillis() - id) < 0) { return null; + } else if (!config.getConfigurationProvider().getSessionTrackingEnabled()) { + L.d("[SessionImpl] recover, session tracking is disabled by the SDK behavior settings, removing session " + id + " without ending it"); + return Storage.remove(config, this); } else { Future future; if (began == null) { return Storage.remove(config, this); } else if (ended == null && updated == null) { - future = end(began, null, null); + future = endAutomatically(began, null, null); } else if (ended == null) { - future = end(updated, null, null); + future = endAutomatically(updated, null, null); } else { // began != null && ended != null return Storage.remove(config, this); @@ -260,6 +332,22 @@ public boolean isActive() { return began != null && ended == null; } + /** + * Whether the SDK behavior settings allow session tracking. While they do not, beginning, + * updating and ending a session are ignored, and the session keeps its state. + * + * @param function the ignored call, for the log + * @return {@code true} when session tracking is enabled + */ + private boolean isSessionTrackingEnabled(String function) { + if (config.getConfigurationProvider().getSessionTrackingEnabled()) { + return true; + } + + L.d("[SessionImpl] " + function + ", session tracking is disabled by the SDK behavior settings, ignoring the call"); + return false; + } + /** * Calculate time since last {@link #update()} or since {@link #begin()} if no {@link #update()} yet made, * set {@link #updated} to now. @@ -289,6 +377,9 @@ public Event event(String key) { * @deprecated use {@link ModuleEvents.Events#startEvent(String)}} instead via instance().events() call */ public Event timedEvent(String key) { + L.w("[SessionImpl] timedEvent, this function is deprecated, use 'events().startEvent' instead"); + L.recordLogCode("w120"); + L.recordUsage(HealthCheckCounter.AREA_EVENTS, "timedEvent:d"); return timedEvents().event(config, key); } @@ -308,14 +399,14 @@ protected TimedEvents timedEvents() { */ @Override public void recordEvent(Event event) { - L.d("[SessionImpl] recordEvent: " + event.toString()); if (!SDKCore.enabled(CoreFeature.Events)) { L.i("[SessionImpl] recordEvent: Skipping event - feature is not enabled"); return; } + L.d("[SessionImpl] recordEvent"); if (began == null) { - begin(); + beginAutomatically(); } ModuleEvents eventsModule = (ModuleEvents) SDKCore.instance.module(CoreFeature.Events); @@ -345,6 +436,10 @@ public Session addCrashReport(Throwable t, boolean fatal, String name, Map crashSegments = null; @@ -368,11 +463,11 @@ public Session addLocation(double latitude, double longitude) { return this; } - L.d("[SessionImpl] addLocation: latitude = " + latitude + " longitude = " + longitude); if (!SDKCore.enabled(CoreFeature.Location)) { L.i("[SessionImpl] addLocation: Skipping event - feature is not enabled"); return this; } + L.d("[SessionImpl] addLocation"); Countly.instance().location().setLocation(null, null, latitude + "," + longitude, null); return this; } @@ -386,11 +481,14 @@ public Session addLocation(double latitude, double longitude) { * @deprecated use {@link ModuleViews.Views#startView(String)} instead via {@link Countly#views()} */ public View view(String name, boolean start) { - L.d("[SessionImpl] view: name = " + name + " start = " + start); if (!SDKCore.enabled(CoreFeature.Views)) { L.i("[SessionImpl] view: Skipping view - feature is not enabled"); return null; } + L.d("[SessionImpl] view: start = " + start); + L.w("[SessionImpl] view, this function is deprecated, use 'views().startView' instead"); + L.recordLogCode("w120"); + L.recordUsage(HealthCheckCounter.AREA_VIEWS, "view:d"); if (currentView != null) { currentView.stop(false); } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/Storage.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/Storage.java index 255529b36..48f0011a1 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/Storage.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/Storage.java @@ -2,6 +2,7 @@ import java.util.List; import java.util.Map; +import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -184,6 +185,28 @@ public Boolean call() throws Exception { return false; } + /** + * Runs a job on the storage thread and waits for it, so no other storage task reads or changes + * the stored files while the job runs. + * + * @param config to configure + * @param job the job to run + * @return the result of the job, {@code null} when it failed or the wait was interrupted + */ + static T runAndWait(final InternalConfig config, final Callable job) { + try { + return tasks.run(new Tasks.Task(Tasks.ID_STRICT) { + @Override + public T call() throws Exception { + return job.call(); + } + }).get(); + } catch (InterruptedException | ExecutionException e) { + config.getLogger().e("[Storage] runAndWait, the storage job failed, [" + e + "]"); + } + return null; + } + /** * Reinitializes storable with data stored previously in device internal memory. * @@ -228,8 +251,11 @@ public static Future readAsync(final InternalConfig conf public T call() throws Exception { Boolean done = config.sdk.sdkStorage.storableRead(config, storable); T ret = null; - if (done == null || !done) { - config.getLogger().e("[Storage] No data for file " + name(storable)); + if (done == null) { + //every storable starts without a file, and one that could not be read was logged as an error already + config.getLogger().d("[Storage] No data for file " + name(storable)); + } else if (!done) { + config.getLogger().e("[Storage] Could not restore the data of file " + name(storable)); } else { ret = storable; } 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 1983dd7aa..4b82010b5 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 @@ -69,4 +69,59 @@ public interface StorageProvider { * @return true if empty, false otherwise */ boolean isCountlyStorageEmpty(); + + /** + * Persist the most-recently-validated SDK behavior settings JSON. + * + * @param config serialized configuration object, or {@code null} to clear + */ + void setServerConfig(String config); + + /** + * Read the persisted SDK behavior settings JSON. + * + * @return serialized configuration, or {@code null} if none persisted yet + */ + String getServerConfig(); + + /** + * Read the stored health check counters. + * + * @return the counters as JSON text, {@code null} or empty when none are stored + */ + String getHealthCheckState(); + + /** + * Store the health check counters. + * + * @param state the counters as JSON text, empty to clear them + */ + 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. + */ + void incrementAutomaticCrashCount(); + + /** + * Read the automatically detected crashes counted since the last call, and set the stored count back to 0. + * + * @return the stored count of automatically detected crashes + */ + int takeAutomaticCrashCount(); } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/TimeUtils.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/TimeUtils.java index d5d460df5..5edac50d4 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/TimeUtils.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/TimeUtils.java @@ -72,6 +72,18 @@ public static synchronized long uniqueTimestampS() { return uniqueTimestampMs() / MS_IN_SECOND; } + /** + * Returns the id of a new stored request, session or crash, from {@link UniqueTimeGenerator#id()}. + * The id names the file the object is stored in, orders the request queue and keys the storage + * task that writes it, so two objects with one id would share a file or a task and one of them + * would be lost. + * + * @return a new storage id + */ + public static synchronized long uniqueStorageId() { + return uniqueTimer.id(); + } + /** * Wraps {@link System#currentTimeMillis()} and returns it * diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/Transport.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/Transport.java index e745e30bf..3bd05c6e0 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/Transport.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/Transport.java @@ -30,6 +30,9 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.Future; +import java.util.function.LongConsumer; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; @@ -52,9 +55,16 @@ //class Network extends ModuleBase { - may be public class Transport implements X509TrustManager { + /** + * The response code handed to the module that owns a request when an attempt to send it ended + * before any response arrived. + */ + static final int NO_RESPONSE_CODE = -1; + private Log L = null; private static final String PARAMETER_TAMPERING_DIGEST = "SHA-256"; private static final String CHECKSUM = "checksum256"; + static final String REQUEST_COMPRESSION_MARKER = "content_encoding=gzip"; private InternalConfig config; private SSLContext sslContext; // ssl context to use if pinning is enabled @@ -132,33 +142,41 @@ HttpURLConnection connection(final Request request) throws IOException { endpoint = "/i?"; } - String path = config.getServerURL().toString() + endpoint; + URL serverUrl = config.getServerURL(); + String path = serverUrl.toString() + endpoint; byte[] maybePictureData = getPictureDataFromRequest(request); - boolean usingGET = !config.isHTTPPostForced() && request.isGettable(config.getServerURL()) && maybePictureData == null; + boolean usingGET = !config.isHTTPPostForced() && request.isGettable(serverUrl) && maybePictureData == null; if (usingGET && config.getParameterTamperingProtectionSalt() != null) { request.params.add(CHECKSUM, Utils.digestHex(PARAMETER_TAMPERING_DIGEST, request.params + config.getParameterTamperingProtectionSalt(), L)); } + byte[] compressedBody = new byte[0]; + if (!usingGET && maybePictureData == null) { + if (config.getParameterTamperingProtectionSalt() != null) { + request.params.add(CHECKSUM, Utils.digestHex(PARAMETER_TAMPERING_DIGEST, request.params + config.getParameterTamperingProtectionSalt(), L)); + } + String markedPath = compressedRequestPath(path); + if (markedPath != null && config.getConfigurationProvider().isRequestCompressionAllowed()) { + String body = request.params.toString(); + compressedBody = Utils.gzipRequestBody(body, L); + if (compressedBody.length > 0) { + path = markedPath; + L.d("[Transport] connection, the request body is sent gzip-compressed, [" + body.length() + "] -> [" + compressedBody.length + "] bytes"); + } + } + } + HttpURLConnection connection = openConnection(path, request.params.toString(), usingGET); connection.setConnectTimeout(1000 * config.getNetworkConnectionTimeout()); connection.setReadTimeout(1000 * config.getNetworkReadTimeout()); - if (connection instanceof HttpsURLConnection && sslContext != null) { - HttpsURLConnection https = (HttpsURLConnection) connection; - https.setSSLSocketFactory(sslContext.getSocketFactory()); - } + usePinningSocketFactory(connection); if (config.getCustomNetworkRequestHeaders() != null) { //if there are custom header values, add them - L.v("[Transport] connection, Adding [" + config.getCustomNetworkRequestHeaders() + "] custom header fields"); - for (Map.Entry entry : config.getCustomNetworkRequestHeaders().entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); - if (key != null && value != null && !key.isEmpty()) { - connection.addRequestProperty(key, value); - } - } + L.v("[Transport] connection, Adding [" + config.getCustomNetworkRequestHeaders().size() + "] custom header fields"); + addCustomRequestHeaders(connection); } if (!usingGET) { @@ -190,17 +208,19 @@ HttpURLConnection connection(final Request request) throws IOException { writer.append("--").append(boundary).append("--").append(Utils.CRLF).flush(); } else { //picture data is "null". If it was sent, we send "null" to server to clear the image there - //we send a normal request in HTTP POST - if (config.getParameterTamperingProtectionSalt() != null) { - request.params.add(CHECKSUM, Utils.digestHex(PARAMETER_TAMPERING_DIGEST, request.params + config.getParameterTamperingProtectionSalt(), L)); - } + //we send a normal request in HTTP POST, its checksum was added above connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); output = connection.getOutputStream(); - writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true); + if (compressedBody.length > 0) { + output.write(compressedBody); + output.flush(); + } else { + writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true); - writer.write(request.params.toString()); - writer.flush(); + writer.write(request.params.toString()); + writer.flush(); + } } } finally { if (writer != null) { @@ -221,6 +241,118 @@ HttpURLConnection connection(final Request request) throws IOException { return connection; } + /** + * The URL a compressed request goes to: the request URL with the compression marker as its only + * query. Endpoints end with an empty query, as in {@code /i?}, which the marker fills. + * + * @param url the URL the request goes to + * @return the URL with the marker, or {@code null} when the URL already has a query, where the + * marker could not be the only one + */ + static String compressedRequestPath(@Nonnull String url) { + int query = url.indexOf('?'); + if (query == -1) { + return url + "?" + REQUEST_COMPRESSION_MARKER; + } + return query == url.length() - 1 ? url + REQUEST_COMPRESSION_MARKER : null; + } + + /** + * Tells whether a connection made by {@link #connection(Request)} sends its body gzip-compressed. + * + * @param connection the connection + * @return {@code true} when its URL carries the compression marker as its query + */ + static boolean isCompressedRequest(@Nullable HttpURLConnection connection) { + return connection != null && REQUEST_COMPRESSION_MARKER.equals(connection.getURL().getQuery()); + } + + /** + * Stops request compression when the connection sent a compressed body; called after its answer + * was not accepted. + * + * @param connection the connection whose answer was not accepted + */ + void blockCompressionIfCompressed(@Nullable HttpURLConnection connection) { + if (isCompressedRequest(connection)) { + config.getConfigurationProvider().blockRequestCompression(); + } + } + + /** + * Opens the GET of one connection test probe: a bare request, built as + * {@link #openBareGetConnection(String, int)} builds it, that verifies the server against the + * configured pins and carries the custom request headers, as every queued request does. Nothing + * is sent before the response is read. + * + * @param url the probe URL + * @param timeoutMs the connect and the read timeout, in milliseconds + * @return the connection, not connected yet + * @throws IOException when the connection cannot be opened + */ + HttpURLConnection openProbeConnection(@Nonnull String url, int timeoutMs) throws IOException { + HttpURLConnection connection = openBareGetConnection(url, timeoutMs); + usePinningSocketFactory(connection); + addCustomRequestHeaders(connection); + return connection; + } + + /** + * Opens a GET that carries nothing but its URL, follows no redirect and uses no cache. The + * redirect setting is made on this connection only, never through the default of every + * connection. + * + * @param url the URL + * @param timeoutMs the connect and the read timeout, in milliseconds + * @return the connection, not connected yet + * @throws IOException when the connection cannot be opened + */ + static HttpURLConnection openBareGetConnection(@Nonnull String url, int timeoutMs) throws IOException { + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setRequestMethod("GET"); + connection.setInstanceFollowRedirects(false); + connection.setUseCaches(false); + connection.setConnectTimeout(timeoutMs); + connection.setReadTimeout(timeoutMs); + connection.setDoInput(true); + connection.setDoOutput(false); + return connection; + } + + /** + * Makes an HTTPS connection verify the server against the configured pins, when pins are + * configured. + * + * @param connection the connection, not connected yet + */ + private void usePinningSocketFactory(HttpURLConnection connection) { + if (connection instanceof HttpsURLConnection && sslContext != null) { + HttpsURLConnection https = (HttpsURLConnection) connection; + https.setSSLSocketFactory(sslContext.getSocketFactory()); + } + } + + /** + * Adds the custom request headers of the configuration, skipping any with a {@code null} or + * empty name or a {@code null} value. + * + * @param connection the connection, not connected yet + */ + private void addCustomRequestHeaders(HttpURLConnection connection) { + Map headers = config.getCustomNetworkRequestHeaders(); + if (headers == null) { + return; + } + + for (Map.Entry entry : headers.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (key != null && value != null && !key.isEmpty()) { + connection.addRequestProperty(key, value); + } + } + } + void addMultipart(OutputStream output, PrintWriter writer, final String boundary, final String contentType, final String name, final String value, final byte[] file) throws IOException { writer.append("--").append(boundary).append(Utils.CRLF); if (file != null) { @@ -300,27 +432,58 @@ String response(HttpURLConnection connection) { } } + /** + * Sends a request once and hands its response to the module that owns it. While the request + * carries a batch of gathered log lines, the sending thread is marked as doing their transport + * work, so nothing logged about the upload is gathered. + * + * @param request request to send + * @return the task sending the request, resolving to whether the server accepted it + */ public Tasks.Task send(final Request request) { + return send(request, null); + } + + /** + * Sends a request as {@link #send(Request)} does, and tells how long the server took to answer + * it: from opening the connection, which sends the request, to reading the whole response. + * + * @param request request to send + * @param responseTimeListener given the response time in milliseconds once a response was read, + * never called when none was; {@code null} for none + * @return the task sending the request, resolving to whether the server accepted it + */ + Tasks.Task send(final Request request, @Nullable final LongConsumer responseTimeListener) { return new Tasks.Task(request.storageId()) { @Override public Boolean call() { - return send(); + L.setOwnTransportWork(request.params.has(Log.keySdkLogs)); + try { + return send(); + } finally { + L.setOwnTransportWork(false); + } } public Boolean send() { L.i("[network] [send] Sending request: " + request); HttpURLConnection connection = null; + Class requestOwner = null; try { - Class requestOwner = request.owner(); + requestOwner = request.owner(); request.params.remove(Request.MODULE); + long sendStartNs = System.nanoTime(); connection = connection(request); connection.connect(); int code = connection.getResponseCode(); String response = response(connection); + if (responseTimeListener != null) { + responseTimeListener.accept((System.nanoTime() - sendStartNs) / 1_000_000L); + } try { if (request.params.has(Params.PARAM_OLD_DEVICE_ID) || request.params.has("token_session")) { @@ -338,9 +501,14 @@ public Boolean send() { SDKCore.instance.onRequestCompleted(request, response, code, requestOwner); - return processResponse(code, response, request.storageId()); + Boolean accepted = processResponse(code, response, request.storageId()); + if (!Boolean.TRUE.equals(accepted)) { + blockCompressionIfCompressed(connection); + } + return accepted; } catch (IOException e) { - L.w("[network] Error while sending request " + request + " " + e); + L.d("[network] Error while sending request " + request + " " + e); + notifyOwnerOfAttemptWithoutResponse(request, requestOwner); return false; } catch (Exception e) { L.e("[network] Unexpected error while sending request " + request + " " + e); @@ -354,25 +522,88 @@ public Boolean send() { }; } + /** + * Tells the module that owns a request that an attempt to send it ended before a response + * arrived, with a {@code null} response and {@link #NO_RESPONSE_CODE}. + * + * @param request the request + * @param requestOwner the module that owns it, {@code null} for none + */ + private void notifyOwnerOfAttemptWithoutResponse(Request request, Class requestOwner) { + SDKCore core = SDKCore.instance; + if (core == null || requestOwner == null) { + return; + } + + try { + core.onRequestCompleted(request, null, NO_RESPONSE_CODE, requestOwner); + } catch (Exception e) { + L.e("[network] Failed to tell the owner of request [" + request.storageId() + "] that it got no response, [" + e + "]"); + } + } + + /** + * Whether a response means the server accepted the request: a 2xx code and a JSON object body + * that has a {@code result}, the rule {@link #processResponse(int, String, Long)} applies. + * + * @param code the response code + * @param response the response body, {@code null} when none arrived + * @return {@code true} when the request was accepted + */ + static boolean isSuccessfulResponse(int code, String response) { + if (response == null) { + return false; + } + + try { + return isSuccessfulResponse(code, new JSONObject(response)); + } catch (Exception e) { + return false; + } + } + + /** + * Whether a parsed response means the server accepted the request. + * + * @param code the response code + * @param response the parsed response body + * @return {@code true} for a 2xx code with a {@code result} + */ + private static boolean isSuccessfulResponse(int code, JSONObject response) { + return code >= 200 && code < 300 && response.has("result"); + } + + /** + * Whether the server accepted a queued request. An answer it did not accept is kept for the + * health check, which reports the last one; a request without an answer changes nothing there. + * A failed request is logged at debug level, as the health check reports it on its own. + * + * @param code the response code + * @param response the response body, {@code null} when none could be read + * @param requestId the storage ID of the request, for the log + * @return {@code true} when the server accepted the request + */ Boolean processResponse(int code, String response, Long requestId) { L.i("[network] [processResponse] Code [" + code + "] response [" + response + "] for request[" + requestId + "]"); if (response == null) { - L.w("[network] Null response for request [" + requestId + "]"); + L.d("[network] Null response for request [" + requestId + "]"); return false; } try { JSONObject jsonObject = new JSONObject(response); - if (code >= 200 && code < 300 && jsonObject.has("result")) { + if (isSuccessfulResponse(code, jsonObject)) { L.d("[network] Success"); return true; } else { - L.w("[network] Fail: code :" + code + ", result: " + response); + L.d("[network] Fail: code :" + code + ", result: " + response); + L.logFailedNetworkRequest(code, response); return false; } } catch (Exception e) { - L.w("[network] Failed to parse response as JSON for request [" + requestId + "], response: [" + response + "], error: [" + e.getMessage() + "]"); + L.d("[network] Failed to parse response as JSON for request [" + requestId + "], response: [" + response + "], error: [" + e.getMessage() + "]"); + L.logFailedNetworkRequest(code, response); return false; } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/UniqueTimeGenerator.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/UniqueTimeGenerator.java index 40d70d3b1..2454c9aa9 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/UniqueTimeGenerator.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/UniqueTimeGenerator.java @@ -10,6 +10,7 @@ class UniqueTimeGenerator { final List lastTsMs = new ArrayList<>(10); long addition = 0; + long lastId = 0; long currentTimeMillis() { return System.currentTimeMillis() + addition; @@ -37,4 +38,17 @@ public synchronized long timestamp() { lastTsMs.add(ms); return ms; } + + /** + * Returns the current time in milliseconds, or one more than the previous id while the clock + * has not moved past it. Unlike {@link #timestamp()}, which only remembers its last 10 values, + * an id never repeats or goes back within a process, not in a burst and not after the clock is + * set back. + * + * @return an id greater than every id returned before + */ + synchronized long id() { + lastId = Math.max(currentTimeMillis(), lastId + 1); + return lastId; + } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/UserEditorImpl.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/UserEditorImpl.java index 33e586cca..ca8eda24f 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/UserEditorImpl.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/UserEditorImpl.java @@ -1,6 +1,7 @@ package ly.count.sdk.java.internal; import java.io.File; +import java.util.function.Consumer; import ly.count.sdk.java.Countly; import ly.count.sdk.java.PredefinedUserPropertyKeys; import ly.count.sdk.java.User; @@ -100,68 +101,70 @@ public UserEditor setBirthyear(String birthyear) { @Override public UserEditor setLocale(String locale) { - L.d("setLocale: locale = " + locale); + L.d("[UserEditorImpl] setLocale"); return this; } @Override public UserEditor setCountry(String country) { - L.d("setCountry: country = " + country); + L.d("[UserEditorImpl] setCountry"); String countryLegacy = country == null ? JSONObject.NULL.toString() : country; - callLocationService(() -> SDKCore.instance.module(ModuleLocation.class).setLocationLegacy(countryLegacy, null, null)); + callLocationService(module -> module.setLocationLegacy(countryLegacy, null, null)); return this; } @Override public UserEditor setCity(String city) { - L.d("setCity: city = " + city); + L.d("[UserEditorImpl] setCity"); String cityLegacy = city == null ? JSONObject.NULL.toString() : city; - callLocationService(() -> SDKCore.instance.module(ModuleLocation.class).setLocationLegacy(null, cityLegacy, null)); + callLocationService(module -> module.setLocationLegacy(null, cityLegacy, null)); return this; } @Override public UserEditor setLocation(String location) { - L.d("setLocation: location = " + location); + L.d("[UserEditorImpl] setLocation"); if (location != null) { String[] comps = location.split(","); if (comps.length == 2) { try { String locationString = Double.parseDouble(comps[0]) + "," + Double.parseDouble(comps[1]); - callLocationService(() -> SDKCore.instance.module(ModuleLocation.class).setLocationLegacy(null, null, locationString)); + callLocationService(module -> module.setLocationLegacy(null, null, locationString)); return this; } catch (Throwable t) { - L.e("[UserEditorImpl] Invalid location format: " + location + " " + t); + L.e("[UserEditorImpl] setLocation, invalid location format, " + t.getClass().getSimpleName()); return this; } } else { - L.e("[UserEditorImpl] Invalid location format: " + location); + L.e("[UserEditorImpl] setLocation, invalid location format"); return this; } } else { - callLocationService(() -> SDKCore.instance.module(ModuleLocation.class).setLocationLegacy(null, null, JSONObject.NULL)); + callLocationService(module -> module.setLocationLegacy(null, null, JSONObject.NULL)); return this; } } @Override public UserEditor setLocation(double latitude, double longitude) { - L.d("setLocation: latitude = " + latitude + " longitude" + longitude); + L.d("[UserEditorImpl] setLocation"); String locationString = latitude + "," + longitude; - callLocationService(() -> SDKCore.instance.module(ModuleLocation.class).setLocationLegacy(null, null, locationString)); + callLocationService(module -> module.setLocationLegacy(null, null, locationString)); return this; } @Override public UserEditor optOutFromLocationServices() { L.d("optOutFromLocationServices"); - callLocationService(() -> SDKCore.instance.module(ModuleLocation.class).setLocationLegacy(JSONObject.NULL, JSONObject.NULL, JSONObject.NULL)); + callLocationService(module -> module.setLocationLegacy(JSONObject.NULL, JSONObject.NULL, JSONObject.NULL)); return this; } - private void callLocationService(Runnable runnable) { - if (Countly.instance().location() != null) { - runnable.run(); + private void callLocationService(Consumer call) { + SDKCore core = SDKCore.instance; + ModuleLocation location = core == null ? null : core.runningModule(CoreFeature.Location, ModuleLocation.class); + if (location != null) { + call.accept(location); } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/Utils.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/Utils.java index 20e784a6f..51b4785b8 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/Utils.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/Utils.java @@ -22,6 +22,7 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; +import java.util.zip.GZIPOutputStream; /** * Utility class @@ -31,6 +32,9 @@ public class Utils { public static final String UTF8 = "UTF-8"; public static final String CRLF = "\r\n"; public static final char[] BASE_16 = "0123456789ABCDEF".toCharArray(); + static final int REQUEST_COMPRESSION_MIN_BYTES = 1024; + // the server refuses a compressed body that is larger than this once decoded + static final int REQUEST_COMPRESSION_MAX_BYTES = 1024 * 1024; /** * Joins objects with a separator @@ -183,6 +187,33 @@ public static String digestHex(final String digestName, final String string, Log } } + /** + * Compresses a request body with gzip, for sending it with the compression marker as the URL query. + * + * @param body the url encoded request body, checksum included + * @param L logger + * @return the gzip bytes, or an empty array when the body is smaller than + * {@link #REQUEST_COMPRESSION_MIN_BYTES} or larger than {@link #REQUEST_COMPRESSION_MAX_BYTES}, + * compressing fails, or the result is not smaller than the body + */ + static byte[] gzipRequestBody(String body, Log L) { + byte[] plain = body.getBytes(StandardCharsets.UTF_8); + if (plain.length < REQUEST_COMPRESSION_MIN_BYTES || plain.length > REQUEST_COMPRESSION_MAX_BYTES) { + return new byte[0]; + } + + ByteArrayOutputStream out = new ByteArrayOutputStream(plain.length / 2); + try (GZIPOutputStream gzip = new GZIPOutputStream(out)) { + gzip.write(plain); + } catch (IOException e) { + L.d("[Utils] gzipRequestBody, compressing failed, the body is sent uncompressed: [" + e + "]"); + return new byte[0]; + } + + byte[] compressed = out.toByteArray(); + return compressed.length < plain.length ? compressed : new byte[0]; + } + /** * Get hexadecimal string representation of a byte array * @@ -423,6 +454,7 @@ public static void removeInvalidDataFromSegments(Map segments, L toRemove.forEach(key -> { L.w("[Utils] removeInvalidDataFromSegments, In segmentation Data type '" + segments.get(key) + "' of item '" + key + "' isn't valid."); + L.recordLogCode("w206"); segments.remove(key); }); } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/UtilsInternalLimits.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/UtilsInternalLimits.java new file mode 100644 index 000000000..9810b2d56 --- /dev/null +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/UtilsInternalLimits.java @@ -0,0 +1,312 @@ +package ly.count.sdk.java.internal; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * Applies the SDK internal limits of the SDK behavior settings: the key length {@code lkl}, the value + * size {@code lvs}, the number of segmentation entries {@code lsv}, the stack trace lines per thread + * {@code ltlpt} and the stack trace line length {@code ltl}. {@link Integer#MAX_VALUE} is no limit, + * and whatever no limit cuts is returned as the same instance. + *

+ * A map is never changed in place. One that has to change is rebuilt in sorted key order, so the + * outcome never depends on the order of the map: when two keys are cut to the same key the one that + * sorts last keeps its value, and over the entry limit the entries whose keys sort first are kept. + * Strings are cut in UTF-16 characters and never inside a surrogate pair. Every cut is logged as a + * warning that names the caller. + */ +final class UtilsInternalLimits { + + /** + * The order every limit walks keys in, a {@code null} key first. + */ + private static final Comparator KEY_ORDER = Comparator.nullsFirst(Comparator.naturalOrder()); + + /** + * Not instantiated: the limits are static helpers. + */ + private UtilsInternalLimits() { + } + + /** + * Cuts a key to the key length limit, {@code lkl}: an event key, a view name, a segmentation key + * or a custom user property key. + * + * @param key the key, {@code null} for none + * @param maxKeyLength the limit + * @param L logger + * @param tag the caller, for the log + * @return the key, cut when it is longer than the limit + */ + @Nullable + static String truncateKey(@Nullable String key, int maxKeyLength, @Nonnull Log L, @Nonnull String tag) { + if (key == null || key.length() <= maxKeyLength) { + return key; + } + + String truncated = truncate(key, maxKeyLength); + L.w(tag + ", the key [" + key + "] is longer than the key length limit of [" + maxKeyLength + "] of the SDK behavior settings, it is truncated to [" + truncated + "]"); + L.recordLogCode("w201"); + return truncated; + } + + /** + * Cuts a string value to the value size limit, {@code lvs}. + * + * @param value the value, {@code null} for none + * @param maxValueSize the limit + * @param L logger + * @param tag the caller, for the log + * @return the value, cut when it is longer than the limit + */ + @Nullable + static String truncateValue(@Nullable String value, int maxValueSize, @Nonnull Log L, @Nonnull String tag) { + if (value == null || value.length() <= maxValueSize) { + return value; + } + + String truncated = truncate(value, maxValueSize); + L.w(tag + ", a value of [" + value.length() + "] characters is longer than the value size limit of [" + maxValueSize + "] of the SDK behavior settings, it is truncated to [" + truncated + "]"); + L.recordLogCode("w202"); + return truncated; + } + + /** + * Cuts a value to the value size limit, {@code lvs}, when it is a string. A value of any other + * type is returned as it is, strings inside arrays included. + * + * @param value the value, {@code null} for none + * @param maxValueSize the limit + * @param L logger + * @param tag the caller, for the log + * @return the value, cut when it is a string longer than the limit + */ + @Nullable + static Object truncateIfString(@Nullable Object value, int maxValueSize, @Nonnull Log L, @Nonnull String tag) { + if (value instanceof String) { + return truncateValue((String) value, maxValueSize, L, tag); + } + return value; + } + + /** + * Applies the key length, value size and segmentation entry limits, {@code lkl}, {@code lvs} and + * {@code lsv}, to a segmentation. Keys and values are cut first, so two keys that end up the same + * are counted once. + * + * @param segmentation the segmentation, {@code null} for none, never changed + * @param limits the settings in effect + * @param L logger + * @param tag the caller, for the log + * @return the segmentation within the limits, the same instance when it already was + */ + @Nullable + static Map applySegmentationLimits(@Nullable Map segmentation, @Nonnull ConfigurationProvider limits, @Nonnull Log L, @Nonnull String tag) { + Map truncated = truncateSegmentationKeysAndValues(segmentation, limits.getMaxKeyLength(), limits.getMaxValueSize(), L, tag); + return limitSegmentationEntries(truncated, limits.getMaxSegmentationValues(), L, tag); + } + + /** + * Cuts the keys of a segmentation to the key length limit, {@code lkl}, and its string values to + * the value size limit, {@code lvs}. When two keys are cut to the same key, the entry whose key + * sorts last keeps its value. + * + * @param segmentation the segmentation, {@code null} for none, never changed + * @param maxKeyLength the key length limit + * @param maxValueSize the value size limit + * @param L logger + * @param tag the caller, for the log + * @return a copy in sorted key order when a key or a value was cut, otherwise the same instance + */ + @Nullable + static Map truncateSegmentationKeysAndValues(@Nullable Map segmentation, int maxKeyLength, int maxValueSize, @Nonnull Log L, @Nonnull String tag) { + if (segmentation == null || !exceedsKeyOrValueLimit(segmentation, maxKeyLength, maxValueSize)) { + return segmentation; + } + + Map truncated = new LinkedHashMap<>(); + for (String key : sortedKeys(segmentation.keySet())) { + String truncatedKey = truncateKey(key, maxKeyLength, L, tag); + if (truncated.containsKey(truncatedKey)) { + L.w(tag + ", the key [" + key + "] is truncated to the key of another segmentation entry, its value replaces that of [" + truncatedKey + "]"); + } + truncated.put(truncatedKey, truncateIfString(segmentation.get(key), maxValueSize, L, tag)); + } + return truncated; + } + + /** + * Keeps a segmentation within the segmentation entry limit, {@code lsv}, by keeping the entries + * whose keys sort first. + * + * @param segmentation the segmentation, {@code null} for none, never changed + * @param maxSegmentationValues the limit + * @param L logger + * @param tag the caller, for the log + * @return a copy in sorted key order when entries were dropped, otherwise the same instance + */ + @Nullable + static Map limitSegmentationEntries(@Nullable Map segmentation, int maxSegmentationValues, @Nonnull Log L, @Nonnull String tag) { + if (segmentation == null || segmentation.size() <= maxSegmentationValues) { + return segmentation; + } + + List keys = sortedKeys(segmentation.keySet()); + Map kept = new LinkedHashMap<>(); + for (String key : keys.subList(0, maxSegmentationValues)) { + kept.put(key, segmentation.get(key)); + } + + L.w(tag + ", the segmentation has [" + keys.size() + "] entries, over the limit of [" + maxSegmentationValues + "] of the SDK behavior settings, dropped the entries of the keys that sort last: " + keys.subList(maxSegmentationValues, keys.size())); + L.recordLogCode("w203"); + return kept; + } + + /** + * Cuts the string values of a map to the value size limit, {@code lvs}, leaving its keys and its + * number of entries as they are. + * + * @param map the map, never changed + * @param maxValueSize the limit + * @param L logger + * @param tag the caller, for the log + * @return a copy in the order of the map when a value was cut, otherwise the same instance + */ + @Nonnull + static Map truncateStringValues(@Nonnull Map map, int maxValueSize, @Nonnull Log L, @Nonnull String tag) { + if (!exceedsKeyOrValueLimit(map, Integer.MAX_VALUE, maxValueSize)) { + return map; + } + + Map truncated = new LinkedHashMap<>(); + for (Map.Entry entry : map.entrySet()) { + truncated.put(entry.getKey(), truncateIfString(entry.getValue(), maxValueSize, L, tag)); + } + return truncated; + } + + /** + * Cuts every line of a stack trace to the stack trace line length limit, {@code ltl}. Line breaks, + * {@code \n} or {@code \r\n}, are kept as they are and do not count as characters of the line. + * + * @param stackTrace the stack trace + * @param maxLineLength the limit + * @param L logger + * @param tag the caller, for the log + * @return the stack trace, a new one when a line was cut + */ + @Nonnull + static String truncateStackTraceLines(@Nonnull String stackTrace, int maxLineLength, @Nonnull Log L, @Nonnull String tag) { + StringBuilder truncated = null; + int truncatedLines = 0; + int lineStart = 0; + while (lineStart < stackTrace.length()) { + int lineBreak = stackTrace.indexOf('\n', lineStart); + int nextLineStart = lineBreak < 0 ? stackTrace.length() : lineBreak + 1; + int lineEnd = lineBreak < 0 ? stackTrace.length() : lineBreak; + if (lineEnd > lineStart && stackTrace.charAt(lineEnd - 1) == '\r') { + lineEnd--; + } + + if (lineEnd - lineStart > maxLineLength) { + if (truncated == null) { + truncated = new StringBuilder(stackTrace.length()); + truncated.append(stackTrace, 0, lineStart); + } + truncated.append(truncate(stackTrace.substring(lineStart, lineEnd), maxLineLength)).append(stackTrace, lineEnd, nextLineStart); + truncatedLines++; + } else if (truncated != null) { + truncated.append(stackTrace, lineStart, nextLineStart); + } + lineStart = nextLineStart; + } + + if (truncated == null) { + return stackTrace; + } + + L.w(tag + ", [" + truncatedLines + "] stack trace lines are longer than the line length limit of [" + maxLineLength + "] of the SDK behavior settings, they are truncated"); + L.recordLogCode("w205"); + return truncated.toString(); + } + + /** + * How many lines of the stack trace of one thread the stack trace lines per thread limit, + * {@code ltlpt}, keeps: the top ones. + * + * @param lineCount the number of lines of the stack trace + * @param maxLinesPerThread the limit + * @param threadName the thread, for the log + * @param L logger + * @param tag the caller, for the log + * @return the number of top lines to keep + */ + static int stackTraceLinesToKeep(int lineCount, int maxLinesPerThread, @Nullable String threadName, @Nonnull Log L, @Nonnull String tag) { + if (lineCount <= maxLinesPerThread) { + return lineCount; + } + + L.w(tag + ", the stack trace of the thread [" + threadName + "] has [" + lineCount + "] lines, over the limit of [" + maxLinesPerThread + "] lines per thread of the SDK behavior settings, dropped the bottom ones"); + L.recordLogCode("w205"); + return maxLinesPerThread; + } + + /** + * Whether a key of a map is longer than a key length limit or one of its string values is longer + * than a value size limit. + * + * @param map the map + * @param maxKeyLength the key length limit + * @param maxValueSize the value size limit + * @return {@code true} when a key or a value has to be cut + */ + private static boolean exceedsKeyOrValueLimit(@Nonnull Map map, int maxKeyLength, int maxValueSize) { + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + if (key != null && key.length() > maxKeyLength) { + return true; + } + Object value = entry.getValue(); + if (value instanceof String && ((String) value).length() > maxValueSize) { + return true; + } + } + return false; + } + + /** + * The keys of a map in the order every limit walks them. + * + * @param keys the keys + * @return the keys, sorted + */ + @Nonnull + private static List sortedKeys(@Nonnull Collection keys) { + List sorted = new ArrayList<>(keys); + sorted.sort(KEY_ORDER); + return sorted; + } + + /** + * Cuts a string that is longer than a limit. A cut never splits a surrogate pair: it falls before + * the pair, or after it when the pair starts the string, which is then one character over the limit. + * + * @param value the string, longer than the limit + * @param limit the limit, at least 1 + * @return the start of the string + */ + @Nonnull + private static String truncate(@Nonnull String value, int limit) { + int end = limit; + if (Character.isHighSurrogate(value.charAt(end - 1)) && Character.isLowSurrogate(value.charAt(end))) { + end = end == 1 ? 2 : end - 1; + } + return value.substring(0, end); + } +} diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/UtilsListingFilters.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/UtilsListingFilters.java new file mode 100644 index 000000000..2d62ab459 --- /dev/null +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/UtilsListingFilters.java @@ -0,0 +1,122 @@ +package ly.count.sdk.java.internal; + +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * Applies the listing filters of the SDK behavior settings: the event filter, the user property + * filter, the segmentation filter and the segmentation filter of each event. A filter without names + * allows everything; otherwise a whitelist keeps only its names and a blacklist removes its names. + */ +final class UtilsListingFilters { + + /** + * Not instantiated: the filters are static helpers. + */ + private UtilsListingFilters() { + } + + /** + * Whether the event filter, {@code eb} or {@code ew}, lets a custom event be recorded. + * + * @param eventKey the key of the custom event + * @param configProvider the settings in effect + * @return {@code true} when the event may be recorded + */ + static boolean applyEventFilter(@Nonnull String eventKey, @Nonnull ConfigurationProvider configProvider) { + return applyListFilter(eventKey, configProvider.getEventFilterList()); + } + + /** + * Whether the user property filter, {@code upb} or {@code upw}, lets a custom user property be + * set or modified. + * + * @param propertyKey the key of the custom user property + * @param configProvider the settings in effect + * @return {@code true} when the property may be set or modified + */ + static boolean applyUserPropertyFilter(@Nullable String propertyKey, @Nonnull ConfigurationProvider configProvider) { + return applyListFilter(propertyKey, configProvider.getUserPropertyFilterList()); + } + + /** + * Removes from a segmentation the keys the segmentation filter, {@code sb} or {@code sw}, does not allow. + * + * @param segmentation the segmentation, changed in place + * @param configProvider the settings in effect + * @param L logger + */ + static void applySegmentationFilter(@Nonnull Map segmentation, @Nonnull ConfigurationProvider configProvider, @Nonnull Log L) { + if (segmentation.isEmpty()) { + return; + } + + ConfigurationProvider.FilterList> filter = configProvider.getSegmentationFilterList(); + applyMapFilter(segmentation, filter.getFilterList(), filter.isWhitelist(), L); + } + + /** + * Removes from the segmentation of an event the keys that the segmentation filter of that event, + * {@code esb} or {@code esw}, does not allow. An event without names in the filter keeps every key. + * + * @param eventKey the key of the event + * @param segmentation the segmentation, changed in place + * @param configProvider the settings in effect + * @param L logger + */ + static void applyEventSegmentationFilter(@Nonnull String eventKey, @Nonnull Map segmentation, @Nonnull ConfigurationProvider configProvider, @Nonnull Log L) { + ConfigurationProvider.FilterList>> filter = configProvider.getEventSegmentationFilterList(); + if (segmentation.isEmpty() || filter.getFilterList().isEmpty()) { + return; + } + + Set names = filter.getFilterList().get(eventKey); + if (names == null) { + return; + } + + applyMapFilter(segmentation, names, filter.isWhitelist(), L); + } + + /** + * Removes the keys of a map that a filter does not allow. + * + * @param map the map, changed in place + * @param names the names of the filter + * @param isWhitelist {@code true} when only the names are allowed, {@code false} when they are rejected + * @param L logger + */ + private static void applyMapFilter(@Nonnull Map map, @Nonnull Set names, boolean isWhitelist, @Nonnull Log L) { + if (names.isEmpty()) { + return; + } + + Iterator> entries = map.entrySet().iterator(); + while (entries.hasNext()) { + String key = entries.next().getKey(); + if (isWhitelist != names.contains(key)) { + entries.remove(); + L.d("[UtilsListingFilters] applyMapFilter, removed the segmentation key [" + key + "], " + (isWhitelist ? "it is not in the whitelist" : "it is in the blacklist")); + } + } + } + + /** + * Whether a filter allows a name. + * + * @param name the name + * @param filter the filter + * @return {@code true} when the filter has no names or allows this one + */ + private static boolean applyListFilter(@Nullable String name, @Nonnull ConfigurationProvider.FilterList> filter) { + Set names = filter.getFilterList(); + if (names.isEmpty()) { + return true; + } + + return filter.isWhitelist() == names.contains(name); + } +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/AppKeyChangeTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/AppKeyChangeTests.java new file mode 100644 index 000000000..7d73bd0d7 --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/AppKeyChangeTests.java @@ -0,0 +1,395 @@ +package ly.count.sdk.java.internal; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Changing the app key while the SDK runs and the request queue calls, asserted on the request + * queue and the event queue the SDK stores. + */ +@RunWith(JUnit4.class) +public class AppKeyChangeTests { + + private static final String NEW_APP_KEY = "NEW_APP_KEY"; + private static final String VIEW_EVENT = "[CLY]_view"; + + /** + * Starts every test without SDK files. + */ + @Before + public void beforeTest() { + TestUtils.createCleanTestState(); + } + + /** + * Stops the SDK and deletes its data. + */ + @After + public void stop() { + Countly.instance().halt(); + } + + /** + * The running view, the queued events, the pending user profile changes and the running session + * of the old app go out under the old key, then a session begins under the new key. The timed + * event keeps running and goes out under the new key, and the device ID stays. + */ + @Test + public void changeAppKey_closesTheOldAppAndBeginsTheNewOne() { + Countly.instance().init(config(Config.Feature.Sessions, Config.Feature.Views, Config.Feature.Events, Config.Feature.UserProfiles)); + Countly.session().begin(); + Countly.instance().views().startView("home"); + Countly.instance().events().startEvent("timed"); + Countly.instance().events().recordEvent("before_change"); + Countly.instance().userProfile().setProperty("plan", "pro"); + Assert.assertEquals(1, TestUtils.getCurrentRQ().length); + + Countly.instance().changeAppKey(NEW_APP_KEY); + + Map[] rq = TestUtils.getCurrentRQ(); + Assert.assertEquals(NEW_APP_KEY, SDKCore.instance.config.getServerAppKey()); + Assert.assertEquals(0, TestUtils.getCurrentEQ().size()); + Assert.assertEquals("1", rq[0].get("begin_session")); + Assert.assertEquals("1", rq[rq.length - 2].get("end_session")); + Assert.assertEquals("1", rq[rq.length - 1].get("begin_session")); + Assert.assertEquals(NEW_APP_KEY, rq[rq.length - 1].get("app_key")); + Assert.assertNull(rq[rq.length - 1].get("events")); + for (int i = 0; i < rq.length - 1; i++) { + Assert.assertEquals(TestUtils.SERVER_APP_KEY, rq[i].get("app_key")); + } + for (Map request : rq) { + Assert.assertEquals(TestUtils.DEVICE_ID, request.get("device_id")); + } + + List oldAppEvents = events(rq, TestUtils.SERVER_APP_KEY); + Assert.assertEquals(1, count(oldAppEvents, "before_change")); + Assert.assertEquals(0, count(oldAppEvents, "timed")); + Assert.assertTrue("the running view is stopped under the old key", oldAppEvents.stream().anyMatch(e -> VIEW_EVENT.equals(e.getString("key")) && e.has("dur"))); + Assert.assertEquals(1, requestsWith(rq, "user_details", TestUtils.SERVER_APP_KEY)); + + Countly.instance().events().endEvent("timed"); + Countly.instance().attemptToSendStoredRequests(); + Map[] after = TestUtils.getCurrentRQ(); + Assert.assertEquals(rq.length + 1, after.length); + List newAppEvents = events(after, NEW_APP_KEY); + Assert.assertEquals(1, count(newAppEvents, "timed")); + Assert.assertEquals("the stopped view is not restarted", 0, count(newAppEvents, VIEW_EVENT)); + } + + /** + * An empty or placeholder app key is ignored with log code e103, and the key in use is ignored + * too: nothing is closed or sent, and the key stays. + */ + @Test + public void changeAppKey_invalidPlaceholderAndSameKeyAreIgnored() { + Countly.instance().init(config(Config.Feature.Sessions, Config.Feature.Events)); + Countly.session().begin(); + Countly.instance().events().recordEvent("stays_queued"); + + Countly.instance().changeAppKey(null); + Countly.instance().changeAppKey(""); + Countly.instance().changeAppKey("YOUR_APP_KEY"); + Countly.instance().changeAppKey(TestUtils.SERVER_APP_KEY); + + Assert.assertEquals(TestUtils.SERVER_APP_KEY, SDKCore.instance.config.getServerAppKey()); + Assert.assertEquals(3, logCode("e103")); + Map[] rq = TestUtils.getCurrentRQ(); + Assert.assertEquals(1, rq.length); + Assert.assertEquals("1", rq[0].get("begin_session")); + Assert.assertEquals(1, TestUtils.getCurrentEQ().size()); + Assert.assertTrue(Countly.session().isActive()); + } + + /** + * Without a running session no session is ended or begun: only the queued events are sent under + * the old key, and what is recorded afterwards carries the new key. + */ + @Test + public void changeAppKey_withoutSession_beginsNoSession() { + Countly.instance().init(config(Config.Feature.Sessions, Config.Feature.Events)); + Countly.instance().events().recordEvent("old_app"); + + Countly.instance().changeAppKey(NEW_APP_KEY); + Countly.instance().events().recordEvent("new_app"); + Countly.instance().attemptToSendStoredRequests(); + + Map[] rq = TestUtils.getCurrentRQ(); + Assert.assertEquals(2, rq.length); + Assert.assertEquals(1, count(events(rq, TestUtils.SERVER_APP_KEY), "old_app")); + Assert.assertEquals(1, count(events(rq, NEW_APP_KEY), "new_app")); + for (Map request : rq) { + Assert.assertNull(request.get("begin_session")); + Assert.assertNull(request.get("end_session")); + } + } + + /** + * Queued requests keep the key they were created with until the queue call rewrites them all + * to the current key, the rest of each request untouched. + */ + @Test + public void replaceAllAppKeysInQueueWithCurrentAppKey_rewritesTheOldRequests() { + Map[] before = queueOneRequestPerAppKey(); + Assert.assertEquals(TestUtils.SERVER_APP_KEY, before[0].get("app_key")); + Assert.assertEquals(NEW_APP_KEY, before[1].get("app_key")); + + Countly.instance().replaceAllAppKeysInQueueWithCurrentAppKey(); + + Map[] after = TestUtils.getCurrentRQ(); + Assert.assertEquals(2, after.length); + for (int i = 0; i < after.length; i++) { + Assert.assertEquals(NEW_APP_KEY, after[i].get("app_key")); + Assert.assertEquals(before[i].get("events"), after[i].get("events")); + Assert.assertEquals(before[i].get("timestamp"), after[i].get("timestamp")); + Assert.assertEquals(before[i].size(), after[i].size()); + } + } + + /** + * The queue call removes the requests created under another key and keeps the ones of the + * current key. + */ + @Test + public void removeDifferentAppKeysFromQueue_dropsTheOldRequests() { + Map[] before = queueOneRequestPerAppKey(); + + Countly.instance().removeDifferentAppKeysFromQueue(); + + Map[] after = TestUtils.getCurrentRQ(); + Assert.assertEquals(1, after.length); + Assert.assertEquals(NEW_APP_KEY, after[0].get("app_key")); + Assert.assertEquals(before[1].get("events"), after[0].get("events")); + } + + /** + * Flushing drops the queued requests and events. The timed event, the running view, the pending + * user profile change and the health check counters are kept, and what follows is queued again. + */ + @Test + public void flushQueues_dropsQueuedDataAndKeepsWhatIsNotQueued() { + Countly.instance().init(config(Config.Feature.Sessions, Config.Feature.Views, Config.Feature.Events, Config.Feature.UserProfiles)); + Countly.session().begin(); + Countly.instance().views().startView("running"); + Countly.instance().events().startEvent("timed"); + Countly.instance().events().recordEvent("flushed_request"); + Countly.instance().attemptToSendStoredRequests(); + Countly.instance().events().recordEvent("flushed_event"); + Countly.instance().userProfile().setProperty("kept", "yes"); + Countly.instance().changeAppKey(""); + Assert.assertEquals(2, TestUtils.getCurrentRQ().length); + Assert.assertEquals(1, TestUtils.getCurrentEQ().size()); + + Countly.instance().flushQueues(); + + Assert.assertEquals(0, TestUtils.getCurrentRQ().length); + Assert.assertEquals(0, TestUtils.getCurrentEQ().size()); + Assert.assertEquals(1, logCode("e103")); + + Countly.instance().userProfile().save(); + Countly.instance().events().endEvent("timed"); + Countly.instance().views().stopViewWithName("running"); + Countly.instance().attemptToSendStoredRequests(); + Map[] rq = TestUtils.getCurrentRQ(); + Assert.assertEquals(1, requestsWith(rq, "user_details", TestUtils.SERVER_APP_KEY)); + List events = events(rq, TestUtils.SERVER_APP_KEY); + Assert.assertEquals(1, count(events, "timed")); + Assert.assertTrue(events.stream().anyMatch(e -> VIEW_EVENT.equals(e.getString("key")) && e.has("dur"))); + Assert.assertEquals(0, count(events, "flushed_request") + count(events, "flushed_event")); + } + + /** + * The settings and remote config answers to the requests of the old app that arrive after the + * app key changed are not applied; the answers to the requests of the new app are. + */ + @Test + public void changeAppKey_lateAnswersForTheOldAppAreNotApplied() { + List requests = new CopyOnWriteArrayList<>(); + InternalConfig config = new InternalConfig(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.RemoteConfig).enableRemoteConfigAutomaticTriggers()); + config.immediateRequestGenerator = () -> (requestData, customEndpoint, cp, delayed, networkingIsEnabled, callback, log) -> requests.add(new Object[] { requestData, callback }); + Countly.instance().init(config); + int eventQueueSize = SDKCore.instance.config.getConfigurationProvider().getEventQueueSizeThreshold(); + Assert.assertNotEquals(7, eventQueueSize); + + Countly.instance().changeAppKey(NEW_APP_KEY); + answer(requests, "sc", TestUtils.SERVER_APP_KEY, new ServerConfigBuilder().eventQueueSize(7).build()); + answer(requests, "rc", TestUtils.SERVER_APP_KEY, "{\"color\":\"red\"}"); + + Assert.assertEquals(eventQueueSize, SDKCore.instance.config.getConfigurationProvider().getEventQueueSizeThreshold()); + Assert.assertTrue(Countly.instance().remoteConfig().getValues().isEmpty()); + + answer(requests, "sc", NEW_APP_KEY, new ServerConfigBuilder().eventQueueSize(7).build()); + answer(requests, "rc", NEW_APP_KEY, "{\"size\":\"big\"}"); + + Assert.assertEquals(7, SDKCore.instance.config.getConfigurationProvider().getEventQueueSizeThreshold()); + Assert.assertEquals(1, Countly.instance().remoteConfig().getValues().size()); + Assert.assertTrue(Countly.instance().remoteConfig().getValues().containsKey("size")); + } + + /** + * Backend mode keeps the app key the application set on each request: the app key change and + * the queue calls that rewrite or drop requests are ignored. The server URL change and sending + * the stored requests work. + */ + @Test + public void backendMode_ignoresTheAppKeyCalls() throws Exception { + Countly.instance().init(TestUtils.getBaseConfig().enableBackendMode()); + ModuleRequests.pushAsync(SDKCore.instance.config, new Request("app_key", "OTHER", "k", "v")).get(); + Countly.instance().backendM().sessionBegin("backend_device", null, null, null); + Countly.instance().backendM().recordEvent("backend_device", "backend_event", 1, null, null, null, null); + int queued = SDKCore.instance.requestQueueMemory.size(); + Assert.assertTrue(queued > 0); + + Countly.instance().changeAppKey(NEW_APP_KEY); + Countly.instance().flushQueues(); + Countly.instance().replaceAllAppKeysInQueueWithCurrentAppKey(); + Countly.instance().removeDifferentAppKeysFromQueue(); + + Assert.assertEquals(TestUtils.SERVER_APP_KEY, SDKCore.instance.config.getServerAppKey()); + Map[] stored = TestUtils.getCurrentRQ(); + Assert.assertEquals(1, stored.length); + Assert.assertEquals("OTHER", stored[0].get("app_key")); + Assert.assertEquals(queued, SDKCore.instance.requestQueueMemory.size()); + for (Request request : SDKCore.instance.requestQueueMemory) { + Assert.assertEquals(TestUtils.SERVER_APP_KEY, request.params.get("app_key")); + } + + Countly.instance().attemptToSendStoredRequests(); + Assert.assertEquals(queued + 1, SDKCore.instance.requestQueueMemory.size()); + Assert.assertTrue(((ModuleBackendMode) Countly.instance().backendM().getModule()).eventQueues.isEmpty()); + + Countly.instance().changeServerUrl("https://other.test.server.com"); + Assert.assertEquals("https://other.test.server.com", SDKCore.instance.config.getServerURL().toString()); + } + + /** + * Every call made before init does nothing and is counted as log code w101. The URL and key of + * a change are kept in memory only, so the next init uses the ones of the configuration. + */ + @Test + public void beforeInitAndNextInit() { + Countly.instance().init(TestUtils.getBaseConfig()); + Countly.instance().halt(); + + Countly.instance().changeServerUrl("https://other.test.server.com"); + Countly.instance().changeAppKey(NEW_APP_KEY); + Countly.instance().flushQueues(); + Countly.instance().replaceAllAppKeysInQueueWithCurrentAppKey(); + Countly.instance().removeDifferentAppKeysFromQueue(); + Countly.instance().attemptToSendStoredRequests(); + + Config config = TestUtils.getBaseConfig(); + Countly.instance().init(config); + Assert.assertEquals(6, logCode("w101")); + Assert.assertEquals(TestUtils.SERVER_URL, SDKCore.instance.config.getServerURL().toString()); + Assert.assertEquals(TestUtils.SERVER_APP_KEY, SDKCore.instance.config.getServerAppKey()); + + Countly.instance().changeServerUrl("https://other.test.server.com"); + Countly.instance().changeAppKey(NEW_APP_KEY); + Countly.instance().stop(); + Countly.instance().init(config); + Assert.assertEquals(TestUtils.SERVER_URL, SDKCore.instance.config.getServerURL().toString()); + Assert.assertEquals(TestUtils.SERVER_APP_KEY, SDKCore.instance.config.getServerAppKey()); + Assert.assertEquals(TestUtils.SERVER_URL, config.getServerURL().toString()); + Assert.assertEquals(TestUtils.SERVER_APP_KEY, config.getServerAppKey()); + } + + // region helpers + + /** + * The base test configuration with the given features and an event queue that holds ten events. + */ + private static Config config(Config.Feature... features) { + return TestUtils.getBaseConfig().enableFeatures(features).setEventQueueSizeToSend(10); + } + + /** + * Queues one event request under the configured key, changes the key, then queues one under the + * new key. + * + * @return the request queue + */ + private static Map[] queueOneRequestPerAppKey() { + Countly.instance().init(config(Config.Feature.Events)); + Countly.instance().events().recordEvent("old_app"); + Countly.instance().attemptToSendStoredRequests(); + Countly.instance().changeAppKey(NEW_APP_KEY); + Countly.instance().events().recordEvent("new_app"); + Countly.instance().attemptToSendStoredRequests(); + + Map[] rq = TestUtils.getCurrentRQ(); + Assert.assertEquals(2, rq.length); + return rq; + } + + /** + * Answers every captured immediate request of a method and app key with the given response. + */ + private static void answer(List requests, String method, String appKey, String response) { + int answered = 0; + for (Object[] request : requests) { + String data = (String) request[0]; + if (data.contains("method=" + method) && data.contains("app_key=" + appKey)) { + ((ImmediateRequestMaker.InternalImmediateRequestCallback) request[1]).callback(new JSONObject(response)); + answered++; + } + } + Assert.assertEquals(1, answered); + } + + /** + * How often the running health check counter recorded a log code. + */ + private static int logCode(String code) { + return SDKCore.instance.healthCheckCounter.snapshot().getJSONObject("lc").optInt(code, 0); + } + + /** + * The events of the queued requests that carry the given app key, in queue order. + */ + private static List events(Map[] rq, String appKey) { + List events = new ArrayList<>(); + for (Map request : rq) { + if (appKey.equals(request.get("app_key")) && request.containsKey("events")) { + JSONArray array = new JSONArray(request.get("events")); + for (int i = 0; i < array.length(); i++) { + events.add(array.getJSONObject(i)); + } + } + } + return events; + } + + /** + * How many of the events have the given key. + */ + private static int count(List events, String key) { + return (int) events.stream().filter(e -> key.equals(e.getString("key"))).count(); + } + + /** + * How many queued requests with the given app key carry the given parameter. + */ + private static int requestsWith(Map[] rq, String param, String appKey) { + int found = 0; + for (Map request : rq) { + if (appKey.equals(request.get("app_key")) && request.containsKey(param)) { + found++; + } + } + return found; + } + + // endregion +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/BackendModeTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/BackendModeTests.java index 5e8dc8e3d..2e3981ffd 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/BackendModeTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/BackendModeTests.java @@ -5,6 +5,7 @@ import java.io.StringWriter; import java.math.BigDecimal; import java.util.Calendar; +import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -833,7 +834,7 @@ public void testCrashSegmentDataType() { public void testRecordDirectRequest() { ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); - // Direct request with timestamp and device id + // Values in the map replace the base request's values Map requestData = new ConcurrentHashMap<>(); requestData.put("data1", "value1"); requestData.put("device_id", "device-id-1"); @@ -852,7 +853,14 @@ public void testRecordDirectRequest() { Assert.assertEquals("value1", request.params.get("data1")); Assert.assertEquals("value3", request.params.get("data3")); Assert.assertEquals("1", request.params.get("dr")); - validateRequestTimeFields("device-id-2", 1_647_938_191_782L, request); + Assert.assertEquals("device-id-1", request.params.get("device_id")); + Assert.assertEquals("1647938191782", request.params.get("timestamp")); + Assert.assertEquals("100", request.params.get("tz")); + Assert.assertEquals("0", request.params.get("dow")); + Assert.assertEquals("9", request.params.get("hour")); + for (String key : new String[] { "device_id", "timestamp", "tz", "dow", "hour" }) { + Assert.assertEquals(key + " is sent more than once: " + request.params, 1, countParam(request.params, key)); + } // Direct request without timestamp and device id requestData = new ConcurrentHashMap<>(); @@ -872,6 +880,92 @@ public void testRecordDirectRequest() { validateRequestTimeFields("device-id-2", 987_654_321L, request); } + /** + * Every backend mode request carries the device ID type "developer supplied" (t=0), + * so the server counts the users recorded in backend mode as identified. + */ + @Test + public void testEveryRequestCarriesDeveloperSuppliedDeviceIdType() { + ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); + Map userProperties = new HashMap<>(); + userProperties.put("name", "Full Name"); + Map requestData = new HashMap<>(); + requestData.put("custom_key", "custom_value"); + + backendMode.sessionBegin("device-id-1", new HashMap<>(), null, 1_646_640_780_130L); + backendMode.sessionUpdate("device-id-1", 10, 1_646_640_780_130L); + backendMode.recordEvent("device-id-1", "key-1", 1, null, null, null, 1_646_640_780_130L); + backendMode.sessionEnd("device-id-1", 20, 1_646_640_780_130L); + backendMode.recordException("device-id-1", "message", "stacktrace", null, null, 1_646_640_780_130L); + backendMode.recordUserProperties("device-id-1", userProperties, 1_646_640_780_130L); + backendMode.recordDirectRequest("device-id-1", requestData, 1_646_640_780_130L); + + Assert.assertEquals(7, SDKCore.instance.requestQueueMemory.size()); + for (Request request : SDKCore.instance.requestQueueMemory) { + Assert.assertEquals(request.params.toString(), "0", request.params.get("t")); + } + } + + /** + * In a direct request, a value given in the map replaces the SDK's value, so each key is sent once. + * sdk_name, sdk_version, checksum and checksum256 stay the SDK's. + */ + @Test + public void testRecordDirectRequestMapValuesReplaceBaseValues() { + ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); + Map requestData = new HashMap<>(); + requestData.put("app_key", "other-app-key"); + requestData.put("old_device_id", "old-device-id"); + requestData.put("t", "1"); + requestData.put("sdk_name", "other-sdk"); + requestData.put("sdk_version", "0.0.0"); + requestData.put("checksum", "given"); + requestData.put("checksum256", "given"); + + backendMode.recordDirectRequest("device-id-1", requestData, 1_646_640_780_130L); + + Assert.assertEquals(1, SDKCore.instance.requestQueueMemory.size()); + Request request = SDKCore.instance.requestQueueMemory.remove(); + Assert.assertEquals("other-app-key", request.params.get("app_key")); + Assert.assertEquals("old-device-id", request.params.get("old_device_id")); + Assert.assertEquals("1", request.params.get("t")); + Assert.assertEquals("java-native-backend", request.params.get("sdk_name")); + Assert.assertNotEquals("0.0.0", request.params.get("sdk_version")); + Assert.assertFalse(request.params.has("checksum")); + Assert.assertFalse(request.params.has("checksum256")); + for (String key : new String[] { "app_key", "old_device_id", "t", "sdk_name", "sdk_version", "device_id", "timestamp" }) { + Assert.assertEquals(key + " is sent more than once: " + request.params, 1, countParam(request.params, key)); + } + } + + /** + * Recording a direct request leaves the given map unchanged, so an unmodifiable map works too. + */ + @Test + public void testRecordDirectRequestKeepsGivenMapUnchanged() { + ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); + Map data = new HashMap<>(); + data.put("custom_key", "custom_value"); + data.put("checksum", "given"); + Map requestData = Collections.unmodifiableMap(data); + + backendMode.recordDirectRequest("device-id-1", requestData, 1_646_640_780_130L); + + Assert.assertEquals(2, requestData.size()); + Assert.assertEquals(1, SDKCore.instance.requestQueueMemory.size()); + Assert.assertEquals("custom_value", SDKCore.instance.requestQueueMemory.remove().params.get("custom_key")); + } + + private int countParam(Params params, String key) { + int count = 0; + for (String pair : params.toString().split("&")) { + if (pair.split("=")[0].equals(key)) { + count++; + } + } + return count; + } + private Map populateUserProperties(boolean addUserDetail, boolean addCustomDetail, boolean addOperation) { Map userDetail = new ConcurrentHashMap<>(); if (addUserDetail) { diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ConfigSurfaceTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ConfigSurfaceTests.java index 25086e94c..fb4db1d1a 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ConfigSurfaceTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ConfigSurfaceTests.java @@ -51,6 +51,7 @@ public void fluentChain_acceptsEverySaneValueAndReadsItBack() { .setEventQueueSizeToSend(9) .setRequestQueueMaxSize(321) .setMaxBreadcrumbCount(12) + .setMaxKeyLength(64) .setNetworkConnectTimeout(11) .setNetworkReadTimeout(12) .setNetworkRequestCooldown(1300) @@ -92,6 +93,7 @@ public void fluentChain_acceptsEverySaneValueAndReadsItBack() { Assert.assertEquals("test-platform", SDKCore.instance.config.getSdkPlatform()); // These two are only readable off the internal config, which is what the modules see. Assert.assertEquals(12, SDKCore.instance.config.getMaxBreadcrumbCount()); + Assert.assertEquals(64, SDKCore.instance.config.getMaxKeyLength()); Assert.assertFalse(SDKCore.instance.config.isUnhandledCrashReportingEnabled()); } @@ -144,6 +146,15 @@ public void outOfRangeValues_areRefusedAndLeaveTheGoodValueInPlace() { config.setEventQueueSizeToSend(-5); Assert.assertEquals("a negative event queue size must be refused", 23, config.getEventsBufferSize()); + // key length accepts 1 and up, and sets no limit until it is called + Assert.assertEquals(Integer.MAX_VALUE, new InternalConfig(config).getMaxKeyLength()); + config.setMaxKeyLength(40); + for (int bad : new int[] { 0, -1, Integer.MIN_VALUE }) { + config.setMaxKeyLength(bad); + Assert.assertEquals("key length must reject " + bad, 40, new InternalConfig(config).getMaxKeyLength()); + } + Assert.assertEquals(1, new InternalConfig(config.setMaxKeyLength(1)).getMaxKeyLength()); + // The boundary values themselves are valid. Assert.assertEquals(300, config.setNetworkConnectTimeout(300).getNetworkConnectionTimeout()); Assert.assertEquals(1, config.setNetworkReadTimeout(1).getNetworkReadTimeout()); diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/CoreRobustnessTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/CoreRobustnessTests.java index 860fb210d..0bc887da5 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/CoreRobustnessTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/CoreRobustnessTests.java @@ -1,7 +1,9 @@ package ly.count.sdk.java.internal; import java.io.File; +import java.util.List; import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; import ly.count.sdk.java.Config; import ly.count.sdk.java.Countly; import org.junit.After; @@ -76,36 +78,42 @@ public void init_withANullConfig_isRefusedWithoutCrashing() { } /** - * Feature accessors for features that were never enabled return null rather than throwing. + * Feature accessors for features that were never enabled hand out an interface that ignores every + * call, rather than null or throwing. *

* They dereferenced a module that was never built, and consent is not the gate that stops them: * with consent not required, the consent check passes and the null module was used anyway. */ @Test - public void accessors_forFeaturesThatWereNeverEnabled_returnNull() { + public void accessors_forFeaturesThatWereNeverEnabled_handOutInterfacesThatIgnoreCalls() { Countly.instance().init(TestUtils.getConfigEvents(2)); - Assert.assertNull(Countly.instance().feedback()); - Assert.assertNull(Countly.instance().crashes()); - Assert.assertNull(Countly.instance().remoteConfig()); - Assert.assertNull(Countly.instance().content()); + Assert.assertSame(SDKCore.dormantFeedback, Countly.instance().feedback()); + Assert.assertSame(SDKCore.dormantCrashes, Countly.instance().crashes()); + Assert.assertSame(SDKCore.dormantRemoteConfig, Countly.instance().remoteConfig()); + Assert.assertSame(SDKCore.dormantContent, Countly.instance().content()); + int queued = TestUtils.getCurrentRQ().length; + Countly.instance().crashes().recordHandledException(new RuntimeException("never enabled")); + Countly.instance().content().enterContentZone(); + Assert.assertEquals(queued, TestUtils.getCurrentRQ().length); // The feature that IS enabled still works, so the guards did not break the happy path. - Assert.assertNotNull(Countly.instance().events()); + Assert.assertNotSame(SDKCore.dormantEvents, Countly.instance().events()); } /** - * Accessors used before init log and return null. "location" logged through a logger that does - * not exist yet, unlike every sibling accessor. + * Accessors used before init log and hand out an interface that ignores calls, backend mode + * aside, which still answers null. "location" logged through a logger that does not exist yet, + * unlike every sibling accessor. */ @Test - public void accessors_beforeInit_returnNullWithoutCrashing() { + public void accessors_beforeInit_doNotThrow() { Countly.instance().halt(); - Assert.assertNull(Countly.instance().location()); - Assert.assertNull(Countly.instance().feedback()); - Assert.assertNull(Countly.instance().content()); - Assert.assertNull(Countly.instance().remoteConfig()); + Assert.assertSame(SDKCore.dormantLocation, Countly.instance().location()); + Assert.assertSame(SDKCore.dormantFeedback, Countly.instance().feedback()); + Assert.assertSame(SDKCore.dormantContent, Countly.instance().content()); + Assert.assertSame(SDKCore.dormantRemoteConfig, Countly.instance().remoteConfig()); Assert.assertNull(Countly.instance().backendM()); } @@ -166,6 +174,62 @@ public void aStorableThatCannotSerialise_leavesNoFileBehind() { Assert.assertEquals("no file should have been created, found: " + litter.length, 0, litter.length); } + /** + * A fresh init reads storage files that do not exist yet, which is the normal first run state: + * each one is logged at debug level, and no error is logged for any of them. + */ + @Test + public void freshInit_logsTheStorageFilesThatDoNotExistYet_atDebugLevel() { + List missingFileLines = new CopyOnWriteArrayList<>(); + Countly.instance().init(TestUtils.getConfigEvents(2).setLoggingLevel(Config.LoggingLevel.VERBOSE) + .setLogListener((message, level) -> { + if (message.contains("No data for file")) { + missingFileLines.add(level + " " + message); + } + })); + + Assert.assertFalse(missingFileLines.isEmpty()); + for (String line : missingFileLines) { + Assert.assertTrue(line, line.startsWith(Config.LoggingLevel.DEBUG + " ")); + } + } + + /** + * A storage file that exists but cannot be opened, unlike a missing one, is logged as an error. + */ + @Test + public void init_withAStorageFileThatCannotBeOpened_logsAnError() { + Assert.assertTrue(new File(TestUtils.getTestSDirectory(), "[CLY]_timedEvent_0").mkdir()); + List errors = new CopyOnWriteArrayList<>(); + Countly.instance().init(TestUtils.getConfigEvents(2).setLoggingLevel(Config.LoggingLevel.VERBOSE) + .setLogListener((message, level) -> { + if (level == Config.LoggingLevel.ERROR && message.contains("timedEvent_0")) { + errors.add(message); + } + })); + + Assert.assertEquals(errors.toString(), 1, errors.size()); + Assert.assertTrue(errors.get(0), errors.get(0).contains("Error while opening file")); + } + + /** + * A second init is refused before it changes the running SDK, so given the same configuration + * object again it leaves the logger the running SDK and its configuration log through in place. + */ + @Test + public void secondInit_withTheSameConfigObject_keepsTheRunningLogger() { + InternalConfig config = new InternalConfig(TestUtils.getConfigEvents(2)); + Countly.instance().init(config); + Log running = SDKCore.instance.L; + Assert.assertSame(running, config.getLogger()); + + Countly.instance().init(config); + + Assert.assertTrue(Countly.isInitialized()); + Assert.assertSame(running, SDKCore.instance.L); + Assert.assertSame(running, config.getLogger()); + } + /** * The queued crash request, or null when none was queued. * diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/CountlyFacadeTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/CountlyFacadeTests.java index 973fdccab..be8f9dd28 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/CountlyFacadeTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/CountlyFacadeTests.java @@ -1,7 +1,12 @@ package ly.count.sdk.java.internal; +import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import ly.count.sdk.java.Config; import ly.count.sdk.java.Countly; @@ -18,9 +23,9 @@ /** * The static {@link Countly} facade and the {@link SDKCore} accessors behind it. *

- * Two contracts are covered: before {@code init} every accessor must answer with null and a logged - * error instead of throwing, and after {@code init} the deprecated {@link Usage} API must still route - * to the live session. Both matter because they are the surface an integration touches first. + * Two contracts are covered: before {@code init} no accessor may throw, and every feature interface + * is handed out but ignores calls, and after {@code init} the deprecated {@link Usage} API must still + * route to the live session. Both matter because they are the surface an integration touches first. */ @RunWith(JUnit4.class) public class CountlyFacadeTests { @@ -39,26 +44,41 @@ public void stop() { /** * Nothing may throw before {@code init}. Every module accessor and every state query is walked in - * one pass, so a newly added accessor that forgets its guard shows up here. + * one pass, so a newly added accessor that forgets its guard shows up here. Each feature interface + * is handed out and ignores calls, so code that calls it before init does not throw either, and a + * call with a callback gets its answer. */ @Test - public void beforeInit_everyAccessorAnswersNullInsteadOfThrowing() { + public void beforeInit_noAccessorThrows_andEveryFeatureInterfaceIgnoresCalls() { Assert.assertFalse(Countly.isInitialized()); Assert.assertNull(Countly.session()); Assert.assertNull(Countly.instance().backendM()); Assert.assertNull(Countly.backendMode()); - Assert.assertNull(Countly.instance().feedback()); - Assert.assertNull(Countly.instance().content()); - Assert.assertNull(Countly.instance().events()); - Assert.assertNull(Countly.instance().views()); - Assert.assertNull(Countly.instance().crashes()); - Assert.assertNull(Countly.instance().remoteConfig()); - Assert.assertNull(Countly.instance().deviceId()); - Assert.assertNull(Countly.instance().userProfile()); - // Countly.location() is deliberately NOT called here: its own uninitialised guard logs - // through the instance logger without a null check, so it throws NPE before it can return - // null. Reported as a bug rather than asserted, so a fix does not have to touch this test. + Assert.assertSame(SDKCore.dormantFeedback, Countly.instance().feedback()); + Assert.assertSame(SDKCore.dormantContent, Countly.instance().content()); + Assert.assertSame(SDKCore.dormantEvents, Countly.instance().events()); + Assert.assertSame(SDKCore.dormantViews, Countly.instance().views()); + Assert.assertSame(SDKCore.dormantCrashes, Countly.instance().crashes()); + Assert.assertSame(SDKCore.dormantRemoteConfig, Countly.instance().remoteConfig()); + Assert.assertSame(SDKCore.dormantDeviceId, Countly.instance().deviceId()); + Assert.assertSame(SDKCore.dormantUserProfile, Countly.instance().userProfile()); + Assert.assertSame(SDKCore.dormantLocation, Countly.instance().location()); + + Assert.assertFalse(Countly.instance().events().startEvent("before_init")); + Countly.instance().events().recordEvent("before_init"); + Assert.assertNull(Countly.instance().views().startView("home")); + Countly.instance().crashes().recordHandledException(new RuntimeException("before init")); + Assert.assertNull(Countly.instance().deviceId().getID()); + Assert.assertTrue(Countly.instance().remoteConfig().getValues().isEmpty()); + Countly.instance().userProfile().setProperty("plan", "pro"); + Countly.instance().location().setLocation("TR", "Izmir", "38.4,27.1", null); + Countly.instance().content().enterContentZone(); + List errors = new CopyOnWriteArrayList<>(); + Countly.instance().feedback().getAvailableFeedbackWidgets((widgets, error) -> errors.add(error)); + Countly.instance().remoteConfig().downloadAllKeys((result, error, fullValueUpdate, values) -> errors.add(error)); + Assert.assertEquals(2, errors.size()); + Assert.assertFalse(Countly.isInitialized()); // isTracking short circuits on the uninitialised check rather than dereferencing the SDK. for (Config.Feature feature : Config.Feature.values()) { @@ -258,11 +278,12 @@ public void stop(InternalConfig config, boolean clear) { } /** - * Consent gating of the accessors. With consent required and nothing granted the feature - * interfaces must be withheld; granting afterwards must hand them over. + * Consent gating of the accessors. With consent required and nothing granted every feature + * interface ignores calls; granting afterwards hands over the running ones, and removing the + * consent again hands out the ignoring ones. */ @Test - public void consentGating_withholdsThenReleasesTheFeatureInterfaces() { + public void consentGating_handsOutInterfacesThatIgnoreCalls_untilTheConsentIsGiven() { Config config = TestUtils.getBaseConfig() .enableFeatures(Config.Feature.Events, Config.Feature.Views, Config.Feature.Location, Config.Feature.Feedback, Config.Feature.RemoteConfig, Config.Feature.CrashReporting) @@ -270,28 +291,265 @@ public void consentGating_withholdsThenReleasesTheFeatureInterfaces() { Countly.instance().init(config); Assert.assertFalse(Countly.isTracking(Config.Feature.Events)); - Assert.assertNull(Countly.instance().events()); - Assert.assertNull(Countly.instance().views()); - Assert.assertNull(Countly.instance().location()); - Assert.assertNull(Countly.instance().feedback()); - Assert.assertNull(Countly.instance().remoteConfig()); - Assert.assertNull(Countly.instance().crashes()); + Assert.assertSame(SDKCore.dormantEvents, Countly.instance().events()); + Assert.assertSame(SDKCore.dormantViews, Countly.instance().views()); + Assert.assertSame(SDKCore.dormantLocation, Countly.instance().location()); + Assert.assertSame(SDKCore.dormantFeedback, Countly.instance().feedback()); + Assert.assertSame(SDKCore.dormantRemoteConfig, Countly.instance().remoteConfig()); + Assert.assertSame(SDKCore.dormantCrashes, Countly.instance().crashes()); + Countly.instance().events().recordEvent("before_consent"); + TestUtils.validateEQSize(0); Countly.onConsent(Config.Feature.values()); Assert.assertTrue(Countly.isTracking(Config.Feature.Events)); - Assert.assertNotNull(Countly.instance().events()); - Assert.assertNotNull(Countly.instance().views()); - Assert.assertNotNull(Countly.instance().location()); - Assert.assertNotNull(Countly.instance().feedback()); - Assert.assertNotNull(Countly.instance().remoteConfig()); - Assert.assertNotNull(Countly.instance().crashes()); + Assert.assertSame(SDKCore.instance.module(ModuleEvents.class).eventsInterface, Countly.instance().events()); + Assert.assertNotSame(SDKCore.dormantViews, Countly.instance().views()); + Assert.assertNotSame(SDKCore.dormantLocation, Countly.instance().location()); + Assert.assertNotSame(SDKCore.dormantFeedback, Countly.instance().feedback()); + Assert.assertNotSame(SDKCore.dormantRemoteConfig, Countly.instance().remoteConfig()); + Assert.assertNotSame(SDKCore.dormantCrashes, Countly.instance().crashes()); Countly.onConsentRemoval(Config.Feature.values()); Assert.assertFalse(Countly.isTracking(Config.Feature.Events)); - Assert.assertNull(Countly.instance().events()); - Assert.assertNull(Countly.instance().views()); + Assert.assertSame(SDKCore.dormantEvents, Countly.instance().events()); + Assert.assertSame(SDKCore.dormantViews, Countly.instance().views()); + } + + /** + * Every interface sends its calls to the module of its feature once that runs, wherever it came + * from, as a caller may keep the one it got first. + *

+ * Verifies that an events interface handed out before init and one handed out before the consent + * record once the consent is given, that a views interface handed out before the consent starts a + * view then, and that a running events interface kept across a removal of its consent ignores + * calls until the consent is given again and then records into the new module. + */ + @Test + public void aKeptInterface_reachesTheModuleOnceItsFeatureRuns() { + ModuleEvents.Events beforeInit = Countly.instance().events(); + Countly.instance().init(TestUtils.getBaseConfig().enableFeatures(Config.Feature.Events, Config.Feature.Views) + .setRequiresConsent(true).setEventQueueSizeToSend(100)); + ModuleEvents.Events beforeConsent = Countly.instance().events(); + ModuleViews.Views viewsBeforeConsent = Countly.instance().views(); + beforeConsent.recordEvent("ignored_before_consent"); + Assert.assertNull(viewsBeforeConsent.startView("ignored")); + TestUtils.validateEQSize(0); + + Countly.onConsent(Config.Feature.Events, Config.Feature.Views); + + beforeInit.recordEvent("from_before_init"); + beforeConsent.recordEvent("from_before_consent"); + Assert.assertNotNull(viewsBeforeConsent.startView("home")); + Assert.assertTrue(beforeConsent.startEvent("timed")); + Assert.assertTrue(Countly.instance().events().endEvent("timed")); + Assert.assertEquals(Arrays.asList("from_before_init", "from_before_consent", ModuleViews.KEY_VIEW_EVENT, "timed"), TestUtils.keysInEQ()); + + ModuleEvents.Events running = Countly.instance().events(); + Countly.onConsentRemoval(Config.Feature.Events); + running.recordEvent("ignored_after_removal"); + TestUtils.validateEQSize(0); + + Countly.onConsent(Config.Feature.Events); + running.recordEvent("after_consent_again"); + Assert.assertEquals(Collections.singletonList("after_consent_again"), TestUtils.keysInEQ()); + } + + /** + * Events carry the view IDs of the views module that runs now. + *

+ * Verifies that while the views consent is removed an event carries no current view ID, and that + * once it is given again an event carries the ID of the view the new module started, as does the + * next view as its previous one. + */ + @Test + public void viewIds_followTheViewsModuleThatRuns_acrossAViewsConsentChange() { + Countly.instance().init(TestUtils.getBaseConfig().enableFeatures(Config.Feature.Events, Config.Feature.Views) + .setRequiresConsent(true).setEventQueueSizeToSend(100)); + Countly.onConsent(Config.Feature.Events, Config.Feature.Views); + Assert.assertNotNull(Countly.instance().views().startView("first")); + + Countly.onConsentRemoval(Config.Feature.Views); + Countly.instance().events().recordEvent("without_views"); + Countly.onConsent(Config.Feature.Views); + String second = Countly.instance().views().startView("second"); + Countly.instance().events().recordEvent("with_views"); + Countly.instance().views().startView("third"); + + List queued = TestUtils.getCurrentEQ(); + Assert.assertEquals(Arrays.asList(ModuleViews.KEY_VIEW_EVENT, "without_views", ModuleViews.KEY_VIEW_EVENT, "with_views", ModuleViews.KEY_VIEW_EVENT), TestUtils.keysInEQ()); + Assert.assertTrue(Utils.isEmptyOrNull(queued.get(1).cvid)); + Assert.assertEquals(second, queued.get(3).cvid); + Assert.assertEquals(second, queued.get(4).pvid); + } + + /** + * A module that fails on a timer tick is logged and the timer keeps ticking for every module. + */ + @Test + public void aModuleFailingOnATick_doesNotStopTheTimer() throws InterruptedException { + AtomicInteger ticks = new AtomicInteger(); + SDKCore.testDummyModule = new ModuleBase() { + /** + * Counts the tick and fails on the first one. + */ + @Override + public void onTimer() { + if (ticks.incrementAndGet() == 1) { + throw new IllegalStateException("failing on the first tick"); + } + } + }; + try { + Countly.instance().init(TestUtils.getBaseConfig().setUpdateSessionTimerDelay(1)); + long deadline = System.currentTimeMillis() + 10_000; + while (ticks.get() < 2 && System.currentTimeMillis() < deadline) { + Thread.sleep(50); + } + Assert.assertTrue("ticks: " + ticks.get(), ticks.get() >= 2); + } finally { + SDKCore.testDummyModule = null; + } + } + + /** + * The deprecated API and the user editor log no user data before the feature it belongs to + * checks its consent, as such a line can be gathered for the server under another consent. + */ + @Test + public void deprecatedCallsAndTheUserEditor_logNoUserData_beforeTheirConsentCheck() { + List lines = new CopyOnWriteArrayList<>(); + Countly.instance().init(TestUtils.getBaseConfig().setRequiresConsent(true).setLoggingLevel(Config.LoggingLevel.VERBOSE) + .enableFeatures(Config.Feature.Sessions, Config.Feature.Location, Config.Feature.Views, Config.Feature.CrashReporting, Config.Feature.UserProfiles) + .setLogListener((message, level) -> { + if (message.startsWith("[Countly]") || message.startsWith("[UserEditorImpl]")) { + lines.add(message); + } + })); + Countly.onConsent(Config.Feature.Sessions); + Map segments = new HashMap<>(); + segments.put("secret_key", "secret_value"); + + Countly.api().addLocation(12.345_678, 98.765_432); + Countly.api().view("SecretViewName"); + Countly.api().addCrashReport(new RuntimeException("secret crash message"), false, "secret_crash_name", segments); + Countly.api().addParam("param_key", "secret_param_value"); + Countly.instance().user().edit().setLocale("tr_TR").setCountry("TR_country").setCity("SecretCity") + .setLocation(1.234_567, 2.345_678).setLocation("38.456789,27.123456").setLocation("not a location").commit(); + + Assert.assertFalse(lines.isEmpty()); + for (String line : lines) { + for (String secret : Arrays.asList("12.345678", "SecretViewName", "secret", "tr_TR", "TR_country", "SecretCity", "1.234567", "38.456789", "not a location")) { + Assert.assertFalse(line, line.contains(secret)); + } + } + } + + /** + * Removing a consent stops the modules of the features it names and no others, so the device ID + * module, which has no consent of its own, keeps running. + *

+ * Verifies that after the location consent is removed the location interface ignores calls while + * the device ID, events, views and user profile interfaces keep working and recording, and that + * an events interface kept from before the events consent is removed ignores calls instead of + * recording into the stopped module. + */ + @Test + public void consentRemoval_stopsOnlyTheFeaturesItNames_andAKeptInterfaceIgnoresCalls() { + Countly.instance().init(TestUtils.getBaseConfig() + .enableFeatures(Config.Feature.Events, Config.Feature.Views, Config.Feature.Location, Config.Feature.UserProfiles) + .setRequiresConsent(true).setEventQueueSizeToSend(100)); + Countly.onConsent(Config.Feature.values()); + ModuleEvents.Events keptEvents = Countly.instance().events(); + + Countly.onConsentRemoval(Config.Feature.Location); + + Assert.assertFalse(Countly.isTracking(Config.Feature.Location)); + Assert.assertSame(SDKCore.dormantLocation, Countly.instance().location()); + Assert.assertEquals(TestUtils.DEVICE_ID, Countly.instance().deviceId().getID()); + Assert.assertSame(keptEvents, Countly.instance().events()); + keptEvents.recordEvent("after_location_removal"); + Countly.instance().views().startView("home"); + Assert.assertEquals(2, TestUtils.getCurrentEQ().size()); + Countly.instance().userProfile().setProperty("plan", "pro"); + Countly.instance().userProfile().save(); + Assert.assertEquals(1, requestsContaining("user_details")); + + Countly.onConsentRemoval(Config.Feature.Events); + + Assert.assertSame(SDKCore.dormantEvents, Countly.instance().events()); + keptEvents.recordEvent("after_events_removal"); + Assert.assertFalse(keptEvents.startEvent("timed_after_events_removal")); + TestUtils.validateEQSize(0); + Assert.assertEquals(TestUtils.DEVICE_ID, Countly.instance().deviceId().getID()); + } + + /** + * Consent changes add and remove modules while the transport hands responses to their owners, + * and every response still reaches its owner. + *

+ * Verifies that while another thread keeps giving and removing a consent, handing responses + * over throws nothing and each one reaches the module that owns the request, that the consent + * changes throw nothing either, and that the last removal took effect. + */ + @Test + public void requestCompletions_reachTheirOwner_whileConsentChangesAddAndRemoveModules() throws InterruptedException { + AtomicInteger delivered = new AtomicInteger(); + SDKCore.testDummyModule = new ModuleBase() { + /** + * Counts a response handed over. + * + * @param request the request that was sent + * @param response the response body + * @param responseCode the response code + */ + @Override + public void onRequestCompleted(Request request, String response, int responseCode) { + delivered.incrementAndGet(); + } + }; + try { + Countly.instance().init(TestUtils.getBaseConfig().enableFeatures(Config.Feature.Feedback).setRequiresConsent(true)); + SDKCore core = SDKCore.instance; + Class owner = SDKCore.testDummyModule.getClass(); + Request request = ModuleRequests.nonSessionRequest(core.config); + List failures = new CopyOnWriteArrayList<>(); + AtomicInteger handedOver = new AtomicInteger(); + AtomicBoolean changingConsents = new AtomicBoolean(true); + + Thread completions = new Thread(() -> { + while (changingConsents.get()) { + try { + core.onRequestCompleted(request, "{\"result\":\"Success\"}", 200, owner); + handedOver.incrementAndGet(); + } catch (Throwable t) { + failures.add(t); + return; + } + } + }); + completions.start(); + try { + for (int i = 0; i < 2000 && failures.isEmpty(); i++) { + Countly.onConsent(Config.Feature.Feedback); + Countly.onConsentRemoval(Config.Feature.Feedback); + } + } catch (RuntimeException e) { + failures.add(e); + } finally { + changingConsents.set(false); + completions.join(30_000); + } + + Assert.assertFalse(completions.isAlive()); + Assert.assertTrue("failed: " + failures, failures.isEmpty()); + Assert.assertTrue(handedOver.get() > 0); + Assert.assertEquals(handedOver.get(), delivered.get()); + Assert.assertSame(SDKCore.dormantFeedback, Countly.instance().feedback()); + } finally { + SDKCore.testDummyModule = null; + } } // endregion diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/CrashFlowTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/CrashFlowTests.java index 2b488c34f..7a0f0cc62 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/CrashFlowTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/CrashFlowTests.java @@ -3,6 +3,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; import ly.count.sdk.java.Config; import ly.count.sdk.java.Countly; import ly.count.sdk.java.Crash; @@ -138,8 +139,36 @@ public void crashReporting_refusesBadInputAndStandsDownUnderBackendMode() { } /** - * Consent gating. With consent required and CrashReporting not granted the interface is withheld - * entirely; once granted the crash flows. + * With consent required, an unhandled crash is recorded once the crash reporting consent is given + * after init, and still reaches the handler the application installed. + */ + @Test + public void unhandledCrash_isRecorded_whenTheConsentIsGivenAfterInit() throws InterruptedException { + Thread.UncaughtExceptionHandler before = Thread.getDefaultUncaughtExceptionHandler(); + List reachedTheApp = new CopyOnWriteArrayList<>(); + Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> reachedTheApp.add(throwable)); + try { + Countly.instance().init(TestUtils.getBaseConfig().enableFeatures(Config.Feature.CrashReporting).setRequiresConsent(true)); + Countly.onConsent(Config.Feature.CrashReporting); + + Thread crashing = new Thread(() -> { + throw new IllegalStateException("unhandled after consent"); + }); + crashing.start(); + crashing.join(); + Storage.await(SDKCore.instance.config.getLogger()); + + Assert.assertEquals(1, reachedTheApp.size()); + Assert.assertEquals(1, crashRequestCount()); + } finally { + Countly.instance().halt(); + Thread.setDefaultUncaughtExceptionHandler(before); + } + } + + /** + * Consent gating. With consent required and CrashReporting not granted the interface ignores every + * call; once granted the crash flows. */ @Test public void crashReporting_isGatedOnConsent() { @@ -148,7 +177,8 @@ public void crashReporting_isGatedOnConsent() { .setRequiresConsent(true); Countly.instance().init(config); - Assert.assertNull("no consent means no crash interface", Countly.instance().crashes()); + Assert.assertSame("no consent means a crash interface that ignores calls", SDKCore.dormantCrashes, Countly.instance().crashes()); + Countly.instance().crashes().recordHandledException(new RuntimeException("before consent")); Countly.onConsent(Config.Feature.CrashReporting); Assert.assertNotNull(Countly.instance().crashes()); diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/DefaultNetworkingRecheckTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/DefaultNetworkingRecheckTests.java new file mode 100644 index 000000000..c6c071df2 --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/DefaultNetworkingRecheckTests.java @@ -0,0 +1,79 @@ +package ly.count.sdk.java.internal; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import ly.count.sdk.java.Countly; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import static org.mockito.Mockito.mock; + +/** + * The checks {@link DefaultNetworking} keeps while it drains the request queue. + */ +@RunWith(JUnit4.class) +public class DefaultNetworkingRecheckTests { + + @Before + public void beforeTest() { + TestUtils.createCleanTestState(); + } + + @After + public void afterTest() { + Countly.instance().halt(); + } + + /** + * A drain that fails still runs the check asked for while it ran, so a request queued meanwhile + * does not wait for the next check. + */ + @Test + public void aFailingDrain_stillRunsTheCheckAskedForMeanwhile() throws Exception { + Countly.instance().init(TestUtils.getBaseConfig()); + InternalConfig config = SDKCore.instance.config; + CountDownLatch firstDrainRuns = new CountDownLatch(1); + CountDownLatch checkAskedFor = new CountDownLatch(1); + CountDownLatch nextDrainRan = new CountDownLatch(1); + AtomicInteger drains = new AtomicInteger(); + DefaultNetworking networking = new DefaultNetworking() { + /** + * Fails the first drain once a check was asked for while it ran, and records the next. + */ + @Override + protected Tasks.Task submit(InternalConfig config, boolean followsOwnTransportWork) { + return new Tasks.Task(Tasks.ID_STRICT) { + /** + * Fails the first time, after the check was asked for, and records the next. + */ + @Override + public Boolean call() throws Exception { + if (drains.incrementAndGet() == 1) { + firstDrainRuns.countDown(); + Assert.assertTrue(checkAskedFor.await(10, TimeUnit.SECONDS)); + throw new IllegalStateException("the first drain fails"); + } + nextDrainRan.countDown(); + return false; + } + }; + } + }; + networking.init(config, mock(IStorageForRequestQueue.class)); + try { + networking.check(config); + Assert.assertTrue(firstDrainRuns.await(10, TimeUnit.SECONDS)); + networking.check(config); + checkAskedFor.countDown(); + + Assert.assertTrue("the check asked for during the failing drain never ran", nextDrainRan.await(10, TimeUnit.SECONDS)); + } finally { + networking.stop(config); + } + } +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/GzipStandInRequest.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/GzipStandInRequest.java new file mode 100644 index 000000000..2e5595c58 --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/GzipStandInRequest.java @@ -0,0 +1,82 @@ +package ly.count.sdk.java.internal; + +import com.sun.net.httpserver.HttpExchange; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.zip.GZIPInputStream; + +/** + * One request as {@link GzipStandInServer} received it: the body decoded and its parameters read + * the way the Countly server reads them, which takes a body as gzip only when the compression + * marker is the only query of the URL. + */ +final class GzipStandInRequest { + + static final String MARKER_QUERY = "content_encoding=gzip"; + + final String method; + final String path; + final boolean compressed; + final String body; + final int bodyBytes; + final String contentType; + final String contentEncoding; + final Map params; + final AtomicBoolean answered = new AtomicBoolean(false); + + /** + * Reads a request from its exchange. + * + * @param exchange the exchange the request arrived in + * @throws IOException when the body cannot be read or decoded + */ + GzipStandInRequest(HttpExchange exchange) throws IOException { + method = exchange.getRequestMethod(); + path = exchange.getRequestURI().getPath(); + String query = exchange.getRequestURI().getRawQuery(); + compressed = MARKER_QUERY.equals(query); + byte[] raw = readAll(exchange.getRequestBody()); + bodyBytes = raw.length; + body = new String(compressed ? gunzip(raw) : raw, StandardCharsets.UTF_8); + contentType = exchange.getRequestHeaders().getFirst("Content-Type"); + contentEncoding = exchange.getRequestHeaders().getFirst("Content-Encoding"); + params = TestUtils.parseQueryParams(compressed || !Utils.isNotEmpty(query) ? body : query); + params.replaceAll((key, value) -> Utils.urldecode(value)); + } + + /** + * Decodes gzip bytes. + * + * @param compressed gzip bytes + * @return the decoded bytes + * @throws IOException when the bytes are not gzip + */ + static byte[] gunzip(byte[] compressed) throws IOException { + try (InputStream in = new GZIPInputStream(new ByteArrayInputStream(compressed))) { + return readAll(in); + } + } + + /** + * Reads a stream to its end. + * + * @param stream the stream to read + * @return every byte of the stream + * @throws IOException when the stream cannot be read + */ + static byte[] readAll(InputStream stream) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[8192]; + int read = stream.read(buffer); + while (read != -1) { + out.write(buffer, 0, read); + read = stream.read(buffer); + } + return out.toByteArray(); + } +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/GzipStandInServer.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/GzipStandInServer.java new file mode 100644 index 000000000..558ec569c --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/GzipStandInServer.java @@ -0,0 +1,161 @@ +package ly.count.sdk.java.internal; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import org.json.JSONObject; +import org.junit.Assert; + +/** + * A Countly server stand-in on loopback for the request compression tests, which records every + * request. It answers the SDK behavior settings with the answer set by {@link #answer(int, boolean)}, + * remote config with {@link #remoteConfigCode} and {@link #remoteConfigAnswer}, and anything else + * with success; it can refuse or drop compressed requests and hold its settings answer until a + * latch opens. + */ +final class GzipStandInServer { + + final HttpServer http; + final List received = new CopyOnWriteArrayList<>(); + final AtomicReference settingsAnswer = new AtomicReference<>("{}"); + final AtomicReference remoteConfigAnswer = new AtomicReference<>("{}"); + final AtomicInteger remoteConfigCode = new AtomicInteger(200); + final AtomicInteger refuseCompressed = new AtomicInteger(0); + final AtomicBoolean dropCompressed = new AtomicBoolean(false); + final AtomicReference holdSettings = new AtomicReference<>(null); + + /** + * Starts the server on a free loopback port. + * + * @throws IOException when the server cannot start + */ + GzipStandInServer() throws IOException { + http = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + http.createContext("/", this::handle); + http.setExecutor(Executors.newCachedThreadPool()); + http.start(); + } + + /** + * Sets the settings answer: an {@code lkl} value that tells it apart, with "gzip": true when + * the server reads compressed bodies. + * + * @param lkl the key length limit of the answer + * @param gzip whether the answer says that the server reads compressed bodies + */ + void answer(int lkl, boolean gzip) { + JSONObject answer = new JSONObject().put("v", 1).put("t", 1_700_000_000_000L).put("c", new JSONObject().put("lkl", lkl)); + if (gzip) { + answer.put("gzip", true); + } + settingsAnswer.set(answer.toString()); + } + + /** + * Records a request and answers it. + * + * @param exchange the exchange the request arrived in + * @throws IOException when the request cannot be read or answered + */ + private void handle(HttpExchange exchange) throws IOException { + GzipStandInRequest request = new GzipStandInRequest(exchange); + received.add(request); + String method = request.params.get("method"); + int code = 200; + String response = "{\"result\":\"Success\"}"; + if ("sc".equals(method)) { + CountDownLatch hold = holdSettings.get(); + if (hold != null) { + try { + hold.await(15, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + response = settingsAnswer.get(); + } else if ("rc".equals(method)) { + code = remoteConfigCode.get(); + response = remoteConfigAnswer.get(); + } + if (request.compressed && dropCompressed.get()) { + exchange.close(); + return; + } + if (request.compressed && refuseCompressed.getAndUpdate(left -> left > 0 ? left - 1 : 0) > 0) { + code = 400; + response = "{\"result\":\"Invalid request body\"}"; + } + byte[] out = response.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(code, out.length == 0 ? -1 : out.length); + try (OutputStream stream = exchange.getResponseBody()) { + stream.write(out); + } + request.answered.set(true); + } + + /** + * The URL the SDK reaches this server at. + * + * @return the server URL + */ + String url() { + return "http://127.0.0.1:" + http.getAddress().getPort(); + } + + /** + * How many received requests match. + * + * @param filter the requests to count + * @return the number of matching requests + */ + int count(Predicate filter) { + return (int) received.stream().filter(filter).count(); + } + + /** + * Every received request that matches, in arrival order. + * + * @param filter the requests to return + * @return the matching requests + */ + List all(Predicate filter) { + return received.stream().filter(filter).collect(Collectors.toList()); + } + + /** + * Waits for the first matching request and returns it. + * + * @param filter the request to wait for + * @return the first matching request + * @throws InterruptedException when the wait is interrupted + */ + GzipStandInRequest await(Predicate filter) throws InterruptedException { + Assert.assertTrue("no matching request arrived at " + url() + ", it received " + received.size(), TestUtils.waitFor(15_000, () -> count(filter) > 0)); + return received.stream().filter(filter).findFirst().orElse(null); + } + + /** + * Opens a held settings answer and stops the server. + */ + void stop() { + CountDownLatch hold = holdSettings.get(); + if (hold != null) { + hold.countDown(); + } + http.stop(0); + } +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/JsonFileStorageTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/JsonFileStorageTests.java index 8111d5dcc..09fccd1fe 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/JsonFileStorageTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/JsonFileStorageTests.java @@ -4,6 +4,9 @@ import java.io.IOException; import java.math.BigDecimal; import java.nio.file.Files; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import org.json.JSONObject; import org.junit.After; import org.junit.Assert; import org.junit.Test; @@ -238,6 +241,168 @@ public void deleteAndSave() { validateStorageSize(0, 1); } + /** + * "getJsonObj" hands out a deep copy. + *

+ * Verifies that changing the returned object, and an object and an array nested in it, changes + * neither what the storage returns next nor what "save" writes; that a missing key and a value + * that is not an object return the default; that the changed copy is stored once it is handed back + * through "addAndSave"; and that saving on one thread while another changes its copy and stores it, + * as the remote config values are, never fails to serialize and leaves every key on disk. + */ + @Test + public void getJsonObj_returnsADeepCopy_soAChangeReachesTheStorageOnlyThroughAdd() throws InterruptedException { + Log logger = Mockito.mock(Log.class); + setupJsonFile("{\"rc\":{\"color\":{\"v\":\"red\",\"c\":1},\"list\":[{\"a\":1}]},\"plain\":\"text\"}"); + storage = new JsonFileStorage(jsonFile(), logger); + + JSONObject copy = storage.getJsonObj("rc", null); + copy.getJSONObject("color").put("c", 0); + copy.getJSONArray("list").getJSONObject(0).put("a", 2); + copy.put("size", "large"); + + JSONObject stored = storage.getJsonObj("rc", null); + Assert.assertNotSame(copy, stored); + Assert.assertEquals(1, stored.getJSONObject("color").getInt("c")); + Assert.assertEquals(1, stored.getJSONArray("list").getJSONObject(0).getInt("a")); + Assert.assertFalse(stored.has("size")); + storage.save(); + Assert.assertTrue(stored.similar(TestUtils.readJsonFile(jsonFile()).getJSONObject("rc"))); + + JSONObject fallback = new JSONObject(); + Assert.assertSame(fallback, storage.getJsonObj("missing", fallback)); + Assert.assertSame(fallback, storage.getJsonObj("plain", fallback)); + Assert.assertNull(storage.getJsonObj("missing", null)); + + storage.addAndSave("rc", copy); + Assert.assertTrue(copy.similar(storage.getJsonObj("rc", null))); + Assert.assertTrue(copy.similar(TestUtils.readJsonFile(jsonFile()).getJSONObject("rc"))); + + storage.add("device", "device_id"); + List failures = new CopyOnWriteArrayList<>(); + long deadline = System.currentTimeMillis() + 400; + Thread changer = new Thread(() -> { + try { + for (int round = 0; System.currentTimeMillis() < deadline; round++) { + JSONObject values = storage.getJsonObj("rc", new JSONObject()); + for (int i = 0; i < 50; i++) { + values.put("key_" + ((round * 50 + i) % 400), new JSONObject().put("v", i).put("c", 1)); + } + for (int i = 0; i < 20; i++) { + values.remove("key_" + ((round * 37 + i) % 400)); + } + storage.add("rc", values); + } + } catch (Throwable t) { + failures.add(t); + } + }); + changer.start(); + try { + while (System.currentTimeMillis() < deadline) { + storage.save(); + } + } catch (Throwable t) { + failures.add(t); + } + changer.join(); + + Assert.assertTrue("failures: " + failures, failures.isEmpty()); + Mockito.verify(logger, Mockito.never()).e(Mockito.startsWith("[JsonFileStorage] save, Failed to serialize")); + storage.save(); + JSONObject onDisk = TestUtils.readJsonFile(jsonFile()); + Assert.assertEquals("device_id", onDisk.getString("device")); + Assert.assertEquals("text", onDisk.getString("plain")); + Assert.assertTrue(onDisk.getJSONObject("rc").similar(storage.getJsonObj("rc", null))); + } + + /** + * "save" when the data cannot be serialized. + *

+ * Verifies that the file keeps what it had instead of being emptied, and that the failure is logged. + */ + @Test + public void save_leavesTheFileAsItIs_whenTheDataCannotBeSerialized() { + Log logger = Mockito.mock(Log.class); + setupJsonFile("{\"device\":\"device_id\"}"); + storage = new JsonFileStorage(jsonFile(), logger); + storage.add("broken", new JSONObject() { + /** + * Fails as a value that cannot be serialized does. + * + * @param writer the writer + * @param indentFactor the indentation of each level + * @param indent the indentation of this level + * @return never + */ + @Override + public java.io.Writer write(java.io.Writer writer, int indentFactor, int indent) { + throw new IllegalStateException("cannot be written"); + } + }); + + storage.save(); + + Assert.assertEquals("device_id", TestUtils.readJsonFile(jsonFile()).getString("device")); + Assert.assertFalse(TestUtils.readJsonFile(jsonFile()).has("broken")); + Mockito.verify(logger).e(Mockito.startsWith("[JsonFileStorage] save, Failed to serialize the data")); + } + + /** + * A json file cut short, as a process stopped while writing leaves it, does not stop the storage. + *

+ * Verifies that the storage starts empty, that the failure is logged, and that the next save + * replaces the broken file with valid json. + */ + @Test + public void readJsonFile_brokenJson_startsEmptyAndTheNextSaveReplacesIt() { + Log logger = Mockito.mock(Log.class); + setupJsonFile("{\"did\":\"generated_uuid\",\"sc\":\"{\\\"c\\\":{"); + storage = new JsonFileStorage(jsonFile(), logger); + + Assert.assertEquals(0, storage.size()); + Mockito.verify(logger).e(Mockito.startsWith("[JsonFileStorage] readJsonFile, The json file is not valid json")); + + storage.addAndSave("key", "value"); + Assert.assertEquals("value", TestUtils.readJsonFile(jsonFile()).getString("key")); + } + + /** + * "save" writes next to the file and moves the result over it. + *

+ * Verifies that the file holds what was stored before and what was added, and that no temporary + * file is left behind. + */ + @Test + public void save_replacesTheFileWhole_andLeavesNoTemporaryFile() { + setupJsonFile("{\"old\":\"value\"}"); + storage = new JsonFileStorage(jsonFile(), L); + storage.addAndSave("new", "value"); + + JSONObject saved = TestUtils.readJsonFile(jsonFile()); + Assert.assertEquals("value", saved.getString("old")); + Assert.assertEquals("value", saved.getString("new")); + Assert.assertFalse(JsonFileStorage.temporaryFileOf(jsonFile()).exists()); + } + + /** + * The temporary file of a save stopped before its move is deleted when the storage opens. + *

+ * Verifies that the storage reads the json file, which holds the previous save, and that the + * leftover file is gone, so it is not taken for other stored SDK data. + */ + @Test + public void constructor_deletesTheTemporaryFileOfAnInterruptedSave() throws IOException { + setupJsonFile("{\"saved\":\"before\"}"); + File leftover = JsonFileStorage.temporaryFileOf(jsonFile()); + Files.write(leftover.toPath(), "{\"saved\":".getBytes()); + + storage = new JsonFileStorage(jsonFile(), L); + + Assert.assertEquals("before", storage.getString("saved")); + Assert.assertFalse(leftover.exists()); + } + private static File jsonFile() { return new File(TestUtils.getTestSDirectory(), JSON_FILE_NAME); } diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/LogTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/LogTests.java index 9d7c95a4a..965d7dcf8 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/LogTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/LogTests.java @@ -1,5 +1,20 @@ package ly.count.sdk.java.internal; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Deque; +import java.util.List; +import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import javax.annotation.Nonnull; +import ly.count.sdk.java.internal.ConfigurationProvider.LogGatheringState; +import org.json.JSONArray; +import org.json.JSONObject; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -12,6 +27,7 @@ import static ly.count.sdk.java.Config.LoggingLevel.ERROR; import static ly.count.sdk.java.Config.LoggingLevel.INFO; import static ly.count.sdk.java.Config.LoggingLevel.OFF; +import static ly.count.sdk.java.Config.LoggingLevel.VERBOSE; import static ly.count.sdk.java.Config.LoggingLevel.WARN; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -24,6 +40,43 @@ public class LogTests { private static final Throwable exception = new IllegalStateException("IAS"); private InternalConfig config; + private final List handedOver = new ArrayList<>(); + private final List queuedBatches = new CopyOnWriteArrayList<>(); + //the storage IDs of the batches the played request queue still holds, oldest first + private final Deque waitingBatchIds = new ConcurrentLinkedDeque<>(); + private final AtomicLong nextRequestId = new AtomicLong(1); + private final AtomicInteger queueAttempts = new AtomicInteger(); + private volatile boolean queueAccepts = true; + + /** + * Plays the request queue: records each batch, or refuses it while {@link #queueAccepts} is off, + * and holds it until {@link #sendOldestBatch(Log)}. + */ + private final Log.LogBatchQueue queue = new Log.LogBatchQueue() { + /** + * Records the batch and holds it, or refuses it. + */ + @Override + public Long queueLogBatch(@Nonnull String payload) { + queueAttempts.incrementAndGet(); + if (!queueAccepts) { + return null; + } + queuedBatches.add(new JSONObject(payload)); + long requestId = nextRequestId.getAndIncrement(); + waitingBatchIds.addLast(requestId); + return requestId; + } + + /** + * Whether the batch was not sent yet. + */ + @Override + public boolean isQueued(@Nonnull Long requestId) { + return waitingBatchIds.contains(requestId); + } + }; + @Before public void setupEveryTest() { String serverUrl = "http://www.serverurl.com"; @@ -33,6 +86,9 @@ public void setupEveryTest() { @After public void cleanupEveryTests() { + for (Log log : handedOver) { + log.endLogGathering(false); + } config = null; } @@ -40,4 +96,622 @@ public void cleanupEveryTests() { public void logInit_null() { Log log = new Log(null, null); } + + /** + * Every level method prints as the print level says and informs the listener, and it feeds the + * capture whatever the print level. + *

+ * Verifies, for a logger printing nothing, only errors and everything, that the listener hears + * every line with its level, that the print level stays as configured, that every line waits for + * its consent while no consent provider is set, and that an armed directive uploads them with + * their level characters. + */ + @Test + public void levelMethods_informTheListenerAndFeedTheCapture_whateverThePrintLevel() throws Exception { + for (Config.LoggingLevel printLevel : new Config.LoggingLevel[] { OFF, ERROR, VERBOSE }) { + List heard = new ArrayList<>(); + Log log = new Log(printLevel, (logMessage, level) -> heard.add(level + " " + logMessage)); + log.v("aa"); + log.d("bb"); + log.i("cc"); + log.w("dd"); + log.e("ee"); + + Assert.assertEquals(Arrays.asList("VERBOSE aa", "DEBUG bb", "INFO cc", "WARN dd", "ERROR ee"), heard); + Assert.assertEquals(printLevel, log.getPrintLevel()); + Assert.assertEquals(LogGatheringState.UNDECIDED, log.logGatheringState); + Assert.assertEquals(5, log.awaitingConsentLineCount()); + + queuedBatches.clear(); + handOver(log, settings(LogGatheringState.GATHERING, "gather_levels", ModuleConfiguration.logGatheringAllLevels, 100)); + log.onSdkInitFinished(); + awaitDelivery(log); + JSONArray lines = queuedBatches.get(0).getJSONArray("l"); + String[] expected = { "v aa", "d bb", "i cc", "w dd", "e ee" }; + for (int i = 0; i < expected.length; i++) { + JSONObject line = lines.getJSONObject(i); + Assert.assertEquals(expected[i], line.getString("l") + " " + line.getString("m")); + } + } + } + + /** + * The buffer holds at most 500 lines and 128 KB of characters, dropping the oldest lines and + * counting them, and a message is cut to what the server keeps. + *

+ * Verifies both ceilings with the drop count and the character count they leave, that the first + * batch reports every dropped line in {@code d}, and that a message is cut at 4096 characters, + * or one less where the cut would split a surrogate pair. + */ + @Test + public void buffer_holdsAtMost500LinesAnd128KB_droppingTheOldestIntoD_andCutsLongMessages() throws Exception { + Log lines = new Log(OFF, null); + handOver(lines, settings(LogGatheringState.UNDECIDED, null, ModuleConfiguration.logGatheringAllLevels, ModuleConfiguration.logGatheringDefaultBatchSize)); + int handOverLines = lines.heldLogLineCount(); + for (int i = 0; i < 600; i++) { + lines.e("line " + i); + } + Assert.assertEquals(ModuleConfiguration.logGatheringMaxBufferedLines, lines.heldLogLineCount()); + Assert.assertEquals(handOverLines + 100, lines.droppedLogLineCount); + + Log characters = new Log(OFF, null); + handOver(characters, settings(LogGatheringState.GATHERING, "gather_characters", "e", 500)); + String longest = repeat('x', Log.maxMessageLength); + for (int i = 0; i < 40; i++) { + characters.e(longest); + } + int fitting = Log.gatheredCharCeiling / Log.maxMessageLength; + Assert.assertEquals(fitting, characters.heldLogLineCount()); + Assert.assertEquals(40 - fitting, characters.droppedLogLineCount); + Assert.assertEquals(Log.gatheredCharCeiling, characters.gatheredChars); + + characters.onSdkInitFinished(); + awaitDelivery(characters); + Assert.assertEquals(1, queuedBatches.size()); + Assert.assertEquals(40 - fitting, queuedBatches.get(0).getInt("d")); + Assert.assertEquals(fitting, queuedBatches.get(0).getJSONArray("l").length()); + + Log cut = new Log(OFF, null); + cut.e(repeat('y', 5000)); + cut.e(repeat('z', Log.maxMessageLength - 1) + "\uD83D\uDE00 after the pair"); + cut.e("short"); + queuedBatches.clear(); + handOver(cut, settings(LogGatheringState.GATHERING, "gather_cut", "e", 10)); + cut.onSdkInitFinished(); + awaitDelivery(cut); + JSONArray cutLines = queuedBatches.get(0).getJSONArray("l"); + Assert.assertEquals(repeat('y', Log.maxMessageLength), cutLines.getJSONObject(0).getString("m")); + Assert.assertEquals(repeat('z', Log.maxMessageLength - 1), cutLines.getJSONObject(1).getString("m")); + Assert.assertEquals("short", cutLines.getJSONObject(2).getString("m")); + } + + /** + * Once something decides against gathering, capturing costs nothing: no line is held and no + * delivery thread is started. + */ + @Test + public void notGathering_holdsNothing_andStartsNoDeliveryThread() { + Log log = new Log(OFF, null); + log.e("held while undecided"); + Assert.assertEquals(1, log.awaitingConsentLineCount()); + + handOver(log, settings(LogGatheringState.NOT_GATHERING, null, ModuleConfiguration.logGatheringAllLevels, ModuleConfiguration.logGatheringDefaultBatchSize)); + Assert.assertEquals(LogGatheringState.NOT_GATHERING, log.logGatheringState); + Assert.assertFalse(log.isCapturingLogs()); + Assert.assertEquals(0, log.heldLogLineCount()); + Assert.assertEquals(0, log.awaitingConsentLineCount()); + + for (int i = 0; i < 1000; i++) { + log.e("error " + i); + log.v("verbose " + i); + } + log.flushGatheredLogs(); + Assert.assertEquals(0, log.heldLogLineCount()); + Assert.assertEquals(0, log.droppedLogLineCount); + Assert.assertEquals(0, log.gatheredChars); + Assert.assertNull(log.logDeliveryExecutor); + Assert.assertEquals(0, queueAttempts.get()); + } + + /** + * A line that carries an uploaded batch, and a line logged by a thread doing this feature's own + * transport work, are never held, while other threads are captured meanwhile. + */ + @Test + public void selfCapture_batchCarryingLinesAndLinesOfAMarkedThread_areNotHeld() throws InterruptedException { + Log log = new Log(OFF, null); + handOver(log, settings(LogGatheringState.UNDECIDED, null, ModuleConfiguration.logGatheringAllLevels, ModuleConfiguration.logGatheringDefaultBatchSize)); + int handOverLines = log.heldLogLineCount(); + log.d("New request 1: [1] app_key=key&" + Log.transportMarker + "%7B%22i%22%3A%22gather%22%7D"); + Assert.assertEquals(handOverLines, log.heldLogLineCount()); + + log.setOwnTransportWork(true); + log.i("logged while doing transport work"); + Assert.assertEquals(handOverLines, log.heldLogLineCount()); + Thread other = new Thread(() -> log.i("logged by another thread meanwhile")); + other.start(); + other.join(); + Assert.assertEquals(handOverLines + 1, log.heldLogLineCount()); + + log.setOwnTransportWork(false); + log.i("logged once the mark is cleared"); + Assert.assertEquals(handOverLines + 2, log.heldLogLineCount()); + } + + /** + * A batch the queue refuses goes back to the front of the buffer with its drop count, so the + * later deliveries, one batch at a time as each is sent, upload every line in order and still + * report the loss. + */ + @Test + public void refusedBatch_goesBackToTheFrontOfTheBuffer_withItsDropCount() throws Exception { + Log log = new Log(OFF, null); + handOver(log, settings(LogGatheringState.GATHERING, "gather_refused", "e", 100)); + for (int i = 0; i < 505; i++) { + log.e("line " + i); + } + queueAccepts = false; + log.onSdkInitFinished(); + awaitDelivery(log); + Assert.assertEquals(1, queueAttempts.get()); + Assert.assertEquals(ModuleConfiguration.logGatheringMaxBufferedLines, log.heldLogLineCount()); + Assert.assertEquals(5, log.droppedLogLineCount); + + queueAccepts = true; + log.flushGatheredLogs(); + awaitDelivery(log); + sendQueuedBatches(log); + Assert.assertEquals(0, log.heldLogLineCount()); + Assert.assertEquals(5, queuedBatches.size()); + List messages = new ArrayList<>(); + for (int b = 0; b < queuedBatches.size(); b++) { + Assert.assertEquals(b == 0 ? 5 : 0, queuedBatches.get(b).getInt("d")); + messages.addAll(messagesOf(queuedBatches.get(b))); + } + List expected = new ArrayList<>(); + for (int i = 5; i < 505; i++) { + expected.add("line " + i); + } + Assert.assertEquals(expected, messages); + } + + /** + * Ending the gathering queues what is held, synchronously, only when asked, and leaves a logger + * that neither captures nor queues anything, whatever is decided afterwards. + */ + @Test + public void endedGathering_queuesTheHeldLinesOnlyWhenAsked_andIgnoresEverythingAfterwards() throws Exception { + Log kept = new Log(OFF, null); + handOver(kept, settings(LogGatheringState.GATHERING, "gather_end", "e", 100)); + kept.onSdkInitFinished(); + kept.e("tail 1"); + kept.e("tail 2"); + kept.endLogGathering(true); + Assert.assertEquals(1, queuedBatches.size()); + Assert.assertEquals("gather_end", queuedBatches.get(0).getString("i")); + Assert.assertEquals(Arrays.asList("tail 1", "tail 2"), messagesOf(queuedBatches.get(0))); + Assert.assertEquals(LogGatheringState.NOT_GATHERING, kept.logGatheringState); + Assert.assertNull(kept.logDeliveryExecutor); + + kept.setLogGatheringProviders(settings(LogGatheringState.GATHERING, "gather_again", "e", 10), () -> ~0, queue); + kept.e("logged after the end"); + kept.flushGatheredLogs(); + Assert.assertEquals(LogGatheringState.NOT_GATHERING, kept.logGatheringState); + Assert.assertEquals(0, kept.heldLogLineCount()); + Assert.assertNull(kept.logDeliveryExecutor); + Assert.assertEquals(1, queueAttempts.get()); + + Log discarded = new Log(OFF, null); + handOver(discarded, settings(LogGatheringState.GATHERING, "gather_discarded", "e", 100)); + discarded.onSdkInitFinished(); + discarded.e("discarded line"); + discarded.endLogGathering(false); + Assert.assertEquals(1, queueAttempts.get()); + Assert.assertEquals(0, discarded.heldLogLineCount()); + Assert.assertEquals(LogGatheringState.NOT_GATHERING, discarded.logGatheringState); + } + + /** + * A line is gathered only once the consent of the feature it belongs to is given, found from + * the name it starts with in brackets, and a line of no feature needs both the events and the + * user profiles consent. Until then it waits apart, and it joins the gather in capture order. + *

+ * Verifies that every line waits before the providers are set; that with only the sessions + * consent given only the session lines are held; that each consent given releases exactly its + * lines, the line of no feature once both of its consents are given; that the batch keeps the + * order the lines were logged in; and that the waiting lines are capped at 500, oldest first, + * without counting into {@code d}. + */ + @Test + public void perLineConsent_gathersALineOnlyWithTheConsentOfItsFeature_inCaptureOrder() throws Exception { + Log log = new Log(OFF, null); + log.e("[ModuleLocation] setLocation, gps:[12.345678,98.765432]"); + log.e("[SessionImpl] begin"); + Assert.assertEquals(0, log.heldLogLineCount()); + Assert.assertEquals(2, log.awaitingConsentLineCount()); + + AtomicInteger given = new AtomicInteger(CoreFeature.Sessions.getIndex()); + handedOver.add(log); + log.setLogGatheringProviders(settings(LogGatheringState.GATHERING, "gather_consent", "e", 100), given::get, queue); + Assert.assertEquals(1, log.heldLogLineCount()); + log.e("[ModuleEvents] recordEventInternal, key:[purchase]"); + log.e("[Test] a line of no feature"); + log.e("[Views] startView, name:[home]"); + Assert.assertEquals(1, log.heldLogLineCount()); + Assert.assertEquals(4, log.awaitingConsentLineCount()); + + given.set(given.get() | CoreFeature.Events.getIndex()); + log.releaseConsentedLogLines(); + Assert.assertEquals(2, log.heldLogLineCount()); + given.set(given.get() | CoreFeature.UserProfiles.getIndex() | CoreFeature.Location.getIndex()); + log.releaseConsentedLogLines(); + Assert.assertEquals(4, log.heldLogLineCount()); + Assert.assertEquals(1, log.awaitingConsentLineCount()); + + log.onSdkInitFinished(); + awaitDelivery(log); + Assert.assertEquals(1, queuedBatches.size()); + Assert.assertEquals(Arrays.asList("[ModuleLocation] setLocation, gps:[12.345678,98.765432]", "[SessionImpl] begin", + "[ModuleEvents] recordEventInternal, key:[purchase]", "[Test] a line of no feature"), messagesOf(queuedBatches.get(0))); + + for (int i = 0; i < 520; i++) { + log.e("[ModuleViews] waiting line " + i); + } + Assert.assertEquals(ModuleConfiguration.logGatheringMaxBufferedLines, log.awaitingConsentLineCount()); + Assert.assertEquals(0, log.droppedLogLineCount); + } + + /** + * One batch waits in the request queue at a time: until it is sent the lines stay in the + * buffer, and each send lets the next batch go, a partial one included. + *

+ * Verifies that a delivery queues a single batch however many are held; that neither a full + * batch nor a flush queues another while it waits; that each sent batch lets exactly one more + * go, until every line went out once, in order; and that a refused batch does not count as + * waiting. + */ + @Test + public void oneBatchAtATime_holdsTheLinesUntilTheWaitingBatchIsSent() throws Exception { + Log log = new Log(OFF, null); + handOver(log, settings(LogGatheringState.GATHERING, "gather_one", "e", 10)); + for (int i = 0; i < 35; i++) { + log.e("line " + i); + } + log.onSdkInitFinished(); + awaitDelivery(log); + Assert.assertEquals(1, queuedBatches.size()); + Assert.assertEquals(1, waitingBatchIds.size()); + Assert.assertEquals(25, log.heldLogLineCount()); + + log.e("line 35"); + log.flushGatheredLogs(); + awaitDelivery(log); + Assert.assertEquals(1, queuedBatches.size()); + Assert.assertEquals(26, log.heldLogLineCount()); + + for (int sent = 1; sent <= 3; sent++) { + sendOldestBatch(log); + awaitDelivery(log); + Assert.assertEquals(sent + 1, queuedBatches.size()); + Assert.assertEquals(1, waitingBatchIds.size()); + } + sendOldestBatch(log); + awaitDelivery(log); + Assert.assertEquals(4, queuedBatches.size()); + Assert.assertEquals(0, waitingBatchIds.size()); + List messages = new ArrayList<>(); + for (JSONObject batch : queuedBatches) { + messages.addAll(messagesOf(batch)); + } + List expected = new ArrayList<>(); + for (int i = 0; i < 36; i++) { + expected.add("line " + i); + } + Assert.assertEquals(expected, messages); + + queueAccepts = false; + log.e("refused line"); + log.flushGatheredLogs(); + awaitDelivery(log); + Assert.assertEquals(0, waitingBatchIds.size()); + queueAccepts = true; + log.flushGatheredLogs(); + awaitDelivery(log); + Assert.assertEquals(5, queuedBatches.size()); + Assert.assertEquals(Arrays.asList("refused line"), messagesOf(queuedBatches.get(4))); + } + + /** + * The batch waiting in the request queue holds the next one back only while the queue holds it, + * and its send resumes only a delivery it held back. + *

+ * Verifies that a batch the queue dropped without sending, as when the queue is over its size, + * no longer holds the lines back on the next flush; that a send that held nothing back queues + * nothing, so a line logged meanwhile waits for the next flush; and that a send after a delivery + * it held back queues the line that waited, a partial batch. + */ + @Test + public void theWaitingBatch_holdsTheNextBackOnlyWhileQueued_andItsSendResumesOnlyADeliveryItHeldBack() throws Exception { + Log log = new Log(OFF, null); + handOver(log, settings(LogGatheringState.GATHERING, "gather_waiting", "e", 10)); + log.e("line 0"); + log.onSdkInitFinished(); + awaitDelivery(log); + log.e("line 1"); + log.flushGatheredLogs(); + awaitDelivery(log); + Assert.assertEquals(1, queuedBatches.size()); + Assert.assertEquals(1, log.heldLogLineCount()); + + waitingBatchIds.clear(); + log.flushGatheredLogs(); + awaitDelivery(log); + Assert.assertEquals(2, queuedBatches.size()); + Assert.assertEquals(Collections.singletonList("line 1"), messagesOf(queuedBatches.get(1))); + + log.e("line 2"); + sendOldestBatch(log); + awaitDelivery(log); + Assert.assertEquals(2, queuedBatches.size()); + Assert.assertEquals(1, log.heldLogLineCount()); + + log.flushGatheredLogs(); + awaitDelivery(log); + log.e("line 3"); + log.flushGatheredLogs(); + awaitDelivery(log); + Assert.assertEquals(3, queuedBatches.size()); + sendOldestBatch(log); + awaitDelivery(log); + Assert.assertEquals(4, queuedBatches.size()); + Assert.assertEquals(Collections.singletonList("line 3"), messagesOf(queuedBatches.get(3))); + } + + /** + * A removed consent drops the held lines that needed it, so nothing gathered for a feature goes + * out once its consent is withdrawn, and the lines dropped are reported in {@code d}. + */ + @Test + public void removedConsent_dropsTheHeldLinesThatNeededIt_countingThemIntoD() throws Exception { + Log log = new Log(OFF, null); + AtomicInteger given = new AtomicInteger(CoreFeature.Events.getIndex() | CoreFeature.Location.getIndex() | CoreFeature.UserProfiles.getIndex()); + handedOver.add(log); + log.setLogGatheringProviders(settings(LogGatheringState.GATHERING, "gather_withdrawn", "e", 100), given::get, queue); + log.e("[ModuleEvents] an events line"); + log.e("[ModuleLocation] a location line"); + log.e("[Test] a line of no feature"); + Assert.assertEquals(3, log.heldLogLineCount()); + + given.set(CoreFeature.Events.getIndex()); + log.dropLinesWithoutConsent(); + + Assert.assertEquals(1, log.heldLogLineCount()); + log.onSdkInitFinished(); + awaitDelivery(log); + Assert.assertEquals(Collections.singletonList("[ModuleEvents] an events line"), messagesOf(queuedBatches.get(0))); + Assert.assertEquals(2, queuedBatches.get(0).getInt("d")); + } + + /** + * A gather the server stops queues the lines it still holds once, with its id, while a gather + * replaced by another drops them, and so does a decision against gathering made while nothing + * was decided. + *

+ * Verifies that stopping a gather queues one batch of exactly its held lines, with its id and + * past a batch already waiting; that the capture stops; that a gather replaced by a new id + * queues nothing; and that deciding off while undecided queues nothing. + */ + @Test + public void stoppedGather_queuesItsHeldLinesOnceWithItsId_whileAReplacedGatherDropsThem() throws Exception { + ModuleConfiguration stopped = settings(LogGatheringState.GATHERING, "gather_tail", "e", 10); + Log log = new Log(OFF, null); + handOver(log, stopped); + log.onSdkInitFinished(); + for (int i = 0; i < 13; i++) { + log.e("line " + i); + } + awaitDelivery(log); + Assert.assertEquals(1, queuedBatches.size()); + Assert.assertEquals(3, log.heldLogLineCount()); + + stopped.currentVLogGathering = ModuleConfiguration.LogGatheringDirective.NOT_GATHERING; + log.applyLogGatheringDirective("test"); + Assert.assertTrue("the held lines were not queued", TestUtils.waitFor(10_000, () -> queuedBatches.size() == 2)); + Assert.assertEquals("gather_tail", queuedBatches.get(1).getString("i")); + Assert.assertEquals(0, queuedBatches.get(1).getInt("d")); + Assert.assertEquals(Arrays.asList("line 10", "line 11", "line 12"), messagesOf(queuedBatches.get(1))); + Assert.assertFalse(log.isCapturingLogs()); + log.e("logged after the stop"); + Assert.assertEquals(0, log.heldLogLineCount()); + + ModuleConfiguration replaced = settings(LogGatheringState.GATHERING, "gather_one", "e", 100); + Log other = new Log(OFF, null); + handOver(other, replaced); + other.onSdkInitFinished(); + awaitDelivery(other); + other.e("line of the first gather"); + replaced.currentVLogGathering = new ModuleConfiguration.LogGatheringDirective(LogGatheringState.GATHERING, "gather_two", "e", 100); + other.applyLogGatheringDirective("test"); + awaitDelivery(other); + Assert.assertEquals(0, other.heldLogLineCount()); + + Log undecided = new Log(OFF, null); + undecided.e("line held while undecided"); + handOver(undecided, settings(LogGatheringState.NOT_GATHERING, null, ModuleConfiguration.logGatheringAllLevels, ModuleConfiguration.logGatheringDefaultBatchSize)); + undecided.onSdkInitFinished(); + Thread.sleep(100); + Assert.assertEquals(2, queuedBatches.size()); + Assert.assertEquals(2, queueAttempts.get()); + } + + /** + * Before the device ID changes without merge the gather stops: every held line is queued on + * the calling thread, past a batch already waiting, the lines waiting for their consent are + * dropped, and a later directive can still arm a new gather. + *

+ * Verifies that the held lines are queued before the call returns, in batches of at most + * {@code b} and in order; that a line waiting for its consent is not queued; that nothing is + * captured afterwards; and that a directive applied later arms a gather again. + */ + @Test + public void deviceIdChange_queuesTheHeldLinesThenStops_andALaterDirectiveCanArmAgain() throws Exception { + AtomicInteger given = new AtomicInteger(Log.UNATTRIBUTED_LINE_CONSENT); + ModuleConfiguration settings = settings(LogGatheringState.GATHERING, "gather_did", "e", 10); + Log log = new Log(OFF, null); + handedOver.add(log); + log.setLogGatheringProviders(settings, given::get, queue); + log.onSdkInitFinished(); + for (int i = 0; i < 25; i++) { + log.e("[Test] user A line " + i); + } + log.e("[ModuleLocation] user A location"); + awaitDelivery(log); + Assert.assertEquals(1, queuedBatches.size()); + Assert.assertEquals(1, log.awaitingConsentLineCount()); + + log.stopLogGatheringForDeviceIdChange(); + Assert.assertEquals(3, queuedBatches.size()); + List messages = new ArrayList<>(); + for (JSONObject batch : queuedBatches) { + Assert.assertEquals("gather_did", batch.getString("i")); + Assert.assertTrue(batch.getJSONArray("l").length() <= 10); + messages.addAll(messagesOf(batch)); + } + List expected = new ArrayList<>(); + for (int i = 0; i < 25; i++) { + expected.add("[Test] user A line " + i); + } + Assert.assertEquals(expected, messages); + Assert.assertEquals(LogGatheringState.NOT_GATHERING, log.logGatheringState); + Assert.assertEquals(0, log.awaitingConsentLineCount()); + log.e("[Test] user B line"); + Assert.assertEquals(0, log.heldLogLineCount()); + Assert.assertNull(log.logDeliveryExecutor); + + settings.currentVLogGathering = new ModuleConfiguration.LogGatheringDirective(LogGatheringState.GATHERING, "gather_b", "e", 10); + log.applyLogGatheringDirective("test"); + Assert.assertTrue(log.isGatheringLogs()); + log.e("[Test] user B armed line"); + Assert.assertEquals(1, log.heldLogLineCount()); + } + + /** + * A batch is valid JSON with its keys always in the same order, every message escaped. + */ + @Test + public void batchPayload_isJsonWithItsKeysInOrder_andEscapesEveryMessage() { + String awkward = "quote \" backslash \\ newline \n tab \t closing pair \uD83D\uDE00"; + List lines = Arrays.asList(new Log.LogLine(0, 1_755_500_000_000L, 'e', awkward, 0), new Log.LogLine(1, 1_755_500_000_001L, 'd', "", 0)); + String payload = Log.buildLogBatchPayload("gather \"quoted\"", 3, lines); + Assert.assertTrue(payload, payload.startsWith("{\"i\":\"gather \\\"quoted\\\"\",\"d\":3,\"l\":[{\"t\":1755500000000,\"l\":\"e\",\"m\":\"")); + + JSONObject batch = new JSONObject(payload); + Assert.assertEquals("gather \"quoted\"", batch.getString("i")); + Assert.assertEquals(3, batch.getInt("d")); + JSONArray parsed = batch.getJSONArray("l"); + Assert.assertEquals(2, parsed.length()); + Assert.assertEquals(1_755_500_000_000L, parsed.getJSONObject(0).getLong("t")); + Assert.assertEquals("e", parsed.getJSONObject(0).getString("l")); + Assert.assertEquals(awkward, parsed.getJSONObject(0).getString("m")); + Assert.assertEquals("d", parsed.getJSONObject(1).getString("l")); + Assert.assertEquals("", parsed.getJSONObject(1).getString("m")); + + Assert.assertEquals("{\"i\":\"gather\",\"d\":0,\"l\":[]}", Log.buildLogBatchPayload("gather", 0, Collections.emptyList())); + } + + /** + * Settings that hold nothing but the given log gathering directive. + * + * @param state the decision + * @param gatherId the gather id + * @param levels the level characters + * @param batchSize the batch size + * @return the settings + */ + private static ModuleConfiguration settings(LogGatheringState state, String gatherId, String levels, int batchSize) { + ModuleConfiguration settings = new ModuleConfiguration(); + settings.currentVLogGathering = new ModuleConfiguration.LogGatheringDirective(state, gatherId, levels, batchSize); + return settings; + } + + /** + * Hands a logger the given settings, every consent given and {@link #queue}, as an SDK + * that requires no consent does once its settings are resolved. Nothing is uploaded before the + * test tells the logger that init finished. + * + * @param log the logger + * @param settings the settings + */ + private void handOver(Log log, ModuleConfiguration settings) { + handedOver.add(log); + log.setLogGatheringProviders(settings, () -> ~0, queue); + } + + /** + * Waits until every delivery the logger was asked for so far ran. + * + * @param log the logger + * @throws Exception when the delivery thread does not finish in time + */ + private static void awaitDelivery(Log log) throws Exception { + ExecutorService executor = log.logDeliveryExecutor; + if (executor != null) { + executor.submit(() -> { + }).get(10, TimeUnit.SECONDS); + } + } + + /** + * Plays the request queue sending every batch the logger queued, one at a time, each send + * letting the logger queue its next batch, until none waits. + * + * @param log the logger + * @throws Exception when a delivery does not finish in time + */ + private void sendQueuedBatches(Log log) throws Exception { + for (int i = 0; i < 1000 && !waitingBatchIds.isEmpty(); i++) { + sendOldestBatch(log); + awaitDelivery(log); + } + } + + /** + * Plays the request queue sending its oldest batch, then telling the logger. + * + * @param log the logger + */ + private void sendOldestBatch(Log log) { + waitingBatchIds.pollFirst(); + log.onLogBatchSent(); + } + + /** + * The messages of a batch, in order. + * + * @param batch the batch + * @return the messages + */ + private static List messagesOf(JSONObject batch) { + List messages = new ArrayList<>(); + JSONArray lines = batch.getJSONArray("l"); + for (int i = 0; i < lines.length(); i++) { + messages.add(lines.getJSONObject(i).getString("m")); + } + return messages; + } + + /** + * A text of one character repeated. + * + * @param character the character + * @param count how many times + * @return the text + */ + private static String repeat(char character, int count) { + StringBuilder text = new StringBuilder(count); + for (int i = 0; i < count; i++) { + text.append(character); + } + return text.toString(); + } } 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 new file mode 100644 index 000000000..8e8f83403 --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationContentTests.java @@ -0,0 +1,799 @@ +package ly.count.sdk.java.internal; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import static ly.count.sdk.java.internal.ServerConfigBuilder.names; + +/** + * The content settings and the journey triggers of the SDK behavior settings: {@code ecz}, + * {@code czi}, {@code rcz}, {@code jte} and {@code jtv}, observed through the public API. + *

+ * Settings requests and content fetches go through a {@link SettingsAndContentServer}, which answers + * on the calling thread. The zone timer's first tick is held an hour away, so the zone fetches only + * when a test ticks it by hand, and a tick that fetches proves the zone is active. The journey + * scenarios send the event requests through the real networking stack to a local HTTP server, since + * the content zone is refreshed only after the server answers the request carrying the trigger. + */ +@RunWith(JUnit4.class) +public class ModuleConfigurationContentTests { + + private static final String CONTENT_ENDPOINT = "/o/sdk/content?"; + private static final String NO_CONTENT_RESPONSE = "{\"jsonArray\":[{\"result\":\"No content block found!\"}]}"; + private static final String CONTENT_RESPONSE = "{\"html\":\"https://content.count.ly/block-1\",\"geo\":{" + + "\"p\":{\"x\":10,\"y\":20,\"w\":300,\"h\":400},\"l\":{\"x\":30,\"y\":40,\"w\":500,\"h\":600}}}"; + private static final long WAIT_BUDGET_MS = 30_000; + + private SettingsAndContentServer server; + private QueueServer queueServer; + private FakeDisplay display; + private final List logs = new CopyOnWriteArrayList<>(); + + /** + * Starts every test from empty storage, without a test module and with fresh fakes. + */ + @Before + public void beforeTest() { + TestUtils.createCleanTestState(); + SDKCore.testDummyModule = null; + server = new SettingsAndContentServer(); + queueServer = null; + display = new FakeDisplay(); + logs.clear(); + } + + /** + * Stops the SDK, clearing its data, and the local HTTP server when one was started. + */ + @After + public void afterTest() { + Countly.instance().halt(); + if (queueServer != null) { + queueServer.http.stop(0); + } + } + + // region scenarios + + /** + * {@code ecz} decides only whether the SDK enters the content zone at init. + *

+ * 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_decidesOnlyTheEntryAtInit() throws InterruptedException { + server.settings.respondWith(new ServerConfigBuilder().contentZone(true)); + init(contentConfig()); + holdTheZoneTimer(); + + awaitLogs("it is entered once a content display is registered", 1); + assertZoneIsInactive(0); + Countly.instance().content().setContentDisplay(display); + assertZoneFetches(1); + + push(new ServerConfigBuilder().contentZone(false)); + assertZoneFetches(2); + + Countly.instance().content().exitContentZone(); + assertZoneIsInactive(2); + push(new ServerConfigBuilder().contentZone(true)); + assertZoneIsInactive(2); + Countly.instance().stop(); + + server.settings.pending(); + init(contentConfig()); + holdTheZoneTimer(); + assertZoneIsInactive(2); + Countly.instance().content().setContentDisplay(display); + assertZoneFetches(3); + } + + /** + * {@code czi} is the fetch interval of a zone, read when the zone is entered. + *

+ * Verifies that without the setting the developer's interval is used, that the setting overrides + * it, that a response changing it restarts the timer of the active zone at the new interval while + * the zone keeps fetching, that a response repeating it keeps the running timer, and that a change + * while no zone is active starts nothing and applies when a zone is entered. + */ + @Test + public void contentZoneInterval_isReadWhenTheZoneIsEntered_andAChangeRestartsTheTimerOfTheActiveZone() { + server.settings.pending(); + init(contentConfig().content.setZoneTimerInterval(20)); + holdTheZoneTimer(); + Countly.instance().content().setContentDisplay(display); + Countly.instance().content().enterContentZone(); + Assert.assertEquals(20, zoneTimer().getTimerDelaySeconds()); + Countly.instance().halt(); + + server.settings.respondWith(new ServerConfigBuilder().contentZoneInterval(60)); + init(contentConfig().content.setZoneTimerInterval(20)); + holdTheZoneTimer(); + Assert.assertEquals(60, provider().getContentZoneTimerInterval()); + Countly.instance().content().setContentDisplay(display); + Countly.instance().content().enterContentZone(); + CountlyTimer atEnter = zoneTimer(); + Assert.assertEquals(60, atEnter.getTimerDelaySeconds()); + assertZoneFetches(1); + + push(new ServerConfigBuilder().contentZoneInterval(90)); + CountlyTimer restarted = zoneTimer(); + Assert.assertNotSame(atEnter, restarted); + Assert.assertEquals(90, restarted.getTimerDelaySeconds()); + assertZoneFetches(2); + + push(new ServerConfigBuilder().contentZoneInterval(90).eventQueueSize(3)); + Assert.assertSame(restarted, zoneTimer()); + + Countly.instance().content().exitContentZone(); + push(new ServerConfigBuilder().contentZoneInterval(120)); + Assert.assertNull(zoneTimer()); + Countly.instance().content().enterContentZone(); + Assert.assertEquals(120, zoneTimer().getTimerDelaySeconds()); + assertZoneFetches(3); + } + + /** + * 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 contentTriggers_areAskedForAndStored_unlessTurnedOff() { + server.settings.respondWith(new ServerConfigBuilder().topLevelKey("jt", triggers("e", "purchase"))); + init(contentConfig()); + + 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(); + + TestUtils.createCleanTestState(); + server = new SettingsAndContentServer(); + server.settings.respondWith(new ServerConfigBuilder().topLevelKey("jt", triggers("e", "purchase"))); + Config config = contentConfig(); + config.content.disableAutoContentTriggers(); + init(config); + + Assert.assertNull(server.settings.requests.get(0).get("jt")); + Assert.assertNull(provider().getContentTriggers()); + } + + /** + * 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 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 contentTriggers_aListedEventSendsTheQueueThenAsksForContent() throws IOException, InterruptedException { + startQueueServer(); + server.settings.respondWith(new ServerConfigBuilder().topLevelKey("jt", triggers("e", "purchase"))); + init(networkedContentConfig()); + holdTheZoneTimer(); + Countly.instance().content().setContentDisplay(display); + Countly.instance().content().enterContentZone(); + + Countly.instance().events().recordEvent("regular"); + Countly.instance().events().recordEvent("purchase"); + awaitContentRequests(3); + Assert.assertEquals("[\"regular\",\"purchase\"]", eventKeys(queueServer.eventRequests().get(0)).toString()); + Assert.assertEquals(Integer.valueOf(0), server.queuedRequestsAtFetch.get(0)); + + Countly.instance().events().recordEvent("purchase"); + awaitLogs("started a round less than [10] seconds ago", 1); + Thread.sleep(1500); + Assert.assertEquals(3, server.contentFetches.size()); + } + + /** + * 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 IOException, InterruptedException { + startQueueServer(); + server.settings.respondWith(new ServerConfigBuilder().journeyTriggerEvents(names("legacy")).topLevelKey("jt", triggers("e", "purchase"))); + init(networkedContentConfig()); + holdTheZoneTimer(); + Countly.instance().content().setContentDisplay(display); + + Countly.instance().events().recordEvent("purchase"); + 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()); + } + + /** + * 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 journeyTriggers_askForContentDirectly_forEventsOfTheAppAndBothEventsOfAView() throws IOException, InterruptedException { + startQueueServer(); + 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().events().recordEvent("[CLY]_star_rating"); + Thread.sleep(2000); + Assert.assertEquals(0, server.contentFetches.size()); + + Countly.instance().events().recordEvent("purchase"); + awaitContentRequests(3); + + Countly.instance().views().startView("checkout"); + 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 IOException, InterruptedException { + 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); + } + + /** + * A settings change turning {@code ecz} on that arrives while the SDK stops starts no zone timer. + *

+ * Verifies, with the change handed over right after the content module left its zone during + * {@code halt()}, while its display is still registered, that the stopping SDK dispatches the + * change to no module, and that the content module, told directly, enters no zone, so no zone + * timer outlives the SDK. + */ + @Test + public void contentZoneEnabled_arrivingWhileTheSdkStops_startsNoZoneTimer() { + AtomicInteger dispatchedChanges = new AtomicInteger(); + SDKCore.testDummyModule = new ModuleBase() { + /** + * Counts a dispatched settings change. + * + * @param config configuration of the running SDK + */ + @Override + protected void onSdkConfigurationChanged(InternalConfig config) { + dispatchedChanges.incrementAndGet(); + } + }; + AtomicReference onZoneLeft = new AtomicReference<>(); + server.settings.respondWith(new ServerConfigBuilder()); + init(TestUtils.getConfigSdkBehaviorSettings() + .enableFeatures(Config.Feature.Content, Config.Feature.Events) + .setLogListener((message, level) -> { + Runnable hook = message != null && message.startsWith("[ModuleContent] exitContentZoneInternal, left the content zone") ? onZoneLeft.getAndSet(null) : null; + if (hook != null) { + hook.run(); + } + })); + Countly.instance().content().setContentDisplay(display); + ModuleContent content = contentModule(); + ModuleConfiguration configuration = SDKCore.instance.module(ModuleConfiguration.class); + InternalConfig config = SDKCore.instance.config; + Assert.assertNull(content.contentTimer); + int dispatchedBeforeStop = dispatchedChanges.get(); + + onZoneLeft.set(() -> { + configuration.currentVContentZone = true; + config.sdk.onSdkConfigurationChanged(config); + content.onSdkConfigurationChanged(config); + }); + try { + Countly.instance().halt(); + Assert.assertNull("the change was never handed over", onZoneLeft.get()); + Assert.assertEquals(dispatchedBeforeStop, dispatchedChanges.get()); + Assert.assertNull(content.contentTimer); + } finally { + SDKCore.testDummyModule = null; + CountlyTimer leaked = content.contentTimer; + if (leaked != null) { + leaked.stopTimer(false); + } + } + } + + // endregion + // region helpers + + /** + * The settings of the journey trigger scenario: two trigger events, one trigger view, a queue + * that waits for 100 events and networking off, so every request stays on disk. Each response + * replaces the stored settings, so every response of the scenario starts from these. + * + * @return a builder holding those settings + */ + /** + * @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()); + } + + /** + * Stands in for the settings and the content endpoints of the server. Settings requests go to a + * {@link ModuleConfigurationTests.ServerConfigResponder}; content fetches are recorded and answered + * on the calling thread with {@link #contentResponse}, unless networking is off, where the SDK's own + * request maker sends nothing. + */ + 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; + + /** + * A request maker that routes by endpoint. + * + * @return the request maker + */ + @Override + public ImmediateRequestI createImmediateRequestMaker() { + ImmediateRequestI settingsRequestMaker = settings.createImmediateRequestMaker(); + return (requestData, customEndpoint, transport, requestShouldBeDelayed, networkingIsEnabled, callback, log) -> { + if (!CONTENT_ENDPOINT.equals(customEndpoint)) { + settingsRequestMaker.doWork(requestData, customEndpoint, transport, requestShouldBeDelayed, networkingIsEnabled, callback, log); + return; + } + if (!networkingIsEnabled) { + callback.callback(null); + return; + } + queuedRequestsAtFetch.add(queuedRequestCount()); + contentFetches.add(requestData); + callback.callback(new JSONObject(contentResponse)); + }; + } + } + + /** + * A local HTTP server standing in for the request queue endpoint {@code /i}: it records the + * parameters of every request and accepts it, rejects it with a 500, or drops the connection + * without any response. + */ + private static final class QueueServer { + static final int ACCEPT = 0; + static final int REJECT = 1; + static final int DROP = 2; + + final HttpServer http; + final List> received = new CopyOnWriteArrayList<>(); + volatile int mode = ACCEPT; + + /** + * Starts the server on a free loopback port. + * + * @throws IOException when the server cannot start + */ + QueueServer() throws IOException { + http = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + http.createContext("/", this::handle); + http.setExecutor(Executors.newSingleThreadExecutor()); + http.start(); + } + + /** + * Records a request and answers it as {@link #mode} says. + * + * @param exchange the request and its response + * @throws IOException when the response cannot be written + */ + private void handle(HttpExchange exchange) throws IOException { + String query = exchange.getRequestURI().getRawQuery(); + String body = new String(readAll(exchange.getRequestBody()), StandardCharsets.UTF_8); + received.add(parseParams(query != null && !query.isEmpty() ? query : body)); + + int currentMode = mode; + if (currentMode == DROP) { + exchange.close(); + return; + } + + byte[] response = (currentMode == ACCEPT ? "{\"result\":\"Success\"}" : "{\"result\":\"Server error\"}").getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(currentMode == ACCEPT ? 200 : 500, response.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(response); + } + } + + /** + * The received requests that carry events, in the order they arrived. + * + * @return the parameters of each request + */ + List> eventRequests() { + List> requests = new ArrayList<>(); + for (Map params : received) { + if (params.containsKey("events")) { + requests.add(params); + } + } + return requests; + } + + /** + * The port the server listens on. + * + * @return the port + */ + int port() { + return http.getAddress().getPort(); + } + } + + /** + * A display that records what it was asked to show and lets a test close it. + */ + private static final class FakeDisplay implements ContentDisplay { + final List presented = new CopyOnWriteArrayList<>(); + volatile ContentCloseCallback lastCallback; + + /** + * A landscape screen. + * + * @return the screen + */ + @Override + public ContentScreen getScreen() { + return new ContentScreen(1600, 900); + } + + /** + * Records the content and keeps the callback that closes it. + * + * @param content the content to show + * @param onClosed called when the content closes + */ + @Override + public void present(ContentData content, ContentCloseCallback onClosed) { + presented.add(content); + lastCallback = onClosed; + } + } + + /** + * Initializes the SDK with {@link #server} answering its settings requests and content fetches. + * + * @param config the configuration + */ + private void init(Config config) { + InternalConfig internalConfig = new InternalConfig(config); + internalConfig.immediateRequestGenerator = server; + Countly.instance().init(internalConfig); + } + + /** + * Answers the next settings request with the given payload and makes the SDK fetch, as the + * refresh timer does. + * + * @param builder the payload + */ + private void push(ServerConfigBuilder builder) { + server.settings.respondWith(builder); + SDKCore.instance.module(ModuleConfiguration.class).fetchConfigFromServer(SDKCore.instance.config); + } + + /** + * The settings in effect in the running SDK. + * + * @return the provider + */ + private static ConfigurationProvider provider() { + return SDKCore.instance.config.getConfigurationProvider(); + } + + /** + * The settings test configuration with content and events, keeping every log line. + * + * @return the configuration + */ + private Config contentConfig() { + return TestUtils.getConfigSdkBehaviorSettings() + .enableFeatures(Config.Feature.Content, Config.Feature.Events) + .setLogListener((message, level) -> logs.add(message)); + } + + /** + * A configuration pointing at {@link #queueServer}, with content, events and views, an event + * queue that only a trigger flushes, no request cooldowns, and every log line kept. + * + * @return the configuration + */ + private Config networkedContentConfig() { + File directory = TestUtils.getTestSDirectory(); + TestUtils.checkSdkStorageRootDirectoryExist(directory); + return new Config("http://127.0.0.1:" + queueServer.port(), TestUtils.SERVER_APP_KEY, directory) + .setApplicationVersion(TestUtils.APPLICATION_VERSION) + .setCustomDeviceId(TestUtils.DEVICE_ID) + .enableFeatures(Config.Feature.Content, Config.Feature.Events, Config.Feature.Views) + .setEventQueueSizeToSend(100) + .setNetworkRequestCooldown(0) + .setNetworkImportantRequestCooldown(0) + .setLogListener((message, level) -> logs.add(message)); + } + + /** + * Starts {@link #queueServer}, accepting every request. + * + * @throws IOException when the server cannot start + */ + private void startQueueServer() throws IOException { + queueServer = new QueueServer(); + } + + /** + * Holds the first tick of every zone timer an hour away, so the zone fetches only when a test + * ticks it by hand. + */ + private static void holdTheZoneTimer() { + contentModule().startedAtForTests(System.currentTimeMillis() + 60L * 60L * 1000L); + } + + /** + * The content module of the running SDK. + * + * @return the module + */ + private static ModuleContent contentModule() { + return SDKCore.instance.module(ModuleContent.class); + } + + /** + * The timer of the active zone. + * + * @return the timer, {@code null} while no zone is active + */ + private static CountlyTimer zoneTimer() { + return contentModule().contentTimer; + } + + /** + * Ticks the zone once by hand and asserts the total number of content fetches after the tick. + * + * @param expectedFetches the fetches expected so far + */ + private void assertZoneFetches(int expectedFetches) { + contentModule().onZoneTimerTick(); + Assert.assertEquals(expectedFetches, server.contentFetches.size()); + } + + /** + * Ticks the zone once by hand and asserts that it fetched nothing, as no zone is active. + * + * @param fetchesSoFar the fetches made so far + */ + private void assertZoneIsInactive(int fetchesSoFar) { + assertZoneFetches(fetchesSoFar); + } + + /** + * Ticks the zone by hand until it fetches, which it does once a refresh entered it. + * + * @param expectedFetches the fetches expected once it fetched + */ + private void awaitZoneFetch(int expectedFetches) throws InterruptedException { + boolean fetched = waitFor(() -> { + contentModule().onZoneTimerTick(); + return server.contentFetches.size() >= expectedFetches; + }); + Assert.assertTrue("the content zone never fetched, logs: " + logs, fetched); + Assert.assertEquals(expectedFetches, server.contentFetches.size()); + } + + /** + * Waits until the log holds a number of lines containing a text. + * + * @param text the text + * @param count how many lines + */ + private void awaitLogs(String text, int count) throws InterruptedException { + Assert.assertTrue("never logged [" + text + "] " + count + " times", waitFor(() -> logsContaining(text) >= count)); + Assert.assertEquals(count, logsContaining(text)); + } + + /** + * Waits until every stored request was sent and removed. + */ + private void awaitEmptyQueue() throws InterruptedException { + Assert.assertTrue("the request queue never drained", waitFor(() -> queuedRequestCount() == 0)); + } + + /** + * How many log lines so far contain a text. + * + * @param text the text + * @return the number of lines + */ + private int logsContaining(String text) { + int count = 0; + for (String line : logs) { + if (line.contains(text)) { + count++; + } + } + return count; + } + + /** + * Counts the stored requests without reading them, as the network loop can remove one while it + * is read. + * + * @return the number of stored requests + */ + private static int queuedRequestCount() { + File[] files = TestUtils.getTestSDirectory().listFiles((dir, name) -> name.startsWith("[CLY]_request_")); + return files == null ? 0 : files.length; + } + + /** + * The storage IDs of the stored requests. + * + * @return the IDs + */ + private static Set storedRequestIds() { + Set ids = new HashSet<>(); + File[] files = TestUtils.getTestSDirectory().listFiles((dir, name) -> name.startsWith("[CLY]_request_")); + if (files != null) { + for (File file : files) { + ids.add(Long.parseLong(file.getName().substring("[CLY]_request_".length()))); + } + } + return ids; + } + + /** + * The keys of the events a request carries, in order. + * + * @param params the parameters of the request + * @return the keys as a JSON array + */ + private static JSONArray eventKeys(Map params) { + JSONArray events = new JSONArray(params.get("events")); + JSONArray keys = new JSONArray(); + for (int i = 0; i < events.length(); i++) { + keys.put(events.getJSONObject(i).getString("key")); + } + return keys; + } + + /** + * Polls until the condition holds or {@link #WAIT_BUDGET_MS} runs out, nudging the send loop on + * every round, as it only picks up a request when something is pushed. + * + * @param condition the condition + * @return whether the condition holds + */ + private static boolean waitFor(BooleanSupplier condition) throws InterruptedException { + long deadline = System.currentTimeMillis() + WAIT_BUDGET_MS; + while (System.currentTimeMillis() < deadline) { + if (condition.getAsBoolean()) { + return true; + } + SDKCore core = SDKCore.instance; + if (core != null && core.networking != null) { + core.networking.check(core.config); + } + Thread.sleep(50); + } + return condition.getAsBoolean(); + } + + /** + * Decodes url encoded request parameters. + * + * @param data the parameters + * @return the parameters by name + */ + private static Map parseParams(String data) { + Map params = new HashMap<>(); + for (String pair : data.split("&")) { + if (pair.isEmpty()) { + continue; + } + String[] keyValue = pair.split("=", 2); + params.put(Utils.urldecode(keyValue[0]), keyValue.length > 1 ? Utils.urldecode(keyValue[1]) : ""); + } + return params; + } + + /** + * Reads a stream to its end. + * + * @param stream the stream + * @return the bytes + * @throws IOException when the stream cannot be read + */ + private static byte[] readAll(InputStream stream) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int read; + while ((read = stream.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + return out.toByteArray(); + } + + // endregion +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationFiltersTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationFiltersTests.java new file mode 100644 index 000000000..ba7773d1b --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationFiltersTests.java @@ -0,0 +1,447 @@ +package ly.count.sdk.java.internal; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; +import ly.count.sdk.java.PredefinedUserPropertyKeys; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import static ly.count.sdk.java.internal.ServerConfigBuilder.names; + +/** + * The listing filters and the user property cache limit of the SDK behavior settings, observed + * through the public API: which custom events, segmentation keys and custom user properties reach + * the event queue and the request queue, while internal events and predefined user properties pass. + *

+ * Settings requests go through a {@link ModuleConfigurationTests.ServerConfigResponder}, which answers + * on the calling thread, so the response of the fetch made at init applies before init returns and a + * later one is pushed by fetching the way the refresh timer does. Networking is off through the + * settings, so every stored request stays on disk to be read. + */ +@RunWith(JUnit4.class) +public class ModuleConfigurationFiltersTests { + + private ModuleConfigurationTests.ServerConfigResponder server; + private final List warnings = new CopyOnWriteArrayList<>(); + + /** + * Starts every test from empty storage, without a test module and with a fresh responder. + */ + @Before + public void beforeTest() { + TestUtils.createCleanTestState(); + SDKCore.testDummyModule = null; + server = new ModuleConfigurationTests.ServerConfigResponder(); + warnings.clear(); + } + + /** + * Stops the SDK and clears its data. + */ + @After + public void afterTest() { + Countly.instance().halt(); + } + + // region scenarios + + /** + * {@code eb} and then {@code ew} decide which custom events are recorded, while internal events + * always pass. + *

+ * Verifies that with a blacklist, listed keys, spaces and dashes and a {@code [CLY]_} key the SDK + * does not record itself included, are dropped with one warning each, timed events too, while an + * unlisted key, a view and an internal event listed in the blacklist are recorded; that a response bringing a whitelist replaces the blacklist, so only + * its keys are recorded, a view still is and a key the blacklist dropped is dropped again; and that + * an empty whitelist allows every key. + */ + @Test + public void eventFilter_blacklistThenWhitelist_decideCustomEventsOnly_andAnEmptyListAllowsEverything() { + server.respondWith(new ServerConfigBuilder() + .eventFilterList(names("blocked_event", "event with spaces", "event-with-dashes", "[CLY]_not_an_sdk_event", ModuleViews.KEY_VIEW_EVENT, "[CLY]_star_rating"), false) + .networking(false)); + init(configWithWarnings().enableFeatures(Config.Feature.Events, Config.Feature.Views).setEventQueueSizeToSend(100)); + + Countly.instance().events().recordEvent("blocked_event"); + Countly.instance().events().recordEvent("event with spaces"); + Countly.instance().events().recordEvent("event-with-dashes", TestUtils.map("colour", "red")); + Countly.instance().events().recordEvent("[CLY]_not_an_sdk_event"); + Countly.instance().events().startEvent("blocked_event"); + Countly.instance().events().endEvent("blocked_event"); + TestUtils.validateEQSize(0); + Assert.assertEquals(5, warningsContaining("is filtered out by the event filter")); + + Countly.instance().events().recordEvent("allowed_event"); + Countly.instance().views().startView("home"); + Countly.instance().events().recordEvent("[CLY]_star_rating"); + Assert.assertEquals(Arrays.asList("allowed_event", ModuleViews.KEY_VIEW_EVENT, "[CLY]_star_rating"), TestUtils.keysInEQ()); + + push(new ServerConfigBuilder().eventFilterList(names("allowed_event", "another_allowed"), true)); + Countly.instance().events().recordEvent("allowed_event"); + Countly.instance().events().recordEvent("not_in_whitelist"); + Countly.instance().events().recordEvent("another_allowed", 2); + Countly.instance().events().recordEvent("blocked_event"); + Countly.instance().views().stopViewWithName("home"); + Assert.assertEquals(Arrays.asList("allowed_event", ModuleViews.KEY_VIEW_EVENT, "[CLY]_star_rating", + "allowed_event", "another_allowed", ModuleViews.KEY_VIEW_EVENT), TestUtils.keysInEQ()); + Assert.assertEquals(7, warningsContaining("is filtered out by the event filter")); + + push(new ServerConfigBuilder().eventFilterList(names(), true)); + Countly.instance().events().recordEvent("not_in_whitelist"); + Countly.instance().events().recordEvent("blocked_event"); + List keys = TestUtils.keysInEQ(); + Assert.assertEquals(Arrays.asList("not_in_whitelist", "blocked_event"), keys.subList(6, keys.size())); + Assert.assertEquals(7, warningsContaining("is filtered out by the event filter")); + Assert.assertEquals(0, TestUtils.getCurrentRQ().length); + } + + /** + * {@code sb} and {@code esb}, then {@code sw} and {@code esw}, remove segmentation keys of custom + * events on a copy of the map the caller passed. + *

+ * Verifies on the wire that the segmentation blacklist and then the blacklist of each event apply + * together, that an event without rules keeps everything but the general blacklist, that the + * caller's unmodifiable map is left as it was and can be passed again, that an internal event and + * a view keep every key, that empty and missing segmentation still record, and that a response + * bringing whitelists replaces both blacklists, the general whitelist applying before the one of + * the event. + */ + @Test + public void segmentationFilters_generalThenPerEvent_filterACopyOfTheCallersMap_andNeverTouchInternalEvents() { + Map> perEvent = new LinkedHashMap<>(); + perEvent.put("event1", names("blocked_for_event1")); + perEvent.put("event2", names("key_b")); + server.respondWith(new ServerConfigBuilder() + .segmentationFilterList(names("general_blocked"), false) + .eventSegmentationFilterMap(perEvent, false) + .eventQueueSize(1) + .networking(false)); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.Events, Config.Feature.Views)); + + Map callers = Collections.unmodifiableMap(TestUtils.map("general_blocked", "g", "blocked_for_event1", "e1", "key_a", "a", "key_b", "b")); + Countly.instance().events().recordEvent("event1", callers); + TestUtils.letTheClockCatchUp(); + Countly.instance().events().recordEvent("event2", callers); + TestUtils.letTheClockCatchUp(); + Countly.instance().events().recordEvent("event3", callers); + TestUtils.letTheClockCatchUp(); + Countly.instance().events().recordEvent("[CLY]_star_rating", callers); + TestUtils.letTheClockCatchUp(); + Countly.instance().views().startView("home", TestUtils.map("general_blocked", "v")); + TestUtils.letTheClockCatchUp(); + Countly.instance().events().recordEvent("event1", new HashMap<>()); + TestUtils.letTheClockCatchUp(); + Countly.instance().events().recordEvent("event1"); + TestUtils.letTheClockCatchUp(); + + List sent = sentEvents(); + Assert.assertEquals(keysOf(sent).toString(), 7, sent.size()); + assertEvent(sent.get(0), "event1", TestUtils.map("key_a", "a", "key_b", "b")); + assertEvent(sent.get(1), "event2", TestUtils.map("blocked_for_event1", "e1", "key_a", "a")); + assertEvent(sent.get(2), "event3", TestUtils.map("blocked_for_event1", "e1", "key_a", "a", "key_b", "b")); + assertEvent(sent.get(3), "[CLY]_star_rating", callers); + Assert.assertEquals(ModuleViews.KEY_VIEW_EVENT, sent.get(4).key); + Assert.assertEquals("v", sent.get(4).segmentation.get("general_blocked")); + Assert.assertEquals("home", sent.get(4).segmentation.get(ModuleViews.KEY_NAME)); + Assert.assertEquals("event1", sent.get(5).key); + Assert.assertTrue(sent.get(5).segmentation == null || sent.get(5).segmentation.isEmpty()); + Assert.assertEquals("event1", sent.get(6).key); + Assert.assertTrue(sent.get(6).segmentation == null || sent.get(6).segmentation.isEmpty()); + Assert.assertEquals(TestUtils.map("general_blocked", "g", "blocked_for_event1", "e1", "key_a", "a", "key_b", "b"), callers); + + Map> perEventWhitelist = new LinkedHashMap<>(); + perEventWhitelist.put("event1", names("key_a")); + push(new ServerConfigBuilder() + .segmentationFilterList(names("key_a", "key_b", "blocked_for_event1"), true) + .eventSegmentationFilterMap(perEventWhitelist, true) + .eventQueueSize(1) + .networking(false)); + Countly.instance().events().recordEvent("event1", callers); + TestUtils.letTheClockCatchUp(); + Countly.instance().events().recordEvent("event2", callers); + TestUtils.letTheClockCatchUp(); + Countly.instance().events().recordEvent("event4", TestUtils.map("key_b", "b", "other", "o")); + TestUtils.letTheClockCatchUp(); + + sent = sentEvents(); + Assert.assertEquals(keysOf(sent).toString(), 10, sent.size()); + assertEvent(sent.get(7), "event1", TestUtils.map("key_a", "a")); + assertEvent(sent.get(8), "event2", TestUtils.map("blocked_for_event1", "e1", "key_a", "a", "key_b", "b")); + assertEvent(sent.get(9), "event4", TestUtils.map("key_b", "b")); + Assert.assertEquals(4, callers.size()); + } + + /** + * {@code upb} and then {@code upw} decide which custom user properties are set and modified, + * while predefined properties are never filtered. + *

+ * Verifies on the wire that with a blacklist listing custom keys and predefined ones, the + * predefined name and email are still sent while a listed custom key is dropped from a batch, + * from a single set and from each of the nine modifications, with one warning per dropped call, + * and every unlisted key keeps its set or modification; and that a response bringing a whitelist + * keeps only its custom keys while a predefined key outside it is still sent. + */ + @Test + public void userPropertyFilter_appliesToCustomKeysOfEverySetAndModification_whilePredefinedKeysBypassIt() { + server.respondWith(new ServerConfigBuilder() + .userPropertyFilterList(names("blocked_prop", "blocked_counter", PredefinedUserPropertyKeys.NAME, PredefinedUserPropertyKeys.EMAIL), false) + .networking(false)); + init(configWithWarnings()); + + Map batch = new LinkedHashMap<>(); + batch.put(PredefinedUserPropertyKeys.NAME, "John"); + batch.put(PredefinedUserPropertyKeys.EMAIL, "john@example.com"); + batch.put("blocked_prop", "value1"); + batch.put("allowed_prop", "value2"); + Countly.instance().userProfile().setProperties(Collections.unmodifiableMap(batch)); + Countly.instance().userProfile().setProperty("blocked_prop", "value3"); + modifyWithEveryOperation("blocked_counter"); + modifyWithEveryOperation("allowed_counter"); + Countly.instance().userProfile().save(); + TestUtils.letTheClockCatchUp(); + + JSONObject details = userDetails(0); + Assert.assertEquals("John", details.getString(PredefinedUserPropertyKeys.NAME)); + Assert.assertEquals("john@example.com", details.getString(PredefinedUserPropertyKeys.EMAIL)); + JSONObject custom = details.getJSONObject(ModuleUserProfile.CUSTOM_KEY); + Assert.assertEquals(names("allowed_prop", "allowed_counter"), custom.keySet()); + Assert.assertEquals("value2", custom.getString("allowed_prop")); + JSONObject counter = custom.getJSONObject("allowed_counter"); + Assert.assertEquals(names("$inc", "$mul", "$max", "$min", "$setOnce", "$push", "$addToSet", "$pull"), counter.keySet()); + Assert.assertEquals(5, counter.getInt("$inc")); + Assert.assertEquals(11, warningsContaining("is filtered out by the user property filter")); + + push(new ServerConfigBuilder().userPropertyFilterList(names("plan", "visits"), true)); + Countly.instance().userProfile().setProperty("plan", "gold"); + Countly.instance().userProfile().setProperty("allowed_prop", "not_listed_now"); + Countly.instance().userProfile().setProperty(PredefinedUserPropertyKeys.USERNAME, "jdoe"); + Countly.instance().userProfile().increment("visits"); + Countly.instance().userProfile().increment("allowed_counter"); + Countly.instance().userProfile().save(); + TestUtils.letTheClockCatchUp(); + + details = userDetails(1); + Assert.assertEquals("jdoe", details.getString(PredefinedUserPropertyKeys.USERNAME)); + custom = details.getJSONObject(ModuleUserProfile.CUSTOM_KEY); + Assert.assertEquals(names("plan", "visits"), custom.keySet()); + Assert.assertEquals("gold", custom.getString("plan")); + Assert.assertEquals(1, custom.getJSONObject("visits").getInt("$inc")); + Assert.assertEquals(13, warningsContaining("is filtered out by the user property filter")); + } + + /** + * {@code upcl} caps the pending custom properties and the keys with pending modifications apart. + *

+ * Verifies that without the setting any number of custom properties is sent; that with it, a + * batch over the limit keeps its newest keys, predefined properties are neither counted nor + * dropped, updating a pending key does not count again, a new key drops the oldest one, and each + * drop warns; that modifications count distinct keys, so repeating one does not count, and going + * over the limit drops every modification of the oldest key; that the request carries exactly + * what was kept; and that a save starts the count again. + */ + @Test + public void userPropertyCacheLimit_capsPendingCustomSetsAndModifiedKeysApart_droppingTheOldestFirst() { + server.respondWith(new ServerConfigBuilder().networking(false)); + init(configWithWarnings()); + Assert.assertEquals(ModuleConfiguration.NO_LIMIT, provider().getUserPropertyCacheLimit()); + + for (int i = 1; i <= 150; i++) { + Countly.instance().userProfile().setProperty("bulk_" + i, i); + } + Countly.instance().userProfile().save(); + TestUtils.letTheClockCatchUp(); + Assert.assertEquals(150, userDetails(0).getJSONObject(ModuleUserProfile.CUSTOM_KEY).length()); + + push(new ServerConfigBuilder().userPropertyCacheLimit(3)); + Map batch = new LinkedHashMap<>(); + for (int i = 1; i <= 5; i++) { + batch.put("prop" + i, "value" + i); + } + batch.put(PredefinedUserPropertyKeys.NAME, "John"); + batch.put(PredefinedUserPropertyKeys.EMAIL, "john@example.com"); + batch.put(PredefinedUserPropertyKeys.USERNAME, "jdoe"); + Countly.instance().userProfile().setProperties(batch); + Assert.assertEquals(1, warningsContaining("over the cache limit of [3]")); + Countly.instance().userProfile().setProperty("prop3", "updated"); + Assert.assertEquals(1, warningsContaining("over the cache limit of [3]")); + Countly.instance().userProfile().setProperty("prop6", "value6"); + Assert.assertEquals(2, warningsContaining("over the cache limit of [3]")); + + Countly.instance().userProfile().incrementBy("counter1", 1); + Countly.instance().userProfile().incrementBy("counter2", 2); + Countly.instance().userProfile().incrementBy("counter1", 10); + Countly.instance().userProfile().incrementBy("counter3", 3); + Assert.assertEquals(2, warningsContaining("over the cache limit of [3]")); + Countly.instance().userProfile().multiply("factor", 2); + Countly.instance().userProfile().push("list", "x"); + Assert.assertEquals(4, warningsContaining("over the cache limit of [3]")); + Countly.instance().userProfile().save(); + TestUtils.letTheClockCatchUp(); + + JSONObject details = userDetails(1); + Assert.assertEquals("John", details.getString(PredefinedUserPropertyKeys.NAME)); + Assert.assertEquals("john@example.com", details.getString(PredefinedUserPropertyKeys.EMAIL)); + Assert.assertEquals("jdoe", details.getString(PredefinedUserPropertyKeys.USERNAME)); + JSONObject custom = details.getJSONObject(ModuleUserProfile.CUSTOM_KEY); + Assert.assertEquals(names("prop4", "prop5", "prop6", "counter3", "factor", "list"), custom.keySet()); + Assert.assertEquals("value4", custom.getString("prop4")); + Assert.assertEquals(3, custom.getJSONObject("counter3").getInt("$inc")); + Assert.assertEquals(2.0, custom.getJSONObject("factor").getDouble("$mul"), 0.0); + Assert.assertEquals("x", custom.getJSONObject("list").getString("$push")); + + Countly.instance().userProfile().setProperties(TestUtils.map("fresh1", "a", "fresh2", "b", "fresh3", "c")); + Countly.instance().userProfile().save(); + TestUtils.letTheClockCatchUp(); + Assert.assertEquals(3, userDetails(2).getJSONObject(ModuleUserProfile.CUSTOM_KEY).length()); + Assert.assertEquals(4, warningsContaining("over the cache limit of [3]")); + } + + // endregion + // region helpers + + /** + * Initializes the SDK with {@link #server} answering its settings requests. + * + * @param config the configuration + */ + private void init(Config config) { + InternalConfig internalConfig = new InternalConfig(config); + internalConfig.immediateRequestGenerator = server; + Countly.instance().init(internalConfig); + } + + /** + * Answers the next settings request with the given payload and makes the SDK fetch, as the + * refresh timer does. + * + * @param builder the payload + */ + private void push(ServerConfigBuilder builder) { + server.respondWith(builder); + SDKCore.instance.module(ModuleConfiguration.class).fetchConfigFromServer(SDKCore.instance.config); + } + + /** + * The settings in effect in the running SDK. + * + * @return the provider + */ + private static ConfigurationProvider provider() { + return SDKCore.instance.config.getConfigurationProvider(); + } + + /** + * The settings test configuration with a listener that keeps every warning. + * + * @return the configuration + */ + private Config configWithWarnings() { + return TestUtils.getConfigSdkBehaviorSettings().setLogListener((message, level) -> { + if (level == Config.LoggingLevel.WARN) { + warnings.add(message); + } + }); + } + + /** + * How many warnings so far contain a text. + * + * @param text the text + * @return the number of warnings + */ + private int warningsContaining(String text) { + int count = 0; + for (String warning : warnings) { + if (warning.contains(text)) { + count++; + } + } + return count; + } + + /** + * Every event of every stored request, in queue order. + * + * @return the events + */ + private static List sentEvents() { + List events = new ArrayList<>(); + int requestCount = TestUtils.getCurrentRQ().length; + for (int i = 0; i < requestCount; i++) { + events.addAll(TestUtils.readEventsFromRequest(i, TestUtils.DEVICE_ID)); + } + return events; + } + + /** + * The keys of events, in order. + * + * @param events the events + * @return the keys + */ + private static List keysOf(List events) { + List keys = new ArrayList<>(); + for (EventImpl event : events) { + keys.add(event.key); + } + return keys; + } + + /** + * Asserts the key and the whole segmentation of an event. + * + * @param event the event + * @param key the expected key + * @param segmentation the expected segmentation + */ + private static void assertEvent(EventImpl event, String key, Map segmentation) { + Assert.assertEquals(key, event.key); + Assert.assertEquals(segmentation, new HashMap<>(event.segmentation)); + } + + /** + * The {@code user_details} object of a stored request. + * + * @param requestIndex the index of the request in the queue + * @return the user details + */ + private static JSONObject userDetails(int requestIndex) { + Map[] requests = TestUtils.getCurrentRQ(); + Assert.assertTrue("no request at index " + requestIndex + " in " + Arrays.toString(requests), requests.length > requestIndex); + return new JSONObject(requests[requestIndex].get("user_details")); + } + + /** + * Applies each of the nine modifications of the user profile interface to one key. + * + * @param key the custom user property key + */ + private static void modifyWithEveryOperation(String key) { + ModuleUserProfile.UserProfile profile = Countly.instance().userProfile(); + profile.increment(key); + profile.incrementBy(key, 4); + profile.multiply(key, 3); + profile.saveMax(key, 10); + profile.saveMin(key, 1); + profile.setOnce(key, "first"); + profile.push(key, "a"); + profile.pushUnique(key, "b"); + profile.pull(key, "c"); + } + + // endregion +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationGatesTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationGatesTests.java new file mode 100644 index 000000000..153aa39d4 --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationGatesTests.java @@ -0,0 +1,876 @@ +package ly.count.sdk.java.internal; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; +import ly.count.sdk.java.PredefinedUserPropertyKeys; +import ly.count.sdk.java.View; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * The switches and tunables of the SDK behavior settings, observed through the public API: what each + * one lets into the request queue and the event queue, both when it comes from the stored or provided + * settings at init and when a server response changes it while the SDK runs. + *

+ * Settings requests go through a {@link ModuleConfigurationTests.ServerConfigResponder}, which answers + * on the calling thread: the response of the fetch made at init is applied before init returns, and a + * later one is pushed by fetching the way the refresh timer does. Most scenarios switch networking off + * through the settings, so every stored request stays on disk to be read. + */ +@RunWith(JUnit4.class) +public class ModuleConfigurationGatesTests { + + private ModuleConfigurationTests.ServerConfigResponder server; + private Thread.UncaughtExceptionHandler defaultHandlerBeforeTest; + + /** + * Starts every test from empty storage, without a test module and with a fresh responder. + */ + @Before + public void beforeTest() { + defaultHandlerBeforeTest = Thread.getDefaultUncaughtExceptionHandler(); + TestUtils.createCleanTestState(); + SDKCore.testDummyModule = null; + server = new ModuleConfigurationTests.ServerConfigResponder(); + } + + /** + * Stops the SDK, clearing its data, and puts back the default uncaught exception handler. + */ + @After + public void afterTest() { + Countly.instance().halt(); + SDKCore.testDummyModule = null; + Thread.setDefaultUncaughtExceptionHandler(defaultHandlerBeforeTest); + } + + // region scenarios + + /** + * {@code tracking} off keeps everything new out of storage. + *

+ * Verifies with the switch provided at init that custom and internal events, timed events, views, + * sessions, breadcrumbs, handled and unhandled crashes, location, user properties, an A/B test + * enrollment and a device ID merge store no request and no event and leave no crash file, that a + * crash file left by an earlier run is still turned into a request, and that events are recorded + * again once a response turns tracking back on. + */ + @Test + public void tracking_off_storesNoRequestAndNoEvent_whileACrashOfAnEarlierRunIsStillSent() { + long crashId = TimeUtils.uniqueTimestampMs(); + TestUtils.writeToFile("crash_" + crashId, new JSONObject().put("_error", "earlier_run_crash").put("_nonfatal", false).toString()); + server.pending(); + init(TestUtils.getConfigSdkBehaviorSettings() + .enableFeatures(Config.Feature.Events, Config.Feature.Sessions, Config.Feature.Views, Config.Feature.CrashReporting, + Config.Feature.Location, Config.Feature.UserProfiles, Config.Feature.RemoteConfig) + .setEventQueueSizeToSend(1) + .setSdkBehaviorSettings(new ServerConfigBuilder().tracking(false).networking(false).build())); + + Assert.assertFalse(provider().getTrackingEnabled()); + Map[] requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(1, requests.length); + Assert.assertTrue(requests[0].get("crash").contains("earlier_run_crash")); + Assert.assertEquals(0, filesWithPrefix("[CLY]_crash_")); + + Countly.instance().events().recordEvent("custom_event"); + Countly.instance().events().recordEvent("[CLY]_star_rating"); + Countly.instance().events().startEvent("timed_event"); + Countly.instance().events().endEvent("timed_event"); + Assert.assertNull(Countly.instance().views().startView("home")); + Countly.session().begin(); + Countly.session().update(); + Countly.session().end(); + Countly.instance().crashes().addCrashBreadcrumb("breadcrumb"); + Countly.instance().crashes().recordHandledException(new Exception("handled_while_tracking_is_off")); + Countly.instance().crashes().recordUnhandledException(new Exception("unhandled_while_tracking_is_off")); + Countly.instance().location().setLocation("TR", "Izmir", "1,2", "1.1.1.1"); + Countly.instance().location().disableLocation(); + Countly.instance().userProfile().setProperty("plan", "gold"); + Countly.instance().userProfile().save(); + Countly.instance().remoteConfig().enrollIntoABTestsForKeys(new String[] { "button_color" }); + Countly.instance().deviceId().changeWithMerge("merged_device_id"); + + Assert.assertEquals(1, TestUtils.getCurrentRQ().length); + TestUtils.validateEQSize(0); + Assert.assertEquals(0, filesWithPrefix("[CLY]_crash_")); + Assert.assertEquals(0, filesWithPrefix("[CLY]_session_")); + + push(new ServerConfigBuilder().tracking(true)); + Countly.instance().events().recordEvent("custom_event_after"); + + requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(2, requests.length); + Assert.assertEquals("merged_device_id", requests[1].get("device_id")); + Assert.assertEquals("custom_event_after", new JSONArray(requests[1].get("events")).getJSONObject(0).getString("key")); + } + + /** + * {@code st} off ignores beginning, updating and ending a session, whatever calls them. + *

+ * Verifies that after a response turns session tracking off, an update, an end, a timer tick and a + * device ID change without merge send no session request while the running session keeps its + * state, that the session file left by that run is removed at the next init without an end + * request, that a session neither begins through the public API nor through a device ID change + * while the stored switch is off, that consent to sessions begins nothing either, and that a + * response turning it back on lets a session begin. + */ + @Test + public void sessionTracking_off_sendsNoSessionRequest_fromAnyCaller_andRecoveryDropsTheLeftoverSession() { + server.respondWith(new ServerConfigBuilder().networking(false)); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.Sessions)); + + Countly.session().begin(); + Assert.assertEquals(1, requestsWith("begin_session")); + + push(new ServerConfigBuilder().sessionTracking(false)); + Countly.session().update(); + Countly.session().end(); + SDKCore.instance.module(ModuleSessions.class).onTimer(); + Countly.instance().deviceId().changeWithoutMerge("device_id_2"); + + Assert.assertTrue(Countly.session().isActive()); + Assert.assertEquals(1, TestUtils.getCurrentRQ().length); + Assert.assertEquals(0, requestsWith("session_duration") + requestsWith("end_session")); + Countly.instance().stop(); + Assert.assertEquals(1, filesWithPrefix("[CLY]_session_")); + + server.pending(); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.Sessions)); + + Assert.assertFalse(provider().getSessionTrackingEnabled()); + Assert.assertEquals(0, filesWithPrefix("[CLY]_session_")); + SessionImpl session = (SessionImpl) Countly.session(); + session.begin(); + Assert.assertFalse(session.isActive()); + Assert.assertNull(session.update(null)); + Assert.assertNull(session.end(null, null, null)); + Countly.instance().deviceId().changeWithoutMerge("device_id_3"); + Assert.assertFalse(Countly.session().isActive()); + Map[] requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(1, requests.length); + Assert.assertEquals("1", requests[0].get("begin_session")); + Countly.instance().halt(); + + init(TestUtils.getConfigSdkBehaviorSettings() + .enableFeatures(Config.Feature.Sessions) + .setRequiresConsent(true) + .setSdkBehaviorSettings(new ServerConfigBuilder().sessionTracking(false).networking(false).build())); + Countly.onConsent(Config.Feature.Sessions); + Assert.assertTrue(Countly.isTracking(Config.Feature.Sessions)); + Assert.assertFalse(Countly.session().isActive()); + Assert.assertEquals(0, TestUtils.getCurrentRQ().length); + + push(new ServerConfigBuilder().sessionTracking(true)); + Countly.session().begin(); + Assert.assertTrue(Countly.session().isActive()); + Assert.assertEquals(1, requestsWith("begin_session")); + } + + /** + * {@code vt} off ignores every view call, while custom events keep being recorded. + *

+ * Verifies that after a response turns view tracking off, starting, stopping by name and by ID, + * pausing, resuming and stopping all views record no {@code [CLY]_view} event, through the views + * interface and through the deprecated session views alike, that a custom event is still + * recorded, that the views keep running and end once a response turns view tracking back on, + * and that the stored switch keeps views off after a restart. + */ + @Test + public void viewTracking_off_ignoresEveryViewCall_whileCustomEventsStillRecord() { + Config config = TestUtils.getConfigSdkBehaviorSettings() + .enableFeatures(Config.Feature.Events, Config.Feature.Views, Config.Feature.Sessions) + .setEventQueueSizeToSend(100); + server.respondWith(new ServerConfigBuilder().networking(false)); + init(config); + + String homeId = Countly.instance().views().startView("home"); + String settingsId = Countly.instance().views().startView("settings"); + Assert.assertEquals(2, viewEvents().size()); + + push(new ServerConfigBuilder().viewTracking(false)); + Assert.assertNull(Countly.instance().views().startView("blocked")); + Assert.assertNull(Countly.instance().views().startAutoStoppedView("blocked_auto_stopped")); + Countly.instance().views().stopViewWithName("home"); + Countly.instance().views().stopViewWithID(settingsId); + Countly.instance().views().pauseViewWithID(homeId); + Countly.instance().views().resumeViewWithID(homeId); + Countly.instance().views().stopAllViews(null); + View legacyView = ((SessionImpl) Countly.session()).view("legacy_view"); + legacyView.stop(false); + Countly.instance().events().recordEvent("custom_event"); + + List events = TestUtils.getCurrentEQ(); + Assert.assertEquals(3, events.size()); + Assert.assertEquals("custom_event", events.get(2).key); + Assert.assertEquals(2, viewEvents().size()); + + push(new ServerConfigBuilder().viewTracking(true)); + Countly.instance().views().stopViewWithID(homeId); + Countly.instance().views().stopAllViews(null); + + List views = viewEvents(); + Assert.assertEquals(4, views.size()); + Assert.assertEquals("home", views.get(2).segmentation.get("name")); + Assert.assertEquals("settings", views.get(3).segmentation.get("name")); + Assert.assertNull(views.get(2).segmentation.get("visit")); + Assert.assertEquals(0, TestUtils.getCurrentRQ().length); + + push(new ServerConfigBuilder().viewTracking(false)); + Countly.instance().stop(); + server.pending(); + init(config); + + Assert.assertFalse(provider().getViewTrackingEnabled()); + Assert.assertNull(Countly.instance().views().startView("after_restart")); + Assert.assertEquals(4, viewEvents().size()); + Assert.assertEquals(5, TestUtils.getCurrentEQ().size()); + } + + /** + * {@code crt} and {@code acr} decide whether unhandled crashes are caught, a response can install + * the handler while the SDK runs, and handled exceptions follow {@code crt} alone. + *

+ * Verifies that the handler is not installed while {@code acr} is off, that a response turning it + * on installs it, that a later change never installs it twice, that it records an unhandled crash + * only while both switches are on at crash time and always hands the crash to the handler it + * replaced, that handled and unhandled exceptions reported through the crashes interface are + * recorded whenever {@code crt} is on, and that stopping the SDK leaves in place a handler the + * application installed over it, which then only reaches the application's handler. + */ + @Test + public void crashSwitches_decideWhatIsRecorded_andAResponseInstallsTheHandlerOnce() throws InterruptedException { + List reachedTheApp = new CopyOnWriteArrayList<>(); + Thread.UncaughtExceptionHandler appHandler = (thread, throwable) -> reachedTheApp.add(throwable); + Thread.setDefaultUncaughtExceptionHandler(appHandler); + List crashesBeingRecorded = new CopyOnWriteArrayList<>(); + + server.respondWith(new ServerConfigBuilder().automaticCrashReporting(false).networking(false)); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.CrashReporting).setLogListener((message, level) -> { + if (message.startsWith("[ModuleCrash] onCrash:")) { + crashesBeingRecorded.add(message); + } + })); + + Assert.assertTrue(provider().getCrashReportingEnabled()); + Assert.assertFalse(provider().getAutomaticCrashReportingEnabled()); + Assert.assertSame(appHandler, Thread.getDefaultUncaughtExceptionHandler()); + crashOnAThread(new RuntimeException("crash_while_acr_is_off")); + Assert.assertEquals(1, reachedTheApp.size()); + Assert.assertEquals(0, crashRequests().size()); + + push(new ServerConfigBuilder().automaticCrashReporting(true)); + Thread.UncaughtExceptionHandler installed = Thread.getDefaultUncaughtExceptionHandler(); + Assert.assertNotSame(appHandler, installed); + push(new ServerConfigBuilder().automaticCrashReporting(true).eventQueueSize(5)); + Assert.assertSame(installed, Thread.getDefaultUncaughtExceptionHandler()); + + crashOnAThread(new RuntimeException("crash_while_both_are_on")); + Assert.assertEquals(2, reachedTheApp.size()); + List crashes = crashRequests(); + Assert.assertEquals(1, crashes.size()); + Assert.assertTrue(crashes.get(0).getString("_error").contains("crash_while_both_are_on")); + Assert.assertFalse(crashes.get(0).getBoolean("_nonfatal")); + + push(new ServerConfigBuilder().crashReporting(false)); + crashOnAThread(new RuntimeException("crash_while_crt_is_off")); + Countly.instance().crashes().recordHandledException(new Exception("handled_while_crt_is_off")); + Assert.assertEquals(3, reachedTheApp.size()); + Assert.assertEquals(1, crashRequests().size()); + + push(new ServerConfigBuilder().crashReporting(true).automaticCrashReporting(false)); + crashOnAThread(new RuntimeException("crash_while_acr_is_off_again")); + Countly.instance().crashes().recordHandledException(new Exception("handled_while_crt_is_on")); + Countly.instance().crashes().recordUnhandledException(new Exception("reported_while_crt_is_on")); + Assert.assertEquals(4, reachedTheApp.size()); + Assert.assertSame(installed, Thread.getDefaultUncaughtExceptionHandler()); + crashes = crashRequests(); + Assert.assertEquals(3, crashes.size()); + Assert.assertTrue(crashes.get(1).getString("_error").contains("handled_while_crt_is_on")); + Assert.assertTrue(crashes.get(1).getBoolean("_nonfatal")); + Assert.assertTrue(crashes.get(2).getString("_error").contains("reported_while_crt_is_on")); + Assert.assertFalse(crashes.get(2).getBoolean("_nonfatal")); + Assert.assertEquals(3, crashesBeingRecorded.size()); + + List reachedTheLaterHandler = new CopyOnWriteArrayList<>(); + Thread.UncaughtExceptionHandler laterHandler = (thread, throwable) -> { + reachedTheLaterHandler.add(throwable); + installed.uncaughtException(thread, throwable); + }; + Thread.setDefaultUncaughtExceptionHandler(laterHandler); + push(new ServerConfigBuilder().automaticCrashReporting(true)); + Countly.instance().halt(); + + Assert.assertSame(laterHandler, Thread.getDefaultUncaughtExceptionHandler()); + crashOnAThread(new RuntimeException("crash_after_halt")); + Assert.assertEquals(1, reachedTheLaterHandler.size()); + Assert.assertEquals(5, reachedTheApp.size()); + Assert.assertEquals(3, crashesBeingRecorded.size()); + Assert.assertEquals(0, filesWithPrefix("[CLY]_crash_")); + Assert.assertEquals(0, filesWithPrefix("[CLY]_request_")); + } + + /** + * The handler installed at init follows the resolved {@code crt} and {@code acr} and crash consent. + *

+ * Verifies that the developer default installs it, that a developer who disabled unhandled crash + * reporting gets none unless the response of the fetch made at init turns {@code acr} on, which + * installs it once even though the response arrives before the crash module finished its init, + * that stored {@code crt} off keeps it out until a response turns {@code crt} on, that it waits + * for crash consent, and that each stop puts the application's handler back. + */ + @Test + public void crashHandler_atInit_followsTheResolvedSwitchesAndConsent() { + Thread.UncaughtExceptionHandler appHandler = (thread, throwable) -> { + }; + Thread.setDefaultUncaughtExceptionHandler(appHandler); + + server.failing(); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.CrashReporting)); + Assert.assertNotSame(appHandler, Thread.getDefaultUncaughtExceptionHandler()); + Countly.instance().halt(); + Assert.assertSame(appHandler, Thread.getDefaultUncaughtExceptionHandler()); + + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.CrashReporting).disableUnhandledCrashReporting()); + Assert.assertFalse(provider().getAutomaticCrashReportingEnabled()); + Assert.assertSame(appHandler, Thread.getDefaultUncaughtExceptionHandler()); + Countly.instance().halt(); + + server.respondWith(new ServerConfigBuilder().automaticCrashReporting(true)); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.CrashReporting).disableUnhandledCrashReporting()); + Assert.assertTrue(provider().getAutomaticCrashReportingEnabled()); + Assert.assertNotSame(appHandler, Thread.getDefaultUncaughtExceptionHandler()); + Countly.instance().halt(); + Assert.assertSame(appHandler, Thread.getDefaultUncaughtExceptionHandler()); + + server.pending(); + init(TestUtils.getConfigSdkBehaviorSettings() + .enableFeatures(Config.Feature.CrashReporting) + .setSdkBehaviorSettings(new ServerConfigBuilder().crashReporting(false).build())); + Assert.assertTrue(provider().getAutomaticCrashReportingEnabled()); + Assert.assertSame(appHandler, Thread.getDefaultUncaughtExceptionHandler()); + push(new ServerConfigBuilder().crashReporting(true)); + Assert.assertNotSame(appHandler, Thread.getDefaultUncaughtExceptionHandler()); + Countly.instance().stop(); + Assert.assertSame(appHandler, Thread.getDefaultUncaughtExceptionHandler()); + + server.pending(); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.CrashReporting).setRequiresConsent(true)); + Assert.assertSame(appHandler, Thread.getDefaultUncaughtExceptionHandler()); + Countly.onConsent(Config.Feature.CrashReporting); + Assert.assertNotSame(appHandler, Thread.getDefaultUncaughtExceptionHandler()); + Countly.instance().halt(); + Assert.assertSame(appHandler, Thread.getDefaultUncaughtExceptionHandler()); + } + + /** + * {@code lt} off keeps location out of every request, and turning it off erases the location + * stored on the server. + *

+ * Verifies that with location tracking on, a location is sent on its own and with the begin + * request; that a response turning it off sends one erase request and a later change sends no + * second one; that while it is off setting a location through the location interface, the + * deprecated session call and the deprecated request builder sends nothing and a begin request + * carries no location; that while session tracking is off a location is not held back for a + * session that will not begin; that a response at init turning it off while the developer + * disabled location sends a single erase request; and that the stored switch keeps the + * developer's location out of the next init. + */ + @Test + public void locationTracking_off_keepsLocationOutOfEveryRequest_andTurningItOffErasesIt() { + Config config = TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.Location, Config.Feature.Sessions); + server.respondWith(new ServerConfigBuilder().networking(false)); + init(config); + + Countly.instance().location().setLocation("TR", "Izmir", "1,2", "1.1.1.1"); + Countly.session().begin(); + Countly.session().end(); + Map[] requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(3, requests.length); + Assert.assertEquals("Izmir", requests[0].get("city")); + Assert.assertEquals("1", requests[1].get("begin_session")); + Assert.assertEquals("Izmir", requests[1].get("city")); + Assert.assertEquals("1.1.1.1", requests[1].get("ip")); + + push(new ServerConfigBuilder().locationTracking(false)); + push(new ServerConfigBuilder().locationTracking(false).eventQueueSize(5)); + requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(4, requests.length); + Assert.assertEquals("", requests[3].get("location")); + Assert.assertFalse(requests[3].containsKey("city")); + + Countly.instance().location().setLocation("US", "New York", "3,4", "2.2.2.2"); + Countly.session().addLocation(5.0, 6.0); + Assert.assertNull(ModuleRequests.location(SDKCore.instance.config, 7.0, 8.0)); + Countly.session().begin(); + Countly.session().end(); + requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(Arrays.toString(requests), 6, requests.length); + Assert.assertEquals("1", requests[4].get("begin_session")); + assertNoLocation(requests[4]); + + push(new ServerConfigBuilder().locationTracking(true).sessionTracking(false)); + Assert.assertNotNull(Countly.session()); + Countly.instance().location().setLocation("NL", "Amsterdam", null, null); + requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(7, requests.length); + Assert.assertEquals("Amsterdam", requests[6].get("city")); + Countly.instance().halt(); + + server.respondWith(new ServerConfigBuilder().locationTracking(false).networking(false)); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.Location, Config.Feature.Sessions).disableLocation()); + requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(1, requests.length); + Assert.assertEquals("", requests[0].get("location")); + Countly.instance().stop(); + + server.pending(); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.Location, Config.Feature.Sessions).setLocation("DE", "Berlin", "9,9", null)); + Assert.assertFalse(provider().getLocationTrackingEnabled()); + Countly.session().begin(); + requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(2, requests.length); + Assert.assertEquals("1", requests[1].get("begin_session")); + assertNoLocation(requests[1]); + } + + /** + * {@code lt} off keeps the location of the deprecated user editor out of the user details. + *

+ * Verifies that with location tracking on, a location committed through the user editor is + * sent; that after a response turning it off sends the erase request, neither a location, + * country and city committed through the user editor nor a country and city held from before + * are sent with the user details; that opting out of location services still sends its null + * values; that a country and city held while it is on are not sent once it is turned off and on + * again; and that a location committed then is sent. + */ + @Test + public void locationTracking_off_keepsTheUserEditorLocationOutOfUserDetails() { + server.respondWith(new ServerConfigBuilder().networking(false)); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.Location, Config.Feature.UserProfiles)); + + Countly.instance().user().edit().setLocation(1.5, 2.5).commit(); + Map[] requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(1, requests.length); + Assert.assertEquals("1.5,2.5", requests[0].get("location")); + + Countly.instance().user().edit().setCountry("TR").setCity("Izmir"); + push(new ServerConfigBuilder().locationTracking(false)); + requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(2, requests.length); + Assert.assertEquals("", requests[1].get("location")); + + Countly.instance().user().edit().setLocation(56.4, 123.4).setCountry("US").setCity("New York").set(PredefinedUserPropertyKeys.NAME, "Name").commit(); + requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(3, requests.length); + Assert.assertEquals("Name", new JSONObject(requests[2].get("user_details")).getString("name")); + assertNoLocation(requests[2]); + + Countly.instance().user().edit().optOutFromLocationServices().commit(); + requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(4, requests.length); + Assert.assertEquals("null", requests[3].get("location")); + Assert.assertEquals("null", requests[3].get("city")); + Assert.assertEquals("null", requests[3].get("country_code")); + + push(new ServerConfigBuilder().locationTracking(true)); + Countly.instance().user().edit().setCountry("NL").setCity("Amsterdam"); + push(new ServerConfigBuilder().locationTracking(false)); + push(new ServerConfigBuilder().locationTracking(true)); + Countly.instance().user().edit().set(PredefinedUserPropertyKeys.NAME, "Other").commit(); + requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(5, requests.length); + Assert.assertEquals("Other", new JSONObject(requests[4].get("user_details")).getString("name")); + assertNoLocation(requests[4]); + + Countly.instance().user().edit().setLocation(3.5, 4.5).commit(); + requests = TestUtils.getCurrentRQ(); + Assert.assertEquals(6, requests.length); + Assert.assertEquals("3.5,4.5", requests[5].get("location")); + } + + /** + * {@code log} decides what the SDK prints, while the log listener hears every line. + *

+ * Verifies that with the developer level off, provided logging on prints every level from init + * and a response turning it off prints nothing; that a stored off silences a developer level of + * warnings until a response turns it on, which prints that level and not every level; and that + * without the setting the developer level prints as it is. The listener hears the lines that are + * not printed. + */ + @Test + public void logging_decidesWhatIsPrinted_whileTheListenerHearsEveryLine() { + List heard = new CopyOnWriteArrayList<>(); + ByteArrayOutputStream printed = new ByteArrayOutputStream(); + PrintStream originalOut = System.out; + System.setOut(new PrintStream(printed, true)); + try { + server.pending(); + init(configWithProbeListener(heard).setSdkBehaviorSettings(new ServerConfigBuilder().logging(true).build())); + Log log = SDKCore.instance.config.getLogger(); + Assert.assertEquals(Config.LoggingLevel.VERBOSE, log.getPrintLevel()); + log.v("probe_verbose_printed"); + Assert.assertTrue(printedText(printed).contains("probe_verbose_printed")); + + push(new ServerConfigBuilder().logging(false)); + Assert.assertEquals(Config.LoggingLevel.OFF, log.getPrintLevel()); + log.e("probe_error_silenced"); + Assert.assertFalse(printedText(printed).contains("probe_error_silenced")); + Assert.assertTrue(heard.contains("probe_error_silenced")); + Countly.instance().stop(); + + server.pending(); + init(configWithProbeListener(heard).setLoggingLevel(Config.LoggingLevel.WARN)); + log = SDKCore.instance.config.getLogger(); + Assert.assertEquals(Config.LoggingLevel.OFF, log.getPrintLevel()); + log.w("probe_warning_silenced"); + Assert.assertFalse(printedText(printed).contains("probe_warning_silenced")); + + push(new ServerConfigBuilder().logging(true)); + Assert.assertEquals(Config.LoggingLevel.WARN, log.getPrintLevel()); + log.d("probe_debug_below_the_level"); + log.w("probe_warning_printed"); + Assert.assertFalse(printedText(printed).contains("probe_debug_below_the_level")); + Assert.assertTrue(printedText(printed).contains("probe_warning_printed")); + Assert.assertTrue(heard.containsAll(Arrays.asList("probe_warning_silenced", "probe_debug_below_the_level", "probe_warning_printed"))); + Countly.instance().halt(); + + server.pending(); + init(configWithProbeListener(heard).setLoggingLevel(Config.LoggingLevel.ERROR)); + Assert.assertEquals(Config.LoggingLevel.ERROR, SDKCore.instance.config.getLogger().getPrintLevel()); + Countly.instance().halt(); + + init(configWithProbeListener(heard)); + Assert.assertEquals(Config.LoggingLevel.OFF, SDKCore.instance.config.getLogger().getPrintLevel()); + } finally { + System.setOut(originalOut); + } + } + + /** + * {@code rqs} caps the stored request queue only when the settings set it. + *

+ * Verifies that the developer request queue size leaves the stored queue unbounded, that once a + * response sets a size, storing a request drops the oldest ones over it with a warning saying how + * many, and that a stored size also holds at the next init for a crash of an earlier run that is + * turned into a request. + */ + @Test + public void requestQueueSize_fromTheSettings_capsTheStoredQueue_andWithoutItTheQueueIsUnbounded() { + List dropWarnings = new CopyOnWriteArrayList<>(); + Config config = TestUtils.getConfigSdkBehaviorSettings() + .enableFeatures(Config.Feature.Events) + .setEventQueueSizeToSend(1) + .setRequestQueueMaxSize(2) + .setLogListener((message, level) -> { + if (level == Config.LoggingLevel.WARN && message.startsWith("[ModuleRequests] dropOldestRequestsOverQueueLimit")) { + dropWarnings.add(message); + } + }); + server.respondWith(new ServerConfigBuilder().networking(false)); + init(config); + + for (int i = 1; i <= 4; i++) { + Countly.instance().events().recordEvent("event_" + i); + letTheClockCatchUp(); + } + Assert.assertFalse(provider().isRequestQueueMaxSizeFromBehaviorSettings()); + Assert.assertEquals(Arrays.asList("event_1", "event_2", "event_3", "event_4"), contentOfEachRequest()); + Assert.assertTrue(dropWarnings.isEmpty()); + + push(new ServerConfigBuilder().requestQueueSize(3)); + Countly.instance().events().recordEvent("event_5"); + Assert.assertEquals(Arrays.asList("event_3", "event_4", "event_5"), contentOfEachRequest()); + Assert.assertEquals(1, dropWarnings.size()); + Assert.assertTrue(dropWarnings.get(0), dropWarnings.get(0).contains("size of [3]") && dropWarnings.get(0).contains("dropped the [2] oldest")); + + Countly.instance().events().recordEvent("event_6"); + Assert.assertEquals(Arrays.asList("event_4", "event_5", "event_6"), contentOfEachRequest()); + Assert.assertEquals(2, dropWarnings.size()); + Assert.assertTrue(dropWarnings.get(1), dropWarnings.get(1).contains("dropped the [1] oldest")); + Countly.instance().stop(); + + TestUtils.writeToFile("crash_" + TimeUtils.uniqueTimestampMs(), new JSONObject().put("_error", "earlier_run_crash").put("_nonfatal", false).toString()); + server.pending(); + init(config); + Assert.assertTrue(provider().isRequestQueueMaxSizeFromBehaviorSettings()); + Assert.assertEquals(Arrays.asList("event_5", "event_6", "crash"), contentOfEachRequest()); + Assert.assertEquals(3, dropWarnings.size()); + } + + /** + * {@code lbc} is read each time a breadcrumb is added. + *

+ * Verifies that the limit of the response at init overrides the developer's, that the crash + * request carries only the newest breadcrumbs within it, and that after a response shrinks the + * limit while breadcrumbs are kept, the next breadcrumb brings them within the new limit. + */ + @Test + public void breadcrumbLimit_isReadWhenABreadcrumbIsAdded() { + server.respondWith(new ServerConfigBuilder().breadcrumbLimit(3).networking(false)); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.CrashReporting).setMaxBreadcrumbCount(10)); + Assert.assertEquals(3, provider().getMaxBreadcrumbCount()); + + addBreadcrumbs("a", 5); + Countly.instance().crashes().recordHandledException(new Exception("first")); + + push(new ServerConfigBuilder().breadcrumbLimit(5)); + addBreadcrumbs("b", 5); + push(new ServerConfigBuilder().breadcrumbLimit(2)); + Countly.instance().crashes().addCrashBreadcrumb("c1"); + Countly.instance().crashes().recordHandledException(new Exception("second")); + + List crashes = crashRequests(); + Assert.assertEquals(2, crashes.size()); + Assert.assertEquals("a3\na4\na5", crashes.get(0).getString("_logs")); + Assert.assertEquals("b5\nc1", crashes.get(1).getString("_logs")); + } + + /** + * {@code eqs} and {@code sui} changed by a response apply while the SDK runs. + *

+ * Verifies that the event queue is flushed at the new threshold the next time an event is added, + * that a changed session update interval restarts the global timer at that interval, and that a + * response repeating it keeps the running timer. + */ + @Test + public void eventQueueSizeAndSessionUpdateInterval_changedByAResponse_applyWhileTheSdkRuns() { + server.respondWith(new ServerConfigBuilder().eventQueueSize(5).sessionUpdateInterval(30).networking(false)); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.Events).setEventQueueSizeToSend(100)); + CountlyTimer timerAtInit = SDKCore.instance.countlyTimer; + Assert.assertEquals(30, timerAtInit.getTimerDelaySeconds()); + + Countly.instance().events().recordEvent("e1"); + Countly.instance().events().recordEvent("e2"); + push(new ServerConfigBuilder().eventQueueSize(3)); + TestUtils.validateEQSize(2); + Assert.assertEquals(0, TestUtils.getCurrentRQ().length); + + Countly.instance().events().recordEvent("e3"); + TestUtils.validateEQSize(0); + Assert.assertEquals(3, TestUtils.readEventsFromRequest(0, TestUtils.DEVICE_ID).size()); + + push(new ServerConfigBuilder().eventQueueSize(1)); + Countly.instance().events().recordEvent("e4"); + Assert.assertEquals(2, TestUtils.getCurrentRQ().length); + Assert.assertEquals("e4", TestUtils.readEventsFromRequest(1, TestUtils.DEVICE_ID).get(0).key); + + push(new ServerConfigBuilder().sessionUpdateInterval(45)); + CountlyTimer restarted = SDKCore.instance.countlyTimer; + Assert.assertNotSame(timerAtInit, restarted); + Assert.assertEquals(45, restarted.getTimerDelaySeconds()); + + push(new ServerConfigBuilder().sessionUpdateInterval(45).eventQueueSize(2)); + Assert.assertSame(restarted, SDKCore.instance.countlyTimer); + Countly.instance().events().recordEvent("e5"); + TestUtils.validateEQSize(1); + Countly.instance().events().recordEvent("e6"); + TestUtils.validateEQSize(0); + Assert.assertEquals(3, TestUtils.getCurrentRQ().length); + } + + // endregion + // region helpers + + /** + * Initializes the SDK with {@link #server} answering its settings requests. + * + * @param config the configuration + */ + private void init(Config config) { + InternalConfig internalConfig = new InternalConfig(config); + internalConfig.immediateRequestGenerator = server; + Countly.instance().init(internalConfig); + letTheClockCatchUp(); + } + + /** + * Answers the next settings request with the given payload and makes the SDK fetch, as the + * refresh timer does. + * + * @param builder the payload + */ + private void push(ServerConfigBuilder builder) { + letTheClockCatchUp(); + server.respondWith(builder); + SDKCore.instance.module(ModuleConfiguration.class).fetchConfigFromServer(SDKCore.instance.config); + } + + /** + * The settings in effect in the running SDK. + * + * @return the provider + */ + private static ConfigurationProvider provider() { + return SDKCore.instance.config.getConfigurationProvider(); + } + + /** + * Waits until the clock is past every timestamp handed out so far. A request file is named after + * a {@link TimeUtils#uniqueTimestampMs()} value, which is unique among the last ten values only, + * so a long burst of requests could reuse a name and overwrite a queued request. + */ + private static void letTheClockCatchUp() { + long latest = TimeUtils.uniqueTimestampMs(); + while (System.currentTimeMillis() <= latest) { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + } + + /** + * How many stored requests carry a parameter. + * + * @param param the parameter name + * @return the number of requests + */ + private static int requestsWith(String param) { + int count = 0; + for (Map request : TestUtils.getCurrentRQ()) { + if (request.containsKey(param)) { + count++; + } + } + return count; + } + + /** + * What each stored request carries, in queue order: the key of its first event, or + * {@code "crash"} for a crash request. + * + * @return one entry per request + */ + private static List contentOfEachRequest() { + List contents = new ArrayList<>(); + for (Map request : TestUtils.getCurrentRQ()) { + if (request.containsKey("crash")) { + contents.add("crash"); + } else { + contents.add(new JSONArray(request.get("events")).getJSONObject(0).getString("key")); + } + } + return contents; + } + + /** + * The crash objects of the stored crash requests, in queue order. + * + * @return the crash objects + */ + private static List crashRequests() { + List crashes = new ArrayList<>(); + for (Map request : TestUtils.getCurrentRQ()) { + if (request.containsKey("crash")) { + crashes.add(new JSONObject(request.get("crash"))); + } + } + return crashes; + } + + /** + * The {@code [CLY]_view} events in the event queue, in queue order. + * + * @return the view events + */ + private static List viewEvents() { + List views = new ArrayList<>(); + for (EventImpl event : TestUtils.getCurrentEQ()) { + if (ModuleViews.KEY_VIEW_EVENT.equals(event.key)) { + views.add(event); + } + } + return views; + } + + /** + * How many files in the storage directory start with a prefix. + * + * @param prefix the file name prefix + * @return the number of files + */ + private static int filesWithPrefix(String prefix) { + File[] files = TestUtils.getTestSDirectory().listFiles((dir, name) -> name.startsWith(prefix)); + return files == null ? 0 : files.length; + } + + /** + * Asserts that a request carries no location parameter, not even the empty one that erases it. + * + * @param request the request parameters + */ + private static void assertNoLocation(Map request) { + for (String param : Arrays.asList("location", "city", "country_code", "ip")) { + Assert.assertFalse("carries " + param + ": " + request, request.containsKey(param)); + } + } + + /** + * Adds numbered breadcrumbs, {@code prefix1} to {@code prefixN}. + * + * @param prefix the text before the number + * @param count how many + */ + private static void addBreadcrumbs(String prefix, int count) { + for (int i = 1; i <= count; i++) { + Countly.instance().crashes().addCrashBreadcrumb(prefix + i); + } + } + + /** + * Throws on a new thread and waits for it to end, which is after the default uncaught exception + * handler returned. + * + * @param crash what the thread throws + */ + private static void crashOnAThread(RuntimeException crash) throws InterruptedException { + Thread thread = new Thread(() -> { + throw crash; + }); + thread.start(); + thread.join(); + } + + /** + * The settings test configuration with a log listener that keeps the probe lines of the logging test. + * + * @param heard where the probe lines go + * @return the configuration + */ + private static Config configWithProbeListener(List heard) { + return TestUtils.getConfigSdkBehaviorSettings().setLogListener((message, level) -> { + if (message.startsWith("probe_")) { + heard.add(message); + } + }); + } + + /** + * What was printed so far. + * + * @param printed the captured output + * @return the text + */ + private static String printedText(ByteArrayOutputStream printed) { + return new String(printed.toByteArray(), StandardCharsets.UTF_8); + } + + // endregion +} 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 new file mode 100644 index 000000000..0b6860d58 --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationLimitsTests.java @@ -0,0 +1,830 @@ +package ly.count.sdk.java.internal; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; +import ly.count.sdk.java.Crash; +import ly.count.sdk.java.CrashProcessor; +import ly.count.sdk.java.PredefinedUserPropertyKeys; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import static ly.count.sdk.java.internal.ServerConfigBuilder.names; + +/** + * The SDK internal limits of the SDK behavior settings, {@code lkl}, {@code lvs}, {@code lsv}, + * {@code ltlpt} and {@code ltl}, with the breadcrumb limit {@code lbc}, observed through the public + * API: what custom events, timed events, views, user properties, crashes and feedback widget results + * send once the settings set limits, how a later response changes them, and that nothing is cut + * while the settings set none. + *

+ * Settings requests go through a {@link ModuleConfigurationTests.ServerConfigResponder}, which answers + * on the calling thread, so the response of the fetch made at init applies before init returns and a + * later one is pushed by fetching the way the refresh timer does. Networking is off through the + * settings wherever they are fetched, so every stored request stays on disk to be read. + */ +@RunWith(JUnit4.class) +public class ModuleConfigurationLimitsTests { + + private ModuleConfigurationTests.ServerConfigResponder server; + private final List warnings = new CopyOnWriteArrayList<>(); + + /** + * Starts every test from empty storage, without a test module, with a fresh responder and with + * the crash processor passing crashes through. + */ + @Before + public void beforeTest() { + TestUtils.createCleanTestState(); + SDKCore.testDummyModule = null; + server = new ModuleConfigurationTests.ServerConfigResponder(); + warnings.clear(); + DumpingCrashProcessor.replaceWithDump = false; + DumpingCrashProcessor.framesPerThread = 5; + } + + /** + * Stops the SDK and clears its data. + */ + @After + public void afterTest() { + Countly.instance().halt(); + DumpingCrashProcessor.replaceWithDump = false; + } + + // region scenarios + + /** + * {@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, 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 + * sort last are dropped and that the caller's map is left as it was; that an event whose truncated + * key is whitelisted but whose full + * key is not is dropped; that a timed event is cut the same way; and that a feedback widget + * result keeps every key and entry and the values the SDK adds, only its own strings being cut. + */ + @Test + public void customEvents_areCutAfterTheFilters_andInternalEventsOnlyGetWidgetValuesCut() { + server.respondWith(smallLimits() + .eventFilterList(names("purchase_completed", "timed_checkout", "check"), true) + .segmentationFilterList(names("internal_notes", "payme"), false)); + init(configWithWarnings().enableFeatures(Config.Feature.Events, Config.Feature.Feedback).setEventQueueSizeToSend(100)); + + Map segmentation = new HashMap<>(); + segmentation.put("payment_method", "credit_card"); + segmentation.put("category_a", "books"); + segmentation.put("category_b", "movies"); + segmentation.put("internal_notes", "removed_by_the_filter"); + segmentation.put("aa_unsupported", new Object()); + 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); + sendEventQueue(); + + List sent = sentEvents(); + Assert.assertEquals(keysOf(sent).toString(), 1, sent.size()); + assertEvent(sent.get(0), "purch", TestUtils.map("categ", "movies", "payme", "credit")); + Assert.assertEquals(2, sent.get(0).count); + Assert.assertEquals(9.99, sent.get(0).sum, 0.0); + Assert.assertEquals(segmentation, callers); + Assert.assertEquals(1, warningsContaining("[ModuleEvents] recordEventInternal, the key [purchase_completed] is longer than the key length limit of [5]")); + Assert.assertEquals(1, warningsContaining("its value replaces that of [categ]")); + Assert.assertEquals(1, warningsContaining("the segmentation has [3] entries, over the limit of [2]")); + + Countly.instance().events().recordEvent("checkout_started"); + Assert.assertEquals(1, warningsContaining("is filtered out by the event filter")); + + Countly.instance().events().startEvent("timed_checkout"); + Countly.instance().events().endEvent("timed_checkout", TestUtils.map("duration_bucket", "long_running", "attempt", 2), 1, null); + + CountlyFeedbackWidget widget = new CountlyFeedbackWidget(); + widget.widgetId = "rating_widget_identifier"; + widget.type = FeedbackWidgetType.rating; + widget.name = "rating"; + widget.tags = new String[0]; + Map widgetResult = new HashMap<>(); + widgetResult.put("rating", 4); + widgetResult.put("comment", "a comment longer than six characters"); + widgetResult.put("email", "user@example.com"); + widgetResult.put("contactMe", true); + Countly.instance().feedback().reportFeedbackWidgetManually(widget, null, widgetResult); + + List queued = TestUtils.getCurrentEQ(); + Assert.assertEquals(keysOf(queued).toString(), 2, queued.size()); + assertEvent(queued.get(0), "timed", TestUtils.map("attem", 2, "durat", "long_r")); + assertEvent(queued.get(1), FeedbackWidgetType.rating.eventKey, TestUtils.map("platform", WidgetUrlBuilder.PLATFORM, + "app_version", TestUtils.APPLICATION_VERSION, "widget_id", "rating_widget_identifier", + "rating", 4, "comment", "a comm", "email", "user@e", "contactMe", true)); + Assert.assertEquals(1, TestUtils.getCurrentRQ().length); + } + + /** + * {@code lkl}, {@code lvs} and {@code lsv} cut the name and the segmentation of views, while the + * keys the SDK adds are neither cut nor counted. + *

+ * Verifies on the wire that the name is cut to 5 characters on the start and the end event, that + * the global, the added and the given segmentation are merged and then cut, that a key cut to a + * 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, and that a view started under a long name is still + * stopped by that name. + */ + @Test + public void views_nameAndSegmentationAreCut_whileTheKeysTheSdkAddsAreNeitherCutNorCounted() { + 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")); + + String viewId = Countly.instance().views().startView("SettingsScreen", TestUtils.map("visitor_type", "returning", "aa_first", 1)); + 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 })); + sendEventQueue(); + + List sent = sentEvents(); + Assert.assertEquals(keysOf(sent).toString(), 2, sent.size()); + assertEvent(sent.get(0), ModuleViews.KEY_VIEW_EVENT, TestUtils.map("aa_fi", 1, "globa", "global", + ModuleViews.KEY_NAME, "Setti", ModuleViews.KEY_VISIT, "1", ModuleViews.KEY_START, "1", ModuleViews.KEY_SEGMENT, platform)); + assertEvent(sent.get(1), ModuleViews.KEY_VIEW_EVENT, TestUtils.map("added", "added_", "bb_se", 2, + ModuleViews.KEY_NAME, "Setti", ModuleViews.KEY_SEGMENT, platform)); + Assert.assertEquals(viewId, sent.get(1).id); + Assert.assertEquals(2, warningsContaining("[ModuleViews] createViewEventSegmentation, a key truncated to the reserved key [visit] is removed")); + + Countly.instance().views().startView("Home"); + Countly.instance().views().startView("ProfileScreen"); + Countly.instance().views().stopViewWithName("ProfileScreen"); + + List queued = TestUtils.getCurrentEQ(); + Assert.assertEquals(keysOf(queued).toString(), 3, queued.size()); + assertEvent(queued.get(0), ModuleViews.KEY_VIEW_EVENT, TestUtils.map("globa", "global", + ModuleViews.KEY_NAME, "Home", ModuleViews.KEY_VISIT, "1", ModuleViews.KEY_SEGMENT, platform)); + Assert.assertEquals("Profi", queued.get(1).segmentation.get(ModuleViews.KEY_NAME)); + 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(1, TestUtils.getCurrentRQ().length); + } + + /** + * {@code lkl}, {@code lvs} and {@code lsv} cut custom user properties, sets and modifications, + * while predefined properties only get their string values cut and the picture is never cut. The + * limits in effect when the request is built apply. + *

+ * Verifies on the wire that predefined keys stay whole, that the name, email and organization + * are cut to 6 characters while the picture URL, the gender and the birth year are sent as they + * are; that custom keys are cut to 5 characters, the key that sorts last winning a collision, + * string values cut to 6, and past 2 sets the keys that sort last are dropped; that modification + * keys and string operands are cut the same way and never count against the entry limit; and + * that a property set before a response lowered the key length limit is cut by the new limit. + */ + @Test + public void userProperties_customKeysAndValuesAreCutForSetsAndModifications_predefinedOnlyTheirValuesAndNeverThePicture() { + server.respondWith(smallLimits()); + init(configWithWarnings()); + + String pictureUrl = "https://example.com/pictures/avatar.png"; + Map batch = new LinkedHashMap<>(); + batch.put(PredefinedUserPropertyKeys.NAME, "Johnathan Doe"); + batch.put(PredefinedUserPropertyKeys.EMAIL, "johnathan@example.com"); + batch.put(PredefinedUserPropertyKeys.ORGANIZATION, "Countly Ltd"); + batch.put(PredefinedUserPropertyKeys.PICTURE_PATH, pictureUrl); + batch.put(PredefinedUserPropertyKeys.GENDER, "M"); + batch.put(PredefinedUserPropertyKeys.BIRTH_YEAR, 1990); + batch.put("favourite_colour", "turquoise"); + batch.put("favourite_food", "spaghetti"); + batch.put("aaa_first", 1); + batch.put("zzz_last", "dropped"); + Countly.instance().userProfile().setProperties(batch); + Countly.instance().userProfile().increment("login_count_total"); + Countly.instance().userProfile().push("visited_pages", "homepage_long"); + Countly.instance().userProfile().setOnce("first_seen_at", "2024-01-01"); + Countly.instance().userProfile().save(); + TestUtils.letTheClockCatchUp(); + + JSONObject details = userDetails(0); + Assert.assertEquals("Johnat", details.getString(PredefinedUserPropertyKeys.NAME)); + Assert.assertEquals("johnat", details.getString(PredefinedUserPropertyKeys.EMAIL)); + Assert.assertEquals("Countl", details.getString(PredefinedUserPropertyKeys.ORGANIZATION)); + Assert.assertEquals(pictureUrl, details.getString(PredefinedUserPropertyKeys.PICTURE)); + Assert.assertEquals("M", details.getString(PredefinedUserPropertyKeys.GENDER)); + Assert.assertEquals(1990, details.getInt(PredefinedUserPropertyKeys.BIRTH_YEAR)); + JSONObject custom = details.getJSONObject(ModuleUserProfile.CUSTOM_KEY); + Assert.assertEquals(names("aaa_f", "favou", "login", "visit", "first"), custom.keySet()); + Assert.assertEquals(1, custom.getInt("aaa_f")); + Assert.assertEquals("spaghe", custom.getString("favou")); + Assert.assertEquals(1, custom.getJSONObject("login").getInt("$inc")); + Assert.assertEquals("homepa", custom.getJSONObject("visit").getString("$push")); + Assert.assertEquals("2024-0", custom.getJSONObject("first").getString("$setOnce")); + Assert.assertEquals(1, warningsContaining("[ModuleUserProfile] perform, the segmentation has [3] entries, over the limit of [2]")); + + Countly.instance().userProfile().setProperty("abc_property", "value"); + Countly.instance().userProfile().incrementBy("xyz_counter", 3); + push(new ServerConfigBuilder().keyLengthLimit(3)); + Countly.instance().userProfile().save(); + TestUtils.letTheClockCatchUp(); + + custom = userDetails(1).getJSONObject(ModuleUserProfile.CUSTOM_KEY); + Assert.assertEquals(names("abc", "xyz"), custom.keySet()); + Assert.assertEquals("value", custom.getString("abc")); + Assert.assertEquals(3, custom.getJSONObject("xyz").getInt("$inc")); + } + + /** + * {@code ltl} cuts every stack trace line, {@code ltlpt} the lines of each thread of a trace dump, + * {@code lkl}, {@code lvs} and {@code lsv} the custom segments, and {@code lvs} and {@code lbc} + * the breadcrumbs, including what a crash processor adds. + *

+ * Verifies on the wire that a handled exception keeps every line of its stack trace, each cut to + * 20 characters, that its segments are cut to 5 character keys and 6 character values with the 2 + * keys that sort first kept, and that only the 2 newest breadcrumbs are sent, cut to 6 characters; + * and that when a crash processor replaces the stack trace with a dump of two threads and sets its + * own segments and breadcrumbs, each thread keeps its 3 top lines, the lines are cut to 20 + * characters and the segments and breadcrumbs it set are cut as well. + */ + @Test + public void crashes_stackTraceLinesSegmentsAndBreadcrumbsAreCut_includingWhatACrashProcessorAdds() { + server.respondWith(smallLimits().breadcrumbLimit(2)); + init(configWithWarnings().enableFeatures(Config.Feature.CrashReporting).setCrashProcessorClass(DumpingCrashProcessor.class)); + + Countly.instance().crashes().addCrashBreadcrumb("first_breadcrumb"); + Countly.instance().crashes().addCrashBreadcrumb("second_breadcrumb"); + Countly.instance().crashes().addCrashBreadcrumb("third_breadcrumb"); + Exception exception = new Exception("a message longer than twenty characters"); + Countly.instance().crashes().recordHandledException(exception, TestUtils.map("screen_name", "checkout_page", "retry_count", 3, "zz_last", "value")); + TestUtils.letTheClockCatchUp(); + + DumpingCrashProcessor.replaceWithDump = true; + Countly.instance().crashes().recordUnhandledException(new RuntimeException("dumped")); + TestUtils.letTheClockCatchUp(); + + List crashes = crashRequests(); + Assert.assertEquals(2, crashes.size()); + + JSONObject handled = crashes.get(0); + String fullStackTrace = stackTraceOf(exception); + Assert.assertTrue(lineCount(fullStackTrace) > 3); + Assert.assertEquals(truncateLines(fullStackTrace, 20), handled.getString("_error")); + Assert.assertEquals(lineCount(fullStackTrace), lineCount(handled.getString("_error"))); + Assert.assertTrue(handled.getBoolean("_nonfatal")); + Assert.assertEquals("second\nthird_", handled.getString("_logs")); + JSONObject segments = handled.getJSONObject("_custom"); + Assert.assertEquals(names("retry", "scree"), segments.keySet()); + Assert.assertEquals(3, segments.getInt("retry")); + Assert.assertEquals("checko", segments.getString("scree")); + + JSONObject dumped = crashes.get(1); + String frameLine = "\tat ly.count.Example\n"; + String expectedDump = "Thread [main]:" + System.lineSeparator() + frameLine + frameLine + frameLine + "\n\n" + + "Thread [worker-threa\n" + frameLine + frameLine + frameLine + "\n\n"; + Assert.assertEquals("anr", dumped.getString("_type")); + Assert.assertFalse(dumped.getBoolean("_nonfatal")); + Assert.assertEquals(expectedDump, dumped.getString("_error")); + segments = dumped.getJSONObject("_custom"); + Assert.assertEquals(names("anoth", "proce"), segments.keySet()); + Assert.assertEquals("anothe", segments.getString("anoth")); + Assert.assertEquals("proces", segments.getString("proce")); + Assert.assertEquals("proces", dumped.getString("_logs")); + Assert.assertEquals(2, warningsContaining("[ModuleCrash] onCrash, the stack trace of the thread")); + } + + /** + * A response that changes a limit applies from the next call, lowering or raising it. + *

+ * Verifies that an event recorded before any limit is sent whole, that after a response brings + * key and value limits the same call is cut by them, that a later response lowering the key + * length and adding an entry limit lifts the value limit it leaves out, that one raising + * every limit sends the event whole again from the caller's untouched map, and that breadcrumbs + * and stack trace lines follow the limits in effect when each breadcrumb is added and when the + * crash is recorded. + */ + @Test + public void aResponseChangingTheLimits_appliesFromTheNextCall() { + server.respondWith(new ServerConfigBuilder().networking(false)); + init(configWithWarnings().enableFeatures(Config.Feature.Events, Config.Feature.CrashReporting).setEventQueueSizeToSend(100)); + Map segmentation = TestUtils.map("segment_key", "segment_value", "second", 2); + + Countly.instance().events().recordEvent("event_key", segmentation); + push(new ServerConfigBuilder().keyLengthLimit(8).valueSizeLimit(4)); + Countly.instance().events().recordEvent("event_key", segmentation); + push(new ServerConfigBuilder().keyLengthLimit(3).segmentationValuesLimit(1)); + Assert.assertEquals(ModuleConfiguration.NO_LIMIT, provider().getMaxValueSize()); + Countly.instance().events().recordEvent("event_key", segmentation); + push(new ServerConfigBuilder().keyLengthLimit(64).valueSizeLimit(64).segmentationValuesLimit(64)); + Countly.instance().events().recordEvent("event_key", segmentation); + + List queued = TestUtils.getCurrentEQ(); + Assert.assertEquals(keysOf(queued).toString(), 4, queued.size()); + assertEvent(queued.get(0), "event_key", segmentation); + assertEvent(queued.get(1), "event_ke", TestUtils.map("segment_", "segm", "second", 2)); + assertEvent(queued.get(2), "eve", TestUtils.map("sec", 2)); + assertEvent(queued.get(3), "event_key", segmentation); + + push(new ServerConfigBuilder().valueSizeLimit(4)); + Countly.instance().crashes().addCrashBreadcrumb("alpha_breadcrumb"); + push(new ServerConfigBuilder().valueSizeLimit(4).breadcrumbLimit(1).traceLengthLimit(12)); + Countly.instance().crashes().addCrashBreadcrumb("omega_breadcrumb"); + Exception exception = new Exception("recorded after the change"); + Countly.instance().crashes().recordHandledException(exception); + TestUtils.letTheClockCatchUp(); + + List crashes = crashRequests(); + Assert.assertEquals(1, crashes.size()); + Assert.assertEquals("omeg", crashes.get(0).getString("_logs")); + Assert.assertEquals(truncateLines(stackTraceOf(exception), 12), crashes.get(0).getString("_error")); + } + + /** + * The key length limit of the developer configuration cuts keys while the settings set none, the + * settings override it while they carry {@code lkl}, and it applies again once they stop. + *

+ * Verifies that a developer limit of 5 cuts the event key and the segmentation keys while the + * values stay whole, that a response with a key length limit of 8 cuts to 8 instead, and that a + * response leaving the limit out brings back the developer limit of 5. + */ + @Test + public void theDeveloperKeyLengthLimit_cutsKeys_untilTheSettingsOverrideIt() { + server.respondWith(new ServerConfigBuilder().networking(false)); + init(configWithWarnings().enableFeatures(Config.Feature.Events).setEventQueueSizeToSend(100).setMaxKeyLength(5)); + Assert.assertEquals(5, provider().getMaxKeyLength()); + Map segmentation = TestUtils.map("segment_key", "segment_value", "second", 2); + + Countly.instance().events().recordEvent("event_key", segmentation); + push(new ServerConfigBuilder().keyLengthLimit(8)); + Assert.assertEquals(8, provider().getMaxKeyLength()); + Countly.instance().events().recordEvent("event_key", segmentation); + push(new ServerConfigBuilder().networking(false)); + Assert.assertEquals(5, provider().getMaxKeyLength()); + Countly.instance().events().recordEvent("event_key", segmentation); + + List queued = TestUtils.getCurrentEQ(); + Assert.assertEquals(keysOf(queued).toString(), 3, queued.size()); + assertEvent(queued.get(0), "event", TestUtils.map("segme", "segment_value", "secon", 2)); + assertEvent(queued.get(1), "event_ke", TestUtils.map("segment_", "segment_value", "second", 2)); + assertEvent(queued.get(2), "event", TestUtils.map("segme", "segment_value", "secon", 2)); + } + + /** + * Without any SDK behavior settings, the key length limit of the developer configuration cuts the + * keys of events, views and custom user properties. + *

+ * Verifies with a limit of 4 the event key and segmentation keys, the view name, and the custom + * user property keys of a set and of a modification, while the keys the SDK adds to a view stay + * whole. + */ + @Test + public void withoutSettings_theDeveloperKeyLengthLimitCutsKeys() { + Countly.instance().init(TestUtils.getBaseConfig().setLogListener(this::keepWarning) + .enableFeatures(Config.Feature.Events, Config.Feature.Views, Config.Feature.UserProfiles) + .setEventQueueSizeToSend(100).setMaxKeyLength(4)); + + Countly.instance().events().recordEvent("event_key", TestUtils.map("segment_key", "segment_value")); + Countly.instance().views().startView("view_name"); + List queued = TestUtils.getCurrentEQ(); + Assert.assertEquals(keysOf(queued).toString(), 2, queued.size()); + assertEvent(queued.get(0), "even", TestUtils.map("segm", "segment_value")); + Assert.assertEquals("view", queued.get(1).segmentation.get(ModuleViews.KEY_NAME)); + Assert.assertEquals("1", queued.get(1).segmentation.get(ModuleViews.KEY_VISIT)); + + Countly.instance().userProfile().setProperty("custom_key", "custom_value"); + Countly.instance().userProfile().push("list_key", "item"); + Countly.instance().userProfile().save(); + TestUtils.letTheClockCatchUp(); + + JSONObject details = null; + for (Map request : TestUtils.getCurrentRQ()) { + if (request.containsKey("user_details")) { + details = new JSONObject(request.get("user_details")); + } + } + Assert.assertNotNull(details); + JSONObject custom = details.getJSONObject(ModuleUserProfile.CUSTOM_KEY); + Assert.assertEquals("custom_value", custom.getString("cust")); + Assert.assertEquals("item", custom.getJSONObject("list").getString("$push")); + Assert.assertEquals(2, custom.length()); + Assert.assertTrue(warningsContaining("key length limit of [4]") > 0); + } + + /** + * With a live response that sets no limit, nothing any feature sends is cut, however long or wide. + *

+ * Verifies that the provider reports no key, value, entry, lines per thread and line length limit + * and the developer breadcrumb limit, and then the same as + * {@link #assertNothingIsCut()}. + */ + @Test + public void withSettingsThatSetNoLimit_nothingIsCut() { + server.respondWith(new ServerConfigBuilder().networking(false)); + init(configWithWarnings().enableFeatures(Config.Feature.Events, Config.Feature.Views, Config.Feature.CrashReporting, Config.Feature.Feedback) + .setEventQueueSizeToSend(1000).setCrashProcessorClass(DumpingCrashProcessor.class)); + + ConfigurationProvider provider = provider(); + Assert.assertEquals(ModuleConfiguration.NO_LIMIT, provider.getMaxKeyLength()); + Assert.assertEquals(ModuleConfiguration.NO_LIMIT, provider.getMaxValueSize()); + Assert.assertEquals(ModuleConfiguration.NO_LIMIT, provider.getMaxSegmentationValues()); + Assert.assertEquals(ModuleConfiguration.NO_LIMIT, provider.getMaxStackTraceLinesPerThread()); + Assert.assertEquals(ModuleConfiguration.NO_LIMIT, provider.getMaxStackTraceLineLength()); + Assert.assertEquals(100, provider.getMaxBreadcrumbCount()); + + assertNothingIsCut(); + } + + /** + * Without any SDK behavior settings, the settings requests being disabled as for an upgrading app + * that never received any, nothing any feature sends is cut, however long or wide. + *

+ * Verifies the same as {@link #assertNothingIsCut()}. + */ + @Test + public void withoutSettings_nothingIsCut() { + Countly.instance().init(TestUtils.getBaseConfig().setLogListener(this::keepWarning) + .enableFeatures(Config.Feature.Events, Config.Feature.Views, Config.Feature.CrashReporting, Config.Feature.Feedback) + .setEventQueueSizeToSend(1000).setCrashProcessorClass(DumpingCrashProcessor.class)); + + assertNothingIsCut(); + } + + // endregion + // region helpers + + /** + * Records a 200 character event key with 150 segments of 200 character keys and 300 character + * values as an event, a timed event and a view with its end event, reports a feedback widget + * result with a 300 character comment, sets 150 such custom user properties with a 300 character + * name and a modification, and records a crash with that segmentation, a 300 character message + * and breadcrumb and a crash processor dump of 40 lines per thread. Asserts that every key, value, + * entry and stack trace line is sent whole and that no limit warning was logged. + */ + private void assertNothingIsCut() { + String longKey = repeat("key_", 50); + String longValue = repeat("value_", 50); + Map wide = new HashMap<>(); + for (int i = 0; i < 150; i++) { + wide.put(longKey + i, longValue + i); + } + + Countly.instance().events().recordEvent(longKey, wide); + Countly.instance().events().startEvent(longKey + "timed"); + Countly.instance().events().endEvent(longKey + "timed", wide, 1, null); + String viewId = Countly.instance().views().startView(longKey, wide); + Countly.instance().views().stopViewWithID(viewId, wide); + CountlyFeedbackWidget widget = new CountlyFeedbackWidget(); + widget.widgetId = "rating_widget_identifier"; + widget.type = FeedbackWidgetType.rating; + widget.name = "rating"; + widget.tags = new String[0]; + Countly.instance().feedback().reportFeedbackWidgetManually(widget, null, TestUtils.map("rating", 5, "comment", longValue)); + + List queued = TestUtils.getCurrentEQ(); + Assert.assertEquals(keysOf(queued).toString(), 5, queued.size()); + assertEvent(queued.get(0), longKey, wide); + assertEvent(queued.get(1), longKey + "timed", wide); + Map viewStart = new HashMap<>(queued.get(2).segmentation); + Assert.assertEquals(longKey, viewStart.remove(ModuleViews.KEY_NAME)); + Assert.assertEquals("1", viewStart.remove(ModuleViews.KEY_VISIT)); + Assert.assertEquals("1", viewStart.remove(ModuleViews.KEY_START)); + Assert.assertNotNull(viewStart.remove(ModuleViews.KEY_SEGMENT)); + Assert.assertEquals(wide, viewStart); + Map viewEnd = new HashMap<>(queued.get(3).segmentation); + Assert.assertEquals(longKey, viewEnd.remove(ModuleViews.KEY_NAME)); + Assert.assertNotNull(viewEnd.remove(ModuleViews.KEY_SEGMENT)); + Assert.assertEquals(wide, viewEnd); + Assert.assertEquals(longValue, queued.get(4).segmentation.get("comment")); + + Map properties = new HashMap<>(wide); + properties.put(PredefinedUserPropertyKeys.NAME, longValue); + Countly.instance().userProfile().setProperties(properties); + Countly.instance().userProfile().push(longKey + "list", longValue); + Countly.instance().userProfile().save(); + TestUtils.letTheClockCatchUp(); + + JSONObject details = null; + for (Map request : TestUtils.getCurrentRQ()) { + if (request.containsKey("user_details")) { + details = new JSONObject(request.get("user_details")); + } + } + Assert.assertNotNull(details); + Assert.assertEquals(longValue, details.getString(PredefinedUserPropertyKeys.NAME)); + JSONObject custom = details.getJSONObject(ModuleUserProfile.CUSTOM_KEY); + Assert.assertEquals(151, custom.length()); + for (Map.Entry entry : wide.entrySet()) { + Assert.assertEquals(entry.getValue(), custom.getString(entry.getKey())); + } + Assert.assertEquals(longValue, custom.getJSONObject(longKey + "list").getString("$push")); + + Countly.instance().crashes().addCrashBreadcrumb(longValue); + Exception exception = new Exception(longValue); + Countly.instance().crashes().recordHandledException(exception, wide); + TestUtils.letTheClockCatchUp(); + DumpingCrashProcessor.replaceWithDump = true; + DumpingCrashProcessor.framesPerThread = 40; + Countly.instance().crashes().recordHandledException(new Exception("dumped")); + TestUtils.letTheClockCatchUp(); + + List crashes = crashRequests(); + Assert.assertEquals(2, crashes.size()); + Assert.assertEquals(stackTraceOf(exception), crashes.get(0).getString("_error")); + Assert.assertEquals(longValue, crashes.get(0).getString("_logs")); + JSONObject segments = crashes.get(0).getJSONObject("_custom"); + Assert.assertEquals(wide.size(), segments.length()); + for (Map.Entry entry : wide.entrySet()) { + Assert.assertEquals(entry.getValue(), segments.getString(entry.getKey())); + } + String dump = crashes.get(1).getString("_error"); + Assert.assertEquals(80, dump.split("\tat ly.count.Example.method", -1).length - 1); + Assert.assertTrue(dump.contains("Thread [worker-thread]:\n")); + Assert.assertEquals(3, crashes.get(1).getJSONObject("_custom").length()); + Assert.assertEquals("processor_breadcrumb", crashes.get(1).getString("_logs")); + + Assert.assertEquals(0, warningsContaining("limit of [")); + Assert.assertEquals(0, warningsContaining("reserved key")); + } + + /** + * The limits most scenarios run with: keys of 5 characters, values of 6, 2 segmentation entries + * and 3 stack trace lines per thread of 20 characters each, with networking off. + * + * @return the settings + */ + private static ServerConfigBuilder smallLimits() { + return new ServerConfigBuilder().keyLengthLimit(5).valueSizeLimit(6).segmentationValuesLimit(2) + .traceLinesLimit(3).traceLengthLimit(20).networking(false); + } + + /** + * Initializes the SDK with {@link #server} answering its settings requests. + * + * @param config the configuration + */ + private void init(Config config) { + InternalConfig internalConfig = new InternalConfig(config); + internalConfig.immediateRequestGenerator = server; + Countly.instance().init(internalConfig); + } + + /** + * Answers the next settings request with the given payload and makes the SDK fetch, as the + * refresh timer does. + * + * @param builder the payload + */ + private void push(ServerConfigBuilder builder) { + server.respondWith(builder); + SDKCore.instance.module(ModuleConfiguration.class).fetchConfigFromServer(SDKCore.instance.config); + } + + /** + * The settings in effect in the running SDK. + * + * @return the provider + */ + private static ConfigurationProvider provider() { + return SDKCore.instance.config.getConfigurationProvider(); + } + + /** + * The settings test configuration with a listener that keeps every warning. + * + * @return the configuration + */ + private Config configWithWarnings() { + return TestUtils.getConfigSdkBehaviorSettings().setLogListener(this::keepWarning); + } + + /** + * A log listener that keeps every warning. + * + * @param message the log line + * @param level its level + */ + private void keepWarning(String message, Config.LoggingLevel level) { + if (level == Config.LoggingLevel.WARN) { + warnings.add(message); + } + } + + /** + * How many warnings so far contain a text. + * + * @param text the text + * @return the number of warnings + */ + private int warningsContaining(String text) { + int count = 0; + for (String warning : warnings) { + if (warning.contains(text)) { + count++; + } + } + return count; + } + + /** + * Every event of every stored request, in queue order. + * + * @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; + for (int i = 0; i < requestCount; i++) { + events.addAll(TestUtils.readEventsFromRequest(i, TestUtils.DEVICE_ID)); + } + return events; + } + + /** + * The keys of events, in order. + * + * @param events the events + * @return the keys + */ + private static List keysOf(List events) { + List keys = new ArrayList<>(); + for (EventImpl event : events) { + keys.add(event.key); + } + return keys; + } + + /** + * Asserts the key and the whole segmentation of an event. + * + * @param event the event + * @param key the expected key + * @param segmentation the expected segmentation + */ + private static void assertEvent(EventImpl event, String key, Map segmentation) { + Assert.assertEquals(key, event.key); + Assert.assertEquals(segmentation, new HashMap<>(event.segmentation)); + } + + /** + * The {@code user_details} object of a stored request. + * + * @param requestIndex the index of the request in the queue + * @return the user details + */ + private static JSONObject userDetails(int requestIndex) { + Map[] requests = TestUtils.getCurrentRQ(); + Assert.assertTrue("no request at index " + requestIndex + " in " + Arrays.toString(requests), requests.length > requestIndex); + return new JSONObject(requests[requestIndex].get("user_details")); + } + + /** + * The crash of every stored crash request, in queue order. + * + * @return the crashes + */ + private static List crashRequests() { + List crashes = new ArrayList<>(); + for (Map request : TestUtils.getCurrentRQ()) { + if (request.containsKey("crash")) { + crashes.add(new JSONObject(request.get("crash"))); + } + } + return crashes; + } + + /** + * The stack trace of a throwable as the SDK prints it. + * + * @param throwable the throwable + * @return the stack trace + */ + private static String stackTraceOf(Throwable throwable) { + StringWriter writer = new StringWriter(); + throwable.printStackTrace(new PrintWriter(writer)); + return writer.toString(); + } + + /** + * Cuts every line of a text to a length, keeping its line breaks. + * + * @param text the text + * @param maxLength the length + * @return the cut text + */ + private static String truncateLines(String text, int maxLength) { + StringBuilder truncated = new StringBuilder(); + String[] lines = text.split("\n", -1); + for (int i = 0; i < lines.length; i++) { + String line = lines[i]; + String carriageReturn = ""; + if (line.endsWith("\r")) { + line = line.substring(0, line.length() - 1); + carriageReturn = "\r"; + } + truncated.append(line.length() > maxLength ? line.substring(0, maxLength) : line).append(carriageReturn); + if (i < lines.length - 1) { + truncated.append('\n'); + } + } + return truncated.toString(); + } + + /** + * The number of line breaks of a text. + * + * @param text the text + * @return the number of lines that end with a line break + */ + private static int lineCount(String text) { + return text.split("\n", -1).length - 1; + } + + /** + * A text repeated. + * + * @param text the text + * @param times how many times + * @return the repeated text + */ + private static String repeat(String text, int times) { + StringBuilder repeated = new StringBuilder(text.length() * times); + for (int i = 0; i < times; i++) { + repeated.append(text); + } + return repeated.toString(); + } + + /** + * A crash processor that, when asked to, replaces the stack trace with a dump of a main and a + * worker thread and sets its own segments and breadcrumbs, as a customer's processor may. + */ + public static class DumpingCrashProcessor implements CrashProcessor { + static volatile boolean replaceWithDump = false; + static volatile int framesPerThread = 5; + private static final Thread MAIN_THREAD = new Thread(() -> { + }, "main"); + private static final Thread WORKER_THREAD = new Thread(() -> { + }, "worker-thread"); + + /** + * Replaces the stack trace, the segments and the breadcrumbs when asked to. + * + * @param crash the crash + * @return the same crash, never vetoed + */ + @Override + public Crash process(Crash crash) { + if (replaceWithDump) { + Map traces = new LinkedHashMap<>(); + traces.put(MAIN_THREAD, frames(framesPerThread)); + traces.put(WORKER_THREAD, frames(framesPerThread)); + crash.addTraces(MAIN_THREAD, traces); + Map segments = new HashMap<>(); + segments.put("processor_segment", "processor_value"); + segments.put("another_segment", "another_value"); + segments.put("zzz", "z"); + crash.setSegments(segments); + crash.setLogs(new String[] { "processor_breadcrumb" }); + } + return crash; + } + + /** + * Stack trace lines of a made up class. + * + * @param count how many + * @return the lines + */ + private static StackTraceElement[] frames(int count) { + StackTraceElement[] frames = new StackTraceElement[count]; + for (int i = 0; i < count; i++) { + frames[i] = new StackTraceElement("ly.count.Example", "method" + i, "Example.java", i + 1); + } + return frames; + } + } + + // endregion +} 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 new file mode 100644 index 000000000..92db25d25 --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationNetworkTests.java @@ -0,0 +1,946 @@ +package ly.count.sdk.java.internal; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.Set; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.BooleanSupplier; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import static ly.count.sdk.java.internal.ServerConfigBuilder.names; + +/** + * The network resilience settings of the SDK behavior settings, observed through the public API: the + * backoff mechanism, {@code bom}, {@code bom_at}, {@code bom_rqp}, {@code bom_ra} and {@code bom_d}, + * and the request drop age, {@code dort}. + *

+ * Settings requests go through a {@link ModuleConfigurationTests.ServerConfigResponder}, which answers + * on the calling thread. Queued requests go through the real networking stack to a local HTTP server + * that can hold each answer back and records when every request arrived and when its answer started, + * so the gap a backoff leaves between two requests can be measured. Backoff settings are set to + * seconds, never left at their defaults, and no wait relies on the 60 second SDK timer. + */ +@RunWith(JUnit4.class) +public class ModuleConfigurationNetworkTests { + + private static final long SLOW_ANSWER_MS = 1_200; + //longer than the wait budget, so a backoff that should not happen fails the wait instead of slowing it + private static final int BACKOFF_LONGER_THAN_THE_BUDGET_SECONDS = 60; + private static final long WAIT_BUDGET_MS = 30_000; + private static final long POLL_MS = 50; + private static final long TIMER_SLACK_MS = 50; + private static final long LATE_RESUME_MS = 5_000; + private static final long MINUTE_MS = 60L * 1000L; + private static final long HOUR_MS = 60L * MINUTE_MS; + + private static final String BACKOFF_STARTED = "holding the request queue back for ["; + private static final String BACKOFF_ENDED = "the backoff is over"; + private static final String NOT_BACKING_OFF = "not backing off"; + private static final String DROPPED_UNSENT = "dropping it without sending"; + private static final String CONTENT_ENDPOINT = "/o/sdk/content?"; + private static final String NO_CONTENT_RESPONSE = "{\"jsonArray\":[{\"result\":\"No content block found!\"}]}"; + + private SettingsAndContentServer server; + private QueueServer queueServer; + private final List logs = new CopyOnWriteArrayList<>(); + + /** + * Starts every test from empty storage, without a test module and with fresh fakes. + */ + @Before + public void beforeTest() { + TestUtils.createCleanTestState(); + SDKCore.testDummyModule = null; + server = new SettingsAndContentServer(); + queueServer = null; + logs.clear(); + } + + /** + * Stops the SDK, clearing its data, and the local HTTP server when one was started. + */ + @After + public void afterTest() { + Countly.instance().halt(); + if (queueServer != null) { + queueServer.stop(); + } + } + + // region scenarios + + /** + * A request the server answers slowly while few requests are queued holds the queue back for + * {@code bom_d}, then the queue drains on its own. + *

+ * Verifies against a local server that after an answer slower than {@code bom_at}, with two + * requests left, the next request arrives only once {@code bom_d} has passed since the server + * started answering; that meanwhile a newly recorded request and nudges of the send loop send + * nothing and the queue stays on disk as it was; that the backoff ends without any nudge; and + * that the fast answers after it hold nothing back. + */ + @Test + public void backoff_slowAnswerWithFewRequestsQueued_holdsTheQueueBackForTheDuration_thenItDrainsOnItsOwn() throws Exception { + startQueueServer(); + queueServer.holdTheNextAnswers(SLOW_ANSWER_MS); + server.settings.respondWith(new ServerConfigBuilder().backoffAcceptedTimeout(1).backoffDuration(3)); + init(networkedConfig()); + + recordEvents("first", "second", "third"); + awaitLogs(BACKOFF_STARTED, 1); + Assert.assertEquals(1, logsContaining("and [2] requests remain queued, " + BACKOFF_STARTED + "3] seconds")); + Assert.assertEquals(1, queueServer.received.size()); + + Countly.instance().events().recordEvent("during_backoff"); + TestUtils.letTheClockCatchUp(); + Map[] held = TestUtils.getCurrentRQ(); + Assert.assertEquals(3, held.length); + Assert.assertEquals("[\"second\"]", eventKeys(held[0]).toString()); + Assert.assertEquals("[\"third\"]", eventKeys(held[1]).toString()); + Assert.assertEquals("[\"during_backoff\"]", eventKeys(held[2]).toString()); + + nudgeUntil(queueServer.received.get(0).answeredAtNs + 2_000L * 1_000_000L); + Assert.assertEquals(1, queueServer.received.size()); + Assert.assertEquals(3, queuedRequestCount()); + Assert.assertEquals(0, logsContaining(BACKOFF_ENDED)); + + Assert.assertTrue("the queue never drained after the backoff, logs: " + logs, waitFor(() -> queueServer.received.size() == 4 && queuedRequestCount() == 0)); + long gapMs = gapBeforeRequestMs(1); + Assert.assertTrue("the next request came [" + gapMs + "] ms after the slow answer", gapMs >= 3_000 - TIMER_SLACK_MS); + Assert.assertTrue("the queue resumed [" + gapMs + "] ms after the slow answer", gapMs < 3_000 + LATE_RESUME_MS); + Assert.assertEquals(Arrays.asList("first", "second", "third", "during_backoff"), receivedEventKeys()); + Assert.assertEquals(1, logsContaining(BACKOFF_STARTED)); + Assert.assertEquals(1, logsContaining(BACKOFF_ENDED)); + Assert.assertEquals(0, logsContaining(NOT_BACKING_OFF)); + } + + /** + * The backoff needs a slow answer and the requests still queued within {@code bom_rqp} of the + * request queue size. + *

+ * Verifies against a local server, with {@code rqs} 4 and {@code bom_rqp} 0.25, so at most one + * request left, that a slow answer with two requests left holds nothing back, that the next slow + * answer, with one request left, holds the queue back for {@code bom_d}, and that the fast answer + * to the last request holds nothing back. + */ + @Test + public void backoff_needsTheQueueWithinItsShareOfTheQueueSize_andASlowAnswer() throws Exception { + startQueueServer(); + queueServer.holdTheNextAnswers(SLOW_ANSWER_MS, SLOW_ANSWER_MS); + server.settings.respondWith(new ServerConfigBuilder().requestQueueSize(4).backoffRequestQueuePercentage(0.25) + .backoffAcceptedTimeout(1).backoffDuration(2)); + init(networkedConfig()); + + recordEvents("a", "b", "c"); + Assert.assertTrue("the queue never drained, logs: " + logs, waitFor(() -> queueServer.received.size() == 3 && queuedRequestCount() == 0)); + + Assert.assertEquals(Arrays.asList("a", "b", "c"), receivedEventKeys()); + Assert.assertEquals(1, logsContaining("but [2] requests remain queued, more than [1.0], " + NOT_BACKING_OFF)); + Assert.assertEquals(1, logsContaining("and [1] requests remain queued, " + BACKOFF_STARTED + "2] seconds")); + Assert.assertEquals(1, logsContaining(BACKOFF_STARTED)); + Assert.assertEquals(1, logsContaining(NOT_BACKING_OFF)); + long gapAfterFirstMs = gapBeforeRequestMs(1); + long gapAfterSecondMs = gapBeforeRequestMs(2); + Assert.assertTrue("the second request waited [" + gapAfterFirstMs + "] ms", gapAfterFirstMs < 2_000); + Assert.assertTrue("the third request waited only [" + gapAfterSecondMs + "] ms", gapAfterSecondMs >= 2_000 - TIMER_SLACK_MS); + } + + /** + * The backoff never holds the queue back after a request older than {@code bom_ra}, nor while the + * server turns it off with {@code bom}. + *

+ * Verifies against a local server, with a {@code bom_d} longer than the wait budget so that a + * backoff fails the wait, that two stored requests recorded two hours ago are both sent although + * each is answered slowly, each slow answer logged as coming too late to back off; and, after a + * restart with {@code bom} false from the server, that two new requests answered slowly are sent + * one after the other without any backoff. + */ + @Test + public void backoff_neverAfterARequestOlderThanTheRequestAge_norWhileTheServerTurnsItOff() throws Exception { + startQueueServer(); + long twoHoursAgo = System.currentTimeMillis() - 2 * HOUR_MS; + storeRequest(twoHoursAgo, "old_1", twoHoursAgo); + storeRequest(twoHoursAgo + 1, "old_2", twoHoursAgo + 1); + queueServer.holdTheNextAnswers(SLOW_ANSWER_MS, SLOW_ANSWER_MS); + server.settings.respondWith(new ServerConfigBuilder().backoffAcceptedTimeout(1).backoffRequestAge(1) + .backoffDuration(BACKOFF_LONGER_THAN_THE_BUDGET_SECONDS)); + init(networkedConfig()); + + Assert.assertTrue("the old requests never drained, logs: " + logs, waitFor(() -> queueServer.received.size() == 2 && queuedRequestCount() == 0)); + Assert.assertEquals(Arrays.asList("old_1", "old_2"), receivedParams("marker")); + awaitLogs("but the request is older than [1] hours, " + NOT_BACKING_OFF, 2); + Assert.assertEquals(0, logsContaining(BACKOFF_STARTED)); + Countly.instance().halt(); + + queueServer.received.clear(); + logs.clear(); + queueServer.holdTheNextAnswers(SLOW_ANSWER_MS, SLOW_ANSWER_MS); + server.settings.respondWith(new ServerConfigBuilder().backoffMechanism(false).backoffAcceptedTimeout(1) + .backoffDuration(BACKOFF_LONGER_THAN_THE_BUDGET_SECONDS)); + init(networkedConfig()); + Assert.assertFalse(provider().getBOMEnabled()); + + recordEvents("x", "y"); + Assert.assertTrue("the new requests never drained, logs: " + logs, waitFor(() -> queueServer.received.size() == 2 && queuedRequestCount() == 0)); + Assert.assertEquals(Arrays.asList("x", "y"), receivedEventKeys()); + Assert.assertEquals(0, logsContaining(BACKOFF_STARTED)); + Assert.assertEquals(0, logsContaining(NOT_BACKING_OFF)); + } + + /** + * {@link Config#disableBackoffMechanism()} keeps the backoff off while the settings server stays + * silent, and a {@code bom} true from the server turns it back on. + *

+ * Verifies against a local server, with the settings server never answering and the provided + * settings setting {@code bom_at} and a {@code bom_d} longer than the wait budget, that slow + * answers hold nothing back; then that once a response sets {@code bom} true with a short + * {@code bom_d}, the next slow answer holds the queue back for that long. + */ + @Test + public void backoff_offByTheDeveloper_staysOffWithASilentServer_andTheServerTurnsItBackOn() throws Exception { + startQueueServer(); + queueServer.holdTheNextAnswers(SLOW_ANSWER_MS, SLOW_ANSWER_MS, SLOW_ANSWER_MS); + server.settings.pending(); + init(networkedConfig().disableBackoffMechanism().setSdkBehaviorSettings(new ServerConfigBuilder() + .backoffAcceptedTimeout(1).backoffDuration(BACKOFF_LONGER_THAN_THE_BUDGET_SECONDS).build())); + Assert.assertFalse(provider().getBOMEnabled()); + Assert.assertEquals(1, provider().getBOMAcceptedTimeoutSeconds()); + + recordEvents("a", "b"); + Assert.assertTrue("the queue never drained, logs: " + logs, waitFor(() -> queueServer.received.size() == 2 && queuedRequestCount() == 0)); + Assert.assertEquals(0, logsContaining(BACKOFF_STARTED)); + + push(new ServerConfigBuilder().backoffMechanism(true).backoffAcceptedTimeout(1).backoffDuration(2)); + Assert.assertTrue(provider().getBOMEnabled()); + Assert.assertEquals(2, provider().getBOMDuration()); + + recordEvents("c", "d"); + Assert.assertTrue("the queue never drained after the backoff, logs: " + logs, waitFor(() -> queueServer.received.size() == 4 && queuedRequestCount() == 0)); + Assert.assertEquals(Arrays.asList("a", "b", "c", "d"), receivedEventKeys()); + Assert.assertEquals(1, logsContaining("and [1] requests remain queued, " + BACKOFF_STARTED + "2] seconds")); + long gapMs = gapBeforeRequestMs(3); + Assert.assertTrue("the last request waited only [" + gapMs + "] ms", gapMs >= 2_000 - TIMER_SLACK_MS); + } + + /** + * Backend mode never holds its request queue back and never drops a request for its age, whatever + * the resolved values say. + *

+ * Verifies against a local server, with the settings inert in backend mode and the resolved + * backoff and drop age values forced to ones that would back off and drop, that three requests, + * the first two answered slowly and the first recorded three hours ago, are all sent in order with + * their own timestamps, that nothing backs off or is dropped, and that no settings request is made. + */ + @Test + public void backendMode_neverHoldsTheQueueBack_norDropsARequestForItsAge() throws Exception { + startQueueServer(); + queueServer.holdTheNextAnswers(SLOW_ANSWER_MS, SLOW_ANSWER_MS); + init(networkedConfig().enableBackendMode()); + ModuleConfiguration module = SDKCore.instance.module(ModuleConfiguration.class); + module.currentVBOMAcceptedTimeoutSeconds = 1; + module.currentVBOMDuration = BACKOFF_LONGER_THAN_THE_BUDGET_SECONDS; + module.currentVDropAgeHours = 1; + Assert.assertTrue(provider().getBOMEnabled()); + + long threeHoursAgo = System.currentTimeMillis() - 3 * HOUR_MS; + Countly.instance().backendM().sessionBegin("device_old", null, null, threeHoursAgo); + Countly.instance().backendM().sessionBegin("device_fresh", null, null, null); + Countly.instance().backendM().sessionBegin("device_last", null, null, null); + + Assert.assertTrue("the memory queue never drained, logs: " + logs, waitFor(() -> queueServer.received.size() == 3 && memoryQueueSize() == 0)); + Assert.assertEquals(Arrays.asList("device_old", "device_fresh", "device_last"), receivedParams("device_id")); + Assert.assertEquals(String.valueOf(threeHoursAgo), queueServer.received.get(0).params.get("timestamp")); + Assert.assertEquals(0, logsContaining(BACKOFF_STARTED)); + Assert.assertEquals(0, logsContaining(NOT_BACKING_OFF)); + Assert.assertEquals(0, logsContaining(DROPPED_UNSENT)); + Assert.assertTrue(server.settings.requests.isEmpty()); + } + + /** + * Stopping the SDK while the queue is held back ends the backoff for good. + *

+ * Verifies against a local server that once the SDK stopped during a backoff, nothing is sent + * after the backoff would have ended, the held request stays on disk, the backoff thread is gone + * and the backoff never reports its end, and that the next init sends the held request. + */ + @Test + public void backoff_stopWhileHeldBack_sendsNothingAfterwards_leavesNoThread_andTheNextInitSendsTheHeldRequest() throws Exception { + startQueueServer(); + queueServer.holdTheNextAnswers(SLOW_ANSWER_MS); + server.settings.respondWith(new ServerConfigBuilder().backoffAcceptedTimeout(1).backoffDuration(2)); + Set threadsBefore = backoffThreads(); + init(networkedConfig()); + + recordEvents("first", "held"); + awaitLogs(BACKOFF_STARTED, 1); + Set threads = backoffThreads(); + threads.removeAll(threadsBefore); + Assert.assertEquals(1, threads.size()); + Assert.assertEquals(1, queuedRequestCount()); + + Countly.instance().stop(); + Assert.assertTrue("the backoff thread outlived stop()", waitFor(() -> noneAlive(threads))); + sleepUntil(queueServer.received.get(0).answeredAtNs + 3_500L * 1_000_000L); + Assert.assertEquals(1, queueServer.received.size()); + Assert.assertEquals(1, queuedRequestCount()); + Assert.assertEquals(0, logsContaining(BACKOFF_ENDED)); + + init(networkedConfig()); + Assert.assertTrue("the held request was never sent, logs: " + logs, waitFor(() -> queueServer.received.size() == 2 && queuedRequestCount() == 0)); + Assert.assertEquals(Arrays.asList("first", "held"), receivedEventKeys()); + Assert.assertEquals(1, logsContaining(BACKOFF_STARTED)); + } + + /** + * {@code dort} drops the stored requests older than it without sending them and sends the others, + * and {@code dort} 0 drops nothing. + *

+ * Verifies against a local server that the age of a request comes from its {@code timestamp} + * parameter, so an old storage ID with a fresh timestamp is sent and a fresh storage ID with an + * old timestamp is dropped, and from its storage ID when it has no timestamp; that each drop is + * logged with the request it dropped; and that with {@code dort} 0 the same old requests are all + * sent in order. + */ + @Test + public void requestDropAge_dropsTheStoredRequestsOlderThanIt_unsent_andZeroDropsNothing() throws Exception { + startQueueServer(); + long now = System.currentTimeMillis(); + long threeHoursAgo = now - 3 * HOUR_MS; + storeRequest(threeHoursAgo, "old_timestamp", threeHoursAgo); + storeRequest(threeHoursAgo + 1, "fresh_timestamp_old_id", now); + storeRequest(threeHoursAgo + 2, "no_timestamp_old_id", null); + storeRequest(now - 2 * MINUTE_MS, "old_timestamp_fresh_id", now - 2 * HOUR_MS); + storeRequest(now - MINUTE_MS, "within_the_drop_age", now - 30 * MINUTE_MS); + server.settings.failing(); + init(networkedConfig().setSdkBehaviorSettings(new ServerConfigBuilder().dropOldRequestTime(1).build())); + Assert.assertEquals(1, provider().getRequestDropAgeHours()); + + Assert.assertTrue("the queue never drained, logs: " + logs, waitNudging(() -> queuedRequestCount() == 0 && queueServer.received.size() == 2)); + Assert.assertEquals(Arrays.asList("fresh_timestamp_old_id", "within_the_drop_age"), receivedParams("marker")); + Assert.assertEquals(3, logsContaining(DROPPED_UNSENT)); + for (long droppedId : new long[] { threeHoursAgo, threeHoursAgo + 2, now - 2 * MINUTE_MS }) { + Assert.assertEquals(1, logsContaining("request [" + droppedId + "] is older than the request drop age of [1] hours")); + } + + TestUtils.createCleanTestState(); + queueServer.received.clear(); + logs.clear(); + storeRequest(threeHoursAgo, "old_timestamp", threeHoursAgo); + storeRequest(threeHoursAgo + 2, "no_timestamp_old_id", null); + storeRequest(now - 2 * MINUTE_MS, "old_timestamp_fresh_id", now - 2 * HOUR_MS); + init(networkedConfig().setSdkBehaviorSettings(new ServerConfigBuilder().dropOldRequestTime(0).build())); + Assert.assertEquals(0, provider().getRequestDropAgeHours()); + + Assert.assertTrue("the queue never drained, logs: " + logs, waitNudging(() -> queuedRequestCount() == 0 && queueServer.received.size() == 3)); + Assert.assertEquals(Arrays.asList("old_timestamp", "no_timestamp_old_id", "old_timestamp_fresh_id"), receivedParams("marker")); + Assert.assertEquals(0, logsContaining(DROPPED_UNSENT)); + } + + // endregion + // region helpers + + /** + * Stands in for the settings and the content endpoints of the server. Settings requests go to a + * {@link ModuleConfigurationTests.ServerConfigResponder}; content fetches are recorded and + * answered on the calling thread with no content, unless networking is off. + */ + private static final class SettingsAndContentServer implements ImmediateRequestGenerator { + final ModuleConfigurationTests.ServerConfigResponder settings = new ModuleConfigurationTests.ServerConfigResponder(); + final List contentFetches = new CopyOnWriteArrayList<>(); + + /** + * A request maker that routes by endpoint. + * + * @return the request maker + */ + @Override + public ImmediateRequestI createImmediateRequestMaker() { + ImmediateRequestI settingsRequestMaker = settings.createImmediateRequestMaker(); + return (requestData, customEndpoint, transport, requestShouldBeDelayed, networkingIsEnabled, callback, log) -> { + if (!CONTENT_ENDPOINT.equals(customEndpoint)) { + settingsRequestMaker.doWork(requestData, customEndpoint, transport, requestShouldBeDelayed, networkingIsEnabled, callback, log); + return; + } + if (!networkingIsEnabled) { + callback.callback(null); + return; + } + contentFetches.add(requestData); + callback.callback(new JSONObject(NO_CONTENT_RESPONSE)); + }; + } + } + + /** + * One request as the local server saw it. + */ + private static final class Received { + final Map params; + final long receivedAtNs; + volatile long answeredAtNs; + + /** + * Records a request as it arrives. + * + * @param params the decoded request parameters + * @param receivedAtNs {@link System#nanoTime()} when it arrived + */ + Received(Map params, long receivedAtNs) { + this.params = params; + this.receivedAtNs = receivedAtNs; + } + } + + /** + * A local HTTP server standing in for the request queue endpoint: it accepts every request, holds + * back the answers a test asks it to, and records each request with the moment it arrived and the + * moment its answer started. One handler thread, so requests are recorded in the order they came. + */ + private static final class QueueServer { + final HttpServer http; + final List received = new CopyOnWriteArrayList<>(); + private final ExecutorService executor = Executors.newSingleThreadExecutor(); + private final Queue answerDelaysMs = new ConcurrentLinkedQueue<>(); + + /** + * Starts the server on a free loopback port. + * + * @throws IOException when the server cannot start + */ + QueueServer() throws IOException { + http = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + http.createContext("/", this::handle); + http.setExecutor(executor); + http.start(); + } + + /** + * Holds back the answers to the next requests, one delay per request in arrival order. Any + * request after those is answered right away. + * + * @param delaysMs how long to hold each answer back, in milliseconds + */ + void holdTheNextAnswers(long... delaysMs) { + for (long delayMs : delaysMs) { + answerDelaysMs.add(delayMs); + } + } + + /** + * Records a request, holds its answer back when asked to, then accepts it. + * + * @param exchange the request and its response + * @throws IOException when the response cannot be written + */ + private void handle(HttpExchange exchange) throws IOException { + String query = exchange.getRequestURI().getRawQuery(); + String body = new String(readAll(exchange.getRequestBody()), StandardCharsets.UTF_8); + Received request = new Received(parseParams(query != null && !query.isEmpty() ? query : body), System.nanoTime()); + received.add(request); + + Long delayMs = answerDelaysMs.poll(); + if (delayMs != null && delayMs > 0) { + try { + Thread.sleep(delayMs); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + byte[] response = "{\"result\":\"Success\"}".getBytes(StandardCharsets.UTF_8); + request.answeredAtNs = System.nanoTime(); + exchange.sendResponseHeaders(200, response.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(response); + } + } + + /** + * The port the server listens on. + * + * @return the port + */ + int port() { + return http.getAddress().getPort(); + } + + /** + * Stops the server and its handler thread, even while it holds an answer back. + */ + void stop() { + http.stop(0); + executor.shutdownNow(); + } + } + + /** + * A display that shows nothing, so the content zone can be entered. + */ + private static final class FakeDisplay implements ContentDisplay { + /** + * A landscape screen. + * + * @return the screen + */ + @Override + public ContentScreen getScreen() { + return new ContentScreen(1600, 900); + } + + /** + * Shows nothing. + * + * @param content the content to show + * @param onClosed called when the content closes + */ + @Override + public void present(ContentData content, ContentCloseCallback onClosed) { + } + } + + /** + * Starts {@link #queueServer}. + * + * @throws IOException when the server cannot start + */ + private void startQueueServer() throws IOException { + queueServer = new QueueServer(); + } + + /** + * Initializes the SDK with {@link #server} answering its settings requests and content fetches. + * + * @param config the configuration + */ + private void init(Config config) { + InternalConfig internalConfig = new InternalConfig(config); + internalConfig.immediateRequestGenerator = server; + Countly.instance().init(internalConfig); + } + + /** + * Answers the next settings request with the given payload and makes the SDK fetch, as the + * refresh timer does. + * + * @param builder the payload + */ + private void push(ServerConfigBuilder builder) { + server.settings.respondWith(builder); + SDKCore.instance.module(ModuleConfiguration.class).fetchConfigFromServer(SDKCore.instance.config); + } + + /** + * The settings in effect in the running SDK. + * + * @return the provider + */ + private static ConfigurationProvider provider() { + return SDKCore.instance.config.getConfigurationProvider(); + } + + /** + * A configuration pointing at {@link #queueServer}, with events sent one per request, no request + * cooldowns, and every log line kept. + * + * @return the configuration + */ + private Config networkedConfig() { + File directory = TestUtils.getTestSDirectory(); + TestUtils.checkSdkStorageRootDirectoryExist(directory); + return new Config("http://127.0.0.1:" + queueServer.port(), TestUtils.SERVER_APP_KEY, directory) + .setApplicationVersion(TestUtils.APPLICATION_VERSION) + .setCustomDeviceId(TestUtils.DEVICE_ID) + .enableFeatures(Config.Feature.Events) + .setEventQueueSizeToSend(1) + .setNetworkRequestCooldown(0) + .setNetworkImportantRequestCooldown(0) + .setLogListener((message, level) -> logs.add(message)); + } + + /** + * Records events one after another, letting the clock move on after each, so every request gets + * a storage ID of its own. + * + * @param keys the event keys + */ + private static void recordEvents(String... keys) { + for (String key : keys) { + Countly.instance().events().recordEvent(key); + TestUtils.letTheClockCatchUp(); + } + } + + /** + * Stores a request file before init, as an earlier run would have left it. + * + * @param id the storage ID, which names the file + * @param marker a parameter that tells the requests apart on the server + * @param timestamp the {@code timestamp} parameter, {@code null} for none + * @throws IOException when the file cannot be written + */ + private static void storeRequest(long id, String marker, Long timestamp) throws IOException { + Request request = new Request(id); + request.params = new Params("app_key", TestUtils.SERVER_APP_KEY, "device_id", TestUtils.DEVICE_ID, "marker", marker); + if (timestamp != null) { + request.params.add("timestamp", timestamp); + } + File directory = TestUtils.getTestSDirectory(); + TestUtils.checkSdkStorageRootDirectoryExist(directory); + Files.write(new File(directory, "[CLY]_request_" + id).toPath(), request.store(new Log(Config.LoggingLevel.OFF, null))); + } + + /** + * Moves the {@code timestamp} parameter of every stored request back by the given time, as if it + * had been recorded that much earlier, keeping its storage ID. + * + * @param byMs how far back, in milliseconds + * @throws IOException when a file cannot be rewritten + */ + private static void ageStoredRequests(long byMs) throws IOException { + Pattern timestamp = Pattern.compile("(^|&)timestamp=(\\d+)"); + for (File file : requestFiles()) { + String content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + Matcher matcher = timestamp.matcher(content); + Assert.assertTrue("no timestamp in " + file.getName(), matcher.find()); + long aged = Long.parseLong(matcher.group(2)) - byMs; + String agedContent = content.substring(0, matcher.start(2)) + aged + content.substring(matcher.end(2)); + Files.write(file.toPath(), agedContent.getBytes(StandardCharsets.UTF_8)); + } + } + + /** + * The stored request files. + * + * @return the files, never {@code null} + */ + private static File[] requestFiles() { + File[] files = TestUtils.getTestSDirectory().listFiles((dir, name) -> name.startsWith("[CLY]_request_")); + return files == null ? new File[0] : files; + } + + /** + * Counts the stored requests without reading them, as the network loop can remove one while it + * is read. + * + * @return the number of stored requests + */ + private static int queuedRequestCount() { + return requestFiles().length; + } + + /** + * The storage IDs of the stored requests. + * + * @return the IDs + */ + private static Set storedRequestIds() { + Set ids = new HashSet<>(); + for (File file : requestFiles()) { + ids.add(Long.parseLong(file.getName().substring("[CLY]_request_".length()))); + } + return ids; + } + + /** + * How many requests the memory queue of backend mode holds. + * + * @return the number of requests + */ + private static int memoryQueueSize() { + SDKCore core = SDKCore.instance; + synchronized (core.lockBRQStorage) { + return core.requestQueueMemory.size(); + } + } + + /** + * The key of the event each request the server received carried, in the order they arrived. + * + * @return the event keys + */ + private List receivedEventKeys() { + List keys = new ArrayList<>(); + for (Received request : queueServer.received) { + JSONArray requestKeys = eventKeys(request.params); + for (int i = 0; i < requestKeys.length(); i++) { + keys.add(requestKeys.getString(i)); + } + } + return keys; + } + + /** + * One parameter of each request the server received, in the order they arrived. + * + * @param key the parameter + * @return its values + */ + private List receivedParams(String key) { + List values = new ArrayList<>(); + for (Received request : queueServer.received) { + values.add(request.params.get(key)); + } + return values; + } + + /** + * How long the server had to wait for a request after it started answering the one before it. + * + * @param index the position of the request, from 1 + * @return the gap in milliseconds + */ + private long gapBeforeRequestMs(int index) { + Received previous = queueServer.received.get(index - 1); + Received next = queueServer.received.get(index); + return (next.receivedAtNs - previous.answeredAtNs) / 1_000_000L; + } + + /** + * The keys of the events a request carries, in order. + * + * @param params the parameters of the request + * @return the keys as a JSON array, empty when the request carries no events + */ + private static JSONArray eventKeys(Map params) { + JSONArray keys = new JSONArray(); + String events = params.get("events"); + if (events == null) { + return keys; + } + JSONArray eventArray = new JSONArray(events); + for (int i = 0; i < eventArray.length(); i++) { + keys.put(eventArray.getJSONObject(i).getString("key")); + } + return keys; + } + + /** + * The live backoff threads. + * + * @return the threads + */ + private static Set backoffThreads() { + Set threads = new HashSet<>(); + for (Thread thread : Thread.getAllStackTraces().keySet()) { + if (DefaultNetworking.BACKOFF_THREAD_NAME.equals(thread.getName()) && thread.isAlive()) { + threads.add(thread); + } + } + return threads; + } + + /** + * Whether every given thread has ended. + * + * @param threads the threads + * @return {@code true} when none is alive + */ + private static boolean noneAlive(Set threads) { + for (Thread thread : threads) { + if (thread.isAlive()) { + return false; + } + } + return true; + } + + /** + * Holds the first tick of every zone timer an hour away, so the zone fetches only when a test + * ticks it by hand. + */ + private static void holdTheZoneTimer() { + contentModule().startedAtForTests(System.currentTimeMillis() + HOUR_MS); + } + + /** + * The content module of the running SDK. + * + * @return the module + */ + private static ModuleContent contentModule() { + return SDKCore.instance.module(ModuleContent.class); + } + + /** + * Ticks the zone once by hand and asserts that it fetched nothing, as no zone is active. + * + * @param fetchesSoFar the content fetches made so far + */ + private void assertZoneIsInactive(int fetchesSoFar) { + contentModule().onZoneTimerTick(); + Assert.assertEquals(fetchesSoFar, server.contentFetches.size()); + } + + /** + * Ticks the zone by hand until it fetches, which it does once a refresh entered it. + * + * @param expectedFetches the content fetches expected once it fetched + */ + private void awaitZoneFetch(int expectedFetches) throws InterruptedException { + boolean fetched = waitNudging(() -> { + contentModule().onZoneTimerTick(); + return server.contentFetches.size() >= expectedFetches; + }); + Assert.assertTrue("the content zone never fetched, logs: " + logs, fetched); + Assert.assertEquals(expectedFetches, server.contentFetches.size()); + } + + /** + * Waits until the log holds a number of lines containing a text. + * + * @param text the text + * @param count how many lines + */ + private void awaitLogs(String text, int count) throws InterruptedException { + Assert.assertTrue("never logged [" + text + "] " + count + " times, logs: " + logs, waitFor(() -> logsContaining(text) >= count)); + Assert.assertEquals(count, logsContaining(text)); + } + + /** + * How many log lines so far contain a text. + * + * @param text the text + * @return the number of lines + */ + private int logsContaining(String text) { + int count = 0; + for (String line : logs) { + if (line.contains(text)) { + count++; + } + } + return count; + } + + /** + * Makes the send loop look at the queue, as a newly stored request does. + */ + private static void nudge() { + SDKCore core = SDKCore.instance; + if (core != null && core.networking != null && core.config != null) { + core.networking.check(core.config); + } + } + + /** + * Nudges the send loop every {@link #POLL_MS} until the given moment. + * + * @param deadlineNs the moment, as {@link System#nanoTime()} + */ + private static void nudgeUntil(long deadlineNs) throws InterruptedException { + while (System.nanoTime() < deadlineNs) { + nudge(); + Thread.sleep(POLL_MS); + } + } + + /** + * Sleeps until the given moment. + * + * @param deadlineNs the moment, as {@link System#nanoTime()} + */ + private static void sleepUntil(long deadlineNs) throws InterruptedException { + long remainingMs = (deadlineNs - System.nanoTime()) / 1_000_000L; + if (remainingMs > 0) { + Thread.sleep(remainingMs); + } + } + + /** + * Polls until the condition holds or {@link #WAIT_BUDGET_MS} runs out, without nudging the send + * loop, so the SDK has to drain its queue on its own. + * + * @param condition the condition + * @return whether the condition holds + */ + private static boolean waitFor(BooleanSupplier condition) throws InterruptedException { + long deadline = System.currentTimeMillis() + WAIT_BUDGET_MS; + while (System.currentTimeMillis() < deadline) { + if (condition.getAsBoolean()) { + return true; + } + Thread.sleep(POLL_MS); + } + return condition.getAsBoolean(); + } + + /** + * Polls like {@link #waitFor(BooleanSupplier)}, nudging the send loop on every round. + * + * @param condition the condition + * @return whether the condition holds + */ + private static boolean waitNudging(BooleanSupplier condition) throws InterruptedException { + return waitFor(() -> { + nudge(); + return condition.getAsBoolean(); + }); + } + + /** + * Decodes url encoded request parameters. + * + * @param data the parameters + * @return the parameters by name + */ + private static Map parseParams(String data) { + Map params = new HashMap<>(); + for (String pair : data.split("&")) { + if (pair.isEmpty()) { + continue; + } + String[] keyValue = pair.split("=", 2); + params.put(Utils.urldecode(keyValue[0]), keyValue.length > 1 ? Utils.urldecode(keyValue[1]) : ""); + } + return params; + } + + /** + * Reads a stream to its end. + * + * @param stream the stream + * @return the bytes + * @throws IOException when the stream cannot be read + */ + private static byte[] readAll(InputStream stream) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int read; + while ((read = stream.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + return out.toByteArray(); + } + + // endregion +} 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 new file mode 100644 index 000000000..11ae59119 --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConfigurationTests.java @@ -0,0 +1,1289 @@ +package ly.count.sdk.java.internal; + +import com.sun.net.httpserver.HttpServer; +import java.io.OutputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.math.BigDecimal; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BooleanSupplier; +import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import static ly.count.sdk.java.internal.ServerConfigBuilder.names; + +/** + * SDK behavior settings, the server side configuration served by {@code /o/sdk?method=sc}: how + * {@link ModuleConfiguration} validates, stores and resolves them, and how the SDK applies + * the values it owns at init and when a response changes them. + *

+ * The settings request goes through a {@link ServerConfigResponder} injected on the + * {@link InternalConfig} before init. It answers on the calling thread, so the response of the fetch + * made at init is applied before init returns, and a later response is pushed by calling + * {@link ModuleConfiguration#fetchConfigFromServer(InternalConfig)} the way the refresh timer does. + */ +@RunWith(JUnit4.class) +public class ModuleConfigurationTests { + + private static final Set TOP_LEVEL_KEYS = names("v", "t", "c", "lg", "ct", "gzip", "jt"); + + private ServerConfigResponder server; + + /** + * Starts every test from empty storage, without a test module and with a fresh responder. + */ + @Before + public void beforeTest() { + TestUtils.createCleanTestState(); + SDKCore.testDummyModule = null; + server = new ServerConfigResponder(); + } + + /** + * Stops the SDK, clearing its data, and removes the test module. + */ + @After + public void afterTest() { + Countly.instance().halt(); + SDKCore.testDummyModule = null; + } + + // region scenarios + + /** + * The type table of every settings key, run through the validation a response goes through. + *

+ * Verifies that each of the 42 keys keeps every valid value and loses every value of the wrong + * type or range, that unknown keys are dropped, and that a decimal, which the JSON parser hands + * over as a {@link BigDecimal}, is still accepted as {@code bom_rqp}. + */ + @Test + public void removeUnsupportedKeys_keepsEveryValidValueAndDropsTheRest() throws IllegalAccessException { + server.failing(); + init(TestUtils.getConfigSdkBehaviorSettings()); + ModuleConfiguration module = module(); + + Map> valid = new LinkedHashMap<>(); + Map> invalid = new LinkedHashMap<>(); + for (String key : Arrays.asList("tracking", "networking", "st", "vt", "cet", "ecz", "crt", "ast", "avt", "acr", "lt", "rcz", "bom", "log", "cr")) { + valid.put(key, Arrays.asList("true", "false")); + invalid.put(key, Arrays.asList("1", "0", "\"true\"", "null", "{}", "[]")); + } + for (String key : Arrays.asList("scui", "rqs", "eqs", "sui", "lkl", "lvs", "lsv", "lbc", "ltlpt", "ltl", "upcl", "bom_at", "bom_ra", "bom_d")) { + valid.put(key, Arrays.asList("1", "7", "2147483647")); + invalid.put(key, Arrays.asList("0", "-5", "1.5", "5.0", "\"5\"", "true", "3000000000", "null")); + } + valid.put("dort", Arrays.asList("0", "1", "72")); + invalid.put("dort", Arrays.asList("-1", "0.5", "\"1\"", "false")); + valid.put("czi", Arrays.asList("16", "300")); + invalid.put("czi", Arrays.asList("15", "0", "-16", "16.0", "\"16\"")); + valid.put("bom_rqp", Arrays.asList("0.5", "0.01", "0.99", "1e-1")); + invalid.put("bom_rqp", Arrays.asList("0", "1", "0.0", "1.0", "-0.5", "1.5", "\"0.5\"", "true", "null")); + for (String key : Arrays.asList("eb", "ew", "sb", "sw", "upb", "upw", "jte", "jtv")) { + valid.put(key, Arrays.asList("[]", "[\"a\",\"b\"]")); + invalid.put(key, Arrays.asList("\"a\"", "{}", "1", "true", "null")); + } + for (String key : Arrays.asList("esb", "esw")) { + valid.put(key, Arrays.asList("{}", "{\"purchase\":[\"card\"]}")); + invalid.put(key, Arrays.asList("[]", "\"a\"", "1", "null")); + } + + Set settingsKeys = new HashSet<>(settingsKeysOfTheModule()); + Assert.assertEquals("the table covers every settings key the module declares", settingsKeys, valid.keySet()); + Assert.assertEquals(42, settingsKeys.size()); + + for (Map.Entry> entry : valid.entrySet()) { + for (String literal : entry.getValue()) { + assertKeptByValidation(module, entry.getKey(), literal, true); + } + } + for (Map.Entry> entry : invalid.entrySet()) { + for (String literal : entry.getValue()) { + assertKeptByValidation(module, entry.getKey(), literal, false); + } + } + for (String unknownKey : Arrays.asList("heartbeat", "TRACKING", "someFutureFeature", "")) { + assertKeptByValidation(module, unknownKey, "true", false); + } + + JSONObject settings = validated(module, "{\"bom_rqp\":0.25,\"tracking\":\"no\",\"eqs\":3}"); + Assert.assertTrue(settings.get("bom_rqp") instanceof BigDecimal); + Assert.assertEquals(2, settings.length()); + + push(new JSONObject().put("v", 1).put("t", 1).put("c", new JSONObject("{\"bom_rqp\":0.25}")).toString()); + Assert.assertEquals(0.25, provider().getBOMRQPercentage(), 0.0); + } + + /** + * Every settings key at once, one key of each blacklist and whitelist pair, at a valid value that + * differs from the default, then every key at an invalid value. + *

+ * Verifies that each value reaches its provider getter and the store, that the request queue size + * is reported as coming from the settings, and that a response made only of invalid values stores + * no setting and brings every one back to the developer value, as one more change. + */ + @Test + public void allSettings_resolveFromAResponse_andInvalidValuesFallBackToTheDeveloperValues() throws IllegalAccessException { + AtomicInteger changes = installCountingModule().changes; + ServerConfigBuilder allKeys = new ServerConfigBuilder().allKeysAtNonDefaultValues(); + server.respondWith(allKeys); + init(TestUtils.getConfigSdkBehaviorSettings()); + + allKeys.validateAgainst(provider()); + Assert.assertTrue(provider().isRequestQueueMaxSizeFromBehaviorSettings()); + Assert.assertEquals(1, changes.get()); + JSONObject storedSettings = storedConfig().getJSONObject("c"); + Assert.assertEquals(allKeys.config.keySet(), storedSettings.keySet()); + + ServerConfigBuilder allInvalid = new ServerConfigBuilder(); + for (String key : settingsKeysOfTheModule()) { + allInvalid.set(key, "tracking".equals(key) ? -1 : "not a valid value"); + } + push(allInvalid); + + ConfigurationProvider developer = ModuleConfiguration.developerDefaults(new InternalConfig(TestUtils.getConfigSdkBehaviorSettings())); + Set nameFilterKeys = names("eb", "ew", "upb", "upw", "sb", "sw", "esb", "esw"); + for (String key : allKeys.config.keySet()) { + if (!nameFilterKeys.contains(key)) { + Assert.assertEquals("value of '" + key + "'", ServerConfigBuilder.valueOf(developer, key), ServerConfigBuilder.valueOf(provider(), key)); + } + } + assertFilter(provider().getEventFilterList(), false, names()); + assertFilter(provider().getUserPropertyFilterList(), false, names()); + assertFilter(provider().getSegmentationFilterList(), false, names()); + Assert.assertTrue(provider().getEventSegmentationFilterList().getFilterList().isEmpty()); + Assert.assertFalse(provider().isRequestQueueMaxSizeFromBehaviorSettings()); + Assert.assertEquals(2, changes.get()); + Assert.assertEquals(0, storedConfig().getJSONObject("c").length()); + } + + /** + * The envelope of a response: {@code v}, {@code t} and an object {@code c} are required, any + * other top level key is allowed. + *

+ * Verifies that a response missing one of the three, or with a {@code c} that is not an object, + * is rejected without touching the store, that an empty {@code c} is accepted, that extra top + * level keys are accepted quietly and never stored, so neither {@code lg} nor {@code ct} ever is + * while {@code ct} still asks for one connection test, and that a rejected response after an + * accepted one keeps the merged settings. + */ + @Test + public void envelope_requiresVersionTimestampAndSettingsObject_andOnlyThoseAreStored() { + List warnings = new CopyOnWriteArrayList<>(); + server.failing(); + init(TestUtils.getConfigSdkBehaviorSettings().setLogListener((message, level) -> { + if (level == Config.LoggingLevel.WARN || level == Config.LoggingLevel.ERROR) { + warnings.add(message); + } + })); + Assert.assertNull(storedConfig()); + + for (String rejected : Arrays.asList("{}", "{'t':2,'c':{'tracking':false}}", "{'v':1,'c':{'tracking':false}}", "{'v':1,'t':2}", + "{'v':1,'t':2,'c':123}", "{'v':1,'t':2,'c':false}", "{'v':1,'t':2,'c':'fdf'}", "{'v':1,'t':2,'c':[]}")) { + push(rejected); + Assert.assertNull("stored after " + rejected, storedConfig()); + Assert.assertTrue(provider().getTrackingEnabled()); + } + + push("{'v':1,'t':2,'c':{}}"); + Assert.assertTrue(new JSONObject("{'v':1,'t':2,'c':{}}").similar(storedConfig())); + + warnings.clear(); + List connectionTestRequests = new CopyOnWriteArrayList<>(); + //the connection test module would run its probe battery against the test server over the network + module().setConnectionTestListener(connectionTestRequests::add); + push(new ServerConfigBuilder().version(2).timestamp(3).tracking(false) + .logGatheringOn("gather_id", "ew", 20) + .connectionTest(1) + .topLevelKey("someFutureFeature", "a value this SDK has never heard of")); + + Assert.assertEquals(1, connectionTestRequests.size()); + Assert.assertFalse(provider().getTrackingEnabled()); + Assert.assertEquals(ConfigurationProvider.LogGatheringState.GATHERING, provider().getLogGatheringState()); + JSONObject stored = storedConfig(); + Assert.assertEquals(names("v", "t", "c"), stored.keySet()); + Assert.assertEquals(2, stored.getInt("v")); + Assert.assertEquals(3, stored.getLong("t")); + Assert.assertFalse(stored.getJSONObject("c").getBoolean("tracking")); + for (String warning : warnings) { + Assert.assertFalse("warned about a top level key: " + warning, warning.contains("someFutureFeature") || warning.contains("[lg]") || warning.contains("[ct]")); + } + + push("{'t':4,'c':{'tracking':true}}"); + Assert.assertFalse(provider().getTrackingEnabled()); + Assert.assertTrue(stored.similar(storedConfig())); + } + + /** + * The layers of a value: developer configuration, then the provided settings while nothing is + * stored, then the stored settings, then each server response. + *

+ * Verifies each layer overriding the one below it, that the provided settings are stored and + * ignored once something is stored, that a response replaces the stored settings, so a setting it + * leaves out goes back to the developer value, and that the replacement survives {@code stop()} + * and a new init. + */ + @Test + public void precedence_developerThenProvidedThenStoredThenServer_andAResponseReplacesTheStoredSettings() { + server.pending(); + init(developerConfig()); + + Assert.assertEquals(7, provider().getEventQueueSizeThreshold()); + Assert.assertEquals(50, provider().getRequestQueueMaxSize()); + Assert.assertFalse(provider().isRequestQueueMaxSizeFromBehaviorSettings()); + Assert.assertEquals(30, provider().getSessionUpdateInterval()); + Assert.assertEquals(40, provider().getMaxBreadcrumbCount()); + Assert.assertEquals(ModuleConfiguration.NO_LIMIT, provider().getMaxKeyLength()); + Assert.assertEquals(ModuleConfiguration.NO_LIMIT, provider().getUserPropertyCacheLimit()); + Assert.assertTrue(provider().getLoggingEnabled()); + Assert.assertNull(storedConfig()); + Countly.instance().halt(); + + init(developerConfig().setSdkBehaviorSettings(new ServerConfigBuilder().eventQueueSize(11).requestQueueSize(22).build())); + + Assert.assertEquals(11, provider().getEventQueueSizeThreshold()); + Assert.assertEquals(22, provider().getRequestQueueMaxSize()); + Assert.assertTrue(provider().isRequestQueueMaxSizeFromBehaviorSettings()); + Assert.assertEquals(30, provider().getSessionUpdateInterval()); + Assert.assertEquals(2, storedConfig().getJSONObject("c").length()); + + push(new ServerConfigBuilder().eventQueueSize(33).breadcrumbLimit(5).logging(false)); + + Assert.assertEquals(33, provider().getEventQueueSizeThreshold()); + Assert.assertEquals(50, provider().getRequestQueueMaxSize()); + Assert.assertFalse(provider().isRequestQueueMaxSizeFromBehaviorSettings()); + Assert.assertEquals(5, provider().getMaxBreadcrumbCount()); + Assert.assertEquals(30, provider().getSessionUpdateInterval()); + Assert.assertFalse(provider().getLoggingEnabled()); + JSONObject storedSettings = storedConfig().getJSONObject("c"); + Assert.assertEquals(names("eqs", "lbc", "log"), storedSettings.keySet()); + Countly.instance().stop(); + + server.failing(); + init(developerConfig().setSdkBehaviorSettings(new ServerConfigBuilder().eventQueueSize(99).sessionTracking(false).build())); + + Assert.assertEquals(33, provider().getEventQueueSizeThreshold()); + Assert.assertEquals(50, provider().getRequestQueueMaxSize()); + Assert.assertEquals(5, provider().getMaxBreadcrumbCount()); + Assert.assertFalse(provider().getLoggingEnabled()); + Assert.assertTrue(provider().getSessionTrackingEnabled()); + Assert.assertTrue(storedSettings.similar(storedConfig().getJSONObject("c"))); + } + + /** + * The settings request itself. + *

+ * Verifies that init sends exactly one request, to {@code /o/sdk?} with {@code method=sc} and the + * parameters every request carries, that it goes out even while the settings forbid networking, + * that the configuration module is initialized once and sits at its fixed index ahead of the + * feature modules, and that with settings requests disabled nothing is requested while the + * provided settings still apply. + */ + @Test + public void fetch_requestsTheSettingsAtInitWithTheRequiredParams_andNeverWhenDisabled() { + List initLines = new CopyOnWriteArrayList<>(); + server.respondWith(new ServerConfigBuilder().networking(false)); + init(TestUtils.getConfigSdkBehaviorSettings().setLogListener((message, level) -> { + if (message.startsWith("[ModuleConfiguration] init,")) { + initLines.add(message); + } + })); + + Assert.assertEquals(1, server.requests.size()); + Assert.assertEquals("/o/sdk?", server.endpoints.get(0)); + Map params = server.requests.get(0); + Assert.assertEquals("sc", params.get("method")); + TestUtils.validateRequiredParams(params); + Assert.assertEquals(TestUtils.SDK_NAME, params.get("sdk_name")); + Assert.assertEquals(TestUtils.SDK_VERSION, params.get("sdk_version")); + Assert.assertTrue(server.networkingFlags.get(0)); + + Assert.assertEquals(1, initLines.size()); + Assert.assertSame(module(), SDKCore.instance.modules.get(-1)); + Assert.assertSame(module(), SDKCore.instance.config.getConfigurationProvider()); + Assert.assertEquals(4L * 60 * 60, module().serverConfigUpdateTimer.getTimerDelaySeconds()); + + Assert.assertFalse(provider().getNetworkingEnabled()); + push(new ServerConfigBuilder().networking(true)); + Assert.assertEquals(2, server.requests.size()); + Assert.assertTrue(server.networkingFlags.get(1)); + Assert.assertTrue(provider().getNetworkingEnabled()); + Countly.instance().halt(); + + server = new ServerConfigResponder(); + init(TestUtils.getConfigSdkBehaviorSettings() + .disableSdkBehaviorSettingsUpdates() + .setSdkBehaviorSettings(new ServerConfigBuilder().tracking(false).build())); + + Assert.assertTrue(server.requests.isEmpty()); + Assert.assertFalse(provider().getTrackingEnabled()); + Assert.assertNull(module().serverConfigUpdateTimer); + Assert.assertEquals(ConfigurationProvider.LogGatheringState.NOT_GATHERING, provider().getLogGatheringState()); + } + + /** + * Backend mode keeps the settings inert. + *

+ * Verifies that with stored and provided settings present, backend mode requests nothing, serves + * the developer configuration, starts no refresh timer, decides against log gathering and leaves + * the stored settings as they are for a later run without backend mode. + */ + @Test + public void backendMode_keepsTheSettingsInert() { + server.respondWith(new ServerConfigBuilder().tracking(false).eventQueueSize(3).requestQueueSize(5)); + init(TestUtils.getConfigSdkBehaviorSettings()); + Assert.assertFalse(provider().getTrackingEnabled()); + JSONObject storedBefore = storedConfig(); + Countly.instance().stop(); + + server = new ServerConfigResponder().respondWith(new ServerConfigBuilder().networking(false)); + init(TestUtils.getConfigSdkBehaviorSettings() + .enableBackendMode() + .setEventQueueSizeToSend(9) + .setRequestQueueMaxSize(40) + .setSdkBehaviorSettings(new ServerConfigBuilder().networking(false).build())); + + Assert.assertTrue(server.requests.isEmpty()); + Assert.assertTrue(provider().getTrackingEnabled()); + Assert.assertTrue(provider().getNetworkingEnabled()); + Assert.assertTrue(SDKCore.instance.config.getNetworkingEnabled()); + Assert.assertEquals(9, provider().getEventQueueSizeThreshold()); + Assert.assertEquals(40, provider().getRequestQueueMaxSize()); + Assert.assertFalse(provider().isRequestQueueMaxSizeFromBehaviorSettings()); + Assert.assertEquals(ConfigurationProvider.LogGatheringState.NOT_GATHERING, provider().getLogGatheringState()); + Assert.assertNull(module().serverConfigUpdateTimer); + Assert.assertTrue(storedBefore.similar(storedConfig())); + } + + /** + * The consent requirement is applied when the SDK initializes, and only then. + *

+ * Verifies that a {@code cr} arriving while the SDK runs is stored but leaves the running SDK + * without consent gating, that the stored value is in place before the modules are built on the + * next init, so the feature modules wait for consent while an integration that never asked for + * consent calls an events interface that ignores calls instead of throwing, and that removing + * consent stops feature modules but never the configuration module, which keeps applying + * responses. + */ + @Test + public void consentRequirement_appliesAtInitOnly_andConsentRemovalNeverStopsTheConfigurationModule() { + server.respondWith(new ServerConfigBuilder().consentRequired(true)); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.Events)); + + Assert.assertTrue(provider().getConsentRequired()); + Assert.assertFalse(SDKCore.instance.config.requiresConsent()); + Assert.assertTrue(Countly.isTracking(Config.Feature.Events)); + Assert.assertNotNull(Countly.instance().events()); + Assert.assertTrue(storedConfig().getJSONObject("c").getBoolean("cr")); + Countly.instance().stop(); + + server.pending(); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.Events)); + + Assert.assertTrue(SDKCore.instance.config.requiresConsent()); + Assert.assertFalse(Countly.isTracking(Config.Feature.Events)); + Assert.assertSame(SDKCore.dormantEvents, Countly.instance().events()); + Countly.instance().events().recordEvent("before_consent"); + TestUtils.validateEQSize(0); + + Countly.onConsent(Config.Feature.Events); + Assert.assertTrue(Countly.isTracking(Config.Feature.Events)); + + ModuleConfiguration configurationModule = module(); + CountlyTimer refreshTimer = configurationModule.serverConfigUpdateTimer; + Assert.assertNotNull(refreshTimer); + + Countly.onConsentRemoval(Config.Feature.Events); + + Assert.assertFalse(Countly.isTracking(Config.Feature.Events)); + Assert.assertSame(configurationModule, SDKCore.instance.modules.get(-1)); + Assert.assertSame(configurationModule, SDKCore.instance.config.getConfigurationProvider()); + Assert.assertTrue(configurationModule.isActive()); + Assert.assertSame(refreshTimer, configurationModule.serverConfigUpdateTimer); + + push(new ServerConfigBuilder().consentRequired(false).tracking(false)); + Assert.assertFalse(provider().getTrackingEnabled()); + Assert.assertFalse(provider().getConsentRequired()); + Assert.assertTrue(SDKCore.instance.config.requiresConsent()); + } + + /** + * The global timer follows the session update interval, and the refresh timer follows the + * update interval of the settings. + *

+ * Verifies that a stored {@code sui} starts the global timer at init, which then really ticks every + * second, that a changed {@code sui} restarts the timer and notifies every module once, that a + * response changing nothing restarts nothing and notifies nobody, that another change notifies the + * modules without touching the timer, and that a changed {@code scui} restarts the refresh timer. + */ + @Test + public void timers_followTheResolvedIntervals_andChangesAreDispatchedOnce() throws InterruptedException { + CountingModule counter = installCountingModule(); + AtomicInteger changes = counter.changes; + AtomicInteger ticks = counter.ticks; + + server.respondWith(new ServerConfigBuilder().sessionUpdateInterval(1)); + init(TestUtils.getConfigSdkBehaviorSettings()); + Assert.assertEquals(1, SDKCore.instance.countlyTimer.getTimerDelaySeconds()); + Assert.assertEquals(1, changes.get()); + Countly.instance().stop(); + + changes.set(0); + ticks.set(0); + server.pending(); + init(TestUtils.getConfigSdkBehaviorSettings()); + + CountlyTimer timerAtInit = SDKCore.instance.countlyTimer; + Assert.assertEquals(1, timerAtInit.getTimerDelaySeconds()); + Assert.assertEquals(0, changes.get()); + Assert.assertTrue("the global timer did not tick every second", waitFor(10_000, () -> ticks.get() >= 2)); + + ServerConfigBuilder slower = new ServerConfigBuilder().sessionUpdateInterval(3); + push(slower); + CountlyTimer restarted = SDKCore.instance.countlyTimer; + Assert.assertNotSame(timerAtInit, restarted); + Assert.assertEquals(3, restarted.getTimerDelaySeconds()); + Assert.assertEquals(1, changes.get()); + + push(slower); + Assert.assertSame(restarted, SDKCore.instance.countlyTimer); + Assert.assertEquals(1, changes.get()); + + push(new ServerConfigBuilder().sessionUpdateInterval(3).eventQueueSize(4)); + Assert.assertSame(restarted, SDKCore.instance.countlyTimer); + Assert.assertEquals(2, changes.get()); + + CountlyTimer refreshTimer = module().serverConfigUpdateTimer; + Assert.assertEquals(4L * 60 * 60, refreshTimer.getTimerDelaySeconds()); + push(new ServerConfigBuilder().serverConfigUpdateInterval(2)); + Assert.assertNotSame(refreshTimer, module().serverConfigUpdateTimer); + Assert.assertEquals(2L * 60 * 60, module().serverConfigUpdateTimer.getTimerDelaySeconds()); + Assert.assertEquals(3, changes.get()); + } + + /** + * {@code cet} covers custom events only, {@code tracking} covers every event. + *

+ * Verifies on the wire that with custom event tracking off a custom event, a {@code [CLY]_} key + * the SDK does not record itself included, is dropped while a view + * started through the views interface and an internal event still reach the queue, flushed at the + * event queue size the settings resolved, that tracking off then drops internal events too, and + * that custom events are recorded again once both are back on. Networking is off throughout, so + * the request stays on disk to be read. + */ + @Test + public void customEventTracking_off_dropsCustomEventsOnly_whileTrackingGatesEveryEvent() { + server.respondWith(new ServerConfigBuilder().customEventTracking(false).eventQueueSize(2).networking(false)); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.Events, Config.Feature.Views).setEventQueueSizeToSend(100)); + + Countly.instance().events().recordEvent("custom_event"); + Countly.instance().events().recordEvent("[CLY]_not_an_sdk_event"); + TestUtils.validateEQSize(0); + + Countly.instance().views().startView("home"); + TestUtils.validateEQSize(1); + Assert.assertEquals(ModuleViews.KEY_VIEW_EVENT, TestUtils.getCurrentEQ().get(0).key); + Assert.assertEquals(0, TestUtils.getCurrentRQ().length); + + Countly.instance().events().recordEvent("[CLY]_star_rating"); + Assert.assertEquals(1, TestUtils.getCurrentRQ().length); + List sent = TestUtils.readEventsFromRequest(0, TestUtils.DEVICE_ID); + Assert.assertEquals(2, sent.size()); + Assert.assertEquals(ModuleViews.KEY_VIEW_EVENT, sent.get(0).key); + Assert.assertEquals("[CLY]_star_rating", sent.get(1).key); + TestUtils.validateEQSize(0); + + push(new ServerConfigBuilder().tracking(false)); + Countly.instance().events().recordEvent("[CLY]_star_rating"); + Countly.instance().views().startView("settings"); + TestUtils.validateEQSize(0); + Assert.assertEquals(1, TestUtils.getCurrentRQ().length); + + push(new ServerConfigBuilder().tracking(true).customEventTracking(true)); + Countly.instance().events().recordEvent("custom_event"); + TestUtils.validateEQSize(1); + Assert.assertEquals("custom_event", TestUtils.getCurrentEQ().get(0).key); + } + + /** + * Listing filters and journey trigger sets are published as immutable snapshots. + *

+ * Verifies every filter family and both journey sets as parsed, that a reader's snapshot never + * changes under it, that each response replaces every filter and journey set, so one it leaves out + * is turned off, and that the filters of the last response survive a restart. + */ + @Test + public void listingFilters_arePublishedAsSnapshots_andEachResponseReplacesThem() { + Map> perEvent = new LinkedHashMap<>(); + perEvent.put("purchase", names("card")); + server.respondWith(new ServerConfigBuilder() + .eventFilterList(names("blocked_a", "blocked_b"), false) + .segmentationFilterList(names("secret"), false) + .eventSegmentationFilterMap(perEvent, false) + .userPropertyFilterList(names("plan"), true) + .journeyTriggerEvents(names("checkout")) + .journeyTriggerViews(names("paywall"))); + init(TestUtils.getConfigSdkBehaviorSettings()); + + ConfigurationProvider.FilterList> events = provider().getEventFilterList(); + assertFilter(events, false, names("blocked_a", "blocked_b")); + assertFilter(provider().getSegmentationFilterList(), false, names("secret")); + assertFilter(provider().getUserPropertyFilterList(), true, names("plan")); + Assert.assertFalse(provider().getEventSegmentationFilterList().isWhitelist()); + Assert.assertEquals(perEvent, provider().getEventSegmentationFilterList().getFilterList()); + Assert.assertEquals(names("checkout"), provider().getJourneyTriggerEvents()); + Assert.assertEquals(names("paywall"), provider().getJourneyTriggerViews()); + assertUnmodifiable(events.getFilterList()); + assertUnmodifiable(provider().getEventSegmentationFilterList().getFilterList().get("purchase")); + assertUnmodifiable(provider().getJourneyTriggerEvents()); + try { + provider().getEventSegmentationFilterList().getFilterList().put("other", names("x")); + Assert.fail("the event segmentation filter can be changed by a reader"); + } catch (UnsupportedOperationException expected) { + Assert.assertEquals(1, provider().getEventSegmentationFilterList().getFilterList().size()); + } + + push(new ServerConfigBuilder().eventFilterList(names("allowed_event"), true)); + + assertFilter(events, false, names("blocked_a", "blocked_b")); + assertFilter(provider().getEventFilterList(), true, names("allowed_event")); + assertFilter(provider().getSegmentationFilterList(), false, names()); + assertFilter(provider().getUserPropertyFilterList(), false, names()); + Assert.assertTrue(provider().getEventSegmentationFilterList().getFilterList().isEmpty()); + Assert.assertTrue(provider().getJourneyTriggerEvents().isEmpty()); + Assert.assertTrue(provider().getJourneyTriggerViews().isEmpty()); + Assert.assertEquals(names("ew"), storedConfig().getJSONObject("c").keySet()); + + push(new ServerConfigBuilder().tracking(false)); + assertFilter(provider().getEventFilterList(), false, names()); + + push(new ServerConfigBuilder().segmentationFilterList(names("secret"), false).journeyTriggerEvents(names("checkout"))); + assertFilter(provider().getSegmentationFilterList(), false, names("secret")); + Assert.assertEquals(names("checkout"), provider().getJourneyTriggerEvents()); + Assert.assertTrue(provider().getTrackingEnabled()); + Assert.assertEquals(names("sb", "jte"), storedConfig().getJSONObject("c").keySet()); + Countly.instance().stop(); + + server.pending(); + init(TestUtils.getConfigSdkBehaviorSettings()); + assertFilter(provider().getSegmentationFilterList(), false, names("secret")); + Assert.assertEquals(names("checkout"), provider().getJourneyTriggerEvents()); + Assert.assertTrue(provider().getJourneyTriggerViews().isEmpty()); + Assert.assertTrue(provider().getTrackingEnabled()); + } + + /** + * A setting the server stops sending goes back to the developer value, or to the SDK default when + * the developer sets none, instead of keeping the last server value. + *

+ * Verifies with a developer configuration that sets the event and request queue sizes and the + * breadcrumb limit that a response leaving out tracking, the event queue size, the key length + * limit and an event blacklist brings back the default tracking, the developer's queue size, no + * key length limit and no event filter, that only what that response carries is stored, and that + * a response with no settings, which the server sends once every setting is removed, brings back + * every developer value and stores no setting. + */ + @Test + public void removedSettings_goBackToTheDeveloperValues_andAnEmptyResponseBringsBackAll() { + server.respondWith(new ServerConfigBuilder().tracking(false).eventQueueSize(3).keyLengthLimit(20).breadcrumbLimit(5) + .requestQueueSize(22).eventFilterList(names("blocked_event"), false)); + init(developerConfig()); + Assert.assertFalse(provider().getTrackingEnabled()); + Assert.assertEquals(3, provider().getEventQueueSizeThreshold()); + Assert.assertEquals(20, provider().getMaxKeyLength()); + assertFilter(provider().getEventFilterList(), false, names("blocked_event")); + + push(new ServerConfigBuilder().networking(true).requestQueueSize(22).breadcrumbLimit(5)); + Assert.assertTrue(provider().getTrackingEnabled()); + Assert.assertEquals(7, provider().getEventQueueSizeThreshold()); + Assert.assertEquals(ModuleConfiguration.NO_LIMIT, provider().getMaxKeyLength()); + assertFilter(provider().getEventFilterList(), false, names()); + Assert.assertEquals(22, provider().getRequestQueueMaxSize()); + Assert.assertEquals(5, provider().getMaxBreadcrumbCount()); + Assert.assertEquals(names("networking", "rqs", "lbc"), storedConfig().getJSONObject("c").keySet()); + + push("{'v':1,'t':3,'c':{}}"); + Assert.assertEquals(50, provider().getRequestQueueMaxSize()); + Assert.assertFalse(provider().isRequestQueueMaxSizeFromBehaviorSettings()); + Assert.assertEquals(40, provider().getMaxBreadcrumbCount()); + Assert.assertTrue(provider().getLoggingEnabled()); + Assert.assertEquals(0, storedConfig().getJSONObject("c").length()); + } + + /** + * Settings provided at init stand in for the server's until its first response, which replaces + * them. + *

+ * Verifies that the provided settings apply at init, and that the first response, carrying only + * the request queue size, brings tracking and the event queue size back to the developer values + * and is all that is stored. + */ + @Test + public void providedSettings_applyUntilTheFirstResponse() { + server.pending(); + init(developerConfig().setSdkBehaviorSettings(new ServerConfigBuilder().tracking(false).eventQueueSize(11).build())); + Assert.assertFalse(provider().getTrackingEnabled()); + Assert.assertEquals(11, provider().getEventQueueSizeThreshold()); + + push(new ServerConfigBuilder().requestQueueSize(500)); + Assert.assertTrue(provider().getTrackingEnabled()); + Assert.assertEquals(7, provider().getEventQueueSizeThreshold()); + Assert.assertEquals(500, provider().getRequestQueueMaxSize()); + Assert.assertEquals(names("rqs"), storedConfig().getJSONObject("c").keySet()); + } + + /** + * The settings can add a consent requirement but never lift the one the developer set. + *

+ * Verifies with {@link Config#setRequiresConsent(boolean)} on that a provided, a live and a stored + * {@code cr} false all leave consent required, so the feature modules wait for consent, and that + * without the developer's requirement a {@code cr} true is lifted again by a response without it. + */ + @Test + public void consentRequirement_aFalseFromTheSettingsNeverLiftsTheDevelopersRequirement() { + server.respondWith(new ServerConfigBuilder().consentRequired(false)); + init(TestUtils.getConfigSdkBehaviorSettings().setRequiresConsent(true).enableFeatures(Config.Feature.Events) + .setSdkBehaviorSettings(new ServerConfigBuilder().consentRequired(false).build())); + + Assert.assertTrue(provider().getConsentRequired()); + Assert.assertTrue(SDKCore.instance.config.requiresConsent()); + Assert.assertFalse(Countly.isTracking(Config.Feature.Events)); + Assert.assertFalse(storedConfig().getJSONObject("c").getBoolean("cr")); + Countly.instance().stop(); + + server.pending(); + init(TestUtils.getConfigSdkBehaviorSettings().setRequiresConsent(true).enableFeatures(Config.Feature.Events)); + Assert.assertTrue(provider().getConsentRequired()); + Assert.assertTrue(SDKCore.instance.config.requiresConsent()); + Assert.assertFalse(Countly.isTracking(Config.Feature.Events)); + Countly.instance().halt(); + + server = new ServerConfigResponder().respondWith(new ServerConfigBuilder().consentRequired(true)); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.Events)); + Assert.assertTrue(provider().getConsentRequired()); + push(new ServerConfigBuilder().tracking(true)); + Assert.assertFalse(provider().getConsentRequired()); + } + + /** + * A journey trigger that a device ID change without merge ends is sent with the other events of + * the previous device ID, under that ID. + *

+ * Verifies with {@code checkout} as a journey trigger and networking off that ending a timed + * {@code checkout} on the change does not send the queue under the new ID: the queued event and + * the trigger are stored in one request that carries the previous device ID, and that request + * refreshes no content zone for the new device ID. + */ + @Test + public void journeyTrigger_endedByADeviceIdChange_isSentUnderThePreviousDeviceId() { + server.respondWith(new ServerConfigBuilder().journeyTriggerEvents(names("checkout")).eventQueueSize(100).networking(false)); + init(TestUtils.getConfigSdkBehaviorSettings().enableFeatures(Config.Feature.Events)); + + Countly.instance().events().recordEvent("old_user_event"); + Countly.instance().events().startEvent("checkout"); + Countly.instance().deviceId().changeWithoutMerge("new_device_id"); + TestUtils.letTheClockCatchUp(); + + Assert.assertEquals(1, TestUtils.getCurrentRQ().length); + List events = TestUtils.readEventsFromRequest(0, TestUtils.DEVICE_ID); + Assert.assertEquals(2, events.size()); + Assert.assertEquals("old_user_event", events.get(0).key); + Assert.assertEquals("checkout", events.get(1).key); + } + + /** + * The {@code ct} connection test flag of a live response. + *

+ * Verifies the truthiness table of the flag and that it is removed from the response, then through + * live fetches that a truthy flag reaches the registered listener once, after the settings of the + * same response were applied, with the latency measured from just before the request to its + * response, that a falsy flag does not, that a response whose settings are rejected can still ask, + * and that the flag is never stored. + */ + @Test + public void connectionTestFlag_isReadByValue_strippedFromTheResponse_andHandedOnWithTheFetchLatency() { + Object[][] table = { + { "true", true }, { "false", false }, { "1", true }, { "0", false }, { "0.0", false }, { "2.5", true }, { "-1", true }, + { "\"1\"", true }, { "\"0\"", false }, { "\"false\"", false }, { "\"FALSE\"", false }, { "\" false \"", false }, + { "\"\"", false }, { "\" \"", false }, { "\"yes\"", true }, { "\"true\"", true }, { "null", false }, + { "{}", true }, { "[]", true }, { "{\"a\":1}", true } + }; + for (Object[] row : table) { + JSONObject response = new JSONObject("{\"v\":1,\"t\":1,\"c\":{},\"ct\":" + row[0] + "}"); + Assert.assertEquals("ct = " + row[0], row[1], ModuleConfiguration.extractConnectionTestFlag(response)); + Assert.assertFalse("ct = " + row[0] + " was left in the response", response.has("ct")); + } + Assert.assertFalse(ModuleConfiguration.extractConnectionTestFlag(new JSONObject("{\"v\":1,\"t\":1,\"c\":{}}"))); + Assert.assertFalse(ModuleConfiguration.extractConnectionTestFlag(null)); + + server.failing(); + init(TestUtils.getConfigSdkBehaviorSettings()); + List latencies = new CopyOnWriteArrayList<>(); + List trackingWhenNotified = new CopyOnWriteArrayList<>(); + module().setConnectionTestListener(fetchLatencyMs -> { + latencies.add(fetchLatencyMs); + trackingWhenNotified.add(provider().getTrackingEnabled()); + }); + + server.delayedBy(80); + push(new ServerConfigBuilder().tracking(false).connectionTest(1)); + Assert.assertEquals(1, latencies.size()); + Assert.assertTrue("latency " + latencies.get(0), latencies.get(0) >= 70); + Assert.assertEquals(Arrays.asList(false), trackingWhenNotified); + + server.delayedBy(0); + push(new ServerConfigBuilder().connectionTest(0)); + push(new ServerConfigBuilder().connectionTest("false")); + push(new ServerConfigBuilder()); + Assert.assertEquals(1, latencies.size()); + + push("{\"ct\":true}"); + Assert.assertEquals(2, latencies.size()); + Assert.assertFalse(storedConfig().has("ct")); + + module().setConnectionTestListener(null); + push(new ServerConfigBuilder().connectionTest(1).tracking(true)); + Assert.assertTrue(provider().getTrackingEnabled()); + Assert.assertEquals(2, latencies.size()); + } + + /** + * The {@code lg} directive of a live response turns log gathering on and off. + *

+ * Verifies that a directive with a gather id arms gathering with its levels and batch size and is + * never stored, that {@code "e":false} and a response without any directive both decide off and + * drop the gather id, and that a failed fetch after a decision changes nothing. + */ + @Test + public void logGatheringDirective_enabledThenDisabled_isAppliedBothWays() { + server.respondWith(new ServerConfigBuilder().logGatheringOn("gather_id_3", "ewd", 40)); + init(TestUtils.getConfigSdkBehaviorSettings()); + + assertGathering("gather_id_3", "ewd", 40); + Assert.assertFalse(storedConfig().has("lg")); + + push(new ServerConfigBuilder().logGatheringOff()); + assertNotGathering(); + + push(new ServerConfigBuilder().logGatheringOn("gather_id_3", "ewd", 40)); + assertGathering("gather_id_3", "ewd", 40); + + push(new ServerConfigBuilder().tracking(false)); + assertNotGathering(); + Assert.assertFalse(provider().getTrackingEnabled()); + + push(new ServerConfigBuilder().logGatheringOn("gather_id_4", "e", 20)); + server.failing(); + module().fetchConfigFromServer(SDKCore.instance.config); + assertGathering("gather_id_4", "e", 20); + } + + /** + * A directive that enables gathering without a usable gather id, or with {@code e} that is not a + * boolean {@code true}, decides off. A working directive is applied between the cases, so no + * assertion passes because the state was already off. + */ + @Test + public void logGatheringDirective_withoutUsableGatherId_doesNotEnableGathering() { + server.respondWith(new ServerConfigBuilder().logGatheringOn("gather_id_4", "ew", 20)); + init(TestUtils.getConfigSdkBehaviorSettings()); + assertGathering("gather_id_4", "ew", 20); + + List unusable = Arrays.asList( + new ServerConfigBuilder().logGatheringDirective(true, null, "ew", 20), + new ServerConfigBuilder().logGatheringDirective(true, " ", "ew", 20), + new ServerConfigBuilder().logGatheringDirective(true, 42, "ew", 20), + new ServerConfigBuilder().logGatheringDirective("true", "gather_id_4", "ew", 20), + new ServerConfigBuilder().logGatheringDirective(1, "gather_id_4", "ew", 20), + new ServerConfigBuilder().topLevelKey("lg", "on")); + for (ServerConfigBuilder directive : unusable) { + push(directive); + assertNotGathering(); + + push(new ServerConfigBuilder().logGatheringOn("gather_id_4", "ew", 20)); + assertGathering("gather_id_4", "ew", 20); + } + + push(new ServerConfigBuilder().logGatheringOn(" gather_id_5 ", "ew", 20)); + assertGathering("gather_id_5", "ew", 20); + } + + /** + * The levels and the batch size of a directive are sanitized: unknown level characters go, the + * rest is lower cased and deduplicated in the order sent, nothing usable falls back to every level, + * and the batch size is clamped into [10, 500] or falls back to 100 when it is not a number. + */ + @Test + public void logGatheringDirective_levelsAndBatchSize_areSanitized() { + server.respondWith(new ServerConfigBuilder().logGatheringOn("gather_id_5", "xyz!", 100)); + init(TestUtils.getConfigSdkBehaviorSettings()); + assertGathering("gather_id_5", ModuleConfiguration.logGatheringAllLevels, 100); + + Object[][] steps = { + { "ew", 100, "ew", 100 }, + { null, 100, ModuleConfiguration.logGatheringAllLevels, 100 }, + { "ew", 100, "ew", 100 }, + { 5, 100, ModuleConfiguration.logGatheringAllLevels, 100 }, + { "EWID", 100, "ewid", 100 }, + { "wweeww", 100, "we", 100 }, + { "vq d", 100, "vd", 100 }, + { "ew", 1, "ew", ModuleConfiguration.logGatheringMinBatchSize }, + { "ew", 9999, "ew", ModuleConfiguration.logGatheringMaxBufferedLines }, + { "ew", 250, "ew", 250 }, + { "ew", "250", "ew", ModuleConfiguration.logGatheringDefaultBatchSize }, + { "ew", 250, "ew", 250 }, + { "ew", null, "ew", ModuleConfiguration.logGatheringDefaultBatchSize }, + { "ew", 37.9, "ew", 37 } + }; + for (Object[] step : steps) { + push(new ServerConfigBuilder().logGatheringDirective(true, "gather_id_5", step[0], step[1])); + assertGathering("gather_id_5", (String) step[2], (Integer) step[3]); + } + } + + /** + * Only a live response decides log gathering. + *

+ * Verifies that a stored directive, even an armed one, leaves the state undecided and is dropped + * from the stored copy, that a stored configuration without one also stays undecided, that a + * failed fetch decides off while undecided, and that disabled settings requests decide off at + * init even with an armed directive in the provided settings. + */ + @Test + public void logGathering_isUndecidedUntilALiveResponse_failedFetchAndDisabledRequestsDecideOff() { + TestUtils.writeToFile(SDKStorage.JSON_FILE_NAME, new JSONObject() + .put("sc", new ServerConfigBuilder().tracking(false).logGatheringOn("stored_gather_id", "ewidv", 40).build()).toString()); + server.pending(); + init(TestUtils.getConfigSdkBehaviorSettings()); + + Assert.assertFalse(provider().getTrackingEnabled()); + Assert.assertEquals(ConfigurationProvider.LogGatheringState.UNDECIDED, provider().getLogGatheringState()); + Assert.assertNull(provider().getLogGatheringId()); + Assert.assertEquals(ModuleConfiguration.logGatheringAllLevels, provider().getLogGatheringLevels()); + Assert.assertEquals(ModuleConfiguration.logGatheringDefaultBatchSize, provider().getLogGatheringBatchSize()); + Assert.assertFalse(storedConfig().has("lg")); + Countly.instance().stop(); + + init(TestUtils.getConfigSdkBehaviorSettings()); + Assert.assertEquals(ConfigurationProvider.LogGatheringState.UNDECIDED, provider().getLogGatheringState()); + Countly.instance().stop(); + + server.failing(); + init(TestUtils.getConfigSdkBehaviorSettings()); + assertNotGathering(); + Countly.instance().halt(); + + server = new ServerConfigResponder(); + init(TestUtils.getConfigSdkBehaviorSettings() + .disableSdkBehaviorSettingsUpdates() + .setSdkBehaviorSettings(new ServerConfigBuilder().logGatheringOn("provided_gather_id", "ew", 20).build())); + assertNotGathering(); + Assert.assertTrue(server.requests.isEmpty()); + } + + /** + * A queue held back by {@code networking: false} drains as soon as a response allows networking + * again, without waiting for another request or for the global timer. + *

+ * Verifies against a local server that nothing is sent while networking is off and that both held + * requests arrive once it is back on. + */ + @Test + public void networking_turningBackOn_drainsTheRequestsItHeldBack() throws Exception { + AtomicInteger received = new AtomicInteger(); + HttpServer httpServer = HttpServer.create(new InetSocketAddress("localhost", 0), 0); + httpServer.createContext("/", exchange -> { + if (exchange.getRequestURI().getPath().startsWith("/i")) { + received.incrementAndGet(); + } + byte[] body = "{\"result\":\"Success\"}".getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, body.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(body); + } + }); + httpServer.start(); + + try { + Config config = new Config("http://localhost:" + httpServer.getAddress().getPort(), TestUtils.SERVER_APP_KEY, TestUtils.getTestSDirectory()) + .setApplicationVersion(TestUtils.APPLICATION_VERSION) + .setCustomDeviceId(TestUtils.DEVICE_ID) + .enableFeatures(Config.Feature.Events) + .setEventQueueSizeToSend(1) + .setSdkBehaviorSettings(new ServerConfigBuilder().networking(false).build()); + server.pending(); + init(config); + + Countly.instance().events().recordEvent("held_1"); + Countly.instance().events().recordEvent("held_2"); + Assert.assertEquals(2, TestUtils.getCurrentRQ().length); + //a queue that ignored the switch would have sent the first request well within this + Thread.sleep(1000); + Assert.assertEquals(0, received.get()); + Assert.assertEquals(2, TestUtils.getCurrentRQ().length); + + push(new ServerConfigBuilder().networking(true)); + + Assert.assertTrue("the held requests never drained", waitFor(30_000, () -> received.get() >= 2 && TestUtils.getCurrentRQ().length == 0)); + Assert.assertEquals(2, received.get()); + } finally { + Countly.instance().halt(); + httpServer.stop(0); + } + } + + // endregion + // region helpers + + /** + * Stands in for the settings endpoint of the server: records every immediate request the SDK + * makes and answers it on the calling thread with the response set at that moment. + */ + static final class ServerConfigResponder implements ImmediateRequestGenerator { + final List> requests = new CopyOnWriteArrayList<>(); + final List endpoints = new CopyOnWriteArrayList<>(); + final List networkingFlags = new CopyOnWriteArrayList<>(); + private volatile String response = null; + private volatile boolean answering = true; + private volatile long delayMs = 0; + + /** + * Answers every request with the given payload. + * + * @param builder the payload + * @return this responder + */ + ServerConfigResponder respondWith(ServerConfigBuilder builder) { + return respondWith(builder.build()); + } + + /** + * Answers every request with the given JSON text. + * + * @param json the response + * @return this responder + */ + ServerConfigResponder respondWith(String json) { + response = json; + answering = true; + return this; + } + + /** + * Answers every request as a failed one. + * + * @return this responder + */ + ServerConfigResponder failing() { + response = null; + answering = true; + return this; + } + + /** + * Never answers, as a server that has not answered yet. + * + * @return this responder + */ + ServerConfigResponder pending() { + answering = false; + return this; + } + + /** + * Waits before answering. + * + * @param delayMs how long, in milliseconds + * @return this responder + */ + ServerConfigResponder delayedBy(long delayMs) { + this.delayMs = delayMs; + return this; + } + + /** + * A request maker that records the request and answers it. + * + * @return the request maker + */ + @Override + public ImmediateRequestI createImmediateRequestMaker() { + return (requestData, customEndpoint, transport, requestShouldBeDelayed, networkingIsEnabled, callback, log) -> { + requests.add(parseParams(requestData)); + endpoints.add(customEndpoint); + networkingFlags.add(networkingIsEnabled); + if (!answering) { + return; + } + if (delayMs > 0) { + try { + Thread.sleep(delayMs); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + String current = response; + callback.callback(current == null ? null : new JSONObject(current)); + }; + } + + /** + * Decodes url encoded request parameters. + * + * @param requestData the parameters + * @return the parameters by name + */ + private static Map parseParams(String requestData) { + Map params = new HashMap<>(); + for (String pair : requestData.split("&")) { + String[] keyValue = pair.split("=", 2); + params.put(Utils.urldecode(keyValue[0]), keyValue.length > 1 ? Utils.urldecode(keyValue[1]) : ""); + } + return params; + } + } + + /** + * Initializes the SDK with {@link #server} answering its settings requests. + * + * @param config the configuration + */ + private void init(Config config) { + InternalConfig internalConfig = new InternalConfig(config); + internalConfig.immediateRequestGenerator = server; + Countly.instance().init(internalConfig); + } + + /** + * Answers the next settings request with the given payload and makes the SDK fetch, as the + * refresh timer does. + * + * @param builder the payload + */ + private void push(ServerConfigBuilder builder) { + push(builder.build()); + } + + /** + * Answers the next settings request with the given JSON text and makes the SDK fetch. + * + * @param json the response + */ + private void push(String json) { + server.respondWith(json); + module().fetchConfigFromServer(SDKCore.instance.config); + } + + /** + * The configuration module of the running SDK. + * + * @return the module + */ + private static ModuleConfiguration module() { + return SDKCore.instance.module(ModuleConfiguration.class); + } + + /** + * The settings in effect in the running SDK. + * + * @return the provider + */ + private static ConfigurationProvider provider() { + return SDKCore.instance.config.getConfigurationProvider(); + } + + /** + * The settings as stored on disk. + * + * @return the stored settings, {@code null} when nothing is stored + */ + private static JSONObject storedConfig() { + String stored = TestUtils.readJsonFile(SDKStorage.JSON_FILE_NAME).optString("sc", null); + return stored == null ? null : new JSONObject(stored); + } + + /** + * A developer configuration that sets every value the precedence test follows. + * + * @return the configuration + */ + private static Config developerConfig() { + return TestUtils.getConfigSdkBehaviorSettings() + .setEventQueueSizeToSend(7) + .setRequestQueueMaxSize(50) + .setUpdateSessionTimerDelay(30) + .setMaxBreadcrumbCount(40) + .setLoggingLevel(Config.LoggingLevel.ERROR); + } + + /** + * A test module that counts the ticks of the global timer and the configuration changes the SDK + * dispatches to every module. + */ + private static final class CountingModule extends ModuleBase { + final AtomicInteger changes = new AtomicInteger(); + final AtomicInteger ticks = new AtomicInteger(); + + /** + * Counts a tick of the global timer. + */ + @Override + protected void onTimer() { + ticks.incrementAndGet(); + } + + /** + * Counts a dispatched configuration change. + * + * @param config configuration of the running SDK + */ + @Override + protected void onSdkConfigurationChanged(InternalConfig config) { + changes.incrementAndGet(); + } + } + + /** + * Installs a {@link CountingModule} for the next init. + * + * @return the module + */ + private static CountingModule installCountingModule() { + CountingModule module = new CountingModule(); + SDKCore.testDummyModule = module; + return module; + } + + /** + * Every settings key the module declares, read off its {@code keyR} constants. + * + * @return the settings keys, without the top level keys + */ + private static List settingsKeysOfTheModule() throws IllegalAccessException { + List keys = new ArrayList<>(); + for (Field field : ModuleConfiguration.class.getDeclaredFields()) { + if (field.getName().startsWith("keyR") && Modifier.isStatic(field.getModifiers())) { + String key = (String) field.get(null); + if (!TOP_LEVEL_KEYS.contains(key)) { + keys.add(key); + } + } + } + return keys; + } + + /** + * Runs a settings object through the validation of a response. + * + * @param module the module that validates + * @param settings the settings object, as JSON text + * @return the settings left after validation + */ + private static JSONObject validated(ModuleConfiguration module, String settings) { + JSONObject envelope = new JSONObject("{\"v\":1,\"t\":1,\"c\":" + settings + "}"); + Assert.assertTrue(module.validateServerConfig(envelope)); + return envelope.getJSONObject("c"); + } + + /** + * Asserts whether validation keeps one setting. + * + * @param module the module that validates + * @param key the settings key + * @param literal the value, as JSON text + * @param kept whether the setting must be kept + */ + private static void assertKeptByValidation(ModuleConfiguration module, String key, String literal, boolean kept) { + JSONObject settings = validated(module, "{\"" + key + "\":" + literal + "}"); + Assert.assertEquals("[" + key + "] = " + literal, kept, settings.has(key)); + } + + /** + * Asserts the kind and the names of a filter. + * + * @param filter the filter + * @param isWhitelist the expected kind + * @param expected the expected names + */ + private static void assertFilter(ConfigurationProvider.FilterList> filter, boolean isWhitelist, Set expected) { + Assert.assertEquals(isWhitelist, filter.isWhitelist()); + Assert.assertEquals(expected, filter.getFilterList()); + } + + /** + * Asserts that a reader cannot change a collection. + * + * @param collection the collection + */ + private static void assertUnmodifiable(Collection collection) { + try { + collection.add("added_by_a_reader"); + Assert.fail("a reader can change " + collection); + } catch (UnsupportedOperationException expected) { + Assert.assertFalse(collection.contains("added_by_a_reader")); + } + } + + /** + * Asserts that log gathering is on with the given directive. + * + * @param gatherId the gather id + * @param levels the levels + * @param batchSize the batch size + */ + private static void assertGathering(String gatherId, String levels, int batchSize) { + Assert.assertEquals(ConfigurationProvider.LogGatheringState.GATHERING, provider().getLogGatheringState()); + Assert.assertEquals(gatherId, provider().getLogGatheringId()); + Assert.assertEquals(levels, provider().getLogGatheringLevels()); + Assert.assertEquals(batchSize, provider().getLogGatheringBatchSize()); + } + + /** + * Asserts that log gathering was decided off and nothing of a previous directive is left. + */ + private static void assertNotGathering() { + Assert.assertEquals(ConfigurationProvider.LogGatheringState.NOT_GATHERING, provider().getLogGatheringState()); + Assert.assertNull(provider().getLogGatheringId()); + Assert.assertEquals(ModuleConfiguration.logGatheringAllLevels, provider().getLogGatheringLevels()); + Assert.assertEquals(ModuleConfiguration.logGatheringDefaultBatchSize, provider().getLogGatheringBatchSize()); + } + + /** + * Polls until the condition holds or the budget runs out. + * + * @param timeoutMs the budget + * @param condition the condition + * @return whether the condition holds + */ + private static boolean waitFor(long timeoutMs, BooleanSupplier condition) throws InterruptedException { + long deadline = System.currentTimeMillis() + timeoutMs; + while (System.currentTimeMillis() < deadline) { + if (condition.getAsBoolean()) { + return true; + } + Thread.sleep(50); + } + return condition.getAsBoolean(); + } + + // endregion +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConnectionTestTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConnectionTestTests.java new file mode 100644 index 000000000..1ef6782a1 --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleConnectionTestTests.java @@ -0,0 +1,1433 @@ +package ly.count.sdk.java.internal; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.nio.charset.StandardCharsets; +import java.security.KeyPairGenerator; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.net.ssl.HttpsURLConnection; +import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; +import ly.count.sdk.java.internal.ModuleConnectionTest.ProbeOutcome; +import ly.count.sdk.java.internal.ModuleConnectionTest.ResultRow; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import static ly.count.sdk.java.internal.ModuleConnectionTest.keyResults; +import static ly.count.sdk.java.internal.ServerConfigBuilder.names; + +/** + * The connection test a live SDK behavior settings response arms with its top level {@code ct} + * flag: one battery of parameterless GET probes against every endpoint the SDK depends on, graded + * and queued as one {@code ct_results} report. + *

+ * Settings requests go through a {@link ModuleConfigurationTests.ServerConfigResponder}, which + * answers on the calling thread, so a response to the fetch made at init arms the test before init + * returns. Probes go to a local HTTP server that answers every path the way a Countly server behind + * the path prefix {@value #PREFIX} does. It refuses the SDK's own requests, which carry the app key, + * so the report stays in the request queue, where {@link TestUtils#getCurrentRQ()} reads it. A test + * that needs short deadlines or a fake probe transport sets them through the test hooks before it + * arms the test; no wait relies on the 10 second probe timeout or on the 60 second SDK timer. + */ +@RunWith(JUnit4.class) +public class ModuleConnectionTestTests { + + private static final String PREFIX = "/countly"; + private static final String[] EXPECTED_ORDER = { + "core", "core-write", "sc", "rc", "ab", "feedback", "feedback-widget", "feedback-submit", "content", "feedback-page", "feedback-assets", "content-page" + }; + private static final List EXPECTED_PATHS = Arrays.asList( + "/o/ping", "/i", "/o/sdk?method=rc", "/o/sdk?method=ab_fetch_variants", "/o/sdk?method=feedback", + "/o/surveys/nps/widget", "/o/surveys/survey/widget", "/o/feedback/widget", "/i/feedback/inputs", "/o/sdk/content", + "/feedback/nps", "/feedback/survey", "/feedback/rating", "/surveys/images/ct-probe.png", "/star-rating/images/ct-probe.png", + "/_external/content/"); + private static final Set ROW_KEYS = names("f", "ok", "st", "ms", "e", "n"); + private static final String MISSING_PARAMETER = "{\"result\":\"Missing parameter \\\"app_key\\\" or \\\"device_id\\\"\"}"; + private static final String NOT_RUN = "not run: battery cap"; + + private static final String BATTERY_STARTED = "[ModuleConnectionTest] startBattery, the server asked for a connection test"; + private static final String ALREADY_RUNNING = "[ModuleConnectionTest] startBattery, a battery is already running"; + private static final String NETWORKING_DISABLED = "[ModuleConnectionTest] startBattery, networking is disabled"; + private static final String REPORT_DROPPED = "[ModuleConnectionTest] runBatteryAndReport, the SDK stopped during the battery, dropping the report"; + + private static final long WAIT_BUDGET_MS = 30_000; + private static final long POLL_MS = 20; + + private ModuleConfigurationTests.ServerConfigResponder settings; + private ProbeServer server; + private final List logs = new CopyOnWriteArrayList<>(); + + /** + * Starts every test from empty storage, without a test module, with a fresh settings responder + * and a fresh local server. + * + * @throws IOException when the local server cannot start + */ + @Before + public void beforeTest() throws IOException { + TestUtils.createCleanTestState(); + SDKCore.testDummyModule = null; + settings = new ModuleConfigurationTests.ServerConfigResponder(); + server = new ProbeServer(); + logs.clear(); + } + + /** + * Stops the SDK, clearing its data, then the local server. + */ + @After + public void afterTest() { + Countly.instance().halt(); + server.stop(); + } + + // region scenarios + + /** + * A healthy server behind a path prefix, armed by the response to the fetch made at init. + *

+ * Verifies that the battery reports every row reachable, in table order, with the status a + * Countly server answers a bare request with; that the report is one queued request of its own + * carrying the SDK identity and the required parameters and nothing else; that each of the 16 + * probes is a bare GET resolved against the prefix, with a single slash at the join although + * the configured URL ends in slashes, carrying only the method selector, the marker and the + * cache buster, no body and the custom request headers; that the flag is never stored while the + * rest of the response applies; and that the report then rides the queue to the server. + */ + @Test + public void armed_healthyServer_reportsEveryRowReachable_fromBareProbesResolvedAgainstThePathPrefix() throws Exception { + Map headers = new HashMap<>(); + headers.put("X-Countly-Test", "yes"); + settings.respondWith(new ServerConfigBuilder().viewTracking(false).connectionTest(1)); + init(config(server.url(PREFIX + "//")).addCustomNetworkRequestHeaders(headers)); + awaitBatteryIdle(connectionTest()); + + Map queued = onlyQueuedReport(); + TestUtils.validateRequiredParams(queued); + for (String param : Arrays.asList("events", "begin_session", "end_session", "session_id", "metrics", "method", "user_details")) { + Assert.assertFalse("the report carries [" + param + "]", queued.containsKey(param)); + } + + JSONObject report = new JSONObject(queued.get(keyResults)); + Assert.assertEquals(names("ts", "sdk", "results"), report.keySet()); + Assert.assertTrue(report.getLong("ts") > 0); + Assert.assertEquals(TestUtils.SDK_NAME, report.getJSONObject("sdk").getString("name")); + Assert.assertEquals(TestUtils.SDK_VERSION, report.getJSONObject("sdk").getString("version")); + assertRowOrder(report); + Map rows = rowsByFeature(report); + assertRow(rows.get("core"), true, 200, null, null); + assertRow(rows.get("core-write"), true, 400, null, null); + assertRow(rows.get("sc"), true, 200, null, null); + assertRow(rows.get("rc"), true, 400, null, null); + assertRow(rows.get("ab"), true, 400, null, null); + assertRow(rows.get("feedback"), true, 400, null, null); + assertRow(rows.get("feedback-widget"), true, 400, null, 3); + assertRow(rows.get("feedback-submit"), true, 400, null, null); + assertRow(rows.get("content"), true, 400, null, null); + assertRow(rows.get("feedback-page"), true, 200, null, 3); + assertRow(rows.get("feedback-assets"), true, 200, null, 2); + assertRow(rows.get("content-page"), true, 200, null, null); + + List probedPaths = new ArrayList<>(); + for (Received probe : server.probes) { + Assert.assertEquals("GET", probe.method); + Assert.assertTrue(probe.path, probe.path.startsWith(PREFIX + "/")); + Assert.assertFalse(probe.path, probe.path.contains("//")); + Assert.assertTrue(probe.rawQuery, probe.rawQuery.matches("(method=[a-z_]+&)?ct=1&_=\\d+")); + Assert.assertEquals(0, probe.bodyLength); + Assert.assertEquals("yes", probe.headers.get("x-countly-test")); + String method = probe.params.get("method"); + probedPaths.add(probe.path.substring(PREFIX.length()) + (method == null ? "" : "?method=" + method)); + } + Assert.assertEquals(EXPECTED_PATHS, probedPaths); + + Assert.assertEquals(names("v", "t", "c"), storedConfig().keySet()); + Assert.assertFalse(provider().getViewTrackingEnabled()); + + Assert.assertTrue("the report never reached the server", waitFor(() -> !reportsSentToTheServer().isEmpty())); + Received sent = reportsSentToTheServer().get(0); + Assert.assertEquals(queued.get(keyResults), sent.params.get(keyResults)); + Assert.assertEquals("yes", sent.headers.get("x-countly-test")); + } + + /** + * A server that fails in every way the grading tells apart. + *

+ * Verifies that {@code /o/ping} answering {@code 404 DB Error} and an image route answering 404 + * are faults on the two rows that need a 2xx, that a 403, a 5xx and a redirect are faults on any + * row, each with its own {@code e}, that a combined row keeps probing after its first failing + * path and reports that path's status, and that the redirect is read as a 3xx and never + * followed. + */ + @Test + public void armed_brokenServer_gradesEveryFailureToItsReason_andNeverFollowsARedirect() throws Exception { + server.overrides.put(PREFIX + "/o/ping", Answer.json(404, "{\"result\":\"DB Error\"}")); + server.overrides.put(PREFIX + "/i", Answer.page(403, "text/html", "forbidden")); + server.overrides.put(PREFIX + "/o/sdk", Answer.json(500, "{\"result\":\"boom\"}")); + server.overrides.put(PREFIX + "/o/surveys/survey/widget", Answer.redirect(PREFIX + "/o/ping")); + server.overrides.put(PREFIX + "/star-rating/images/ct-probe.png", Answer.page(404, "text/html", "no such image")); + server.overrides.put(PREFIX + "/feedback/rating", Answer.page(502, "text/html", "bad gateway")); + settings.respondWith(new ServerConfigBuilder().connectionTest(true)); + init(config(server.url(PREFIX))); + awaitBatteryIdle(connectionTest()); + + JSONObject report = new JSONObject(onlyQueuedReport().get(keyResults)); + assertRowOrder(report); + Map rows = rowsByFeature(report); + assertRow(rows.get("core"), false, 404, "HTTP 404", null); + assertRow(rows.get("core-write"), false, 403, "HTTP 403", null); + assertRow(rows.get("sc"), true, 200, null, null); + assertRow(rows.get("rc"), false, 500, "HTTP 500", null); + assertRow(rows.get("ab"), false, 500, "HTTP 500", null); + assertRow(rows.get("feedback"), false, 500, "HTTP 500", null); + assertRow(rows.get("feedback-widget"), false, 302, "redirected", 3); + assertRow(rows.get("feedback-submit"), true, 400, null, null); + assertRow(rows.get("content"), true, 400, null, null); + assertRow(rows.get("feedback-page"), false, 502, "HTTP 502", 3); + assertRow(rows.get("feedback-assets"), false, 404, "HTTP 404", 2); + assertRow(rows.get("content-page"), true, 200, null, null); + + Assert.assertEquals(16, server.probes.size()); + Assert.assertEquals(1, probesTo(PREFIX + "/o/ping")); + Assert.assertEquals(1, probesTo(PREFIX + "/o/feedback/widget")); + } + + /** + * A response without the flag, or with a falsy one. + *

+ * Verifies, for an absent flag and for {@code 0}, {@code false}, {@code "0"}, {@code "false"}, + * {@code ""} and {@code null}, each delivered by the fetch made at init, that no battery starts, + * no probe reaches the server and no report is queued, while the settings of the same response + * apply and the flag is never stored. + */ + @Test + public void notArmed_anAbsentOrFalsyFlag_runsNothing_whileTheSettingsStillApply() throws Exception { + Object[] variants = { null, 0, false, "0", "false", "", JSONObject.NULL }; + for (Object variant : variants) { + String label = "ct = " + (variant == null ? "absent" : JSONObject.valueToString(variant)); + TestUtils.createCleanTestState(); + ServerConfigBuilder response = new ServerConfigBuilder().viewTracking(false); + if (variant != null) { + response.connectionTest(variant); + } + settings.respondWith(response); + init(config(server.url(PREFIX))); + + Assert.assertFalse(label, provider().getViewTrackingEnabled()); + Assert.assertFalse(label, connectionTest().batteryRunning.get()); + Assert.assertEquals(label, 0, logsContaining(BATTERY_STARTED)); + Assert.assertEquals(label, names("v", "t", "c"), storedConfig().keySet()); + Assert.assertTrue(label, queuedReports().isEmpty()); + } + + Assert.assertEquals(variants.length, settings.requests.size()); + Assert.assertTrue(server.probes.isEmpty()); + } + + /** + * An armed response that also switches networking off. + *

+ * Verifies that the battery is skipped, so no probe and no report go out, and that nothing about + * the skipped test is kept: the next armed response, which allows networking again, runs the + * battery and queues its report. + */ + @Test + public void armed_whileNetworkingIsDisabled_skipsTheBattery_andTheNextArmedResponseRunsIt() throws Exception { + settings.respondWith(new ServerConfigBuilder().networking(false).connectionTest(1)); + init(config(server.url(PREFIX))); + ModuleConnectionTest module = connectionTest(); + + Assert.assertFalse(provider().getNetworkingEnabled()); + Assert.assertFalse(module.batteryRunning.get()); + Assert.assertEquals(1, logsContaining(NETWORKING_DISABLED)); + Assert.assertEquals(0, logsContaining(BATTERY_STARTED)); + Assert.assertTrue(queuedReports().isEmpty()); + Assert.assertTrue(server.probes.isEmpty()); + + push(new ServerConfigBuilder().networking(true).connectionTest(1)); + awaitBatteryIdle(module); + + Assert.assertEquals(16, server.probes.size()); + assertRowOrder(new JSONObject(onlyQueuedReport().get(keyResults))); + } + + /** + * An armed SDK whose server refuses every connection. + *

+ * Verifies that every probed row is a transport error with status 0, keeping its path count, + * that the {@code sc} row still carries the measured settings request, and that the report is + * queued with the SDK identity and stays queued after the queue failed to send it. + */ + @Test + public void armed_serverDown_reportsATransportErrorOnEveryProbedRow_andTheReportStaysQueued() throws Exception { + settings.respondWith(new ServerConfigBuilder().connectionTest("1")); + init(config(deadUrl())); + awaitBatteryIdle(connectionTest()); + + Assert.assertTrue("the queue never tried to send the report, logs: " + logs, + waitFor(() -> logs.stream().anyMatch(line -> line.contains("Error while sending request") && line.contains(keyResults)))); + Map queued = onlyQueuedReport(); + Assert.assertEquals(TestUtils.SERVER_APP_KEY, queued.get("app_key")); + Assert.assertEquals(TestUtils.DEVICE_ID, queued.get("device_id")); + + JSONObject report = new JSONObject(queued.get(keyResults)); + assertRowOrder(report); + Map rows = rowsByFeature(report); + Map pathCounts = new HashMap<>(); + pathCounts.put("feedback-widget", 3); + pathCounts.put("feedback-page", 3); + pathCounts.put("feedback-assets", 2); + for (String feature : EXPECTED_ORDER) { + if ("sc".equals(feature)) { + assertRow(rows.get(feature), true, 200, null, null); + } else { + assertRow(rows.get(feature), false, 0, "transport error", pathCounts.get(feature)); + } + } + } + + /** + * An endpoint that accepts the connection but never answers. + *

+ * Verifies with a one second per request timeout that the silent endpoint is reported as a + * timeout with status 0 after at least the timeout, while the rows around it are unaffected. + */ + @Test + public void armed_silentEndpoint_reportsATimeout_andTheOtherRowsAreUnaffected() throws Exception { + server.overrides.put(PREFIX + "/o/sdk/content", Answer.SILENT); + settings.pending(); + init(config(server.url(PREFIX))); + ModuleConnectionTest module = connectionTest(); + module.perRequestTimeoutMs = 1_000; + + push(new ServerConfigBuilder().connectionTest(1)); + awaitBatteryIdle(module); + + Map rows = rowsByFeature(new JSONObject(onlyQueuedReport().get(keyResults))); + JSONObject content = rows.get("content"); + assertRow(content, false, 0, "timeout", null); + Assert.assertTrue("ms " + content.getLong("ms"), content.getLong("ms") >= 1_000); + assertRow(rows.get("core"), true, 200, null, null); + assertRow(rows.get("feedback-submit"), true, 400, null, null); + assertRow(rows.get("feedback-page"), true, 200, null, 3); + assertRow(rows.get("content-page"), true, 200, null, null); + } + + /** + * Deliveries that overlap a running battery, and one after it. + *

+ * Verifies that a delivery while a battery runs is ignored, that the battery runs on a daemon + * thread named {@value ModuleConnectionTest#THREAD_NAME}, never on the thread that delivered the + * response, and hands every probe the transport of the queued requests, and that a delivery after + * the battery finished runs it again with the latency of its own settings request. + */ + @Test + public void aDeliveryWhileABatteryRuns_isIgnored_andOneAfterItRunsAgain_onADaemonThreadOfItsOwn() throws Exception { + settings.pending(); + init(config(server.url(PREFIX))); + ModuleConnectionTest module = connectionTest(); + FakeTransport first = FakeTransport.gated(); + module.transport = first; + + push(new ServerConfigBuilder().connectionTest(1)); + Assert.assertTrue(first.firstProbeStarted.await(WAIT_BUDGET_MS, TimeUnit.MILLISECONDS)); + Assert.assertTrue(module.batteryRunning.get()); + + push(new ServerConfigBuilder().connectionTest(true)); + push(new ServerConfigBuilder().connectionTest("yes")); + Assert.assertEquals(2, logsContaining(ALREADY_RUNNING)); + Assert.assertEquals(1, first.urls.size()); + + first.gate.countDown(); + awaitBatteryIdle(module); + Assert.assertEquals(16, first.urls.size()); + Assert.assertEquals(Collections.singleton(ModuleConnectionTest.THREAD_NAME), first.threadNames); + Assert.assertFalse(first.daemonFlags.contains(false)); + Transport queueTransport = SDKCore.instance.networking.getTransport(); + Assert.assertNotNull(queueTransport); + for (Transport used : first.transports) { + Assert.assertSame(queueTransport, used); + } + Assert.assertEquals(1, queuedReports().size()); + + FakeTransport second = FakeTransport.instant(1); + module.transport = second; + settings.delayedBy(80); + push(new ServerConfigBuilder().connectionTest(1)); + awaitBatteryIdle(module); + + Assert.assertEquals(16, second.urls.size()); + Assert.assertEquals(2, logsContaining(BATTERY_STARTED)); + List> reports = queuedReports(); + Assert.assertEquals(2, reports.size()); + long latencyMs = rowsByFeature(new JSONObject(reports.get(1).get(keyResults))).get("sc").getLong("ms"); + Assert.assertTrue("sc ms " + latencyMs, latencyMs >= 70); + } + + /** + * The SDK stops while a battery runs. + *

+ * Verifies that the module listens to the configuration module of its SDK from init and stops + * listening on stop, that the stopped battery ends before its next row and queues no report, + * not even into the queue of an SDK started again meanwhile, and that the stopped module refuses + * a later delivery. + */ + @Test + public void stop_duringABattery_endsItBeforeTheNextRow_queuesNoReport_andStopsListening() throws Exception { + settings.pending(); + init(config(server.url(PREFIX))); + ModuleConnectionTest module = connectionTest(); + ModuleConfiguration configuration = SDKCore.instance.module(ModuleConfiguration.class); + Assert.assertSame(module, SDKCore.instance.modules.get(0)); + Assert.assertSame(module, configuration.connectionTestListener); + FakeTransport gated = FakeTransport.gated(); + module.transport = gated; + + push(new ServerConfigBuilder().connectionTest(1)); + Assert.assertTrue(gated.firstProbeStarted.await(WAIT_BUDGET_MS, TimeUnit.MILLISECONDS)); + Countly.instance().stop(); + + Assert.assertTrue(module.halted); + Assert.assertNull(configuration.connectionTestListener); + + //started before the stopped battery moves on, so a report it queued would land in this queue + settings.pending(); + init(config(server.url(PREFIX))); + gated.gate.countDown(); + awaitBatteryIdle(module); + + Assert.assertEquals(1, gated.urls.size()); + Assert.assertEquals(1, logsContaining(REPORT_DROPPED)); + Assert.assertTrue(queuedReports().isEmpty()); + + module.onConnectionTestRequested(5); + Assert.assertFalse(module.batteryRunning.get()); + Assert.assertEquals(1, gated.urls.size()); + Assert.assertNotSame(module, connectionTest()); + Assert.assertSame(connectionTest(), SDKCore.instance.module(ModuleConfiguration.class).connectionTestListener); + } + + /** + * The battery cap, attempted requests times the per request timeout plus the extra time. + *

+ * Verifies with a 160 ms cap and probes that take 40 ms each that the first row is always + * probed, that the {@code sc} row is never capped, that once the cap is reached every later + * probed row is reported as not run, with status 0, 0 ms and no path count, that no probe is + * issued for those rows, and that the report still goes out. + */ + @Test + public void batteryCap_reportsEveryRowItIsReachedBeforeAsNotRun_andTheReportStillGoesOut() throws Exception { + settings.pending(); + init(config(server.url(PREFIX))); + ModuleConnectionTest module = connectionTest(); + module.perRequestTimeoutMs = 10; + module.batteryCapExtraMs = 0; + FakeTransport slow = FakeTransport.slow(40); + module.transport = slow; + + push(new ServerConfigBuilder().connectionTest(1)); + awaitBatteryIdle(module); + + JSONObject report = new JSONObject(onlyQueuedReport().get(keyResults)); + assertRowOrder(report); + JSONArray results = report.getJSONArray("results"); + assertRow(results.getJSONObject(0), true, 200, null, null); + assertRow(results.getJSONObject(2), true, 200, null, null); + + boolean capReached = false; + int probedPaths = 0; + for (int i = 0; i < results.length(); i++) { + JSONObject row = results.getJSONObject(i); + String feature = row.getString("f"); + if ("sc".equals(feature)) { + continue; + } + if (NOT_RUN.equals(row.optString("e"))) { + capReached = true; + assertRow(row, false, 0, NOT_RUN, null); + Assert.assertEquals(feature, 0, row.getLong("ms")); + } else { + Assert.assertFalse(feature + " was probed after the cap was reached", capReached); + Assert.assertTrue(feature, row.getBoolean("ok")); + probedPaths += row.optInt("n", 1); + } + } + Assert.assertTrue(capReached); + Assert.assertEquals(NOT_RUN, results.getJSONObject(results.length() - 1).getString("e")); + Assert.assertEquals(probedPaths, slow.urls.size()); + Assert.assertTrue(slow.urls.size() < 16); + } + + /** + * The grading table. + *

+ * Verifies that a 2xx is reached, that a 4xx other than 403 is reached except on a row that + * needs a 2xx, that a redirect, a 403, a 5xx and an informational status are faults with their + * {@code e}, and that no status reports its failure, a transport error when none is known. + */ + @Test + public void grade_followsTheGradingTable() { + Object[][] cases = { + // status, failure, requires a 2xx, expected e (null when reached) + { 200, null, false, null }, { 204, null, false, null }, { 400, null, false, null }, { 404, null, false, null }, + { 499, null, false, null }, { 403, null, false, "HTTP 403" }, { 500, null, false, "HTTP 500" }, { 502, null, false, "HTTP 502" }, + { 503, null, false, "HTTP 503" }, { 301, null, false, "redirected" }, { 302, null, false, "redirected" }, + { 307, null, false, "redirected" }, { 308, null, false, "redirected" }, { 100, null, false, "HTTP 100" }, + { 0, "timeout", false, "timeout" }, { 0, "transport error", false, "transport error" }, { 0, null, false, "transport error" }, + { -1, null, false, "transport error" }, + { 200, null, true, null }, { 299, null, true, null }, { 400, null, true, "HTTP 400" }, { 404, null, true, "HTTP 404" }, + { 403, null, true, "HTTP 403" }, { 302, null, true, "redirected" }, { 500, null, true, "HTTP 500" }, { 0, "timeout", true, "timeout" }, + }; + for (Object[] c : cases) { + ProbeOutcome outcome = new ProbeOutcome(); + outcome.status = (int) c[0]; + outcome.failure = (String) c[1]; + Assert.assertEquals("status " + c[0] + ", requires a 2xx " + c[2], c[3], ModuleConnectionTest.grade(outcome, (boolean) c[2])); + } + } + + /** + * Probe URLs. + *

+ * Verifies that a path resolves against the configured URL with its path prefix kept, trailing + * slashes stripped and exactly one slash at the join, that the marker and the cache buster follow + * a {@code ?}, or an {@code &} after the method selector of a path that has one, and that the + * cache buster is the current time. + */ + @Test + public void buildProbeUrl_keepsThePathPrefix_stripsTrailingSlashes_andAppendsTheMarkerAndTheCacheBuster() { + long before = System.currentTimeMillis(); + String plain = ModuleConnectionTest.buildProbeUrl("https://x.com", "/o/ping"); + long after = System.currentTimeMillis(); + Assert.assertTrue(plain, plain.startsWith("https://x.com/o/ping?ct=1&_=")); + long cacheBuster = Long.parseLong(plain.substring(plain.indexOf("_=") + 2)); + Assert.assertTrue(cacheBuster >= before && cacheBuster <= after); + + Assert.assertTrue(ModuleConnectionTest.buildProbeUrl("https://x.com/countly", "/o/ping").startsWith("https://x.com/countly/o/ping?ct=1&_=")); + Assert.assertTrue(ModuleConnectionTest.buildProbeUrl("https://x.com/countly/", "/o/ping").startsWith("https://x.com/countly/o/ping?ct=1&_=")); + Assert.assertTrue(ModuleConnectionTest.buildProbeUrl("https://x.com/countly///", "o/ping").startsWith("https://x.com/countly/o/ping?ct=1&_=")); + Assert.assertTrue(ModuleConnectionTest.buildProbeUrl("http://127.0.0.1:8080/a/b/", "/_external/content/").startsWith("http://127.0.0.1:8080/a/b/_external/content/?ct=1&_=")); + + String withSelector = ModuleConnectionTest.buildProbeUrl("https://x.com/countly/", "/o/sdk?method=rc"); + Assert.assertTrue(withSelector, withSelector.matches("https://x\\.com/countly/o/sdk\\?method=rc&ct=1&_=\\d+")); + } + + /** + * The caps of the report. + *

+ * Verifies that a report keeps at most 32 rows, that one over 8 KB loses every {@code e} except + * {@code opaque} before any row, that a small one keeps its {@code e} cut at 256 characters, and + * that rows too large even without their {@code e} are dropped from the end, the size counted in + * UTF-8 bytes rather than characters. + */ + @Test + public void buildReport_keepsAtMost32Rows_within8KB_dropsErrorsBeforeRows_andOpaqueSurvives() { + init(TestUtils.getBaseConfig()); + ModuleConnectionTest module = connectionTest(); + String longError = repeat('x', 300); + + List rows = new ArrayList<>(); + for (int i = 0; i < 40; i++) { + rows.add(resultRow("row" + i, false, 403, i, longError, 1)); + } + rows.set(5, resultRow("opaque-row", true, 0, 3, "opaque", 1)); + + JSONObject report = new JSONObject(module.buildReport(rows)); + JSONArray results = report.getJSONArray("results"); + Assert.assertEquals(32, results.length()); + Assert.assertTrue(ModuleConnectionTest.utf8Length(report.toString()) <= 8 * 1024); + for (int i = 0; i < results.length(); i++) { + JSONObject row = results.getJSONObject(i); + if (i == 5) { + Assert.assertEquals("opaque-row", row.getString("f")); + Assert.assertEquals("opaque", row.getString("e")); + } else { + Assert.assertEquals("row" + i, row.getString("f")); + Assert.assertFalse(row.has("e")); + Assert.assertEquals(403, row.getInt("st")); + Assert.assertEquals(i, row.getLong("ms")); + } + } + + JSONObject small = new JSONObject(module.buildReport(Collections.singletonList(resultRow("core", false, 500, 10, longError, 1)))); + JSONObject row = small.getJSONArray("results").getJSONObject(0); + Assert.assertEquals(longError.substring(0, 256), row.getString("e")); + Assert.assertEquals(500, row.getInt("st")); + Assert.assertFalse(row.has("n")); + Assert.assertTrue(small.getLong("ts") > 0); + Assert.assertEquals(TestUtils.SDK_NAME, small.getJSONObject("sdk").getString("name")); + + List wide = new ArrayList<>(); + JSONArray untrimmed = new JSONArray(); + for (int i = 0; i < 32; i++) { + ResultRow wideRow = resultRow(i + "-" + repeat('ü', 150), true, 200, 0, "opaque", 1); + wide.add(wideRow); + untrimmed.put(ModuleConnectionTest.rowToJson(wideRow)); + } + Assert.assertTrue("32 rows fit by characters", untrimmed.toString().length() < 8 * 1024); + JSONObject trimmed = new JSONObject(module.buildReport(wide)); + JSONArray kept = trimmed.getJSONArray("results"); + Assert.assertTrue("kept " + kept.length(), kept.length() > 0 && kept.length() < 32); + Assert.assertTrue(ModuleConnectionTest.utf8Length(trimmed.toString()) <= 8 * 1024); + for (int i = 0; i < kept.length(); i++) { + Assert.assertTrue(kept.getJSONObject(i).getString("f").startsWith(i + "-")); + Assert.assertEquals("opaque", kept.getJSONObject(i).getString("e")); + } + } + + /** + * A battery without a measured settings request. + *

+ * Verifies that the {@code sc} row is left out rather than invented, that the other rows keep + * their order, and that a combined row sums the latencies of its paths and reports how many it + * probed, which a single path row leaves out of its JSON. + */ + @Test + public void runBattery_withoutAScLatency_leavesTheScRowOut_andCombinesEveryMultiPathRow() { + init(TestUtils.getBaseConfig()); + ModuleConnectionTest module = connectionTest(); + module.transport = FakeTransport.instant(2); + + List rows = module.runBattery(-1); + + List expected = new ArrayList<>(Arrays.asList(EXPECTED_ORDER)); + expected.remove("sc"); + List features = new ArrayList<>(); + Map byFeature = new HashMap<>(); + for (ResultRow row : rows) { + features.add(row.feature); + byFeature.put(row.feature, row); + Assert.assertTrue(row.feature, row.ok); + Assert.assertNull(row.feature, row.error); + } + Assert.assertEquals(expected, features); + assertCombined(byFeature.get("feedback-widget"), 400, 6, 3); + assertCombined(byFeature.get("feedback-page"), 400, 6, 3); + assertCombined(byFeature.get("feedback-assets"), 200, 4, 2); + assertCombined(byFeature.get("core"), 200, 2, 1); + Assert.assertFalse(ModuleConnectionTest.rowToJson(byFeature.get("core")).has("n")); + Assert.assertEquals(3, ModuleConnectionTest.rowToJson(byFeature.get("feedback-widget")).getInt("n")); + } + + /** + * The connection a probe is sent on. + *

+ * Verifies that it is a bare GET that follows no redirect, without touching the default of + * every connection, uses no cache and has the given timeouts, that it carries the custom request + * headers with a usable name and value, that an HTTPS probe verifies the server against the pins + * only when pins are configured, and that the plain connection used without a transport is the + * same bare GET without any header. + */ + @Test + public void probeConnection_isABareGet_withTheCustomHeaders_andThePinsOnlyWhenPinned() throws Exception { + Map headers = new HashMap<>(); + headers.put("X-Countly-Test", "yes"); + headers.put("", "a header without a name"); + headers.put("X-Null-Value", null); + Transport unpinned = initializedTransport(TestUtils.getBaseConfig().addCustomNetworkRequestHeaders(headers)); + + HttpURLConnection probe = unpinned.openProbeConnection("http://127.0.0.1:9" + PREFIX + "/o/ping?ct=1&_=5", 1_234); + assertBareGet(probe, 1_234); + Assert.assertTrue(HttpURLConnection.getFollowRedirects()); + Assert.assertEquals("yes", probe.getRequestProperty("X-Countly-Test")); + Assert.assertEquals(1, probe.getRequestProperties().size()); + + HttpsURLConnection unpinnedHttps = (HttpsURLConnection) unpinned.openProbeConnection("https://127.0.0.1:9/o/ping", 100); + Assert.assertSame(HttpsURLConnection.getDefaultSSLSocketFactory(), unpinnedHttps.getSSLSocketFactory()); + + Transport pinned = initializedTransport(TestUtils.getBaseConfig().addPublicKeyPin(generatedPublicKeyPin())); + HttpsURLConnection pinnedHttps = (HttpsURLConnection) pinned.openProbeConnection("https://127.0.0.1:9/o/ping", 100); + assertBareGet(pinnedHttps, 100); + Assert.assertNotSame(HttpsURLConnection.getDefaultSSLSocketFactory(), pinnedHttps.getSSLSocketFactory()); + Assert.assertTrue(pinnedHttps.getRequestProperties().isEmpty()); + + HttpURLConnection bare = Transport.openBareGetConnection("http://127.0.0.1:9/o/ping", 77); + assertBareGet(bare, 77); + Assert.assertTrue(bare.getRequestProperties().isEmpty()); + } + + /** + * The default probe transport, used without a transport of the SDK. + *

+ * Verifies against the local server that it reads the real status of a 2xx, a 4xx and a 3xx, + * which it never follows, that it reads a body larger than it drains, that a silent endpoint + * becomes a timeout with status 0 after at least the timeout, and that a refused connection + * becomes a transport error with status 0. + */ + @Test + public void httpProbe_readsTheRealStatus_neverFollowsARedirect_andMapsEveryFailureToItsReason() throws Exception { + server.overrides.put(PREFIX + "/moved", Answer.redirect(PREFIX + "/o/ping")); + server.overrides.put(PREFIX + "/large", Answer.page(200, "text/html", repeat('x', 200 * 1024))); + server.overrides.put(PREFIX + "/silent", Answer.SILENT); + ModuleConnectionTest.HttpProbeTransport http = new ModuleConnectionTest.HttpProbeTransport(); + + assertOutcome(http.probe(server.url(PREFIX + "/o/ping?ct=1"), 2_000, null), 200, null); + assertOutcome(http.probe(server.url(PREFIX + "/i?ct=1"), 2_000, null), 400, null); + assertOutcome(http.probe(server.url(PREFIX + "/o/feedback/widget?ct=1"), 2_000, null), 404, null); + assertOutcome(http.probe(server.url(PREFIX + "/moved?ct=1"), 2_000, null), 302, null); + assertOutcome(http.probe(server.url(PREFIX + "/large?ct=1"), 2_000, null), 200, null); + Assert.assertEquals(1, probesTo(PREFIX + "/o/ping")); + + ProbeOutcome silent = http.probe(server.url(PREFIX + "/silent?ct=1"), 300, null); + assertOutcome(silent, 0, "timeout"); + Assert.assertTrue("ms " + silent.ms, silent.ms >= 300); + + assertOutcome(http.probe(deadUrl() + "/o/ping?ct=1", 2_000, null), 0, "transport error"); + } + + /** + * The rules of the request queue that the report is subject to. + *

+ * Verifies that the module is built and the report queued while consent is required and none is + * given, as the probes carry no identity, and that while the settings switch tracking off the + * battery still runs but the queue drops its report. + */ + @Test + public void report_isQueuedWithoutAnyConsent_butDroppedWhileTrackingIsOff() throws Exception { + settings.respondWith(new ServerConfigBuilder().connectionTest(1)); + init(config(server.url(PREFIX)).setRequiresConsent(true).enableFeatures(Config.Feature.Events)); + ModuleConnectionTest module = connectionTest(); + awaitBatteryIdle(module); + + Assert.assertTrue(SDKCore.instance.config.requiresConsent()); + Assert.assertFalse(Countly.isTracking(Config.Feature.Events)); + Assert.assertSame(module, SDKCore.instance.modules.get(0)); + Assert.assertEquals(16, server.probes.size()); + Assert.assertEquals(1, queuedReports().size()); + + push(new ServerConfigBuilder().tracking(false).connectionTest(1)); + awaitBatteryIdle(module); + + Assert.assertEquals(32, server.probes.size()); + Assert.assertEquals(1, queuedReports().size()); + Assert.assertEquals(1, logsContaining("[ModuleRequests] pushAsync, tracking disabled by SDK behavior settings; dropping request")); + } + + // endregion + // region helpers + + /** + * One request as the local server saw it. + */ + private static final class Received { + final String method; + final String path; + final String rawQuery; + final int bodyLength; + final Map headers = new HashMap<>(); + final Map params = new LinkedHashMap<>(); + + /** + * Records a request as it arrives: its method, path, query, body, headers by lower case + * name, and its parameters, decoded from the query and the body. + * + * @param exchange the request + * @throws IOException when the body cannot be read + */ + Received(HttpExchange exchange) throws IOException { + method = exchange.getRequestMethod(); + path = exchange.getRequestURI().getPath(); + rawQuery = exchange.getRequestURI().getRawQuery(); + byte[] body = readAll(exchange.getRequestBody()); + bodyLength = body.length; + for (Map.Entry> header : exchange.getRequestHeaders().entrySet()) { + if (!header.getValue().isEmpty()) { + headers.put(header.getKey().toLowerCase(Locale.ROOT), header.getValue().get(0)); + } + } + addParams(rawQuery); + addParams(new String(body, StandardCharsets.UTF_8)); + } + + /** + * Decodes url encoded parameters into {@link #params}. + * + * @param encoded the parameters, {@code null} for none + */ + private void addParams(String encoded) { + if (encoded == null || encoded.isEmpty()) { + return; + } + for (String pair : encoded.split("&")) { + String[] keyValue = pair.split("=", 2); + params.put(Utils.urldecode(keyValue[0]), keyValue.length > 1 ? Utils.urldecode(keyValue[1]) : ""); + } + } + } + + /** + * How the local server answers a request. + */ + private static final class Answer { + static final Answer SILENT = new Answer(0, null, "", null, true); + + final int status; + final String contentType; + final String body; + final String location; + final boolean silent; + + /** + * Describes an answer. + * + * @param status the status + * @param contentType the content type + * @param body the body, empty for none + * @param location the redirect target, {@code null} for none + * @param silent whether the server holds the request without ever answering it + */ + private Answer(int status, String contentType, String body, String location, boolean silent) { + this.status = status; + this.contentType = contentType; + this.body = body; + this.location = location; + this.silent = silent; + } + + /** + * A JSON answer. + * + * @param status the status + * @param body the JSON text + * @return the answer + */ + static Answer json(int status, String body) { + return new Answer(status, "application/json", body, null, false); + } + + /** + * A page, an image or any other body. + * + * @param status the status + * @param contentType the content type + * @param body the body + * @return the answer + */ + static Answer page(int status, String contentType, String body) { + return new Answer(status, contentType, body, null, false); + } + + /** + * A 302 to the given location, without a body. + * + * @param location the redirect target + * @return the answer + */ + static Answer redirect(String location) { + return new Answer(302, "text/html", "", location, false); + } + } + + /** + * A local stand in for a Countly server behind {@link #PREFIX}. A probe gets the answer a + * healthy server gives a request without app key and device ID, unless a test overrides its + * path: {@code /o/ping} 200, {@code /o/feedback/widget} 404, the frontend pages 200 or 400, the + * images 200 and every other API path 400. The SDK's own requests, which carry the app key, are + * recorded and refused, so they stay queued. Handlers run on a thread pool, so a silent answer + * never holds up the next probe. + */ + private static final class ProbeServer { + final List probes = new CopyOnWriteArrayList<>(); + final List sdkRequests = new CopyOnWriteArrayList<>(); + final Map overrides = new ConcurrentHashMap<>(); + private final CountDownLatch silenceEnds = new CountDownLatch(1); + private final ExecutorService executor = Executors.newCachedThreadPool(runnable -> { + Thread thread = new Thread(runnable, "ct-probe-server"); + thread.setDaemon(true); + return thread; + }); + private final HttpServer http; + + /** + * Starts the server on a free loopback port. + * + * @throws IOException when the server cannot start + */ + ProbeServer() throws IOException { + http = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + http.createContext("/", this::handle); + http.setExecutor(executor); + http.start(); + } + + /** + * The URL of a path on this server. + * + * @param path the path, with any query + * @return the URL + */ + String url(String path) { + return "http://127.0.0.1:" + http.getAddress().getPort() + path; + } + + /** + * Records a request and answers it. + * + * @param exchange the request and its response + * @throws IOException when the answer cannot be written + */ + private void handle(HttpExchange exchange) throws IOException { + Received received = new Received(exchange); + if (received.params.containsKey("app_key")) { + sdkRequests.add(received); + send(exchange, Answer.json(500, "{\"result\":\"refused by the test server\"}")); + return; + } + + probes.add(received); + Answer override = overrides.get(received.path); + send(exchange, override != null ? override : healthyAnswer(received.path)); + } + + /** + * What a healthy server answers a bare request to a path. + * + * @param path the request path + * @return the answer + */ + private static Answer healthyAnswer(String path) { + if (!path.startsWith(PREFIX + "/")) { + return Answer.page(404, "text/html", "no such location"); + } + + switch (path.substring(PREFIX.length())) { + case "/o/ping": + return Answer.json(200, "{\"result\":\"Success\"}"); + case "/o/feedback/widget": + return Answer.json(404, "{\"result\":\"Widget not found\"}"); + case "/feedback/nps": + case "/feedback/survey": + case "/_external/content/": + return Answer.page(200, "text/html", ""); + case "/feedback/rating": + return Answer.page(400, "text/html", "missing widget id"); + case "/surveys/images/ct-probe.png": + case "/star-rating/images/ct-probe.png": + return Answer.page(200, "image/png", "png"); + default: + return Answer.json(400, MISSING_PARAMETER); + } + } + + /** + * Writes an answer, or holds the request until the server stops for a silent one. + * + * @param exchange the request and its response + * @param answer the answer + * @throws IOException when the answer cannot be written + */ + private void send(HttpExchange exchange, Answer answer) throws IOException { + if (answer.silent) { + try { + silenceEnds.await(WAIT_BUDGET_MS, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + exchange.close(); + return; + } + + byte[] body = answer.body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", answer.contentType); + if (answer.location != null) { + exchange.getResponseHeaders().set("Location", answer.location); + } + exchange.sendResponseHeaders(answer.status, body.length == 0 ? -1 : body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + } + + /** + * Lets every silent request go, then stops the server and its handler threads. + */ + void stop() { + silenceEnds.countDown(); + http.stop(0); + executor.shutdownNow(); + } + } + + /** + * A probe transport without the network that answers like a healthy server, 200 for + * {@code /o/ping} and the images and 400 for everything else. It records every probe with the + * thread it ran on and the transport it was handed, and can hold every probe at a gate or take + * a given time. + */ + private static final class FakeTransport implements ModuleConnectionTest.ProbeTransport { + final List urls = new CopyOnWriteArrayList<>(); + final List transports = new CopyOnWriteArrayList<>(); + final Set threadNames = ConcurrentHashMap.newKeySet(); + final List daemonFlags = new CopyOnWriteArrayList<>(); + final CountDownLatch firstProbeStarted = new CountDownLatch(1); + final CountDownLatch gate; + private final long takesMs; + private final long reportedMs; + + /** + * Describes the fake. + * + * @param gated whether every probe waits at {@link #gate} until a test opens it + * @param takesMs how long every probe takes, in milliseconds + * @param reportedMs the latency every probe reports, in milliseconds + */ + private FakeTransport(boolean gated, long takesMs, long reportedMs) { + this.gate = new CountDownLatch(gated ? 1 : 0); + this.takesMs = takesMs; + this.reportedMs = reportedMs; + } + + /** + * A fake whose probes answer at once. + * + * @param reportedMs the latency every probe reports, in milliseconds + * @return the fake + */ + static FakeTransport instant(long reportedMs) { + return new FakeTransport(false, 0, reportedMs); + } + + /** + * A fake whose probes wait at the gate. + * + * @return the fake + */ + static FakeTransport gated() { + return new FakeTransport(true, 0, 1); + } + + /** + * A fake whose probes take the given time. + * + * @param takesMs how long every probe takes, in milliseconds + * @return the fake + */ + static FakeTransport slow(long takesMs) { + return new FakeTransport(false, takesMs, takesMs); + } + + /** + * Records the probe, waits at the gate and for the time a probe takes, then answers. + * + * @param url the probe URL + * @param timeoutMs the per request timeout + * @param transport the transport of the queued requests + * @return the answer of a healthy server + */ + @Nonnull + @Override + public ProbeOutcome probe(@Nonnull String url, int timeoutMs, @Nullable Transport transport) { + urls.add(url); + transports.add(transport); + threadNames.add(Thread.currentThread().getName()); + daemonFlags.add(Thread.currentThread().isDaemon()); + firstProbeStarted.countDown(); + try { + gate.await(WAIT_BUDGET_MS, TimeUnit.MILLISECONDS); + if (takesMs > 0) { + Thread.sleep(takesMs); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + + ProbeOutcome outcome = new ProbeOutcome(); + outcome.status = url.contains("/o/ping?") || url.contains(".png?") ? 200 : 400; + outcome.ms = reportedMs; + return outcome; + } + } + + /** + * A configuration pointing at the given server URL, with no request cooldowns and every log line + * kept in {@link #logs}. + * + * @param serverUrl the server URL + * @return the configuration + */ + private Config config(String serverUrl) { + File directory = TestUtils.getTestSDirectory(); + TestUtils.checkSdkStorageRootDirectoryExist(directory); + return new Config(serverUrl, TestUtils.SERVER_APP_KEY, directory) + .setApplicationVersion(TestUtils.APPLICATION_VERSION) + .setCustomDeviceId(TestUtils.DEVICE_ID) + .setNetworkRequestCooldown(0) + .setNetworkImportantRequestCooldown(0) + .setLogListener((message, level) -> logs.add(message)) + .disableHealthCheck(); + } + + /** + * Initializes the SDK with {@link #settings} answering its settings requests. + * + * @param config the configuration + */ + private void init(Config config) { + InternalConfig internalConfig = new InternalConfig(config); + internalConfig.immediateRequestGenerator = settings; + Countly.instance().init(internalConfig); + } + + /** + * Answers the next settings request with the given payload and makes the SDK fetch, as the + * refresh timer does. The response is applied, and the test armed, before this returns. + * + * @param builder the payload + */ + private void push(ServerConfigBuilder builder) { + settings.respondWith(builder); + SDKCore.instance.module(ModuleConfiguration.class).fetchConfigFromServer(SDKCore.instance.config); + } + + /** + * The connection test module of the running SDK. + * + * @return the module + */ + private static ModuleConnectionTest connectionTest() { + return SDKCore.instance.module(ModuleConnectionTest.class); + } + + /** + * The settings in effect in the running SDK. + * + * @return the provider + */ + private static ConfigurationProvider provider() { + return SDKCore.instance.config.getConfigurationProvider(); + } + + /** + * The settings as stored on disk. + * + * @return the stored settings, {@code null} when nothing is stored + */ + private static JSONObject storedConfig() { + String stored = TestUtils.readJsonFile(SDKStorage.JSON_FILE_NAME).optString("sc", null); + return stored == null ? null : new JSONObject(stored); + } + + /** + * Waits until no battery runs. + * + * @param module the connection test module + * @throws InterruptedException when the wait is interrupted + */ + private static void awaitBatteryIdle(ModuleConnectionTest module) throws InterruptedException { + Assert.assertTrue("the battery did not finish in time", waitFor(() -> !module.batteryRunning.get())); + } + + /** + * Every queued request that carries a report. + * + * @return the parameters of each, in queue order + */ + private static List> queuedReports() { + List> reports = new ArrayList<>(); + for (Map request : TestUtils.getCurrentRQ()) { + if (request.containsKey(keyResults)) { + reports.add(request); + } + } + return reports; + } + + /** + * The one queued request that carries a report. + * + * @return its parameters + */ + private static Map onlyQueuedReport() { + List> reports = queuedReports(); + Assert.assertEquals("queued reports", 1, reports.size()); + return reports.get(0); + } + + /** + * The requests carrying a report that the queue sent to the local server. + * + * @return the requests, in arrival order + */ + private List reportsSentToTheServer() { + List sent = new ArrayList<>(); + for (Received request : server.sdkRequests) { + if (request.params.containsKey(keyResults)) { + sent.add(request); + } + } + return sent; + } + + /** + * How many probes reached a path. + * + * @param path the path + * @return the number of probes + */ + private int probesTo(String path) { + int count = 0; + for (Received probe : server.probes) { + if (path.equals(probe.path)) { + count++; + } + } + return count; + } + + /** + * How many log lines contain a text. + * + * @param text the text + * @return the number of lines + */ + private int logsContaining(String text) { + int count = 0; + for (String line : logs) { + if (line.contains(text)) { + count++; + } + } + return count; + } + + /** + * The rows of a report by feature key. + * + * @param report the report + * @return the rows + */ + private static Map rowsByFeature(JSONObject report) { + JSONArray results = report.getJSONArray("results"); + Map rows = new HashMap<>(); + for (int i = 0; i < results.length(); i++) { + JSONObject row = results.getJSONObject(i); + rows.put(row.getString("f"), row); + } + return rows; + } + + /** + * Asserts that a report holds the twelve rows in table order. + * + * @param report the report + */ + private static void assertRowOrder(JSONObject report) { + JSONArray results = report.getJSONArray("results"); + Assert.assertEquals(EXPECTED_ORDER.length, results.length()); + for (int i = 0; i < EXPECTED_ORDER.length; i++) { + Assert.assertEquals(EXPECTED_ORDER[i], results.getJSONObject(i).getString("f")); + } + } + + /** + * Asserts one report row, which carries only the report keys and never {@code sk}. + * + * @param row the row + * @param ok the expected verdict + * @param st the expected status + * @param e the expected reason, {@code null} when the row has none + * @param n the expected path count, {@code null} when the row has none + */ + private static void assertRow(JSONObject row, boolean ok, int st, String e, Integer n) { + Assert.assertNotNull("missing row", row); + String label = row.getString("f"); + Assert.assertTrue(label + " keys " + row.keySet(), ROW_KEYS.containsAll(row.keySet())); + Assert.assertEquals(label + " ok", ok, row.getBoolean("ok")); + Assert.assertEquals(label + " st", st, row.getInt("st")); + Assert.assertTrue(label + " ms", row.getLong("ms") >= 0); + if (e == null) { + Assert.assertFalse(label + " has e", row.has("e")); + } else { + Assert.assertEquals(label + " e", e, row.getString("e")); + } + if (n == null) { + Assert.assertFalse(label + " has n", row.has("n")); + } else { + Assert.assertEquals(label + " n", (int) n, row.getInt("n")); + } + } + + /** + * Asserts a graded row that reached every path. + * + * @param row the row + * @param status the expected status + * @param ms the expected summed latency + * @param pathCount the expected number of paths + */ + private static void assertCombined(ResultRow row, int status, long ms, int pathCount) { + Assert.assertTrue(row.feature, row.ok); + Assert.assertEquals(row.feature, status, row.status); + Assert.assertEquals(row.feature, ms, row.ms); + Assert.assertEquals(row.feature, pathCount, row.pathCount); + } + + /** + * Asserts what a probe observed. + * + * @param outcome the outcome + * @param status the expected status + * @param failure the expected failure, {@code null} for none + */ + private static void assertOutcome(ProbeOutcome outcome, int status, String failure) { + Assert.assertEquals(status, outcome.status); + Assert.assertEquals(failure, outcome.failure); + Assert.assertTrue(outcome.ms >= 0); + } + + /** + * Asserts that a connection is a bare GET with the given timeouts. + * + * @param connection the connection, not connected yet + * @param timeoutMs the expected connect and read timeout + */ + private static void assertBareGet(HttpURLConnection connection, int timeoutMs) { + Assert.assertEquals("GET", connection.getRequestMethod()); + Assert.assertFalse(connection.getInstanceFollowRedirects()); + Assert.assertFalse(connection.getUseCaches()); + Assert.assertTrue(connection.getDoInput()); + Assert.assertFalse(connection.getDoOutput()); + Assert.assertEquals(timeoutMs, connection.getConnectTimeout()); + Assert.assertEquals(timeoutMs, connection.getReadTimeout()); + } + + /** + * A graded row. + * + * @param feature the feature key + * @param ok the verdict + * @param status the status + * @param ms the latency + * @param error the reason, {@code null} for none + * @param pathCount the number of paths + * @return the row + */ + private static ResultRow resultRow(String feature, boolean ok, int status, long ms, String error, int pathCount) { + ResultRow row = new ResultRow(feature); + row.ok = ok; + row.status = status; + row.ms = ms; + row.error = error; + row.pathCount = pathCount; + return row; + } + + /** + * A transport initialized with the given configuration. + * + * @param config the configuration + * @return the transport + */ + private static Transport initializedTransport(Config config) { + Transport transport = new Transport(); + transport.init(TestUtils.getInternalConfigWithLogger(config)); + return transport; + } + + /** + * A public key pin for a key generated for the test, base64 encoded as a pin may be given. + * + * @return the pin + * @throws Exception when no key can be generated + */ + private static String generatedPublicKeyPin() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return Base64.getEncoder().encodeToString(generator.generateKeyPair().getPublic().getEncoded()); + } + + /** + * The URL of a loopback port nothing listens on. + * + * @return the URL, with {@link #PREFIX} + * @throws IOException when no free port can be found + */ + private static String deadUrl() throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + return "http://127.0.0.1:" + socket.getLocalPort() + PREFIX; + } + } + + /** + * A text of one character repeated. + * + * @param character the character + * @param count how many times + * @return the text + */ + private static String repeat(char character, int count) { + char[] characters = new char[count]; + Arrays.fill(characters, character); + return new String(characters); + } + + /** + * Reads a stream to its end. + * + * @param stream the stream + * @return the bytes + * @throws IOException when the stream cannot be read + */ + private static byte[] readAll(InputStream stream) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int read; + while ((read = stream.read(buffer)) != -1) { + bytes.write(buffer, 0, read); + } + return bytes.toByteArray(); + } + + /** + * Polls a condition until it holds or the wait budget runs out. + * + * @param condition the condition + * @return whether it held + * @throws InterruptedException when the wait is interrupted + */ + private static boolean waitFor(BooleanSupplier condition) throws InterruptedException { + long deadline = System.currentTimeMillis() + WAIT_BUDGET_MS; + while (System.currentTimeMillis() < deadline) { + if (condition.getAsBoolean()) { + return true; + } + Thread.sleep(POLL_MS); + } + return condition.getAsBoolean(); + } + + // endregion +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleContentTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleContentTests.java index 1691226a4..81639399d 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleContentTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleContentTests.java @@ -129,8 +129,9 @@ public void enterContentZone_withoutADisplay_isIgnored() throws JSONException { } /** - * With consent required, the content interface is unreachable until content consent is given, - * and a zone that is already running is torn down when that consent is taken away again. + * With consent required, the content interface ignores calls until content consent is given, and + * a zone that is already running is torn down when that consent is taken away again, after which + * the interface kept from before ignores calls too. */ @Test public void content_isGatedByConsent() throws JSONException { @@ -138,7 +139,7 @@ public void content_isGatedByConsent() throws JSONException { init(config); nextResponse = new JSONObject(CONTENT_RESPONSE); - Assert.assertNull(Countly.instance().content()); + Assert.assertSame(SDKCore.dormantContent, Countly.instance().content()); Countly.onConsent(Config.Feature.Content, Config.Feature.Events); installRequestMaker(); @@ -151,7 +152,9 @@ public void content_isGatedByConsent() throws JSONException { Assert.assertEquals(1, requests.size()); Countly.onConsentRemoval(Config.Feature.Content); - Assert.assertNull(Countly.instance().content()); + Assert.assertSame(SDKCore.dormantContent, Countly.instance().content()); + content.enterContentZone(); + content.refreshContentZone(); Assert.assertEquals(1, requests.size()); } diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleCrashesTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleCrashesTests.java index 84d3f2340..3ea89209f 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleCrashesTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleCrashesTests.java @@ -2,8 +2,12 @@ import java.io.PrintWriter; import java.io.StringWriter; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import ly.count.sdk.java.Config; import ly.count.sdk.java.Countly; @@ -146,6 +150,45 @@ public void addCrashBreadcrumb() { validateCrashInRQ(testThrowable, false, null, null, 1); } + /** + * "addCrashBreadcrumb" while the uncaught exception handler records crashes + * Validating that breadcrumbs added through the interface while crashes are recorded on another + * thread, as the uncaught exception handler does, are each taken by one crash or kept for the + * next, none of them lost, and that no call throws + */ + @Test + public void addCrashBreadcrumb_whileAnotherThreadRecordsCrashes_losesNone() throws InterruptedException { + BreadcrumbCountingProcessor.taken.set(0); + int breadcrumbs = 20_000; + Countly.instance().init(TestUtils.getBaseConfig().enableFeatures(Config.Feature.CrashReporting) + .setMaxBreadcrumbCount(breadcrumbs).setCrashProcessorClass(BreadcrumbCountingProcessor.class)); + ModuleCrashes module = SDKCore.instance.module(ModuleCrashes.class); + List failures = new CopyOnWriteArrayList<>(); + AtomicBoolean adding = new AtomicBoolean(true); + + Thread crashes = new Thread(() -> { + try { + while (adding.get()) { + module.recordExceptionInternal(new IllegalStateException("crash"), false, null, null); + } + } catch (Throwable t) { + failures.add(t); + } + }); + crashes.start(); + try { + for (int i = 0; i < breadcrumbs; i++) { + Countly.instance().crashes().addCrashBreadcrumb("breadcrumb" + i); + } + } finally { + adding.set(false); + crashes.join(30_000); + } + + Assert.assertTrue("failed: " + failures, failures.isEmpty()); + Assert.assertEquals(breadcrumbs, BreadcrumbCountingProcessor.taken.get() + module.logs.size()); + } + /** * "addCrashBreadcrumb" with default "maxBreadcrumbCount" * Validating that handled exception is recorded correctly to request queue and has breadcrumbs, @@ -270,6 +313,22 @@ private void recordExceptionWithSegment_base(boolean fatal, BiConsumer logs = crash.getLogs(); + if (logs != null) { + taken.addAndGet(logs.size()); + } + return null; + } + } + public static class TestCrashProcessor implements CrashProcessor { public TestCrashProcessor() { 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 new file mode 100644 index 000000000..aca1aab1b --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleHealthCheckTests.java @@ -0,0 +1,719 @@ +package ly.count.sdk.java.internal; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; +import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import static org.mockito.Mockito.mock; + +@RunWith(JUnit4.class) +public class ModuleHealthCheckTests { + + /** + * One immediate request the SDK made. + */ + static class SentRequest { + final String data; + final String endpoint; + + SentRequest(String data, String endpoint) { + this.data = data; + this.endpoint = endpoint; + } + + Map params() { + Map decoded = new HashMap<>(); + for (Map.Entry param : TestUtils.parseQueryParams(data).entrySet()) { + decoded.put(param.getKey(), Utils.urldecode(param.getValue())); + } + return decoded; + } + + JSONObject healthCheck() { + return new JSONObject(params().get("hc")); + } + } + + /** + * An in-memory storage for the counter tests. + */ + static class MemoryStorage implements StorageProvider { + String healthCheckState = null; + int automaticCrashes = 0; + + @Override public String getDeviceID() { + return null; + } + + @Override public void setDeviceID(String deviceID) { + } + + @Override public String getDeviceIdType() { + return null; + } + + @Override public void setDeviceIdType(String deviceIdTypeString) { + } + + @Override public void setRemoteConfigValues(JSONObject remoteConfigValues) { + } + + @Override public JSONObject getRemoteConfigValues() { + return new JSONObject(); + } + + @Override public Integer getMigrationVersion() { + return 0; + } + + @Override public void setMigrationVersion(Integer migrationVersion) { + } + + @Override public boolean isCountlyStorageEmpty() { + return true; + } + + @Override public void setServerConfig(String config) { + } + + @Override public String getServerConfig() { + return null; + } + + @Override public String getHealthCheckState() { + return healthCheckState; + } + + @Override public void setHealthCheckState(String state) { + healthCheckState = state; + } + + @Override public String getContentTriggerGaps() { + return null; + } + + @Override public void setContentTriggerGaps(String gaps) { + } + + @Override public void incrementAutomaticCrashCount() { + automaticCrashes++; + } + + @Override public int takeAutomaticCrashCount() { + int count = automaticCrashes; + automaticCrashes = 0; + return count; + } + } + + private final List sentRequests = new ArrayList<>(); + private JSONObject serverAnswer = new JSONObject().put("result", "Success"); + + @Before + public void beforeTest() { + TestUtils.createCleanTestState(); + //a start takes the log codes other tests recorded while no SDK ran, so each test begins without them + Countly.instance().init(TestUtils.getBaseConfig()); + TestUtils.createCleanTestState(); + sentRequests.clear(); + serverAnswer = new JSONObject().put("result", "Success"); + } + + @After + public void stop() { + Countly.instance().halt(); + } + + private HealthCheckCounter counter(MemoryStorage storage, Predicate consent) { + return new HealthCheckCounter(storage, mock(Log.class), consent); + } + + private HealthCheckCounter counter(MemoryStorage storage) { + return counter(storage, feature -> true); + } + + /** + * A configuration whose health check is on, as the test base configuration turns it off, with + * an immediate request generator that keeps every request and answers with {@link #serverAnswer}. + */ + private InternalConfig healthCheckConfig() { + Config config = new Config(TestUtils.SERVER_URL, TestUtils.SERVER_APP_KEY, TestUtils.getTestSDirectory()) + .setApplicationVersion(TestUtils.APPLICATION_VERSION) + .setCustomDeviceId(TestUtils.DEVICE_ID) + .disableSdkBehaviorSettingsUpdates() + .enableFeatures(Config.Feature.Events, Config.Feature.Sessions, Config.Feature.Views, Config.Feature.CrashReporting); + return withRecordingServer(new InternalConfig(config)); + } + + private InternalConfig withRecordingServer(InternalConfig config) { + config.immediateRequestGenerator = () -> (requestData, customEndpoint, cp, requestShouldBeDelayed, networkingIsEnabled, callback, log) -> { + sentRequests.add(new SentRequest(requestData, customEndpoint)); + callback.callback(serverAnswer); + }; + return config; + } + + private List healthChecks() { + List found = new ArrayList<>(); + for (SentRequest request : sentRequests) { + if (request.params().containsKey("hc")) { + found.add(request); + } + } + return found; + } + + private HealthCheckCounter runningCounter() { + return SDKCore.instance.module(ModuleHealthCheck.class).counter(); + } + + private static int usage(JSONObject snapshot, String area, String method) { + JSONObject methods = snapshot.getJSONObject("fu").optJSONObject(area); + return methods == null ? 0 : methods.optInt(method, 0); + } + + private static int code(JSONObject snapshot, String code) { + return snapshot.getJSONObject("lc").optInt(code, 0); + } + + /** + * A new counter reports the defaults, with "fu" and "lc" present as empty objects. + */ + @Test + public void counter_defaults() { + JSONObject snapshot = counter(new MemoryStorage()).snapshot(); + Assert.assertEquals(0, snapshot.getLong("el")); + Assert.assertEquals(0, snapshot.getLong("wl")); + Assert.assertEquals(-1, snapshot.getInt("sc")); + Assert.assertEquals("", snapshot.getString("em")); + Assert.assertEquals(0, snapshot.getLong("bom")); + Assert.assertEquals(0, snapshot.getInt("cbom")); + Assert.assertEquals(0, snapshot.getJSONObject("fu").length()); + Assert.assertEquals(0, snapshot.getJSONObject("lc").length()); + } + + /** + * A stored state is restored, entries of the wrong type are skipped, and the saved state uses + * the storage keys of the guide. + */ + @Test + public void counter_restoresAndSavesState() { + MemoryStorage storage = new MemoryStorage(); + storage.healthCheckState = "{\"LErr\":2,\"LWar\":3,\"RStatC\":503,\"REMsg\":\"Service Unavailable\",\"BReq\":4,\"CBReq\":2," + + "\"MU\":{\"events\":{\"record\":5,\"start\":\"x\"},\"views\":7},\"LC\":{\"w740\":1,\"w720\":\"y\"}}"; + + HealthCheckCounter counter = counter(storage); + JSONObject snapshot = counter.snapshot(); + Assert.assertEquals(2, snapshot.getLong("el")); + Assert.assertEquals(3, snapshot.getLong("wl")); + Assert.assertEquals(503, snapshot.getInt("sc")); + Assert.assertEquals("Service Unavailable", snapshot.getString("em")); + Assert.assertEquals(4, snapshot.getLong("bom")); + Assert.assertEquals(2, snapshot.getInt("cbom")); + Assert.assertEquals(5, usage(snapshot, "events", "record")); + Assert.assertEquals(0, usage(snapshot, "events", "start")); + Assert.assertNull(snapshot.getJSONObject("fu").optJSONObject("views")); + Assert.assertEquals(1, code(snapshot, "w740")); + Assert.assertFalse(snapshot.getJSONObject("lc").has("w720")); + + counter.logError(); + counter.saveState(); + JSONObject stored = new JSONObject(storage.healthCheckState); + Assert.assertEquals(3, stored.getLong("LErr")); + Assert.assertEquals(3, stored.getLong("LWar")); + Assert.assertEquals(503, stored.getInt("RStatC")); + Assert.assertEquals("Service Unavailable", stored.getString("REMsg")); + Assert.assertEquals(4, stored.getLong("BReq")); + Assert.assertEquals(2, stored.getInt("CBReq")); + Assert.assertEquals(5, stored.getJSONObject("MU").getJSONObject("events").getInt("record")); + Assert.assertEquals(1, stored.getJSONObject("LC").getInt("w740")); + } + + /** + * A stored state that is not valid JSON is cleared, the counters start from zero and the + * condition is reported as log code e503. + */ + @Test + public void counter_malformedStateIsResetWithE503() { + MemoryStorage storage = new MemoryStorage(); + storage.healthCheckState = "{not json"; + + JSONObject snapshot = counter(storage).snapshot(); + Assert.assertEquals("", storage.healthCheckState); + Assert.assertEquals(0, snapshot.getLong("el")); + Assert.assertEquals(1, code(snapshot, "e503")); + } + + /** + * The automatically detected crashes the previous run counted are reported as "crashes" / + * "record:a" and their stored count goes back to 0. + */ + @Test + public void counter_addsAutomaticCrashesOfThePreviousRun() { + MemoryStorage storage = new MemoryStorage(); + storage.automaticCrashes = 2; + + JSONObject snapshot = counter(storage).snapshot(); + Assert.assertEquals(2, usage(snapshot, "crashes", "record:a")); + Assert.assertEquals(0, storage.automaticCrashes); + Assert.assertEquals(2, new JSONObject(storage.healthCheckState).getJSONObject("MU").getJSONObject("crashes").getInt("record:a")); + } + + /** + * Only the last refused request is kept, status codes outside 1..999 are ignored and the + * message is cut to 1000 characters. + */ + @Test + public void counter_failedRequests() { + HealthCheckCounter counter = counter(new MemoryStorage()); + counter.logFailedNetworkRequest(500, "first"); + counter.logFailedNetworkRequest(0, "ignored"); + counter.logFailedNetworkRequest(1000, "ignored"); + StringBuilder longBody = new StringBuilder(); + for (int a = 0; a < 1200; a++) { + longBody.append('x'); + } + counter.logFailedNetworkRequest(400, longBody.toString()); + + JSONObject snapshot = counter.snapshot(); + Assert.assertEquals(400, snapshot.getInt("sc")); + Assert.assertEquals(1000, snapshot.getString("em").length()); + } + + /** + * "bom" counts every backoff, "cbom" keeps the longest run of backoffs in a row, w320 is + * recorded for every backoff and w321 for every backoff that continues a run. + */ + @Test + public void counter_backoffRuns() { + HealthCheckCounter counter = counter(new MemoryStorage()); + counter.logBackoffRequest(); + counter.logBackoffRequest(); + counter.logBackoffRequest(); + counter.saveState(); + counter.logConsecutiveBackoffRequest(); + counter.logBackoffRequest(); + counter.logBackoffRequest(); + + JSONObject snapshot = counter.snapshot(); + Assert.assertEquals(5, snapshot.getLong("bom")); + Assert.assertEquals(3, snapshot.getInt("cbom")); + Assert.assertEquals(5, code(snapshot, "w320")); + Assert.assertEquals(3, code(snapshot, "w321")); + } + + /** + * Method usage and the log codes of a feature area count only while that feature has consent, + * an unknown area never counts, and every count stops at 65535. + */ + @Test + public void counter_consentAndCap() { + HealthCheckCounter counter = counter(new MemoryStorage(), feature -> feature != CoreFeature.Views); + counter.recordUsage("views", "start"); + counter.recordUsage("events", "record"); + counter.recordUsage("unknown", "call"); + counter.recordUsage("events", ""); + counter.recordLogCode("w730", "views"); + counter.recordLogCode("w720", "events"); + counter.recordLogCode("w101", 70000); + counter.recordLogCode("w101", 1); + + JSONObject snapshot = counter.snapshot(); + Assert.assertEquals(0, usage(snapshot, "views", "start")); + Assert.assertEquals(1, usage(snapshot, "events", "record")); + Assert.assertNull(snapshot.getJSONObject("fu").optJSONObject("unknown")); + Assert.assertEquals(0, code(snapshot, "w730")); + Assert.assertEquals(1, code(snapshot, "w720")); + Assert.assertEquals(HealthCheckCounter.COUNT_CAP, code(snapshot, "w101")); + } + + /** + * While an automatic crash is reported, method usage and log codes are ignored; warnings and + * errors are still counted. Counting resumes afterwards. + */ + @Test + public void counter_crashStop() { + HealthCheckCounter counter = counter(new MemoryStorage()); + counter.stopRecordingForCrash(); + counter.recordUsage("events", "record"); + counter.recordLogCode("w202", 1); + counter.logError(); + counter.resumeRecordingAfterCrash(); + counter.recordUsage("events", "record"); + + JSONObject snapshot = counter.snapshot(); + Assert.assertEquals(1, usage(snapshot, "events", "record")); + Assert.assertEquals(0, code(snapshot, "w202")); + Assert.assertEquals(1, snapshot.getLong("el")); + } + + /** + * An accepted health check takes away only what it reported: what was counted while it was on + * its way stays, and a failed request or a backoff run that changed meanwhile is kept. + */ + @Test + public void counter_clearSentValuesSubtractsWhatWasReported() { + MemoryStorage storage = new MemoryStorage(); + HealthCheckCounter counter = counter(storage); + counter.logWarning(); + counter.logWarning(); + counter.logFailedNetworkRequest(500, "down"); + counter.logBackoffRequest(); + counter.recordUsage("events", "record"); + counter.recordLogCode("w720", 1); + + JSONObject snapshot = counter.snapshot(); + + counter.logWarning(); + counter.logFailedNetworkRequest(400, "bad"); + counter.logBackoffRequest(); + counter.recordUsage("events", "record"); + counter.recordUsage("views", "start"); + + counter.clearSentValues(snapshot); + JSONObject left = counter.snapshot(); + Assert.assertEquals(1, left.getLong("wl")); + Assert.assertEquals(400, left.getInt("sc")); + Assert.assertEquals("bad", left.getString("em")); + Assert.assertEquals(1, left.getLong("bom")); + Assert.assertEquals(2, left.getInt("cbom")); + Assert.assertEquals(1, usage(left, "events", "record")); + Assert.assertEquals(1, usage(left, "views", "start")); + Assert.assertFalse(left.getJSONObject("lc").has("w720")); + Assert.assertEquals(1, new JSONObject(storage.healthCheckState).getLong("LWar")); + + counter.clearSentValues(counter.snapshot()); + JSONObject empty = counter.snapshot(); + Assert.assertEquals(-1, empty.getInt("sc")); + Assert.assertEquals("", empty.getString("em")); + Assert.assertEquals(0, empty.getInt("cbom")); + Assert.assertEquals(0, empty.getJSONObject("fu").length()); + } + + /** + * The health check is sent once, right after init, as an immediate request to /i with the base + * request parameters, the app version as metrics and the counters. The warnings logged before + * the counter existed, such as an invalid init value, are in it. + */ + @Test + public void healthCheck_sentOnceAfterInit() { + InternalConfig config = healthCheckConfig(); + config.setRequestQueueMaxSize(0); + config.setLoggingLevel(Config.LoggingLevel.OFF); + Countly.instance().init(config); + + List healthChecks = healthChecks(); + Assert.assertEquals(1, healthChecks.size()); + SentRequest request = healthChecks.get(0); + Assert.assertEquals("/i?", request.endpoint); + + Map params = request.params(); + TestUtils.validateRequiredParams(params); + Assert.assertEquals("{\"_app_version\":\"" + TestUtils.APPLICATION_VERSION + "\"}", params.get("metrics")); + + JSONObject hc = request.healthCheck(); + for (String key : new String[] { "el", "wl", "sc", "em", "bom", "cbom", "fu", "lc" }) { + Assert.assertTrue("missing " + key, hc.has(key)); + } + Assert.assertTrue(hc.getLong("wl") >= 1); + Assert.assertEquals(1, code(hc, "w121")); + + SDKCore.instance.module(ModuleHealthCheck.class).sendHealthCheck(); + Assert.assertEquals(1, healthChecks().size()); + } + + /** + * An accepted health check takes the reported counts away and stores what is left; a refused + * one leaves the counters for the next initialization. + */ + @Test + public void healthCheck_acceptedClearsRefusedKeeps() { + serverAnswer = new JSONObject().put("result", "Success"); + InternalConfig first = healthCheckConfig(); + first.setRequestQueueMaxSize(0); + Countly.instance().init(first); + Assert.assertEquals(1, code(healthChecks().get(0).healthCheck(), "w121")); + Countly.instance().events().endEvent("never started"); + JSONObject afterAccepted = runningCounter().snapshot(); + Assert.assertEquals(1, code(afterAccepted, "w720")); + Assert.assertEquals(0, code(afterAccepted, "w121")); + Countly.instance().stop(); + + serverAnswer = new JSONObject().put("error", "App does not exist"); + Countly.instance().init(healthCheckConfig()); + Assert.assertEquals(1, code(healthChecks().get(1).healthCheck(), "w720")); + Assert.assertEquals(1, code(runningCounter().snapshot(), "w720")); + + serverAnswer = null; + Countly.instance().stop(); + Countly.instance().init(healthCheckConfig()); + Assert.assertEquals(1, code(runningCounter().snapshot(), "w720")); + } + + /** + * With the health check disabled nothing is sent, but warnings are still counted. + */ + @Test + public void healthCheck_disabled() { + InternalConfig config = healthCheckConfig(); + config.disableHealthCheck(); + Countly.instance().init(config); + + Assert.assertTrue(healthChecks().isEmpty()); + long before = runningCounter().snapshot().getLong("wl"); + Countly.instance().events().cancelEvent("never started"); + Assert.assertEquals(before + 1, runningCounter().snapshot().getLong("wl")); + } + + /** + * While the SDK behavior settings turn networking off, nothing is sent and the counters wait + * for the next initialization. + */ + @Test + public void healthCheck_networkingOff() { + InternalConfig config = healthCheckConfig(); + config.setSdkBehaviorSettings("{\"v\":1,\"t\":1700000000000,\"c\":{\"networking\":false}}"); + Countly.instance().init(config); + + Assert.assertTrue(healthChecks().isEmpty()); + Assert.assertFalse(SDKCore.instance.module(ModuleHealthCheck.class).isHealthCheckSent()); + } + + /** + * Backend mode sends no health check and runs no health check module. + */ + @Test + public void healthCheck_backendMode() { + InternalConfig config = healthCheckConfig(); + config.enableBackendMode(); + Countly.instance().init(config); + + Assert.assertTrue(healthChecks().isEmpty()); + Assert.assertNull(SDKCore.instance.module(ModuleHealthCheck.class)); + } + + /** + * Without the sessions consent, which carries the metrics in this SDK, the health check is sent + * without metrics; the health check itself needs no consent. + */ + @Test + public void healthCheck_withoutConsent() { + InternalConfig config = healthCheckConfig(); + config.setRequiresConsent(true); + Countly.instance().init(config); + + Assert.assertEquals(1, healthChecks().size()); + Assert.assertNull(healthChecks().get(0).params().get("metrics")); + } + + /** + * The overridden app version is the one the health check metrics carry. + */ + @Test + public void healthCheck_appVersionOverride() { + InternalConfig config = healthCheckConfig(); + Map overrides = new HashMap<>(); + overrides.put("_app_version", "9.9.9"); + config.setMetricOverride(overrides); + Countly.instance().init(config); + + Assert.assertEquals("{\"_app_version\":\"9.9.9\"}", healthChecks().get(0).params().get("metrics")); + } + + /** + * Every listed method of the session, event, view and crash features is counted once per call, + * under the names of the guide. + */ + @Test + public void methodUsage_counted() { + Countly.instance().init(healthCheckConfig()); + + Countly.session().begin(); + Countly.session().update(); + Countly.session().end(); + + Countly.instance().events().recordEvent("a"); + Countly.instance().events().recordEvent("b", 2); + Countly.instance().events().startEvent("timed"); + Countly.instance().events().endEvent("timed"); + Countly.instance().events().startEvent("cancelled"); + Countly.instance().events().cancelEvent("cancelled"); + + String first = Countly.instance().views().startView("first"); + Countly.instance().views().startAutoStoppedView("auto"); + Countly.instance().views().pauseViewWithID(first); + Countly.instance().views().resumeViewWithID(first); + Countly.instance().views().stopViewWithID(first); + Countly.instance().views().startView("named"); + Countly.instance().views().stopViewWithName("named"); + Countly.instance().views().stopAllViews(null); + + Countly.instance().crashes().addCrashBreadcrumb("crumb"); + Countly.instance().crashes().recordHandledException(new RuntimeException("handled")); + + JSONObject snapshot = runningCounter().snapshot(); + Assert.assertEquals(1, usage(snapshot, "sessions", "begin")); + Assert.assertEquals(1, usage(snapshot, "sessions", "update")); + Assert.assertEquals(1, usage(snapshot, "sessions", "end")); + Assert.assertEquals(2, usage(snapshot, "events", "record")); + Assert.assertEquals(2, usage(snapshot, "events", "start")); + Assert.assertEquals(1, usage(snapshot, "events", "end")); + Assert.assertEquals(1, usage(snapshot, "events", "cancel")); + Assert.assertEquals(2, usage(snapshot, "views", "start")); + Assert.assertEquals(1, usage(snapshot, "views", "startAuto")); + Assert.assertEquals(1, usage(snapshot, "views", "pause")); + Assert.assertEquals(1, usage(snapshot, "views", "resume")); + Assert.assertEquals(2, usage(snapshot, "views", "stop")); + Assert.assertEquals(1, usage(snapshot, "views", "stopAll")); + Assert.assertEquals(1, usage(snapshot, "crashes", "log")); + Assert.assertEquals(1, usage(snapshot, "crashes", "record")); + } + + /** + * Calls the SDK makes by itself carry ":a", and deprecated calls carry ":d" with log code w120. + */ + @Test + public void methodUsage_automaticAndDeprecated() { + Countly.instance().init(healthCheckConfig()); + + Countly.api().event("legacy").record(); + Countly.api().addCrashReport(new RuntimeException("legacy"), false); + Countly.api().view("legacy view"); + + JSONObject snapshot = runningCounter().snapshot(); + Assert.assertEquals(1, usage(snapshot, "events", "record:d")); + Assert.assertEquals(1, usage(snapshot, "sessions", "begin:a")); + Assert.assertEquals(1, usage(snapshot, "crashes", "addCrashReport:d")); + Assert.assertEquals(1, usage(snapshot, "views", "view:d")); + Assert.assertEquals(3, code(snapshot, "w120")); + } + + /** + * While consent is required, the calls of a feature without consent are not counted, and + * neither are the log codes they record. + */ + @Test + public void methodUsage_followsConsent() { + InternalConfig config = healthCheckConfig(); + config.setRequiresConsent(true); + Countly.instance().init(config); + + Countly.instance().events().recordEvent("no consent"); + Countly.instance().events().endEvent("no consent"); + Assert.assertEquals(0, usage(runningCounter().snapshot(), "events", "record")); + + Countly.onConsent(Config.Feature.Events); + Countly.instance().events().recordEvent("consent"); + Countly.instance().events().endEvent("consent"); + JSONObject snapshot = runningCounter().snapshot(); + Assert.assertEquals(1, usage(snapshot, "events", "record")); + Assert.assertEquals(1, code(snapshot, "w720")); + } + + /** + * Misuse of the event, view and session methods records the codes of the guide. + */ + @Test + public void logCodes_misuse() { + Countly.instance().init(healthCheckConfig()); + + Countly.instance().events().recordEvent(""); + Countly.instance().events().recordEvent("count", 0); + Countly.instance().events().startEvent("twice"); + Countly.instance().events().startEvent("twice"); + Countly.instance().events().endEvent("not running"); + Countly.instance().events().cancelEvent("not running"); + Countly.instance().events().startEvent(""); + Countly.instance().views().startView(""); + Countly.instance().views().stopViewWithID("unknown"); + String view = Countly.instance().views().startView("view"); + Countly.instance().views().pauseViewWithID(view); + Countly.instance().views().pauseViewWithID(view); + Countly.session().begin(); + Countly.session().begin(); + Countly.onConsent(); + + JSONObject snapshot = runningCounter().snapshot(); + Assert.assertEquals(1, code(snapshot, "w701")); + Assert.assertEquals(1, code(snapshot, "w750")); + Assert.assertEquals(1, code(snapshot, "w722")); + Assert.assertEquals(1, code(snapshot, "w720")); + Assert.assertEquals(1, code(snapshot, "w721")); + Assert.assertEquals(1, code(snapshot, "w700")); + Assert.assertEquals(1, code(snapshot, "w710")); + Assert.assertEquals(1, code(snapshot, "w730")); + Assert.assertEquals(1, code(snapshot, "w731")); + Assert.assertEquals(1, code(snapshot, "w760")); + Assert.assertEquals(1, code(snapshot, "w402")); + } + + /** + * A call made before init is reported as w101 by the health check of the next start. + */ + @Test + public void logCodes_callBeforeInit() { + Countly.instance().events().recordEvent("too early"); + Countly.instance().init(healthCheckConfig()); + + Assert.assertEquals(1, code(healthChecks().get(0).healthCheck(), "w101")); + } + + /** + * A queued request the server refuses is reported in "sc" and "em" as plain text; a request + * the server accepts changes neither. + */ + @Test + public void failedQueuedRequest_reported() { + Countly.instance().init(healthCheckConfig()); + Transport transport = SDKCore.instance.networking.getTransport(); + + Assert.assertFalse(transport.processResponse(400, "{\"result\":\"App does not exist\"}", 1L)); + Assert.assertTrue(transport.processResponse(200, "{\"result\":\"Success\"}", 2L)); + + JSONObject snapshot = runningCounter().snapshot(); + Assert.assertEquals(400, snapshot.getInt("sc")); + Assert.assertEquals("{\"result\":\"App does not exist\"}", snapshot.getString("em")); + } + + /** + * The counters are stored when the SDK stops and keeps its data, and the next start reports them. + */ + @Test + public void state_storedOnStopAndReportedNextStart() { + serverAnswer = null; + Countly.instance().init(healthCheckConfig()); + Countly.instance().events().cancelEvent("not running"); + Countly.instance().stop(); + + JSONObject stored = new JSONObject((String) TestUtils.getJsonStorageProperty("HEALTH_CHECK")); + Assert.assertEquals(1, stored.getJSONObject("LC").getInt("w721")); + + Countly.instance().init(healthCheckConfig()); + Assert.assertEquals(1, code(healthChecks().get(1).healthCheck(), "w721")); + } + + /** + * An automatically detected crash is counted as a stored number, which the next start reports + * as "crashes" / "record:a". + */ + @Test + public void automaticCrash_reportedNextStart() { + Countly.instance().init(healthCheckConfig()); + SDKCore.instance.config.storageProvider.incrementAutomaticCrashCount(); + Countly.instance().stop(); + + Countly.instance().init(healthCheckConfig()); + Assert.assertEquals(1, usage(healthChecks().get(1).healthCheck(), "crashes", "record:a")); + } +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleLocationsTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleLocationsTests.java index 6784b085d..139c56710 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleLocationsTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleLocationsTests.java @@ -35,6 +35,21 @@ public void disableLocation() { validateLocationRequestInRQ(TestUtils.map("location", ""), 0); } + /** + * Removing the location consent erases the location on the server right away + * Request queue should hold the location request and then one with an empty location + */ + @Test + public void locationConsentRemoval_erasesTheLocation() { + Countly.instance().init(TestUtils.getBaseConfig().enableFeatures(Config.Feature.Location).setRequiresConsent(true)); + Countly.onConsent(Config.Feature.Location); + Countly.instance().location().setLocation("TR", "Izmir", "38.4,27.1", null); + + Countly.onConsentRemoval(Config.Feature.Location); + + validateLocationRequestInRQ(TestUtils.map("location", ""), 1); + } + /** * "disableLocation" * Validating that empty location parameter is not sent because location is not enabled @@ -43,7 +58,8 @@ public void disableLocation() { @Test public void disableLocation_noConsent() { Countly.instance().init(TestUtils.getBaseConfig()); - Assert.assertNull(Countly.instance().location()); + Assert.assertSame(SDKCore.dormantLocation, Countly.instance().location()); + Countly.instance().location().disableLocation(); Assert.assertEquals(0, TestUtils.getCurrentRQ().length); } diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleRemoteConfigTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleRemoteConfigTests.java index 346a8038e..0f24654d3 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleRemoteConfigTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleRemoteConfigTests.java @@ -1,7 +1,11 @@ package ly.count.sdk.java.internal; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; +import java.util.List; import java.util.Map; +import ly.count.sdk.java.Config; import ly.count.sdk.java.Countly; import org.json.JSONArray; import org.json.JSONObject; @@ -134,11 +138,10 @@ public void getValue_nullKey() { @Test public void registerDownloadCallback_null() { Countly.instance().init(TestUtils.getConfigRemoteConfigs()); - ModuleRemoteConfig rcModule = SDKCore.instance.module(ModuleRemoteConfig.class); - Assert.assertEquals(0, rcModule.downloadCallbacks.size()); + Assert.assertEquals(0, SDKCore.instance.remoteConfigDownloadCallbacks.size()); Countly.instance().remoteConfig().registerDownloadCallback(null); - Assert.assertEquals(0, rcModule.downloadCallbacks.size()); + Assert.assertEquals(0, SDKCore.instance.remoteConfigDownloadCallbacks.size()); } /** @@ -149,12 +152,32 @@ public void registerDownloadCallback_null() { @Test public void registerDownloadCallback() { Countly.instance().init(TestUtils.getConfigRemoteConfigs()); - ModuleRemoteConfig rcModule = SDKCore.instance.module(ModuleRemoteConfig.class); - Assert.assertEquals(0, rcModule.downloadCallbacks.size()); + Assert.assertEquals(0, SDKCore.instance.remoteConfigDownloadCallbacks.size()); Countly.instance().remoteConfig().registerDownloadCallback((rResult, error, fullValueUpdate, downloadedValues) -> { }); - Assert.assertEquals(1, rcModule.downloadCallbacks.size()); + Assert.assertEquals(1, SDKCore.instance.remoteConfigDownloadCallbacks.size()); + } + + /** + * "registerDownloadCallback" before the consent + * Validating that a callback registered while remote config does not run is called by the module + * started once the consent is given, and that one removed meanwhile is not + */ + @Test + public void registerDownloadCallback_beforeTheConsent_isCalledOnceRemoteConfigRuns() { + Countly.instance().init(TestUtils.getConfigRemoteConfigs().setRequiresConsent(true)); + List results = new ArrayList<>(); + RCDownloadCallback removed = (rResult, error, fullValueUpdate, downloadedValues) -> results.add(null); + Countly.instance().remoteConfig().registerDownloadCallback((rResult, error, fullValueUpdate, downloadedValues) -> results.add(rResult)); + Countly.instance().remoteConfig().registerDownloadCallback(removed); + Countly.instance().remoteConfig().removeDownloadCallback(removed); + + Countly.onConsent(Config.Feature.RemoteConfig); + SDKCore.instance.config.immediateRequestGenerator = () -> remoteConfigRequestMaker(new JSONObject(), null, null, null); + Countly.instance().remoteConfig().downloadAllKeys(null); + + Assert.assertEquals(Collections.singletonList(RequestResult.Success), results); } /** @@ -165,11 +188,10 @@ public void registerDownloadCallback() { @Test public void removeDownloadCallback_null() { Countly.instance().init(TestUtils.getConfigRemoteConfigs()); - ModuleRemoteConfig rcModule = SDKCore.instance.module(ModuleRemoteConfig.class); - Assert.assertEquals(0, rcModule.downloadCallbacks.size()); + Assert.assertEquals(0, SDKCore.instance.remoteConfigDownloadCallbacks.size()); Countly.instance().remoteConfig().removeDownloadCallback(null); - Assert.assertEquals(0, rcModule.downloadCallbacks.size()); + Assert.assertEquals(0, SDKCore.instance.remoteConfigDownloadCallbacks.size()); } /** @@ -181,11 +203,10 @@ public void removeDownloadCallback_null() { public void removeDownloadCallback() { RCDownloadCallback callback = (rResult, error, fullValueUpdate, downloadedValues) -> Assert.assertEquals(RequestResult.Success, rResult); Countly.instance().init(TestUtils.getConfigRemoteConfigs().remoteConfigRegisterGlobalCallback(callback)); - ModuleRemoteConfig rcModule = SDKCore.instance.module(ModuleRemoteConfig.class); - Assert.assertEquals(1, rcModule.downloadCallbacks.size()); + Assert.assertEquals(1, SDKCore.instance.remoteConfigDownloadCallbacks.size()); Countly.instance().remoteConfig().removeDownloadCallback(callback); - Assert.assertEquals(0, rcModule.downloadCallbacks.size()); + Assert.assertEquals(0, SDKCore.instance.remoteConfigDownloadCallbacks.size()); } /** diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleViewsTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleViewsTests.java index 2c25479da..07fc1d747 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleViewsTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleViewsTests.java @@ -17,8 +17,9 @@ public class ModuleViewsTests { @Before - public void beforeTest() { + public void beforeTest() throws InterruptedException { TestUtils.createCleanTestState(); + TestUtils.awaitStartOfSecond(); } @After diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/RequestCompressionTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/RequestCompressionTests.java new file mode 100644 index 000000000..d72dada10 --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/RequestCompressionTests.java @@ -0,0 +1,498 @@ +package ly.count.sdk.java.internal; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Request compression, against HTTP servers on loopback that read a body as gzip the way the + * Countly server does: only when the compression marker is the only query of the URL. Each + * settings answer carries its own {@code lkl} value, so a test can wait until the SDK has read it. + * The assertions are on what the servers received. + */ +@RunWith(JUnit4.class) +public class RequestCompressionTests { + + private static final String SALT = "gzip-salt"; + private static final int BIG = 5000; + + private GzipStandInServer server; + private GzipStandInServer otherServer; + + /** + * Starts every test without SDK files and with a new server. + */ + @Before + public void beforeTest() throws IOException { + TestUtils.createCleanTestState(); + server = new GzipStandInServer(); + } + + /** + * Stops the SDK, deletes its data and stops the servers. + */ + @After + public void afterTest() { + Countly.instance().halt(); + server.stop(); + if (otherServer != null) { + otherServer.stop(); + } + } + + /** + * Without {@link Config#enableRequestCompression()} the settings request does not ask for + * gzip, and a big request goes plain although the server says it reads gzip. + */ + @Test + public void compressionOff_settingsRequestDoesNotAskAndRequestsArePlain() throws InterruptedException { + server.answer(101, true); + Countly.instance().init(config(server)); + awaitSettings(101); + + queueRequest("big", BIG); + GzipStandInRequest big = server.await(withMarker("big")); + + Assert.assertNull(server.await(withMethod("sc")).params.get("gzip")); + Assert.assertFalse(big.compressed); + Assert.assertEquals(BIG, big.params.get("payload").length()); + Assert.assertFalse(provider().isRequestCompressionAllowed()); + } + + /** + * Once the server says it reads gzip, a body of at least 1 KB goes compressed to the endpoint + * with the marker as the only query, as a form body without a Content-Encoding header, and its + * checksum is the one of the plain body. + */ + @Test + public void compressionOn_serverReadsGzip_bigRequestIsCompressed() throws InterruptedException { + server.answer(101, true); + Countly.instance().init(config(server).enableRequestCompression().enableParameterTamperingProtection(SALT)); + awaitSettings(101); + Assert.assertTrue(provider().isRequestCompressionAllowed()); + + queueRequest("big", BIG); + GzipStandInRequest big = server.await(withMarker("big")); + + Assert.assertEquals("1", server.await(withMethod("sc")).params.get("gzip")); + Assert.assertTrue(big.compressed); + Assert.assertEquals("/i", big.path); + Assert.assertTrue("the compressed body has " + big.bodyBytes + " bytes", big.bodyBytes < 1000); + Assert.assertEquals("application/x-www-form-urlencoded", big.contentType); + Assert.assertNull(big.contentEncoding); + Assert.assertEquals(repeat('a', BIG), big.params.get("payload")); + String[] signed = big.body.split("&checksum256="); + Assert.assertEquals(2, signed.length); + Assert.assertEquals(Utils.digestHex("SHA-256", signed[0] + SALT, null), signed[1]); + } + + /** + * A body under 1 KB goes plain, also as a POST, and a bigger one after it is compressed. + */ + @Test + public void compressionOn_smallRequestStaysPlain() throws InterruptedException { + server.answer(101, true); + Countly.instance().init(config(server).enableRequestCompression().enableForcedHTTPPost()); + awaitSettings(101); + + queueRequest("small", 300); + GzipStandInRequest small = server.await(withMarker("small")); + queueRequest("big", BIG); + GzipStandInRequest big = server.await(withMarker("big")); + + Assert.assertEquals("POST", small.method); + Assert.assertFalse(small.compressed); + Assert.assertTrue(small.bodyBytes < 1024); + Assert.assertTrue(big.compressed); + } + + /** + * A settings answer without the gzip key keeps every body plain. + */ + @Test + public void compressionOn_serverDoesNotSayGzip_requestsArePlain() throws InterruptedException { + server.answer(101, false); + Countly.instance().init(config(server).enableRequestCompression()); + awaitSettings(101); + + queueRequest("big", BIG); + GzipStandInRequest big = server.await(withMarker("big")); + + Assert.assertEquals("1", server.await(withMethod("sc")).params.get("gzip")); + Assert.assertFalse(big.compressed); + Assert.assertFalse(provider().isRequestCompressionAllowed()); + } + + /** + * A body over 1 MB goes plain, as the server refuses a bigger compressed body, and compression + * stays on for the requests after it. + */ + @Test + public void compressionOn_bodyOverOneMegabyteStaysPlain_compressionStaysOn() throws InterruptedException { + server.answer(101, true); + Countly.instance().init(config(server).enableRequestCompression()); + awaitSettings(101); + + queueRequest("huge", Utils.REQUEST_COMPRESSION_MAX_BYTES); + GzipStandInRequest huge = server.await(withMarker("huge")); + queueRequest("big", BIG); + GzipStandInRequest big = server.await(withMarker("big")); + + Assert.assertFalse(huge.compressed); + Assert.assertTrue(huge.bodyBytes > Utils.REQUEST_COMPRESSION_MAX_BYTES); + Assert.assertTrue(big.compressed); + } + + /** + * A refused compressed request stays queued and goes plain on its next try, and so do the + * requests after it. + */ + @Test + public void compressedRequestRefused_retryAndLaterRequestsArePlain() throws InterruptedException { + server.answer(101, true); + server.refuseCompressed.set(1); + Countly.instance().init(config(server).enableRequestCompression()); + awaitSettings(101); + + queueRequest("refused", BIG); + server.await(withMarker("refused")); + awaitSendHandled(); + Countly.instance().attemptToSendStoredRequests(); + Assert.assertTrue(TestUtils.waitFor(15_000, () -> server.count(withMarker("refused")) == 2)); + queueRequest("after", BIG); + GzipStandInRequest after = server.await(withMarker("after")); + + List refused = server.all(withMarker("refused")); + Assert.assertEquals(Arrays.asList(true, false), compressedFlags(refused)); + Assert.assertEquals(refused.get(0).params, refused.get(1).params); + Assert.assertFalse(after.compressed); + } + + /** + * After a refusal stopped compression, a settings answer without gzip leaves it stopped, and the + * next one with "gzip": true turns it on again. + */ + @Test + public void compressedRequestRefused_nextGzipAnswerTurnsCompressionOnAgain() throws InterruptedException { + server.answer(101, true); + server.refuseCompressed.set(1); + Countly.instance().init(config(server).enableRequestCompression()); + awaitSettings(101); + queueRequest("refused", BIG); + server.await(withMarker("refused")); + Assert.assertTrue(TestUtils.waitFor(10_000, () -> !provider().isRequestCompressionAllowed())); + + server.answer(102, false); + fetchSettings(); + awaitSettings(102); + Assert.assertFalse(provider().isRequestCompressionAllowed()); + + server.answer(103, true); + fetchSettings(); + awaitSettings(103); + Assert.assertTrue(TestUtils.waitFor(10_000, () -> provider().isRequestCompressionAllowed())); + awaitSendHandled(); + Countly.instance().attemptToSendStoredRequests(); + queueRequest("after_gzip_answer", BIG); + GzipStandInRequest after = server.await(withMarker("after_gzip_answer")); + + Assert.assertTrue(after.compressed); + Assert.assertEquals(Arrays.asList(true, false), compressedFlags(server.all(withMarker("refused")))); + } + + /** + * A compressed remote config download answered with JSON leaves compression on. + */ + @Test + public void compressedImmediateRequestAnsweredWithJson_compressionStaysOn() throws InterruptedException { + Assert.assertTrue(immediateRequestKeepsCompression(200, "{\"color\":\"red\"}")); + } + + /** + * A compressed remote config download answered with a page, as a proxy in front of the server + * may send, was not accepted: compression stops. + */ + @Test + public void compressedImmediateRequestAnsweredWithPage_stopsCompression() throws InterruptedException { + Assert.assertFalse(immediateRequestKeepsCompression(200, "Bad gateway")); + } + + /** + * A compressed remote config download answered with an error status was not accepted: + * compression stops. + */ + @Test + public void compressedImmediateRequestAnsweredWithError_stopsCompression() throws InterruptedException { + Assert.assertFalse(immediateRequestKeepsCompression(400, "{\"result\":\"Invalid request body\"}")); + } + + /** + * A compressed remote config download answered with nothing was not accepted: compression stops. + */ + @Test + public void compressedImmediateRequestAnsweredWithNothing_stopsCompression() throws InterruptedException { + Assert.assertFalse(immediateRequestKeepsCompression(200, "")); + } + + /** + * A compressed request that failed without an answer does not stop compression: the next try + * goes compressed again. + */ + @Test + public void compressedRequestWithoutAnswer_compressionStaysOn() throws InterruptedException { + server.answer(101, true); + server.dropCompressed.set(true); + Countly.instance().init(config(server).enableRequestCompression()); + awaitSettings(101); + + queueRequest("dropped", BIG); + server.await(withMarker("dropped")); + awaitSendHandled(); + server.dropCompressed.set(false); + Countly.instance().attemptToSendStoredRequests(); + Assert.assertTrue(TestUtils.waitFor(15_000, () -> server.count(withMarker("dropped").and(r -> r.answered.get())) == 1)); + + List dropped = server.all(withMarker("dropped")); + Assert.assertTrue(dropped.size() >= 2); + for (GzipStandInRequest received : dropped) { + Assert.assertTrue(received.compressed); + } + Assert.assertTrue(provider().isRequestCompressionAllowed()); + } + + /** + * The gzip key is read from the live answer only, never stored with the settings. + */ + @Test + public void gzipAnswer_isNotStored() throws InterruptedException { + server.answer(101, true); + Countly.instance().init(config(server).enableRequestCompression()); + awaitSettings(101); + + ModuleConfiguration configuration = SDKCore.instance.module(ModuleConfiguration.class); + synchronized (configuration) { + Assert.assertFalse(configuration.latestRetrievedConfiguration.has("gzip")); + } + String stored = SDKCore.instance.sdkStorage.getServerConfig(); + Assert.assertNotNull(stored); + Assert.assertFalse(stored.contains("gzip")); + } + + /** + * After a server URL change the requests go plain, until the new server says it reads gzip. + */ + @Test + public void serverUrlChange_newServerGetsPlainRequestsUntilItSaysGzip() throws IOException, InterruptedException { + server.answer(101, true); + otherServer = new GzipStandInServer(); + otherServer.answer(102, true); + CountDownLatch release = new CountDownLatch(1); + otherServer.holdSettings.set(release); + Countly.instance().init(config(server).enableRequestCompression()); + awaitSettings(101); + + Countly.instance().changeServerUrl(otherServer.url()); + otherServer.await(withMethod("sc")); + queueRequest("before_answer", BIG); + GzipStandInRequest before = otherServer.await(withMarker("before_answer")); + release.countDown(); + awaitSettings(102); + queueRequest("after_answer", BIG); + GzipStandInRequest after = otherServer.await(withMarker("after_answer")); + + Assert.assertFalse(before.compressed); + Assert.assertTrue(after.compressed); + Assert.assertEquals(0, server.count(withMarker("before_answer"))); + } + + /** + * Only an answer with "gzip": true counts, and the key is removed from it. + */ + @Test + public void extractGzipFlag_onlyTrueCounts() { + JSONObject accepted = new JSONObject("{\"v\":1,\"t\":1,\"c\":{},\"gzip\":true}"); + Assert.assertTrue(ModuleConfiguration.extractGzipFlag(accepted)); + Assert.assertFalse(accepted.has("gzip")); + + for (String answer : new String[] { "{\"gzip\":false}", "{\"gzip\":\"true\"}", "{\"gzip\":1}", "{\"c\":{\"gzip\":true}}", "{}" }) { + Assert.assertFalse(answer, gzipFlagOf(answer)); + } + Assert.assertFalse(ModuleConfiguration.extractGzipFlag(null)); + } + + /** + * Bodies under 1 KB and over 1 MB are left alone, the ones between are compressed into gzip + * that decodes to the body. + */ + @Test + public void gzipRequestBody_bounds() throws IOException { + Log log = new Log(Config.LoggingLevel.OFF, null); + Assert.assertEquals(0, Utils.gzipRequestBody(repeat('a', Utils.REQUEST_COMPRESSION_MIN_BYTES - 1), log).length); + Assert.assertEquals(0, Utils.gzipRequestBody(repeat('a', Utils.REQUEST_COMPRESSION_MAX_BYTES + 1), log).length); + for (int size : new int[] { Utils.REQUEST_COMPRESSION_MIN_BYTES, Utils.REQUEST_COMPRESSION_MAX_BYTES }) { + String body = "app_key=key&payload=" + repeat('a', size - 20); + byte[] compressed = Utils.gzipRequestBody(body, log); + Assert.assertTrue(compressed.length > 0 && compressed.length < body.length()); + Assert.assertEquals(body, gunzipText(compressed)); + } + } + + /** + * The marker fills the empty query of an endpoint, or becomes the query of a URL without one; a + * URL that already has a query cannot carry it. + */ + @Test + public void compressedRequestPath_markerIsTheOnlyQuery() { + Assert.assertEquals("http://host/i?content_encoding=gzip", Transport.compressedRequestPath("http://host/i?")); + Assert.assertEquals("http://host/o/sdk?content_encoding=gzip", Transport.compressedRequestPath("http://host/o/sdk")); + Assert.assertNull(Transport.compressedRequestPath("http://host/o/sdk?method=rc")); + } + + // region helpers + + /** + * Downloads remote config with 120 keys, a compressed POST, answered with the given status and + * text, then tells whether a big request sent after it was compressed. + */ + private boolean immediateRequestKeepsCompression(int remoteConfigCode, String remoteConfigAnswer) throws InterruptedException { + server.answer(101, true); + server.remoteConfigCode.set(remoteConfigCode); + server.remoteConfigAnswer.set(remoteConfigAnswer); + Countly.instance().init(config(server, Config.Feature.RemoteConfig).enableRequestCompression()); + awaitSettings(101); + + String[] keys = new String[120]; + for (int i = 0; i < keys.length; i++) { + keys[i] = "remote_config_key_" + i; + } + CountDownLatch downloaded = new CountDownLatch(1); + Countly.instance().remoteConfig().downloadSpecificKeys(keys, (result, error, fullValueUpdate, values) -> downloaded.countDown()); + Assert.assertTrue(downloaded.await(15, TimeUnit.SECONDS)); + queueRequest("after_download", BIG); + GzipStandInRequest after = server.await(withMarker("after_download")); + + GzipStandInRequest download = server.await(withMethod("rc")); + Assert.assertTrue(download.compressed); + Assert.assertEquals(120, new org.json.JSONArray(download.params.get("keys")).length()); + return after.compressed; + } + + /** + * A configuration that sends to the given server without request cooldowns or health check. + */ + private static Config config(GzipStandInServer server, Config.Feature... features) { + File directory = TestUtils.getTestSDirectory(); + TestUtils.checkSdkStorageRootDirectoryExist(directory); + + Config config = new Config(server.url(), TestUtils.SERVER_APP_KEY, directory); + config.setApplicationVersion(TestUtils.APPLICATION_VERSION); + config.setCustomDeviceId(TestUtils.DEVICE_ID); + config.disableHealthCheck(); + config.enableFeatures(features); + config.setNetworkRequestCooldown(0); + config.setNetworkImportantRequestCooldown(0); + return config; + } + + /** + * The SDK behavior settings in effect. + */ + private static ConfigurationProvider provider() { + return SDKCore.instance.config.getConfigurationProvider(); + } + + /** + * Waits until the SDK has read the settings answer that carries the given {@code lkl} value. + */ + private static void awaitSettings(int lkl) throws InterruptedException { + Assert.assertTrue("the settings answer with lkl " + lkl + " was not read", TestUtils.waitFor(15_000, () -> provider().getMaxKeyLength() == lkl)); + } + + /** + * Fetches the settings again, as the refresh timer does. + */ + private static void fetchSettings() { + SDKCore.instance.module(ModuleConfiguration.class).fetchConfigFromServer(SDKCore.instance.config); + } + + /** + * Queues a request with a payload of the given length, told apart by its marker parameter. + */ + private static void queueRequest(String marker, int payloadLength) { + InternalConfig config = SDKCore.instance.config; + Request request = new Request(); + request.params.add(ModuleRequests.prepareRequiredParams(config)); + request.params.add("marker", marker); + request.params.add("payload", repeat('a', payloadLength)); + ModuleRequests.pushAsync(config, request); + } + + /** + * Waits until the SDK finished handling the request it is sending, so a send asked for next is + * not folded into it. + */ + private static void awaitSendHandled() throws InterruptedException { + Assert.assertTrue("the send in progress must end", TestUtils.waitFor(10_000, () -> !SDKCore.instance.networking.isSending())); + } + + /** + * Matches the request that carries the given marker parameter. + */ + private static Predicate withMarker(String marker) { + return r -> marker.equals(r.params.get("marker")); + } + + /** + * Matches an immediate request of the given method. + */ + private static Predicate withMethod(String method) { + return r -> method.equals(r.params.get("method")); + } + + /** + * Whether each request came compressed. + */ + private static List compressedFlags(List requests) { + return requests.stream().map(r -> r.compressed).collect(Collectors.toList()); + } + + /** + * A text of the given length made of one character. + */ + private static String repeat(char c, int length) { + char[] chars = new char[length]; + Arrays.fill(chars, c); + return new String(chars); + } + + /** + * Reads the gzip flag of a settings answer given as text. + */ + private static boolean gzipFlagOf(String answer) { + return ModuleConfiguration.extractGzipFlag(new JSONObject(answer)); + } + + /** + * Decodes gzip bytes into text. + */ + private static String gunzipText(byte[] compressed) throws IOException { + return new String(GzipStandInRequest.gunzip(compressed), StandardCharsets.UTF_8); + } + + // endregion +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/RequestScenarioTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/RequestScenarioTests.java new file mode 100644 index 000000000..70b2fb730 --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/RequestScenarioTests.java @@ -0,0 +1,541 @@ +package ly.count.sdk.java.internal; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; +import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; +import org.json.JSONArray; +import org.json.JSONObject; +import org.json.JSONTokener; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * In each request scenario the SDK queues the requests sdk-java/api/requests/[scenario].json records, with the values + * that change from run to run masked. The scenarios make the calls the other Countly SDKs make in their own request + * tests. A deliberate change: run COUNTLY_UPDATE_REQUESTS=1 ./gradlew :sdk-java:test --tests '*RequestScenarioTests' + * --rerun, which writes the records, check the difference and add a line to CHANGELOG.md. + */ +@RunWith(JUnit4.class) +public class RequestScenarioTests { + + private static final String MASK = ""; + private static final List MASKED_PARAMS = Arrays.asList("timestamp", "hour", "dow", "tz", "sdk_version", "av", "rr", "checksum", "checksum256", "session_duration", "session_id"); + private static final List JSON_PARAMS = Arrays.asList("events", "metrics", "user_details", "crash", "consent", "hc"); + private static final List MASKED_EVENT_FIELDS = Arrays.asList("timestamp", "hour", "dow", "id", "pvid", "cvid", "peid"); + private static final List MASKED_VIEW_FIELDS = Arrays.asList("timestamp", "hour", "dow", "id", "pvid", "cvid", "peid", "dur"); + private static final List MASKED_CRASH_FIELDS = Arrays.asList("_error", "_run", "_os", "_os_version", "_resolution", "_density", "_locale", "_device", "_device_type", "_manufacture", "_cpu", "_opengl", "_ram_current", "_ram_total", "_disk_current", "_disk_total", "_bat", "_orientation", "_root", "_online", "_muted", "_background"); + // a view's "segment" is the operating system the SDK runs on + private static final List MASKED_VIEW_SEGMENTS = Arrays.asList("segment"); + private static final List FULLY_MASKED_PARAMS = Arrays.asList("metrics", "hc"); + private static final String EVENTS_PARAM = "events"; + private static final String CRASH_PARAM = "crash"; + private static final String VIEW_KEY = "[CLY]_view"; + private static final File RECORDS = new File("api/requests"); + private static final long SETTLE_QUIET_MS = 500; + private static final long SETTLE_LIMIT_MS = 10_000; + private static final char FIRST_PRINTABLE = ' '; + + /** + * The calls of a scenario. + */ + private interface Scenario { + /** + * Makes the calls of the scenario. + * + * @throws InterruptedException when waiting for the SDK is interrupted + */ + void run() throws InterruptedException; + } + + /** + * Starts every scenario from an empty SDK storage, with fixed device details, no metric overrides that other tests + * left and without the timer of a test that shortened it. + * + * @throws ReflectiveOperationException when the device's metric overrides cannot be reached + */ + @Before + @SuppressWarnings("PMD.AvoidAccessibilityAlteration") + public void setUp() throws ReflectiveOperationException { + TestUtils.createCleanTestState(); + CountlyTimer.TIMER_DELAY_MS = 0; + TestUtils.setAdditionalDeviceMetrics(); + // every test shares the device, and its API can only add metric overrides + Field metricOverride = Device.class.getDeclaredField("metricOverride"); + metricOverride.setAccessible(true); + ((Map) metricOverride.get(Device.dev)).clear(); + } + + /** + * Stops the SDK and empties its storage. + */ + @After + public void tearDown() { + TestUtils.createCleanTestState(); + } + + /** + * A session with an event of every segmentation value type, the user details and a session update. + * + * @throws IOException when the record cannot be read or written + * @throws InterruptedException when waiting for the SDK is interrupted + */ + @Test + public void parity() throws IOException, InterruptedException { + assertRequests("parity", config(), () -> { + Countly.session().begin(); + Countly.instance().events().recordEvent("purchase", paritySegmentation(), 2, 9.99, 5.0); + Map properties = new ConcurrentHashMap<>(); + properties.put("name", "John Doe"); + properties.put("username", "john_d"); + properties.put("email", "john@example.com"); + properties.put("organization", "Countly"); + properties.put("phone", "1234567890"); + properties.put("picture", "https://example.com/picture.jpg"); + properties.put("gender", "M"); + properties.put("byear", 1980); + properties.put("tier", "gold"); + properties.put("age", 30); + Countly.instance().userProfile().setProperties(properties); + Countly.instance().userProfile().save(); + // a session update reports elapsed seconds, so at least one has to pass for it to be sent + Thread.sleep(1100); + Countly.session().update(); + Countly.session().end(); + }); + } + + /** + * Two views in a session, the first with segmentation. + * + * @throws IOException when the record cannot be read or written + * @throws InterruptedException when waiting for the SDK is interrupted + */ + @Test + public void views() throws IOException, InterruptedException { + assertRequests("views", config(), () -> { + Countly.session().begin(); + Map segmentation = new ConcurrentHashMap<>(); + segmentation.put("source", "scenario"); + Countly.instance().views().startView("Home", segmentation); + Countly.instance().views().stopViewWithName("Home"); + Countly.instance().views().startView("Settings"); + Countly.session().end(); + }); + } + + /** + * A handled exception with a breadcrumb and segmentation. + * + * @throws IOException when the record cannot be read or written + * @throws InterruptedException when waiting for the SDK is interrupted + */ + @Test + public void crash() throws IOException, InterruptedException { + assertRequests("crash", config(), () -> { + Countly.instance().crashes().addCrashBreadcrumb("breadcrumb one"); + Map segmentation = new ConcurrentHashMap<>(); + segmentation.put("tier", "gold"); + Countly.instance().crashes().recordHandledException(new Exception("parity crash"), segmentation); + }); + } + + /** + * Consent given for sessions and events, then taken back for events. + * + * @throws IOException when the record cannot be read or written + * @throws InterruptedException when waiting for the SDK is interrupted + */ + @Test + public void consent() throws IOException, InterruptedException { + assertRequests("consent", config().setRequiresConsent(true), () -> { + Countly.onConsent(Config.Feature.Sessions, Config.Feature.Events); + Countly.session().begin(); + Countly.instance().events().recordEvent("consented"); + settle(); + Countly.onConsentRemoval(Config.Feature.Events); + Countly.instance().events().recordEvent("not_consented"); + Countly.session().end(); + }); + } + + /** + * A device ID change with merge, then one without. + * + * @throws IOException when the record cannot be read or written + * @throws InterruptedException when waiting for the SDK is interrupted + */ + @Test + public void deviceId() throws IOException, InterruptedException { + assertRequests("device-id", config(), () -> { + Countly.session().begin(); + Countly.instance().deviceId().changeWithMerge("parity-device-002"); + Countly.instance().events().recordEvent("after_merge"); + settle(); + Countly.instance().deviceId().changeWithoutMerge("parity-device-003"); + Countly.instance().events().recordEvent("after_new_id"); + Countly.session().end(); + }); + } + + /** + * The init config every scenario starts from: the parity app key and device ID, a server that cannot be reached so + * that every request stays queued, and the features the scenarios use. + * + * @return config + */ + private Config config() { + return new Config("https://parity.example", "parity-app-key", TestUtils.getTestSDirectory()) + .setCustomDeviceId("parity-device-001") + .enableFeatures(Config.Feature.Events, Config.Feature.Sessions, Config.Feature.Views, Config.Feature.CrashReporting, Config.Feature.UserProfiles) + .setLoggingLevel(Config.LoggingLevel.VERBOSE); + } + + /** + * The event segmentation of the parity scenario, with one value of every type. + * + * @return segmentation + */ + private Map paritySegmentation() { + Map segmentation = new ConcurrentHashMap<>(); + segmentation.put("nar", "uto"); + segmentation.put("sasuke", Integer.MAX_VALUE); + segmentation.put("sakura", false); + segmentation.put("itachi", Double.MAX_VALUE); + segmentation.put("kakaski", Double.MIN_VALUE); + segmentation.put("hashirama", -Integer.MAX_VALUE); + Map tobi = new ConcurrentHashMap<>(); + tobi.put("obito", "uchiha"); + tobi.put("zetsu", "white"); + segmentation.put("tobi", tobi); + segmentation.put("stringList", Arrays.asList("value1", "value2", "value3")); + segmentation.put("intList", Arrays.asList(1, 2, 3)); + segmentation.put("doubleList", Arrays.asList(1.1, 2.2, 3.3)); + segmentation.put("boolList", Arrays.asList(true, false, true)); + segmentation.put("mixedList", Arrays.asList("value1", 2, 3.3, true)); + segmentation.put("mapList", Arrays.asList(mapListEntry(1), mapListEntry(2), mapListEntry(3))); + return segmentation; + } + + /** + * An entry of the parity scenario's list of objects. + * + * @param index position of the entry, from 1 + * @return the entry + */ + private Map mapListEntry(int index) { + Map entry = new ConcurrentHashMap<>(); + entry.put("key1", "value" + index); + entry.put("key2", index + 1); + return entry; + } + + /** + * Moves the recorded events into the request queue and waits until the queue stops growing, so that what the calls + * before queued stays apart from what follows. + * + * @throws InterruptedException when waiting is interrupted + */ + private void settle() throws InterruptedException { + // without the events consent the module is not loaded + ModuleEvents events = SDKCore.instance.module(ModuleEvents.class); + if (events != null) { + events.onTimer(); + } + int count = -1; + long quietSince = System.currentTimeMillis(); + long started = quietSince; + while (System.currentTimeMillis() - started < SETTLE_LIMIT_MS) { + Thread.sleep(50); + int queued = TestUtils.getCurrentRQ().length; + if (queued == count) { + if (System.currentTimeMillis() - quietSince > SETTLE_QUIET_MS) { + return; + } + } else { + count = queued; + quietSince = System.currentTimeMillis(); + } + } + Assert.fail("the request queue kept changing for 10 seconds"); + } + + /** + * Runs a scenario on a new SDK instance and compares the requests it queued with the record of the scenario, or + * writes the record when COUNTLY_UPDATE_REQUESTS is set. + * + * @param name scenario name, the record file name without .json + * @param config init config + * @param scenario the calls + * @throws IOException when the record cannot be read or written + * @throws InterruptedException when waiting for the SDK is interrupted + */ + private void assertRequests(String name, Config config, Scenario scenario) throws IOException, InterruptedException { + Countly.instance().init(config); + scenario.run(); + settle(); + String current = report(TestUtils.getCurrentRQ()); + File file = new File(RECORDS, name + ".json"); + if (System.getenv("COUNTLY_UPDATE_REQUESTS") != null) { + Files.createDirectories(RECORDS.toPath()); + Files.write(file.toPath(), current.getBytes(StandardCharsets.UTF_8)); + return; + } + String committed = file.exists() ? new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8).replace("\r\n", "\n") : "(no sdk-java/api/requests/" + name + ".json)\n"; + Assert.assertEquals("the requests of the " + name + " scenario differ from sdk-java/api/requests/" + name + ".json. If that is deliberate, run COUNTLY_UPDATE_REQUESTS=1 ./gradlew :sdk-java:test --tests '*RequestScenarioTests' --rerun, check the difference and add a line to CHANGELOG.md.", committed, current); + } + + /** + * The record of queued requests as the SDK sends them: each with its path and its parameters, the values that + * change from run to run masked, the JSON parameters parsed and the keys of every object sorted. + * + * @param requests the request queue, as TestUtils.getCurrentRQ gives it + * @return file content + */ + private String report(Map[] requests) { + StringBuilder out = new StringBuilder(8192).append('['); + for (int i = 0; i < requests.length; i++) { + out.append(i == 0 ? "\n" : ",\n").append(" {\n \"path\": "); + string(out, pathOf(requests[i])); + out.append(",\n \"params\": "); + write(out, recordedParams(requests[i]), " "); + out.append("\n }"); + } + return out.append(requests.length == 0 ? "]\n" : "\n]\n").toString(); + } + + /** + * The path a queued request is sent to: its endpoint without the query mark, or /i. + * + * @param request the queued request's parameters + * @return the path + */ + private String pathOf(Map request) { + String endpoint = request.get(Request.ENDPOINT); + return endpoint == null ? "/i" : endpoint.replaceAll("\\?$", ""); + } + + /** + * The parameters of a queued request as the SDK sends them, with the values that change from run to run masked and + * the JSON parameters parsed. + * + * @param request the queued request's parameters + * @return the parameters + */ + private JSONObject recordedParams(Map request) { + JSONObject params = new JSONObject(); + for (Map.Entry param : request.entrySet()) { + String name = param.getKey(); + // the SDK takes both out of a queued request before it sends it + if (Request.MODULE.equals(name) || Request.ENDPOINT.equals(name)) { + continue; + } + if (MASKED_PARAMS.contains(name)) { + params.put(name, MASK); + } else if (JSON_PARAMS.contains(name) && !param.getValue().isEmpty()) { + params.put(name, maskedJson(name, parsed(param.getValue()))); + } else { + params.put(name, param.getValue()); + } + } + return params; + } + + /** + * The value a JSON parameter holds. + * + * @param json the parameter's text + * @return the parsed value + */ + private Object parsed(String json) { + return new JSONTokener(json).nextValue(); + } + + /** + * The value of a JSON parameter with the values that change from run to run masked. + * + * @param name parameter name + * @param value parsed parameter value + * @return the masked value + */ + private Object maskedJson(String name, Object value) { + if (FULLY_MASKED_PARAMS.contains(name) && value instanceof JSONObject) { + return masked((JSONObject) value, keys((JSONObject) value)); + } + if (EVENTS_PARAM.equals(name) && value instanceof JSONArray) { + JSONArray events = (JSONArray) value; + JSONArray result = new JSONArray(); + for (int i = 0; i < events.length(); i++) { + result.put(maskedEvent(events.getJSONObject(i))); + } + return result; + } + if (CRASH_PARAM.equals(name) && value instanceof JSONObject) { + return masked((JSONObject) value, MASKED_CRASH_FIELDS); + } + return value; + } + + /** + * An event with the values that change from run to run masked, for a view also in its segmentation. + * + * @param event the event + * @return the masked copy + */ + private JSONObject maskedEvent(JSONObject event) { + if (!VIEW_KEY.equals(event.optString("key"))) { + return masked(event, MASKED_EVENT_FIELDS); + } + JSONObject view = masked(event, MASKED_VIEW_FIELDS); + JSONObject segmentation = view.optJSONObject("segmentation"); + if (segmentation != null) { + view.put("segmentation", masked(segmentation, MASKED_VIEW_SEGMENTS)); + } + return view; + } + + /** + * A copy of an object with the values of the given keys masked. + * + * @param value object + * @param fields keys to mask + * @return the masked copy + */ + private JSONObject masked(JSONObject value, List fields) { + JSONObject copy = new JSONObject(); + for (String key : keys(value)) { + copy.put(key, fields.contains(key) ? MASK : value.get(key)); + } + return copy; + } + + /** + * The keys of an object, sorted. + * + * @param value object + * @return keys + */ + private List keys(JSONObject value) { + TreeSet keys = new TreeSet<>(); + Iterator it = value.keys(); + while (it.hasNext()) { + keys.add(it.next()); + } + return new ArrayList<>(keys); + } + + /** + * Writes a JSON value with two-space indentation and sorted object keys, escaping only what JSON requires. + * + * @param out where to write + * @param value JSON value + * @param indent indentation of the line the value starts on + */ + private void write(StringBuilder out, Object value, String indent) { + if (value instanceof JSONObject) { + writeObject(out, (JSONObject) value, indent); + } else if (value instanceof JSONArray) { + writeArray(out, (JSONArray) value, indent); + } else if (value instanceof String) { + string(out, (String) value); + } else if (value == null || value == JSONObject.NULL) { + out.append("null"); + } else { + out.append(value); + } + } + + /** + * Writes a JSON object with its keys sorted. + * + * @param out where to write + * @param value the object + * @param indent indentation of the line the object starts on + */ + private void writeObject(StringBuilder out, JSONObject value, String indent) { + List keys = keys(value); + if (keys.isEmpty()) { + out.append("{}"); + return; + } + out.append('{'); + for (int i = 0; i < keys.size(); i++) { + out.append(i == 0 ? "\n" : ",\n").append(indent).append(" "); + string(out, keys.get(i)); + out.append(": "); + write(out, value.get(keys.get(i)), indent + " "); + } + out.append('\n').append(indent).append('}'); + } + + /** + * Writes a JSON array. + * + * @param out where to write + * @param array the array + * @param indent indentation of the line the array starts on + */ + private void writeArray(StringBuilder out, JSONArray array, String indent) { + if (array.length() == 0) { + out.append("[]"); + return; + } + out.append('['); + for (int i = 0; i < array.length(); i++) { + out.append(i == 0 ? "\n" : ",\n").append(indent).append(" "); + write(out, array.get(i), indent + " "); + } + out.append('\n').append(indent).append(']'); + } + + /** + * Writes a JSON string, escaping quotes, backslashes and control characters. + * + * @param out where to write + * @param value text + */ + private void string(StringBuilder out, String value) { + out.append('"'); + for (char c : value.toCharArray()) { + switch (c) { + case '"': + out.append("\\\""); + break; + case '\\': + out.append("\\\\"); + break; + case '\n': + out.append("\\n"); + break; + case '\r': + out.append("\\r"); + break; + case '\t': + out.append("\\t"); + break; + default: + if (c < FIRST_PRINTABLE) { + out.append(String.format("\\u%04x", (int) c)); + } else { + out.append(c); + } + break; + } + } + out.append('"'); + } +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/RequestTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/RequestTests.java index 5535dd273..39a7c18f9 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/RequestTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/RequestTests.java @@ -24,6 +24,20 @@ private static String getEOR() throws Exception { return (String) field.get(null); } + /** + * Requests created faster than the clock moves get strictly increasing ids, so none of them is + * stored in the file of another. + */ + @Test + public void request_burstGetsDistinctIncreasingIds() { + long previous = new Request().storageId(); + for (int i = 0; i < 1_000; i++) { + long id = new Request().storageId(); + Assert.assertTrue(id + " is not greater than the previous id " + previous, id > previous); + previous = id; + } + } + @Test public void request_constructorString() { String paramVals = "a=1&b=2"; diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ScenarioInitRecoveryTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ScenarioInitRecoveryTests.java index da006423f..7eb14a1f5 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ScenarioInitRecoveryTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ScenarioInitRecoveryTests.java @@ -45,7 +45,7 @@ private JSONObject createCrashData(String error, boolean nonfatal) { } private long plantCrashFile(JSONObject crashData) { - long crashId = TimeUtils.uniqueTimestampMs(); + long crashId = TimeUtils.uniqueStorageId(); TestUtils.writeToFile("crash_" + crashId, crashData.toString()); return crashId; } @@ -197,6 +197,20 @@ public void init_withCrashAndSessionFiles() throws InterruptedException { // ── Corrupt/empty file resilience ─────────────────────────────────── + /** + * "init_withBrokenStoreFile" + * A store file cut short, as a process stopped while writing leaves it, must not stop the SDK + * from initializing: the storage starts empty instead of throwing to the application. + */ + @Test + public void init_withBrokenStoreFile() { + TestUtils.writeToFile(SDKStorage.JSON_FILE_NAME, "{\"did\":\"generated_uuid\",\"sc\":\"{\\\"c\\\":{"); + + Countly.instance().init(TestUtils.getBaseConfig()); + + Assert.assertTrue("SDK should be initialized even with a broken store file", Countly.isInitialized()); + } + /** * "init_withCorruptCrashFile" * Corrupt crash file should not block initialization. diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ScenarioRequestQueueStallTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ScenarioRequestQueueStallTests.java index 7dab91b7f..f03adca92 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ScenarioRequestQueueStallTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ScenarioRequestQueueStallTests.java @@ -94,7 +94,9 @@ private Config configForLocalServer() { .setLoggingLevel(Config.LoggingLevel.VERBOSE) .setDeviceIdStrategy(Config.DeviceIdStrategy.UUID) .enableFeatures(Config.Feature.Events, Config.Feature.Sessions) - .setEventQueueSizeToSend(1); + .setEventQueueSizeToSend(1) + // request #1 can be held past the backoff's accepted timeout, and a backoff would hold the backlog past the drain timeout + .disableBackoffMechanism(); } /** diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/SdkLogGatheringTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/SdkLogGatheringTests.java new file mode 100644 index 000000000..fd502a1ac --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/SdkLogGatheringTests.java @@ -0,0 +1,1367 @@ +package ly.count.sdk.java.internal; + +import com.sun.net.httpserver.HttpServer; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; +import ly.count.sdk.java.internal.ConfigurationProvider.LogGatheringState; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import static ly.count.sdk.java.internal.ServerConfigBuilder.names; +import static org.mockito.Mockito.mock; + +/** + * Operator armed SDK log gathering: the {@code lg} directive of a live SDK behavior settings + * response arms it, and the SDK uploads its own log lines as the {@code sdk_logs} parameter of + * requests of their own, {@code {"i":gatherId,"d":dropped,"l":[{"t":ms,"l":"e","m":message}]}}. + *

+ * The settings request goes through a {@link ModuleConfigurationTests.ServerConfigResponder}, which + * answers on the calling thread, so the directive of the fetch made at init is applied before init + * returns. Batches are queued on the delivery thread of the logger; a test waits for it with + * {@link #awaitLogDelivery()} and reads the batches off the request queue. Unless a test is about + * sending, the responses switch networking off, so every queued request stays on disk. The lines a + * test counts are logged at a level the SDK does not use in these flows, mostly {@code e}. + */ +@RunWith(JUnit4.class) +public class SdkLogGatheringTests { + + private static final String REQUEST_FILE_PREFIX = "[CLY]_request_"; + + private ModuleConfigurationTests.ServerConfigResponder server; + + /** + * Starts every test from empty storage, with the default timer and a fresh responder. + */ + @Before + public void beforeTest() { + TestUtils.createCleanTestState(); + SDKCore.testDummyModule = null; + CountlyTimer.TIMER_DELAY_MS = 0; + server = new ModuleConfigurationTests.ServerConfigResponder(); + } + + /** + * Stops the SDK, clearing its data, and restores the default timer. + */ + @After + public void afterTest() { + Countly.instance().halt(); + CountlyTimer.TIMER_DELAY_MS = 0; + } + + // region scenarios + + /** + * An armed directive adopts what was captured before it arrived. + *

+ * Verifies against a local server that the lines of the directive's levels logged during init, + * before any response, are uploaded once init finishes, the very first line of the SDK first; + * that every batch echoes the gather id, carries the required request parameters and at most + * {@code b} lines, each with exactly {@code t}, {@code l} and {@code m}, none of another level + * and none quoting a batch; that a partial batch waits for a flush while no batch is in flight; + * that a full batch goes out on its own, the lines after it following once it is sent; and that + * a full batch is too long for a GET, so it is sent as a POST. An unknown top level key next to + * {@code lg} changes none of it. + */ + @Test + public void armedDirective_uploadsTheInitLinesOfItsLevels_withTheGatherIdInBatchesOfAtMostB() throws Exception { + long startMs = System.currentTimeMillis(); + List requests = new CopyOnWriteArrayList<>(); + HttpServer httpServer = startRecordingServer(requests); + try { + server.respondWith(new ServerConfigBuilder() + .logGatheringOn("gather_init", "wi", 10) + .topLevelKey("someFutureFeature", "a value this SDK has never heard of")); + init(localConfig(httpServer)); + assertGathering("gather_init", "wi", 10); + + awaitSentBatches(); + List initBatches = receivedBatches(requests); + Assert.assertFalse("init end queued nothing", initBatches.isEmpty()); + Assert.assertEquals("[SDKCore] Initializing Countly", initBatches.get(0).getJSONArray("l").getJSONObject(0).getString("m")); + + List partialLines = numbered("[Test] partial line ", 0, 5); + for (String line : partialLines) { + logger().w(line); + } + awaitLogDelivery(); + Thread.sleep(200); + Assert.assertTrue(linesStartingWith("[Test] partial line ", receivedBatches(requests)).isEmpty()); + logger().flushGatheredLogs(); + awaitSentBatches(); + Assert.assertEquals(partialLines, linesStartingWith("[Test] partial line ", receivedBatches(requests))); + + String padding = repeat('p', 80); + List armedLines = new ArrayList<>(); + for (int i = 0; i < 25; i++) { + armedLines.add("[Test] armed line " + i + " " + padding); + logger().w(armedLines.get(i)); + } + awaitSentBatches(); + Assert.assertEquals(armedLines, linesStartingWith("[Test] armed line ", receivedBatches(requests))); + + int fullArmedBatches = 0; + for (ReceivedRequest request : requests) { + if (!request.params.containsKey(Log.keySdkLogs)) { + continue; + } + TestUtils.validateRequiredParams(request.params); + JSONObject batch = new JSONObject(request.params.get(Log.keySdkLogs)); + Assert.assertEquals(names("i", "d", "l"), batch.keySet()); + Assert.assertEquals("gather_init", batch.getString("i")); + Assert.assertEquals(0, batch.getInt("d")); + + JSONArray lines = batch.getJSONArray("l"); + Assert.assertTrue("a batch of [" + lines.length() + "] lines", lines.length() >= 1 && lines.length() <= 10); + for (int i = 0; i < lines.length(); i++) { + JSONObject line = lines.getJSONObject(i); + Assert.assertEquals(names("t", "l", "m"), line.keySet()); + long timestamp = line.getLong("t"); + Assert.assertTrue(timestamp >= startMs && timestamp <= System.currentTimeMillis()); + Assert.assertTrue("w".equals(line.getString("l")) || "i".equals(line.getString("l"))); + Assert.assertFalse(line.getString("m").contains(Log.keySdkLogs)); + } + if (request.params.get(Log.keySdkLogs).contains("[Test] armed line 9 ")) { + Assert.assertEquals("a full batch fits a GET", "POST", request.method); + fullArmedBatches++; + } + } + Assert.assertEquals(1, fullArmedBatches); + } finally { + Countly.instance().halt(); + httpServer.stop(0); + } + } + + /** + * While tracking is off the lines are held, the buffer keeps the newest 500 of them, and the + * lines it drops are reported once, with the next batch. + *

+ * Verifies against a local server that nothing is queued while tracking is off, flush or not; + * that once tracking is back on the held lines go out oldest first in full batches of {@code b}, + * one at a time as each is sent, the first one reporting every dropped line in {@code d}, so the + * uploaded and the dropped lines add up to every line logged; and that a {@code b} over the + * buffer ceiling is clamped to it, so no batch ever holds more than 500 lines. + */ + @Test + public void trackingOffHold_keepsTheNewest500Lines_andDAccountsForEveryDroppedLine() throws Exception { + List requests = new CopyOnWriteArrayList<>(); + HttpServer httpServer = startRecordingServer(requests); + try { + server.respondWith(heldGather("gather_hold", "e", 25)); + init(localConfig(httpServer)); + assertGathering("gather_hold", "e", 25); + + Log logger = logger(); + //what the SDK logged at the same level during init is held too, and is the oldest + int initLines = logger.heldLogLineCount(); + for (int i = 0; i < 520; i++) { + logger.e("[Test] held line " + i); + } + Assert.assertEquals(ModuleConfiguration.logGatheringMaxBufferedLines, logger.heldLogLineCount()); + Assert.assertEquals(initLines + 20, logger.droppedLogLineCount); + logger.flushGatheredLogs(); + awaitLogDelivery(); + Assert.assertEquals(ModuleConfiguration.logGatheringMaxBufferedLines, logger.heldLogLineCount()); + Assert.assertTrue(logRequests().isEmpty()); + + push(new ServerConfigBuilder().tracking(true).logGatheringOn("gather_hold", "e", 25)); + assertGathering("gather_hold", "e", 25); + logger.flushGatheredLogs(); + awaitSentBatches(); + Assert.assertEquals(0, logger.heldLogLineCount()); + + List batches = receivedBatches(requests); + Assert.assertEquals(20, batches.size()); + List uploaded = new ArrayList<>(); + int dropped = 0; + for (int b = 0; b < batches.size(); b++) { + JSONObject batch = batches.get(b); + Assert.assertEquals("gather_hold", batch.getString("i")); + Assert.assertEquals(b == 0 ? initLines + 20 : 0, batch.getInt("d")); + Assert.assertEquals(25, batch.getJSONArray("l").length()); + dropped += batch.getInt("d"); + uploaded.addAll(messagesOf(batch)); + } + Assert.assertEquals(numbered("[Test] held line ", 20, 520), uploaded); + Assert.assertEquals(initLines + 520, uploaded.size() + dropped); + + push(heldGather("gather_hold", "e", 9999)); + assertGathering("gather_hold", "e", ModuleConfiguration.logGatheringMaxBufferedLines); + int heldBefore = logger.heldLogLineCount(); + for (int i = 0; i < 600; i++) { + logger.e("[Test] second line " + i); + } + push(new ServerConfigBuilder().tracking(true).logGatheringOn("gather_hold", "e", 9999)); + logger.flushGatheredLogs(); + awaitSentBatches(); + + List later = receivedBatches(requests).subList(20, receivedBatches(requests).size()); + Assert.assertEquals(1, later.size()); + Assert.assertEquals(heldBefore + 100, later.get(0).getInt("d")); + Assert.assertEquals(numbered("[Test] second line ", 100, 600), messagesOf(later.get(0))); + } finally { + Countly.instance().halt(); + httpServer.stop(0); + } + } + + /** + * Every way a gather ends leaves nothing held, and a new gather never carries the lines of an + * earlier one. + *

+ * Verifies, with tracking off so nothing leaves until the end, that the same directive repeated + * and a change of levels or batch size within one gather keep the held lines; that + * {@code "e":false}, a directive without a usable gather id and a live response without any + * directive each stop the capture and release the delivery thread, their held lines offered to + * the request queue once, which refuses them while tracking is off; that a new gather id drops + * the lines of the previous gather; and that only the lines of the gather in effect, with its id, + * are ever uploaded. + */ + @Test + public void endedOrReplacedGather_leavesNothingHeld_andANewGatherNeverCarriesTheOldOnes() throws Exception { + server.respondWith(heldGather("gather_a", "e", 10)); + init(TestUtils.getConfigSdkBehaviorSettings()); + Log logger = logger(); + int initLines = logger.heldLogLineCount(); + logger.e("[Test] a1"); + logger.e("[Test] a2"); + Assert.assertEquals(initLines + 2, logger.heldLogLineCount()); + + push(heldGather("gather_a", "e", 10)); + Assert.assertEquals(initLines + 2, logger.heldLogLineCount()); + push(heldGather("gather_a", "ew", 20)); + assertGathering("gather_a", "ew", 20); + Assert.assertTrue(logger.heldLogLineCount() >= initLines + 2); + push(heldGather("gather_a", "e", 10)); + assertGathering("gather_a", "e", 10); + Assert.assertEquals(initLines + 2, logger.heldLogLineCount()); + + pushStop(new ServerConfigBuilder().networking(false).tracking(false).logGatheringOff()); + assertNotGathering(); + logger.e("[Test] logged while off"); + Assert.assertEquals(0, logger.heldLogLineCount()); + + push(heldGather("gather_b", "e", 10)); + assertGathering("gather_b", "e", 10); + Assert.assertEquals(0, logger.heldLogLineCount()); + logger.e("[Test] b1"); + push(heldGather("gather_c", "e", 10)); + assertGathering("gather_c", "e", 10); + Assert.assertEquals(0, logger.heldLogLineCount()); + logger.e("[Test] c1"); + + pushStop(new ServerConfigBuilder().networking(false).tracking(false).logGatheringDirective(true, " ", "e", 10)); + assertNotGathering(); + + push(heldGather("gather_d", "e", 10)); + logger.e("[Test] d1"); + pushStop(new ServerConfigBuilder().networking(false).tracking(false)); + assertNotGathering(); + + push(heldGather("gather_e", "e", 10)); + logger.e("[Test] e1"); + logger.e("[Test] e2"); + push(new ServerConfigBuilder().networking(false).tracking(true).logGatheringOn("gather_e", "e", 10)); + logger.flushGatheredLogs(); + awaitLogDelivery(); + + List batches = batches(); + Assert.assertEquals(1, batches.size()); + Assert.assertEquals("gather_e", batches.get(0).getString("i")); + Assert.assertEquals(0, batches.get(0).getInt("d")); + Assert.assertEquals(Arrays.asList("[Test] e1", "[Test] e2"), linesStartingWith("[Test] ", batches)); + } + + /** + * Only a live response decides. + *

+ * Verifies that an armed directive in the stored settings leaves the logger undecided, still + * capturing the init lines speculatively and queueing nothing even when flushed; that a run + * whose fetch fails decides off, lets go of what it held and captures nothing more; that a + * running gather survives a failed refresh with its lines; and that a stopped logger ignores + * every later line. + */ + @Test + public void onlyALiveResponseDecides_storedDirectiveStaysUndecided_andAFailedFetchDecidesOffOnlyWhileUndecided() throws Exception { + TestUtils.writeToFile(SDKStorage.JSON_FILE_NAME, new JSONObject() + .put("sc", new ServerConfigBuilder().networking(false).logGatheringOn("stored_gather_id", "ewidv", 40).build()).toString()); + server.pending(); + init(TestUtils.getConfigSdkBehaviorSettings()); + + Log undecided = logger(); + Assert.assertEquals(LogGatheringState.UNDECIDED, undecided.logGatheringState); + Assert.assertNull(undecided.logGatherId); + Assert.assertTrue(undecided.isCapturingLogs()); + Assert.assertFalse(undecided.isGatheringLogs()); + Assert.assertTrue(undecided.heldLogLineCount() > 0); + undecided.flushGatheredLogs(); + Assert.assertNull(undecided.logDeliveryExecutor); + Assert.assertTrue(logRequests().isEmpty()); + Countly.instance().stop(); + + Assert.assertEquals(LogGatheringState.NOT_GATHERING, undecided.logGatheringState); + undecided.e("[Test] logged after stop"); + Assert.assertEquals(0, undecided.heldLogLineCount()); + + server.failing(); + init(TestUtils.getConfigSdkBehaviorSettings()); + Log failed = logger(); + Assert.assertEquals(LogGatheringState.NOT_GATHERING, failed.logGatheringState); + Assert.assertEquals(0, failed.heldLogLineCount()); + failed.e("[Test] logged after the failed fetch"); + Assert.assertEquals(0, failed.heldLogLineCount()); + Countly.instance().halt(); + + server.respondWith(heldGather("gather_live", "e", 10)); + init(TestUtils.getConfigSdkBehaviorSettings()); + Log live = logger(); + live.e("[Test] kept across a failed refresh"); + int held = live.heldLogLineCount(); + Assert.assertTrue(held > 0); + server.failing(); + module().fetchConfigFromServer(SDKCore.instance.config); + assertGathering("gather_live", "e", 10); + Assert.assertEquals(held, live.heldLogLineCount()); + } + + /** + * While consent is required, a gathered line goes out only once the consent of the feature it + * belongs to is given, a line of no feature needs both the events and the user profiles + * consent, and the coordinates handed to a session are logged only with location consent. + *

+ * Verifies, with networking off, that the batch queued with only the sessions consent given + * holds no line of another feature and no coordinates; that the stop that follows events consent + * queues the events line but neither the location line nor the line of no feature; and that + * with location consent given the coordinates are gathered. + */ + @Test + public void requiredConsent_gathersEachLineOnlyWithTheConsentOfItsFeature() throws Exception { + Config config = TestUtils.getConfigSdkBehaviorSettings().setRequiresConsent(true) + .enableFeatures(Config.Feature.Events, Config.Feature.Sessions, Config.Feature.Location, Config.Feature.UserProfiles); + server.respondWith(new ServerConfigBuilder().networking(false).logGatheringOn("gather_consent", "ewidv", 500)); + init(config); + assertGathering("gather_consent", "ewidv", 500); + + Log logger = logger(); + logger.e("[Test] a line of no feature"); + logger.e("[ModuleEvents] an events line"); + logger.e("[ModuleLocation] a location line"); + Countly.onConsent(Config.Feature.Sessions); + Countly.session().begin(); + ((SessionImpl) Countly.session()).addLocation(12.345_678, 98.765_432); + logger.flushGatheredLogs(); + awaitLogDelivery(); + + List queued = receivedLines(batches()); + Assert.assertFalse(queued.isEmpty()); + Assert.assertFalse(queued.contains("[Test] a line of no feature")); + Assert.assertFalse(queued.contains("[ModuleEvents] an events line")); + Assert.assertFalse(queued.contains("[ModuleLocation] a location line")); + for (String line : queued) { + Assert.assertFalse(line, line.contains("12.345678")); + } + Assert.assertTrue(logger.awaitingConsentLineCount() >= 3); + + Countly.onConsent(Config.Feature.Events); + Countly.instance().stop(); + List stopped = receivedLines(storedBatchesOnDisk()); + Assert.assertTrue(stopped.contains("[ModuleEvents] an events line")); + Assert.assertFalse(stopped.contains("[ModuleLocation] a location line")); + Assert.assertFalse(stopped.contains("[Test] a line of no feature")); + for (String line : stopped) { + Assert.assertFalse(line, line.contains("12.345678")); + } + + server.respondWith(new ServerConfigBuilder().networking(false).logGatheringOn("gather_location", "ewidv", 500)); + init(config); + Countly.onConsent(Config.Feature.Sessions, Config.Feature.Location); + Countly.session().begin(); + ((SessionImpl) Countly.session()).addLocation(12.345_678, 98.765_432); + Countly.instance().stop(); + boolean coordinatesGathered = false; + for (JSONObject batch : storedBatchesOnDisk()) { + if ("gather_location".equals(batch.getString("i"))) { + for (String line : messagesOf(batch)) { + coordinatesGathered |= line.contains("12.345678"); + } + } + } + Assert.assertTrue(coordinatesGathered); + } + + /** + * While consent is required, a feature the app did not enable holds no line back, and a removed + * consent drops the held lines of its feature. + *

+ * Verifies, with networking off and the user profiles feature not enabled, that a line of no + * feature is gathered once the events and sessions consents are given; and that after the + * events consent is removed the stop queues the held sessions line but not the held events line. + */ + @Test + public void requiredConsent_aFeatureNotEnabledHoldsNoLineBack_andARemovedConsentDropsItsLines() throws Exception { + Config config = TestUtils.getConfigSdkBehaviorSettings().setRequiresConsent(true) + .enableFeatures(Config.Feature.Events, Config.Feature.Sessions); + server.respondWith(new ServerConfigBuilder().networking(false).logGatheringOn("gather_enabled", "e", 500)); + init(config); + Log logger = logger(); + logger.e("[Test] a line of no feature"); + Countly.onConsent(Config.Feature.Events, Config.Feature.Sessions); + logger.flushGatheredLogs(); + awaitLogDelivery(); + Assert.assertTrue(receivedLines(batches()).contains("[Test] a line of no feature")); + + logger.e("[ModuleEvents] a held events line"); + logger.e("[SessionImpl] a held sessions line"); + Countly.onConsentRemoval(Config.Feature.Events); + Countly.instance().stop(); + + List stopped = receivedLines(storedBatchesOnDisk()); + Assert.assertTrue(stopped.contains("[SessionImpl] a held sessions line")); + Assert.assertFalse(stopped.contains("[ModuleEvents] a held events line")); + } + + /** + * The global timer flushes a batch that is not full, a stop queues what is held before the + * storage stops, and a halt discards it. Either way the logger ends for good. + *

+ * Verifies that a line below the batch size reaches a local server on a tick of a fast global + * timer; that, with networking off, {@code stop()} queues the held line synchronously, so it is + * on disk once stop returns, with the gather id; that the stopped logger captures and queues + * nothing more and its delivery thread ends; and that {@code halt()} queues nothing at all. + */ + @Test + public void timerTick_flushesAPartialBatch_stopQueuesWhatIsHeld_andHaltDiscardsIt() throws Exception { + List queuedLogRequests = new CopyOnWriteArrayList<>(); + LogCallback listener = (message, level) -> { + if (message != null && message.startsWith("New request ") && message.contains(Log.transportMarker)) { + queuedLogRequests.add(message); + } + }; + List requests = new CopyOnWriteArrayList<>(); + HttpServer httpServer = startRecordingServer(requests); + try { + server.respondWith(new ServerConfigBuilder().logGatheringOn("gather_tick", "e", 100)); + init(localConfig(httpServer).setLogListener(listener)); + Log logger = logger(); + awaitSentBatches(); + + //the timer ticks through the modules, so it is sped up only after init built them + CountlyTimer.TIMER_DELAY_MS = 50; + push(new ServerConfigBuilder().sessionUpdateInterval(30).logGatheringOn("gather_tick", "e", 100)); + logger.e("[Test] tick line"); + Assert.assertTrue("no tick flushed the partial batch", TestUtils.waitFor(10_000, () -> !linesStartingWith("[Test] tick line", receivedBatches(requests)).isEmpty())); + + CountlyTimer.TIMER_DELAY_MS = 0; + push(new ServerConfigBuilder().networking(false).sessionUpdateInterval(60).logGatheringOn("gather_tick", "e", 100)); + //a tick of the replaced fast timer may still be running + Thread.sleep(250); + awaitLogDelivery(); + logger.e("[Test] tail line"); + Assert.assertEquals(1, logger.heldLogLineCount()); + Set deliveryThreads = liveDeliveryThreads(); + Assert.assertFalse(deliveryThreads.isEmpty()); + int queuedBeforeStop = queuedLogRequests.size(); + + Countly.instance().stop(); + Assert.assertEquals(queuedBeforeStop + 1, queuedLogRequests.size()); + JSONObject tail = null; + for (JSONObject batch : storedBatchesOnDisk()) { + if (messagesOf(batch).contains("[Test] tail line")) { + tail = batch; + } + } + Assert.assertNotNull("stop did not queue the held line", tail); + Assert.assertEquals("gather_tick", tail.getString("i")); + Assert.assertEquals(Arrays.asList("[Test] tail line"), messagesOf(tail)); + + Assert.assertEquals(LogGatheringState.NOT_GATHERING, logger.logGatheringState); + logger.e("[Test] logged after stop"); + logger.flushGatheredLogs(); + Assert.assertEquals(0, logger.heldLogLineCount()); + Assert.assertNull(logger.logDeliveryExecutor); + Assert.assertEquals(queuedBeforeStop + 1, queuedLogRequests.size()); + Assert.assertTrue("the delivery thread outlived the SDK", TestUtils.waitFor(5_000, () -> { + for (Thread thread : deliveryThreads) { + if (thread.isAlive()) { + return false; + } + } + return true; + })); + + server.respondWith(new ServerConfigBuilder().networking(false).logGatheringOn("gather_halt", "e", 100)); + init(TestUtils.getConfigSdkBehaviorSettings().setLogListener(listener)); + Log halted = logger(); + assertGathering("gather_halt", "e", 100); + awaitLogDelivery(); + int heldAtStart = halted.heldLogLineCount(); + halted.e("[Test] halted line"); + Assert.assertEquals(heldAtStart + 1, halted.heldLogLineCount()); + int queuedBeforeHalt = queuedLogRequests.size(); + + Countly.instance().halt(); + Assert.assertEquals(queuedBeforeHalt, queuedLogRequests.size()); + Assert.assertEquals(LogGatheringState.NOT_GATHERING, halted.logGatheringState); + Assert.assertEquals(0, halted.heldLogLineCount()); + } finally { + Countly.instance().halt(); + httpServer.stop(0); + } + } + + /** + * The threads that upload a batch never gather what they log meanwhile, or every upload would + * report on itself, while the lines about ordinary requests are gathered. + *

+ * Verifies against a local server that, once uploads and an ordinary event request were sent, + * no uploaded line quotes a batch, comes from the delivery thread or reports the preparing, + * sending or completion of an upload, while the completion of the event request is reported. + */ + @Test + public void uploadThreads_neverGatherTheirOwnLines_whileLinesAboutOrdinaryRequestsAreGathered() throws Exception { + List requests = new CopyOnWriteArrayList<>(); + HttpServer httpServer = startRecordingServer(requests); + + List heard = new CopyOnWriteArrayList<>(); + try { + Config config = localConfig(httpServer) + .enableFeatures(Config.Feature.Events) + .setEventQueueSizeToSend(1) + .setLogListener((message, level) -> heard.add(message)); + server.respondWith(new ServerConfigBuilder().logGatheringOn("gather_net", "ewidv", 50)); + init(config); + + Assert.assertTrue("no upload arrived", TestUtils.waitFor(30_000, () -> !receivedBatches(requests).isEmpty())); + Assert.assertTrue("no upload completed", TestUtils.waitFor(30_000, () -> !completedRequests(heard, requestIds(heard, Log.transportMarker)).isEmpty())); + + Countly.instance().events().recordEvent("ordinary_event"); + Assert.assertTrue("the event request never arrived", TestUtils.waitFor(30_000, () -> requests.stream().anyMatch(request -> request.params.containsKey("events")))); + Assert.assertTrue("the event request never completed", TestUtils.waitFor(30_000, () -> !completedRequests(heard, requestIds(heard, "events=")).isEmpty())); + Set eventIds = completedRequests(heard, requestIds(heard, "events=")); + + logger().flushGatheredLogs(); + Assert.assertTrue("the completion of the event request was not uploaded", TestUtils.waitFor(30_000, () -> { + for (String line : receivedLines(receivedBatches(requests))) { + for (String eventId : eventIds) { + if (line.startsWith("[Networking] Request " + eventId + " sent?: true")) { + return true; + } + } + } + return false; + })); + + Set uploadIds = completedRequests(heard, requestIds(heard, Log.transportMarker)); + Assert.assertFalse(uploadIds.isEmpty()); + for (JSONObject batch : receivedBatches(requests)) { + Assert.assertEquals("gather_net", batch.getString("i")); + } + for (String line : receivedLines(receivedBatches(requests))) { + Assert.assertFalse(line, line.contains(Log.keySdkLogs)); + Assert.assertFalse(line, line.startsWith("[Log] deliverHeldLogBatches")); + for (String uploadId : uploadIds) { + Assert.assertFalse(line, line.contains("Request " + uploadId + " sent?")); + Assert.assertFalse(line, line.contains("for request[" + uploadId + "]")); + } + } + } finally { + Countly.instance().halt(); + httpServer.stop(0); + } + } + + /** + * An armed SDK that is otherwise idle uploads nothing about its own uploads. + *

+ * Verifies against a local server that once the lines logged before went out a tick uploads + * nothing, that a line logged then goes out in one batch on the next tick, and that the ticks + * after that upload nothing, as neither queueing nor sending a batch, nor the drain that + * follows it, is gathered. + */ + @Test + public void idleArmedSdk_uploadsNothingAboutItsOwnUploads_onTheTicksAfterAnUpload() throws Exception { + List requests = new CopyOnWriteArrayList<>(); + HttpServer httpServer = startRecordingServer(requests); + try { + server.respondWith(new ServerConfigBuilder().logGatheringOn("gather_idle", "ewidv", 100)); + init(localConfig(httpServer)); + + awaitIdleTicks(requests); + logger().e("[Test] idle probe"); + Assert.assertEquals(1, tickAndCountBatches(requests)); + List received = receivedBatches(requests); + Assert.assertTrue(messagesOf(received.get(received.size() - 1)).contains("[Test] idle probe")); + for (int tick = 0; tick < 3; tick++) { + Assert.assertEquals("tick " + tick, 0, tickAndCountBatches(requests)); + } + Assert.assertEquals(0, logger().heldLogLineCount()); + } finally { + Countly.instance().halt(); + httpServer.stop(0); + } + } + + /** + * While nothing is sent, one log batch waits in the request queue and the rest stays in the + * capped buffer; once networking is back on, the batches go out one after another until nothing + * is held. + *

+ * Verifies, with networking off, that full batches and flushes queue nothing while a batch + * waits, the lines staying held; then, with networking on against a local server, that every + * held line arrives once, in order, with never more than one batch stored at a time. + */ + @Test + public void networkingOff_queuesOneBatchAtATime_andTheRestFollowsOnceItIsSent() throws Exception { + List requests = new CopyOnWriteArrayList<>(); + HttpServer httpServer = startRecordingServer(requests); + try { + server.respondWith(new ServerConfigBuilder().networking(false).logGatheringOn("gather_offline", "e", 10)); + init(localConfig(httpServer)); + awaitLogDelivery(); + Log logger = logger(); + for (int i = 0; i < 30; i++) { + logger.e("[Test] offline line " + i); + } + for (int flush = 0; flush < 3; flush++) { + logger.flushGatheredLogs(); + awaitLogDelivery(); + } + Assert.assertEquals(1, storedBatchCount()); + Assert.assertTrue(logger.heldLogLineCount() >= 20); + + push(new ServerConfigBuilder().logGatheringOn("gather_offline", "e", 10)); + int mostStored = 0; + long end = System.currentTimeMillis() + 30_000; + while (System.currentTimeMillis() < end) { + mostStored = Math.max(mostStored, storedBatchCount()); + if (logger.heldLogLineCount() == 0 && storedBatchCount() == 0) { + break; + } + Thread.sleep(5); + } + awaitSentBatches(); + Assert.assertEquals(1, mostStored); + Assert.assertEquals(numbered("[Test] offline line ", 0, 30), linesStartingWith("[Test] offline line ", receivedBatches(requests))); + } finally { + Countly.instance().halt(); + httpServer.stop(0); + } + } + + /** + * A device ID change without merge queues the gathered lines under the previous device ID and + * stops the gather, an answer requested for a previous device ID does not arm it again, and a + * change with merge keeps a gather running. + *

+ * Verifies, with networking off, that the line logged before the change is stored before the + * change returns, under the previous device ID and with the gather id; that nothing logged + * afterwards is held; that a settings answer requested before a later change and applied after + * it leaves the gather stopped while its other settings apply; that an answer for the current + * device ID arms a gather again; that a change with merge leaves that gather running; and that + * an answer requested before a change with merge arms its gather. + */ + @Test + public void deviceIdChangeWithoutMerge_queuesTheLinesUnderThePreviousId_andStopsTheGather() throws Exception { + server.respondWith(new ServerConfigBuilder().networking(false).logGatheringOn("gather_user_a", "e", 100)); + init(TestUtils.getConfigSdkBehaviorSettings()); + awaitLogDelivery(); + logger().e("[Test] line of user A"); + Countly.instance().deviceId().changeWithoutMerge("user_B"); + + Map userA = null; + for (Map request : logRequests()) { + if (request.get(Log.keySdkLogs).contains("[Test] line of user A")) { + userA = request; + } + } + Assert.assertNotNull("the line of user A was not queued before the change", userA); + Assert.assertEquals(TestUtils.DEVICE_ID, userA.get("device_id")); + Assert.assertEquals("gather_user_a", new JSONObject(userA.get(Log.keySdkLogs)).getString("i")); + assertNotGathering(); + logger().e("[Test] line of user B"); + Assert.assertEquals(0, logger().heldLogLineCount()); + + AtomicReference heldAnswer = new AtomicReference<>(); + InternalConfig config = SDKCore.instance.config; + config.immediateRequestGenerator = () -> (requestData, customEndpoint, transport, requestShouldBeDelayed, networkingIsEnabled, callback, log) -> heldAnswer.set(callback); + module().fetchConfigFromServer(config); + Assert.assertNotNull(heldAnswer.get()); + Countly.instance().deviceId().changeWithoutMerge("user_C"); + heldAnswer.get().callback(new JSONObject(new ServerConfigBuilder().networking(false).sessionUpdateInterval(45).logGatheringOn("gather_stale", "e", 100).build())); + assertNotGathering(); + Assert.assertEquals(45, module().getSessionUpdateInterval()); + + config.immediateRequestGenerator = server; + push(new ServerConfigBuilder().networking(false).logGatheringOn("gather_user_c", "e", 100)); + assertGathering("gather_user_c", "e", 100); + Countly.instance().deviceId().changeWithMerge("user_D"); + assertGathering("gather_user_c", "e", 100); + + config.immediateRequestGenerator = () -> (requestData, customEndpoint, transport, requestShouldBeDelayed, networkingIsEnabled, callback, log) -> heldAnswer.set(callback); + module().fetchConfigFromServer(config); + Countly.instance().deviceId().changeWithMerge("user_E"); + heldAnswer.get().callback(new JSONObject(new ServerConfigBuilder().networking(false).logGatheringOn("gather_after_merge", "e", 100).build())); + assertGathering("gather_after_merge", "e", 100); + } + + /** + * A gather the server stops queues the lines it held once, with its id, and a gather replaced + * by a new id drops them. + *

+ * Verifies, with networking off and tracking on, that after {@code "e":false} exactly the lines + * held until then are stored, in one batch with the stopped gather's id, past the batch already + * waiting, and nothing logged afterwards; and that a gather replaced by a new id holds none of + * the lines of the one before. + */ + @Test + public void stoppedGather_queuesItsHeldLinesOnce_whileAReplacedGatherDropsThem() throws Exception { + server.respondWith(new ServerConfigBuilder().networking(false).logGatheringOn("gather_stopped", "e", 100)); + init(TestUtils.getConfigSdkBehaviorSettings()); + awaitLogDelivery(); + logger().e("[Test] stopped 1"); + logger().e("[Test] stopped 2"); + + push(new ServerConfigBuilder().networking(false).logGatheringOff()); + assertNotGathering(); + Assert.assertTrue("the held lines were not queued", TestUtils.waitFor(10_000, () -> linesStartingWith("[Test] stopped ", batches()).size() == 2)); + JSONObject tail = null; + for (JSONObject batch : batches()) { + if (messagesOf(batch).contains("[Test] stopped 1")) { + tail = batch; + } + } + Assert.assertNotNull(tail); + Assert.assertEquals("gather_stopped", tail.getString("i")); + Assert.assertEquals(Arrays.asList("[Test] stopped 1", "[Test] stopped 2"), linesStartingWith("[Test] stopped ", Arrays.asList(tail))); + logger().e("[Test] after the stop"); + Thread.sleep(200); + Assert.assertTrue(linesStartingWith("[Test] after the stop", batches()).isEmpty()); + + push(new ServerConfigBuilder().networking(false).logGatheringOn("gather_first", "e", 100)); + logger().e("[Test] first gather line"); + Assert.assertTrue(logger().heldLogLineCount() >= 1); + push(new ServerConfigBuilder().networking(false).logGatheringOn("gather_second", "e", 100)); + assertGathering("gather_second", "e", 100); + Assert.assertEquals(0, logger().heldLogLineCount()); + } + + /** + * Queueing a batch that is given up while the storage is busy cancels its store. + *

+ * Verifies, with the storage thread held busy, that a queueing interrupted while it waits for + * the store reports the batch as not queued, and that the store never runs once the storage is + * free again, so the batch is not stored behind the lines kept for another batch. + */ + @Test + public void queueingABatch_givenUpWhileTheStorageIsBusy_cancelsItsStore() throws Exception { + server.respondWith(new ServerConfigBuilder().networking(false).logGatheringOff()); + init(TestUtils.getConfigSdkBehaviorSettings()); + InternalConfig config = SDKCore.instance.config; + Storage.await(mock(Log.class)); + int storedBefore = logRequests().size(); + + CountDownLatch storageBusy = new CountDownLatch(1); + CountDownLatch storageFree = new CountDownLatch(1); + Storage.removeAsync(config, new Request(1L), removed -> { + storageBusy.countDown(); + storageFree.await(30, TimeUnit.SECONDS); + }); + AtomicReference queuedBatch = new AtomicReference<>(-1L); + Thread queueing = new Thread(() -> queuedBatch.set(ModuleRequests.pushSdkLogs(config, "{\"i\":\"gather_cancel\",\"d\":0,\"l\":[]}"))); + try { + Assert.assertTrue(storageBusy.await(30, TimeUnit.SECONDS)); + queueing.start(); + Assert.assertTrue("the queueing never waited for its store", TestUtils.waitFor(30_000, () -> isWaitingForAFuture(queueing))); + queueing.interrupt(); + queueing.join(30_000); + } finally { + storageFree.countDown(); + } + + Assert.assertNull(queuedBatch.get()); + Storage.await(mock(Log.class)); + Assert.assertEquals(storedBefore, logRequests().size()); + } + + // endregion + // region helpers + + /** + * A request a local server received. + */ + private static final class ReceivedRequest { + final String method; + final Map params; + + /** + * Holds one request. + * + * @param method the HTTP method it came with + * @param params its parameters, from the query and the body + */ + ReceivedRequest(String method, Map params) { + this.method = method; + this.params = params; + } + } + + /** + * Starts a local server that accepts every request and records it. + * + * @param requests where the requests go, in arrival order + * @return the started server + * @throws IOException when the server cannot start + */ + private static HttpServer startRecordingServer(List requests) throws IOException { + HttpServer httpServer = HttpServer.create(new InetSocketAddress("localhost", 0), 0); + httpServer.createContext("/", exchange -> { + String query = exchange.getRequestURI().getRawQuery(); + requests.add(new ReceivedRequest(exchange.getRequestMethod(), decode((query == null ? "" : query) + "&" + readAll(exchange.getRequestBody())))); + byte[] body = "{\"result\":\"Success\"}".getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, body.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(body); + } + }); + httpServer.start(); + return httpServer; + } + + /** + * The log batches among the requests a local server received. + * + * @param requests the requests, in arrival order + * @return the batches, in arrival order + */ + private static List receivedBatches(List requests) { + List received = new ArrayList<>(); + for (ReceivedRequest request : requests) { + if (request.params.containsKey(Log.keySdkLogs)) { + received.add(new JSONObject(request.params.get(Log.keySdkLogs))); + } + } + return received; + } + + /** + * The test configuration, sending to a local server instead of the test server. + * + * @param httpServer the local server + * @return the configuration + */ + private static Config localConfig(HttpServer httpServer) { + return new Config("http://localhost:" + httpServer.getAddress().getPort(), TestUtils.SERVER_APP_KEY, TestUtils.getTestSDirectory()) + .setApplicationVersion(TestUtils.APPLICATION_VERSION) + .setCustomDeviceId(TestUtils.DEVICE_ID) + .setNetworkRequestCooldown(0); + } + + /** + * Waits until every batch the logger queued was sent and no delivery is left to run, as each + * sent batch lets the next one go. + * + * @throws Exception when the batches are not all sent in time + */ + private static void awaitSentBatches() throws Exception { + for (int round = 0; round < 200; round++) { + awaitLogDelivery(); + Assert.assertTrue("a queued batch never reached the server", TestUtils.waitFor(30_000, () -> storedBatchCount() == 0)); + //the networking removes a sent batch before it lets the logger queue the next one + awaitNetworking(); + awaitLogDelivery(); + if (storedBatchCount() == 0) { + return; + } + } + Assert.fail("the logger kept queueing batches"); + } + + /** + * Waits until the networking finished the task it was running, the handling of a sent request + * included. + */ + private static void awaitNetworking() { + SDKCore core = SDKCore.instance; + if (core != null && core.networking instanceof DefaultNetworking) { + ((DefaultNetworking) core.networking).tasks.await(); + } + } + + /** + * The log batches stored on disk, read straight from the request files, which works once the + * SDK stopped too. + * + * @return the batches + * @throws IOException when a request file cannot be read + */ + private static List storedBatchesOnDisk() throws IOException { + List stored = new ArrayList<>(); + for (String params : storedRequestParams()) { + Map decoded = decode(params); + if (decoded.containsKey(Log.keySdkLogs)) { + stored.add(new JSONObject(decoded.get(Log.keySdkLogs))); + } + } + return stored; + } + + /** + * Ticks until a tick queues no batch, which an idle SDK reaches once the lines it logged before + * went out, as nothing it logs about a batch is gathered. + * + * @param requests the requests a local server received + * @throws Exception when a batch does not go out in time + */ + private static void awaitIdleTicks(List requests) throws Exception { + for (int tick = 0; tick < 10; tick++) { + if (tickAndCountBatches(requests) == 0) { + return; + } + } + Assert.fail("every tick queued another batch, so each batch reported on the one before"); + } + + /** + * Flushes what is held, as a timer tick does, waits until the batches it queued are sent, then + * lets the drain that follows them run. + * + * @param requests the requests a local server received + * @return how many batches the tick queued + * @throws Exception when a batch does not go out in time + */ + private static int tickAndCountBatches(List requests) throws Exception { + int before = settledBatchCount(requests); + logger().flushGatheredLogs(); + awaitLogDelivery(); + int after = settledBatchCount(requests); + //nothing tells when the drain a stored batch asked for has finished, so it gets a moment + Thread.sleep(200); + return after - before; + } + + /** + * How many batches a local server received, counted once every stored one was sent. + * + * @param requests the requests a local server received + * @return the number of batches + * @throws InterruptedException when interrupted while waiting + */ + private static int settledBatchCount(List requests) throws InterruptedException { + Assert.assertTrue("a queued batch never reached the server", TestUtils.waitFor(30_000, () -> storedBatchCount() == 0)); + return receivedBatches(requests).size(); + } + + /** + * How many stored requests carry a log batch, read straight from disk, skipping a request the + * queue removes while it is read. + * + * @return the number of requests + */ + private static int storedBatchCount() { + File[] files = TestUtils.getTestSDirectory().listFiles((directory, name) -> name.startsWith(REQUEST_FILE_PREFIX)); + int count = 0; + for (File file : files == null ? new File[0] : files) { + try { + if (new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8).contains(Log.transportMarker)) { + count++; + } + } catch (IOException ignored) { + //sent and removed while it was read + } + } + return count; + } + + /** + * Whether a thread is waiting for the result of a future. + * + * @param thread the thread + * @return {@code true} while it waits in {@link java.util.concurrent.Future#get} + */ + private static boolean isWaitingForAFuture(Thread thread) { + for (StackTraceElement frame : thread.getStackTrace()) { + if ("java.util.concurrent.FutureTask".equals(frame.getClassName()) && "get".equals(frame.getMethodName())) { + return true; + } + } + return false; + } + + /** + * Initializes the SDK with {@link #server} answering its settings requests. + * + * @param config the configuration + */ + private void init(Config config) { + InternalConfig internalConfig = new InternalConfig(config); + internalConfig.immediateRequestGenerator = server; + Countly.instance().init(internalConfig); + } + + /** + * Answers the next settings request with the given payload and makes the SDK fetch, as the + * refresh timer does. + * + * @param builder the payload + */ + private void push(ServerConfigBuilder builder) { + server.respondWith(builder); + module().fetchConfigFromServer(SDKCore.instance.config); + } + + /** + * Answers the next settings request with a payload that stops the gather, makes the SDK fetch, + * and waits until the delivery thread offered the last batch of the stopped gather to the + * request queue and ended, so the settings that follow cannot change how the queue answers. + * + * @param builder the payload + * @throws InterruptedException when interrupted while waiting + */ + private void pushStop(ServerConfigBuilder builder) throws InterruptedException { + ExecutorService executor = logger().logDeliveryExecutor; + push(builder); + if (executor != null) { + Assert.assertTrue("the delivery thread did not end", executor.awaitTermination(30, TimeUnit.SECONDS)); + } + } + + /** + * An armed directive next to settings that switch tracking off, so the gathered lines are held, + * and networking off, so nothing queued is sent. + * + * @param gatherId {@code i} + * @param levels {@code l} + * @param batchSize {@code b} + * @return the payload + */ + private static ServerConfigBuilder heldGather(String gatherId, String levels, int batchSize) { + return new ServerConfigBuilder().networking(false).tracking(false).logGatheringOn(gatherId, levels, batchSize); + } + + /** + * The configuration module of the running SDK. + * + * @return the module + */ + private static ModuleConfiguration module() { + return SDKCore.instance.module(ModuleConfiguration.class); + } + + /** + * The logger of the running SDK. + * + * @return the logger + */ + private static Log logger() { + return SDKCore.instance.L; + } + + /** + * Waits until every delivery the logger was asked for so far ran, and until the storage wrote + * every request it was handed. + * + * @throws Exception when the delivery thread does not finish in time + */ + private static void awaitLogDelivery() throws Exception { + ExecutorService executor = logger().logDeliveryExecutor; + if (executor != null) { + executor.submit(() -> { + }).get(30, TimeUnit.SECONDS); + } + Storage.await(mock(Log.class)); + } + + /** + * Asserts the directive twice over: as the configuration module decided it and as the logger + * mirrors it, which is what decides the capture. + * + * @param gatherId the gather id + * @param levels the level characters + * @param batchSize the batch size + */ + private static void assertGathering(String gatherId, String levels, int batchSize) { + ConfigurationProvider provider = SDKCore.instance.config.getConfigurationProvider(); + Assert.assertEquals(LogGatheringState.GATHERING, provider.getLogGatheringState()); + Assert.assertEquals(gatherId, provider.getLogGatheringId()); + Assert.assertEquals(levels, provider.getLogGatheringLevels()); + Assert.assertEquals(batchSize, provider.getLogGatheringBatchSize()); + + Log logger = logger(); + Assert.assertEquals(LogGatheringState.GATHERING, logger.logGatheringState); + Assert.assertTrue(logger.isGatheringLogs()); + Assert.assertTrue(logger.isCapturingLogs()); + Assert.assertEquals(gatherId, logger.logGatherId); + Assert.assertEquals(levels, logger.logGatherLevels); + Assert.assertEquals(batchSize, logger.logGatherBatchSize); + } + + /** + * Asserts that a decision against gathering was mirrored: nothing is captured or held, no + * gather id is left and no delivery thread is kept. + */ + private static void assertNotGathering() { + ConfigurationProvider provider = SDKCore.instance.config.getConfigurationProvider(); + Assert.assertEquals(LogGatheringState.NOT_GATHERING, provider.getLogGatheringState()); + Assert.assertNull(provider.getLogGatheringId()); + + Log logger = logger(); + Assert.assertEquals(LogGatheringState.NOT_GATHERING, logger.logGatheringState); + Assert.assertFalse(logger.isGatheringLogs()); + Assert.assertFalse(logger.isCapturingLogs()); + Assert.assertNull(logger.logGatherId); + Assert.assertEquals(ModuleConfiguration.logGatheringAllLevels, logger.logGatherLevels); + Assert.assertEquals(ModuleConfiguration.logGatheringDefaultBatchSize, logger.logGatherBatchSize); + Assert.assertEquals(0, logger.heldLogLineCount()); + Assert.assertNull(logger.logDeliveryExecutor); + } + + /** + * The queued requests that carry a log batch, oldest first. + * + * @return the parameters of each request + */ + private static List> logRequests() { + List> requests = new ArrayList<>(); + for (Map request : TestUtils.getCurrentRQ()) { + if (request.containsKey(Log.keySdkLogs)) { + requests.add(request); + } + } + return requests; + } + + /** + * The queued log batches, oldest first. + * + * @return the batches + */ + private static List batches() { + List batches = new ArrayList<>(); + for (Map request : logRequests()) { + batches.add(new JSONObject(request.get(Log.keySdkLogs))); + } + return batches; + } + + /** + * The messages of a batch, in order. + * + * @param batch the batch + * @return the messages + */ + private static List messagesOf(JSONObject batch) { + List messages = new ArrayList<>(); + JSONArray lines = batch.getJSONArray("l"); + for (int i = 0; i < lines.length(); i++) { + messages.add(lines.getJSONObject(i).getString("m")); + } + return messages; + } + + /** + * The messages of every batch that start with the given prefix, in upload order. + * + * @param prefix the prefix + * @param batches the batches + * @return the messages + */ + private static List linesStartingWith(String prefix, List batches) { + List messages = new ArrayList<>(); + for (JSONObject batch : batches) { + for (String message : messagesOf(batch)) { + if (message.startsWith(prefix)) { + messages.add(message); + } + } + } + return messages; + } + + /** + * The messages of every batch a server received. + * + * @param received the batches, in arrival order + * @return the messages + */ + private static List receivedLines(List received) { + List messages = new ArrayList<>(); + for (JSONObject batch : new ArrayList<>(received)) { + messages.addAll(messagesOf(batch)); + } + return messages; + } + + /** + * The storage IDs of the queued requests whose parameters contain the given text, read off + * the lines the SDK logs as it queues a request. + * + * @param heard every line the SDK logged + * @param paramsFragment the text + * @return the IDs + */ + private static Set requestIds(List heard, String paramsFragment) { + Pattern queued = Pattern.compile("^New request (\\d+): "); + Set ids = new HashSet<>(); + for (String line : heard) { + Matcher matcher = queued.matcher(line == null ? "" : line); + if (matcher.find() && line.contains(paramsFragment)) { + ids.add(matcher.group(1)); + } + } + return ids; + } + + /** + * The given requests the SDK reported as sent and accepted. + * + * @param heard every line the SDK logged + * @param ids storage IDs of requests + * @return the IDs of those that completed + */ + private static Set completedRequests(List heard, Set ids) { + Set completed = new HashSet<>(); + for (String line : heard) { + for (String id : ids) { + if (line != null && line.startsWith("[Networking] Request " + id + " sent?: true")) { + completed.add(id); + } + } + } + return completed; + } + + /** + * The live delivery threads of every logger. + * + * @return the threads + */ + private static Set liveDeliveryThreads() { + Set threads = new HashSet<>(); + for (Thread thread : Thread.getAllStackTraces().keySet()) { + if (Log.DELIVERY_THREAD_NAME.equals(thread.getName()) && thread.isAlive()) { + threads.add(thread); + } + } + return threads; + } + + /** + * The parameters of every stored request, oldest first, read straight from disk, so they can be + * read after the storage stopped. + * + * @return the url encoded parameters of each request + * @throws IOException when a request cannot be read + */ + private static List storedRequestParams() throws IOException { + File[] files = TestUtils.getTestSDirectory().listFiles((directory, name) -> name.startsWith(REQUEST_FILE_PREFIX)); + List sorted = new ArrayList<>(Arrays.asList(files == null ? new File[0] : files)); + sorted.sort(Comparator.comparing(file -> Long.parseLong(file.getName().substring(REQUEST_FILE_PREFIX.length())))); + + List params = new ArrayList<>(); + for (File file : sorted) { + String content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + int end = content.indexOf('\n'); + params.add(end < 0 ? content : content.substring(0, end)); + } + return params; + } + + /** + * Decodes url encoded parameters. + * + * @param params the parameters + * @return the parameters by name + */ + private static Map decode(String params) { + Map decoded = new HashMap<>(); + for (String pair : params.split("&")) { + if (pair.isEmpty()) { + continue; + } + String[] keyValue = pair.split("=", 2); + decoded.put(Utils.urldecode(keyValue[0]), keyValue.length > 1 ? Utils.urldecode(keyValue[1]) : ""); + } + return decoded; + } + + /** + * Reads a stream to its end. + * + * @param stream the stream + * @return its content as UTF-8 text + * @throws IOException when it cannot be read + */ + private static String readAll(InputStream stream) throws IOException { + ByteArrayOutputStream content = new ByteArrayOutputStream(); + byte[] buffer = new byte[8192]; + int read; + while ((read = stream.read(buffer)) != -1) { + content.write(buffer, 0, read); + } + return new String(content.toByteArray(), StandardCharsets.UTF_8); + } + + /** + * Numbered lines, a prefix followed by each number in a range. + * + * @param prefix the prefix + * @param from the first number + * @param to one past the last number + * @return the lines + */ + private static List numbered(String prefix, int from, int to) { + List lines = new ArrayList<>(); + for (int i = from; i < to; i++) { + lines.add(prefix + i); + } + return lines; + } + + /** + * A text of one character repeated. + * + * @param character the character + * @param count how many times + * @return the text + */ + private static String repeat(char character, int count) { + StringBuilder text = new StringBuilder(count); + for (int i = 0; i < count; i++) { + text.append(character); + } + return text.toString(); + } + + + // endregion +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ServerConfigBuilder.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ServerConfigBuilder.java new file mode 100644 index 000000000..745e8a2c5 --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ServerConfigBuilder.java @@ -0,0 +1,709 @@ +package ly.count.sdk.java.internal; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; +import org.json.JSONObject; +import org.junit.Assert; + +import static ly.count.sdk.java.internal.ModuleConfiguration.keyLGBatchSize; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyLGEnabled; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyLGId; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyLGLevels; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRAutomaticCrashReporting; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRAutomaticSessionTracking; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRAutomaticViewTracking; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRBOMAcceptedTimeout; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRBOMDuration; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRBOMRQPercentage; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRBOMRequestAge; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRBackoffMechanism; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRConfig; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRConnectionTest; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRConsentRequired; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRContentZoneInterval; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRCrashReporting; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRCustomEventTracking; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRDropOldRequestTime; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyREnterContentZone; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyREventBlacklist; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyREventQueueSize; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyREventSegmentationBlacklist; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyREventSegmentationWhitelist; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyREventWhitelist; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRJourneyTriggerEvents; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRJourneyTriggerViews; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRLimitBreadcrumb; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRLimitKeyLength; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRLimitSegValues; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRLimitTraceLength; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRLimitTraceLine; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRLimitValueSize; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRLocationTracking; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRLogGathering; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRLogging; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRNetworking; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRRefreshContentZone; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRReqQueueSize; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRSegmentationBlacklist; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRSegmentationWhitelist; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRServerConfigUpdateInterval; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRSessionTracking; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRSessionUpdateInterval; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRTimestamp; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRTracking; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRUserPropertyBlacklist; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRUserPropertyCacheLimit; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRUserPropertyWhitelist; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRVersion; +import static ly.count.sdk.java.internal.ModuleConfiguration.keyRViewTracking; + +/** + * Builds SDK behavior settings payloads, {@code {"v":..,"t":..,"c":{..}}} plus any sibling of + * {@code c}, and checks a {@link ConfigurationProvider} against the settings it holds. + */ +class ServerConfigBuilder { + final Map config = new LinkedHashMap<>(); + /** + * Keys that sit next to {@code c}, not inside it: the {@code lg} directive, the {@code ct} + * flag and anything a newer server may add. + */ + final Map topLevelKeys = new LinkedHashMap<>(); + private Object timestamp = System.currentTimeMillis(); + private Object version = 1; + + /** + * Sets the {@code t} value. + * + * @param timestamp the value + * @return this builder + */ + ServerConfigBuilder timestamp(Object timestamp) { + this.timestamp = timestamp; + return this; + } + + /** + * Sets the {@code v} value. + * + * @param version the value + * @return this builder + */ + ServerConfigBuilder version(Object version) { + this.version = version; + return this; + } + + /** + * Sets any setting to any value, including the ones the SDK has to reject. + * + * @param key the settings key + * @param value the value + * @return this builder + */ + ServerConfigBuilder set(String key, Object value) { + config.put(key, value); + return this; + } + + /** + * @param enabled {@code tracking} + * @return this builder + */ + ServerConfigBuilder tracking(boolean enabled) { + return set(keyRTracking, enabled); + } + + /** + * @param enabled {@code networking} + * @return this builder + */ + ServerConfigBuilder networking(boolean enabled) { + return set(keyRNetworking, enabled); + } + + /** + * @param enabled {@code st} + * @return this builder + */ + ServerConfigBuilder sessionTracking(boolean enabled) { + return set(keyRSessionTracking, enabled); + } + + /** + * @param enabled {@code vt} + * @return this builder + */ + ServerConfigBuilder viewTracking(boolean enabled) { + return set(keyRViewTracking, enabled); + } + + /** + * @param enabled {@code cet} + * @return this builder + */ + ServerConfigBuilder customEventTracking(boolean enabled) { + return set(keyRCustomEventTracking, enabled); + } + + /** + * @param enabled {@code ecz} + * @return this builder + */ + ServerConfigBuilder contentZone(boolean enabled) { + return set(keyREnterContentZone, enabled); + } + + /** + * @param enabled {@code crt} + * @return this builder + */ + ServerConfigBuilder crashReporting(boolean enabled) { + return set(keyRCrashReporting, enabled); + } + + /** + * @param enabled {@code ast} + * @return this builder + */ + ServerConfigBuilder automaticSessionTracking(boolean enabled) { + return set(keyRAutomaticSessionTracking, enabled); + } + + /** + * @param enabled {@code avt} + * @return this builder + */ + ServerConfigBuilder automaticViewTracking(boolean enabled) { + return set(keyRAutomaticViewTracking, enabled); + } + + /** + * @param enabled {@code acr} + * @return this builder + */ + ServerConfigBuilder automaticCrashReporting(boolean enabled) { + return set(keyRAutomaticCrashReporting, enabled); + } + + /** + * @param enabled {@code lt} + * @return this builder + */ + ServerConfigBuilder locationTracking(boolean enabled) { + return set(keyRLocationTracking, enabled); + } + + /** + * @param enabled {@code rcz} + * @return this builder + */ + ServerConfigBuilder refreshContentZone(boolean enabled) { + return set(keyRRefreshContentZone, enabled); + } + + /** + * @param enabled {@code bom} + * @return this builder + */ + ServerConfigBuilder backoffMechanism(boolean enabled) { + return set(keyRBackoffMechanism, enabled); + } + + /** + * @param enabled {@code log} + * @return this builder + */ + ServerConfigBuilder logging(boolean enabled) { + return set(keyRLogging, enabled); + } + + /** + * @param required {@code cr} + * @return this builder + */ + ServerConfigBuilder consentRequired(boolean required) { + return set(keyRConsentRequired, required); + } + + /** + * @param hours {@code scui} + * @return this builder + */ + ServerConfigBuilder serverConfigUpdateInterval(int hours) { + return set(keyRServerConfigUpdateInterval, hours); + } + + /** + * @param size {@code rqs} + * @return this builder + */ + ServerConfigBuilder requestQueueSize(int size) { + return set(keyRReqQueueSize, size); + } + + /** + * @param size {@code eqs} + * @return this builder + */ + ServerConfigBuilder eventQueueSize(int size) { + return set(keyREventQueueSize, size); + } + + /** + * @param seconds {@code sui} + * @return this builder + */ + ServerConfigBuilder sessionUpdateInterval(int seconds) { + return set(keyRSessionUpdateInterval, seconds); + } + + /** + * @param limit {@code lkl} + * @return this builder + */ + ServerConfigBuilder keyLengthLimit(int limit) { + return set(keyRLimitKeyLength, limit); + } + + /** + * @param limit {@code lvs} + * @return this builder + */ + ServerConfigBuilder valueSizeLimit(int limit) { + return set(keyRLimitValueSize, limit); + } + + /** + * @param limit {@code lsv} + * @return this builder + */ + ServerConfigBuilder segmentationValuesLimit(int limit) { + return set(keyRLimitSegValues, limit); + } + + /** + * @param limit {@code lbc} + * @return this builder + */ + ServerConfigBuilder breadcrumbLimit(int limit) { + return set(keyRLimitBreadcrumb, limit); + } + + /** + * @param limit {@code ltlpt} + * @return this builder + */ + ServerConfigBuilder traceLinesLimit(int limit) { + return set(keyRLimitTraceLine, limit); + } + + /** + * @param limit {@code ltl} + * @return this builder + */ + ServerConfigBuilder traceLengthLimit(int limit) { + return set(keyRLimitTraceLength, limit); + } + + /** + * @param limit {@code upcl} + * @return this builder + */ + ServerConfigBuilder userPropertyCacheLimit(int limit) { + return set(keyRUserPropertyCacheLimit, limit); + } + + /** + * @param seconds {@code bom_at} + * @return this builder + */ + ServerConfigBuilder backoffAcceptedTimeout(int seconds) { + return set(keyRBOMAcceptedTimeout, seconds); + } + + /** + * @param share {@code bom_rqp} + * @return this builder + */ + ServerConfigBuilder backoffRequestQueuePercentage(double share) { + return set(keyRBOMRQPercentage, share); + } + + /** + * @param hours {@code bom_ra} + * @return this builder + */ + ServerConfigBuilder backoffRequestAge(int hours) { + return set(keyRBOMRequestAge, hours); + } + + /** + * @param seconds {@code bom_d} + * @return this builder + */ + ServerConfigBuilder backoffDuration(int seconds) { + return set(keyRBOMDuration, seconds); + } + + /** + * @param hours {@code dort} + * @return this builder + */ + ServerConfigBuilder dropOldRequestTime(int hours) { + return set(keyRDropOldRequestTime, hours); + } + + /** + * @param seconds {@code czi} + * @return this builder + */ + ServerConfigBuilder contentZoneInterval(int seconds) { + return set(keyRContentZoneInterval, seconds); + } + + /** + * Sets {@code eb} or {@code ew}, dropping the other one. + * + * @param names the event keys + * @param isWhitelist {@code true} for {@code ew} + * @return this builder + */ + ServerConfigBuilder eventFilterList(Set names, boolean isWhitelist) { + return filter(keyREventBlacklist, keyREventWhitelist, names, isWhitelist); + } + + /** + * Sets {@code upb} or {@code upw}, dropping the other one. + * + * @param names the user property keys + * @param isWhitelist {@code true} for {@code upw} + * @return this builder + */ + ServerConfigBuilder userPropertyFilterList(Set names, boolean isWhitelist) { + return filter(keyRUserPropertyBlacklist, keyRUserPropertyWhitelist, names, isWhitelist); + } + + /** + * Sets {@code sb} or {@code sw}, dropping the other one. + * + * @param names the segmentation keys + * @param isWhitelist {@code true} for {@code sw} + * @return this builder + */ + ServerConfigBuilder segmentationFilterList(Set names, boolean isWhitelist) { + return filter(keyRSegmentationBlacklist, keyRSegmentationWhitelist, names, isWhitelist); + } + + /** + * Sets {@code esb} or {@code esw}, dropping the other one. + * + * @param namesPerEvent the segmentation keys of each event key + * @param isWhitelist {@code true} for {@code esw} + * @return this builder + */ + ServerConfigBuilder eventSegmentationFilterMap(Map> namesPerEvent, boolean isWhitelist) { + config.remove(isWhitelist ? keyREventSegmentationBlacklist : keyREventSegmentationWhitelist); + return set(isWhitelist ? keyREventSegmentationWhitelist : keyREventSegmentationBlacklist, namesPerEvent); + } + + /** + * @param eventKeys {@code jte} + * @return this builder + */ + ServerConfigBuilder journeyTriggerEvents(Set eventKeys) { + return set(keyRJourneyTriggerEvents, eventKeys); + } + + /** + * @param viewNames {@code jtv} + * @return this builder + */ + ServerConfigBuilder journeyTriggerViews(Set viewNames) { + return set(keyRJourneyTriggerViews, viewNames); + } + + /** + * Sets one of a blacklist and whitelist pair, dropping the other one. + * + * @param blacklistKey the blacklist key + * @param whitelistKey the whitelist key + * @param names the names + * @param isWhitelist whether to set the whitelist + * @return this builder + */ + private ServerConfigBuilder filter(String blacklistKey, String whitelistKey, Set names, boolean isWhitelist) { + config.remove(isWhitelist ? blacklistKey : whitelistKey); + return set(isWhitelist ? whitelistKey : blacklistKey, names); + } + + /** + * Sets any key next to {@code c}. + * + * @param key the top level key + * @param value the value + * @return this builder + */ + ServerConfigBuilder topLevelKey(String key, Object value) { + topLevelKeys.put(key, value); + return this; + } + + /** + * Sets the {@code ct} connection test flag. + * + * @param value the flag, of any type + * @return this builder + */ + ServerConfigBuilder connectionTest(Object value) { + return topLevelKey(keyRConnectionTest, value); + } + + /** + * A log gathering directive that turns gathering off, {@code {"e":false}}. + * + * @return this builder + */ + ServerConfigBuilder logGatheringOff() { + return logGatheringDirective(false, null, null, null); + } + + /** + * A log gathering directive with every field filled in. + * + * @param gatherId {@code i} + * @param levels {@code l} + * @param batchSize {@code b} + * @return this builder + */ + ServerConfigBuilder logGatheringOn(String gatherId, String levels, int batchSize) { + return logGatheringDirective(true, gatherId, levels, batchSize); + } + + /** + * A log gathering directive from raw values, so malformed ones can be built too. A {@code null} + * value is left out rather than written as JSON null. + * + * @param enabled {@code e} + * @param gatherId {@code i} + * @param levels {@code l} + * @param batchSize {@code b} + * @return this builder + */ + ServerConfigBuilder logGatheringDirective(Object enabled, Object gatherId, Object levels, Object batchSize) { + JSONObject directive = new JSONObject(); + putIfNotNull(directive, keyLGEnabled, enabled); + putIfNotNull(directive, keyLGId, gatherId); + putIfNotNull(directive, keyLGLevels, levels); + putIfNotNull(directive, keyLGBatchSize, batchSize); + return topLevelKey(keyRLogGathering, directive); + } + + /** + * Puts a value unless it is {@code null}. + * + * @param target the object to put into + * @param key the key + * @param value the value + */ + private static void putIfNotNull(JSONObject target, String key, Object value) { + if (value != null) { + target.put(key, value); + } + } + + /** + * Every setting at a valid value that differs from what the SDK uses by default. + * + * @return this builder + */ + ServerConfigBuilder allKeysAtNonDefaultValues() { + tracking(false).networking(false).sessionTracking(false).viewTracking(false).customEventTracking(false) + .contentZone(true).crashReporting(false).automaticSessionTracking(true).automaticViewTracking(true) + .automaticCrashReporting(false).locationTracking(false).refreshContentZone(false).backoffMechanism(false) + .logging(true).consentRequired(true); + + serverConfigUpdateInterval(8).requestQueueSize(2000).eventQueueSize(200).sessionUpdateInterval(120) + .keyLengthLimit(89).valueSizeLimit(43).segmentationValuesLimit(25).breadcrumbLimit(90) + .traceLinesLimit(89).traceLengthLimit(78).userPropertyCacheLimit(67) + .backoffAcceptedTimeout(12).backoffRequestQueuePercentage(0.25).backoffRequestAge(36).backoffDuration(90) + .dropOldRequestTime(5).contentZoneInterval(60); + + eventFilterList(names("blocked_event"), false); + userPropertyFilterList(names("allowed_property"), true); + segmentationFilterList(names("blocked_segment"), false); + Map> perEvent = new LinkedHashMap<>(); + perEvent.put("purchase", names("card_number")); + eventSegmentationFilterMap(perEvent, false); + journeyTriggerEvents(names("journey_event")); + return journeyTriggerViews(names("journey_view")); + } + + /** + * A set of names in the given order. + * + * @param names the names + * @return the set + */ + static Set names(String... names) { + return new LinkedHashSet<>(Arrays.asList(names)); + } + + /** + * The payload as the server sends it. + * + * @return the JSON text + */ + String build() { + return buildJson().toString(); + } + + /** + * The payload as a JSON object. + * + * @return the payload + */ + JSONObject buildJson() { + JSONObject json = new JSONObject(); + json.put(keyRVersion, version); + json.put(keyRTimestamp, timestamp); + json.put(keyRConfig, new JSONObject(config)); + for (Map.Entry entry : topLevelKeys.entrySet()) { + json.put(entry.getKey(), entry.getValue()); + } + return json; + } + + /** + * Asserts that the provider serves every setting this builder holds. + * + * @param provider the provider to check + */ + @SuppressWarnings("unchecked") + void validateAgainst(ConfigurationProvider provider) { + for (Map.Entry entry : config.entrySet()) { + String key = entry.getKey(); + Object expected = entry.getValue(); + switch (key) { + case keyREventBlacklist: + case keyREventWhitelist: + assertFilter(key, (Set) expected, keyREventWhitelist.equals(key), provider.getEventFilterList()); + break; + case keyRUserPropertyBlacklist: + case keyRUserPropertyWhitelist: + assertFilter(key, (Set) expected, keyRUserPropertyWhitelist.equals(key), provider.getUserPropertyFilterList()); + break; + case keyRSegmentationBlacklist: + case keyRSegmentationWhitelist: + assertFilter(key, (Set) expected, keyRSegmentationWhitelist.equals(key), provider.getSegmentationFilterList()); + break; + case keyREventSegmentationBlacklist: + case keyREventSegmentationWhitelist: + ConfigurationProvider.FilterList>> perEvent = provider.getEventSegmentationFilterList(); + Assert.assertEquals("kind of '" + key + "'", keyREventSegmentationWhitelist.equals(key), perEvent.isWhitelist()); + Assert.assertEquals("names of '" + key + "'", expected, perEvent.getFilterList()); + break; + default: + Assert.assertEquals("value of '" + key + "'", expected, valueOf(provider, key)); + break; + } + } + } + + /** + * Asserts one names filter. + * + * @param key the settings key + * @param expected the names + * @param isWhitelist the expected kind + * @param actual the filter the provider serves + */ + private static void assertFilter(String key, Set expected, boolean isWhitelist, ConfigurationProvider.FilterList> actual) { + Assert.assertEquals("kind of '" + key + "'", isWhitelist, actual.isWhitelist()); + Assert.assertEquals("names of '" + key + "'", expected, actual.getFilterList()); + } + + /** + * The value a provider serves for a setting that is not a listing filter. + * + * @param provider the provider + * @param key the settings key + * @return the served value, boxed + */ + static Object valueOf(ConfigurationProvider provider, String key) { + switch (key) { + case keyRTracking: + return provider.getTrackingEnabled(); + case keyRNetworking: + return provider.getNetworkingEnabled(); + case keyRSessionTracking: + return provider.getSessionTrackingEnabled(); + case keyRViewTracking: + return provider.getViewTrackingEnabled(); + case keyRCustomEventTracking: + return provider.getCustomEventTrackingEnabled(); + case keyREnterContentZone: + return provider.getContentZoneEnabled(); + case keyRCrashReporting: + return provider.getCrashReportingEnabled(); + case keyRAutomaticSessionTracking: + return provider.getAutomaticSessionTrackingEnabled(); + case keyRAutomaticViewTracking: + return provider.getAutomaticViewTrackingEnabled(); + case keyRAutomaticCrashReporting: + return provider.getAutomaticCrashReportingEnabled(); + case keyRLocationTracking: + return provider.getLocationTrackingEnabled(); + case keyRRefreshContentZone: + return provider.getRefreshContentZoneEnabled(); + case keyRBackoffMechanism: + return provider.getBOMEnabled(); + case keyRLogging: + return provider.getLoggingEnabled(); + case keyRConsentRequired: + return provider.getConsentRequired(); + case keyRServerConfigUpdateInterval: + return provider.getServerConfigUpdateInterval(); + case keyRReqQueueSize: + return provider.getRequestQueueMaxSize(); + case keyREventQueueSize: + return provider.getEventQueueSizeThreshold(); + case keyRSessionUpdateInterval: + return provider.getSessionUpdateInterval(); + case keyRLimitKeyLength: + return provider.getMaxKeyLength(); + case keyRLimitValueSize: + return provider.getMaxValueSize(); + case keyRLimitSegValues: + return provider.getMaxSegmentationValues(); + case keyRLimitBreadcrumb: + return provider.getMaxBreadcrumbCount(); + case keyRLimitTraceLine: + return provider.getMaxStackTraceLinesPerThread(); + case keyRLimitTraceLength: + return provider.getMaxStackTraceLineLength(); + case keyRUserPropertyCacheLimit: + return provider.getUserPropertyCacheLimit(); + case keyRBOMAcceptedTimeout: + return provider.getBOMAcceptedTimeoutSeconds(); + case keyRBOMRQPercentage: + return provider.getBOMRQPercentage(); + case keyRBOMRequestAge: + return provider.getBOMRequestAge(); + case keyRBOMDuration: + return provider.getBOMDuration(); + case keyRDropOldRequestTime: + return provider.getRequestDropAgeHours(); + case keyRContentZoneInterval: + return provider.getContentZoneTimerInterval(); + case keyRJourneyTriggerEvents: + return provider.getJourneyTriggerEvents(); + case keyRJourneyTriggerViews: + return provider.getJourneyTriggerViews(); + default: + throw new IllegalArgumentException("no getter for settings key [" + key + "]"); + } + } +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ServerUrlChangeTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ServerUrlChangeTests.java new file mode 100644 index 000000000..58f48e29c --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ServerUrlChangeTests.java @@ -0,0 +1,421 @@ +package ly.count.sdk.java.internal; + +import com.sun.net.httpserver.HttpServer; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.Predicate; +import ly.count.sdk.java.Config; +import ly.count.sdk.java.Countly; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Changing the server URL and the app key while the SDK runs, and the request queue calls, against + * two real HTTP servers on loopback standing in for an old and a new Countly server. The assertions + * are on what each server received. + */ +@RunWith(JUnit4.class) +public class ServerUrlChangeTests { + + private static final String NEW_APP_KEY = "NEW_APP_KEY"; + + private static final String PUBLIC_KEY_PEM = + "-----BEGIN PUBLIC KEY-----\n" + + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoEAoIix1JRqGjxxZlVLc\n" + + "EYuoQE5QvdClJjdFxtkqnTxHim0Qlvh8tA0EoiFgDdhCvp2HLk3w8EloR5Op2JQK\n" + + "kyTEqPk5OY7ftg39WVsGIAP0CxwoyCymGgmP2gRimjV1wa+58Ng3f5MktTKAVWX9\n" + + "1/ki9khQ2XVIXUv5wq3Yx0VyCZa80W7bifXqfDnLmkhOA8jFy7effR/pkLk5j0HS\n" + + "9g3zYPFmid1gJHxF2/j7oZ9NOG7KBfKuB3Aml8R3Y9Xg/3RAbbh7jVwlYj8CJ1gC\n" + + "TU7V9bCRX+DFjX8XcCP7hVM8yHadS63dsnKPPlUtUbVQouNKqWA+ubhEpQsrxEmv\n" + + "jQIDAQAB\n" + + "-----END PUBLIC KEY-----\n"; + + private Server serverA; + private Server serverB; + + /** + * Starts every test without SDK files and with two new servers. + */ + @Before + public void beforeTest() throws IOException { + TestUtils.createCleanTestState(); + serverA = new Server(); + serverB = new Server(); + } + + /** + * Stops the SDK, deletes its data and stops both servers. + */ + @After + public void afterTest() { + Countly.instance().halt(); + serverA.stop(); + serverB.stop(); + } + + /** + * A request that failed at the old server is retried at the new one, given with trailing "/" + * characters, which are removed, so the path is not doubled. Later requests go there too, with + * the same app key, and changing back to the old URL brings the traffic back. + */ + @Test + public void changeServerUrl_queuedAndLaterRequestsGoToTheNewServer() throws Exception { + serverA.responseCode = 503; + Countly.instance().init(config(serverA, Config.Feature.Events).setEventQueueSizeToSend(1)); + Countly.instance().events().recordEvent("queued_while_down"); + serverA.await(withEvent("queued_while_down")); + awaitSendHandled(); + + Countly.instance().changeServerUrl(serverB.url() + "///"); + + Assert.assertEquals(serverB.url(), SDKCore.instance.config.getServerURL().toString()); + Received retried = serverB.await(withEvent("queued_while_down")); + Assert.assertEquals("/i", retried.path); + Assert.assertEquals(TestUtils.SERVER_APP_KEY, retried.params.get("app_key")); + Assert.assertEquals(TestUtils.DEVICE_ID, retried.params.get("device_id")); + + Countly.instance().events().recordEvent("after_change"); + Received later = serverB.await(withEvent("after_change")); + Assert.assertEquals("/i", later.path); + Assert.assertEquals(TestUtils.SERVER_APP_KEY, later.params.get("app_key")); + Assert.assertEquals(1, serverA.count(withEvent("queued_while_down"))); + Assert.assertEquals(0, serverA.count(withEvent("after_change"))); + + serverA.responseCode = 200; + Countly.instance().changeServerUrl(serverA.url()); + Countly.instance().events().recordEvent("after_revert"); + serverA.await(withEvent("after_revert")); + Assert.assertEquals(0, serverB.count(withEvent("after_revert"))); + Assert.assertTrue("the request queue must drain", TestUtils.waitFor(10_000, () -> queuedRequestCount() == 0)); + } + + /** + * An invalid URL is ignored with log code e102, and the SDK keeps sending to the current server. + */ + @Test + public void changeServerUrl_invalidUrlsAreIgnored() throws Exception { + Countly.instance().init(config(serverA, Config.Feature.Events).setEventQueueSizeToSend(1)); + + String[] invalid = { null, "", "not a url", "ftp://x", "http://", "http:///no_host", "http://exa mple.com" }; + for (String url : invalid) { + Countly.instance().changeServerUrl(url); + } + + Assert.assertEquals(serverA.url(), SDKCore.instance.config.getServerURL().toString()); + Assert.assertEquals(invalid.length, logCode("e102")); + Countly.instance().events().recordEvent("still_on_a"); + Received received = serverA.await(withEvent("still_on_a")); + Assert.assertEquals(TestUtils.SERVER_APP_KEY, received.params.get("app_key")); + Assert.assertTrue(serverB.received.isEmpty()); + } + + /** + * While a public key pin is set, only an https URL is accepted. + */ + @Test + public void changeServerUrl_withPins_acceptsHttpsOnly() { + Countly.instance().init(config(serverA).addPublicKeyPin(PUBLIC_KEY_PEM)); + + Countly.instance().changeServerUrl(serverB.url()); + Assert.assertEquals(serverA.url(), SDKCore.instance.config.getServerURL().toString()); + Assert.assertEquals(1, logCode("e102")); + + Countly.instance().changeServerUrl(TestUtils.SERVER_URL + "/"); + Assert.assertEquals(TestUtils.SERVER_URL, SDKCore.instance.config.getServerURL().toString()); + Assert.assertEquals(1, logCode("e102")); + } + + /** + * Right after a URL change the new server is asked for the SDK behavior settings and, as remote + * config downloads automatically, for remote config, with the same app key. Immediate requests + * made later, as the feedback widget list, go to the new server too. + */ + @Test + public void changeServerUrl_catchesUpTheNewServer() throws Exception { + Config config = config(serverA, Config.Feature.RemoteConfig, Config.Feature.Feedback).enableRemoteConfigAutomaticTriggers(); + Countly.instance().init(config); + serverA.await(withMethod("sc")); + serverA.await(withMethod("rc")); + + Countly.instance().changeServerUrl(serverB.url()); + + Received settings = serverB.await(withMethod("sc")); + Received remoteConfig = serverB.await(withMethod("rc")); + Assert.assertEquals("/o/sdk", settings.path); + Assert.assertEquals("/o/sdk", remoteConfig.path); + Assert.assertEquals(TestUtils.SERVER_APP_KEY, settings.params.get("app_key")); + Assert.assertEquals(TestUtils.SERVER_APP_KEY, remoteConfig.params.get("app_key")); + Assert.assertEquals(TestUtils.DEVICE_ID, remoteConfig.params.get("device_id")); + + Countly.instance().feedback().getAvailableFeedbackWidgets((widgets, error) -> { + }); + serverB.await(withMethod("feedback")); + Assert.assertEquals(0, serverA.count(withMethod("feedback"))); + Assert.assertEquals(1, serverA.count(withMethod("sc"))); + Assert.assertEquals(1, serverA.count(withMethod("rc"))); + } + + /** + * Right after an app key change the server is asked for the SDK behavior settings and remote + * config of the new app. The remote config values of the old app are cleared first, so they are + * gone even when the new download fails. + */ + @Test + public void changeAppKey_catchesUpTheNewApp_andClearsTheRemoteConfigOfTheOldApp() throws Exception { + Countly.instance().init(config(serverA, Config.Feature.RemoteConfig).enableRemoteConfigAutomaticTriggers()); + serverA.await(withMethod("rc")); + Assert.assertTrue(TestUtils.waitFor(5_000, () -> Countly.instance().remoteConfig().getValues().containsKey("color"))); + + serverA.failRemoteConfig = true; + Countly.instance().changeAppKey(NEW_APP_KEY); + + Received settings = serverA.await(withMethod("sc").and(r -> NEW_APP_KEY.equals(r.params.get("app_key")))); + Received remoteConfig = serverA.await(withMethod("rc").and(r -> NEW_APP_KEY.equals(r.params.get("app_key")))); + Assert.assertEquals(TestUtils.DEVICE_ID, settings.params.get("device_id")); + Assert.assertEquals(TestUtils.DEVICE_ID, remoteConfig.params.get("device_id")); + Assert.assertTrue(Countly.instance().remoteConfig().getValues().isEmpty()); + } + + /** + * The queued events are packed into a request and the request queue is sent right away: first + * the event that waited in the event queue, then, once the server is back, the request that + * failed, without waiting for the timer. + */ + @Test + public void attemptToSendStoredRequests_sendsTheEventQueueAndTheRequestQueueNow() throws Exception { + serverA.responseCode = 503; + Countly.instance().init(config(serverA, Config.Feature.Events).setEventQueueSizeToSend(10)); + Countly.instance().events().recordEvent("waiting_in_the_event_queue"); + Assert.assertEquals(1, TestUtils.getCurrentEQ().size()); + + Countly.instance().attemptToSendStoredRequests(); + serverA.await(withEvent("waiting_in_the_event_queue")); + awaitSendHandled(); + Assert.assertEquals(0, TestUtils.getCurrentEQ().size()); + Assert.assertEquals(1, queuedRequestCount()); + + serverA.responseCode = 200; + Countly.instance().attemptToSendStoredRequests(); + Assert.assertTrue(TestUtils.waitFor(5_000, () -> serverA.count(withEvent("waiting_in_the_event_queue")) == 2)); + Assert.assertTrue(TestUtils.waitFor(5_000, () -> queuedRequestCount() == 0)); + } + + /** + * The queue calls never lose a request that is not sent: the request being sent while the queue + * is flushed finishes, the flushed ones never arrive, and the one queued behind it before it + * finished is sent next, not removed in its place. + */ + @Test + public void flushQueues_whileARequestIsBeingSent() throws Exception { + serverA.gate = new CountDownLatch(1); + Countly.instance().init(config(serverA, Config.Feature.Events).setEventQueueSizeToSend(1)); + Countly.instance().events().recordEvent("being_sent"); + serverA.await(withEvent("being_sent")); + Countly.instance().events().recordEvent("flushed_1"); + Countly.instance().events().recordEvent("flushed_2"); + Assert.assertTrue(TestUtils.waitFor(5_000, () -> queuedRequestCount() == 3)); + + Countly.instance().flushQueues(); + Assert.assertEquals(0, queuedRequestCount()); + Countly.instance().events().recordEvent("after_flush"); + Assert.assertEquals(1, queuedRequestCount()); + serverA.gate.countDown(); + + serverA.await(withEvent("after_flush")); + Assert.assertTrue(TestUtils.waitFor(5_000, () -> queuedRequestCount() == 0)); + Assert.assertEquals(0, serverA.count(withEvent("flushed_1"))); + Assert.assertEquals(0, serverA.count(withEvent("flushed_2"))); + Assert.assertEquals(1, serverA.count(withEvent("being_sent"))); + } + + // region helpers + + /** + * A configuration that sends to the given server without request cooldowns or health check. + */ + private Config config(Server server, Config.Feature... features) { + File directory = TestUtils.getTestSDirectory(); + TestUtils.checkSdkStorageRootDirectoryExist(directory); + + Config config = new Config(server.url(), TestUtils.SERVER_APP_KEY, directory); + config.setApplicationVersion(TestUtils.APPLICATION_VERSION); + config.setCustomDeviceId(TestUtils.DEVICE_ID); + config.disableHealthCheck(); + config.enableFeatures(features); + config.setNetworkRequestCooldown(0); + config.setNetworkImportantRequestCooldown(0); + return config; + } + + /** + * How often the running health check counter recorded a log code. + */ + private static int logCode(String code) { + return SDKCore.instance.healthCheckCounter.snapshot().getJSONObject("lc").optInt(code, 0); + } + + /** + * How many requests are stored, once the pending storage tasks ran. + */ + private static int queuedRequestCount() { + Storage.await(null); + File[] files = TestUtils.getTestSDirectory().listFiles((dir, name) -> name.startsWith("[CLY]_request_")); + return files == null ? 0 : files.length; + } + + /** + * Waits until the SDK finished handling the request it is sending. A send asked for while a + * failed send is still being handled waits for the next request or timer tick, so a retry is + * asked for only once the failed send is handled. + */ + private static void awaitSendHandled() throws InterruptedException { + Assert.assertTrue("the send in progress must end", TestUtils.waitFor(10_000, () -> !SDKCore.instance.networking.isSending())); + } + + /** + * Matches a request that carries an event with the given key. + */ + private static Predicate withEvent(String key) { + return r -> r.params.containsKey("events") && r.params.get("events").contains("\"" + key + "\""); + } + + /** + * Matches an immediate request of the given method. + */ + private static Predicate withMethod(String method) { + return r -> method.equals(r.params.get("method")); + } + + /** + * One request as a server received it, with its parameters decoded. + */ + private static final class Received { + final String path; + final Map params; + + /** + * A request with its path and decoded parameters. + */ + Received(String path, Map params) { + this.path = path; + this.params = params; + } + } + + /** + * A Countly server stand-in on loopback that records every request. It answers remote config + * with one value, the SDK behavior settings with none, and anything else with success, unless + * told to fail; it can hold every event request until a gate opens. + */ + private static final class Server { + final HttpServer http; + final List received = new CopyOnWriteArrayList<>(); + volatile int responseCode = 200; + volatile boolean failRemoteConfig = false; + volatile CountDownLatch gate = null; + + /** + * Starts the server on a free loopback port. + */ + Server() throws IOException { + http = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + http.createContext("/", exchange -> { + String query = exchange.getRequestURI().getRawQuery(); + String body = new String(readAll(exchange.getRequestBody()), StandardCharsets.UTF_8); + Map params = TestUtils.parseQueryParams(Utils.isNotEmpty(query) ? query : body); + params.replaceAll((key, value) -> Utils.urldecode(value)); + received.add(new Received(exchange.getRequestURI().getPath(), params)); + + CountDownLatch waitFor = gate; + if (waitFor != null && params.containsKey("events")) { + try { + waitFor.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + int code = responseCode; + String response = "{\"result\":\"Success\"}"; + if ("rc".equals(params.get("method"))) { + code = failRemoteConfig ? 500 : code; + response = "{\"color\":\"red\"}"; + } else if ("sc".equals(params.get("method"))) { + response = "{}"; + } else if ("feedback".equals(params.get("method"))) { + response = "{\"result\":[]}"; + } + byte[] out = response.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(code, out.length); + try (OutputStream stream = exchange.getResponseBody()) { + stream.write(out); + } + }); + http.setExecutor(Executors.newSingleThreadExecutor()); + http.start(); + } + + /** + * The URL the SDK reaches this server at. + */ + String url() { + return "http://127.0.0.1:" + http.getAddress().getPort(); + } + + /** + * How many received requests match. + */ + int count(Predicate filter) { + return (int) received.stream().filter(filter).count(); + } + + /** + * Waits for the first matching request and returns it. + */ + Received await(Predicate filter) throws InterruptedException { + Assert.assertTrue("no matching request arrived at " + url() + ", it received " + received.size(), TestUtils.waitFor(15_000, () -> count(filter) > 0)); + return received.stream().filter(filter).findFirst().orElse(null); + } + + /** + * Opens the gate and stops the server. + */ + void stop() { + CountDownLatch waitFor = gate; + if (waitFor != null) { + waitFor.countDown(); + } + http.stop(0); + } + + /** + * Reads a request body. + */ + private static byte[] readAll(InputStream stream) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int read; + while ((read = stream.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + return out.toByteArray(); + } + } + + // endregion +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/SessionImplTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/SessionImplTests.java index 74b38403e..2b903399c 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/SessionImplTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/SessionImplTests.java @@ -614,13 +614,14 @@ public void view() { * start, stop and next view should be recorded to EQ */ @Test - public void view_stopStartedAndNext() { + public void view_stopStartedAndNext() throws InterruptedException { InternalConfig config = new InternalConfig(TestUtils.getConfigSessions(Config.Feature.Views, Config.Feature.Events).setEventQueueSizeToSend(4)); config.viewIdGenerator = TestUtils.idGenerator(); Countly.instance().init(config); SessionImpl session = (SessionImpl) Countly.session(); TestUtils.validateEQSize(0); + TestUtils.awaitStartOfSecond(); session.view("start"); TestUtils.validateEQSize(1); session.view("next"); diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/StorageLayerTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/StorageLayerTests.java index 168559913..0badf4a67 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/StorageLayerTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/StorageLayerTests.java @@ -1,9 +1,13 @@ package ly.count.sdk.java.internal; import java.io.File; +import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.concurrent.Future; import ly.count.sdk.java.Config; import ly.count.sdk.java.Countly; import org.junit.After; @@ -94,6 +98,37 @@ public void storableLifecycle_pushesListsReadsAndPops() { Assert.assertEquals(1, Storage.list(config, Request.getStoragePrefix()).size()); } + /** + * A burst of requests pushed without waiting, as the SDK queues them when every event is sent + * on its own, keeps every request: none is skipped as a duplicate write or overwritten. + */ + @Test + public void burstOfRequests_keepsEveryRequest() throws Exception { + List> writes = new ArrayList<>(); + for (int i = 0; i < 50; i++) { + writes.add(Storage.pushAsync(config, new Request("burst", i))); + } + for (Future write : writes) { + Assert.assertTrue(write.get()); + } + + Assert.assertEquals(50, Storage.list(config, Request.getStoragePrefix()).size()); + } + + /** + * Requests, sessions and crashes created together never share an id: the storage task that + * writes one of them is keyed by its id, so a shared id would drop the other write. + */ + @Test + public void storablesOfEveryKind_neverShareAnId() { + Set ids = new HashSet<>(); + for (int i = 0; i < 300; i++) { + Assert.assertTrue(ids.add(new Request().storageId())); + Assert.assertTrue(ids.add(new SessionImpl(config).storageId())); + Assert.assertTrue(ids.add(new CrashImpl(config.getLogger()).storageId())); + } + } + /** * Everything that can be absent or broken on disk, in one pass. Each must answer with null or * false rather than throwing, because the SDK runs inside a customer's application and a storage diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/TestUtils.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/TestUtils.java index 491973593..e7fe9b8d6 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/TestUtils.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/TestUtils.java @@ -13,6 +13,7 @@ import java.util.Scanner; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BooleanSupplier; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; @@ -39,7 +40,7 @@ public class TestUtils { static String SERVER_APP_KEY = "COUNTLY_APP_KEY"; static String DEVICE_ID = "some_random_test_device_id"; static String SDK_NAME = "java-native"; - static String SDK_VERSION = "26.8.0"; + static String SDK_VERSION = "26.12.0"; static String APPLICATION_VERSION = "1.0"; public static final String[] eKeys = new String[] { "eventKey1", "eventKey2", "eventKey3", "eventKey4", "eventKey5", "eventKey6", "eventKey7" }; @@ -57,12 +58,40 @@ static Config getBaseConfig() { } static Config getBaseConfig(String deviceID) { + Config config = getConfigSdkBehaviorSettings(deviceID); + // Disable server config requests by default in tests so the suite doesn't fire HTTP calls + // to a non-existent test host on every init. Tests covering ModuleConfiguration opt back in + // explicitly. + config.disableSdkBehaviorSettingsUpdates(); + return config; + } + + /** + * The base configuration with the SDK behavior settings requests left on, for the tests that + * exercise them. Pair it with an immediate request generator, or every init asks the test + * server for its settings. + * + * @return the configuration + */ + static Config getConfigSdkBehaviorSettings() { + return getConfigSdkBehaviorSettings(DEVICE_ID); + } + + /** + * The base configuration with the SDK behavior settings requests left on, for a given device ID. + * + * @param deviceID the custom device ID + * @return the configuration + */ + static Config getConfigSdkBehaviorSettings(String deviceID) { File sdkStorageRootDirectory = getTestSDirectory(); checkSdkStorageRootDirectoryExist(sdkStorageRootDirectory); Config config = new Config(SERVER_URL, SERVER_APP_KEY, sdkStorageRootDirectory); config.setApplicationVersion(APPLICATION_VERSION); - config.setCustomDeviceId(deviceID); + // Off by default in tests, so no init sends a health check to the test host or counts as an + // immediate request; ModuleHealthCheckTests builds its own configuration with it on. + config.disableHealthCheck(); return config; } @@ -326,6 +355,20 @@ public static Map parseQueryParams(String data) { */ private static final double SLEEP_OVERRUN_TOLERANCE_SECONDS = 2.0; + /** + * Waits for the next second when the clock is past the first 200 ms of the current one. A view + * duration is the difference of two whole-second timestamps, so a view stopped right after it + * started reports 1 s when the two calls fall on either side of a second boundary. + * + * @throws InterruptedException when the wait is interrupted + */ + static void awaitStartOfSecond() throws InterruptedException { + long intoSecond = System.currentTimeMillis() % 1000; + if (intoSecond > 200) { + Thread.sleep(1000 - intoSecond); + } + } + static void validateEvent(EventImpl gonnaValidate, String key, Map segmentation, int count, Double sum, Double duration, String id, String pvid, String cvid, String peid) { Assert.assertEquals(key, gonnaValidate.key); @@ -425,6 +468,19 @@ static void validateEQSize(int expectedSize) { Assert.assertEquals(expectedSize, getCurrentEQ().size()); } + /** + * The keys of the events in the event queue, in queue order. + * + * @return the keys + */ + static List keysInEQ() { + List keys = new ArrayList<>(); + for (EventImpl event : getCurrentEQ()) { + keys.add(event.key); + } + return keys; + } + static String getOS() { return System.getProperty("os.name"); } @@ -698,4 +754,40 @@ static InternalConfig getConfigViews(Map segmentation) { config.views.setGlobalViewSegmentation(segmentation); return config; } + + /** + * Waits until the clock is past every timestamp handed out so far. A request file is named after + * a {@link TimeUtils#uniqueTimestampMs()} value, which is unique among the last ten values only, + * so requests stored back to back could reuse a name and overwrite each other. + */ + static void letTheClockCatchUp() { + long latest = TimeUtils.uniqueTimestampMs(); + while (System.currentTimeMillis() <= latest) { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + } + + /** + * Polls a condition until it holds or the time is up. + * + * @param timeoutMs how long to wait at most, in milliseconds + * @param condition the condition + * @return whether it held in time + * @throws InterruptedException when interrupted while waiting + */ + static boolean waitFor(long timeoutMs, BooleanSupplier condition) throws InterruptedException { + long deadline = System.currentTimeMillis() + timeoutMs; + while (System.currentTimeMillis() < deadline) { + if (condition.getAsBoolean()) { + return true; + } + Thread.sleep(10); + } + return condition.getAsBoolean(); + } } diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/TimeGeneratorTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/TimeGeneratorTests.java index 8adf8f3c1..1796f5a9f 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/TimeGeneratorTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/TimeGeneratorTests.java @@ -73,4 +73,39 @@ public void testMidTimeRandomChange() { Assert.assertNotSame(last, next); } } + + /** + * Ids drawn faster than the clock moves, and across clock jumps backwards and forwards, are + * strictly increasing, so no two stored objects ever share an id. + */ + @Test + public void id_neverRepeatsOrGoesBack() { + UniqueTimeGenerator simulator = new UniqueTimeGenerator(); + + long last = simulator.id(); + for (int i = 0; i < 100_000; i++) { + if (i % 30 == 0) { + simulator.addition = Math.round(Math.random() * 10_000 - 5000); + } + long next = simulator.id(); + Assert.assertTrue(next + " is not greater than the previous id " + last, next > last); + last = next; + } + } + + /** + * Once the clock has moved past the last id, the next id is the current time again, so ids + * keep dating the objects they name. + */ + @Test + public void id_followsTheClockOnceItIsAhead() { + UniqueTimeGenerator simulator = new UniqueTimeGenerator(); + + long first = simulator.id(); + simulator.addition = 60_000; + long later = simulator.id(); + + Assert.assertTrue(later >= first + 60_000); + Assert.assertTrue(later <= System.currentTimeMillis() + 60_000); + } } diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/TransportConnectionTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/TransportConnectionTests.java index 731986264..d4152390b 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/TransportConnectionTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/TransportConnectionTests.java @@ -110,8 +110,19 @@ private Config localServerConfig() { } private Transport buildTransport(Config config) { + return buildTransport(config, null); + } + + /** + * Builds a transport whose log lines go to the given callback. + * + * @param config the configuration to build it from + * @param logCallback receives every log line, or null for none + * @return the initialized transport + */ + private Transport buildTransport(Config config, LogCallback logCallback) { InternalConfig ic = new InternalConfig(config); - ic.setLogger(new Log(Config.LoggingLevel.OFF, null)); + ic.setLogger(new Log(Config.LoggingLevel.OFF, logCallback)); Transport transport = new Transport(); transport.init(ic); return transport; @@ -186,6 +197,31 @@ public void connection_shortGetRequest_defaultEndpointDeviceIdFallbackAndCustomH Assert.assertFalse(request.params.has(Request.ENDPOINT)); } + /** + * Custom header values often carry credentials, so the log says how many headers are added + * and never shows a value, while the header itself still reaches the server. + */ + @Test + public void connection_logsTheCustomHeaderCountButNoValue() throws IOException { + Config config = localServerConfig(); + Map customHeaders = new ConcurrentHashMap<>(); + customHeaders.put("Authorization", "Bearer secret-token"); + config.addCustomNetworkRequestHeaders(customHeaders); + List logLines = Collections.synchronizedList(new ArrayList<>()); + Transport transport = buildTransport(config, (message, level) -> logLines.add(message)); + + HttpURLConnection connection = transport.connection(new Request()); + connection.connect(); + Assert.assertEquals(200, connection.getResponseCode()); + connection.disconnect(); + + Assert.assertTrue(logLines.contains("[Transport] connection, Adding [1] custom header fields")); + for (String line : logLines) { + Assert.assertFalse(line, line.contains("secret-token")); + } + Assert.assertEquals("Bearer secret-token", lastRequest().headers.get("Authorization")); + } + /** * When the request already carries a "device_id" the fallback from {@link InternalConfig#getDeviceId()} * must not override it, even though a device id is configured. diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/UtilsInternalLimitsTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/UtilsInternalLimitsTests.java new file mode 100644 index 000000000..4f3ad28df --- /dev/null +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/UtilsInternalLimitsTests.java @@ -0,0 +1,168 @@ +package ly.count.sdk.java.internal; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import ly.count.sdk.java.Config; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * The truncation rules of {@link UtilsInternalLimits} that the scenarios through the public API cannot + * reach on every platform: surrogate pairs, {@code \r\n} line breaks, {@code null} keys and the + * independence from the order of a map. + */ +@RunWith(JUnit4.class) +public class UtilsInternalLimitsTests { + + private static final String TAG = "[Caller] method"; + private final List warnings = new CopyOnWriteArrayList<>(); + private Log log; + + /** + * Starts every test with a logger that keeps every warning. + */ + @Before + public void beforeTest() { + warnings.clear(); + log = new Log(Config.LoggingLevel.OFF, (message, level) -> { + if (level == Config.LoggingLevel.WARN) { + warnings.add(message); + } + }); + } + + /** + * Keys and values are cut to the limit and never inside a surrogate pair. + *

+ * Verifies that {@code null}, empty and short strings come back as the same instance without a + * warning; that a longer string is cut to the limit with one warning naming the caller; that a + * cut falling inside a surrogate pair falls before it, or after it when the pair starts the + * string; and that only strings are cut by value, other types coming back as they are. + */ + @Test + public void strings_areCutToTheLimit_neverInsideASurrogatePair() { + String shortKey = "key"; + Assert.assertSame(shortKey, UtilsInternalLimits.truncateKey(shortKey, 3, log, TAG)); + Assert.assertNull(UtilsInternalLimits.truncateKey(null, 1, log, TAG)); + Assert.assertEquals("", UtilsInternalLimits.truncateValue("", 1, log, TAG)); + Assert.assertEquals(0, warnings.size()); + + Assert.assertEquals("abc", UtilsInternalLimits.truncateKey("abcdef", 3, log, TAG)); + Assert.assertEquals(1, warnings.size()); + Assert.assertTrue(warnings.get(0), warnings.get(0).startsWith(TAG + ", the key [abcdef] is longer than the key length limit of [3]")); + Assert.assertEquals("abcd", UtilsInternalLimits.truncateValue("abcdefgh", 4, log, TAG)); + Assert.assertTrue(warnings.get(1), warnings.get(1).startsWith(TAG + ", a value of [8] characters is longer than the value size limit of [4]")); + + String grinning = "😀"; + Assert.assertEquals("ab", UtilsInternalLimits.truncateValue("ab" + grinning + "cd", 3, log, TAG)); + Assert.assertEquals("ab" + grinning, UtilsInternalLimits.truncateValue("ab" + grinning + "cd", 4, log, TAG)); + Assert.assertEquals(grinning, UtilsInternalLimits.truncateKey(grinning + "rest", 1, log, TAG)); + + Integer number = 123_456_789; + Assert.assertSame(number, UtilsInternalLimits.truncateIfString(number, 2, log, TAG)); + Assert.assertEquals("12", UtilsInternalLimits.truncateIfString("123456789", 2, log, TAG)); + } + + /** + * A segmentation is cut and trimmed the same way whatever the order of its map, and never in place. + *

+ * Verifies that a segmentation within every limit, and {@code null}, come back as the same + * instance; that the same entries in two insertion orders give the same result, where of the keys + * cut to the same key the one that sorts last keeps its value and past the entry limit the keys + * that sort first are kept; that the caller's map is left as it was; that a {@code null} key + * sorts first and is never cut; and that cutting values only keeps every key in the order of the map. + */ + @Test + public void segmentation_isCutTheSameWayWhateverTheOrderOfTheMap_andNeverInPlace() { + Map within = TestUtils.map("abc", "value", "number", 12_345_678); + Assert.assertSame(within, UtilsInternalLimits.applySegmentationLimits(within, limits(6, 5, 2), log, TAG)); + Assert.assertNull(UtilsInternalLimits.applySegmentationLimits(null, limits(1, 1, 1), log, TAG)); + Assert.assertEquals(0, warnings.size()); + + Map forward = new LinkedHashMap<>(); + forward.put("colour_a", "red"); + forward.put("colour_b", "green"); + forward.put("colour_c", "blue"); + forward.put("amount", 5); + forward.put("zone", "europe_west"); + Map backward = new LinkedHashMap<>(); + List keys = Arrays.asList(forward.keySet().toArray(new String[0])); + Collections.reverse(keys); + for (String key : keys) { + backward.put(key, forward.get(key)); + } + Map forwardCopy = new HashMap<>(forward); + + Map expected = TestUtils.map("amoun", 5, "colou", "blue"); + Assert.assertEquals(expected, UtilsInternalLimits.applySegmentationLimits(forward, limits(5, 6, 2), log, TAG)); + Assert.assertEquals(expected, UtilsInternalLimits.applySegmentationLimits(backward, limits(5, 6, 2), log, TAG)); + Assert.assertEquals(Arrays.asList("amoun", "colou"), Arrays.asList(UtilsInternalLimits.applySegmentationLimits(backward, limits(5, 6, 2), log, TAG).keySet().toArray())); + Assert.assertEquals(forwardCopy, forward); + + Map withNullKey = new HashMap<>(); + withNullKey.put(null, "null_key_value"); + withNullKey.put("longer_key", 1); + Map limited = UtilsInternalLimits.applySegmentationLimits(withNullKey, limits(3, 100, 1), log, TAG); + Assert.assertEquals(Collections.singletonMap(null, "null_key_value"), limited); + + Map ordered = new LinkedHashMap<>(); + ordered.put("zeta", "long_value"); + ordered.put("alpha", 1); + ordered.put("mid", "short"); + Assert.assertSame(ordered, UtilsInternalLimits.truncateStringValues(ordered, 10, log, TAG)); + Map valuesCut = UtilsInternalLimits.truncateStringValues(ordered, 5, log, TAG); + Assert.assertEquals(Arrays.asList("zeta", "alpha", "mid"), Arrays.asList(valuesCut.keySet().toArray())); + Assert.assertEquals("long_", valuesCut.get("zeta")); + Assert.assertEquals("long_value", ordered.get("zeta")); + } + + /** + * Stack trace lines are cut without touching the line breaks, and the lines of a thread are + * counted from the top. + *

+ * Verifies that a stack trace within the limit comes back as the same instance; that {@code \n} + * and {@code \r\n} breaks, empty lines and a last line without a break are kept, the {@code \r} + * never counting as a character of its line; that one warning is logged per stack trace; and + * that the lines to keep of a thread are the limit only when the thread has more. + */ + @Test + public void stackTraces_linesAreCutWithoutTouchingTheLineBreaks_andLinesPerThreadCountFromTheTop() { + String within = "abc\r\nde\n\nf"; + Assert.assertSame(within, UtilsInternalLimits.truncateStackTraceLines(within, 3, log, TAG)); + + String stackTrace = "java.lang.Exception: message\r\n\tat first.frame(File.java:1)\n\n\tat last.frame(File.java:2)\r\nno_break_at_the_end"; + Assert.assertEquals("java.lang.\r\n\tat first.\n\n\tat last.f\r\nno_break_a", UtilsInternalLimits.truncateStackTraceLines(stackTrace, 10, log, TAG)); + Assert.assertEquals(1, warnings.size()); + Assert.assertTrue(warnings.get(0), warnings.get(0).startsWith(TAG + ", [4] stack trace lines are longer than the line length limit of [10]")); + Assert.assertEquals("12\r\n34\r\n", UtilsInternalLimits.truncateStackTraceLines("123\r\n345\r\n", 2, log, TAG)); + + Assert.assertEquals(5, UtilsInternalLimits.stackTraceLinesToKeep(5, 5, "worker", log, TAG)); + Assert.assertEquals(2, warnings.size()); + Assert.assertEquals(3, UtilsInternalLimits.stackTraceLinesToKeep(5, 3, "worker", log, TAG)); + Assert.assertTrue(warnings.get(2), warnings.get(2).startsWith(TAG + ", the stack trace of the thread [worker] has [5] lines, over the limit of [3]")); + } + + /** + * A settings provider serving the given key length, value size and segmentation entry limits. + * + * @param maxKeyLength the key length limit + * @param maxValueSize the value size limit + * @param maxSegmentationValues the segmentation entry limit + * @return the provider + */ + private static ConfigurationProvider limits(int maxKeyLength, int maxValueSize, int maxSegmentationValues) { + ModuleConfiguration limits = new ModuleConfiguration(); + limits.currentVMaxKeyLength = maxKeyLength; + limits.currentVMaxValueSize = maxValueSize; + limits.currentVMaxSegmentationValues = maxSegmentationValues; + return limits; + } +} diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/sc_MV_ManualViewTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/sc_MV_ManualViewTests.java index b94a9eadd..0725a0b3a 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/sc_MV_ManualViewTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/sc_MV_ManualViewTests.java @@ -16,8 +16,9 @@ @RunWith(JUnit4.class) public class sc_MV_ManualViewTests { @Before - public void beforeTest() { + public void beforeTest() throws InterruptedException { TestUtils.createCleanTestState(); + TestUtils.awaitStartOfSecond(); } @After