Add decompiled APK source code (JADX)

- 28,932 files
- Full Java source code
- Smali files
- Resources

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-02-18 14:52:23 -08:00
parent cc210a65ea
commit f9d20bb3fc
26991 changed files with 2541449 additions and 0 deletions

View File

@@ -0,0 +1,488 @@
package com.google.firebase.perf.metrics;
import android.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Process;
import android.view.View;
import android.view.ViewTreeObserver;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ProcessLifecycleOwner;
import com.facebook.internal.security.CertificateUtil;
import com.google.firebase.FirebaseApp;
import com.google.firebase.StartupTime;
import com.google.firebase.perf.config.ConfigResolver;
import com.google.firebase.perf.logging.AndroidLogger;
import com.google.firebase.perf.session.PerfSession;
import com.google.firebase.perf.session.SessionManager;
import com.google.firebase.perf.transport.TransportManager;
import com.google.firebase.perf.util.Clock;
import com.google.firebase.perf.util.Constants$TraceNames;
import com.google.firebase.perf.util.FirstDrawDoneListener;
import com.google.firebase.perf.util.PreDrawListener;
import com.google.firebase.perf.util.Timer;
import com.google.firebase.perf.v1.ApplicationProcessState;
import com.google.firebase.perf.v1.TraceMetric;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/* loaded from: classes3.dex */
public class AppStartTrace implements Application.ActivityLifecycleCallbacks, LifecycleObserver {
private static final int CORE_POOL_SIZE = 0;
private static final int MAX_POOL_SIZE = 1;
private static ExecutorService executorService;
private static volatile AppStartTrace instance;
private Context appContext;
private WeakReference<Activity> appStartActivity;
private final Clock clock;
private final ConfigResolver configResolver;
private final TraceMetric.Builder experimentTtid;
@Nullable
private final Timer firebaseClassLoadTime;
private WeakReference<Activity> launchActivity;
@Nullable
private final Timer processStartTime;
private PerfSession startSession;
private final TransportManager transportManager;
@NonNull
private static final Timer PERF_CLASS_LOAD_TIME = new Clock().getTime();
private static final long MAX_LATENCY_BEFORE_UI_INIT = TimeUnit.MINUTES.toMicros(1);
private boolean isRegisteredForLifecycleCallbacks = false;
private boolean isTooLateToInitUI = false;
private Timer onCreateTime = null;
private Timer onStartTime = null;
private Timer onResumeTime = null;
private Timer firstForegroundTime = null;
@Nullable
private Timer firstBackgroundTime = null;
private Timer preDrawPostTime = null;
private Timer preDrawPostAtFrontOfQueueTime = null;
private Timer onDrawPostAtFrontOfQueueTime = null;
private boolean isStartedFromBackground = false;
private int onDrawCount = 0;
private final DrawCounter onDrawCounterListener = new DrawCounter();
private boolean systemForegroundCheck = false;
@NonNull
private Timer getClassLoadTimeCompat() {
Timer timer = this.firebaseClassLoadTime;
return timer != null ? timer : PERF_CLASS_LOAD_TIME;
}
@Keep
public static void setLauncherActivityOnCreateTime(String str) {
}
@Keep
public static void setLauncherActivityOnResumeTime(String str) {
}
@Keep
public static void setLauncherActivityOnStartTime(String str) {
}
@VisibleForTesting
public Timer getOnCreateTime() {
return this.onCreateTime;
}
@VisibleForTesting
public Timer getOnResumeTime() {
return this.onResumeTime;
}
@VisibleForTesting
public Timer getOnStartTime() {
return this.onStartTime;
}
@Override // android.app.Application.ActivityLifecycleCallbacks
public void onActivityDestroyed(Activity activity) {
}
@Override // android.app.Application.ActivityLifecycleCallbacks
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override // android.app.Application.ActivityLifecycleCallbacks
public void onActivityStopped(Activity activity) {
}
@VisibleForTesting
public void setIsStartFromBackground() {
this.isStartedFromBackground = true;
}
public static /* synthetic */ int access$308(AppStartTrace appStartTrace) {
int i = appStartTrace.onDrawCount;
appStartTrace.onDrawCount = i + 1;
return i;
}
public static AppStartTrace getInstance() {
return instance != null ? instance : getInstance(TransportManager.getInstance(), new Clock());
}
@SuppressLint({"ThreadPoolCreation"})
public static AppStartTrace getInstance(TransportManager transportManager, Clock clock) {
if (instance == null) {
synchronized (AppStartTrace.class) {
try {
if (instance == null) {
instance = new AppStartTrace(transportManager, clock, ConfigResolver.getInstance(), new ThreadPoolExecutor(0, 1, MAX_LATENCY_BEFORE_UI_INIT + 10, TimeUnit.SECONDS, new LinkedBlockingQueue()));
}
} finally {
}
}
}
return instance;
}
/* JADX WARN: Multi-variable type inference failed */
public AppStartTrace(@NonNull TransportManager transportManager, @NonNull Clock clock, @NonNull ConfigResolver configResolver, @NonNull ExecutorService executorService2) {
this.transportManager = transportManager;
this.clock = clock;
this.configResolver = configResolver;
executorService = executorService2;
this.experimentTtid = TraceMetric.newBuilder().setName("_experiment_app_start_ttid");
this.processStartTime = Timer.ofElapsedRealtime(Process.getStartElapsedRealtime());
StartupTime startupTime = (StartupTime) FirebaseApp.getInstance().get(StartupTime.class);
this.firebaseClassLoadTime = startupTime != null ? Timer.ofElapsedRealtime(startupTime.getElapsedRealtime()) : null;
}
public synchronized void registerActivityLifecycleCallbacks(@NonNull Context context) {
boolean z;
try {
if (this.isRegisteredForLifecycleCallbacks) {
return;
}
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
Context applicationContext = context.getApplicationContext();
if (applicationContext instanceof Application) {
((Application) applicationContext).registerActivityLifecycleCallbacks(this);
if (!this.systemForegroundCheck && !isAnyAppProcessInForeground(applicationContext)) {
z = false;
this.systemForegroundCheck = z;
this.isRegisteredForLifecycleCallbacks = true;
this.appContext = applicationContext;
}
z = true;
this.systemForegroundCheck = z;
this.isRegisteredForLifecycleCallbacks = true;
this.appContext = applicationContext;
}
} catch (Throwable th) {
throw th;
}
}
public synchronized void unregisterActivityLifecycleCallbacks() {
if (this.isRegisteredForLifecycleCallbacks) {
ProcessLifecycleOwner.get().getLifecycle().removeObserver(this);
((Application) this.appContext).unregisterActivityLifecycleCallbacks(this);
this.isRegisteredForLifecycleCallbacks = false;
}
}
@NonNull
private Timer getStartTimerCompat() {
Timer timer = this.processStartTime;
return timer != null ? timer : getClassLoadTimeCompat();
}
/* JADX INFO: Access modifiers changed from: private */
public void recordPreDraw() {
if (this.preDrawPostTime != null) {
return;
}
this.preDrawPostTime = this.clock.getTime();
this.experimentTtid.setClientStartTimeUs(getStartTimerCompat().getMicros()).setDurationUs(getStartTimerCompat().getDurationMicros(this.preDrawPostTime));
logExperimentTrace(this.experimentTtid);
}
/* JADX INFO: Access modifiers changed from: private */
public void recordPreDrawFrontOfQueue() {
if (this.preDrawPostAtFrontOfQueueTime != null) {
return;
}
this.preDrawPostAtFrontOfQueueTime = this.clock.getTime();
this.experimentTtid.addSubtraces((TraceMetric) TraceMetric.newBuilder().setName("_experiment_preDrawFoQ").setClientStartTimeUs(getStartTimerCompat().getMicros()).setDurationUs(getStartTimerCompat().getDurationMicros(this.preDrawPostAtFrontOfQueueTime)).build());
logExperimentTrace(this.experimentTtid);
}
/* JADX INFO: Access modifiers changed from: private */
public void recordOnDrawFrontOfQueue() {
if (this.onDrawPostAtFrontOfQueueTime != null) {
return;
}
this.onDrawPostAtFrontOfQueueTime = this.clock.getTime();
this.experimentTtid.addSubtraces((TraceMetric) TraceMetric.newBuilder().setName("_experiment_onDrawFoQ").setClientStartTimeUs(getStartTimerCompat().getMicros()).setDurationUs(getStartTimerCompat().getDurationMicros(this.onDrawPostAtFrontOfQueueTime)).build());
if (this.processStartTime != null) {
this.experimentTtid.addSubtraces((TraceMetric) TraceMetric.newBuilder().setName("_experiment_procStart_to_classLoad").setClientStartTimeUs(getStartTimerCompat().getMicros()).setDurationUs(getStartTimerCompat().getDurationMicros(getClassLoadTimeCompat())).build());
}
this.experimentTtid.putCustomAttributes("systemDeterminedForeground", this.systemForegroundCheck ? "true" : "false");
this.experimentTtid.putCounters("onDrawCount", this.onDrawCount);
this.experimentTtid.addPerfSessions(this.startSession.build());
logExperimentTrace(this.experimentTtid);
}
/* JADX WARN: Removed duplicated region for block: B:16:0x003e A[Catch: all -> 0x001a, TRY_LEAVE, TryCatch #0 {all -> 0x001a, blocks: (B:3:0x0001, B:5:0x0005, B:8:0x000a, B:10:0x000f, B:14:0x001d, B:16:0x003e), top: B:2:0x0001 }] */
@Override // android.app.Application.ActivityLifecycleCallbacks
/*
Code decompiled incorrectly, please refer to instructions dump.
To view partially-correct add '--show-bad-code' argument
*/
public synchronized void onActivityCreated(android.app.Activity r4, android.os.Bundle r5) {
/*
r3 = this;
monitor-enter(r3)
boolean r5 = r3.isStartedFromBackground // Catch: java.lang.Throwable -> L1a
if (r5 != 0) goto L42
com.google.firebase.perf.util.Timer r5 = r3.onCreateTime // Catch: java.lang.Throwable -> L1a
if (r5 == 0) goto La
goto L42
La:
boolean r5 = r3.systemForegroundCheck // Catch: java.lang.Throwable -> L1a
r0 = 1
if (r5 != 0) goto L1c
android.content.Context r5 = r3.appContext // Catch: java.lang.Throwable -> L1a
boolean r5 = isAnyAppProcessInForeground(r5) // Catch: java.lang.Throwable -> L1a
if (r5 == 0) goto L18
goto L1c
L18:
r5 = 0
goto L1d
L1a:
r4 = move-exception
goto L44
L1c:
r5 = r0
L1d:
r3.systemForegroundCheck = r5 // Catch: java.lang.Throwable -> L1a
java.lang.ref.WeakReference r5 = new java.lang.ref.WeakReference // Catch: java.lang.Throwable -> L1a
r5.<init>(r4) // Catch: java.lang.Throwable -> L1a
r3.launchActivity = r5 // Catch: java.lang.Throwable -> L1a
com.google.firebase.perf.util.Clock r4 = r3.clock // Catch: java.lang.Throwable -> L1a
com.google.firebase.perf.util.Timer r4 = r4.getTime() // Catch: java.lang.Throwable -> L1a
r3.onCreateTime = r4 // Catch: java.lang.Throwable -> L1a
com.google.firebase.perf.util.Timer r4 = r3.getStartTimerCompat() // Catch: java.lang.Throwable -> L1a
com.google.firebase.perf.util.Timer r5 = r3.onCreateTime // Catch: java.lang.Throwable -> L1a
long r4 = r4.getDurationMicros(r5) // Catch: java.lang.Throwable -> L1a
long r1 = com.google.firebase.perf.metrics.AppStartTrace.MAX_LATENCY_BEFORE_UI_INIT // Catch: java.lang.Throwable -> L1a
int r4 = (r4 > r1 ? 1 : (r4 == r1 ? 0 : -1))
if (r4 <= 0) goto L40
r3.isTooLateToInitUI = r0 // Catch: java.lang.Throwable -> L1a
L40:
monitor-exit(r3)
return
L42:
monitor-exit(r3)
return
L44:
monitor-exit(r3)
throw r4
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.firebase.perf.metrics.AppStartTrace.onActivityCreated(android.app.Activity, android.os.Bundle):void");
}
@Override // android.app.Application.ActivityLifecycleCallbacks
public synchronized void onActivityStarted(Activity activity) {
if (!this.isStartedFromBackground && this.onStartTime == null && !this.isTooLateToInitUI) {
this.onStartTime = this.clock.getTime();
}
}
@Override // android.app.Application.ActivityLifecycleCallbacks
public synchronized void onActivityResumed(Activity activity) {
try {
if (!this.isStartedFromBackground && !this.isTooLateToInitUI) {
boolean isExperimentTTIDEnabled = this.configResolver.getIsExperimentTTIDEnabled();
if (isExperimentTTIDEnabled) {
View findViewById = activity.findViewById(R.id.content);
findViewById.getViewTreeObserver().addOnDrawListener(this.onDrawCounterListener);
FirstDrawDoneListener.registerForNextDraw(findViewById, new Runnable() { // from class: com.google.firebase.perf.metrics.AppStartTrace$$ExternalSyntheticLambda0
@Override // java.lang.Runnable
public final void run() {
AppStartTrace.this.recordOnDrawFrontOfQueue();
}
});
PreDrawListener.registerForNextDraw(findViewById, new Runnable() { // from class: com.google.firebase.perf.metrics.AppStartTrace$$ExternalSyntheticLambda1
@Override // java.lang.Runnable
public final void run() {
AppStartTrace.this.recordPreDraw();
}
}, new Runnable() { // from class: com.google.firebase.perf.metrics.AppStartTrace$$ExternalSyntheticLambda2
@Override // java.lang.Runnable
public final void run() {
AppStartTrace.this.recordPreDrawFrontOfQueue();
}
});
}
if (this.onResumeTime != null) {
return;
}
this.appStartActivity = new WeakReference<>(activity);
this.onResumeTime = this.clock.getTime();
this.startSession = SessionManager.getInstance().perfSession();
AndroidLogger.getInstance().debug("onResume(): " + activity.getClass().getName() + ": " + getClassLoadTimeCompat().getDurationMicros(this.onResumeTime) + " microseconds");
executorService.execute(new Runnable() { // from class: com.google.firebase.perf.metrics.AppStartTrace$$ExternalSyntheticLambda3
@Override // java.lang.Runnable
public final void run() {
AppStartTrace.this.logAppStartTrace();
}
});
if (!isExperimentTTIDEnabled) {
unregisterActivityLifecycleCallbacks();
}
}
} finally {
}
}
private void logExperimentTrace(final TraceMetric.Builder builder) {
if (this.preDrawPostTime == null || this.preDrawPostAtFrontOfQueueTime == null || this.onDrawPostAtFrontOfQueueTime == null) {
return;
}
executorService.execute(new Runnable() { // from class: com.google.firebase.perf.metrics.AppStartTrace$$ExternalSyntheticLambda4
@Override // java.lang.Runnable
public final void run() {
AppStartTrace.this.lambda$logExperimentTrace$0(builder);
}
});
unregisterActivityLifecycleCallbacks();
}
/* JADX INFO: Access modifiers changed from: private */
public /* synthetic */ void lambda$logExperimentTrace$0(TraceMetric.Builder builder) {
this.transportManager.log((TraceMetric) builder.build(), ApplicationProcessState.FOREGROUND_BACKGROUND);
}
/* JADX INFO: Access modifiers changed from: private */
public void logAppStartTrace() {
TraceMetric.Builder durationUs = TraceMetric.newBuilder().setName(Constants$TraceNames.APP_START_TRACE_NAME.toString()).setClientStartTimeUs(getClassLoadTimeCompat().getMicros()).setDurationUs(getClassLoadTimeCompat().getDurationMicros(this.onResumeTime));
ArrayList arrayList = new ArrayList(3);
arrayList.add((TraceMetric) TraceMetric.newBuilder().setName(Constants$TraceNames.ON_CREATE_TRACE_NAME.toString()).setClientStartTimeUs(getClassLoadTimeCompat().getMicros()).setDurationUs(getClassLoadTimeCompat().getDurationMicros(this.onCreateTime)).build());
if (this.onStartTime != null) {
TraceMetric.Builder newBuilder = TraceMetric.newBuilder();
newBuilder.setName(Constants$TraceNames.ON_START_TRACE_NAME.toString()).setClientStartTimeUs(this.onCreateTime.getMicros()).setDurationUs(this.onCreateTime.getDurationMicros(this.onStartTime));
arrayList.add((TraceMetric) newBuilder.build());
TraceMetric.Builder newBuilder2 = TraceMetric.newBuilder();
newBuilder2.setName(Constants$TraceNames.ON_RESUME_TRACE_NAME.toString()).setClientStartTimeUs(this.onStartTime.getMicros()).setDurationUs(this.onStartTime.getDurationMicros(this.onResumeTime));
arrayList.add((TraceMetric) newBuilder2.build());
}
durationUs.addAllSubtraces(arrayList).addPerfSessions(this.startSession.build());
this.transportManager.log((TraceMetric) durationUs.build(), ApplicationProcessState.FOREGROUND_BACKGROUND);
}
@Override // android.app.Application.ActivityLifecycleCallbacks
public void onActivityPaused(Activity activity) {
if (this.isStartedFromBackground || this.isTooLateToInitUI || !this.configResolver.getIsExperimentTTIDEnabled()) {
return;
}
activity.findViewById(R.id.content).getViewTreeObserver().removeOnDrawListener(this.onDrawCounterListener);
}
@Keep
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onAppEnteredForeground() {
if (this.isStartedFromBackground || this.isTooLateToInitUI || this.firstForegroundTime != null) {
return;
}
this.firstForegroundTime = this.clock.getTime();
this.experimentTtid.addSubtraces((TraceMetric) TraceMetric.newBuilder().setName("_experiment_firstForegrounding").setClientStartTimeUs(getStartTimerCompat().getMicros()).setDurationUs(getStartTimerCompat().getDurationMicros(this.firstForegroundTime)).build());
}
@Keep
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onAppEnteredBackground() {
if (this.isStartedFromBackground || this.isTooLateToInitUI || this.firstBackgroundTime != null) {
return;
}
this.firstBackgroundTime = this.clock.getTime();
this.experimentTtid.addSubtraces((TraceMetric) TraceMetric.newBuilder().setName("_experiment_firstBackgrounding").setClientStartTimeUs(getStartTimerCompat().getMicros()).setDurationUs(getStartTimerCompat().getDurationMicros(this.firstBackgroundTime)).build());
}
public static boolean isAnyAppProcessInForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService("activity");
if (activityManager == null) {
return true;
}
List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
if (runningAppProcesses == null) {
return false;
}
String packageName = context.getPackageName();
String str = packageName + CertificateUtil.DELIMITER;
for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) {
if (runningAppProcessInfo.importance == 100 && (runningAppProcessInfo.processName.equals(packageName) || runningAppProcessInfo.processName.startsWith(str))) {
return true;
}
}
return false;
}
public static boolean isScreenOn(Context context) {
PowerManager powerManager = (PowerManager) context.getSystemService("power");
if (powerManager == null) {
return true;
}
return powerManager.isInteractive();
}
public static class StartFromBackgroundRunnable implements Runnable {
public final AppStartTrace trace;
public StartFromBackgroundRunnable(AppStartTrace appStartTrace) {
this.trace = appStartTrace;
}
@Override // java.lang.Runnable
public void run() {
if (this.trace.onCreateTime == null) {
this.trace.isStartedFromBackground = true;
}
}
}
public final class DrawCounter implements ViewTreeObserver.OnDrawListener {
public DrawCounter() {
}
@Override // android.view.ViewTreeObserver.OnDrawListener
public void onDraw() {
AppStartTrace.access$308(AppStartTrace.this);
}
}
@Nullable
@VisibleForTesting
public Activity getLaunchActivity() {
return this.launchActivity.get();
}
@Nullable
@VisibleForTesting
public Activity getAppStartActivity() {
return this.appStartActivity.get();
}
}

View File

@@ -0,0 +1,59 @@
package com.google.firebase.perf.metrics;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.concurrent.atomic.AtomicLong;
/* loaded from: classes3.dex */
public class Counter implements Parcelable {
public static final Parcelable.Creator<Counter> CREATOR = new Parcelable.Creator() { // from class: com.google.firebase.perf.metrics.Counter.1
@Override // android.os.Parcelable.Creator
public Counter createFromParcel(Parcel parcel) {
return new Counter(parcel);
}
@Override // android.os.Parcelable.Creator
public Counter[] newArray(int i) {
return new Counter[i];
}
};
public final AtomicLong count;
public final String name;
@Override // android.os.Parcelable
public int describeContents() {
return 0;
}
public String getName() {
return this.name;
}
public Counter(String str) {
this.name = str;
this.count = new AtomicLong(0L);
}
public Counter(Parcel parcel) {
this.name = parcel.readString();
this.count = new AtomicLong(parcel.readLong());
}
public void increment(long j) {
this.count.addAndGet(j);
}
public long getCount() {
return this.count.get();
}
public void setCount(long j) {
this.count.set(j);
}
@Override // android.os.Parcelable
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(this.name);
parcel.writeLong(this.count.get());
}
}

View File

@@ -0,0 +1,64 @@
package com.google.firebase.perf.metrics;
import android.util.SparseIntArray;
/* loaded from: classes3.dex */
public abstract class FrameMetricsCalculator {
public static class PerfFrameMetrics {
public int frozenFrames;
public int slowFrames;
public int totalFrames;
public int getFrozenFrames() {
return this.frozenFrames;
}
public int getSlowFrames() {
return this.slowFrames;
}
public int getTotalFrames() {
return this.totalFrames;
}
public PerfFrameMetrics(int i, int i2, int i3) {
this.totalFrames = i;
this.slowFrames = i2;
this.frozenFrames = i3;
}
public PerfFrameMetrics deltaFrameMetricsFromSnapshot(PerfFrameMetrics perfFrameMetrics) {
return new PerfFrameMetrics(this.totalFrames - perfFrameMetrics.getTotalFrames(), this.slowFrames - perfFrameMetrics.getSlowFrames(), this.frozenFrames - perfFrameMetrics.getFrozenFrames());
}
}
public static PerfFrameMetrics calculateFrameMetrics(SparseIntArray[] sparseIntArrayArr) {
int i;
int i2;
SparseIntArray sparseIntArray;
int i3 = 0;
if (sparseIntArrayArr == null || (sparseIntArray = sparseIntArrayArr[0]) == null) {
i = 0;
i2 = 0;
} else {
int i4 = 0;
i = 0;
i2 = 0;
while (i3 < sparseIntArray.size()) {
int keyAt = sparseIntArray.keyAt(i3);
int valueAt = sparseIntArray.valueAt(i3);
i4 += valueAt;
if (keyAt > 700) {
i2 += valueAt;
}
if (keyAt > 16) {
i += valueAt;
}
i3++;
}
i3 = i4;
}
return new PerfFrameMetrics(i3, i, i2);
}
}

View File

@@ -0,0 +1,248 @@
package com.google.firebase.perf.metrics;
import com.google.firebase.perf.application.AppStateMonitor;
import com.google.firebase.perf.application.AppStateUpdateHandler;
import com.google.firebase.perf.logging.AndroidLogger;
import com.google.firebase.perf.network.NetworkRequestMetricBuilderUtil;
import com.google.firebase.perf.session.PerfSession;
import com.google.firebase.perf.session.SessionAwareObject;
import com.google.firebase.perf.session.SessionManager;
import com.google.firebase.perf.session.gauges.GaugeManager;
import com.google.firebase.perf.transport.TransportManager;
import com.google.firebase.perf.util.Utils;
import com.google.firebase.perf.v1.NetworkRequestMetric;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/* loaded from: classes3.dex */
public final class NetworkRequestMetricBuilder extends AppStateUpdateHandler implements SessionAwareObject {
public static final AndroidLogger logger = AndroidLogger.getInstance();
public final NetworkRequestMetric.Builder builder;
public final GaugeManager gaugeManager;
public boolean isManualNetworkRequestMetric;
public boolean isReportSent;
public final List sessions;
public final TransportManager transportManager;
public String userAgent;
public final WeakReference weakReference;
public NetworkRequestMetricBuilder setUserAgent(String str) {
this.userAgent = str;
return this;
}
@Override // com.google.firebase.perf.session.SessionAwareObject
public void updateSession(PerfSession perfSession) {
if (perfSession == null) {
logger.warn("Unable to add new SessionId to the Network Trace. Continuing without it.");
} else {
if (!hasStarted() || isStopped()) {
return;
}
this.sessions.add(perfSession);
}
}
public static NetworkRequestMetricBuilder builder(TransportManager transportManager) {
return new NetworkRequestMetricBuilder(transportManager);
}
public NetworkRequestMetricBuilder(TransportManager transportManager) {
this(transportManager, AppStateMonitor.getInstance(), GaugeManager.getInstance());
}
public NetworkRequestMetricBuilder(TransportManager transportManager, AppStateMonitor appStateMonitor, GaugeManager gaugeManager) {
super(appStateMonitor);
this.builder = NetworkRequestMetric.newBuilder();
this.weakReference = new WeakReference(this);
this.transportManager = transportManager;
this.gaugeManager = gaugeManager;
this.sessions = Collections.synchronizedList(new ArrayList());
registerForAppState();
}
public NetworkRequestMetricBuilder setUrl(String str) {
if (str != null) {
this.builder.setUrl(Utils.truncateURL(Utils.stripSensitiveInfo(str), 2000));
}
return this;
}
public NetworkRequestMetricBuilder setHttpMethod(String str) {
NetworkRequestMetric.HttpMethod httpMethod;
if (str != null) {
NetworkRequestMetric.HttpMethod httpMethod2 = NetworkRequestMetric.HttpMethod.HTTP_METHOD_UNKNOWN;
String upperCase = str.toUpperCase();
upperCase.hashCode();
switch (upperCase) {
case "OPTIONS":
httpMethod = NetworkRequestMetric.HttpMethod.OPTIONS;
break;
case "GET":
httpMethod = NetworkRequestMetric.HttpMethod.GET;
break;
case "PUT":
httpMethod = NetworkRequestMetric.HttpMethod.PUT;
break;
case "HEAD":
httpMethod = NetworkRequestMetric.HttpMethod.HEAD;
break;
case "POST":
httpMethod = NetworkRequestMetric.HttpMethod.POST;
break;
case "PATCH":
httpMethod = NetworkRequestMetric.HttpMethod.PATCH;
break;
case "TRACE":
httpMethod = NetworkRequestMetric.HttpMethod.TRACE;
break;
case "CONNECT":
httpMethod = NetworkRequestMetric.HttpMethod.CONNECT;
break;
case "DELETE":
httpMethod = NetworkRequestMetric.HttpMethod.DELETE;
break;
default:
httpMethod = NetworkRequestMetric.HttpMethod.HTTP_METHOD_UNKNOWN;
break;
}
this.builder.setHttpMethod(httpMethod);
}
return this;
}
public NetworkRequestMetricBuilder setHttpResponseCode(int i) {
this.builder.setHttpResponseCode(i);
return this;
}
public boolean hasHttpResponseCode() {
return this.builder.hasHttpResponseCode();
}
public NetworkRequestMetricBuilder setRequestPayloadBytes(long j) {
this.builder.setRequestPayloadBytes(j);
return this;
}
public NetworkRequestMetricBuilder setRequestStartTimeMicros(long j) {
PerfSession perfSession = SessionManager.getInstance().perfSession();
SessionManager.getInstance().registerForSessionUpdates(this.weakReference);
this.builder.setClientStartTimeUs(j);
updateSession(perfSession);
if (perfSession.isGaugeAndEventCollectionEnabled()) {
this.gaugeManager.collectGaugeMetricOnce(perfSession.getTimer());
}
return this;
}
public NetworkRequestMetricBuilder setTimeToRequestCompletedMicros(long j) {
this.builder.setTimeToRequestCompletedUs(j);
return this;
}
public NetworkRequestMetricBuilder setTimeToResponseInitiatedMicros(long j) {
this.builder.setTimeToResponseInitiatedUs(j);
return this;
}
public long getTimeToResponseInitiatedMicros() {
return this.builder.getTimeToResponseInitiatedUs();
}
public NetworkRequestMetricBuilder setTimeToResponseCompletedMicros(long j) {
this.builder.setTimeToResponseCompletedUs(j);
if (SessionManager.getInstance().perfSession().isGaugeAndEventCollectionEnabled()) {
this.gaugeManager.collectGaugeMetricOnce(SessionManager.getInstance().perfSession().getTimer());
}
return this;
}
public NetworkRequestMetricBuilder setResponsePayloadBytes(long j) {
this.builder.setResponsePayloadBytes(j);
return this;
}
public NetworkRequestMetricBuilder setResponseContentType(String str) {
if (str == null) {
this.builder.clearResponseContentType();
return this;
}
if (isValidContentType(str)) {
this.builder.setResponseContentType(str);
} else {
logger.warn("The content type of the response is not a valid content-type:" + str);
}
return this;
}
public NetworkRequestMetricBuilder setNetworkClientErrorReason() {
this.builder.setNetworkClientErrorReason(NetworkRequestMetric.NetworkClientErrorReason.GENERIC_CLIENT_ERROR);
return this;
}
public NetworkRequestMetric build() {
SessionManager.getInstance().unregisterForSessionUpdates(this.weakReference);
unregisterForAppState();
com.google.firebase.perf.v1.PerfSession[] buildAndSort = PerfSession.buildAndSort(getSessions());
if (buildAndSort != null) {
this.builder.addAllPerfSessions(Arrays.asList(buildAndSort));
}
NetworkRequestMetric networkRequestMetric = (NetworkRequestMetric) this.builder.build();
if (!NetworkRequestMetricBuilderUtil.isAllowedUserAgent(this.userAgent)) {
logger.debug("Dropping network request from a 'User-Agent' that is not allowed");
return networkRequestMetric;
}
if (this.isReportSent) {
if (this.isManualNetworkRequestMetric) {
logger.debug("This metric has already been queued for transmission. Please create a new HttpMetric for each request/response");
}
return networkRequestMetric;
}
this.transportManager.log(networkRequestMetric, getAppState());
this.isReportSent = true;
return networkRequestMetric;
}
private boolean isStopped() {
return this.builder.hasTimeToResponseCompletedUs();
}
private boolean hasStarted() {
return this.builder.hasClientStartTimeUs();
}
public List getSessions() {
List unmodifiableList;
synchronized (this.sessions) {
try {
ArrayList arrayList = new ArrayList();
for (PerfSession perfSession : this.sessions) {
if (perfSession != null) {
arrayList.add(perfSession);
}
}
unmodifiableList = Collections.unmodifiableList(arrayList);
} catch (Throwable th) {
throw th;
}
}
return unmodifiableList;
}
public static boolean isValidContentType(String str) {
if (str.length() > 128) {
return false;
}
for (int i = 0; i < str.length(); i++) {
char charAt = str.charAt(i);
if (charAt <= 31 || charAt > 127) {
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,375 @@
package com.google.firebase.perf.metrics;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.firebase.perf.application.AppStateMonitor;
import com.google.firebase.perf.application.AppStateUpdateHandler;
import com.google.firebase.perf.config.ConfigResolver;
import com.google.firebase.perf.logging.AndroidLogger;
import com.google.firebase.perf.metrics.validator.PerfMetricValidator;
import com.google.firebase.perf.session.PerfSession;
import com.google.firebase.perf.session.SessionAwareObject;
import com.google.firebase.perf.session.SessionManager;
import com.google.firebase.perf.session.gauges.GaugeManager;
import com.google.firebase.perf.transport.TransportManager;
import com.google.firebase.perf.util.Clock;
import com.google.firebase.perf.util.Timer;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/* loaded from: classes3.dex */
public class Trace extends AppStateUpdateHandler implements Parcelable, SessionAwareObject {
public final Clock clock;
public final Map counterNameToCounterMap;
public final Map customAttributesMap;
public Timer endTime;
public final GaugeManager gaugeManager;
public final String name;
public final Trace parent;
public final WeakReference sessionAwareObject;
public final List sessions;
public Timer startTime;
public final List subtraces;
public final TransportManager transportManager;
public static final AndroidLogger logger = AndroidLogger.getInstance();
public static final Map traceNameToTraceMap = new ConcurrentHashMap();
@Keep
public static final Parcelable.Creator<Trace> CREATOR = new Parcelable.Creator() { // from class: com.google.firebase.perf.metrics.Trace.1
@Override // android.os.Parcelable.Creator
public Trace createFromParcel(Parcel parcel) {
return new Trace(parcel, false);
}
@Override // android.os.Parcelable.Creator
public Trace[] newArray(int i) {
return new Trace[i];
}
};
public static final Parcelable.Creator CREATOR_DATAONLY = new Parcelable.Creator() { // from class: com.google.firebase.perf.metrics.Trace.2
@Override // android.os.Parcelable.Creator
public Trace createFromParcel(Parcel parcel) {
return new Trace(parcel, true);
}
@Override // android.os.Parcelable.Creator
public Trace[] newArray(int i) {
return new Trace[i];
}
};
@Override // android.os.Parcelable
@Keep
public int describeContents() {
return 0;
}
public Map getCounters() {
return this.counterNameToCounterMap;
}
public Timer getEndTime() {
return this.endTime;
}
public String getName() {
return this.name;
}
public Timer getStartTime() {
return this.startTime;
}
public List getSubtraces() {
return this.subtraces;
}
public boolean hasStarted() {
return this.startTime != null;
}
public boolean isStopped() {
return this.endTime != null;
}
@Override // com.google.firebase.perf.session.SessionAwareObject
public void updateSession(PerfSession perfSession) {
if (perfSession == null) {
logger.warn("Unable to add new SessionId to the Trace. Continuing without it.");
} else {
if (!hasStarted() || isStopped()) {
return;
}
this.sessions.add(perfSession);
}
}
public Trace(String str, TransportManager transportManager, Clock clock, AppStateMonitor appStateMonitor) {
this(str, transportManager, clock, appStateMonitor, GaugeManager.getInstance());
}
public Trace(String str, TransportManager transportManager, Clock clock, AppStateMonitor appStateMonitor, GaugeManager gaugeManager) {
super(appStateMonitor);
this.sessionAwareObject = new WeakReference(this);
this.parent = null;
this.name = str.trim();
this.subtraces = new ArrayList();
this.counterNameToCounterMap = new ConcurrentHashMap();
this.customAttributesMap = new ConcurrentHashMap();
this.clock = clock;
this.transportManager = transportManager;
this.sessions = Collections.synchronizedList(new ArrayList());
this.gaugeManager = gaugeManager;
}
public Trace(Parcel parcel, boolean z) {
super(z ? null : AppStateMonitor.getInstance());
this.sessionAwareObject = new WeakReference(this);
this.parent = (Trace) parcel.readParcelable(Trace.class.getClassLoader());
this.name = parcel.readString();
ArrayList arrayList = new ArrayList();
this.subtraces = arrayList;
parcel.readList(arrayList, Trace.class.getClassLoader());
ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap();
this.counterNameToCounterMap = concurrentHashMap;
this.customAttributesMap = new ConcurrentHashMap();
parcel.readMap(concurrentHashMap, Counter.class.getClassLoader());
this.startTime = (Timer) parcel.readParcelable(Timer.class.getClassLoader());
this.endTime = (Timer) parcel.readParcelable(Timer.class.getClassLoader());
List synchronizedList = Collections.synchronizedList(new ArrayList());
this.sessions = synchronizedList;
parcel.readList(synchronizedList, PerfSession.class.getClassLoader());
if (z) {
this.transportManager = null;
this.clock = null;
this.gaugeManager = null;
} else {
this.transportManager = TransportManager.getInstance();
this.clock = new Clock();
this.gaugeManager = GaugeManager.getInstance();
}
}
@Keep
public void start() {
if (!ConfigResolver.getInstance().isPerformanceMonitoringEnabled()) {
logger.debug("Trace feature is disabled.");
return;
}
String validateTraceName = PerfMetricValidator.validateTraceName(this.name);
if (validateTraceName != null) {
logger.error("Cannot start trace '%s'. Trace name is invalid.(%s)", this.name, validateTraceName);
return;
}
if (this.startTime != null) {
logger.error("Trace '%s' has already started, should not start again!", this.name);
return;
}
this.startTime = this.clock.getTime();
registerForAppState();
PerfSession perfSession = SessionManager.getInstance().perfSession();
SessionManager.getInstance().registerForSessionUpdates(this.sessionAwareObject);
updateSession(perfSession);
if (perfSession.isGaugeAndEventCollectionEnabled()) {
this.gaugeManager.collectGaugeMetricOnce(perfSession.getTimer());
}
}
@Keep
public void stop() {
if (!hasStarted()) {
logger.error("Trace '%s' has not been started so unable to stop!", this.name);
return;
}
if (isStopped()) {
logger.error("Trace '%s' has already stopped, should not stop again!", this.name);
return;
}
SessionManager.getInstance().unregisterForSessionUpdates(this.sessionAwareObject);
unregisterForAppState();
Timer time = this.clock.getTime();
this.endTime = time;
if (this.parent == null) {
setEndTimeOfLastStage(time);
if (!this.name.isEmpty()) {
this.transportManager.log(new TraceMetricBuilder(this).build(), getAppState());
if (SessionManager.getInstance().perfSession().isGaugeAndEventCollectionEnabled()) {
this.gaugeManager.collectGaugeMetricOnce(SessionManager.getInstance().perfSession().getTimer());
return;
}
return;
}
logger.error("Trace name is empty, no log is sent to server");
}
}
public final void setEndTimeOfLastStage(Timer timer) {
if (this.subtraces.isEmpty()) {
return;
}
Trace trace = (Trace) this.subtraces.get(this.subtraces.size() - 1);
if (trace.endTime == null) {
trace.endTime = timer;
}
}
public final Counter obtainOrCreateCounterByName(String str) {
Counter counter = (Counter) this.counterNameToCounterMap.get(str);
if (counter != null) {
return counter;
}
Counter counter2 = new Counter(str);
this.counterNameToCounterMap.put(str, counter2);
return counter2;
}
@Keep
public void incrementMetric(@NonNull String str, long j) {
String validateMetricName = PerfMetricValidator.validateMetricName(str);
if (validateMetricName != null) {
logger.error("Cannot increment metric '%s'. Metric name is invalid.(%s)", str, validateMetricName);
return;
}
if (!hasStarted()) {
logger.warn("Cannot increment metric '%s' for trace '%s' because it's not started", str, this.name);
} else {
if (isStopped()) {
logger.warn("Cannot increment metric '%s' for trace '%s' because it's been stopped", str, this.name);
return;
}
Counter obtainOrCreateCounterByName = obtainOrCreateCounterByName(str.trim());
obtainOrCreateCounterByName.increment(j);
logger.debug("Incrementing metric '%s' to %d on trace '%s'", str, Long.valueOf(obtainOrCreateCounterByName.getCount()), this.name);
}
}
@Keep
public long getLongMetric(@NonNull String str) {
Counter counter = str != null ? (Counter) this.counterNameToCounterMap.get(str.trim()) : null;
if (counter == null) {
return 0L;
}
return counter.getCount();
}
@Keep
public void putMetric(@NonNull String str, long j) {
String validateMetricName = PerfMetricValidator.validateMetricName(str);
if (validateMetricName != null) {
logger.error("Cannot set value for metric '%s'. Metric name is invalid.(%s)", str, validateMetricName);
return;
}
if (!hasStarted()) {
logger.warn("Cannot set value for metric '%s' for trace '%s' because it's not started", str, this.name);
} else if (isStopped()) {
logger.warn("Cannot set value for metric '%s' for trace '%s' because it's been stopped", str, this.name);
} else {
obtainOrCreateCounterByName(str.trim()).setCount(j);
logger.debug("Setting metric '%s' to '%s' on trace '%s'", str, Long.valueOf(j), this.name);
}
}
public void finalize() {
try {
if (isActive()) {
logger.warn("Trace '%s' is started but not stopped when it is destructed!", this.name);
incrementTsnsCount(1);
}
} finally {
super.finalize();
}
}
public boolean isActive() {
return hasStarted() && !isStopped();
}
@Override // android.os.Parcelable
@Keep
public void writeToParcel(@NonNull Parcel parcel, int i) {
parcel.writeParcelable(this.parent, 0);
parcel.writeString(this.name);
parcel.writeList(this.subtraces);
parcel.writeMap(this.counterNameToCounterMap);
parcel.writeParcelable(this.startTime, 0);
parcel.writeParcelable(this.endTime, 0);
synchronized (this.sessions) {
parcel.writeList(this.sessions);
}
}
@Keep
public void putAttribute(@NonNull String str, @NonNull String str2) {
boolean z = false;
try {
str = str.trim();
str2 = str2.trim();
checkAttribute(str, str2);
logger.debug("Setting attribute '%s' to '%s' on trace '%s'", str, str2, this.name);
z = true;
} catch (Exception e) {
logger.error("Can not set attribute '%s' with value '%s' (%s)", str, str2, e.getMessage());
}
if (z) {
this.customAttributesMap.put(str, str2);
}
}
public final void checkAttribute(String str, String str2) {
if (isStopped()) {
throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Trace '%s' has been stopped", this.name));
}
if (!this.customAttributesMap.containsKey(str) && this.customAttributesMap.size() >= 5) {
throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Exceeds max limit of number of attributes - %d", 5));
}
PerfMetricValidator.validateAttribute(str, str2);
}
@Keep
public void removeAttribute(@NonNull String str) {
if (isStopped()) {
logger.error("Can't remove a attribute from a Trace that's stopped.");
} else {
this.customAttributesMap.remove(str);
}
}
@Nullable
@Keep
public String getAttribute(@NonNull String str) {
return (String) this.customAttributesMap.get(str);
}
@NonNull
@Keep
public Map<String, String> getAttributes() {
return new HashMap(this.customAttributesMap);
}
public List getSessions() {
List unmodifiableList;
synchronized (this.sessions) {
try {
ArrayList arrayList = new ArrayList();
for (PerfSession perfSession : this.sessions) {
if (perfSession != null) {
arrayList.add(perfSession);
}
}
unmodifiableList = Collections.unmodifiableList(arrayList);
} catch (Throwable th) {
throw th;
}
}
return unmodifiableList;
}
}

View File

@@ -0,0 +1,36 @@
package com.google.firebase.perf.metrics;
import com.google.firebase.perf.v1.PerfSession;
import com.google.firebase.perf.v1.TraceMetric;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/* loaded from: classes3.dex */
public class TraceMetricBuilder {
public final Trace trace;
public TraceMetricBuilder(Trace trace) {
this.trace = trace;
}
public TraceMetric build() {
TraceMetric.Builder durationUs = TraceMetric.newBuilder().setName(this.trace.getName()).setClientStartTimeUs(this.trace.getStartTime().getMicros()).setDurationUs(this.trace.getStartTime().getDurationMicros(this.trace.getEndTime()));
for (Counter counter : this.trace.getCounters().values()) {
durationUs.putCounters(counter.getName(), counter.getCount());
}
List subtraces = this.trace.getSubtraces();
if (!subtraces.isEmpty()) {
Iterator it = subtraces.iterator();
while (it.hasNext()) {
durationUs.addSubtraces(new TraceMetricBuilder((Trace) it.next()).build());
}
}
durationUs.putAllCustomAttributes(this.trace.getAttributes());
PerfSession[] buildAndSort = com.google.firebase.perf.session.PerfSession.buildAndSort(this.trace.getSessions());
if (buildAndSort != null) {
durationUs.addAllPerfSessions(Arrays.asList(buildAndSort));
}
return (TraceMetric) durationUs.build();
}
}

View File

@@ -0,0 +1,55 @@
package com.google.firebase.perf.metrics.validator;
import com.google.firebase.perf.logging.AndroidLogger;
import com.google.firebase.perf.v1.ApplicationInfo;
/* loaded from: classes3.dex */
public class FirebasePerfApplicationInfoValidator extends PerfMetricValidator {
public static final AndroidLogger logger = AndroidLogger.getInstance();
public final ApplicationInfo applicationInfo;
public FirebasePerfApplicationInfoValidator(ApplicationInfo applicationInfo) {
this.applicationInfo = applicationInfo;
}
@Override // com.google.firebase.perf.metrics.validator.PerfMetricValidator
public boolean isValidPerfMetric() {
if (isValidApplicationInfo()) {
return true;
}
logger.warn("ApplicationInfo is invalid");
return false;
}
public final boolean isValidApplicationInfo() {
ApplicationInfo applicationInfo = this.applicationInfo;
if (applicationInfo == null) {
logger.warn("ApplicationInfo is null");
return false;
}
if (!applicationInfo.hasGoogleAppId()) {
logger.warn("GoogleAppId is null");
return false;
}
if (!this.applicationInfo.hasAppInstanceId()) {
logger.warn("AppInstanceId is null");
return false;
}
if (!this.applicationInfo.hasApplicationProcessState()) {
logger.warn("ApplicationProcessState is null");
return false;
}
if (!this.applicationInfo.hasAndroidAppInfo()) {
return true;
}
if (!this.applicationInfo.getAndroidAppInfo().hasPackageName()) {
logger.warn("AndroidAppInfo.packageName is null");
return false;
}
if (this.applicationInfo.getAndroidAppInfo().hasSdkVersion()) {
return true;
}
logger.warn("AndroidAppInfo.sdkVersion is null");
return false;
}
}

View File

@@ -0,0 +1,17 @@
package com.google.firebase.perf.metrics.validator;
import com.google.firebase.perf.v1.GaugeMetric;
/* loaded from: classes3.dex */
public final class FirebasePerfGaugeMetricValidator extends PerfMetricValidator {
public final GaugeMetric gaugeMetric;
public FirebasePerfGaugeMetricValidator(GaugeMetric gaugeMetric) {
this.gaugeMetric = gaugeMetric;
}
@Override // com.google.firebase.perf.metrics.validator.PerfMetricValidator
public boolean isValidPerfMetric() {
return this.gaugeMetric.hasSessionId() && (this.gaugeMetric.getCpuMetricReadingsCount() > 0 || this.gaugeMetric.getAndroidMemoryReadingsCount() > 0 || (this.gaugeMetric.hasGaugeMetadata() && this.gaugeMetric.getGaugeMetadata().hasMaxAppJavaHeapMemoryKb()));
}
}

View File

@@ -0,0 +1,154 @@
package com.google.firebase.perf.metrics.validator;
import android.content.Context;
import com.google.firebase.perf.logging.AndroidLogger;
import com.google.firebase.perf.util.URLAllowlist;
import com.google.firebase.perf.v1.NetworkRequestMetric;
import java.net.URI;
/* loaded from: classes3.dex */
public final class FirebasePerfNetworkValidator extends PerfMetricValidator {
public static final AndroidLogger logger = AndroidLogger.getInstance();
public final Context appContext;
public final NetworkRequestMetric networkMetric;
public final boolean isValidHttpResponseCode(int i) {
return i > 0;
}
public final boolean isValidPayload(long j) {
return j >= 0;
}
public final boolean isValidPort(int i) {
return i == -1 || i > 0;
}
public final boolean isValidTime(long j) {
return j >= 0;
}
public final boolean isValidUserInfo(String str) {
return str == null;
}
public FirebasePerfNetworkValidator(NetworkRequestMetric networkRequestMetric, Context context) {
this.appContext = context;
this.networkMetric = networkRequestMetric;
}
@Override // com.google.firebase.perf.metrics.validator.PerfMetricValidator
public boolean isValidPerfMetric() {
if (isEmptyUrl(this.networkMetric.getUrl())) {
logger.warn("URL is missing:" + this.networkMetric.getUrl());
return false;
}
URI resultUrl = getResultUrl(this.networkMetric.getUrl());
if (resultUrl == null) {
logger.warn("URL cannot be parsed");
return false;
}
if (!isAllowlisted(resultUrl, this.appContext)) {
logger.warn("URL fails allowlist rule: " + resultUrl);
return false;
}
if (!isValidHost(resultUrl.getHost())) {
logger.warn("URL host is null or invalid");
return false;
}
if (!isValidScheme(resultUrl.getScheme())) {
logger.warn("URL scheme is null or invalid");
return false;
}
if (!isValidUserInfo(resultUrl.getUserInfo())) {
logger.warn("URL user info is null");
return false;
}
if (!isValidPort(resultUrl.getPort())) {
logger.warn("URL port is less than or equal to 0");
return false;
}
if (!isValidHttpMethod(this.networkMetric.hasHttpMethod() ? this.networkMetric.getHttpMethod() : null)) {
logger.warn("HTTP Method is null or invalid: " + this.networkMetric.getHttpMethod());
return false;
}
if (this.networkMetric.hasHttpResponseCode() && !isValidHttpResponseCode(this.networkMetric.getHttpResponseCode())) {
logger.warn("HTTP ResponseCode is a negative value:" + this.networkMetric.getHttpResponseCode());
return false;
}
if (this.networkMetric.hasRequestPayloadBytes() && !isValidPayload(this.networkMetric.getRequestPayloadBytes())) {
logger.warn("Request Payload is a negative value:" + this.networkMetric.getRequestPayloadBytes());
return false;
}
if (this.networkMetric.hasResponsePayloadBytes() && !isValidPayload(this.networkMetric.getResponsePayloadBytes())) {
logger.warn("Response Payload is a negative value:" + this.networkMetric.getResponsePayloadBytes());
return false;
}
if (!this.networkMetric.hasClientStartTimeUs() || this.networkMetric.getClientStartTimeUs() <= 0) {
logger.warn("Start time of the request is null, or zero, or a negative value:" + this.networkMetric.getClientStartTimeUs());
return false;
}
if (this.networkMetric.hasTimeToRequestCompletedUs() && !isValidTime(this.networkMetric.getTimeToRequestCompletedUs())) {
logger.warn("Time to complete the request is a negative value:" + this.networkMetric.getTimeToRequestCompletedUs());
return false;
}
if (this.networkMetric.hasTimeToResponseInitiatedUs() && !isValidTime(this.networkMetric.getTimeToResponseInitiatedUs())) {
logger.warn("Time from the start of the request to the start of the response is null or a negative value:" + this.networkMetric.getTimeToResponseInitiatedUs());
return false;
}
if (!this.networkMetric.hasTimeToResponseCompletedUs() || this.networkMetric.getTimeToResponseCompletedUs() <= 0) {
logger.warn("Time from the start of the request to the end of the response is null, negative or zero:" + this.networkMetric.getTimeToResponseCompletedUs());
return false;
}
if (this.networkMetric.hasHttpResponseCode()) {
return true;
}
logger.warn("Did not receive a HTTP Response Code");
return false;
}
public final boolean isEmptyUrl(String str) {
return isBlank(str);
}
public final URI getResultUrl(String str) {
if (str == null) {
return null;
}
try {
return URI.create(str);
} catch (IllegalArgumentException | IllegalStateException e) {
logger.warn("getResultUrl throws exception %s", e.getMessage());
return null;
}
}
public final boolean isAllowlisted(URI uri, Context context) {
if (uri == null) {
return false;
}
return URLAllowlist.isURLAllowlisted(uri, context);
}
public final boolean isValidHost(String str) {
return (str == null || isBlank(str) || str.length() > 255) ? false : true;
}
public final boolean isValidScheme(String str) {
if (str == null) {
return false;
}
return "http".equalsIgnoreCase(str) || "https".equalsIgnoreCase(str);
}
public boolean isValidHttpMethod(NetworkRequestMetric.HttpMethod httpMethod) {
return (httpMethod == null || httpMethod == NetworkRequestMetric.HttpMethod.HTTP_METHOD_UNKNOWN) ? false : true;
}
public final boolean isBlank(String str) {
if (str == null) {
return true;
}
return str.trim().isEmpty();
}
}

View File

@@ -0,0 +1,161 @@
package com.google.firebase.perf.metrics.validator;
import com.google.firebase.perf.logging.AndroidLogger;
import com.google.firebase.perf.util.Constants$CounterNames;
import com.google.firebase.perf.v1.TraceMetric;
import java.util.Iterator;
import java.util.Map;
/* loaded from: classes3.dex */
public final class FirebasePerfTraceValidator extends PerfMetricValidator {
public static final AndroidLogger logger = AndroidLogger.getInstance();
public final TraceMetric traceMetric;
public final boolean isValidCounterValue(Long l) {
return l != null;
}
public FirebasePerfTraceValidator(TraceMetric traceMetric) {
this.traceMetric = traceMetric;
}
@Override // com.google.firebase.perf.metrics.validator.PerfMetricValidator
public boolean isValidPerfMetric() {
if (!isValidTrace(this.traceMetric, 0)) {
logger.warn("Invalid Trace:" + this.traceMetric.getName());
return false;
}
if (!hasCounters(this.traceMetric) || areCountersValid(this.traceMetric)) {
return true;
}
logger.warn("Invalid Counters for Trace:" + this.traceMetric.getName());
return false;
}
public final boolean hasCounters(TraceMetric traceMetric) {
if (traceMetric.getCountersCount() > 0) {
return true;
}
Iterator it = traceMetric.getSubtracesList().iterator();
while (it.hasNext()) {
if (((TraceMetric) it.next()).getCountersCount() > 0) {
return true;
}
}
return false;
}
public final boolean areCountersValid(TraceMetric traceMetric) {
return areCountersValid(traceMetric, 0);
}
public final boolean areCountersValid(TraceMetric traceMetric, int i) {
if (traceMetric == null) {
return false;
}
if (i > 1) {
logger.warn("Exceed MAX_SUBTRACE_DEEP:1");
return false;
}
for (Map.Entry entry : traceMetric.getCountersMap().entrySet()) {
if (!isValidCounterId((String) entry.getKey())) {
logger.warn("invalid CounterId:" + ((String) entry.getKey()));
return false;
}
if (!isValidCounterValue((Long) entry.getValue())) {
logger.warn("invalid CounterValue:" + entry.getValue());
return false;
}
}
Iterator it = traceMetric.getSubtracesList().iterator();
while (it.hasNext()) {
if (!areCountersValid((TraceMetric) it.next(), i + 1)) {
return false;
}
}
return true;
}
public final boolean isScreenTrace(TraceMetric traceMetric) {
return traceMetric.getName().startsWith("_st_");
}
public final boolean isValidScreenTrace(TraceMetric traceMetric) {
Long l = (Long) traceMetric.getCountersMap().get(Constants$CounterNames.FRAMES_TOTAL.toString());
return l != null && l.compareTo((Long) 0L) > 0;
}
public final boolean isValidTrace(TraceMetric traceMetric, int i) {
if (traceMetric == null) {
logger.warn("TraceMetric is null");
return false;
}
if (i > 1) {
logger.warn("Exceed MAX_SUBTRACE_DEEP:1");
return false;
}
if (!isValidTraceId(traceMetric.getName())) {
logger.warn("invalid TraceId:" + traceMetric.getName());
return false;
}
if (!isValidTraceDuration(traceMetric)) {
logger.warn("invalid TraceDuration:" + traceMetric.getDurationUs());
return false;
}
if (!traceMetric.hasClientStartTimeUs()) {
logger.warn("clientStartTimeUs is null.");
return false;
}
if (isScreenTrace(traceMetric) && !isValidScreenTrace(traceMetric)) {
logger.warn("non-positive totalFrames in screen trace " + traceMetric.getName());
return false;
}
Iterator it = traceMetric.getSubtracesList().iterator();
while (it.hasNext()) {
if (!isValidTrace((TraceMetric) it.next(), i + 1)) {
return false;
}
}
return areAllAttributesValid(traceMetric.getCustomAttributesMap());
}
public final boolean isValidTraceId(String str) {
if (str == null) {
return false;
}
String trim = str.trim();
return !trim.isEmpty() && trim.length() <= 100;
}
public final boolean isValidTraceDuration(TraceMetric traceMetric) {
return traceMetric != null && traceMetric.getDurationUs() > 0;
}
public final boolean isValidCounterId(String str) {
if (str == null) {
return false;
}
String trim = str.trim();
if (trim.isEmpty()) {
logger.warn("counterId is empty");
return false;
}
if (trim.length() <= 100) {
return true;
}
logger.warn("counterId exceeded max length 100");
return false;
}
public final boolean areAllAttributesValid(Map map) {
for (Map.Entry entry : map.entrySet()) {
try {
PerfMetricValidator.validateAttribute((String) entry.getKey(), (String) entry.getValue());
} catch (IllegalArgumentException e) {
logger.warn(e.getLocalizedMessage());
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,105 @@
package com.google.firebase.perf.metrics.validator;
import android.content.Context;
import com.google.firebase.perf.logging.AndroidLogger;
import com.google.firebase.perf.util.Constants$CounterNames;
import com.google.firebase.perf.util.Constants$TraceNames;
import com.google.firebase.perf.v1.PerfMetric;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
/* loaded from: classes3.dex */
public abstract class PerfMetricValidator {
public abstract boolean isValidPerfMetric();
public static List getValidators(PerfMetric perfMetric, Context context) {
ArrayList arrayList = new ArrayList();
if (perfMetric.hasTraceMetric()) {
arrayList.add(new FirebasePerfTraceValidator(perfMetric.getTraceMetric()));
}
if (perfMetric.hasNetworkRequestMetric()) {
arrayList.add(new FirebasePerfNetworkValidator(perfMetric.getNetworkRequestMetric(), context));
}
if (perfMetric.hasApplicationInfo()) {
arrayList.add(new FirebasePerfApplicationInfoValidator(perfMetric.getApplicationInfo()));
}
if (perfMetric.hasGaugeMetric()) {
arrayList.add(new FirebasePerfGaugeMetricValidator(perfMetric.getGaugeMetric()));
}
return arrayList;
}
public static boolean isValid(PerfMetric perfMetric, Context context) {
List validators = getValidators(perfMetric, context);
if (validators.isEmpty()) {
AndroidLogger.getInstance().debug("No validators found for PerfMetric.");
return false;
}
Iterator it = validators.iterator();
while (it.hasNext()) {
if (!((PerfMetricValidator) it.next()).isValidPerfMetric()) {
return false;
}
}
return true;
}
public static String validateTraceName(String str) {
if (str == null) {
return "Trace name must not be null";
}
if (str.length() > 100) {
return String.format(Locale.US, "Trace name must not exceed %d characters", 100);
}
if (!str.startsWith("_")) {
return null;
}
for (Constants$TraceNames constants$TraceNames : Constants$TraceNames.values()) {
if (constants$TraceNames.toString().equals(str)) {
return null;
}
}
if (str.startsWith("_st_")) {
return null;
}
return "Trace name must not start with '_'";
}
public static String validateMetricName(String str) {
if (str == null) {
return "Metric name must not be null";
}
if (str.length() > 100) {
return String.format(Locale.US, "Metric name must not exceed %d characters", 100);
}
if (!str.startsWith("_")) {
return null;
}
for (Constants$CounterNames constants$CounterNames : Constants$CounterNames.values()) {
if (constants$CounterNames.toString().equals(str)) {
return null;
}
}
return "Metric name must not start with '_'";
}
public static void validateAttribute(String str, String str2) {
if (str == null || str.length() == 0) {
throw new IllegalArgumentException("Attribute key must not be null or empty");
}
if (str2 == null || str2.length() == 0) {
throw new IllegalArgumentException("Attribute value must not be null or empty");
}
if (str.length() > 40) {
throw new IllegalArgumentException(String.format(Locale.US, "Attribute key length must not exceed %d characters", 40));
}
if (str2.length() > 100) {
throw new IllegalArgumentException(String.format(Locale.US, "Attribute value length must not exceed %d characters", 100));
}
if (!str.matches("^(?!(firebase_|google_|ga_))[A-Za-z][A-Za-z_0-9]*")) {
throw new IllegalArgumentException("Attribute key must start with letter, must only contain alphanumeric characters and underscore and must not start with \"firebase_\", \"google_\" and \"ga_");
}
}
}