-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathFileSyncDaemon.swift
368 lines (322 loc) · 11.5 KB
/
FileSyncDaemon.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import Foundation
import GRPC
import NIO
import os
import Semaphore
import Subprocess
import SwiftUI
@MainActor
public protocol FileSyncDaemon: ObservableObject {
var state: DaemonState { get }
var sessionState: [FileSyncSession] { get }
var logFile: URL { get }
func tryStart() async
func stop() async
func refreshSessions() async
func createSession(arg: CreateSyncSessionRequest) async throws(DaemonError)
func deleteSessions(ids: [String]) async throws(DaemonError)
func pauseSessions(ids: [String]) async throws(DaemonError)
func resumeSessions(ids: [String]) async throws(DaemonError)
func resetSessions(ids: [String]) async throws(DaemonError)
}
@MainActor
public class MutagenDaemon: FileSyncDaemon {
let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "mutagen")
@Published public var state: DaemonState = .stopped {
didSet {
logger.info("daemon state set: \(self.state.description, privacy: .public)")
if case .failed = state {
Task {
try? await cleanupGRPC()
}
mutagenProcess?.kill()
mutagenProcess = nil
}
}
}
@Published public var sessionState: [FileSyncSession] = []
private var mutagenProcess: Subprocess?
private let mutagenPath: URL!
private let mutagenDataDirectory: URL
private let mutagenDaemonSocket: URL
public let logFile: URL
// Managing sync sessions could take a while, especially with prompting
let sessionMgmtReqTimeout: TimeAmount = .seconds(15)
// Non-nil when the daemon is running
var client: DaemonClient?
private var group: MultiThreadedEventLoopGroup?
private var channel: GRPCChannel?
private var waitForExit: (@Sendable () async -> Void)?
// Protect start & stop transitions against re-entrancy
private let transition = AsyncSemaphore(value: 1)
public init(mutagenPath: URL? = nil,
mutagenDataDirectory: URL = FileManager.default.urls(
for: .applicationSupportDirectory,
in: .userDomainMask
).first!.appending(path: "Coder Desktop").appending(path: "Mutagen"))
{
self.mutagenPath = mutagenPath
self.mutagenDataDirectory = mutagenDataDirectory
mutagenDaemonSocket = mutagenDataDirectory.appending(path: "daemon").appending(path: "daemon.sock")
logFile = mutagenDataDirectory.appending(path: "daemon.log")
// It shouldn't be fatal if the app was built without Mutagen embedded,
// but file sync will be unavailable.
if mutagenPath == nil {
logger.warning("Mutagen not embedded in app, file sync will be unavailable")
state = .unavailable
return
}
}
public func tryStart() async {
if case .failed = state { state = .stopped }
do throws(DaemonError) {
try await start()
} catch {
state = .failed(error)
return
}
await refreshSessions()
if sessionState.isEmpty {
logger.info("No sync sessions found on startup, stopping daemon")
await stop()
}
}
func start() async throws(DaemonError) {
if case .unavailable = state { return }
// Stop an orphaned daemon, if there is one
try? await connect()
await stop()
// Creating the same process twice from Swift will crash the MainActor,
// so we need to wait for an earlier process to die
await waitForExit?()
await transition.wait()
defer { transition.signal() }
logger.info("starting mutagen daemon")
mutagenProcess = createMutagenProcess()
let (standardError, waitForExit): (Pipe.AsyncBytes, @Sendable () async -> Void)
do {
(_, standardError, waitForExit) = try mutagenProcess!.run()
} catch {
throw .daemonStartFailure(error)
}
self.waitForExit = waitForExit
Task {
await handleDaemonLogs(io: standardError)
logger.info("standard error stream closed")
}
Task {
await terminationHandler(waitForExit: waitForExit)
}
do {
try await connect()
} catch {
throw .daemonStartFailure(error)
}
try await waitForDaemonStart()
state = .running
logger.info(
"""
mutagen daemon started, pid:
\(self.mutagenProcess?.pid.description ?? "unknown", privacy: .public)
"""
)
}
// The daemon takes a moment to open the socket, and we don't want to hog the main actor
// so poll for it on a background thread
private func waitForDaemonStart(
maxAttempts: Int = 5,
attemptInterval: Duration = .milliseconds(100)
) async throws(DaemonError) {
do {
try await Task.detached(priority: .background) {
for attempt in 0 ... maxAttempts {
do {
_ = try await self.client!.mgmt.version(
Daemon_VersionRequest(),
callOptions: .init(timeLimit: .timeout(.milliseconds(500)))
)
return
} catch {
if attempt == maxAttempts {
throw error
}
try? await Task.sleep(for: attemptInterval)
}
}
}.value
} catch {
throw .daemonStartFailure(error)
}
}
private func connect() async throws(DaemonError) {
guard client == nil else {
// Already connected
return
}
group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
do {
channel = try GRPCChannelPool.with(
target: .unixDomainSocket(mutagenDaemonSocket.path),
transportSecurity: .plaintext,
eventLoopGroup: group!
)
client = DaemonClient(
mgmt: Daemon_DaemonAsyncClient(channel: channel!),
sync: Synchronization_SynchronizationAsyncClient(channel: channel!),
prompt: Prompting_PromptingAsyncClient(channel: channel!)
)
logger.info(
"Successfully connected to mutagen daemon, socket: \(self.mutagenDaemonSocket.path, privacy: .public)"
)
} catch {
logger.error("Failed to connect to gRPC: \(error)")
try? await cleanupGRPC()
throw .connectionFailure(error)
}
}
private func cleanupGRPC() async throws {
try? await channel?.close().get()
try? await group?.shutdownGracefully()
client = nil
channel = nil
group = nil
}
public func stop() async {
if case .unavailable = state { return }
await transition.wait()
defer { transition.signal() }
logger.info("stopping mutagen daemon")
state = .stopped
guard FileManager.default.fileExists(atPath: mutagenDaemonSocket.path) else {
// Already stopped
return
}
// "We don't check the response or error, because the daemon
// may terminate before it has a chance to send the response."
_ = try? await client?.mgmt.terminate(
Daemon_TerminateRequest(),
callOptions: .init(timeLimit: .timeout(.milliseconds(500)))
)
try? await cleanupGRPC()
mutagenProcess?.kill()
mutagenProcess = nil
logger.info("Daemon stopped and gRPC connection closed")
}
private func createMutagenProcess() -> Subprocess {
let process = Subprocess([mutagenPath.path, "daemon", "run"])
process.environment = [
"MUTAGEN_DATA_DIRECTORY": mutagenDataDirectory.path,
"MUTAGEN_SSH_PATH": "/usr/bin",
]
logger.info("setting mutagen data directory: \(self.mutagenDataDirectory.path, privacy: .public)")
return process
}
private func terminationHandler(waitForExit: @Sendable () async -> Void) async {
await waitForExit()
switch state {
case .stopped:
logger.info("mutagen daemon stopped")
default:
logger.error(
"""
mutagen daemon exited unexpectedly with code:
\(self.mutagenProcess?.exitCode.description ?? "unknown")
"""
)
state = .failed(.terminatedUnexpectedly)
return
}
}
private func handleDaemonLogs(io: Pipe.AsyncBytes) async {
if !FileManager.default.fileExists(atPath: logFile.path) {
guard FileManager.default.createFile(atPath: logFile.path, contents: nil) else {
logger.error("Failed to create log file")
return
}
}
guard let fileHandle = try? FileHandle(forWritingTo: logFile) else {
logger.error("Failed to open log file for writing")
return
}
for await line in io.lines {
logger.info("\(line, privacy: .public)")
do {
try fileHandle.write(contentsOf: Data("\(line)\n".utf8))
} catch {
logger.error("Failed to write to daemon log file: \(error)")
}
}
try? fileHandle.close()
}
}
struct DaemonClient {
let mgmt: Daemon_DaemonAsyncClient
let sync: Synchronization_SynchronizationAsyncClient
let prompt: Prompting_PromptingAsyncClient
}
public enum DaemonState {
case running
case stopped
case failed(DaemonError)
case unavailable
public var description: String {
switch self {
case .running:
"Running"
case .stopped:
"Stopped"
case let .failed(error):
"\(error.description)"
case .unavailable:
"Unavailable"
}
}
public var color: Color {
switch self {
case .running:
.green
case .stopped:
.gray
case .failed:
.red
case .unavailable:
.gray
}
}
// `if case`s are a pain to work with: they're not bools (such as for ORing)
// and you can't negate them without doing `if case .. {} else`.
public var isFailed: Bool {
if case .failed = self {
return true
}
return false
}
}
public enum DaemonError: Error {
case daemonNotRunning
case daemonStartFailure(Error)
case connectionFailure(Error)
case terminatedUnexpectedly
case grpcFailure(Error)
case invalidGrpcResponse(String)
case unexpectedStreamClosure
public var description: String {
switch self {
case let .daemonStartFailure(error):
"Daemon start failure: \(error)"
case let .connectionFailure(error):
"Connection failure: \(error)"
case .terminatedUnexpectedly:
"Daemon terminated unexpectedly"
case .daemonNotRunning:
"The daemon must be started first"
case let .grpcFailure(error):
"Failed to communicate with daemon: \(error)"
case let .invalidGrpcResponse(response):
"Invalid gRPC response: \(response)"
case .unexpectedStreamClosure:
"Unexpected stream closure"
}
}
public var localizedDescription: String { description }
}