mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-04 09:06:04 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5181e42b46 | ||
|
|
eb1c914e4a | ||
|
|
b90ad82d90 | ||
|
|
0fa10e4330 |
No files matched your search
@@ -47,6 +47,7 @@ _db_singleton = None
|
||||
EventType = Literal[
|
||||
"banner_reconnecting",
|
||||
"banner_unavailable",
|
||||
"banner_waking",
|
||||
"lyrics_load_failed",
|
||||
"waveform_slow",
|
||||
"waveform_failed",
|
||||
|
||||
@@ -11,9 +11,13 @@ import html
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import smtplib
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from email.message import EmailMessage
|
||||
from email.utils import formataddr
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import NamedTuple, Optional, List
|
||||
from zoneinfo import ZoneInfo
|
||||
@@ -175,29 +179,40 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
|
||||
API_URL = "https://api.postmarkapp.com/email"
|
||||
|
||||
# Seconds to sleep before each retry of a transient failure. Postmark's edge
|
||||
# intermittently answers some us-central1 Cloud Run egress IPs with a bare
|
||||
# nginx HTML 403 (not its JSON error format) — a fresh connection a moment
|
||||
# later often succeeds. Kept short: magic-link sends block the request.
|
||||
# SMTP fallback for when Postmark's API edge blocks us. Since 2026-09-30 the
|
||||
# edge has answered us-central1 Cloud Run egress IPs with a bare nginx HTML
|
||||
# 403 for hours at a time, so retrying the API doesn't help; SMTP is served
|
||||
# by separate infrastructure. Auth = server token as username and password.
|
||||
SMTP_HOST = "smtp.postmarkapp.com"
|
||||
SMTP_PORT = 587
|
||||
SMTP_TIMEOUT = 15
|
||||
MESSAGE_STREAM = "outbound"
|
||||
|
||||
# Seconds to sleep before each retry of a transient failure (429 / 5xx /
|
||||
# connect timeout). Kept short: magic-link sends block the request.
|
||||
RETRY_DELAYS = (1.0, 3.0)
|
||||
|
||||
@staticmethod
|
||||
def _is_transient_failure(response: requests.Response) -> bool:
|
||||
"""True for failures worth retrying: 429, 5xx, or a non-JSON 403.
|
||||
"""True for failures worth retrying against the API: 429 or 5xx."""
|
||||
status = response.status_code
|
||||
return status == 429 or status >= 500
|
||||
|
||||
@staticmethod
|
||||
def _is_edge_block(response: requests.Response) -> bool:
|
||||
"""True for a 403 without a JSON body: an IP-level block at Postmark's edge.
|
||||
|
||||
Postmark's own API errors (bad token, invalid payload, suppressed
|
||||
recipient) come back as JSON and are deterministic, so retrying them
|
||||
would just repeat the same answer. A 403 without a JSON body is an
|
||||
edge/IP-level block, not a verdict on the request itself.
|
||||
recipient) come back as JSON and are verdicts on the request itself; a
|
||||
bare HTML 403 never reached the API, so the message was not accepted and
|
||||
it's safe to resend it over SMTP.
|
||||
"""
|
||||
status = response.status_code
|
||||
if status == 429 or status >= 500:
|
||||
if response.status_code != 403:
|
||||
return False
|
||||
try:
|
||||
response.json()
|
||||
except ValueError:
|
||||
return True
|
||||
if status == 403:
|
||||
try:
|
||||
response.json()
|
||||
except ValueError:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _post_with_retry(self, payload: dict) -> requests.Response:
|
||||
@@ -295,7 +310,20 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
if bcc_emails:
|
||||
payload["Bcc"] = ", ".join(_dedupe_emails(bcc_emails))
|
||||
|
||||
response = self._post_with_retry(payload)
|
||||
try:
|
||||
response = self._post_with_retry(payload)
|
||||
except requests.ConnectTimeout:
|
||||
# Never connected, so Postmark didn't accept it: safe to resend.
|
||||
logger.warning("Postmark API connect timed out on every attempt; falling back to SMTP")
|
||||
return self._send_via_smtp(to_email, subject, html_content, text_content,
|
||||
cc_emails, bcc_emails, sender_email)
|
||||
|
||||
if self._is_edge_block(response):
|
||||
logger.warning(
|
||||
f"Postmark API edge returned HTML 403 for {to_email}; falling back to SMTP"
|
||||
)
|
||||
return self._send_via_smtp(to_email, subject, html_content, text_content,
|
||||
cc_emails, bcc_emails, sender_email)
|
||||
|
||||
if 200 <= response.status_code < 300:
|
||||
cc_info = f" (CC: {', '.join(cc_emails)})" if cc_emails else ""
|
||||
@@ -338,6 +366,58 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
logger.exception("Failed to send email via Postmark")
|
||||
return SendResult(success=False, message_id=None)
|
||||
|
||||
def _send_via_smtp(
|
||||
self,
|
||||
to_email: str,
|
||||
subject: str,
|
||||
html_content: str,
|
||||
text_content: Optional[str],
|
||||
cc_emails: Optional[List[str]],
|
||||
bcc_emails: Optional[List[str]],
|
||||
sender_email: str,
|
||||
) -> SendResult:
|
||||
"""Send through Postmark's SMTP endpoint (used when the API is unreachable).
|
||||
|
||||
SMTP returns no Postmark MessageID and can't report suppressed
|
||||
recipients synchronously (Postmark logs those as bounces instead).
|
||||
"""
|
||||
cc = _dedupe_emails(cc_emails) if cc_emails else []
|
||||
bcc = _dedupe_emails(bcc_emails) if bcc_emails else []
|
||||
try:
|
||||
msg = EmailMessage()
|
||||
msg["From"] = formataddr((self.from_name, sender_email))
|
||||
msg["To"] = to_email
|
||||
msg["Subject"] = subject
|
||||
msg["X-PM-Message-Stream"] = self.MESSAGE_STREAM
|
||||
if cc:
|
||||
msg["Cc"] = ", ".join(cc)
|
||||
if text_content:
|
||||
msg.set_content(text_content)
|
||||
msg.add_alternative(html_content, subtype="html")
|
||||
else:
|
||||
msg.set_content(html_content, subtype="html")
|
||||
|
||||
smtp = smtplib.SMTP(self.SMTP_HOST, self.SMTP_PORT, timeout=self.SMTP_TIMEOUT)
|
||||
try:
|
||||
smtp.starttls(context=ssl.create_default_context())
|
||||
smtp.login(self.server_token, self.server_token)
|
||||
smtp.send_message(msg, to_addrs=[to_email, *cc, *bcc])
|
||||
finally:
|
||||
# A failed QUIT after an accepted send must not fail the send
|
||||
# (a caller retry would then duplicate the email).
|
||||
try:
|
||||
smtp.quit()
|
||||
except (smtplib.SMTPException, OSError):
|
||||
smtp.close()
|
||||
except (smtplib.SMTPException, OSError, ValueError):
|
||||
# ValueError: EmailMessage rejects CR/LF in header values.
|
||||
logger.exception(f"Failed to send email to {to_email} via Postmark SMTP fallback")
|
||||
return SendResult(success=False, message_id=None)
|
||||
|
||||
logger.info(f"Email sent to {to_email} via Postmark SMTP fallback")
|
||||
self.last_message_id = None
|
||||
return SendResult(success=True, message_id=None)
|
||||
|
||||
|
||||
# Query params that carry single-use auth/capability tokens (magic-link sign-in,
|
||||
# lyrics/instrumental review access, referral codes). We persist a redacted copy
|
||||
|
||||
@@ -51,6 +51,15 @@ class TestReportClientEvent:
|
||||
# Query string (may carry tokens) must be stripped before persisting.
|
||||
assert "SECRET" not in doc["url"]
|
||||
|
||||
def test_cold_start_waking_event_accepted(self, client, fresh_limiter_and_db):
|
||||
resp = client.post(
|
||||
"/api/client-events",
|
||||
json=_event(type="banner_waking", detail={"stall_ms": 5000, "since_reachable_ms": None}),
|
||||
)
|
||||
assert resp.status_code == 202
|
||||
(doc,) = fresh_limiter_and_db.collection.return_value.add.call_args[0]
|
||||
assert doc["type"] == "banner_waking"
|
||||
|
||||
def test_unknown_event_type_rejected(self, client):
|
||||
resp = client.post("/api/client-events", json=_event(type="something_else"))
|
||||
assert resp.status_code == 422
|
||||
|
||||
@@ -285,25 +285,101 @@ class TestPostmarkRetry:
|
||||
def provider(self):
|
||||
return PostmarkEmailProvider(server_token="t", from_email="f@e.com")
|
||||
|
||||
def test_html_403_then_success_is_retried(self, provider):
|
||||
"""The prod failure mode: nginx HTML 403 from Postmark's edge, then OK."""
|
||||
@pytest.fixture
|
||||
def mock_smtp(self):
|
||||
with patch("backend.services.email_service.smtplib.SMTP") as smtp_cls:
|
||||
self.smtp = smtp_cls.return_value
|
||||
yield smtp_cls
|
||||
|
||||
def test_html_403_falls_back_to_smtp_without_api_retries(self, provider, mock_smtp):
|
||||
"""The prod failure mode: nginx HTML 403 from Postmark's edge lasts hours."""
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.side_effect = [self._response(403, json_body=False), self._response(200)]
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is True
|
||||
assert result.message_id == "abc"
|
||||
assert mock_post.call_count == 2
|
||||
self.mock_sleep.assert_called_once_with(1.0)
|
||||
assert result.message_id is None
|
||||
assert mock_post.call_count == 1
|
||||
self.mock_sleep.assert_not_called()
|
||||
mock_smtp.assert_called_once_with("smtp.postmarkapp.com", 587, timeout=15)
|
||||
self.smtp.starttls.assert_called_once()
|
||||
self.smtp.login.assert_called_once_with("t", "t")
|
||||
msg = self.smtp.send_message.call_args.args[0]
|
||||
assert msg["To"] == "user@example.com"
|
||||
assert msg["From"] == "Nomad Karaoke <f@e.com>"
|
||||
assert msg["X-PM-Message-Stream"] == "outbound"
|
||||
assert self.smtp.send_message.call_args.kwargs["to_addrs"] == ["user@example.com"]
|
||||
|
||||
def test_html_403_gives_up_after_all_attempts(self, provider):
|
||||
def test_smtp_fallback_builds_multipart_with_cc_bcc(self, provider, mock_smtp):
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
result = provider.send_email_detailed(
|
||||
to_email="user@example.com",
|
||||
subject="Ünïcode subject",
|
||||
html_content="<p>hi</p>",
|
||||
text_content="hi",
|
||||
cc_emails=["cc@example.com", "CC@example.com"],
|
||||
bcc_emails=["bcc@example.com"],
|
||||
from_email_override="tenant@example.com",
|
||||
)
|
||||
|
||||
assert result.success is True
|
||||
msg = self.smtp.send_message.call_args.args[0]
|
||||
assert msg["Cc"] == "cc@example.com"
|
||||
assert msg["Bcc"] is None # BCC never appears in headers
|
||||
assert msg["Subject"] == "Ünïcode subject"
|
||||
assert msg["From"] == "Nomad Karaoke <tenant@example.com>"
|
||||
assert msg.get_body(("plain",)).get_content().strip() == "hi"
|
||||
assert msg.get_body(("html",)).get_content().strip() == "<p>hi</p>"
|
||||
assert self.smtp.send_message.call_args.kwargs["to_addrs"] == [
|
||||
"user@example.com", "cc@example.com", "bcc@example.com"
|
||||
]
|
||||
|
||||
def test_smtp_fallback_failure_reports_failure(self, provider, mock_smtp):
|
||||
import smtplib as _smtplib
|
||||
self.smtp.login.side_effect = _smtplib.SMTPAuthenticationError(535, b"bad")
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is False
|
||||
assert mock_post.call_count == 3
|
||||
assert [c.args[0] for c in self.mock_sleep.call_args_list] == [1.0, 3.0]
|
||||
|
||||
def test_smtp_fallback_connection_error_reports_failure(self, provider, mock_smtp):
|
||||
mock_smtp.side_effect = OSError("unreachable")
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is False
|
||||
|
||||
def test_smtp_fallback_rejects_header_injection_without_raising(self, provider, mock_smtp):
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
result = provider.send_email_detailed(
|
||||
to_email="user@example.com", subject="Song\nBcc: evil@example.com", html_content="<p>x</p>"
|
||||
)
|
||||
|
||||
assert result.success is False
|
||||
self.smtp.send_message.assert_not_called()
|
||||
|
||||
def test_quit_failure_after_send_still_reports_success(self, provider, mock_smtp):
|
||||
"""Postmark already accepted the message; a failed QUIT must not trigger a resend."""
|
||||
import smtplib as _smtplib
|
||||
self.smtp.quit.side_effect = _smtplib.SMTPServerDisconnected("gone")
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is True
|
||||
self.smtp.close.assert_called_once()
|
||||
|
||||
def test_smtp_success_clears_stale_message_id(self, provider, mock_smtp):
|
||||
provider.last_message_id = "old"
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
self._send(provider)
|
||||
|
||||
assert provider.last_message_id is None
|
||||
|
||||
@pytest.mark.parametrize("status", [429, 500, 503])
|
||||
def test_rate_limit_and_server_errors_are_retried(self, provider, status):
|
||||
@@ -340,14 +416,15 @@ class TestPostmarkRetry:
|
||||
assert result.success is True
|
||||
assert mock_post.call_count == 2
|
||||
|
||||
def test_connect_timeout_on_every_attempt_fails_cleanly(self, provider):
|
||||
def test_connect_timeout_on_every_attempt_falls_back_to_smtp(self, provider, mock_smtp):
|
||||
import requests as _requests
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.side_effect = _requests.ConnectTimeout("slow")
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is False
|
||||
assert result.success is True
|
||||
assert mock_post.call_count == 3
|
||||
self.smtp.send_message.assert_called_once()
|
||||
|
||||
def test_read_timeout_not_retried_to_avoid_duplicate_send(self, provider):
|
||||
"""Postmark may have accepted the message; it has no idempotency key."""
|
||||
|
||||
+3
-2
@@ -2930,8 +2930,9 @@ POST /api/client-events
|
||||
```
|
||||
|
||||
Unauthenticated, rate-limited (120/min/IP — sized so a many-tab burst from one IP is fully recorded), bot-filtered. The frontend reports every
|
||||
user-visible degraded-service surface: `banner_reconnecting`, `banner_unavailable`
|
||||
(the connectivity banner — reported by `BackendStatusBanner`), `lyrics_load_failed`
|
||||
user-visible degraded-service surface: `banner_reconnecting`, `banner_unavailable`,
|
||||
`banner_waking` (the connectivity banner — reported by `BackendStatusBanner`; `banner_waking`
|
||||
is the calm "starting up our karaoke servers" cold-start state), `lyrics_load_failed`
|
||||
(review page "temporarily unavailable"), `waveform_slow` / `waveform_failed`
|
||||
(Waveforms-mode strips late or missing). Body: `{type, url, job_id?, user_email?,
|
||||
locale, release, detail?}` — `detail` is size-capped server-side (≤12 keys, ≤200
|
||||
|
||||
@@ -1415,6 +1415,20 @@ quota/billing/key errors (not per-minute 429s) skip retries, degrade, and Discor
|
||||
at most once per 6h. (Supersedes the old "Vertex AI Auth" / "global location" notes —
|
||||
the Developer API has no project/location.)
|
||||
|
||||
**Manual (non-Pulumi) changes made 2026-10-02 (admin@nomadkaraoke.com), after v0.262.0
|
||||
deployed and Vertex `request_count` stayed at zero:**
|
||||
- 02:46Z `roles/aiplatform.user` binding for `karaoke-backend` deleted (Pulumi, targeted).
|
||||
- 02:47Z removed cross-project `roles/aiplatform.user` for
|
||||
`aquarius-backend@aquarius-fundraising-mvp.iam.gserviceaccount.com` (zero traffic).
|
||||
- 02:48Z `gcloud services disable aiplatform.googleapis.com generativelanguage.googleapis.com`
|
||||
(no `--force` needed). Re-enable with `gcloud services enable ...` if ever required.
|
||||
- 02:49Z deleted unused restricted API key `98073667-…` ("Generative Language API Key";
|
||||
0 valid requests in 30 days; undelete possible for 30 days via `gcloud services api-keys undelete`).
|
||||
- `gemini-api-key` belongs to AI Studio project `gen-lang-client-0983596166` (number
|
||||
810524901596), billed to "Aquarius Billing". To swap keys: `printf '%s' "$KEY" | gcloud
|
||||
secrets versions add gemini-api-key --project=nomadkaraoke --data-file=-`, then roll the
|
||||
service (any new revision) — jobs pick it up on their next execution.
|
||||
|
||||
### LangChain: REST over gRPC
|
||||
Use `langchain-google-genai` (REST) instead of `langchain-google-vertexai` (gRPC) to avoid silent hangs.
|
||||
|
||||
|
||||
+17
-9
@@ -68,25 +68,33 @@ defense-in-depth beneath the signing-free review path.
|
||||
`Failed to send magic link email to …`.
|
||||
|
||||
**Cause:** a bare nginx HTML 403 (not Postmark's JSON error format) is an edge/IP-level
|
||||
block at `api.postmarkapp.com`, not a token or payload problem. Seen intermittently
|
||||
from `karaoke-backend` (us-central1, shared Cloud Run egress IPs) since 2026-09-30;
|
||||
us-east4 Cloud Run Jobs were unaffected. A JSON 403 (`ErrorCode=10`) is a real bad-token error instead.
|
||||
block at `api.postmarkapp.com`, not a token or payload problem. Seen from
|
||||
`karaoke-backend` and karaoke-decide (us-central1, shared Cloud Run egress IPs) since
|
||||
2026-09-30, in blocks lasting hours (all sends failed 2026-10-02 11:25 UTC onward);
|
||||
us-east4 Cloud Run Jobs were unaffected. IP Allowlisting is OFF in Postmark (checked
|
||||
2026-10-02), so this is Postmark's network firewall — ticket #11562402. A JSON 403
|
||||
(`ErrorCode=10`) is a real bad-token error instead.
|
||||
|
||||
**Mitigation in code:** `PostmarkEmailProvider` retries 429 / 5xx / non-JSON 403 /
|
||||
connect timeouts (backoff 1s, 3s). JSON Postmark errors and read timeouts are not
|
||||
retried (deterministic, or risk of a duplicate send).
|
||||
**Mitigation in code:** on an HTML 403, `PostmarkEmailProvider` immediately re-sends via
|
||||
Postmark SMTP (`smtp.postmarkapp.com:587`, STARTTLS, server token as user+password,
|
||||
`X-PM-Message-Stream: outbound`) — API retries never got past a block. Also falls back
|
||||
when every API attempt hits a connect timeout. 429 / 5xx / connect timeouts are still
|
||||
retried on the API (backoff 1s, 3s). JSON Postmark errors and read timeouts never fall
|
||||
back (deterministic, or risk of a duplicate send). SMTP sends log
|
||||
`Email sent to … via Postmark SMTP fallback` and have no Postmark MessageID; SMTP access
|
||||
must stay enabled on the Postmark server (Server → Settings).
|
||||
|
||||
**Diagnosis:**
|
||||
```bash
|
||||
gcloud logging read 'resource.labels.service_name="karaoke-backend" AND (textPayload:"Postmark returned status" OR textPayload:"Failed to send")' \
|
||||
gcloud logging read 'resource.labels.service_name="karaoke-backend" AND (textPayload:"Postmark returned status" OR textPayload:"Failed to send" OR textPayload:"SMTP")' \
|
||||
--project nomadkaraoke --freshness 2d --limit 50 --format='value(timestamp,textPayload)'
|
||||
```
|
||||
The E2E `waitForEmail` helper now checks `GET /api/admin/users/{email}/emails` on
|
||||
timeout and reports whether the backend sent anything ("backend has NO record…" =
|
||||
server-side send failure; "backend sent N email(s)…" = delivery/testmail problem).
|
||||
|
||||
**If it persists after retries:** contact Postmark support with failure timestamps, or
|
||||
give the backend a static egress IP (Direct VPC egress + Cloud NAT).
|
||||
**If SMTP fallback also fails:** follow up on the Postmark ticket, or give the backend a
|
||||
static egress IP (Direct VPC egress + Cloud NAT).
|
||||
|
||||
## Fast rollback (bad backend deploy)
|
||||
|
||||
|
||||
@@ -6,10 +6,14 @@
|
||||
* and backend calls are addressed with relative "/api/..." URLs.
|
||||
*/
|
||||
|
||||
import { apiFetch, BackendUnavailableError, __backendHealthProbe } from '@/lib/api'
|
||||
import { apiFetch, BackendUnavailableError, __backendHealthProbe, __backendPrewarm } from '@/lib/api'
|
||||
import {
|
||||
getBackendStatus,
|
||||
configureHealthProbe,
|
||||
configurePrewarm,
|
||||
markBackendReachable,
|
||||
prewarmBackend,
|
||||
__resetBackendStatusForTest,
|
||||
STALL_RECONNECTING_MS,
|
||||
STALL_UNAVAILABLE_MS,
|
||||
} from '@/lib/backend-status'
|
||||
@@ -44,8 +48,14 @@ describe('apiFetch', () => {
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset()
|
||||
;(globalThis as unknown as { fetch: unknown }).fetch = fetchMock
|
||||
// Re-register the real probe so its cached verdict resets between tests.
|
||||
// Reset the store (reachability, in-flight reads) and re-register the real
|
||||
// probe so its cached verdict resets between tests.
|
||||
__resetBackendStatusForTest()
|
||||
configureHealthProbe(__backendHealthProbe)
|
||||
configurePrewarm(__backendPrewarm)
|
||||
// Default to a WARM session (backend answered moments ago); cold-start tests
|
||||
// reset this explicitly.
|
||||
markBackendReachable()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -155,6 +165,9 @@ describe('apiFetch', () => {
|
||||
|
||||
it('surfaces the banner for a stalled GET once the health probe confirms the outage, then clears', async () => {
|
||||
jest.useFakeTimers()
|
||||
// The backend WAS answering moments ago, so this stall is a recycle/outage,
|
||||
// not a cold start — the normal reconnecting/unavailable path applies.
|
||||
markBackendReachable()
|
||||
// Everything hangs — the backend is genuinely unreachable (recycle-style: the
|
||||
// origin holds requests open, so the probe only fails via its own timeout).
|
||||
let settleGet!: (r: Response) => void
|
||||
@@ -190,6 +203,58 @@ describe('apiFetch', () => {
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
it('shows the calm waking state (not the warning) when a fresh session hits a cold backend', async () => {
|
||||
jest.useFakeTimers()
|
||||
__resetBackendStatusForTest()
|
||||
configureHealthProbe(__backendHealthProbe)
|
||||
// Nothing has answered yet this session; Cloud Run queues every request
|
||||
// (including /api/health) for ~18s while an instance boots.
|
||||
let settleGet!: (r: Response) => void
|
||||
fetchMock.mockImplementation((url: unknown) => {
|
||||
if (String(url).includes('/api/health')) return new Promise<Response>(() => {})
|
||||
return new Promise<Response>((res) => {
|
||||
settleGet = res
|
||||
})
|
||||
})
|
||||
|
||||
const p = apiFetch('/api/jobs')
|
||||
p.catch(() => {})
|
||||
|
||||
// Cold mode probes at 1s; the probe times out at 4s → waking by ~6s.
|
||||
await jest.advanceTimersByTimeAsync(3_000)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
await jest.advanceTimersByTimeAsync(3_000)
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
// Still calm at 18s — never the reconnecting/unavailable warning.
|
||||
await jest.advanceTimersByTimeAsync(12_000)
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
|
||||
// Instance is up: the queued GET completes (no hard-timeout at 45s hit).
|
||||
settleGet(mockResponse(200, { jobs: [] }))
|
||||
const res = await p
|
||||
expect(res.status).toBe(200)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
it('prewarm sends an untracked, preflight-free GET /api/health and marks the backend reachable', async () => {
|
||||
jest.useFakeTimers()
|
||||
__resetBackendStatusForTest()
|
||||
fetchMock.mockResolvedValue(mockResponse(200))
|
||||
prewarmBackend()
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
const [url, init] = fetchMock.mock.calls[0]
|
||||
expect(String(url)).toMatch(/\/api\/health$/)
|
||||
expect(init).toEqual({ cache: 'no-store', keepalive: true }) // no headers → no preflight
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
|
||||
// Reachable now, so a later stall is treated as a recycle (normal path),
|
||||
// and a second prewarm within the freshness window is a no-op.
|
||||
prewarmBackend()
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('never surfaces the banner for a slow GET while the backend is reachable (health probe OK)', async () => {
|
||||
jest.useFakeTimers()
|
||||
// The read is legitimately slow (e.g. first-time instrumental-analysis
|
||||
|
||||
@@ -12,9 +12,19 @@ import {
|
||||
beginRequest,
|
||||
endRequest,
|
||||
configureHealthProbe,
|
||||
configurePrewarm,
|
||||
markBackendReachable,
|
||||
prewarmBackend,
|
||||
installBackendPrewarm,
|
||||
__resetBackendStatusForTest,
|
||||
STALL_RECONNECTING_MS,
|
||||
STALL_UNAVAILABLE_MS,
|
||||
PROBE_FRESH_MS,
|
||||
REACHABLE_FRESH_MS,
|
||||
WAKING_SHOW_MS,
|
||||
WAKING_ESCALATE_MS,
|
||||
COLD_PROBE_AFTER_MS,
|
||||
PREWARM_AFTER_HIDDEN_MS,
|
||||
} from '@/lib/backend-status'
|
||||
|
||||
describe('backend-status store (stall-based)', () => {
|
||||
@@ -23,6 +33,10 @@ describe('backend-status store (stall-based)', () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers()
|
||||
open = []
|
||||
// These suites cover a WARM session (the backend answered moments ago), so
|
||||
// a stall is a recycle/outage rather than a cold start.
|
||||
__resetBackendStatusForTest()
|
||||
markBackendReachable()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -98,6 +112,10 @@ describe('backend-status store (health-probe confirmation)', () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers()
|
||||
open = []
|
||||
// These suites cover a WARM session (the backend answered moments ago), so
|
||||
// a stall is a recycle/outage rather than a cold start.
|
||||
__resetBackendStatusForTest()
|
||||
markBackendReachable()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -209,3 +227,235 @@ describe('backend-status store (health-probe confirmation)', () => {
|
||||
expect(debug.lastProbeOk).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('backend-status store (cold start / waking)', () => {
|
||||
let open: number[] = []
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers()
|
||||
open = []
|
||||
__resetBackendStatusForTest() // fresh page load: nothing has answered yet
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
open.forEach((id) => endRequest(id))
|
||||
__resetBackendStatusForTest()
|
||||
jest.clearAllTimers()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
/** A probe that hangs like a cold instance and fails via its 4s timeout. */
|
||||
const coldProbe = () =>
|
||||
jest.fn(() => new Promise<boolean>((res) => setTimeout(() => res(false), 4000)))
|
||||
|
||||
it('cold start: shows the calm waking state within seconds, then clears when the read completes', async () => {
|
||||
const probe = coldProbe()
|
||||
configureHealthProbe(probe)
|
||||
|
||||
const id = beginRequest()
|
||||
open.push(id)
|
||||
expect(probe).not.toHaveBeenCalled() // a normal fast load never probes
|
||||
await jest.advanceTimersByTimeAsync(COLD_PROBE_AFTER_MS)
|
||||
expect(probe).toHaveBeenCalledTimes(1) // probed at 1s, not at 10s
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
|
||||
await jest.advanceTimersByTimeAsync(WAKING_SHOW_MS)
|
||||
expect(getBackendStatus()).toBe('online') // probe has no verdict yet (t=4s)
|
||||
|
||||
await jest.advanceTimersByTimeAsync(1000) // t=5s: probe failed at its 4s timeout
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
|
||||
// Through a typical ~18s cold start it stays calm — never the warning.
|
||||
await jest.advanceTimersByTimeAsync(13_000) // t=18s
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
|
||||
markBackendReachable()
|
||||
endRequest(id)
|
||||
open = []
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
it('cold start: a read that answers quickly never shows anything', async () => {
|
||||
configureHealthProbe(coldProbe())
|
||||
const id = beginRequest()
|
||||
await jest.advanceTimersByTimeAsync(2000)
|
||||
markBackendReachable()
|
||||
endRequest(id)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
it('cold start: a warm backend with a merely slow endpoint shows nothing (probe OK)', async () => {
|
||||
configureHealthProbe(() => Promise.resolve(true))
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS + 5000)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
it('cold start that drags on past WAKING_ESCALATE_MS escalates to the normal banner', async () => {
|
||||
configureHealthProbe(coldProbe())
|
||||
open.push(beginRequest())
|
||||
|
||||
await jest.advanceTimersByTimeAsync(WAKING_ESCALATE_MS - 1000)
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
|
||||
await jest.advanceTimersByTimeAsync(2000)
|
||||
// Many consecutive probe failures by now → straight to the full message.
|
||||
expect(getBackendStatus()).toBe('unavailable')
|
||||
})
|
||||
|
||||
it('escalation is measured from the start of the cold episode, so a long outage never flaps back to waking', async () => {
|
||||
configureHealthProbe(coldProbe())
|
||||
const first = beginRequest()
|
||||
open.push(first)
|
||||
await jest.advanceTimersByTimeAsync(30_000)
|
||||
open.push(beginRequest()) // e.g. a polling read starting mid-episode
|
||||
await jest.advanceTimersByTimeAsync(31_000) // t=61s
|
||||
expect(getBackendStatus()).toBe('unavailable')
|
||||
|
||||
// The first read times out; the newer one (only 31s old) is now the oldest.
|
||||
endRequest(first)
|
||||
open = open.filter((id) => id !== first)
|
||||
await jest.advanceTimersByTimeAsync(1000)
|
||||
expect(getBackendStatus()).toBe('unavailable') // not back to 'waking'
|
||||
})
|
||||
|
||||
it('a stale failed-probe verdict from before the backend answered cannot trigger waking', async () => {
|
||||
// An earlier episode leaves a failed verdict behind...
|
||||
configureHealthProbe(() => Promise.resolve(false))
|
||||
const old = beginRequest()
|
||||
await jest.advanceTimersByTimeAsync(6000)
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
markBackendReachable()
|
||||
endRequest(old)
|
||||
expect(getBackendStatusDebug().lastProbeOk).toBeNull() // verdict dropped
|
||||
|
||||
// ...much later (backend idle-timeout window passed, but kept warm by others),
|
||||
// a read that's merely slow: the fresh probe answers OK → nothing shown.
|
||||
configureHealthProbe(() => new Promise<boolean>((res) => setTimeout(() => res(true), 2500)))
|
||||
markBackendReachable()
|
||||
await jest.advanceTimersByTimeAsync(REACHABLE_FRESH_MS + 1000)
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(3500) // past WAKING_SHOW_MS, probe still pending
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
await jest.advanceTimersByTimeAsync(5000)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
it('previously reachable, then a stall → normal reconnecting banner (recycle, not a cold start)', async () => {
|
||||
configureHealthProbe(coldProbe())
|
||||
markBackendReachable()
|
||||
await jest.advanceTimersByTimeAsync(30_000) // backend answered 30s ago
|
||||
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(8000)
|
||||
expect(getBackendStatus()).toBe('online') // no waking state for a recycle
|
||||
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS) // probe at 10s, fails at 14s
|
||||
expect(getBackendStatus()).toBe('reconnecting')
|
||||
})
|
||||
|
||||
it('reachable long ago (backend idled to zero) → a new stall is treated as a cold start', async () => {
|
||||
configureHealthProbe(coldProbe())
|
||||
markBackendReachable()
|
||||
await jest.advanceTimersByTimeAsync(REACHABLE_FRESH_MS + 1000)
|
||||
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(6000)
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
})
|
||||
|
||||
it('without a probe (pure stall mode) a cold stall still shows waking, not the warning', async () => {
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(WAKING_SHOW_MS)
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS)
|
||||
expect(getBackendStatus()).toBe('waking')
|
||||
})
|
||||
|
||||
it('exposes time since the backend last answered for telemetry', async () => {
|
||||
expect(getBackendStatusDebug().sinceReachableMs).toBeNull()
|
||||
markBackendReachable()
|
||||
await jest.advanceTimersByTimeAsync(1500)
|
||||
expect(getBackendStatusDebug().sinceReachableMs).toBe(1500)
|
||||
})
|
||||
})
|
||||
|
||||
describe('backend-status prewarm', () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers()
|
||||
__resetBackendStatusForTest()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
configurePrewarm(null)
|
||||
__resetBackendStatusForTest()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
it('installBackendPrewarm registers the passed fetch when api.ts has not', async () => {
|
||||
configurePrewarm(null)
|
||||
const warm = jest.fn(() => Promise.resolve(true))
|
||||
installBackendPrewarm(warm)
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
expect(warm).toHaveBeenCalledTimes(1)
|
||||
expect(getBackendStatusDebug().sinceReachableMs).toBe(0)
|
||||
})
|
||||
|
||||
it('fires once while in flight and marks the backend reachable on success', async () => {
|
||||
let finish!: (ok: boolean) => void
|
||||
const warm = jest.fn(() => new Promise<boolean>((res) => (finish = res)))
|
||||
configurePrewarm(warm)
|
||||
|
||||
prewarmBackend()
|
||||
prewarmBackend() // de-duped while the first is in flight
|
||||
expect(warm).toHaveBeenCalledTimes(1)
|
||||
expect(getBackendStatusDebug().sinceReachableMs).toBeNull()
|
||||
|
||||
finish(true)
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
expect(getBackendStatusDebug().sinceReachableMs).toBe(0)
|
||||
|
||||
// Recently reachable → no need to warm again.
|
||||
prewarmBackend()
|
||||
expect(warm).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('a failed prewarm does not mark the backend reachable and can be retried', async () => {
|
||||
const warm = jest.fn(() => Promise.resolve(false))
|
||||
configurePrewarm(warm)
|
||||
prewarmBackend()
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
expect(getBackendStatusDebug().sinceReachableMs).toBeNull()
|
||||
prewarmBackend()
|
||||
expect(warm).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('re-warms when the tab returns after a long absence, but not after a short one', async () => {
|
||||
const warm = jest.fn(() => Promise.resolve(true))
|
||||
configurePrewarm(warm)
|
||||
let visibility: DocumentVisibilityState = 'visible'
|
||||
Object.defineProperty(document, 'visibilityState', {
|
||||
configurable: true,
|
||||
get: () => visibility,
|
||||
})
|
||||
const setVisibility = (v: DocumentVisibilityState) => {
|
||||
visibility = v
|
||||
document.dispatchEvent(new Event('visibilitychange'))
|
||||
}
|
||||
|
||||
installBackendPrewarm()
|
||||
await jest.advanceTimersByTimeAsync(0)
|
||||
expect(warm).toHaveBeenCalledTimes(1)
|
||||
|
||||
// Short absence: no re-warm.
|
||||
setVisibility('hidden')
|
||||
await jest.advanceTimersByTimeAsync(60_000)
|
||||
setVisibility('visible')
|
||||
expect(warm).toHaveBeenCalledTimes(1)
|
||||
|
||||
// Long absence (backend may have scaled to zero): re-warm.
|
||||
setVisibility('hidden')
|
||||
await jest.advanceTimersByTimeAsync(PREWARM_AFTER_HIDDEN_MS + 1000)
|
||||
setVisibility('visible')
|
||||
expect(warm).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import React, { useEffect, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { getAccessToken } from "@/lib/api"
|
||||
import { getAccessToken, __backendPrewarm } from "@/lib/api"
|
||||
import { installBackendPrewarm } from "@/lib/backend-status"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { Loader2 } from "lucide-react"
|
||||
@@ -104,6 +105,12 @@ export default function AdminLayout({
|
||||
// to satisfy React's Rules of Hooks
|
||||
const { showTestData, setShowTestData } = useAdminSettings()
|
||||
|
||||
// Admin isn't under [locale] (no BackendStatusBanner), so pre-warm a possibly
|
||||
// scaled-to-zero backend here too.
|
||||
useEffect(() => {
|
||||
installBackendPrewarm(__backendPrewarm)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const token = getAccessToken()
|
||||
if (!token) {
|
||||
|
||||
@@ -6,9 +6,11 @@ import { Loader2, CloudOff, X } from "lucide-react"
|
||||
import {
|
||||
useBackendStatus,
|
||||
getBackendStatusDebug,
|
||||
installBackendPrewarm,
|
||||
__installBackendStatusDevHook,
|
||||
} from "@/lib/backend-status"
|
||||
import { reportDegradationEvent } from "@/lib/degradation-events"
|
||||
import { __backendPrewarm } from "@/lib/api"
|
||||
|
||||
/**
|
||||
* App-wide, non-blocking banner that reacts to backend connectivity (see
|
||||
@@ -17,6 +19,8 @@ import { reportDegradationEvent } from "@/lib/degradation-events"
|
||||
* broken and any in-flight karaoke renders keep running. Rather than every screen
|
||||
* showing its own scary error, this shows a single reassuring message:
|
||||
*
|
||||
* - "waking": a calm, branded "starting up our karaoke servers" card while a
|
||||
* scaled-to-zero backend cold-starts (~15-20s). No warning colours.
|
||||
* - "reconnecting": a subtle pill with a spinner while we transparently retry.
|
||||
* - "unavailable": a gentle card explaining it's temporary and that ongoing jobs
|
||||
* are unaffected, once trouble persists past the threshold.
|
||||
@@ -29,8 +33,11 @@ export function BackendStatusBanner() {
|
||||
const t = useTranslations("backendStatus")
|
||||
const [dismissed, setDismissed] = useState(false)
|
||||
|
||||
// Expose the dev/preview trigger (window.__nkBackendStatus) for manual UX review.
|
||||
// Expose the dev/preview trigger (window.__nkBackendStatus) for manual UX review,
|
||||
// and pre-warm a possibly scaled-to-zero backend as early as possible (this
|
||||
// banner is mounted app-wide, so every page that talks to the backend gets it).
|
||||
useEffect(() => {
|
||||
installBackendPrewarm(__backendPrewarm)
|
||||
__installBackendStatusDevHook()
|
||||
}, [])
|
||||
|
||||
@@ -49,18 +56,45 @@ export function BackendStatusBanner() {
|
||||
if (status === "unavailable" && dismissed) return
|
||||
const debug = getBackendStatusDebug()
|
||||
reportDegradationEvent(
|
||||
status === "unavailable" ? "banner_unavailable" : "banner_reconnecting",
|
||||
status === "unavailable"
|
||||
? "banner_unavailable"
|
||||
: status === "waking"
|
||||
? "banner_waking"
|
||||
: "banner_reconnecting",
|
||||
{
|
||||
stall_ms: debug.oldestStallMs,
|
||||
in_flight: debug.inFlightCount,
|
||||
probe_ok: debug.lastProbeOk,
|
||||
probe_failures: debug.consecutiveProbeFailures,
|
||||
since_reachable_ms: debug.sinceReachableMs,
|
||||
},
|
||||
)
|
||||
}, [status, dismissed])
|
||||
|
||||
if (status === "online") return null
|
||||
|
||||
if (status === "waking") {
|
||||
return (
|
||||
<div
|
||||
className="fixed top-3 left-1/2 z-[60] w-[calc(100%-1.5rem)] max-w-md -translate-x-1/2 pointer-events-none"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
data-testid="backend-waking"
|
||||
>
|
||||
<div className="flex items-center gap-3 rounded-xl border border-[var(--card-border)] bg-[var(--card)]/95 px-4 py-3 text-[var(--text)] shadow-2xl backdrop-blur">
|
||||
<Loader2
|
||||
className="h-5 w-5 shrink-0 animate-spin"
|
||||
style={{ color: "var(--tenant-primary)" }}
|
||||
/>
|
||||
<div className="space-y-0.5">
|
||||
<p className="text-sm font-semibold">{t("waking.title")}</p>
|
||||
<p className="text-xs leading-relaxed text-[var(--text-muted)]">{t("waking.body")}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (status === "reconnecting") {
|
||||
return (
|
||||
<div
|
||||
|
||||
+27
-1
@@ -5,7 +5,13 @@
|
||||
import type { VideoThemeSummary, VideoThemeDetail, ThemesListResponse, ThemeDetailResponse, ColorOverrides } from './video-themes';
|
||||
import type { MagicLinkResponse, VerifyMagicLinkResponse, UserProfileResponse, ReferralInterstitial, ReferralDashboard, ReferralLink, VanityRequest, BoardResponse, SubmitRequestResponse, SongRequestPublic, DailyVoteStatus, ClaimWelcomeCreditResponse } from './types';
|
||||
import type { CorrectionData, CorrectionAnnotation, EditLog, SearchLyricsResponse, AddLyricsResult } from './lyrics-review/types';
|
||||
import { beginRequest, endRequest, configureHealthProbe } from './backend-status';
|
||||
import {
|
||||
beginRequest,
|
||||
endRequest,
|
||||
configureHealthProbe,
|
||||
configurePrewarm,
|
||||
markBackendReachable,
|
||||
} from './backend-status';
|
||||
import { ApiError } from './api-error';
|
||||
import { putFileToSignedUrl, uploadFilesToSignedUrls, type UploadProgress } from './upload';
|
||||
|
||||
@@ -546,6 +552,20 @@ export function __backendHealthProbe(): Promise<boolean> {
|
||||
}
|
||||
configureHealthProbe(__backendHealthProbe);
|
||||
|
||||
// Cold-start pre-warm (see prewarmBackend in backend-status.ts): an untracked,
|
||||
// fire-and-forget GET /api/health so a scaled-to-zero backend starts booting while
|
||||
// the user is still reading the page. Deliberately NOT time-boxed: aborting it
|
||||
// would gain nothing, and letting it complete is how we learn the backend is up.
|
||||
// A plain GET with no custom headers, so it never needs a CORS preflight.
|
||||
/** Exported for tests. */
|
||||
export function __backendPrewarm(): Promise<boolean> {
|
||||
return globalThis
|
||||
.fetch(`${API_BASE_URL}/api/health`, { cache: 'no-store', keepalive: true })
|
||||
.then((res) => res.ok)
|
||||
.catch(() => false);
|
||||
}
|
||||
configurePrewarm(__backendPrewarm);
|
||||
|
||||
/** True only for calls to our own backend API — GCS signed-URL uploads and any other
|
||||
* third-party host pass straight through apiFetch untouched (no timeout/retry/status).
|
||||
* Resolves relative URLs and Request inputs (whose `.url` is always absolute) against
|
||||
@@ -664,6 +684,12 @@ export async function apiFetch(
|
||||
}
|
||||
cleanup();
|
||||
|
||||
if (!TRANSIENT_STATUS.has(response.status)) {
|
||||
// The backend answered (even a 4xx is proof it's up) — this is what lets
|
||||
// the status store tell a later stall (recycle) from a cold start.
|
||||
markBackendReachable();
|
||||
}
|
||||
|
||||
if (TRANSIENT_STATUS.has(response.status)) {
|
||||
if (allowRetry && attempt < maxAttempts) {
|
||||
if (response.status === 429) {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
/**
|
||||
* Global backend-connectivity status.
|
||||
*
|
||||
* The backend runs on Cloud Run with `--min-instances 1`. When Cloud Run recycles
|
||||
* The backend runs on Cloud Run (now min-instances 0, see COLD STARTS below). When it recycles
|
||||
* that single instance (routine host maintenance / instance max-lifetime), there is
|
||||
* a brief window where the origin is unreachable and requests HANG (Cloud Run holds
|
||||
* them during the cold start) even though nothing is actually broken — and any
|
||||
@@ -30,6 +30,28 @@
|
||||
* hangs) lets the banner surface.
|
||||
*/
|
||||
|
||||
/*
|
||||
* COLD STARTS (min-instances 0). The backend now scales to zero when idle, so the
|
||||
* first request after a quiet spell waits ~15-20s while Cloud Run starts an
|
||||
* instance (requests are QUEUED, so reads hang rather than fail, and the health
|
||||
* probe times out exactly like it does during a recycle). From the client a cold
|
||||
* start and a recycle look identical, so we tell them apart by recency:
|
||||
*
|
||||
* - If no backend response has succeeded in the REACHABLE_FRESH_MS before the
|
||||
* oldest stalled read began (fresh page load, or a tab left idle long enough
|
||||
* for the backend to scale to zero), a confirmed stall is a cold start: show
|
||||
* the calm 'waking' state ("Starting up our karaoke servers...") from
|
||||
* WAKING_SHOW_MS, without warning colours.
|
||||
* - If that stall outlasts WAKING_ESCALATE_MS it's no longer a plausible cold
|
||||
* start, so the normal reconnecting/unavailable logic takes over.
|
||||
* - If the backend WAS answering just before the stall, it's a recycle/outage:
|
||||
* the normal reconnecting/unavailable logic applies straight away.
|
||||
*
|
||||
* prewarmBackend() fires an untracked GET /api/health on app load (and when a tab
|
||||
* returns after a long absence) so the instance starts while the user is still
|
||||
* reading the page; its success also marks the backend reachable.
|
||||
*/
|
||||
|
||||
import { useSyncExternalStore } from 'react'
|
||||
|
||||
export type BackendStatus =
|
||||
@@ -39,6 +61,9 @@ export type BackendStatus =
|
||||
| 'reconnecting'
|
||||
/** A read has been stalled long enough to show the full "temporarily unavailable". */
|
||||
| 'unavailable'
|
||||
/** Cold start: the backend hasn't answered recently and is (most likely) waking
|
||||
* up from scale-to-zero. Calm "starting up our servers" message. */
|
||||
| 'waking'
|
||||
|
||||
/** A tracked read must be outstanding at least this long before we show ANYTHING —
|
||||
* so a normal slow-but-successful load never surfaces the banner. */
|
||||
@@ -52,6 +77,25 @@ export const PROBE_FRESH_MS = 10_000
|
||||
* transcode pinning the CPU) is not an outage. The reconnecting pill still
|
||||
* shows after a single failure; the assertive message waits for confirmation. */
|
||||
export const UNAVAILABLE_PROBE_FAILURES = 2
|
||||
/** A backend response this recent (relative to when the oldest stalled read began)
|
||||
* means the backend was up and has since stopped answering: a recycle/outage,
|
||||
* not a cold start. Cloud Run scales an idle service to zero after ~15 min, so
|
||||
* anything older than this may well be a cold start. */
|
||||
export const REACHABLE_FRESH_MS = 10 * 60_000
|
||||
/** Cold-start mode: show the calm waking state once a read has been outstanding
|
||||
* this long AND the health probe has failed (it times out at ~4s on a cold
|
||||
* instance, so in practice the waking state appears ~4-5s into a cold start). */
|
||||
export const WAKING_SHOW_MS = 3_000
|
||||
/** Cold-start mode probes once the oldest read has been outstanding this long
|
||||
* (instead of waiting for STALL_RECONNECTING_MS). Short enough that the waking
|
||||
* state appears ~5s into a cold start; long enough that the normal warm-backend
|
||||
* page load (reads done in well under a second) never sends an extra probe. */
|
||||
export const COLD_PROBE_AFTER_MS = 1_000
|
||||
/** Cold starts take ~15-20s. A stall past this is no longer plausibly a cold
|
||||
* start, so we escalate to the normal reconnecting/unavailable banner. */
|
||||
export const WAKING_ESCALATE_MS = 60_000
|
||||
/** Re-prewarm when a tab becomes visible after being hidden at least this long. */
|
||||
export const PREWARM_AFTER_HIDDEN_MS = 10 * 60_000
|
||||
|
||||
let nextId = 1
|
||||
/** id -> startedAt (ms) for every tracked backend GET currently in flight. */
|
||||
@@ -75,6 +119,11 @@ let consecutiveProbeFailures = 0
|
||||
/** Bumped on configureHealthProbe so a probe from a previous config can't land. */
|
||||
let probeEpoch = 0
|
||||
|
||||
/** When a backend response last succeeded (0 = never in this page session). */
|
||||
let lastReachableAt = 0
|
||||
/** Start of the current cold-start episode (null = none); cleared by any response. */
|
||||
let coldEpisodeStartedAt: number | null = null
|
||||
|
||||
const listeners = new Set<() => void>()
|
||||
|
||||
function emit() {
|
||||
@@ -87,18 +136,39 @@ function setStatus(next: BackendStatus) {
|
||||
emit()
|
||||
}
|
||||
|
||||
function computeFromStalls(): BackendStatus {
|
||||
if (inFlight.size === 0) return 'online'
|
||||
function oldestStartedAt(): number {
|
||||
let oldest = Infinity
|
||||
for (const startedAt of inFlight.values()) {
|
||||
if (startedAt < oldest) oldest = startedAt
|
||||
}
|
||||
const age = Date.now() - oldest
|
||||
return oldest
|
||||
}
|
||||
|
||||
function computeFromStalls(): BackendStatus {
|
||||
if (inFlight.size === 0) return 'online'
|
||||
const age = Date.now() - oldestStartedAt()
|
||||
if (age >= STALL_UNAVAILABLE_MS) return 'unavailable'
|
||||
if (age >= STALL_RECONNECTING_MS) return 'reconnecting'
|
||||
return 'online'
|
||||
}
|
||||
|
||||
/** True when the oldest outstanding read is (plausibly) waiting on a cold start:
|
||||
* nothing from the backend succeeded in the REACHABLE_FRESH_MS before it began,
|
||||
* and it hasn't yet outlasted a plausible cold start. */
|
||||
function inColdStartWindow(): boolean {
|
||||
if (inFlight.size === 0) return false
|
||||
const oldest = oldestStartedAt()
|
||||
const notRecentlyReachable =
|
||||
lastReachableAt === 0 || lastReachableAt < oldest - REACHABLE_FRESH_MS
|
||||
if (!notRecentlyReachable) return false
|
||||
// Escalation is measured from when this cold episode BEGAN, not from the oldest
|
||||
// read still pending — otherwise, as stalled reads time out and newer (e.g.
|
||||
// polling) reads become the oldest, a genuine outage would flap
|
||||
// unavailable → waking → unavailable. Only a backend response ends the episode.
|
||||
if (coldEpisodeStartedAt === null) coldEpisodeStartedAt = oldest
|
||||
return Date.now() - coldEpisodeStartedAt < WAKING_ESCALATE_MS
|
||||
}
|
||||
|
||||
/** Fire a health probe if one isn't running and the last verdict has gone stale. */
|
||||
function maybeStartProbe() {
|
||||
if (!healthProbe || probeInFlight) return
|
||||
@@ -109,6 +179,7 @@ function maybeStartProbe() {
|
||||
if (epoch !== probeEpoch) return
|
||||
lastProbeOk = ok
|
||||
consecutiveProbeFailures = ok ? 0 : consecutiveProbeFailures + 1
|
||||
if (ok) lastReachableAt = Date.now()
|
||||
}
|
||||
healthProbe()
|
||||
.then(
|
||||
@@ -124,6 +195,17 @@ function maybeStartProbe() {
|
||||
}
|
||||
|
||||
function recompute() {
|
||||
if (devOverride === null && inColdStartWindow()) {
|
||||
// Cold start: probe after just COLD_PROBE_AFTER_MS (rather than waiting for
|
||||
// the 10s stall threshold) so the calm waking state can appear within a few seconds. The
|
||||
// probe still gates it: a warm backend answers /api/health instantly, so a
|
||||
// merely slow endpoint never shows the waking state.
|
||||
const age = Date.now() - oldestStartedAt()
|
||||
if (healthProbe && age >= COLD_PROBE_AFTER_MS) maybeStartProbe()
|
||||
const probeSaysDown = !healthProbe || lastProbeOk === false
|
||||
setStatus(age >= WAKING_SHOW_MS && probeSaysDown ? 'waking' : 'online')
|
||||
return
|
||||
}
|
||||
let next = devOverride ?? computeFromStalls()
|
||||
// A stall only becomes a banner once the health probe CONFIRMS the backend is
|
||||
// unreachable. While the probe answers OK (or hasn't answered yet), the stalled
|
||||
@@ -169,6 +251,84 @@ export function endRequest(id: number): void {
|
||||
if (inFlight.delete(id)) recompute()
|
||||
}
|
||||
|
||||
/**
|
||||
* Record that the backend just answered (any non-transient HTTP response, from any
|
||||
* request). This is what distinguishes "was up, now stalled" (recycle/outage:
|
||||
* normal banner) from "hasn't answered lately" (cold start: calm waking state).
|
||||
*/
|
||||
export function markBackendReachable(): void {
|
||||
lastReachableAt = Date.now()
|
||||
coldEpisodeStartedAt = null
|
||||
// The backend just answered, so any earlier failed-probe verdict is stale: drop
|
||||
// it rather than let it vouch for a future stall (re-probe instead).
|
||||
if (lastProbeOk === false) {
|
||||
lastProbeOk = null
|
||||
consecutiveProbeFailures = 0
|
||||
}
|
||||
if (inFlight.size > 0 || status !== 'online') recompute()
|
||||
}
|
||||
|
||||
/** Untracked warm-up request (GET /api/health). Must never reject. */
|
||||
type Prewarm = () => Promise<boolean>
|
||||
let prewarmFn: Prewarm | null = null
|
||||
let prewarmInFlight = false
|
||||
let hiddenAt: number | null = null
|
||||
let visibilityListenerInstalled = false
|
||||
|
||||
/** Registered once by lib/api.ts (keeps this module free of fetch/URL concerns). */
|
||||
export function configurePrewarm(fn: Prewarm | null): void {
|
||||
prewarmFn = fn
|
||||
prewarmInFlight = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire-and-forget wake-up for a backend that may have scaled to zero, so the cold
|
||||
* start overlaps with the user reading the page instead of blocking their first
|
||||
* action. Untracked: it never drives the banner itself. A no-op if one is already
|
||||
* in flight or the backend answered within REACHABLE_FRESH_MS.
|
||||
*/
|
||||
export function prewarmBackend(): void {
|
||||
if (!prewarmFn || prewarmInFlight) return
|
||||
if (lastReachableAt !== 0 && Date.now() - lastReachableAt < REACHABLE_FRESH_MS) return
|
||||
prewarmInFlight = true
|
||||
prewarmFn()
|
||||
.then(
|
||||
(ok) => {
|
||||
if (ok) markBackendReachable()
|
||||
},
|
||||
() => {},
|
||||
)
|
||||
.finally(() => {
|
||||
prewarmInFlight = false
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-warm now, and again whenever the tab becomes visible after being hidden for
|
||||
* PREWARM_AFTER_HIDDEN_MS (long enough that the backend may have scaled to zero).
|
||||
* Idempotent; call from any client component mounted app-wide, passing
|
||||
* `__backendPrewarm` from lib/api.ts.
|
||||
*/
|
||||
export function installBackendPrewarm(fn?: Prewarm): void {
|
||||
if (typeof document === 'undefined') return
|
||||
// Callers pass the fetch explicitly so the pre-warm works even on a page that
|
||||
// hasn't (yet) loaded lib/api.ts, which is where it's otherwise registered.
|
||||
if (fn && !prewarmFn) configurePrewarm(fn)
|
||||
prewarmBackend()
|
||||
if (visibilityListenerInstalled) return
|
||||
visibilityListenerInstalled = true
|
||||
if (document.visibilityState === 'hidden') hiddenAt = Date.now()
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'hidden') {
|
||||
hiddenAt = Date.now()
|
||||
return
|
||||
}
|
||||
const wasHiddenFor = hiddenAt === null ? 0 : Date.now() - hiddenAt
|
||||
hiddenAt = null
|
||||
if (wasHiddenFor >= PREWARM_AFTER_HIDDEN_MS) prewarmBackend()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the reachability probe used to confirm a stall before the banner shows.
|
||||
* The probe must never reject and must settle within a few seconds (race against
|
||||
@@ -190,19 +350,34 @@ export function getBackendStatusDebug(): {
|
||||
inFlightCount: number
|
||||
lastProbeOk: boolean | null
|
||||
consecutiveProbeFailures: number
|
||||
/** ms since the backend last answered (null = never this session). */
|
||||
sinceReachableMs: number | null
|
||||
} {
|
||||
let oldest = Infinity
|
||||
for (const startedAt of inFlight.values()) {
|
||||
if (startedAt < oldest) oldest = startedAt
|
||||
}
|
||||
return {
|
||||
oldestStallMs: inFlight.size === 0 ? 0 : Date.now() - oldest,
|
||||
oldestStallMs: inFlight.size === 0 ? 0 : Date.now() - oldestStartedAt(),
|
||||
inFlightCount: inFlight.size,
|
||||
lastProbeOk,
|
||||
consecutiveProbeFailures,
|
||||
sinceReachableMs: lastReachableAt === 0 ? null : Date.now() - lastReachableAt,
|
||||
}
|
||||
}
|
||||
|
||||
/** Test-only: reset all module state (reachability, prewarm, in-flight reads). */
|
||||
export function __resetBackendStatusForTest(): void {
|
||||
inFlight.clear()
|
||||
devOverride = null
|
||||
lastReachableAt = 0
|
||||
coldEpisodeStartedAt = null
|
||||
prewarmInFlight = false
|
||||
hiddenAt = null
|
||||
configureHealthProbe(null)
|
||||
if (ticker) {
|
||||
clearInterval(ticker)
|
||||
ticker = null
|
||||
}
|
||||
status = 'online'
|
||||
}
|
||||
|
||||
export function getBackendStatus(): BackendStatus {
|
||||
return status
|
||||
}
|
||||
@@ -236,6 +411,7 @@ export function __installBackendStatusDevHook() {
|
||||
recompute()
|
||||
}
|
||||
;(window as unknown as { __nkBackendStatus?: unknown }).__nkBackendStatus = {
|
||||
waking: () => simulate('waking'),
|
||||
reconnecting: () => simulate('reconnecting'),
|
||||
unavailable: () => simulate('unavailable'),
|
||||
online: () => simulate(null),
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
export type DegradationEventType =
|
||||
| 'banner_reconnecting'
|
||||
| 'banner_unavailable'
|
||||
| 'banner_waking'
|
||||
| 'lyrics_load_failed'
|
||||
| 'waveform_slow'
|
||||
| 'waveform_failed'
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "أي مقاطع فيديو كاريوكي يتم إنشاؤها حالياً لن تتأثر وستستمر قيد المعالجة.",
|
||||
"title": "نواجه مشكلة في الوصول إلى خوادمنا"
|
||||
},
|
||||
"dismiss": "تجاهل"
|
||||
"dismiss": "تجاهل",
|
||||
"waking": {
|
||||
"body": "يستغرق هذا عادةً حوالي 20 ثانية. شكرًا لصبرك!",
|
||||
"title": "جارٍ تشغيل خوادم الكاريوكي…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "تتم الآن معالجة {count} من المسارات.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Els vídeos de karaoke que s'estiguin creant ara mateix no es veuran afectats i es continuaran processant.",
|
||||
"title": "Tenim problemes per connectar amb els nostres servidors"
|
||||
},
|
||||
"dismiss": "Descarta"
|
||||
"dismiss": "Descarta",
|
||||
"waking": {
|
||||
"body": "Normalment triga uns 20 segons. Gràcies per la teva paciència!",
|
||||
"title": "S'estan iniciant els nostres servidors de karaoke…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "S'estan processant {count} pistes.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Právě vytvářená karaoke videa nejsou nijak ovlivněna a budou se nadále zpracovávat.",
|
||||
"title": "Nedaří se nám spojit s našimi servery"
|
||||
},
|
||||
"dismiss": "Zavřít"
|
||||
"dismiss": "Zavřít",
|
||||
"waking": {
|
||||
"body": "Obvykle to trvá asi 20 sekund. Díky za trpělivost!",
|
||||
"title": "Spouštíme naše karaoke servery…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} skladeb se nyní zpracovává.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Eventuelle karaokevideoer, der i øjeblikket bliver lavet, påvirkes ikke og vil fortsat blive behandlet.",
|
||||
"title": "Vi har problemer med at få forbindelse til vores servere"
|
||||
},
|
||||
"dismiss": "Afvis"
|
||||
"dismiss": "Afvis",
|
||||
"waking": {
|
||||
"body": "Det tager normalt omkring 20 sekunder. Tak for din tålmodighed!",
|
||||
"title": "Starter vores karaokeservere…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} numre bliver nu behandlet.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Alle Karaoke-Videos, die gerade erstellt werden, sind davon nicht betroffen und werden weiterverarbeitet.",
|
||||
"title": "Wir haben Probleme, unsere Server zu erreichen"
|
||||
},
|
||||
"dismiss": "Ausblenden"
|
||||
"dismiss": "Ausblenden",
|
||||
"waking": {
|
||||
"body": "Das dauert normalerweise etwa 20 Sekunden. Danke für deine Geduld!",
|
||||
"title": "Unsere Karaoke-Server werden gestartet…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} Tracks werden jetzt verarbeitet.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Τυχόν βίντεο καραόκε που δημιουργούνται αυτήν τη στιγμή δεν επηρεάζονται και η επεξεργασία τους θα συνεχιστεί.",
|
||||
"title": "Αντιμετωπίζουμε πρόβλημα σύνδεσης με τους διακομιστές μας"
|
||||
},
|
||||
"dismiss": "Απόρριψη"
|
||||
"dismiss": "Απόρριψη",
|
||||
"waking": {
|
||||
"body": "Αυτό συνήθως διαρκεί περίπου 20 δευτερόλεπτα. Ευχαριστούμε για την υπομονή σου!",
|
||||
"title": "Εκκίνηση των διακομιστών καραόκε μας…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} κομμάτια βρίσκονται τώρα σε επεξεργασία.",
|
||||
|
||||
@@ -371,6 +371,10 @@
|
||||
},
|
||||
"backendStatus": {
|
||||
"reconnecting": "Reconnecting…",
|
||||
"waking": {
|
||||
"title": "Starting up our karaoke servers…",
|
||||
"body": "This usually takes about 20 seconds. Thanks for your patience!"
|
||||
},
|
||||
"unavailable": {
|
||||
"title": "We're having trouble reaching our servers",
|
||||
"body": "This is usually temporary — please try again in a couple of minutes.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Los videos de karaoke que se estén creando en este momento no se verán afectados y seguirán procesándose.",
|
||||
"title": "Tenemos problemas para conectar con nuestros servidores"
|
||||
},
|
||||
"dismiss": "Descartar"
|
||||
"dismiss": "Descartar",
|
||||
"waking": {
|
||||
"body": "Esto suele tardar unos 20 segundos. ¡Gracias por tu paciencia!",
|
||||
"title": "Iniciando nuestros servidores de karaoke…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} pistas se están procesando ahora.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Tämä ei vaikuta parhaillaan luotaviin karaokevideoihin, vaan niiden käsittely jatkuu normaalisti.",
|
||||
"title": "Palvelimiimme yhdistämisessä on ongelmia"
|
||||
},
|
||||
"dismiss": "Ohita"
|
||||
"dismiss": "Ohita",
|
||||
"waking": {
|
||||
"body": "Tämä kestää yleensä noin 20 sekuntia. Kiitos kärsivällisyydestäsi!",
|
||||
"title": "Käynnistetään karaokepalvelimiamme…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} kappaletta on nyt käsittelyssä.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Les vidéos de karaoké en cours de création ne sont pas affectées et continueront d'être traitées.",
|
||||
"title": "Nous avons des difficultés à joindre nos serveurs"
|
||||
},
|
||||
"dismiss": "Ignorer"
|
||||
"dismiss": "Ignorer",
|
||||
"waking": {
|
||||
"body": "Cela prend généralement une vingtaine de secondes. Merci de ta patience !",
|
||||
"title": "Démarrage de nos serveurs de karaoké…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} pistes sont maintenant en cours de traitement.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "סרטוני קריוקי שנוצרים כרגע לא יושפעו וימשיכו בתהליך העיבוד.",
|
||||
"title": "אנחנו מתקשים להתחבר לשרתים שלנו"
|
||||
},
|
||||
"dismiss": "התעלם"
|
||||
"dismiss": "התעלם",
|
||||
"waking": {
|
||||
"body": "זה בדרך כלל לוקח כ-20 שניות. תודה על הסבלנות!",
|
||||
"title": "מפעילים את שרתי הקריוקי שלנו…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} רצועות נמצאות כעת בעיבוד.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "अभी बन रहे किसी भी कराओके वीडियो पर कोई असर नहीं पड़ा है और उनकी प्रोसेसिंग जारी रहेगी।",
|
||||
"title": "हमें अपने सर्वर तक पहुँचने में परेशानी हो रही है"
|
||||
},
|
||||
"dismiss": "हटाओ"
|
||||
"dismiss": "हटाओ",
|
||||
"waking": {
|
||||
"body": "इसमें आमतौर पर लगभग 20 सेकंड लगते हैं। तुम्हारे धैर्य के लिए धन्यवाद!",
|
||||
"title": "हमारे कराओके सर्वर शुरू हो रहे हैं…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} ट्रैक्स अब प्रोसेस किए जा रहे हैं।",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Ovo ne utječe na karaoke videozapise koji se trenutno izrađuju i njihova će se obrada nastaviti.",
|
||||
"title": "Imamo problema s povezivanjem na naše servere"
|
||||
},
|
||||
"dismiss": "Odbaci"
|
||||
"dismiss": "Odbaci",
|
||||
"waking": {
|
||||
"body": "Ovo obično traje oko 20 sekundi. Hvala ti na strpljenju!",
|
||||
"title": "Pokrećemo naše karaoke poslužitelje…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} pjesama se sada obrađuje.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "A jelenleg készülő karaoke videókat ez nem érinti, a feldolgozásuk zavartalanul folytatódik.",
|
||||
"title": "Nem tudjuk elérni a szervereinket"
|
||||
},
|
||||
"dismiss": "Elvetés"
|
||||
"dismiss": "Elvetés",
|
||||
"waking": {
|
||||
"body": "Ez általában körülbelül 20 másodpercet vesz igénybe. Köszönjük a türelmedet!",
|
||||
"title": "Karaokeszervereink indítása…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} szám feldolgozása folyamatban van.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Video karaoke yang sedang dibuat tidak akan terpengaruh dan akan terus diproses.",
|
||||
"title": "Kami kesulitan terhubung ke server"
|
||||
},
|
||||
"dismiss": "Abaikan"
|
||||
"dismiss": "Abaikan",
|
||||
"waking": {
|
||||
"body": "Proses ini biasanya membutuhkan waktu sekitar 20 detik. Terima kasih atas kesabaran Anda!",
|
||||
"title": "Menyalakan server karaoke kami…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} trek sedang diproses.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "I video karaoke attualmente in fase di creazione non subiranno interruzioni e continueranno a essere elaborati.",
|
||||
"title": "Abbiamo problemi a raggiungere i nostri server"
|
||||
},
|
||||
"dismiss": "Ignora"
|
||||
"dismiss": "Ignora",
|
||||
"waking": {
|
||||
"body": "Di solito ci vogliono circa 20 secondi. Grazie per la pazienza!",
|
||||
"title": "Avvio dei nostri server karaoke in corso…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} tracce sono ora in fase di elaborazione.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "現在作成中のカラオケ動画に影響はありません。そのまま処理が継続されます。",
|
||||
"title": "サーバーへの接続に問題が発生しています"
|
||||
},
|
||||
"dismiss": "閉じる"
|
||||
"dismiss": "閉じる",
|
||||
"waking": {
|
||||
"body": "通常約20秒かかります。そのまま少々お待ちください!",
|
||||
"title": "カラオケサーバーを起動しています…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count}曲のトラックを処理しています。",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "현재 생성 중인 노래방 영상은 영향을 받지 않고 정상적으로 처리됩니다.",
|
||||
"title": "서버에 연결하는 데 문제가 발생했습니다"
|
||||
},
|
||||
"dismiss": "닫기"
|
||||
"dismiss": "닫기",
|
||||
"waking": {
|
||||
"body": "보통 20초 정도 걸려요. 잠시만 기다려 주세요!",
|
||||
"title": "가라오케 서버를 시작하는 중…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count}개의 트랙이 현재 처리 중입니다.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Sebarang video karaoke yang sedang dihasilkan tidak terjejas dan akan terus diproses.",
|
||||
"title": "Kami menghadapi masalah menyambung ke pelayan kami"
|
||||
},
|
||||
"dismiss": "Tutup"
|
||||
"dismiss": "Tutup",
|
||||
"waking": {
|
||||
"body": "Ini biasanya mengambil masa kira-kira 20 saat. Terima kasih atas kesabaran anda!",
|
||||
"title": "Memulakan pelayan karaoke kami…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} trek sedang diproses sekarang.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Eventuelle karaokevideoer som lages akkurat nå påvirkes ikke, og vil fortsette å behandles.",
|
||||
"title": "Vi har problemer med å nå serverne våre"
|
||||
},
|
||||
"dismiss": "Lukk"
|
||||
"dismiss": "Lukk",
|
||||
"waking": {
|
||||
"body": "Dette tar vanligvis rundt 20 sekunder. Takk for tålmodigheten!",
|
||||
"title": "Starter opp karaokeserverne våre…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} låter blir nå behandlet.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Karaokevideo's die momenteel worden gemaakt, ondervinden hier geen hinder van en worden gewoon verder verwerkt.",
|
||||
"title": "We kunnen onze servers even niet bereiken"
|
||||
},
|
||||
"dismiss": "Sluiten"
|
||||
"dismiss": "Sluiten",
|
||||
"waking": {
|
||||
"body": "Dit duurt meestal ongeveer 20 seconden. Bedankt voor je geduld!",
|
||||
"title": "Onze karaokeservers worden opgestart…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} tracks worden nu verwerkt.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Obecnie tworzone filmy karaoke są bezpieczne i będą nadal przetwarzane.",
|
||||
"title": "Mamy problem z połączeniem z naszymi serwerami"
|
||||
},
|
||||
"dismiss": "Zamknij"
|
||||
"dismiss": "Zamknij",
|
||||
"waking": {
|
||||
"body": "Zwykle zajmuje to około 20 sekund. Dziękujemy za cierpliwość!",
|
||||
"title": "Uruchamiamy nasze serwery karaoke…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} utworów jest teraz przetwarzanych.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Os vídeos de karaokê que estão sendo criados no momento não serão afetados e continuarão sendo processados.",
|
||||
"title": "Estamos com problemas para acessar nossos servidores"
|
||||
},
|
||||
"dismiss": "Dispensar"
|
||||
"dismiss": "Dispensar",
|
||||
"waking": {
|
||||
"body": "Isso geralmente leva cerca de 20 segundos. Agradecemos a sua paciência!",
|
||||
"title": "Iniciando nossos servidores de karaokê…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} faixas estão sendo processadas agora.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Videoclipurile de karaoke aflate în curs de creare nu sunt afectate și vor continua să fie procesate.",
|
||||
"title": "Întâmpinăm probleme la conectarea cu serverele noastre"
|
||||
},
|
||||
"dismiss": "Închide"
|
||||
"dismiss": "Închide",
|
||||
"waking": {
|
||||
"body": "De obicei, durează aproximativ 20 de secunde. Îți mulțumim pentru răbdare!",
|
||||
"title": "Pornim serverele de karaoke…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} piese sunt acum în curs de procesare.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Это не повлияет на караоке-видео, которые сейчас создаются — они продолжат обрабатываться.",
|
||||
"title": "Возникли проблемы с подключением к нашим серверам"
|
||||
},
|
||||
"dismiss": "Скрыть"
|
||||
"dismiss": "Скрыть",
|
||||
"waking": {
|
||||
"body": "Обычно это занимает около 20 секунд. Спасибо за терпение!",
|
||||
"title": "Запускаем наши караоке-серверы…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "Сейчас обрабатывается {count} треков.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Karaoke videá, ktoré sa práve vytvárajú, to neovplyvní a ich spracovanie bude pokračovať.",
|
||||
"title": "Máme problémy s pripojením k našim serverom"
|
||||
},
|
||||
"dismiss": "Zavrieť"
|
||||
"dismiss": "Zavrieť",
|
||||
"waking": {
|
||||
"body": "Zvyčajne to trvá približne 20 sekúnd. Ďakujeme za trpezlivosť!",
|
||||
"title": "Spúšťame naše karaoke servery…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} skladieb sa teraz spracúva.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Karaokevideor som håller på att skapas påverkas inte, utan fortsätter att bearbetas.",
|
||||
"title": "Vi har problem med att nå våra servrar"
|
||||
},
|
||||
"dismiss": "Avfärda"
|
||||
"dismiss": "Avfärda",
|
||||
"waking": {
|
||||
"body": "Det brukar ta cirka 20 sekunder. Tack för ditt tålamod!",
|
||||
"title": "Startar våra karaokeservrar…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} spår bearbetas nu.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "วิดีโอคาราโอเกะที่กำลังสร้างอยู่จะไม่ได้รับผลกระทบ และจะประมวลผลต่อไป",
|
||||
"title": "เราพบปัญหาในการเชื่อมต่อกับเซิร์ฟเวอร์"
|
||||
},
|
||||
"dismiss": "ปิดทิ้ง"
|
||||
"dismiss": "ปิดทิ้ง",
|
||||
"waking": {
|
||||
"body": "ขั้นตอนนี้มักใช้เวลาประมาณ 20 วินาที ขอบคุณที่รออย่างอดทนนะครับ/ค่ะ!",
|
||||
"title": "กำลังเริ่มการทำงานของเซิร์ฟเวอร์คาราโอเกะ…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "กำลังประมวลผลเพลงจำนวน {count} เพลง",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Ang anumang karaoke video na kasalukuyang ginagawa ay hindi maaapektuhan at patuloy na ipoproseso.",
|
||||
"title": "Nahihirapan kaming kumonekta sa aming mga server"
|
||||
},
|
||||
"dismiss": "I-dismiss"
|
||||
"dismiss": "I-dismiss",
|
||||
"waking": {
|
||||
"body": "Karaniwang tumatagal ito nang mga 20 segundo. Salamat sa iyong paghihintay!",
|
||||
"title": "Sinisimulan na ang aming mga karaoke server…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "Pinoproseso na ang {count} track.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Şu anda oluşturulmakta olan karaoke videoları bu durumdan etkilenmez ve işlenmeye devam eder.",
|
||||
"title": "Sunucularımıza ulaşmakta sorun yaşıyoruz"
|
||||
},
|
||||
"dismiss": "Kapat"
|
||||
"dismiss": "Kapat",
|
||||
"waking": {
|
||||
"body": "Bu işlem genellikle yaklaşık 20 saniye sürer. Sabrın için teşekkürler!",
|
||||
"title": "Karaoke sunucularımız başlatılıyor…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} parça şu anda işleniyor.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Це не вплине на караоке-відео, які зараз створюються, їхня обробка продовжиться.",
|
||||
"title": "Виникли проблеми зі зв'язком із нашими серверами"
|
||||
},
|
||||
"dismiss": "Закрити"
|
||||
"dismiss": "Закрити",
|
||||
"waking": {
|
||||
"body": "Зазвичай це займає близько 20 секунд. Дякуємо за терпіння!",
|
||||
"title": "Запускаємо наші караоке-сервери…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} треків зараз обробляються.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "Các video karaoke đang được tạo sẽ không bị ảnh hưởng và vẫn tiếp tục được xử lý.",
|
||||
"title": "Chúng tôi đang gặp sự cố khi kết nối với máy chủ"
|
||||
},
|
||||
"dismiss": "Bỏ qua"
|
||||
"dismiss": "Bỏ qua",
|
||||
"waking": {
|
||||
"body": "Quá trình này thường mất khoảng 20 giây. Cảm ơn bạn đã kiên nhẫn chờ đợi!",
|
||||
"title": "Đang khởi động hệ thống máy chủ karaoke…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} bài hát hiện đang được xử lý.",
|
||||
|
||||
@@ -1825,7 +1825,11 @@
|
||||
"reassurance": "当前正在制作的卡拉OK视频不会受到影响,系统将继续进行处理。",
|
||||
"title": "我们连接服务器时遇到了一些问题"
|
||||
},
|
||||
"dismiss": "忽略"
|
||||
"dismiss": "忽略",
|
||||
"waking": {
|
||||
"body": "通常需要大约 20 秒,感谢您的耐心等待!",
|
||||
"title": "正在启动卡拉OK服务器…"
|
||||
}
|
||||
},
|
||||
"tenantBulk": {
|
||||
"allSubmittedDesc": "{count} 首曲目正在处理中。",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.262.0"
|
||||
version = "0.263.2"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
Reference in new issue
Block a user