Skip to content
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

feat(rc): Add custom signals support #8602

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add support to set/update custom signals
- Also takes care of setting the signals in the fetch request
  • Loading branch information
ashish-kothari committed Oct 25, 2024
commit 4cfd43b7f658cae9042ab6190a23d24d02b3f5dc
10 changes: 10 additions & 0 deletions common/api-review/remote-config.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ import { FirebaseApp } from '@firebase/app';
// @public
export function activate(remoteConfig: RemoteConfig): Promise<boolean>;

// @alpha
export type CustomSignals = {
[key: string]: string | number;
};

// @public
export function ensureInitialized(remoteConfig: RemoteConfig): Promise<void>;

Expand Down Expand Up @@ -62,6 +67,11 @@ export interface RemoteConfigSettings {
minimumFetchIntervalMillis: number;
}

// Warning: (ae-incompatible-release-tags) The symbol "setCustomSignals" is marked as @public, but its signature references "CustomSignals" which is marked as @alpha
//
// @public (undocumented)
export function setCustomSignals(remoteConfig: RemoteConfig, customSignals: CustomSignals): Promise<void>;

// @public
export function setLogLevel(remoteConfig: RemoteConfig, logLevel: LogLevel): void;

Expand Down
14 changes: 14 additions & 0 deletions packages/remote-config-types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,20 @@ export type FetchStatus = 'no-fetch-yet' | 'success' | 'failure' | 'throttle';
*/
export type LogLevel = 'debug' | 'error' | 'silent';

/**
* Defines the type for representing custom signals and their values.
*
* <p>The values in CustomSignals must be one of the following types:
*
* <ul>
* <li><code>string</code>
* <li><code>number</code>
* </ul>
*
* @alpha
*/
export type CustomSignals = {[key: string]: string | number};

declare module '@firebase/component' {
interface NameServiceMapping {
'remoteConfig-compat': RemoteConfig;
Expand Down
11 changes: 10 additions & 1 deletion packages/remote-config/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import { _getProvider, FirebaseApp, getApp } from '@firebase/app';
import {
CustomSignals,
LogLevel as RemoteConfigLogLevel,
RemoteConfig,
Value
Expand Down Expand Up @@ -108,6 +109,7 @@ export async function fetchConfig(remoteConfig: RemoteConfig): Promise<void> {
// * it applies to all retries (like curl's max-time arg)
// * it is consistent with the Fetch API's signal input
const abortSignal = new RemoteConfigAbortSignal();
const customSignals = rc._storageCache.getCustomSignals();

setTimeout(async () => {
// Note a very low delay, eg < 10ms, can elapse before listeners are initialized.
Expand All @@ -118,7 +120,8 @@ export async function fetchConfig(remoteConfig: RemoteConfig): Promise<void> {
try {
await rc._client.fetch({
cacheMaxAgeMillis: rc.settings.minimumFetchIntervalMillis,
signal: abortSignal
signal: abortSignal,
customSignals: rc._storageCache.getCustomSignals()
});

await rc._storageCache.setLastFetchStatus('success');
Expand Down Expand Up @@ -258,3 +261,9 @@ export function setLogLevel(
function getAllKeys(obj1: {} = {}, obj2: {} = {}): string[] {
return Object.keys({ ...obj1, ...obj2 });
}

export async function setCustomSignals(
remoteConfig: RemoteConfig, customSignals: CustomSignals): Promise<void> {
const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;
return rc._storageCache.setCustomSignals(customSignals);
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
* limitations under the License.
*/

import { CustomSignals } from "../public_types";

/**
* Defines a client, as in https://en.wikipedia.org/wiki/Client%E2%80%93server_model, for the
* Remote Config server (https://firebase.google.com/docs/reference/remote-config/rest).
Expand Down Expand Up @@ -99,6 +101,13 @@ export interface FetchRequest {
* <p>Comparable to passing `headers = { 'If-None-Match': <eTag> }` to the native Fetch API.
*/
eTag?: string;


/** The custom signals stored for the app instance.
*
* <p>Optional in case no custom signals are set for the instance.
*/
customSignals?: CustomSignals;
}

/**
Expand Down
5 changes: 4 additions & 1 deletion packages/remote-config/src/client/rest_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* limitations under the License.
*/

import { CustomSignals } from '../public_types';
import {
FetchResponse,
RemoteConfigFetchClient,
Expand All @@ -41,6 +42,7 @@ interface FetchRequestBody {
app_instance_id_token: string;
app_id: string;
language_code: string;
custom_signals?: CustomSignals;
/* eslint-enable camelcase */
}

Expand Down Expand Up @@ -92,7 +94,8 @@ export class RestClient implements RemoteConfigFetchClient {
app_instance_id: installationId,
app_instance_id_token: installationToken,
app_id: this.appId,
language_code: getUserLanguage()
language_code: getUserLanguage(),
custom_signals: request.customSignals
/* eslint-enable camelcase */
};

Expand Down
14 changes: 14 additions & 0 deletions packages/remote-config/src/public_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,20 @@ export type FetchStatus = 'no-fetch-yet' | 'success' | 'failure' | 'throttle';
*/
export type LogLevel = 'debug' | 'error' | 'silent';

/**
* Defines the type for representing custom signals and their values.
*
* <p>The values in CustomSignals must be one of the following types:
*
* <ul>
* <li><code>string</code>
* <li><code>number</code>
* </ul>
*
* @alpha
*/
export type CustomSignals = {[key: string]: string | number};

declare module '@firebase/component' {
interface NameServiceMapping {
'remote-config': RemoteConfig;
Expand Down
52 changes: 50 additions & 2 deletions packages/remote-config/src/storage/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* limitations under the License.
*/

import { FetchStatus } from '@firebase/remote-config-types';
import { FetchStatus, CustomSignals } from '@firebase/remote-config-types';
import {
FetchResponse,
FirebaseRemoteConfigObject
Expand Down Expand Up @@ -70,7 +70,8 @@ type ProjectNamespaceKeyFieldValue =
| 'last_successful_fetch_timestamp_millis'
| 'last_successful_fetch_response'
| 'settings'
| 'throttle_metadata';
| 'throttle_metadata'
| 'custom_signals';

// Visible for testing.
export function openDatabase(): Promise<IDBDatabase> {
Expand Down Expand Up @@ -181,6 +182,53 @@ export class Storage {
return this.delete('throttle_metadata');
}

getCustomSignals(): Promise<CustomSignals | undefined> {
return this.get<CustomSignals>('custom_signals');
}

async setCustomSignals(customSignals: CustomSignals): Promise<void> {
const db = await this.openDbPromise;
return new Promise((resolve, reject) => {
const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');
const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);
const compositeKey = this.createCompositeKey("custom_signals");
try {
const storedSignalsRequest = objectStore.get(compositeKey);
storedSignalsRequest.onerror = event => {
reject(toFirebaseError(event, ErrorCode.STORAGE_GET));
};
storedSignalsRequest.onsuccess = event => {
const storedSignals = (event.target as IDBRequest).result.value;
const combinedSignals = {
...storedSignals,
...customSignals
};
const signalsToUpdate = Object.fromEntries(Object.entries(combinedSignals).filter(([_, v]) => v !== null));
if (signalsToUpdate) {
const setSignalsRequest = objectStore.put({compositeKey, signalsToUpdate});
setSignalsRequest.onerror = event => {
reject(toFirebaseError(event, ErrorCode.STORAGE_SET));
};
setSignalsRequest.onsuccess = event => {
const result = (event.target as IDBRequest).result;
if (result) {
resolve(result.value);
} else {
resolve(undefined);
}
};
}
};
} catch (e) {
reject(
ERROR_FACTORY.create(ErrorCode.STORAGE_SET, {
originalErrorMessage: (e as Error)?.message
})
);
}
});
}

async get<T>(key: ProjectNamespaceKeyFieldValue): Promise<T | undefined> {
const db = await this.openDbPromise;
return new Promise((resolve, reject) => {
Expand Down
20 changes: 19 additions & 1 deletion packages/remote-config/src/storage/storage_cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* limitations under the License.
*/

import { FetchStatus } from '@firebase/remote-config-types';
import { FetchStatus, CustomSignals } from '@firebase/remote-config-types';
import { FirebaseRemoteConfigObject } from '../client/remote_config_fetch_client';
import { Storage } from './storage';

Expand All @@ -31,6 +31,8 @@ export class StorageCache {
private lastFetchStatus?: FetchStatus;
private lastSuccessfulFetchTimestampMillis?: number;
private activeConfig?: FirebaseRemoteConfigObject;
private customSignals?: CustomSignals;


/**
* Memory-only getters
Expand All @@ -47,6 +49,11 @@ export class StorageCache {
return this.activeConfig;
}

getCustomSignals(): CustomSignals | undefined {
return this.customSignals;
}


/**
* Read-ahead getter
*/
Expand All @@ -55,6 +62,7 @@ export class StorageCache {
const lastSuccessfulFetchTimestampMillisPromise =
this.storage.getLastSuccessfulFetchTimestampMillis();
const activeConfigPromise = this.storage.getActiveConfig();
const customSignalsPromise = this.storage.getCustomSignals();

// Note:
// 1. we consistently check for undefined to avoid clobbering defined values
Expand All @@ -78,6 +86,11 @@ export class StorageCache {
if (activeConfig) {
this.activeConfig = activeConfig;
}

const customSignals = await customSignalsPromise;
if (customSignals) {
this.customSignals = customSignals;
}
}

/**
Expand All @@ -99,4 +112,9 @@ export class StorageCache {
this.activeConfig = activeConfig;
return this.storage.setActiveConfig(activeConfig);
}

setCustomSignals(customSignals: CustomSignals): Promise<void> {
this.customSignals = customSignals;
return this.storage.setCustomSignals(customSignals);
}
}