Skip to content

Add initializeAnalytics() to analytics-exp #4575

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jun 14, 2021
Merged

Conversation

hsubox76
Copy link
Contributor

@hsubox76 hsubox76 commented Mar 2, 2021

Create an initializeAnalytics() method that can only be called once, which can take an AnalyticsOptions object with an initial config. Allows users to set useful custom gtag config parameters such as send_page_view on initialization of analytics.

Updated some documentation comments.

Design doc (internal link):
go/firebase-analytics-initial-config

@changeset-bot
Copy link

changeset-bot bot commented Mar 2, 2021

⚠️ No Changeset found

Latest commit: aa563ba

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@google-oss-bot
Copy link
Contributor

google-oss-bot commented Mar 2, 2021

Binary Size Report

Affected SDKs

No changes between base commit (4bdc9f3) and head commit (fc48310).

Test Logs

@google-oss-bot
Copy link
Contributor

google-oss-bot commented Mar 2, 2021

Size Analysis Report

Affected Products

  • @firebase/analytics-exp

    • getAnalytics

      Size Table

      TypeBase (4bdc9f3)Head (fc48310)Diff
      size
      9.10 kB
      9.58 kB
      +477 B (+5.2%)
      size-with-ext-deps
      27.8 kB
      28.2 kB
      +480 B (+1.7%)

      Dependency Table

      TypeBase (4bdc9f3)Head (fc48310)Diff
      functions

      22 dependencies

      attemptFetchDynamicConfigWithRetry
      factory
      fetchDynamicConfig
      fetchDynamicConfigWithRetry
      findGtagScriptOnPage
      getAnalytics
      getHeaders
      getOrCreateDataLayer
      gtagOnConfig
      gtagOnEvent
      initializeAnalytics
      insertScriptTag
      isRetriableError
      logEvent
      logEvent$1
      promiseAllSettled
      registerAnalytics
      setAbortableTimeout
      validateIndexedDB
      warnOnBrowserContextMismatch
      wrapGtag
      wrapOrCreateGtag
      

      23 dependencies

      attemptFetchDynamicConfigWithRetry
      factory
      fetchDynamicConfig
      fetchDynamicConfigWithRetry
      findGtagScriptOnPage
      getAnalytics
      getHeaders
      getOrCreateDataLayer
      gtagOnConfig
      gtagOnEvent
      initializeAnalytics
      initializeAnalytics$1
      insertScriptTag
      isRetriableError
      logEvent
      logEvent$1
      promiseAllSettled
      registerAnalytics
      setAbortableTimeout
      validateIndexedDB
      warnOnBrowserContextMismatch
      wrapGtag
      wrapOrCreateGtag
      

      + initializeAnalytics$1

    • initializeAnalytics

      Size Table

      TypeBase (4bdc9f3)Head (fc48310)Diff
      size
      ?
      9.47 kB
      ? (?)
      size-with-ext-deps
      ?
      27.5 kB
      ? (?)

      Dependency Table

      TypeBase (4bdc9f3)Head (fc48310)Diff
      functions
      ?

      21 dependencies

      attemptFetchDynamicConfigWithRetry
      factory
      fetchDynamicConfig
      fetchDynamicConfigWithRetry
      findGtagScriptOnPage
      getHeaders
      getOrCreateDataLayer
      gtagOnConfig
      gtagOnEvent
      initializeAnalytics
      insertScriptTag
      isRetriableError
      logEvent
      logEvent$1
      promiseAllSettled
      registerAnalytics
      setAbortableTimeout
      validateIndexedDB
      warnOnBrowserContextMismatch
      wrapGtag
      wrapOrCreateGtag
      

      ?
      classes
      ?

      AnalyticsAbortSignal
      AnalyticsService
      RetryData
      

      ?
      variables
      ?

      22 dependencies

      ANALYTICS_TYPE
      BASE_INTERVAL_MILLIS
      DYNAMIC_CONFIG_URL
      ERRORS
      ERROR_FACTORY
      FETCH_TIMEOUT_MILLIS
      GA_FID_KEY
      GTAG_URL
      LONG_RETRY_FACTOR
      ORIGIN_KEY
      dataLayerName
      defaultRetryData
      dynamicConfigPromisesList
      globalInitDone
      gtagCoreFunction
      gtagName
      initializationPromisesMap
      logger
      measurementIdToAppId
      name
      version
      wrappedGtagFunction
      

      ?
      enums
      ?
      ?

      External Dependency Table

      ModuleBase (4bdc9f3)Head (fc48310)Diff
      @firebase/app-exp
      ?

      _getProvider
      _registerComponent
      registerVersion
      

      ?
      @firebase/logger
      ?

      Logger
      

      ?
      @firebase/util
      ?

      ErrorFactory
      FirebaseError
      areCookiesEnabled
      calculateBackoffMillis
      getModularInstance
      isBrowserExtension
      isIndexedDBAvailable
      validateIndexedDBOpenable
      

      ?
      @firebase/component
      ?

      Component
      

      ?
    • isSupported

      Size Table

      TypeBase (4bdc9f3)Head (fc48310)Diff
      size
      9.13 kB
      9.45 kB
      +314 B (+3.4%)
      size-with-ext-deps
      27.2 kB
      27.5 kB
      +314 B (+1.2%)
    • logEvent

      Size Table

      TypeBase (4bdc9f3)Head (fc48310)Diff
      size
      8.99 kB
      9.30 kB
      +314 B (+3.5%)
      size-with-ext-deps
      27.1 kB
      27.4 kB
      +314 B (+1.2%)
    • setAnalyticsCollectionEnabled

      Size Table

      TypeBase (4bdc9f3)Head (fc48310)Diff
      size
      9.15 kB
      9.47 kB
      +314 B (+3.4%)
      size-with-ext-deps
      27.2 kB
      27.5 kB
      +314 B (+1.2%)
    • setCurrentScreen

      Size Table

      TypeBase (4bdc9f3)Head (fc48310)Diff
      size
      9.24 kB
      9.55 kB
      +314 B (+3.4%)
      size-with-ext-deps
      27.3 kB
      27.6 kB
      +314 B (+1.2%)
    • setUserId

      Size Table

      TypeBase (4bdc9f3)Head (fc48310)Diff
      size
      9.22 kB
      9.54 kB
      +314 B (+3.4%)
      size-with-ext-deps
      27.3 kB
      27.6 kB
      +314 B (+1.2%)
    • setUserProperties

      Size Table

      TypeBase (4bdc9f3)Head (fc48310)Diff
      size
      9.30 kB
      9.61 kB
      +314 B (+3.4%)
      size-with-ext-deps
      27.4 kB
      27.7 kB
      +314 B (+1.1%)
    • settings

      Size Table

      TypeBase (4bdc9f3)Head (fc48310)Diff
      size
      9.12 kB
      9.43 kB
      +314 B (+3.4%)
      size-with-ext-deps
      27.2 kB
      27.5 kB
      +314 B (+1.2%)

// Async but non-blocking.
// This map reflects the completion state of all promises for each appId.
initializationPromisesMap[appId] = initializeAnalytics(
// Factory will have thrown if options has no appId.
initializationPromisesMap[app.options.appId!] = _initializeAnalytics(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After giving it some thought, I realize we can't do initialization outside the factory, otherwise FCM, which depends on Analytics, might try to use an uninitialized Analytics service, as shown in the below example:

import { initializeApp } from 'firebase/app';
import { getMessaging, onMessage } from 'firebase/messaging';
import { getAnalytics } from 'firebase/analytics';

const app = initializeApp({...});

/**
 * Messaging calls `const analytics = await messaging.firebaseDependencies.analyticsProvider.get();` 
 * which will create and return an uninitialized Analytics service.
 * And it will probably throw when calling `analytics.logEvent(...)`
 */
const msg = getMessaging(app);
onMessage(msg, () => { 
    // process messages
});

// getAnalytics async after a timeout
setTimeout(() => getAnalytics(), 1000);

We should let analytics initialize with the default options in this situation.
To support this, some changes to the component framework need to be made, e.g. allow it to take an option and pass it to the factory.

I need to think more about it and let's chat offline. This PR will need to be put on hold for now, Sorry!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#4595 is merged. We can use Provider.initialize() to initialize Auth in the factory function.

@@ -121,12 +123,13 @@ export async function initializeAnalytics(
// We keep it together with other initialization logic for better code structure.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(gtagCore as any)('js', new Date());
// User config added first. We don't want users to accidentally overwrite
// base Firebase config properties.
const configProperties: Record<string, unknown> = options?.config ?? {};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice! a lot of ?s

resource.name.includes('en=login')
);
if (callsWithEvent.length === 0) {
return checkForEventCalls();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should add a limit on the number of retries, otherwise it may run forever.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought the karma timeout will catch it but I added a timeout and extracted the function, which helped me realize the second test was not correct (performance entries were not cleared from the browser between tests), so I fixed it.

@Feiyang1 Feiyang1 assigned hsubox76 and unassigned Feiyang1 May 14, 2021
@hsubox76 hsubox76 force-pushed the ch-init-analytics branch from ae97224 to aa563ba Compare May 20, 2021 22:10
@hsubox76 hsubox76 assigned Feiyang1 and unassigned hsubox76 Jun 2, 2021
@Feiyang1 Feiyang1 assigned hsubox76 and unassigned Feiyang1 Jun 3, 2021
@hsubox76 hsubox76 merged commit 8250047 into master Jun 14, 2021
@hsubox76 hsubox76 deleted the ch-init-analytics branch June 14, 2021 19:46
@firebase firebase locked and limited conversation to collaborators Jul 15, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants