Repository navigation
Expand file tree
/
Copy pathFcmDevicePushProvider.php
More file actions
275 lines (218 loc) · 11.1 KB
/
Copy pathFcmDevicePushProvider.php
File metadata and controls
275 lines (218 loc) · 11.1 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
<?php
declare(strict_types=1);
namespace App\Services\DevicePushProviders;
use App\Contracts\Services\DevicePushProvider;
use App\Dto\DevicePush;
use App\Dto\DevicePushResult;
use App\Dto\FcmCredentials;
use App\Exceptions\DevicePushCredentialsRejected;
use App\Models\Device;
use DomainException;
use Firebase\JWT\JWT;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Database\QueryException;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Fluent;
use RuntimeException;
/**
* Pushes through Firebase Cloud Messaging's HTTP v1 API, which reaches both platforms: Firebase hands iPhone pushes on
* to APNs with the key uploaded in its console. The service account's key comes from the environment, never the
* repository; without it nothing is pushed. It buys an access token, kept encrypted until shortly before it expires.
*/
final readonly class FcmDevicePushProvider implements DevicePushProvider
{
/**
* Google asks for at least a minute after a rate limit before the next try.
*/
private const int RATE_LIMIT_SECONDS = 60;
public function send(Device $device, DevicePush $push): DevicePushResult
{
$credentials = FcmCredentials::fromConfig();
if (! $credentials instanceof FcmCredentials) {
return DevicePushResult::settled();
}
try {
$accessToken = $this->accessToken($credentials);
if ($accessToken instanceof DevicePushResult) {
return $accessToken;
}
$quotaKey = 'fcm-quota:'.hash('sha256', $credentials->projectId);
foreach ([$quotaKey, $quotaKey.':'.$device->push_token_hash] as $key) {
$seconds = Cache::integer($key, 0) - now()->getTimestamp();
if ($seconds > 0) {
return DevicePushResult::defer($seconds);
}
}
return DB::transaction(function () use ($device, $push, $credentials, $accessToken, $quotaKey): DevicePushResult {
if (! DB::scalar('select pg_try_advisory_xact_lock(hashtextextended(?, 0))', ['device-push:'.$device->id])) {
return DevicePushResult::defer(5);
}
// The unique token hash makes registration changes conflict, but last_used_at can still be written.
$currentDevice = Device::query()->whereKey($device->id)
->where('user_id', $device->user_id)->where('push_token_hash', $device->push_token_hash)
->lock('for key share nowait')->first();
if (! $currentDevice instanceof Device || $currentDevice->push_token === null) {
return DevicePushResult::settled();
}
$response = Http::withToken($accessToken)->timeout(10)
->post("https://fcm.googleapis.com/v1/projects/{$credentials->projectId}/messages:send", ['message' => [
'token' => $currentDevice->push_token,
'notification' => ['title' => $push->title, 'body' => $push->body],
'data' => $push->data,
'android' => ['priority' => 'high', 'ttl' => $push->ttl.'s'],
'apns' => ['headers' => ['apns-expiration' => (string) now()->addSeconds($push->ttl)->getTimestamp()], 'payload' => ['aps' => ['sound' => 'default', ...$push->group === null ? [] : ['thread-id' => $push->group]]]],
]]);
if (in_array('UNREGISTERED', $response->collect('error.details')->pluck('errorCode')->all(), true)) {
// Only the token that was sent, in case the phone registered a new one meanwhile.
Device::query()->whereKey($currentDevice->id)->where('push_token_hash', $currentDevice->push_token_hash)
->update(['push_token_hash' => null, 'push_token' => null, 'push_platform' => null]);
return DevicePushResult::settled();
}
if (in_array('THIRD_PARTY_AUTH_ERROR', $response->collect('error.details')->pluck('errorCode')->all(), true)) {
$this->reportFailure(new RuntimeException('FCM APNs credentials were rejected (THIRD_PARTY_AUTH_ERROR).'));
return DevicePushResult::settled();
}
if ($response->unauthorized()) {
$cacheKey = $this->accessTokenKey($credentials);
Cache::lock($cacheKey.':lock', 30)->block(15, function () use ($cacheKey, $accessToken): void {
$cached = $this->cachedAccessToken($cacheKey);
if ($cached === null || $cached === $accessToken) {
Cache::forget($cacheKey);
}
});
}
if ($response->status() === 429) {
$violations = $response->collect('error.details')->where('@type', 'type.googleapis.com/google.rpc.QuotaFailure')
->pluck('violations')->flatten(1);
if ($violations->isNotEmpty() && $violations->every(fn (array $violation): bool => new Fluent($violation)->string('subject')->contains('/registrations/'))) {
$quotaKey .= ':'.$currentDevice->push_token_hash;
}
$seconds = $this->retryAfterSeconds($response) ?? self::RATE_LIMIT_SECONDS;
Cache::lock($quotaKey.':lock', 5)->block(2, function () use ($quotaKey, $seconds): void {
$retryAt = max(Cache::integer($quotaKey, 0), now()->getTimestamp() + $seconds);
Cache::put($quotaKey, $retryAt, $retryAt - now()->getTimestamp());
});
}
if (! $response->serverError() && ! $response->unauthorized() && $response->status() !== 429) {
if ($response->clientError()) {
$this->reportFailure(new RuntimeException("FCM send request failed (HTTP {$response->status()})."));
}
return DevicePushResult::settled();
}
return DevicePushResult::retry($this->retryAfterSeconds($response));
});
} catch (QueryException $exception) {
throw_if($exception->getCode() !== '55P03', $exception);
return DevicePushResult::defer(5);
} catch (ConnectionException) {
return DevicePushResult::retry();
} catch (DecryptException) {
$this->reportFailure(new RuntimeException('FCM device token could not be decrypted.'));
return DevicePushResult::settled();
}
}
private function reportFailure(RuntimeException $exception): void
{
report_if(Cache::add('fcm-error:'.hash('sha256', $exception->getMessage()), true, now()->addMinutes(5)), $exception);
}
private function accessTokenKey(FcmCredentials $credentials): string
{
return 'fcm-access-token:'.hash('sha256', implode("\0", [
$credentials->projectId, $credentials->clientEmail, $credentials->privateKey, $credentials->tokenUri,
]));
}
/**
* What Google asked us to wait before the next try, in seconds. A rate limit waits a minute even without a header.
*/
private function retryAfterSeconds(Response $response): ?int
{
$header = mb_trim($response->header('Retry-After'));
$seconds = ctype_digit($header) ? (int) $header : $this->dateSeconds($header);
if ($response->status() === 429) {
return max($seconds ?? 0, self::RATE_LIMIT_SECONDS);
}
return $seconds;
}
private function dateSeconds(string $header): ?int
{
$timestamp = strtotime($header);
return $timestamp === false ? null : max(0, $timestamp - now()->getTimestamp());
}
/**
* The access token, or a retry result when Google temporarily cannot hand one out.
*/
private function accessToken(FcmCredentials $credentials): string|DevicePushResult
{
$cacheKey = $this->accessTokenKey($credentials);
$cached = $this->cachedAccessToken($cacheKey);
if ($cached !== null) {
return $cached;
}
$lock = Cache::lock($cacheKey.':lock', 30);
if (! $lock->get()) {
return DevicePushResult::defer(5);
}
try {
$cached = $this->cachedAccessToken($cacheKey);
if ($cached !== null) {
return $cached;
}
try {
$assertion = JWT::encode([
'iss' => $credentials->clientEmail,
'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
'aud' => $credentials->tokenUri,
'iat' => now()->getTimestamp(),
'exp' => now()->addHour()->getTimestamp(),
], $credentials->privateKey, 'RS256');
} catch (DomainException) {
$exception = new DevicePushCredentialsRejected('FCM OAuth credentials could not sign a request.');
$this->reportFailure($exception);
throw $exception;
}
$response = Http::asForm()->timeout(10)->post($credentials->tokenUri, [
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $assertion,
]);
if ($response->status() === 429 || ($response->serverError() && $this->retryAfterSeconds($response) > 0)) {
$seconds = $this->retryAfterSeconds($response) ?? self::RATE_LIMIT_SECONDS;
Cache::put($cacheKey, now()->getTimestamp() + $seconds, $seconds);
return DevicePushResult::retry($seconds);
}
if ($response->serverError()) {
return DevicePushResult::retry($this->retryAfterSeconds($response));
}
if (! $response->successful()) {
$exception = new DevicePushCredentialsRejected("FCM OAuth request failed (HTTP {$response->status()}).");
$this->reportFailure($exception);
throw $exception;
}
$token = $response->json('access_token');
assert(is_string($token));
Cache::put($cacheKey, Crypt::encryptString($token), now()->addSeconds($response->fluent()->integer('expires_in', 3600) - 60));
return $token;
} finally {
$lock->release();
}
}
private function cachedAccessToken(string $cacheKey): string|DevicePushResult|null
{
$cached = Cache::get($cacheKey);
if (is_numeric($cached)) {
return DevicePushResult::defer(max(0, (int) $cached - now()->getTimestamp()));
}
if (is_string($cached)) {
try {
return Crypt::decryptString($cached);
} catch (DecryptException) {
return null;
}
}
return null;
}
}