-
Notifications
You must be signed in to change notification settings - Fork 35
Adding metadata to shardcake's internal calls. #155
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ghostdogpr
merged 10 commits into
devsisters:series/2.x
from
douglasthomsen:add-request-metadata
Apr 12, 2025
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
0754af8
Example of adding metadata to shardcake's internal calls.
douglasthomsen 5666b73
Updating var name.
douglasthomsen f01a7bc
Renaming GrpcConfig vars
douglasthomsen f3f0d1b
Moving HandlerAspect to an argument in Server.run.
douglasthomsen f3cd4a0
Updating comments.
douglasthomsen 85d0c61
Removing unused changes.
douglasthomsen aec52d8
Adding serverInterceptors implementation.
douglasthomsen 4f79abf
Adding tests
douglasthomsen 4f1627b
Merge branch 'series/2.x' into add-request-metadata
douglasthomsen 15e94e1
Adding tests
douglasthomsen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| package example | ||
|
|
||
| import com.devsisters.shardcake._ | ||
| import com.devsisters.shardcake.interfaces.{ Pods, Storage } | ||
| import io.grpc.{ Metadata, Status } | ||
| import scalapb.zio_grpc.{ ZClientInterceptor, ZTransform } | ||
| import zio.test._ | ||
| import zio.{ Config => _, _ } | ||
|
|
||
| object GrpcAuthExampleSpec extends ZIOSpecDefault { | ||
|
|
||
| private val validAuthenticationKey = "validAuthenticationKey" | ||
|
|
||
| private val authKey = Metadata.Key.of("authentication-key", io.grpc.Metadata.ASCII_STRING_MARSHALLER) | ||
|
|
||
| private val config = ZLayer.succeed(Config.default.copy(simulateRemotePods = true)) | ||
|
|
||
| private def grpcConfigLayer(clientAuthKey: String): ULayer[GrpcConfig] = | ||
| ZLayer.succeed( | ||
| GrpcConfig.default.copy( | ||
| clientInterceptors = Seq( | ||
| ZClientInterceptor.headersUpdater((_, _, md) => md.put(authKey, clientAuthKey).unit) | ||
| ), | ||
| serverInterceptors = Seq( | ||
| ZTransform { requestContext => | ||
| for { | ||
| authenticated <- requestContext.metadata.get(authKey).map(_.contains(validAuthenticationKey)) | ||
| _ <- ZIO.when(!authenticated)(ZIO.fail(Status.UNAUTHENTICATED.asException)) | ||
| } yield requestContext | ||
| } | ||
| ) | ||
| ) | ||
| ) | ||
|
|
||
| def spec: Spec[TestEnvironment with Scope, Any] = | ||
| suite("GrpcAuthExampleSpec")( | ||
| test("auth example for gRPC") { | ||
| val podAddress = PodAddress("localhost", 54321) | ||
| ZIO.scoped { | ||
| for { | ||
| _ <- Sharding.registerScoped | ||
| podsClient <- ZIO.service[Pods] | ||
| invalidPodsClient <- ZIO | ||
| .service[Pods] | ||
| .provide( | ||
| grpcConfigLayer("invalid"), | ||
| GrpcPods.live | ||
| ) | ||
| validRequest <- podsClient.ping(podAddress).exit | ||
| invalidRequest <- invalidPodsClient.ping(podAddress).exit | ||
| } yield assertTrue(validRequest.isSuccess, invalidRequest.isFailure) | ||
| } | ||
| } | ||
| ).provide( | ||
| ShardManagerClient.local, | ||
| Storage.memory, | ||
| config, | ||
| grpcConfigLayer(validAuthenticationKey), | ||
| Sharding.live, | ||
| KryoSerialization.live, | ||
| GrpcPods.live, | ||
| GrpcShardingService.live | ||
| ) | ||
| } |
65 changes: 65 additions & 0 deletions
65
examples/src/test/scala/example/ShardManagerAuthExampleSpec.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| package example | ||
|
|
||
| import com.devsisters.shardcake.{ Config, ManagerConfig, Server, ShardManager, ShardManagerClient } | ||
| import com.devsisters.shardcake.interfaces.{ Pods, PodsHealth, Storage } | ||
| import sttp.client3.SttpBackend | ||
| import sttp.client3.asynchttpclient.zio.AsyncHttpClientZioBackend | ||
| import sttp.client3.httpclient.zio.ZioWebSocketsStreams | ||
| import zio.Clock.ClockLive | ||
| import zio.http.{ Header, Middleware } | ||
| import zio.test._ | ||
| import zio.{ Config => _, _ } | ||
|
|
||
| object ShardManagerAuthExampleSpec extends ZIOSpecDefault { | ||
|
|
||
| val validToken = "validBearerToken" | ||
|
|
||
| val shardManagerServerLayer: ZLayer[ManagerConfig, Throwable, Unit] = | ||
| ZLayer.makeSome[ManagerConfig, Unit]( | ||
| ZLayer( | ||
| Server | ||
| .run(Middleware.bearerAuthZIO(secret => ZIO.succeed(secret.stringValue.equals(validToken)))) | ||
| .forkDaemon *> ClockLive.sleep(3 seconds).unit | ||
| ), | ||
| Storage.memory, | ||
| ShardManager.live, | ||
| Pods.noop, | ||
| PodsHealth.noop | ||
| ) | ||
|
|
||
| def sttpBackendWithAuthTokenLayer(token: String): ZLayer[Scope, Throwable, SttpBackend[Task, ZioWebSocketsStreams]] = | ||
| ZLayer { | ||
| val authHeader = Header.Authorization.Bearer(token) | ||
| AsyncHttpClientZioBackend.scoped(customizeRequest = | ||
| builder => builder.addHeader(authHeader.headerName, authHeader.renderedValue) | ||
| ) | ||
| } | ||
|
|
||
| def spec: Spec[TestEnvironment, Any] = | ||
| suite("ShardManagerAuthSpec")( | ||
| test("auth example for shard manager") { | ||
| ZIO.scoped { | ||
| for { | ||
| validClient <- ZIO | ||
| .service[ShardManagerClient] | ||
| .provideSome[Config & Scope]( | ||
| sttpBackendWithAuthTokenLayer(validToken), | ||
| ShardManagerClient.live | ||
| ) | ||
| invalidClient <- ZIO | ||
| .service[ShardManagerClient] | ||
| .provideSome[Config & Scope]( | ||
| sttpBackendWithAuthTokenLayer("invalid"), | ||
| ShardManagerClient.live | ||
| ) | ||
| validRequest <- validClient.getAssignments.exit | ||
| invalidRequest <- invalidClient.getAssignments.exit | ||
| } yield assertTrue(validRequest.isSuccess, invalidRequest.isFailure) | ||
| } | ||
| } | ||
| ).provide( | ||
| shardManagerServerLayer, | ||
| ZLayer.succeed(Config.default), | ||
| ZLayer.succeed(ManagerConfig.default) | ||
| ) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -84,29 +84,38 @@ object GrpcShardingService { | |
| val live: ZLayer[Config with Sharding with GrpcConfig, Throwable, Unit] = | ||
| ZLayer.scoped[Config with Sharding with GrpcConfig] { | ||
| for { | ||
| config <- ZIO.service[Config] | ||
| grpcConfig <- ZIO.service[GrpcConfig] | ||
| sharding <- ZIO.service[Sharding] | ||
| builder = grpcConfig.executor match { | ||
| case Some(executor) => | ||
| ServerBuilder | ||
| .forPort(config.shardingPort) | ||
| .executor(executor) | ||
| case None => | ||
| ServerBuilder.forPort(config.shardingPort) | ||
| } | ||
| services <- ServiceList.add(new GrpcShardingService(sharding, config.sendTimeout) {}).bindAll | ||
| server: Server = services | ||
| .foldLeft(builder) { case (builder0, service) => builder0.addService(service) } | ||
| .addService(ProtoReflectionService.newInstance()) | ||
| .build() | ||
| _ <- ZIO.acquireRelease(ZIO.attempt(server.start()))(server => | ||
| ZIO.attemptBlocking { | ||
| server.shutdown() | ||
| server.awaitTermination(grpcConfig.shutdownTimeout.toMillis, TimeUnit.MILLISECONDS) | ||
| server.shutdownNow() | ||
| }.ignore | ||
| ) | ||
| config <- ZIO.service[Config] | ||
| grpcConfig <- ZIO.service[GrpcConfig] | ||
| sharding <- ZIO.service[Sharding] | ||
| builder = grpcConfig.executor match { | ||
| case Some(executor) => | ||
| ServerBuilder | ||
| .forPort(config.shardingPort) | ||
| .executor(executor) | ||
| case None => | ||
| ServerBuilder.forPort(config.shardingPort) | ||
| } | ||
| grpcShardingService = new GrpcShardingService(sharding, config.sendTimeout) {} | ||
| services <- | ||
| ServiceList | ||
| .add( | ||
| grpcConfig.serverInterceptors | ||
| .reduceOption(_.andThen(_)) | ||
| .map(t => grpcShardingService.transform(t)) | ||
| .getOrElse(grpcShardingService.asGeneric) | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The |
||
| ) | ||
| .bindAll | ||
| server: Server = services | ||
| .foldLeft(builder) { case (builder0, service) => builder0.addService(service) } | ||
| .addService(ProtoReflectionService.newInstance()) | ||
| .build() | ||
| _ <- ZIO.acquireRelease(ZIO.attempt(server.start()))(server => | ||
| ZIO.attemptBlocking { | ||
| server.shutdown() | ||
| server.awaitTermination(grpcConfig.shutdownTimeout.toMillis, TimeUnit.MILLISECONDS) | ||
| server.shutdownNow() | ||
| }.ignore | ||
| ) | ||
| } yield () | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Originally, I tried the following to add the interceptors:
but it did not like that I changed the type of the service from
GShardingService[Any, StatusException]toGShardingService[RequestContext, StatusException]. So combining all of the server interceptors into one interceptor was the simplest solution.