refactor: share async invoke bridge across native platforms

This commit is contained in:
Levi committed 2026-09-06 11:59:11 +08:00
1 parent d12122ea86
commit 607d1729e6
17 files changed
+464 -222

No files matched your search

@@ -1,6 +1,7 @@
package com.gopeed.gopeed
import com.gopeed.libgopeed.Libgopeed
import com.gopeed.libgopeed.InvokeResultListener
import com.gopeed.libgopeed.TaskEventListener
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
@@ -38,13 +39,23 @@ class MainActivity : FlutterActivity() {
"restartApiServer" -> result.success(Libgopeed.restartAPIServer())
"invoke" -> {
try {
result.success(
Libgopeed.invoke(
call.argument<String>("method") ?: "",
call.argument<String>("path") ?: "",
call.argument<String>("query") ?: "",
call.argument<String>("body") ?: "",
),
Libgopeed.invokeAsync(
call.argument<String>("method") ?: "",
call.argument<String>("path") ?: "",
call.argument<String>("query") ?: "",
call.argument<String>("body") ?: "",
call.argument<Number>("requestID")?.toLong() ?: 0L,
object : InvokeResultListener {
override fun onResult(requestID: Long, success: Boolean, payload: String?) {
runOnUiThread {
if (success) {
result.success(payload ?: "")
} else {
result.error("ERROR", payload ?: "InvokeAsync failed", null)
}
}
}
},
)
} catch (error: Exception) {
result.error("ERROR", error.message, null)
@@ -259,7 +259,6 @@ GetAPIServerState
StartAPIServer
StopAPIServer
RestartAPIServer
Invoke
InvokeAsync
FreeCString
SubscribeTaskEvents
@@ -269,12 +268,12 @@ Requirements:
- Use the cgo C-string ABI in the first phase. Reconsider pointer-and-length parameters only during a future ABI-breaking revision.
- Memory allocated by Go must be released with `FreeCString`.
- `InvokeAsync` copies every Dart-owned input string before returning, queues the request in a bounded-concurrency Go executor, and completes it through a `NativeCallable.listener` callback.
- The async executor uses `clamp(GOMAXPROCS * 2, 4, 32)` workers. Requests wait in FIFO order when every worker is busy; pool saturation is backpressure, not an API error.
- Dart-owned input memory must be released after the synchronous native entry call returns. Go-owned callback payloads remain valid until Dart copies them and calls `FreeCString`.
- `Invoke` returns the same Result JSON as REST; business errors do not use a separate ABI error model.
- Keep `Invoke` as a compatibility entry point, but route Desktop application requests through `InvokeAsync` in the FFI bridge isolate.
- Run blocking Desktop FFI work outside the Flutter UI isolate. The bridge isolate owns the dynamic library and native callbacks, decodes callback JSON, and forwards sendable Dart values to the UI isolate. Mobile MethodChannel handlers likewise run blocking Go work on a background task queue.
- `InvokeAsync` is the only native invocation entry point. Desktop and gomobile adapters both submit to the shared bounded-concurrency executor in `bind/native`.
- The shared executor uses `clamp(GOMAXPROCS * 2, 4, 32)` workers. Requests wait in FIFO order when every worker is busy; pool saturation is backpressure, not an API error.
- The Desktop adapter copies every Dart-owned input string before returning and completes through a `NativeCallable.listener` callback.
- Dart-owned input memory must be released after the non-blocking `InvokeAsync` native entry returns. Go-owned callback payloads remain valid until Dart copies them and calls `FreeCString`.
- `InvokeAsync` returns the same Result JSON as REST through its callback; business errors do not use a separate ABI error model.
- The Desktop bridge isolate owns the dynamic library and native callbacks, decodes callback JSON, and forwards sendable Dart values to the UI isolate. Mobile MethodChannel handlers run on background task queues, while invoke completion is delivered through the shared Go callback flow.
- Dart bindings are generated from `include/libgopeed.h` with `ffigen`. Every exported Desktop symbol must be added to the `ffigen.functions.include` allowlist.
- Never hand-edit `lib/core/ffi/libgopeed_bind.dart`; regenerate it with `flutter pub run ffigen` after changing the C header.
@@ -289,14 +288,14 @@ GetAPIServerState()
StartAPIServer()
StopAPIServer()
RestartAPIServer()
Invoke(method, path, query, body)
InvokeAsync(method, path, query, body, requestID, listener)
SubscribeTaskEvents(mask, listener)
```
Flutter bridge rules:
- Normal calls use MethodChannel.
- Android performs normal calls on a background task queue.
- Normal calls use MethodChannel, while `InvokeAsync` completes the pending MethodChannel result through a gomobile listener.
- Android and iOS run the Libgopeed MethodChannel handler on a serial background task queue; callback adapters marshal completion back to the platform UI thread.
- Events reuse the same MethodChannel through the reverse `taskEvent` message.
- Kotlin and Swift contain no business logic. They only forward arguments, dispatch callbacks to the UI thread, and translate errors.
@@ -593,8 +592,8 @@ Flutter converts all of them into `GopeedException`. Components do not handle Di
### 11.3 Platform smoke tests
- Windows, macOS, Linux: startup, Invoke, events, shutdown, and repeated startup.
- Android, iOS: gomobile Invoke, reverse MethodChannel events, and background/foreground transitions.
- Windows, macOS, Linux: startup, InvokeAsync, events, shutdown, and repeated startup.
- Android, iOS: gomobile InvokeAsync callbacks, reverse MethodChannel events, and background/foreground transitions.
- Web: REST, login, proxy, and task-file downloads.
- Native: enabling and disabling REST does not interrupt download tasks.
@@ -609,7 +608,7 @@ Flutter converts all of them into `GopeedException`. Components do not handle Di
### Phase 2: Native in-process calls — implemented on this branch
- Integrate the FFI Transport on Desktop.
- Extend gomobile Invoke and MethodChannel on Mobile.
- Extend gomobile InvokeAsync callbacks and MethodChannel on Mobile.
- Move Flutter API calls to the unified Transport so each typed method is maintained once.
- Do not create a socket listener by default on native clients.
-1
View File
@@ -112,7 +112,6 @@ extern char* GetAPIServerState(void);
extern char* StartAPIServer(void);
extern char* StopAPIServer(void);
extern char* RestartAPIServer(void);
extern char* Invoke(char* method, char* path, char* query, char* body);
extern void InvokeAsync(char* method, char* path, char* query, char* body, long long unsigned int requestID, uintptr_t callback);
extern void SubscribeTaskEvents(long long unsigned int mask, uintptr_t callback);
extern void FreeCString(char* value);
+6 -2
View File
@@ -14,10 +14,13 @@ import UIKit
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
let messenger = engineBridge.applicationRegistrar.messenger()
let libgopeedTaskQueue = messenger.makeBackgroundTaskQueue?()
let libgopeedChannel = FlutterMethodChannel(
name: "gopeed.com/libgopeed",
binaryMessenger: messenger
binaryMessenger: messenger,
codec: FlutterStandardMethodCodec.sharedInstance(),
taskQueue: libgopeedTaskQueue
)
let taskEventForwarder = GopeedTaskEventForwarder(channel: libgopeedChannel)
libgopeedChannel.setMethodCallHandler { call, result in
@@ -56,7 +59,8 @@ import UIKit
let path = arguments?["path"] as? String ?? ""
let query = arguments?["query"] as? String ?? ""
let body = arguments?["body"] as? String ?? ""
result(LibgopeedInvoke(method, path, query, body))
let requestID = (arguments?["requestID"] as? NSNumber)?.int64Value ?? 0
GopeedInvokeAsyncWithResult(method, path, query, body, requestID, result)
case "subscribeTaskEvents":
let arguments = call.arguments as? [String: Any]
let mask = (arguments?["mask"] as? NSNumber)?.int64Value ?? 0
@@ -13,4 +13,12 @@ FOUNDATION_EXPORT void GopeedSubscribeTaskEventsWithForwarder(
int64_t mask,
GopeedTaskEventForwarder * _Nullable listener);
FOUNDATION_EXPORT void GopeedInvokeAsyncWithResult(
NSString *method,
NSString *path,
NSString *query,
NSString *body,
int64_t requestID,
FlutterResult result);
NS_ASSUME_NONNULL_END
@@ -8,6 +8,45 @@
@end
@interface GopeedInvokeResultForwarder : NSObject <LibgopeedInvokeResultListener>
@property(nonatomic, copy, nullable) FlutterResult result;
- (instancetype)initWithResult:(FlutterResult)result;
@end
@implementation GopeedInvokeResultForwarder
- (instancetype)initWithResult:(FlutterResult)result {
self = [super init];
if (self) {
_result = [result copy];
}
return self;
}
- (void)onResult:(int64_t)requestID
success:(BOOL)success
payload:(NSString * _Nullable)payload {
FlutterResult result = self.result;
self.result = nil;
if (result == nil) {
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
if (success) {
result(payload ?: @"");
} else {
result([FlutterError errorWithCode:@"ERROR"
message:payload ?: @"InvokeAsync failed"
details:nil]);
}
});
}
@end
@implementation GopeedTaskEventForwarder
- (instancetype)initWithChannel:(FlutterMethodChannel *)channel {
@@ -33,3 +72,15 @@ void GopeedSubscribeTaskEventsWithForwarder(
GopeedTaskEventForwarder * _Nullable listener) {
LibgopeedSubscribeTaskEvents(mask, listener);
}
void GopeedInvokeAsyncWithResult(
NSString *method,
NSString *path,
NSString *query,
NSString *body,
int64_t requestID,
FlutterResult result) {
GopeedInvokeResultForwarder *forwarder =
[[GopeedInvokeResultForwarder alloc] initWithResult:result];
LibgopeedInvokeAsync(method, path, query, body, requestID, forwarder);
}
@@ -11,6 +11,7 @@ import 'task_event.dart';
class LibgopeedChannel implements LibgopeedInterface {
static const _channel = MethodChannel('gopeed.com/libgopeed');
final _taskEvents = StreamController<TaskEvent>.broadcast();
int _requestID = 0;
LibgopeedChannel() {
_channel.setMethodCallHandler((call) async {
@@ -50,7 +51,9 @@ class LibgopeedChannel implements LibgopeedInterface {
@override
Future<String> invoke(String method, String path, {String query = '', String body = ''}) async {
final requestID = _requestID++;
final result = await _channel.invokeMethod<String>('invoke', {
'requestID': requestID,
'method': method,
'path': path,
'query': query,
@@ -58,36 +58,6 @@ class LibgopeedBind {
late final _RestartAPIServerPtr = _lookup<ffi.NativeFunction<ffi.Pointer<ffi.Char> Function()>>('RestartAPIServer');
late final _RestartAPIServer = _RestartAPIServerPtr.asFunction<ffi.Pointer<ffi.Char> Function()>();
ffi.Pointer<ffi.Char> Invoke(
ffi.Pointer<ffi.Char> method,
ffi.Pointer<ffi.Char> path,
ffi.Pointer<ffi.Char> query,
ffi.Pointer<ffi.Char> body,
) {
return _Invoke(method, path, query, body);
}
late final _InvokePtr =
_lookup<
ffi.NativeFunction<
ffi.Pointer<ffi.Char> Function(
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
)
>
>('Invoke');
late final _Invoke =
_InvokePtr.asFunction<
ffi.Pointer<ffi.Char> Function(
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
)
>();
void InvokeAsync(
ffi.Pointer<ffi.Char> method,
ffi.Pointer<ffi.Char> path,
-1
View File
@@ -208,7 +208,6 @@ ffigen:
- "StartAPIServer"
- "StopAPIServer"
- "RestartAPIServer"
- "Invoke"
- "InvokeAsync"
- "SubscribeTaskEvents"
- "FreeCString"
@@ -0,0 +1,29 @@
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gopeed/core/common/libgopeed_channel.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const channel = MethodChannel('gopeed.com/libgopeed');
final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
tearDown(() {
messenger.setMockMethodCallHandler(channel, null);
});
test('mobile invokes carry unique request IDs for async callbacks', () async {
final requestIDs = <int>[];
messenger.setMockMethodCallHandler(channel, (call) async {
expect(call.method, 'invoke');
final arguments = (call.arguments as Map<Object?, Object?>).cast<String, Object?>();
requestIDs.add(arguments['requestID']! as int);
return '{"code":0}';
});
final bridge = LibgopeedChannel();
await Future.wait([bridge.invoke('GET', '/api/v1/info'), bridge.invoke('GET', '/api/v1/config')]);
expect(requestIDs, [0, 1]);
});
}