-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathGithubPanicErrorReporter.swift
More file actions
201 lines (177 loc) · 7.87 KB
/
GithubPanicErrorReporter.swift
File metadata and controls
201 lines (177 loc) · 7.87 KB
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
import Foundation
import TelemetryServiceProvider
import UserDefaultsObserver
import Preferences
public class GitHubPanicErrorReporter {
private static let panicEndpoint = URL(string: "https://copilot-telemetry.githubusercontent.com/telemetry")!
private static let sessionId = UUID().uuidString
private static let standardChannelKey = Bundle.main
.object(forInfoDictionaryKey: "STANDARD_TELEMETRY_CHANNEL_KEY") as! String
private static let userDefaultsObserver = UserDefaultsObserver(
object: UserDefaults.shared,
forKeyPaths: [
UserDefaultPreferenceKeys().gitHubCopilotProxyUrl.key,
UserDefaultPreferenceKeys().gitHubCopilotProxyUsername.key,
UserDefaultPreferenceKeys().gitHubCopilotProxyPassword.key,
UserDefaultPreferenceKeys().gitHubCopilotUseStrictSSL.key,
],
context: nil
)
// Use static initializer to set up the observer
private static let _initializer: Void = {
userDefaultsObserver.onChange = {
urlSession = configuredURLSession()
}
}()
private static var urlSession: URLSession = {
// Initialize urlSession after observer setup
_ = _initializer
return configuredURLSession()
}()
// Helper: Format current time in ISO8601 style
private static func currentTime() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSX"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter.string(from: Date())
}
// Helper: Create failbot payload JSON string and update properties
private static func createFailbotPayload(
for request: TelemetryExceptionRequest,
properties: inout [String: Any]
) -> String? {
let payload: [String: Any] = [
"context": [:],
"app": "copilot-xcode",
"catalog_service": "CopilotXcode",
"release": "copilot-xcode@\(properties["common_extversion"] ?? "0.0.0")",
"rollup_id": "auto",
"platform": "macOS",
"exception_detail": request.exceptionDetail?.toDictionary() ?? []
]
guard let data = try? JSONSerialization.data(withJSONObject: payload, options: []) else {
return nil
}
return String(data: data, encoding: .utf8)
}
// Helper: Create payload with a channel input, but always using standard telemetry key.
private static func createPayload(
for request: TelemetryExceptionRequest,
properties: inout [String: Any]
) -> [String: Any] {
// Build and add failbot payload to properties
if let payloadString = createFailbotPayload(for: request, properties: &properties) {
properties["failbot_payload"] = payloadString
}
properties["common_vscodesessionid"] = sessionId
properties["client_sessionid"] = sessionId
let baseData: [String: Any] = [
"ver": 2,
"severityLevel": "Error",
"name": "agent/error.exception",
"properties": properties,
"exceptions": [],
"measurements": [:]
]
return [
"ver": 1,
"time": currentTime(),
"severityLevel": "Error",
"name": "Microsoft.ApplicationInsights.standard.Event",
"iKey": standardChannelKey,
"data": [
"baseData": baseData,
"baseType": "ExceptionData"
]
]
}
private static func configuredURLSession() -> URLSession {
let proxyURL = UserDefaults.shared.value(for: \.gitHubCopilotProxyUrl)
let strictSSL = UserDefaults.shared.value(for: \.gitHubCopilotUseStrictSSL)
// If no proxy, use shared session
if proxyURL.isEmpty {
return .shared
}
let configuration = URLSessionConfiguration.default
if let url = URL(string: proxyURL) {
var proxyConfig: [String: Any] = [:]
let scheme = url.scheme?.lowercased()
// Set proxy type based on URL scheme
switch scheme {
case "https":
proxyConfig[kCFProxyTypeKey as String] = kCFProxyTypeHTTPS
proxyConfig[kCFNetworkProxiesHTTPSEnable as String] = true
proxyConfig[kCFNetworkProxiesHTTPSProxy as String] = url.host
proxyConfig[kCFNetworkProxiesHTTPSPort as String] = url.port
case "socks", "socks5":
proxyConfig[kCFProxyTypeKey as String] = kCFProxyTypeSOCKS
proxyConfig[kCFNetworkProxiesSOCKSEnable as String] = true
proxyConfig[kCFNetworkProxiesSOCKSProxy as String] = url.host
proxyConfig[kCFNetworkProxiesSOCKSPort as String] = url.port
default:
proxyConfig[kCFProxyTypeKey as String] = kCFProxyTypeHTTP
proxyConfig[kCFProxyHostNameKey as String] = url.host
proxyConfig[kCFProxyPortNumberKey as String] = url.port
}
// Add proxy authentication if configured
let username = UserDefaults.shared.value(for: \.gitHubCopilotProxyUsername)
let password = UserDefaults.shared.value(for: \.gitHubCopilotProxyPassword)
if !username.isEmpty {
proxyConfig[kCFProxyUsernameKey as String] = username
proxyConfig[kCFProxyPasswordKey as String] = password
}
configuration.connectionProxyDictionary = proxyConfig
}
// Configure SSL verification
if strictSSL {
return URLSession(configuration: configuration)
}
let sessionDelegate = CustomURLSessionDelegate()
return URLSession(
configuration: configuration,
delegate: sessionDelegate,
delegateQueue: nil
)
}
private class CustomURLSessionDelegate: NSObject, URLSessionDelegate {
func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
) {
// Accept all certificates when strict SSL is disabled
guard let serverTrust = challenge.protectionSpace.serverTrust else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
let credential = URLCredential(trust: serverTrust)
completionHandler(.useCredential, credential)
}
}
public static func report(_ request: TelemetryExceptionRequest) async {
do {
var properties: [String : Any] = request.properties ?? [:]
let payload = createPayload(
for: request,
properties: &properties
)
let jsonData = try JSONSerialization.data(withJSONObject: [payload], options: [])
var httpRequest = URLRequest(url: panicEndpoint)
httpRequest.httpMethod = "POST"
httpRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
httpRequest.httpBody = jsonData
// Use the cached URLSession instead of creating a new one
let (_, response) = try await urlSession.data(for: httpRequest)
#if DEBUG
guard let httpResp = response as? HTTPURLResponse, httpResp.statusCode == 200 else {
throw URLError(.badServerResponse)
}
#endif
} catch {
#if DEBUG
print("Fails to send to Panic Endpoint: \(error)")
#endif
}
}
}