feat(#173): SSE live des bulles + ack sans modale
Abonnement /cards/stream pour sync co-parent en temps réel ; acquittement (arrêt maladie) en un clic, sans confirmation. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:p_tits_pas/models/carte_bulle.dart';
|
||||
import 'package:p_tits_pas/services/api/api_config.dart';
|
||||
import 'package:p_tits_pas/services/api/tokenService.dart';
|
||||
|
||||
import 'cards_stream_connector_stub.dart'
|
||||
if (dart.library.html) 'cards_stream_connector_web.dart'
|
||||
if (dart.library.io) 'cards_stream_connector_io.dart';
|
||||
|
||||
/// Événement temps réel file d'attention — ticket #195.
|
||||
class CardsStreamEvent {
|
||||
final String type;
|
||||
final String? cardId;
|
||||
final CarteBulle? card;
|
||||
|
||||
const CardsStreamEvent({
|
||||
required this.type,
|
||||
this.cardId,
|
||||
this.card,
|
||||
});
|
||||
}
|
||||
|
||||
/// Client SSE `GET /cards/stream` avec reconnexion.
|
||||
class CardsStreamClient {
|
||||
final void Function(CardsStreamEvent event) onEvent;
|
||||
final VoidCallback? onReconnectSync;
|
||||
|
||||
CardsStreamClient({
|
||||
required this.onEvent,
|
||||
this.onReconnectSync,
|
||||
});
|
||||
|
||||
final CardsStreamConnector _connector = CardsStreamConnector();
|
||||
bool _started = false;
|
||||
bool _stopRequested = false;
|
||||
int _attempt = 0;
|
||||
Timer? _retryTimer;
|
||||
bool _hadConnection = false;
|
||||
|
||||
void start() {
|
||||
if (_started) return;
|
||||
_started = true;
|
||||
_stopRequested = false;
|
||||
_attempt = 0;
|
||||
unawaited(_connect());
|
||||
}
|
||||
|
||||
void stop() {
|
||||
_stopRequested = true;
|
||||
_started = false;
|
||||
_retryTimer?.cancel();
|
||||
_retryTimer = null;
|
||||
_connector.close();
|
||||
}
|
||||
|
||||
Future<void> _connect() async {
|
||||
if (_stopRequested) return;
|
||||
|
||||
final token = await TokenService.getToken();
|
||||
if (token == null || token.isEmpty) {
|
||||
_scheduleRetry();
|
||||
return;
|
||||
}
|
||||
|
||||
final base =
|
||||
'${ApiConfig.baseUrl}${ApiConfig.cardsStream}'.replaceAll(
|
||||
RegExp(r'/+$'),
|
||||
'',
|
||||
);
|
||||
|
||||
// Web (EventSource) : token en query. IO : Bearer dans le connecteur.
|
||||
final url = kIsWeb
|
||||
? Uri.parse(base).replace(
|
||||
queryParameters: {'access_token': token},
|
||||
).toString()
|
||||
: base;
|
||||
|
||||
await _connector.connect(
|
||||
url: url,
|
||||
bearerToken: kIsWeb ? null : token,
|
||||
onEvent: _handleRaw,
|
||||
onError: (_) {
|
||||
if (_stopRequested) return;
|
||||
_connector.close();
|
||||
_scheduleRetry();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _handleRaw(String eventType, String data) {
|
||||
if (_stopRequested) return;
|
||||
|
||||
// Premier événement (souvent heartbeat) = connexion OK.
|
||||
if (!_hadConnection) {
|
||||
_hadConnection = true;
|
||||
_attempt = 0;
|
||||
} else if (eventType == 'heartbeat') {
|
||||
_attempt = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
if (eventType == 'heartbeat') return;
|
||||
|
||||
try {
|
||||
final decoded = jsonDecode(data);
|
||||
if (decoded is! Map) return;
|
||||
final map = Map<String, dynamic>.from(decoded);
|
||||
final type = (map['event']?.toString().isNotEmpty == true)
|
||||
? map['event'].toString()
|
||||
: eventType;
|
||||
final cardId = map['card_id']?.toString();
|
||||
final payload = map['data'];
|
||||
|
||||
CarteBulle? card;
|
||||
if (type == 'response.added' && payload is Map) {
|
||||
final nested = payload['card'];
|
||||
if (nested is Map) {
|
||||
card = CarteBulle.fromJson(Map<String, dynamic>.from(nested));
|
||||
}
|
||||
} else if ((type == 'card.created' || type == 'card.updated') &&
|
||||
payload is Map) {
|
||||
card = CarteBulle.fromJson(Map<String, dynamic>.from(payload));
|
||||
}
|
||||
|
||||
onEvent(
|
||||
CardsStreamEvent(
|
||||
type: type,
|
||||
cardId: cardId ?? card?.id,
|
||||
card: card,
|
||||
),
|
||||
);
|
||||
} catch (_) {
|
||||
// Événement mal formé : ignorer.
|
||||
}
|
||||
}
|
||||
|
||||
void _scheduleRetry() {
|
||||
if (_stopRequested) return;
|
||||
_retryTimer?.cancel();
|
||||
final delaySec = (1 << _attempt.clamp(0, 4)).clamp(1, 30);
|
||||
_attempt++;
|
||||
_retryTimer = Timer(Duration(seconds: delaySec), () {
|
||||
if (_stopRequested) return;
|
||||
if (_hadConnection) {
|
||||
// Resync REST après coupure pour ne pas manquer d'événements.
|
||||
onReconnectSync?.call();
|
||||
}
|
||||
unawaited(_connect());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
/// Connecteur SSE via HTTP stream (IO / mobile) — ticket #195.
|
||||
class CardsStreamConnector {
|
||||
http.Client? _client;
|
||||
StreamSubscription<List<int>>? _sub;
|
||||
bool _closed = false;
|
||||
|
||||
Future<void> connect({
|
||||
required String url,
|
||||
String? bearerToken,
|
||||
required void Function(String eventType, String data) onEvent,
|
||||
required void Function(Object error) onError,
|
||||
}) async {
|
||||
close();
|
||||
_closed = false;
|
||||
final client = http.Client();
|
||||
_client = client;
|
||||
|
||||
try {
|
||||
final request = http.Request('GET', Uri.parse(url));
|
||||
request.headers['Accept'] = 'text/event-stream';
|
||||
request.headers['Cache-Control'] = 'no-cache';
|
||||
if (bearerToken != null && bearerToken.isNotEmpty) {
|
||||
request.headers['Authorization'] = 'Bearer $bearerToken';
|
||||
}
|
||||
|
||||
final response = await client.send(request);
|
||||
if (response.statusCode != 200) {
|
||||
onError(
|
||||
StateError('SSE cards HTTP ${response.statusCode}'),
|
||||
);
|
||||
close();
|
||||
return;
|
||||
}
|
||||
|
||||
String? eventType;
|
||||
final dataBuf = StringBuffer();
|
||||
final lineBuf = StringBuffer();
|
||||
|
||||
void flushEvent() {
|
||||
if (dataBuf.isEmpty) {
|
||||
eventType = null;
|
||||
return;
|
||||
}
|
||||
onEvent(eventType ?? 'message', dataBuf.toString());
|
||||
dataBuf.clear();
|
||||
eventType = null;
|
||||
}
|
||||
|
||||
void handleLine(String line) {
|
||||
if (line.isEmpty) {
|
||||
flushEvent();
|
||||
return;
|
||||
}
|
||||
if (line.startsWith(':')) return;
|
||||
if (line.startsWith('event:')) {
|
||||
eventType = line.substring(6).trim();
|
||||
return;
|
||||
}
|
||||
if (line.startsWith('data:')) {
|
||||
final payload = line.length > 5 ? line.substring(5) : '';
|
||||
final trimmed = payload.startsWith(' ')
|
||||
? payload.substring(1)
|
||||
: payload;
|
||||
if (dataBuf.isNotEmpty) dataBuf.write('\n');
|
||||
dataBuf.write(trimmed);
|
||||
}
|
||||
}
|
||||
|
||||
_sub = response.stream.listen(
|
||||
(chunk) {
|
||||
if (_closed) return;
|
||||
lineBuf.write(utf8.decode(chunk, allowMalformed: true));
|
||||
var content = lineBuf.toString();
|
||||
var idx = content.indexOf('\n');
|
||||
while (idx >= 0) {
|
||||
var line = content.substring(0, idx);
|
||||
if (line.endsWith('\r')) {
|
||||
line = line.substring(0, line.length - 1);
|
||||
}
|
||||
handleLine(line);
|
||||
content = content.substring(idx + 1);
|
||||
idx = content.indexOf('\n');
|
||||
}
|
||||
lineBuf
|
||||
..clear()
|
||||
..write(content);
|
||||
},
|
||||
onError: (Object e) {
|
||||
if (!_closed) onError(e);
|
||||
},
|
||||
onDone: () {
|
||||
if (!_closed) onError(StateError('SSE cards fermé'));
|
||||
},
|
||||
cancelOnError: true,
|
||||
);
|
||||
} catch (e) {
|
||||
if (!_closed) onError(e);
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
void close() {
|
||||
_closed = true;
|
||||
_sub?.cancel();
|
||||
_sub = null;
|
||||
_client?.close();
|
||||
_client = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import 'dart:async';
|
||||
|
||||
/// Connecteur SSE — stub (tests / plateformes sans impl).
|
||||
class CardsStreamConnector {
|
||||
Future<void> connect({
|
||||
required String url,
|
||||
String? bearerToken,
|
||||
required void Function(String eventType, String data) onEvent,
|
||||
required void Function(Object error) onError,
|
||||
}) async {}
|
||||
|
||||
void close() {}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Connecteur web uniquement (import conditionnel).
|
||||
// ignore_for_file: avoid_web_libraries_in_flutter, deprecated_member_use
|
||||
|
||||
import 'dart:html' as html;
|
||||
|
||||
/// Connecteur SSE navigateur (EventSource) — ticket #195.
|
||||
/// Auth via `?access_token=` (EventSource ne permet pas Authorization).
|
||||
class CardsStreamConnector {
|
||||
html.EventSource? _source;
|
||||
final Map<String, html.EventListener> _listeners = {};
|
||||
|
||||
Future<void> connect({
|
||||
required String url,
|
||||
String? bearerToken,
|
||||
required void Function(String eventType, String data) onEvent,
|
||||
required void Function(Object error) onError,
|
||||
}) async {
|
||||
close();
|
||||
final source = html.EventSource(url);
|
||||
_source = source;
|
||||
|
||||
const names = [
|
||||
'card.created',
|
||||
'card.updated',
|
||||
'card.deleted',
|
||||
'response.added',
|
||||
'heartbeat',
|
||||
];
|
||||
for (final name in names) {
|
||||
void listener(html.Event raw) {
|
||||
final msg = raw as html.MessageEvent;
|
||||
final data = msg.data?.toString() ?? '';
|
||||
if (data.isEmpty) return;
|
||||
onEvent(name, data);
|
||||
}
|
||||
|
||||
_listeners[name] = listener;
|
||||
source.addEventListener(name, listener);
|
||||
}
|
||||
|
||||
void onErr(html.Event _) {
|
||||
onError(StateError('SSE cards déconnecté'));
|
||||
}
|
||||
|
||||
_listeners['error'] = onErr;
|
||||
source.addEventListener('error', onErr);
|
||||
}
|
||||
|
||||
void close() {
|
||||
final source = _source;
|
||||
if (source != null) {
|
||||
_listeners.forEach((name, listener) {
|
||||
source.removeEventListener(name, listener);
|
||||
});
|
||||
source.close();
|
||||
}
|
||||
_listeners.clear();
|
||||
_source = null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user