Overview
Automatically renews Gmail push notification watches before they expire. Gmail watches expire after 7 days and must be renewed to continue receiving real-time notifications. This function should be run periodically (e.g., via cron job).Endpoint
Authentication
Requires internal authentication. This endpoint is designed to be called by scheduled jobs (cron) or internal services only.Headers
Internal service authentication tokenFormat:
Bearer {internal_token}Must be
application/jsonExample Request
Response
Success Response
Returns details of renewal operations:Summary message
Number of watches successfully renewed
Number of watches that failed to renew
Detailed results for each watch
Gmail email address
Renewal status: “renewed”, “failed”, “no_tokens”, or “disconnected”
New expiration timestamp (ISO 8601) if renewed successfully
Error message if renewal failed
No Watches to Renew
When no watches are expiring soon:Error Responses
401 Unauthorized
Returned when internal authentication fails.405 Method Not Allowed
Returned when using any HTTP method other than POST.500 Internal Server Error
Watch Fetch Failed
General Error
Processing Flow
1. Expiration Check
Queriesgmail_watches table for watches expiring within 48 hours:
2. Token Resolution
For each expiring watch:- Creates system notification about expiring watch
- Retrieves active OAuth token for the user and Gmail email
- Ensures fresh access token via
ensureFreshAccessToken()
3. Watch Renewal
Calls Gmail API to renew the watch:4. Database Update
Updatesgmail_watches table with new watch metadata:
5. Error Handling
Token Reconnection Required
WhenGmailReconnectRequiredError is caught:
- Deletes the watch from
gmail_watchestable - Creates system notification for user to reconnect
- Marks result as “disconnected”
- Continues processing other watches
API Failures
When Gmail API call fails:- Logs error details
- Creates system notification for user
- Marks result as “failed”
- Continues processing other watches
No Active Tokens
When no OAuth token found:- Creates system notification
- Marks result as “no_tokens”
- Continues processing other watches
Notifications
Watch Expiring (Normal Priority)
Created when renewal process starts:Watch Renewal Failed (High Priority)
Created when renewal fails:Implementation Details
Environment Variables Required
SUPABASE_URL- Supabase project URLSUPABASE_SERVICE_ROLE_KEY- Service role key for database access
Expiration Window
Renews watches that expire within 48 hours (2 days) to provide buffer time for retries.Watch Expiration
Gmail watches expire 7 days after creation. The API returns expiration as Unix timestamp in milliseconds:Database Operations
Fetch Expiring Watches
Update Watch
Delete Watch (on reconnection required)
Error Recovery
Gracefully handles errors without failing the entire batch:- Continues processing remaining watches even if some fail
- Creates user notifications for failures
- Returns detailed results for monitoring
Deployment
Cron Schedule
Recommended schedule: Daily Example using Supabase Edge Functions Cron:Monitoring
Monitor the following:- Renewal success rate - Track
renewed / (renewed + failed) - Failed watches - Alert on
failed > 0 - Function execution - Ensure daily execution
- Token disconnections - Track “disconnected” status results
Retry Logic
Since watches expire in 7 days and renewal starts at 48 hours before expiration, there are multiple chances for retry:- Day 5: First renewal attempt (48 hours before expiration)
- Day 6: Second renewal attempt (24 hours before expiration)
- Day 7: Final renewal attempt (on expiration day)
Best Practices
Scheduling
- Run daily to catch watches expiring within 48 hours
- Run at low-traffic times (e.g., 2 AM) to reduce load
- Use multiple retries with exponential backoff for API failures
Monitoring
- Set up alerts for high failure rates
- Log detailed error messages for debugging
- Track renewal success metrics
- Monitor notification delivery to users
Security
- Use internal authentication tokens
- Restrict endpoint to internal network or specific IPs
- Rotate internal service tokens regularly
- Use service role key for database access (not anon key)
User Communication
- Notify users when watches expire and cannot be renewed
- Provide clear instructions for reconnecting Gmail
- Use appropriate notification priority levels
Related Functions
- auth-callback - Initial watch setup during OAuth
- gmail-webhook - Processes notifications from watches