jawaduddin commited on
Commit
79b79ac
·
1 Parent(s): 0bbc893

Fix: Robust idempotent Firebase initialization

Browse files
Files changed (1) hide show
  1. backend/utils/firebase_db.py +28 -12
backend/utils/firebase_db.py CHANGED
@@ -31,12 +31,13 @@ class FirebaseManager:
31
  def connect(self):
32
  """Establish connection to Firebase Firestore"""
33
  try:
34
- # Check if Firebase app is already initialized
35
- if firebase_admin._apps:
36
  self.app = firebase_admin.get_app()
37
  logger.info("Using existing Firebase app")
38
- else:
39
- # Initialize Firebase with service account
 
40
  # Debug logging to see what's actually available
41
  env_keys = [k for k in os.environ.keys() if k.startswith('FIREBASE_')]
42
  logger.info(f"Available FIREBASE env vars: {env_keys}")
@@ -98,10 +99,16 @@ class FirebaseManager:
98
  if cred_dict:
99
  try:
100
  cred = credentials.Certificate(cred_dict)
101
- self.app = firebase_admin.initialize_app(cred)
102
- logger.info("Initialized new Firebase app")
 
 
 
 
 
103
  except Exception as e:
104
  logger.error(f"Failed to initialize Firebase app with credentials: {e}")
 
105
  else:
106
  # Load from file (local development)
107
  cred_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), self.credentials_path)
@@ -111,13 +118,17 @@ class FirebaseManager:
111
  return False
112
 
113
  cred = credentials.Certificate(cred_path)
114
- logger.info(f"Loaded Firebase credentials from file: {self.credentials_path}")
 
 
 
 
 
115
 
116
- self.app = firebase_admin.initialize_app(cred)
117
- logger.info("Initialized new Firebase app")
118
-
119
- # Get Firestore client
120
- self.db = firestore.client()
121
 
122
  # Test connection by attempting to read from a collection
123
  # This will create the collection if it doesn't exist
@@ -131,6 +142,11 @@ class FirebaseManager:
131
  logger.warning(f"Failed to connect to Firebase: {str(e)}")
132
  logger.warning("Server will continue without database connection")
133
  return False
 
 
 
 
 
134
 
135
  # ============ USER MANAGEMENT METHODS ============
136
 
 
31
  def connect(self):
32
  """Establish connection to Firebase Firestore"""
33
  try:
34
+ # Robust initialization pattern: Try to get app, if fails, initialize it.
35
+ try:
36
  self.app = firebase_admin.get_app()
37
  logger.info("Using existing Firebase app")
38
+ except ValueError:
39
+ # App not returned by get_app(), try to initialize
40
+
41
  # Debug logging to see what's actually available
42
  env_keys = [k for k in os.environ.keys() if k.startswith('FIREBASE_')]
43
  logger.info(f"Available FIREBASE env vars: {env_keys}")
 
99
  if cred_dict:
100
  try:
101
  cred = credentials.Certificate(cred_dict)
102
+ # Try to initialize, but handle race conditions where it might have just been created
103
+ try:
104
+ self.app = firebase_admin.initialize_app(cred)
105
+ logger.info("Initialized new Firebase app")
106
+ except ValueError:
107
+ self.app = firebase_admin.get_app()
108
+ logger.info("Using existing Firebase app (caught race condition)")
109
  except Exception as e:
110
  logger.error(f"Failed to initialize Firebase app with credentials: {e}")
111
+ return False
112
  else:
113
  # Load from file (local development)
114
  cred_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), self.credentials_path)
 
118
  return False
119
 
120
  cred = credentials.Certificate(cred_path)
121
+ try:
122
+ self.app = firebase_admin.initialize_app(cred)
123
+ logger.info(f"Loaded Firebase credentials from file: {self.credentials_path}")
124
+ except ValueError:
125
+ self.app = firebase_admin.get_app()
126
+ logger.info("Using existing Firebase app (local)")
127
 
128
+ # Get Firestore client explicitly using the app we have
129
+ logger.info("Getting Firestore client...")
130
+ self.db = firestore.client(app=self.app)
131
+ logger.info("Firestore client created")
 
132
 
133
  # Test connection by attempting to read from a collection
134
  # This will create the collection if it doesn't exist
 
142
  logger.warning(f"Failed to connect to Firebase: {str(e)}")
143
  logger.warning("Server will continue without database connection")
144
  return False
145
+
146
+ except Exception as e:
147
+ logger.warning(f"Failed to connect to Firebase: {str(e)}")
148
+ logger.warning("Server will continue without database connection")
149
+ return False
150
 
151
  # ============ USER MANAGEMENT METHODS ============
152