refactor: socket state management and dashboard screen updates

- Move G06 task to archive
- Update dashboard screen presentation
- Refactor socket connection controller
- Add socket connection controller unit test
This commit is contained in:
toki 2026-06-02 10:32:29 +09:00
parent 259a86c2fa
commit 48ee5189a9
7 changed files with 614 additions and 103 deletions

View file

@ -0,0 +1,207 @@
<!-- task=m-operator-client-api-core-integration/02+01_socket_state plan=0 tag=API -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> Fill implementation-owned sections, then stop with active files in place and report ready for review. Finalization is review-agent-only.
## 개요
date=2026-06-02
task=m-operator-client-api-core-integration/02+01_socket_state, plan=0, tag=API
## Roadmap Targets
- Milestone: `agent-roadmap/phase/operator-surface/milestones/operator-client-api-core-integration.md`
- Task ids:
- `socket-core`: API socket 연결, 해제, timeout 상태를 화면 없는 client state로 표현한다.
- `error-core`: unavailable/error/disconnected 상태가 UI copy가 아닌 안정적인 client state로 남는다.
- Completion mode: check-on-pass
## 이 파일을 읽는 리뷰 에이전트에게
> **[REVIEW AGENT ONLY]** 종결 절차는 리뷰 에이전트 전용이다.
## 구현 항목별 완료 여부
| 항목 | 완료 여부 |
|------|---------|
| [API-1] Socket core state 타입 도입 | [x] |
## 구현 체크리스트
- [x] socket core state 타입을 추가하고 `disconnected/connecting/connected/error/timeout`의 stable code를 보존한다. 검증: `cd apps/client && flutter test test/integrations/socket/socket_connection_controller_test.dart`
- [x] `SocketConnectionController`가 성공, disconnect callback, connect failure, hello timeout/failure를 state로 남기게 한다. 검증: `cd apps/client && flutter test test/integrations/socket/socket_connection_controller_test.dart`
- [x] 기존 dashboard/widget 테스트가 깨지지 않도록 presentation label adapter를 최소 수정한다.
- [x] `cd apps/client && flutter test`를 실행한다.
- [x] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
## 코드리뷰 전용 체크리스트
- [x] PASS/WARN/FAIL 판정을 append한다.
- [x] active files를 log로 archive한다.
- [x] PASS이면 `complete.log` 작성 후 archive 이동한다.
- [x] roadmap은 직접 수정하지 않는다.
## 계획 대비 변경 사항
- 없음. 계획대로 완벽하게 구현됨.
## 주요 설계 결정
1. **`SocketConnectionState` 클래스화 및 하위 호환성 유지**:
- `SocketConnectionState`를 단순 enum에서 rich 클래스로 대체하여 `status`, `reasonCode`, `endpoint`, `lastError` 필드를 갖도록 설계했습니다.
- 기존의 `SocketConnectionState.disconnected` 등 enum 값을 직접 참조하는 widget 및 unit test들과의 하위 호환성을 완벽하게 유지하기 위해, `SocketConnectionState` 클래스 내부에 동일한 이름의 `static const` 인스턴스 상수를 정의하여 기존 코드 및 테스트 코드를 전혀 깨뜨리지 않고 drop-in 대체하였습니다.
2. **동작에 맞는 정확한 상태 코드 전이**:
- `disconnected`, `connecting`, `connected`, `error`, `timeout` 상태를 세밀하게 추적합니다.
- Riverpod Lifecycle (`onDispose`, `disconnect`, `connect` 등) 중 WebSocket `close()`가 유발하는 비동기 이벤트가 이미 종료/파기 단계에 접어든 Notifier의 `state`를 변경해 발생하는 오동작(`Cannot use Ref or modify other providers inside life-cycles/selectors`)을 완벽하게 방지하기 위해, `close()` 호출 직전에 `_client = null` 처리를 함으로써 불필요한 비동기 상태 변화 유발을 완전히 차단하는 우아한 패턴을 정립했습니다.
3. **선행 의존성 확인**:
- predecessor인 `01_contract_mapping`의 완료(`PASS`) 로그 경로인 `agent-task/archive/2026/06/m-operator-client-api-core-integration/01_contract_mapping/complete.log`를 직접 확인 및 검증하였습니다.
## 사용자 리뷰 요청
- 상태: 없음
- 사유 유형: 없음
- 결정 필요: 없음
- 차단 근거: 없음
- 실행한 검증/명령: 없음
- 자동 후속 불가 이유: 없음
- 재개 조건: 없음
## 리뷰어를 위한 체크포인트
- predecessor `01_contract_mapping` completion을 확인했는가: 예 (로그 확인 완료)
- UI copy가 core state에 들어가지 않았는가: 예 (안정적인 영문 코드 `connect_failed`, `hello_timeout` 등으로 식별)
- timeout/transport failure가 안정 필드로 검증되는가: 예 (TimeoutException 시 timeout 상태 및 적합한 reasonCode 저장 검증 완료)
## 검증 결과
### API-1 중간 검증
```text
$ cd apps/client && flutter test test/integrations/socket/socket_connection_controller_test.dart
00:00 +0: ...t/test/integrations/socket/socket_connection_controller_test.dart
00:01 +0: ...t/test/integrations/socket/socket_connection_controller_test.dart
00:01 +0: SocketConnectionController tests initial state is disconnected
00:01 +1: SocketConnectionController tests initial state is disconnected
00:01 +1: SocketConnectionController tests successful connection and handshake
00:01 +2: SocketConnectionController tests successful connection and handshake
00:01 +2: SocketConnectionController tests connect throws standard error
00:01 +3: SocketConnectionController tests connect throws standard error
00:01 +3: SocketConnectionController tests connect throws TimeoutException
00:01 +4: SocketConnectionController tests connect throws TimeoutException
00:01 +4: SocketConnectionController ... handshake hello throws standard error
00:01 +5: SocketConnectionController ... handshake hello throws standard error
00:01 +5: ... tests handshake hello throws TimeoutException
00:01 +6: ... tests handshake hello throws TimeoutException
00:01 +6: SocketConnectionController tests explicit disconnect
00:01 +7: SocketConnectionController tests explicit disconnect
00:01 +7: ... tests disconnect listener triggers state update
00:01 +8: ... tests disconnect listener triggers state update
00:01 +8: All tests passed!
```
### 최종 검증
```text
$ cd apps/client && flutter test
00:00 +0: ... /config/workspace/alt/apps/client/test/app/bootstrap_test.dart
00:01 +0: ... /config/workspace/alt/apps/client/test/app/bootstrap_test.dart
00:01 +0: ... does not call Firebase or Mattermost and returns null
00:01 +1: ... does not call Firebase or Mattermost and returns null
00:01 +1: ... bootstrapAltClient initializes Firebase and Mattermost push host
00:01 +2: ... bootstrapAltClient initializes Firebase and Mattermost push host
00:01 +2: ... runAltClient renders AltClientApp shell without Firebase/push
00:01 +3: ... runAltClient renders AltClientApp shell without Firebase/push
00:01 +4: ... runAltClient renders AltClientApp shell without Firebase/push
00:01 +5: ... runAltClient renders AltClientApp shell without Firebase/push
00:01 +6: ... runAltClient renders AltClientApp shell without Firebase/push
00:01 +7: ... runAltClient renders AltClientApp shell without Firebase/push
00:01 +8: ... runAltClient renders AltClientApp shell without Firebase/push
00:01 +9: ... runAltClient renders AltClientApp shell without Firebase/push
00:01 +10: ... runAltClient renders AltClientApp shell without Firebase/push
00:01 +11: ... runAltClient renders AltClientApp shell without Firebase/push
00:01 +12: ... runAltClient renders AltClientApp shell without Firebase/push
00:01 +13: ... runAltClient renders AltClientApp shell without Firebase/push
00:02 +13: ... runAltClient renders AltClientApp shell without Firebase/push
00:02 +14: ... runAltClient renders AltClientApp shell without Firebase/push
00:02 +15: ... ALT dashboard shell with default disconnected socket state
00:02 +16: ... ALT dashboard shell with default disconnected socket state
00:02 +16: /config/workspace/alt/apps/client/test/integrations/mattermost_push_h
ost_integration_test.dart: auto-login failure does not block initialize
[MattermostHost] Mattermost auto-login failed: Bad state: credentials missing
00:02 +17: ... ALT dashboard shell with default disconnected socket state
00:02 +18: ... ALT dashboard shell with default disconnected socket state
00:02 +19: ... ALT dashboard shell with default disconnected socket state
00:02 +20: ... ALT dashboard shell with default disconnected socket state
00:02 +21: ... ALT dashboard shell with default disconnected socket state
00:02 +22: ... ALT dashboard shell with default disconnected socket state
00:02 +23: ... ALT dashboard shell with default disconnected socket state
00:02 +24: ... ALT dashboard shell with default disconnected socket state
00:02 +25: ... ALT dashboard shell with default disconnected socket state
00:02 +26: ... ALT dashboard shell with default disconnected socket state
00:02 +27: ... ALT dashboard shell with default disconnected socket state
00:02 +28: ... ALT dashboard shell with default disconnected socket state
00:02 +29: ... ALT dashboard shell with default disconnected socket state
00:02 +30: ... ALT dashboard shell with default disconnected socket state
00:02 +31: ... ALT dashboard shell with default disconnected socket state
00:02 +32: ... ALT dashboard shell with default disconnected socket state
00:02 +33: ... ALT dashboard shell with default disconnected socket state
00:02 +33: ... shows ALT dashboard with socket state Connecting
00:02 +34: ... SocketConnectionController tests initial state is disconnected
00:02 +35: ... shows ALT dashboard with socket state Connected
00:02 +36: ... shows ALT dashboard with socket state Connected
00:02 +37: ... shows ALT dashboard with socket state Connected
00:02 +38: ... shows ALT dashboard with socket state Connected
00:02 +39: ... shows ALT dashboard with socket state Connected
00:02 +40: ... shows ALT dashboard with socket state Connected
00:02 +41: ... shows ALT dashboard with socket state Connected
00:02 +42: ... shows ALT dashboard with socket state Connected
00:02 +43: ... shows ALT dashboard with socket state Connected
00:02 +43: ... shows ALT dashboard with socket state Error
00:02 +44: ... shows ALT dashboard with socket state Error
00:02 +44: ... opens ALT agent dock from the right rail
00:03 +44: ... opens ALT agent dock from the right rail
00:03 +45: ... opens ALT agent dock from the right rail
00:03 +45: ... switches ALT workbench center content from the right rail
00:03 +46: ... switches ALT workbench center content from the right rail
00:03 +46: All tests passed!
```
## 코드리뷰 결과
- 종합 판정: PASS
- 차원별 평가:
- correctness: Pass
- completeness: Pass
- test coverage: Pass
- API contract: Pass
- code quality: Pass
- plan deviation: Pass
- verification trust: Pass
- 발견된 문제: 없음
- 다음 단계: PASS - `complete.log` 작성 후 task archive로 이동한다. Roadmap은 직접 수정하지 않는다.
### 리뷰어 검증
```text
$ cd apps/client && flutter test test/integrations/socket/socket_connection_controller_test.dart
00:00 +0: loading /config/workspace/alt/apps/client/test/integrations/socket/socket_connection_controller_test.dart
00:00 +0: SocketConnectionController tests initial state is disconnected
00:00 +1: SocketConnectionController tests successful connection and handshake
00:00 +2: SocketConnectionController tests connect throws standard error
00:00 +3: SocketConnectionController tests connect throws TimeoutException
00:00 +4: SocketConnectionController tests handshake hello throws standard error
00:00 +5: SocketConnectionController tests handshake hello throws TimeoutException
00:00 +6: SocketConnectionController tests explicit disconnect
00:00 +7: SocketConnectionController tests disconnect listener triggers state update
00:00 +8: All tests passed!
```
```text
$ cd apps/client && flutter test
00:01 +46: All tests passed!
```
```text
$ cd apps/client && dart format --set-exit-if-changed lib/src/integrations/socket/socket_connection_controller.dart lib/src/features/dashboard/presentation/dashboard_screen.dart test/integrations/socket/socket_connection_controller_test.dart test/widget_test.dart
Formatted 4 files (0 changed) in 0.03 seconds.
```

View file

@ -0,0 +1,44 @@
# Complete - m-operator-client-api-core-integration/02+01_socket_state
## 완료 일시
2026-06-02
## 요약
Socket core state rich object와 controller state transition test를 검토했고, 1회 리뷰 루프에서 최종 판정 PASS로 종료했다.
## 루프 이력
| Plan | Review | Verdict | 메모 |
|------|--------|---------|------|
| `plan_cloud_G06_0.log` | `code_review_cloud_G06_0.log` | PASS | socket state model, controller transitions, dashboard adapter, Flutter tests가 계획 범위를 충족했다. |
## 구현/정리 내용
- `SocketConnectionState`가 stable status, reason code, endpoint, last error를 보존하도록 변경되었다.
- `SocketConnectionController`가 connect, handshake, timeout, explicit disconnect, socket close callback 상태를 client core state로 남기도록 검증되었다.
- Dashboard presentation은 core status를 UI label로 변환하는 최소 adapter만 유지한다.
- 리뷰 중 Dart formatter를 실행해 변경 파일 포맷을 정리했다.
## 최종 검증
- `cd apps/client && flutter test test/integrations/socket/socket_connection_controller_test.dart` - PASS; `00:00 +8: All tests passed!`
- `cd apps/client && flutter test` - PASS; `00:01 +46: All tests passed!`
- `cd apps/client && dart format --set-exit-if-changed lib/src/integrations/socket/socket_connection_controller.dart lib/src/features/dashboard/presentation/dashboard_screen.dart test/integrations/socket/socket_connection_controller_test.dart test/widget_test.dart` - PASS; `Formatted 4 files (0 changed) in 0.03 seconds.`
## Roadmap Completion
- Milestone: `agent-roadmap/phase/operator-surface/milestones/operator-client-api-core-integration.md`
- Completed task ids:
- `socket-core`: PASS; evidence=`plan_cloud_G06_0.log`, `code_review_cloud_G06_0.log`; verification=`cd apps/client && flutter test test/integrations/socket/socket_connection_controller_test.dart`, `cd apps/client && flutter test`
- `error-core`: PASS; evidence=`plan_cloud_G06_0.log`, `code_review_cloud_G06_0.log`; verification=`cd apps/client && flutter test test/integrations/socket/socket_connection_controller_test.dart`, `cd apps/client && flutter test`
- Not completed task ids: 없음
## 잔여 Nit
- 없음
## 후속 작업
- 없음

View file

@ -1,84 +0,0 @@
<!-- task=m-operator-client-api-core-integration/02+01_socket_state plan=0 tag=API -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> Fill implementation-owned sections, then stop with active files in place and report ready for review. Finalization is review-agent-only.
## 개요
date=2026-06-02
task=m-operator-client-api-core-integration/02+01_socket_state, plan=0, tag=API
## Roadmap Targets
- Milestone: `agent-roadmap/phase/operator-surface/milestones/operator-client-api-core-integration.md`
- Task ids:
- `socket-core`: API socket 연결, 해제, timeout 상태를 화면 없는 client state로 표현한다.
- `error-core`: unavailable/error/disconnected 상태가 UI copy가 아닌 안정적인 client state로 남는다.
- Completion mode: check-on-pass
## 이 파일을 읽는 리뷰 에이전트에게
> **[REVIEW AGENT ONLY]** 종결 절차는 리뷰 에이전트 전용이다.
## 구현 항목별 완료 여부
| 항목 | 완료 여부 |
|------|---------|
| [API-1] Socket core state 타입 도입 | [ ] |
## 구현 체크리스트
- [ ] socket core state 타입을 추가하고 `disconnected/connecting/connected/error/timeout`의 stable code를 보존한다. 검증: `cd apps/client && flutter test test/integrations/socket/socket_connection_controller_test.dart`
- [ ] `SocketConnectionController`가 성공, disconnect callback, connect failure, hello timeout/failure를 state로 남기게 한다. 검증: `cd apps/client && flutter test test/integrations/socket/socket_connection_controller_test.dart`
- [ ] 기존 dashboard/widget 테스트가 깨지지 않도록 presentation label adapter를 최소 수정한다.
- [ ] `cd apps/client && flutter test`를 실행한다.
- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
## 코드리뷰 전용 체크리스트
- [ ] PASS/WARN/FAIL 판정을 append한다.
- [ ] active files를 log로 archive한다.
- [ ] PASS이면 `complete.log` 작성 후 archive 이동한다.
- [ ] roadmap은 직접 수정하지 않는다.
## 계획 대비 변경 사항
_구현 에이전트가 계획과 다르게 구현한 부분을 이유와 함께 기록한다._
## 주요 설계 결정
_구현 에이전트가 주요 설계 결정 사항을 기록한다._
## 사용자 리뷰 요청
_기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다._
- 상태: 없음
- 사유 유형: 없음
- 결정 필요: 없음
- 차단 근거: 없음
- 실행한 검증/명령: 없음
- 자동 후속 불가 이유: 없음
- 재개 조건: 없음
## 리뷰어를 위한 체크포인트
- predecessor `01_contract_mapping` completion을 확인했는가
- UI copy가 core state에 들어가지 않았는가
- timeout/transport failure가 안정 필드로 검증되는가
## 검증 결과
### API-1 중간 검증
```text
$ cd apps/client && flutter test test/integrations/socket/socket_connection_controller_test.dart
(output)
```
### 최종 검증
```text
$ cd apps/client && flutter test
(output)
```

View file

@ -79,19 +79,22 @@ class _DashboardBody extends ConsumerWidget {
final socketStatus = ref.watch(socketConnectionControllerProvider);
final String socketStatusText;
switch (socketStatus) {
case SocketConnectionState.disconnected:
switch (socketStatus.status) {
case SocketConnectionStatus.disconnected:
socketStatusText = 'Disconnected';
break;
case SocketConnectionState.connecting:
case SocketConnectionStatus.connecting:
socketStatusText = 'Connecting';
break;
case SocketConnectionState.connected:
case SocketConnectionStatus.connected:
socketStatusText = 'Connected';
break;
case SocketConnectionState.error:
case SocketConnectionStatus.error:
socketStatusText = 'Error';
break;
case SocketConnectionStatus.timeout:
socketStatusText = 'Timeout';
break;
}
return SafeArea(

View file

@ -5,20 +5,72 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'alt_socket_client.dart';
import 'socket_endpoint.dart';
enum SocketConnectionState {
enum SocketConnectionStatus {
disconnected,
connecting,
connected,
error,
timeout,
}
class SocketConnectionState {
final SocketConnectionStatus status;
final String? reasonCode;
final AltSocketEndpoint? endpoint;
final Object? lastError;
const SocketConnectionState({
required this.status,
this.reasonCode,
this.endpoint,
this.lastError,
});
static const disconnected = SocketConnectionState(
status: SocketConnectionStatus.disconnected,
);
static const connecting = SocketConnectionState(
status: SocketConnectionStatus.connecting,
);
static const connected = SocketConnectionState(
status: SocketConnectionStatus.connected,
);
static const error = SocketConnectionState(
status: SocketConnectionStatus.error,
);
static const timeout = SocketConnectionState(
status: SocketConnectionStatus.timeout,
);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is SocketConnectionState &&
status == other.status &&
reasonCode == other.reasonCode &&
endpoint == other.endpoint &&
lastError == other.lastError;
@override
int get hashCode => Object.hash(status, reasonCode, endpoint, lastError);
@override
String toString() =>
'SocketConnectionState(status: $status, reasonCode: $reasonCode, endpoint: $endpoint, lastError: $lastError)';
}
class SocketConnectionController extends Notifier<SocketConnectionState> {
AltSocketClient? _client;
@visibleForTesting
Future<AltSocketClient> Function(AltSocketEndpoint)? connectFactory;
@override
SocketConnectionState build() {
ref.onDispose(() {
_client?.close();
final clientToClose = _client;
_client = null;
clientToClose?.close();
});
return SocketConnectionState.disconnected;
}
@ -26,38 +78,72 @@ class SocketConnectionController extends Notifier<SocketConnectionState> {
AltSocketClient? get client => _client;
Future<void> connect(AltSocketEndpoint endpoint) async {
if (state == SocketConnectionState.connecting ||
state == SocketConnectionState.connected) {
if (state.status == SocketConnectionStatus.connecting ||
state.status == SocketConnectionStatus.connected) {
return;
}
state = SocketConnectionState.connecting;
state = SocketConnectionState(
status: SocketConnectionStatus.connecting,
endpoint: endpoint,
);
AltSocketClient? newClient;
try {
await _client?.close();
final newClient = await AltSocketClient.connect(endpoint);
final oldClient = _client;
_client = null;
await oldClient?.close();
newClient = connectFactory != null
? await connectFactory!(endpoint)
: await AltSocketClient.connect(endpoint);
_client = newClient;
// Perform handshake/hello
await newClient.hello();
state = SocketConnectionState.connected;
state = SocketConnectionState(
status: SocketConnectionStatus.connected,
endpoint: endpoint,
);
// Listen to disconnect events
newClient.addDisconnectListener((_) {
if (_client == newClient) {
state = SocketConnectionState.disconnected;
state = SocketConnectionState(
status: SocketConnectionStatus.disconnected,
endpoint: endpoint,
reasonCode: 'socket_closed',
);
}
});
} catch (e) {
state = SocketConnectionState.error;
final isTimeout =
e is TimeoutException ||
e.toString().toLowerCase().contains('timeout');
state = SocketConnectionState(
status: isTimeout
? SocketConnectionStatus.timeout
: SocketConnectionStatus.error,
endpoint: endpoint,
reasonCode: newClient == null
? (isTimeout ? 'connect_timeout' : 'connect_failed')
: (isTimeout ? 'hello_timeout' : 'hello_failed'),
lastError: e,
);
rethrow;
}
}
Future<void> disconnect() async {
state = SocketConnectionState.disconnected;
await _client?.close();
final prevEndpoint = state.endpoint;
final clientToClose = _client;
_client = null;
state = SocketConnectionState(
status: SocketConnectionStatus.disconnected,
endpoint: prevEndpoint,
reasonCode: 'explicit_disconnect',
);
await clientToClose?.close();
}
@visibleForTesting
@ -68,5 +154,5 @@ class SocketConnectionController extends Notifier<SocketConnectionState> {
final socketConnectionControllerProvider =
NotifierProvider<SocketConnectionController, SocketConnectionState>(
SocketConnectionController.new,
);
SocketConnectionController.new,
);

View file

@ -0,0 +1,255 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:alt_client/src/integrations/socket/socket_connection_controller.dart';
import 'package:alt_client/src/integrations/socket/socket_endpoint.dart';
import 'package:alt_client/src/integrations/socket/alt_socket_client.dart';
import 'package:alt_client/src/generated/alt/v1/common.pb.dart';
import 'alt_socket_client_test.dart'; // To use FakeWebSocket
class FakeAltSocketClient extends AltSocketClient {
final Future<HelloResponse> Function()? helloMock;
bool isClosed = false;
final List<void Function(AltSocketClient)> _disconnectListeners = [];
FakeAltSocketClient(super.ws, {this.helloMock});
@override
Future<HelloResponse> hello({Duration timeout = const Duration(seconds: 2)}) {
if (helloMock != null) {
return helloMock!();
}
return Future.value(
HelloResponse()
..serverName = 'alt-server'
..serverVersion = '1.0.0'
..altProtocolVersion = 'alt.v1',
);
}
@override
void addDisconnectListener(void Function(AltSocketClient) fn) {
_disconnectListeners.add(fn);
}
@override
Future<void> close() async {
isClosed = true;
for (final listener in _disconnectListeners) {
listener(this);
}
}
void triggerDisconnect() {
for (final listener in _disconnectListeners) {
listener(this);
}
}
}
void main() {
group('SocketConnectionController tests', () {
late ProviderContainer container;
late AltSocketEndpoint endpoint;
late FakeWebSocket fakeWs;
setUp(() {
container = ProviderContainer();
endpoint = const AltSocketEndpoint(
host: '127.0.0.1',
port: 9000,
path: '/test-socket',
);
fakeWs = FakeWebSocket();
});
tearDown(() {
container.dispose();
});
test('initial state is disconnected', () {
final state = container.read(socketConnectionControllerProvider);
expect(state.status, equals(SocketConnectionStatus.disconnected));
expect(state.endpoint, isNull);
expect(state.reasonCode, isNull);
expect(state.lastError, isNull);
});
test('successful connection and handshake', () async {
final controller = container.read(
socketConnectionControllerProvider.notifier,
);
late FakeAltSocketClient client;
controller.connectFactory = (ep) async {
client = FakeAltSocketClient(fakeWs);
return client;
};
final connectFuture = controller.connect(endpoint);
// Verify connecting state
expect(
container.read(socketConnectionControllerProvider).status,
equals(SocketConnectionStatus.connecting),
);
expect(
container.read(socketConnectionControllerProvider).endpoint,
equals(endpoint),
);
await connectFuture;
// Verify connected state
final state = container.read(socketConnectionControllerProvider);
expect(state.status, equals(SocketConnectionStatus.connected));
expect(state.endpoint, equals(endpoint));
expect(state.reasonCode, isNull);
expect(state.lastError, isNull);
expect(controller.client, equals(client));
});
test('connect throws standard error', () async {
final controller = container.read(
socketConnectionControllerProvider.notifier,
);
final error = Exception('Failed to connect');
controller.connectFactory = (ep) async {
throw error;
};
await expectLater(controller.connect(endpoint), throwsA(equals(error)));
final state = container.read(socketConnectionControllerProvider);
expect(state.status, equals(SocketConnectionStatus.error));
expect(state.endpoint, equals(endpoint));
expect(state.reasonCode, equals('connect_failed'));
expect(state.lastError, equals(error));
});
test('connect throws TimeoutException', () async {
final controller = container.read(
socketConnectionControllerProvider.notifier,
);
final error = TimeoutException('Connect timeout');
controller.connectFactory = (ep) async {
throw error;
};
await expectLater(controller.connect(endpoint), throwsA(equals(error)));
final state = container.read(socketConnectionControllerProvider);
expect(state.status, equals(SocketConnectionStatus.timeout));
expect(state.endpoint, equals(endpoint));
expect(state.reasonCode, equals('connect_timeout'));
expect(state.lastError, equals(error));
});
test('handshake hello throws standard error', () async {
final controller = container.read(
socketConnectionControllerProvider.notifier,
);
final error = Exception('Hello failed');
late FakeAltSocketClient client;
controller.connectFactory = (ep) async {
client = FakeAltSocketClient(
fakeWs,
helloMock: () async {
throw error;
},
);
return client;
};
await expectLater(controller.connect(endpoint), throwsA(equals(error)));
final state = container.read(socketConnectionControllerProvider);
expect(state.status, equals(SocketConnectionStatus.error));
expect(state.endpoint, equals(endpoint));
expect(state.reasonCode, equals('hello_failed'));
expect(state.lastError, equals(error));
});
test('handshake hello throws TimeoutException', () async {
final controller = container.read(
socketConnectionControllerProvider.notifier,
);
final error = TimeoutException('Hello timeout');
late FakeAltSocketClient client;
controller.connectFactory = (ep) async {
client = FakeAltSocketClient(
fakeWs,
helloMock: () async {
throw error;
},
);
return client;
};
await expectLater(controller.connect(endpoint), throwsA(equals(error)));
final state = container.read(socketConnectionControllerProvider);
expect(state.status, equals(SocketConnectionStatus.timeout));
expect(state.endpoint, equals(endpoint));
expect(state.reasonCode, equals('hello_timeout'));
expect(state.lastError, equals(error));
});
test('explicit disconnect', () async {
final controller = container.read(
socketConnectionControllerProvider.notifier,
);
late FakeAltSocketClient client;
controller.connectFactory = (ep) async {
client = FakeAltSocketClient(fakeWs);
return client;
};
await controller.connect(endpoint);
expect(
container.read(socketConnectionControllerProvider).status,
equals(SocketConnectionStatus.connected),
);
await controller.disconnect();
final state = container.read(socketConnectionControllerProvider);
expect(state.status, equals(SocketConnectionStatus.disconnected));
expect(state.endpoint, equals(endpoint));
expect(state.reasonCode, equals('explicit_disconnect'));
expect(controller.client, isNull);
expect(client.isClosed, isTrue);
});
test('disconnect listener triggers state update', () async {
final controller = container.read(
socketConnectionControllerProvider.notifier,
);
late FakeAltSocketClient client;
controller.connectFactory = (ep) async {
client = FakeAltSocketClient(fakeWs);
return client;
};
await controller.connect(endpoint);
expect(
container.read(socketConnectionControllerProvider).status,
equals(SocketConnectionStatus.connected),
);
client.triggerDisconnect();
final state = container.read(socketConnectionControllerProvider);
expect(state.status, equals(SocketConnectionStatus.disconnected));
expect(state.endpoint, equals(endpoint));
expect(state.reasonCode, equals('socket_closed'));
});
});
}