Skip to content

util/ctxkey: add package for type-safe context keys - #10841

Merged
dsnet merged 1 commit into
mainfrom
dsnet/ctxkey
Jan 13, 2024
Merged

dsnet merged 1 commit into
mainfrom
dsnet/ctxkey

Conversation

@dsnet

@dsnet dsnet commented Jan 12, 2024

Copy link
Copy Markdown
Member

The lack of type-safety in context.WithValue leads to the common pattern of defining of package-scoped type to ensure global uniqueness:

type fooKey struct{}

func withFoo(ctx context, v Foo) context.Context {
	return context.WithValue(ctx, fooKey{}, v)
}

func fooValue(ctx context) Foo {
	v, _ := ctx.Value(fooKey{}).(Foo)
	return v
}

where usage becomes:

ctx = withFoo(ctx, foo)
foo := fooValue(ctx)

With many different context keys, this can be quite tedious.

Using generics, we can simplify this as:

var fooKey = ctxkey.New("mypkg.fooKey", Foo{})

where usage becomes:

ctx = fooKey.WithValue(ctx, foo)
foo := fooKey.Value(ctx)

See https://go.dev/issue/49189

Updates #cleanup

Comment thread util/ctxkey/key.go Resolved
@danderson

Copy link
Copy Markdown
Member

General implementation question: IIRC, context values are implemented as a linked list within the stdlib context package, so lookups get increasingly slow as more keys get piled into the context.

Given the external API of this library, it seems to me like we could use a package-internal secret key to register a map[*string]any onto the context, and then attach all externally defined keys to that map. That would keep the context chain constant length as we add more data over time. And given that you don't give callers access to the raw key already, this change would be invisible to package users.

Would that be worth doing, or do we expect the context linked list to remain short enough that it's not worth it?

@dsnet

dsnet commented Jan 12, 2024

Copy link
Copy Markdown
Member Author

Interesting idea, but I don't know how we would prevent the mutability of the map from leaking.

Consider the following:

ctx1 := context.Background()
ctx2 := key.WithValue(ctx1, "foo")  // presumably this creates the underlying map
ctx2a := key.WithValue(ctx2, "bar") // this mutates the map
ctx2b := key.WithValue(ctx2, "baz") // this also mutates the map

fmt.Println(key.Value(ctx2))  // should print foo
fmt.Println(key.Value(ctx2a)) // should print bar
fmt.Println(key.Value(ctx2b)) // should print baz

with the map idea, all of them would print "baz", which is incorrect.

Comment thread util/ctxkey/key.go Resolved
@dsnet
dsnet force-pushed the dsnet/ctxkey branch 2 times, most recently from d0145e9 to 19d9d53 Compare January 13, 2024 01:06
@dsnet

dsnet commented Jan 13, 2024

Copy link
Copy Markdown
Member Author

Adjusted the code to assist in debugging. Printing a context will now print the key and values in the entire chain after https://go-review.googlesource.com/c/go/+/555697 gets merged upstream.

@dsnet
dsnet force-pushed the dsnet/ctxkey branch 4 times, most recently from 742610f to b88d487 Compare January 13, 2024 01:25
The lack of type-safety in context.WithValue leads to the common pattern
of defining of package-scoped type to ensure global uniqueness:

	type fooKey struct{}

	func withFoo(ctx context, v Foo) context.Context {
		return context.WithValue(ctx, fooKey{}, v)
	}

	func fooValue(ctx context) Foo {
		v, _ := ctx.Value(fooKey{}).(Foo)
		return v
	}

where usage becomes:

	ctx = withFoo(ctx, foo)
	foo := fooValue(ctx)

With many different context keys, this can be quite tedious.

Using generics, we can simplify this as:

	var fooKey = ctxkey.New("mypkg.fooKey", Foo{})

where usage becomes:

	ctx = fooKey.WithValue(ctx, foo)
	foo := fooKey.Value(ctx)

See https://go.dev/issue/49189

Updates #cleanup

Signed-off-by: Joe Tsai <[email protected]>
@dsnet
dsnet merged commit 241a541 into main Jan 13, 2024
@dsnet
dsnet deleted the dsnet/ctxkey branch January 13, 2024 01:35
Asutorufa pushed a commit to Asutorufa/tailscale that referenced this pull request Jan 19, 2024
The lack of type-safety in context.WithValue leads to the common pattern
of defining of package-scoped type to ensure global uniqueness:

	type fooKey struct{}

	func withFoo(ctx context, v Foo) context.Context {
		return context.WithValue(ctx, fooKey{}, v)
	}

	func fooValue(ctx context) Foo {
		v, _ := ctx.Value(fooKey{}).(Foo)
		return v
	}

where usage becomes:

	ctx = withFoo(ctx, foo)
	foo := fooValue(ctx)

With many different context keys, this can be quite tedious.

Using generics, we can simplify this as:

	var fooKey = ctxkey.New("mypkg.fooKey", Foo{})

where usage becomes:

	ctx = fooKey.WithValue(ctx, foo)
	foo := fooKey.Value(ctx)

See https://go.dev/issue/49189

Updates #cleanup

Signed-off-by: Joe Tsai <[email protected]>
chen8945 pushed a commit to Ckid-Home/tailscale that referenced this pull request Jul 31, 2024
The lack of type-safety in context.WithValue leads to the common pattern
of defining of package-scoped type to ensure global uniqueness:

	type fooKey struct{}

	func withFoo(ctx context, v Foo) context.Context {
		return context.WithValue(ctx, fooKey{}, v)
	}

	func fooValue(ctx context) Foo {
		v, _ := ctx.Value(fooKey{}).(Foo)
		return v
	}

where usage becomes:

	ctx = withFoo(ctx, foo)
	foo := fooValue(ctx)

With many different context keys, this can be quite tedious.

Using generics, we can simplify this as:

	var fooKey = ctxkey.New("mypkg.fooKey", Foo{})

where usage becomes:

	ctx = fooKey.WithValue(ctx, foo)
	foo := fooKey.Value(ctx)

See https://go.dev/issue/49189

Updates #cleanup

Signed-off-by: Joe Tsai <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants