diff --git a/docs/DEPLOY-VPS.md b/docs/DEPLOY-VPS.md index 137b2944..5315cc78 100644 --- a/docs/DEPLOY-VPS.md +++ b/docs/DEPLOY-VPS.md @@ -784,6 +784,8 @@ npm run phase-b:init npm run phase-b:up ``` +Si `phase-b:up` échoue avec `6379/tcp: address already in use`, ou si la prédiction / le Support affichent `Stream isn't writeable…` / `Connection is closed` : voir **[TROUBLESHOOTING-REDIS-PORT.md](./TROUBLESHOOTING-REDIS-PORT.md)**. + Accès : **http://prediqo.redirectme.net:9080** (avec le port, en **http**) ### Parcours B — HTTPS avec Let’s Encrypt (recommandé) diff --git a/docs/TROUBLESHOOTING-REDIS-PORT.md b/docs/TROUBLESHOOTING-REDIS-PORT.md new file mode 100644 index 00000000..9cd6ac40 --- /dev/null +++ b/docs/TROUBLESHOOTING-REDIS-PORT.md @@ -0,0 +1,123 @@ +# Dépannage : Redis port 6379 déjà utilisé + +## Symptômes + +Lors de `npm run phase-b:up` (ou `docker compose --profile http up -d --build`) : + +```text +Error response from daemon: failed to set up container networking: +... endpoint crypto_wallet_redis ... +failed to bind host port 0.0.0.0:6379/tcp: address already in use +``` + +Sur l’app (page prédiction Candle Predict, Tloto Support, realtime) : + +- `Stream isn't writeable and enableOfflineQueue options is false` +- `Connection is closed` + +**Ce n’est pas un bug marketing / Live Activity.** C’est Redis indisponible : le backend Redis client utilise `enableOfflineQueue: false` et échoue immédiatement si Redis est down. + +Un simple « rebuild » peut parfois « marcher » parce qu’il arrête/recrée des conteneurs et libère temporairement le port — le conflit peut revenir au prochain `up`. + +## Cause + +Le conteneur Redis (`crypto_wallet_redis`) publie le port hôte **6379**. Si un autre process ou un autre conteneur Redis l’occupe déjà, le démarrage échoue. Les services API / WS / workers démarrent parfois sans Redis → erreurs realtime ci-dessus. + +## Diagnostic + +Sur le VPS (dans le dépôt du projet) : + +```bash +# Qui écoute sur 6379 ? +sudo ss -tlnp | grep 6379 +# ou +sudo lsof -i :6379 + +# Conteneurs Redis (y compris arrêtés) +docker ps -a --filter name=redis +docker ps -a | grep -i redis + +# État de la stack +sudo npm run phase-b:status +# ou +docker compose ps +``` + +Interpréter : + +| Observation | Interprétation | +|-------------|----------------| +| Conteneur `crypto_wallet_redis` Exit / Created | Échec de bind ; Redis de la stack n’est pas up | +| Autre conteneur Redis « Up » sur 6379 | Deux stacks Docker se disputent le port | +| Process `redis-server` hors Docker | Redis système qui occupe 6379 | + +## Résolution + +### 1. Libérer le port (cas le plus fréquent) + +```bash +# Ancien conteneur Redis de cette stack +docker stop crypto_wallet_redis 2>/dev/null +docker rm crypto_wallet_redis 2>/dev/null + +# Autre Redis Docker (adapter le nom si besoin) +docker ps -a | grep -i redis +docker stop +docker rm + +# Redis installé sur l’hôte (si ss/lsof le montre) +sudo systemctl stop redis +# ou +sudo systemctl stop redis-server +``` + +Puis relancer : + +```bash +sudo npm run phase-b:up +# HTTPS : +# sudo npm run phase-b:up:https +``` + +Vérifier : + +```bash +docker ps --filter name=crypto_wallet_redis +# doit être "Up" +sudo ss -tlnp | grep 6379 +# doit être le conteneur Docker Redis de la stack +``` + +### 2. Éviter deux stacks en parallèle + +Ne pas laisser tourner en même temps : + +- `phase-b` (prod VPS) **et** +- une autre compose qui mappe aussi `6379:6379` (ex. ancien projet, `docker:local` sur la même machine) + +Garder **une seule** stack qui expose 6379, ou changer le mapping de l’autre (ex. `"6380:6379"`) dans son `docker-compose` — **sans** changer Redis côté app tant que l’URL interne Docker reste `redis:6379`. + +### 3. Confirmer que les erreurs app disparaissent + +Après Redis up : + +1. Recharger la page prédiction et le Support. +2. Les messages `Stream isn't writeable…` / `Connection is closed` ne doivent plus apparaître. +3. Logs utiles : + ```bash + docker logs crypto_wallet_redis --tail 50 + docker logs crypto_wallet_api --tail 80 + docker logs crypto_wallet_ws --tail 80 + ``` + +## Prévention + +- Avant un `phase-b:up`, vérifier : `sudo ss -tlnp | grep 6379`. +- Après un déploiement raté, ne pas enchaîner des rebuilds sans regarder Redis : corriger le port d’abord. +- Sur un VPS partagé, ne pas installer Redis système **et** Redis Docker sur le même `6379`. + +## Références code + +- Client Redis (échec rapide) : `backend/src/realtime/redis/client.ts` (`enableOfflineQueue: false`) +- Compose / service Redis : `docker-compose` (service redis, port hôte `6379`) +- Commandes stack : `docs/DEPLOY-VPS.md` (`phase-b:up`, `phase-b:status`, `phase-b:logs`) diff --git a/prediqo_mobile/lib/data/repositories/marketing_repository_impl.dart b/prediqo_mobile/lib/data/repositories/marketing_repository_impl.dart index 201b8d9d..d0a01f0f 100644 --- a/prediqo_mobile/lib/data/repositories/marketing_repository_impl.dart +++ b/prediqo_mobile/lib/data/repositories/marketing_repository_impl.dart @@ -1,4 +1,3 @@ -import 'package:dio/dio.dart'; import '../../core/network/api_client.dart'; import '../../data/models/marketing_models.dart'; import '../../domain/repositories/marketing_repository.dart'; @@ -44,7 +43,8 @@ class _Store { } } -/// Public marketing reads. On failure, returns empty (never invents fictives). +/// Public marketing reads. Network failures throw so UI can show SectionError; +/// successful empty responses stay empty (no invented fictives). Cache only updates on success. class MarketingRepositoryImpl implements MarketingRepository { MarketingRepositoryImpl(this._api); @@ -99,30 +99,20 @@ class MarketingRepositoryImpl implements MarketingRepository { } Future _fetchActivity() async { - try { - final res = await _api.dio.get('/api/v1/marketing/activity-feed'); - final data = res.data; - if (data is! Map) return emptyMarketingActivityFeed; - return MarketingActivityFeed.fromJson(Map.from(data)); - } on DioException { - return emptyMarketingActivityFeed; - } catch (_) { - return emptyMarketingActivityFeed; - } + final res = await _api.dio.get('/api/v1/marketing/activity-feed'); + final data = res.data; + if (data is! Map) return emptyMarketingActivityFeed; + return MarketingActivityFeed.fromJson(Map.from(data)); } Future> _fetchWithdrawals() async { - try { - final res = await _api.dio.get('/api/v1/marketing/withdrawal-feed'); - final data = res.data; - final list = data is Map ? data['items'] : null; - if (list is! List) return const []; - return list - .whereType() - .map((e) => MarketingWithdrawalItem.fromJson(Map.from(e))) - .toList(); - } catch (_) { - return const []; - } + final res = await _api.dio.get('/api/v1/marketing/withdrawal-feed'); + final data = res.data; + final list = data is Map ? data['items'] : null; + if (list is! List) return const []; + return list + .whereType() + .map((e) => MarketingWithdrawalItem.fromJson(Map.from(e))) + .toList(); } } diff --git a/prediqo_mobile/lib/features/welcome/presentation/welcome_screen.dart b/prediqo_mobile/lib/features/welcome/presentation/welcome_screen.dart index d27d664f..0a3017c0 100644 --- a/prediqo_mobile/lib/features/welcome/presentation/welcome_screen.dart +++ b/prediqo_mobile/lib/features/welcome/presentation/welcome_screen.dart @@ -60,8 +60,12 @@ class _WelcomeScreenState extends State { bool _withdrawalsLoading = true; bool _adsRetrying = false; bool _gamesRetrying = false; + bool _activityRetrying = false; + bool _withdrawalsRetrying = false; String? _adsError; String? _gamesError; + String? _activityError; + String? _withdrawalsError; Future? _adsInFlight; Future? _gamesInFlight; @@ -249,15 +253,21 @@ class _WelcomeScreenState extends State { _activePlayersCount = 0; _activityVisible = const []; _activityLoading = false; + _activityRetrying = false; + _activityError = null; }); return Future.value(); } if (_activityInFlight != null) return _activityInFlight!; final keep = _activityPool.isNotEmpty && !force; final future = () async { - if (!keep) { - setState(() => _activityLoading = true); - } + setState(() { + if (!keep) _activityLoading = true; + if (force) { + _activityRetrying = true; + _activityError = null; + } + }); try { final feed = await sl().getActivityFeed(force: force); @@ -267,6 +277,8 @@ class _WelcomeScreenState extends State { _activePlayersCount = feed.activePlayersCount; _rotateActivityVisible(); _activityLoading = false; + _activityRetrying = false; + _activityError = null; }); _restartMarketingTimers( pollSeconds: feed.clientRefreshSeconds, @@ -274,8 +286,14 @@ class _WelcomeScreenState extends State { ); } catch (_) { if (!mounted) return; - // Keep last good pool if any; otherwise stay empty (no invented fictives). - setState(() => _activityLoading = false); + // Keep last good pool if any; otherwise show section error (no invented fictives). + setState(() { + _activityLoading = false; + _activityRetrying = false; + if (_activityPool.isEmpty) { + _activityError = AppException.connectionFailedMessage; + } + }); } }(); _activityInFlight = future.whenComplete(() => _activityInFlight = null); @@ -287,15 +305,21 @@ class _WelcomeScreenState extends State { setState(() { _withdrawals = const []; _withdrawalsLoading = false; + _withdrawalsRetrying = false; + _withdrawalsError = null; }); return Future.value(); } if (_withdrawalsInFlight != null) return _withdrawalsInFlight!; final keep = _withdrawals.isNotEmpty && !force; final future = () async { - if (!keep) { - setState(() => _withdrawalsLoading = true); - } + setState(() { + if (!keep) _withdrawalsLoading = true; + if (force) { + _withdrawalsRetrying = true; + _withdrawalsError = null; + } + }); try { final items = await sl().getWithdrawalFeed(force: force); @@ -303,11 +327,18 @@ class _WelcomeScreenState extends State { setState(() { _withdrawals = items; _withdrawalsLoading = false; + _withdrawalsRetrying = false; + _withdrawalsError = null; }); } catch (_) { if (!mounted) return; - // Keep last good list if any; otherwise stay empty. - setState(() => _withdrawalsLoading = false); + setState(() { + _withdrawalsLoading = false; + _withdrawalsRetrying = false; + if (_withdrawals.isEmpty) { + _withdrawalsError = AppException.connectionFailedMessage; + } + }); } }(); _withdrawalsInFlight = @@ -551,11 +582,17 @@ class _WelcomeScreenState extends State { activePlayersCount: _activePlayersCount, loading: _activityLoading, listGeneration: _activityGeneration, + error: _activityError, + retrying: _activityRetrying, + onRetry: () => _loadActivity(force: true), ), const SizedBox(height: 18), WelcomeWithdrawalTicker( items: _withdrawals, loading: _withdrawalsLoading, + error: _withdrawalsError, + retrying: _withdrawalsRetrying, + onRetry: () => _loadWithdrawals(force: true), ), const SizedBox(height: 22), Text( diff --git a/prediqo_mobile/lib/features/welcome/presentation/widgets/welcome_activity_ticker.dart b/prediqo_mobile/lib/features/welcome/presentation/widgets/welcome_activity_ticker.dart index e8ecaf91..f4b931f6 100644 --- a/prediqo_mobile/lib/features/welcome/presentation/widgets/welcome_activity_ticker.dart +++ b/prediqo_mobile/lib/features/welcome/presentation/widgets/welcome_activity_ticker.dart @@ -4,8 +4,10 @@ import '../../../../data/models/marketing_models.dart'; import '../../../../l10n/app_strings.dart'; import '../../../../shared/widgets/pred_card.dart'; import '../../../../shared/widgets/pred_skeleton.dart'; +import '../../../../shared/widgets/section_error.dart'; /// Live activity list — Playing only; trailing shows "Playing" (no stakes / no Won). +/// Title/structure always visible (Featured Games pattern); body is skeleton / list / error. class WelcomeActivityTicker extends StatelessWidget { const WelcomeActivityTicker({ super.key, @@ -13,12 +15,18 @@ class WelcomeActivityTicker extends StatelessWidget { required this.activePlayersCount, required this.loading, this.listGeneration = 0, + this.error, + this.retrying = false, + this.onRetry, }); final List items; final int activePlayersCount; final bool loading; final int listGeneration; + final String? error; + final bool retrying; + final VoidCallback? onRetry; static String formatActiveCount(int n) { final s = n.toString(); @@ -38,23 +46,10 @@ class WelcomeActivityTicker extends StatelessWidget { ? '${s.welcomeActivityTitle} · ${formatActiveCount(activePlayersCount)} ${s.welcomePlaying}' : s.welcomeActivityTitle; - if (loading && items.isEmpty) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - _ActivityHeader(title: title, subtitle: s.welcomeActivitySubtitle), - const SizedBox(height: 10), - const PredSkeletonCard(height: 120), - ], - ); - } - if (items.isEmpty) return const SizedBox.shrink(); - final playing = items .where((e) => e.statusLabel.toLowerCase() != 'won' && e.kind != 'win') .take(5) .toList(); - if (playing.isEmpty) return const SizedBox.shrink(); return Column( key: const Key('welcome_activity_ticker'), @@ -62,25 +57,45 @@ class WelcomeActivityTicker extends StatelessWidget { children: [ _ActivityHeader(title: title, subtitle: s.welcomeActivitySubtitle), const SizedBox(height: 10), - AnimatedSwitcher( - duration: const Duration(milliseconds: 380), - switchInCurve: Curves.easeOutCubic, - switchOutCurve: Curves.easeInCubic, - child: PredCard( - key: ValueKey('activity-gen-$listGeneration'), - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), - child: Column( - children: playing - .map( - (e) => _PlayingRow( - publicId: e.publicId, - playingLabel: s.welcomePlaying, - ), - ) - .toList(), + if (loading && playing.isEmpty) + const PredSkeletonCard(height: 120) + else if (error != null && playing.isEmpty) + SectionError( + message: error!, + compact: true, + retrying: retrying, + onRetry: onRetry, + ) + else if (playing.isNotEmpty) + AnimatedSwitcher( + duration: const Duration(milliseconds: 380), + switchInCurve: Curves.easeOutCubic, + switchOutCurve: Curves.easeInCubic, + child: PredCard( + key: ValueKey('activity-gen-$listGeneration'), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + child: Column( + children: playing + .map( + (e) => _PlayingRow( + publicId: e.publicId, + playingLabel: s.welcomePlaying, + ), + ) + .toList(), + ), + ), + ) + else + PredCard( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 16), + child: Text( + s.welcomeActivityEmpty, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: AppColors.textMuted, + ), ), ), - ), ], ); } @@ -163,87 +178,107 @@ class _PlayingRow extends StatelessWidget { } /// Confirmed withdrawals list (anonymized). +/// Title always visible; body is skeleton / list / SectionError. class WelcomeWithdrawalTicker extends StatelessWidget { const WelcomeWithdrawalTicker({ super.key, required this.items, required this.loading, + this.error, + this.retrying = false, + this.onRetry, }); final List items; final bool loading; + final String? error; + final bool retrying; + final VoidCallback? onRetry; @override Widget build(BuildContext context) { final s = context.strings; - if (loading && items.isEmpty) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - _WithdrawHeader(title: s.welcomeWithdrawalsTitle, subtitle: s.welcomeWithdrawalsSubtitle), - const SizedBox(height: 10), - const PredSkeletonCard(height: 120), - ], - ); - } - if (items.isEmpty) return const SizedBox.shrink(); + final visible = items.take(5).toList(); return Column( key: const Key('welcome_withdrawal_ticker'), crossAxisAlignment: CrossAxisAlignment.start, children: [ - _WithdrawHeader(title: s.welcomeWithdrawalsTitle, subtitle: s.welcomeWithdrawalsSubtitle), - const SizedBox(height: 10), - PredCard( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), - child: Column( - children: items.take(5).map((e) { - return Padding( - padding: const EdgeInsets.symmetric(vertical: 8), - child: Row( - children: [ - CircleAvatar( - radius: 14, - backgroundColor: AppColors.surfaceElevated, - child: Text( - e.publicId.isNotEmpty ? e.publicId[0].toUpperCase() : '?', - style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w700), - ), - ), - const SizedBox(width: 10), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - e.publicId, - style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 13), - ), - Text( - e.statusLabel, - style: const TextStyle( - color: AppColors.success, - fontSize: 11, - fontWeight: FontWeight.w600, - ), - ), - ], - ), - ), - Text( - '${e.amountLabel} USDT', - style: const TextStyle( - fontWeight: FontWeight.w800, - color: AppColors.accentGold, - fontSize: 13, - ), - ), - ], - ), - ); - }).toList(), - ), + _WithdrawHeader( + title: s.welcomeWithdrawalsTitle, + subtitle: s.welcomeWithdrawalsSubtitle, ), + const SizedBox(height: 10), + if (loading && visible.isEmpty) + const PredSkeletonCard(height: 120) + else if (error != null && visible.isEmpty) + SectionError( + message: error!, + compact: true, + retrying: retrying, + onRetry: onRetry, + ) + else if (visible.isNotEmpty) + PredCard( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + child: Column( + children: visible.map((e) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Row( + children: [ + CircleAvatar( + radius: 14, + backgroundColor: AppColors.surfaceElevated, + child: Text( + e.publicId.isNotEmpty ? e.publicId[0].toUpperCase() : '?', + style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w700), + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + e.publicId, + style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 13), + ), + Text( + e.statusLabel, + style: const TextStyle( + color: AppColors.success, + fontSize: 11, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ), + Text( + '${e.amountLabel} USDT', + style: const TextStyle( + fontWeight: FontWeight.w800, + color: AppColors.accentGold, + fontSize: 13, + ), + ), + ], + ), + ); + }).toList(), + ), + ) + else + PredCard( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 16), + child: Text( + s.welcomeWithdrawalsEmpty, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: AppColors.textMuted, + ), + ), + ), ], ); } @@ -266,6 +301,7 @@ class _WithdrawHeader extends StatelessWidget { children: [ Text( title, + key: const Key('welcome_withdrawals_title'), style: Theme.of(context).textTheme.titleMedium?.copyWith( fontWeight: FontWeight.w800, ), diff --git a/prediqo_mobile/lib/l10n/app_strings.dart b/prediqo_mobile/lib/l10n/app_strings.dart index 5abd27ad..3bc31e05 100644 --- a/prediqo_mobile/lib/l10n/app_strings.dart +++ b/prediqo_mobile/lib/l10n/app_strings.dart @@ -74,6 +74,14 @@ class AppStrings { 'Confirmed payouts (anonymized)', 'Paiements confirmés (anonymisés)', ); + String get welcomeActivityEmpty => t( + 'No live activity right now. Check back soon.', + 'Aucune activité en direct pour le moment. Revenez bientôt.', + ); + String get welcomeWithdrawalsEmpty => t( + 'No recent withdrawals to show.', + 'Aucun retrait récent à afficher.', + ); String get welcomeOpen => t('Open', 'Ouvrir'); diff --git a/prediqo_mobile/test/welcome_section_load_test.dart b/prediqo_mobile/test/welcome_section_load_test.dart index 44397a39..4bd213c9 100644 --- a/prediqo_mobile/test/welcome_section_load_test.dart +++ b/prediqo_mobile/test/welcome_section_load_test.dart @@ -369,7 +369,7 @@ void main() { await tester.pump(); }); - testWidgets('Welcome marketing soft-fails empty without connection banners', (tester) async { + testWidgets('Welcome marketing soft-fails with titles and section retry', (tester) async { _tallSurface(tester); final ads = _ControllableAds( cached: const [ @@ -393,12 +393,21 @@ void main() { ); await _pumpFrames(tester); - expect(find.textContaining('Connection failed'), findsNothing); - // Empty Live Activity (no invented fictives) — ticker collapses when pool is empty. - expect(find.byKey(const Key('welcome_activity_ticker')), findsNothing); - expect(find.textContaining('Playing'), findsNothing); + // Structure always visible (Featured Games pattern); section-level error only. + expect(find.byKey(const Key('welcome_activity_ticker')), findsOneWidget); + expect(find.byKey(const Key('welcome_activity_title')), findsOneWidget); + expect(find.byKey(const Key('welcome_withdrawal_ticker')), findsOneWidget); + expect(find.byKey(const Key('welcome_withdrawals_title')), findsOneWidget); + expect(find.textContaining('Connection failed'), findsWidgets); expect(find.byKey(const Key('welcome_stats_strip')), findsNothing); + // Independent retry restores activity without full page reload. + marketing.failActivity = null; + await tester.tap(find.byKey(const Key('section_error_retry')).first); + await _pumpFrames(tester); + expect(find.textContaining('Playing'), findsWidgets); + expect(find.byKey(const Key('welcome_activity_title')), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); await tester.pump(); });