mirror of
https://github.com/linagora/tmail-flutter.git
synced 2026-12-06 16:04:20 +00:00
Propose refactor plan
This commit is contained in:
1 parent
eeaab49e93
commit
6c3a36bcdb
6 files changed
+2035
No files matched your search
@@ -0,0 +1,626 @@
|
||||
# 80. SOLID Refactor — God Controller Decomposition
|
||||
|
||||
Date: 2026-04-03
|
||||
Last revised: 2026-04-13 (abstract pattern plan)
|
||||
|
||||
## Status
|
||||
|
||||
Accepted
|
||||
|
||||
## Context
|
||||
|
||||
The presentation layer has accumulated god controllers that violate every SOLID principle. A god controller is any controller exceeding ~700 LOC, owning 3+ unrelated domains, or accumulating 10+ constructor dependencies.
|
||||
|
||||
Typical symptoms of a god controller:
|
||||
- Multiple unrelated mixins on a single controller; many extension files all extending `on GodController` (accessing `this.selectedMailbox`, `this.accountId`, etc. — tightly coupled through `this`)
|
||||
- Other features call `Get.find<GodController>()` to reach state or invoke actions that belong to a specific domain
|
||||
- A single bindings file with dozens of `Get.put`/`Get.lazyPut` calls, one per dependency
|
||||
- Zero delegates despite the pattern being documented in `CLAUDE.md`
|
||||
- Test files mock the god controller — mocking a 40+ dependency controller is expensive and fragile
|
||||
|
||||
At the time this ADR was written, the largest god controller had ~3500 LOC, 40+ dependencies, and 10+ unrelated domains. Its bindings file exceeded 500 LOC with 100+ registration calls. Another screen-level controller had ~2400 LOC and 10 domains. `BaseController` itself had accumulated 14 field-level `Get.find` calls for auth, cache, and UI utilities — concerns unrelated to its lifecycle role.
|
||||
|
||||
The codebase **cannot grow sustainably** in this state — new features are added by appending to god controllers, which compounds the problem.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Core patterns
|
||||
|
||||
#### 1. Controller Delegate — plain Dart class, lifecycle propagated by DomainRegistry
|
||||
|
||||
A delegate owns one feature's state and behaviour. The canonical `ControllerDelegate` is a **plain Dart class** — not a `GetxController`, not a `BaseController`. Its lifecycle is driven by its owning `DomainRegistry` via `init()` / `dispose()`.
|
||||
|
||||
This is a deliberate fix for a GetX hazard: when a delegate is stored as a `late final` field inside a `GetxService` (the registry), GetX never calls `onInit`/`onClose` on the delegate. Workers leak. Plain Dart classes with explicit `init`/`dispose` controlled by the registry avoid this entirely.
|
||||
|
||||
```dart
|
||||
// lib/features/base/delegate/controller_delegate.dart
|
||||
abstract class ControllerDelegate {
|
||||
final _workers = <Worker>[];
|
||||
final _subs = <StreamSubscription>[];
|
||||
|
||||
@protected
|
||||
Worker trackWorker(Worker worker) { _workers.add(worker); return worker; }
|
||||
|
||||
@protected
|
||||
StreamSubscription<T> trackSub<T>(StreamSubscription<T> sub) { _subs.add(sub); return sub; }
|
||||
|
||||
@mustCallSuper void init() {}
|
||||
|
||||
@mustCallSuper
|
||||
void dispose() {
|
||||
for (final w in _workers) w.dispose();
|
||||
for (final s in _subs) s.cancel();
|
||||
_workers.clear();
|
||||
_subs.clear();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```dart
|
||||
// Example — extracted in a per-controller Layer 2 phase, not in the foundation
|
||||
class EmailActionDelegate extends ControllerDelegate {
|
||||
final ActionQueue _queue;
|
||||
final SessionService _session;
|
||||
final MailboxStateService _mailboxState;
|
||||
final IEmailMoveRepository _moveRepo;
|
||||
|
||||
EmailActionDelegate(this._queue, this._session, this._mailboxState, this._moveRepo);
|
||||
|
||||
final listEmailSelected = RxList<PresentationEmail>([]);
|
||||
|
||||
@override
|
||||
void init() {
|
||||
super.init();
|
||||
trackWorker(ever(_mailboxState.selectedMailbox, (_) => _clearSelection()));
|
||||
}
|
||||
|
||||
void moveToTrash(PresentationEmail email) =>
|
||||
_queue.submit(MoveToTrashAction(email, _moveRepo));
|
||||
}
|
||||
```
|
||||
|
||||
**Rule:** delegates never call `Get.find<>()` in their own body. They receive pre-resolved dependencies from the registry constructor. The only places where `Get.find<>()` appears are `*_bindings.dart` files and `DomainRegistry` subclasses.
|
||||
|
||||
#### 2. DomainRegistry — single DI entry, lifecycle propagation
|
||||
|
||||
A `DomainRegistry` is a `GetxService` that owns a group of delegates for one screen or domain. It:
|
||||
|
||||
1. Resolves all infrastructure dependencies via `Get.find<>()` — the **only** layer allowed to do so outside `*_bindings.dart`.
|
||||
2. Exposes each delegate as a `late final` field.
|
||||
3. Calls `init()` on every delegate in its own `onInit()`.
|
||||
4. Calls `dispose()` on every delegate in reverse order in its `onClose()`.
|
||||
|
||||
```dart
|
||||
// lib/features/base/delegate/domain_registry.dart
|
||||
abstract class DomainRegistry extends GetxService {
|
||||
List<ControllerDelegate> get delegates;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
for (final d in delegates) d.init();
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
for (final d in delegates.reversed) d.dispose();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```dart
|
||||
class DashboardDomainRegistry extends DomainRegistry {
|
||||
final ActionQueue _queue;
|
||||
final SessionService _session;
|
||||
final AppEventBus _eventBus;
|
||||
final MailboxStateService _mailboxState;
|
||||
final EmailListStateService _emailListState;
|
||||
|
||||
DashboardDomainRegistry(
|
||||
this._queue, this._session, this._eventBus,
|
||||
this._mailboxState, this._emailListState,
|
||||
);
|
||||
|
||||
late final emailAction = EmailActionDelegate(
|
||||
_queue, _session, _mailboxState,
|
||||
Get.find<IEmailMoveRepository>(),
|
||||
);
|
||||
late final search = SearchDelegate(_session, _emailListState);
|
||||
|
||||
@override
|
||||
List<ControllerDelegate> get delegates => [emailAction, search];
|
||||
}
|
||||
|
||||
// View access via the registry:
|
||||
Get.find<DashboardDomainRegistry>().emailAction.moveToTrash(email);
|
||||
```
|
||||
|
||||
Adding a new delegate = one `late final` line + one entry in `delegates`. Zero bindings edits.
|
||||
|
||||
#### 3. AppEventBus — wrapper events, no domain inheritance
|
||||
|
||||
Cross-feature announcements flow through a typed event bus. Domain `Success`/`Failure` types belong to the domain layer and **must not** extend `AppEvent` — that would invert the dependency rule and break Clean Architecture. Cross-feature delivery uses **wrapper events** defined in the base layer.
|
||||
|
||||
```dart
|
||||
// lib/features/base/event_bus/app_event.dart
|
||||
sealed class AppEvent {}
|
||||
|
||||
// lib/features/base/event_bus/events/action_events.dart
|
||||
class ActionCompleted<T extends Success> extends AppEvent {
|
||||
final T result;
|
||||
const ActionCompleted(this.result);
|
||||
}
|
||||
|
||||
class ActionFailed<T extends Failure> extends AppEvent {
|
||||
final T failure;
|
||||
const ActionFailed(this.failure);
|
||||
}
|
||||
|
||||
// lib/features/base/event_bus/app_event_bus.dart
|
||||
class AppEventBus extends GetxService {
|
||||
final _subject = PublishSubject<AppEvent>();
|
||||
|
||||
Stream<T> on<T extends AppEvent>() => _subject.stream.whereType<T>();
|
||||
void emit(AppEvent event) => _subject.add(event);
|
||||
|
||||
@override void onClose() { _subject.close(); super.onClose(); }
|
||||
}
|
||||
```
|
||||
|
||||
**Scope of named events:** intentional cross-feature commands (`SessionEstablishedEvent`, `SessionEndedEvent`, `ComposerOpenedEvent`, `SpamBannerRefreshEvent`). Domain outcomes use `ActionCompleted<T>` / `ActionFailed<T>` wrappers fired by `ActionQueue`.
|
||||
|
||||
**Rule:** Always consume via `eventBus.on<T>().listen(...)`. Never use `switch (event)` on `AppEvent` directly — adding a new subclass would silently miss exhaustive-switch consumers without a compile error.
|
||||
|
||||
#### 4. SessionService — constructor-injected EventBus, no public setter
|
||||
|
||||
`SessionService` holds the session as read-only Rx refs. Writes happen **only** inside its own `SessionEstablishedEvent` listener. There is no public setter. The login feature emits an event — it never imports `SessionService`.
|
||||
|
||||
`AppEventBus` is passed via the constructor (not via `Get.find` in `onInit`), so `SessionService` is DIP-compliant and testable without the DI container.
|
||||
|
||||
```dart
|
||||
class SessionService extends GetxService {
|
||||
final AppEventBus _eventBus;
|
||||
SessionService(this._eventBus);
|
||||
|
||||
final _session = Rxn<Session>();
|
||||
final _accountId = Rxn<AccountId>();
|
||||
Rxn<Session> get session => _session;
|
||||
Rxn<AccountId> get accountId => _accountId;
|
||||
|
||||
StreamSubscription? _established;
|
||||
StreamSubscription? _ended;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
_established = _eventBus.on<SessionEstablishedEvent>().listen((e) {
|
||||
_session.value = e.session;
|
||||
_accountId.value = e.accountId;
|
||||
});
|
||||
_ended = _eventBus.on<SessionEndedEvent>().listen((_) {
|
||||
_session.value = null;
|
||||
_accountId.value = null;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_established?.cancel();
|
||||
_ended?.cancel();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```dart
|
||||
// Login success handler — emits only:
|
||||
Get.find<AppEventBus>().emit(SessionEstablishedEvent(session, accountId));
|
||||
```
|
||||
|
||||
#### 5. State services — single-writer rule
|
||||
|
||||
State that multiple delegates need (session, selected mailbox, email list) moves to dedicated `GetxService` instances. Delegates depend on state services, not on god controllers. Each Rx field is documented with its **single writer** — the one delegate (or the service itself) allowed to update it. Other delegates read-only.
|
||||
|
||||
```dart
|
||||
class MailboxStateService extends GetxService {
|
||||
/// Writer: MailboxNavigationDelegate
|
||||
final _selectedMailbox = Rxn<PresentationMailbox>();
|
||||
Rxn<PresentationMailbox> get selectedMailbox => _selectedMailbox;
|
||||
void updateSelectedMailbox(PresentationMailbox? value) => _selectedMailbox.value = value;
|
||||
|
||||
/// Writer: MailboxCatalogDelegate
|
||||
final _mapMailboxById = <MailboxId, PresentationMailbox>{}.obs;
|
||||
RxMap<MailboxId, PresentationMailbox> get mapMailboxById => _mapMailboxById;
|
||||
void replaceMailboxMap(Map<MailboxId, PresentationMailbox> v) {
|
||||
_mapMailboxById..clear()..addAll(v);
|
||||
}
|
||||
|
||||
void clear() { _selectedMailbox.value = null; _mapMailboxById.clear(); }
|
||||
}
|
||||
```
|
||||
|
||||
State services expose `update*` / `replace*` methods — never a public setter. Cross-delegate reads are OK; cross-delegate writes go through the named owner or an event.
|
||||
|
||||
Both state services registered as permanent in `main_bindings.dart`. Cleared (not deleted) on logout via the `SessionEndedEvent` listener; reused on re-login.
|
||||
|
||||
#### 6. ActionQueue — centralised async execution
|
||||
|
||||
`consumeState()` is `@Deprecated`. New delegates submit self-contained action objects to a centralised queue. The queue:
|
||||
|
||||
1. **Cancel-before-replace.** Submitting a new action with an existing `tag` cancels the in-flight subscription first — preventing leaked subs on tag collision.
|
||||
2. **No-op on missing session.** If `SessionService` has no session, `submit()` logs and returns. It never throws.
|
||||
3. **Wrapper events.** Success fires `ActionCompleted<T>`; failure fires `ActionFailed<T>`. Domain types are never cast to `AppEvent`.
|
||||
4. **`cancelAll()`.** Called on `onSessionEnd()` to purge all in-flight subscriptions before session-scoped services are deleted.
|
||||
|
||||
```dart
|
||||
abstract class DomainAction<R extends Success> {
|
||||
String get tag; // e.g. 'MarkAsRead:${emailId.value}'
|
||||
Stream<Either<Failure, Success>> execute(Session session, AccountId accountId);
|
||||
}
|
||||
|
||||
class ActionQueue extends GetxService {
|
||||
final AppEventBus _eventBus;
|
||||
final SessionService _session;
|
||||
final _active = <String, StreamSubscription>{};
|
||||
|
||||
ActionQueue(this._eventBus, this._session);
|
||||
|
||||
void submit(DomainAction action, {CancellationToken? token, ValueChanged<Success>? onSuccess, ValueChanged<Failure>? onFailure}) {
|
||||
final s = _session.session.value;
|
||||
final id = _session.accountId.value;
|
||||
if (s == null || id == null) { log('ActionQueue::submit skipped ${action.tag}'); return; }
|
||||
|
||||
_active.remove(action.tag)?.cancel(); // cancel-before-replace
|
||||
|
||||
late StreamSubscription sub;
|
||||
sub = action.execute(s, id).listen(
|
||||
(result) => result.fold(
|
||||
(f) { _eventBus.emit(ActionFailed(f)); if (token?.isCancelled != true) onFailure?.call(f); },
|
||||
(r) { _eventBus.emit(ActionCompleted(r)); if (token?.isCancelled != true) onSuccess?.call(r); },
|
||||
),
|
||||
onDone: () { if (identical(_active[action.tag], sub)) _active.remove(action.tag); },
|
||||
);
|
||||
_active[action.tag] = sub;
|
||||
}
|
||||
|
||||
void cancelAll() {
|
||||
for (final s in _active.values) s.cancel();
|
||||
_active.clear();
|
||||
}
|
||||
|
||||
@override void onClose() { cancelAll(); super.onClose(); }
|
||||
}
|
||||
```
|
||||
|
||||
**`CancellationToken`:** screen-scoped callbacks skip when cancelled; HTTP still completes. Omit token = background execution that survives controller disposal.
|
||||
|
||||
#### 7. BaseController strip — four focused services
|
||||
|
||||
`BaseController` accumulated 14 field-level `Get.find` calls unrelated to lifecycle. Delegates that need a GetxController base (rare — the default is plain `ControllerDelegate`) must inherit a lean base, not 14 unrelated dependencies. Extract into four services registered in `main_bindings.dart`:
|
||||
|
||||
- `AuthService` — auth interceptors, logout interactors.
|
||||
- `CacheService` — caching managers.
|
||||
- `UIService` — toast, uuid, toast manager, app manager.
|
||||
- `ViewContextService` — `imagePaths`, `responsiveUtils`. View-layer helpers that both views and controllers read.
|
||||
|
||||
After extraction, `BaseController` ≤250 LOC. It retains only lifecycle concerns (`workerObxVariables`, `_stateSubscriptions`, `onClose`).
|
||||
|
||||
#### 8. DIP rule: `Get.find<>()` and `XBindings().dependencies()` only in bindings + registries
|
||||
|
||||
Controllers and delegates declare dependencies in their constructors. `Get.find<>()` and `XBindings().dependencies()` appear only inside `*_bindings.dart` files and `DomainRegistry` subclasses — never in business logic.
|
||||
|
||||
**Accepted exceptions:**
|
||||
|
||||
| Exception | Reason |
|
||||
|---|---|
|
||||
| `inject*()` methods in `BaseController` / `ReloadableController` | JMAP capabilities are only known after session establishment; capability-gated interactor bindings are permitted here and must register interactors only — never controllers |
|
||||
| `fcm_message_controller.dart` | Dart isolate for background push must re-bootstrap full DI |
|
||||
| `main_entry.dart` | App startup |
|
||||
|
||||
**Panel-scoped widget-swap pattern** — on web, some panels are rendered via widget swap (not `Get.toNamed`/`GetPage`). GetX does NOT manage their lifecycle automatically. The fix: register panel controllers in the **parent route's binding** using `Get.lazyPut(fenix: true)`, and dispose via `Get.delete<XController>(force: true)` in the exit handler — never via `XBindings().disposeBindings()` from a controller body.
|
||||
|
||||
**Enforcement:**
|
||||
|
||||
- **Runtime:** `scripts/check_architecture.sh` — auto-discovering LOC gate for controllers ≥700 LOC, plus grep-based rules for `Get.find` placement, bare `ever()`, binding calls, cross-feature datasource injection, and domain `AppEvent` inheritance.
|
||||
- **IDE:** `custom_lint` package at `tools/tmail_lint/` with four rules: `avoid_bare_ever`, `no_get_find_outside_bindings`, `no_binding_call_outside_bindings`, `no_appevent_domain_inheritance`.
|
||||
|
||||
The CI script runs on every PR and is authoritative. Lint rules catch violations in-IDE before CI.
|
||||
|
||||
#### 9. ISP for repositories
|
||||
|
||||
Split fat repository interfaces into focused ones per delegate. Each delegate depends **only** on the interface covering its domain. Existing fat repositories silently implement all the narrow interfaces — zero data-layer changes.
|
||||
|
||||
Narrow interfaces are declared **just-in-time**: in the same commit that creates the delegate consuming them. No upfront interface sprawl.
|
||||
|
||||
#### 10. Session lifecycle protocol
|
||||
|
||||
Explicit create/clear/delete contract at each session boundary:
|
||||
|
||||
```dart
|
||||
void onSessionReady(Session session, AccountId accountId) {
|
||||
Get.find<AppEventBus>().emit(SessionEstablishedEvent(session, accountId));
|
||||
// SessionService + state services react to the event and populate.
|
||||
|
||||
// Session-scoped registries (created by per-controller Layer 2 phases):
|
||||
Get.put(XDomainRegistry(...));
|
||||
}
|
||||
|
||||
void onSessionEnd() {
|
||||
Get.find<AppEventBus>().emit(const SessionEndedEvent());
|
||||
// SessionService + state services react to SessionEndedEvent and clear.
|
||||
|
||||
Get.find<ActionQueue>().cancelAll();
|
||||
|
||||
// Session-scoped registries: delete (onClose disposes every delegate)
|
||||
Get.delete<XDomainRegistry>();
|
||||
}
|
||||
```
|
||||
|
||||
| Tier | Components | Created | Destroyed |
|
||||
|---|---|---|---|
|
||||
| **Boot** (permanent) | `AppEventBus`, `ActionQueue`, `SessionService`, state services, `AuthService`, `CacheService`, `UIService`, `ViewContextService` | `main_bindings.dart` | Never (cleared on `SessionEndedEvent`) |
|
||||
| **Session** | Session-scoped domain registries | `onSessionReady()` | `onSessionEnd()` |
|
||||
| **Route** | Route-scoped domain registries, screen controllers | Route binding | Route pop |
|
||||
| **Widget** | Micro-controllers | Widget build | Widget dispose |
|
||||
|
||||
The foundation plan establishes this contract. Actual integration into login/logout flow happens in the first per-controller Layer 2 phase that requires a session-scoped registry.
|
||||
|
||||
#### 11. Operation lifetime classification
|
||||
|
||||
| Duration | Owner | Example |
|
||||
|---|---|---|
|
||||
| Instant (<1s) | Delegate | Toggle star, mark read |
|
||||
| Short (1–5s) | Delegate + toast on fail | Move to folder |
|
||||
| Long (>5s, user may navigate) | Session-lifetime service | Download, send email, empty trash |
|
||||
| Background (survives app) | Platform service (WorkManager / FCM) | FCM sync, sending queue |
|
||||
|
||||
Long-running controllers are reclassified as session-lifetime `GetxService` instances by the per-controller phase that touches them. Views observe via `Get.find<XService>().state` — independent of any screen controller.
|
||||
|
||||
### Target metrics (foundation)
|
||||
|
||||
Per-controller LOC targets are tracked in each controller's Layer 2 phase file when it is created. Foundation targets apply after Phases 0–2 land:
|
||||
|
||||
| Metric | Target | When |
|
||||
|---|---|---|
|
||||
| `BaseController` LOC | ≤250 | Phase 2 |
|
||||
| `ReloadableController` field `Get.find` | 0 | Phase 2 |
|
||||
| Bare `ever()` calls | 0 (ratcheted) | Foundation → Layer 2 |
|
||||
| `Get.find<>()` outside bindings | ratcheted from current baseline | Foundation → Layer 2 |
|
||||
| `XBindings().dependencies()` outside bindings | 0 | Phase 2 |
|
||||
| Cross-feature `DataSource` in bindings | 0 (CI-enforced) | Foundation |
|
||||
| Domain types extending `AppEvent` | 0 (CI-enforced) | Phase 0 |
|
||||
| Controllers >700 LOC | Auto-discovered + gated (no regressions) | Phase 0 |
|
||||
| Pilot delegate | `NotificationDelegate` shipped to production | Phase 2 |
|
||||
|
||||
Per-controller targets (LOC reduction, delegate count, Rxn elimination, ISP interfaces, session lifecycle wiring) are owned by each Layer 2 phase file.
|
||||
|
||||
### Refactor phases
|
||||
|
||||
See `plans/260403-1706-solid-refactor/plan.md` for the full phased plan.
|
||||
|
||||
| Phase | What | Blocking | Effort |
|
||||
|---|---|---|---|
|
||||
| 0 | Safety Foundation: `workerObxVariables` → `BaseController`, `consumeState()` stream fix + `@Deprecated`, `ControllerDelegate` abstract base class, auto-discovering CI script, `custom_lint` package | Non-blocking — additive only | 2d |
|
||||
| 1 | Core Infrastructure: `AppEventBus` + wrapper events, constructor-injected `SessionService`, state services with single-writer rule, `ActionQueue` + `DomainAction` + `CancellationToken` (cancel-before-replace, `cancelAll()`), `DomainRegistry` abstract base with lifecycle propagation, characterization test template | Non-blocking — new files only | 3d |
|
||||
| 2 | BaseController strip (→≤250 LOC), `ReloadableController` ctor injection, `AuthService` / `CacheService` / `UIService` / `ViewContextService` extraction, bindings split, panel-scoped binding migration, **`NotificationDelegate` pilot shipped to production** | **4-day coordination window** | 4d |
|
||||
| N | Generic per-controller extraction protocol (template). One instance created JIT per god controller, smallest LOC first. Runs in git worktrees. Includes domain table discovery, delegate extraction, Rxn→wrapper-event migration, satellite decoupling, session lifecycle wiring (if session-scoped). | Non-blocking (git worktree) | per controller |
|
||||
|
||||
**Foundation total: ~2 weeks.** Per-controller phases are scheduled independently.
|
||||
|
||||
---
|
||||
|
||||
## How to refactor without regression
|
||||
|
||||
### Zero-tolerance regression rules (enforce before every commit)
|
||||
|
||||
1. `workerObxVariables.add(ever(...))` for GetxControllers; `trackWorker(ever(...))` for `ControllerDelegate`. Never bare `ever()`.
|
||||
2. `consumeState()` is `@Deprecated`. Zero NEW callers in delegates or registries.
|
||||
3. Every `ControllerDelegate` with EventBus subscriptions stores and cancels them via `trackSub(...)`.
|
||||
4. `SessionService` has no public setter; writes happen only in the `SessionEstablishedEvent` / `SessionEndedEvent` listeners.
|
||||
5. One delegate per commit, CI green before the next extraction starts.
|
||||
6. Each decomposition phase file owns the event files it introduces — no cross-phase edits to event files.
|
||||
7. `Get.find<>()` never inside delegate bodies, extension methods, or mixin bodies. Bindings + `DomainRegistry` subclasses only.
|
||||
8. `XBindings().dependencies()` never called from a controller body (accepted exceptions: `inject*()` methods in `BaseController`/`ReloadableController`, `fcm_message_controller.dart`, `main_entry.dart`).
|
||||
9. Domain `Success`/`Failure` types never extend `AppEvent`. Cross-feature delivery uses `ActionCompleted<T>` wrapper events or named base-layer events.
|
||||
10. `ActionQueue.submit()` cancels any existing subscription for the same `tag` before installing a new one.
|
||||
11. `ActionQueue.cancelAll()` is called on `onSessionEnd()` — no orphaned streams survive logout.
|
||||
12. Every Rxn action type owned by a delegate is replaced with a typed wrapper event in the same commit as the delegate extraction. When all types for a Rxn stream are migrated, the Rxn field is deleted.
|
||||
13. `ControllerDelegate` is a plain Dart class (not a `BaseController`). It does not appear in `Get.find<>()` directly — it is owned by its registry.
|
||||
14. State services expose one `update*` method per Rx var, documented with the name of the single writer delegate.
|
||||
|
||||
### Delegate extraction process (per delegate)
|
||||
|
||||
1. Identify the domain boundary from the Layer 2 phase's Day 0 table.
|
||||
2. Write characterization tests against the current god controller before touching production code.
|
||||
3. Create the narrow ISP repository interface.
|
||||
4. Extract the delegate (subclass `ControllerDelegate`, no `Get.find`, track workers and subs).
|
||||
5. Add a forwarding stub in the god controller — keeps the codebase green during transition.
|
||||
6. Migrate Rxn action types owned by this delegate to typed wrapper events.
|
||||
7. Add a `late final` field in the domain registry (creating the registry if this is the first delegate for the screen).
|
||||
8. Update views to read via the registry: `Get.find<XDomainRegistry>().y.doThing(...)`.
|
||||
9. Migrate tests inline — mock the ISP interface and `ActionQueue`, not the fat repository or god controller.
|
||||
10. Run `dart run build_runner build --delete-conflicting-outputs`.
|
||||
11. Delete forwarding stub + absorbed extension files.
|
||||
12. Full regression gate: `flutter analyze && flutter test && bash scripts/check_architecture.sh`.
|
||||
13. One delegate per commit.
|
||||
|
||||
If tests fail after extraction: revert the extraction, not the tests.
|
||||
|
||||
---
|
||||
|
||||
## How new features must be added (SOLID compliance)
|
||||
|
||||
### Rule: new capability = new `ControllerDelegate` subclass + one `late final` line in the registry
|
||||
|
||||
**Never add state or logic to an existing controller.** Instead:
|
||||
|
||||
1. Create a delegate at `lib/features/{feature}/presentation/delegates/{capability}_delegate.dart` extending `ControllerDelegate`.
|
||||
2. Create a narrow ISP interface if repository access is needed.
|
||||
3. Add a `late final` field in the domain registry (and include it in `delegates`).
|
||||
4. Bind the view via the registry: `Get.find<XDomainRegistry>().snooze.snoozedEmails`.
|
||||
|
||||
The existing controller and bindings are **never modified**. Zero bindings edits.
|
||||
|
||||
### Decision table
|
||||
|
||||
| Situation | Pattern | Location |
|
||||
|---|---|---|
|
||||
| New UI state for an existing screen | `ControllerDelegate` via domain registry | `presentation/delegates/` |
|
||||
| State shared across 2+ features | `GetxService` | `presentation/services/` |
|
||||
| Stateless helper (pure function) | Extension method | `presentation/extensions/` |
|
||||
| New usecase coordination | `ControllerDelegate` with `ActionQueue.submit()` | `presentation/delegates/` |
|
||||
| Cross-feature event (e.g. email sent → refresh thread) | `AppEventBus` event | emit in delegate, listen in another delegate |
|
||||
|
||||
### Example: adding "Snooze email"
|
||||
|
||||
```
|
||||
❌ Wrong: open mailbox_dashboard_controller.dart and add snoozeEmail() + snoozeUntil Rx
|
||||
|
||||
✓ Correct:
|
||||
1. Create lib/features/mailbox_dashboard/presentation/delegates/snooze_delegate.dart
|
||||
extends ControllerDelegate
|
||||
- Deps: ActionQueue, SessionService, ISnoozeRepository (narrow ISP interface)
|
||||
- State: RxList<SnoozedEmail> snoozedEmails
|
||||
- Method: void snoozeEmail(email, duration) => _queue.submit(SnoozeAction(...))
|
||||
|
||||
2. Add to DashboardDomainRegistry:
|
||||
late final snooze = SnoozeDelegate(_queue, _session, Get.find<ISnoozeRepository>());
|
||||
// and append `snooze` to the `delegates` list
|
||||
// Zero changes to bindings file
|
||||
|
||||
3. Bind view widget via registry:
|
||||
Obx(() => Get.find<DashboardDomainRegistry>().snooze.snoozedEmails.isEmpty
|
||||
? SizedBox.shrink()
|
||||
: SnoozeListWidget())
|
||||
```
|
||||
|
||||
### Checklist for any new feature PR
|
||||
|
||||
- [ ] No new methods added to an existing god controller
|
||||
- [ ] New delegate extends `ControllerDelegate`, < 200 LOC
|
||||
- [ ] Delegate constructor lists all dependencies explicitly (no `Get.find<>()` inside)
|
||||
- [ ] Delegate uses `ActionQueue.submit()` for async operations — never `consumeState()`
|
||||
- [ ] All `ever()` / `debounce()` calls wrapped in `trackWorker(...)`
|
||||
- [ ] Delegate depends on narrow `IXxxRepository` interface, not fat repository
|
||||
- [ ] Delegate registered in a `DomainRegistry` subclass — not individual `Get.lazyPut`
|
||||
- [ ] Delegate included in the registry's `delegates` list (for lifecycle)
|
||||
- [ ] View binds via registry, not direct `Get.find<XDelegate>()`
|
||||
- [ ] Unit test file created alongside delegate; mocks the ISP interface + `ActionQueue`
|
||||
- [ ] No stateful `.obs` in extension files
|
||||
- [ ] No `Get.find<>()` inside extension methods (use constructor injection via registry)
|
||||
- [ ] Domain types do not extend `AppEvent` — use `ActionCompleted<T>` wrapper
|
||||
- [ ] `flutter analyze` passes
|
||||
- [ ] `bash scripts/check_architecture.sh` exits 0
|
||||
|
||||
---
|
||||
|
||||
## ELI5: What are the classes and their roles?
|
||||
|
||||
Think of the app as an office building. Each class is a type of person or room with one job.
|
||||
|
||||
**`BaseController` — the safety inspector**
|
||||
Every worker in the building must sign in and sign out. `BaseController` holds the sign-in sheet (`workerObxVariables`, `_stateSubscriptions`). When a worker leaves (`onClose`), it makes sure they cancelled every subscription and disposed every reactive listener.
|
||||
|
||||
**`ReloadableController` — the badge checker**
|
||||
Extends `BaseController`. Before starting work each day, it re-validates the session (your access badge). If the badge expired overnight, it re-authenticates. Subclasses pass their session tools in via constructor — it never goes hunting for them.
|
||||
|
||||
**`ControllerDelegate` — the specialist (plain Dart class)**
|
||||
One delegate = one job. `SearchDelegate` only knows about search. `LabelDelegate` only knows about labels. It is a plain Dart class — not a GetxController, not a BaseController. Its manager (the `DomainRegistry`) tells it when to start (`init()`) and when to stop (`dispose()`). It never goes to `Get.find<>()` itself; the registry delivers its tools at the door. Max 200 LOC. Workers tracked via `trackWorker`, subscriptions via `trackSub`.
|
||||
|
||||
**`DomainRegistry` — the department manager**
|
||||
Owns a set of delegates for one screen or department. It's the only layer (outside bindings) allowed to call `Get.find<>()` for infrastructure. It hands each delegate exactly the dependencies it needs via constructor. Drives the delegate lifecycle: calls `init()` on everyone when the manager starts, and `dispose()` in reverse order when the manager shuts down. Adding a new specialist = one `late final` line in the manager's roster.
|
||||
|
||||
**State Services (`SessionService`, `MailboxStateService`, `EmailListStateService`) — the shared whiteboards**
|
||||
Information everyone needs (current session, selected mailbox, email list) lives here. Each whiteboard field has exactly ONE person allowed to erase and rewrite it — the name is in the comment above the field. Everyone else can only read. `SessionService` listens to the PA system for `SessionEstablishedEvent` and updates itself — login never touches it directly.
|
||||
|
||||
**`AppEventBus` — the PA system**
|
||||
When something important happens (email moved, draft saved, composer opened), a delegate announces it on the PA system. Other delegates that care tune in. Crucially, domain results (`MarkAsEmailReadSuccess`) are wrapped in `ActionCompleted<T>` before being announced — the PA system only speaks "base language", so domain classes don't leak across layer boundaries.
|
||||
|
||||
**`ActionQueue` — the task dispatcher**
|
||||
When a delegate needs async work, it hands a self-contained task slip (`DomainAction`) to the dispatcher. The dispatcher checks the session badge, runs the task, and announces the result (wrapped in `ActionCompleted<T>`) on the PA system. Tag uniqueness: if you submit "MarkAsRead:email123" twice in a row, the first one is cancelled before the second starts — no leaked subs. At logout, `cancelAll()` kills every in-flight task.
|
||||
|
||||
**`*_bindings.dart` — the front desk**
|
||||
Registers the department managers and the permanent whiteboards. `Get.find<>()` appears only here and in `DomainRegistry` subclasses — never inside a delegate, controller, or view logic. One binding = one screen's wiring diagram.
|
||||
|
||||
**ISP repository interfaces (`IXRepository`) — the job description**
|
||||
Instead of giving a delegate the entire `EmailRepository` (a 40-method fat class), we write a narrow job description. The delegate depends on the description, not the whole department. The existing fat repository silently implements all narrow interfaces — no data layer changes required.
|
||||
|
||||
**Extension methods (`on XController`) — the calculator on the desk**
|
||||
A stateless helper that derives a value from state the controller already has. No memory, no `Get.find<>()`, no `.obs`. If it needs an external dependency, it is not an extension — it belongs in a delegate constructor.
|
||||
|
||||
---
|
||||
|
||||
## ELI5: How do the layers talk to each other?
|
||||
|
||||
There are exactly six ways things communicate. If you find a seventh, it is a bug.
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────┐
|
||||
│ VIEW │
|
||||
│ reads state: Get.find<DashboardDomainRegistry>().x.rxVar │
|
||||
│ triggers: Get.find<DashboardDomainRegistry>().x.doX() │
|
||||
└──────────────────┬───────────────────────────────────────────┘
|
||||
│ (1) reactive read + action call
|
||||
▼
|
||||
┌──────────────────────────────────────────────────────────────┐
|
||||
│ DOMAIN REGISTRY (owns + drives delegate lifecycle) │
|
||||
│ ControllerDelegates — plain Dart, init()/dispose() │
|
||||
│ observes shared state via: ever(_stateService.rx, ...) │──(2) state service Rx ref
|
||||
│ submits async work via: _queue.submit(DomainAction) │──(4) ActionQueue
|
||||
│ announces events via: eventBus.emit(...) │──(3) EventBus
|
||||
│ listens to events via: eventBus.on<T>().listen │
|
||||
└──────────────────────────────────────────────────────────────┘
|
||||
(2) ▲ (3) ▲ ▼ (4) ▼
|
||||
│ │ ┌─────────────────┐
|
||||
┌──────────────────┐ ┌──────────┐ │ ActionQueue │
|
||||
│ State Services │ │ EventBus │ │ cancel-replace │
|
||||
│ (single writer) │ │ PA sys │ │ cancelAll() │──→ EventBus
|
||||
└──────────────────┘ └──────────┘ └─────────────────┘
|
||||
▲ (5) (6) ▲
|
||||
Login emits SessionEstablishedEvent onSessionReady/End
|
||||
SessionService subscribes creates/deletes registries
|
||||
```
|
||||
|
||||
**(1) View → Registry → Delegate** — the only way the UI gets data or sends actions.
|
||||
|
||||
**(2) State Services → Delegate constructor** — Rx references injected at registry creation.
|
||||
|
||||
**(3) Cross-feature announcements** — EventBus with wrapper events. Never state.
|
||||
|
||||
**(4) Delegate → ActionQueue → Domain** — async work via self-contained action objects.
|
||||
|
||||
**(5) Login → Session** — login emits `SessionEstablishedEvent`; `SessionService` owns its own update via its listener.
|
||||
|
||||
**(6) Session lifecycle** — explicit create/clear/delete via `onSessionReady` / `onSessionEnd`.
|
||||
|
||||
**The one rule that summarises all six:** data flows through state service Rx references; actions flow through ActionQueue; cross-feature side-effects flow through EventBus with wrapper events; session boundaries flow through the lifecycle protocol. Nothing else.
|
||||
|
||||
---
|
||||
|
||||
## Consequences
|
||||
|
||||
**Benefits:**
|
||||
- Each concern is independently testable in isolation
|
||||
- New features add zero coupling to existing controllers (OCP) — one `late final` line in the registry
|
||||
- Dependencies are explicit and injectable (DIP)
|
||||
- Controller LOC drops substantially — readable, reviewable
|
||||
- Onboarding: new developers understand one delegate at a time
|
||||
- `ActionQueue` eliminates per-delegate stream subscription boilerplate — submit and forget
|
||||
- Wrapper events eliminate destructive-read race conditions from Rxn dispatch and keep domain types off the base layer
|
||||
- State services decouple delegates from god controllers — delegates depend on services, not each other
|
||||
- Session lifecycle protocol prevents stale state across login/logout cycles
|
||||
- `DomainRegistry` lifecycle propagation eliminates the GetX hazard where `late final` delegates never receive `onInit`/`onClose`
|
||||
|
||||
**Costs:**
|
||||
- Foundation is ~2 weeks before the first god controller is touched
|
||||
- Per-controller extraction is effort-intensive — each Layer 2 phase is 1–2 weeks depending on size
|
||||
- Views updated to reference delegates via registries — mass find-replace across many files
|
||||
- `Get.find<>()` discipline enforced by `custom_lint` package (4 rules) + CI script
|
||||
|
||||
**Risks:**
|
||||
- Stateful extension files have hidden interdependencies — extract one at a time
|
||||
- Mock regeneration will temporarily break test files — fix immediately per phase
|
||||
- Complex mixins with state may require their own delegates — evaluate before absorbing
|
||||
- Rxn→wrapper-event migration must be atomic per delegate — partial migration leaves both systems active
|
||||
- `DomainRegistry` lifecycle discipline depends on subclasses correctly listing delegates in the `delegates` override — forgetting one leaks workers. Mitigation: unit tests verify `dispose()` drops workers to zero for every registry
|
||||
@@ -0,0 +1,346 @@
|
||||
## Phase 0: Safety Foundation
|
||||
|
||||
**Priority:** P1 | **Status:** pending | **Effort:** 2 days
|
||||
**Blocking:** Non-blocking — all changes are additive or bug fixes. Land directly on `master`. Feature PRs unaffected.
|
||||
|
||||
> After this phase, the CI enforcement script is in place and new feature PRs are gated by current-baseline thresholds (not yet ratcheted). Any new code following the delegate pattern will pass automatically. The `ControllerDelegate` base class is available but has no subclasses yet — the first one lands as the pilot in Phase 2.
|
||||
|
||||
---
|
||||
|
||||
### Tasks
|
||||
|
||||
#### 0. Move `workerObxVariables` to `BaseController`
|
||||
|
||||
```dart
|
||||
// lib/features/base/base_controller.dart
|
||||
abstract class BaseController extends GetxController {
|
||||
// All ever()/debounce() workers MUST be registered here — never bare ever().
|
||||
final workerObxVariables = <Worker>[];
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
for (final w in workerObxVariables) w.dispose();
|
||||
workerObxVariables.clear();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Remove any duplicate `workerObxVariables` declarations from subclasses (god controllers often redeclare this — search and delete).
|
||||
|
||||
#### 0b. Fix `consumeState()` stream leak + deprecate
|
||||
|
||||
Fix the leak first (existing code still uses it), then mark deprecated. Phase 1 introduces `ActionQueue` as the replacement.
|
||||
|
||||
```dart
|
||||
// Add field:
|
||||
final _stateSubscriptions = <StreamSubscription>[];
|
||||
|
||||
// Replace consumeState():
|
||||
@Deprecated('Use ActionQueue.submit() for new delegates. '
|
||||
'consumeState will be removed after all controllers migrate.')
|
||||
void consumeState(Stream<Either<Failure, Success>> newStateStream) {
|
||||
_stateSubscriptions.add(newStateStream.listen(onData, onError: onError, onDone: onDone));
|
||||
}
|
||||
|
||||
// Extend onClose():
|
||||
@override
|
||||
void onClose() {
|
||||
for (final sub in _stateSubscriptions) sub.cancel();
|
||||
_stateSubscriptions.clear();
|
||||
for (final w in workerObxVariables) w.dispose();
|
||||
workerObxVariables.clear();
|
||||
super.onClose();
|
||||
}
|
||||
```
|
||||
|
||||
The `@Deprecated` annotation produces analyzer warnings in any new code calling `consumeState()`. Existing code compiles without error. Removal happens after all controllers migrate to `ActionQueue`.
|
||||
|
||||
#### 0c. `ControllerDelegate` abstract base class
|
||||
|
||||
Introduce the canonical delegate base as a **plain Dart class** (not a `GetxController`, not a `BaseController`). Delegates are owned by their `DomainRegistry`, which drives their lifecycle deterministically. This avoids a known GetX hazard: when a delegate is stored as a `late final` inside a `GetxService`, GetX never calls `onInit`/`onClose` on the delegate — workers leak.
|
||||
|
||||
```dart
|
||||
// lib/features/base/delegate/controller_delegate.dart
|
||||
import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
/// Base class for all controller delegates.
|
||||
///
|
||||
/// A delegate owns one feature's state and behavior. It is NOT a GetxController.
|
||||
/// Its lifecycle is driven by its parent DomainRegistry via init() / dispose().
|
||||
///
|
||||
/// Delegates register GetX workers (ever/debounce/once/interval) via
|
||||
/// [trackWorker] and event bus subscriptions via [trackSub]. Both are
|
||||
/// disposed in [dispose], which the registry calls from its onClose().
|
||||
abstract class ControllerDelegate {
|
||||
final _workers = <Worker>[];
|
||||
final _subs = <StreamSubscription>[];
|
||||
|
||||
/// Register a GetX worker for automatic disposal.
|
||||
/// Usage: `trackWorker(ever(stateService.selectedMailbox, _onChange));`
|
||||
@protected
|
||||
Worker trackWorker(Worker worker) {
|
||||
_workers.add(worker);
|
||||
return worker;
|
||||
}
|
||||
|
||||
/// Register a stream subscription for automatic disposal.
|
||||
/// Usage: `trackSub(eventBus.on<XEvent>().listen(_handle));`
|
||||
@protected
|
||||
StreamSubscription<T> trackSub<T>(StreamSubscription<T> sub) {
|
||||
_subs.add(sub);
|
||||
return sub;
|
||||
}
|
||||
|
||||
/// Called once by the owning DomainRegistry in its onInit().
|
||||
/// Subclasses register workers and event subscriptions here.
|
||||
@mustCallSuper
|
||||
void init() {}
|
||||
|
||||
/// Called once by the owning DomainRegistry in its onClose().
|
||||
/// Disposes all tracked workers and subscriptions.
|
||||
@mustCallSuper
|
||||
void dispose() {
|
||||
for (final w in _workers) w.dispose();
|
||||
for (final s in _subs) s.cancel();
|
||||
_workers.clear();
|
||||
_subs.clear();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** This class has zero subclasses in Phase 0. The first subclass is the `NotificationDelegate` pilot in Phase 2. The CI lint rules below enforce that when subclasses appear, they follow the template (no bare `ever()`, no `Get.find<>()` inside delegate body).
|
||||
|
||||
#### 1. CI enforcement script — auto-discovering controller LOC gate
|
||||
|
||||
Create `scripts/check_architecture.sh`. Thresholds start at **current baselines** — CI never fails existing code; only prevents regressions beyond baseline.
|
||||
|
||||
**Key design — auto-discovery of god controllers.** Instead of hardcoding a list of controller paths, the script walks `lib/features/**/presentation/controller/*_controller.dart`, gates any controller at or above 700 LOC, and records its baseline. Baselines live in `scripts/controller_loc_baselines.txt` (one `path=loc` per line). A PR cannot increase any baselined controller's LOC. When a controller's LOC drops below 700, it is removed from the baseline file and no longer gated.
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
set -e
|
||||
FAIL=0
|
||||
|
||||
BASE_LOC=$(wc -l < lib/features/base/base_controller.dart | tr -d ' ')
|
||||
BASE_MAX=${BASE_MAX:-647} # ratcheted to 250 after Phase 2
|
||||
|
||||
echo "BaseController LOC: $BASE_LOC / $BASE_MAX"
|
||||
[ "$BASE_LOC" -le "$BASE_MAX" ] || { echo "FAIL: BaseController $BASE_LOC LOC (max $BASE_MAX)"; FAIL=1; }
|
||||
|
||||
# ── Auto-discover controllers over 700 LOC and gate each against baseline ──
|
||||
BASELINE_FILE="scripts/controller_loc_baselines.txt"
|
||||
touch "$BASELINE_FILE"
|
||||
|
||||
# Build current snapshot: path=loc for every controller >= 700 LOC
|
||||
CURRENT_GOD_CTRLS=$(find lib/features -type f -name '*_controller.dart' \
|
||||
-path '*/presentation/controller/*' \
|
||||
| while IFS= read -r f; do
|
||||
loc=$(wc -l < "$f" | tr -d ' ')
|
||||
if [ "$loc" -ge 700 ]; then
|
||||
echo "$f=$loc"
|
||||
fi
|
||||
done)
|
||||
|
||||
echo "=== God controllers (>=700 LOC) ==="
|
||||
echo "$CURRENT_GOD_CTRLS"
|
||||
|
||||
# For each current god controller, check against stored baseline (or add it)
|
||||
while IFS='=' read -r path loc; do
|
||||
[ -z "$path" ] && continue
|
||||
baseline=$(grep -E "^${path}=" "$BASELINE_FILE" | cut -d= -f2 || true)
|
||||
if [ -z "$baseline" ]; then
|
||||
echo "NEW GOD CONTROLLER: $path=$loc — adding to baseline"
|
||||
echo "$path=$loc" >> "$BASELINE_FILE"
|
||||
elif [ "$loc" -gt "$baseline" ]; then
|
||||
echo "FAIL: $path grew from $baseline to $loc LOC"
|
||||
FAIL=1
|
||||
fi
|
||||
done <<< "$CURRENT_GOD_CTRLS"
|
||||
|
||||
# Prune baseline entries for controllers that dropped below 700 LOC
|
||||
TMP_BASELINE=$(mktemp)
|
||||
while IFS='=' read -r path loc; do
|
||||
[ -z "$path" ] && continue
|
||||
if [ -f "$path" ]; then
|
||||
current=$(wc -l < "$path" | tr -d ' ')
|
||||
if [ "$current" -ge 700 ]; then
|
||||
echo "$path=$current" >> "$TMP_BASELINE"
|
||||
else
|
||||
echo "GRADUATED: $path dropped to $current LOC — removed from baseline"
|
||||
fi
|
||||
fi
|
||||
done < "$BASELINE_FILE"
|
||||
mv "$TMP_BASELINE" "$BASELINE_FILE"
|
||||
|
||||
# ── Get.find outside bindings (ratcheted) ──
|
||||
VIOLATIONS=$(grep -rn 'Get\.find' lib/features/ --include='*.dart' \
|
||||
| grep -v '_bindings\.dart' \
|
||||
| grep -v 'logout_mixin\.dart' \
|
||||
| grep -v '_test\.dart' \
|
||||
| wc -l | tr -d ' ')
|
||||
VIOLATIONS_MAX=${VIOLATIONS_MAX:-207}
|
||||
echo "Get.find outside bindings: $VIOLATIONS / $VIOLATIONS_MAX"
|
||||
[ "$VIOLATIONS" -le "$VIOLATIONS_MAX" ] || { echo "FAIL: $VIOLATIONS Get.find calls outside bindings"; FAIL=1; }
|
||||
|
||||
# Delegate LOC (each <=200 LOC) — applies once delegates exist
|
||||
while IFS= read -r f; do
|
||||
loc=$(wc -l < "$f" | tr -d ' ')
|
||||
if [ "$loc" -gt 200 ]; then
|
||||
echo "FAIL: delegate $f has $loc LOC (max 200)"
|
||||
FAIL=1
|
||||
fi
|
||||
done < <(find lib -path '*/delegates/*.dart' 2>/dev/null)
|
||||
|
||||
# Bare ever() calls (ratcheted — must reach 0 over time)
|
||||
BARE_EVER=$(grep -rn '^\s*ever(' lib/features/ --include='*.dart' \
|
||||
| grep -v 'workerObxVariables' \
|
||||
| grep -v 'trackWorker' \
|
||||
| grep -v '_test\.dart' \
|
||||
| wc -l | tr -d ' ')
|
||||
BARE_EVER_MAX=${BARE_EVER_MAX:-23}
|
||||
echo "Bare ever() calls: $BARE_EVER / $BARE_EVER_MAX"
|
||||
[ "$BARE_EVER" -le "$BARE_EVER_MAX" ] || { echo "FAIL: $BARE_EVER bare ever() (max $BARE_EVER_MAX)"; FAIL=1; }
|
||||
|
||||
# Stateful extension files (.obs in extensions/ dir)
|
||||
STATEFUL_EXTS=$(grep -rn '\.obs\b' lib/features/*/presentation/extensions/ --include='*.dart' 2>/dev/null | wc -l | tr -d ' ')
|
||||
echo "Stateful .obs vars in extension files: $STATEFUL_EXTS"
|
||||
[ "$STATEFUL_EXTS" -eq 0 ] || { echo "FAIL: $STATEFUL_EXTS .obs vars in extension files"; FAIL=1; }
|
||||
|
||||
# Cross-feature datasource injection in bindings
|
||||
CROSS_DS=0
|
||||
for feature in mailbox email thread composer; do
|
||||
other_features=$(echo "mailbox email thread composer" | tr ' ' '\n' | grep -v "^${feature}$")
|
||||
while IFS= read -r other; do
|
||||
count=$(grep -rn "${other^}DataSource\|${other}DataSource" \
|
||||
lib/features/${feature}/presentation/bindings/ --include='*_bindings.dart' 2>/dev/null | wc -l | tr -d ' ')
|
||||
if [ "$count" -gt 0 ]; then
|
||||
echo "WARN: ${feature} bindings inject ${other} DataSource ($count occurrences)"
|
||||
CROSS_DS=$((CROSS_DS + count))
|
||||
fi
|
||||
done <<< "$other_features"
|
||||
done
|
||||
echo "Cross-feature datasource injections in bindings: $CROSS_DS (target: 0)"
|
||||
[ "$CROSS_DS" -eq 0 ] || { echo "FAIL: $CROSS_DS cross-feature DataSource injections in bindings"; FAIL=1; }
|
||||
|
||||
# XBindings().dependencies() calls outside bindings (ratcheted)
|
||||
BINDING_VIOLATIONS=$(grep -rn '\.dependencies()' lib/features/ --include='*.dart' \
|
||||
| grep -v '_bindings\.dart' \
|
||||
| grep -v 'inject[A-Z]' \
|
||||
| grep -v 'fcm_message_controller\.dart' \
|
||||
| grep -v 'main_entry\.dart' \
|
||||
| wc -l | tr -d ' ')
|
||||
BINDING_VIOLATIONS_MAX=${BINDING_VIOLATIONS_MAX:-36}
|
||||
echo "XBindings().dependencies() violations: $BINDING_VIOLATIONS / $BINDING_VIOLATIONS_MAX"
|
||||
[ "$BINDING_VIOLATIONS" -le "$BINDING_VIOLATIONS_MAX" ] || { echo "FAIL: $BINDING_VIOLATIONS binding calls outside bindings (max $BINDING_VIOLATIONS_MAX)"; FAIL=1; }
|
||||
|
||||
# Binding file LOC (each <=60 LOC — skipped until Phase 2 bindings split)
|
||||
if [ -z "$SKIP_BINDING_CHECK" ]; then
|
||||
while IFS= read -r f; do
|
||||
loc=$(wc -l < "$f" | tr -d ' ')
|
||||
if [ "$loc" -gt 60 ]; then
|
||||
echo "WARN: binding $f has $loc LOC (target <=60)"
|
||||
fi
|
||||
done < <(find lib -name '*_bindings.dart' 2>/dev/null)
|
||||
fi
|
||||
|
||||
# ReloadableController — must have zero Get.find (after Phase 2)
|
||||
RELOAD_VIOLATIONS=$(grep -c 'Get\.find' lib/features/base/reloadable/reloadable_controller.dart 2>/dev/null || echo 0)
|
||||
RELOAD_MAX=${RELOAD_MAX:-0}
|
||||
echo "ReloadableController Get.find: $RELOAD_VIOLATIONS / $RELOAD_MAX"
|
||||
[ "$RELOAD_VIOLATIONS" -le "$RELOAD_MAX" ] || { echo "FAIL: $RELOAD_VIOLATIONS Get.find in ReloadableController"; FAIL=1; }
|
||||
|
||||
# Domain Success/Failure extending AppEvent (must be 0 — use wrapper events instead)
|
||||
DOMAIN_APPEVENT=$(grep -rn 'extends AppEvent' lib/features/ --include='*.dart' 2>/dev/null \
|
||||
| grep -v 'lib/features/base/event_bus/' \
|
||||
| wc -l | tr -d ' ')
|
||||
echo "Domain types extending AppEvent: $DOMAIN_APPEVENT (target: 0)"
|
||||
[ "$DOMAIN_APPEVENT" -eq 0 ] || { echo "FAIL: $DOMAIN_APPEVENT domain types extend AppEvent; use wrapper events"; FAIL=1; }
|
||||
|
||||
echo ""
|
||||
if [ "$FAIL" -eq 0 ]; then
|
||||
echo "PASS: All architecture checks passed."
|
||||
else
|
||||
echo "FAIL: Architecture checks failed."
|
||||
exit 1
|
||||
fi
|
||||
```
|
||||
|
||||
**Commit `scripts/controller_loc_baselines.txt` as part of this phase.** Bootstrap by running the script once — it auto-populates the file with every controller currently ≥700 LOC.
|
||||
|
||||
Add to CI (GitHub Actions):
|
||||
|
||||
```yaml
|
||||
- name: Architecture checks
|
||||
run: |
|
||||
BASE_MAX=647 VIOLATIONS_MAX=207 BINDING_VIOLATIONS_MAX=36 BARE_EVER_MAX=23 RELOAD_MAX=20 \
|
||||
bash scripts/check_architecture.sh
|
||||
```
|
||||
|
||||
**Ratchet schedule** — update CI YAML at the end of each phase:
|
||||
|
||||
| After Phase | `BASE_MAX` | `VIOLATIONS_MAX` | `BINDING_VIOLATIONS_MAX` | `BARE_EVER_MAX` | `RELOAD_MAX` |
|
||||
|---|---|---|---|---|---|
|
||||
| 0 | 647 | 207 | 36 | 23 | 20 |
|
||||
| 2 | **250** | ratchet downward as delegates land | **0** | ratchet downward | **0** |
|
||||
| N (per controller) | 250 | further ratchet | 0 | further ratchet | 0 |
|
||||
|
||||
The controller LOC gate is ratcheted automatically via the baseline file — no YAML change needed.
|
||||
|
||||
#### 2. Custom lint rules via `custom_lint` (parallel with Task 1)
|
||||
|
||||
Create `tools/tmail_lint/` with 4 custom lint rules. IDE warnings — complement the shell script.
|
||||
|
||||
```yaml
|
||||
# tools/tmail_lint/pubspec.yaml
|
||||
name: tmail_lint
|
||||
dependencies:
|
||||
custom_lint_builder: ^0.6.0
|
||||
analyzer: ^6.0.0
|
||||
```
|
||||
|
||||
```yaml
|
||||
# analysis_options.yaml (root) — add:
|
||||
analyzer:
|
||||
plugins:
|
||||
- custom_lint
|
||||
custom_lint:
|
||||
rules:
|
||||
- avoid_bare_ever
|
||||
- no_get_find_outside_bindings
|
||||
- no_binding_call_outside_bindings
|
||||
- no_appevent_domain_inheritance
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- **`avoid_bare_ever`** — ERROR if `ever()` called without `workerObxVariables.add(...)` or `trackWorker(...)`.
|
||||
- **`no_get_find_outside_bindings`** — ERROR if `Get.find<>()` appears in non-binding files. Whitelist: `logout_mixin.dart`, `*_test.dart`, `controller_delegate.dart`, `*_domain_registry.dart`.
|
||||
- **`no_binding_call_outside_bindings`** — WARN if `XBindings().dependencies()` appears outside a `*_bindings.dart` file and not inside a method named `inject*`. Whitelist: `fcm_message_controller.dart`, `main_entry.dart`.
|
||||
- **`no_appevent_domain_inheritance`** — ERROR if a domain Success/Failure class `extends AppEvent`. Use `ActionCompleted<T>` or named wrapper events.
|
||||
|
||||
---
|
||||
|
||||
### Execution Order
|
||||
|
||||
1. `consumeState()` stream fix (Task 0b)
|
||||
2. `workerObxVariables` → `BaseController` (Task 0)
|
||||
3. `ControllerDelegate` abstract base class (Task 0c)
|
||||
4. CI script + controller LOC baseline file + CI YAML (Task 1) **[parallel with Task 2]**
|
||||
5. `custom_lint` package (Task 2) **[parallel with Task 1]**
|
||||
|
||||
---
|
||||
|
||||
### Success Criteria
|
||||
|
||||
- [ ] `workerObxVariables` in `BaseController`; duplicate removed from subclasses
|
||||
- [ ] `consumeState()` uses `_stateSubscriptions`; list cancelled in `onClose()`
|
||||
- [ ] `@Deprecated` annotation on `consumeState()` produces analyzer warning in new call sites
|
||||
- [ ] `ControllerDelegate` base class created at `lib/features/base/delegate/controller_delegate.dart`; zero subclasses yet
|
||||
- [ ] `scripts/check_architecture.sh` created and exits 0 with Phase 0 baselines
|
||||
- [ ] `scripts/controller_loc_baselines.txt` committed, auto-populated from current state
|
||||
- [ ] CI YAML updated with architecture check step (`BASE_MAX=647`, `VIOLATIONS_MAX=207`, `BINDING_VIOLATIONS_MAX=36`, `BARE_EVER_MAX=23`)
|
||||
- [ ] `custom_lint` package (`tools/tmail_lint/`) created with 4 rules; `flutter analyze` reports lint violations
|
||||
- [ ] `dart run build_runner build --delete-conflicting-outputs` + `flutter test` pass
|
||||
@@ -0,0 +1,434 @@
|
||||
## Phase 1: Core Infrastructure
|
||||
|
||||
**Priority:** P1 | **Status:** pending | **Effort:** 3 days
|
||||
**Depends on:** Phase 0
|
||||
**Blocking:** Non-blocking — all changes are new files. Zero conflicts with ongoing feature work.
|
||||
|
||||
> All tasks in this phase create new files only. Feature PRs can land on `master` at any time during this phase. No existing controller is touched. No god controller is named.
|
||||
|
||||
---
|
||||
|
||||
### Tasks
|
||||
|
||||
#### 1. `AppEventBus` + wrapper event contracts (day 1)
|
||||
|
||||
```dart
|
||||
// lib/features/base/event_bus/app_event.dart
|
||||
sealed class AppEvent {}
|
||||
|
||||
// lib/features/base/event_bus/events/action_events.dart
|
||||
/// Wrapper event fired by ActionQueue when a DomainAction succeeds.
|
||||
/// Listeners subscribe via: eventBus.on<ActionCompleted<MarkAsEmailReadSuccess>>()
|
||||
class ActionCompleted<T extends Success> extends AppEvent {
|
||||
final T result;
|
||||
const ActionCompleted(this.result);
|
||||
}
|
||||
|
||||
/// Wrapper event fired by ActionQueue when a DomainAction fails.
|
||||
class ActionFailed<T extends Failure> extends AppEvent {
|
||||
final T failure;
|
||||
const ActionFailed(this.failure);
|
||||
}
|
||||
|
||||
// lib/features/base/event_bus/events/session_events.dart
|
||||
class SessionEstablishedEvent extends AppEvent {
|
||||
final Session session;
|
||||
final AccountId accountId;
|
||||
const SessionEstablishedEvent(this.session, this.accountId);
|
||||
}
|
||||
|
||||
class SessionEndedEvent extends AppEvent {
|
||||
const SessionEndedEvent();
|
||||
}
|
||||
|
||||
// lib/features/base/event_bus/app_event_bus.dart
|
||||
class AppEventBus extends GetxService {
|
||||
final _subject = PublishSubject<AppEvent>();
|
||||
|
||||
/// Typed event subscription — the ONLY supported consumption pattern.
|
||||
/// Never switch(event) on AppEvent — adding a new subclass silently misses
|
||||
/// exhaustive consumers without a compile error.
|
||||
Stream<T> on<T extends AppEvent>() => _subject.stream.whereType<T>();
|
||||
|
||||
void emit(AppEvent event) => _subject.add(event);
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_subject.close();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Register in `lib/main/bindings/main_bindings.dart` as permanent, before any other service that depends on it.
|
||||
|
||||
**CI rule (already added in Phase 0):** `no_appevent_domain_inheritance` — domain `Success`/`Failure` types are forbidden from extending `AppEvent`.
|
||||
|
||||
#### 2. `SessionService` — constructor-injected EventBus, no public setter (day 1)
|
||||
|
||||
```dart
|
||||
// lib/features/base/services/session_service.dart
|
||||
class SessionService extends GetxService {
|
||||
final AppEventBus _eventBus;
|
||||
SessionService(this._eventBus);
|
||||
|
||||
final _session = Rxn<Session>();
|
||||
final _accountId = Rxn<AccountId>();
|
||||
|
||||
/// Read-only access — no public setter. Writes happen only in the
|
||||
/// SessionEstablishedEvent listener below.
|
||||
Rxn<Session> get session => _session;
|
||||
Rxn<AccountId> get accountId => _accountId;
|
||||
|
||||
StreamSubscription? _sessionEstablishedSub;
|
||||
StreamSubscription? _sessionEndedSub;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
_sessionEstablishedSub = _eventBus.on<SessionEstablishedEvent>().listen((event) {
|
||||
_session.value = event.session;
|
||||
_accountId.value = event.accountId;
|
||||
});
|
||||
_sessionEndedSub = _eventBus.on<SessionEndedEvent>().listen((_) => _clear());
|
||||
}
|
||||
|
||||
void _clear() {
|
||||
_session.value = null;
|
||||
_accountId.value = null;
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_sessionEstablishedSub?.cancel();
|
||||
_sessionEndedSub?.cancel();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Register in main bindings, **after** `AppEventBus`:
|
||||
|
||||
```dart
|
||||
Get.put<AppEventBus>(AppEventBus(), permanent: true);
|
||||
Get.put<SessionService>(SessionService(Get.find<AppEventBus>()), permanent: true);
|
||||
```
|
||||
|
||||
**Login integration (contract only — actual wiring lands in the first Layer 2 phase that touches login):**
|
||||
|
||||
```dart
|
||||
// Login success handler — imports AppEventBus only, never SessionService:
|
||||
Get.find<AppEventBus>().emit(SessionEstablishedEvent(session, accountId));
|
||||
```
|
||||
|
||||
Phase 1 delivers the contract. Production wiring into login flow is NOT part of Phase 1 — it happens when the first per-controller Layer 2 phase needs an end-to-end session flow.
|
||||
|
||||
#### 3. State services with single-writer rule (day 2)
|
||||
|
||||
State services own shared Rx references. Each Rx field is documented with its **single writer** — the one delegate (or the service itself) allowed to update it. All other delegates read-only.
|
||||
|
||||
```dart
|
||||
// lib/features/base/services/mailbox_state_service.dart
|
||||
class MailboxStateService extends GetxService {
|
||||
/// Writer: MailboxNavigationDelegate (owned by DashboardDomainRegistry)
|
||||
final _selectedMailbox = Rxn<PresentationMailbox>();
|
||||
Rxn<PresentationMailbox> get selectedMailbox => _selectedMailbox;
|
||||
void updateSelectedMailbox(PresentationMailbox? value) => _selectedMailbox.value = value;
|
||||
|
||||
/// Writer: MailboxNavigationDelegate
|
||||
final _selectedMailboxNode = Rxn<SelectedMailboxNode>();
|
||||
Rxn<SelectedMailboxNode> get selectedMailboxNode => _selectedMailboxNode;
|
||||
void updateSelectedMailboxNode(SelectedMailboxNode? value) => _selectedMailboxNode.value = value;
|
||||
|
||||
/// Writer: MailboxCatalogDelegate
|
||||
final _mapMailboxById = <MailboxId, PresentationMailbox>{}.obs;
|
||||
RxMap<MailboxId, PresentationMailbox> get mapMailboxById => _mapMailboxById;
|
||||
void replaceMailboxMap(Map<MailboxId, PresentationMailbox> value) {
|
||||
_mapMailboxById
|
||||
..clear()
|
||||
..addAll(value);
|
||||
}
|
||||
|
||||
void clear() {
|
||||
_selectedMailbox.value = null;
|
||||
_selectedMailboxNode.value = null;
|
||||
_mapMailboxById.clear();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```dart
|
||||
// lib/features/base/services/email_list_state_service.dart
|
||||
class EmailListStateService extends GetxService {
|
||||
/// Writer: EmailListLoadDelegate
|
||||
final _emailsInCurrentMailbox = <PresentationEmail>[].obs;
|
||||
RxList<PresentationEmail> get emailsInCurrentMailbox => _emailsInCurrentMailbox;
|
||||
void replaceEmails(List<PresentationEmail> value) {
|
||||
_emailsInCurrentMailbox
|
||||
..clear()
|
||||
..addAll(value);
|
||||
}
|
||||
|
||||
/// Writer: SearchDelegate
|
||||
final _listResultSearch = <PresentationEmail>[].obs;
|
||||
RxList<PresentationEmail> get listResultSearch => _listResultSearch;
|
||||
void replaceSearchResults(List<PresentationEmail> value) {
|
||||
_listResultSearch
|
||||
..clear()
|
||||
..addAll(value);
|
||||
}
|
||||
|
||||
/// Writer: SearchDelegate
|
||||
final _isInSearchMode = false.obs;
|
||||
RxBool get isInSearchMode => _isInSearchMode;
|
||||
void updateSearchMode(bool value) => _isInSearchMode.value = value;
|
||||
|
||||
void clear() {
|
||||
_emailsInCurrentMailbox.clear();
|
||||
_listResultSearch.clear();
|
||||
_isInSearchMode.value = false;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** The delegate names in doc comments (`MailboxNavigationDelegate`, `SearchDelegate`, etc.) are **contracts**, not commitments. When a Layer 2 phase extracts each delegate, it updates the writer name to match the actual delegate it creates. Phase 1 writes the rule; Layer 2 phases fill in the names.
|
||||
|
||||
Register both state services in main bindings as permanent.
|
||||
|
||||
#### 4. `DomainAction` + `CancellationToken` + `ActionQueue` (day 2)
|
||||
|
||||
```dart
|
||||
// lib/features/base/action/domain_action.dart
|
||||
/// Base class for all actions submitted to ActionQueue.
|
||||
/// Subclasses encapsulate parameters and stream creation for one operation.
|
||||
abstract class DomainAction<R extends Success> {
|
||||
/// Unique identifier for this logical operation.
|
||||
/// Submitting a new action with an existing tag CANCELS the in-flight one.
|
||||
/// Example: 'MarkAsRead:${emailId.value}'
|
||||
String get tag;
|
||||
|
||||
/// Creates the domain stream. Called by the queue with session/account.
|
||||
Stream<Either<Failure, Success>> execute(Session session, AccountId accountId);
|
||||
}
|
||||
```
|
||||
|
||||
```dart
|
||||
// lib/features/base/action/cancellation_token.dart
|
||||
/// Screen-scoped cancellation. Callbacks skip when cancelled; HTTP still completes.
|
||||
/// Omit token = background execution (survives controller disposal).
|
||||
class CancellationToken {
|
||||
bool _cancelled = false;
|
||||
bool get isCancelled => _cancelled;
|
||||
void cancel() => _cancelled = true;
|
||||
}
|
||||
```
|
||||
|
||||
```dart
|
||||
// lib/features/base/action/action_queue.dart
|
||||
/// Centralised DomainAction execution. Replaces consumeState() for new delegates.
|
||||
///
|
||||
/// Contracts:
|
||||
/// - Tag uniqueness: submit() cancels any in-flight subscription for the same
|
||||
/// tag before installing the new one.
|
||||
/// - No-op on missing session: submit() logs and returns if SessionService
|
||||
/// has no session — it never throws.
|
||||
/// - Wrapper events: success fires ActionCompleted<T>, failure fires
|
||||
/// ActionFailed<T>. Domain types are never cast to AppEvent.
|
||||
/// - cancelAll(): called on session end to purge all in-flight subscriptions.
|
||||
class ActionQueue extends GetxService {
|
||||
final AppEventBus _eventBus;
|
||||
final SessionService _session;
|
||||
final _active = <String, StreamSubscription>{};
|
||||
|
||||
ActionQueue(this._eventBus, this._session);
|
||||
|
||||
void submit(
|
||||
DomainAction action, {
|
||||
CancellationToken? token,
|
||||
ValueChanged<Success>? onSuccess,
|
||||
ValueChanged<Failure>? onFailure,
|
||||
}) {
|
||||
final session = _session.session.value;
|
||||
final accountId = _session.accountId.value;
|
||||
if (session == null || accountId == null) {
|
||||
log('ActionQueue::submit skipped for ${action.tag} — no session');
|
||||
return;
|
||||
}
|
||||
|
||||
// Cancel-before-replace: ensures tag collisions do not leak subs.
|
||||
_active.remove(action.tag)?.cancel();
|
||||
|
||||
log('ActionQueue::submit ${action.tag}');
|
||||
|
||||
late StreamSubscription sub;
|
||||
sub = action.execute(session, accountId).listen(
|
||||
(result) => result.fold(
|
||||
(failure) {
|
||||
_eventBus.emit(ActionFailed(failure));
|
||||
if (token?.isCancelled != true) onFailure?.call(failure);
|
||||
},
|
||||
(success) {
|
||||
_eventBus.emit(ActionCompleted(success));
|
||||
if (token?.isCancelled != true) onSuccess?.call(success);
|
||||
},
|
||||
),
|
||||
onDone: () {
|
||||
// Only remove if this sub is still the active one for this tag.
|
||||
// (A later submit() may have replaced it.)
|
||||
if (identical(_active[action.tag], sub)) {
|
||||
_active.remove(action.tag);
|
||||
}
|
||||
},
|
||||
);
|
||||
_active[action.tag] = sub;
|
||||
}
|
||||
|
||||
/// Cancel all in-flight actions. Called on session end.
|
||||
void cancelAll() {
|
||||
for (final s in _active.values) {
|
||||
s.cancel();
|
||||
}
|
||||
_active.clear();
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
cancelAll();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Register in main bindings after `SessionService`:
|
||||
|
||||
```dart
|
||||
Get.put<ActionQueue>(
|
||||
ActionQueue(Get.find<AppEventBus>(), Get.find<SessionService>()),
|
||||
permanent: true,
|
||||
);
|
||||
```
|
||||
|
||||
#### 5. `DomainRegistry` contract + lifecycle propagation (day 3)
|
||||
|
||||
A `DomainRegistry` is a `GetxService` that owns a group of `ControllerDelegate` instances for one domain (e.g. one screen). The registry is the **only** Layer that calls `Get.find<>()` for infrastructure dependencies — delegates receive pre-resolved references via constructor. The registry drives delegate lifecycle by calling `init()` and `dispose()` from its own `onInit()`/`onClose()`.
|
||||
|
||||
```dart
|
||||
// lib/features/base/delegate/domain_registry.dart
|
||||
/// Base class for all domain registries.
|
||||
///
|
||||
/// A registry is a GetxService that owns a collection of ControllerDelegate
|
||||
/// instances for one screen or domain. It:
|
||||
/// 1. Resolves all infrastructure dependencies via Get.find<>() (the ONLY
|
||||
/// layer allowed to do so outside *_bindings.dart files).
|
||||
/// 2. Exposes each delegate as a late final field.
|
||||
/// 3. Calls init() on every delegate in its onInit().
|
||||
/// 4. Calls dispose() on every delegate in its onClose().
|
||||
///
|
||||
/// Subclasses override [delegates] to return all owned delegates in creation
|
||||
/// order. Views access delegates via Get.find<XDomainRegistry>().yDelegate.
|
||||
abstract class DomainRegistry extends GetxService {
|
||||
/// Every delegate owned by this registry, in the order they should be
|
||||
/// initialised. Must include every `late final` delegate field.
|
||||
List<ControllerDelegate> get delegates;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
for (final d in delegates) {
|
||||
d.init();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
// Dispose in reverse order so later delegates drop their subscriptions
|
||||
// before earlier ones (which may own state those subscriptions read).
|
||||
for (final d in delegates.reversed) {
|
||||
d.dispose();
|
||||
}
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Reference implementation (example only — not shipped in Phase 1):**
|
||||
|
||||
```dart
|
||||
class ExampleDomainRegistry extends DomainRegistry {
|
||||
final ActionQueue _queue;
|
||||
final SessionService _session;
|
||||
final AppEventBus _eventBus;
|
||||
|
||||
ExampleDomainRegistry(this._queue, this._session, this._eventBus);
|
||||
|
||||
late final featureA = FeatureADelegate(_eventBus);
|
||||
late final featureB = FeatureBDelegate(_queue, _session);
|
||||
|
||||
@override
|
||||
List<ControllerDelegate> get delegates => [featureA, featureB];
|
||||
}
|
||||
```
|
||||
|
||||
Phase 1 ships `DomainRegistry` as an abstract class only. The first concrete subclass lands in Phase 2 alongside the `NotificationDelegate` pilot.
|
||||
|
||||
#### 6. Generic characterization test template (day 3)
|
||||
|
||||
Write a test template — not per-controller tests. Layer 2 phase files copy this template when they need characterization coverage before touching a god controller.
|
||||
|
||||
```dart
|
||||
// test/features/base/characterization_template.dart
|
||||
//
|
||||
// TEMPLATE: Copy into your Layer 2 phase's test folder, rename, and fill in.
|
||||
//
|
||||
// Characterization tests lock CURRENT behavior of a god controller before any
|
||||
// extraction. They are deliberately NOT unit tests — they mirror the messy
|
||||
// reality of the controller as it exists today, so that any delegate extraction
|
||||
// that changes behavior is caught.
|
||||
//
|
||||
// After extraction:
|
||||
// - Rename the file to match the delegate (e.g., email_action_delegate_test.dart)
|
||||
// - Point mocks at the narrow ISP interface, not the fat repository
|
||||
// - Point bus assertions at ActionCompleted<XSuccess> wrapper events
|
||||
|
||||
void main() {
|
||||
group('<Feature> characterization — locks current god-controller behavior', () {
|
||||
// TODO(layer2): instantiate the god controller with minimum viable mocks
|
||||
// TODO(layer2): list every method / Rx var this phase plans to extract
|
||||
// TODO(layer2): one test per extraction target — input, expected output
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Characterization test **authoring** happens inside each Layer 2 phase. Phase 1 ships only the template.
|
||||
|
||||
---
|
||||
|
||||
### Execution Order
|
||||
|
||||
Run `dart run build_runner build --delete-conflicting-outputs` + `flutter test` after each step:
|
||||
|
||||
1. `AppEventBus` + wrapper event files (Task 1)
|
||||
2. `SessionService` with constructor-injected bus (Task 2)
|
||||
3. `MailboxStateService` + `EmailListStateService` with single-writer rule (Task 3)
|
||||
4. `ActionQueue` + `DomainAction` + `CancellationToken` (Task 4)
|
||||
5. `DomainRegistry` abstract base (Task 5)
|
||||
6. Characterization test template (Task 6)
|
||||
|
||||
All Phase 1 files are new. Zero existing controllers are modified.
|
||||
|
||||
---
|
||||
|
||||
### Success Criteria
|
||||
|
||||
- [ ] `AppEventBus` registered as permanent; basic emit/on unit test passes
|
||||
- [ ] `ActionCompleted<T>` + `ActionFailed<T>` wrapper events defined; no domain type extends `AppEvent`
|
||||
- [ ] `SessionService` constructor takes `AppEventBus`; no `Get.find` in `onInit`
|
||||
- [ ] `SessionService` has no public setter; unit test verifies state updates only via `SessionEstablishedEvent`
|
||||
- [ ] `MailboxStateService` + `EmailListStateService` registered; each Rx field has a documented single-writer delegate name
|
||||
- [ ] `ActionQueue` registered with cancel-before-replace + `cancelAll()`; tag collision test passes
|
||||
- [ ] `ActionQueue.submit()` logs + returns when session is null; unit test passes
|
||||
- [ ] `ActionQueue` fires `ActionCompleted<MockSuccess>` wrapper event in test
|
||||
- [ ] `DomainRegistry` abstract class created; unit test verifies `init()` / `dispose()` propagation across mock delegates
|
||||
- [ ] Characterization test template committed in `test/features/base/`
|
||||
- [ ] `dart run build_runner build --delete-conflicting-outputs` + `flutter test` pass
|
||||
- [ ] `bash scripts/check_architecture.sh` exits 0 with Phase 0 thresholds (no regression)
|
||||
@@ -0,0 +1,277 @@
|
||||
## Phase 2: BaseController, DI Refactor, and Pilot Delegate
|
||||
|
||||
**Priority:** P1 | **Status:** pending | **Effort:** 4 days
|
||||
**Depends on:** Phase 0 + Phase 1
|
||||
**Blocks:** All Layer 2 per-controller phases
|
||||
|
||||
> **Coordination window.** This phase modifies `BaseController`, `ReloadableController`, several bindings files, and the notification feature. Notify the team before starting. Feature branches touching these files should rebase after this phase lands.
|
||||
>
|
||||
> Duration is short (4 days) by design. After this phase, Layer 2 per-controller phases run in git worktrees and `master` is always open for feature work.
|
||||
>
|
||||
> **This phase ships one production delegate — `NotificationDelegate`.** It is chosen because it has zero coupling to the largest god controllers, so it proves the full extraction loop (delegate → registry → view → test → CI) on a low-risk target.
|
||||
|
||||
---
|
||||
|
||||
### Tasks
|
||||
|
||||
#### 1. `ReloadableController` — constructor injection
|
||||
|
||||
Remove field-level `Get.find` calls. Pass interactors via constructor.
|
||||
|
||||
```dart
|
||||
// lib/features/base/reloadable/reloadable_controller.dart
|
||||
abstract class ReloadableController extends BaseController {
|
||||
final GetSessionInteractor _getSessionInteractor;
|
||||
final GetAuthenticatedAccountInteractor _getAuthenticatedAccountInteractor;
|
||||
final UpdateAccountCacheInteractor _updateAccountCacheInteractor;
|
||||
final GetOidcUserInfoInteractor _getOidcUserInfoInteractor;
|
||||
|
||||
ReloadableController(
|
||||
this._getSessionInteractor,
|
||||
this._getAuthenticatedAccountInteractor,
|
||||
this._updateAccountCacheInteractor,
|
||||
this._getOidcUserInfoInteractor,
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Update all subclasses to pass through constructor args. Run `dart run build_runner build --delete-conflicting-outputs`.
|
||||
|
||||
#### 2. `BaseController` strip — 4 focused services
|
||||
|
||||
Extract the 14 field-level `Get.find` calls currently living on `BaseController` into **four focused services**. After this task, `BaseController` is ≤250 LOC and contains only lifecycle concerns (`workerObxVariables`, `_stateSubscriptions`, `onClose`).
|
||||
|
||||
```dart
|
||||
// lib/features/base/services/auth_service.dart
|
||||
class AuthService extends GetxService {
|
||||
final AuthorizationInterceptors authInterceptors;
|
||||
final AuthorizationInterceptors authIsolateInterceptors;
|
||||
final DynamicUrlInterceptors dynamicUrlInterceptors;
|
||||
final DeleteCredentialInteractor deleteCredential;
|
||||
final LogoutOidcInteractor logoutOidc;
|
||||
final DeleteAuthorityOidcInteractor deleteAuthorityOidc;
|
||||
|
||||
AuthService(
|
||||
this.authInterceptors, this.authIsolateInterceptors,
|
||||
this.dynamicUrlInterceptors, this.deleteCredential,
|
||||
this.logoutOidc, this.deleteAuthorityOidc,
|
||||
);
|
||||
}
|
||||
|
||||
// lib/features/base/services/cache_service.dart
|
||||
class CacheService extends GetxService {
|
||||
final CachingManager cachingManager;
|
||||
final LanguageCacheManager languageCacheManager;
|
||||
CacheService(this.cachingManager, this.languageCacheManager);
|
||||
}
|
||||
|
||||
// lib/features/base/services/ui_service.dart
|
||||
class UIService extends GetxService {
|
||||
final AppToast appToast;
|
||||
final Uuid uuid;
|
||||
final ToastManager toastManager;
|
||||
final TwakeAppManager twakeAppManager;
|
||||
UIService(this.appToast, this.uuid, this.toastManager, this.twakeAppManager);
|
||||
}
|
||||
|
||||
// lib/features/base/services/view_context_service.dart
|
||||
/// Pure view-layer helpers that controllers and views both read.
|
||||
/// Previously held as BaseController fields; moved here to keep the base lean.
|
||||
class ViewContextService extends GetxService {
|
||||
final ImagePaths imagePaths;
|
||||
final ResponsiveUtils responsiveUtils;
|
||||
ViewContextService(this.imagePaths, this.responsiveUtils);
|
||||
}
|
||||
```
|
||||
|
||||
Register all four as permanent in `main_bindings.dart`. Remove the 14 field declarations from `BaseController`.
|
||||
|
||||
Update `LogoutMixin` to use `Get.find<AuthService>()` instead of BaseController fields.
|
||||
|
||||
For legacy controllers accessing `appToast`/`uuid`/`toastManager`/`imagePaths`/`responsiveUtils` via inheritance: use `Get.find<UIService>().appToast` or `Get.find<ViewContextService>().imagePaths` inline. Do NOT mass-migrate — only fix compilation errors. A lingering tech-debt TODO is fine and is tracked by the CI `VIOLATIONS_MAX` ratchet.
|
||||
|
||||
**Target:** `BaseController` ≤250 LOC after extraction.
|
||||
|
||||
#### 3. Bindings split
|
||||
|
||||
Break large dashboard/composer bindings files into domain-scoped files. This is a **transitional** structure — the per-controller Layer 2 phase for each screen replaces individual delegate registration with a `DomainRegistry` entry.
|
||||
|
||||
Example layout for a dashboard-style bindings folder:
|
||||
|
||||
```
|
||||
lib/features/<screen>/presentation/bindings/
|
||||
├── <screen>_bindings.dart # orchestrator (~30 LOC)
|
||||
├── <screen>_email_interactor_bindings.dart
|
||||
├── <screen>_mailbox_interactor_bindings.dart
|
||||
├── <screen>_search_interactor_bindings.dart
|
||||
└── <screen>_composer_interactor_bindings.dart
|
||||
```
|
||||
|
||||
Each file ≤60 LOC. The orchestrator calls `.dependencies()` on each sub-binding. **Do not** pre-register domain registries here — they appear when the Layer 2 phase for that screen extracts its first delegate.
|
||||
|
||||
#### 4. Standardise DI patterns
|
||||
|
||||
Replace field-level `Get.find` calls in sub-controllers with constructor injection via bindings. Target any controller that currently pulls its collaborators via `Get.find` at field-init time. After this task, `BaseController` subclasses never do `Get.find` in a field initializer.
|
||||
|
||||
Do NOT attempt to migrate every legacy controller — scope this task to subclasses of `BaseController` and `ReloadableController`. Track progress against the CI `VIOLATIONS_MAX` threshold.
|
||||
|
||||
#### 5. Panel-scoped binding migration (DIP cleanup)
|
||||
|
||||
**Category A — panel widget-swap controllers:**
|
||||
|
||||
| Violation | Fix |
|
||||
|---|---|
|
||||
| Controller calls `XBindings().dependencies()` mid-method (panel binding triggered from user navigation) | Move registration to the parent binding using `Get.lazyPut(fenix: true)`; panel creation happens on first `Get.find<>()` |
|
||||
| Controller calls `XBindings().disposeBindings()` on exit | Replace with `Get.delete<XController>(force: true)` directly |
|
||||
|
||||
In each `XBindings.bindingsController()`: change `Get.put(XController(...))` → `Get.lazyPut(() => XController(...), fenix: true)`. `fenix: true` lets a deleted controller be recreated on the next widget build without a binding call from the controller body.
|
||||
|
||||
**Category B — account/settings panel bindings:**
|
||||
|
||||
Move any sub-panel bindings called inside a panel-switching method to the parent route's binding. Delete the `_bindingControllerMenuItemView`-style methods once all sub-bindings are registered at route startup.
|
||||
|
||||
**Accepted exceptions (do NOT migrate):**
|
||||
|
||||
- `inject*()` methods in `BaseController` / `ReloadableController` — capability-gated interactor bindings (JMAP capabilities are only known after session establishment).
|
||||
- `fcm_message_controller.dart` — background FCM isolate bootstrap needs a full re-DI.
|
||||
- `main_entry.dart` — app startup.
|
||||
|
||||
After this task: ratchet CI `BINDING_VIOLATIONS_MAX` to 0.
|
||||
|
||||
#### 6. Pilot delegate — `NotificationDelegate` shipped to production
|
||||
|
||||
Pick `NotificationDelegate` as the pilot because notification settings are self-contained: no Rxn dispatch stream coupling, no cross-controller reads, no shared state with the large god controllers. If the pilot loop works for Notification, it will work for any target.
|
||||
|
||||
**Scope:** Extract the notification settings feature into a `ControllerDelegate` subclass and a `NotificationDomainRegistry`. Ship it. No feature flag — the old code path is deleted in the same commit.
|
||||
|
||||
```dart
|
||||
// lib/features/notification/presentation/delegates/notification_delegate.dart
|
||||
class NotificationDelegate extends ControllerDelegate {
|
||||
final ActionQueue _queue;
|
||||
final AppEventBus _eventBus;
|
||||
final INotificationSettingsRepository _repo;
|
||||
|
||||
NotificationDelegate(this._queue, this._eventBus, this._repo);
|
||||
|
||||
final isEnabled = RxBool(false);
|
||||
final isLoading = RxBool(false);
|
||||
|
||||
@override
|
||||
void init() {
|
||||
super.init();
|
||||
_loadSettings();
|
||||
trackSub(
|
||||
_eventBus
|
||||
.on<ActionCompleted<UpdateNotificationSettingsSuccess>>()
|
||||
.listen(_onSettingsUpdated),
|
||||
);
|
||||
}
|
||||
|
||||
void toggleNotifications(bool value) {
|
||||
isLoading.value = true;
|
||||
_queue.submit(
|
||||
UpdateNotificationSettingsAction(value, _repo),
|
||||
onSuccess: (_) => isEnabled.value = value,
|
||||
onFailure: (_) => isLoading.value = false,
|
||||
);
|
||||
}
|
||||
|
||||
void _loadSettings() { /* ... */ }
|
||||
void _onSettingsUpdated(ActionCompleted<UpdateNotificationSettingsSuccess> e) {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```dart
|
||||
// lib/features/notification/presentation/registries/notification_domain_registry.dart
|
||||
class NotificationDomainRegistry extends DomainRegistry {
|
||||
final ActionQueue _queue;
|
||||
final AppEventBus _eventBus;
|
||||
final INotificationSettingsRepository _repo;
|
||||
|
||||
NotificationDomainRegistry(this._queue, this._eventBus, this._repo);
|
||||
|
||||
late final settings = NotificationDelegate(_queue, _eventBus, _repo);
|
||||
|
||||
@override
|
||||
List<ControllerDelegate> get delegates => [settings];
|
||||
}
|
||||
```
|
||||
|
||||
**Binding wiring:**
|
||||
|
||||
```dart
|
||||
// lib/features/notification/presentation/bindings/notification_bindings.dart
|
||||
class NotificationBindings extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<INotificationSettingsRepository>(() => NotificationSettingsRepositoryImpl(...));
|
||||
Get.lazyPut<NotificationDomainRegistry>(() => NotificationDomainRegistry(
|
||||
Get.find<ActionQueue>(),
|
||||
Get.find<AppEventBus>(),
|
||||
Get.find<INotificationSettingsRepository>(),
|
||||
), fenix: true);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**View wiring:**
|
||||
|
||||
```dart
|
||||
// Views read via the registry — never Get.find<NotificationDelegate>()
|
||||
Obx(() {
|
||||
final d = Get.find<NotificationDomainRegistry>().settings;
|
||||
return Switch(
|
||||
value: d.isEnabled.value,
|
||||
onChanged: d.isLoading.value ? null : d.toggleNotifications,
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
**Deliverables for the pilot:**
|
||||
|
||||
- `NotificationDelegate` (≤200 LOC) subclassing `ControllerDelegate`
|
||||
- `NotificationDomainRegistry` subclassing `DomainRegistry`
|
||||
- `INotificationSettingsRepository` ISP interface
|
||||
- Existing fat repository implements the new interface (no data layer changes)
|
||||
- Views rewritten to read via the registry
|
||||
- Unit test suite for the delegate, mocking the ISP interface and `ActionQueue`
|
||||
- `DomainRegistry.init()` / `dispose()` lifecycle verified in test (worker count before/after)
|
||||
- Old notification controller + its bindings deleted
|
||||
- Smoke test on web + mobile: toggle notifications → settings persist → reload → state restored
|
||||
- CI script green
|
||||
|
||||
If the pilot fails end-to-end smoke, STOP. Do not start Layer 2 phases. Debug and re-pilot until it ships.
|
||||
|
||||
---
|
||||
|
||||
### Execution Order
|
||||
|
||||
Run `dart run build_runner build --delete-conflicting-outputs` + `flutter test` after each step:
|
||||
|
||||
1. `ReloadableController` ctor injection (Task 1)
|
||||
2. `AuthService` / `CacheService` / `UIService` / `ViewContextService` extraction (Task 2)
|
||||
3. Bindings split (Task 3)
|
||||
4. Standardise DI patterns (Task 4)
|
||||
5. Panel-scoped binding migration (Task 5)
|
||||
6. `NotificationDelegate` pilot (Task 6) — ships to production
|
||||
|
||||
Update CI YAML at end of phase: `BASE_MAX=250`, `BINDING_VIOLATIONS_MAX=0`, `RELOAD_MAX=0`, remove `SKIP_BINDING_CHECK`.
|
||||
|
||||
---
|
||||
|
||||
### Success Criteria
|
||||
|
||||
- [ ] `ReloadableController` has 0 field-level `Get.find` calls; all subclasses updated; mocks regenerated
|
||||
- [ ] `BaseController` ≤250 LOC; `AuthService`, `CacheService`, `UIService`, `ViewContextService` registered as permanent GetxServices
|
||||
- [ ] `LogoutMixin` uses `AuthService` (not `BaseController` fields)
|
||||
- [ ] Panel-scoped binding migration complete; `BINDING_VIOLATIONS_MAX=0`
|
||||
- [ ] Bindings split into ≤60 LOC files; `SKIP_BINDING_CHECK` removed from CI
|
||||
- [ ] `NotificationDelegate` shipped to production, extends `ControllerDelegate`
|
||||
- [ ] `NotificationDomainRegistry` extends `DomainRegistry`; `init()`/`dispose()` propagation verified by test
|
||||
- [ ] `INotificationSettingsRepository` ISP interface created; fat repository silently implements it
|
||||
- [ ] Old notification controller and its bindings deleted
|
||||
- [ ] Smoke test: notification toggle works on web + mobile; state persists
|
||||
- [ ] `bash scripts/check_architecture.sh` exits 0 with Phase 2 thresholds (`BASE_MAX=250`, `BINDING_VIOLATIONS_MAX=0`, `RELOAD_MAX=0`)
|
||||
- [ ] `flutter analyze` + `flutter test` pass
|
||||
@@ -0,0 +1,235 @@
|
||||
## Phase N: Generic Per-Controller Extraction Protocol (Template)
|
||||
|
||||
**Priority:** P2 | **Status:** template (not actionable) | **Effort:** per controller
|
||||
**Depends on:** Phase 2 complete, pilot delegate shipped
|
||||
**Blocking:** Non-blocking — runs in a git worktree. `master` is always open for feature work.
|
||||
|
||||
> **This file is a template.** When a god controller is chosen for decomposition, copy this file to `phase-NN-<controller-name>-decomposition.md`, replace placeholders, and start work. Do NOT edit this template in place for a specific controller.
|
||||
>
|
||||
> **Ordering rule:** Tackle god controllers smallest LOC first. Earlier controllers validate the pattern and tooling on lower-risk targets before touching the largest.
|
||||
|
||||
---
|
||||
|
||||
### Copy checklist (before starting a per-controller phase)
|
||||
|
||||
- [ ] Copy this file to `phase-NN-<controller>-decomposition.md`
|
||||
- [ ] Update the header (priority, effort estimate, branch name)
|
||||
- [ ] Fill in the **controller baseline** section (LOC, deps, extensions, mixins)
|
||||
- [ ] Fill in the **domain boundary table** with every Rx var and extension
|
||||
- [ ] Fill in the **Rxn dispatch inventory** if this controller has `Rxn<UIAction>` streams
|
||||
- [ ] Name each delegate you plan to extract and list its coupling level
|
||||
- [ ] Pre-create a git worktree: `git worktree add ../tmail-<controller>-refactor refactor/solid-<controller>`
|
||||
- [ ] Announce the phase on the team channel (file ownership + estimated duration)
|
||||
|
||||
---
|
||||
|
||||
### Controller baseline (fill in per controller)
|
||||
|
||||
| Metric | Current | Target |
|
||||
|--------|---------|--------|
|
||||
| Controller LOC | TBD | ≤700 |
|
||||
| Constructor deps | TBD | ≤10 |
|
||||
| Field-level `Get.find` | TBD | 0 |
|
||||
| Extension files | TBD | ≤ (controller/3) |
|
||||
| Mixins (stateful) | TBD | 0 |
|
||||
| Rxn dispatch streams | TBD | 0 |
|
||||
| Test files mocking the controller | TBD | 0 (migrated per delegate) |
|
||||
|
||||
---
|
||||
|
||||
### Day 0: Discovery (before any extraction)
|
||||
|
||||
#### 0a. Domain boundary table
|
||||
|
||||
Inventory every extension file, mixin, and Rx var. For each, record the primary domain, which Rx vars it reads/writes, cross-domain dependencies, and the delegate that will own it.
|
||||
|
||||
| Extension / Mixin / Rx group | Primary domain | Rx vars read | Rx vars written | Cross-domain deps | Target delegate |
|
||||
|---|---|---|---|---|---|
|
||||
| *fill in* | | | | | |
|
||||
|
||||
#### 0b. Rxn dispatch inventory (if applicable)
|
||||
|
||||
For every `Rxn<UIAction>` stream on the controller, list the action subtypes, their consumers, and the typed wrapper event that will replace each.
|
||||
|
||||
| Rxn stream | Action type | Consumer | Replacement event |
|
||||
|---|---|---|---|
|
||||
| *fill in* | | | |
|
||||
|
||||
#### 0c. Satellite controller audit
|
||||
|
||||
Identify any controller under `lib/features/` that calls `Get.find<ThisGodController>()`. For each caller, decide:
|
||||
|
||||
- **Re-use as-is:** the caller is already focused on one domain; swap its `Get.find` for `Get.find<XDomainRegistry>().y` or a state service read.
|
||||
- **Extract residual:** the caller leaks state back into the god controller; extract that state into the caller first.
|
||||
|
||||
Record the decision here. Satellite migration happens incrementally as delegates become available.
|
||||
|
||||
#### 0d. Characterization tests
|
||||
|
||||
Copy the Phase 1 template to `test/features/<feature>/characterization/<controller>_characterization_test.dart`. Write one test per method you plan to extract. Run green against the current god controller before touching anything. These are the regression net.
|
||||
|
||||
---
|
||||
|
||||
### Day N: Delegate extraction loop (repeat per delegate, lowest coupling first)
|
||||
|
||||
For each delegate identified in the domain boundary table:
|
||||
|
||||
1. **Create the narrow ISP interface.** `lib/features/<feature>/domain/repositories/i_<name>_repository.dart`. Existing fat repository silently implements it — no data-layer changes.
|
||||
|
||||
2. **Create the delegate file.** Subclass `ControllerDelegate`. Constructor takes `ActionQueue`, state services it needs, `AppEventBus` (if it listens), and the ISP repository. Zero `Get.find` in the body. Use `trackWorker` and `trackSub` for all workers and subscriptions.
|
||||
|
||||
3. **Add a forwarding stub in the god controller.** Methods on the controller delegate to the new delegate via `Get.find<XDomainRegistry>().y`. Keeps the codebase green while callers migrate.
|
||||
|
||||
4. **Migrate Rxn action types owned by this delegate to typed wrapper events.**
|
||||
- Create a typed event class (or reuse `ActionCompleted<XSuccess>`)
|
||||
- Replace `dispatchXxxAction(ActionType())` calls with `eventBus.emit(...)`
|
||||
- In consuming controllers, replace `_registerObxStreamListener` cases with `eventBus.on<T>().listen(...)` tracked in `workerObxVariables` or `trackSub`
|
||||
- When all types for a Rxn stream are migrated, delete the Rxn field and the `_registerObxStreamListener` method
|
||||
|
||||
5. **Create or extend the domain registry.** If this is the first delegate for the controller, create `lib/features/<feature>/presentation/registries/<feature>_domain_registry.dart` subclassing `DomainRegistry`. Add the delegate as a `late final` field and include it in `delegates`. Register the registry in the feature binding.
|
||||
|
||||
6. **Update views.** Views read state and trigger actions via `Get.find<XDomainRegistry>().y`. No views reference `Get.find<XDelegate>()` directly.
|
||||
|
||||
7. **Move state into state services where applicable.** If the delegate owns shared state (e.g. selected mailbox), update the state service's single-writer doc to name this delegate.
|
||||
|
||||
8. **Migrate tests inline.** For every test that previously mocked the god controller:
|
||||
- Rename to match the delegate
|
||||
- Mock the ISP interface and `ActionQueue` instead of the fat repository and controller
|
||||
- Assert on `ActionCompleted<XSuccess>` wrapper events (or named events) instead of on Rxn dispatch
|
||||
|
||||
9. **Run the build gate.**
|
||||
```bash
|
||||
dart run build_runner build --delete-conflicting-outputs
|
||||
flutter analyze
|
||||
flutter test
|
||||
bash scripts/check_architecture.sh
|
||||
```
|
||||
All four must exit 0.
|
||||
|
||||
10. **Delete the forwarding stub + absorbed extension files** from the god controller.
|
||||
|
||||
11. **Commit — one delegate per commit.** Message format: `refactor(<feature>): extract <Name>Delegate`.
|
||||
|
||||
12. **Ratchet CI thresholds** for this controller's baseline entry in `scripts/controller_loc_baselines.txt`. The auto-discovery gate picks this up automatically.
|
||||
|
||||
---
|
||||
|
||||
### Cross-feature decoupling (runs incrementally alongside delegate extraction)
|
||||
|
||||
As delegates become available:
|
||||
|
||||
- Replace `Get.find<ThisGodController>()` calls in satellite controllers with:
|
||||
- `Get.find<SessionService>()` for session/account
|
||||
- `Get.find<MailboxStateService>()` or `Get.find<EmailListStateService>()` for shared Rx state
|
||||
- `Get.find<XDomainRegistry>().y` for domain actions
|
||||
|
||||
- Convert every bare `ever()` in satellite controllers to `workerObxVariables.add(ever(...))`.
|
||||
|
||||
- When the controller's Rxn dispatch streams are fully migrated, delete the fields and the `_registerObxStreamListener` methods. Confirm `scripts/check_architecture.sh` passes.
|
||||
|
||||
---
|
||||
|
||||
### Session lifecycle integration (runs once per session-scoped registry)
|
||||
|
||||
If this controller's domain registry is session-scoped (not route-scoped), wire it into the session lifecycle protocol:
|
||||
|
||||
```dart
|
||||
// Implementation lives in the login / logout flow, not in a delegate:
|
||||
void onSessionReady(Session session, AccountId accountId) {
|
||||
Get.find<AppEventBus>().emit(SessionEstablishedEvent(session, accountId));
|
||||
// SessionService reacts via its own listener — no direct assignment.
|
||||
|
||||
// Session-scoped registries:
|
||||
Get.put(XDomainRegistry(
|
||||
Get.find<ActionQueue>(),
|
||||
Get.find<AppEventBus>(),
|
||||
// ...
|
||||
));
|
||||
}
|
||||
|
||||
void onSessionEnd() {
|
||||
Get.find<AppEventBus>().emit(const SessionEndedEvent());
|
||||
// SessionService + state services react to SessionEndedEvent and clear.
|
||||
|
||||
Get.find<ActionQueue>().cancelAll();
|
||||
|
||||
Get.delete<XDomainRegistry>(); // triggers dispose() on every delegate
|
||||
}
|
||||
```
|
||||
|
||||
Lifecycle tier table (reference):
|
||||
|
||||
| Tier | Components | Created | Destroyed |
|
||||
|---|---|---|---|
|
||||
| **Boot** (permanent) | AppEventBus, ActionQueue, SessionService, state services, ViewContextService, AuthService, CacheService, UIService | `main_bindings.dart` | Never (cleared on logout via `SessionEndedEvent`) |
|
||||
| **Session** | Session-scoped domain registries | `onSessionReady()` | `onSessionEnd()` |
|
||||
| **Route** | Route-scoped domain registries, screen controllers | Route binding | Route pop |
|
||||
| **Widget** | Micro-controllers (e.g. `RichTextWebController`) | Widget build | Widget dispose |
|
||||
|
||||
---
|
||||
|
||||
### Operation lifetime reclassification (case-by-case)
|
||||
|
||||
If this controller owns work that outlives its scope, reclassify:
|
||||
|
||||
| Duration | Owner | Example |
|
||||
|---|---|---|
|
||||
| Instant (<1s) | Delegate | Toggle star, mark read |
|
||||
| Short (1–5s) | Delegate + toast on fail | Move to folder |
|
||||
| Long (>5s, user may navigate) | Session-lifetime service | Download, send email, empty trash |
|
||||
| Background (survives app) | Platform service (WorkManager/FCM) | FCM sync, sending queue |
|
||||
|
||||
Reclassify long-running controllers (e.g. `DownloadController`, `SendingQueueController`) as session-lifetime `GetxService` instances. Move their `Get.put` from route binding to `onSessionReady`. Views observe via `Get.find<XService>().state` — independent of any screen controller.
|
||||
|
||||
---
|
||||
|
||||
### Verification gate (per delegate)
|
||||
|
||||
After every delegate extraction:
|
||||
|
||||
```bash
|
||||
dart run build_runner build --delete-conflicting-outputs
|
||||
flutter analyze
|
||||
flutter test
|
||||
bash scripts/check_architecture.sh
|
||||
```
|
||||
|
||||
If any of the four fails, revert the extraction and debug. Never comment out a test to get green.
|
||||
|
||||
---
|
||||
|
||||
### Per-controller success criteria (fill in baseline numbers)
|
||||
|
||||
- [ ] Day 0 domain boundary table complete (every extension + Rx var mapped)
|
||||
- [ ] Day 0 Rxn dispatch inventory complete (if controller has Rxn streams)
|
||||
- [ ] Day 0 satellite audit complete (each caller has a re-use or extract decision)
|
||||
- [ ] Day 0 characterization tests pass against current god controller
|
||||
- [ ] Controller LOC ≤ 700 (ratchet target)
|
||||
- [ ] Delegates created: (N) — each ≤200 LOC
|
||||
- [ ] Domain registry created; `init()`/`dispose()` lifecycle tested
|
||||
- [ ] All delegates use `ControllerDelegate` base class (not `BaseController`)
|
||||
- [ ] All delegates use `ActionQueue.submit()` — zero new `consumeState()` calls
|
||||
- [ ] All Rxn dispatch streams owned by this controller deleted (if any existed)
|
||||
- [ ] Satellite `Get.find<ThisGodController>()` references = 0
|
||||
- [ ] Bare `ever()` in new code = 0
|
||||
- [ ] ISP repository interfaces created: one per delegate
|
||||
- [ ] Inline test migration complete; no test mocks the god controller
|
||||
- [ ] `scripts/controller_loc_baselines.txt` updated or entry removed (if LOC dropped below 700)
|
||||
- [ ] `bash scripts/check_architecture.sh` exits 0
|
||||
- [ ] `flutter analyze` + `flutter test` pass
|
||||
- [ ] Smoke test on web + mobile passes
|
||||
- [ ] One commit per delegate (clean history)
|
||||
|
||||
---
|
||||
|
||||
### When all god controllers are decomposed
|
||||
|
||||
Run a final sweep phase (documented JIT when the time comes):
|
||||
|
||||
- Update `docs/system-architecture.md` with the new architecture (delegates, registries, state services, EventBus catalog)
|
||||
- Update `docs/adr/0079-solid-refactor-controller-decomposition.md` with the "Consequences: Actual" section: real metrics achieved, patterns that worked, tech debt that remains
|
||||
- Delete `consumeState()` from `BaseController` once all legacy callers are gone
|
||||
- Verify `BASE_MAX=250`, `VIOLATIONS_MAX=0`, `BARE_EVER_MAX=0`, `BINDING_VIOLATIONS_MAX=0`, `RELOAD_MAX=0`
|
||||
- Verify `scripts/controller_loc_baselines.txt` is empty (no controller exceeds 700 LOC)
|
||||
|
||||
This final sweep is not pre-scheduled — it happens after the last Layer 2 phase lands.
|
||||
@@ -0,0 +1,117 @@
|
||||
---
|
||||
title: "SOLID Refactor — Abstract Pattern Plan"
|
||||
description: "Patterns, contracts, and protocol for decomposing god controllers. Per-controller work deferred to JIT phase files."
|
||||
status: pending
|
||||
priority: P1
|
||||
effort: foundation: 2w · pilot delegate: 2d · per-controller: JIT
|
||||
branch: refactor/solid-controller-decomposition
|
||||
tags: [solid, refactor, getx, delegates, registries, architecture]
|
||||
updated: 2026-04-13
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The presentation layer has accumulated god controllers that violate SOLID. This plan establishes the **patterns, contracts, and enforcement** needed to decompose any god controller in the codebase — **without naming specific targets**. Per-controller decomposition work is deferred and tackled one controller at a time after the foundation lands.
|
||||
|
||||
### Goal
|
||||
|
||||
After this plan's foundation phases (0–2) land, adding a new delegate to any screen is one file + one `late final` line in a domain registry. Zero bindings edits. CI gates every controller >700 LOC on every PR, ratcheting down as controllers are decomposed.
|
||||
|
||||
### Two-layer structure
|
||||
|
||||
**Layer 1 — Abstract foundation (Phases 0–2):** Infrastructure, tooling, pattern template, and one production pilot delegate. Written once; applies to every god controller. Lands on `master` non-blocking.
|
||||
|
||||
**Layer 2 — Per-controller phases (JIT):** One phase file created when each controller is tackled. Contains that controller's domain boundary table, Rx var inventory, delegate specs, and extraction order. Not written upfront.
|
||||
|
||||
### Progressive declaration rule
|
||||
|
||||
> Declare each artifact in the same commit that creates the thing needing it.
|
||||
> Never declare upfront for work that doesn't exist yet.
|
||||
|
||||
| Artifact | When to add |
|
||||
|---|---|
|
||||
| ISP interface `IXRepository` | Same commit as the delegate depending on it |
|
||||
| CI ratchet threshold update | After a delegate is extracted, tested, and CI green |
|
||||
| Event class file | Same commit as the first delegate that emits/listens to it |
|
||||
| Registry `late final` field | Same commit as the delegate it exposes |
|
||||
| New controller phase file (Layer 2) | Moment you start work on that controller |
|
||||
|
||||
### Core patterns (established in Phases 0–2)
|
||||
|
||||
| Pattern | Purpose | Phase |
|
||||
|---|---|---|
|
||||
| `ControllerDelegate` (plain Dart class) | Units of decomposition. Owns workers + subscriptions. Lifecycle driven by parent registry. | 0 |
|
||||
| `AppEventBus` + wrapper events | Cross-feature announcements. Domain `Success`/`Failure` wrapped — never inherit `AppEvent`. | 1 |
|
||||
| `SessionService` (constructor-injected EventBus) | Single source of truth for session. Written only by `SessionEstablishedEvent`. | 1 |
|
||||
| State services with single-writer rule | Shared Rx state with named owning delegate. | 1 |
|
||||
| `ActionQueue` + `DomainAction` + `CancellationToken` | Centralised async execution. Tag-unique, cancel-before-replace, `cancelAll()`. | 1 |
|
||||
| `ControllerDelegate` base + lifecycle propagation via `DomainRegistry` | Delegates get `init()`/`dispose()` called deterministically by their registry. | 1 |
|
||||
| `BaseController` strip + `ViewContextService` + `AuthService` / `CacheService` / `UIService` | Lean base for delegates to extend when a GetxController is needed. | 2 |
|
||||
| Domain Registry lifecycle propagation | Single DI entry per domain; owns its delegates' init/dispose. | 2 |
|
||||
| Pilot delegate shipped to production | Proves the full loop before touching any god controller. | 2 |
|
||||
| Per-controller extraction protocol | Generic template for JIT Layer 2 phases. | N |
|
||||
|
||||
### Zero-tolerance regression rules (enforced by CI on every commit)
|
||||
|
||||
1. `workerObxVariables.add(ever(...))` for GetxControllers; `trackWorker(ever(...))` for `ControllerDelegate`. Never bare `ever()`.
|
||||
2. `consumeState()` is `@Deprecated`. Zero NEW callers in delegates or registries.
|
||||
3. Every `ControllerDelegate` with EventBus subscriptions stores and cancels them in `dispose()`.
|
||||
4. `SessionService` has no public setter; writes only happen in its own `SessionEstablishedEvent` listener.
|
||||
5. One delegate per commit, CI green before the next extraction starts.
|
||||
6. Each decomposition phase file owns the event files it introduces — no cross-phase edits to event files.
|
||||
7. `Get.find<>()` never inside extension methods, mixin bodies, or delegate bodies. Bindings + registries only.
|
||||
8. `XBindings().dependencies()` never called from a controller body. Accepted exceptions: `inject*()` methods in `BaseController`/`ReloadableController` (capability-gated), `fcm_message_controller.dart` (background isolate bootstrap).
|
||||
9. Domain `Success`/`Failure` types never extend `AppEvent`. Cross-feature delivery uses wrapper events (`ActionCompleted<T>` or named events).
|
||||
10. `ActionQueue.submit()` cancels any existing subscription for the same `tag` before installing a new one.
|
||||
11. `ActionQueue.cancelAll()` called on `onSessionEnd()` — no orphaned streams survive logout.
|
||||
12. Controllers >700 LOC are CI-gated; the gate auto-discovers new violators.
|
||||
13. `ControllerDelegate` is a plain Dart class (not a `BaseController`). It does not appear in `Get.find<>()` directly — it is owned by its registry.
|
||||
14. State services expose a single `update*` method per Rx var, documented with the name of the delegate allowed to call it.
|
||||
|
||||
## Phases
|
||||
|
||||
> **Non-blocking by design.** Phases 0–1 are additive; land directly on `master`. Phase 2 is a 4-day coordination window (BaseController + bindings files only). Layer 2 per-controller phases run in git worktrees.
|
||||
|
||||
| # | Phase | Blocking | Effort | Status | File |
|
||||
|---|-------|----------|--------|--------|------|
|
||||
| 0 | Safety Foundation: `workerObxVariables` → `BaseController`, `consumeState()` stream fix + deprecation, `ControllerDelegate` abstract base, auto-discovering CI script, `custom_lint` rules | Non-blocking | 2d | pending | [phase-00](phase-00-safety-foundation.md) |
|
||||
| 1 | Core Infrastructure: `AppEventBus` + wrapper events, constructor-injected `SessionService`, state services with single-writer rule, `ActionQueue` + `DomainAction` + `CancellationToken` (cancel-before-replace, `cancelAll()`), generic characterization test template | Non-blocking | 3d | pending | [phase-01](phase-01-new-infrastructure.md) |
|
||||
| 2 | BaseController & DI Refactor + Pilot: `BaseController` strip (→≤250 LOC), `ReloadableController` ctor injection, `AuthService` / `CacheService` / `UIService` / `ViewContextService` extraction, bindings split, panel-scoped binding migration, **NotificationDelegate pilot shipped to production** | **Coordination window** | 4d | pending | [phase-02](phase-02-base-refactor-and-di.md) |
|
||||
| N | Generic per-controller extraction protocol (template). One instance created JIT per god controller, smallest LOC first. Run in git worktrees. Includes Rxn→EventBus migration per delegate. | Non-blocking (git worktree) | per controller | template | [phase-N-template](phase-N-generic-controller-extraction.md) |
|
||||
|
||||
Layer 2 per-controller phase files are created JIT when work on each controller begins. They are **not** pre-written in this plan.
|
||||
|
||||
## Foundation targets
|
||||
|
||||
These targets apply after Phases 0–2 land:
|
||||
|
||||
| Metric | Target | Verified by |
|
||||
|--------|--------|-------------|
|
||||
| `BaseController` LOC | ≤250 | CI (`BASE_MAX=250`) |
|
||||
| `ReloadableController` field-level `Get.find` | 0 | CI |
|
||||
| Bare `ever()` calls | 0 (ratcheted from baseline) | CI |
|
||||
| `Get.find<>()` outside bindings | ≤ current baseline, ratchets down | CI |
|
||||
| `XBindings().dependencies()` outside bindings | 0 | CI |
|
||||
| Cross-feature `DataSource` in bindings | 0 | CI |
|
||||
| Pilot delegate shipped | NotificationDelegate in production | Smoke test |
|
||||
| Controllers >700 LOC | Auto-discovered + gated (no regressions) | CI (`controller_loc_gate`) |
|
||||
|
||||
Per-controller targets (LOC reduction, delegate count, Rxn elimination) are owned by each Layer 2 phase file and recorded when that controller's decomposition begins.
|
||||
|
||||
## Dependencies
|
||||
|
||||
- Phase 0 → additive, no blockers. Establishes CI enforcement at current baselines.
|
||||
- Phase 1 → additive, no blockers. Can run immediately after or in parallel with Phase 0.
|
||||
- Phase 2 → depends on Phases 0 + 1. **Only phase requiring team coordination** (4-day window).
|
||||
- Phase 2 → blocks all Layer 2 decomposition phases. BaseController must be lean before any delegate extends it (for cases where a delegate must be a `BaseController` subclass — though the canonical `ControllerDelegate` is a plain Dart class).
|
||||
- Layer 2 phases → run in git worktrees, may be parallelised across controllers. Feature PRs land on `master` freely throughout.
|
||||
|
||||
## Out of scope for this plan
|
||||
|
||||
The following are deferred to Layer 2 phase files (JIT) or later initiatives:
|
||||
|
||||
- **Specific god controller decomposition.** No controller is named in actionable targets.
|
||||
- **Cross-feature decoupling.** Each Layer 2 phase handles its own cross-feature cleanup.
|
||||
- **Session lifecycle protocol integration** in existing login/logout flow. Registered as a contract in Phase 1; wired into production by the first Layer 2 phase that requires session-scoped registries.
|
||||
- **Operation lifetime reclassification** (`DownloadService`, `SendingQueueService`, etc.). Addressed when the owning controller is decomposed.
|
||||
- **Documentation sweep** (`docs/system-architecture.md`, ADR "actual metrics" section). Happens after enough Layer 2 phases land to have representative numbers.
|
||||
Reference in new issue
Block a user