forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTelemetryService.swift
More file actions
337 lines (305 loc) · 11.5 KB
/
TelemetryService.swift
File metadata and controls
337 lines (305 loc) · 11.5 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
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
import Foundation
import SystemUtils
import TelemetryServiceProvider
import BuiltinExtension
import GitHubCopilotService
public protocol WrappedTelemetryServiceType {
func sendError(
_ error: Error?,
transaction: String?,
additionalProperties: [String: String]?,
category: String,
file: StaticString,
line: UInt,
function: StaticString,
from symbols: [String]
)
func sendError(
_ message: String,
transaction: String?,
additionalProperties: [String: String]?,
category: String,
file: StaticString,
line: UInt,
function: StaticString,
from symbols: [String]
)
}
public actor TelemetryService: WrappedTelemetryServiceType {
private let telemetryProvider: TelemetryServiceProvider?
private var commonProperties: [String: String] = [:]
private let telemetryCleaner: TelemetryCleaner = TelemetryCleaner(cleanupPatterns: [])
public static var shared: TelemetryService = TelemetryService.service()
init(
provider: any TelemetryServiceProvider
) {
telemetryProvider = provider
self.commonProperties = [
"common_extname": "copilot-xcode",
"common_extversion": SystemUtils.editorPluginVersionString,
"common_os": "darwin",
"common_platformversion": SystemUtils.osVersion,
"common_uikind": "desktop",
"common_vscodemachineid": SystemUtils.machineId,
"client_machineid": SystemUtils.machineId,
"editor_version": SystemUtils.editorVersionString,
"editor_plugin_version": "copilot-xcode/\(SystemUtils.editorPluginVersionString)",
"copilot_build": SystemUtils.build,
"copilot_buildType": SystemUtils.buildType
]
}
public static func service() -> TelemetryService {
let provider = BuiltinExtensionTelemetryServiceProvider(
extension: GitHubCopilotExtension.self
)
return TelemetryService(provider: provider)
}
enum TelemetryServiceError: Error {
case providerNotFound
}
private enum ErrorSource {
case message(String)
case error(Error?)
}
/// Sends an error with the given parameters
public nonisolated func sendError(
_ error: Error?,
transaction: String? = nil,
additionalProperties: [String: String]? = nil,
category: String = "",
file: StaticString,
line: UInt,
function: StaticString,
from symbols: [String]
) {
Task.detached(priority: .background) {
await self.sendErrorInternal(
.error(error),
transaction: transaction,
additionalProperties: additionalProperties,
category: category,
file: file,
line: line,
function: function,
from: symbols
)
}
}
/// Sends an error message with the given parameters
public nonisolated func sendError(
_ message: String,
transaction: String? = nil,
additionalProperties: [String: String]? = nil,
category: String = "",
file: StaticString,
line: UInt,
function: StaticString,
from symbols: [String]
) {
Task.detached(priority: .background) {
await self.sendErrorInternal(
.message(message),
transaction: transaction,
additionalProperties: additionalProperties,
category: category,
file: file,
line: line,
function: function,
from: symbols
)
}
}
/// Internal implementation for sending errors
private func sendErrorInternal(
_ source: ErrorSource,
transaction: String? = nil,
additionalProperties: [String: String]? = nil,
category: String = "",
file: StaticString,
line: UInt,
function: StaticString,
from symbols: [String]
) async {
var props = commonProperties
additionalProperties?.forEach { props[$0.key] = $0.value }
let fileName: String = telemetryCleaner.redact(String(describing: file)) ?? ""
let request = createTelemetryExceptionRequest(
errorSource: source,
transaction: transaction,
additionalProperties: props,
category: category,
file: fileName,
line: line,
function: function,
symbols: symbols
)
do {
if let provider = telemetryProvider {
try await provider.sendError(request)
} else {
throw TelemetryServiceError.providerNotFound
}
} catch {
await GitHubPanicErrorReporter.report(request)
}
}
/// Creates a telemetry exception request from the given parameters
private func createTelemetryExceptionRequest(
errorSource: ErrorSource,
transaction: String?,
additionalProperties: [String: String],
category: String,
file: String,
line: UInt,
function: StaticString,
symbols: [String]
) -> TelemetryExceptionRequest {
let stacktrace: String? = switch errorSource {
case .message(let message):
message
case .error(let error):
error?.localizedDescription
}
let exceptionDetails = convertErrorToExceptionDetails(
errorSource,
category: category,
file: file,
line: line,
function: function,
from: symbols
)
return TelemetryExceptionRequest(
transaction: transaction,
stacktrace: telemetryCleaner.redact(stacktrace),
properties: additionalProperties,
platform: "macOS",
exceptionDetail: exceptionDetails
)
}
/// Converts error source to exception details array
private func convertErrorToExceptionDetails(
_ errorSource: ErrorSource,
category: String,
file: String,
line: UInt,
function: StaticString,
from symbols: [String]
) -> [ExceptionDetail] {
let (errorType, errorValue) = extractErrorInfo(from: errorSource, category: category)
let stackFrames = createStackFrames(
errorSource: errorSource,
file: file,
line: line,
function: function,
symbols: symbols
)
return [
ExceptionDetail(
type: errorType,
value: telemetryCleaner.redact(errorValue),
stacktrace: stackFrames
)
]
}
/// Extracts error type and value from error source
private func extractErrorInfo(from errorSource: ErrorSource, category: String) -> (type: String, value: String) {
switch errorSource {
case .message(let message):
let type = "ErrorMessage \(category)"
return (type, message)
case .error(let error):
guard let error = error else {
let type = "UnknownError \(category)"
return (type, "Unknown error occurred")
}
var typePrefix = String(describing: type(of: error))
if typePrefix == "NSError" {
let nsError = error as NSError
typePrefix += ":\(nsError.domain):\(nsError.code)"
}
let type = typePrefix + " \(category)"
return (type, error.localizedDescription)
}
}
/// Creates stack trace frames from error information
private func createStackFrames(
errorSource: ErrorSource,
file: String,
line: UInt,
function: StaticString,
symbols: [String]
) -> [StackTraceFrame] {
let callSiteFrame = StackTraceFrame(
filename: file,
lineno: .integer(Int(line)),
colno: nil,
function: String(describing: function),
inApp: true
)
switch errorSource {
case .message:
return [callSiteFrame]
case .error:
var frames = parseStackFrames(from: symbols)
frames.insert(callSiteFrame, at: 0)
return frames
}
}
/// Parses call stack symbols into stack trace frames
private func parseStackFrames(from symbols: [String]) -> [StackTraceFrame] {
symbols.map { symbol -> StackTraceFrame? in
let pattern = #"^(\d+)\s+(.+?)\s+(0x[0-9a-fA-F]+)\s+(.+?)\s+\+\s+(\d+)$"#
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return nil }
guard let match = regex.firstMatch(in: symbol, range: NSRange(symbol.startIndex..., in: symbol)) else { return nil }
let components = (1..<match.numberOfRanges).map { i -> String in
if let range = Range(match.range(at: i), in: symbol) {
return String(symbol[range])
}
return ""
}
guard components.count == 5,
let offset = Int(components[4]) else { return nil }
let module = components[1]
let parsedSymbol = parseDemangledSymbol(swift_demangle(components[3]))
return StackTraceFrame(
filename: parsedSymbol?.module ?? module,
lineno: .integer(offset),
colno: nil,
function: parsedSymbol?.function ?? components[3],
inApp: module.contains("GitHub Copilot for Xcode Extension")
)
}.compactMap { $0 }
}
/// Demangles Swift symbol names using the Swift runtime
typealias Swift_Demangle = @convention(c) (_ mangledName: UnsafePointer<UInt8>?,
_ mangledNameLength: Int,
_ outputBuffer: UnsafeMutablePointer<UInt8>?,
_ outputBufferSize: UnsafeMutablePointer<Int>?,
_ flags: UInt32) -> UnsafeMutablePointer<Int8>?
func swift_demangle(_ mangled: String) -> String {
let RTLD_DEFAULT = dlopen(nil, RTLD_NOW)
if let sym = dlsym(RTLD_DEFAULT, "swift_demangle") {
let f = unsafeBitCast(sym, to: Swift_Demangle.self)
if let cString = f(mangled, mangled.count, nil, nil, 0) {
defer { cString.deallocate() }
return String(cString: cString)
}
}
return ""
}
/// Parses demangled symbol into module and function components
func parseDemangledSymbol(_ demangled: String) -> (module: String, function: String)? {
let regex = try! NSRegularExpression(
pattern: #"^\((\d+)\)\s*(.*?)\s*for\s*([^\s]+(?: [^\s]+)*?)\s*((?:async)?)\s*((?:throws)?)\s*(?:->\s*(.*))?$"#,
options: [.anchorsMatchLines]
)
guard let match = regex.firstMatch(
in: demangled, options: [],
range: NSRange(location: 0, length: demangled.utf16.count)
) else {
return nil
}
let functionName = (demangled as NSString).substring(with: match.range(at: 3))
return (module: functionName, function: demangled)
}
}