Skip to content

Commit 745f711

Browse files
noctellajenkins
authored andcommitted
finagle/finagle-core: Add retaintIds method to MarshalledContext
Problem A service may want to remove extraneous contexts from being broadcasted downstream. Solution Add method `retainIds` to remove all contexts except those specified. Differential Revision: https://phabricator.twitter.biz/D1178842
1 parent d173acb commit 745f711

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

finagle-core/src/main/scala/com/twitter/finagle/context/MarshalledContext.scala

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,11 @@ final class MarshalledContext private[context] extends Context {
127127
letLocal(next)(fn)
128128
}
129129

130+
private[finagle] def retainIds[R](ids: Set[String])(fn: => R): R = {
131+
val next = env.filter { case (id, _) => ids.contains(id) }
132+
letLocal(next)(fn)
133+
}
134+
130135
def letClearAll[R](fn: => R): R = local.letClear(fn)
131136

132137
/**

finagle-core/src/test/scala/com/twitter/finagle/context/MarshalledContextTest.scala

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,55 @@ class MarshalledContextTest extends AbstractContextTest {
6262
}
6363
}
6464

65+
test("retainIds") {
66+
val ctx = new MarshalledContext
67+
68+
def stringKey(id: String): ctx.Key[String] = new ctx.Key[String](id) {
69+
def marshal(value: String): Buf = Buf.Utf8(value)
70+
def tryUnmarshal(buf: Buf): Return[String] = buf match {
71+
case Buf.Utf8(value) => Return(value)
72+
}
73+
}
74+
75+
val fooKey = stringKey("foo")
76+
val barKey = stringKey("bar")
77+
val bazKey = stringKey("baz")
78+
79+
ctx.let(
80+
Seq(
81+
ctx.KeyValuePair(fooKey, "foo-value"),
82+
ctx.KeyValuePair(barKey, "bar-value"),
83+
ctx.KeyValuePair(bazKey, "baz-value"))) {
84+
85+
assert(
86+
ctx.marshal() == Map(
87+
fooKey.marshalId -> Buf.Utf8("foo-value"),
88+
barKey.marshalId -> Buf.Utf8("bar-value"),
89+
bazKey.marshalId -> Buf.Utf8("baz-value"),
90+
))
91+
92+
ctx.retainIds(Set("foo", "baz")) {
93+
assert(
94+
ctx.marshal() == Map(
95+
fooKey.marshalId -> Buf.Utf8("foo-value"),
96+
bazKey.marshalId -> Buf.Utf8("baz-value")
97+
))
98+
99+
ctx.retainIds(Set("foo")) {
100+
assert(
101+
ctx.marshal() == Map(
102+
fooKey.marshalId -> Buf.Utf8("foo-value")
103+
))
104+
105+
// qux doesn't exist
106+
ctx.retainIds(Set("qux")) {
107+
assert(ctx.marshal().isEmpty)
108+
}
109+
}
110+
}
111+
}
112+
}
113+
65114
test("key lookups are case insensitive") {
66115
val ctx = new MarshalledContext
67116
val lowerKey = new ctx.Key[String]("foo") {

0 commit comments

Comments
 (0)