-
Notifications
You must be signed in to change notification settings - Fork 841
Expand file tree
/
Copy pathCopilotUsageModels.swift
More file actions
346 lines (306 loc) · 13.4 KB
/
CopilotUsageModels.swift
File metadata and controls
346 lines (306 loc) · 13.4 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
338
339
340
341
342
343
344
345
346
import Foundation
public struct CopilotUsageResponse: Sendable, Decodable {
private struct AnyCodingKey: CodingKey {
let stringValue: String
let intValue: Int?
init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
init?(intValue: Int) {
self.stringValue = String(intValue)
self.intValue = intValue
}
}
public struct QuotaSnapshot: Sendable, Decodable {
public let entitlement: Double
public let remaining: Double
public let percentRemaining: Double
public let quotaId: String
public let hasPercentRemaining: Bool
public var isPlaceholder: Bool {
self.entitlement == 0 && self.remaining == 0 && self.percentRemaining == 0 && self.quotaId.isEmpty
}
private enum CodingKeys: String, CodingKey {
case entitlement
case remaining
case percentRemaining = "percent_remaining"
case quotaId = "quota_id"
}
public init(
entitlement: Double,
remaining: Double,
percentRemaining: Double,
quotaId: String,
hasPercentRemaining: Bool = true)
{
self.entitlement = entitlement
self.remaining = remaining
self.percentRemaining = percentRemaining
self.quotaId = quotaId
self.hasPercentRemaining = hasPercentRemaining
}
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let decodedEntitlement = Self.decodeNumberIfPresent(container: container, key: .entitlement)
let decodedRemaining = Self.decodeNumberIfPresent(container: container, key: .remaining)
self.entitlement = decodedEntitlement ?? 0
self.remaining = decodedRemaining ?? 0
let decodedPercent = Self.decodeNumberIfPresent(container: container, key: .percentRemaining)
if let decodedPercent {
self.percentRemaining = max(0, min(100, decodedPercent))
self.hasPercentRemaining = true
} else if let entitlement = decodedEntitlement,
entitlement > 0,
let remaining = decodedRemaining
{
let derived = (remaining / entitlement) * 100
self.percentRemaining = max(0, min(100, derived))
self.hasPercentRemaining = true
} else {
// Without percent_remaining and both inputs for derivation, the percent is unknown.
self.percentRemaining = 0
self.hasPercentRemaining = false
}
self.quotaId = try container.decodeIfPresent(String.self, forKey: .quotaId) ?? ""
}
private static func decodeNumberIfPresent(
container: KeyedDecodingContainer<CodingKeys>,
key: CodingKeys) -> Double?
{
if let value = try? container.decodeIfPresent(Double.self, forKey: key) {
return value
}
if let value = try? container.decodeIfPresent(Int.self, forKey: key) {
return Double(value)
}
if let value = try? container.decodeIfPresent(String.self, forKey: key) {
return Double(value)
}
return nil
}
}
public struct QuotaCounts: Sendable, Decodable {
public let chat: Double?
public let completions: Double?
private enum CodingKeys: String, CodingKey {
case chat
case completions
}
public init(chat: Double?, completions: Double?) {
self.chat = chat
self.completions = completions
}
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.chat = Self.decodeNumberIfPresent(container: container, key: .chat)
self.completions = Self.decodeNumberIfPresent(container: container, key: .completions)
}
private static func decodeNumberIfPresent(
container: KeyedDecodingContainer<CodingKeys>,
key: CodingKeys) -> Double?
{
if let value = try? container.decodeIfPresent(Double.self, forKey: key) {
return value
}
if let value = try? container.decodeIfPresent(Int.self, forKey: key) {
return Double(value)
}
if let value = try? container.decodeIfPresent(String.self, forKey: key) {
return Double(value)
}
return nil
}
}
public struct QuotaSnapshots: Sendable, Decodable {
public let premiumInteractions: QuotaSnapshot?
public let chat: QuotaSnapshot?
private enum CodingKeys: String, CodingKey {
case premiumInteractions = "premium_interactions"
case chat
}
public init(premiumInteractions: QuotaSnapshot?, chat: QuotaSnapshot?) {
self.premiumInteractions = premiumInteractions
self.chat = chat
}
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
var premium = try container.decodeIfPresent(QuotaSnapshot.self, forKey: .premiumInteractions)
var chat = try container.decodeIfPresent(QuotaSnapshot.self, forKey: .chat)
if premium?.isPlaceholder == true {
premium = nil
}
if chat?.isPlaceholder == true {
chat = nil
}
if premium == nil || chat == nil {
let dynamic = try decoder.container(keyedBy: AnyCodingKey.self)
var fallbackPremium: QuotaSnapshot?
var fallbackChat: QuotaSnapshot?
var firstUsable: QuotaSnapshot?
for key in dynamic.allKeys {
let value: QuotaSnapshot
do {
guard let decoded = try dynamic.decodeIfPresent(QuotaSnapshot.self, forKey: key) else {
continue
}
guard !decoded.isPlaceholder else { continue }
value = decoded
} catch {
continue
}
let name = key.stringValue.lowercased()
if firstUsable == nil {
firstUsable = value
}
if fallbackChat == nil, name.contains("chat") {
fallbackChat = value
continue
}
if fallbackPremium == nil,
name.contains("premium") || name.contains("completion") || name.contains("code")
{
fallbackPremium = value
}
}
if premium == nil {
premium = fallbackPremium
}
if chat == nil {
chat = fallbackChat
}
if premium == nil, chat == nil {
// If keys are unfamiliar, still expose one usable quota instead of failing.
chat = firstUsable
}
}
self.premiumInteractions = premium
self.chat = chat
}
}
public struct QuotaWindow: Sendable, Equatable {
public let assignedAt: Date
public let resetsAt: Date
public let windowMinutes: Int
}
public let quotaSnapshots: QuotaSnapshots
public let copilotPlan: String
public let assignedDate: String?
public let quotaResetDate: String?
public var quotaWindow: QuotaWindow? {
guard let resetsAt = Self.parseQuotaDate(self.quotaResetDate),
let assignedAt = Self.calendarMonthStart(for: resetsAt),
resetsAt > assignedAt
else {
return nil
}
let windowMinutes = Int((resetsAt.timeIntervalSince(assignedAt) / 60).rounded())
guard windowMinutes > 0 else { return nil }
return QuotaWindow(assignedAt: assignedAt, resetsAt: resetsAt, windowMinutes: windowMinutes)
}
private enum CodingKeys: String, CodingKey {
case quotaSnapshots = "quota_snapshots"
case copilotPlan = "copilot_plan"
case assignedDate = "assigned_date"
case quotaResetDate = "quota_reset_date"
case monthlyQuotas = "monthly_quotas"
case limitedUserQuotas = "limited_user_quotas"
}
public init(
quotaSnapshots: QuotaSnapshots,
copilotPlan: String,
assignedDate: String?,
quotaResetDate: String?)
{
self.quotaSnapshots = quotaSnapshots
self.copilotPlan = copilotPlan
self.assignedDate = assignedDate
self.quotaResetDate = quotaResetDate
}
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let directSnapshots = try container.decodeIfPresent(QuotaSnapshots.self, forKey: .quotaSnapshots)
let monthlyQuotas = try container.decodeIfPresent(QuotaCounts.self, forKey: .monthlyQuotas)
let limitedUserQuotas = try container.decodeIfPresent(QuotaCounts.self, forKey: .limitedUserQuotas)
let monthlyLimitedSnapshots = Self.makeQuotaSnapshots(monthly: monthlyQuotas, limited: limitedUserQuotas)
let premium = Self.usableQuotaSnapshot(from: directSnapshots?.premiumInteractions) ??
Self.usableQuotaSnapshot(from: monthlyLimitedSnapshots?.premiumInteractions)
let chat = Self.usableQuotaSnapshot(from: directSnapshots?.chat) ??
Self.usableQuotaSnapshot(from: monthlyLimitedSnapshots?.chat)
if premium != nil || chat != nil {
self.quotaSnapshots = QuotaSnapshots(premiumInteractions: premium, chat: chat)
} else {
self.quotaSnapshots = directSnapshots ?? QuotaSnapshots(premiumInteractions: nil, chat: nil)
}
self.copilotPlan = try container.decodeIfPresent(String.self, forKey: .copilotPlan) ?? "unknown"
self.assignedDate = try container.decodeIfPresent(String.self, forKey: .assignedDate)
self.quotaResetDate = try container.decodeIfPresent(String.self, forKey: .quotaResetDate)
}
private static func makeQuotaSnapshots(monthly: QuotaCounts?, limited: QuotaCounts?) -> QuotaSnapshots? {
let premium = Self.makeQuotaSnapshot(
monthly: monthly?.completions,
limited: limited?.completions,
quotaID: "completions")
let chat = Self.makeQuotaSnapshot(
monthly: monthly?.chat,
limited: limited?.chat,
quotaID: "chat")
guard premium != nil || chat != nil else { return nil }
return QuotaSnapshots(premiumInteractions: premium, chat: chat)
}
private static func makeQuotaSnapshot(monthly: Double?, limited: Double?, quotaID: String) -> QuotaSnapshot? {
guard monthly != nil || limited != nil else { return nil }
guard let monthly else {
// Without a monthly denominator, avoid fabricating a misleading percentage.
return nil
}
guard let limited else {
// Without the limited/remaining value, usage is unknown.
return nil
}
let entitlement = max(0, monthly)
guard entitlement > 0 else {
// A zero denominator cannot produce a meaningful percentage.
return nil
}
let remaining = max(0, limited)
let percentRemaining = max(0, min(100, (remaining / entitlement) * 100))
return QuotaSnapshot(
entitlement: entitlement,
remaining: remaining,
percentRemaining: percentRemaining,
quotaId: quotaID)
}
private static func usableQuotaSnapshot(from snapshot: QuotaSnapshot?) -> QuotaSnapshot? {
guard let snapshot, !snapshot.isPlaceholder, snapshot.hasPercentRemaining else {
return nil
}
return snapshot
}
private static func parseQuotaDate(_ value: String?) -> Date? {
guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else {
return nil
}
let isoFormatter = ISO8601DateFormatter()
isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
if let date = isoFormatter.date(from: value) {
return date
}
isoFormatter.formatOptions = [.withInternetDateTime]
if let date = isoFormatter.date(from: value) {
return date
}
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.calendar = Calendar(identifier: .gregorian)
formatter.timeZone = TimeZone(secondsFromGMT: 0) ?? .gmt
formatter.dateFormat = "yyyy-MM-dd"
return formatter.date(from: value)
}
private static func calendarMonthStart(for resetDate: Date) -> Date? {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0) ?? .gmt
let resetMonth = calendar.dateInterval(of: .month, for: resetDate)?.start
return calendar.date(byAdding: .month, value: -1, to: resetMonth ?? resetDate)
}
}