diff --git a/apps/client/lib/core/app_router.dart b/apps/client/lib/core/app_router.dart index 74aab43..d9dfbdc 100644 --- a/apps/client/lib/core/app_router.dart +++ b/apps/client/lib/core/app_router.dart @@ -8,6 +8,7 @@ import '../features/message/compose_page.dart'; import '../features/message/message_page.dart'; import '../features/message/reply_draft.dart'; import '../features/settings/settings_page.dart'; +import '../services/mail_api_client.dart'; final appRouterProvider = Provider((ref) { return GoRouter( @@ -54,6 +55,18 @@ final appRouterProvider = Provider((ref) { ), ), ), + GoRoute( + // Pushed on top of any open composer so its input survives; popping returns to it. + path: '/compose/recover', + redirect: (context, state) => state.extra is ComposeDraft ? null : '/accounts', + pageBuilder: (context, state) { + final draft = state.extra! as ComposeDraft; + return _verticalPage( + state: state, + child: ComposePage(initialAccountId: draft.accountId, initialDraft: draft), + ); + }, + ), GoRoute( path: '/compose', pageBuilder: (context, state) => _verticalPage( diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index bc80478..2ac0626 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -283,6 +283,30 @@ class AppStrings { 'password' => _ko ? '비밀번호' : 'Password', _ => mode, }; + String get mailSending => _ko ? '메일을 보내는 중입니다.' : 'Sending mail...'; + String get undoSend => _ko ? '보내기 취소' : 'Undo send'; + String get sendCancelled => + _ko ? '보내기를 취소했습니다.' : 'Sending was cancelled.'; + String get sendAlreadySent => + _ko ? '이미 발송되어 취소할 수 없습니다.' : 'Already sent; it cannot be cancelled.'; + String get sendCancelFailed => + _ko ? '취소하지 못했습니다. 메일이 발송될 수 있습니다.' : 'Could not cancel; the mail may be sent.'; + String sendDeliveryFailed(String reason) => _ko + ? '메일을 보내지 못했습니다: $reason' + : 'The mail could not be delivered: $reason'; + String get sendFailedShort => _ko ? '발송에 실패했습니다.' : 'Sending failed.'; + String failedSendsCount(int n) => _ko ? '발송 실패 $n건' : '$n failed to send'; + String pendingSendsCount(int n) => _ko ? '보내기 대기 $n건' : '$n waiting to send'; + String get viewPendingSends => _ko ? '보기' : 'View'; + String get viewFailedSends => _ko ? '보기' : 'View'; + String get deleteFailedSend => _ko ? '삭제' : 'Delete'; + String get rewriteMail => _ko ? '다시 작성' : 'Rewrite'; + String get undoSendSetting => _ko ? '보내기 취소 시간' : 'Undo send delay'; + String get undoSendSettingDescription => _ko + ? '보낸 메일을 이 시간 동안 서버가 보관하며 취소할 수 있습니다.' + : 'The server holds sent mail for this long so you can cancel it.'; + String secondsLabel(int seconds) => + seconds == 0 ? (_ko ? '끔' : 'Off') : (_ko ? '$seconds초' : '${seconds}s'); String get registerThisDevice => _ko ? '이 기기 등록' : 'Register this device'; String get registerThisDeviceDescription => _ko ? '플랫폼 푸시 토큰을 메일 서버에 등록합니다.' diff --git a/apps/client/lib/features/message/compose_page.dart b/apps/client/lib/features/message/compose_page.dart index b54f96a..fc06f56 100644 --- a/apps/client/lib/features/message/compose_page.dart +++ b/apps/client/lib/features/message/compose_page.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; @@ -5,6 +7,8 @@ import 'package:go_router/go_router.dart'; import '../../core/i18n/language_controller.dart'; import '../../services/mail_api_client.dart'; import '../../widgets/app_shell.dart'; +import 'failed_sends.dart'; +import 'pending_sends.dart'; import 'reply_draft.dart'; import '../accounts/accounts_page.dart' show friendlyError; @@ -16,10 +20,14 @@ class ComposePage extends ConsumerStatefulWidget { const ComposePage({ super.key, this.initialAccountId, + this.initialDraft, this.reply, }); final String? initialAccountId; + + /// Reopened failed send (from `/compose/recover`). + final ComposeDraft? initialDraft; final ReplyDraft? reply; @override @@ -38,8 +46,14 @@ class _ComposePageState extends ConsumerState { void initState() { super.initState(); _accountId = widget.initialAccountId; + final draft = widget.initialDraft; final reply = widget.reply; - if (reply != null) { + if (draft != null) { + _toController.text = draft.to; + _ccController.text = draft.cc; + _subjectController.text = draft.subject; + _bodyController.text = draft.body; + } else if (reply != null) { _toController.text = reply.to.join(', '); _ccController.text = reply.cc.join(', '); _subjectController.text = reply.subject; @@ -71,7 +85,7 @@ class _ComposePageState extends ConsumerState { AppBar( leading: IconButton( tooltip: strings.close, - onPressed: () => context.go(returnPath), + onPressed: () => context.canPop() ? context.pop() : context.go(returnPath), icon: const Icon(Icons.close), ), title: Text(strings.compose), @@ -170,17 +184,29 @@ class _ComposePageState extends ConsumerState { return; } + final client = ref.read(mailApiClientProvider); + final delay = ref.read(undoSendDelayProvider); + final router = GoRouter.of(context); + final container = ProviderScope.containerOf(context); + final failedSends = container.read(failedSendsProvider.notifier); + final pendingSends = container.read(pendingSendsProvider.notifier); + final inReplyTo = widget.initialDraft?.inReplyTo ?? widget.reply?.inReplyTo; + final references = + widget.initialDraft?.references ?? widget.reply?.references ?? const []; + setState(() => _sending = true); + final SendReceipt receipt; try { - await ref.read(mailApiClientProvider).sendMail( - accountId: accountId, - to: to, - cc: _addresses(_ccController.text), - subject: _subjectController.text, - body: _bodyController.text, - inReplyTo: widget.reply?.inReplyTo, - references: widget.reply?.references ?? const [], - ); + receipt = await client.sendMail( + accountId: accountId, + to: to, + cc: _addresses(_ccController.text), + subject: _subjectController.text, + body: _bodyController.text, + delaySeconds: delay, + inReplyTo: inReplyTo, + references: references, + ); } catch (error) { // The draft stays on screen so the user can fix it and retry. if (mounted) setState(() => _sending = false); @@ -188,7 +214,40 @@ class _ComposePageState extends ConsumerState { return; } - if (mounted) context.go('/accounts/$accountId/mail'); + // The countdown comes from the server's deadline: show immediately (not behind + // older snackbars) and expire when the server actually sends. Earlier sends stay + // cancellable from the app-level pending list after clearSnackBars(). + if (delay > 0 && receipt.remaining > Duration.zero) { + pendingSends.add( + PendingSend( + id: receipt.id, + to: _toController.text, + subject: _subjectController.text, + ), + receipt.remaining, + ); + messenger.clearSnackBars(); + messenger.showSnackBar(SnackBar( + content: Text(strings.mailSending), + duration: receipt.remaining, + action: SnackBarAction( + label: strings.undoSend, + onPressed: () => cancelPendingSend( + client, strings, messenger, pendingSends, receipt.id), + ), + )); + } + + // Detached from this page on purpose: the composer closes right after sending. + unawaited(_reportFailure(client, receipt, strings, messenger, router, failedSends)); + + // Pushed pages (recovery compose) pop so the composer underneath keeps its input. + if (!mounted) return; + if (context.canPop()) { + context.pop(); + } else { + context.go('/accounts/$accountId/mail'); + } } List _addresses(String value) => value @@ -197,3 +256,55 @@ class _ComposePageState extends ConsumerState { .where((item) => item.isNotEmpty) .toList(); } + +/// Polls the queued send after the undo window; on failure offers to reopen the draft. +Future _reportFailure( + MailApiClient client, + SendReceipt receipt, + AppStrings strings, + ScaffoldMessengerState messenger, + GoRouter router, + FailedSendsNotifier failedSends, +) async { + final outcome = await awaitSendOutcome(client, receipt); + final draft = outcome?.draft; + if (outcome == null || draft == null) return; + final item = FailedSend(id: receipt.id, draft: draft, error: outcome.error ?? ''); + // Also kept in the app-level list: a later send's clearSnackBars() must not lose it. + failedSends.add(item); + messenger.showSnackBar(SnackBar( + content: Text(strings.sendDeliveryFailed(outcome.error ?? '')), + duration: const Duration(seconds: 15), + action: SnackBarAction( + label: strings.rewriteMail, + onPressed: () => rewriteFailedSend(router, failedSends, item), + ), + )); +} + +/// Waits out the undo window, then polls with backoff while the send is pending/sending, up to [maxWait]. +/// Returns the outcome only when the send failed. +Future awaitSendOutcome( + MailApiClient client, + SendReceipt receipt, { + Duration interval = const Duration(seconds: 2), + Duration maxInterval = const Duration(seconds: 15), + Duration maxWait = const Duration(minutes: 5), +}) async { + if (receipt.remaining > Duration.zero) await Future.delayed(receipt.remaining); + var waited = Duration.zero; + var delay = interval; + while (waited < maxWait) { + await Future.delayed(delay); + waited += delay; + try { + final outcome = await client.fetchSendOutcome(receipt.id); + if (outcome.status == 'failed') return outcome; + if (outcome.status == 'sent' || outcome.status == 'cancelled') return null; + } catch (_) { + // Transient error or expired entry: keep trying until maxWait. + } + delay = delay * 2 > maxInterval ? maxInterval : delay * 2; + } + return null; +} diff --git a/apps/client/lib/features/message/failed_sends.dart b/apps/client/lib/features/message/failed_sends.dart new file mode 100644 index 0000000..ca6e3b2 --- /dev/null +++ b/apps/client/lib/features/message/failed_sends.dart @@ -0,0 +1,136 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../core/i18n/language_controller.dart'; +import '../../services/mail_api_client.dart'; + +class FailedSend { + const FailedSend( + {required this.id, required this.draft, required this.error}); + final String id; + final ComposeDraft draft; + final String error; +} + +/// App-level so a failed draft outlives the page and snackbars that reported it. +class FailedSendsNotifier extends Notifier> { + @override + List build() => const []; + + void add(FailedSend item) => + state = [...state.where((e) => e.id != item.id), item]; + + void remove(String id) => state = [...state.where((e) => e.id != id)]; +} + +final failedSendsProvider = + NotifierProvider>( + FailedSendsNotifier.new); + +/// Reopens a failed draft in the stacked recovery composer and drops it from the list. +void rewriteFailedSend( + GoRouter router, FailedSendsNotifier notifier, FailedSend item) { + notifier.remove(item.id); + router.push('/compose/recover', extra: item.draft); +} + +/// Persistent single-row "N failed" indicator; the list lives in a bounded dialog so the +/// banner never grows and pushes the mail area off screen. +class FailedSendsBanner extends ConsumerWidget { + const FailedSendsBanner({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final items = ref.watch(failedSendsProvider); + if (items.isEmpty) return const SizedBox.shrink(); + final strings = ref.watch(appStringsProvider); + final scheme = Theme.of(context).colorScheme; + + return Material( + color: scheme.errorContainer, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Row( + children: [ + Expanded( + child: Text( + strings.failedSendsCount(items.length), + style: Theme.of(context).textTheme.labelLarge?.copyWith( + color: scheme.onErrorContainer, + fontWeight: FontWeight.w700, + ), + ), + ), + TextButton( + onPressed: () => showDialog( + context: context, + builder: (_) => + _FailedSendsDialog(router: GoRouter.of(context)), + ), + child: Text(strings.viewFailedSends), + ), + ], + ), + ), + ); + } +} + +class _FailedSendsDialog extends ConsumerWidget { + const _FailedSendsDialog({required this.router}); + final GoRouter router; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final items = ref.watch(failedSendsProvider); + final strings = ref.watch(appStringsProvider); + final notifier = ref.read(failedSendsProvider.notifier); + return AlertDialog( + title: Text(strings.failedSendsCount(items.length)), + content: SizedBox( + width: 480, + child: ListView.builder( + shrinkWrap: true, + itemCount: items.length, + itemBuilder: (context, i) { + final item = items[i]; + return Row( + children: [ + Expanded( + child: Text( + item.draft.subject.isEmpty + ? item.draft.to + : '${item.draft.subject} · ${item.draft.to}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + TextButton( + onPressed: () { + Navigator.of(context).pop(); + rewriteFailedSend(router, notifier, item); + }, + child: Text(strings.rewriteMail), + ), + TextButton( + onPressed: () { + if (items.length == 1) Navigator.of(context).pop(); + notifier.remove(item.id); + }, + child: Text(strings.deleteFailedSend), + ), + ], + ); + }, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(strings.close), + ), + ], + ); + } +} diff --git a/apps/client/lib/features/message/pending_sends.dart b/apps/client/lib/features/message/pending_sends.dart new file mode 100644 index 0000000..a4f2ef1 --- /dev/null +++ b/apps/client/lib/features/message/pending_sends.dart @@ -0,0 +1,163 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../core/i18n/language_controller.dart'; +import '../../services/mail_api_client.dart'; + +class PendingSend { + const PendingSend({required this.id, required this.to, required this.subject}); + final String id; + final String to; + final String subject; +} + +/// App-level list of sends still inside the undo window, so a newer send's snackbar +/// never takes away the way to cancel an earlier one. +class PendingSendsNotifier extends Notifier> { + final _timers = {}; + + @override + List build() { + ref.onDispose(() { + for (final t in _timers.values) { + t.cancel(); + } + }); + return const []; + } + + /// Drops the item by itself once the server deadline passes. + void add(PendingSend item, Duration remaining) { + _timers[item.id]?.cancel(); + _timers[item.id] = Timer(remaining, () => remove(item.id)); + state = [...state.where((e) => e.id != item.id), item]; + } + + void remove(String id) { + _timers.remove(id)?.cancel(); + state = [...state.where((e) => e.id != id)]; + } +} + +final pendingSendsProvider = + NotifierProvider>( + PendingSendsNotifier.new); + +/// Cancels on the server, drops the item, and reports the result in a snackbar. +Future cancelPendingSend( + MailApiClient client, + AppStrings strings, + ScaffoldMessengerState messenger, + PendingSendsNotifier pending, + String id, +) async { + String result; + try { + final status = await client.cancelSend(id); + result = switch (status) { + 'cancelled' => strings.sendCancelled, + 'failed' => strings.sendFailedShort, + _ => strings.sendAlreadySent, + }; + pending.remove(id); + } catch (_) { + result = strings.sendCancelFailed; + } + messenger.showSnackBar(SnackBar(content: Text(result))); +} + +/// Single-row "N waiting" indicator; each send can be cancelled from its dialog. +class PendingSendsBanner extends ConsumerWidget { + const PendingSendsBanner({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final items = ref.watch(pendingSendsProvider); + if (items.isEmpty) return const SizedBox.shrink(); + final strings = ref.watch(appStringsProvider); + final scheme = Theme.of(context).colorScheme; + + return Material( + color: scheme.secondaryContainer, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Row( + children: [ + Expanded( + child: Text( + strings.pendingSendsCount(items.length), + style: Theme.of(context).textTheme.labelLarge?.copyWith( + color: scheme.onSecondaryContainer, + fontWeight: FontWeight.w700, + ), + ), + ), + TextButton( + onPressed: () => showDialog( + context: context, + builder: (_) => _PendingSendsDialog( + messenger: ScaffoldMessenger.of(context)), + ), + child: Text(strings.viewPendingSends), + ), + ], + ), + ), + ); + } +} + +class _PendingSendsDialog extends ConsumerWidget { + const _PendingSendsDialog({required this.messenger}); + final ScaffoldMessengerState messenger; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final items = ref.watch(pendingSendsProvider); + final strings = ref.watch(appStringsProvider); + final notifier = ref.read(pendingSendsProvider.notifier); + final client = ref.read(mailApiClientProvider); + return AlertDialog( + title: Text(strings.pendingSendsCount(items.length)), + content: SizedBox( + width: 480, + child: ListView.builder( + shrinkWrap: true, + itemCount: items.length, + itemBuilder: (context, i) { + final item = items[i]; + return Row( + children: [ + Expanded( + child: Text( + item.subject.isEmpty + ? item.to + : '${item.subject} · ${item.to}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + TextButton( + onPressed: () { + if (items.length == 1) Navigator.of(context).pop(); + cancelPendingSend( + client, strings, messenger, notifier, item.id); + }, + child: Text(strings.undoSend), + ), + ], + ); + }, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(strings.close), + ), + ], + ); + } +} diff --git a/apps/client/lib/features/settings/settings_page.dart b/apps/client/lib/features/settings/settings_page.dart index 8466c21..aca683d 100644 --- a/apps/client/lib/features/settings/settings_page.dart +++ b/apps/client/lib/features/settings/settings_page.dart @@ -46,6 +46,26 @@ class SettingsPage extends ConsumerWidget { }, ), ), + ListTile( + leading: const Icon(Icons.undo), + title: Text(strings.undoSendSetting), + subtitle: Text(strings.undoSendSettingDescription), + trailing: DropdownButton( + value: ref.watch(undoSendDelayProvider), + items: [ + for (final seconds in undoSendDelayOptions) + DropdownMenuItem( + value: seconds, + child: Text(strings.secondsLabel(seconds)), + ), + ], + onChanged: (value) { + if (value != null) { + ref.read(undoSendDelayProvider.notifier).state = value; + } + }, + ), + ), ListTile( leading: const Icon(Icons.notifications_active_outlined), title: Text(strings.registerThisDevice), diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index 6617a28..dc38469 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -4,6 +4,43 @@ import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +const undoSendDelayOptions = [0, 5, 10, 20, 30]; + +/// Seconds the server holds a sent mail so it can still be cancelled. +final undoSendDelayProvider = StateProvider((ref) => 5); + +class SendReceipt { + const SendReceipt(this.id, this.remaining); + final String id; + final Duration remaining; +} + +class ComposeDraft { + const ComposeDraft({ + required this.accountId, + required this.to, + required this.subject, + required this.body, + this.cc = '', + this.inReplyTo, + this.references = const [], + }); + final String accountId; + final String to; + final String cc; + final String subject; + final String body; + final String? inReplyTo; + final List references; +} + +class SendOutcome { + const SendOutcome({required this.status, this.error, this.draft}); + final String status; + final String? error; + final ComposeDraft? draft; +} + final mailApiClientProvider = Provider((ref) { return MailApiClient( baseUrl: resolveMailApiBaseUrl(), @@ -242,24 +279,65 @@ class MailApiClient { }); } - Future sendMail({ + /// Queues the mail on the server; the receipt carries the id and the server's send deadline. + Future sendMail({ required String accountId, required List to, required String subject, required String body, + int delaySeconds = 5, List cc = const [], String? inReplyTo, List references = const [], }) async { - await _dio.post('/mail/send', data: { + final elapsed = Stopwatch()..start(); + final response = await _dio.post('/mail/send', data: { 'accountId': accountId, 'to': to, if (cc.isNotEmpty) 'cc': cc, 'subject': subject, 'text': body, + 'delaySeconds': delaySeconds, if (inReplyTo != null) 'inReplyTo': inReplyTo, if (inReplyTo != null && references.isNotEmpty) 'references': references, }); + final data = response.data as Map; + // remaining = sendAt - server now, so client clock skew does not matter. The whole + // round trip is subtracted too: response transit is unknown, so err on the short side. + final remaining = DateTime.parse(data['sendAt'] as String) + .difference(DateTime.parse(data['now'] as String)) - + elapsed.elapsed; + return SendReceipt(data['id'] as String, remaining); + } + + /// Returns the resulting status: 'cancelled', or why it could not be cancelled. + Future cancelSend(String id) async { + final response = await _dio.post( + '/mail/send/$id/cancel', + options: Options(validateStatus: (code) => code == 200 || code == 409), + ); + return (response.data as Map)['status'] as String; + } + + Future fetchSendOutcome(String id) async { + final response = await _dio.get('/mail/send/$id'); + final data = response.data as Map; + final draft = data['draft'] as Map?; + return SendOutcome( + status: data['status'] as String, + error: data['error'] as String?, + draft: draft == null + ? null + : ComposeDraft( + accountId: draft['accountId'] as String, + to: (draft['to'] as List).cast().join(', '), + cc: ((draft['cc'] as List?) ?? const []).cast().join(', '), + subject: draft['subject'] as String? ?? '', + body: draft['text'] as String? ?? '', + inReplyTo: draft['inReplyTo'] as String?, + references: ((draft['references'] as List?) ?? const []).cast(), + ), + ); } } diff --git a/apps/client/lib/widgets/app_shell.dart b/apps/client/lib/widgets/app_shell.dart index 6eccb3f..ae25f04 100644 --- a/apps/client/lib/widgets/app_shell.dart +++ b/apps/client/lib/widgets/app_shell.dart @@ -4,6 +4,8 @@ import 'package:go_router/go_router.dart'; import '../core/i18n/language_controller.dart'; import '../features/accounts/account_providers.dart'; +import '../features/message/failed_sends.dart'; +import '../features/message/pending_sends.dart'; class AppShell extends ConsumerWidget { const AppShell({ @@ -87,15 +89,23 @@ class AppShell extends ConsumerWidget { child: navigation, ) : null, - body: compact - ? child - : Row( - children: [ - SizedBox(width: 284, child: navigation), - const VerticalDivider(width: 1), - Expanded(child: child), - ], - ), + body: Column( + children: [ + const PendingSendsBanner(), + const FailedSendsBanner(), + Expanded( + child: compact + ? child + : Row( + children: [ + SizedBox(width: 284, child: navigation), + const VerticalDivider(width: 1), + Expanded(child: child), + ], + ), + ), + ], + ), floatingActionButton: floatingActionButton, ); } diff --git a/apps/client/test/compose_send_test.dart b/apps/client/test/compose_send_test.dart index c0a06bf..aa86610 100644 --- a/apps/client/test/compose_send_test.dart +++ b/apps/client/test/compose_send_test.dart @@ -27,21 +27,26 @@ class _SendingApi extends MailApiClient { _SendingApi() : super(baseUrl: 'http://127.0.0.1:1'); final sent = >[]; - Completer reply = Completer(); + Completer reply = Completer(); @override - Future sendMail({ + Future sendMail({ required String accountId, required List to, - List cc = const [], required String subject, required String body, + int delaySeconds = 5, + List cc = const [], String? inReplyTo, List references = const [], }) { sent.add(to); return reply.future; } + + @override + Future fetchSendOutcome(String id) async => + const SendOutcome(status: 'sent'); } Future<_SendingApi> _openComposer(WidgetTester tester) async { @@ -100,11 +105,14 @@ void main() { expect(find.byType(ComposePage), findsOneWidget); expect(find.widgetWithText(TextField, 'Hello'), findsOneWidget); - api.reply = Completer()..complete(); + api.reply = Completer() + ..complete(const SendReceipt('id', Duration.zero)); await tester.tap(find.byTooltip('보내기')); await tester.pumpAndSettle(); expect(api.sent, hasLength(2)); expect(find.byType(ComposePage), findsNothing); + // Let the post-send outcome poll finish so no timer is left pending. + await tester.pump(const Duration(seconds: 3)); }); testWidgets('asks for a recipient instead of sending an empty list', diff --git a/apps/client/test/send_failure_test.dart b/apps/client/test/send_failure_test.dart new file mode 100644 index 0000000..7696723 --- /dev/null +++ b/apps/client/test/send_failure_test.dart @@ -0,0 +1,447 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; + +import 'package:daily_postbox/features/message/compose_page.dart'; +import 'package:daily_postbox/features/message/failed_sends.dart'; +import 'package:daily_postbox/features/accounts/account_providers.dart'; +import 'package:daily_postbox/services/mail_api_client.dart'; +import 'package:daily_postbox/widgets/app_shell.dart'; + +const _draft = ComposeDraft( + accountId: 'a1', + to: 'x@example.com, y@example.com', + subject: 'Hello', + body: 'Body text', +); + +class _PollApi extends MailApiClient { + _PollApi(this.outcomes) : super(baseUrl: 'http://127.0.0.1:1'); + final List outcomes; + int calls = 0; + + @override + Future fetchSendOutcome(String id) async => + outcomes[calls++ < outcomes.length ? calls - 1 : outcomes.length - 1]; +} + +class _SendApi extends MailApiClient { + _SendApi() : super(baseUrl: 'http://127.0.0.1:1'); + + @override + Future sendMail({ + required String accountId, + required List to, + required String subject, + required String body, + int delaySeconds = 5, + List cc = const [], + String? inReplyTo, + List references = const [], + }) async => + const SendReceipt('id', Duration(seconds: 5)); + + @override + Future fetchSendOutcome(String id) async => + const SendOutcome(status: 'sent'); +} + +void main() { + _failedSendsTests(); + _pendingSendsTests(); + + test('undo countdown subtracts the round trip of a slow response', () async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(() => server.close(force: true)); + server.listen((req) async { + final now = DateTime.now().toUtc(); + await Future.delayed(const Duration(milliseconds: 400)); + req.response + ..headers.contentType = ContentType.json + ..write(jsonEncode({ + 'id': 'q1', + 'now': now.toIso8601String(), + 'sendAt': now.add(const Duration(seconds: 5)).toIso8601String(), + })); + await req.response.close(); + }); + // flutter_test answers every HTTP request with 400; use a real client here. + final receipt = await HttpOverrides.runWithHttpOverrides( + () => MailApiClient(baseUrl: 'http://127.0.0.1:${server.port}') + .sendMail( + accountId: 'a1', to: ['x@example.com'], subject: '', body: ''), + _RealHttp()); + expect(receipt.remaining, + lessThanOrEqualTo(const Duration(milliseconds: 4600))); + expect(receipt.remaining, greaterThan(Duration.zero)); + }); + const receipt = SendReceipt('id', Duration.zero); + const tick = Duration(milliseconds: 1); + + test('polls past sending and returns the failed outcome with its draft', + () async { + final api = _PollApi([ + const SendOutcome(status: 'pending'), + const SendOutcome(status: 'sending'), + const SendOutcome(status: 'failed', error: 'auth', draft: _draft), + ]); + final outcome = await awaitSendOutcome(api, receipt, interval: tick); + expect(outcome?.error, 'auth'); + expect(outcome?.draft?.subject, 'Hello'); + expect(api.calls, 3); + }); + + test('stops quietly once the mail is sent', () async { + final api = _PollApi([const SendOutcome(status: 'sent')]); + expect(await awaitSendOutcome(api, receipt, interval: tick), isNull); + expect(api.calls, 1); + }); + + testWidgets('composer reopens prefilled with the failed draft', + (tester) async { + await tester.pumpWidget(ProviderScope( + overrides: [ + composeAccountsProvider.overrideWith((ref) async => const []), + ], + child: const MaterialApp(home: ComposePage(initialDraft: _draft)), + )); + await tester.pump(); + expect(find.text('x@example.com, y@example.com'), findsOneWidget); + expect(find.text('Hello'), findsOneWidget); + expect(find.text('Body text'), findsOneWidget); + }); + + test('keeps polling past 10 tries while still sending, until failure', + () async { + final api = _PollApi([ + for (var i = 0; i < 25; i++) const SendOutcome(status: 'sending'), + const SendOutcome(status: 'failed', error: 'late', draft: _draft), + ]); + final outcome = await awaitSendOutcome(api, receipt, + interval: tick, maxInterval: tick, maxWait: const Duration(seconds: 5)); + expect(outcome?.error, 'late'); + expect(api.calls, 26); + }); + + test('gives up after maxWait while still pending', () async { + final api = _PollApi([const SendOutcome(status: 'pending')]); + expect( + await awaitSendOutcome(api, receipt, + interval: tick, + maxInterval: tick, + maxWait: const Duration(milliseconds: 20)), + isNull); + }); + + testWidgets('recovery is stacked: original compose input survives pop', + (tester) async { + final router = GoRouter(routes: [ + GoRoute(path: '/', builder: (_, __) => const ComposePage()), + GoRoute( + path: '/compose/recover', + builder: (_, state) => + ComposePage(initialDraft: state.extra as ComposeDraft), + ), + ]); + await tester.pumpWidget(ProviderScope( + overrides: [ + composeAccountsProvider.overrideWith((ref) async => const []) + ], + child: MaterialApp.router(routerConfig: router), + )); + await tester.pump(); + await tester.enterText(find.byType(TextField).first, 'typing in progress'); + router.push('/compose/recover', extra: _draft); + await tester.pumpAndSettle(); + expect(find.text('Hello'), findsOneWidget); + router.pop(); + await tester.pumpAndSettle(); + expect(find.text('typing in progress'), findsOneWidget); + expect(find.text('Hello'), findsNothing); + }); + + testWidgets( + 'sending from recovery pops back to the original compose with undo snackbar', + (tester) async { + final router = GoRouter(routes: [ + GoRoute(path: '/', builder: (_, __) => const ComposePage()), + GoRoute( + path: '/compose/recover', + builder: (_, state) => + ComposePage(initialDraft: state.extra as ComposeDraft), + ), + ]); + await tester.pumpWidget(ProviderScope( + overrides: [ + mailApiClientProvider.overrideWithValue(_SendApi()), + composeAccountsProvider.overrideWith((ref) async => const [ + MailAccountSummary( + id: 'a1', + providerId: 'p', + emailAddress: 'me@example.test', + incomingProtocol: 'imap', + authMode: 'password', + syncStatus: 'idle', + syncError: null, + initialSync: null, + lastSyncedAtLabel: '', + ), + ]), + ], + child: MaterialApp.router(routerConfig: router), + )); + await tester.pump(); + await tester.enterText(find.byType(TextField).first, 'typing in progress'); + router.push('/compose/recover', extra: _draft); + await tester.pumpAndSettle(); + expect(find.text('Hello'), findsOneWidget); + + await tester.tap(find.byIcon(Icons.send_outlined)); + await tester.pumpAndSettle(const Duration(milliseconds: 100)); + + expect(find.text('typing in progress'), findsOneWidget); + expect(find.text('Hello'), findsNothing); + expect(find.byType(SnackBar), findsOneWidget); + expect(find.byType(SnackBarAction), findsOneWidget); + + // Let the snackbar and the detached outcome poll finish before teardown. + await tester.pump(const Duration(seconds: 6)); + await tester.pump(const Duration(seconds: 3)); + }); +} + +class _FailApi extends _SendApi { + @override + Future fetchSendOutcome(String id) async => + const SendOutcome(status: 'failed', error: 'auth', draft: _draft); +} + +void _failedSendsTests() { + Future pumpApp(WidgetTester tester) async { + Widget shell(Widget child) => + AppShell(selectedDestinationId: 'x', child: child); + final router = GoRouter(routes: [ + GoRoute( + path: '/', + builder: (_, __) => const ComposePage(initialAccountId: 'a1'), + ), + GoRoute( + path: '/accounts/:id/mail', + builder: (_, __) => shell(const Text('mailbox')), + ), + GoRoute( + path: '/compose/recover', + builder: (_, state) => + ComposePage(initialDraft: state.extra as ComposeDraft), + ), + ]); + await tester.pumpWidget(ProviderScope( + overrides: [ + mailApiClientProvider.overrideWithValue(_FailApi()), + accountsProvider.overrideWith((ref) async => const []), + composeAccountsProvider.overrideWith((ref) async => const [ + MailAccountSummary( + id: 'a1', + providerId: 'p', + emailAddress: 'me@example.test', + incomingProtocol: 'imap', + authMode: 'password', + syncStatus: 'idle', + syncError: null, + initialSync: null, + lastSyncedAtLabel: '', + ), + ]), + ], + child: MaterialApp.router(routerConfig: router), + )); + await tester.pump(); + return router; + } + + testWidgets( + 'failed draft stays recoverable from banner after snackbars are cleared', + (tester) async { + final router = await pumpApp(tester); + await tester.enterText(find.byType(TextField).first, 'x@example.test'); + await tester.tap(find.byIcon(Icons.send_outlined)); + await tester.pumpAndSettle(const Duration(milliseconds: 100)); + // Undo window (5s) + first poll (2s), then the failure surfaces. + await tester.pump(const Duration(seconds: 6)); + await tester.pump(const Duration(seconds: 3)); + expect(find.text('발송 실패 1건'), findsOneWidget); + expect(find.byType(SnackBarAction), findsOneWidget); + + // A new send does this to the earlier failure snackbar. + ScaffoldMessenger.of(tester.element(find.text('mailbox'))).clearSnackBars(); + await tester.pumpAndSettle(); + expect(find.byType(SnackBar), findsNothing); + expect(find.text('발송 실패 1건'), findsOneWidget); + + await tester.tap(find.text('보기')); + await tester.pumpAndSettle(); + await tester.tap(find.text('다시 작성')); + await tester.pumpAndSettle(); + expect(router.state.uri.path, '/compose/recover'); + expect(find.text('Hello'), findsOneWidget); + router.pop(); + await tester.pumpAndSettle(); + expect(find.text('발송 실패 1건'), findsNothing); + }); + + testWidgets('banner delete drops the failed draft', (tester) async { + await pumpApp(tester); + await tester.enterText(find.byType(TextField).first, 'x@example.test'); + await tester.tap(find.byIcon(Icons.send_outlined)); + await tester.pumpAndSettle(const Duration(milliseconds: 100)); + await tester.pump(const Duration(seconds: 6)); + await tester.pump(const Duration(seconds: 3)); + await tester.tap(find.text('보기')); + await tester.pumpAndSettle(); + await tester.tap(find.text('삭제')); + await tester.pumpAndSettle(); + expect(find.text('발송 실패 1건'), findsNothing); + }); + + testWidgets( + '30 failures stay one compact row; dialog list is bounded and rewrite works', + (tester) async { + tester.view.physicalSize = const Size(800, 500); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final router = await pumpApp(tester); + final container = + ProviderScope.containerOf(tester.element(find.byType(MaterialApp))); + router.go('/accounts/a1/mail'); + await tester.pumpAndSettle(); + for (var i = 0; i < 30; i++) { + container.read(failedSendsProvider.notifier).add(FailedSend( + id: 'f$i', + draft: ComposeDraft( + accountId: 'a1', + to: 't$i@example.com', + subject: 'S$i', + body: 'b'), + error: 'e')); + } + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.text('발송 실패 30건'), findsOneWidget); + expect(find.text('mailbox'), findsOneWidget); + expect(tester.getRect(find.text('mailbox')).bottom, lessThan(500)); + expect(find.text('다시 작성'), findsNothing); + + await tester.tap(find.text('보기')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(tester.getRect(find.byType(AlertDialog)).height, + lessThanOrEqualTo(500)); + + await tester.tap(find.text('다시 작성').first); + await tester.pumpAndSettle(); + expect(router.state.uri.path, '/compose/recover'); + expect(find.text('S0'), findsOneWidget); + router.pop(); + await tester.pumpAndSettle(); + expect(find.text('발송 실패 29건'), findsOneWidget); + }); +} + +class _RealHttp extends HttpOverrides {} + +class _UndoApi extends _SendApi { + int sent = 0; + final cancelled = []; + + @override + Future sendMail({ + required String accountId, + required List to, + required String subject, + required String body, + int delaySeconds = 5, + List cc = const [], + String? inReplyTo, + List references = const [], + }) async => + SendReceipt('s${++sent}', const Duration(seconds: 30)); + + @override + Future cancelSend(String id) async { + cancelled.add(id); + return 'cancelled'; + } +} + +void _pendingSendsTests() { + testWidgets( + 'two sends in the undo window: the first stays cancellable after the second snackbar', + (tester) async { + final api = _UndoApi(); + final router = GoRouter(routes: [ + GoRoute( + path: '/', + builder: (_, __) => const ComposePage(initialAccountId: 'a1'), + ), + GoRoute( + path: '/accounts/:id/mail', + builder: (_, __) => + const AppShell(selectedDestinationId: 'x', child: Text('mailbox')), + ), + ]); + await tester.pumpWidget(ProviderScope( + overrides: [ + mailApiClientProvider.overrideWithValue(api), + accountsProvider.overrideWith((ref) async => const []), + composeAccountsProvider.overrideWith((ref) async => const [ + MailAccountSummary( + id: 'a1', + providerId: 'p', + emailAddress: 'me@example.test', + incomingProtocol: 'imap', + authMode: 'password', + syncStatus: 'idle', + syncError: null, + initialSync: null, + lastSyncedAtLabel: '', + ), + ]), + ], + child: MaterialApp.router(routerConfig: router), + )); + await tester.pump(); + + for (final subject in ['First', 'Second']) { + router.go('/'); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField).first, 'x@example.test'); + await tester.enterText(find.byType(TextField).at(1), subject); + await tester.tap(find.byIcon(Icons.send_outlined)); + await tester.pumpAndSettle(const Duration(milliseconds: 100)); + } + // Only the newest snackbar is visible; both sends are listed. + expect(find.byType(SnackBarAction), findsOneWidget); + expect(find.text('보내기 대기 2건'), findsOneWidget); + + await tester.tap(find.text('보기')); + await tester.pumpAndSettle(); + await tester.tap(find + .descendant(of: find.byType(AlertDialog), matching: find.text('보내기 취소')) + .first); + await tester.pumpAndSettle(); + expect(api.cancelled, ['s1']); + expect(find.text('보내기 대기 1건'), findsWidgets); + await tester.tap(find.text('닫기')); + await tester.pumpAndSettle(); + + // The rest expires with the server deadline. + await tester.pump(const Duration(seconds: 31)); + await tester.pumpAndSettle(); + expect(find.text('보내기 대기 1건'), findsNothing); + await tester.pump(const Duration(seconds: 10)); + }); +} diff --git a/apps/server/package.json b/apps/server/package.json index c40dd00..ae37be8 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "tsx src/server.ts", - "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/messageFlags.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/searchQuery.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/imapCapabilities.test.ts test/attachments.test.ts test/attachmentAccess.test.ts test/mailSearchAccess.test.ts test/replyRecipients.test.ts test/existsQueue.test.ts test/pop3Unsupported.test.ts test/deletedAccountSync.test.ts test/oauthSessionExpiry.test.ts test/noopPushNotifier.test.ts test/serverExposure.test.ts test/uidValidity.test.ts test/accountScopedMessage.test.ts test/customServerAccount.test.ts", + "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/messageFlags.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/searchQuery.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/imapCapabilities.test.ts test/attachments.test.ts test/attachmentAccess.test.ts test/mailSearchAccess.test.ts test/replyRecipients.test.ts test/sendQueue.test.ts test/existsQueue.test.ts test/pop3Unsupported.test.ts test/deletedAccountSync.test.ts test/oauthSessionExpiry.test.ts test/noopPushNotifier.test.ts test/serverExposure.test.ts test/uidValidity.test.ts test/accountScopedMessage.test.ts test/customServerAccount.test.ts", "typecheck": "tsc --noEmit", "start": "node dist/server.js", "build": "tsc" diff --git a/apps/server/src/api/routes.ts b/apps/server/src/api/routes.ts index 589fa42..674fcdc 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -3,6 +3,12 @@ import { randomUUID } from "node:crypto"; import { z } from "zod"; import type { SearchObject } from "imapflow"; import type { MailSender } from "../mail/MailSender.js"; +import { + SendQueue, + SendQueueFullError, + defaultUndoDelaySeconds, + undoDelaySeconds +} from "../mail/SendQueue.js"; import type { AttachmentDownload, AuthMode, @@ -35,6 +41,12 @@ const sendSchema = z.object({ subject: z.string().default(""), html: z.string().optional(), text: z.string().optional(), + delaySeconds: z + .number() + .refine((value) => (undoDelaySeconds as readonly number[]).includes(value), { + message: `delaySeconds must be one of ${undoDelaySeconds.join(", ")}` + }) + .default(defaultUndoDelaySeconds), inReplyTo: z.string().regex(/^<[^<>\s]+>$/).optional(), references: z.array(z.string().regex(/^<[^<>\s]+>$/)).optional() }); @@ -120,6 +132,7 @@ export async function registerRoutes( app: FastifyInstance, deps: { sender: MailSender; + sendQueue?: SendQueue; accounts: AccountRepository; validateAccount: (account: MailAccount) => Promise; fetchMessageContent: ( @@ -149,6 +162,10 @@ export async function registerRoutes( stopAccountSync: (accountId: string) => Promise; } ): Promise { + const sendQueue = + deps.sendQueue ?? + new SendQueue(deps.sender, (error) => app.log.error({ err: error }, "mail send failed")); + app.get("/health", async () => ({ ok: true })); app.get("/providers", async () => { @@ -526,16 +543,48 @@ export async function registerRoutes( })); }); - app.post("/mail/send", async (request, reply) => { - const draft = sendSchema.parse(request.body) as OutgoingMessageDraft; + // 10 MiB: explicit cap on the send body (Fastify default is 1 MiB). + app.post("/mail/send", { bodyLimit: 10 * 1024 * 1024 }, async (request, reply) => { + const { delaySeconds, ...parsed } = sendSchema.parse(request.body); + const draft = parsed as OutgoingMessageDraft; const account = await deps.accounts.getAccount(draft.accountId); if (!account) { return reply.code(404).send({ error: "Account not found" }); } - const result = await deps.sender.send(account, draft); - return reply.code(202).send(result); + let queued: { id: string; sendAt: Date }; + try { + queued = sendQueue.enqueue(account, draft, delaySeconds); + } catch (error) { + if (error instanceof SendQueueFullError) { + return reply.code(429).send({ error: "Too many pending sends" }); + } + throw error; + } + return reply + .code(202) + .send({ id: queued.id, delaySeconds, sendAt: queued.sendAt.toISOString(), now: new Date().toISOString() }); + }); + + app.get("/mail/send/:id", async (request, reply) => { + const { id } = request.params as { id: string }; + const info = sendQueue.status(id); + if (!info) return reply.code(404).send({ error: "Send request not found" }); + return info; + }); + + app.post("/mail/send/:id/cancel", async (request, reply) => { + const { id } = request.params as { id: string }; + const status = sendQueue.cancel(id); + + if (!status) { + return reply.code(404).send({ error: "Send request not found" }); + } + if (status !== "cancelled") { + return reply.code(409).send({ error: "Message already sent", status }); + } + return reply.code(200).send({ id, status }); }); app.post("/devices/push-token", async (request, reply) => { diff --git a/apps/server/src/mail/SendQueue.ts b/apps/server/src/mail/SendQueue.ts new file mode 100644 index 0000000..1733a63 --- /dev/null +++ b/apps/server/src/mail/SendQueue.ts @@ -0,0 +1,160 @@ +import { randomUUID } from "node:crypto"; +import type { MailAccount, OutgoingMessageDraft } from "../domain/types.js"; +import type { MailSender } from "./MailSender.js"; + +export const undoDelaySeconds = [0, 5, 10, 20, 30] as const; +export const defaultUndoDelaySeconds = 5; + +export type SendStatus = "pending" | "sending" | "sent" | "failed" | "cancelled"; + +export interface SendStatusInfo { + status: SendStatus; + sendAt: string; + error?: string; + /** Only for failed sends, so the client can reopen the draft. */ + draft?: OutgoingMessageDraft; +} + +export interface SendQueueLimits { + maxEntries: number; + maxPendingPerAccount: number; + maxConcurrentSends: number; +} + +export const defaultSendQueueLimits: SendQueueLimits = { + maxEntries: 200, + maxPendingPerAccount: 20, + maxConcurrentSends: 4 +}; + +export class SendQueueFullError extends Error { + constructor() { + super("Send queue is full"); + } +} + +interface Entry { + accountId: string; + settled: boolean; + status: SendStatus; + sendAt: Date; + draft: OutgoingMessageDraft; + error?: string; + timer?: NodeJS.Timeout; + sending?: Promise; + run: () => Promise; +} + +// shortcut: queue lives in memory; pending mail is flushed on shutdown, but a crash loses it. Persist with scheduled send (issue #34 stage 2). +export class SendQueue { + private readonly entries = new Map(); + private readonly limits: SendQueueLimits; + private activeSends = 0; + private readonly waiters: Array<() => void> = []; + + constructor( + private readonly sender: MailSender, + private readonly onError: (error: unknown) => void = () => undefined, + private readonly retainMs = 10 * 60_000, // >= client polling horizon (5 min) + limits: Partial = {} + ) { + this.limits = { ...defaultSendQueueLimits, ...limits }; + } + + private async acquire(): Promise { + if (this.activeSends < this.limits.maxConcurrentSends) { + this.activeSends++; + return; + } + // The releasing send hands its slot over, so activeSends stays unchanged. + await new Promise((resolve) => this.waiters.push(resolve)); + } + + private release(): void { + const next = this.waiters.shift(); + if (next) next(); + else this.activeSends--; + } + + enqueue( + account: MailAccount, + draft: OutgoingMessageDraft, + delaySeconds: number + ): { id: string; sendAt: Date } { + if (this.entries.size >= this.limits.maxEntries) throw new SendQueueFullError(); + let pendingForAccount = 0; + for (const e of this.entries.values()) { + if (e.accountId === account.id && !e.settled) pendingForAccount++; + } + if (pendingForAccount >= this.limits.maxPendingPerAccount) throw new SendQueueFullError(); + + const id = randomUUID(); + const entry: Entry = { + accountId: account.id, + settled: false, + status: "pending", + sendAt: new Date(Date.now() + delaySeconds * 1000), + draft, + run: () => { + // flush() during an in-flight send must await the same promise, never send twice. + if (entry.sending) return entry.sending; + if (entry.status !== "pending") return Promise.resolve(); + clearTimeout(entry.timer); + entry.status = "sending"; + entry.sending = (async () => { + await this.acquire(); + try { + await this.sender.send(account, draft); + entry.status = "sent"; + } catch (error) { + entry.status = "failed"; + entry.error = error instanceof Error ? error.message : String(error); + this.onError(error); + } finally { + this.release(); + } + entry.settled = true; + this.expire(id); + })(); + return entry.sending; + } + }; + entry.timer = setTimeout(() => void entry.run(), delaySeconds * 1000); + this.entries.set(id, entry); + return { id, sendAt: entry.sendAt }; + } + + /** Result of a queued send; failed entries keep their draft until retention ends. */ + status(id: string): SendStatusInfo | undefined { + const entry = this.entries.get(id); + if (!entry) return undefined; + const info: SendStatusInfo = { status: entry.status, sendAt: entry.sendAt.toISOString() }; + if (entry.status === "failed") { + info.error = entry.error; + info.draft = entry.draft; + } + return info; + } + + private expire(id: string): void { + setTimeout(() => this.entries.delete(id), this.retainMs).unref(); + } + + /** Returns undefined for unknown id, otherwise the status after the attempt. */ + cancel(id: string): SendStatus | undefined { + const entry = this.entries.get(id); + if (!entry) return undefined; + if (entry.status === "pending") { + clearTimeout(entry.timer); + entry.status = "cancelled"; + entry.settled = true; + this.expire(id); + } + return entry.status; + } + + /** Send everything still waiting (server shutdown). */ + async flush(): Promise { + await Promise.all([...this.entries.values()].map((entry) => entry.run())); + } +} diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 5d52276..4712f7e 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -14,6 +14,7 @@ import { InMemoryAccountRepository } from "./workers/AccountRepository.js"; import type { AccountRepository } from "./workers/AccountRepository.js"; import { LocalFileAccountRepository } from "./workers/LocalFileAccountRepository.js"; import { MailSyncWorker } from "./workers/MailSyncWorker.js"; +import { SendQueue } from "./mail/SendQueue.js"; import { registerRoutes } from "./api/routes.js"; import { OAuthAccountFlow } from "./auth/OAuthAccountFlow.js"; import { OAuthTokenManager } from "./auth/OAuthTokenManager.js"; @@ -47,8 +48,14 @@ const worker = new MailSyncWorker(accounts, imap, pop3, push, { imapReconnectMaxDelayMs: 60_000 }); +const sendQueue = new SendQueue(sender, (error) => + app.log.error({ err: error }, "mail send failed") +); +app.addHook("onClose", async () => sendQueue.flush()); + await registerRoutes(app, { sender, + sendQueue, accounts, validateAccount: async (account) => { if (account.incomingProtocol === "imap") { @@ -139,6 +146,10 @@ await app.listen({ host: env.HOST }); +for (const signal of ["SIGINT", "SIGTERM"] as const) { + process.once(signal, () => void app.close().finally(() => process.exit(0))); +} + function createPushNotifier(): PushNotifier { if (env.PUSH_PROVIDER !== "apns") return new NoopPushNotifier(); if (!env.APNS_KEY_PATH || !env.APNS_KEY_ID || !env.APNS_TEAM_ID) { diff --git a/apps/server/test/sendQueue.test.ts b/apps/server/test/sendQueue.test.ts new file mode 100644 index 0000000..486882f --- /dev/null +++ b/apps/server/test/sendQueue.test.ts @@ -0,0 +1,191 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import Fastify from "fastify"; +import type { MailAccount } from "../src/domain/types.js"; +import { registerRoutes } from "../src/api/routes.js"; +import { SendQueue } from "../src/mail/SendQueue.js"; +import { InMemoryAccountRepository } from "../src/workers/AccountRepository.js"; + +async function setup() { + const now = new Date(); + const accounts = new InMemoryAccountRepository(); + await accounts.addAccount({ + id: "account-1", + userId: "demo-user", + providerId: "naver", + emailAddress: "user@example.com", + authMode: "app-password", + incomingProtocol: "imap", + encryptedSecretRef: "app-password", + syncStatus: "idle", + createdAt: now, + updatedAt: now + } as MailAccount); + const sent: string[] = []; + const sender = { + send: async (_a: MailAccount, draft: { subject: string }) => { + sent.push(draft.subject); + return { accepted: [], rejected: [] }; + } + }; + const errors: unknown[] = []; + const sendQueue = new SendQueue(sender as never, (e) => errors.push(e)); + const app = Fastify(); + await registerRoutes(app, { accounts, sender: sender as never, sendQueue } as never); + const post = (delaySeconds: number) => + app.inject({ + method: "POST", + url: "/mail/send", + payload: { accountId: "account-1", to: ["a@example.com"], subject: "hi", delaySeconds } + }); + return { app, sent, errors, sendQueue, post }; +} + +test("cancel before delay prevents sending", async () => { + const { app, sent, post } = await setup(); + const { id } = (await post(30)).json(); + const cancel = await app.inject({ method: "POST", url: `/mail/send/${id}/cancel` }); + assert.equal(cancel.statusCode, 200); + await new Promise((r) => setTimeout(r, 20)); + assert.deepEqual(sent, []); +}); + +test("delay 0 sends, later cancel returns 409", async () => { + const { app, sent, post } = await setup(); + const { id } = (await post(0)).json(); + await new Promise((r) => setTimeout(r, 30)); + assert.deepEqual(sent, ["hi"]); + const cancel = await app.inject({ method: "POST", url: `/mail/send/${id}/cancel` }); + assert.equal(cancel.statusCode, 409); +}); + +test("unknown id 404 and invalid delay rejected", async () => { + const { app, post } = await setup(); + const cancel = await app.inject({ method: "POST", url: "/mail/send/nope/cancel" }); + assert.equal(cancel.statusCode, 404); + assert.notEqual((await post(7)).statusCode, 202); +}); + +test("flush sends pending mail once and reports failures", async () => { + const { sent, sendQueue, post } = await setup(); + await post(30); + await sendQueue.flush(); + await sendQueue.flush(); + assert.deepEqual(sent, ["hi"]); +}); + +test("flush awaits an in-flight send without sending twice", async () => { + let release!: () => void; + const gate = new Promise((r) => (release = r)); + const sent: string[] = []; + const sender = { send: async (_a: unknown, d: { subject: string }) => { sent.push(d.subject); await gate; } }; + const queue = new SendQueue(sender as never); + queue.enqueue({} as MailAccount, { subject: "x" } as never, 0); + await new Promise((r) => setTimeout(r, 10)); + let flushed = false; + const flushing = queue.flush().then(() => (flushed = true)); + await new Promise((r) => setTimeout(r, 10)); + assert.equal(flushed, false); + release(); + await flushing; + assert.deepEqual(sent, ["x"]); +}); + +test("cancelled entries are removed after retention", async () => { + const queue = new SendQueue({ send: async () => undefined } as never, undefined, 10); + const { id } = queue.enqueue({} as MailAccount, {} as never, 30); + assert.equal(queue.cancel(id), "cancelled"); + await new Promise((r) => setTimeout(r, 40)); + assert.equal(queue.cancel(id), undefined); +}); + +test("enqueue over per-account or total limit is rejected with 429", async () => { + const sender = { send: async () => undefined }; + const queue = new SendQueue(sender as never, undefined, 60_000, { maxPendingPerAccount: 2, maxEntries: 3 }); + const app = Fastify(); + const accounts = new InMemoryAccountRepository(); + const now = new Date(); + for (const id of ["a", "b"]) { + await accounts.addAccount({ id, userId: "u", providerId: "naver", emailAddress: `${id}@example.com`, + authMode: "app-password", incomingProtocol: "imap", encryptedSecretRef: "x", syncStatus: "idle", + createdAt: now, updatedAt: now } as MailAccount); + } + await registerRoutes(app, { accounts, sender: sender as never, sendQueue: queue } as never); + const post = (accountId: string) => + app.inject({ method: "POST", url: "/mail/send", payload: { accountId, to: ["x@example.com"], subject: "s", delaySeconds: 30 } }); + assert.equal((await post("a")).statusCode, 202); + assert.equal((await post("a")).statusCode, 202); + assert.equal((await post("a")).statusCode, 429); + assert.equal((await post("b")).statusCode, 202); + assert.equal((await post("b")).statusCode, 429); + await queue.flush(); +}); + +test("concurrent SMTP sends are capped and waiting entries still go out", async () => { + let running = 0; + let peak = 0; + const sender = { + send: async () => { + peak = Math.max(peak, ++running); + await new Promise((r) => setTimeout(r, 20)); + running--; + } + }; + const queue = new SendQueue(sender as never, undefined, 60_000, { maxConcurrentSends: 2 }); + for (let i = 0; i < 5; i++) queue.enqueue({ id: "a" } as MailAccount, {} as never, 0); + await queue.flush(); + assert.equal(peak, 2); + assert.equal(running, 0); +}); + +test("enqueue response carries the server sendAt", async () => { + const { post, sendQueue } = await setup(); + const before = Date.now(); + const body = (await post(30)).json(); + assert.equal(Date.parse(body.sendAt) - Date.parse(body.now), 30_000); + assert.ok(Date.parse(body.now) >= before); + await sendQueue.flush(); +}); + +test("failed send keeps its draft and error for status polling; cancel reports failed", async () => { + const sender = { send: async () => { throw new Error("535 auth failed"); } }; + const errors: unknown[] = []; + const sendQueue = new SendQueue(sender as never, (e) => errors.push(e)); + const accounts = new InMemoryAccountRepository(); + const now = new Date(); + await accounts.addAccount({ id: "account-1", userId: "u", providerId: "naver", emailAddress: "u@example.com", + authMode: "app-password", incomingProtocol: "imap", encryptedSecretRef: "x", syncStatus: "idle", + createdAt: now, updatedAt: now } as MailAccount); + const app = Fastify(); + await registerRoutes(app, { accounts, sender: sender as never, sendQueue } as never); + const { id } = (await app.inject({ method: "POST", url: "/mail/send", + payload: { accountId: "account-1", to: ["a@example.com"], subject: "hi", text: "body", delaySeconds: 0 } })).json(); + await new Promise((r) => setTimeout(r, 30)); + const res = await app.inject({ method: "GET", url: `/mail/send/${id}` }); + assert.equal(res.statusCode, 200); + const info = res.json(); + assert.equal(info.status, "failed"); + assert.equal(info.error, "535 auth failed"); + assert.equal(info.draft.subject, "hi"); + assert.equal(info.draft.text, "body"); + assert.equal(errors.length, 1); + const cancel = await app.inject({ method: "POST", url: `/mail/send/${id}/cancel` }); + assert.equal(cancel.statusCode, 409); + assert.equal(cancel.json().status, "failed"); + assert.equal((await app.inject({ method: "GET", url: "/mail/send/nope" })).statusCode, 404); +}); + +test("status goes pending, sending, sent and hides the draft on success", async () => { + let release!: () => void; + const gate = new Promise((r) => (release = r)); + const queue = new SendQueue({ send: () => gate } as never); + const { id } = queue.enqueue({} as MailAccount, { subject: "x" } as never, 0.01); + assert.equal(queue.status(id)?.status, "pending"); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(queue.status(id)?.status, "sending"); + release(); + await queue.flush(); + const info = queue.status(id); + assert.equal(info?.status, "sent"); + assert.equal(info?.draft, undefined); +});