-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttps_namespace.dart
More file actions
306 lines (278 loc) · 9.38 KB
/
https_namespace.dart
File metadata and controls
306 lines (278 loc) · 9.38 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
// 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 'package:meta/meta.dart';
import 'package:shelf/shelf.dart';
import '../common/utilities.dart';
import '../firebase.dart';
import 'auth.dart';
import 'callable.dart';
import 'error.dart';
import 'options.dart';
/// HTTPS triggers namespace.
///
/// Provides methods to define HTTP-triggered Cloud Functions.
class HttpsNamespace extends FunctionsNamespace {
const HttpsNamespace(super.firebase);
/// Creates an HTTPS function that handles raw HTTP requests.
///
/// The handler receives a Shelf [Request] and must return a Shelf [Response].
///
/// Example:
/// ```dart
/// firebase.https.onRequest(
/// name: 'hello',
/// (request) async {
/// return Response.ok('Hello World!');
/// },
/// );
/// ```
void onRequest(
Future<Response> Function(Request request) handler, {
// ignore: experimental_member_use
@mustBeConst required String name,
// ignore: experimental_member_use
@mustBeConst HttpsOptions? options = const HttpsOptions(),
}) {
firebase.registerFunction(name, (request) async {
try {
return await handler(request);
} on HttpsError catch (e) {
return e.toShelfResponse();
} catch (e, stackTrace) {
return logInternalError(e, stackTrace).toShelfResponse();
}
}, external: true);
}
/// Creates an HTTPS callable function (untyped data).
///
/// Callable functions provide a simple RPC interface with automatic
/// request/response handling and Firebase Auth integration.
///
/// Example:
/// ```dart
/// firebase.https.onCall(
/// name: 'greet',
/// (request, response) async {
/// final name = request.data['name'] as String;
/// return CallableResult({'message': 'Hello $name!'});
/// },
/// );
/// ```
void onCall<T extends Object>(
Future<CallableResult<T>> Function(
CallableRequest<Object?> request,
CallableResponse<T> response,
)
handler, {
// ignore: experimental_member_use
@mustBeConst required String name,
// ignore: experimental_member_use
@mustBeConst CallableOptions? options = const CallableOptions(),
}) {
firebase.registerFunction(name, (request) async {
final bodyString = await request.change().readAsString();
Map<String, dynamic>? body;
if (bodyString.isNotEmpty) {
try {
body = jsonDecode(bodyString) as Map<String, dynamic>;
} catch (_) {
// Invalid JSON - body stays null, validation will fail
}
}
// Extract auth and app check tokens
final tokens = await checkTokens(
request,
adminApp: firebase.$env.skipTokenVerification
? null
: firebase.adminApp,
);
// Check for invalid auth token
if (tokens.result.auth == TokenStatus.invalid) {
return UnauthenticatedError().toShelfResponse();
}
// Check for invalid or missing app check token if enforced
final enforceAppCheck = options?.enforceAppCheck?.runtimeValue() ?? false;
if (tokens.result.app == TokenStatus.invalid) {
if (enforceAppCheck) {
return UnauthenticatedError().toShelfResponse();
}
}
if (tokens.result.app == TokenStatus.missing && enforceAppCheck) {
return UnauthenticatedError().toShelfResponse();
}
final callableRequest = CallableRequest(
request,
body?['data'],
null,
auth: tokens.authData,
app: tokens.appCheckData,
);
return _handleCallable<Object?, T, CallableResult<T>>(
request,
callableRequest,
body,
options,
handler,
(result) => result.data,
(result) => result.toResponse(),
);
});
}
/// Creates an HTTPS callable function with typed data.
///
/// Provides type-safe request/response handling with custom serialization.
///
/// Example:
/// ```dart
/// class GreetRequest {
/// final String name;
/// GreetRequest(this.name);
/// factory GreetRequest.fromJson(Map<String, dynamic> json) =>
/// GreetRequest(json['name'] as String);
/// }
///
/// firebase.https.onCallWithData<GreetRequest, String>(
/// name: 'greetTyped',
/// fromJson: GreetRequest.fromJson,
/// (request, response) async {
/// return 'Hello ${request.data.name}!';
/// },
/// );
/// ```
void onCallWithData<Input extends Object, Output extends Object>(
Future<Output> Function(
CallableRequest<Input> request,
CallableResponse<Output> response,
)
handler, {
required Input Function(Map<String, dynamic>) fromJson,
// ignore: experimental_member_use
@mustBeConst required String name,
// ignore: experimental_member_use
@mustBeConst CallableOptions? options = const CallableOptions(),
}) {
firebase.registerFunction(name, (request) async {
final body = await request.json as Map<String, dynamic>?;
// Extract auth and app check tokens
final tokens = await checkTokens(
request,
adminApp: firebase.$env.skipTokenVerification
? null
: firebase.adminApp,
);
// Check for invalid auth token
if (tokens.result.auth == TokenStatus.invalid) {
return UnauthenticatedError().toShelfResponse();
}
// Check for invalid or missing app check token if enforced
final enforceAppCheck = options?.enforceAppCheck?.runtimeValue() ?? false;
if (tokens.result.app == TokenStatus.invalid) {
if (enforceAppCheck) {
return UnauthenticatedError().toShelfResponse();
}
}
if (tokens.result.app == TokenStatus.missing && enforceAppCheck) {
return UnauthenticatedError().toShelfResponse();
}
final callableRequest = CallableRequest<Input>(
request,
body?['data'],
fromJson,
auth: tokens.authData,
app: tokens.appCheckData,
);
return _handleCallable<Input, Output, Output>(
request,
callableRequest,
body,
options,
handler,
(result) => result,
(result) => Response.ok(
jsonEncode({'result': result}),
headers: {'Content-Type': 'application/json'},
),
);
});
}
/// Internal handler for callable functions.
///
/// Handles both streaming and non-streaming responses, error handling,
/// and request validation.
Future<Response> _handleCallable<
Req extends Object?,
StreamType extends Object,
Res extends Object
>(
Request request,
CallableRequest<Req> callableRequest,
Map<String, dynamic>? body,
CallableOptions? options,
Future<Res> Function(
CallableRequest<Req> request,
CallableResponse<StreamType> response,
)
handler,
dynamic Function(Res result) extractResultData,
Response Function(Res result) createNonStreamingResponse,
) async {
// Validate request - pass empty map if body is null to avoid double-read
if (!await request.isValidRequest(body ?? {})) {
return InvalidArgumentError('Invalid callable request').toShelfResponse();
}
final heartbeatSeconds = options?.heartBeatIntervalSeconds?.runtimeValue();
final callableResponse = CallableResponse<StreamType>(
acceptsStreaming: callableRequest.acceptsStreaming,
heartbeatSeconds: heartbeatSeconds,
);
try {
// Initialize streaming if requested
if (callableRequest.acceptsStreaming) {
callableResponse.initializeStreaming();
}
// Execute handler
final result = await handler(callableRequest, callableResponse);
// Handle streaming response
if (callableRequest.acceptsStreaming && !callableResponse.aborted) {
final finalResult = {'result': extractResultData(result)};
callableResponse.writeSSE(finalResult);
await callableResponse.closeStream();
return callableResponse.streamingResponse!;
}
// Non-streaming response
return createNonStreamingResponse(result);
} on HttpsError catch (e) {
// Handle HttpsError - use SSE format if streaming
if (callableRequest.acceptsStreaming && !callableResponse.aborted) {
callableResponse.writeSSE(e.toErrorResponse());
await callableResponse.closeStream();
return callableResponse.streamingResponse!;
}
return e.toShelfResponse();
} catch (e, stackTrace) {
// Unexpected error - don't expose details to client
final error = logInternalError(e, stackTrace);
if (callableRequest.acceptsStreaming && !callableResponse.aborted) {
callableResponse.writeSSE(error.toErrorResponse());
await callableResponse.closeStream();
return callableResponse.streamingResponse!;
}
return error.toShelfResponse();
} finally {
callableResponse.clearHeartbeat();
}
}
}