Skip to content
This repository was archived by the owner on Apr 23, 2021. It is now read-only.

Commit dbcbed9

Browse files
authored
Final API proposal - Baggage + Context (#34)
1 parent 11ce8e1 commit dbcbed9

30 files changed

+1527
-772
lines changed

Package.resolved

Lines changed: 16 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Package.swift

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import PackageDescription
33

44
let package = Package(
5-
name: "swift-baggage-context",
5+
name: "swift-context",
66
products: [
77
.library(
88
name: "Baggage",
@@ -11,14 +11,14 @@ let package = Package(
1111
]
1212
),
1313
.library(
14-
name: "BaggageLogging",
14+
name: "BaggageContext",
1515
targets: [
16-
"BaggageLogging",
16+
"BaggageContext",
1717
]
1818
),
1919
],
2020
dependencies: [
21-
.package(url: "https://github.com/apple/swift-log.git", from: "1.3.0"),
21+
.package(url: "https://github.com/apple/swift-log.git", from: "1.4.0"),
2222
],
2323
targets: [
2424
.target(
@@ -27,7 +27,7 @@ let package = Package(
2727
),
2828

2929
.target(
30-
name: "BaggageLogging",
30+
name: "BaggageContext",
3131
dependencies: [
3232
"Baggage",
3333
.product(name: "Logging", package: "swift-log"),
@@ -45,26 +45,25 @@ let package = Package(
4545
),
4646

4747
.testTarget(
48-
name: "BaggageLoggingTests",
48+
name: "BaggageContextTests",
4949
dependencies: [
5050
"Baggage",
51-
"BaggageLogging",
51+
"BaggageContext",
5252
]
5353
),
5454

5555
// ==== --------------------------------------------------------------------------------------------------------
5656
// MARK: Performance / Benchmarks
5757

5858
.target(
59-
name: "BaggageBenchmarks",
59+
name: "BaggageContextBenchmarks",
6060
dependencies: [
61-
"Baggage",
62-
"BaggageLogging",
63-
"BaggageBenchmarkTools",
61+
"BaggageContext",
62+
"BaggageContextBenchmarkTools",
6463
]
6564
),
6665
.target(
67-
name: "BaggageBenchmarkTools",
66+
name: "BaggageContextBenchmarkTools",
6867
dependencies: []
6968
),
7069
]

Sources/Baggage/Baggage.swift

Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift Baggage Context open source project
4+
//
5+
// Copyright (c) 2020 Moritz Lang and the Swift Baggage Context project authors
6+
// Licensed under Apache License v2.0
7+
//
8+
// See LICENSE.txt for license information
9+
//
10+
// SPDX-License-Identifier: Apache-2.0
11+
//
12+
//===----------------------------------------------------------------------===//
13+
14+
// ==== ----------------------------------------------------------------------------------------------------------------
15+
// MARK: Baggage
16+
17+
/// A `Baggage` is a heterogeneous storage type with value semantics for keyed values in a type-safe fashion.
18+
///
19+
/// Its values are uniquely identified via `Baggage.Key`s (by type identity). These keys also dictate the type of
20+
/// value allowed for a specific key-value pair through their associated type `Value`.
21+
///
22+
/// ## Defining keys and accessing values
23+
/// Baggage keys are defined as types, most commonly case-less enums (as no actual instances are actually required)
24+
/// which conform to the `Baggage.Key` protocol:
25+
///
26+
/// private enum TestIDKey: Baggage.Key {
27+
/// typealias Value = String
28+
/// }
29+
///
30+
/// While defining a key, one should also immediately declare an extension on `Baggage`,
31+
/// to allow convenient and discoverable ways to interact with the baggage item, the extension should take the form of:
32+
///
33+
/// extension Baggage {
34+
/// var testID: String? {
35+
/// get {
36+
/// self[TestIDKey.self]
37+
/// } set {
38+
/// self[TestIDKey.self] = newValue
39+
/// }
40+
/// }
41+
/// }
42+
///
43+
/// For consistency, it is recommended to name key types with the `...Key` suffix (e.g. `SomethingKey`) and the property
44+
/// used to access a value identifier by such key the prefix of the key (e.g. `something`). Please also observe the usual
45+
/// Swift naming conventions, e.g. prefer `ID` to `Id` etc.
46+
///
47+
/// ## Usage
48+
/// Using a baggage container is fairly straight forward, as it boils down to using the prepared computed properties:
49+
///
50+
/// var baggage = Baggage.topLevel
51+
/// // set a new value
52+
/// baggage.testID = "abc"
53+
/// // retrieve a stored value
54+
/// let testID = baggage.testID ?? "default"
55+
/// // remove a stored value
56+
/// baggage.testIDKey = nil
57+
///
58+
/// Note that normally a baggage should not be "created" ad-hoc by user code, but rather it should be passed to it from
59+
/// a runtime. For example, when working in an HTTP server framework, it is most likely that the baggage is already passed
60+
/// directly or indirectly (e.g. in a `FrameworkContext`)
61+
///
62+
/// ### Accessing all values
63+
///
64+
/// The only way to access "all" values in a baggage context is by using the `forEach` function.
65+
/// The baggage container on purpose does not expose more functions to prevent abuse and treating it as too much of an
66+
/// arbitrary value smuggling container, but only make it convenient for tracing and instrumentation systems which need
67+
/// to access either specific or all items carried inside a baggage.
68+
public struct Baggage {
69+
public typealias Key = BaggageKey
70+
71+
private var _storage = [AnyBaggageKey: Any]()
72+
73+
/// Internal on purpose, please use `Baggage.TODO` or `Baggage.topLevel` to create an "empty" context,
74+
/// which carries more meaning to other developers why an empty context was used.
75+
init() {}
76+
}
77+
78+
extension Baggage {
79+
/// Creates a new empty "top level" baggage, generally used as an "initial" baggage to immediately be populated with
80+
/// some values by a framework or runtime. Another use case is for tasks starting in the "background" (e.g. on a timer),
81+
/// which don't have a "request context" per se that they can pick up, and as such they have to create a "top level"
82+
/// baggage for their work.
83+
///
84+
/// ## Usage in frameworks and libraries
85+
/// This function is really only intended to be used frameworks and libraries, at the "top-level" where a request's,
86+
/// message's or task's processing is initiated. For example, a framework handling requests, should create an empty
87+
/// context when handling a request only to immediately populate it with useful trace information extracted from e.g.
88+
/// request headers.
89+
///
90+
/// ## Usage in applications
91+
/// Application code should never have to create an empty context during the processing lifetime of any request,
92+
/// and only should create contexts if some processing is performed in the background - thus the naming of this property.
93+
///
94+
/// Usually, a framework such as an HTTP server or similar "request handler" would already provide users
95+
/// with a context to be passed along through subsequent calls.
96+
///
97+
/// If unsure where to obtain a context from, prefer using `.TODO("Not sure where I should get a context from here?")`,
98+
/// in order to inform other developers that the lack of context passing was not done on purpose, but rather because either
99+
/// not being sure where to obtain a context from, or other framework limitations -- e.g. the outer framework not being
100+
/// baggage context aware just yet.
101+
public static var topLevel: Baggage {
102+
return Baggage()
103+
}
104+
}
105+
106+
extension Baggage {
107+
/// A baggage intended as a placeholder until a real value can be passed through a function call.
108+
///
109+
/// It should ONLY be used while prototyping or when the passing of the proper context is not yet possible,
110+
/// e.g. because an external library did not pass it correctly and has to be fixed before the proper context
111+
/// can be obtained where the TO-DO is currently used.
112+
///
113+
/// ## Crashing on TO-DO context creation
114+
/// You may set the `BAGGAGE_CRASH_TODOS` variable while compiling a project in order to make calls to this function crash
115+
/// with a fatal error, indicating where a to-do baggage context was used. This comes in handy when wanting to ensure that
116+
/// a project never ends up using with code initially was written as "was lazy, did not pass context", yet the
117+
/// project requires context passing to be done correctly throughout the application. Similar checks can be performed
118+
/// at compile time easily using linters (not yet implemented), since it is always valid enough to detect a to-do context
119+
/// being passed as illegal and warn or error when spotted.
120+
///
121+
/// ## Example
122+
///
123+
/// let baggage = Baggage.TODO("The framework XYZ should be modified to pass us a context here, and we'd pass it along"))
124+
///
125+
/// - Parameters:
126+
/// - reason: Informational reason for developers, why a placeholder context was used instead of a proper one,
127+
/// - Returns: Empty "to-do" baggage context which should be eventually replaced with a carried through one, or `background`.
128+
public static func TODO(_ reason: StaticString? = "", function: String = #function, file: String = #file, line: UInt = #line) -> Baggage {
129+
var context = Baggage.topLevel
130+
#if BAGGAGE_CRASH_TODOS
131+
fatalError("BAGGAGE_CRASH_TODOS: at \(file):\(line) (function \(function)), reason: \(reason)")
132+
#else
133+
context[TODOKey.self] = .init(file: file, line: line)
134+
return context
135+
#endif
136+
}
137+
138+
private enum TODOKey: BaggageKey {
139+
typealias Value = TODOLocation
140+
static var nameOverride: String? {
141+
return "todo"
142+
}
143+
}
144+
}
145+
146+
extension Baggage {
147+
/// Provides type-safe access to the baggage's values.
148+
/// This API should ONLY be used inside of accessor implementations.
149+
///
150+
/// End users rather than using this subscript should use "accessors" the key's author MUST define, following this pattern:
151+
///
152+
/// internal enum TestID: Baggage.Key {
153+
/// typealias Value = TestID
154+
/// }
155+
///
156+
/// extension Baggage {
157+
/// public internal(set) var testID: TestID? {
158+
/// get {
159+
/// self[TestIDKey.self]
160+
/// }
161+
/// set {
162+
/// self[TestIDKey.self] = newValue
163+
/// }
164+
/// }
165+
/// }
166+
///
167+
/// This is in order to enforce a consistent style across projects and also allow for fine grained control over
168+
/// who may set and who may get such property. Just access control to the Key type itself lacks such fidelity.
169+
///
170+
/// Note that specific baggage and context types MAY (and usually do), offer also a way to set baggage values,
171+
/// however in the most general case it is not required, as some frameworks may only be able to offer reading.
172+
public subscript<Key: BaggageKey>(_ key: Key.Type) -> Key.Value? {
173+
get {
174+
guard let value = self._storage[AnyBaggageKey(key)] else { return nil }
175+
// safe to force-cast as this subscript is the only way to set a value.
176+
return (value as! Key.Value)
177+
}
178+
set {
179+
self._storage[AnyBaggageKey(key)] = newValue
180+
}
181+
}
182+
183+
/// Number of contained baggage items.
184+
public var count: Int {
185+
return self._storage.count
186+
}
187+
188+
/// Calls the given closure for each item contained in the underlying `Baggage`.
189+
///
190+
/// Order of those invocations is NOT guaranteed and should not be relied on.
191+
///
192+
/// - Parameter body: A closure invoked with the type erased key and value stored for the key in this baggage.
193+
public func forEach(_ body: (AnyBaggageKey, Any) throws -> Void) rethrows {
194+
try self._storage.forEach { key, value in
195+
try body(key, value)
196+
}
197+
}
198+
}
199+
200+
extension Baggage: CustomStringConvertible {
201+
/// A context's description prints only keys of the contained values.
202+
/// This is in order to prevent spilling a lot of detailed information of carried values accidentally.
203+
///
204+
/// `Baggage`s are not intended to be printed "raw" but rather inter-operate with tracing, logging and other systems,
205+
/// which can use the `forEach` function providing access to its underlying values.
206+
public var description: String {
207+
return "\(type(of: self).self)(keys: \(self._storage.map { $0.key.name }))"
208+
}
209+
}
210+
211+
/// Carried automatically by a "to do" baggage.
212+
/// It can be used to track where a context originated and which "to do" context must be fixed into a real one to avoid this.
213+
public struct TODOLocation {
214+
/// Source file location where the to-do `Baggage` was created
215+
public let file: String
216+
/// Source line location where the to-do `Baggage` was created
217+
public let line: UInt
218+
}

0 commit comments

Comments
 (0)