-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathfunctions_request_handler.dart
More file actions
292 lines (250 loc) · 9.57 KB
/
functions_request_handler.dart
File metadata and controls
292 lines (250 loc) · 9.57 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
part of 'functions.dart';
/// Parsed resource name components.
class _ParsedResource {
_ParsedResource({this.projectId, this.locationId, required this.resourceId});
String? projectId;
String? locationId;
final String resourceId;
}
/// Request handler for Cloud Functions Task Queue operations.
///
/// Handles complex business logic, request/response transformations,
/// and validation. Delegates API calls to [FunctionsHttpClient].
class FunctionsRequestHandler {
FunctionsRequestHandler(FirebaseApp app, {FunctionsHttpClient? httpClient})
: _httpClient = httpClient ?? FunctionsHttpClient(app);
final FunctionsHttpClient _httpClient;
FunctionsHttpClient get httpClient => _httpClient;
/// Enqueues a task to the specified function's queue.
Future<void> enqueue(
Map<String, dynamic> data,
String functionName,
String? extensionId,
TaskOptions? options,
) async {
validateNonEmptyString(functionName, 'functionName');
// Parse the function name to extract project, location, and function ID
final resources = _parseResourceName(functionName, 'functions');
return _httpClient.cloudTasks((api, projectId) async {
// Fill in missing resource components
resources.projectId ??= projectId;
resources.locationId ??= _defaultLocation;
validateNonEmptyString(resources.resourceId, 'resourceId');
// Apply extension ID prefix if provided
var queueId = resources.resourceId;
if (extensionId != null && extensionId.isNotEmpty) {
queueId = 'ext-$extensionId-$queueId';
}
// Build the task
final task = _buildTask(data, resources, queueId, options);
// Update task with proper authentication (OIDC token or Authorization header)
await _updateTaskAuth(task, await _httpClient.client, extensionId);
final parent = _httpClient.buildTasksParent(
projectId: resources.projectId!,
locationId: resources.locationId!,
queueId: queueId,
);
try {
await api.projects.locations.queues.tasks.create(
tasks2.CreateTaskRequest(task: task),
parent,
);
} on tasks2.DetailedApiRequestError catch (error) {
// Handle 409 Conflict (task already exists)
if (error.status == 409) {
throw FirebaseFunctionsAdminException(
FunctionsClientErrorCode.taskAlreadyExists,
'A task with ID ${options?.id} already exists',
);
}
rethrow; // Will be caught by _functionsGuard
}
});
}
/// Deletes a task from the specified function's queue.
Future<void> delete(
String id,
String functionName,
String? extensionId,
) async {
validateNonEmptyString(functionName, 'functionName');
validateNonEmptyString(id, 'id');
if (!isValidTaskId(id)) {
throw FirebaseFunctionsAdminException(
FunctionsClientErrorCode.invalidArgument,
'id can contain only letters ([A-Za-z]), numbers ([0-9]), '
'hyphens (-), or underscores (_). The maximum length is 500 characters.',
);
}
// Parse the function name
final resources = _parseResourceName(functionName, 'functions');
return _httpClient.cloudTasks((api, projectId) async {
// Fill in missing resource components
resources.projectId ??= projectId;
resources.locationId ??= _defaultLocation;
validateNonEmptyString(resources.resourceId, 'resourceId');
// Apply extension ID prefix if provided
var queueId = resources.resourceId;
if (extensionId != null && extensionId.isNotEmpty) {
queueId = 'ext-$extensionId-$queueId';
}
// Build the full task name
final taskName = _httpClient.buildTaskName(
projectId: resources.projectId!,
locationId: resources.locationId!,
queueId: queueId,
taskId: id,
);
try {
await api.projects.locations.queues.tasks.delete(taskName);
} on tasks2.DetailedApiRequestError catch (error) {
// If the task doesn't exist (404), ignore the error
if (error.status == 404) {
return;
}
rethrow; // Will be caught by _functionsGuard
}
});
}
/// Parses a resource name into its components.
///
/// Supports:
/// - Full: `projects/{project}/locations/{location}/functions/{functionName}`
/// - Partial: `locations/{location}/functions/{functionName}`
/// - Simple: `{functionName}`
_ParsedResource _parseResourceName(
String resourceName,
String resourceIdKey,
) {
// Simple case: no slashes means it's just the resource ID
if (!resourceName.contains('/')) {
return _ParsedResource(resourceId: resourceName);
}
// Parse full or partial resource name
final regex = RegExp(
'^(projects/([^/]+)/)?locations/([^/]+)/$resourceIdKey/([^/]+)\$',
);
final match = regex.firstMatch(resourceName);
if (match == null) {
throw FirebaseFunctionsAdminException(
FunctionsClientErrorCode.invalidArgument,
'Invalid resource name format.',
);
}
return _ParsedResource(
projectId: match.group(2), // Optional project ID
locationId: match.group(3), // Required location
resourceId: match.group(4)!, // Required resource ID
);
}
/// Builds a Cloud Tasks Task from the given data and options.
tasks2.Task _buildTask(
Map<String, dynamic> data,
_ParsedResource resources,
String queueId,
TaskOptions? options,
) {
// Base64 encode the data payload
final bodyBytes = utf8.encode(jsonEncode({'data': data}));
final bodyBase64 = base64Encode(bodyBytes);
// Build HTTP request
final httpRequest = tasks2.HttpRequest(
body: bodyBase64,
headers: {'Content-Type': 'application/json', ...?options?.headers},
);
// Build the task
final task = tasks2.Task(httpRequest: httpRequest);
// Set schedule time using pattern matching on DeliverySchedule
switch (options?.schedule) {
case AbsoluteDelivery(:final scheduleTime):
task.scheduleTime = scheduleTime.toUtc().toIso8601String();
case DelayDelivery(:final scheduleDelaySeconds):
final scheduledTime = DateTime.now().toUtc().add(
Duration(seconds: scheduleDelaySeconds),
);
task.scheduleTime = scheduledTime.toIso8601String();
case null:
// No scheduling specified - task will be enqueued immediately
break;
}
// Set dispatch deadline
if (options?.dispatchDeadlineSeconds != null) {
task.dispatchDeadline = '${options!.dispatchDeadlineSeconds}s';
}
// Set task ID (for deduplication)
if (options?.id != null) {
task.name = _httpClient.buildTaskName(
projectId: resources.projectId!,
locationId: resources.locationId!,
queueId: queueId,
taskId: options!.id!,
);
}
// Set custom URI if provided (experimental feature)
if (options?.experimental?.uri != null) {
httpRequest.url = options!.experimental!.uri;
} else {
// Use default function URL
httpRequest.url = _httpClient.buildFunctionUrl(
projectId: resources.projectId!,
locationId: resources.locationId!,
functionName: queueId,
);
}
// Note: Authentication (OIDC token or Authorization header) is set
// separately via _updateTaskAuth after the task is built.
return task;
}
/// Updates the task with proper authentication.
///
/// This method handles the authentication strategy based on the credential type:
/// - When running with emulator: Uses a default emulated service account email
/// - When running as an extension with ComputeEngine credentials: Uses ID token
/// with Authorization header (Cloud Tasks will not override this)
/// - Otherwise: Uses OIDC token with the service account email
Future<void> _updateTaskAuth(
tasks2.Task task,
googleapis_auth.AuthClient authClient,
String? extensionId,
) async {
final httpRequest = task.httpRequest!;
// Check if running with emulator
if (Environment.isCloudTasksEmulatorEnabled()) {
httpRequest.oidcToken = tasks2.OidcToken(
serviceAccountEmail: _emulatedServiceAccountDefault,
);
return;
}
// Service credentials via `FirebaseApp.options`.
final isComputeEngine =
_httpClient.app.options.credential?.serviceAccountCredentials == null;
if (extensionId != null && extensionId.isNotEmpty && isComputeEngine) {
// Running as extension with ComputeEngine - use ID token with Authorization header.
final idToken = authClient.credentials.idToken;
if (idToken != null && idToken.isNotEmpty) {
httpRequest.headers = {
...?httpRequest.headers,
'Authorization': 'Bearer $idToken',
};
// Don't set oidcToken when using Authorization header,
// as Cloud Tasks would overwrite our Authorization header.
httpRequest.oidcToken = null;
return;
}
}
// Default: Use OIDC token with service account email.
// Try to get service account email from credential first, then from metadata service.
final serviceAccountEmail = await _httpClient.app.serviceAccountEmail;
if (serviceAccountEmail.isEmpty) {
throw FirebaseFunctionsAdminException(
FunctionsClientErrorCode.invalidCredential,
'Failed to determine service account email. Initialize the SDK with '
'service account credentials or ensure you are running on Google Cloud '
'infrastructure with a default service account.',
);
}
httpRequest.oidcToken = tasks2.OidcToken(
serviceAccountEmail: serviceAccountEmail,
);
}
}