feat(server): deliver push without a Firebase project

Every notification depended on Firebase Cloud Messaging, so a missing
Firebase project, which is the current state, meant no notification could be
delivered on any platform. Web Push and token-based Apple Push are now first
class transports alongside FCM, chosen per registered device, and a scheduled
Cloudflare Worker drain retries an outbox so a provider outage delays rather
than drops a message.
This commit is contained in:
Yun Chan 2026-09-16 23:24:44 +09:00
parent 5aa268970a
commit bb0e54dcee
13 changed files with 1412 additions and 41 deletions

View file

@ -1,9 +1,17 @@
// server/cloudflare-worker/src/index.ts
// D3RO Voice — Global Cloudflare Edge Gateway & Proxy Worker
import { drainPushDispatches } from './push-drain.ts'
export interface Env {
BACKEND_ORIGIN: string
SERVICE_NAME?: string
/** Supabase project base URL, e.g. https://<ref>.supabase.co */
SUPABASE_URL?: string
/** Supabase service-role key (secret). Used only for the scheduled drain. */
SUPABASE_SERVICE_ROLE_KEY?: string
/** Optional drain batch size, 1-100 (default 20). */
PUSH_DRAIN_BATCH_LIMIT?: string
}
const CORS_HEADERS: Record<string, string> = {
@ -93,4 +101,26 @@ export default {
)
}
},
// Cron trigger: drain the Supabase push outbox. Nothing else in the
// repository scheduled this, so transactionally enqueued notifications
// (team invites, transcription completion, billing) never left the queue.
async scheduled(
_event: unknown,
env: Env,
ctx: { waitUntil(promise: Promise<unknown>): void },
): Promise<void> {
ctx.waitUntil(drainAndLog(env))
},
}
async function drainAndLog(env: Env): Promise<void> {
const result = await drainPushDispatches(env)
if (result.ok) {
console.log(
`[push-drain] claimed=${result.claimed ?? 0} completed=${result.completed ?? 0} pending=${result.pending ?? 0}`,
)
} else {
console.error(`[push-drain] failed status=${result.status} error=${result.error ?? 'unknown'}`)
}
}

View file

@ -0,0 +1,69 @@
// server/cloudflare-worker/src/push-drain.test.ts
import { drainPushDispatches, resolveBatchLimit } from './push-drain.ts'
function assert(condition: boolean, message: string): asserts condition {
if (!condition) throw new Error(message)
}
const env = { SUPABASE_URL: 'https://example.supabase.co', SUPABASE_SERVICE_ROLE_KEY: 'x'.repeat(40) }
function jsonResponse(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
})
}
Deno.test('batch limit is clamped to the edge function contract', () => {
assert(resolveBatchLimit(undefined) === 20, 'default is 20')
assert(resolveBatchLimit('5') === 5, 'explicit value is used')
assert(resolveBatchLimit('9999') === 100, 'upper bound is 100')
assert(resolveBatchLimit('0') === 20, 'zero falls back to the default')
assert(resolveBatchLimit('abc') === 20, 'garbage falls back to the default')
})
Deno.test('drain fails closed without configuration', async () => {
const result = await drainPushDispatches({}, () => {
throw new Error('must not be called')
})
assert(result.ok === false, 'not ok')
assert(result.error === 'push_drain_not_configured', 'clear configuration error')
assert(result.status === 503, 'service unavailable')
})
Deno.test('drain posts to the drain endpoint with the service role bearer', async () => {
const calls: Array<{ url: string; init: RequestInit }> = []
const fetchImpl = ((url: string | URL | Request, init?: RequestInit) => {
calls.push({ url: String(url), init: init ?? {} })
return Promise.resolve(jsonResponse(200, { claimed: 3, completed: 2, pending: 1 }))
}) as unknown as typeof fetch
const result = await drainPushDispatches(env, fetchImpl)
assert(result.ok === true, 'ok')
assert(result.claimed === 3 && result.completed === 2 && result.pending === 1, 'summary parsed')
assert(calls[0].url === 'https://example.supabase.co/functions/v1/send-push?mode=drain&limit=20', 'drain url')
const headers = calls[0].init.headers as Record<string, string>
assert(headers.Authorization === `Bearer ${env.SUPABASE_SERVICE_ROLE_KEY}`, 'service role bearer')
assert(headers['Content-Type'] === 'application/json', 'json content type')
assert(calls[0].init.body === '{}', 'empty json body')
assert(calls[0].init.method === 'POST', 'post method')
})
Deno.test('drain reports upstream failures without throwing', async () => {
const httpFail = ((() => Promise.resolve(new Response('nope', { status: 500 }))) as unknown as typeof fetch)
const result = await drainPushDispatches(env, httpFail)
assert(result.ok === false, 'not ok')
assert(result.error === 'push_drain_http_500', 'http error surfaced')
assert(result.status === 500, 'status surfaced')
const unreachable = (() => Promise.reject(new Error('network'))) as unknown as typeof fetch
const unreachableResult = await drainPushDispatches(env, unreachable)
assert(unreachableResult.error === 'push_drain_unreachable', 'network error surfaced')
})
Deno.test('drain tolerates a malformed success body', async () => {
const fetchImpl = ((() => Promise.resolve(new Response('not-json', { status: 200 }))) as unknown as typeof fetch)
const result = await drainPushDispatches(env, fetchImpl)
assert(result.ok === true, 'ok')
assert(result.claimed === undefined, 'summary left undefined')
})

View file

@ -0,0 +1,84 @@
// server/cloudflare-worker/src/push-drain.ts
// Cloudflare Cron-triggered drain for the Supabase push outbox.
//
// Supabase owns the durable outbox and the send-push Edge Function; nothing in
// the repository scheduled the drain, so transactionally enqueued notifications
// (team invites, transcription completion, billing) never left the queue. This
// worker drains them on a cron schedule.
export interface PushDrainEnv {
SUPABASE_URL?: string
SUPABASE_SERVICE_ROLE_KEY?: string
PUSH_DRAIN_BATCH_LIMIT?: string
}
export interface PushDrainResult {
ok: boolean
status: number
claimed?: number
completed?: number
pending?: number
error?: string
}
const DEFAULT_BATCH_LIMIT = 20
const MAX_BATCH_LIMIT = 100
const REQUEST_TIMEOUT_MS = 30_000
export function resolveBatchLimit(raw: string | undefined): number {
const parsed = Number(raw ?? DEFAULT_BATCH_LIMIT)
if (!Number.isSafeInteger(parsed) || parsed < 1) return DEFAULT_BATCH_LIMIT
return Math.min(parsed, MAX_BATCH_LIMIT)
}
export async function drainPushDispatches(
env: PushDrainEnv,
fetchImpl: typeof fetch = fetch,
): Promise<PushDrainResult> {
const baseUrl = env.SUPABASE_URL?.trim().replace(/\/+$/, '') ?? ''
const serviceRoleKey = env.SUPABASE_SERVICE_ROLE_KEY?.trim() ?? ''
if (!baseUrl || serviceRoleKey.length < 20) {
return { ok: false, status: 503, error: 'push_drain_not_configured' }
}
const limit = resolveBatchLimit(env.PUSH_DRAIN_BATCH_LIMIT)
let response: Response
try {
response = await fetchImpl(
`${baseUrl}/functions/v1/send-push?mode=drain&limit=${limit}`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${serviceRoleKey}`,
'Content-Type': 'application/json',
},
body: '{}',
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
},
)
} catch {
return { ok: false, status: 502, error: 'push_drain_unreachable' }
}
if (!response.ok) {
return { ok: false, status: response.status, error: `push_drain_http_${response.status}` }
}
let body: Record<string, unknown> = {}
try {
const parsed = await response.json()
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
body = parsed as Record<string, unknown>
}
} catch {
body = {}
}
return {
ok: true,
status: response.status,
claimed: typeof body.claimed === 'number' ? body.claimed : undefined,
completed: typeof body.completed === 'number' ? body.completed : undefined,
pending: typeof body.pending === 'number' ? body.pending : undefined,
}
}

View file

@ -5,6 +5,14 @@ compatibility_date = "2024-04-01"
[vars]
BACKEND_ORIGIN = "http://192.168.0.39:5050"
SERVICE_NAME = "D3RO Voice Cloud Gateway"
# Supabase project base URL for the scheduled push-outbox drain.
# SUPABASE_URL = "https://<project-ref>.supabase.co"
# PUSH_DRAIN_BATCH_LIMIT = "20"
# Scheduled drain of the Supabase push outbox (every minute).
# Requires the secret: wrangler secret put SUPABASE_SERVICE_ROLE_KEY
[triggers]
crons = ["* * * * *"]
# Cloudflare Custom Domain / Route Binding (선택 시 활성화)
# routes = [