aboutsummaryrefslogtreecommitdiff
path: root/Hutch/Networking/SRHTClient.swift
blob: 37fd6b8ed762d70847b9df9c8b52158e0885c0db (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
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
import CryptoKit
import Foundation
import os

private let logger = Logger(subsystem: "net.cleberg.Hutch", category: "SRHTClient")

struct MultipartUploadFile: Sendable {
    let variablePath: String
    let fileData: Data
    let fileName: String
    let mimeType: String
}

/// Placeholder type for decoding GraphQL error responses when the data shape is unknown.
private struct EmptyData: Decodable {}

/// A lightweight GraphQL client for SourceHut services.
/// All requests require a personal access token set via ``token``.
final class SRHTClient: Sendable {

    private let session: URLSession
    private let decoder: JSONDecoder
    private let encoder: JSONEncoder
    private let cache: any APICache
    private let requestCoalescer = RequestCoalescer()

    /// The personal access token used for `Authorization: Bearer` headers.
    /// Loaded from Keychain on init; can be refreshed via ``reloadToken()``.
    private let tokenLock: OSAllocatedUnfairLock<String?>

    /// In-memory response cache for stale-while-revalidate pattern.
    let responseCache = ResponseCache()

    var hasToken: Bool {
        tokenLock.withLock { $0 != nil }
    }

    init(
        session: URLSession = .shared,
        token: String? = nil,
        cache: (any APICache)? = nil
    ) {
        self.session = session
        self.decoder = JSONDecoder()
        self.decoder.dateDecodingStrategy = .srhtFlexible
        self.encoder = JSONEncoder()
        self.tokenLock = OSAllocatedUnfairLock(initialState: token)
        self.cache = cache ?? PersistentAPICache(
            configuration: .accountScoped(accountID: token.map { Self.tokenCacheScope($0) } ?? "anonymous")
        )
    }

    /// Update the stored token (e.g. after the user saves a new one in Keychain).
    func setToken(_ token: String?) {
        tokenLock.withLock { $0 = token }
    }

    /// Execute a GraphQL query or mutation against a SourceHut service.
    ///
    /// - Parameters:
    ///   - service: The target SourceHut service (determines the endpoint URL).
    ///   - query: The GraphQL query or mutation string.
    ///   - variables: Optional dictionary of GraphQL variables.
    ///   - responseType: The expected `Decodable` type nested under `data`.
    /// - Returns: The decoded `data` payload.
    func execute<T: Decodable>(
        service: SRHTService,
        query: String,
        variables: [String: any Sendable]? = nil,
        responseType _: T.Type
    ) async throws -> T {
        guard let token = tokenLock.withLock({ $0 }), !token.isEmpty else {
            throw SRHTError.unauthorized
        }

        // Build request
        var request = URLRequest(url: service.url)
        request.httpMethod = "POST"
        request.setValue(Bundle.main.hutchUserAgent, forHTTPHeaderField: "User-Agent")
        request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let body = GraphQLRequestBody(
            query: query,
            variables: variables?.mapValues { AnyCodable($0) }
        )
        request.httpBody = try encoder.encode(body)

        // Execute
        let (data, response): (Data, URLResponse)
        do {
            (data, response) = try await session.data(for: request)
        } catch {
            throw SRHTError.networkError(error)
        }

        // Check HTTP status
        if let http = response as? HTTPURLResponse {
            if http.statusCode == 401 {
                throw SRHTError.unauthorized
            }
            if !(200...299).contains(http.statusCode) {
                try throwGraphQLErrorsIfPresent(in: data)
                throw SRHTError.httpError(http.statusCode)
            }
        }

        try throwGraphQLErrorsIfPresent(in: data)

        // Decode GraphQL response envelope
        let graphQLResponse: GraphQLResponse<T>
        do {
            graphQLResponse = try decoder.decode(GraphQLResponse<T>.self, from: data)
        } catch {
            #if DEBUG
            let responseBody = String(data: data, encoding: .utf8) ?? "<non-utf8 response>"
            let variablesDescription = String(describing: variables)
            if let decodingError = error as? DecodingError {
                logger.error(
                    """
                    Decoding failed for \(String(describing: T.self), privacy: .public)
                    service: \(service.rawValue, privacy: .public)
                    query:
                    \(query, privacy: .public)
                    variables:
                    \(variablesDescription, privacy: .public)
                    decodingError:
                    \(String(describing: decodingError), privacy: .public)
                    response:
                    \(responseBody, privacy: .public)
                    """
                )
            } else {
                logger.error(
                    """
                    Decoding failed for \(String(describing: T.self), privacy: .public)
                    service: \(service.rawValue, privacy: .public)
                    query:
                    \(query, privacy: .public)
                    variables:
                    \(variablesDescription, privacy: .public)
                    error:
                    \(String(describing: error), privacy: .public)
                    response:
                    \(responseBody, privacy: .public)
                    """
                )
            }
            #else
            logger.error("Decoding failed for \(String(describing: T.self), privacy: .public): \(error, privacy: .public)")
            #endif
            throw SRHTError.decodingError(error)
        }

        // Surface GraphQL-level errors
        if let errors = graphQLResponse.errors, !errors.isEmpty {
            throw SRHTError.graphQLErrors(errors)
        }

        guard let result = graphQLResponse.data else {
            throw SRHTError.decodingError(
                DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "No data in response"))
            )
        }

        return result
    }

    func executeCached<T: Decodable>(
        service: SRHTService,
        query: String,
        variables: [String: any Sendable]? = nil,
        responseType _: T.Type,
        cacheKey: String,
        resourceType: CacheResourceType,
        ttl: TimeInterval,
        policy: CachePolicy = .cacheFirstThenRefresh
    ) async throws -> CachedValue<T> {
        switch policy {
        case .networkOnly:
            let data = try await performGraphQLRequest(
                service: service,
                query: query,
                variables: variables
            )
            let value: T = try decodeGraphQLData(data, service: service, query: query, variables: variables)
            return CachedValue(value: value, metadata: nil, source: .network)

        case .cacheOnly:
            let entry = try await cache.read(cacheKey: cacheKey)
            let value: T = try decodeGraphQLData(entry.payload, service: service, query: query, variables: variables)
            return CachedValue(value: value, metadata: entry.metadata, source: .cache)

        case .cacheFirstThenRefresh:
            if let entry = try? await cache.read(cacheKey: cacheKey) {
                let value: T = try decodeGraphQLData(entry.payload, service: service, query: query, variables: variables)
                if entry.metadata.isExpired() {
                    Task.detached { [self] in
                        _ = try? await self.fetchAndCacheGraphQLData(
                            service: service,
                            query: query,
                            variables: variables,
                            cacheKey: cacheKey,
                            resourceType: resourceType,
                            ttl: ttl
                        )
                    }
                }
                return CachedValue(value: value, metadata: entry.metadata, source: .cache)
            }

            let (value, metadata): (T, CacheEntryMetadata?) = try await fetchAndCacheGraphQL(
                service: service,
                query: query,
                variables: variables,
                cacheKey: cacheKey,
                resourceType: resourceType,
                ttl: ttl
            )
            return CachedValue(value: value, metadata: metadata, source: .network)

        case .refreshIgnoringCache:
            let (value, metadata): (T, CacheEntryMetadata?) = try await fetchAndCacheGraphQL(
                service: service,
                query: query,
                variables: variables,
                cacheKey: cacheKey,
                resourceType: resourceType,
                ttl: ttl
            )
            return CachedValue(value: value, metadata: metadata, source: .network)
        }
    }

    func fetchCachedText(
        url: URL,
        cacheKey: String,
        resourceType: CacheResourceType = .buildLog,
        ttl: TimeInterval,
        policy: CachePolicy = .cacheFirstThenRefresh
    ) async throws -> CachedValue<String> {
        switch policy {
        case .networkOnly:
            let text = try await fetchText(url: url)
            return CachedValue(value: text, metadata: nil, source: .network)
        case .cacheOnly:
            let entry = try await cache.read(cacheKey: cacheKey)
            guard let text = String(data: entry.payload, encoding: .utf8) else {
                throw SRHTError.decodingError(
                    DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Cached text is not UTF-8"))
                )
            }
            return CachedValue(value: text, metadata: entry.metadata, source: .cache)
        case .cacheFirstThenRefresh:
            if let entry = try? await cache.read(cacheKey: cacheKey),
               let text = String(data: entry.payload, encoding: .utf8) {
                if entry.metadata.isExpired() {
                    Task.detached { [self] in
                        _ = try? await self.fetchAndCacheText(url: url, cacheKey: cacheKey, resourceType: resourceType, ttl: ttl)
                    }
                }
                return CachedValue(value: text, metadata: entry.metadata, source: .cache)
            }
            let (text, metadata) = try await fetchAndCacheText(url: url, cacheKey: cacheKey, resourceType: resourceType, ttl: ttl)
            return CachedValue(value: text, metadata: metadata, source: .network)
        case .refreshIgnoringCache:
            let (text, metadata) = try await fetchAndCacheText(url: url, cacheKey: cacheKey, resourceType: resourceType, ttl: ttl)
            return CachedValue(value: text, metadata: metadata, source: .network)
        }
    }

    func cachedPayload(forKey cacheKey: String) async -> Data? {
        if let entry = try? await cache.read(cacheKey: cacheKey) {
            return entry.payload
        }
        return responseCache.get(forKey: cacheKey)
    }

    func invalidateCache(prefix: String) async {
        await cache.removeByPrefix(prefix)
    }

    func removeCachedValue(forKey cacheKey: String) async {
        await cache.remove(cacheKey: cacheKey)
        responseCache.remove(forKey: cacheKey)
    }

    func clearPersistentCache() async {
        await cache.clearAll()
        responseCache.clear()
    }

    // MARK: - Multipart Upload

    /// Execute a GraphQL mutation with a file upload using the
    /// graphql-multipart-request-spec (multipart/form-data).
    ///
    /// - Parameters:
    ///   - service: The target SourceHut service.
    ///   - query: The GraphQL mutation string.
    ///   - variables: Variables dict; the file variable should be set to `nil`.
    ///   - file: Multipart file payload (`variablePath` is the dot-separated GraphQL variable, e.g. `input.avatar`).
    ///   - responseType: The expected `Decodable` type nested under `data`.
    func executeMultipart<T: Decodable>(
        service: SRHTService,
        query: String,
        variables: [String: any Sendable],
        file: MultipartUploadFile,
        responseType _: T.Type
    ) async throws -> T {
        guard let token = tokenLock.withLock({ $0 }), !token.isEmpty else {
            throw SRHTError.unauthorized
        }

        let boundary = "Boundary-\(UUID().uuidString)"

        var request = URLRequest(url: service.url)
        request.httpMethod = "POST"
        request.setValue(Bundle.main.hutchUserAgent, forHTTPHeaderField: "User-Agent")
        request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

        // Build the operations JSON (file variable mapped to null)
        let operationsBody = GraphQLRequestBody(
            query: query,
            variables: variables.mapValues { AnyCodable($0) }
        )
        let operationsData = try encoder.encode(operationsBody)

        // Build the map JSON: { "0": ["variables.<variablePath>"] }
        let mapDict = ["0": ["variables.\(file.variablePath)"]]
        let mapData = try encoder.encode(mapDict)

        // Assemble multipart body
        var body = Data()

        // Part: operations
        body.append("--\(boundary)\r\n")
        body.append("Content-Disposition: form-data; name=\"operations\"\r\n")
        body.append("Content-Type: application/json\r\n\r\n")
        body.append(operationsData)
        body.append("\r\n")

        // Part: map
        body.append("--\(boundary)\r\n")
        body.append("Content-Disposition: form-data; name=\"map\"\r\n")
        body.append("Content-Type: application/json\r\n\r\n")
        body.append(mapData)
        body.append("\r\n")

        // Part: file
        body.append("--\(boundary)\r\n")
        body.append("Content-Disposition: form-data; name=\"0\"; filename=\"\(file.fileName)\"\r\n")
        body.append("Content-Type: \(file.mimeType)\r\n\r\n")
        body.append(file.fileData)
        body.append("\r\n")

        // Closing boundary
        body.append("--\(boundary)--\r\n")

        request.httpBody = body

        let (data, response): (Data, URLResponse)
        do {
            (data, response) = try await session.data(for: request)
        } catch {
            throw SRHTError.networkError(error)
        }

        if let http = response as? HTTPURLResponse {
            if http.statusCode == 401 {
                throw SRHTError.unauthorized
            }
            if !(200...299).contains(http.statusCode) {
                try throwGraphQLErrorsIfPresent(in: data)
                throw SRHTError.httpError(http.statusCode)
            }
        }

        try throwGraphQLErrorsIfPresent(in: data)

        let graphQLResponse: GraphQLResponse<T>
        do {
            graphQLResponse = try decoder.decode(GraphQLResponse<T>.self, from: data)
        } catch {
            #if DEBUG
            let responseBody = String(data: data, encoding: .utf8) ?? "<non-utf8 response>"
            let variablesDescription = String(describing: variables)
            if let decodingError = error as? DecodingError {
                logger.error(
                    """
                    Decoding failed for \(String(describing: T.self), privacy: .public)
                    service: \(service.rawValue, privacy: .public)
                    query:
                    \(query, privacy: .public)
                    variables:
                    \(variablesDescription, privacy: .public)
                    decodingError:
                    \(String(describing: decodingError), privacy: .public)
                    response:
                    \(responseBody, privacy: .public)
                    """
                )
            } else {
                logger.error(
                    """
                    Decoding failed for \(String(describing: T.self), privacy: .public)
                    service: \(service.rawValue, privacy: .public)
                    query:
                    \(query, privacy: .public)
                    variables:
                    \(variablesDescription, privacy: .public)
                    error:
                    \(String(describing: error), privacy: .public)
                    response:
                    \(responseBody, privacy: .public)
                    """
                )
            }
            #else
            logger.error("Decoding failed for \(String(describing: T.self), privacy: .public): \(error, privacy: .public)")
            #endif
            throw SRHTError.decodingError(error)
        }

        if let errors = graphQLResponse.errors, !errors.isEmpty {
            throw SRHTError.graphQLErrors(errors)
        }

        guard let result = graphQLResponse.data else {
            throw SRHTError.decodingError(
                DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "No data in response"))
            )
        }

        return result
    }

    func executeMultipartFiles<T: Decodable>(
        service: SRHTService,
        query: String,
        variables: [String: any Sendable],
        files: [MultipartUploadFile],
        responseType _: T.Type
    ) async throws -> T {
        guard let token = tokenLock.withLock({ $0 }), !token.isEmpty else {
            throw SRHTError.unauthorized
        }

        let boundary = "Boundary-\(UUID().uuidString)"

        var request = URLRequest(url: service.url)
        request.httpMethod = "POST"
        request.setValue(Bundle.main.hutchUserAgent, forHTTPHeaderField: "User-Agent")
        request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

        let operationsBody = GraphQLRequestBody(
            query: query,
            variables: variables.mapValues { AnyCodable($0) }
        )
        let operationsData = try encoder.encode(operationsBody)

        let mapDict = Dictionary(uniqueKeysWithValues: files.enumerated().map { index, file in
            (String(index), ["variables.\(file.variablePath)"])
        })
        let mapData = try encoder.encode(mapDict)

        var body = Data()

        body.append("--\(boundary)\r\n")
        body.append("Content-Disposition: form-data; name=\"operations\"\r\n")
        body.append("Content-Type: application/json\r\n\r\n")
        body.append(operationsData)
        body.append("\r\n")

        body.append("--\(boundary)\r\n")
        body.append("Content-Disposition: form-data; name=\"map\"\r\n")
        body.append("Content-Type: application/json\r\n\r\n")
        body.append(mapData)
        body.append("\r\n")

        for (index, file) in files.enumerated() {
            body.append("--\(boundary)\r\n")
            body.append("Content-Disposition: form-data; name=\"\(index)\"; filename=\"\(file.fileName)\"\r\n")
            body.append("Content-Type: \(file.mimeType)\r\n\r\n")
            body.append(file.fileData)
            body.append("\r\n")
        }

        body.append("--\(boundary)--\r\n")
        request.httpBody = body

        let (data, response): (Data, URLResponse)
        do {
            (data, response) = try await session.data(for: request)
        } catch {
            throw SRHTError.networkError(error)
        }

        if let http = response as? HTTPURLResponse {
            if http.statusCode == 401 {
                throw SRHTError.unauthorized
            }
            if !(200...299).contains(http.statusCode) {
                try throwGraphQLErrorsIfPresent(in: data)
                throw SRHTError.httpError(http.statusCode)
            }
        }

        try throwGraphQLErrorsIfPresent(in: data)

        let graphQLResponse: GraphQLResponse<T>
        do {
            graphQLResponse = try decoder.decode(GraphQLResponse<T>.self, from: data)
        } catch {
            throw SRHTError.decodingError(error)
        }

        if let errors = graphQLResponse.errors, !errors.isEmpty {
            throw SRHTError.graphQLErrors(errors)
        }

        guard let result = graphQLResponse.data else {
            throw SRHTError.decodingError(
                DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "No data in response"))
            )
        }

        return result
    }

    // MARK: - Cached Execute

    /// Execute a query and cache the raw response data. Returns cached data
    /// immediately on cache hit, then refreshes in the background via the
    /// `onRefresh` callback.
    func executeCached<T: Decodable>(
        service: SRHTService,
        query: String,
        variables: [String: any Sendable]? = nil,
        responseType _: T.Type,
        cacheKey: String
    ) async throws -> T {
        // Try cache first
        if let cachedData = responseCache.get(forKey: cacheKey),
           let cached = try? decoder.decode(GraphQLResponse<T>.self, from: cachedData),
           let data = cached.data {
            return data
        }

        // No cache hit — fetch normally
        return try await executeAndCache(
            service: service,
            query: query,
            variables: variables,
            responseType: T.self,
            cacheKey: cacheKey
        )
    }

    /// Execute a query, cache the raw data, and return the decoded result.
    func executeAndCache<T: Decodable>(
        service: SRHTService,
        query: String,
        variables: [String: any Sendable]? = nil,
        responseType _: T.Type,
        cacheKey: String
    ) async throws -> T {
        guard let token = tokenLock.withLock({ $0 }), !token.isEmpty else {
            throw SRHTError.unauthorized
        }

        var request = URLRequest(url: service.url)
        request.httpMethod = "POST"
        request.setValue(Bundle.main.hutchUserAgent, forHTTPHeaderField: "User-Agent")
        request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let body = GraphQLRequestBody(
            query: query,
            variables: variables?.mapValues { AnyCodable($0) }
        )
        request.httpBody = try encoder.encode(body)

        let (data, response): (Data, URLResponse)
        do {
            (data, response) = try await session.data(for: request)
        } catch {
            throw SRHTError.networkError(error)
        }

        if let http = response as? HTTPURLResponse {
            if http.statusCode == 401 {
                throw SRHTError.unauthorized
            }
            if !(200...299).contains(http.statusCode) {
                try throwGraphQLErrorsIfPresent(in: data)
                throw SRHTError.httpError(http.statusCode)
            }
        }

        // Cache the raw response data before decoding
        responseCache.set(data, forKey: cacheKey)

        let graphQLResponse: GraphQLResponse<T>
        do {
            graphQLResponse = try decoder.decode(GraphQLResponse<T>.self, from: data)
        } catch {
            #if DEBUG
            let responseBody = String(data: data, encoding: .utf8) ?? "<non-utf8 response>"
            let variablesDescription = String(describing: variables)
            if let decodingError = error as? DecodingError {
                logger.error(
                    """
                    Decoding failed for \(String(describing: T.self), privacy: .public)
                    service: \(service.rawValue, privacy: .public)
                    query:
                    \(query, privacy: .public)
                    variables:
                    \(variablesDescription, privacy: .public)
                    decodingError:
                    \(String(describing: decodingError), privacy: .public)
                    response:
                    \(responseBody, privacy: .public)
                    """
                )
            } else {
                logger.error(
                    """
                    Decoding failed for \(String(describing: T.self), privacy: .public)
                    service: \(service.rawValue, privacy: .public)
                    query:
                    \(query, privacy: .public)
                    variables:
                    \(variablesDescription, privacy: .public)
                    error:
                    \(String(describing: error), privacy: .public)
                    response:
                    \(responseBody, privacy: .public)
                    """
                )
            }
            #else
            logger.error("Decoding failed for \(String(describing: T.self), privacy: .public): \(error, privacy: .public)")
            #endif
            throw SRHTError.decodingError(error)
        }

        if let errors = graphQLResponse.errors, !errors.isEmpty {
            throw SRHTError.graphQLErrors(errors)
        }

        guard let result = graphQLResponse.data else {
            throw SRHTError.decodingError(
                DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "No data in response"))
            )
        }

        return result
    }

    // MARK: - Plain-text fetch

    /// Fetch the contents of a URL as plain text, using the same authorization header.
    /// Used for build logs and other non-GraphQL resources.
    func fetchText(url: URL) async throws -> String {
        guard let token = tokenLock.withLock({ $0 }), !token.isEmpty else {
            throw SRHTError.unauthorized
        }
        guard Self.isTrustedAuthenticatedTextURL(url) else {
            throw SRHTError.invalidAuthenticatedURL(url)
        }

        var request = URLRequest(url: url)
        request.setValue(Bundle.main.hutchUserAgent, forHTTPHeaderField: "User-Agent")
        request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")

        let (data, response): (Data, URLResponse)
        do {
            (data, response) = try await session.data(for: request)
        } catch {
            throw SRHTError.networkError(error)
        }

        if let http = response as? HTTPURLResponse {
            if http.statusCode == 401 {
                throw SRHTError.unauthorized
            }
            if !(200...299).contains(http.statusCode) {
                throw SRHTError.httpError(http.statusCode)
            }
        }

        guard let text = String(data: data, encoding: .utf8) else {
            throw SRHTError.decodingError(
                DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Response is not UTF-8 text"))
            )
        }

        return text
    }

    // MARK: - Pagination

    /// Returns an `AsyncSequence` that lazily iterates through all pages of a
    /// paginated sr.ht GraphQL query.
    ///
    /// The query must accept a `$cursor: String` variable and return the standard
    /// `{ results: [T], cursor: String? }` shape at the given key path.
    func paginated<T: Decodable & Sendable>(
        service: SRHTService,
        query: String,
        variables: [String: any Sendable]? = nil,
        resultKeyPath: String
    ) -> SRHTPaginatedSequence<T> {
        SRHTPaginatedSequence(
            client: self,
            service: service,
            query: query,
            variables: variables,
            resultKeyPath: resultKeyPath
        )
    }

    /// Fetches all pages of a paginated sr.ht GraphQL query and returns the
    /// collected results.
    func fetchAll<T: Decodable & Sendable>(
        service: SRHTService,
        query: String,
        variables: [String: any Sendable]? = nil,
        resultKeyPath: String
    ) async throws -> [T] {
        var all: [T] = []
        let pages: SRHTPaginatedSequence<T> = paginated(
            service: service,
            query: query,
            variables: variables,
            resultKeyPath: resultKeyPath
        )
        for try await element in pages {
            all.append(element)
        }
        return all
    }
}

// MARK: - Data Helper

private extension SRHTClient {
    func performGraphQLRequest(
        service: SRHTService,
        query: String,
        variables: [String: any Sendable]?
    ) async throws -> Data {
        guard let token = tokenLock.withLock({ $0 }), !token.isEmpty else {
            throw SRHTError.unauthorized
        }

        var request = URLRequest(url: service.url)
        request.httpMethod = "POST"
        request.setValue(Bundle.main.hutchUserAgent, forHTTPHeaderField: "User-Agent")
        request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let body = GraphQLRequestBody(
            query: query,
            variables: variables?.mapValues { AnyCodable($0) }
        )
        request.httpBody = try encoder.encode(body)

        let (data, response): (Data, URLResponse)
        do {
            (data, response) = try await session.data(for: request)
        } catch {
            throw SRHTError.networkError(error)
        }

        if let http = response as? HTTPURLResponse {
            if http.statusCode == 401 {
                throw SRHTError.unauthorized
            }
            if !(200...299).contains(http.statusCode) {
                try throwGraphQLErrorsIfPresent(in: data)
                throw SRHTError.httpError(http.statusCode)
            }
        }

        try throwGraphQLErrorsIfPresent(in: data)
        return data
    }

    func decodeGraphQLData<T: Decodable>(
        _ data: Data,
        service: SRHTService,
        query: String,
        variables: [String: any Sendable]?
    ) throws -> T {
        let graphQLResponse: GraphQLResponse<T>
        do {
            graphQLResponse = try decoder.decode(GraphQLResponse<T>.self, from: data)
        } catch {
            #if DEBUG
            let responseBody = String(data: data, encoding: .utf8) ?? "<non-utf8 response>"
            logger.error(
                """
                Decoding failed for \(String(describing: T.self), privacy: .public)
                service: \(service.rawValue, privacy: .public)
                query:
                \(query, privacy: .public)
                variables:
                \(String(describing: variables), privacy: .public)
                error:
                \(String(describing: error), privacy: .public)
                response:
                \(responseBody, privacy: .public)
                """
            )
            #endif
            throw SRHTError.decodingError(error)
        }

        if let errors = graphQLResponse.errors, !errors.isEmpty {
            throw SRHTError.graphQLErrors(errors)
        }

        guard let result = graphQLResponse.data else {
            throw SRHTError.decodingError(
                DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "No data in response"))
            )
        }
        return result
    }

    func fetchAndCacheGraphQL<T: Decodable>(
        service: SRHTService,
        query: String,
        variables: [String: any Sendable]?,
        cacheKey: String,
        resourceType: CacheResourceType,
        ttl: TimeInterval
    ) async throws -> (T, CacheEntryMetadata?) {
        let data = try await requestCoalescer.value(for: cacheKey) {
            try await self.performGraphQLRequest(service: service, query: query, variables: variables)
        }
        let value: T = try decodeGraphQLData(data, service: service, query: query, variables: variables)
        responseCache.set(data, forKey: cacheKey)
        let metadata = try? await cache.write(payload: data, cacheKey: cacheKey, resourceType: resourceType, ttl: ttl)
        return (value, metadata)
    }

    func fetchAndCacheGraphQLData(
        service: SRHTService,
        query: String,
        variables: [String: any Sendable]?,
        cacheKey: String,
        resourceType: CacheResourceType,
        ttl: TimeInterval
    ) async throws -> CacheEntryMetadata? {
        let data = try await requestCoalescer.value(for: cacheKey) {
            try await self.performGraphQLRequest(service: service, query: query, variables: variables)
        }
        responseCache.set(data, forKey: cacheKey)
        return try? await cache.write(payload: data, cacheKey: cacheKey, resourceType: resourceType, ttl: ttl)
    }

    func fetchAndCacheText(
        url: URL,
        cacheKey: String,
        resourceType: CacheResourceType,
        ttl: TimeInterval
    ) async throws -> (String, CacheEntryMetadata?) {
        let data = try await requestCoalescer.value(for: cacheKey) {
            let text = try await self.fetchText(url: url)
            guard let data = text.data(using: .utf8) else {
                throw SRHTError.decodingError(
                    DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Text could not be encoded as UTF-8"))
                )
            }
            return data
        }
        guard let text = String(data: data, encoding: .utf8) else {
            throw SRHTError.decodingError(
                DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Response is not UTF-8 text"))
            )
        }
        responseCache.set(data, forKey: cacheKey)
        let metadata = try? await cache.write(payload: data, cacheKey: cacheKey, resourceType: resourceType, ttl: ttl)
        return (text, metadata)
    }

    static func tokenCacheScope(_ token: String) -> String {
        let digest = SHA256.hash(data: Data(token.utf8))
        return digest.prefix(8).map { String(format: "%02x", $0) }.joined()
    }

    func throwGraphQLErrorsIfPresent(in data: Data) throws {
        if let envelope = try? decoder.decode(GraphQLResponse<EmptyData>.self, from: data),
           let errors = envelope.errors,
           !errors.isEmpty {
            throw SRHTError.graphQLErrors(errors)
        }
    }

    static func isTrustedAuthenticatedTextURL(_ url: URL) -> Bool {
        guard url.scheme?.localizedCaseInsensitiveCompare("https") == .orderedSame,
              let host = url.host?.lowercased() else {
            return false
        }

        return host.hasSuffix(".sr.ht")
    }
}

private actor RequestCoalescer {
    private var tasks: [String: Task<Data, Error>] = [:]

    func value(for key: String, operation: @Sendable @escaping () async throws -> Data) async throws -> Data {
        if let task = tasks[key] {
            return try await task.value
        }

        let task = Task {
            try await operation()
        }
        tasks[key] = task
        defer { tasks.removeValue(forKey: key) }
        return try await task.value
    }
}

private extension Data {
    mutating func append(_ string: String) {
        if let data = string.data(using: .utf8) {
            append(data)
        }
    }
}