Merge branch 'auto-claude/002-migrate-api-routes-from-http-to-grpc'
This commit is contained in:
@@ -3,12 +3,108 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../api/types.dart';
|
||||
import '../api/client.dart';
|
||||
import '../api/grpc_client.dart';
|
||||
import '../api/grpc_config.dart';
|
||||
import '../api/openapi_config.dart';
|
||||
import '../services/auth_service.dart';
|
||||
import '../models/user_profile.dart';
|
||||
import '../models/delivery_route.dart';
|
||||
import '../models/delivery.dart';
|
||||
|
||||
// ============================================================================
|
||||
// API Mode Configuration - Feature Flag for HTTP/gRPC Transport
|
||||
// ============================================================================
|
||||
|
||||
/// Enum representing the available API transport modes.
|
||||
enum ApiMode {
|
||||
/// Use HTTP/REST-based CQRS API client
|
||||
http,
|
||||
|
||||
/// Use gRPC-based CQRS API client
|
||||
grpc,
|
||||
}
|
||||
|
||||
/// Configuration for API transport mode selection.
|
||||
///
|
||||
/// This class allows switching between HTTP and gRPC transports
|
||||
/// for API calls. Following the pattern from [ApiClientConfig].
|
||||
///
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// // To switch to gRPC, override the apiModeConfigProvider:
|
||||
/// ProviderScope(
|
||||
/// overrides: [
|
||||
/// apiModeConfigProvider.overrideWithValue(ApiModeConfig.developmentGrpc),
|
||||
/// ],
|
||||
/// child: MyApp(),
|
||||
/// )
|
||||
/// ```
|
||||
class ApiModeConfig {
|
||||
/// The transport mode to use for API calls.
|
||||
final ApiMode mode;
|
||||
|
||||
/// Whether to fall back to HTTP on gRPC failures.
|
||||
/// Only applicable when [mode] is [ApiMode.grpc].
|
||||
final bool fallbackToHttpOnError;
|
||||
|
||||
const ApiModeConfig({
|
||||
required this.mode,
|
||||
this.fallbackToHttpOnError = true,
|
||||
});
|
||||
|
||||
/// Development configuration - defaults to HTTP for stability.
|
||||
/// Use this for safe development when gRPC backend may be unavailable.
|
||||
static const ApiModeConfig development = ApiModeConfig(
|
||||
mode: ApiMode.http,
|
||||
fallbackToHttpOnError: true,
|
||||
);
|
||||
|
||||
/// gRPC-first development configuration for testing gRPC integration.
|
||||
/// Use this when actively developing/testing gRPC functionality.
|
||||
static const ApiModeConfig developmentGrpc = ApiModeConfig(
|
||||
mode: ApiMode.grpc,
|
||||
fallbackToHttpOnError: true,
|
||||
);
|
||||
|
||||
/// Production configuration - uses HTTP until gRPC is verified stable.
|
||||
static const ApiModeConfig production = ApiModeConfig(
|
||||
mode: ApiMode.http,
|
||||
fallbackToHttpOnError: false,
|
||||
);
|
||||
|
||||
/// Production gRPC configuration for when gRPC is production-ready.
|
||||
static const ApiModeConfig productionGrpc = ApiModeConfig(
|
||||
mode: ApiMode.grpc,
|
||||
fallbackToHttpOnError: false,
|
||||
);
|
||||
|
||||
/// Whether the current mode is gRPC.
|
||||
bool get isGrpc => mode == ApiMode.grpc;
|
||||
|
||||
/// Whether the current mode is HTTP.
|
||||
bool get isHttp => mode == ApiMode.http;
|
||||
}
|
||||
|
||||
/// Provider for API mode configuration.
|
||||
///
|
||||
/// Override this provider to switch between HTTP and gRPC:
|
||||
/// ```dart
|
||||
/// ProviderScope(
|
||||
/// overrides: [
|
||||
/// apiModeConfigProvider.overrideWithValue(ApiModeConfig.developmentGrpc),
|
||||
/// ],
|
||||
/// child: MyApp(),
|
||||
/// )
|
||||
/// ```
|
||||
final apiModeConfigProvider = Provider<ApiModeConfig>((ref) {
|
||||
// Default to HTTP for safety during transition
|
||||
return ApiModeConfig.development;
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Core Service Providers
|
||||
// ============================================================================
|
||||
|
||||
final authServiceProvider = Provider<AuthService>((ref) {
|
||||
return AuthService(config: AuthConfig.development);
|
||||
});
|
||||
@@ -21,6 +117,31 @@ final apiClientProvider = Provider<CqrsApiClient>((ref) {
|
||||
);
|
||||
});
|
||||
|
||||
/// Provider for the gRPC-based CQRS API client.
|
||||
///
|
||||
/// Uses auto-dispose to properly shut down the gRPC channel when the provider
|
||||
/// is no longer being watched. This ensures network resources are cleaned up.
|
||||
///
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// final grpcClient = ref.watch(grpcClientProvider);
|
||||
/// final result = await grpcClient.getDeliveryRoutes();
|
||||
/// ```
|
||||
final grpcClientProvider = Provider.autoDispose<GrpcCqrsApiClient>((ref) {
|
||||
final authService = ref.watch(authServiceProvider);
|
||||
final client = GrpcCqrsApiClient(
|
||||
config: GrpcConfig.development,
|
||||
authService: authService,
|
||||
);
|
||||
|
||||
// Register disposal callback to clean up gRPC channel resources
|
||||
ref.onDispose(() {
|
||||
client.shutdown();
|
||||
});
|
||||
|
||||
return client;
|
||||
});
|
||||
|
||||
final isAuthenticatedProvider = FutureProvider<bool>((ref) async {
|
||||
final authService = ref.watch(authServiceProvider);
|
||||
return await authService.isAuthenticated();
|
||||
@@ -38,7 +159,9 @@ final authTokenProvider = FutureProvider<String?>((ref) async {
|
||||
return await authService.getToken();
|
||||
});
|
||||
|
||||
final deliveryRoutesProvider = FutureProvider<List<DeliveryRoute>>((ref) async {
|
||||
/// Internal HTTP-based delivery routes provider.
|
||||
/// Use [deliveryRoutesProvider] instead, which respects the API mode configuration.
|
||||
final _httpDeliveryRoutesProvider = FutureProvider<List<DeliveryRoute>>((ref) async {
|
||||
final authService = ref.watch(authServiceProvider);
|
||||
final isAuthenticated = await authService.isAuthenticated();
|
||||
|
||||
@@ -68,7 +191,120 @@ final deliveryRoutesProvider = FutureProvider<List<DeliveryRoute>>((ref) async {
|
||||
return result.whenSuccess((routes) => routes) ?? [];
|
||||
});
|
||||
|
||||
final deliveriesProvider = FutureProvider.family<List<Delivery>, int>((ref, routeFragmentId) async {
|
||||
/// Unified delivery routes provider that respects the API mode configuration.
|
||||
///
|
||||
/// Automatically switches between HTTP and gRPC based on [apiModeConfigProvider].
|
||||
/// When gRPC mode is enabled and [ApiModeConfig.fallbackToHttpOnError] is true,
|
||||
/// falls back to HTTP on gRPC failures.
|
||||
///
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// final routes = ref.watch(deliveryRoutesProvider);
|
||||
/// routes.when(
|
||||
/// data: (data) => displayRoutes(data),
|
||||
/// loading: () => showLoading(),
|
||||
/// error: (error, stack) => showError(error),
|
||||
/// );
|
||||
/// ```
|
||||
final deliveryRoutesProvider = FutureProvider<List<DeliveryRoute>>((ref) async {
|
||||
final apiModeConfig = ref.watch(apiModeConfigProvider);
|
||||
|
||||
if (apiModeConfig.isGrpc) {
|
||||
try {
|
||||
return await ref.watch(grpcDeliveryRoutesProvider.future);
|
||||
} catch (e) {
|
||||
if (apiModeConfig.fallbackToHttpOnError) {
|
||||
debugPrint('gRPC failed, falling back to HTTP: $e');
|
||||
return await ref.watch(_httpDeliveryRoutesProvider.future);
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
return await ref.watch(_httpDeliveryRoutesProvider.future);
|
||||
});
|
||||
|
||||
/// Provider for delivery routes using gRPC.
|
||||
///
|
||||
/// This is the gRPC-based alternative to [deliveryRoutesProvider].
|
||||
/// Uses [GrpcCqrsApiClient] for improved performance and type safety.
|
||||
///
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// final routes = ref.watch(grpcDeliveryRoutesProvider);
|
||||
/// routes.when(
|
||||
/// data: (data) => displayRoutes(data),
|
||||
/// loading: () => showLoading(),
|
||||
/// error: (error, stack) => showError(error),
|
||||
/// );
|
||||
/// ```
|
||||
final grpcDeliveryRoutesProvider = FutureProvider<List<DeliveryRoute>>((ref) async {
|
||||
final authService = ref.watch(authServiceProvider);
|
||||
final isAuthenticated = await authService.isAuthenticated();
|
||||
|
||||
if (!isAuthenticated) {
|
||||
throw Exception('User not authenticated');
|
||||
}
|
||||
|
||||
final grpcClient = ref.watch(grpcClientProvider);
|
||||
final result = await grpcClient.getDeliveryRoutes();
|
||||
|
||||
return result.when(
|
||||
success: (routes) => routes,
|
||||
onError: (error) {
|
||||
debugPrint('ERROR fetching delivery routes via gRPC: ${error.message}');
|
||||
if (error.originalException != null) {
|
||||
debugPrint('Original exception: ${error.originalException}');
|
||||
}
|
||||
throw Exception(error.message);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
/// Provider for deliveries using gRPC.
|
||||
///
|
||||
/// This is the gRPC-based alternative to [deliveriesProvider].
|
||||
/// Uses [GrpcCqrsApiClient] for improved performance and type safety.
|
||||
/// Takes a [routeFragmentId] parameter to fetch deliveries for a specific route.
|
||||
///
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// final deliveries = ref.watch(grpcDeliveriesProvider(routeFragmentId));
|
||||
/// deliveries.when(
|
||||
/// data: (data) => displayDeliveries(data),
|
||||
/// loading: () => showLoading(),
|
||||
/// error: (error, stack) => showError(error),
|
||||
/// );
|
||||
/// ```
|
||||
final grpcDeliveriesProvider = FutureProvider.family<List<Delivery>, int>((ref, routeFragmentId) async {
|
||||
final authService = ref.watch(authServiceProvider);
|
||||
final isAuthenticated = await authService.isAuthenticated();
|
||||
|
||||
if (!isAuthenticated) {
|
||||
throw Exception('User not authenticated');
|
||||
}
|
||||
|
||||
final grpcClient = ref.watch(grpcClientProvider);
|
||||
final result = await grpcClient.getDeliveries(routeFragmentId: routeFragmentId);
|
||||
|
||||
final deliveries = result.when(
|
||||
success: (deliveries) => deliveries,
|
||||
onError: (error) {
|
||||
debugPrint('ERROR fetching deliveries for route $routeFragmentId via gRPC: ${error.message}');
|
||||
if (error.originalException != null) {
|
||||
debugPrint('Original exception: ${error.originalException}');
|
||||
}
|
||||
throw Exception(error.message);
|
||||
},
|
||||
);
|
||||
|
||||
// Always append the warehouse delivery at the end
|
||||
return [...deliveries, Delivery.createWarehouseDelivery()];
|
||||
});
|
||||
|
||||
/// Internal HTTP-based deliveries provider.
|
||||
/// Use [deliveriesProvider] instead, which respects the API mode configuration.
|
||||
final _httpDeliveriesProvider = FutureProvider.family<List<Delivery>, int>((ref, routeFragmentId) async {
|
||||
final authService = ref.watch(authServiceProvider);
|
||||
final isAuthenticated = await authService.isAuthenticated();
|
||||
|
||||
@@ -108,6 +344,41 @@ final deliveriesProvider = FutureProvider.family<List<Delivery>, int>((ref, rout
|
||||
return [...deliveries, Delivery.createWarehouseDelivery()];
|
||||
});
|
||||
|
||||
/// Unified deliveries provider that respects the API mode configuration.
|
||||
///
|
||||
/// Automatically switches between HTTP and gRPC based on [apiModeConfigProvider].
|
||||
/// When gRPC mode is enabled and [ApiModeConfig.fallbackToHttpOnError] is true,
|
||||
/// falls back to HTTP on gRPC failures.
|
||||
///
|
||||
/// Takes a [routeFragmentId] parameter to fetch deliveries for a specific route.
|
||||
///
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// final deliveries = ref.watch(deliveriesProvider(routeFragmentId));
|
||||
/// deliveries.when(
|
||||
/// data: (data) => displayDeliveries(data),
|
||||
/// loading: () => showLoading(),
|
||||
/// error: (error, stack) => showError(error),
|
||||
/// );
|
||||
/// ```
|
||||
final deliveriesProvider = FutureProvider.family<List<Delivery>, int>((ref, routeFragmentId) async {
|
||||
final apiModeConfig = ref.watch(apiModeConfigProvider);
|
||||
|
||||
if (apiModeConfig.isGrpc) {
|
||||
try {
|
||||
return await ref.watch(grpcDeliveriesProvider(routeFragmentId).future);
|
||||
} catch (e) {
|
||||
if (apiModeConfig.fallbackToHttpOnError) {
|
||||
debugPrint('gRPC failed for route $routeFragmentId, falling back to HTTP: $e');
|
||||
return await ref.watch(_httpDeliveriesProvider(routeFragmentId).future);
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
return await ref.watch(_httpDeliveriesProvider(routeFragmentId).future);
|
||||
});
|
||||
|
||||
/// Provider to get all deliveries from all routes
|
||||
final allDeliveriesProvider = FutureProvider<List<Delivery>>((ref) async {
|
||||
final routes = await ref.read(deliveryRoutesProvider.future);
|
||||
|
||||
Reference in New Issue
Block a user