pyios-firebase 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. pyios_firebase/__init__.py +26 -0
  2. pyios_firebase/analytics/__init__.py +434 -0
  3. pyios_firebase/analytics/names.py +251 -0
  4. pyios_firebase/app_check/__init__.py +483 -0
  5. pyios_firebase/auth/__init__.py +131 -0
  6. pyios_firebase/auth/_apple_name_cache.py +97 -0
  7. pyios_firebase/auth/_common.py +121 -0
  8. pyios_firebase/auth/_ui.py +21 -0
  9. pyios_firebase/auth/apple.py +326 -0
  10. pyios_firebase/auth/auth.py +592 -0
  11. pyios_firebase/auth/credentials.py +551 -0
  12. pyios_firebase/auth/errors.py +321 -0
  13. pyios_firebase/auth/facebook.py +240 -0
  14. pyios_firebase/auth/google.py +167 -0
  15. pyios_firebase/auth/multi_factor.py +394 -0
  16. pyios_firebase/auth/results.py +361 -0
  17. pyios_firebase/auth/user.py +457 -0
  18. pyios_firebase/core/__init__.py +32 -0
  19. pyios_firebase/crashlytics/__init__.py +463 -0
  20. pyios_firebase/database/__init__.py +62 -0
  21. pyios_firebase/database/database.py +144 -0
  22. pyios_firebase/database/errors.py +80 -0
  23. pyios_firebase/database/query.py +569 -0
  24. pyios_firebase/database/reference.py +428 -0
  25. pyios_firebase/database/snapshot.py +218 -0
  26. pyios_firebase/database/values.py +271 -0
  27. pyios_firebase/firestore/__init__.py +59 -0
  28. pyios_firebase/firestore/_limits.py +48 -0
  29. pyios_firebase/firestore/_query_state.py +228 -0
  30. pyios_firebase/firestore/_write.py +18 -0
  31. pyios_firebase/firestore/aggregate.py +137 -0
  32. pyios_firebase/firestore/collection_reference.py +100 -0
  33. pyios_firebase/firestore/document_change.py +63 -0
  34. pyios_firebase/firestore/document_reference.py +229 -0
  35. pyios_firebase/firestore/document_snapshot.py +102 -0
  36. pyios_firebase/firestore/enums.py +66 -0
  37. pyios_firebase/firestore/field_value.py +94 -0
  38. pyios_firebase/firestore/filter.py +319 -0
  39. pyios_firebase/firestore/firestore.py +184 -0
  40. pyios_firebase/firestore/listener_registration.py +55 -0
  41. pyios_firebase/firestore/query.py +679 -0
  42. pyios_firebase/firestore/query_snapshot.py +103 -0
  43. pyios_firebase/firestore/snapshot_metadata.py +36 -0
  44. pyios_firebase/firestore/transaction.py +130 -0
  45. pyios_firebase/firestore/write_batch.py +125 -0
  46. pyios_firebase/functions/__init__.py +329 -0
  47. pyios_firebase/messaging/__init__.py +37 -0
  48. pyios_firebase/messaging/messaging.py +435 -0
  49. pyios_firebase/messaging/notifications.py +292 -0
  50. pyios_firebase/performance/__init__.py +486 -0
  51. pyios_firebase/py.typed +0 -0
  52. pyios_firebase/remote_config/__init__.py +660 -0
  53. pyios_firebase/storage/__init__.py +41 -0
  54. pyios_firebase/storage/errors.py +103 -0
  55. pyios_firebase/storage/metadata.py +202 -0
  56. pyios_firebase/storage/reference.py +402 -0
  57. pyios_firebase/storage/storage.py +120 -0
  58. pyios_firebase/storage/task.py +198 -0
  59. pyios_firebase/types.py +93 -0
  60. pyios_firebase/util.py +413 -0
  61. pyios_firebase-0.2.0.dist-info/METADATA +1969 -0
  62. pyios_firebase-0.2.0.dist-info/RECORD +65 -0
  63. pyios_firebase-0.2.0.dist-info/WHEEL +5 -0
  64. pyios_firebase-0.2.0.dist-info/licenses/LICENSE +21 -0
  65. pyios_firebase-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,486 @@
1
+ """Firebase Performance Monitoring: custom code traces and network requests.
2
+
3
+ from pyios_firebase.performance import HTTPMethod, HTTPMetric, Performance
4
+
5
+ with Performance.performance().trace("load_feed") as trace:
6
+ items = load_feed()
7
+ trace.increment_metric("items", len(items))
8
+ trace.put_attribute("source", "cache")
9
+
10
+ metric = HTTPMetric("https://api.example.com/feed", HTTPMethod.GET)
11
+ metric.start()
12
+ ... # make the request
13
+ metric.response_code = 200
14
+ metric.response_payload_size = len(body)
15
+ metric.stop()
16
+
17
+ The SDK measures app start, screen rendering and the requests made with
18
+ ``NSURLSession`` by itself. Requests made from Python (``urllib``,
19
+ ``requests``, ``httpx``...) do not use ``NSURLSession``: measure them with
20
+ ``HTTPMetric``.
21
+
22
+ Bad names and values raise ``ValueError`` (the SDK would drop the trace,
23
+ metric or attribute quietly). While data collection is off, traces and HTTP
24
+ metrics are inactive (``active`` is ``False``) and do nothing.
25
+
26
+ Needs the ``FirebasePerformance`` framework.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ __all__ = (
32
+ "HTTPMethod",
33
+ "HTTPMetric",
34
+ "Performance",
35
+ "Trace",
36
+ )
37
+
38
+ import re
39
+ from types import TracebackType
40
+ from typing import Any, ClassVar, Final, Self
41
+ from urllib.parse import urlsplit
42
+
43
+ from ..types import ObjCObject
44
+ from ..util import objc_class, to_python
45
+
46
+ _MAX_NAME: Final = 100
47
+ _MAX_ATTRIBUTE_NAME: Final = 40
48
+ _MAX_ATTRIBUTE_VALUE: Final = 100
49
+ _MAX_ATTRIBUTES: Final = 5
50
+ _MAX_URL: Final = 2000
51
+ _ATTRIBUTE_NAME: Final = re.compile(r"[A-Za-z0-9_]*\Z")
52
+ _RESERVED_ATTRIBUTE_PREFIXES: Final = ("firebase_", "google_", "ga_")
53
+ _INT64: Final = 2**63
54
+
55
+
56
+ class HTTPMethod:
57
+ """The method of an ``HTTPMetric``'s request (``FIRHTTPMethod``)."""
58
+
59
+ GET: Final = 0
60
+ PUT: Final = 1
61
+ POST: Final = 2
62
+ DELETE: Final = 3
63
+ HEAD: Final = 4
64
+ PATCH: Final = 5
65
+ OPTIONS: Final = 6
66
+ TRACE: Final = 7
67
+ CONNECT: Final = 8
68
+
69
+
70
+ _METHODS: Final = {
71
+ name: value for name, value in vars(HTTPMethod).items() if isinstance(value, int)
72
+ }
73
+
74
+
75
+ def _name(name: str, what: str) -> str:
76
+ """A trace or metric name, as the SDK checks it (``FPRReservableName``)."""
77
+ if not isinstance(name, str):
78
+ raise TypeError(f"a {what} name must be a str, not {type(name).__name__}")
79
+ stripped = name.strip(" \t")
80
+ if not stripped:
81
+ raise ValueError(f"a {what} name cannot be empty")
82
+ if stripped.startswith("_"):
83
+ raise ValueError(f"invalid {what} name {name!r}: the '_' prefix is reserved")
84
+ if len(stripped) > _MAX_NAME:
85
+ raise ValueError(f"a {what} name can be at most {_MAX_NAME} characters")
86
+ return stripped
87
+
88
+
89
+ def _attribute(name: str, value: str) -> tuple[str, str]:
90
+ """An attribute, as the SDK checks it (``FPRReservableAttributeName``)."""
91
+ if not isinstance(name, str) or not isinstance(value, str):
92
+ raise TypeError("attribute names and values are str")
93
+ stripped = name.strip(" \t")
94
+ if stripped.startswith(_RESERVED_ATTRIBUTE_PREFIXES):
95
+ raise ValueError(
96
+ f"invalid attribute name {name!r}: the prefixes firebase_, google_ and "
97
+ "ga_ are reserved"
98
+ )
99
+ if not stripped:
100
+ raise ValueError("an attribute name cannot be empty")
101
+ if not _ATTRIBUTE_NAME.match(stripped):
102
+ raise ValueError(
103
+ f"invalid attribute name {name!r}: letters, digits and underscores only"
104
+ )
105
+ if len(stripped) > _MAX_ATTRIBUTE_NAME:
106
+ raise ValueError(
107
+ f"an attribute name can be at most {_MAX_ATTRIBUTE_NAME} characters"
108
+ )
109
+ if not value:
110
+ raise ValueError("an attribute value cannot be empty")
111
+ if len(value) > _MAX_ATTRIBUTE_VALUE:
112
+ raise ValueError(
113
+ f"an attribute value can be at most {_MAX_ATTRIBUTE_VALUE} characters"
114
+ )
115
+ return stripped, value
116
+
117
+
118
+ class _Attributable:
119
+ """Custom attributes, shared by ``Trace`` and ``HTTPMetric``."""
120
+
121
+ _native: ObjCObject | None
122
+
123
+ @property
124
+ def active(self) -> bool:
125
+ """``False`` when the SDK made nothing (data collection is off): then
126
+ every method does nothing."""
127
+ return self._native is not None
128
+
129
+ @property
130
+ def native(self) -> ObjCObject | None:
131
+ """The native object, or ``None`` when inactive."""
132
+ return self._native
133
+
134
+ @property
135
+ def attributes(self) -> dict[str, str]:
136
+ """The custom attributes."""
137
+ if self._native is None:
138
+ return {}
139
+ return dict(to_python(self._native.attributes) or {})
140
+
141
+ def put_attribute(self, name: str, value: str) -> None:
142
+ """Set a custom attribute (at most 5), to filter by in the console.
143
+
144
+ Args:
145
+ name: up to 40 letters, digits and underscores (the prefixes
146
+ ``firebase_``, ``google_`` and ``ga_`` are reserved).
147
+ value: 1 to 100 characters.
148
+
149
+ Raises:
150
+ ValueError: an invalid name or value, or a sixth attribute.
151
+ """
152
+ name, value = _attribute(name, value)
153
+ if self._native is None:
154
+ return
155
+ attributes = self.attributes
156
+ if name not in attributes and len(attributes) >= _MAX_ATTRIBUTES:
157
+ raise ValueError(f"at most {_MAX_ATTRIBUTES} custom attributes")
158
+ self._native.setValue_forAttribute_(value, name)
159
+
160
+ def get_attribute(self, name: str) -> str | None:
161
+ """A custom attribute's value, or ``None``.
162
+
163
+ Args:
164
+ name: the attribute's name.
165
+ """
166
+ if self._native is None:
167
+ return None
168
+ value = self._native.valueForAttribute_(name)
169
+ return None if value is None else str(value)
170
+
171
+ def remove_attribute(self, name: str) -> None:
172
+ """Remove a custom attribute.
173
+
174
+ Args:
175
+ name: the attribute's name.
176
+ """
177
+ if self._native is not None:
178
+ self._native.removeAttribute_(name)
179
+
180
+
181
+ class _Timed(_Attributable):
182
+ """Start and stop, once each, and the ``with`` statement."""
183
+
184
+ _state: str = "new" # "new", "started", "stopped"
185
+
186
+ def _what(self) -> str:
187
+ raise NotImplementedError
188
+
189
+ def start(self) -> None:
190
+ """Start measuring.
191
+
192
+ Raises:
193
+ RuntimeError: it was already started.
194
+ """
195
+ if self._state != "new":
196
+ raise RuntimeError(f"the {self._what()} was already started")
197
+ self._state = "started"
198
+ if self._native is not None:
199
+ self._native.start()
200
+
201
+ def stop(self) -> None:
202
+ """Stop measuring, and send it.
203
+
204
+ Raises:
205
+ RuntimeError: it is not running.
206
+ """
207
+ if self._state != "started":
208
+ raise RuntimeError(f"the {self._what()} is not running")
209
+ self._state = "stopped"
210
+ if self._native is not None:
211
+ self._native.stop()
212
+
213
+ @property
214
+ def running(self) -> bool:
215
+ """``True`` between ``start`` and ``stop``."""
216
+ return self._state == "started"
217
+
218
+ def __enter__(self) -> Self:
219
+ if self._state == "new":
220
+ self.start()
221
+ return self
222
+
223
+ def __exit__(
224
+ self,
225
+ kind: type[BaseException] | None,
226
+ exception: BaseException | None,
227
+ tb: TracebackType | None,
228
+ ) -> None:
229
+ if self._state == "started":
230
+ self.stop()
231
+
232
+
233
+ class Trace(_Timed):
234
+ """A custom code trace: the time between ``start`` and ``stop``, with your
235
+ own metrics (counters) and attributes. Get it from ``Performance``.
236
+
237
+ Use it with ``with`` to start and stop it::
238
+
239
+ with Performance.performance().trace("checkout") as trace:
240
+ trace.increment_metric("items", 3)
241
+
242
+ Args:
243
+ native: the native ``FIRTrace``, or ``None`` (inactive).
244
+ name: the trace's name.
245
+ """
246
+
247
+ def __init__(self, native: ObjCObject | None, name: str) -> None:
248
+ self._native = native
249
+ self._name = name
250
+ self._state = "new"
251
+
252
+ def _what(self) -> str:
253
+ return f"trace {self._name!r}"
254
+
255
+ @property
256
+ def name(self) -> str:
257
+ """The trace's name."""
258
+ return self._name
259
+
260
+ def _metric(self, name: str) -> str:
261
+ metric = _name(name, "metric")
262
+ if self._state != "started":
263
+ raise RuntimeError(f"start the {self._what()} before changing its metrics")
264
+ return metric
265
+
266
+ def increment_metric(self, name: str, by: int = 1) -> None:
267
+ """Add to a metric (a metric starts at 0).
268
+
269
+ Args:
270
+ name: the metric's name (as for trace names).
271
+ by: the amount to add (negative to subtract).
272
+
273
+ Raises:
274
+ ValueError: an invalid name.
275
+ RuntimeError: the trace is not running.
276
+ """
277
+ metric = self._metric(name)
278
+ if self._native is not None:
279
+ self._native.incrementMetric_byInt_(metric, _int64(by))
280
+
281
+ def set_metric(self, name: str, value: int) -> None:
282
+ """Set a metric.
283
+
284
+ Args:
285
+ name: the metric's name.
286
+ value: the value.
287
+
288
+ Raises:
289
+ ValueError: an invalid name.
290
+ RuntimeError: the trace is not running.
291
+ """
292
+ metric = self._metric(name)
293
+ if self._native is not None:
294
+ self._native.setIntValue_forMetric_(_int64(value), metric)
295
+
296
+ def get_metric(self, name: str) -> int:
297
+ """A metric's value (0 if it was never set).
298
+
299
+ Args:
300
+ name: the metric's name.
301
+ """
302
+ if self._native is None:
303
+ return 0
304
+ return int(self._native.valueForIntMetric_(name.strip(" \t")))
305
+
306
+ def __repr__(self) -> str:
307
+ return f"Trace({self._name!r}, {self._state})"
308
+
309
+
310
+ def _int64(value: int) -> int:
311
+ if isinstance(value, bool) or not isinstance(value, int):
312
+ raise TypeError(f"metric values are int, not {type(value).__name__}")
313
+ if not -_INT64 <= value < _INT64:
314
+ raise ValueError("metric values must fit in 64 bits")
315
+ return value
316
+
317
+
318
+ class HTTPMetric(_Timed):
319
+ """A network request you measure yourself (for requests made from Python,
320
+ which the SDK does not see). Start it before sending the request, set the
321
+ response fields, then stop it.
322
+
323
+ Args:
324
+ url: the request's ``http`` or ``https`` URL.
325
+ method: an ``HTTPMethod``.
326
+
327
+ Raises:
328
+ ValueError: not an ``http(s)`` URL, or an unknown method.
329
+ """
330
+
331
+ def __init__(self, url: str, method: int = HTTPMethod.GET) -> None:
332
+ parts = urlsplit(url)
333
+ if parts.scheme not in ("http", "https") or not parts.netloc:
334
+ raise ValueError(f"an HTTP metric needs an http(s) URL, not {url!r}")
335
+ if method not in _METHODS.values():
336
+ raise ValueError(f"unknown HTTP method {method!r}: use HTTPMethod")
337
+ self._url = url
338
+ self._state = "new"
339
+ native_url = objc_class("NSURL").URLWithString_(url[:_MAX_URL])
340
+ self._native = (
341
+ objc_class("FIRHTTPMetric")
342
+ .alloc()
343
+ .initWithURL_HTTPMethod_(native_url, method)
344
+ )
345
+
346
+ def _what(self) -> str:
347
+ return f"HTTP metric for {self._url!r}"
348
+
349
+ @property
350
+ def url(self) -> str:
351
+ """The request's URL."""
352
+ return self._url
353
+
354
+ def _get(self, name: str, default: Any) -> Any:
355
+ return default if self._native is None else getattr(self._native, name)
356
+
357
+ def _set(self, name: str, value: Any) -> None:
358
+ if self._native is not None:
359
+ setattr(self._native, name, value)
360
+
361
+ @property
362
+ def response_code(self) -> int:
363
+ """The HTTP status code (set it before ``stop``)."""
364
+ return int(self._get("responseCode", 0))
365
+
366
+ @response_code.setter
367
+ def response_code(self, code: int) -> None:
368
+ self._set("responseCode", int(code))
369
+
370
+ @property
371
+ def request_payload_size(self) -> int:
372
+ """The request body's size in bytes."""
373
+ return int(self._get("requestPayloadSize", 0))
374
+
375
+ @request_payload_size.setter
376
+ def request_payload_size(self, size: int) -> None:
377
+ self._set("requestPayloadSize", int(size))
378
+
379
+ @property
380
+ def response_payload_size(self) -> int:
381
+ """The response body's size in bytes."""
382
+ return int(self._get("responsePayloadSize", 0))
383
+
384
+ @response_payload_size.setter
385
+ def response_payload_size(self, size: int) -> None:
386
+ self._set("responsePayloadSize", int(size))
387
+
388
+ @property
389
+ def response_content_type(self) -> str | None:
390
+ """The response's ``Content-Type``, for example ``"application/json"``."""
391
+ value = self._get("responseContentType", None)
392
+ return None if value is None else str(value)
393
+
394
+ @response_content_type.setter
395
+ def response_content_type(self, content_type: str | None) -> None:
396
+ self._set("responseContentType", content_type)
397
+
398
+ def __repr__(self) -> str:
399
+ return f"HTTPMetric({self._url!r}, {self._state})"
400
+
401
+
402
+ class Performance:
403
+ """Performance Monitoring. Get it with ``Performance.performance()``.
404
+
405
+ Args:
406
+ native: the native ``FIRPerformance``.
407
+ """
408
+
409
+ _shared: ClassVar[Performance | None] = None
410
+
411
+ def __init__(self, native: ObjCObject) -> None:
412
+ self._native = native
413
+
414
+ @classmethod
415
+ def performance(cls) -> Performance:
416
+ """The shared ``Performance``."""
417
+ if cls._shared is None:
418
+ cls._shared = cls(objc_class("FIRPerformance").sharedInstance())
419
+ return cls._shared
420
+
421
+ @property
422
+ def native(self) -> ObjCObject:
423
+ """The ``FIRPerformance``."""
424
+ return self._native
425
+
426
+ @property
427
+ def data_collection_enabled(self) -> bool:
428
+ """Collect and send data (custom traces too). Setting it is kept across
429
+ launches; to start with it off, set
430
+ ``firebase_performance_collection_enabled`` to ``NO`` in ``Info.plist``."""
431
+ value = self._native.isDataCollectionEnabled
432
+ return bool(value() if callable(value) else value)
433
+
434
+ @data_collection_enabled.setter
435
+ def data_collection_enabled(self, enabled: bool) -> None:
436
+ self._native.setDataCollectionEnabled_(bool(enabled))
437
+
438
+ @property
439
+ def instrumentation_enabled(self) -> bool:
440
+ """Measure app start, screens and ``NSURLSession`` requests automatically.
441
+ Takes effect at the next launch; ``firebase_performance_instrumentation_enabled``
442
+ in ``Info.plist`` sets it at build time."""
443
+ value = self._native.isInstrumentationEnabled
444
+ return bool(value() if callable(value) else value)
445
+
446
+ @instrumentation_enabled.setter
447
+ def instrumentation_enabled(self, enabled: bool) -> None:
448
+ self._native.setInstrumentationEnabled_(bool(enabled))
449
+
450
+ def trace(self, name: str) -> Trace:
451
+ """A new trace, not started (use ``with``, or ``start()`` / ``stop()``).
452
+
453
+ Args:
454
+ name: 1 to 100 characters, not starting with ``_``.
455
+
456
+ Returns:
457
+ A ``Trace`` (inactive when data collection is off).
458
+
459
+ Raises:
460
+ ValueError: an invalid name.
461
+ RuntimeError: Firebase is not configured yet (the SDK would abort
462
+ the app).
463
+ """
464
+ checked = _name(name, "trace")
465
+ if objc_class("FIRApp").defaultApp() is None:
466
+ raise RuntimeError(
467
+ "configure Firebase (core.configure()) before making traces"
468
+ )
469
+ return Trace(self._native.traceWithName_(checked), checked)
470
+
471
+ def start_trace(self, name: str) -> Trace:
472
+ """A new trace, already started.
473
+
474
+ Args:
475
+ name: as for ``trace``.
476
+
477
+ Returns:
478
+ The running ``Trace``.
479
+
480
+ Raises:
481
+ ValueError: an invalid name.
482
+ RuntimeError: Firebase is not configured yet.
483
+ """
484
+ trace = self.trace(name)
485
+ trace.start()
486
+ return trace
File without changes