feat: Use Websockets to update server jobs status

This commit is contained in:
Inex Code 2024-07-04 21:13:20 +04:00
parent 135ed30ee3
commit e0232bfa44
3 changed files with 29 additions and 1 deletions

View file

@ -101,7 +101,13 @@ abstract class GraphQLApiMap {
final WebSocketLink webSocketLink = WebSocketLink(
'ws://api.$rootAddress/graphql',
config: SocketClientConfig(
// TODO: Figure out the keep alive pings, as the app disconnects after 30s of inactivity.
autoReconnect: true,
initialPayload: _token.isEmpty
? null
: {
'Authorization': 'Bearer $_token',
},
headers: _token.isEmpty
? null
: {

View file

@ -22,6 +22,18 @@ mixin JobsApi on GraphQLApiMap {
return jobsList;
}
Stream<List<ServerJob>> getServerJobsStream() async* {
final GraphQLClient client = await getSubscriptionClient();
final subscription = client.subscribe$JobUpdates();
await for (final response in subscription) {
final jobsList = response.parsedData?.jobUpdates
.map<ServerJob>((final job) => ServerJob.fromGraphQL(job))
.toList() ??
[];
yield jobsList;
}
}
Future<GenericResult<bool>> removeApiJob(final String uid) async {
try {
final GraphQLClient client = await getClient();

View file

@ -44,6 +44,8 @@ class ApiConnectionRepository {
Timer? _timer;
StreamSubscription<List<ServerJob>>? _serverJobsStreamSubscription;
Future<void> removeServerJob(final String uid) async {
await api.removeApiJob(uid);
_apiData.serverJobs.data
@ -273,6 +275,12 @@ class ApiConnectionRepository {
connectionStatus = ConnectionStatus.connected;
_connectionStatusStream.add(connectionStatus);
_serverJobsStreamSubscription =
api.getServerJobsStream().listen((final List<ServerJob> jobs) {
_apiData.serverJobs.data = jobs;
_dataStream.add(_apiData);
});
// Use timer to periodically check for new jobs
_timer = Timer.periodic(
const Duration(seconds: 10),
@ -284,6 +292,7 @@ class ApiConnectionRepository {
connectionStatus = ConnectionStatus.nonexistent;
_connectionStatusStream.add(connectionStatus);
_timer?.cancel();
await _serverJobsStreamSubscription?.cancel();
}
Future<void> _refetchEverything(final Version version) async {
@ -338,7 +347,8 @@ class ApiData {
),
serverJobs = ApiDataElement<List<ServerJob>>(
fetchData: () async => api.getServerJobs(),
ttl: 10,
// TODO: Figure this out later, as ws keeps this updated
ttl: 10000,
),
backupConfig = ApiDataElement<BackupConfiguration>(
fetchData: () async => api.getBackupsConfiguration(),