swift-http-types
swift-http-types copied to clipboard
Consider adding metadata property
There are many use cases where you may want to store some metadata on the request or even response (for example storing a request ID or a trace ID for distributed systems). Currently there's no way to do this, without adding an additional header which may not be desirable, or a pseudo header which feels like it's working around the problem rather than solving it.
Would a dictionary property or similar be something the team would consider?
Yes please! When I implemented this in my own code, I used a protocol-based approach like SwiftUI's EnvironmentKey
, with an underlying dictionary for storage. That made it very nice for storing arbitrary metadata on requests (authorization providers, authentication challenge responders, retry strategies, throttling behaviors, redirection handlers, etc) in a type-safe way.
I don’t think putting metadata on the request object here is appropriate. The request object represents a HTTP request, not a request plus arbitrary context. It seems more appropriate for that combination to be separate from the specifics of this type. If it isn’t semantically part of the type, it shouldn’t be here, IMO.
I agree with @Lukasa here. These types should be the raw representation of the specs and provide a common set of types that we can share across the various frameworks and platforms. Adding arbitrary metadata or extracting common metadata from headers should be handled at a higher level like Vapor or Hummingbird.
Speaking from experience. NSURLRequest supported custom properties through NSURLProtocol, and it has caused us a few headaches over the years:
- Unexpected memory usage because NSURLCache kept some requests in memory and didn't realize that they each kept a large graph of objects alive.
- Difficulty in serialization and deserialization when sending these objects across XPC since custom properties might not be secure coding compliant and we don't know which types to allow when decoding. We ended up sanitizing these properties to just property list types during serialization.
Yes, having extra metadata is often useful, but there should be a better way to achieve this than having [AnyHashable: Any]
hanging on every type.