-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfirestore_namespace.dart
More file actions
798 lines (726 loc) · 26.3 KB
/
firestore_namespace.dart
File metadata and controls
798 lines (726 loc) · 26.3 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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
import 'dart:async';
import 'dart:typed_data';
import 'package:meta/meta.dart';
import 'package:shelf/shelf.dart';
import '../common/cloud_event.dart';
import '../firebase.dart';
import 'document_snapshot.dart';
import 'event.dart';
import 'options.dart';
import 'protobuf_parser.dart';
/// Parsed CloudEvent headers from a binary-mode Firestore request.
class _FirestoreHeaders {
_FirestoreHeaders({
required this.id,
required this.source,
required this.time,
required this.type,
required this.documentPath,
required this.database,
required this.namespace,
this.subject,
this.authType,
this.authId,
});
final String id;
final String source;
final String time;
final String type;
final String documentPath;
final String database;
final String namespace;
final String? subject;
final String? authType;
final String? authId;
}
/// Firestore triggers namespace.
///
/// Provides methods to define Firestore-triggered Cloud Functions.
class FirestoreNamespace extends FunctionsNamespace {
const FirestoreNamespace(super.firebase);
/// Event handler that triggers when a document is created in Firestore.
///
/// The handler receives a [FirestoreEvent] containing an [EmulatorDocumentSnapshot].
///
/// Example:
/// ```dart
/// firebase.firestore.onDocumentCreated(
/// document: 'users/{userId}',
/// (event) async {
/// // Access document data (similar to Node.js)
/// final data = event.data?.data();
/// print('User data: $data');
/// print('User name: ${data?['name']}');
///
/// // Access path parameters
/// print('User ID: ${event.params['userId']}');
///
/// // Access document metadata
/// print('Document path: ${event.document}');
/// print('Document ID: ${event.data?.id}');
/// },
/// );
/// ```
void onDocumentCreated(
Future<void> Function(FirestoreEvent<EmulatorDocumentSnapshot?> event)
handler, {
/// The Firestore document path to trigger on.
/// Supports wildcards: 'users/{userId}', 'users/{userId}/posts/{postId}'
// ignore: experimental_member_use
@mustBeConst required String document,
/// Options that can be set on an individual event-handling function.
// ignore: experimental_member_use
@mustBeConst DocumentOptions? options,
}) {
_registerDocumentHandler(
methodName: 'onDocumentCreated',
document: document,
validateEventType: _isFirestoreCreatedEvent,
withAuthContext: false,
handler: handler,
);
}
/// Event handler that triggers when a document is updated in Firestore.
///
/// The handler receives a [FirestoreEvent] containing a [Change] object
/// with `before` and `after` snapshots.
///
/// Example:
/// ```dart
/// firebase.firestore.onDocumentUpdated(
/// document: 'users/{userId}',
/// (event) async {
/// final before = event.data?.before.data();
/// final after = event.data?.after.data();
///
/// print('User ${event.params['userId']} updated');
/// print('Old name: ${before?['name']}');
/// print('New name: ${after?['name']}');
/// },
/// );
/// ```
void onDocumentUpdated(
Future<void> Function(
FirestoreEvent<Change<EmulatorDocumentSnapshot>?> event,
)
handler, {
/// The Firestore document path to trigger on.
/// Supports wildcards: 'users/{userId}', 'users/{userId}/posts/{postId}'
// ignore: experimental_member_use
@mustBeConst required String document,
/// Options that can be set on an individual event-handling function.
// ignore: experimental_member_use
@mustBeConst DocumentOptions? options,
}) {
_registerChangeHandler(
methodName: 'onDocumentUpdated',
document: document,
validateEventType: _isFirestoreUpdatedEvent,
withAuthContext: false,
handler: handler,
);
}
/// Event handler that triggers when a document is deleted in Firestore.
///
/// The handler receives a [FirestoreEvent] containing the deleted document snapshot.
///
/// Example:
/// ```dart
/// firebase.firestore.onDocumentDeleted(
/// document: 'users/{userId}',
/// (event) async {
/// final deletedData = event.data?.data();
/// print('User ${event.params['userId']} deleted');
/// print('Final data: $deletedData');
/// },
/// );
/// ```
void onDocumentDeleted(
Future<void> Function(FirestoreEvent<EmulatorDocumentSnapshot?> event)
handler, {
/// The Firestore document path to trigger on.
/// Supports wildcards: 'users/{userId}', 'users/{userId}/posts/{postId}'
// ignore: experimental_member_use
@mustBeConst required String document,
/// Options that can be set on an individual event-handling function.
// ignore: experimental_member_use
@mustBeConst DocumentOptions? options,
}) {
_registerDocumentHandler(
methodName: 'onDocumentDeleted',
document: document,
validateEventType: _isFirestoreDeletedEvent,
withAuthContext: false,
handler: handler,
);
}
/// Event handler that triggers on any write to a document (create, update, or delete).
///
/// The handler receives a [FirestoreEvent] containing a [Change] object.
/// Use `before.exists` and `after.exists` to determine the operation type.
///
/// Example:
/// ```dart
/// firebase.firestore.onDocumentWritten(
/// document: 'users/{userId}',
/// (event) async {
/// final before = event.data?.before;
/// final after = event.data?.after;
///
/// if (before == null || !before.exists) {
/// print('Document created');
/// } else if (after == null || !after.exists) {
/// print('Document deleted');
/// } else {
/// print('Document updated');
/// }
/// },
/// );
/// ```
void onDocumentWritten(
Future<void> Function(
FirestoreEvent<Change<EmulatorDocumentSnapshot>?> event,
)
handler, {
/// The Firestore document path to trigger on.
/// Supports wildcards: 'users/{userId}', 'users/{userId}/posts/{postId}'
// ignore: experimental_member_use
@mustBeConst required String document,
/// Options that can be set on an individual event-handling function.
// ignore: experimental_member_use
@mustBeConst DocumentOptions? options,
}) {
_registerChangeHandler(
methodName: 'onDocumentWritten',
document: document,
validateEventType: _isFirestoreWrittenEvent,
withAuthContext: false,
handler: handler,
);
}
/// Event handler that triggers when a document is created in Firestore,
/// with authentication context.
///
/// Similar to [onDocumentCreated], but the handler receives a
/// [FirestoreAuthEvent] that includes [AuthType] and an optional auth ID
/// identifying the principal that triggered the write.
///
/// Example:
/// ```dart
/// firebase.firestore.onDocumentCreatedWithAuthContext(
/// document: 'users/{userId}',
/// (event) async {
/// print('Auth type: ${event.authType}');
/// print('Auth ID: ${event.authId}');
/// final data = event.data?.data();
/// print('Document created: ${event.document}');
/// },
/// );
/// ```
void onDocumentCreatedWithAuthContext(
Future<void> Function(FirestoreAuthEvent<EmulatorDocumentSnapshot?> event)
handler, {
// ignore: experimental_member_use
@mustBeConst required String document,
// ignore: experimental_member_use
@mustBeConst DocumentOptions? options,
}) {
_registerDocumentHandler(
methodName: 'onDocumentCreatedWithAuthContext',
document: document,
validateEventType: _isFirestoreCreatedEvent,
withAuthContext: true,
handler: handler,
);
}
/// Event handler that triggers when a document is updated in Firestore,
/// with authentication context.
///
/// Similar to [onDocumentUpdated], but the handler receives a
/// [FirestoreAuthEvent] that includes [AuthType] and an optional auth ID.
///
/// Example:
/// ```dart
/// firebase.firestore.onDocumentUpdatedWithAuthContext(
/// document: 'users/{userId}',
/// (event) async {
/// print('Auth type: ${event.authType}');
/// final before = event.data?.before.data();
/// final after = event.data?.after.data();
/// },
/// );
/// ```
void onDocumentUpdatedWithAuthContext(
Future<void> Function(
FirestoreAuthEvent<Change<EmulatorDocumentSnapshot>?> event,
)
handler, {
// ignore: experimental_member_use
@mustBeConst required String document,
// ignore: experimental_member_use
@mustBeConst DocumentOptions? options,
}) {
_registerChangeHandler(
methodName: 'onDocumentUpdatedWithAuthContext',
document: document,
validateEventType: _isFirestoreUpdatedEvent,
withAuthContext: true,
handler: handler,
);
}
/// Event handler that triggers when a document is deleted in Firestore,
/// with authentication context.
///
/// Similar to [onDocumentDeleted], but the handler receives a
/// [FirestoreAuthEvent] that includes [AuthType] and an optional auth ID.
///
/// Example:
/// ```dart
/// firebase.firestore.onDocumentDeletedWithAuthContext(
/// document: 'users/{userId}',
/// (event) async {
/// print('Auth type: ${event.authType}');
/// print('Deleted by: ${event.authId}');
/// },
/// );
/// ```
void onDocumentDeletedWithAuthContext(
Future<void> Function(FirestoreAuthEvent<EmulatorDocumentSnapshot?> event)
handler, {
// ignore: experimental_member_use
@mustBeConst required String document,
// ignore: experimental_member_use
@mustBeConst DocumentOptions? options,
}) {
_registerDocumentHandler(
methodName: 'onDocumentDeletedWithAuthContext',
document: document,
validateEventType: _isFirestoreDeletedEvent,
withAuthContext: true,
handler: handler,
);
}
/// Event handler that triggers on any write to a document (create, update,
/// or delete), with authentication context.
///
/// Similar to [onDocumentWritten], but the handler receives a
/// [FirestoreAuthEvent] that includes [AuthType] and an optional auth ID.
///
/// Example:
/// ```dart
/// firebase.firestore.onDocumentWrittenWithAuthContext(
/// document: 'users/{userId}',
/// (event) async {
/// print('Auth type: ${event.authType}');
/// print('Auth ID: ${event.authId}');
/// final before = event.data?.before;
/// final after = event.data?.after;
/// },
/// );
/// ```
void onDocumentWrittenWithAuthContext(
Future<void> Function(
FirestoreAuthEvent<Change<EmulatorDocumentSnapshot>?> event,
)
handler, {
// ignore: experimental_member_use
@mustBeConst required String document,
// ignore: experimental_member_use
@mustBeConst DocumentOptions? options,
}) {
_registerChangeHandler(
methodName: 'onDocumentWrittenWithAuthContext',
document: document,
validateEventType: _isFirestoreWrittenEvent,
withAuthContext: true,
handler: handler,
);
}
// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------
/// Extracts and validates all `ce-*` headers from a binary-mode request.
///
/// Returns `null` if required headers (`ce-id`, `ce-source`, `ce-time`,
/// `ce-document`) are missing.
_FirestoreHeaders? _extractHeaders(Request request) {
final ceId = request.headers['ce-id'];
final ceSource = request.headers['ce-source'];
final ceTime = request.headers['ce-time'];
final documentPath = request.headers['ce-document'];
if (ceId == null ||
ceSource == null ||
ceTime == null ||
documentPath == null) {
return null;
}
return _FirestoreHeaders(
id: ceId,
source: ceSource,
time: ceTime,
type: request.headers['ce-type']!,
documentPath: documentPath,
database: request.headers['ce-database'] ?? '(default)',
namespace: request.headers['ce-namespace'] ?? '(default)',
subject: request.headers['ce-subject'],
authType: request.headers['ce-authtype'],
authId: request.headers['ce-authid'],
);
}
/// Reads and parses the protobuf body from a request.
///
/// Returns the parsed map with `'value'` and/or `'old_value'` keys,
/// or `null` if the body is empty or parsing fails.
Future<Map<String, EmulatorDocumentSnapshot?>?> _parseBody(
Request request,
) async {
try {
final bodyBytes = await request.read().fold<List<int>>(
[],
(previous, element) => previous..addAll(element),
);
if (bodyBytes.isNotEmpty) {
return parseDocumentEventData(Uint8List.fromList(bodyBytes));
}
} catch (_) {
// Protobuf parsing failed
}
return null;
}
/// Shared handler for single-snapshot triggers (created/deleted).
///
/// When [withAuthContext] is `false`, [handler] is called with a
/// `FirestoreEvent<EmulatorDocumentSnapshot?>`.
/// When `true`, it is called with a
/// `FirestoreAuthEvent<EmulatorDocumentSnapshot?>`.
void _registerDocumentHandler({
required String methodName,
required String document,
required bool Function(String) validateEventType,
required bool withAuthContext,
required Function handler,
}) {
final functionName = _documentToFunctionName(methodName, document);
firebase.registerFunction(functionName, (request) async {
try {
final isBinaryMode = request.headers.containsKey('ce-type');
if (isBinaryMode) {
final ceType = request.headers['ce-type'];
if (ceType != null && !validateEventType(ceType)) {
return Response(
400,
body: 'Invalid event type for Firestore $methodName: $ceType',
);
}
final headers = _extractHeaders(request);
if (headers == null) {
return Response(400, body: 'Missing required CloudEvent headers');
}
final params = _extractParams(document, headers.documentPath);
final parsed = await _parseBody(request);
final snapshotKey =
(methodName == 'onDocumentDeleted' ||
methodName == 'onDocumentDeletedWithAuthContext')
? 'old_value'
: 'value';
final snapshot = parsed?[snapshotKey];
try {
if (withAuthContext) {
final event = FirestoreAuthEvent<EmulatorDocumentSnapshot?>(
data: snapshot,
id: headers.id,
source: headers.source,
specversion: '1.0',
subject: headers.subject,
time: DateTime.parse(headers.time),
type: headers.type,
location: 'us-central1',
project: _extractProject(headers.source),
database: headers.database,
namespace: headers.namespace,
document: headers.documentPath,
params: params,
authType: AuthType.fromString(headers.authType ?? 'unknown'),
authId: headers.authId,
);
await (handler
as Future<void> Function(
FirestoreAuthEvent<EmulatorDocumentSnapshot?>,
))(event);
} else {
final event = FirestoreEvent<EmulatorDocumentSnapshot?>(
data: snapshot,
id: headers.id,
source: headers.source,
specversion: '1.0',
subject: headers.subject,
time: DateTime.parse(headers.time),
type: headers.type,
location: 'us-central1',
project: _extractProject(headers.source),
database: headers.database,
namespace: headers.namespace,
document: headers.documentPath,
params: params,
);
await (handler
as Future<void> Function(
FirestoreEvent<EmulatorDocumentSnapshot?>,
))(event);
}
} catch (e) {
return Response(500, body: 'Handler error: $e');
}
return Response.ok('');
} else {
// Structured content mode: full CloudEvent in JSON body
// Only supported for onDocumentCreated variants
if (methodName == 'onDocumentCreated' ||
methodName == 'onDocumentCreatedWithAuthContext') {
final json = await parseAndValidateCloudEvent(request);
if (!validateEventType(json['type'] as String)) {
return Response(
400,
body:
'Invalid event type for Firestore $methodName: ${json['type']}',
);
}
if (withAuthContext) {
final event = FirestoreAuthEvent<EmulatorDocumentSnapshot?>(
id: json['id'] as String,
source: json['source'] as String,
specversion: json['specversion'] as String,
subject: json['subject'] as String?,
time: DateTime.parse(json['time'] as String),
type: json['type'] as String,
location: json['location'] as String? ?? 'us-central1',
project: 'unknown',
database: '(default)',
namespace: '(default)',
document: '',
params: {},
authType: AuthType.fromString(
json['authtype'] as String? ?? 'unknown',
),
authId: json['authid'] as String?,
);
await (handler
as Future<void> Function(
FirestoreAuthEvent<EmulatorDocumentSnapshot?>,
))(event);
} else {
final event = FirestoreEvent<EmulatorDocumentSnapshot?>.fromJson(
json,
(data) {
// TODO: Parse protobuf data from structured CloudEvent
return null;
},
);
await (handler
as Future<void> Function(
FirestoreEvent<EmulatorDocumentSnapshot?>,
))(event);
}
return Response.ok('');
}
return Response(
501,
body:
'Structured CloudEvent mode not yet supported for $methodName',
);
}
} on FormatException catch (e) {
return Response(400, body: 'Invalid CloudEvent: ${e.message}');
} catch (e, stackTrace) {
return Response(
500,
body: 'Error processing Firestore event: $e\n$stackTrace',
);
}
}, documentPattern: document);
}
/// Shared handler for change triggers (updated/written).
///
/// When [withAuthContext] is `false`, [handler] is called with a
/// `FirestoreEvent<Change<EmulatorDocumentSnapshot>?>`.
/// When `true`, it is called with a
/// `FirestoreAuthEvent<Change<EmulatorDocumentSnapshot>?>`.
void _registerChangeHandler({
required String methodName,
required String document,
required bool Function(String) validateEventType,
required bool withAuthContext,
required Function handler,
}) {
final functionName = _documentToFunctionName(methodName, document);
firebase.registerFunction(functionName, (request) async {
try {
final isBinaryMode = request.headers.containsKey('ce-type');
if (isBinaryMode) {
final ceType = request.headers['ce-type'];
if (ceType != null && !validateEventType(ceType)) {
return Response(
400,
body: 'Invalid event type for Firestore $methodName: $ceType',
);
}
final headers = _extractHeaders(request);
if (headers == null) {
return Response(400, body: 'Missing required CloudEvent headers');
}
final params = _extractParams(document, headers.documentPath);
final parsed = await _parseBody(request);
final beforeSnapshot = parsed?['old_value'];
final afterSnapshot = parsed?['value'];
try {
final change = Change<EmulatorDocumentSnapshot>(
before: beforeSnapshot,
after: afterSnapshot,
);
if (withAuthContext) {
final event =
FirestoreAuthEvent<Change<EmulatorDocumentSnapshot>?>(
data: change,
id: headers.id,
source: headers.source,
specversion: '1.0',
subject: headers.subject,
time: DateTime.parse(headers.time),
type: headers.type,
location: 'us-central1',
project: _extractProject(headers.source),
database: headers.database,
namespace: headers.namespace,
document: headers.documentPath,
params: params,
authType: AuthType.fromString(
headers.authType ?? 'unknown',
),
authId: headers.authId,
);
await (handler
as Future<void> Function(
FirestoreAuthEvent<Change<EmulatorDocumentSnapshot>?>,
))(event);
} else {
final event = FirestoreEvent<Change<EmulatorDocumentSnapshot>?>(
data: change,
id: headers.id,
source: headers.source,
specversion: '1.0',
subject: headers.subject,
time: DateTime.parse(headers.time),
type: headers.type,
location: 'us-central1',
project: _extractProject(headers.source),
database: headers.database,
namespace: headers.namespace,
document: headers.documentPath,
params: params,
);
await (handler
as Future<void> Function(
FirestoreEvent<Change<EmulatorDocumentSnapshot>?>,
))(event);
}
} catch (e) {
return Response(500, body: 'Handler error: $e');
}
return Response.ok('');
} else {
return Response(
501,
body:
'Structured CloudEvent mode not yet supported for $methodName',
);
}
} catch (e, stackTrace) {
return Response(
500,
body: 'Error processing Firestore event: $e\n$stackTrace',
);
}
}, documentPattern: document);
}
/// Converts a document path to a function name.
///
/// Examples:
/// - 'users/{userId}' -> 'onDocumentCreated_users_userId'
/// - 'users/user123' -> 'onDocumentCreated_users_user123'
String _documentToFunctionName(String eventType, String documentPath) {
// Remove leading/trailing slashes
final cleaned = documentPath.replaceAll(RegExp(r'^/+|/+$'), '');
// Replace path separators and wildcards with underscores
final sanitized = cleaned
.replaceAll('/', '_')
.replaceAll('{', '')
.replaceAll('}', '')
.replaceAll('-', '');
return '${eventType}_$sanitized';
}
/// Checks if the CloudEvent type is a Firestore document created event.
/// Accepts both the base type and the `.withAuthContext` variant.
bool _isFirestoreCreatedEvent(String type) =>
type == 'google.cloud.firestore.document.v1.created' ||
type == 'google.cloud.firestore.document.v1.created.withAuthContext';
/// Checks if the CloudEvent type is a Firestore document updated event.
/// Accepts both the base type and the `.withAuthContext` variant.
bool _isFirestoreUpdatedEvent(String type) =>
type == 'google.cloud.firestore.document.v1.updated' ||
type == 'google.cloud.firestore.document.v1.updated.withAuthContext';
/// Checks if the CloudEvent type is a Firestore document deleted event.
/// Accepts both the base type and the `.withAuthContext` variant.
bool _isFirestoreDeletedEvent(String type) =>
type == 'google.cloud.firestore.document.v1.deleted' ||
type == 'google.cloud.firestore.document.v1.deleted.withAuthContext';
/// Checks if the CloudEvent type is a Firestore document written event.
/// Accepts both the base type and the `.withAuthContext` variant.
bool _isFirestoreWrittenEvent(String type) =>
type == 'google.cloud.firestore.document.v1.written' ||
type == 'google.cloud.firestore.document.v1.written.withAuthContext';
/// Extracts path parameters from a document path by matching against a pattern.
///
/// Example:
/// - pattern: 'users/{userId}'
/// - documentPath: 'users/abc123'
/// - returns: {'userId': 'abc123'}
Map<String, String> _extractParams(String pattern, String documentPath) {
final params = <String, String>{};
final patternParts = pattern.split('/');
final documentParts = documentPath.split('/');
if (patternParts.length != documentParts.length) {
return params;
}
for (var i = 0; i < patternParts.length; i++) {
final patternPart = patternParts[i];
final documentPart = documentParts[i];
// Extract parameter name from wildcards like {userId}
if (patternPart.startsWith('{') && patternPart.endsWith('}')) {
final paramName = patternPart.substring(1, patternPart.length - 1);
params[paramName] = documentPart;
}
}
return params;
}
/// Extracts the project ID from a CloudEvent source.
///
/// Source format: //firestore.googleapis.com/projects/{project}/databases/{database}/...
/// Note: Source may have nested paths like projects/projects/demo-test
String _extractProject(String source) {
final uri = Uri.parse(source.replaceFirst('//', 'https://'));
final pathSegments = uri.pathSegments;
// Find LAST 'projects' segment and return the next one
// This handles cases like: projects/projects/demo-test
var projectIndex = -1;
for (var i = pathSegments.length - 1; i >= 0; i--) {
if (pathSegments[i] == 'projects' && i + 1 < pathSegments.length) {
projectIndex = i;
break;
}
}
if (projectIndex != -1) {
return pathSegments[projectIndex + 1];
}
return 'unknown-project';
}
}