Skip to content

Commit f267395

Browse files
committed
fixing the minor changes
1 parent a98f140 commit f267395

File tree

7 files changed

+550
-112
lines changed

7 files changed

+550
-112
lines changed
Lines changed: 238 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,238 @@
1+
// /**
2+
// * @license
3+
// * Copyright 2025 Google LLC
4+
// *
5+
// * Licensed under the Apache License, Version 2.0 (the "License");
6+
// * you may not use this file except in compliance with the License.
7+
// * You may obtain a copy of the License at
8+
// *
9+
// * http://www.apache.org/licenses/LICENSE-2.0
10+
// *
11+
// * Unless required by applicable law or agreed to in writing, software
12+
// * distributed under the License is distributed on an "AS IS" BASIS,
13+
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
// * See the License for the specific language governing permissions and
15+
// * limitations under the License.
16+
// */
17+
18+
// import { ConfigUpdate, ConfigUpdateObserver, FetchResponse, FirebaseRemoteConfigObject } from '../public_types';
19+
// import { ERROR_FACTORY, ErrorCode } from "../errors";
20+
// import { RestClient } from './rest_client';
21+
// import { Storage } from '../storage/storage';
22+
// import { FirebaseError } from '@firebase/util';
23+
// import { FetchRequest, RemoteConfigAbortSignal } from './remote_config_fetch_client';
24+
25+
// const TEMPLATE_VERSION_KEY = 'latestTemplateVersionNumber';
26+
// const REALTIME_DISABLED_KEY = 'featureDisabled';
27+
// const MAXIMUM_FETCH_ATTEMPTS = 3;
28+
29+
// export class ConfigAutoFetch {
30+
// private readonly decoder = new TextDecoder('utf-8');
31+
32+
// constructor(
33+
// private readonly reader: ReadableStreamDefaultReader<Uint8Array>,
34+
// private readonly restClient: RestClient,
35+
// private readonly observers: Set<ConfigUpdateObserver>,
36+
// private readonly storage: Storage,
37+
// private readonly retryCallback: ConfigUpdateObserver
38+
// ) { }
39+
40+
// private executeAllListenerCallbacks(configUpdate: ConfigUpdate): void {
41+
// this.observers.forEach(observer => observer.next(configUpdate));
42+
// }
43+
44+
// private getChangedParams( newConfig: FirebaseRemoteConfigObject, oldConfig: FirebaseRemoteConfigObject ): Set<string> {
45+
// const changed = new Set<string>();
46+
// const newKeys = new Set(Object.keys(newConfig || {}));
47+
// const oldKeys = new Set(Object.keys(oldConfig || {}));
48+
49+
// for (const key of newKeys) {
50+
// if (!oldKeys.has(key)) {
51+
// changed.add(key);
52+
// continue;
53+
// }
54+
// if (JSON.stringify((newConfig as any)[key]) !== JSON.stringify((oldConfig as any)[key])) {
55+
// changed.add(key);
56+
// continue;
57+
// }
58+
// }
59+
60+
// for (const key of oldKeys) {
61+
// if (!newKeys.has(key)) {
62+
// changed.add(key);
63+
// }
64+
// }
65+
66+
// return changed;
67+
// }
68+
69+
// private fetchResponseIsUpToDate(fetchResponse: FetchResponse, lastKnownVersion: number): boolean {
70+
// if (fetchResponse.config != null) {
71+
// return fetchResponse.templateVersionNumber >= lastKnownVersion;
72+
// }
73+
// return false;
74+
// }
75+
76+
// private async fetchLatestConfig(remainingAttempts: number, targetVersion: number): Promise<void> {
77+
// const remainingAttemptsAfterFetch = remainingAttempts - 1;
78+
// const currentAttempt = MAXIMUM_FETCH_ATTEMPTS - remainingAttemptsAfterFetch;
79+
// //type fetchtype=FetchType.REALTIME
80+
// try {
81+
// const fetchRequest: FetchRequest = {
82+
// cacheMaxAgeMillis: 0,
83+
// signal: new RemoteConfigAbortSignal(),
84+
// //fetchType: 'REALTIME',
85+
// //fetchAttempt: currentAttempt
86+
// };
87+
88+
// const fetchResponse: FetchResponse = await this.restClient.fetch(fetchRequest);
89+
// const activatedConfigs = await this.storage.getActiveConfig();
90+
91+
// if (!this.fetchResponseIsUpToDate(fetchResponse, targetVersion)) {
92+
// console.log("Fetched template version is the same as SDK's current version." + " Retrying fetch.");
93+
// await this.autoFetch(remainingAttemptsAfterFetch, targetVersion);
94+
// return;
95+
// }
96+
97+
// if (fetchResponse.config == null) {
98+
// console.log("The fetch succeeded, but the backend had no updates.");
99+
// return;
100+
// }
101+
102+
// if (activatedConfigs == null) {
103+
// //what to do over here?
104+
// }
105+
106+
// const updatedKeys = this.getChangedParams(fetchResponse.config, activatedConfigs);
107+
108+
// if (updatedKeys.size === 0) {
109+
// console.log("Config was fetched, but no params changed.");
110+
// return;
111+
// }
112+
113+
// const configUpdate: ConfigUpdate = {
114+
// getUpdatedKeys(): Set<string> {
115+
// return new Set(updatedKeys);
116+
// }
117+
// };
118+
119+
// this.executeAllListenerCallbacks(configUpdate);
120+
121+
// } catch (e: unknown) {
122+
// const errorMessage = e instanceof Error ? e.message : String(e);
123+
// const error = ERROR_FACTORY.create(
124+
// ErrorCode.CONFIG_UPDATE_NOT_FETCHED,
125+
// { originalErrorMessage: `Failed to auto-fetch config update: ${errorMessage}` }
126+
// );
127+
// this.retryCallback.error?.(error);
128+
// }
129+
// }
130+
131+
// private getRandomInt(max: number): number {
132+
// return Math.floor(Math.random() * max);
133+
// }
134+
135+
// private async autoFetch(remainingAttempts: number, targetVersion: number): Promise<void> {
136+
// if (remainingAttempts === 0) {
137+
// const error = ERROR_FACTORY.create(
138+
// ErrorCode.CONFIG_UPDATE_NOT_FETCHED,
139+
// { originalErrorMessage: 'Unable to fetch the latest version of the template.' }
140+
// );
141+
// this.retryCallback.error?.(error);
142+
// return;
143+
// }
144+
145+
// const timeTillFetch = this.getRandomInt(4);
146+
// setTimeout(async () => {
147+
// await this.fetchLatestConfig(remainingAttempts, targetVersion);
148+
// }, timeTillFetch);
149+
// }
150+
151+
// private parseAndValidateConfigUpdateMessage(message: string): string {
152+
// const left = message.indexOf('{');
153+
// const right = message.indexOf('}', left);
154+
155+
// if (left < 0 || right < 0) {
156+
// return "";
157+
// }
158+
// return left >= right ? "" : message.substring(left, right + 1);
159+
// }
160+
161+
// private isEventListenersEmpty(): boolean {
162+
// return this.observers.size === 0;
163+
// }
164+
165+
// private propagateError = (e: FirebaseError) => this.observers.forEach(o => o.error?.(e));
166+
167+
// private async handleNotifications(): Promise<void> {
168+
// let partialConfigUpdateMessage: string;
169+
// let currentConfigUpdateMessage = "";
170+
171+
// try {
172+
// while (true) {
173+
// const { done, value } = await this.reader.read();
174+
// if (done) {
175+
// break;
176+
// }
177+
178+
// partialConfigUpdateMessage = this.decoder.decode(value, { stream: true });
179+
// currentConfigUpdateMessage += partialConfigUpdateMessage;
180+
181+
// if (partialConfigUpdateMessage.includes('}')) {
182+
// currentConfigUpdateMessage = this.parseAndValidateConfigUpdateMessage(currentConfigUpdateMessage);
183+
184+
// if (currentConfigUpdateMessage.length === 0) {
185+
// continue;
186+
// }
187+
// try {
188+
// const jsonObject = JSON.parse(currentConfigUpdateMessage);
189+
190+
// if (REALTIME_DISABLED_KEY in jsonObject) {
191+
// const errorMessage = "The server is temporarily unavailable. Try again in a few minutes.";
192+
// const error = ERROR_FACTORY.create(ErrorCode.CONFIG_UPDATE_UNAVAILABLE, { originalErrorMessage: errorMessage });
193+
// this.retryCallback.error?.(error);
194+
// break;
195+
// }
196+
197+
// if (this.isEventListenersEmpty()) {
198+
// break;
199+
// }
200+
201+
// if (TEMPLATE_VERSION_KEY in jsonObject) {
202+
// const oldTemplateVersion = await this.storage.getLastKnownTemplateVersion();
203+
// let targetTemplateVersion = Number(jsonObject[TEMPLATE_VERSION_KEY]);
204+
205+
// if (targetTemplateVersion > oldTemplateVersion) {
206+
// //await this.storage.setLastKnownTemplateVersion(targetVersion);
207+
// await this.autoFetch(MAXIMUM_FETCH_ATTEMPTS, targetTemplateVersion);
208+
// }
209+
// }
210+
// } catch (e: any) {
211+
// console.error("Realtime: Unable to parse config update message.", e);
212+
// this.propagateError(ERROR_FACTORY.create(ErrorCode.CONFIG_UPDATE_MESSAGE_INVALID, {
213+
// originalErrorMessage: e.message
214+
// }));
215+
// }
216+
// currentConfigUpdateMessage = "";
217+
// }
218+
// }
219+
// } catch (e: unknown) {
220+
// if (e instanceof Error) {
221+
// if (e.name !== 'AbortError') {
222+
// const firebaseError = ERROR_FACTORY.create(ErrorCode.CONFIG_UPDATE_STREAM_ERROR, {
223+
// originalErrorMessage: `Error reading real-time stream: ${e.message}`
224+
// });
225+
// this.retryCallback.error?.(firebaseError);
226+
// }
227+
// }
228+
// }
229+
// }
230+
231+
// public async listenForNotifications(): Promise<void> {
232+
// if (!this.reader) {
233+
// return;
234+
// }
235+
// await this.handleNotifications();
236+
// }
237+
238+
// }

0 commit comments

Comments
 (0)