Skip to content

change(fcm): Remove deprecated send_all() and send_multicast() APIs #890

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 0 additions & 122 deletions firebase_admin/_gapic_utils.py

This file was deleted.

118 changes: 0 additions & 118 deletions firebase_admin/messaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,16 @@
from typing import Any, Callable, Dict, List, Optional, cast
import concurrent.futures
import json
import warnings
import asyncio
import logging
import requests
import httpx

from googleapiclient import http
from googleapiclient import _auth

import firebase_admin
from firebase_admin import (
_http_client,
_messaging_encoder,
_messaging_utils,
_gapic_utils,
_utils,
exceptions,
App
Expand Down Expand Up @@ -72,8 +67,6 @@
'WebpushNotificationAction',

'send',
'send_all',
'send_multicast',
'send_each',
'send_each_async',
'send_each_for_multicast',
Expand Down Expand Up @@ -246,64 +239,6 @@ def send_each_for_multicast(multicast_message, dry_run=False, app=None):
) for token in multicast_message.tokens]
return _get_messaging_service(app).send_each(messages, dry_run)

def send_all(messages, dry_run=False, app=None):
"""Sends the given list of messages via Firebase Cloud Messaging as a single batch.

If the ``dry_run`` mode is enabled, the message will not be actually delivered to the
recipients. Instead, FCM performs all the usual validations and emulates the send operation.

Args:
messages: A list of ``messaging.Message`` instances.
dry_run: A boolean indicating whether to run the operation in dry run mode (optional).
app: An App instance (optional).

Returns:
BatchResponse: A ``messaging.BatchResponse`` instance.

Raises:
FirebaseError: If an error occurs while sending the message to the FCM service.
ValueError: If the input arguments are invalid.

send_all() is deprecated. Use send_each() instead.
"""
warnings.warn('send_all() is deprecated. Use send_each() instead.', DeprecationWarning)
return _get_messaging_service(app).send_all(messages, dry_run)

def send_multicast(multicast_message, dry_run=False, app=None):
"""Sends the given mutlicast message to all tokens via Firebase Cloud Messaging (FCM).

If the ``dry_run`` mode is enabled, the message will not be actually delivered to the
recipients. Instead, FCM performs all the usual validations and emulates the send operation.

Args:
multicast_message: An instance of ``messaging.MulticastMessage``.
dry_run: A boolean indicating whether to run the operation in dry run mode (optional).
app: An App instance (optional).

Returns:
BatchResponse: A ``messaging.BatchResponse`` instance.

Raises:
FirebaseError: If an error occurs while sending the message to the FCM service.
ValueError: If the input arguments are invalid.

send_multicast() is deprecated. Use send_each_for_multicast() instead.
"""
warnings.warn('send_multicast() is deprecated. Use send_each_for_multicast() instead.',
DeprecationWarning)
if not isinstance(multicast_message, MulticastMessage):
raise ValueError('Message must be an instance of messaging.MulticastMessage class.')
messages = [Message(
data=multicast_message.data,
notification=multicast_message.notification,
android=multicast_message.android,
webpush=multicast_message.webpush,
apns=multicast_message.apns,
fcm_options=multicast_message.fcm_options,
token=token
) for token in multicast_message.tokens]
return _get_messaging_service(app).send_all(messages, dry_run)

def subscribe_to_topic(tokens, topic, app=None):
"""Subscribes a list of registration tokens to an FCM topic.

Expand Down Expand Up @@ -472,7 +407,6 @@ def __init__(self, app: App) -> None:
self._client = _http_client.JsonHttpClient(credential=self._credential, timeout=timeout)
self._async_client = _http_client.HttpxAsyncClient(
credential=self._credential, timeout=timeout)
self._build_transport = _auth.authorized_http

@classmethod
def encode_message(cls, message):
Expand Down Expand Up @@ -555,45 +489,6 @@ async def send_data(data):
message='Unknown error while making remote service calls: {0}'.format(error),
cause=error)


def send_all(self, messages, dry_run=False):
"""Sends the given messages to FCM via the batch API."""
if not isinstance(messages, list):
raise ValueError('messages must be a list of messaging.Message instances.')
if len(messages) > 500:
raise ValueError('messages must not contain more than 500 elements.')

responses = []

def batch_callback(_, response, error):
exception = None
if error:
exception = self._handle_batch_error(error)
send_response = SendResponse(response, exception)
responses.append(send_response)

batch = http.BatchHttpRequest(
callback=batch_callback, batch_uri=_MessagingService.FCM_BATCH_URL)
transport = self._build_transport(self._credential)
for message in messages:
body = json.dumps(self._message_data(message, dry_run))
req = http.HttpRequest(
http=transport,
postproc=self._postproc,
uri=self._fcm_url,
method='POST',
body=body,
headers=self._fcm_headers
)
batch.add(req)

try:
batch.execute()
except Exception as error:
raise self._handle_batch_error(error)
else:
return BatchResponse(responses)

def make_topic_management_request(self, tokens, topic, operation):
"""Invokes the IID service for topic management functionality."""
if isinstance(tokens, str):
Expand Down Expand Up @@ -670,11 +565,6 @@ def _handle_iid_error(self, error):

return _utils.handle_requests_error(error, msg)

def _handle_batch_error(self, error):
"""Handles errors received from the googleapiclient while making batch requests."""
return _gapic_utils.handle_platform_error_from_googleapiclient(
error, _MessagingService._build_fcm_error_googleapiclient)

def close(self) -> None:
asyncio.run(self._async_client.aclose())

Expand All @@ -700,14 +590,6 @@ def _build_fcm_error_httpx(
message, cause=error, http_response=error.response) if exc_type else None
return exc_type(message, cause=error) if exc_type else None


@classmethod
def _build_fcm_error_googleapiclient(cls, error, message, error_dict, http_response):
"""Parses an error response from the FCM API and creates a FCM-specific exception if
appropriate."""
exc_type = cls._build_fcm_error(error_dict)
return exc_type(message, cause=error, http_response=http_response) if exc_type else None

@classmethod
def _build_fcm_error(
cls,
Expand Down
65 changes: 0 additions & 65 deletions integration/test_messaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,71 +149,6 @@ def test_send_each_for_multicast():
assert response.exception is not None
assert response.message_id is None

@pytest.mark.skip(reason="Replaced with test_send_each")
def test_send_all():
messages = [
messaging.Message(
topic='foo-bar', notification=messaging.Notification('Title', 'Body')),
messaging.Message(
topic='foo-bar', notification=messaging.Notification('Title', 'Body')),
messaging.Message(
token='not-a-token', notification=messaging.Notification('Title', 'Body')),
]

batch_response = messaging.send_all(messages, dry_run=True)

assert batch_response.success_count == 2
assert batch_response.failure_count == 1
assert len(batch_response.responses) == 3

response = batch_response.responses[0]
assert response.success is True
assert response.exception is None
assert re.match('^projects/.*/messages/.*$', response.message_id)

response = batch_response.responses[1]
assert response.success is True
assert response.exception is None
assert re.match('^projects/.*/messages/.*$', response.message_id)

response = batch_response.responses[2]
assert response.success is False
assert isinstance(response.exception, exceptions.InvalidArgumentError)
assert response.message_id is None

@pytest.mark.skip(reason="Replaced with test_send_each_500")
def test_send_all_500():
messages = []
for msg_number in range(500):
topic = 'foo-bar-{0}'.format(msg_number % 10)
messages.append(messaging.Message(topic=topic))

batch_response = messaging.send_all(messages, dry_run=True)

assert batch_response.success_count == 500
assert batch_response.failure_count == 0
assert len(batch_response.responses) == 500
for response in batch_response.responses:
assert response.success is True
assert response.exception is None
assert re.match('^projects/.*/messages/.*$', response.message_id)

@pytest.mark.skip(reason="Replaced with test_send_each_for_multicast")
def test_send_multicast():
multicast = messaging.MulticastMessage(
notification=messaging.Notification('Title', 'Body'),
tokens=['not-a-token', 'also-not-a-token'])

batch_response = messaging.send_multicast(multicast)

assert batch_response.success_count == 0
assert batch_response.failure_count == 2
assert len(batch_response.responses) == 2
for response in batch_response.responses:
assert response.success is False
assert response.exception is not None
assert response.message_id is None

def test_subscribe():
resp = messaging.subscribe_to_topic(_REGISTRATION_TOKEN, 'mock-topic')
assert resp.success_count + resp.failure_count == 1
Expand Down
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ respx == 0.22.0

cachecontrol >= 0.12.14
google-api-core[grpc] >= 1.22.1, < 3.0.0dev; platform.python_implementation != 'PyPy'
google-api-python-client >= 1.7.8
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's include this change in the release notes, as this affects the bundle size

google-cloud-firestore >= 2.19.0; platform.python_implementation != 'PyPy'
google-cloud-storage >= 1.37.1
pyjwt[crypto] >= 2.5.0
Expand Down
1 change: 0 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
install_requires = [
'cachecontrol>=0.12.14',
'google-api-core[grpc] >= 1.22.1, < 3.0.0dev; platform.python_implementation != "PyPy"',
'google-api-python-client >= 1.7.8',
'google-cloud-firestore>=2.19.0; platform.python_implementation != "PyPy"',
'google-cloud-storage>=1.37.1',
'pyjwt[crypto] >= 2.5.0',
Expand Down
Loading