Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsageModels.swift

743 lines26.9 KB

1import Foundation
2​
3public struct FeatureEnvironmentUsage: Identifiable, Equatable, Sendable {
4 public let environmentID: String
5 public let label: String
6 public let summary: UsageSummary?
7 public let errorMessage: String?
8 public let isPending: Bool
9​
10 public var id: String { environmentID }
11​
12 public init(
13 environmentID: String,
14 label: String,
15 summary: UsageSummary?,
16 errorMessage: String? = nil,
17 isPending: Bool = false
18 ) {
19 self.environmentID = environmentID
20 self.label = label
21 self.summary = summary
22 self.errorMessage = errorMessage
23 self.isPending = isPending
24 }
26​
27struct UsageProviderTotals: Identifiable, Equatable {
28 let provider: UsageProviderKind
29 let costUsd: Double
30 let totalTokens: Int
31 let records: Int
32 let costShare: Double
33 let tokenShare: Double
34​
35 var id: UsageProviderKind { provider }
37​
38struct UsageModelTotals: Identifiable, Equatable {
39 let model: String
40 let provider: UsageProviderKind
41 let costUsd: Double
42 let totalTokens: Int
43 let records: Int
44 let costShare: Double
45 var unpricedRecords = 0
46​
47 var id: String { "\(provider.rawValue):\(model)" }
48 var isCostUnknown: Bool { records > 0 && unpricedRecords >= records }
49 var costLabel: String { isCostUnknown ? "Unpriced" : UsageFormat.usd(costUsd) }
50 var costShareLabel: String {
51 isCostUnknown ? "No known rates" : "\(UsageFormat.percent(costShare)) of cost"
52 }
54​
55struct UsageProviderValue: Equatable {
56 var costUsd = 0.0
57 var totalTokens = 0
59​
60struct UsageDailyTotals: Identifiable, Equatable {
61 let day: String
62 let costUsd: Double
63 let totalTokens: Int
64 let byProvider: [UsageProviderKind: UsageProviderValue]
65​
66 var id: String { day }
68​
69struct UsageHourlyTotals: Identifiable, Equatable {
70 let hourStart: String
71 let costUsd: Double
72 let totalTokens: Int
73 let byProvider: [UsageProviderKind: UsageProviderValue]
74​
75 var id: String { hourStart }
77​
78struct UsageCostQuality: Equatable {
79 let providerReportedShare: Double
80 let modelPricedShare: Double
81 let unpricedShare: Double
82 let cacheSavingsUsd: Double
84​
85struct MergedUsage: Equatable {
86 var costUsd = 0.0
87 var uncachedInputTokens = 0
88 var cachedInputTokens = 0
89 var cacheCreationTokens = 0
90 var outputTokens = 0
91 var reasoningTokens = 0
92 var totalTokens = 0
93 var records = 0
94 var sessions = 0
95 var providers: [UsageProviderTotals] = []
96 var models: [UsageModelTotals] = []
97 var daily: [UsageDailyTotals] = []
98 var hourly: [UsageHourlyTotals] = []
99 var costQuality = UsageCostQuality(
100 providerReportedShare: 0,
101 modelPricedShare: 0,
102 unpricedShare: 0,
103 cacheSavingsUsd: 0
104 )
105 var duplicateSources: [String] = []
106 var contributingEnvironments: [String] = []
107 var staleEnvironments: [String] = []
109​
110struct UsageLoadRequest: Equatable {
111 let id: UUID
112 let days: Int
113 let input: UsageSummaryInput
115​
116struct UsageLoadState: Equatable {
117 private(set) var windowDays: Int
118 private(set) var windowInput: UsageSummaryInput
119 private(set) var environments: [FeatureEnvironmentUsage] = []
120 private(set) var merged = MergedUsage()
121 private(set) var presentation = UsagePresentation()
122 private(set) var isLoading = true
123 private(set) var errorMessage: String?
124 private var activeLoadID: UUID?
125​
126 var isPartial: Bool {
127 environments.contains {
128 $0.summary.map {
129 isCompatibleUsageContractVersion($0.contractVersion, resolution: windowInput.resolution)
130 } == true
131 }
132 && environments.contains { $0.isPending && $0.summary == nil }
133 }
134​
135 var hasPendingCachedTotals: Bool {
136 environments.contains { $0.isPending && $0.summary != nil }
137 }
138​
139 init(
140 days: Int = 30,
141 now: Date = Date(),
142 timeZone: TimeZone = .current
143 ) {
144 windowDays = days
145 windowInput = UsageWindow.make(days: days, now: now, timeZone: timeZone)
146 }
147​
148 mutating func begin(
149 days: Int,
150 now: Date = Date(),
151 timeZone: TimeZone = .current
152 ) -> UsageLoadRequest {
153 selectWindow(days: days, now: now, timeZone: timeZone)
154 let request = UsageLoadRequest(
155 id: UUID(),
156 days: days,
157 input: UsageWindow.make(days: days, now: now, timeZone: timeZone)
158 )
159 activeLoadID = request.id
160 isLoading = true
161 errorMessage = nil
162 return request
163 }
164​
165 mutating func selectWindow(
166 days: Int,
167 now: Date = Date(),
168 timeZone: TimeZone = .current
169 ) {
170 guard days != windowDays else { return }
171 windowDays = days
172 windowInput = UsageWindow.make(days: days, now: now, timeZone: timeZone)
173 environments = []
174 merged = MergedUsage()
175 presentation = UsagePresentation()
176 isLoading = true
177 errorMessage = nil
178 }
179​
180 @discardableResult
181 mutating func receive(
182 _ result: [FeatureEnvironmentUsage],
183 for request: UsageLoadRequest
184 ) -> Bool {
185 guard activeLoadID == request.id, request.days == windowDays else { return false }
186 // A pending row may retain the last scan only for the same window.
187 // Results from a previous day or rolling hour must not enter new totals.
188 let previous = windowInput == request.input
189 ? Dictionary(uniqueKeysWithValues: environments.map { ($0.environmentID, $0) })
190 : [:]
191 windowInput = request.input
192 environments = result.map { environment in
193 guard environment.isPending,
194 environment.summary == nil,
195 let summary = previous[environment.environmentID]?.summary else {
196 return environment
197 }
198 return FeatureEnvironmentUsage(
199 environmentID: environment.environmentID,
200 label: environment.label,
201 summary: summary,
202 errorMessage: environment.errorMessage,
203 isPending: true
204 )
205 }
206 merged = UsageMerger.merge(environments, resolution: request.input.resolution)
207 presentation = UsagePresentation.make(merged, input: request.input)
208 errorMessage = nil
209 return true
210 }
211​
212 @discardableResult
213 mutating func fail(
214 _ error: any Error,
215 for request: UsageLoadRequest
216 ) -> Bool {
217 guard activeLoadID == request.id, request.days == windowDays else { return false }
218 errorMessage = error.localizedDescription
219 return true
220 }
221​
222 mutating func finish(_ request: UsageLoadRequest) {
223 guard activeLoadID == request.id, request.days == windowDays else { return }
224 activeLoadID = nil
225 isLoading = false
226 }
228​
229enum UsageMerger {
230 private struct OwnedContribution {
231 let buckets: [UsageBucket]
232 let sessions: Int
233 }
234​
235 private struct ProviderAccumulator {
236 var costUsd = 0.0
237 var totalTokens = 0
238 var records = 0
239 }
240​
241 private struct ModelAccumulator {
242 let provider: UsageProviderKind
243 var costUsd = 0.0
244 var totalTokens = 0
245 var records = 0
246 var unpricedRecords = 0
247 }
248​
249 private struct DailyAccumulator {
250 var costUsd = 0.0
251 var totalTokens = 0
252 var byProvider: [UsageProviderKind: UsageProviderValue] = [:]
253 }
254​
255 static func merge(
256 _ environments: [FeatureEnvironmentUsage],
257 resolution: UsageResolution? = nil
258 ) -> MergedUsage {
259 let available = environments.compactMap { environment -> (FeatureEnvironmentUsage, UsageSummary)? in
260 guard let summary = environment.summary else { return nil }
261 return (environment, summary)
262 }
263 let current = available.filter {
264 isCompatibleUsageContractVersion($0.1.contractVersion, resolution: resolution)
265 }
266 let staleEnvironmentIDs = available.compactMap { environment, summary in
267 isCompatibleUsageContractVersion(summary.contractVersion, resolution: resolution)
268 ? nil
269 : environment.environmentID
270 }
271 let claims = claimSources(current)
272​
273 var result = MergedUsage()
274 result.duplicateSources = claims.duplicates
275 result.staleEnvironments = staleEnvironmentIDs
276​
277 var cacheSavingsUsd = 0.0
278 var providerReportedRecords = 0
279 var unpricedRecords = 0
280 var providers: [UsageProviderKind: ProviderAccumulator] = [:]
281 var models: [String: ModelAccumulator] = [:]
282 var daily: [String: DailyAccumulator] = [:]
283 var hourly: [String: DailyAccumulator] = [:]
284​
285 for (environment, summary) in current {
286 let contribution = ownedContribution(
287 environment: environment,
288 summary: summary,
289 ownerByFingerprint: claims.ownerByFingerprint
290 )
291 if !contribution.buckets.isEmpty {
292 result.contributingEnvironments.append(environment.environmentID)
293 }
294 result.sessions += contribution.sessions
295​
296 for bucket in contribution.buckets {
297 let tokens = totalTokens(bucket)
298 result.costUsd += bucket.costUsd
299 result.uncachedInputTokens += bucket.totals.uncachedInputTokens
300 result.cachedInputTokens += bucket.totals.cachedInputTokens
301 result.cacheCreationTokens += bucket.totals.cacheCreationTokens
302 result.outputTokens += bucket.totals.outputTokens
303 result.reasoningTokens += bucket.totals.reasoningTokens
304 result.records += bucket.records
305 cacheSavingsUsd += bucket.cacheSavingsUsd
306 unpricedRecords += bucket.unpricedRecords
307 if bucket.costSource == .providerReported {
308 providerReportedRecords += bucket.records
309 }
310​
311 var provider = providers[bucket.provider] ?? ProviderAccumulator()
312 provider.costUsd += bucket.costUsd
313 provider.totalTokens += tokens
314 provider.records += bucket.records
315 providers[bucket.provider] = provider
316​
317 let modelKey = "\(bucket.provider.rawValue) \(bucket.model)"
318 var model = models[modelKey] ?? ModelAccumulator(provider: bucket.provider)
319 model.costUsd += bucket.costUsd
320 model.totalTokens += tokens
321 model.records += bucket.records
322 model.unpricedRecords += bucket.unpricedRecords
323 models[modelKey] = model
324​
325 var day = daily[bucket.day] ?? DailyAccumulator()
326 day.costUsd += bucket.costUsd
327 day.totalTokens += tokens
328 var dayProvider = day.byProvider[bucket.provider] ?? UsageProviderValue()
329 dayProvider.costUsd += bucket.costUsd
330 dayProvider.totalTokens += tokens
331 day.byProvider[bucket.provider] = dayProvider
332 daily[bucket.day] = day
333​
334 if let hourStart = bucket.hourStart {
335 var hour = hourly[hourStart] ?? DailyAccumulator()
336 hour.costUsd += bucket.costUsd
337 hour.totalTokens += tokens
338 var hourProvider = hour.byProvider[bucket.provider] ?? UsageProviderValue()
339 hourProvider.costUsd += bucket.costUsd
340 hourProvider.totalTokens += tokens
341 hour.byProvider[bucket.provider] = hourProvider
342 hourly[hourStart] = hour
343 }
344 }
345 }
346​
347 result.totalTokens = result.uncachedInputTokens
348 + result.cachedInputTokens
349 + result.cacheCreationTokens
350 + result.outputTokens
351 result.providers = providers.map { provider, totals in
352 UsageProviderTotals(
353 provider: provider,
354 costUsd: totals.costUsd,
355 totalTokens: totals.totalTokens,
356 records: totals.records,
357 costShare: result.costUsd == 0 ? 0 : totals.costUsd / result.costUsd,
358 tokenShare: result.totalTokens == 0
359 ? 0
360 : Double(totals.totalTokens) / Double(result.totalTokens)
361 )
362 }
363 .sorted { $0.costUsd > $1.costUsd }
364 result.models = models.map { key, totals in
365 UsageModelTotals(
366 model: String(key.split(separator: " ", maxSplits: 1).last ?? ""),
367 provider: totals.provider,
368 costUsd: totals.costUsd,
369 totalTokens: totals.totalTokens,
370 records: totals.records,
371 costShare: result.costUsd == 0 ? 0 : totals.costUsd / result.costUsd,
372 unpricedRecords: totals.unpricedRecords
373 )
374 }
375 .sorted {
376 $0.costUsd == $1.costUsd
377 ? $0.totalTokens > $1.totalTokens
378 : $0.costUsd > $1.costUsd
379 }
380 result.daily = daily.map { day, totals in
381 UsageDailyTotals(
382 day: day,
383 costUsd: totals.costUsd,
384 totalTokens: totals.totalTokens,
385 byProvider: totals.byProvider
386 )
387 }
388 .sorted { $0.day < $1.day }
389 result.hourly = hourly.map { hourStart, totals in
390 UsageHourlyTotals(
391 hourStart: hourStart,
392 costUsd: totals.costUsd,
393 totalTokens: totals.totalTokens,
394 byProvider: totals.byProvider
395 )
396 }
397 .sorted { $0.hourStart < $1.hourStart }
398 result.costQuality = UsageCostQuality(
399 providerReportedShare: result.records == 0
400 ? 0
401 : Double(providerReportedRecords) / Double(result.records),
402 modelPricedShare: result.records == 0
403 ? 0
404 : Double(result.records - providerReportedRecords - unpricedRecords)
405 / Double(result.records),
406 unpricedShare: result.records == 0
407 ? 0
408 : Double(unpricedRecords) / Double(result.records),
409 cacheSavingsUsd: cacheSavingsUsd
410 )
411 return result
412 }
413​
414 private static func claimSources(
415 _ environments: [(FeatureEnvironmentUsage, UsageSummary)]
416 ) -> (ownerByFingerprint: [UsageSourceFingerprint: String], duplicates: [String]) {
417 var selected: [
418 UsageSourceFingerprint: (environmentID: String, status: UsageSourceStatus)
419 ] = [:]
420 var duplicates: [String] = []
421 let ordered = environments.sorted { $0.0.environmentID < $1.0.environmentID }
422​
423 for (environment, summary) in ordered {
424 for source in summary.sources where source.status != .missing {
425 if let current = selected[source.fingerprint] {
426 if source.status.ownershipPriority > current.status.ownershipPriority {
427 selected[source.fingerprint] = (environment.environmentID, source.status)
428 }
429 } else {
430 selected[source.fingerprint] = (environment.environmentID, source.status)
431 }
432 }
433 }
434​
435 let owners = selected.mapValues(\.environmentID)
436 for (environment, summary) in ordered {
437 for source in summary.sources where source.status != .missing {
438 if owners[source.fingerprint] != environment.environmentID {
439 duplicates.append(
440 "\(environment.label): \(source.fingerprint.resolvedHomePath)"
441 )
442 }
443 }
444 }
445 return (owners, duplicates)
446 }
447​
448 private static func ownedContribution(
449 environment: FeatureEnvironmentUsage,
450 summary: UsageSummary,
451 ownerByFingerprint: [UsageSourceFingerprint: String]
452 ) -> OwnedContribution {
453 var providers: Set<UsageProviderKind> = []
454 var sessions = 0
455 for source in summary.sources where source.status != .missing {
456 if ownerByFingerprint[source.fingerprint] == environment.environmentID {
457 providers.insert(source.fingerprint.provider)
458 sessions += source.distinctSessions
459 }
460 }
461 return OwnedContribution(
462 buckets: summary.buckets.filter { providers.contains($0.provider) },
463 sessions: sessions
464 )
465 }
466​
467 private static func totalTokens(_ bucket: UsageBucket) -> Int {
468 bucket.totals.uncachedInputTokens
469 + bucket.totals.cachedInputTokens
470 + bucket.totals.cacheCreationTokens
471 + bucket.totals.outputTokens
472 }
474​
475private extension UsageSourceStatus {
476 var ownershipPriority: Int {
477 switch self {
478 case .missing: 0
479 case .failed: 1
480 case .partial: 2
481 case .ok: 3
482 }
483 }
485​
486enum UsageWindow {
487 static func make(
488 days: Int,
489 now: Date = Date(),
490 timeZone: TimeZone = .current
491 ) -> UsageSummaryInput {
492 var calendar = Calendar(identifier: .gregorian)
493 calendar.timeZone = timeZone
494 let until = calendar.startOfDay(for: now)
495 let since = calendar.date(byAdding: .day, value: -(days - 1), to: until) ?? until
496 let formatter = DateFormatter()
497 formatter.calendar = calendar
498 formatter.locale = Locale(identifier: "en_US_POSIX")
499 formatter.timeZone = timeZone
500 formatter.dateFormat = "yyyy-MM-dd"
501 if days == 1 {
502 let untilTimeInterval = floor(now.timeIntervalSince1970 / 60) * 60
503 let untilTime = Date(timeIntervalSince1970: untilTimeInterval)
504 let sinceTime = untilTime.addingTimeInterval(-24 * 60 * 60)
505 return UsageSummaryInput(
506 sinceDay: formatter.string(from: sinceTime),
507 untilDay: formatter.string(from: untilTime),
508 timeZone: timeZone.identifier,
509 resolution: .hour,
510 sinceTime: isoString(sinceTime),
511 untilTime: isoString(untilTime)
512 )
513 }
514 return UsageSummaryInput(
515 sinceDay: formatter.string(from: since),
516 untilDay: formatter.string(from: until),
517 timeZone: timeZone.identifier,
518 resolution: .day
519 )
520 }
521​
522 static func hours(in input: UsageSummaryInput) -> [String] {
523 guard let sinceValue = input.sinceTime,
524 let untilValue = input.untilTime,
525 let since = isoDate(sinceValue),
526 let until = isoDate(untilValue),
527 since < until else {
528 return []
529 }
530 var result: [String] = []
531 var cursor = since
532 while cursor < until {
533 result.append(isoString(cursor))
534 cursor = cursor.addingTimeInterval(60 * 60)
535 }
536 return result
537 }
538​
539 private static func isoString(_ date: Date) -> String {
540 UsageFormat.isoString(date)
541 }
542​
543 private static func isoDate(_ value: String) -> Date? {
544 UsageFormat.isoDate(value)
545 }
546​
547 static func days(in input: UsageSummaryInput) -> [String] {
548 var calendar = Calendar(identifier: .gregorian)
549 calendar.timeZone = TimeZone(secondsFromGMT: 0)!
550 let parser = DateFormatter()
551 parser.calendar = calendar
552 parser.locale = Locale(identifier: "en_US_POSIX")
553 parser.timeZone = TimeZone(secondsFromGMT: 0)
554 parser.dateFormat = "yyyy-MM-dd"
555 guard let start = parser.date(from: input.sinceDay),
556 let end = parser.date(from: input.untilDay),
557 start <= end else {
558 return []
559 }
560​
561 var result: [String] = []
562 var cursor = start
563 while cursor <= end {
564 result.append(parser.string(from: cursor))
565 guard let next = calendar.date(
566 byAdding: .day,
567 value: 1,
568 to: cursor
569 ) else { break }
570 cursor = next
571 }
572 return result
573 }
575​
576/// Chart bars stack one segment per provider for each day or hour in the window.
577struct UsageChartSegment: Identifiable, Equatable {
578 let period: String
579 let provider: UsageProviderKind
580 let start: Double
581 let end: Double
582​
583 var id: String { "\(period):\(provider.rawValue)" }
585​
586struct UsagePeriodRow: Identifiable, Equatable {
587 let id: String
588 let label: String
589 let costUsd: Double
590 let totalTokens: Int
592​
593/// Sorted, labelled, and charted values the usage screen renders. Computed once
594/// per received result so the view body only reads stored values.
595struct UsagePresentation: Equatable {
596 var providersByCost: [UsageProviderTotals] = []
597 var providersByTokens: [UsageProviderTotals] = []
598 var costSegments: [UsageChartSegment] = []
599 var tokenSegments: [UsageChartSegment] = []
600 var hasCostActivity = false
601 var hasTokenActivity = false
602 /// Newest period first.
603 var periods: [UsagePeriodRow] = []
604 var activePeriodCount = 0
605 var periodAverageTokens = 0
606 var cachedInputShare = 0.0
607 var sinceLabel = ""
608 var untilLabel = ""
609​
610 static func make(_ merged: MergedUsage, input: UsageSummaryInput) -> UsagePresentation {
611 var result = UsagePresentation()
612 result.providersByCost = merged.providers.sorted { $0.costUsd > $1.costUsd }
613 result.providersByTokens = merged.providers.sorted { $0.totalTokens > $1.totalTokens }
614 result.hasCostActivity = merged.daily.contains { $0.costUsd > 0 }
615 result.hasTokenActivity = merged.daily.contains { $0.totalTokens > 0 }
616 result.sinceLabel = UsageFormat.dayShort(input.sinceDay)
617 result.untilLabel = UsageFormat.dayShort(input.untilDay)
618​
619 let periodKeys: [String]
620 let byPeriod: [String: [UsageProviderKind: UsageProviderValue]]
621 if input.resolution == .hour {
622 let hourStyle = UsageFormat.hourStyle(timeZone: input.timeZone)
623 periodKeys = UsageWindow.hours(in: input)
624 byPeriod = Dictionary(uniqueKeysWithValues: merged.hourly.map { ($0.hourStart, $0.byProvider) })
625 result.periods = merged.hourly.reversed().map {
626 UsagePeriodRow(
627 id: $0.hourStart,
628 label: UsageFormat.hourShort($0.hourStart, style: hourStyle),
629 costUsd: $0.costUsd,
630 totalTokens: $0.totalTokens
631 )
632 }
633 result.activePeriodCount = merged.hourly.filter { $0.totalTokens > 0 }.count
634 } else {
635 periodKeys = UsageWindow.days(in: input)
636 byPeriod = Dictionary(uniqueKeysWithValues: merged.daily.map { ($0.day, $0.byProvider) })
637 result.periods = merged.daily.reversed().map {
638 UsagePeriodRow(
639 id: $0.day,
640 label: UsageFormat.dayShort($0.day),
641 costUsd: $0.costUsd,
642 totalTokens: $0.totalTokens
643 )
644 }
645 result.activePeriodCount = merged.daily.filter { $0.totalTokens > 0 }.count
646 }
647 result.costSegments = segments(periodKeys, byPeriod: byPeriod) { $0.costUsd }
648 result.tokenSegments = segments(periodKeys, byPeriod: byPeriod) { Double($0.totalTokens) }
649 result.periodAverageTokens = result.activePeriodCount == 0
650 ? 0
651 : merged.totalTokens / result.activePeriodCount
652 let observedInput = merged.uncachedInputTokens + merged.cachedInputTokens
653 result.cachedInputShare = observedInput == 0
654 ? 0
655 : Double(merged.cachedInputTokens) / Double(observedInput)
656 return result
657 }
658​
659 private static func segments(
660 _ periods: [String],
661 byPeriod: [String: [UsageProviderKind: UsageProviderValue]],
662 value: (UsageProviderValue) -> Double
663 ) -> [UsageChartSegment] {
664 periods.flatMap { period in
665 let totals = byPeriod[period] ?? [:]
666 var start = 0.0
667 return UsageProviderKind.allCases.map { provider in
668 let amount = totals[provider].map(value) ?? 0
669 defer { start += amount }
670 return UsageChartSegment(period: period, provider: provider, start: start, end: start + amount)
671 }
672 }
673 }
675​
676/// Format styles are Sendable values, so each one is built once here instead of
677/// once per call. All of them follow the current locale.
678enum UsageFormat {
679 private static let isoFractional = Date.ISO8601FormatStyle(includingFractionalSeconds: true)
680 private static let isoWholeSeconds = Date.ISO8601FormatStyle()
681 private static let dayParser = Date.ISO8601FormatStyle().year().month().day()
682 private static let dayLabel = Date.FormatStyle(timeZone: .gmt).month(.abbreviated).day()
683 private static let usdStyle = FloatingPointFormatStyle<Double>.Currency(code: "USD")
684 .precision(.fractionLength(2))
685 private static let countStyle = IntegerFormatStyle<Int>()
686 private static let percentStyle = FloatingPointFormatStyle<Double>.Percent()
687 .precision(.fractionLength(1))
688​
689 static func usd(_ value: Double) -> String {
690 usdStyle.format(value)
691 }
692​
693 static func count(_ value: Int) -> String {
694 countStyle.format(value)
695 }
696​
697 static func tokens(_ value: Int) -> String {
698 let magnitude = abs(Double(value))
699 if magnitude >= 1_000_000_000_000 { return compact(Double(value) / 1_000_000_000_000, suffix: "T") }
700 if magnitude >= 1_000_000_000 { return compact(Double(value) / 1_000_000_000, suffix: "B") }
701 if magnitude >= 1_000_000 { return compact(Double(value) / 1_000_000, suffix: "M") }
702 if magnitude >= 1_000 { return compact(Double(value) / 1_000, suffix: "K") }
703 return count(value)
704 }
705​
706 static func percent(_ value: Double) -> String {
707 percentStyle.format(value)
708 }
709​
710 /// "2026-08-18" becomes "Aug 18" in the current locale.
711 static func dayShort(_ day: String) -> String {
712 (try? dayParser.parse(day)).map(dayLabel.format) ?? day
713 }
714​
715 /// One style per window, since the label follows the window's time zone.
716 static func hourStyle(timeZone: String) -> Date.FormatStyle {
717 Date.FormatStyle(timeZone: TimeZone(identifier: timeZone) ?? .current)
718 .weekday(.abbreviated)
719 .hour(.defaultDigits(amPM: .abbreviated))
720 }
721​
722 static func hourShort(_ value: String, style: Date.FormatStyle) -> String {
723 isoDate(value).map(style.format) ?? value
724 }
725​
726 static func isoString(_ date: Date) -> String {
727 isoFractional.format(date)
728 }
729​
730 static func isoDate(_ value: String) -> Date? {
731 (try? isoFractional.parse(value)) ?? (try? isoWholeSeconds.parse(value))
732 }
733​
734 private static func compact(_ value: Double, suffix: String) -> String {
735 let digits = abs(value) >= 100 ? 0 : abs(value) >= 10 ? 1 : 2
736 var formatted = String(format: "%.*f", digits, value)
737 while formatted.hasSuffix("0"), formatted.contains(".") {
738 formatted.removeLast()
739 }
740 if formatted.hasSuffix(".") { formatted.removeLast() }
741 return formatted + suffix
742 }