summaryrefslogtreecommitdiff
path: root/Hutch/Views/Builds/BuildListViewModel.swift
blob: 8d0f96137e8256aabd9ef1a6d7d7e65fdfe0d3d4 (plain) (blame)
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
import Foundation

// MARK: - Response types (file-private to avoid @MainActor Decodable issues)

private struct JobsResponse: Decodable, Sendable {
    let jobs: JobsPage
}

private struct JobsPage: Decodable, Sendable {
    let results: [JobSummary]
    let cursor: String?
}

private struct SubmitJobResponse: Decodable, Sendable {
    let submit: SubmittedJob
}

private struct SubmittedJob: Decodable, Sendable {
    let id: Int
}

// MARK: - View Model

@Observable
@MainActor
final class BuildListViewModel {

    private(set) var jobs: [JobSummary] = []
    private(set) var isLoading = false
    private(set) var isLoadingMore = false
    private(set) var isRefreshing = false
    private(set) var isSubmitting = false
    var error: String?

    private var cursor: String?
    private var hasMore = true
    private let client: SRHTClient

    private static let cacheKey = "builds.jobs"

    init(client: SRHTClient) {
        self.client = client
    }

    // MARK: - Query

    private static let query = """
    query jobs($cursor: Cursor) {
        jobs(cursor: $cursor) {
            results {
                id
                created
                updated
                status
                note
                tags
                visibility
                image
                tasks { name status }
            }
            cursor
        }
    }
    """

    private static let submitMutation = """
    mutation submit($manifest: String!, $tags: [String!], $note: String, $secrets: Boolean, $execute: Boolean, $visibility: Visibility) {
        submit(manifest: $manifest, tags: $tags, note: $note, secrets: $secrets, execute: $execute, visibility: $visibility) {
            id
        }
    }
    """

    // MARK: - Public API

    /// Fetch the first page of jobs. Shows cached data instantly if available,
    /// then refreshes from the network in the background.
    func loadJobs() async {
        // Show cached data immediately on first load
        if jobs.isEmpty {
            loadFromCache()
        }

        if jobs.isEmpty {
            isLoading = true
        } else {
            isRefreshing = true
        }
        error = nil
        cursor = nil
        hasMore = true

        do {
            let page = try await fetchPage(cursor: nil, useCache: true)
            jobs = page.results
            cursor = page.cursor
            hasMore = page.cursor != nil
        } catch {
            if jobs.isEmpty {
                self.error = error.localizedDescription
            }
        }

        isLoading = false
        isRefreshing = false
    }

    func loadMoreIfNeeded(currentItem: JobSummary) async {
        guard let last = jobs.last,
              last.id == currentItem.id,
              hasMore,
              !isLoadingMore else {
            return
        }

        isLoadingMore = true

        do {
            let page = try await fetchPage(cursor: cursor, useCache: false)
            jobs.append(contentsOf: page.results)
            cursor = page.cursor
            hasMore = page.cursor != nil
        } catch {
            self.error = error.localizedDescription
        }

        isLoadingMore = false
    }

    func submitBuild(
        manifest: String,
        tags: [String],
        note: String,
        secrets: Bool,
        execute: Bool,
        visibility: Visibility
    ) async -> Int? {
        guard !isSubmitting else { return nil }

        let trimmedManifest = manifest.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmedManifest.isEmpty else {
            error = "Paste a build manifest."
            return nil
        }

        isSubmitting = true
        error = nil
        defer { isSubmitting = false }

        var variables: [String: any Sendable] = [
            "manifest": trimmedManifest,
            "secrets": secrets,
            "execute": execute,
            "visibility": visibility.rawValue
        ]
        if !tags.isEmpty {
            variables["tags"] = tags
        }
        let trimmedNote = note.trimmingCharacters(in: .whitespacesAndNewlines)
        if !trimmedNote.isEmpty {
            variables["note"] = trimmedNote
        }

        do {
            let result = try await client.execute(
                service: .builds,
                query: Self.submitMutation,
                variables: variables,
                responseType: SubmitJobResponse.self
            )
            await loadJobs()
            return result.submit.id
        } catch {
            self.error = "Couldn’t submit the build. \(error.localizedDescription)"
            return nil
        }
    }

    // MARK: - Private

    private func fetchPage(cursor: String?, useCache: Bool) async throws -> JobsPage {
        var variables: [String: any Sendable] = [:]
        if let cursor {
            variables["cursor"] = cursor
        }

        if useCache && cursor == nil {
            let result = try await client.executeAndCache(
                service: .builds,
                query: Self.query,
                variables: variables.isEmpty ? nil : variables,
                responseType: JobsResponse.self,
                cacheKey: Self.cacheKey
            )
            return result.jobs
        } else {
            let result = try await client.execute(
                service: .builds,
                query: Self.query,
                variables: variables.isEmpty ? nil : variables,
                responseType: JobsResponse.self
            )
            return result.jobs
        }
    }

    private func loadFromCache() {
        guard let data = client.responseCache.get(forKey: Self.cacheKey) else { return }
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .srhtFlexible
        if let response = try? decoder.decode(
            GraphQLResponse<JobsResponse>.self,
            from: data
        ), let page = response.data?.jobs {
            jobs = page.results
            cursor = page.cursor
            hasMore = page.cursor != nil
        }
    }
}