可用于在 Swift 任务和函数间传递额外上下文信息,是构建跨切面工具的基础。它是零依赖的上下文传播容器,支持并发环境安全使用,采用值类型并通过任务本地值传播,为分布式追踪等提供基础支持。【此简介由AI生成】
Access rate limit exceeded. Please log in to continue.
Swift Service Context
ServiceContext is a minimal (zero-dependency) context propagation container, intended to "carry" items for purposes of cross-cutting tools to be built on top of it.
It is modeled after the concepts explained in W3C Baggage and in the spirit of Tracing Plane 's "Baggage Context" type, although by itself it does not define a specific serialization format.
See https://github.com/apple/swift-distributed-tracing for actual instrument types and implementations which can be used to deploy various cross-cutting instruments all reusing the same baggage type. More information can be found in the SSWG meeting notes.
Overview
ServiceContext serves as currency type for carrying around additional contextual information between Swift tasks and functions.
One generally starts from a "top level" (empty) or the "current" (ServiceContext.current) context and then adds values to it.
The context is a value type and is propagated using task-local values so it can be safely used from concurrent contexts like this:
var context = ServiceContext.topLevel
context[FirstTestKey.self] = 42
func exampleFunction() async -> Int {
guard let context = ServiceContext.current else {
return 0
}
guard let value = context[FirstTestKey.self] else {
return 0
}
print("test = \(value)") // test = 42
return value
}
let c = await ServiceContext.withValue(context) {
await exampleFunction()
}
assert(c == 42)
ServiceContext is a fundamental building block for how distributed tracing propagates trace identifiers.
Dependency
In order to depend on this library you can use the Swift Package Manager, and add the following dependency to your Package.swift:
dependencies: [
.package(
url: "https://github.com/apple/swift-service-context.git",
from: "1.0.0"
)
]
and depend on the module in your target:
targets: [
.target(
name: "MyAwesomeApp",
dependencies: [
.product(
name: "ServiceContextModule",
package: "swift-service-context"
),
]
),
// ...
]
Introduction
可用于在 Swift 任务和函数间传递额外上下文信息,是构建跨切面工具的基础。它是零依赖的上下文传播容器,支持并发环境安全使用,采用值类型并通过任务本地值传播,为分布式追踪等提供基础支持。【此简介由AI生成】
Customize your domain