-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathemulator.dart
More file actions
349 lines (300 loc) · 11 KB
/
emulator.dart
File metadata and controls
349 lines (300 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
/// Helper for managing Firebase Functions Emulator lifecycle in tests.
class EmulatorHelper {
EmulatorHelper({
required this.projectPath,
this.functionsPort = 5001,
this.pubsubPort = 8085,
this.firestorePort = 8080,
this.databasePort = 9000,
this.authPort = 9099,
this.storagePort = 9199,
this.startupTimeout = const Duration(seconds: 90),
});
Process? _process;
final String projectPath;
final int functionsPort;
final int pubsubPort;
final int firestorePort;
final int databasePort;
final int authPort;
final int storagePort;
final Duration startupTimeout;
// Completer to signal when emulator is ready
Completer<void>? _readyCompleter;
// Buffer to store emulator output for verification
final List<String> _outputLines = [];
final List<String> _errorLines = [];
/// Starts the Firebase emulator and waits for it to be ready.
Future<void> start() async {
print('Starting Firebase emulator...');
// Check if firebase CLI is available
final firebaseCmd = await _findFirebaseCli();
if (firebaseCmd == null) {
throw Exception(
'Firebase CLI not found. Please install: npm install -g firebase-tools',
);
}
print('Using Firebase CLI: $firebaseCmd');
// Parse command into executable and base arguments
final cmdParts = firebaseCmd.split(' ');
final executable = cmdParts.first;
final baseArgs = cmdParts.skip(1).toList();
// Start the emulator with debug logging
_process = await Process.start(
executable,
[
...baseArgs,
'emulators:start',
'--only',
'functions,pubsub,firestore,database,auth,storage',
'--project',
'demo-test',
'--non-interactive',
],
workingDirectory: projectPath,
environment: {
'FIREBASE_EMULATOR_HUB': 'true',
'FIREBASE_CLI_EXPERIMENTS': 'dartfunctions',
...Platform.environment,
},
);
// Create completer to signal readiness
_readyCompleter = Completer<void>();
// Capture output for debugging and detect readiness
_process!.stdout.transform(utf8.decoder).transform(const LineSplitter()).listen((
line,
) {
print('[EMULATOR] $line');
_outputLines.add(line);
// Detect when emulator is ready
// We need to wait for functions to be initialized, not just the emulator hub
// Look for "http function initialized" which indicates triggers are registered
if (line.contains('http function initialized') ||
line.contains('All emulators ready') ||
line.contains('All emulators started') ||
line.contains('It is now safe to connect')) {
if (!_readyCompleter!.isCompleted) {
_readyCompleter!.complete();
}
}
});
_process!.stderr
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen((line) {
print('[EMULATOR ERROR] $line');
_errorLines.add(line);
});
// Wait for emulator to be ready
try {
print('Waiting for emulator to be ready...');
await _waitForReady();
// Additional wait to ensure Dart runtime is fully initialized
// The first request triggers Dart process startup which takes ~2-3 seconds
print('Waiting for Dart runtime to stabilize...');
await Future<void>.delayed(const Duration(seconds: 2));
print('✓ Emulator is ready');
} catch (e) {
print('Error starting emulator: $e');
await stop();
rethrow;
}
}
/// Stops the Firebase emulator.
Future<void> stop() async {
if (_process == null) return;
print('Stopping Firebase emulator...');
// Try graceful shutdown first
_process!.kill();
// Wait a bit for graceful shutdown
await Future<void>.delayed(const Duration(seconds: 2));
// Force kill if still running
if (!_process!.kill(ProcessSignal.sigkill)) {
print('Warning: Could not kill emulator process');
}
_process = null;
print('✓ Emulator stopped');
}
/// Waits for the emulator to be ready by monitoring stdout and polling the hub.
Future<void> _waitForReady() async {
final client = HttpClient();
final deadline = DateTime.now().add(startupTimeout);
while (DateTime.now().isBefore(deadline)) {
// Check if ready message was received
if (_readyCompleter!.isCompleted) {
client.close();
return;
}
// Poll the hello-world function endpoint as a fallback
// We poll a specific function to ensure triggers are registered, not just the server
try {
final request = await client
.getUrl(
Uri.parse(
'http://127.0.0.1:$functionsPort/demo-test/us-central1/hello-world',
),
)
.timeout(const Duration(seconds: 5));
final response = await request.close().timeout(
const Duration(seconds: 5),
);
await response.drain<void>();
// Only consider ready if we get 200 (not 404 which means function not registered)
if (response.statusCode == 200) {
print('Function hello-world responding on port $functionsPort');
client.close();
if (!_readyCompleter!.isCompleted) {
_readyCompleter!.complete();
}
return;
} else if (response.statusCode == 404) {
// Function not registered yet, keep waiting
print('Waiting for functions to be registered (got 404)...');
}
} catch (e) {
// Connection failed, emulator not ready yet
}
await Future<void>.delayed(const Duration(seconds: 1));
}
client.close();
throw TimeoutException(
'Emulator did not start within ${startupTimeout.inSeconds} seconds',
);
}
/// Finds the Firebase CLI executable.
Future<String?> _findFirebaseCli() async {
// First, try to find the custom firebase-tools with Dart support
// This is in the parent directory structure: ../../firebase-tools
final customFirebasePath = _findCustomFirebaseCli();
if (customFirebasePath != null) {
try {
final result = await Process.run('node', [
customFirebasePath,
'--version',
]);
if (result.exitCode == 0) {
print(
'Using custom firebase-tools with Dart support: $customFirebasePath',
);
return 'node $customFirebasePath';
}
} catch (e) {
// Custom version not found or failed, try standard locations
}
}
// Try common locations
final candidates = [
'firebase', // In PATH
'npx firebase', // Via npx
'/usr/local/bin/firebase',
if (Platform.environment['HOME'] != null)
'${Platform.environment['HOME']}/.npm-global/bin/firebase'
else
null,
].where((c) => c != null).cast<String>();
for (final cmd in candidates) {
try {
final result = await Process.run(cmd.split(' ').first, [
...cmd.split(' ').skip(1),
'--version',
]);
if (result.exitCode == 0) {
return cmd;
}
} catch (e) {
// Command not found, try next
continue;
}
}
return null;
}
/// Finds the custom firebase-tools CLI with Dart support.
/// Returns the path to lib/bin/firebase.js if found.
String? _findCustomFirebaseCli() {
// Start from current directory and traverse up looking for firebase-tools
var dir = Directory.current;
// Check both possible directory names:
// - 'firebase-tools' (local development)
// - 'custom-firebase-tools' (CI environment)
const possibleDirNames = ['firebase-tools', 'custom-firebase-tools'];
for (var i = 0; i < 5; i++) {
// Only check up to 5 levels
for (final dirName in possibleDirNames) {
final firebaseToolsPath = '${dir.path}/$dirName/lib/bin/firebase.js';
if (File(firebaseToolsPath).existsSync()) {
return firebaseToolsPath;
}
}
final parentDir = dir.parent;
if (parentDir.path == dir.path) {
break; // Reached root
}
dir = parentDir;
}
return null;
}
/// Gets the base URL for the functions emulator.
String get functionsUrl =>
'http://localhost:$functionsPort/demo-test/us-central1';
/// Gets the base URL for the Pub/Sub emulator.
String get pubsubUrl => 'http://localhost:$pubsubPort';
/// Gets the base URL for the Firestore emulator REST API.
String get firestoreUrl =>
'http://localhost:$firestorePort/v1/projects/demo-test/databases/(default)/documents';
/// Gets the base URL for the Realtime Database emulator REST API.
String get databaseUrl => 'http://localhost:$databasePort';
/// Gets the base URL for the Auth emulator REST API.
String get authUrl => 'http://localhost:$authPort';
/// Gets the base URL for the Storage emulator REST API.
String get storageUrl => 'http://localhost:$storagePort';
/// Verifies that a function was executed in the emulator logs.
/// Returns true if we find both "Beginning execution" and "Finished" messages.
bool verifyFunctionExecution(String functionName) {
final executionStart = _outputLines.any(
(line) => line.contains('Beginning execution of "$functionName"'),
);
final executionEnd = _outputLines.any(
(line) => line.contains('Finished "$functionName"'),
);
return executionStart && executionEnd;
}
/// Verifies that the Dart runtime actually processed a request.
/// Looks for the Shelf server request logs (timestamp + method + status + path).
bool verifyDartRuntimeRequest(String method, int statusCode, String path) {
// Look for logs like: "2025-11-20T08:19:30.853342 0:00:00.000395 GET [200] /helloWorld"
final pattern = RegExp(
r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+\s+\d+:\d+:\d+\.\d+\s+' +
RegExp.escape(method) +
r'\s+\[' +
statusCode.toString() +
r'\]\s+' +
RegExp.escape(path),
);
return _outputLines.any(pattern.hasMatch);
}
/// Gets all output lines captured from the emulator.
List<String> get outputLines => List.unmodifiable(_outputLines);
/// Gets all error lines captured from the emulator.
List<String> get errorLines => List.unmodifiable(_errorLines);
/// Clears the output buffer (useful for testing specific requests).
void clearOutputBuffer() {
_outputLines.clear();
_errorLines.clear();
}
}