git.iko.soy/parseable-macos
on f4c4ced help sign in
ParseableViewer/App/AppState.swift+5−81
since splitsnapshots
unifiedsplit
@@ -15,10 +15,6 @@ final class AppState {
15 private let networkMonitor = NWPathMonitor()
15 private let networkMonitor = NWPathMonitor()
16 private let networkMonitorQueue = DispatchQueue(label: "com.parseableviewer.network-monitor")
16 private let networkMonitorQueue = DispatchQueue(label: "com.parseableviewer.network-monitor")
17 private var connectTask: Task<Bool, Never>?
17 private var connectTask: Task<Bool, Never>?
18− /// The connection `connectTask` is connecting to. `activeConnection` only
19− /// switches once the new server answers, so this is what identifies an
20− /// in-flight connect whose target the user deletes (see `removeConnection`).
21− private var connectingConnectionID: UUID?
22
18
23 // MARK: - Stream State
19 // MARK: - Stream State
24 var streams: [LogStream] = []
20 var streams: [LogStream] = []
@@ -100,7 +96,6 @@ final class AppState {
100
96
101 if let activeID = ConnectionStore.loadActiveConnectionID(),
97 if let activeID = ConnectionStore.loadActiveConnectionID(),
102 let connection = connections.first(where: { $0.id == activeID }) {
98 let connection = connections.first(where: { $0.id == activeID }) {
103− connectingConnectionID = connection.id
104 connectTask = Task { @MainActor [weak self] in
99 connectTask = Task { @MainActor [weak self] in
105 await self?.performConnect(to: connection) ?? false
100 await self?.performConnect(to: connection) ?? false
106 }
101 }
@@ -120,7 +115,6 @@ final class AppState {
120 existing.cancel()
115 existing.cancel()
121 _ = await existing.value
116 _ = await existing.value
122 }
117 }
123− connectingConnectionID = connection.id
124 let task = Task { @MainActor [weak self] in
118 let task = Task { @MainActor [weak self] in
125 await self?.performConnect(to: connection) ?? false
119 await self?.performConnect(to: connection) ?? false
126 }
120 }
@@ -130,16 +124,9 @@ final class AppState {
130
124
131 @MainActor
125 @MainActor
132 private func performConnect(to connection: ServerConnection) async -> Bool {
126 private func performConnect(to connection: ServerConnection) async -> Bool {
133− defer {
134− if connectingConnectionID == connection.id { connectingConnectionID = nil }
135− }
136 guard !isConnecting else { return false }
127 guard !isConnecting else { return false }
137
128
138− // NWPathMonitor ignores loopback, so with no active network interface it
139− // reports "unsatisfied" even though a local server (the common docker /
140− // dev setup) is reachable. Don't block those; a genuinely unreachable
141− // host still fails below with the same offline message.
142− if !isNetworkAvailable && !Self.isLoopback(connection.baseURL) {
129+ if !isNetworkAvailable {
143 self.errorMessage = "No internet connection. Check your network and try again."
130 self.errorMessage = "No internet connection. Check your network and try again."
144 self.showError = true
131 self.showError = true
145 return false
132 return false
@@ -147,12 +134,7 @@ final class AppState {
147
134
148 isConnecting = true
135 isConnecting = true
149 defer { isConnecting = false }
136 defer { isConnecting = false }
150− // Reset the flag with the message: a previous failed connect left
151− // `showError` set, and if its alert couldn't present (e.g. behind the
152− // connection sheet), it would pop up later — after a successful retry —
153− // reading "An unknown error occurred".
154 errorMessage = nil
137 errorMessage = nil
155− showError = false
156
138
157 // When switching to a different server, clear stream-specific state
139 // When switching to a different server, clear stream-specific state
158 // so stale selections don't reference streams that don't exist.
140 // so stale selections don't reference streams that don't exist.
@@ -182,7 +164,6 @@ final class AppState {
182
164
183 // Test connection — throws on non-200 or network failure
165 // Test connection — throws on non-200 or network failure
184 try await newClient.checkHealth()
166 try await newClient.checkHealth()
185− try await Self.verifyCredentials(with: newClient)
186
167
187 // If the task was cancelled while awaiting (e.g. user clicked
168 // If the task was cancelled while awaiting (e.g. user clicked
188 // Disconnect during auto-reconnect), bail before installing the
169 // Disconnect during auto-reconnect), bail before installing the
@@ -219,12 +200,6 @@ final class AppState {
219 case .success(let list):
200 case .success(let list):
220 self.streams = list
201 self.streams = list
221 self.streamLoadError = nil
202 self.streamLoadError = nil
222− // Like refreshStreams: a selection that doesn't exist on this server
223− // (e.g. one picked from a stale list while the connect was pending)
224− // would keep every stream tab querying a missing stream.
225− if let selected = selectedStream, !list.contains(where: { $0.name == selected }) {
226− selectedStream = nil
227− }
228 case .failure(let error):
203 case .failure(let error):
229 self.streams = []
204 self.streams = []
230 self.streamLoadError = ParseableError.userFriendlyMessage(for: error)
205 self.streamLoadError = ParseableError.userFriendlyMessage(for: error)
@@ -290,13 +265,8 @@ final class AppState {
290 let loaded = try await client.listStreams()
265 let loaded = try await client.listStreams()
291 // Drop results if the active connection changed while awaiting. Still
266 // Drop results if the active connection changed while awaiting. Still
292 // clear isLoadingStreams: this task set the spinner, so leaving it true
267 // clear isLoadingStreams: this task set the spinner, so leaving it true
293− // wedges the indicator and disables Refresh. Compare the client too:
268+ // wedges the indicator and disables Refresh.
294− // editing the active connection's URL/credentials keeps its id but
295− // installs a new client for a possibly different server.
296− guard connID == activeConnection?.id, client === self.client else {
269+ guard connID == activeConnection?.id else { isLoadingStreams = false; return }
297− isLoadingStreams = false
298− return
299− }
300 streams = loaded
270 streams = loaded
301 // Drop a selection that no longer exists server-side (e.g. the stream
271 // Drop a selection that no longer exists server-side (e.g. the stream
302 // was deleted from another client); otherwise the detail tabs keep
272 // was deleted from another client); otherwise the detail tabs keep
@@ -305,10 +275,7 @@ final class AppState {
305 selectedStream = nil
275 selectedStream = nil
306 }
276 }
307 } catch {
277 } catch {
308− guard connID == activeConnection?.id, client === self.client else {
278+ guard connID == activeConnection?.id else { isLoadingStreams = false; return }
309− isLoadingStreams = false
310− return
311− }
312 let message = ParseableError.userFriendlyMessage(for: error)
279 let message = ParseableError.userFriendlyMessage(for: error)
313 streamLoadError = message
280 streamLoadError = message
314 self.errorMessage = "Failed to load streams: \(message)"
281 self.errorMessage = "Failed to load streams: \(message)"
@@ -375,49 +342,9 @@ final class AppState {
375 ConnectionStore.saveConnections(connections)
342 ConnectionStore.saveConnections(connections)
376 if activeConnection?.id == connection.id {
343 if activeConnection?.id == connection.id {
377 disconnect()
344 disconnect()
378− } else if connectingConnectionID == connection.id {
379− // The removed connection is still being connected to (e.g. Cancel in the
380− // connection sheet, or deleting it in Settings during the launch
381− // reconnect). `activeConnection` doesn't point at it yet, so without
382− // this the connect would carry on and install a client for a
383− // connection that no longer exists (or tear down the current session
384− // when it fails) after the user abandoned it.
385− connectTask?.cancel()
386− connectTask = nil
387− connectingConnectionID = nil
388− // Starting that connect already cleared the current server's stream
389− // list and filters; reload them if we're still connected to it.
390− if client != nil {
391− Task { @MainActor [weak self] in
392− await self?.refreshStreams()
393− await self?.refreshFilters()
394− }
395− }
396− }
397− }
398−
399− /// `/api/v1/liveness` is unauthenticated on Parseable (it answers 200 to
400− /// anyone, for load-balancer / k8s probes), so a health check alone accepts
401− /// any username and password. Probe an authenticated endpoint and fail on
402− /// 401. Other failures — e.g. a 403 for a role without the about permission —
403− /// don't show the credentials are wrong, so they're ignored here. The client
404− /// caches the response, so the follow-up `getAbout()` load reuses it.
405− static func verifyCredentials(with client: ParseableClient) async throws {
406− do {
407− _ = try await client.getAbout()
408− } catch ParseableError.unauthorized {
409− throw ParseableError.unauthorized
410− } catch {
411− // Not an authentication failure; leave it to the best-effort loads.
412 }
345 }
413 }
346 }
414
347
415− private static func isLoopback(_ url: URL?) -> Bool {
416− guard let host = url?.host?.lowercased() else { return false }
417− return host == "localhost" || host.hasSuffix(".localhost")
418− || host == "::1" || host.hasPrefix("127.")
419− }
420−
421 // MARK: - Stream Management
348 // MARK: - Stream Management
422
349
423 @MainActor
350 @MainActor
@@ -450,10 +377,7 @@ final class AppState {
450 let connID = activeConnection?.id
377 let connID = activeConnection?.id
451 isLoadingFilters = true
378 isLoadingFilters = true
452 let loaded = (try? await client.listFilters()) ?? []
379 let loaded = (try? await client.listFilters()) ?? []
453− guard connID == activeConnection?.id, client === self.client else {
380+ guard connID == activeConnection?.id else { isLoadingFilters = false; return }
454− isLoadingFilters = false
455− return
456− }
457 filters = loaded
381 filters = loaded
458 isLoadingFilters = false
382 isLoadingFilters = false
459 }
383 }
ParseableViewer/App/ParseableViewerApp.swift+1−13
@@ -4,13 +4,6 @@ import SwiftUI
4struct ParseableViewerApp: App {
4struct ParseableViewerApp: App {
5 @State private var appState = AppState()
5 @State private var appState = AppState()
6
6
7− init() {
8− // All window content shares one AppState (see the File > New group below),
9− // so don't offer window tabs either: the tab bar's "+" would open a second
10− // window just like File > New Window.
11− NSWindow.allowsAutomaticWindowTabbing = false
12− }
13−
14 var body: some Scene {
7 var body: some Scene {
15 WindowGroup {
8 WindowGroup {
16 ContentView()
9 ContentView()
@@ -24,12 +17,7 @@ struct ParseableViewerApp: App {
24 AboutCommand()
17 AboutCommand()
25 }
18 }
26
19
27− // Replace (rather than extend) the File > New group to drop "New Window":
28− // connection, sheet, alert, selection and pending-filter state all live
29− // in the single shared AppState, so a second window would present every
30− // sheet and alert twice and race the first window's QueryView for
31− // saved-filter SQL.
32− CommandGroup(replacing: .newItem) {
20+ CommandGroup(after: .newItem) {
33 Button("New Connection...") {
21 Button("New Connection...") {
34 appState.editingConnection = nil
22 appState.editingConnection = nil
35 appState.showConnectionSheet = true
23 appState.showConnectionSheet = true
ParseableViewer/Info.plist−5
@@ -24,11 +24,6 @@
24 <string>public.app-category.developer-tools</string>
24 <string>public.app-category.developer-tools</string>
25 <key>LSMinimumSystemVersion</key>
25 <key>LSMinimumSystemVersion</key>
26 <string>$(MACOSX_DEPLOYMENT_TARGET)</string>
26 <string>$(MACOSX_DEPLOYMENT_TARGET)</string>
27− <key>NSAppTransportSecurity</key>
28− <dict>
29− <key>NSAllowsArbitraryLoads</key>
30− <true/>
31− </dict>
32 <key>NSMainNibFile</key>
27 <key>NSMainNibFile</key>
33 <string></string>
28 <string></string>
34 <key>NSPrincipalClass</key>
29 <key>NSPrincipalClass</key>
ParseableViewer/Models/ServerConnection.swift+2−19
@@ -56,32 +56,15 @@ struct ServerConnection: Identifiable, Codable, Hashable, Sendable {
56 var baseURL: URL? {
56 var baseURL: URL? {
57 var urlString = url.trimmingCharacters(in: .whitespacesAndNewlines)
57 var urlString = url.trimmingCharacters(in: .whitespacesAndNewlines)
58 if urlString.isEmpty { return nil }
58 if urlString.isEmpty { return nil }
59− if let schemeRange = Self.urlSchemeRange(in: urlString) {
59+ if !urlString.hasPrefix("http://") && !urlString.hasPrefix("https://") {
60− // Normalize the (case-insensitive) scheme so `HTTP://host` behaves
61− // exactly like `http://host` everywhere downstream.
62− urlString.replaceSubrange(schemeRange, with: urlString[schemeRange].lowercased())
63− } else {
64 urlString = "https://\(urlString)"
60 urlString = "https://\(urlString)"
65 }
61 }
66 while urlString.hasSuffix("/") {
62 while urlString.hasSuffix("/") {
67 urlString.removeLast()
63 urlString.removeLast()
68 }
64 }
69− guard let parsed = URL(string: urlString), parsed.host != nil,
65+ guard let parsed = URL(string: urlString), parsed.host != nil else {
70− parsed.scheme == "http" || parsed.scheme == "https" else {
71 return nil
66 return nil
72 }
67 }
73 return parsed
68 return parsed
74 }
69 }
75−
76− /// Whether `string` already starts with a URL scheme (`http://`, `HTTPS://`,
77− /// `ftp://`, …). Schemes are case-insensitive, so a case-sensitive
78− /// `hasPrefix("http://")` check turned `HTTP://host` into
79− /// `https://HTTP://host` — a URL whose host is "HTTP".
80− static func hasURLScheme(_ string: String) -> Bool {
81− urlSchemeRange(in: string) != nil
82− }
83−
84− private static func urlSchemeRange(in string: String) -> Range<String.Index>? {
85− string.range(of: "^[A-Za-z][A-Za-z0-9+.-]*://", options: .regularExpression)
86− }
87}
70}
ParseableViewer/Views/AlertsView.swift+1−12
@@ -5,10 +5,6 @@ struct AlertsView: View {
5 @State private var alertConfig: AlertConfig?
5 @State private var alertConfig: AlertConfig?
6 @State private var isLoading = false
6 @State private var isLoading = false
7 @State private var errorMessage: String?
7 @State private var errorMessage: String?
8− /// Bumped by every load. SwiftUI cancels the previous `.task(id:)` load on a
9− /// stream switch, but that load still resumes (with a cancellation error) —
10− /// and must not touch `isLoading`, which now belongs to the newer load.
11− @State private var loadGeneration = 0
12
8
13 var body: some View {
9 var body: some View {
14 Group {
10 Group {
@@ -81,16 +77,12 @@ struct AlertsView: View {
81 private func loadAlerts(stream: String) async {
77 private func loadAlerts(stream: String) async {
82 guard let client = appState.client else { return }
78 guard let client = appState.client else { return }
83 let connID = appState.activeConnection?.id
79 let connID = appState.activeConnection?.id
84− loadGeneration &+= 1
85− let generation = loadGeneration
86 isLoading = true
80 isLoading = true
87 errorMessage = nil
81 errorMessage = nil
88 alertConfig = nil
82 alertConfig = nil
89
83
90 do {
84 do {
91 let config = try await client.getAlerts(stream: stream)
85 let config = try await client.getAlerts(stream: stream)
92− // Superseded by a newer load: leave its spinner and state alone.
93− guard generation == loadGeneration else { return }
94 // The manual Refresh/Retry buttons spawn detached Tasks not tied to
86 // The manual Refresh/Retry buttons spawn detached Tasks not tied to
95 // `.task(id: stream)` cancellation, so a slow refresh for the old stream
87 // `.task(id: stream)` cancellation, so a slow refresh for the old stream
96 // can resolve after a switch. Drop stale results. Check the connection
88 // can resolve after a switch. Drop stale results. Check the connection
@@ -102,7 +94,6 @@ struct AlertsView: View {
102 connID == appState.activeConnection?.id else { isLoading = false; return }
94 connID == appState.activeConnection?.id else { isLoading = false; return }
103 alertConfig = config
95 alertConfig = config
104 } catch {
96 } catch {
105− guard generation == loadGeneration else { return }
106 guard stream == appState.selectedStream,
97 guard stream == appState.selectedStream,
107 connID == appState.activeConnection?.id else { isLoading = false; return }
98 connID == appState.activeConnection?.id else { isLoading = false; return }
108 errorMessage = ParseableError.userFriendlyMessage(for: error)
99 errorMessage = ParseableError.userFriendlyMessage(for: error)
@@ -212,9 +203,7 @@ struct AlertRowView: View {
212 private var stateColor: Color {
203 private var stateColor: Color {
213 switch alert.state?.lowercased() {
204 switch alert.state?.lowercased() {
214 case "triggered": return .red
205 case "triggered": return .red
215− case "disabled", "silenced": return .gray
206+ case "disabled": return .gray
216− // Parseable's default, healthy state (and 2.x's "resolved") — not a warning.
217− case "not-triggered", "resolved": return .green
218 // A reported-but-unrecognized state is a genuine "needs attention" signal,
207 // A reported-but-unrecognized state is a genuine "needs attention" signal,
219 // so tint it orange; a missing state is simply unknown and stays neutral so
208 // so tint it orange; a missing state is simply unknown and stays neutral so
220 // the bell icon isn't painted as a warning for every stateless alert.
209 // the bell icon isn't painted as a warning for every stateless alert.
ParseableViewer/Views/ConnectionSheet.swift+7−27
@@ -18,10 +18,6 @@ struct ConnectionSheet: View {
18 /// retry (after a failed connect) updates it in place rather than appending a
18 /// retry (after a failed connect) updates it in place rather than appending a
19 /// duplicate.
19 /// duplicate.
20 @State private var createdConnection: ServerConnection?
20 @State private var createdConnection: ServerConnection?
21− /// Bumped on every field edit and every test run, so an in-flight Test
22− /// Connection whose fields have since changed doesn't post its (now stale)
23− /// success/failure under values that were never tested.
24− @State private var testGeneration = 0
25
21
26 enum TestResult {
22 enum TestResult {
27 case success(String)
23 case success(String)
@@ -47,7 +43,7 @@ struct ConnectionSheet: View {
47 TextField("Name:", text: $name)
43 TextField("Name:", text: $name)
48 .textFieldStyle(.roundedBorder)
44 .textFieldStyle(.roundedBorder)
49 .accessibilityLabel("Connection name")
45 .accessibilityLabel("Connection name")
50− .onChange(of: name) { _, _ in invalidateTestResult() }
46+ .onChange(of: name) { _, _ in testResult = nil }
51
47
52 TextField("Server URL:", text: $url)
48 TextField("Server URL:", text: $url)
53 .textFieldStyle(.roundedBorder)
49 .textFieldStyle(.roundedBorder)
@@ -55,7 +51,7 @@ struct ConnectionSheet: View {
55 .onChange(of: url) { _, newValue in
51 .onChange(of: url) { _, newValue in
56 urlValidationError = Self.validateURL(newValue)
52 urlValidationError = Self.validateURL(newValue)
57 // A prior test result no longer reflects the edited fields.
53 // A prior test result no longer reflects the edited fields.
58− invalidateTestResult()
54+ testResult = nil
59 }
55 }
60
56
61 if let urlError = urlValidationError, !url.isEmpty {
57 if let urlError = urlValidationError, !url.isEmpty {
@@ -67,12 +63,12 @@ struct ConnectionSheet: View {
67 TextField("Username:", text: $username)
63 TextField("Username:", text: $username)
68 .textFieldStyle(.roundedBorder)
64 .textFieldStyle(.roundedBorder)
69 .accessibilityLabel("Username")
65 .accessibilityLabel("Username")
70− .onChange(of: username) { _, _ in invalidateTestResult() }
66+ .onChange(of: username) { _, _ in testResult = nil }
71
67
72 SecureField("Password:", text: $password)
68 SecureField("Password:", text: $password)
73 .textFieldStyle(.roundedBorder)
69 .textFieldStyle(.roundedBorder)
74 .accessibilityLabel("Password")
70 .accessibilityLabel("Password")
75− .onChange(of: password) { _, _ in invalidateTestResult() }
71+ .onChange(of: password) { _, _ in testResult = nil }
76 }
72 }
77 .formStyle(.grouped)
73 .formStyle(.grouped)
78 .padding()
74 .padding()
@@ -169,16 +165,9 @@ struct ConnectionSheet: View {
169 }
165 }
170 }
166 }
171
167
172− private func invalidateTestResult() {
173− testGeneration += 1
174− testResult = nil
175− }
176−
177 private func testConnection() {
168 private func testConnection() {
178 isTesting = true
169 isTesting = true
179 testResult = nil
170 testResult = nil
180− testGeneration += 1
181− let generation = testGeneration
182
171
183 Task {
172 Task {
184 do {
173 do {
@@ -190,19 +179,14 @@ struct ConnectionSheet: View {
190 )
179 )
191 let client = try ParseableClient(connection: conn)
180 let client = try ParseableClient(connection: conn)
192 try await client.checkHealth()
181 try await client.checkHealth()
193− // The health endpoint doesn't check credentials; see
194− // AppState.verifyCredentials.
195− try await AppState.verifyCredentials(with: client)
196 await MainActor.run {
182 await MainActor.run {
197− isTesting = false
198− guard generation == testGeneration else { return }
199 testResult = .success("Connection successful")
183 testResult = .success("Connection successful")
184+ isTesting = false
200 }
185 }
201 } catch {
186 } catch {
202 await MainActor.run {
187 await MainActor.run {
203− isTesting = false
204− guard generation == testGeneration else { return }
205 testResult = .failure(ParseableError.userFriendlyMessage(for: error))
188 testResult = .failure(ParseableError.userFriendlyMessage(for: error))
189+ isTesting = false
206 }
190 }
207 }
191 }
208 }
192 }
@@ -237,10 +221,6 @@ struct ConnectionSheet: View {
237 dismiss()
221 dismiss()
238 } else {
222 } else {
239 testResult = .failure(appState.errorMessage ?? "Connection failed")
223 testResult = .failure(appState.errorMessage ?? "Connection failed")
240− // The sheet reports the failure inline; drop the app-wide alert
241− // performConnect also raised, which would otherwise surface
242− // behind/after the sheet (or twice, from the Settings window).
243− appState.showError = false
244 }
224 }
245 }
225 }
246 }
226 }
@@ -251,7 +231,7 @@ struct ConnectionSheet: View {
251 guard !trimmed.isEmpty else { return nil }
231 guard !trimmed.isEmpty else { return nil }
252
232
253 var normalized = trimmed
233 var normalized = trimmed
254− if !ServerConnection.hasURLScheme(normalized) {
234+ if !normalized.hasPrefix("http://") && !normalized.hasPrefix("https://") {
255 normalized = "https://\(normalized)"
235 normalized = "https://\(normalized)"
256 }
236 }
257
237
ParseableViewer/Views/LogTableView.swift+6−53
@@ -315,23 +315,7 @@ struct LogTableView: View {
315 }
315 }
316 .onChange(of: sortColumn) { _, _ in debouncedRebuildSort() }
316 .onChange(of: sortColumn) { _, _ in debouncedRebuildSort() }
317 .onChange(of: sortAscending) { _, _ in debouncedRebuildSort() }
317 .onChange(of: sortAscending) { _, _ in debouncedRebuildSort() }
318− .onChange(of: selectedRecord) { _, newValue in
319− // The owner can drop the selection on its own (QueryViewModel
320− // clears it after every query). When the new result set equals the
321− // old one, `onChange(of: records)` doesn't fire, so nothing would
322− // reconcile the row highlight: the row stayed highlighted with no
323− // detail pane, and the next click on it merely "deselected" it.
324− if newValue == nil { selectedIndex = nil }
325− }
326 .onAppear {
318 .onAppear {
327− // This branch is unmounted while results are empty (e.g. across a
328− // stream switch, which clears them first), so `onChange(of: columns)`
329− // never sees the switch. Drop a sort column the new columns don't
330− // have — or hide — before sorting, or rows would be ordered by an
331− // invisible column with no header showing the sort.
332− if let sortColumn, !columns.contains(sortColumn) {
333− self.sortColumn = nil
334− }
335 recomputeColumnWidths(columns: columns, records: records)
319 recomputeColumnWidths(columns: columns, records: records)
336 rebuildSort()
320 rebuildSort()
337 }
321 }
@@ -417,9 +401,6 @@ struct LogTableView: View {
417 }
401 }
418
402
419 private func rebuildSort() {
403 private func rebuildSort() {
420− // A debounced rebuild scheduled before the table unmounted must not land
421− // after (and overwrite) this synchronous one.
422− sortTask?.cancel()
423 let sevCols = buildSeverityColumnSet(columns: columns)
404 let sevCols = buildSeverityColumnSet(columns: columns)
424 let enumerated = Array(records.enumerated())
405 let enumerated = Array(records.enumerated())
425 let sorted: [(offset: Int, element: LogRecord)]
406 let sorted: [(offset: Int, element: LogRecord)]
@@ -495,28 +476,12 @@ struct LogHeaderView: View {
495
476
496 @State private var draggedColumn: String?
477 @State private var draggedColumn: String?
497 @State private var dropTargetColumn: String?
478 @State private var dropTargetColumn: String?
498− /// `.contextMenu`'s builder runs during body evaluation, so the filter menus
499− /// compute their values while the view is being rendered. Writing an `@State`
500− /// dictionary from there is "modifying state during view update" (undefined
501− /// behavior, and it re-invalidates the header). The cache is therefore a plain
502− /// reference that isn't observed; `recordsGeneration` — bumped outside body
503− /// evaluation — is what invalidates it and triggers the re-render.
504− @State private var uniqueValuesCache = UniqueValuesCache()
479+ @State private var uniqueValuesCache: [String: [JSONValue]] = [:]
505− @State private var recordsGeneration = 0
506−
507− private final class UniqueValuesCache {
508− var generation = -1
509− var values: [String: [JSONValue]] = [:]
510− }
511
480
512 private static let maxFilterValues = 20
481 private static let maxFilterValues = 20
513
482
514 private func uniqueValues(for column: String) -> [JSONValue] {
483 private func uniqueValues(for column: String) -> [JSONValue] {
515− if uniqueValuesCache.generation != recordsGeneration {
516− uniqueValuesCache.generation = recordsGeneration
517− uniqueValuesCache.values = [:]
518− }
519− if let cached = uniqueValuesCache.values[column] {
484+ if let cached = uniqueValuesCache[column] {
520 return cached
485 return cached
521 }
486 }
522 var seen = Set<JSONValue>()
487 var seen = Set<JSONValue>()
@@ -528,7 +493,7 @@ struct LogHeaderView: View {
528 }
493 }
529 }
494 }
530 let sorted = result.sorted()
495 let sorted = result.sorted()
531− uniqueValuesCache.values[column] = sorted
496+ uniqueValuesCache[column] = sorted
532 return sorted
497 return sorted
533 }
498 }
534
499
@@ -671,7 +636,7 @@ struct LogHeaderView: View {
671 .background(Color(nsColor: .controlBackgroundColor))
636 .background(Color(nsColor: .controlBackgroundColor))
672 .border(Color.secondary.opacity(0.2), width: 0.5)
637 .border(Color.secondary.opacity(0.2), width: 0.5)
673 .onChange(of: records) { _, _ in
638 .onChange(of: records) { _, _ in
674− recordsGeneration &+= 1
639+ uniqueValuesCache = [:]
675 }
640 }
676 }
641 }
677}
642}
@@ -704,26 +669,14 @@ private struct ColumnDropDelegate: DropDelegate {
704 }
669 }
705
670
706 func performDrop(info: DropInfo) -> Bool {
671 func performDrop(info: DropInfo) -> Bool {
707− guard let dragged = draggedColumn, dragged != column,
672+ guard let dragged = draggedColumn, dragged != column else {
708− let provider = info.itemProviders(for: [UTType.plainText]).first else {
709 draggedColumn = nil
673 draggedColumn = nil
710 dropTargetColumn = nil
674 dropTargetColumn = nil
711 return false
675 return false
712 }
676 }
677+ onMoveColumn?(dragged, column)
713 draggedColumn = nil
678 draggedColumn = nil
714 dropTargetColumn = nil
679 dropTargetColumn = nil
715− // `draggedColumn` is only cleared by a drop on a header, so a header drag
716− // that was cancelled (or dropped elsewhere) leaves it set, and any later
717− // plain-text drag onto a header would move that stale column. Only move
718− // when the dropped payload really is the column header being dragged.
719− let target = column
720− let move = onMoveColumn
721− _ = provider.loadObject(ofClass: NSString.self) { object, _ in
722− guard let payload = object as? NSString, payload as String == dragged else { return }
723− DispatchQueue.main.async {
724− move?(dragged, target)
725− }
726− }
727 return true
680 return true
728 }
681 }
729
682
ParseableViewer/Views/ServerInfoView.swift+2−12
@@ -9,9 +9,6 @@ struct ServerInfoView: View {
9 @State private var isLoading = true
9 @State private var isLoading = true
10 @State private var isHealthy = false
10 @State private var isHealthy = false
11 @State private var errorMessage: String?
11 @State private var errorMessage: String?
12− /// Bumped by every load so a superseded (cancelled) load can't clear the
13− /// newer load's spinner or overwrite its results.
14− @State private var loadGeneration = 0
15
12
16 var body: some View {
13 var body: some View {
17 ScrollView {
14 ScrollView {
@@ -22,7 +19,7 @@ struct ServerInfoView: View {
22 .fontWeight(.semibold)
19 .fontWeight(.semibold)
23 Spacer()
20 Spacer()
24 Button {
21 Button {
25− Task { await loadInfo(forceRefresh: true) }
22+ Task { await loadInfo() }
26 } label: {
23 } label: {
27 Image(systemName: "arrow.clockwise")
24 Image(systemName: "arrow.clockwise")
28 }
25 }
@@ -156,18 +153,12 @@ struct ServerInfoView: View {
156 }
153 }
157 }
154 }
158
155
159− private func loadInfo(forceRefresh: Bool = false) async {
156+ private func loadInfo() async {
160 // Clear isLoading on the no-client path: since isLoading now starts `true`
157 // Clear isLoading on the no-client path: since isLoading now starts `true`
161 // (to avoid a red "Unhealthy" flash before the first check), an early return
158 // (to avoid a red "Unhealthy" flash before the first check), an early return
162 // without resetting it would wedge the spinner permanently.
159 // without resetting it would wedge the spinner permanently.
163 guard let client = appState.client else { isLoading = false; return }
160 guard let client = appState.client else { isLoading = false; return }
164− // `getAbout()` is cached for 60 s; the Refresh button must bypass that.
165− if forceRefresh {
166− await client.invalidateCache()
167− }
168 let connID = appState.activeConnection?.id
161 let connID = appState.activeConnection?.id
169− loadGeneration &+= 1
170− let generation = loadGeneration
171 isLoading = true
162 isLoading = true
172 errorMessage = nil
163 errorMessage = nil
173 // Seed from the app-wide cache so first load isn't blank, but never fall
164 // Seed from the app-wide cache so first load isn't blank, but never fall
@@ -198,7 +189,6 @@ struct ServerInfoView: View {
198 // load for the previous server can't overwrite the current one's state.
189 // load for the previous server can't overwrite the current one's state.
199 // Still clear isLoading: this task owns the spinner it set, and leaving it
190 // Still clear isLoading: this task owns the spinner it set, and leaving it
200 // true on the stale path wedges the ProgressView and disables Refresh.
191 // true on the stale path wedges the ProgressView and disables Refresh.
201− guard generation == loadGeneration else { return }
202 guard connID == appState.activeConnection?.id else { isLoading = false; return }
192 guard connID == appState.activeConnection?.id else { isLoading = false; return }
203 isHealthy = healthy
193 isHealthy = healthy
204 about = aboutValue
194 about = aboutValue
ParseableViewer/Views/SidebarView.swift+1−19
@@ -6,14 +6,6 @@ struct SidebarView: View {
6 @State private var newStreamName = ""
6 @State private var newStreamName = ""
7 @State private var showDeleteConfirm = false
7 @State private var showDeleteConfirm = false
8 @State private var streamToDelete: String?
8 @State private var streamToDelete: String?
9− /// The connection `streamToDelete` was picked on. Stream names aren't unique
10− /// across servers, and the delete runs against whatever client is current
11− /// when the user confirms — so a server switch while the stats lookup was in
12− /// flight could otherwise delete a same-named stream on the *new* server.
13− @State private var streamToDeleteConnectionID: UUID?
14− /// The client the stream was picked with. Editing the active connection's URL
15− /// keeps its id but installs a new client for a possibly different server.
16− @State private var streamToDeleteClient: ParseableClient?
17 @State private var deleteStreamDetail: String?
9 @State private var deleteStreamDetail: String?
18
10
19 /// Validates a stream name, returning an error message or nil if valid.
11 /// Validates a stream name, returning an error message or nil if valid.
@@ -73,10 +65,7 @@ struct SidebarView: View {
73 // would show the wrong stats on a destructive
65 // would show the wrong stats on a destructive
74 // confirmation.
66 // confirmation.
75 let target = stream.name
67 let target = stream.name
76− let targetConnectionID = appState.activeConnection?.id
77 streamToDelete = target
68 streamToDelete = target
78− streamToDeleteConnectionID = targetConnectionID
79− streamToDeleteClient = appState.client
80 deleteStreamDetail = nil
69 deleteStreamDetail = nil
81 Task {
70 Task {
82 if let client = appState.client,
71 if let client = appState.client,
@@ -92,9 +81,7 @@ struct SidebarView: View {
92 deleteStreamDetail = parts.joined(separator: ", ")
81 deleteStreamDetail = parts.joined(separator: ", ")
93 }
82 }
94 }
83 }
95− if streamToDelete == target,
84+ if streamToDelete == target {
96− appState.activeConnection?.id == targetConnectionID,
97− appState.client === streamToDeleteClient {
98 showDeleteConfirm = true
85 showDeleteConfirm = true
99 }
86 }
100 }
87 }
@@ -200,11 +187,6 @@ struct SidebarView: View {
200 .alert("Delete Stream", isPresented: $showDeleteConfirm) {
187 .alert("Delete Stream", isPresented: $showDeleteConfirm) {
201 Button("Delete", role: .destructive) {
188 Button("Delete", role: .destructive) {
202 if let name = streamToDelete {
189 if let name = streamToDelete {
203− guard appState.activeConnection?.id == streamToDeleteConnectionID,
204− appState.client === streamToDeleteClient else {
205− appState.showErrorMessage("The server changed since \"\(name)\" was selected, so it was not deleted.")
206− return
207− }
208 Task {
190 Task {
209 do {
191 do {
210 try await appState.deleteStream(name: name)
192 try await appState.deleteStream(name: name)
ParseableViewer/Views/StreamDetailView.swift+4−18
@@ -8,9 +8,6 @@ struct StreamDetailView: View {
8 @State private var retention: [RetentionConfig] = []
8 @State private var retention: [RetentionConfig] = []
9 @State private var isLoading = false
9 @State private var isLoading = false
10 @State private var errorMessage: String?
10 @State private var errorMessage: String?
11− /// Bumped by every load. A superseded load (its `.task(id:)` cancelled by a
12− /// stream switch) still resumes, and must not clear the newer load's spinner.
13− @State private var loadGeneration = 0
14
11
15 var body: some View {
12 var body: some View {
16 Group {
13 Group {
@@ -28,7 +25,7 @@ struct StreamDetailView: View {
28 Spacer()
25 Spacer()
29
26
30 Button {
27 Button {
31− Task { await loadData(stream: stream, forceRefresh: true) }
28+ Task { await loadData(stream: stream) }
32 } label: {
29 } label: {
33 Image(systemName: "arrow.clockwise")
30 Image(systemName: "arrow.clockwise")
34 }
31 }
@@ -47,7 +44,7 @@ struct StreamDetailView: View {
47 Text(error)
44 Text(error)
48 Spacer()
45 Spacer()
49 Button("Retry") {
46 Button("Retry") {
50− Task { await loadData(stream: stream, forceRefresh: true) }
47+ Task { await loadData(stream: stream) }
51 }
48 }
52 .buttonStyle(.bordered)
49 .buttonStyle(.bordered)
53 .controlSize(.small)
50 .controlSize(.small)
@@ -177,22 +174,13 @@ struct StreamDetailView: View {
177 }
174 }
178 }
175 }
179
176
180− private func loadData(stream: String, forceRefresh: Bool = false) async {
177+ private func loadData(stream: String) async {
181 guard let client = appState.client else { return }
178 guard let client = appState.client else { return }
182− // The client caches schema/stats/info for 60 s. That's right for the
183− // automatic load on appear, but an explicit Refresh/Retry must hit the
184− // server — otherwise it repaints the same cached numbers and looks like a
185− // refresh that found nothing new.
186− if forceRefresh {
187− await client.invalidateCache()
188− }
189 // Capture the connection this fetch belongs to. Two servers can expose a
179 // Capture the connection this fetch belongs to. Two servers can expose a
190 // same-named stream, so guarding on the stream name alone would let a
180 // same-named stream, so guarding on the stream name alone would let a
191 // slow fetch write the previous server's data under the new server's
181 // slow fetch write the previous server's data under the new server's
192 // stream after a server switch.
182 // stream after a server switch.
193 let connID = appState.activeConnection?.id
183 let connID = appState.activeConnection?.id
194− loadGeneration &+= 1
195− let generation = loadGeneration
196 isLoading = true
184 isLoading = true
197 errorMessage = nil
185 errorMessage = nil
198 // Clear previous stream's data so it isn't shown under the new header
186 // Clear previous stream's data so it isn't shown under the new header
@@ -228,9 +216,7 @@ struct StreamDetailView: View {
228 // resolve after the user switched. Drop stale results instead of writing
216 // resolve after the user switched. Drop stale results instead of writing
229 // them under the new stream's header. Also check the connection so a
217 // them under the new stream's header. Also check the connection so a
230 // same-named stream on a different server doesn't accept the old server's
218 // same-named stream on a different server doesn't accept the old server's
231− // data. Reset `isLoading` on the stale path or the spinner wedges forever —
219+ // data. Reset `isLoading` on the stale path or the spinner wedges forever.
232− // unless a newer load has started, which owns the spinner now.
233− guard generation == loadGeneration else { return }
234 guard stream == appState.selectedStream, connID == appState.activeConnection?.id else {
220 guard stream == appState.selectedStream, connID == appState.activeConnection?.id else {
235 isLoading = false
221 isLoading = false
236 return
222 return
ParseableViewer/Views/UsersView.swift−6
@@ -5,9 +5,6 @@ struct UsersView: View {
5 @State private var users: [UserInfo] = []
5 @State private var users: [UserInfo] = []
6 @State private var isLoading = false
6 @State private var isLoading = false
7 @State private var errorMessage: String?
7 @State private var errorMessage: String?
8− /// Bumped by every load so a superseded (cancelled) load can't clear the
9− /// newer load's spinner.
10− @State private var loadGeneration = 0
11
8
12 var body: some View {
9 var body: some View {
13 VStack(spacing: 0) {
10 VStack(spacing: 0) {
@@ -85,8 +82,6 @@ struct UsersView: View {
85 private func loadUsers() async {
82 private func loadUsers() async {
86 guard let client = appState.client else { return }
83 guard let client = appState.client else { return }
87 let connID = appState.activeConnection?.id
84 let connID = appState.activeConnection?.id
88− loadGeneration &+= 1
89− let generation = loadGeneration
90 isLoading = true
85 isLoading = true
91 errorMessage = nil
86 errorMessage = nil
92 // Clear the previous server's list up front so it can't briefly show through
87 // Clear the previous server's list up front so it can't briefly show through
@@ -107,7 +102,6 @@ struct UsersView: View {
107 // Drop results if the active connection changed while awaiting. Still clear
102 // Drop results if the active connection changed while awaiting. Still clear
108 // isLoading: this task set the spinner, so leaving it true on the stale path
103 // isLoading: this task set the spinner, so leaving it true on the stale path
109 // wedges the ProgressView and disables Refresh.
104 // wedges the ProgressView and disables Refresh.
110− guard generation == loadGeneration else { return }
111 guard connID == appState.activeConnection?.id else { isLoading = false; return }
105 guard connID == appState.activeConnection?.id else { isLoading = false; return }
112 if let loaded { users = loaded }
106 if let loaded { users = loaded }
113 errorMessage = loadError
107 errorMessage = loadError
ParseableViewerTests/ServerConnectionTests.swift−10
@@ -77,14 +77,4 @@ final class ServerConnectionTests: XCTestCase {
77 let conn = ServerConnection(name: "test", url: "https://", username: "admin", password: "pass")
77 let conn = ServerConnection(name: "test", url: "https://", username: "admin", password: "pass")
78 XCTAssertNil(conn.baseURL)
78 XCTAssertNil(conn.baseURL)
79 }
79 }
80−
81− func testBaseURLAcceptsUppercaseScheme() {
82− let conn = ServerConnection(name: "t", url: "HTTP://10.0.0.5:8000", username: "u", password: "p")
83− XCTAssertEqual(conn.baseURL?.absoluteString, "http://10.0.0.5:8000")
84− }
85−
86− func testBaseURLRejectsNonHTTPScheme() {
87− let conn = ServerConnection(name: "t", url: "ftp://example.com", username: "u", password: "p")
88− XCTAssertNil(conn.baseURL)
89− }
90}
80}