code
stringlengths
0
56.1M
repo_name
stringclasses
515 values
path
stringlengths
2
147
language
stringclasses
447 values
license
stringclasses
7 values
size
int64
0
56.8M
github.com/bsm/redislock v0.8.2 h1:W0aDRjt6FNmAZovbG2fPyjl1YZZdlqMkCKKCffJew1o= github.com/bsm/redislock v0.8.2/go.mod h1:tC0JZxZCdJN4DCB31cGxgjgf/ye1R4LLNJQd5ecjg08= github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/dapr/go-sdk v1.8.0 h1:OEleeL3zUTqXxIZ7Vkk3PClAeCh1g8sZ1yR2JFZKfXM= github.com/dapr/go-sdk v1.8.0/go.mod h1:MBcTKXg8PmBc8A968tVWQg1Xt+DZtmeVR6zVVVGcmeA= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/go-chi/chi/v5 v5.0.8 h1:lD+NLqFcAi1ovnVZpsnObHGW4xb4J8lNmoYVfECH1Y0= github.com/go-chi/chi/v5 v5.0.8/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= github.com/go-redis/redis/v9 v9.0.0-rc.1 h1:/+bS+yeUnanqAbuD3QwlejzQZ+4eqgfUtFTG4b+QnXs= github.com/go-redis/redis/v9 v9.0.0-rc.1/go.mod h1:8et+z03j0l8N+DvsVnclzjf3Dl/pFHgRk+2Ct1qw66A= github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= github.com/onsi/gomega v1.21.1 h1:OB/euWYIExnPBohllTicTHmGTrMaqJ67nIu80j0/uEM= github.com/onsi/gomega v1.21.1/go.mod h1:iYAIXgPSaDHak0LCMA+AWBpIKBr8WZicMxnE8luStNc= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50= golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.55.0 h1:3Oj82/tFSCeUrRTg/5E/7d/W5A1tj6Ky1ABAuZuv5ag= google.golang.org/grpc v1.55.0/go.mod h1:iYEXKGkEBhg1PjZQvoYEVPTDkHo1/bjTnfwTeGONTY8= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
mikeee/dapr
tests/apps/perf/actor-activation-locker/go.sum
sum
mit
5,809
FROM golang:1.22.3-bullseye as build_env ENV CGO_ENABLED=0 WORKDIR /app COPY *.go go.mod go.sum ./ RUN go get -d -v && go build -o tester . FROM golang:1.22-bullseye as fortio_build_env WORKDIR /fortio ADD "https://api.github.com/repos/dapr/fortio/branches/v1.38.4-dapr" skipcache RUN git clone https://github.com/dapr/fortio.git RUN cd fortio && git checkout v1.38.4-dapr && go build FROM debian:bullseye-slim WORKDIR / COPY --from=build_env /app/tester / COPY --from=fortio_build_env /fortio/fortio/fortio /usr/local/bin CMD ["/tester"]
mikeee/dapr
tests/apps/perf/actorfeatures/Dockerfile
Dockerfile
mit
543
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "encoding/json" "fmt" "log" "net/http" "os" "strings" chi "github.com/go-chi/chi/v5" ) const ( appPort = 3000 daprV1URL = "http://localhost:3500/v1.0" actorMethodURLFormat = daprV1URL + "/actors/%s/%s/%s/%s" actorSaveStateURLFormat = daprV1URL + "/actors/%s/%s/state/" actorGetStateURLFormat = daprV1URL + "/actors/%s/%s/state/%s/" defaultActorType = "testactorfeatures" // Actor type must be unique per test app. actorTypeEnvName = "TEST_APP_ACTOR_TYPE" // Env variable tests can set to change actor type. actorIdleTimeout = "1h" drainOngoingCallTimeout = "30s" drainRebalancedActors = true secondsToWaitInMethod = 5 ) type daprConfig struct { Entities []string `json:"entities,omitempty"` ActorIdleTimeout string `json:"actorIdleTimeout,omitempty"` DrainOngoingCallTimeout string `json:"drainOngoingCallTimeout,omitempty"` DrainRebalancedActors bool `json:"drainRebalancedActors,omitempty"` } var registeredActorType = map[string]bool{} var daprConfigResponse = daprConfig{ getActorType(), actorIdleTimeout, drainOngoingCallTimeout, drainRebalancedActors, } func getActorType() []string { actorType := os.Getenv(actorTypeEnvName) if actorType == "" { registeredActorType[defaultActorType] = true return []string{defaultActorType} } actorTypes := strings.Split(actorType, ",") for _, tp := range actorTypes { registeredActorType[tp] = true } return actorTypes } // indexHandler is the handler for root path func indexHandler(w http.ResponseWriter, r *http.Request) { log.Println("indexHandler is called") w.WriteHeader(http.StatusOK) } func configHandler(w http.ResponseWriter, r *http.Request) { log.Printf("Processing Dapr request for %s, responding with %#v", r.URL.RequestURI(), daprConfigResponse) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(daprConfigResponse) } func actorMethodHandler(w http.ResponseWriter, r *http.Request) { log.Printf("Processing actor method request for %s", r.URL.RequestURI()) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) } func deactivateActorHandler(w http.ResponseWriter, r *http.Request) { log.Printf("Processing %s actor request for %s", r.Method, r.URL.RequestURI()) actorType := chi.URLParam(r, "actorType") if !registeredActorType[actorType] { log.Printf("Unknown actor type: %s", actorType) w.WriteHeader(http.StatusBadRequest) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) } func healthzHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("")) } // appRouter initializes restful api router func appRouter() http.Handler { router := chi.NewRouter() router.Get("/", indexHandler) router.Get("/dapr/config", configHandler) router.Put("/actors/{actorType}/{id}/method/{method}", actorMethodHandler) router.Put("/actors/{actorType}/{id}/method/{reminderOrTimer}/{method}", actorMethodHandler) router.Post("/actors/{actorType}/{id}", deactivateActorHandler) router.Delete("/actors/{actorType}/{id}", deactivateActorHandler) router.Get("/healthz", healthzHandler) router.HandleFunc("/test", fortioTestHandler) return router } func main() { log.Printf("Actor App - listening on http://localhost:%d", appPort) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", appPort), appRouter())) }
mikeee/dapr
tests/apps/perf/actorfeatures/app.go
GO
mit
4,074
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "encoding/json" "fmt" "io" "log" "net/http" "os" "os/exec" "strconv" ) // TODO: change to take from "github.com/dapr/dapr/tests/perf" once in repository. otherwise fails on go get step in Dockerfile. type TestParameters struct { QPS int `json:"qps"` ClientConnections int `json:"clientConnections"` TargetEndpoint string `json:"targetEndpoint"` TestDuration string `json:"testDuration"` PayloadSizeKB int `json:"payloadSizeKB"` Payload string `json:"payload"` StdClient bool `json:"stdClient"` Grpc bool `json:"grpc"` Dapr string `json:"dapr"` } func fortioTestHandler(w http.ResponseWriter, r *http.Request) { log.Println("Test execution request received") var testParams TestParameters b, err := io.ReadAll(r.Body) if err != nil { w.WriteHeader(500) w.Write([]byte(fmt.Sprintf("error reading request body: %s", err))) return } err = json.Unmarshal(b, &testParams) if err != nil { w.WriteHeader(400) w.Write([]byte(fmt.Sprintf("error parsing test params: %s", err))) return } log.Println("Executing test") results, err := runFortioTest(testParams) if err != nil { w.WriteHeader(500) w.Write([]byte(fmt.Sprintf("error encountered while running test: %s", err))) return } log.Println("Test finished") w.Header().Add("Content-Type", "application/json") w.Write(results) } // runFortioTest accepts a set of test parameters, runs Fortio with the configured setting and returns // the test results in json format. func runFortioTest(params TestParameters) ([]byte, error) { args := buildFortioArgs(params) log.Printf("Running test with params: %s", args) cmd := exec.Command("fortio", args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() if err != nil { return nil, err } return os.ReadFile("result.json") } func buildFortioArgs(params TestParameters) []string { var args []string if len(params.Payload) > 0 { args = []string{ "load", "-json", "result.json", "-content-type", "application/json", "-qps", strconv.Itoa(params.QPS), "-c", strconv.Itoa(params.ClientConnections), "-t", params.TestDuration, "-payload", params.Payload, } } else { args = []string{ "load", "-json", "result.json", "-qps", strconv.Itoa(params.QPS), "-c", strconv.Itoa(params.ClientConnections), "-t", params.TestDuration, "-payload-size", strconv.Itoa(params.PayloadSizeKB), } } if params.StdClient { args = append(args, "-stdclient") } if params.Grpc { args = append(args, "-grpc") } if params.Dapr != "" { args = append(args, "-dapr", params.Dapr) } args = append(args, params.TargetEndpoint) return args }
mikeee/dapr
tests/apps/perf/actorfeatures/fortio.go
GO
mit
3,304
module github.com/dapr/dapr/tests/apps/perf/tester go 1.22.3 require github.com/go-chi/chi/v5 v5.0.10
mikeee/dapr
tests/apps/perf/actorfeatures/go.mod
mod
mit
104
github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk= github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
mikeee/dapr
tests/apps/perf/actorfeatures/go.sum
sum
mit
169
.project .classpath .settings /server.restapi/gitignore /server.restapi/*.log /server.restapi/.settings/* /adminInterface/node_modules /server.restapi.dynamic/target/classes/com/bosch/iot/dashboard/api/adapter/*.class /server.restapi.dynamic/target /webhooks/target /.metadata/ .idea */**/*.iml *.iml /bin/ */**/target/ target/ *.log *.swp */**/lombok*.jar lombok*.jar *private.env.json */**/node_modules/
mikeee/dapr
tests/apps/perf/actorjava/.gitignore
Git
mit
406
# build stage build the jar with all our resources FROM maven:3-eclipse-temurin-11 as build VOLUME /tmp WORKDIR /build COPY pom.xml . RUN mvn dependency:go-offline ADD src/ /build/src/ RUN mvn package # package stage FROM eclipse-temurin:11-jre ARG JAR_FILE COPY --from=build /build/target/app.jar /opt/app.jar WORKDIR /opt/ EXPOSE 3000 ENTRYPOINT java -jar app.jar --server.port=3000
mikeee/dapr
tests/apps/perf/actorjava/Dockerfile
Dockerfile
mit
391
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.0.RELEASE</version> </parent> <groupId>io.dapr.apps.actor</groupId> <artifactId>actorjava</artifactId> <version>0.0.0-SNAPSHOT</version> <packaging>jar</packaging> <name>actorjava</name> <description>Module for polling against adapters</description> <properties> <dapr-sdk.version>1.0.0-rc-6</dapr-sdk.version> </properties> <repositories> <repository> <id>oss-snapshots</id> <url>https://oss.sonatype.org/content/repositories/snapshots</url> </repository> <repository> <id>oss-release</id> <url>https://oss.sonatype.org/content/repositories/releases/</url> </repository> </repositories> <distributionManagement> <!-- BEGIN: Dapr's repositories --> <!-- END: Dapr's repositories --> </distributionManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>io.dapr</groupId> <artifactId>dapr-sdk</artifactId> <version>${dapr-sdk.version}</version> </dependency> <dependency> <groupId>io.dapr</groupId> <artifactId>dapr-sdk-springboot</artifactId> <version>${dapr-sdk.version}</version> </dependency> <dependency> <groupId>io.dapr</groupId> <artifactId>dapr-sdk-actors</artifactId> <version>${dapr-sdk.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-kotlin</artifactId> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.2.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.11.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <finalName>app</finalName> <resources> <resource> <directory>src/main/resources</directory> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
mikeee/dapr
tests/apps/perf/actorjava/pom.xml
XML
mit
3,721
package io.dapr.apps.actor; import io.dapr.actors.client.ActorProxyBuilder; import io.dapr.actors.client.ActorClient; import io.dapr.apps.actor.actors.DemoActorTimer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ActorConfig { public static final ActorClient ACTOR_CLIENT = new ActorClient(); @Bean public ActorProxyBuilder<DemoActorTimer> demoActorProxyBuilder() { return new ActorProxyBuilder<>(DemoActorTimer.class, ACTOR_CLIENT); } }
mikeee/dapr
tests/apps/perf/actorjava/src/main/java/io/dapr/apps/actor/ActorConfig.java
Java
mit
562
package io.dapr.apps.actor; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import io.dapr.actors.runtime.ActorRuntime; import io.dapr.apps.actor.actors.DemoActorTimerImpl; @SpringBootApplication(scanBasePackages = { "io.dapr.apps.actor", "io.dapr.springboot"}) public class Application { public static void main(String[] args) { ActorRuntime.getInstance().registerActor(DemoActorTimerImpl.class); SpringApplication.run(Application.class, args); } }
mikeee/dapr
tests/apps/perf/actorjava/src/main/java/io/dapr/apps/actor/Application.java
Java
mit
551
package io.dapr.apps.actor; import java.util.UUID; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.dapr.actors.ActorId; import io.dapr.actors.client.ActorProxyBuilder; import io.dapr.apps.actor.actors.DemoActorTimer; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.Mono; @RestController @Slf4j @RequiredArgsConstructor public class ApplicationController { private final ActorProxyBuilder<DemoActorTimer> demoActorProxyBuilder; @RequestMapping(value="/actors", method = RequestMethod.POST, consumes = "*") @ResponseStatus(HttpStatus.OK) @ResponseBody public Mono<Void> activateActor() { ActorId actorId = new ActorId(UUID.randomUUID().toString()); return Mono.fromRunnable(() -> { log.info("creating actor with id: {}", actorId); DemoActorTimer demoActor = demoActorProxyBuilder.build(actorId); demoActor.registerDemoActorTimer(); }).doOnError(throwable -> log.warn("error in registerTimer() for actor ".concat(actorId.toString()) .concat(" - ").concat(throwable.getMessage()), throwable)).then(); } @GetMapping(path = "/health") public Mono<Void> health() { return Mono.empty(); } }
mikeee/dapr
tests/apps/perf/actorjava/src/main/java/io/dapr/apps/actor/ApplicationController.java
Java
mit
1,763
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package io.dapr.apps.actor.actors; import io.dapr.actors.ActorType; /** * Example of implementation of an Actor. */ @ActorType(name = "DemoActorTimer") public interface DemoActorTimer { void registerDemoActorTimer(); String say(String something); void noOp(); }
mikeee/dapr
tests/apps/perf/actorjava/src/main/java/io/dapr/apps/actor/actors/DemoActorTimer.java
Java
mit
836
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package io.dapr.apps.actor.actors; import static org.apache.commons.lang3.math.NumberUtils.createDouble; import static org.apache.commons.lang3.math.NumberUtils.isParsable; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.Duration; import java.util.Calendar; import java.util.Random; import java.util.TimeZone; import io.dapr.actors.ActorId; import io.dapr.actors.runtime.AbstractActor; import io.dapr.actors.runtime.ActorRuntimeContext; import lombok.extern.slf4j.Slf4j; /**ß * Implementation of the DemoActor for the server side. */ @Slf4j public class DemoActorTimerImpl extends AbstractActor implements DemoActorTimer { private static final Random RANDOM = new Random(37); /** * Format to output date and time. */ private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); /** * Ratio to which messages are logged, default is 1.0 (100%) */ private final double logRatio; /** * This is the constructor of an actor implementation. * * @param runtimeContext The runtime context object which contains objects such as the state provider. * @param id The id of this actor. */ public DemoActorTimerImpl(ActorRuntimeContext runtimeContext, ActorId id) { super(runtimeContext, id); String logRatioString = System.getenv("LOG_RATIO"); double logRatioTemp = isParsable(logRatioString) ? createDouble(logRatioString) : 1; logRatioTemp = logRatioTemp < 0 ? 0 : logRatioTemp; logRatioTemp = logRatioTemp > 1 ? 1 : logRatioTemp; this.logRatio = logRatioTemp; } @Override public void registerDemoActorTimer() { super.registerActorTimer( "sayTimer", "say", "Hello World!", Duration.ofSeconds(10), Duration.ofSeconds(10)) .subscribe( avoid -> log.info("timer registered successfully"), error -> log.warn(error.getMessage()), () -> log.info("registerTimer completed")); } /** * Prints a message and appends the timestamp. * * @param something Something to be said. * @return Timestamp. */ @Override public String say(String something) { Calendar utcNow = Calendar.getInstance(TimeZone.getTimeZone("GMT")); String utcNowAsString = dateFormat.format(utcNow.getTime()); String timestampedMessage = something == null ? "" : something + " @ " + utcNowAsString; // Handles the request by printing message. if (RANDOM.nextDouble() < logRatio) { log.info("Server say method for actor " + super.getId() + ": " + timestampedMessage); } // Now respond with current timestamp. return utcNowAsString; } @Override public void noOp() { // No-op to test performance without app logic impacting numbers. } }
mikeee/dapr
tests/apps/perf/actorjava/src/main/java/io/dapr/apps/actor/actors/DemoActorTimerImpl.java
Java
mit
3,576
logging.level.root=INFO # Specify the instrumentation key of your Application Insights resource. #azure.application-insights.instrumentation-key=b52f9846-b1c7-40dc-84d8-9c486a676147 # Specify the name of your spring boot application. This can be any logical name you would like to give to your app. spring.application.name=ActorJava
mikeee/dapr
tests/apps/perf/actorjava/src/main/resources/application.properties
Properties
mit
332
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "context" "encoding/json" "errors" "fmt" "io" "log" "net/http" "os" "strconv" "strings" "time" "github.com/google/uuid" "github.com/gorilla/mux" "github.com/redis/go-redis/v9" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/apps/utils" ) const ( daprConfigurationURL = "http://localhost:3500/v1.0/configuration/" daprGRPCPort = 50001 configStoreName = "configstore" separator = "||" redisHost = "dapr-redis-master.dapr-tests.svc.cluster.local:6379" writeTimeout = 5 * time.Second ) var ( appPort = 3000 updater Updater httpClient = utils.NewHTTPClient() grpcClient runtimev1pb.DaprClient notifyCh = make(chan struct{}) subscribeStopChanMap = make(map[string]map[string]chan struct{}) ) type appResponse struct { Message string `json:"message,omitempty"` StartTime int `json:"start_time,omitempty"` EndTime int `json:"end_time,omitempty"` } type Item struct { Value string `json:"value,omitempty"` Version string `json:"version,omitempty"` Metadata map[string]string `json:"metadata,omitempty"` } type UpdateEvent struct { ID string `json:"id"` Items map[string]*Item `json:"items"` } type Updater interface { Init() error Update(items map[string]*Item) error Get(key string) (string, error) Subscribe(keys []string) (string, error) } type RedisUpdater struct { client *redis.Client } func init() { p := os.Getenv("PORT") if p != "" && p != "0" { appPort, _ = strconv.Atoi(p) } } // indexHandler is the handler for root path func indexHandler(w http.ResponseWriter, r *http.Request) { log.Println("indexHandler is called") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{Message: "OK"}) } // sendResponse returns response with status code and message func sendResponse(w http.ResponseWriter, statusCode int, message string) { w.WriteHeader(statusCode) json.NewEncoder(w).Encode(appResponse{Message: message}) } // return key-value pairs as a list of strings func getRedisValuesFromItems(items map[string]*Item) []interface{} { m := make([]interface{}, 0, 2*len(items)+1) for key, item := range items { val := item.Value + separator + item.Version m = append(m, key, val) } return m } // extract value and version from redis value func getRedisValueAndVersion(redisValue string) (string, string) { valueAndRevision := strings.Split(redisValue, separator) if len(valueAndRevision) == 0 { return "", "" } if len(valueAndRevision) == 1 { return valueAndRevision[0], "" } return valueAndRevision[0], valueAndRevision[1] } func buildQueryParams(keys []string) string { if len(keys) == 0 { return "" } ret := "?key=" + keys[0] for i := 1; i < len(keys); i++ { ret = ret + "&key=" + keys[i] } return ret } // extract key from subscribed channel func parseRedisKeyFromChannel(eventChannel string) (string, error) { channelPrefix := "__keyspace@0__:" index := strings.Index(eventChannel, channelPrefix) if index == -1 { return "", fmt.Errorf("wrong format of event channel, it should start with '%s': eventChannel=%s", channelPrefix, eventChannel) } return eventChannel[len(channelPrefix):], nil } func (r *RedisUpdater) Init() error { opts := &redis.Options{ Addr: redisHost, Password: "", DB: 0, } r.client = redis.NewClient(opts) timeoutCtx, cancel := context.WithTimeout(context.Background(), writeTimeout) defer cancel() err := r.client.Ping(timeoutCtx).Err() if err != nil { return fmt.Errorf("error connecting to redis config store. err: %s", err) } return nil } func (r *RedisUpdater) Update(items map[string]*Item) error { timeoutCtx, cancel := context.WithTimeout(context.Background(), writeTimeout) defer cancel() values := getRedisValuesFromItems(items) valuesWithCommand := append([]interface{}{"MSET"}, values...) return r.client.Do(timeoutCtx, valuesWithCommand...).Err() } func (r *RedisUpdater) Get(key string) (string, error) { timeoutCtx, cancel := context.WithTimeout(context.Background(), writeTimeout) defer cancel() return r.client.Get(timeoutCtx, key).Result() } func (r *RedisUpdater) Subscribe(keys []string) (string, error) { subscribeID := uuid.New().String() keyStopChanMap := make(map[string]chan struct{}) for _, k := range keys { stop := make(chan struct{}) redisChannel := "__keyspace@0__:" + k keyStopChanMap[redisChannel] = stop go r.subscribeHandler(redisChannel, subscribeID, stop) } subscribeStopChanMap[subscribeID] = keyStopChanMap return subscribeID, nil } func (r *RedisUpdater) subscribeHandler(redisChannel string, subscribeID string, stop chan struct{}) { ctx := context.Background() r.client.ConfigSet(ctx, "notify-keyspace-events", "Kg$xe") p := r.client.Subscribe(ctx, redisChannel) defer p.Close() for { select { case <-stop: return case <-ctx.Done(): return case msg := <-p.Channel(): r.handleSubscribedChange(ctx, msg, subscribeID) } } } func (r *RedisUpdater) handleSubscribedChange(ctx context.Context, msg *redis.Message, subscribeID string) { key, err := parseRedisKeyFromChannel(msg.Channel) if err != nil { log.Printf("parse redis key failed: %s", err.Error()) return } _, err = getBaseline([]string{key}) if err != nil { log.Printf("error getting values from configstore: %s", err.Error()) return } notifyCh <- struct{}{} } func getDaprHTTP(keys []string) (string, error) { url := daprConfigurationURL + configStoreName + buildQueryParams(keys) resp, err := httpClient.Get(url) if err != nil { return "", fmt.Errorf("error getting key-values from config store. err: %w", err) } defer resp.Body.Close() respInBytes, _ := io.ReadAll(resp.Body) return string(respInBytes), nil } func getDaprGRPC(keys []string) (string, error) { res, err := grpcClient.GetConfiguration(context.Background(), &runtimev1pb.GetConfigurationRequest{ StoreName: configStoreName, Keys: keys, }) if err != nil { return "", fmt.Errorf("error getting key-values from config store. err: %w", err) } items := res.GetItems() respInBytes, _ := json.Marshal(items) return string(respInBytes), nil } func getBaseline(keys []string) (string, error) { items := make(map[string]*Item, 10) for _, key := range keys { redisVal, err := updater.Get(key) if err != nil { return "", err } val, version := getRedisValueAndVersion(redisVal) items[key] = &Item{ Value: val, Version: version, Metadata: map[string]string{}, } } itemsInBytes, err := json.Marshal(items) if err != nil { return "", err } return string(itemsInBytes), nil } // getKeyValues is the handler for getting key-values from config store func getKeyValues(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) protocol := vars["protocol"] test := vars["test"] var keys []string err := json.NewDecoder(r.Body).Decode(&keys) if err != nil { sendResponse(w, http.StatusBadRequest, err.Error()) return } var response string if test == "baseline" { response, err = getBaseline(keys) } else if test == "dapr" { if protocol == "http" { response, err = getDaprHTTP(keys) } else if protocol == "grpc" { response, err = getDaprGRPC(keys) } else { err = fmt.Errorf("unknown protocol in Get call: %s", protocol) } } if err != nil { sendResponse(w, http.StatusInternalServerError, err.Error()) return } sendResponse(w, http.StatusOK, response) } func subscribeGRPC(keys []string) (string, error) { client, err := grpcClient.SubscribeConfiguration(context.Background(), &runtimev1pb.SubscribeConfigurationRequest{ StoreName: configStoreName, Keys: keys, }) if err != nil { return "", fmt.Errorf("error subscribing config updates: %w", err) } res, err := client.Recv() if errors.Is(err, io.EOF) { return "", fmt.Errorf("error subscribe: stream closed before receiving ID") } if err != nil { return "", fmt.Errorf("error subscribe: %w", err) } subscriptionID := res.GetId() go subscribeHandlerGRPC(client) log.Printf("App subscribed to config changes with subscription id: %s", subscriptionID) return subscriptionID, nil } func subscribeHandlerGRPC(client runtimev1pb.Dapr_SubscribeConfigurationClient) { for { rsp, err := client.Recv() if errors.Is(err, io.EOF) || rsp == nil { log.Print("Dapr GRPC subscribe completed") break } if err != nil { log.Printf("Error receiving config updates: %v", err) break } notifyCh <- struct{}{} } } func subscribeHTTP(keys []string) (string, error) { url := daprConfigurationURL + configStoreName + "/subscribe" + buildQueryParams(keys) resp, err := httpClient.Get(url) if err != nil { return "", fmt.Errorf("error subscribing config updates: %w", err) } defer resp.Body.Close() sub, err := io.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("error reading subscription Id: %w", err) } var subscriptionID string if strings.Contains(string(sub), "errorCode") { return "", fmt.Errorf("error subscribing to config updates: %s", string(sub)) } var subid map[string]interface{} json.Unmarshal(sub, &subid) log.Printf("App subscribed to config changes with subscription id: %s", subid["id"]) subscriptionID = subid["id"].(string) return subscriptionID, nil } // subscribeHandlerHTTP is the handler for receiving updates from config store func subscribeHandlerHTTP(w http.ResponseWriter, r *http.Request) { var updateEvent UpdateEvent err := json.NewDecoder(r.Body).Decode(&updateEvent) if err != nil { sendResponse(w, http.StatusBadRequest, err.Error()) return } notifyCh <- struct{}{} sendResponse(w, http.StatusOK, "OK") } // startSubscription is the handler for starting a subscription to config store func startSubscription(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) protocol := vars["protocol"] test := vars["test"] var keys []string err := json.NewDecoder(r.Body).Decode(&keys) if err != nil { sendResponse(w, http.StatusBadRequest, err.Error()) return } var subscriptionID string if test == "baseline" { subscriptionID, err = updater.Subscribe(keys) } else { if protocol == "http" { subscriptionID, err = subscribeHTTP(keys) } else if protocol == "grpc" { subscriptionID, err = subscribeGRPC(keys) } else { err = fmt.Errorf("unknown protocol in Subscribe call: %s", protocol) } } if err != nil { sendResponse(w, http.StatusInternalServerError, err.Error()) return } sendResponse(w, http.StatusOK, subscriptionID) } func unsubscribeHTTP(subscriptionID string) (string, error) { url := daprConfigurationURL + configStoreName + "/" + subscriptionID + "/unsubscribe" resp, err := httpClient.Get(url) if err != nil { return "", fmt.Errorf("error unsubscribing config updates: %w", err) } defer resp.Body.Close() respInBytes, _ := io.ReadAll(resp.Body) return string(respInBytes), nil } func unsubscribeGRPC(subscriptionID string) (string, error) { resp, err := grpcClient.UnsubscribeConfiguration(context.Background(), &runtimev1pb.UnsubscribeConfigurationRequest{ StoreName: configStoreName, Id: subscriptionID, }) if err != nil { return "", fmt.Errorf("error unsubscribing config updates: %w", err) } if !resp.GetOk() { return "", fmt.Errorf("error unsubscribing config updates: %s", resp.GetMessage()) } return resp.GetMessage(), nil } func unsubscribeBaseline(subscriptionID string) (string, error) { if keyStopChanMap, ok := subscribeStopChanMap[subscriptionID]; ok { for _, stop := range keyStopChanMap { close(stop) } delete(subscribeStopChanMap, subscriptionID) return "SUCESSS", nil } return "", fmt.Errorf("subscription with id %s does not exist", subscriptionID) } // stopSubscription is the handler for unsubscribing from config store func stopSubscription(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) subscriptionID := vars["subscriptionID"] protocol := vars["protocol"] test := vars["test"] var response string var err error if test == "baseline" { response, err = unsubscribeBaseline(subscriptionID) } else { if protocol == "http" { response, err = unsubscribeHTTP(subscriptionID) } else if protocol == "grpc" { response, err = unsubscribeGRPC(subscriptionID) } else { err = fmt.Errorf("unknown protocol in unsubscribe call: %s", protocol) } } if err != nil { sendResponse(w, http.StatusInternalServerError, err.Error()) return } sendResponse(w, http.StatusOK, response) } // initializeUpdater is the handler for initializing config updater func initializeUpdater(w http.ResponseWriter, r *http.Request) { log.Printf("Initializing updater with redis component") updater = &RedisUpdater{} err := updater.Init() if err != nil { sendResponse(w, http.StatusInternalServerError, err.Error()) return } sendResponse(w, http.StatusOK, "OK") } // updateKeyValues is the handler for updating key values in the config store func updateKeyValues(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) wait := vars["wait"] items := make(map[string]*Item, 10) err := json.NewDecoder(r.Body).Decode(&items) if err != nil { sendResponse(w, http.StatusBadRequest, err.Error()) return } err = updater.Update(items) if err != nil { sendResponse(w, http.StatusBadRequest, err.Error()) return } if wait == "true" { <-notifyCh } sendResponse(w, http.StatusOK, "OK") } // appRouter initializes restful api router func appRouter() http.Handler { router := mux.NewRouter().StrictSlash(true) // Log requests and their processing time router.Use(utils.LoggerMiddleware) router.HandleFunc("/", indexHandler).Methods("GET") router.HandleFunc("/initialize-updater", initializeUpdater).Methods("GET") router.HandleFunc("/update/{wait}", updateKeyValues).Methods("POST") router.HandleFunc("/get/{test}/{protocol}", getKeyValues).Methods("POST") router.HandleFunc("/subscribe/{test}/{protocol}", startSubscription).Methods("POST") router.HandleFunc("/unsubscribe/{test}/{protocol}/{subscriptionID}", stopSubscription).Methods("GET") router.HandleFunc("/configuration/{storeName}/{key}", subscribeHandlerHTTP).Methods("POST") router.Use(mux.CORSMethodMiddleware(router)) return router } func main() { grpcClient = utils.GetGRPCClient(daprGRPCPort) log.Printf("Starting application on http://localhost:%d", appPort) utils.StartServer(appPort, appRouter, true, false) }
mikeee/dapr
tests/apps/perf/configuration/app.go
GO
mit
15,068
# Build the k6 binary with the extension FROM golang:1.22.3 as builder RUN go install go.k6.io/xk6/cmd/xk6@latest RUN xk6 build --output /k6 --with github.com/grafana/xk6-output-prometheus-remote@latest --with github.com/grafana/xk6-disruptor@350f53204c65040e71757f98a330665a8f189f91 # Use the operator's base image and override the k6 binary FROM loadimpact/k6:latest COPY --from=builder /k6 /usr/bin/k6
mikeee/dapr
tests/apps/perf/k6-custom/Dockerfile
Dockerfile
mit
407
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "errors" "log" "net/http" "os" "strconv" "time" "github.com/gorilla/websocket" ) var ( pubSubName string topic string route string ) var numMessages = 100 var upgrader = websocket.Upgrader{} // messagesCh contains the messages received var messagesCh chan string // notifyCh is used to notify completion of receiving messages var notifyCh = make(chan struct{}) // messagesMap is used to track messages received // and only count unique messages var messagesMap = map[string]struct{}{} func testHandler(w http.ResponseWriter, r *http.Request) { ws, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Printf("error upgrading websocket: %s", err) return } defer ws.Close() <-notifyCh err = ws.WriteMessage(websocket.TextMessage, []byte("true")) if err != nil { log.Printf("error writing message: %s", err) } // gracefully close the connection err = ws.WriteControl( websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(4*time.Second)) if err != nil { log.Printf("error closing websocket: %s", err) } } func notify(msgRecvCh chan string, notifySendCh chan struct{}) { total := 0 for { msg := <-msgRecvCh // only count unique messages if _, present := messagesMap[msg]; !present { messagesMap[msg] = struct{}{} total++ } // notify when we have received all messages if total >= numMessages { notifySendCh <- struct{}{} total -= numMessages } } } func main() { err := readPubsubEnvVar() if err != nil { log.Fatalf("Error reading environment variables : %s", err.Error()) return } val, ok := os.LookupEnv("TEST_NUM_MESSAGES") if ok { ival, err := strconv.Atoi(val) if err != nil { log.Printf("WARNING: error parsing TEST_NUM_MESSAGES: %s, falling back to: %d", err, numMessages) } else { numMessages = ival } } messagesCh = make(chan string, numMessages) go notify(messagesCh, notifyCh) log.Printf("Env variable route is set to %s", route) http.HandleFunc("/dapr/subscribe", subscribeHandler) http.HandleFunc("/"+route+"-bulk", bulkMessageHandler) http.HandleFunc("/"+route, messageHandler) http.HandleFunc("/test", testHandler) log.Fatal(http.ListenAndServe(":3000", nil)) //nolint:gosec } func readPubsubEnvVar() error { pubSubName = os.Getenv("PERF_PUBSUB_HTTP_COMPONENT_NAME") topic = os.Getenv("PERF_PUBSUB_HTTP_TOPIC_NAME") route = os.Getenv("PERF_PUBSUB_HTTP_ROUTE_NAME") if !validateEnvVar("PERF_PUBSUB_HTTP_COMPONENT_NAME", pubSubName) { return errors.New("invalid PERF_PUBSUB_HTTP_COMPONENT_NAME") } if !validateEnvVar("PERF_PUBSUB_HTTP_TOPIC_NAME", topic) { return errors.New("invalid PERF_PUBSUB_HTTP_TOPIC_NAME") } if !validateEnvVar("PERF_PUBSUB_HTTP_ROUTE_NAME", route) { return errors.New("invalid PERF_PUBSUB_HTTP_ROUTE_NAME") } return nil } func validateEnvVar(key string, value string) bool { if value == "" { log.Printf("error: Env variable %s is set to empty", key) return false } log.Printf("Env variable %s is set to %s", key, value) return true }
mikeee/dapr
tests/apps/perf/pubsub_subscribe_http/app.go
GO
mit
3,659
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( cloudevents "github.com/cloudevents/sdk-go/v2" ) type subscription struct { PubsubName string `json:"pubsubName"` Topic string `json:"topic"` Route string `json:"route"` Metadata map[string]string `json:"metadata,omitempty"` BulkSubscribe bulkSubscribe `json:"bulkSubscribe,omitempty"` } type bulkSubscribe struct { Enabled bool `json:"enabled"` MaxMessagesCount int32 `json:"maxMessagesCount,omitempty"` MaxAwaitDurationMs int32 `json:"maxAwaitDurationMs,omitempty"` } type bulkSubscribeMessage struct { Entries []bulkSubscribeMessageEntry `json:"entries"` PubsubName string `json:"pubsubName"` Topic string `json:"topic"` Type string `json:"type"` } type bulkSubscribeMessageEntry struct { EntryID string `json:"entryId"` Event cloudevents.Event `json:"event"` Metadata map[string]string `json:"metadata,omitempty"` } type bulkSubscribeResponse struct { Statuses []bulkSubscribeResponseStatus `json:"statuses"` } type bulkSubscribeResponseStatus struct { EntryID string `json:"entryId"` Status string `json:"status"` }
mikeee/dapr
tests/apps/perf/pubsub_subscribe_http/structs.go
GO
mit
1,798
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "encoding/json" "fmt" "io" "log" "net/http" "os" "github.com/google/uuid" ) func subscribeHandler(w http.ResponseWriter, r *http.Request) { subscriptions := []subscription{} subscribeType := os.Getenv("SUBSCRIBE_TYPE") if subscribeType == "bulk" { subscriptions = append(subscriptions, subscription{ PubsubName: pubSubName, Topic: topic + "-bulk", Route: route + "-bulk", BulkSubscribe: bulkSubscribe{ Enabled: true, }, }) } else { subscriptions = append(subscriptions, subscription{ PubsubName: pubSubName, Topic: topic, Route: route, }) } log.Printf("Sending subscriptions: %#v", subscriptions) jsonBytes, err := json.Marshal(subscriptions) if err != nil { log.Fatalf("Error marshalling subscriptions: %v", err) } w.Header().Set("Content-Type", "application/json") _, err = w.Write(jsonBytes) if err != nil { log.Fatalf("Error writing response: %v", err) } } func bulkMessageHandler(w http.ResponseWriter, r *http.Request) { postBody, err := io.ReadAll(r.Body) if err != nil { log.Fatalf("Error reading request body: %v", err) } var bsm bulkSubscribeMessage err = json.Unmarshal(postBody, &bsm) if err != nil { log.Fatalf("Error unmarshalling request body: %v", err) } // log.Printf("Received %d messages", len(bsm.Entries)) bulkSubscribeResponseStatuses := make([]bulkSubscribeResponseStatus, len(bsm.Entries)) for i, entry := range bsm.Entries { messagesCh <- entry.EntryID bulkSubscribeResponseStatuses[i] = bulkSubscribeResponseStatus{ EntryID: entry.EntryID, Status: "SUCCESS", } } resp := bulkSubscribeResponse{Statuses: bulkSubscribeResponseStatuses} jsonBytes, err := json.Marshal(resp) if err != nil { log.Fatalf("Error marshalling response: %v", err) } w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") _, err = w.Write(jsonBytes) if err != nil { log.Fatalf("Error writing response: %v", err) } } func messageHandler(w http.ResponseWriter, r *http.Request) { _, err := io.ReadAll(r.Body) if err != nil { log.Fatalf("Error reading request body: %v", err) } // log.Printf("received 1 message") uuid, err := uuid.NewUUID() if err != nil { log.Fatalf("Error generating uuid: %v", err) } messagesCh <- uuid.String() w.WriteHeader(http.StatusOK) _, err = fmt.Fprint(w, "SUCCESS") if err != nil { log.Fatalf("Error writing response: %v", err) } }
mikeee/dapr
tests/apps/perf/pubsub_subscribe_http/subscribe.go
GO
mit
3,018
Dockerfile*
mikeee/dapr
tests/apps/perf/service_invocation_grpc/.dockerignore
Dockerfile
mit
11
# # Copyright 2021 The Dapr Authors # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # FROM golang:1.22.3 as build_env ENV CGO_ENABLED=0 WORKDIR /app COPY go.mod go.sum app.go . RUN go get -d -v RUN go build -o app . FROM gcr.io/distroless/base-nossl:nonroot WORKDIR / COPY --from=build_env /app/app / CMD ["/app"]
mikeee/dapr
tests/apps/perf/service_invocation_grpc/Dockerfile
Dockerfile
mit
809
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "context" "log" "github.com/dapr/go-sdk/service/common" daprd "github.com/dapr/go-sdk/service/grpc" ) func main() { s, err := daprd.NewService(":3000") if err != nil { log.Fatalf("failed to start the server: %v", err) } if err := s.AddServiceInvocationHandler("load", loadTestHandle); err != nil { log.Fatalf("error adding invocation handler: %v", err) } if err := s.Start(); err != nil { log.Fatalf("server error: %v", err) } } func loadTestHandle(ctx context.Context, in *common.InvocationEvent) (*common.Content, error) { out := &common.Content{ Data: []byte("response"), ContentType: "text/plain", } return out, nil }
mikeee/dapr
tests/apps/perf/service_invocation_grpc/app.go
GO
mit
1,242
module github.com/dapr/dapr/tests/apps/perf/service_invocation_grpc go 1.22.3 require github.com/dapr/go-sdk v1.8.0 require ( github.com/golang/protobuf v1.5.3 // indirect golang.org/x/net v0.12.0 // indirect golang.org/x/sys v0.10.0 // indirect golang.org/x/text v0.11.0 // indirect google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect google.golang.org/grpc v1.55.0 // indirect google.golang.org/protobuf v1.30.0 // indirect )
mikeee/dapr
tests/apps/perf/service_invocation_grpc/go.mod
mod
mit
460
github.com/dapr/go-sdk v1.8.0 h1:OEleeL3zUTqXxIZ7Vkk3PClAeCh1g8sZ1yR2JFZKfXM= github.com/dapr/go-sdk v1.8.0/go.mod h1:MBcTKXg8PmBc8A968tVWQg1Xt+DZtmeVR6zVVVGcmeA= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50= golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/grpc v1.55.0 h1:3Oj82/tFSCeUrRTg/5E/7d/W5A1tj6Ky1ABAuZuv5ag= google.golang.org/grpc v1.55.0/go.mod h1:iYEXKGkEBhg1PjZQvoYEVPTDkHo1/bjTnfwTeGONTY8= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
mikeee/dapr
tests/apps/perf/service_invocation_grpc/go.sum
sum
mit
2,671
# In perf tests, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing the perf test. apiVersion: apps/v1 kind: Deployment metadata: name: perf-service-invocation-grpc labels: testapp: perf-service-invocation-grpc spec: replicas: 1 selector: matchLabels: testapp: perf-service-invocation-grpc template: metadata: labels: testapp: perf-service-invocation-grpc annotations: dapr.io/enabled: "true" dapr.io/app-id: "testapp" dapr.io/app-port: "3000" dapr.io/app-protocol: "grpc" spec: containers: - name: perf-service-invocation-grpc image: docker.io/[YOUR ALIAS]/perf-service_invocation_grpc:dev ports: - containerPort: 3000 imagePullPolicy: Always
mikeee/dapr
tests/apps/perf/service_invocation_grpc/service.yaml
YAML
mit
875
Dockerfile*
mikeee/dapr
tests/apps/perf/service_invocation_http/.dockerignore
Dockerfile
mit
12
# # Copyright 2021 The Dapr Authors # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # FROM golang:1.22.3 as build_env ENV CGO_ENABLED=0 WORKDIR /app COPY . . RUN go get -d -v RUN go build -o app . FROM gcr.io/distroless/base-nossl:nonroot WORKDIR / COPY --from=build_env /app/app / CMD ["/app"]
mikeee/dapr
tests/apps/perf/service_invocation_http/Dockerfile
Dockerfile
mit
790
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "log" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) } func main() { http.HandleFunc("/test", handler) log.Fatal(http.ListenAndServe(":3000", nil)) }
mikeee/dapr
tests/apps/perf/service_invocation_http/app.go
GO
mit
781
module github.com/dapr/dapr/tests/apps/perf/service_invocation_http go 1.22.3
mikeee/dapr
tests/apps/perf/service_invocation_http/go.mod
mod
mit
79
# In perf tests, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing the perf test. apiVersion: apps/v1 kind: Deployment metadata: name: perf-service-invocation labels: testapp: perf-service-invocation spec: replicas: 1 selector: matchLabels: testapp: perf-service-invocation template: metadata: labels: testapp: perf-service-invocation annotations: dapr.io/enabled: "true" dapr.io/app-id: "testapp" dapr.io/app-port: "3000" spec: containers: - name: perf-service-invocation image: docker.io/[YOUR ALIAS]/perf-service_invocation_http:dev ports: - containerPort: 3000 imagePullPolicy: Always
mikeee/dapr
tests/apps/perf/service_invocation_http/service.yaml
YAML
mit
813
FROM golang:1.22.3-bullseye as build_env ENV CGO_ENABLED=0 WORKDIR /app COPY *.go go.mod ./ RUN go get -d -v && go build -o tester . FROM golang:1.22.3-bullseye as fortio_build_env WORKDIR /fortio ADD "https://api.github.com/repos/dapr/fortio/branches/v1.38.4-dapr" skipcache RUN git clone https://github.com/dapr/fortio.git RUN cd fortio && git checkout v1.38.4-dapr && go build FROM debian:bullseye-slim WORKDIR / COPY --from=build_env /app/tester / COPY --from=fortio_build_env /fortio/fortio/fortio /usr/local/bin CMD ["/tester"]
mikeee/dapr
tests/apps/perf/tester/Dockerfile
Dockerfile
mit
538
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "log" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) } func main() { http.HandleFunc("/", handler) http.HandleFunc("/test", fortioTestHandler) log.Fatal(http.ListenAndServe(":3001", nil)) }
mikeee/dapr
tests/apps/perf/tester/app.go
GO
mit
822
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "encoding/json" "fmt" "io" "log" "net/http" "os" "os/exec" "strconv" ) // TODO: change to take from "github.com/dapr/dapr/tests/perf" once in repository. otherwise fails on go get step in Dockerfile. type TestParameters struct { QPS int `json:"qps"` ClientConnections int `json:"clientConnections"` TargetEndpoint string `json:"targetEndpoint"` TestDuration string `json:"testDuration"` PayloadSizeKB int `json:"payloadSizeKB"` Payload string `json:"payload"` StdClient bool `json:"stdClient"` Grpc bool `json:"grpc"` Dapr string `json:"dapr"` } func fortioTestHandler(w http.ResponseWriter, r *http.Request) { log.Println("Test execution request received") var testParams TestParameters b, err := io.ReadAll(r.Body) if err != nil { w.WriteHeader(500) w.Write([]byte(fmt.Sprintf("error reading request body: %s", err))) return } err = json.Unmarshal(b, &testParams) if err != nil { w.WriteHeader(400) w.Write([]byte(fmt.Sprintf("error parsing test params: %s", err))) return } log.Println("Executing test") results, err := runFortioTest(testParams) if err != nil { w.WriteHeader(500) w.Write([]byte(fmt.Sprintf("error encountered while running test: %s", err))) return } log.Println("Test finished") w.Header().Add("Content-Type", "application/json") w.Write(results) } // runFortioTest accepts a set of test parameters, runs Fortio with the configured setting and returns // the test results in json format. func runFortioTest(params TestParameters) ([]byte, error) { args := buildFortioArgs(params) log.Printf("Running test with params: %s", args) cmd := exec.Command("fortio", args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() if err != nil { return nil, err } return os.ReadFile("result.json") } func buildFortioArgs(params TestParameters) []string { var args []string if len(params.Payload) > 0 { args = []string{ "load", "-json", "result.json", "-content-type", "application/json", "-qps", strconv.Itoa(params.QPS), "-c", strconv.Itoa(params.ClientConnections), "-t", params.TestDuration, "-payload", params.Payload, } } else { args = []string{ "load", "-json", "result.json", "-qps", strconv.Itoa(params.QPS), "-c", strconv.Itoa(params.ClientConnections), "-t", params.TestDuration, "-payload-size", strconv.Itoa(params.PayloadSizeKB), } } if params.StdClient { args = append(args, "-stdclient") } if params.Grpc { args = append(args, "-grpc") } if params.Dapr != "" { args = append(args, "-dapr", params.Dapr) } args = append(args, params.TargetEndpoint) return args }
mikeee/dapr
tests/apps/perf/tester/fortio.go
GO
mit
3,304
module github.com/dapr/dapr/tests/apps/perf/tester go 1.22.3
mikeee/dapr
tests/apps/perf/tester/go.mod
mod
mit
62
# In perf tests, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing the perf test. apiVersion: apps/v1 kind: Deployment metadata: name: perf-tester labels: testapp: perf-tester spec: replicas: 1 selector: matchLabels: testapp: perf-tester template: metadata: labels: testapp: perf-tester annotations: dapr.io/enabled: "true" dapr.io/app-id: "tester" dapr.io/app-port: "3001" spec: containers: - name: perf-tester image: docker.io/[YOUR ALIAS]/perf-tester:dev ports: - containerPort: 3001 imagePullPolicy: Always
mikeee/dapr
tests/apps/perf/tester/service.yaml
YAML
mit
735
FROM python:3.8-slim-buster WORKDIR /app COPY . . RUN pip3 install -r requirements.txt CMD ["python3", "app.py"]
mikeee/dapr
tests/apps/perf/workflowsapp/Dockerfile
Dockerfile
mit
117
# Copyright 2023 The Dapr Authors # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from flask import Flask, request from time import sleep from datetime import datetime from dapr.ext.workflow import WorkflowRuntime, DaprWorkflowContext, WorkflowActivityContext, DaprWorkflowClient, WorkflowStatus, when_all from dapr.conf import Settings from dapr.clients import DaprClient from dapr.clients.exceptions import DaprInternalError import json settings = Settings() api = Flask(__name__) workflowComponent = "dapr" workflowOptions = dict() workflowOptions["task_queue"] = "testQueue" nonExistentIDError = "no such instance exists" appPort = 3000 state_store_name = "statestore" actor_statestore_name = "statestore-actorstore" # state_wf saves a key-value pair of `dataSize` size in the configured statestore, gets it back, validates and then deletes the key def state_wf(ctx:DaprWorkflowContext,input): print(f"{datetime.now():%Y-%m-%d %H:%M:%S.%f} [{ctx.instance_id}] Invoked state_wf") inputObj = json.loads(input) dataSize = int(inputObj["data_size"]) key = inputObj["state_key"] data = "1" * dataSize print("Running state_wf with key=",key,"dataSize=",dataSize) save_input = { "key" : key, "value" : data, } yield ctx.call_activity(state_save_act, input = save_input) res = yield ctx.call_activity(state_get_act, input = key) assert res == data yield ctx.call_activity(state_delete_act,input=key) # state_save_act saves the {key,value} pair in the configured statetsore def state_save_act(ctx:WorkflowActivityContext,input): with DaprClient() as d: d.save_state(store_name=state_store_name, key=input["key"], value=input["value"]) sleep(1) # state_get_act gets the value stored in statestore against {key} def state_get_act(ctx:WorkflowActivityContext, input): key = str(input) with DaprClient() as d: resp = d.get_state(store_name=state_store_name, key=key) sleep(1) return resp.text() # state_delete_act deletes the {key} from statestore def state_delete_act(ctx:WorkflowActivityContext,input): key = str(input) with DaprClient() as d: d.delete_state(store_name=state_store_name, key= key) sleep(1) # sum_series_wf calculates sum of numbers {1..input} by dividing the workload among 5 activties running in series def sum_series_wf(ctx:DaprWorkflowContext, input): print(f"{datetime.now():%Y-%m-%d %H:%M:%S.%f} [{ctx.instance_id}] Invoked sum_series_wf") num = int(input) limit = int(num/5) sum1 = yield ctx.call_activity(sum_activity,input=f"1,{limit}") sum2 = yield ctx.call_activity(sum_activity,input=f"{limit+1},{2*limit}") sum3 = yield ctx.call_activity(sum_activity,input=f"{2*limit+1},{3*limit}") sum4 = yield ctx.call_activity(sum_activity,input=f"{3*limit+1},{4*limit}") sum5 = yield ctx.call_activity(sum_activity,input=f"{4*limit+1},{num}") total_sum = sum1 + sum2 + sum3 + sum4 + sum5 expected_sum = (num*(num+1))/2 assert expected_sum == total_sum # sum_parallel_wf calculates sum of numbers {1..input} by dividing the workload among 5 activties running in parallel def sum_parallel_wf(ctx:DaprWorkflowContext, input): print(f"{datetime.now():%Y-%m-%d %H:%M:%S.%f} [{ctx.instance_id}] Invoked sum_parallel_wf") num = int(input) limit = int(num/5) inputs = [f"1,{limit}",f"{limit+1},{2*limit}",f"{2*limit+1},{3*limit}",f"{3*limit+1},{4*limit}",f"{4*limit+1},{num}"] parallel_tasks = [ctx.call_activity(sum_activity,input=input) for input in inputs] outputs = yield when_all(parallel_tasks) total_sum = 0 for x in outputs: total_sum += int(x) expected_sum=(num*(num+1))/2 assert expected_sum == total_sum # sum_activity calculates sum of numbers in range [num1,num2] (input:'num1,num2') def sum_activity(ctx:WorkflowActivityContext,input): limits = [int(x) for x in str(input).split(",")] num1 = limits[0] num2 = limits[1] sum = 0 for i in range(num1,num2+1): sum += i return sum # start_workflow_runtime starts the workflow runtime and registers the declared workflows and activities @api.route('/start-workflow-runtime', methods=['GET']) def start_workflow_runtime(): global workflowRuntime, workflowClient host = settings.DAPR_RUNTIME_HOST port = settings.DAPR_GRPC_PORT workflowRuntime = WorkflowRuntime(host, port) workflowRuntime.register_workflow(sum_series_wf) workflowRuntime.register_workflow(sum_parallel_wf) workflowRuntime.register_workflow(state_wf) workflowRuntime.register_activity(sum_activity) workflowRuntime.register_activity(state_save_act) workflowRuntime.register_activity(state_get_act) workflowRuntime.register_activity(state_delete_act) workflowRuntime.start() workflowClient = DaprWorkflowClient(host=host,port=port) print("Workflow Runtime Started") return "Workflow Runtime Started" # shutdown_workflow_runtime stops the workflow runtime @api.route('/shutdown-workflow-runtime', methods=['GET']) def shutdown_workflow_runtime(): workflowRuntime.shutdown() print("Workflow Runtime Shutdown") return "Workflow Runtime Shutdown" # run_workflow runs an instance of workflow and waits for it to complete @api.route('/run-workflow/<run_id>', methods=['POST']) def run_workflow(run_id): request_data = request.get_json() workflowName = request_data["workflow_name"] input = request_data["workflow_input"] # For state_wf, the input passed is `dataSize`. Adding `run_id` as the key for saving the data if workflowName == "state_wf": data_size = input input = json.dumps({ "state_key": run_id, "data_size": data_size, }) with DaprClient() as d: try: print(f"{datetime.now():%Y-%m-%d %H:%M:%S.%f} [{run_id}] starting workflow") start_resp = d.start_workflow(workflow_component=workflowComponent, workflow_name=workflowName, input=input, workflow_options=workflowOptions) print(f"{datetime.now():%Y-%m-%d %H:%M:%S.%f} [{run_id}] started workflow with instance_id {start_resp.instance_id}") instance_id = start_resp.instance_id except DaprInternalError as e: print(f"{datetime.now():%Y-%m-%d %H:%M:%S.%f} [{run_id}] error starting workflow: {e.message}") sleep(0.5) workflow_state = workflowClient.wait_for_workflow_completion( instance_id=instance_id, timeout_in_seconds=250) assert workflow_state.runtime_status == WorkflowStatus.COMPLETED try: get_resp = d.get_workflow(instance_id=instance_id, workflow_component=workflowComponent) print(f"{datetime.now():%Y-%m-%d %H:%M:%S.%f} [{run_id}] workflow instance_id {get_resp.instance_id} runtime_status {get_resp.runtime_status}") except DaprInternalError as e: print(f"{datetime.now():%Y-%m-%d %H:%M:%S.%f} [{run_id}] error getting workflow status: {e.message}") try: print(f"{datetime.now():%Y-%m-%d %H:%M:%S.%f} [{run_id}] terminating workflow") terminate_resp = d.terminate_workflow(instance_id=instance_id, workflow_component=workflowComponent) except DaprInternalError as e: print(f"{datetime.now():%Y-%m-%d %H:%M:%S.%f} [{run_id}] error terminating workflow: {e.message}") try: print(f"{datetime.now():%Y-%m-%d %H:%M:%S.%f} [{run_id}] purging workflow") d.purge_workflow(instance_id=instance_id, workflow_component=workflowComponent) except DaprInternalError as e: print(f"{datetime.now():%Y-%m-%d %H:%M:%S.%f} [{run_id}] error purging workflow: {e.message}") print(f"{datetime.now():%Y-%m-%d %H:%M:%S.%f} [{run_id}] workflow run complete") return "Workflow Run completed" if __name__ == '__main__': api.run(host="0.0.0.0",port=appPort)
mikeee/dapr
tests/apps/perf/workflowsapp/app.py
Python
mit
8,565
dapr-ext-workflow dapr flask
mikeee/dapr
tests/apps/perf/workflowsapp/requirements.txt
Text
mit
28
../../../dapr/proto/components/v1/*.proto
mikeee/dapr
tests/apps/pluggable_kafka-bindings/.cache-include
none
mit
41
/* Copyright 2022 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( dapr "github.com/dapr-sandbox/components-go-sdk" "github.com/dapr-sandbox/components-go-sdk/bindings/v1" "github.com/dapr/components-contrib/bindings/kafka" "github.com/dapr/kit/logger" ) var log = logger.NewLogger("kafka-bindings-pluggable") func main() { dapr.Register("kafka-pluggable", dapr.WithInputBinding(func() bindings.InputBinding { return kafka.NewKafka(log) }), dapr.WithOutputBinding(func() bindings.OutputBinding { return kafka.NewKafka(log) }), ) dapr.MustRun() }
mikeee/dapr
tests/apps/pluggable_kafka-bindings/app.go
GO
mit
1,085
module github.com/dapr/dapr/tests/apps/kafka-bindings go 1.22.3 require ( github.com/dapr-sandbox/components-go-sdk v0.0.0-20221213200551-bd485eb929ff github.com/dapr/components-contrib v1.9.1-0.20221213185150-c5c985a68514 github.com/dapr/kit v0.0.4-0.20221211173611-bcf6ee09314e ) require ( github.com/Shopify/sarama v1.37.2 // indirect github.com/cenkalti/backoff/v4 v4.2.0 // indirect github.com/dapr/dapr v1.9.4-0.20221212235750-ac9256f214e0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/eapache/go-resiliency v1.3.0 // indirect github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 // indirect github.com/eapache/queue v1.1.0 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/google/uuid v1.3.0 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/go-uuid v1.0.3 // indirect github.com/jcmturner/aescts/v2 v2.0.0 // indirect github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect github.com/jcmturner/gofork v1.7.6 // indirect github.com/jcmturner/gokrb5/v8 v8.4.3 // indirect github.com/jcmturner/rpc/v2 v2.0.3 // indirect github.com/klauspost/compress v1.15.12 // indirect github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4 // indirect github.com/pierrec/lz4/v4 v4.1.17 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect github.com/sirupsen/logrus v1.9.0 // indirect github.com/xdg-go/pbkdf2 v1.0.0 // indirect github.com/xdg-go/scram v1.1.1 // indirect github.com/xdg-go/stringprep v1.0.3 // indirect golang.org/x/crypto v0.11.0 // indirect golang.org/x/net v0.12.0 // indirect golang.org/x/oauth2 v0.10.0 // indirect golang.org/x/sys v0.10.0 // indirect golang.org/x/text v0.11.0 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto v0.0.0-20221207170731-23e4bf6bdc37 // indirect google.golang.org/grpc v1.51.0 // indirect google.golang.org/protobuf v1.31.0 // indirect )
mikeee/dapr
tests/apps/pluggable_kafka-bindings/go.mod
mod
mit
2,138
github.com/Shopify/sarama v1.37.2 h1:LoBbU0yJPte0cE5TZCGdlzZRmMgMtZU/XgnUKZg9Cv4= github.com/Shopify/sarama v1.37.2/go.mod h1:Nxye/E+YPru//Bpaorfhc3JsSGYwCaDDj+R4bK52U5o= github.com/Shopify/toxiproxy/v2 v2.5.0 h1:i4LPT+qrSlKNtQf5QliVjdP08GyAH8+BUIc9gT0eahc= github.com/Shopify/toxiproxy/v2 v2.5.0/go.mod h1:yhM2epWtAmel9CB8r2+L+PCmhH6yH2pITaPAo7jxJl0= github.com/cenkalti/backoff/v4 v4.2.0 h1:HN5dHm3WBOgndBH6E8V0q2jIYIR3s9yglV8k/+MN3u4= github.com/cenkalti/backoff/v4 v4.2.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/dapr-sandbox/components-go-sdk v0.0.0-20221213200551-bd485eb929ff h1:NnHsBy0rW6n0/TKwjJmT/tA9ezxFmz64XnACslceRHk= github.com/dapr-sandbox/components-go-sdk v0.0.0-20221213200551-bd485eb929ff/go.mod h1:gK31Fk/lEYg0sCaoxFhPyBL54N5AOeeWfeZFl36P2Ko= github.com/dapr/components-contrib v1.9.1-0.20221213185150-c5c985a68514 h1:2HaeVAj6ePRjxwEXJVeUV209VVAiurQ+eS7xB1k7t7g= github.com/dapr/components-contrib v1.9.1-0.20221213185150-c5c985a68514/go.mod h1:o92XRraeBOkmrZKZCUaEGuxAN0OdOH4CGwdqwi8pYMQ= github.com/dapr/dapr v1.9.4-0.20221212235750-ac9256f214e0 h1:Y3WZ1lgR7vBXowF6xbBo1lSEsW2aiXN7U9gRhz8rQcM= github.com/dapr/dapr v1.9.4-0.20221212235750-ac9256f214e0/go.mod h1:chJw8EsdwW+Z0E2e0XJN2JzVO5FgUkMkYCYrRKTIqGc= github.com/dapr/kit v0.0.4-0.20221211173611-bcf6ee09314e h1:/1VuHsZJOeOLZ1KkW+484RDVZ1FqHTunUSCagEtP8bw= github.com/dapr/kit v0.0.4-0.20221211173611-bcf6ee09314e/go.mod h1:+vh2UIRT0KzFm5YJWfj7az4XVSdodys1OCz1WzNe1Eo= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/eapache/go-resiliency v1.3.0 h1:RRL0nge+cWGlxXbUzJ7yMcq6w2XBEr19dCN6HECGaT0= github.com/eapache/go-resiliency v1.3.0/go.mod h1:5yPzW0MIvSe0JDsv0v+DvcjEv2FyD6iZYSs1ZI+iQho= github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 h1:YEetp8/yCZMuEPMUDHG0CW/brkkEp8mzqk2+ODEitlw= github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc= github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8= github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs= github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo= github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM= github.com/jcmturner/gofork v1.7.6 h1:QH0l3hzAU1tfT3rZCnW5zXl+orbkNMMRGJfdJjHVETg= github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo= github.com/jcmturner/goidentity/v6 v6.0.1 h1:VKnZd2oEIMorCTsFBnJWbExfNN7yZr3EhJAxwOkZg6o= github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg= github.com/jcmturner/gokrb5/v8 v8.4.3 h1:iTonLeSJOn7MVUtyMT+arAn5AKAPrkilzhGw8wE/Tq8= github.com/jcmturner/gokrb5/v8 v8.4.3/go.mod h1:dqRwJGXznQrzw6cWmyo6kH+E7jksEQG/CyVWsJEsJO0= github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY= github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= github.com/klauspost/compress v1.15.12 h1:YClS/PImqYbn+UILDnqxQCZ3RehC9N318SU3kElDUEM= github.com/klauspost/compress v1.15.12/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM= github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4 h1:BpfhmLKZf+SjVanKKhCgf3bg+511DmU9eDQTen7LLbY= github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/pierrec/lz4/v4 v4.1.17 h1:kV4Ip+/hUBC+8T6+2EgburRtkE9ef4nbY3f4dFhGjMc= github.com/pierrec/lz4/v4 v4.1.17/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM= github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= github.com/xdg-go/scram v1.1.1 h1:VOMT+81stJgXW3CpHyqHN3AXDYIMsx56mEFrB37Mb/E= github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g= github.com/xdg-go/stringprep v1.0.3 h1:kdwGpVNwPFtjs98xCGkHjQtGKh86rDcRZN17QEMCOIs= github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= golang.org/x/exp v0.0.0-20221028150844-83b7d23a625f h1:Al51T6tzvuh3oiwX11vex3QgJ2XTedFPGmbEVh8cdoc= golang.org/x/exp v0.0.0-20221028150844-83b7d23a625f/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220725212005-46097bf591d3/go.mod h1:AaygXjzTFtRAg2ttMY5RMuhpJ3cNnI0XpyFJD1iQRSM= golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50= golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= golang.org/x/oauth2 v0.10.0 h1:zHCpF2Khkwy4mMB4bv0U37YtJdTGW8jI0glAApi0Kh8= golang.org/x/oauth2 v0.10.0/go.mod h1:kTpgurOux7LqtuxjuyZa4Gj2gdezIt/jQtGnNFfypQI= golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/genproto v0.0.0-20221207170731-23e4bf6bdc37 h1:jmIfw8+gSvXcZSgaFAGyInDXeWzUhvYH57G/5GKMn70= google.golang.org/genproto v0.0.0-20221207170731-23e4bf6bdc37/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= google.golang.org/grpc v1.51.0 h1:E1eGv1FTqoLIdnBCZufiSHgKjlqG6fKFf6pPWtMTh8U= google.golang.org/grpc v1.51.0/go.mod h1:wgNDFcnuBGmxLKI/qn4T+m5BtEBYXJPvibbUPsAIPww= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
mikeee/dapr
tests/apps/pluggable_kafka-bindings/go.sum
sum
mit
12,519
../../../dapr/proto/components/v1/*.proto
mikeee/dapr
tests/apps/pluggable_redis-pubsub/.cache-include
none
mit
41
/* Copyright 2022 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "context" dapr "github.com/dapr-sandbox/components-go-sdk" sdkPubSub "github.com/dapr-sandbox/components-go-sdk/pubsub/v1" "github.com/dapr/components-contrib/pubsub" "github.com/dapr/components-contrib/pubsub/redis" "github.com/dapr/kit/logger" ) type redisPb struct { pubsub.PubSub } // topicPrefix is used to avoid name clashing with other pubsub brokers when using the same underlying redis instance. const topicPrefix = "pluggable-" func (r *redisPb) Subscribe(ctx context.Context, req pubsub.SubscribeRequest, handler pubsub.Handler) error { return r.PubSub.Subscribe(ctx, pubsub.SubscribeRequest{ Topic: topicPrefix + req.Topic, Metadata: req.Metadata, }, handler) } func (r *redisPb) Publish(req *pubsub.PublishRequest) error { return r.PubSub.Publish(&pubsub.PublishRequest{ Data: req.Data, PubsubName: topicPrefix + req.PubsubName, Topic: topicPrefix + req.Topic, Metadata: req.Metadata, ContentType: req.ContentType, }) } var log = logger.NewLogger("redis-pubsub-pluggable") func main() { dapr.Register("redis-pluggable", dapr.WithPubSub(func() sdkPubSub.PubSub { return &redisPb{redis.NewRedisStreams(log)} })) dapr.MustRun() }
mikeee/dapr
tests/apps/pluggable_redis-pubsub/app.go
GO
mit
1,782
module github.com/dapr/dapr/tests/apps/pluggable_redis-pubsub go 1.22.3 require ( github.com/dapr-sandbox/components-go-sdk v0.0.0-20221213200551-bd485eb929ff github.com/dapr/components-contrib v1.9.1-0.20221213185150-c5c985a68514 github.com/dapr/kit v0.0.4-0.20221211173611-bcf6ee09314e ) require ( github.com/cespare/xxhash/v2 v2.1.2 // indirect github.com/dapr/dapr v1.9.4-0.20221212235750-ac9256f214e0 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/go-redis/redis/v8 v8.11.5 // indirect github.com/golang/protobuf v1.5.2 // indirect github.com/google/uuid v1.3.0 // indirect github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/sirupsen/logrus v1.9.0 // indirect golang.org/x/net v0.12.0 // indirect golang.org/x/sys v0.10.0 // indirect golang.org/x/text v0.11.0 // indirect google.golang.org/genproto v0.0.0-20221207170731-23e4bf6bdc37 // indirect google.golang.org/grpc v1.51.0 // indirect google.golang.org/protobuf v1.28.1 // indirect )
mikeee/dapr
tests/apps/pluggable_redis-pubsub/go.mod
mod
mit
1,104
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/dapr-sandbox/components-go-sdk v0.0.0-20221213200551-bd485eb929ff h1:NnHsBy0rW6n0/TKwjJmT/tA9ezxFmz64XnACslceRHk= github.com/dapr-sandbox/components-go-sdk v0.0.0-20221213200551-bd485eb929ff/go.mod h1:gK31Fk/lEYg0sCaoxFhPyBL54N5AOeeWfeZFl36P2Ko= github.com/dapr/components-contrib v1.9.1-0.20221213185150-c5c985a68514 h1:2HaeVAj6ePRjxwEXJVeUV209VVAiurQ+eS7xB1k7t7g= github.com/dapr/components-contrib v1.9.1-0.20221213185150-c5c985a68514/go.mod h1:o92XRraeBOkmrZKZCUaEGuxAN0OdOH4CGwdqwi8pYMQ= github.com/dapr/dapr v1.9.4-0.20221212235750-ac9256f214e0 h1:Y3WZ1lgR7vBXowF6xbBo1lSEsW2aiXN7U9gRhz8rQcM= github.com/dapr/dapr v1.9.4-0.20221212235750-ac9256f214e0/go.mod h1:chJw8EsdwW+Z0E2e0XJN2JzVO5FgUkMkYCYrRKTIqGc= github.com/dapr/kit v0.0.4-0.20221211173611-bcf6ee09314e h1:/1VuHsZJOeOLZ1KkW+484RDVZ1FqHTunUSCagEtP8bw= github.com/dapr/kit v0.0.4-0.20221211173611-bcf6ee09314e/go.mod h1:+vh2UIRT0KzFm5YJWfj7az4XVSdodys1OCz1WzNe1Eo= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4 h1:BpfhmLKZf+SjVanKKhCgf3bg+511DmU9eDQTen7LLbY= github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE= github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= golang.org/x/exp v0.0.0-20221028150844-83b7d23a625f h1:Al51T6tzvuh3oiwX11vex3QgJ2XTedFPGmbEVh8cdoc= golang.org/x/exp v0.0.0-20221028150844-83b7d23a625f/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50= golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/genproto v0.0.0-20221207170731-23e4bf6bdc37 h1:jmIfw8+gSvXcZSgaFAGyInDXeWzUhvYH57G/5GKMn70= google.golang.org/genproto v0.0.0-20221207170731-23e4bf6bdc37/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= google.golang.org/grpc v1.51.0 h1:E1eGv1FTqoLIdnBCZufiSHgKjlqG6fKFf6pPWtMTh8U= google.golang.org/grpc v1.51.0/go.mod h1:wgNDFcnuBGmxLKI/qn4T+m5BtEBYXJPvibbUPsAIPww= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
mikeee/dapr
tests/apps/pluggable_redis-pubsub/go.sum
sum
mit
6,598
../../../dapr/proto/components/v1/*.proto
mikeee/dapr
tests/apps/pluggable_redis-statestore/.cache-include
none
mit
41
/* Copyright 2022 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( dapr "github.com/dapr-sandbox/components-go-sdk" "github.com/dapr-sandbox/components-go-sdk/state/v1" "github.com/dapr/components-contrib/state/redis" "github.com/dapr/kit/logger" ) var log = logger.NewLogger("redis-pluggable") func main() { dapr.Register("redis-pluggable", dapr.WithStateStore(func() state.Store { return redis.NewRedisStateStore(log) }), ) dapr.MustRun() }
mikeee/dapr
tests/apps/pluggable_redis-statestore/app.go
GO
mit
976
module github.com/dapr/dapr/tests/apps/pluggable_redis-statestore go 1.22.3 require ( github.com/dapr-sandbox/components-go-sdk v0.0.0-20221213200551-bd485eb929ff github.com/dapr/components-contrib v1.9.1-0.20221213185150-c5c985a68514 github.com/dapr/kit v0.0.4-0.20221211173611-bcf6ee09314e ) require ( github.com/cespare/xxhash/v2 v2.1.2 // indirect github.com/dapr/dapr v1.9.4-0.20221212235750-ac9256f214e0 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/go-redis/redis/v8 v8.11.5 // indirect github.com/golang/protobuf v1.5.2 // indirect github.com/google/uuid v1.3.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/sirupsen/logrus v1.9.0 // indirect golang.org/x/net v0.12.0 // indirect golang.org/x/sys v0.10.0 // indirect golang.org/x/text v0.11.0 // indirect google.golang.org/genproto v0.0.0-20221207170731-23e4bf6bdc37 // indirect google.golang.org/grpc v1.51.0 // indirect google.golang.org/protobuf v1.28.1 // indirect )
mikeee/dapr
tests/apps/pluggable_redis-statestore/go.mod
mod
mit
1,287
github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a h1:HbKu58rmZpUGpz5+4FfNmIU+FmZg2P3Xaj2v2bfNWmk= github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= github.com/alicebob/miniredis/v2 v2.23.0 h1:+lwAJYjvvdIVg6doFHuotFjueJ/7KY10xo/vm3X3Scw= github.com/alicebob/miniredis/v2 v2.23.0/go.mod h1:XNqvJdQJv5mSuVMc0ynneafpnL/zv52acZ6kqeS0t88= github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/dapr-sandbox/components-go-sdk v0.0.0-20221213200551-bd485eb929ff h1:NnHsBy0rW6n0/TKwjJmT/tA9ezxFmz64XnACslceRHk= github.com/dapr-sandbox/components-go-sdk v0.0.0-20221213200551-bd485eb929ff/go.mod h1:gK31Fk/lEYg0sCaoxFhPyBL54N5AOeeWfeZFl36P2Ko= github.com/dapr/components-contrib v1.9.1-0.20221213185150-c5c985a68514 h1:2HaeVAj6ePRjxwEXJVeUV209VVAiurQ+eS7xB1k7t7g= github.com/dapr/components-contrib v1.9.1-0.20221213185150-c5c985a68514/go.mod h1:o92XRraeBOkmrZKZCUaEGuxAN0OdOH4CGwdqwi8pYMQ= github.com/dapr/dapr v1.9.4-0.20221212235750-ac9256f214e0 h1:Y3WZ1lgR7vBXowF6xbBo1lSEsW2aiXN7U9gRhz8rQcM= github.com/dapr/dapr v1.9.4-0.20221212235750-ac9256f214e0/go.mod h1:chJw8EsdwW+Z0E2e0XJN2JzVO5FgUkMkYCYrRKTIqGc= github.com/dapr/kit v0.0.4-0.20221211173611-bcf6ee09314e h1:/1VuHsZJOeOLZ1KkW+484RDVZ1FqHTunUSCagEtP8bw= github.com/dapr/kit v0.0.4-0.20221211173611-bcf6ee09314e/go.mod h1:+vh2UIRT0KzFm5YJWfj7az4XVSdodys1OCz1WzNe1Eo= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4 h1:BpfhmLKZf+SjVanKKhCgf3bg+511DmU9eDQTen7LLbY= github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE= github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/yuin/gopher-lua v0.0.0-20210529063254-f4c35e4016d9 h1:k/gmLsJDWwWqbLCur2yWnJzwQEKRcAHXo6seXGuSwWw= github.com/yuin/gopher-lua v0.0.0-20210529063254-f4c35e4016d9/go.mod h1:E1AXubJBdNmFERAOucpDIxNzeGfLzg0mYh+UfMWdChA= golang.org/x/exp v0.0.0-20221028150844-83b7d23a625f h1:Al51T6tzvuh3oiwX11vex3QgJ2XTedFPGmbEVh8cdoc= golang.org/x/exp v0.0.0-20221028150844-83b7d23a625f/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50= golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/genproto v0.0.0-20221207170731-23e4bf6bdc37 h1:jmIfw8+gSvXcZSgaFAGyInDXeWzUhvYH57G/5GKMn70= google.golang.org/genproto v0.0.0-20221207170731-23e4bf6bdc37/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= google.golang.org/grpc v1.51.0 h1:E1eGv1FTqoLIdnBCZufiSHgKjlqG6fKFf6pPWtMTh8U= google.golang.org/grpc v1.51.0/go.mod h1:wgNDFcnuBGmxLKI/qn4T+m5BtEBYXJPvibbUPsAIPww= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
mikeee/dapr
tests/apps/pluggable_redis-statestore/go.sum
sum
mit
8,135
../utils/*.go
mikeee/dapr
tests/apps/pubsub-bulk-subscriber/.cache-include
none
mit
13
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "encoding/base64" "encoding/json" "errors" "fmt" "io" "log" "net/http" "os" "strings" "sync" "github.com/google/uuid" "github.com/gorilla/mux" "k8s.io/apimachinery/pkg/util/sets" "github.com/dapr/dapr/tests/apps/utils" ) const ( appPort = 3000 pubsubRawSubTopic = "pubsub-raw-sub-topic-http" pubsubCESubTopic = "pubsub-ce-sub-topic-http" pubsubRawBulkSubTopic = "pubsub-raw-bulk-sub-topic-http" pubsubCEBulkSubTopic = "pubsub-ce-bulk-sub-topic-http" pubsubDeadBulkSubTopic = "pubsub-dead-bulk-sub-topic-http" pubsubDeadLetterBulkSubTopic = "pubsub-dead-letter-bulk-sub-topic-http" PubSubEnvVar = "DAPR_TEST_PUBSUB_NAME" statusSuccess = "SUCCESS" statusDrop = "DROP" ) var pubsubkafkaName = "kafka-messagebus" func init() { if psName := os.Getenv(PubSubEnvVar); len(psName) != 0 { pubsubkafkaName = psName } } type appResponse struct { // Status field for proper handling of errors form pubsub Status string `json:"status,omitempty"` Message string `json:"message,omitempty"` StartTime int `json:"start_time,omitempty"` EndTime int `json:"end_time,omitempty"` } type receivedMessagesResponse struct { ReceivedByTopicRawSub []string `json:"pubsub-raw-sub-topic"` ReceivedByTopicCESub []string `json:"pubsub-ce-sub-topic"` ReceivedByTopicRawBulkSub []string `json:"pubsub-raw-bulk-sub-topic"` ReceivedByTopicCEBulkSub []string `json:"pubsub-ce-bulk-sub-topic"` ReceivedByTopicDead []string `json:"pubsub-dead-bulk-topic"` ReceivedByTopicDeadLetter []string `json:"pubsub-deadletter-bulk-topic"` } type subscription struct { PubsubName string `json:"pubsubname"` Topic string `json:"topic"` Route string `json:"route"` DeadLetterTopic string `json:"deadLetterTopic"` Metadata map[string]string `json:"metadata"` BulkSubscribe BulkSubscribe `json:"bulkSubscribe"` } type BulkSubscribe struct { Enabled bool `json:"enabled"` MaxMessagesCount int32 `json:"maxMessagesCount,omitempty"` MaxAwaitDurationMs int32 `json:"maxAwaitDurationMs,omitempty"` } type BulkRawMessage struct { Entries []BulkMessageRawEntry `json:"entries"` Topic string `json:"topic"` Metadata map[string]string `json:"metadata"` } type BulkMessageRawEntry struct { EntryId string `json:"entryId"` //nolint:stylecheck Event string `json:"event"` ContentType string `json:"contentType,omitempty"` Metadata map[string]string `json:"metadata"` } type BulkMessage struct { Entries []BulkMessageEntry `json:"entries"` Topic string `json:"topic"` Metadata map[string]string `json:"metadata"` } type BulkMessageEntry struct { EntryId string `json:"entryId"` //nolint:stylecheck Event map[string]interface{} `json:"event"` ContentType string `json:"contentType,omitempty"` Metadata map[string]string `json:"metadata"` } type AppBulkMessageEntry struct { EntryId string `json:"entryId"` //nolint:stylecheck EventStr string `json:"event"` ContentType string `json:"contentType,omitempty"` Metadata map[string]string `json:"metadata"` } type BulkSubscribeResponseEntry struct { EntryId string `json:"entryId"` //nolint:stylecheck Status string `json:"status"` } // BulkSubscribeResponse is the whole bulk subscribe response sent by app type BulkSubscribeResponse struct { Statuses []BulkSubscribeResponseEntry `json:"statuses"` } // respondWith determines the response to return when a message // is received. type respondWith int const ( respondWithSuccess respondWith = iota // respond with empty json message respondWithEmptyJSON // respond with error respondWithError // respond with retry respondWithRetry // respond with drop respondWithDrop // respond with invalid status respondWithInvalidStatus // respond with success for all messages in bulk respondWithSuccessBulk ) var ( // using sets to make the test idempotent on multiple delivery of same message receivedMessagesSubRaw sets.Set[string] receivedMessagesSubCE sets.Set[string] receivedMessagesBulkRaw sets.Set[string] receivedMessagesBulkCE sets.Set[string] receivedMessagesBulkDead sets.Set[string] receivedMessagesBulkDeadLetter sets.Set[string] desiredResponse respondWith lock sync.Mutex ) // indexHandler is the handler for root path func indexHandler(w http.ResponseWriter, _ *http.Request) { log.Printf("indexHandler called") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{Message: "OK"}) } // this handles /dapr/subscribe, which is called from dapr into this app. // this returns the list of topics the app is subscribed to. func configureSubscribeHandler(w http.ResponseWriter, _ *http.Request) { t := []subscription{ { PubsubName: pubsubkafkaName, Topic: pubsubRawSubTopic, Route: pubsubRawSubTopic, Metadata: map[string]string{ "rawPayload": "true", }, }, { PubsubName: pubsubkafkaName, Topic: pubsubCESubTopic, Route: pubsubCESubTopic, }, { PubsubName: pubsubkafkaName, Topic: pubsubRawBulkSubTopic, Route: pubsubRawBulkSubTopic, BulkSubscribe: BulkSubscribe{ Enabled: true, MaxMessagesCount: 60, MaxAwaitDurationMs: 1000, }, Metadata: map[string]string{ "rawPayload": "true", }, }, { PubsubName: pubsubkafkaName, Topic: pubsubCEBulkSubTopic, Route: pubsubCEBulkSubTopic, BulkSubscribe: BulkSubscribe{ Enabled: true, MaxMessagesCount: 60, MaxAwaitDurationMs: 1000, }, }, { PubsubName: pubsubkafkaName, Topic: pubsubDeadBulkSubTopic, Route: pubsubDeadBulkSubTopic, DeadLetterTopic: pubsubDeadLetterBulkSubTopic, }, { PubsubName: pubsubkafkaName, Topic: pubsubDeadLetterBulkSubTopic, Route: pubsubDeadLetterBulkSubTopic, }, } log.Printf("configureSubscribeHandler called; subscribing to: %v\n", t) w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(t) } func readMessageBody(reqID string, r *http.Request) (msg string, err error) { defer r.Body.Close() var body []byte if r.Body != nil { var data []byte data, err = io.ReadAll(r.Body) if err == nil { body = data } } else { // error err = errors.New("r.Body is nil") } if err != nil { return "", err } msg, err = extractMessage(reqID, body) if err != nil { return "", fmt.Errorf("error from extractMessage: %w", err) } // Raw data does not have content-type, so it is handled as-is. // Because the publisher encodes to JSON before publishing, we need to decode here. if strings.HasSuffix(r.URL.String(), pubsubRawSubTopic) { var actualMsg string err = json.Unmarshal([]byte(msg), &actualMsg) if err != nil { // Log only log.Printf("(%s) Error extracing JSON from raw event: %v", reqID, err) } else { msg = actualMsg } } return msg, nil } func readBulkMessageBody(reqID string, r *http.Request) (msgs []AppBulkMessageEntry, err error) { defer r.Body.Close() var body []byte if r.Body != nil { var data []byte data, err = io.ReadAll(r.Body) if err == nil { body = data } } else { // error err = errors.New("r.Body is nil") } if err != nil { return nil, err } if strings.HasSuffix(r.URL.String(), pubsubRawBulkSubTopic) { msgs, err = extractBulkMessage(reqID, body, true) if err != nil { return nil, fmt.Errorf("error from extractBulkMessage: %w", err) } } else { msgs, err = extractBulkMessage(reqID, body, false) if err != nil { return nil, fmt.Errorf("error from extractBulkMessage: %w", err) } } return msgs, nil } func subscribeHandler(w http.ResponseWriter, r *http.Request) { reqID, ok := r.Context().Value("reqid").(string) if reqID == "" || !ok { reqID = uuid.New().String() } msg, err := readMessageBody(reqID, r) // Before we handle the error, see if we need to respond in another way // We still want the message so we can log it log.Printf("(%s) subscribeHandler called %s. Message: %s", reqID, r.URL, msg) if err != nil { log.Printf("(%s) Responding with DROP due to error: %v", reqID, err) // Return 200 with DROP status to drop message w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{ Message: err.Error(), Status: statusDrop, }) return } lock.Lock() defer lock.Unlock() if strings.HasSuffix(r.URL.String(), pubsubRawSubTopic) && !receivedMessagesSubRaw.Has(msg) { receivedMessagesSubRaw.Insert(msg) } else if strings.HasSuffix(r.URL.String(), pubsubCESubTopic) && !receivedMessagesSubCE.Has(msg) { receivedMessagesSubCE.Insert(msg) } else { // This case is triggered when there is multiple redelivery of same message or a message // is thre for an unknown URL path errorMessage := fmt.Sprintf("Unexpected/Multiple redelivery of message from %s", r.URL.String()) log.Printf("(%s) Responding with DROP. %s", reqID, errorMessage) // Return success with DROP status to drop message w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{ Message: errorMessage, Status: statusDrop, }) return } w.WriteHeader(http.StatusOK) if desiredResponse == respondWithEmptyJSON { log.Printf("(%s) Responding with {}", reqID) w.Write([]byte("{}")) } else { log.Printf("(%s) Responding with SUCCESS", reqID) json.NewEncoder(w).Encode(appResponse{ Message: "consumed", Status: statusSuccess, }) } } func bulkSubscribeHandler(w http.ResponseWriter, r *http.Request) { reqID, ok := r.Context().Value("reqid").(string) log.Printf("(%s) bulkSubscribeHandler called %s.", reqID, r.URL) if reqID == "" || !ok { reqID = uuid.New().String() } msgs, err := readBulkMessageBody(reqID, r) bulkResponseEntries := make([]BulkSubscribeResponseEntry, len(msgs)) if err != nil { log.Printf("(%s) Responding with DROP due to error: %v", reqID, err) // Return 200 with DROP status to drop message w.WriteHeader(http.StatusOK) for i, msg := range msgs { entryResponse := BulkSubscribeResponseEntry{} entryResponse.EntryId = msg.EntryId entryResponse.Status = statusDrop bulkResponseEntries[i] = entryResponse } json.NewEncoder(w).Encode(BulkSubscribeResponse{ Statuses: bulkResponseEntries, }) return } // Success is the default status for this handler, can be overridden by the desiredResponse. // Supported values are "SUCCESS", "DROP" and "RETRY". returnStatus := statusSuccess if desiredResponse == respondWithDrop { returnStatus = statusDrop } for i, msg := range msgs { entryResponse := BulkSubscribeResponseEntry{} log.Printf("(%s) bulkSubscribeHandler called %s.Index: %d, Message: %s", reqID, r.URL, i, msg) log.Printf("(%s) Responding with %s for entryId %s", reqID, returnStatus, msg.EntryId) entryResponse.EntryId = msg.EntryId entryResponse.Status = returnStatus bulkResponseEntries[i] = entryResponse if strings.HasSuffix(r.URL.String(), pubsubRawBulkSubTopic) && !receivedMessagesBulkRaw.Has(msg.EventStr) { receivedMessagesBulkRaw.Insert(msg.EventStr) } else if strings.HasSuffix(r.URL.String(), pubsubCEBulkSubTopic) && !receivedMessagesBulkCE.Has(msg.EventStr) { receivedMessagesBulkCE.Insert(msg.EventStr) } else if strings.HasSuffix(r.URL.String(), pubsubDeadBulkSubTopic) && !receivedMessagesBulkDead.Has(msg.EventStr) { receivedMessagesBulkDead.Insert(msg.EventStr) } else if strings.HasSuffix(r.URL.String(), pubsubDeadLetterBulkSubTopic) && !receivedMessagesBulkDeadLetter.Has(msg.EventStr) { receivedMessagesBulkDeadLetter.Insert(msg.EventStr) } else { // This case is triggered when there is multiple redelivery of same message or a message // is thre for an unknown URL path errorMessage := fmt.Sprintf("Unexpected/Multiple redelivery of message during bulk subscribe from %s", r.URL.String()) log.Printf("(%s) Responding with DROP during bulk subscribe. %s", reqID, errorMessage) entryResponse.Status = statusDrop } } w.WriteHeader(http.StatusOK) log.Printf("(%s) Responding with SUCCESS", reqID) json.NewEncoder(w).Encode(BulkSubscribeResponse{ Statuses: bulkResponseEntries, }) } func unique(slice []string) []string { keys := make(map[string]bool) list := []string{} for _, entry := range slice { if _, value := keys[entry]; !value { keys[entry] = true list = append(list, entry) } } return list } func extractMessage(reqID string, body []byte) (string, error) { log.Printf("(%s) extractMessage() called with body=%s", reqID, string(body)) m := make(map[string]interface{}) err := json.Unmarshal(body, &m) if err != nil { log.Printf("(%s) Could not unmarshal: %v", reqID, err) return "", err } if m["data_base64"] != nil { b, err := base64.StdEncoding.DecodeString(m["data_base64"].(string)) if err != nil { log.Printf("(%s) Could not base64 decode: %v", reqID, err) return "", err } msg := string(b) log.Printf("(%s) output from base64='%s'", reqID, msg) return msg, nil } msg := m["data"].(string) log.Printf("(%s) output='%s'", reqID, msg) return msg, nil } func extractBulkMessage(reqID string, body []byte, isRawPayload bool) ([]AppBulkMessageEntry, error) { log.Printf("(%s) extractBulkMessage() called with body=%s", reqID, string(body)) if !isRawPayload { var bulkMsg BulkMessage err := json.Unmarshal(body, &bulkMsg) if err != nil { log.Printf("(%s) Could not unmarshal bulkMsg: %v", reqID, err) return nil, err } finalMsgs := make([]AppBulkMessageEntry, len(bulkMsg.Entries)) for i, entry := range bulkMsg.Entries { entryCEData := entry.Event["data"].(string) appMsg := AppBulkMessageEntry{ EntryId: entry.EntryId, EventStr: entryCEData, } finalMsgs[i] = appMsg log.Printf("(%s) output at index: %d, entry id:'%s' is: '%s':", reqID, i, entry.EntryId, entryCEData) } return finalMsgs, nil } var bulkMsg BulkRawMessage err := json.Unmarshal(body, &bulkMsg) if err != nil { log.Printf("(%s) Could not unmarshal raw bulkMsg: %v", reqID, err) return nil, err } finalMsgs := make([]AppBulkMessageEntry, len(bulkMsg.Entries)) for i, entry := range bulkMsg.Entries { entryData, err := base64.StdEncoding.DecodeString(entry.Event) if err != nil { log.Printf("(%s) Could not base64 decode in bulk entry: %v", reqID, err) continue } entryDataStr := string(entryData) log.Printf("(%s) output from base64 in bulk entry %s is:'%s'", reqID, entry.EntryId, entryDataStr) var actualMsg string err = json.Unmarshal([]byte(entryDataStr), &actualMsg) if err != nil { // Log only log.Printf("(%s) Error extracing JSON from raw event in bulk entry %s is: %v", reqID, entry.EntryId, err) } else { log.Printf("(%s) Output of JSON from raw event in bulk entry %s is: %v", reqID, entry.EntryId, actualMsg) entryDataStr = actualMsg } appMsg := AppBulkMessageEntry{ EntryId: entry.EntryId, EventStr: entryDataStr, } finalMsgs[i] = appMsg log.Printf("(%s) output at index: %d, entry id:'%s' is: '%s':", reqID, i, entry.EntryId, entryData) } return finalMsgs, nil } // the test calls this to get the messages received func getReceivedMessages(w http.ResponseWriter, r *http.Request) { reqID, ok := r.Context().Value("reqid").(string) if reqID == "" || !ok { reqID = "s-" + uuid.New().String() } response := receivedMessagesResponse{ ReceivedByTopicRawSub: unique(sets.List(receivedMessagesSubRaw)), ReceivedByTopicCESub: unique(sets.List(receivedMessagesSubCE)), ReceivedByTopicRawBulkSub: unique(sets.List(receivedMessagesBulkRaw)), ReceivedByTopicCEBulkSub: unique(sets.List(receivedMessagesBulkCE)), ReceivedByTopicDead: unique(sets.List(receivedMessagesBulkDead)), ReceivedByTopicDeadLetter: unique(sets.List(receivedMessagesBulkDeadLetter)), } log.Printf("getReceivedMessages called. reqID=%s response=%s", reqID, response) w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(response) } // setDesiredResponse returns an http.HandlerFunc that sets the desired response // to `resp` and logs `msg`. func setDesiredResponse(resp respondWith, msg string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() lock.Lock() defer lock.Unlock() log.Print(msg) desiredResponse = resp w.WriteHeader(http.StatusOK) } } // handler called for empty-json case. func initializeHandler(w http.ResponseWriter, _ *http.Request) { initializeSets() w.WriteHeader(http.StatusOK) } // initialize all the sets for a clean test. func initializeSets() { // initialize all the sets receivedMessagesSubRaw = sets.New[string]() receivedMessagesSubCE = sets.New[string]() receivedMessagesBulkRaw = sets.New[string]() receivedMessagesBulkCE = sets.New[string]() receivedMessagesBulkDead = sets.New[string]() receivedMessagesBulkDeadLetter = sets.New[string]() } // appRouter initializes restful api router func appRouter() http.Handler { log.Printf("Called appRouter()") router := mux.NewRouter().StrictSlash(true) // Log requests and their processing time router.Use(utils.LoggerMiddleware) router.HandleFunc("/", indexHandler).Methods("GET") router.HandleFunc("/getMessages", getReceivedMessages).Methods("POST") router.HandleFunc("/set-respond-success", setDesiredResponse(respondWithSuccess, "set respond with success")).Methods("POST") router.HandleFunc("/set-respond-success-bulk", setDesiredResponse(respondWithSuccessBulk, "set respond with success for bulk")).Methods("POST") router.HandleFunc("/set-respond-error", setDesiredResponse(respondWithError, "set respond with error")).Methods("POST") router.HandleFunc("/set-respond-retry", setDesiredResponse(respondWithRetry, "set respond with retry")).Methods("POST") router.HandleFunc("/set-respond-drop", setDesiredResponse(respondWithDrop, "set respond with drop")).Methods("POST") router.HandleFunc("/set-respond-empty-json", setDesiredResponse(respondWithEmptyJSON, "set respond with empty json")) router.HandleFunc("/set-respond-invalid-status", setDesiredResponse(respondWithInvalidStatus, "set respond with invalid status")).Methods("POST") router.HandleFunc("/initialize", initializeHandler).Methods("POST") router.HandleFunc("/dapr/subscribe", configureSubscribeHandler).Methods("GET") router.HandleFunc("/"+pubsubRawSubTopic, subscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubCESubTopic, subscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubRawBulkSubTopic, bulkSubscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubCEBulkSubTopic, bulkSubscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubDeadBulkSubTopic, bulkSubscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubDeadLetterBulkSubTopic, bulkSubscribeHandler).Methods("POST") router.Use(mux.CORSMethodMiddleware(router)) return router } func main() { // initialize sets on application start initializeSets() log.Printf("Dapr E2E test app: pubsub - listening on http://localhost:%d", appPort) utils.StartServer(appPort, appRouter, true, false) }
mikeee/dapr
tests/apps/pubsub-bulk-subscriber/app.go
GO
mit
20,000
# In e2e test, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing e2e test. kind: Service apiVersion: v1 metadata: name: pubsub-bulk-subscriber labels: testapp: pubsub-bulk-subscriber spec: selector: testapp: pubsub-bulk-subscriber ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer --- apiVersion: apps/v1 kind: Deployment metadata: name: pubsub-bulk-subscriber labels: testapp: pubsub-bulk-subscriber spec: replicas: 1 selector: matchLabels: testapp: pubsub-bulk-subscriber template: metadata: labels: testapp: pubsub-bulk-subscriber annotations: dapr.io/enabled: "true" dapr.io/app-id: "pubsub-bulk-subscriber" dapr.io/app-port: "3000" spec: containers: - name: pubsub-bulk-subscriber image: docker.io/YOUR ID/e2e-pubsub-subscriber:dev ports: - containerPort: 3000 imagePullPolicy: Always
mikeee/dapr
tests/apps/pubsub-bulk-subscriber/service.yaml
YAML
mit
1,061
../../../dapr/proto/common/v1/*.proto ../../../dapr/proto/runtime/v1/*.proto ../utils/*.go
mikeee/dapr
tests/apps/pubsub-publisher/.cache-include
none
mit
90
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "bytes" "context" "encoding/json" "fmt" "io" "log" "net/http" netUrl "net/url" "os" "strconv" "strings" "time" "github.com/google/uuid" "github.com/gorilla/mux" daprhttp "github.com/dapr/dapr/pkg/api/http" commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/apps/utils" ) const ( appPort = 3000 daprPortHTTP = 3500 daprPortGRPC = 50001 metadataPrefix = "metadata." PubSubEnvVar = "DAPR_TEST_PUBSUB_NAME" bulkPubsubMetaKey = "bulkPublishPubsubName" bulkSubTopicIdentity = "sub-topic" ) type bulkPublishMessageEntry struct { EntryId string `json:"entryId,omitempty"` //nolint:stylecheck Event interface{} `json:"event"` ContentType string `json:"ContentType"` Metadata map[string]string `json:"metadata,omitempty"` } var ( pubsubName = "messagebus" pubsubKafka = "kafka-messagebus" ) func init() { if psName := os.Getenv(PubSubEnvVar); len(psName) != 0 { pubsubName = psName } } type publishCommand struct { ReqID string `json:"reqID"` ContentType string `json:"contentType"` Topic string `json:"topic"` Data interface{} `json:"data"` Protocol string `json:"protocol"` Metadata map[string]string `json:"metadata"` } type appResponse struct { Message string `json:"message,omitempty"` StartTime int `json:"start_time,omitempty"` EndTime int `json:"end_time,omitempty"` } type callSubscriberMethodRequest struct { ReqID string `json:"reqID"` RemoteApp string `json:"remoteApp"` Protocol string `json:"protocol"` Method string `json:"method"` } var ( grpcClient runtimev1pb.DaprClient httpClient = utils.NewHTTPClient() ) // indexHandler is the handler for root path func indexHandler(w http.ResponseWriter, r *http.Request) { log.Printf("indexHandler is called\n") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{Message: "OK"}) } func getBulkRequestMetadata(r *http.Request) map[string]string { metadata := map[string]string{} for k, v := range r.URL.Query() { if strings.HasPrefix(k, metadataPrefix) { m := strings.TrimPrefix(k, metadataPrefix) metadata[m] = v[len(v)-1] // get only last occurring value? log.Printf("found metadata %s = %s\n", m, v[len(v)-1]) } } return metadata } func getBulkPublishPubsubOrDefault(reqMeta map[string]string) string { if v, ok := reqMeta[bulkPubsubMetaKey]; ok { delete(reqMeta, bulkPubsubMetaKey) return v } return pubsubName } // when called by the test, this function publishes to dapr func performBulkPublish(w http.ResponseWriter, r *http.Request) { startTime := time.Now() reqID := "s-" + uuid.New().String() reqMetadata := getBulkRequestMetadata(r) pubsubToPublish := getBulkPublishPubsubOrDefault(reqMetadata) log.Printf("publishing to pubsub %s", pubsubToPublish) var commands []publishCommand err := json.NewDecoder(r.Body).Decode(&commands) r.Body.Close() if err != nil { log.Printf("(%s) performBulkPublish() called. Failed to parse command body: %v", reqID, err) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(appResponse{ Message: err.Error(), }) return } topic := "" protocol := "" if len(commands) > 0 { topic = commands[0].Topic protocol = commands[0].Protocol } else { log.Printf("(%s) performBulkPublish() called. No commands to execute", reqID) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(appResponse{ Message: fmt.Sprintf("(%s) performBulkPublish() called. No commands to execute", reqID), }) return } bulkPublishMessage := make([]bulkPublishMessageEntry, len(commands)) for i, command := range commands { if command.Topic != topic { msg := fmt.Sprintf("(%s) performBulkPublish() called. Different topics given for different commands %s, %s", reqID, topic, command.Topic) log.Print(msg) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(appResponse{ Message: msg, }) return } if command.Protocol != protocol { msg := fmt.Sprintf("(%s) performBulkPublish() called. Different protocols given for different commands %s, %s", reqID, protocol, command.Protocol) log.Print(msg) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(appResponse{ Message: msg, }) return } bulkPublishMessage[i].EntryId = strconv.Itoa(i) if command.ReqID != "" { reqID = command.ReqID } enc, _ := json.Marshal(command) log.Printf("(%s) performBulkPublish() called with publishCommand=%s", reqID, string(enc)) bulkPublishMessage[i].Event = command.Data contentType := command.ContentType if contentType == "" { msg := fmt.Sprintf("(%s) performBulkPublish() called. Missing contentType for some events", reqID) log.Print(msg) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(appResponse{ Message: msg, }) return } bulkPublishMessage[i].ContentType = contentType if command.Metadata != nil { bulkPublishMessage[i].Metadata = map[string]string{} for k, v := range command.Metadata { bulkPublishMessage[i].Metadata[k] = v } } } jsonValue, err := json.Marshal(bulkPublishMessage) if err != nil { log.Printf("(%s) Error Marshaling: %v", reqID, err) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(appResponse{ Message: err.Error(), }) return } // publish to dapr if protocol == "http" { bulkRes, status, err := performBulkPublishHTTP(reqID, pubsubToPublish, topic, jsonValue, reqMetadata) if err != nil { log.Printf("(%s) BulkPublish failed with error=%v, StatusCode=%d", reqID, err, status) log.Printf("(%s) BulkPublish failed with bulkRes errorCode=%v", reqID, bulkRes.ErrorCode) for _, stat := range bulkRes.FailedEntries { log.Printf("Failed event with entry ID (%s) and error %s", stat.EntryId, stat.Error) } w.WriteHeader(status) json.NewEncoder(w).Encode(bulkRes) return } // pass on status code to the calling application w.WriteHeader(status) endTime := time.Now() duration := endTime.Sub(startTime) if status == http.StatusOK || status == http.StatusNoContent { log.Printf("(%s) BulkPublish succeeded in %v", reqID, formatDuration(duration)) } else { log.Printf("(%s) BulkPublish failed in %v", reqID, formatDuration(duration)) } json.NewEncoder(w).Encode(bulkRes) return } else if protocol == "grpc" { // Build runtimev1pb.BulkPublishRequestEntry objects entries := make([]*runtimev1pb.BulkPublishRequestEntry, 0, len(bulkPublishMessage)) for _, entry := range bulkPublishMessage { e := &runtimev1pb.BulkPublishRequestEntry{ EntryId: entry.EntryId, ContentType: entry.ContentType, Metadata: entry.Metadata, } // All data coming into gRPC must be in bytes only data, err := daprhttp.ConvertEventToBytes(entry.Event, entry.ContentType) if err != nil { log.Printf("(%s) Error Marshaling: %v", reqID, err) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(appResponse{ Message: err.Error(), }) return } e.Event = data entries = append(entries, e) } bulkRes, status, err := performBulkPublishGRPC(reqID, pubsubToPublish, topic, entries, reqMetadata) log.Printf("status code %d", status) if err != nil { log.Printf("(%s) BulkPublish failed with error=%v, StatusCode=%d", reqID, err, status) log.Printf("(%s) BulkPublish failed with bulkRes errorCode=%v", reqID, bulkRes) for _, stat := range bulkRes.GetFailedEntries() { log.Printf("Failed event with entry ID (%s) and error %s", stat.GetEntryId(), stat.GetError()) } w.WriteHeader(status) json.NewEncoder(w).Encode(bulkRes) return } // pass on status code to the calling application w.WriteHeader(status) endTime := time.Now() duration := endTime.Sub(startTime) if status == http.StatusOK || status == http.StatusNoContent { log.Printf("(%s) BulkPublish succeeded in %v", reqID, formatDuration(duration)) } else { log.Printf("(%s) BulkPublish failed in %v", reqID, formatDuration(duration)) } json.NewEncoder(w).Encode("Done") return } status := http.StatusBadRequest // pass on status code to the calling application w.WriteHeader(status) endTime := time.Now() duration := endTime.Sub(startTime) if status == http.StatusOK || status == http.StatusNoContent { log.Printf("(%s) BulkPublish succeeded in %v", reqID, formatDuration(duration)) } else { log.Printf("(%s) BulkPublish failed in %v", reqID, formatDuration(duration)) } json.NewEncoder(w).Encode("Done") } func performBulkPublishGRPC(reqID string, pubsubToPublish, topic string, entries []*runtimev1pb.BulkPublishRequestEntry, reqMeta map[string]string) (*runtimev1pb.BulkPublishResponse, int, error) { url := fmt.Sprintf("localhost:%d", daprPortGRPC) log.Printf("Connecting to dapr using url %s", url) // change from default pubsub req := &runtimev1pb.BulkPublishRequest{ PubsubName: pubsubToPublish, Topic: topic, Metadata: reqMeta, Entries: entries, } log.Printf("Pubsub to publish to is %s", req.GetPubsubName()) ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) res, err := grpcClient.BulkPublishEventAlpha1(ctx, req) cancel() log.Printf("Error is there? %v", err != nil) if err != nil { log.Printf("(%s) Publish failed with response : %v", reqID, res) log.Printf("(%s) Publish failed: %v", reqID, err) return res, http.StatusInternalServerError, err } return res, http.StatusOK, nil } func performBulkPublishHTTP(reqID string, pubsubToPublish, topic string, jsonValue []byte, reqMeta map[string]string) (daprhttp.BulkPublishResponse, int, error) { url := fmt.Sprintf("http://localhost:%d/v1.0-alpha1/publish/bulk/%s/%s", daprPortHTTP, pubsubToPublish, topic) if len(reqMeta) > 0 { params := netUrl.Values{} for k, v := range reqMeta { params.Set(fmt.Sprintf("metadata.%s", k), v) } url = url + "?" + params.Encode() } log.Printf("(%s) BulkPublishing using url %s and body '%s'", reqID, url, jsonValue) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(jsonValue)) if err != nil { return daprhttp.BulkPublishResponse{}, 0, err } req.Header.Set("Content-Type", "applcation/json") resp, err := httpClient.Do(req) if err != nil { if resp != nil { return daprhttp.BulkPublishResponse{}, resp.StatusCode, err } return daprhttp.BulkPublishResponse{}, http.StatusInternalServerError, err } // Success scenario, no content is returned. if resp.StatusCode == http.StatusNoContent { return daprhttp.BulkPublishResponse{}, resp.StatusCode, nil } defer resp.Body.Close() resBytes, err := io.ReadAll(resp.Body) if err != nil { return daprhttp.BulkPublishResponse{}, http.StatusInternalServerError, fmt.Errorf("error read bulkres as bytes %w", err) } bulkRes := daprhttp.BulkPublishResponse{} err = json.Unmarshal(resBytes, &bulkRes) if err != nil { return daprhttp.BulkPublishResponse{}, http.StatusInternalServerError, fmt.Errorf("error unmarshal bulkres %w", err) } return bulkRes, resp.StatusCode, nil } // when called by the test, this function publishes to dapr func performPublish(w http.ResponseWriter, r *http.Request) { startTime := time.Now() reqID := "s-" + uuid.New().String() var commandBody publishCommand err := json.NewDecoder(r.Body).Decode(&commandBody) r.Body.Close() if err != nil { log.Printf("(%s) performPublish() called. Failed to parse command body: %v", reqID, err) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(appResponse{ Message: err.Error(), }) return } if commandBody.ReqID != "" { reqID = commandBody.ReqID } { enc, _ := json.Marshal(commandBody) log.Printf("(%s) performPublish() called with commandBody=%s", reqID, string(enc)) } // based on commandBody.Topic, send to the appropriate topic resp := appResponse{Message: fmt.Sprintf("%s is not supported", commandBody.Topic)} jsonValue, err := json.Marshal(commandBody.Data) if err != nil { log.Printf("(%s) Error Marshaling: %v", reqID, err) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(appResponse{ Message: err.Error(), }) return } contentType := commandBody.ContentType if contentType == "" { contentType = "application/json" } // publish to dapr var status int if commandBody.Protocol == "grpc" { status, err = performPublishGRPC(reqID, commandBody.Topic, jsonValue, contentType, commandBody.Metadata) } else { status, err = performPublishHTTP(reqID, commandBody.Topic, jsonValue, contentType, commandBody.Metadata) } if err != nil { log.Printf("(%s) Publish failed with error=%v, StatusCode=%d", reqID, err, status) w.WriteHeader(status) json.NewEncoder(w).Encode(appResponse{ Message: err.Error(), }) return } // pass on status code to the calling application w.WriteHeader(status) endTime := time.Now() duration := endTime.Sub(startTime) if status == http.StatusOK || status == http.StatusNoContent { log.Printf("(%s) Publish succeeded in %v", reqID, formatDuration(duration)) resp = appResponse{Message: "Success"} } else { log.Printf("(%s) Publish failed in %v", reqID, formatDuration(duration)) resp = appResponse{Message: "Failed"} } resp.StartTime = epoch(&startTime) resp.EndTime = epoch(&endTime) json.NewEncoder(w).Encode(resp) } func performPublishHTTP(reqID string, topic string, jsonValue []byte, contentType string, metadata map[string]string) (int, error) { psName := pubsubName if strings.Contains(topic, bulkSubTopicIdentity) { psName = pubsubKafka } url := fmt.Sprintf("http://localhost:%d/v1.0/publish/%s/%s", daprPortHTTP, psName, topic) if len(metadata) > 0 { params := netUrl.Values{} for k, v := range metadata { params.Set(fmt.Sprintf("metadata.%s", k), v) } url = url + "?" + params.Encode() } log.Printf("(%s) Publishing using url %s and body '%s'", reqID, url, jsonValue) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(jsonValue)) if err != nil { return 0, err } req.Header.Set("Content-Type", contentType) resp, err := httpClient.Do(req) if err != nil { if resp != nil { return resp.StatusCode, err } return http.StatusInternalServerError, err } resp.Body.Close() return resp.StatusCode, nil } func performPublishGRPC(reqID string, topic string, jsonValue []byte, contentType string, metadata map[string]string) (int, error) { psName := pubsubName if strings.Contains(topic, bulkSubTopicIdentity) { psName = pubsubKafka } url := fmt.Sprintf("localhost:%d", daprPortGRPC) log.Printf("Connecting to dapr using url %s", url) req := &runtimev1pb.PublishEventRequest{ PubsubName: psName, Topic: topic, Data: jsonValue, DataContentType: contentType, Metadata: metadata, } ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) _, err := grpcClient.PublishEvent(ctx, req) cancel() if err != nil { log.Printf("(%s) Publish failed: %v", reqID, err) if strings.Contains(err.Error(), "topic is empty") { return http.StatusNotFound, err } return http.StatusInternalServerError, err } return http.StatusNoContent, nil } func callSubscriberMethod(w http.ResponseWriter, r *http.Request) { startTime := time.Now() reqID := "s-" + uuid.New().String() body, err := io.ReadAll(r.Body) r.Body.Close() if err != nil { log.Printf("(%s) Could not read request body: %v", reqID, err) w.WriteHeader(http.StatusInternalServerError) return } var req callSubscriberMethodRequest err = json.Unmarshal(body, &req) if err != nil { log.Printf("(%s) Could not parse JSON request body: %v", reqID, err) w.WriteHeader(http.StatusInternalServerError) return } if req.ReqID != "" { reqID = req.ReqID } log.Printf("(%s) callSubscriberMethod: Call %s on %s via %s", reqID, req.Method, req.RemoteApp, req.Protocol) var resp []byte if req.Protocol == "grpc" { resp, err = callSubscriberMethodGRPC(reqID, req.RemoteApp, req.Method) } else { resp, err = callSubscriberMethodHTTP(reqID, req.RemoteApp, req.Method) } if err != nil { log.Printf("(%s) Could not get logs from %s: %s", reqID, req.RemoteApp, err.Error()) w.WriteHeader(http.StatusInternalServerError) return } w.Write(resp) duration := time.Now().Sub(startTime) log.Printf("(%s) responded in %v via %s", reqID, formatDuration(duration), req.Protocol) } func callSubscriberMethodGRPC(reqID, appName, method string) ([]byte, error) { invokeReq := &commonv1pb.InvokeRequest{ Method: method, } qs := netUrl.Values{"reqid": []string{reqID}}.Encode() invokeReq.HttpExtension = &commonv1pb.HTTPExtension{ Verb: commonv1pb.HTTPExtension_Verb(commonv1pb.HTTPExtension_Verb_value["POST"]), //nolint:nosnakecase Querystring: qs, } req := &runtimev1pb.InvokeServiceRequest{ Message: invokeReq, Id: appName, } ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) resp, err := grpcClient.InvokeService(ctx, req) cancel() if err != nil { return nil, err } return resp.GetData().GetValue(), nil } func callSubscriberMethodHTTP(reqID, appName, method string) ([]byte, error) { qs := netUrl.Values{"reqid": []string{reqID}}.Encode() url := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/%s?%s", daprPortHTTP, appName, method, qs) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer([]byte{})) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") resp, err := httpClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } return body, nil } // epoch returns the unix epoch timestamp from a time func epoch(t *time.Time) int { return int(t.UnixMilli()) } // formatDuration formats the duration in ms func formatDuration(d time.Duration) string { return fmt.Sprintf("%dms", d.Truncate(100*time.Microsecond).Milliseconds()) } // appRouter initializes restful api router func appRouter() http.Handler { log.Printf("Enter appRouter()") router := mux.NewRouter().StrictSlash(true) // Log requests and their processing time router.Use(utils.LoggerMiddleware) router.HandleFunc("/", indexHandler).Methods("GET") router.HandleFunc("/tests/publish", performPublish).Methods("POST") router.HandleFunc("/tests/bulkpublish", performBulkPublish).Methods("POST") router.HandleFunc("/tests/callSubscriberMethod", callSubscriberMethod).Methods("POST") router.Use(mux.CORSMethodMiddleware(router)) return router } func main() { grpcClient = utils.GetGRPCClient(daprPortGRPC) log.Printf("PubSub Publisher - listening on http://localhost:%d", appPort) utils.StartServer(appPort, appRouter, true, false) }
mikeee/dapr
tests/apps/pubsub-publisher/app.go
GO
mit
19,818
# In e2e test, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing e2e test. kind: Service apiVersion: v1 metadata: name: pubsub-publisher labels: testapp: pubsub-publisher spec: selector: testapp: pubsub-publisher ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer --- apiVersion: apps/v1 kind: Deployment metadata: name: pubsub-publisher labels: testapp: pubsub-publisher spec: replicas: 1 selector: matchLabels: testapp: pubsub-publisher template: metadata: labels: testapp: pubsub-publisher annotations: dapr.io/enabled: "true" dapr.io/app-id: "pubsub-publisher" dapr.io/app-port: "3000" spec: containers: - name: pubsub-publisher image: docker.io/YOUR ID/e2e-pubsub-publisher:dev ports: - containerPort: 3000 imagePullPolicy: Always
mikeee/dapr
tests/apps/pubsub-publisher/service.yaml
YAML
mit
1,006
../utils/*.go
mikeee/dapr
tests/apps/pubsub-subscriber-routing/.cache-include
none
mit
13
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "encoding/base64" "encoding/json" "errors" "io" "log" "net/http" "sync" "github.com/google/uuid" "github.com/gorilla/mux" "k8s.io/apimachinery/pkg/util/sets" "github.com/dapr/dapr/tests/apps/utils" ) const ( appPort = 3000 pubsubName = "messagebus" pubsubTopic = "pubsub-routing-http" pathA = "myevent.A" pathB = "myevent.B" pathC = "myevent.C" pathD = "myevent.D" pathE = "myevent.E" pathF = "myevent.F" ) type appResponse struct { // Status field for proper handling of errors form pubsub Status string `json:"status,omitempty"` Message string `json:"message,omitempty"` StartTime int `json:"start_time,omitempty"` EndTime int `json:"end_time,omitempty"` } type routedMessagesResponse struct { RouteA []string `json:"route-a"` RouteB []string `json:"route-b"` RouteC []string `json:"route-c"` RouteD []string `json:"route-d"` RouteE []string `json:"route-e"` RouteF []string `json:"route-f"` } type subscription struct { PubsubName string `json:"pubsubname"` Topic string `json:"topic"` Metadata map[string]string `json:"metadata"` Routes routes `json:"routes,omitempty"` } type routes struct { Rules []rule `json:"rules,omitempty"` Default string `json:"default,omitempty"` } type rule struct { Match string `json:"match"` Path string `json:"path"` } var ( // using sets to make the test idempotent on multiple delivery of same message routedMessagesA sets.Set[string] routedMessagesB sets.Set[string] routedMessagesC sets.Set[string] routedMessagesD sets.Set[string] routedMessagesE sets.Set[string] routedMessagesF sets.Set[string] lock sync.Mutex ) // initialize all the sets for a clean test. func initializeSets() { lock.Lock() defer lock.Unlock() // initialize all the sets routedMessagesA = sets.New[string]() routedMessagesB = sets.New[string]() routedMessagesC = sets.New[string]() routedMessagesD = sets.New[string]() routedMessagesE = sets.New[string]() routedMessagesF = sets.New[string]() } // indexHandler is the handler for root path func indexHandler(w http.ResponseWriter, _ *http.Request) { log.Printf("indexHandler called") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{Message: "OK"}) } // this handles /dapr/subscribe, which is called from dapr into this app. // this returns the list of topics the app is subscribed to. func configureSubscribeHandler(w http.ResponseWriter, _ *http.Request) { t := []subscription{ { PubsubName: pubsubName, Topic: pubsubTopic, Routes: routes{ Rules: []rule{ { Match: `event.type == "myevent.C"`, Path: pathC, }, { Match: `event.type == "myevent.B"`, Path: pathB, }, }, Default: pathA, }, }, } log.Printf("configureSubscribeHandler called; subscribing to: %v\n", t) w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(t) } func eventHandlerA(w http.ResponseWriter, r *http.Request) { eventHandler(w, r, routedMessagesA) } func eventHandlerB(w http.ResponseWriter, r *http.Request) { eventHandler(w, r, routedMessagesB) } func eventHandlerC(w http.ResponseWriter, r *http.Request) { eventHandler(w, r, routedMessagesC) } func eventHandlerD(w http.ResponseWriter, r *http.Request) { eventHandler(w, r, routedMessagesD) } func eventHandlerE(w http.ResponseWriter, r *http.Request) { eventHandler(w, r, routedMessagesE) } func eventHandlerF(w http.ResponseWriter, r *http.Request) { eventHandler(w, r, routedMessagesF) } func eventHandler(w http.ResponseWriter, r *http.Request, set sets.Set[string]) { reqID, ok := r.Context().Value("reqid").(string) if reqID == "" || !ok { reqID = uuid.New().String() } log.Printf("(%s) eventHandler called %s", reqID, r.URL) var err error var body []byte if r.Body != nil { var data []byte data, err = io.ReadAll(r.Body) if err == nil { body = data } } else { log.Printf("(%s) r.Body is nil", reqID) } msg, err := extractMessage(reqID, body) if err != nil { log.Printf("(%s) Responding with DROP. Error from extractMessage: %v", reqID, err) // Return success with DROP status to drop message w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{ Message: err.Error(), Status: "DROP", }) return } lock.Lock() defer lock.Unlock() set.Insert(msg) w.WriteHeader(http.StatusOK) log.Printf("(%s) Responding with SUCCESS", reqID) json.NewEncoder(w).Encode(appResponse{ Message: "consumed", Status: "SUCCESS", }) } func extractMessage(reqID string, body []byte) (string, error) { log.Printf("(%s) extractMessage() called with body=%s", reqID, string(body)) if body == nil { return "", errors.New("no body") } m := make(map[string]interface{}) err := json.Unmarshal(body, &m) if err != nil { log.Printf("(%s) Could not unmarshal: %v", reqID, err) return "", err } if m["data_base64"] != nil { b, err := base64.StdEncoding.DecodeString(m["data_base64"].(string)) if err != nil { log.Printf("(%s) Could not base64 decode: %v", reqID, err) return "", err } msg := string(b) log.Printf("(%s) output from base64='%s'", reqID, msg) return msg, nil } msg := m["data"].(string) log.Printf("(%s) output='%s'", reqID, msg) return msg, nil } // handler called for empty-json case. func initializeHandler(w http.ResponseWriter, _ *http.Request) { initializeSets() w.WriteHeader(http.StatusOK) } // the test calls this to get the messages received func getReceivedMessages(w http.ResponseWriter, r *http.Request) { reqID, ok := r.Context().Value("reqid").(string) if reqID == "" || !ok { reqID = "s-" + uuid.New().String() } response := routedMessagesResponse{ RouteA: unique(sets.List(routedMessagesA)), RouteB: unique(sets.List(routedMessagesB)), RouteC: unique(sets.List(routedMessagesC)), RouteD: unique(sets.List(routedMessagesD)), RouteE: unique(sets.List(routedMessagesE)), RouteF: unique(sets.List(routedMessagesF)), } log.Printf("getReceivedMessages called. reqID=%s response=%s", reqID, response) w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(response) } func unique(slice []string) []string { keys := make(map[string]struct{}) list := []string{} for _, entry := range slice { if _, exists := keys[entry]; !exists { keys[entry] = struct{}{} list = append(list, entry) } } return list } // appRouter initializes restful api router func appRouter() http.Handler { log.Printf("Called appRouter()") router := mux.NewRouter().StrictSlash(true) // Log requests and their processing time router.Use(utils.LoggerMiddleware) router.HandleFunc("/", indexHandler).Methods("GET") router.HandleFunc("/getMessages", getReceivedMessages).Methods("POST") router.HandleFunc("/initialize", initializeHandler).Methods("POST") router.HandleFunc("/dapr/subscribe", configureSubscribeHandler).Methods("GET") router.HandleFunc("/"+pathA, eventHandlerA).Methods("POST") router.HandleFunc("/"+pathB, eventHandlerB).Methods("POST") router.HandleFunc("/"+pathC, eventHandlerC).Methods("POST") router.HandleFunc("/"+pathD, eventHandlerD).Methods("POST") router.HandleFunc("/"+pathE, eventHandlerE).Methods("POST") router.HandleFunc("/"+pathF, eventHandlerF).Methods("POST") router.Use(mux.CORSMethodMiddleware(router)) return router } func main() { // initialize sets on application start initializeSets() log.Printf("Dapr E2E test app: pubsub subscriber with routing - listening on http://localhost:%d", appPort) utils.StartServer(appPort, appRouter, true, false) }
mikeee/dapr
tests/apps/pubsub-subscriber-routing/app.go
GO
mit
8,174
# In e2e test, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing e2e test. kind: Service apiVersion: v1 metadata: name: pubsub-subscriber-routing labels: testapp: pubsub-subscriber-routing spec: selector: testapp: pubsub-subscriber-routing ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer --- apiVersion: apps/v1 kind: Deployment metadata: name: pubsub-subscriber-routing labels: testapp: pubsub-subscriber-routing spec: replicas: 1 selector: matchLabels: testapp: pubsub-subscriber-routing template: metadata: labels: testapp: pubsub-subscriber-routing annotations: dapr.io/enabled: "true" dapr.io/app-id: "pubsub-subscriber-routing" dapr.io/app-port: "3000" dapr.io/config: "pubsubroutingconfig" spec: containers: - name: pubsub-subscriber-routing image: docker.io/YOUR ID/e2e-pubsub-subscriber:dev ports: - containerPort: 3000 imagePullPolicy: Always
mikeee/dapr
tests/apps/pubsub-subscriber-routing/service.yaml
YAML
mit
1,134
../../../dapr/proto/common/v1/*.proto ../../../dapr/proto/runtime/v1/*.proto
mikeee/dapr
tests/apps/pubsub-subscriber-routing_grpc/.cache-include
none
mit
76
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "context" "encoding/json" "fmt" "log" "net" "net/url" "os" "os/signal" "sync" "syscall" "github.com/google/uuid" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/anypb" "google.golang.org/protobuf/types/known/emptypb" "k8s.io/apimachinery/pkg/util/sets" commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" ) const ( appPort = 3000 pubsubName = "messagebus" pubsubTopic = "pubsub-routing-grpc" pathA = "myevent.A" pathB = "myevent.B" pathC = "myevent.C" pathD = "myevent.D" pathE = "myevent.E" pathF = "myevent.F" ) type routedMessagesResponse struct { RouteA []string `json:"route-a"` RouteB []string `json:"route-b"` RouteC []string `json:"route-c"` RouteD []string `json:"route-d"` RouteE []string `json:"route-e"` RouteF []string `json:"route-f"` } var ( // using sets to make the test idempotent on multiple delivery of same message. routedMessagesA sets.Set[string] routedMessagesB sets.Set[string] routedMessagesC sets.Set[string] routedMessagesD sets.Set[string] routedMessagesE sets.Set[string] routedMessagesF sets.Set[string] lock sync.Mutex ) // server is our user app. type server struct{} func main() { log.Printf("Initializing grpc") /* #nosec */ lis, err := net.Listen("tcp", fmt.Sprintf(":%d", appPort)) if err != nil { log.Fatalf("failed to listen: %v", err) } lock.Lock() initializeSets() lock.Unlock() /* #nosec */ s := grpc.NewServer() runtimev1pb.RegisterAppCallbackServer(s, &server{}) log.Println("Client starting...") // Stop the gRPC server when we get a termination signal stopCh := make(chan os.Signal, 1) signal.Notify(stopCh, syscall.SIGKILL, syscall.SIGTERM, syscall.SIGINT) //nolint:staticcheck go func() { // Wait for cancelation signal <-stopCh log.Println("Shutdown signal received") s.GracefulStop() }() if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } log.Println("App shut down") } // initialize all the sets for a clean test. func initializeSets() { // initialize all the sets. routedMessagesA = sets.New[string]() routedMessagesB = sets.New[string]() routedMessagesC = sets.New[string]() routedMessagesD = sets.New[string]() routedMessagesE = sets.New[string]() routedMessagesF = sets.New[string]() } // This method gets invoked when a remote service has called the app through Dapr. // The payload carries a Method to identify the method, a set of metadata properties and an optional payload. func (s *server) OnInvoke(ctx context.Context, in *commonv1pb.InvokeRequest) (*commonv1pb.InvokeResponse, error) { reqID := "s-" + uuid.New().String() if len(in.GetHttpExtension().GetQuerystring()) > 0 { qs, err := url.ParseQuery(in.GetHttpExtension().GetQuerystring()) if err == nil && qs.Has("reqid") { reqID = qs.Get("reqid") } } log.Printf("(%s) Got invoked method %s", reqID, in.GetMethod()) lock.Lock() defer lock.Unlock() respBody := &anypb.Any{} switch in.GetMethod() { case "getMessages": respBody.Value = s.getMessages(reqID) case "initialize": initializeSets() } return &commonv1pb.InvokeResponse{Data: respBody, ContentType: "application/json"}, nil } func (s *server) getMessages(reqID string) []byte { resp := routedMessagesResponse{ RouteA: sets.List(routedMessagesA), RouteB: sets.List(routedMessagesB), RouteC: sets.List(routedMessagesC), RouteD: sets.List(routedMessagesD), RouteE: sets.List(routedMessagesE), RouteF: sets.List(routedMessagesF), } rawResp, _ := json.Marshal(resp) log.Printf("(%s) getMessages response: %s", reqID, string(rawResp)) return rawResp } // Dapr will call this method to get the list of topics the app wants to subscribe to. In this example, we are telling Dapr. // To subscribe to a topic named TopicA. func (s *server) ListTopicSubscriptions(ctx context.Context, in *emptypb.Empty) (*runtimev1pb.ListTopicSubscriptionsResponse, error) { log.Println("List Topic Subscription called") return &runtimev1pb.ListTopicSubscriptionsResponse{ Subscriptions: []*runtimev1pb.TopicSubscription{ { PubsubName: pubsubName, Topic: pubsubTopic, Routes: &runtimev1pb.TopicRoutes{ Rules: []*runtimev1pb.TopicRule{ { Match: `event.type == "myevent.C"`, Path: pathC, }, { Match: `event.type == "myevent.B"`, Path: pathB, }, }, Default: pathA, }, }, }, }, nil } // This method is fired whenever a message has been published to a topic that has been subscribed. Dapr sends published messages in a CloudEvents 1.0 envelope. func (s *server) OnTopicEvent(ctx context.Context, in *runtimev1pb.TopicEventRequest) (*runtimev1pb.TopicEventResponse, error) { lock.Lock() defer lock.Unlock() reqID := uuid.New().String() log.Printf("(%s) Message arrived - Topic: %s, Message: %s, Path: %s", reqID, in.GetTopic(), string(in.GetData()), in.GetPath()) var set *sets.Set[string] switch in.GetPath() { case pathA: set = &routedMessagesA case pathB: set = &routedMessagesB case pathC: set = &routedMessagesC case pathD: set = &routedMessagesD case pathE: set = &routedMessagesE case pathF: set = &routedMessagesF default: log.Printf("(%s) Responding with DROP. in.GetPath() not found", reqID) // Return success with DROP status to drop message. return &runtimev1pb.TopicEventResponse{ Status: runtimev1pb.TopicEventResponse_DROP, //nolint:nosnakecase }, nil } msg := string(in.GetData()) set.Insert(msg) log.Printf("(%s) Responding with SUCCESS", reqID) return &runtimev1pb.TopicEventResponse{ Status: runtimev1pb.TopicEventResponse_SUCCESS, //nolint:nosnakecase }, nil } // Dapr will call this method to get the list of bindings the app will get invoked by. In this example, we are telling Dapr. // To invoke our app with a binding named storage. func (s *server) ListInputBindings(ctx context.Context, in *emptypb.Empty) (*runtimev1pb.ListInputBindingsResponse, error) { log.Println("List Input Bindings called") return &runtimev1pb.ListInputBindingsResponse{}, nil } // This method gets invoked every time a new event is fired from a registered binding. The message carries the binding name, a payload and optional metadata. func (s *server) OnBindingEvent(ctx context.Context, in *runtimev1pb.BindingEventRequest) (*runtimev1pb.BindingEventResponse, error) { log.Printf("Invoked from binding: %s", in.GetName()) return &runtimev1pb.BindingEventResponse{}, nil }
mikeee/dapr
tests/apps/pubsub-subscriber-routing_grpc/app.go
GO
mit
7,118
# In e2e test, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing e2e test. kind: Service apiVersion: v1 metadata: name: pubsub-subscriber-routing labels: testapp: pubsub-subscriber-routing spec: selector: testapp: pubsub-subscriber-routing ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer --- apiVersion: apps/v1 kind: Deployment metadata: name: pubsub-subscriber-routing labels: testapp: pubsub-subscriber-routing spec: replicas: 1 selector: matchLabels: testapp: pubsub-subscriber-routing template: metadata: labels: testapp: pubsub-subscriber-routing annotations: dapr.io/enabled: "true" dapr.io/app-id: "pubsub-subscriber-routing" dapr.io/app-port: "3000" dapr.io/app-protocol: "grpc" dapr.io/config: "pubsubroutingconfig" spec: containers: - name: pubsub-subscriber-routing image: docker.io/YOUR ID/e2e-pubsub-subscriber_grpc:dev ports: - containerPort: 3000 imagePullPolicy: Always
mikeee/dapr
tests/apps/pubsub-subscriber-routing_grpc/service.yaml
YAML
mit
1,176
../utils/*.go
mikeee/dapr
tests/apps/pubsub-subscriber/.cache-include
none
mit
13
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "encoding/base64" "encoding/json" "errors" "fmt" "io" "log" "net/http" "os" "strings" "sync" "github.com/google/uuid" "github.com/gorilla/mux" "k8s.io/apimachinery/pkg/util/sets" "github.com/dapr/dapr/tests/apps/utils" ) const ( appPort = 3000 pubsubA = "pubsub-a-topic-http" pubsubB = "pubsub-b-topic-http" pubsubC = "pubsub-c-topic-http" pubsubJob = "pubsub-job-topic-http" pubsubRaw = "pubsub-raw-topic-http" pubsubDead = "pubsub-dead-topic-http" pubsubDeadLetter = "pubsub-deadletter-topic-http" pubsubBulkTopic = "pubsub-bulk-topic-http" pubsubRawBulkTopic = "pubsub-raw-bulk-topic-http" pubsubCEBulkTopic = "pubsub-ce-bulk-topic-http" pubsubDefBulkTopic = "pubsub-def-bulk-topic-http" PubSubEnvVar = "DAPR_TEST_PUBSUB_NAME" ) var ( pubsubName = "messagebus" pubsubKafka = "kafka-messagebus" ) func init() { if psName := os.Getenv(PubSubEnvVar); len(psName) != 0 { pubsubName = psName } } type appResponse struct { // Status field for proper handling of errors form pubsub Status string `json:"status,omitempty"` Message string `json:"message,omitempty"` StartTime int `json:"start_time,omitempty"` EndTime int `json:"end_time,omitempty"` } type receivedMessagesResponse struct { ReceivedByTopicA []string `json:"pubsub-a-topic"` ReceivedByTopicB []string `json:"pubsub-b-topic"` ReceivedByTopicC []string `json:"pubsub-c-topic"` ReceivedByTopicJob []string `json:"pubsub-job-topic"` ReceivedByTopicRaw []string `json:"pubsub-raw-topic"` ReceivedByTopicDead []string `json:"pubsub-dead-topic"` ReceivedByTopicDeadLetter []string `json:"pubsub-deadletter-topic"` ReceivedByTopicBulk []string `json:"pubsub-bulk-topic"` ReceivedByTopicRawBulk []string `json:"pubsub-raw-bulk-topic"` ReceivedByTopicCEBulk []string `json:"pubsub-ce-bulk-topic"` ReceivedByTopicDefBulk []string `json:"pubsub-def-bulk-topic"` } type subscription struct { PubsubName string `json:"pubsubname"` Topic string `json:"topic"` Route string `json:"route"` DeadLetterTopic string `json:"deadLetterTopic"` Metadata map[string]string `json:"metadata"` } // respondWith determines the response to return when a message // is received. type respondWith int const ( respondWithSuccess respondWith = iota // respond with empty json message respondWithEmptyJSON // respond with error respondWithError // respond with retry respondWithRetry // respond with drop respondWithDrop // respond with invalid status respondWithInvalidStatus ) var ( // using sets to make the test idempotent on multiple delivery of same message receivedMessagesA sets.Set[string] receivedMessagesB sets.Set[string] receivedMessagesC sets.Set[string] receivedMessagesJob sets.Set[string] receivedMessagesRaw sets.Set[string] receivedMessagesDead sets.Set[string] receivedMessagesDeadLetter sets.Set[string] receivedMessagesBulkTopic sets.Set[string] receivedMessagesRawBulkTopic sets.Set[string] receivedMessagesCEBulkTopic sets.Set[string] receivedMessagesDefBulkTopic sets.Set[string] desiredResponse respondWith lock sync.Mutex ) // indexHandler is the handler for root path func indexHandler(w http.ResponseWriter, _ *http.Request) { log.Printf("indexHandler called") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{Message: "OK"}) } // this handles /dapr/subscribe, which is called from dapr into this app. // this returns the list of topics the app is subscribed to. func configureSubscribeHandler(w http.ResponseWriter, _ *http.Request) { t := []subscription{ { PubsubName: pubsubName, Topic: pubsubA, Route: pubsubA, }, { PubsubName: pubsubName, Topic: pubsubB, Route: pubsubB, }, // pubsub-c-topic is loaded from the YAML/CRD // tests/config/app_topic_subscription_pubsub.yaml. { PubsubName: pubsubName, Topic: pubsubJob, Route: pubsubJob, }, { PubsubName: pubsubName, Topic: pubsubRaw, Route: pubsubRaw, Metadata: map[string]string{ "rawPayload": "true", }, }, { PubsubName: pubsubName, Topic: pubsubDead, Route: pubsubDead, DeadLetterTopic: pubsubDeadLetter, }, { PubsubName: pubsubName, Topic: pubsubDeadLetter, Route: pubsubDeadLetter, }, { // receive normal string message from kafka pubsub PubsubName: pubsubKafka, Topic: pubsubBulkTopic, Route: pubsubBulkTopic, }, { // receive raw payload message from kafka pubsub PubsubName: pubsubKafka, Topic: pubsubRawBulkTopic, Route: pubsubRawBulkTopic, Metadata: map[string]string{ "rawPayload": "true", }, }, { // receive CE payload message from kafka pubsub PubsubName: pubsubKafka, Topic: pubsubCEBulkTopic, Route: pubsubCEBulkTopic, }, { // receive def bulk payload message from redis pubsub (default) PubsubName: pubsubName, Topic: pubsubDefBulkTopic, Route: pubsubDefBulkTopic, }, } log.Printf("configureSubscribeHandler called; subscribing to: %v\n", t) w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(t) } func readMessageBody(reqID string, r *http.Request) (msg string, err error) { defer r.Body.Close() var body []byte if r.Body != nil { var data []byte data, err = io.ReadAll(r.Body) if err == nil { body = data } } else { // error err = errors.New("r.Body is nil") } if err != nil { return "", err } msg, err = extractMessage(reqID, body) if err != nil { return "", fmt.Errorf("error from extractMessage: %w", err) } // Raw data does not have content-type, so it is handled as-is. // Because the publisher encodes to JSON before publishing, we need to decode here. if strings.HasSuffix(r.URL.String(), pubsubRaw) || strings.HasSuffix(r.URL.String(), pubsubRawBulkTopic) { var actualMsg string err = json.Unmarshal([]byte(msg), &actualMsg) if err != nil { // Log only log.Printf("(%s) Error extracing JSON from raw event: %v", reqID, err) } else { msg = actualMsg } } return msg, nil } func subscribeHandler(w http.ResponseWriter, r *http.Request) { reqID, ok := r.Context().Value("reqid").(string) if reqID == "" || !ok { reqID = uuid.New().String() } msg, err := readMessageBody(reqID, r) // Before we handle the error, see if we need to respond in another way // We still want the message so we can log it log.Printf("(%s) subscribeHandler called %s. Message: %s", reqID, r.URL, msg) switch desiredResponse { case respondWithRetry: log.Printf("(%s) Responding with RETRY", reqID) // do not store received messages, respond with success but a retry status w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{ Message: "retry later", Status: "RETRY", }) return case respondWithError: log.Printf("(%s) Responding with ERROR", reqID) // do not store received messages, respond with error w.WriteHeader(http.StatusInternalServerError) return case respondWithInvalidStatus: log.Printf("(%s) Responding with INVALID", reqID) // do not store received messages, respond with success but an invalid status w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{ Message: "invalid status triggers retry", Status: "INVALID", }) return } if err != nil { log.Printf("(%s) Responding with DROP due to error: %v", reqID, err) // Return 200 with DROP status to drop message w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{ Message: err.Error(), Status: "DROP", }) return } lock.Lock() defer lock.Unlock() if strings.HasSuffix(r.URL.String(), pubsubA) && !receivedMessagesA.Has(msg) { receivedMessagesA.Insert(msg) } else if strings.HasSuffix(r.URL.String(), pubsubB) && !receivedMessagesB.Has(msg) { receivedMessagesB.Insert(msg) } else if strings.HasSuffix(r.URL.String(), pubsubC) && !receivedMessagesC.Has(msg) { receivedMessagesC.Insert(msg) } else if strings.HasSuffix(r.URL.String(), pubsubJob) && !receivedMessagesJob.Has(msg) { receivedMessagesJob.Insert(msg) } else if strings.HasSuffix(r.URL.String(), pubsubRaw) && !receivedMessagesRaw.Has(msg) { receivedMessagesRaw.Insert(msg) } else if strings.HasSuffix(r.URL.String(), pubsubDead) && !receivedMessagesDead.Has(msg) { receivedMessagesDead.Insert(msg) } else if strings.HasSuffix(r.URL.String(), pubsubDeadLetter) && !receivedMessagesDeadLetter.Has(msg) { receivedMessagesDeadLetter.Insert(msg) } else if strings.HasSuffix(r.URL.String(), pubsubBulkTopic) && !receivedMessagesBulkTopic.Has(msg) { receivedMessagesBulkTopic.Insert(msg) } else if strings.HasSuffix(r.URL.String(), pubsubRawBulkTopic) && !receivedMessagesRawBulkTopic.Has(msg) { receivedMessagesRawBulkTopic.Insert(msg) } else if strings.HasSuffix(r.URL.String(), pubsubCEBulkTopic) && !receivedMessagesCEBulkTopic.Has(msg) { receivedMessagesCEBulkTopic.Insert(msg) } else if strings.HasSuffix(r.URL.String(), pubsubDefBulkTopic) && !receivedMessagesDefBulkTopic.Has(msg) { receivedMessagesDefBulkTopic.Insert(msg) } else { // This case is triggered when there is multiple redelivery of same message or a message // is thre for an unknown URL path errorMessage := fmt.Sprintf("Unexpected/Multiple redelivery of message from %s", r.URL.String()) log.Printf("(%s) Responding with DROP. %s", reqID, errorMessage) // Return success with DROP status to drop message w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{ Message: errorMessage, Status: "DROP", }) return } // notice that dropped messages are also counted into received messages set if desiredResponse == respondWithDrop { log.Printf("(%s) Responding with DROP", reqID) // Return success with DROP status to drop message w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{ Message: "consumed", Status: "DROP", }) return } w.WriteHeader(http.StatusOK) if desiredResponse == respondWithEmptyJSON { log.Printf("(%s) Responding with {}", reqID) w.Write([]byte("{}")) } else { log.Printf("(%s) Responding with SUCCESS", reqID) json.NewEncoder(w).Encode(appResponse{ Message: "consumed", Status: "SUCCESS", }) } } func extractMessage(reqID string, body []byte) (string, error) { log.Printf("(%s) extractMessage() called with body=%s", reqID, string(body)) m := make(map[string]interface{}) err := json.Unmarshal(body, &m) if err != nil { log.Printf("(%s) Could not unmarshal: %v", reqID, err) return "", err } if m["data_base64"] != nil { b, err := base64.StdEncoding.DecodeString(m["data_base64"].(string)) if err != nil { log.Printf("(%s) Could not base64 decode: %v", reqID, err) return "", err } msg := string(b) log.Printf("(%s) output from base64='%s'", reqID, msg) return msg, nil } msg := m["data"].(string) pubsubName := m["pubsubname"].(string) log.Printf("(%s) pubsub='%s' output='%s'", reqID, pubsubName, msg) return msg, nil } func unique(slice []string) []string { keys := make(map[string]bool) list := []string{} for _, entry := range slice { if _, value := keys[entry]; !value { keys[entry] = true list = append(list, entry) } } return list } // the test calls this to get the messages received func getReceivedMessages(w http.ResponseWriter, r *http.Request) { reqID, ok := r.Context().Value("reqid").(string) if reqID == "" || !ok { reqID = "s-" + uuid.New().String() } response := receivedMessagesResponse{ ReceivedByTopicA: unique(sets.List(receivedMessagesA)), ReceivedByTopicB: unique(sets.List(receivedMessagesB)), ReceivedByTopicC: unique(sets.List(receivedMessagesC)), ReceivedByTopicJob: unique(sets.List(receivedMessagesJob)), ReceivedByTopicRaw: unique(sets.List(receivedMessagesRaw)), ReceivedByTopicDead: unique(sets.List(receivedMessagesDead)), ReceivedByTopicDeadLetter: unique(sets.List(receivedMessagesDeadLetter)), ReceivedByTopicBulk: unique(sets.List(receivedMessagesBulkTopic)), ReceivedByTopicRawBulk: unique(sets.List(receivedMessagesRawBulkTopic)), ReceivedByTopicCEBulk: unique(sets.List(receivedMessagesCEBulkTopic)), ReceivedByTopicDefBulk: unique(sets.List(receivedMessagesDefBulkTopic)), } log.Printf("getReceivedMessages called. reqID=%s response=%s", reqID, response) w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(response) } // setDesiredResponse returns an http.HandlerFunc that sets the desired response // to `resp` and logs `msg`. func setDesiredResponse(resp respondWith, msg string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() lock.Lock() defer lock.Unlock() log.Print(msg) desiredResponse = resp w.WriteHeader(http.StatusOK) } } // handler called for empty-json case. func initializeHandler(w http.ResponseWriter, _ *http.Request) { initializeSets() w.WriteHeader(http.StatusOK) } // initialize all the sets for a clean test. func initializeSets() { // initialize all the sets receivedMessagesA = sets.New[string]() receivedMessagesB = sets.New[string]() receivedMessagesC = sets.New[string]() receivedMessagesJob = sets.New[string]() receivedMessagesRaw = sets.New[string]() receivedMessagesDead = sets.New[string]() receivedMessagesDeadLetter = sets.New[string]() receivedMessagesBulkTopic = sets.New[string]() receivedMessagesRawBulkTopic = sets.New[string]() receivedMessagesCEBulkTopic = sets.New[string]() receivedMessagesDefBulkTopic = sets.New[string]() } // appRouter initializes restful api router func appRouter() http.Handler { log.Printf("Called appRouter()") router := mux.NewRouter().StrictSlash(true) // Log requests and their processing time router.Use(utils.LoggerMiddleware) router.HandleFunc("/", indexHandler).Methods("GET") router.HandleFunc("/getMessages", getReceivedMessages).Methods("POST") router.HandleFunc("/set-respond-success", setDesiredResponse(respondWithSuccess, "set respond with success")).Methods("POST") router.HandleFunc("/set-respond-error", setDesiredResponse(respondWithError, "set respond with error")).Methods("POST") router.HandleFunc("/set-respond-retry", setDesiredResponse(respondWithRetry, "set respond with retry")).Methods("POST") router.HandleFunc("/set-respond-drop", setDesiredResponse(respondWithDrop, "set respond with drop")).Methods("POST") router.HandleFunc("/set-respond-empty-json", setDesiredResponse(respondWithEmptyJSON, "set respond with empty json")) router.HandleFunc("/set-respond-invalid-status", setDesiredResponse(respondWithInvalidStatus, "set respond with invalid status")).Methods("POST") router.HandleFunc("/initialize", initializeHandler).Methods("POST") router.HandleFunc("/dapr/subscribe", configureSubscribeHandler).Methods("GET") router.HandleFunc("/"+pubsubA, subscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubB, subscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubC, subscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubJob, subscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubRaw, subscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubDead, subscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubDeadLetter, subscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubBulkTopic, subscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubRawBulkTopic, subscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubCEBulkTopic, subscribeHandler).Methods("POST") router.HandleFunc("/"+pubsubDefBulkTopic, subscribeHandler).Methods("POST") router.Use(mux.CORSMethodMiddleware(router)) return router } func main() { // initialize sets on application start initializeSets() log.Printf("Dapr E2E test app: pubsub - listening on http://localhost:%d", appPort) utils.StartServer(appPort, appRouter, true, false) }
mikeee/dapr
tests/apps/pubsub-subscriber/app.go
GO
mit
16,844
# In e2e test, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing e2e test. kind: Service apiVersion: v1 metadata: name: pubsub-subscriber labels: testapp: pubsub-subscriber spec: selector: testapp: pubsub-subscriber ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer --- apiVersion: apps/v1 kind: Deployment metadata: name: pubsub-subscriber labels: testapp: pubsub-subscriber spec: replicas: 1 selector: matchLabels: testapp: pubsub-subscriber template: metadata: labels: testapp: pubsub-subscriber annotations: dapr.io/enabled: "true" dapr.io/app-id: "pubsub-subscriber" dapr.io/app-port: "3000" spec: containers: - name: pubsub-subscriber image: docker.io/YOUR ID/e2e-pubsub-subscriber:dev ports: - containerPort: 3000 imagePullPolicy: Always
mikeee/dapr
tests/apps/pubsub-subscriber/service.yaml
YAML
mit
1,016
../../../dapr/proto/common/v1/*.proto ../../../dapr/proto/runtime/v1/*.proto ../utils/*.go
mikeee/dapr
tests/apps/pubsub-subscriber_grpc/.cache-include
none
mit
90
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "context" "encoding/json" "errors" "fmt" "log" "net" "net/url" "os" "os/signal" "strings" "sync" "syscall" "github.com/google/uuid" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/anypb" "google.golang.org/protobuf/types/known/emptypb" "k8s.io/apimachinery/pkg/util/sets" commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" ) const ( appPort = "3000" pubsubA = "pubsub-a-topic-grpc" pubsubB = "pubsub-b-topic-grpc" pubsubC = "pubsub-c-topic-grpc" pubsubRaw = "pubsub-raw-topic-grpc" pubsubBulkTopic = "pubsub-bulk-topic-grpc" pubsubRawBulkTopic = "pubsub-raw-bulk-topic-grpc" pubsubCEBulkTopic = "pubsub-ce-bulk-topic-grpc" pubsubDefBulkTopic = "pubsub-def-bulk-topic-grpc" pubsubRawSubTopic = "pubsub-raw-sub-topic-grpc" pubsubCESubTopic = "pubsub-ce-sub-topic-grpc" pubsubRawBulkSubTopic = "pubsub-raw-bulk-sub-topic-grpc" pubsubCEBulkSubTopic = "pubsub-ce-bulk-sub-topic-grpc" pubsubName = "messagebus" pubsubKafka = "kafka-messagebus" ) var ( // using sets to make the test idempotent on multiple delivery of same message. receivedMessagesA sets.Set[string] receivedMessagesB sets.Set[string] receivedMessagesC sets.Set[string] receivedMessagesRaw sets.Set[string] receivedMessagesBulkTopic sets.Set[string] receivedMessagesRawBulkTopic sets.Set[string] receivedMessagesCEBulkTopic sets.Set[string] receivedMessagesDefBulkTopic sets.Set[string] receivedMessagesSubRaw sets.Set[string] receivedMessagesSubCE sets.Set[string] receivedMessagesRawBulkSub sets.Set[string] receivedMessagesCEBulkSub sets.Set[string] // boolean variable to respond with empty json message if set. respondWithEmptyJSON bool // boolean variable to respond with error if set. respondWithError bool // boolean variable to respond with retry if set. respondWithRetry bool // boolean variable to respond with invalid status if set. respondWithInvalidStatus bool lock sync.Mutex ) type receivedMessagesResponse struct { ReceivedByTopicA []string `json:"pubsub-a-topic"` ReceivedByTopicB []string `json:"pubsub-b-topic"` ReceivedByTopicC []string `json:"pubsub-c-topic"` ReceivedByTopicRaw []string `json:"pubsub-raw-topic"` ReceivedByTopicBulk []string `json:"pubsub-bulk-topic"` ReceivedByTopicRawBulk []string `json:"pubsub-raw-bulk-topic"` ReceivedByTopicCEBulk []string `json:"pubsub-ce-bulk-topic"` ReceivedByTopicDefBulk []string `json:"pubsub-def-bulk-topic"` ReceivedByTopicRawSub []string `json:"pubsub-raw-sub-topic"` ReceivedByTopicCESub []string `json:"pubsub-ce-sub-topic"` ReceivedByTopicRawBulkSub []string `json:"pubsub-raw-bulk-sub-topic"` ReceivedByTopicCEBulkSub []string `json:"pubsub-ce-bulk-sub-topic"` } // server is our user app. type server struct{} func main() { log.Printf("Initializing grpc") /* #nosec */ lis, err := net.Listen("tcp", fmt.Sprintf(":%s", appPort)) if err != nil { log.Fatalf("failed to listen: %v", err) } lock.Lock() initializeSets() lock.Unlock() /* #nosec */ s := grpc.NewServer() runtimev1pb.RegisterAppCallbackServer(s, &server{}) runtimev1pb.RegisterAppCallbackAlphaServer(s, &server{}) log.Println("Client starting...") // Stop the gRPC server when we get a termination signal stopCh := make(chan os.Signal, 1) signal.Notify(stopCh, syscall.SIGKILL, syscall.SIGTERM, syscall.SIGINT) //nolint:staticcheck go func() { // Wait for cancelation signal <-stopCh log.Println("Shutdown signal received") s.GracefulStop() }() if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } log.Println("App shut down") } func initializeSets() { receivedMessagesA = sets.New[string]() receivedMessagesB = sets.New[string]() receivedMessagesC = sets.New[string]() receivedMessagesRaw = sets.New[string]() receivedMessagesBulkTopic = sets.New[string]() receivedMessagesRawBulkTopic = sets.New[string]() receivedMessagesCEBulkTopic = sets.New[string]() receivedMessagesDefBulkTopic = sets.New[string]() receivedMessagesSubRaw = sets.New[string]() receivedMessagesSubCE = sets.New[string]() receivedMessagesRawBulkSub = sets.New[string]() receivedMessagesCEBulkSub = sets.New[string]() } // This method gets invoked when a remote service has called the app through Dapr // The payload carries a Method to identify the method, a set of metadata properties and an optional payload. func (s *server) OnInvoke(ctx context.Context, in *commonv1pb.InvokeRequest) (*commonv1pb.InvokeResponse, error) { reqID := "s-" + uuid.New().String() if len(in.GetHttpExtension().GetQuerystring()) > 0 { qs, err := url.ParseQuery(in.GetHttpExtension().GetQuerystring()) if err == nil && qs.Has("reqid") { reqID = qs.Get("reqid") } } log.Printf("(%s) Got invoked method %s", reqID, in.GetMethod()) lock.Lock() defer lock.Unlock() respBody := &anypb.Any{} switch in.GetMethod() { case "getMessages": respBody.Value = s.getMessages(reqID) case "initialize": initializeSets() case "set-respond-error": s.setRespondWithError() case "set-respond-retry": s.setRespondWithRetry() case "set-respond-empty-json": s.setRespondWithEmptyJSON() case "set-respond-invalid-status": s.setRespondWithInvalidStatus() } return &commonv1pb.InvokeResponse{Data: respBody, ContentType: "application/json"}, nil } func (s *server) getMessages(reqID string) []byte { resp := receivedMessagesResponse{ ReceivedByTopicA: sets.List(receivedMessagesA), ReceivedByTopicB: sets.List(receivedMessagesB), ReceivedByTopicC: sets.List(receivedMessagesC), ReceivedByTopicRaw: sets.List(receivedMessagesRaw), ReceivedByTopicBulk: sets.List(receivedMessagesBulkTopic), ReceivedByTopicRawBulk: sets.List(receivedMessagesRawBulkTopic), ReceivedByTopicCEBulk: sets.List(receivedMessagesCEBulkTopic), ReceivedByTopicDefBulk: sets.List(receivedMessagesDefBulkTopic), ReceivedByTopicRawSub: sets.List(receivedMessagesSubRaw), ReceivedByTopicCESub: sets.List(receivedMessagesSubCE), ReceivedByTopicRawBulkSub: sets.List(receivedMessagesRawBulkSub), ReceivedByTopicCEBulkSub: sets.List(receivedMessagesCEBulkSub), } rawResp, _ := json.Marshal(resp) log.Printf("(%s) getMessages response: %s", reqID, string(rawResp)) return rawResp } func (s *server) setRespondWithError() { log.Println("setRespondWithError called") respondWithError = true } func (s *server) setRespondWithRetry() { log.Println("setRespondWithRetry called") respondWithRetry = true } func (s *server) setRespondWithEmptyJSON() { log.Println("setRespondWithEmptyJSON called") respondWithEmptyJSON = true } func (s *server) setRespondWithInvalidStatus() { log.Println("setRespondWithInvalidStatus called") respondWithInvalidStatus = true } // Dapr will call this method to get the list of topics the app wants to subscribe to. In this example, we are telling Dapr // to subscribe to a topic named TopicA. func (s *server) ListTopicSubscriptions(ctx context.Context, in *emptypb.Empty) (*runtimev1pb.ListTopicSubscriptionsResponse, error) { log.Println("List Topic Subscription called") resp := &runtimev1pb.ListTopicSubscriptionsResponse{ Subscriptions: []*runtimev1pb.TopicSubscription{ { PubsubName: pubsubName, Topic: pubsubA, }, { PubsubName: pubsubName, Topic: pubsubB, }, // pubsub-c-topic-grpc is loaded from the YAML/CRD // tests/config/app_topic_subscription_pubsub_grpc.yaml. { PubsubName: pubsubName, Topic: pubsubRaw, Metadata: map[string]string{ "rawPayload": "true", }, }, // all bulk topics are passed through Kafka which has the bulk publish implemented { PubsubName: pubsubKafka, Topic: pubsubBulkTopic, }, { PubsubName: pubsubKafka, Topic: pubsubRawBulkTopic, Metadata: map[string]string{ "rawPayload": "true", }, }, { PubsubName: pubsubKafka, Topic: pubsubCEBulkTopic, }, // bulk publish default impl goes to redis as that does not have bulk publish implemented { PubsubName: pubsubName, Topic: pubsubDefBulkTopic, }, { PubsubName: pubsubKafka, Topic: pubsubRawSubTopic, Routes: &runtimev1pb.TopicRoutes{ Default: pubsubRawSubTopic, }, Metadata: map[string]string{ "rawPayload": "true", }, }, { PubsubName: pubsubKafka, Topic: pubsubCESubTopic, Routes: &runtimev1pb.TopicRoutes{ Default: pubsubCESubTopic, }, }, { PubsubName: pubsubKafka, Topic: pubsubRawBulkSubTopic, Routes: &runtimev1pb.TopicRoutes{ Default: pubsubRawBulkSubTopic, }, BulkSubscribe: &runtimev1pb.BulkSubscribeConfig{ Enabled: true, MaxMessagesCount: 60, MaxAwaitDurationMs: 1000, }, Metadata: map[string]string{ "rawPayload": "true", }, }, { PubsubName: pubsubKafka, Topic: pubsubCEBulkSubTopic, Routes: &runtimev1pb.TopicRoutes{ Default: pubsubCEBulkSubTopic, }, BulkSubscribe: &runtimev1pb.BulkSubscribeConfig{ Enabled: true, MaxMessagesCount: 60, MaxAwaitDurationMs: 1000, }, }, }, } log.Printf("Returning topic subscriptions as %v", resp) return resp, nil } // This method is fired whenever a message has been published to a topic that has been subscribed. // Dapr sends published messages in a CloudEvents 1.0 envelope. func (s *server) OnTopicEvent(ctx context.Context, in *runtimev1pb.TopicEventRequest) (*runtimev1pb.TopicEventResponse, error) { lock.Lock() defer lock.Unlock() reqID := uuid.New().String() log.Printf("(%s) Message arrived - Topic: %s, Message: %s", reqID, in.GetTopic(), string(in.GetData())) if respondWithRetry { log.Printf("(%s) Responding with RETRY", reqID) return &runtimev1pb.TopicEventResponse{ Status: runtimev1pb.TopicEventResponse_RETRY, //nolint:nosnakecase }, nil } else if respondWithError { log.Printf("(%s) Responding with ERROR", reqID) // do not store received messages, respond with error return nil, errors.New("error response") } else if respondWithInvalidStatus { log.Printf("(%s) Responding with INVALID", reqID) // do not store received messages, respond with success but an invalid status return &runtimev1pb.TopicEventResponse{ Status: 4, }, nil } if in.GetData() == nil { log.Printf("(%s) Responding with DROP. in.GetData() is nil", reqID) // Return success with DROP status to drop message return &runtimev1pb.TopicEventResponse{ Status: runtimev1pb.TopicEventResponse_DROP, //nolint:nosnakecase }, nil } log.Printf("(%s) data %s and the content type (%s)", reqID, in.GetData(), in.GetDataContentType()) var msg string var err error if !strings.Contains(in.GetTopic(), "bulk") { // This is the old flow where always the content type is application/json // and data is always json serialized err = json.Unmarshal(in.GetData(), &msg) if err != nil { log.Printf("(%s) Responding with DROP. Error while unmarshaling JSON data: %v", reqID, err) // Return success with DROP status to drop message return &runtimev1pb.TopicEventResponse{ Status: runtimev1pb.TopicEventResponse_DROP, //nolint:nosnakecase }, err } if strings.HasPrefix(in.GetTopic(), pubsubRaw) { var actualMsg string err = json.Unmarshal([]byte(msg), &actualMsg) if err != nil { log.Printf("(%s) Error extracing JSON from raw event: %v", reqID, err) } else { msg = actualMsg } } } else if strings.Contains(in.GetTopic(), "bulk") { // In bulk publish data and data content type match is important and // enforced/expected if in.GetDataContentType() == "application/json" || in.GetDataContentType() == "application/cloudevents+json" { err = json.Unmarshal(in.GetData(), &msg) if err != nil { log.Printf("(%s) Responding with DROP. Error while unmarshaling JSON data: %v", reqID, err) // Return success with DROP status to drop message return &runtimev1pb.TopicEventResponse{ Status: runtimev1pb.TopicEventResponse_DROP, //nolint:nosnakecase }, err } } else if strings.HasPrefix(in.GetDataContentType(), "text/") { msg = (string)(in.GetData()) } else if strings.Contains(in.GetTopic(), "raw") { // All raw payload topics are assumed to have "raw" in the name // this is for the bulk case // This is simply for E2E only .... // we are assuming raw payload is also a string here .... In general msg should be []byte only and compared as []byte // raw payload for bulk is set from a string so this scenario holds true msg = string(in.GetData()) } } log.Printf("(%s) Received message: %s - %s", reqID, in.GetTopic(), msg) if strings.HasPrefix(in.GetTopic(), pubsubA) && !receivedMessagesA.Has(msg) { receivedMessagesA.Insert(msg) } else if strings.HasPrefix(in.GetTopic(), pubsubB) && !receivedMessagesB.Has(msg) { receivedMessagesB.Insert(msg) } else if strings.HasPrefix(in.GetTopic(), pubsubC) && !receivedMessagesC.Has(msg) { receivedMessagesC.Insert(msg) } else if strings.HasPrefix(in.GetTopic(), pubsubRaw) && !receivedMessagesRaw.Has(msg) { receivedMessagesRaw.Insert(msg) } else if strings.HasSuffix(in.GetTopic(), pubsubBulkTopic) && !receivedMessagesBulkTopic.Has(msg) { receivedMessagesBulkTopic.Insert(msg) } else if strings.HasSuffix(in.GetTopic(), pubsubRawBulkTopic) && !receivedMessagesRawBulkTopic.Has(msg) { receivedMessagesRawBulkTopic.Insert(msg) } else if strings.HasSuffix(in.GetTopic(), pubsubCEBulkTopic) && !receivedMessagesCEBulkTopic.Has(msg) { receivedMessagesCEBulkTopic.Insert(msg) } else if strings.HasSuffix(in.GetTopic(), pubsubDefBulkTopic) && !receivedMessagesDefBulkTopic.Has(msg) { receivedMessagesDefBulkTopic.Insert(msg) } else if strings.HasPrefix(in.GetTopic(), pubsubRawSubTopic) && !receivedMessagesSubRaw.Has(msg) { receivedMessagesSubRaw.Insert(msg) } else if strings.HasPrefix(in.GetTopic(), pubsubCESubTopic) && !receivedMessagesSubCE.Has(msg) { receivedMessagesSubCE.Insert(msg) } else { log.Printf("(%s) Received duplicate message: %s - %s", reqID, in.GetTopic(), msg) } if respondWithEmptyJSON { log.Printf("(%s) Responding with {}", reqID) return &runtimev1pb.TopicEventResponse{}, nil } log.Printf("(%s) Responding with SUCCESS", reqID) return &runtimev1pb.TopicEventResponse{ Status: runtimev1pb.TopicEventResponse_SUCCESS, //nolint:nosnakecase }, nil } func (s *server) OnBulkTopicEventAlpha1(ctx context.Context, in *runtimev1pb.TopicEventBulkRequest) (*runtimev1pb.TopicEventBulkResponse, error) { reqID := uuid.New().String() log.Printf("(%s) Entered in OnBulkTopicEventAlpha1 in Bulk Subscribe - Topic: %s", reqID, in.GetTopic()) lock.Lock() defer lock.Unlock() bulkResponses := make([]*runtimev1pb.TopicEventBulkResponseEntry, len(in.GetEntries())) for i, entry := range in.GetEntries() { if entry.GetEvent() == nil { log.Printf("(%s) Responding with DROP in bulk subscribe for entryId: %s. entry.Event is nil", reqID, entry.GetEntryId()) // Return success with DROP status to drop message bulkResponses[i] = &runtimev1pb.TopicEventBulkResponseEntry{ EntryId: entry.GetEntryId(), Status: runtimev1pb.TopicEventResponse_DROP, //nolint:nosnakecase } } var msg string if strings.HasPrefix(in.GetTopic(), pubsubCEBulkSubTopic) { log.Printf("(%s) Message arrived in Bulk Subscribe - Topic: %s, Message: %s", reqID, in.GetTopic(), string(entry.GetCloudEvent().GetData())) err := json.Unmarshal(entry.GetCloudEvent().GetData(), &msg) if err != nil { log.Printf("(%s) Error extracing ce event in bulk subscribe for entryId: %s: %v", reqID, entry.GetEntryId(), err) bulkResponses[i] = &runtimev1pb.TopicEventBulkResponseEntry{ EntryId: entry.GetEntryId(), Status: runtimev1pb.TopicEventResponse_DROP, //nolint:nosnakecase } continue } log.Printf("(%s) Value of ce event in bulk subscribe for entryId: %s: %s", reqID, entry.GetEntryId(), msg) } else { log.Printf("(%s) Message arrived in Bulk Subscribe - Topic: %s, Message: %s", reqID, in.GetTopic(), string(entry.GetBytes())) err := json.Unmarshal(entry.GetBytes(), &msg) if err != nil { log.Printf("(%s) Error extracing raw event in bulk subscribe for entryId: %s: %v", reqID, entry.GetEntryId(), err) // Return success with DROP status to drop message bulkResponses[i] = &runtimev1pb.TopicEventBulkResponseEntry{ EntryId: entry.GetEntryId(), Status: runtimev1pb.TopicEventResponse_DROP, //nolint:nosnakecase } continue } log.Printf("(%s) Value of raw event in bulk subscribe for entryId: %s: %s", reqID, entry.GetEntryId(), msg) } bulkResponses[i] = &runtimev1pb.TopicEventBulkResponseEntry{ EntryId: entry.GetEntryId(), Status: runtimev1pb.TopicEventResponse_SUCCESS, //nolint:nosnakecase } if strings.HasPrefix(in.GetTopic(), pubsubRawBulkSubTopic) && !receivedMessagesRawBulkSub.Has(msg) { receivedMessagesRawBulkSub.Insert(msg) } else if strings.HasPrefix(in.GetTopic(), pubsubCEBulkSubTopic) && !receivedMessagesCEBulkSub.Has(msg) { receivedMessagesCEBulkSub.Insert(msg) } else { log.Printf("(%s) Received duplicate message in bulk subscribe: %s - %s", reqID, in.GetTopic(), msg) } } log.Printf("(%s) Responding with SUCCESS for bulk subscribe", reqID) return &runtimev1pb.TopicEventBulkResponse{ Statuses: bulkResponses, }, nil } // Dapr will call this method to get the list of bindings the app will get invoked by. In this example, we are telling Dapr // To invoke our app with a binding named storage. func (s *server) ListInputBindings(ctx context.Context, in *emptypb.Empty) (*runtimev1pb.ListInputBindingsResponse, error) { log.Println("List Input Bindings called") return &runtimev1pb.ListInputBindingsResponse{}, nil } // This method gets invoked every time a new event is fired from a registered binding. The message carries the binding name, a payload and optional metadata. func (s *server) OnBindingEvent(ctx context.Context, in *runtimev1pb.BindingEventRequest) (*runtimev1pb.BindingEventResponse, error) { log.Printf("Invoked from binding: %s", in.GetName()) return &runtimev1pb.BindingEventResponse{}, nil }
mikeee/dapr
tests/apps/pubsub-subscriber_grpc/app.go
GO
mit
19,146
../../../dapr/proto/common/v1/*.proto ../../../dapr/proto/runtime/v1/*.proto ../utils/*.go
mikeee/dapr
tests/apps/resiliencyapp/.cache-include
none
mit
90
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "context" "encoding/json" "fmt" "io" "log" "net/http" "os" "strconv" "time" commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/apps/utils" "github.com/gorilla/mux" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" pb "google.golang.org/grpc/examples/helloworld/helloworld" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/types/known/anypb" ) var ( appPort = 3000 daprHttpPort = 3500 daprGrpcPort = 50001 daprClient runtimev1pb.DaprClient callTracking map[string][]CallRecord httpClient = utils.NewHTTPClient() ) type FailureMessage struct { ID string `json:"id"` MaxFailureCount *int `json:"maxFailureCount,omitempty"` Timeout *time.Duration `json:"timeout,omitempty"` ResponseCode *int `json:"responseCode,omitempty"` } type CallRecord struct { Count int TimeSeen time.Time } type PubsubResponse struct { // Status field for proper handling of errors form pubsub Status string `json:"status,omitempty"` Message string `json:"message,omitempty"` } func init() { p := os.Getenv("DAPR_HTTP_PORT") if p != "" && p != "0" { daprHttpPort, _ = strconv.Atoi(p) } p = os.Getenv("DAPR_GRPC_PORT") if p != "" && p != "0" { daprGrpcPort, _ = strconv.Atoi(p) } p = os.Getenv("PORT") if p != "" && p != "0" { appPort, _ = strconv.Atoi(p) } } // Endpoint handling. func indexHandler(w http.ResponseWriter, r *http.Request) { log.Println("indexHandler() called") w.WriteHeader(http.StatusOK) } func healthz(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } func unknownHandler(w http.ResponseWriter, r *http.Request) { // Just some debugging, if this is printed the app isn't setup correctly. log.Printf("Unknown route called: %s", r.RequestURI) w.WriteHeader(http.StatusNotFound) } func configureSubscribeHandler(w http.ResponseWriter, r *http.Request) { log.Println("/dapr/subscribe called") subscriptions := []struct { PubsubName string Topic string Route string }{ { PubsubName: "dapr-resiliency-pubsub", Topic: "resiliency-topic-http", Route: "resiliency-topic-http", }, } b, err := json.Marshal(subscriptions) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.Write(b) } func actorConfigHandler(w http.ResponseWriter, r *http.Request) { log.Println("/dapr/config called") daprConfig := struct { Entities []string }{ Entities: []string{"resiliencyActor"}, } b, err := json.Marshal(daprConfig) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.Write(b) } func resiliencyBindingHandler(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodOptions { log.Println("resiliency binding input has been accepted") w.WriteHeader(http.StatusOK) return } body, _ := io.ReadAll(r.Body) var message FailureMessage json.Unmarshal(body, &message) log.Printf("Binding received message %s\n", string(body)) callCount := 0 if records, ok := callTracking[message.ID]; ok { callCount = records[len(records)-1].Count + 1 } log.Printf("Seen %s %d times.", message.ID, callCount) callTracking[message.ID] = append(callTracking[message.ID], CallRecord{Count: callCount, TimeSeen: time.Now()}) if message.MaxFailureCount != nil && callCount < *message.MaxFailureCount { if message.Timeout != nil { // This request can still succeed if the resiliency policy timeout is longer than this sleep. time.Sleep(*message.Timeout) } else { w.WriteHeader(http.StatusInternalServerError) return } } w.WriteHeader(http.StatusOK) } func resiliencyPubsubHandler(w http.ResponseWriter, r *http.Request) { if r.Body == nil { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(PubsubResponse{ Message: "No body", Status: "DROP", }) } defer r.Body.Close() body, err := io.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(PubsubResponse{ Message: "Couldn't read body", Status: "DROP", }) } log.Printf("Raw body: %s", string(body)) var rawBody map[string]interface{} json.Unmarshal(body, &rawBody) rawData := rawBody["data"].(map[string]interface{}) rawDataBytes, _ := json.Marshal(rawData) var message FailureMessage json.Unmarshal(rawDataBytes, &message) log.Printf("Pubsub received message %s\n", string(rawDataBytes)) callCount := 0 if records, ok := callTracking[message.ID]; ok { callCount = records[len(records)-1].Count + 1 } log.Printf("Seen %s %d times.", message.ID, callCount) callTracking[message.ID] = append(callTracking[message.ID], CallRecord{Count: callCount, TimeSeen: time.Now()}) if message.MaxFailureCount != nil && callCount < *message.MaxFailureCount { if message.Timeout != nil { // This request can still succeed if the resiliency policy timeout is longer than this sleep. time.Sleep(*message.Timeout) } else { w.WriteHeader(http.StatusInternalServerError) return } } w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(PubsubResponse{ Message: "consumed", Status: "SUCCESS", }) } func resiliencyServiceInvocationHandler(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) var message FailureMessage json.Unmarshal(body, &message) log.Printf("HTTP invocation received message %s\n", string(body)) callCount := 0 if records, ok := callTracking[message.ID]; ok { callCount = records[len(records)-1].Count + 1 } log.Printf("Seen %s %d times.", message.ID, callCount) callTracking[message.ID] = append(callTracking[message.ID], CallRecord{Count: callCount, TimeSeen: time.Now()}) if message.ResponseCode != nil { w.WriteHeader(*message.ResponseCode) return } if message.MaxFailureCount != nil && callCount < *message.MaxFailureCount { if message.Timeout != nil { // This request can still succeed if the resiliency policy timeout is longer than this sleep. time.Sleep(*message.Timeout) } else { w.WriteHeader(http.StatusInternalServerError) return } } w.WriteHeader(http.StatusOK) } func resiliencyActorMethodHandler(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) var message FailureMessage json.Unmarshal(body, &message) log.Printf("Actor received message %s\n", string(body)) callCount := 0 if records, ok := callTracking[message.ID]; ok { callCount = records[len(records)-1].Count + 1 } log.Printf("Seen %s %d times.", message.ID, callCount) callTracking[message.ID] = append(callTracking[message.ID], CallRecord{Count: callCount, TimeSeen: time.Now()}) if message.MaxFailureCount != nil && callCount < *message.MaxFailureCount { if message.Timeout != nil { // This request can still succeed if the resiliency policy timeout is longer than this sleep. log.Printf("Sleeping: %v", *message.Timeout) time.Sleep(*message.Timeout) } else { log.Println("Forcing failure.") w.WriteHeader(http.StatusInternalServerError) return } } w.WriteHeader(http.StatusOK) } func appRouter() http.Handler { router := mux.NewRouter().StrictSlash(true) // Log requests and their processing time router.Use(utils.LoggerMiddleware) router.HandleFunc("/", indexHandler).Methods("GET") // Calls from dapr. router.HandleFunc("/dapr/subscribe", configureSubscribeHandler).Methods("GET") router.HandleFunc("/dapr/config", actorConfigHandler).Methods("GET") router.HandleFunc("/healthz", healthz).Methods("GET") // Handling events/methods. router.HandleFunc("/resiliencybinding", resiliencyBindingHandler).Methods("POST", "OPTIONS") router.HandleFunc("/resiliency-topic-http", resiliencyPubsubHandler).Methods("POST") router.HandleFunc("/resiliencyInvocation", resiliencyServiceInvocationHandler).Methods("POST") router.HandleFunc("/actors/{actorType}/{id}/method/{method}", resiliencyActorMethodHandler).Methods("PUT") // Test functions. router.HandleFunc("/tests/getCallCount", TestGetCallCount).Methods("GET") router.HandleFunc("/tests/getCallCountGRPC", TestGetCallCountGRPC).Methods("GET") router.HandleFunc("/tests/invokeBinding/{binding}", TestInvokeOutputBinding).Methods("POST") router.HandleFunc("/tests/publishMessage/{pubsub}/{topic}", TestPublishMessage).Methods("POST") router.HandleFunc("/tests/invokeService/{protocol}", TestInvokeService).Methods("POST") router.HandleFunc("/tests/invokeActor/{protocol}", TestInvokeActorMethod).Methods("POST") router.NotFoundHandler = router.NewRoute().HandlerFunc(unknownHandler).GetHandler() router.Use(mux.CORSMethodMiddleware(router)) return router } func main() { callTracking = map[string][]CallRecord{} daprClient = utils.GetGRPCClient(daprGrpcPort) log.Printf("Resiliency App - listening on http://localhost:%d", appPort) utils.StartServer(appPort, appRouter, true, false) } // Test Functions. func TestGetCallCount(w http.ResponseWriter, r *http.Request) { log.Println("Getting call counts") for key, val := range callTracking { log.Printf("\t%s - Called %d times.\n", key, len(val)) } b, err := json.Marshal(callTracking) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.Write(b) } func TestGetCallCountGRPC(w http.ResponseWriter, r *http.Request) { log.Printf("Getting call counts for gRPC") req := runtimev1pb.InvokeServiceRequest{ Id: "resiliencyappgrpc", Message: &commonv1pb.InvokeRequest{ Method: "GetCallCount", Data: &anypb.Any{}, HttpExtension: &commonv1pb.HTTPExtension{ Verb: commonv1pb.HTTPExtension_POST, }, }, } resp, err := daprClient.InvokeService(context.Background(), &req) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.Write(resp.Data.Value) } func TestInvokeOutputBinding(w http.ResponseWriter, r *http.Request) { binding := mux.Vars(r)["binding"] log.Printf("Making call to output binding %s.", binding) var message FailureMessage err := json.NewDecoder(r.Body).Decode(&message) if err != nil { log.Println("Could not parse message.") w.WriteHeader(http.StatusInternalServerError) return } b, _ := json.Marshal(message) req := &runtimev1pb.InvokeBindingRequest{ Name: binding, Operation: "create", Data: b, } _, err = daprClient.InvokeBinding(context.Background(), req) if err != nil { log.Printf("Error invoking binding: %s", err.Error()) w.WriteHeader(http.StatusInternalServerError) } } func TestPublishMessage(w http.ResponseWriter, r *http.Request) { pubsub := mux.Vars(r)["pubsub"] topic := mux.Vars(r)["topic"] var message FailureMessage err := json.NewDecoder(r.Body).Decode(&message) if err != nil { log.Println("Could not parse message.") w.WriteHeader(http.StatusInternalServerError) return } log.Printf("Publishing to %s/%s - %+v", pubsub, topic, message) b, _ := json.Marshal(message) req := &runtimev1pb.PublishEventRequest{ PubsubName: pubsub, Topic: topic, Data: b, DataContentType: "application/json", } _, err = daprClient.PublishEvent(context.Background(), req) if err != nil { log.Printf("Error publishing event: %s", err.Error()) w.WriteHeader(http.StatusInternalServerError) } } func TestInvokeService(w http.ResponseWriter, r *http.Request) { protocol := mux.Vars(r)["protocol"] log.Printf("Invoking resiliency service with %s", protocol) targetApp := r.URL.Query().Get("target_app") targetMethod := r.URL.Query().Get("target_method") if protocol == "http" { if targetApp == "" { targetApp = "resiliencyapp" } if targetMethod == "" { targetMethod = "resiliencyInvocation" } url := fmt.Sprintf("http://localhost:%d/v1.0/invoke/%s/method/%s", daprHttpPort, targetApp, targetMethod) req, _ := http.NewRequest("POST", url, r.Body) defer r.Body.Close() resp, err := httpClient.Do(req) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(resp.StatusCode) if resp.Body != nil { defer resp.Body.Close() b, _ := io.ReadAll(resp.Body) w.Write(b) } } else if protocol == "grpc" { if targetApp == "" { targetApp = "resiliencyappgrpc" } if targetMethod == "" { targetMethod = "grpcInvoke" } var message FailureMessage err := json.NewDecoder(r.Body).Decode(&message) if err != nil { log.Println("Could not parse message.") w.WriteHeader(http.StatusInternalServerError) return } b, _ := json.Marshal(message) req := &runtimev1pb.InvokeServiceRequest{ Id: targetApp, Message: &commonv1pb.InvokeRequest{ Method: targetMethod, Data: &anypb.Any{ Value: b, }, }, } _, err = daprClient.InvokeService(r.Context(), req) if err != nil { log.Printf("Failed to invoke service: %s", err.Error()) w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("failed to call grpc service: %s", err.Error()))) return } } else if protocol == "grpc_proxy" { var message FailureMessage err := json.NewDecoder(r.Body).Decode(&message) if err != nil { log.Println("Could not parse message.") w.WriteHeader(http.StatusInternalServerError) return } log.Printf("Proxying message: %+v", message) b, _ := json.Marshal(message) conn, err := grpc.Dial( fmt.Sprintf("localhost:%d", daprGrpcPort), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), ) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() client := pb.NewGreeterClient(conn) ctx := r.Context() ctx = metadata.AppendToOutgoingContext(ctx, "dapr-app-id", "resiliencyappgrpc") _, err = client.SayHello(ctx, &pb.HelloRequest{Name: string(b)}) if err != nil { log.Printf("could not proxy request: %s", err.Error()) w.WriteHeader(500) w.Write([]byte(fmt.Sprintf("failed to proxy request: %s", err.Error()))) return } } } func TestInvokeActorMethod(w http.ResponseWriter, r *http.Request) { protocol := mux.Vars(r)["protocol"] log.Printf("Invoking resiliency actor with %s", protocol) if protocol == "http" { httpClient.Timeout = time.Minute url := fmt.Sprintf("http://localhost:%d/v1.0/actors/resiliencyActor/1/method/resiliencyMethod", daprHttpPort) req, _ := http.NewRequest("PUT", url, r.Body) defer r.Body.Close() resp, err := httpClient.Do(req) if err != nil { log.Printf("An error occurred calling actors: %s", err.Error()) w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(resp.StatusCode) } else if protocol == "grpc" { var message FailureMessage err := json.NewDecoder(r.Body).Decode(&message) if err != nil { log.Println("Could not parse message.") w.WriteHeader(http.StatusInternalServerError) return } b, _ := json.Marshal(message) req := &runtimev1pb.InvokeActorRequest{ ActorType: "resiliencyActor", ActorId: "1", Method: "resiliencyMethod", Data: b, } _, err = daprClient.InvokeActor(r.Context(), req) if err != nil { log.Printf("An error occurred calling actors: %s", err.Error()) w.WriteHeader(http.StatusInternalServerError) return } } }
mikeee/dapr
tests/apps/resiliencyapp/app.go
GO
mit
15,780
module github.com/dapr/dapr/tests/apps/resiliencyapp go 1.22.3 require ( github.com/dapr/dapr v0.0.0 github.com/gorilla/mux v1.8.1 google.golang.org/grpc v1.64.0 google.golang.org/grpc/examples v0.0.0-20230224211313-3775f633ce20 google.golang.org/protobuf v1.33.0 ) require ( github.com/google/uuid v1.6.0 // indirect go.opentelemetry.io/otel v1.24.0 // indirect go.opentelemetry.io/otel/trace v1.24.0 // indirect golang.org/x/net v0.24.0 // indirect golang.org/x/sys v0.19.0 // indirect golang.org/x/text v0.14.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20240318140521-94a12d6c2237 // indirect ) replace github.com/dapr/dapr => ../../../
mikeee/dapr
tests/apps/resiliencyapp/go.mod
mod
mit
675
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo= go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo= go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI= go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU= golang.org/x/exp v0.0.0-20240119083558-1b970713d09a h1:Q8/wZp0KX97QFTc2ywcOE0YRjZPVIx+MXInMzdvQqcA= golang.org/x/exp v0.0.0-20240119083558-1b970713d09a/go.mod h1:idGWGoKP1toJGkd5/ig9ZLuPcZBC3ewk7SzmH0uou08= golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= google.golang.org/genproto/googleapis/rpc v0.0.0-20240318140521-94a12d6c2237 h1:NnYq6UN9ReLM9/Y01KWNOWyI5xQ9kbIms5GGJVwS/Yc= google.golang.org/genproto/googleapis/rpc v0.0.0-20240318140521-94a12d6c2237/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY= google.golang.org/grpc v1.64.0 h1:KH3VH9y/MgNQg1dE7b3XfVK0GsPSIzJwdF617gUSbvY= google.golang.org/grpc v1.64.0/go.mod h1:oxjF8E3FBnjp+/gVFYdWacaLDx9na1aqy9oovLpxQYg= google.golang.org/grpc/examples v0.0.0-20230224211313-3775f633ce20 h1:MLBCGN1O7GzIx+cBiwfYPwtmZ41U3Mn/cotLJciaArI= google.golang.org/grpc/examples v0.0.0-20230224211313-3775f633ce20/go.mod h1:Nr5H8+MlGWr5+xX/STzdoEqJrO+YteqFbMyCsrb6mH0= google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
mikeee/dapr
tests/apps/resiliencyapp/go.sum
sum
mit
3,135
../../../dapr/proto/common/v1/*.proto ../../../dapr/proto/runtime/v1/*.proto
mikeee/dapr
tests/apps/resiliencyapp_grpc/.cache-include
none
mit
76
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "context" "encoding/json" "errors" "fmt" "log" "net" "time" commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" "google.golang.org/grpc" grpccodes "google.golang.org/grpc/codes" pb "google.golang.org/grpc/examples/helloworld/helloworld" "google.golang.org/protobuf/types/known/anypb" "google.golang.org/protobuf/types/known/emptypb" ) const ( appPort = "3000" ) // This is our app, which registers various gRPC calls. type server struct { callTracking map[string][]CallRecord pb.UnimplementedGreeterServer } type CallRecord struct { Count int TimeSeen time.Time } type FailureMessage struct { ID string `json:"id"` MaxFailureCount *int `json:"maxFailureCount,omitempty"` Timeout *time.Duration `json:"timeout,omitempty"` ResponseCode *int `json:"responseCode,omitempty"` } // SayHello implements helloworld.GreeterServer // Instead of defining our own proto and generating the client/server, we're going to force our // use case in the sample code. func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { var message FailureMessage err := json.Unmarshal([]byte(in.Name), &message) if err != nil { return nil, errors.New("failed to decode message") } callCount := 0 if records, ok := s.callTracking[message.ID]; ok { callCount = records[len(records)-1].Count + 1 } log.Printf("Proxy has seen %s %d times.", message.ID, callCount) s.callTracking[message.ID] = append(s.callTracking[message.ID], CallRecord{Count: callCount, TimeSeen: time.Now()}) if message.MaxFailureCount != nil && callCount < *message.MaxFailureCount { if message.Timeout != nil { // This request can still succeed if the resiliency policy timeout is longer than this sleep. log.Println("Sleeping.") time.Sleep(*message.Timeout) } else { log.Println("Forcing failure.") return nil, errors.New("forced failure") } } return &pb.HelloReply{Message: "Hello"}, nil } // gRPC server definitions. func (s *server) OnInvoke(ctx context.Context, in *commonv1pb.InvokeRequest) (*commonv1pb.InvokeResponse, error) { log.Printf("Got invoked method %s and data: %s", in.Method, string(in.GetData().Value)) resp := &commonv1pb.InvokeResponse{} if in.Method == "GetCallCount" { log.Println("Getting call counts") for key, val := range s.callTracking { log.Printf("\t%s - Called %d times.", key, len(val)) } b, err := json.Marshal(s.callTracking) if err != nil { resp.Data = &anypb.Any{} } else { resp.Data = &anypb.Any{ Value: b, } } } else if in.Method == "grpcInvoke" { var message FailureMessage err := json.Unmarshal(in.Data.Value, &message) if err != nil { return nil, errors.New("failed to decode message") } callCount := 0 if records, ok := s.callTracking[message.ID]; ok { callCount = records[len(records)-1].Count + 1 } log.Printf("Seen %s %d times.", message.ID, callCount) s.callTracking[message.ID] = append(s.callTracking[message.ID], CallRecord{Count: callCount, TimeSeen: time.Now()}) if message.ResponseCode != nil { return nil, grpc.Errorf(grpccodes.Code(*message.ResponseCode), "forced failure with status code %d", *message.ResponseCode) } if message.MaxFailureCount != nil && callCount < *message.MaxFailureCount { if message.Timeout != nil { // This request can still succeed if the resiliency policy timeout is longer than this sleep. log.Println("Sleeping.") time.Sleep(*message.Timeout) } else { log.Println("Forcing failure.") return nil, errors.New("forced failure") } } resp.Data = &anypb.Any{} } return resp, nil } // Dapr will call this method to get the list of topics the app wants to subscribe to. func (s *server) ListTopicSubscriptions(ctx context.Context, in *emptypb.Empty) (*runtimev1pb.ListTopicSubscriptionsResponse, error) { log.Println("List Topic Subscription called") return &runtimev1pb.ListTopicSubscriptionsResponse{ Subscriptions: []*runtimev1pb.TopicSubscription{ { PubsubName: "dapr-resiliency-pubsub", Topic: "resiliency-topic-grpc", }, }, }, nil } // This method is fired whenever a message has been published to a topic that has been subscribed. Dapr sends published messages in a CloudEvents 1.0 envelope. func (s *server) OnTopicEvent(ctx context.Context, in *runtimev1pb.TopicEventRequest) (*runtimev1pb.TopicEventResponse, error) { log.Printf("Message arrived - Topic: %s, Message: %s\n", in.Topic, string(in.Data)) var message FailureMessage err := json.Unmarshal(in.Data, &message) if err != nil { return nil, errors.New("failed to decode message") } callCount := 0 if records, ok := s.callTracking[message.ID]; ok { callCount = records[len(records)-1].Count + 1 } log.Printf("Seen %s %d times.", message.ID, callCount) s.callTracking[message.ID] = append(s.callTracking[message.ID], CallRecord{Count: callCount, TimeSeen: time.Now()}) if message.MaxFailureCount != nil && callCount < *message.MaxFailureCount { if message.Timeout != nil { // This request can still succeed if the resiliency policy timeout is longer than this sleep. log.Println("Sleeping.") time.Sleep(*message.Timeout) } else { log.Println("Forcing failure.") return nil, errors.New("forced failure") } } return &runtimev1pb.TopicEventResponse{ Status: runtimev1pb.TopicEventResponse_SUCCESS, }, nil } func (s *server) ListInputBindings(ctx context.Context, in *emptypb.Empty) (*runtimev1pb.ListInputBindingsResponse, error) { log.Println("List Input Bindings called") return &runtimev1pb.ListInputBindingsResponse{ Bindings: []string{ "dapr-resiliency-binding-grpc", }, }, nil } // This method gets invoked every time a new event is fired from a registered binding. The message carries the binding name, a payload and optional metadata. func (s *server) OnBindingEvent(ctx context.Context, in *runtimev1pb.BindingEventRequest) (*runtimev1pb.BindingEventResponse, error) { log.Printf("Invoked from binding: %s - %s\n", in.Name, string(in.Data)) var message FailureMessage err := json.Unmarshal(in.Data, &message) if err != nil { return nil, errors.New("failed to decode message") } callCount := 0 if records, ok := s.callTracking[message.ID]; ok { callCount = records[len(records)-1].Count + 1 } log.Printf("Seen %s %d times.", message.ID, callCount) s.callTracking[message.ID] = append(s.callTracking[message.ID], CallRecord{Count: callCount, TimeSeen: time.Now()}) if message.MaxFailureCount != nil && callCount < *message.MaxFailureCount { if message.Timeout != nil { // This request can still succeed if the resiliency policy timeout is longer than this sleep. log.Println("Sleeping.") time.Sleep(*message.Timeout) } else { log.Println("Forcing failure.") return nil, errors.New("forced failure") } } return &runtimev1pb.BindingEventResponse{}, nil } // Init. func main() { log.Printf("Initializing grpc") /* #nosec */ lis, err := net.Listen("tcp", fmt.Sprintf(":%s", appPort)) if err != nil { log.Fatalf("failed to listen: %v", err) } /* #nosec */ server := &server{ callTracking: map[string][]CallRecord{}, } s := grpc.NewServer() runtimev1pb.RegisterAppCallbackServer(s, server) pb.RegisterGreeterServer(s, server) log.Println("Client starting...") if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } }
mikeee/dapr
tests/apps/resiliencyapp_grpc/app.go
GO
mit
8,090
module github.com/dapr/dapr/tests/apps/resiliencyapp_grpc go 1.22.3 require ( github.com/dapr/dapr v1.7.4 google.golang.org/grpc v1.64.0 google.golang.org/grpc/examples v0.0.0-20230224211313-3775f633ce20 google.golang.org/protobuf v1.33.0 ) require ( go.opentelemetry.io/otel v1.24.0 // indirect go.opentelemetry.io/otel/trace v1.24.0 // indirect golang.org/x/net v0.24.0 // indirect golang.org/x/sys v0.19.0 // indirect golang.org/x/text v0.14.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20240318140521-94a12d6c2237 // indirect ) replace github.com/dapr/dapr => ../../../
mikeee/dapr
tests/apps/resiliencyapp_grpc/go.mod
mod
mit
606
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo= go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo= go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI= go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU= golang.org/x/exp v0.0.0-20240119083558-1b970713d09a h1:Q8/wZp0KX97QFTc2ywcOE0YRjZPVIx+MXInMzdvQqcA= golang.org/x/exp v0.0.0-20240119083558-1b970713d09a/go.mod h1:idGWGoKP1toJGkd5/ig9ZLuPcZBC3ewk7SzmH0uou08= golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= google.golang.org/genproto/googleapis/rpc v0.0.0-20240318140521-94a12d6c2237 h1:NnYq6UN9ReLM9/Y01KWNOWyI5xQ9kbIms5GGJVwS/Yc= google.golang.org/genproto/googleapis/rpc v0.0.0-20240318140521-94a12d6c2237/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY= google.golang.org/grpc v1.64.0 h1:KH3VH9y/MgNQg1dE7b3XfVK0GsPSIzJwdF617gUSbvY= google.golang.org/grpc v1.64.0/go.mod h1:oxjF8E3FBnjp+/gVFYdWacaLDx9na1aqy9oovLpxQYg= google.golang.org/grpc/examples v0.0.0-20230224211313-3775f633ce20 h1:MLBCGN1O7GzIx+cBiwfYPwtmZ41U3Mn/cotLJciaArI= google.golang.org/grpc/examples v0.0.0-20230224211313-3775f633ce20/go.mod h1:Nr5H8+MlGWr5+xX/STzdoEqJrO+YteqFbMyCsrb6mH0= google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
mikeee/dapr
tests/apps/resiliencyapp_grpc/go.sum
sum
mit
2,809
../utils/*.go
mikeee/dapr
tests/apps/runtime/.cache-include
none
mit
13
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "context" "encoding/json" "fmt" "log" "net/http" "sync" "sync/atomic" "time" "github.com/gorilla/mux" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "github.com/dapr/dapr/tests/apps/utils" ) const ( appPort = 3000 pubsubHTTPTopic = "runtime-pubsub-http" bindingsTopic = "runtime-bindings-http" daprHTTPAddr = "localhost:3500" daprGRPCAddr = "localhost:50001" ) type topicsList struct { Topic []string } type appResponse struct { Message string `json:"message,omitempty"` StartTime int `json:"start_time,omitempty"` EndTime int `json:"end_time,omitempty"` } type daprAPIResponse struct { DaprHTTPSuccess int `json:"dapr_http_success"` DaprHTTPError int `json:"dapr_http_error"` DaprGRPCSuccess int `json:"dapr_grpc_success"` DaprGRPCError int `json:"dapr_grpc_error"` } var ( pubsubDaprHTTPError, pubsubDaprHTTPSuccess uint32 pubsubDaprGRPCError, pubsubDaprGRPCSuccess uint32 bindingsDaprHTTPError, bindingsDaprHTTPSuccess uint32 bindingsDaprGRPCError, bindingsDaprGRPCSuccess uint32 ) var httpClient = utils.NewHTTPClient() // indexHandler is the handler for root path. func indexHandler(w http.ResponseWriter, r *http.Request) { log.Printf("indexHandler is called\n") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{Message: "OK"}) } // this handles /dapr/subscribe, which is called from dapr into this app. // this returns the list of topics the app is subscribed to. func configureSubscribeHandler(w http.ResponseWriter, r *http.Request) { log.Printf("configureSubscribeHandler called\n") var t topicsList t.Topic = append(t.Topic, pubsubHTTPTopic) log.Printf("configureSubscribeHandler subscribing to:%v\n", t.Topic) w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(t.Topic) } func invokeDaprHTTPAPI() error { healthURL := fmt.Sprintf("http://%s/v1.0/healthz", daprHTTPAddr) r, err := httpClient.Get(healthURL) if err != nil { return err } defer r.Body.Close() return nil } func invokeDaprGRPCAPI() error { // Dial the gRPC endpoint and fail if cannot connect in 10 seconds. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() conn, err := grpc.DialContext(ctx, daprGRPCAddr, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock()) if err != nil { return err } defer conn.Close() return nil } func testAPI(wg *sync.WaitGroup, successCount, errorCount *uint32, invoke func() error, id string) { defer wg.Done() err := invoke() if err != nil { log.Printf("Error calling Dapr %s API: %+v", id, err) atomic.AddUint32(errorCount, 1) } else { log.Printf("Success calling Dapr %s API", id) atomic.AddUint32(successCount, 1) } } func testHTTPAPI(wg *sync.WaitGroup, successCount, errorCount *uint32) { testAPI(wg, successCount, errorCount, invokeDaprHTTPAPI, "HTTP") } func testGRPCAPI(wg *sync.WaitGroup, successCount, errorCount *uint32) { testAPI(wg, successCount, errorCount, invokeDaprGRPCAPI, "gRPC") } // onPubsub handles messages published to "pubsub-http-server" and // validates dapr's HTTP API is healthy. func onPubsub(w http.ResponseWriter, r *http.Request) { log.Printf("onPubsub(): called %s\n", r.URL) var wg sync.WaitGroup wg.Add(1) go testHTTPAPI(&wg, &pubsubDaprHTTPSuccess, &pubsubDaprHTTPError) wg.Add(1) go testGRPCAPI(&wg, &pubsubDaprGRPCSuccess, &pubsubDaprGRPCError) wg.Wait() // Always return success as we want to release the messages w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{ Message: "success", }) } // onInputBinding handles incoming request from an input binding and // validates dapr's HTTP API is healthy. func onInputBinding(w http.ResponseWriter, r *http.Request) { log.Printf("onInputBinding(): called %s\n", r.URL) if r.Method == http.MethodOptions { log.Printf("%s binding input has been accepted", bindingsTopic) // Sending StatusOK back to the topic, so it will not attempt to redeliver. w.WriteHeader(http.StatusOK) return } var wg sync.WaitGroup wg.Add(1) go testHTTPAPI(&wg, &bindingsDaprHTTPSuccess, &bindingsDaprHTTPError) wg.Add(1) go testGRPCAPI(&wg, &bindingsDaprGRPCSuccess, &bindingsDaprGRPCError) wg.Wait() w.WriteHeader(http.StatusOK) } func getPubsubDaprAPIResponse(w http.ResponseWriter, r *http.Request) { log.Println("Enter getDaprAPIResponse") response := daprAPIResponse{ DaprHTTPError: int(pubsubDaprHTTPError), DaprHTTPSuccess: int(pubsubDaprHTTPSuccess), DaprGRPCError: int(pubsubDaprGRPCError), DaprGRPCSuccess: int(pubsubDaprGRPCSuccess), } log.Printf("DaprAPIResponse=%+v", response) w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(response) } func getBindingsDaprAPIResponse(w http.ResponseWriter, r *http.Request) { log.Println("Enter getDaprAPIResponse") response := daprAPIResponse{ DaprHTTPError: int(bindingsDaprHTTPError), DaprHTTPSuccess: int(bindingsDaprHTTPSuccess), DaprGRPCError: int(bindingsDaprGRPCError), DaprGRPCSuccess: int(bindingsDaprGRPCSuccess), } log.Printf("DaprAPIResponse=%+v", response) w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(response) } // appRouter initializes restful api router. func appRouter() http.Handler { log.Printf("Enter appRouter()") router := mux.NewRouter().StrictSlash(true) // Log requests and their processing time router.Use(utils.LoggerMiddleware) router.HandleFunc("/", indexHandler).Methods("GET") router.HandleFunc("/tests/pubsub", getPubsubDaprAPIResponse).Methods("GET") router.HandleFunc("/tests/bindings", getBindingsDaprAPIResponse).Methods("GET") router.HandleFunc("/dapr/subscribe", configureSubscribeHandler).Methods("GET") router.HandleFunc("/"+bindingsTopic, onInputBinding).Methods("POST", "OPTIONS") router.HandleFunc("/"+pubsubHTTPTopic, onPubsub).Methods("POST") router.Use(mux.CORSMethodMiddleware(router)) return router } func main() { log.Printf("Hello Dapr v2 - listening on http://localhost:%d", appPort) utils.StartServer(appPort, appRouter, true, false) }
mikeee/dapr
tests/apps/runtime/app.go
GO
mit
6,657
# In e2e test, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing e2e test. kind: Service apiVersion: v1 metadata: name: runtime labels: testapp: runtime spec: selector: testapp: runtime ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer --- apiVersion: apps/v1 kind: Deployment metadata: name: runtime labels: testapp: runtime spec: replicas: 1 selector: matchLabels: testapp: runtime template: metadata: labels: testapp: runtime annotations: dapr.io/enabled: "true" dapr.io/app-id: "runtime" dapr.io/app-port: "3000" spec: containers: - name: runtime image: docker.io/YOUR ID/e2e-runtime:dev ports: - containerPort: 3000 imagePullPolicy: Always
mikeee/dapr
tests/apps/runtime/service.yaml
YAML
mit
915
../utils/*.go
mikeee/dapr
tests/apps/runtime_init/.cache-include
none
mit
13
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "bytes" "encoding/json" "fmt" "log" "os" "os/signal" "sync" "syscall" "github.com/dapr/dapr/tests/apps/utils" ) const ( daprPort = 3500 pubsubTopic = "runtime-pubsub-http" numPubsubMessages = 10 bindingTopic = "runtime-bindings-http" numBindingMessage = 10 ) var httpClient = utils.NewHTTPClient() func publishMessagesToPubsub(wg *sync.WaitGroup) { defer wg.Done() daprPubsubURL := fmt.Sprintf("http://localhost:%d/v1.0/publish/%s", daprPort, pubsubTopic) for i := 0; i < numPubsubMessages; i++ { m := fmt.Sprintf("message-%d", i) jsonValue, err := json.Marshal(m) if err != nil { log.Fatalf("Error marshalling %s to JSON", m) } log.Printf("Publishing to %s", daprPubsubURL) r, err := httpClient.Post(daprPubsubURL, "application/json", bytes.NewBuffer(jsonValue)) if r != nil { defer r.Body.Close() } if err != nil { log.Fatalf("Error publishing messages to pubsub: %+v", err) } } } func publishMessagesToBinding(wg *sync.WaitGroup) { defer wg.Done() daprBindingURL := fmt.Sprintf("http://localhost:%d/v1.0/bindings/%s", daprPort, bindingTopic) for i := 0; i < numBindingMessage; i++ { b := []byte(fmt.Sprintf(`{"data": {"id": "message%d"}}`, i)) log.Printf("Publishing to %s", daprBindingURL) r, err := httpClient.Post(daprBindingURL, "application/json", bytes.NewBuffer(b)) if r != nil { defer r.Body.Close() } if err != nil { log.Fatalf("Error publishing messages to binding: %+v", err) } } } func main() { var wg sync.WaitGroup // Push messages onto pubsub wg.Add(1) go publishMessagesToPubsub(&wg) // Push messages onto binding wg.Add(1) go publishMessagesToBinding(&wg) wg.Wait() // Block until signalled to close exit := make(chan os.Signal, 1) signal.Notify(exit, os.Interrupt, syscall.SIGTERM) <-exit log.Println("Terminating!") }
mikeee/dapr
tests/apps/runtime_init/app.go
GO
mit
2,441
# In e2e test, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing e2e test. kind: Service apiVersion: v1 metadata: name: runtime_init labels: testapp: runtime_init spec: selector: testapp: runtime_init ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer --- apiVersion: apps/v1 kind: Deployment metadata: name: runtime_init labels: testapp: runtime_init spec: replicas: 1 selector: matchLabels: testapp: runtime_init template: metadata: labels: testapp: runtime_init annotations: dapr.io/enabled: "true" dapr.io/app-id: "runtime_init" dapr.io/app-port: "3000" spec: containers: - name: runtime_init image: docker.io/YOUR ID/e2e-runtime_init:dev ports: - containerPort: 3000 imagePullPolicy: Always
mikeee/dapr
tests/apps/runtime_init/service.yaml
YAML
mit
966
../utils/*.go
mikeee/dapr
tests/apps/secretapp/.cache-include
none
mit
13
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "encoding/json" "fmt" "io" "log" "net/http" "net/url" "time" "github.com/gorilla/mux" "github.com/dapr/dapr/tests/apps/utils" ) const appPort = 3000 // kubernetes is the name of the secret store const ( /* #nosec */ secretURL = "http://localhost:3500/v1.0/secrets/%s/%s?metadata.namespace=dapr-tests" ) var httpClient = utils.NewHTTPClient() // daprSecret represents a secret in Dapr. type daprSecret struct { Key string `json:"key,omitempty"` Store string `json:"store,omitempty"` Value *map[string]string `json:"value,omitempty"` } // requestResponse represents a request or response for the APIs in this app. type requestResponse struct { StartTime int `json:"start_time,omitempty"` EndTime int `json:"end_time,omitempty"` Secrets []daprSecret `json:"secrets,omitempty"` Message string `json:"message,omitempty"` } // indexHandler is the handler for root path func indexHandler(w http.ResponseWriter, _ *http.Request) { log.Println("indexHandler is called") w.WriteHeader(http.StatusOK) } func get(key, store string) (*map[string]string, int, error) { log.Printf("Processing get request for %s.", key) url, err := createSecretURL(key, store) if err != nil { return nil, http.StatusInternalServerError, err } log.Printf("Fetching secret from %s", url) // url is created from user input, it is OK since this is a test app only and will not run in prod. /* #nosec */ res, err := httpClient.Get(url) if err != nil { return nil, http.StatusInternalServerError, fmt.Errorf("could not get value for key %s from Dapr: %s", key, err.Error()) } defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { return nil, http.StatusInternalServerError, fmt.Errorf("could not load value for key %s from Dapr: %s", key, err.Error()) } if res.StatusCode != http.StatusOK { log.Printf("Non 200 StatusCode: %d\n", res.StatusCode) return nil, res.StatusCode, fmt.Errorf("got err response for key %s from Dapr: %s", key, body) } log.Printf("Found secret for key %s: %s", key, body) secret := map[string]string{} if len(body) == 0 { return nil, http.StatusOK, nil } // a key not found in Dapr will return 200 but an empty response. err = json.Unmarshal(body, &secret) if err != nil { return nil, http.StatusInternalServerError, fmt.Errorf("could not parse value for key %s from Dapr: %s", key, err.Error()) } return &secret, http.StatusOK, nil } func getAll(secrets []daprSecret) ([]daprSecret, int, error) { statusCode := http.StatusOK log.Printf("Processing get request for %d secrets.", len(secrets)) output := make([]daprSecret, 0, len(secrets)) for _, secret := range secrets { value, sc, err := get(secret.Key, secret.Store) if err != nil { return nil, sc, err } log.Printf("Result for get request for key %s: %v", secret.Key, value) output = append(output, daprSecret{ Key: secret.Key, Value: value, Store: secret.Store, }) statusCode = sc } log.Printf("Result for get request for %d secrets: %v", len(secrets), output) return output, statusCode, nil } func getBulk(secrets []daprSecret) ([]daprSecret, int, error) { if len(secrets) == 0 { return nil, http.StatusBadRequest, fmt.Errorf("no secret store specified") } store := secrets[0].Store log.Println("Processing get bulk request for secrerts.") output := []daprSecret{} url, err := createSecretURL("bulk", store) if err != nil { return nil, http.StatusInternalServerError, err } log.Printf("Fetching secret from %s", url) // url is created from user input, it is OK since this is a test app only and will not run in prod. /* #nosec */ res, err := httpClient.Get(url) if err != nil { return nil, http.StatusInternalServerError, fmt.Errorf("bulk get secret request faild %w", err) } defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { return nil, http.StatusInternalServerError, fmt.Errorf("reading body of bulk get secret response failed %w", err) } if res.StatusCode != http.StatusOK { log.Printf("Non 200 StatusCode: %d\n", res.StatusCode) return nil, res.StatusCode, fmt.Errorf("got non-200 response for bulk get secret request from Dapr: %s", body) } resMap := map[string]map[string]string{} if len(body) == 0 { return nil, http.StatusOK, nil } // a key not found in Dapr will return 200 but an empty response. err = json.Unmarshal(body, &resMap) if err != nil { return nil, http.StatusInternalServerError, fmt.Errorf("could not parse response for bulk get secret request from Dapr: %w", err) } for key, value := range resMap { value := value output = append(output, daprSecret{ Key: key, Value: &value, Store: store, }) } return output, http.StatusOK, nil } // handles all APIs func handler(w http.ResponseWriter, r *http.Request) { log.Printf("Processing request for %s", r.URL.RequestURI()) // Retrieve request body contents var req requestResponse err := json.NewDecoder(r.Body).Decode(&req) if err != nil { log.Printf("Could not parse request body: %s", err.Error()) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(requestResponse{ Message: err.Error(), }) return } res := requestResponse{} uri := r.URL.RequestURI() var secrets []daprSecret var statusCode int res.StartTime = epoch() cmd := mux.Vars(r)["command"] switch cmd { case "bulk": // Only use req.Secrets for store name for bulk get // Only req.Secrets[0] is used for key secrets, statusCode, err = getBulk(req.Secrets) res.Secrets = secrets if statusCode != http.StatusOK { res.Message = err.Error() } case "get": secrets, statusCode, err = getAll(req.Secrets) res.Secrets = secrets if statusCode != http.StatusOK { res.Message = err.Error() } default: err = fmt.Errorf("invalid URI: %s", uri) statusCode = http.StatusBadRequest res.Message = err.Error() } res.EndTime = epoch() if statusCode != http.StatusOK { log.Printf("Error status code %v: %v", statusCode, res.Message) } w.Header().Set("Content-Type", "application/json") w.WriteHeader(statusCode) json.NewEncoder(w).Encode(res) } func createSecretURL(key, store string) (string, error) { url, err := url.Parse(fmt.Sprintf(secretURL, store, key)) if err != nil { return "", fmt.Errorf("could not parse %s: %s", secretURL, err.Error()) } return url.String(), nil } // epoch returns the current unix epoch timestamp func epoch() int { return int(time.Now().UnixMilli()) } // appRouter initializes restful api router func appRouter() http.Handler { router := mux.NewRouter().StrictSlash(true) // Log requests and their processing time router.Use(utils.LoggerMiddleware) router.HandleFunc("/", indexHandler).Methods("GET") router.HandleFunc("/test/{command}", handler).Methods("POST") router.Use(mux.CORSMethodMiddleware(router)) return router } func main() { log.Printf("Secret App - listening on http://localhost:%d", appPort) log.Printf("Secret endpoint - to be saved at %s", secretURL) utils.StartServer(appPort, appRouter, true, false) }
mikeee/dapr
tests/apps/secretapp/app.go
GO
mit
7,688
# In e2e test, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing e2e test. kind: Service apiVersion: v1 metadata: name: secretapp labels: testapp: secretapp spec: selector: testapp: secretapp ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer --- apiVersion: apps/v1 kind: Deployment metadata: name: secretapp labels: testapp: secretapp spec: replicas: 1 selector: matchLabels: testapp: secretapp template: metadata: labels: testapp: secretapp annotations: dapr.io/enabled: "true" dapr.io/app-id: "secretapp" dapr.io/app-port: "3000" spec: containers: - name: secretapp image: docker.io/YOUR_DOCKER_ALIAS/e2e-secretapp:dev ports: - containerPort: 3000 imagePullPolicy: Always
mikeee/dapr
tests/apps/secretapp/service.yaml
YAML
mit
965
../../../dapr/proto/common/v1/*.proto ../../../dapr/proto/runtime/v1/*.proto ../utils/*.go
mikeee/dapr
tests/apps/service_invocation/.cache-include
none
mit
90
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //nolint:forbidigo package main import ( "bytes" "context" "crypto/rand" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "io" "log" "net/http" "os" "strconv" "strings" "time" guuid "github.com/google/uuid" "github.com/gorilla/mux" "google.golang.org/grpc" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/types/known/anypb" commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/tests/apps/utils" ) var ( appPort = 3000 daprHTTPPort = 3500 daprGRPCPort = 50001 httpClient = utils.NewHTTPClient() daprClient runtimev1pb.DaprClient httpMethods []string pid string ) const ( jsonContentType = "application/json" ) func init() { p := os.Getenv("DAPR_HTTP_PORT") if p != "" && p != "0" { daprHTTPPort, _ = strconv.Atoi(p) } p = os.Getenv("DAPR_GRPC_PORT") if p != "" && p != "0" { daprGRPCPort, _ = strconv.Atoi(p) } p = os.Getenv("PORT") if p != "" && p != "0" { appPort, _ = strconv.Atoi(p) } } type testCommandRequest struct { RemoteApp string `json:"remoteApp,omitempty"` Method string `json:"method,omitempty"` RemoteAppTracing string `json:"remoteAppTracing"` Message *string `json:"message,omitempty"` } type testCommandRequestExternal struct { testCommandRequest `json:",inline"` ExternalIP string `json:"externalIP,omitempty"` } type appResponse struct { Message string `json:"message,omitempty"` } type negativeTestResult struct { MainCallSuccessful bool `json:"callSuccessful"` RawBody []byte `json:"rawBody"` RawError string `json:"rawError"` Results []individualTestResult `json:"results"` } type individualTestResult struct { TestCase string `json:"case"` CallSuccessful bool `json:"callSuccessful"` } type httpTestMethods struct { Verb string Callback string SendBody bool ExpectBody bool } var testMethods = []httpTestMethods{ { Verb: "GET", Callback: "gethandler", SendBody: false, ExpectBody: true, }, { Verb: "HEAD", Callback: "headhandler", SendBody: false, ExpectBody: false, }, { Verb: "POST", Callback: "posthandler", SendBody: true, ExpectBody: true, }, { Verb: "PUT", Callback: "puthandler", SendBody: true, ExpectBody: true, }, { Verb: "DELETE", Callback: "deletehandler", SendBody: true, ExpectBody: true, }, // Go's net/http library does not support sending requests with the CONNECT method /*{ Verb: "CONNECT", Callback: "connecthandler", SendBody: true, ExpectBody: true, },*/ { Verb: "OPTIONS", Callback: "optionshandler", SendBody: true, ExpectBody: true, }, { Verb: "TRACE", Callback: "tracehandler", SendBody: true, ExpectBody: true, }, { Verb: "PATCH", Callback: "patchhandler", SendBody: true, ExpectBody: true, }, } // indexHandler is the handler for root path func indexHandler(w http.ResponseWriter, r *http.Request) { log.Println("indexHandler is called") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{Message: "OK"}) } func pidHandler(w http.ResponseWriter, r *http.Request) { log.Println("pidHandler is called") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{Message: pid}) } func singlehopHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) response := "singlehop is called" json.NewEncoder(w).Encode(appResponse{Message: response}) } func multihopHandler(w http.ResponseWriter, r *http.Request) { response, statusCode, err := invokeService("serviceinvocation-callee-1", "singlehop") if err != nil { onHTTPCallFailed(w, statusCode, err) return } w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(response) } // Handles a request with a JSON body. Extracts s string from the input json and returns in it an appResponse. func withBodyHandler(w http.ResponseWriter, r *http.Request) { log.Printf("withBodyHandler called. HTTP Verb: %s\n", r.Method) body, err := io.ReadAll(r.Body) if err != nil { onBadRequest(w, err) return } if len(body) > 100 { log.Printf("withBodyHandler body (first 100 bytes): %s\n", string(body[:100])) } else { log.Printf("withBodyHandler body: %s\n", string(body)) } var s string err = json.Unmarshal(body, &s) if err != nil { onDeserializationFailed(w, err) return } w.Header().Add("x-dapr-tests-request-method", r.Method) w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{Message: s}) } // Handles a request with no body. Returns an appResponse with appResponse.Message "ok", which caller validates. func noBodyHandler(w http.ResponseWriter, r *http.Request) { fmt.Printf("noBodyHandler called. HTTP Verb: %s \n", r.Method) w.Header().Add("x-dapr-tests-request-method", r.Method) logAndSetResponse(w, http.StatusOK, "ok") } func opAllowHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) response := "opAllow is called" json.NewEncoder(w).Encode(appResponse{Message: response}) } func opDenyHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) response := "opDeny is called" json.NewEncoder(w).Encode(appResponse{Message: response}) } func opRedirectHandler(w http.ResponseWriter, r *http.Request) { w.Header().Add("Location", "http://localhost:3500/v1.0/invoke/serviceinvocation-callee-1/method/opAllow") w.WriteHeader(http.StatusTemporaryRedirect) response := "opRedirect is called" json.NewEncoder(w).Encode(appResponse{Message: response}) } func testHandler(w http.ResponseWriter, r *http.Request) { log.Println("Enter testHandler") var commandBody testCommandRequest err := json.NewDecoder(r.Body).Decode(&commandBody) if err != nil { onBadRequest(w, err) return } log.Printf(" testHandler invoking %s with method %s\n", commandBody.RemoteApp, commandBody.Method) response, statusCode, err := invokeService(commandBody.RemoteApp, commandBody.Method) if err != nil { w.WriteHeader(statusCode) json.NewEncoder(w).Encode(appResponse{ Message: err.Error(), }) return } w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(response) } func invokeService(remoteApp, method string) (appResponse, int, error) { return invokeServiceWithBody(remoteApp, method, nil) } func invokeServiceWithBody(remoteApp, method string, data []byte) (appResponse, int, error) { resp, err := invokeServiceWithBodyHeader(remoteApp, method, data, nil) var statusCode int if resp != nil { statusCode = resp.StatusCode } if err != nil { return appResponse{}, statusCode, err } defer resp.Body.Close() var appResp appResponse err = json.NewDecoder(resp.Body).Decode(&appResp) if err != nil { return appResponse{}, statusCode, err } // invokeServiceWithBodyHeader uses http client.Do method which // returns success for everything except 2xx error codes. Check // the status code to extract non 2xx errors. if statusCode != http.StatusOK { return appResponse{}, statusCode, errors.New(appResp.Message) } return appResp, statusCode, nil } func invokeServiceWithBodyHeader(remoteApp, method string, data []byte, headers http.Header) (*http.Response, error) { url := fmt.Sprintf("http://localhost:%s/v1.0/invoke/%s/method/%s", strconv.Itoa(daprHTTPPort), remoteApp, method) log.Printf("invoke url is %s", url) var t io.Reader if data != nil { t = bytes.NewReader(data) } /* #nosec */ req, _ := http.NewRequest(http.MethodPost, url, t) for k, v := range headers { req.Header[k] = v } req.Header.Add("Content-Type", jsonContentType) return httpClient.Do(req) } func invokeServiceWithDaprAppIDHeader(remoteApp, method string, data []byte, headers http.Header) (*http.Response, error) { url := fmt.Sprintf("http://localhost:%s/%s", strconv.Itoa(daprHTTPPort), method) fmt.Printf("invoke url is %s\n", url) var t io.Reader if data != nil { t = bytes.NewReader(data) } /* #nosec */ req, _ := http.NewRequest(http.MethodPost, url, t) req.Header.Set("dapr-app-id", remoteApp) for k, v := range headers { req.Header[k] = v } req.Header.Set("Content-Type", jsonContentType) return httpClient.Do(req) } func constructRequest(id, method, httpVerb string, body []byte) *runtimev1pb.InvokeServiceRequest { msg := &commonv1pb.InvokeRequest{Method: method} msg.ContentType = jsonContentType msg.Data = &anypb.Any{Value: body} if httpVerb != "" { msg.HttpExtension = &commonv1pb.HTTPExtension{ Verb: commonv1pb.HTTPExtension_Verb(commonv1pb.HTTPExtension_Verb_value[httpVerb]), //nolint:nosnakecase } } return &runtimev1pb.InvokeServiceRequest{ Id: id, Message: msg, } } // appRouter initializes restful api router func appRouter() http.Handler { router := mux.NewRouter().StrictSlash(true).UseEncodedPath() // Log requests and their processing time router.Use(utils.LoggerMiddleware) router.HandleFunc("/", indexHandler).Methods("GET") router.HandleFunc("/pid", pidHandler).Methods("POST") router.HandleFunc("/singlehop", singlehopHandler).Methods("POST") router.HandleFunc("/multihop", multihopHandler).Methods("POST") router.HandleFunc("/opAllow", opAllowHandler).Methods("POST") router.HandleFunc("/opDeny", opDenyHandler).Methods("POST") router.PathPrefix("/opRedirect").Handler(http.HandlerFunc(opRedirectHandler)).Methods("POST") router.HandleFunc("/tests/invoke_test", testHandler) // these are called through dapr service invocation for _, test := range testMethods { if test.SendBody { router.HandleFunc("/"+test.Callback, withBodyHandler).Methods(test.Verb) } else { router.HandleFunc("/"+test.Callback, noBodyHandler).Methods(test.Verb) } } // called through dapr service invocation and meant to cause error router.HandleFunc("/timeouterror", timeoutServiceCall).Methods("POST") router.HandleFunc("/parseerror", parseErrorServiceCall).Methods("POST") router.HandleFunc("/largedatahttp", largeDataErrorServiceCallHTTP).Methods("POST") router.HandleFunc("/largedatagrpc", largeDataErrorServiceCallGrpc).Methods("POST") // called by test to run some cases - these will themselves make calls router.HandleFunc("/httptohttptest", httpTohttpTest).Methods("POST") router.HandleFunc("/grpctogrpctest", grpcToGrpcTest).Methods("POST") router.HandleFunc("/httptogrpctest", httpToGrpcTest).Methods("POST") router.HandleFunc("/grpctohttptest", grpcToHTTPTest).Methods("POST") router.HandleFunc("/badservicecalltesthttp", badServiceCallTestHTTP).Methods("POST") router.HandleFunc("/badservicecalltestgrpc", badServiceCallTestGrpc).Methods("POST") // called by Dapr invocation to ensure path separators are correctly // normalized, but not path segment contents. router.HandleFunc("/foo/%2E", echoPathHandler).Methods("GET", "POST") router.HandleFunc("/foo/%2Fbbb%2F%2E", echoPathHandler).Methods("GET", "POST") router.HandleFunc("/foo/%2Fb/bb%2F%2E", echoPathHandler).Methods("GET", "POST") // service invocation v1 e2e tests router.HandleFunc("/tests/dapr_id_httptohttptest", testDaprIDRequestHTTPToHTTP).Methods("POST") router.HandleFunc("/tests/v1_httptohttptest", testV1RequestHTTPToHTTP).Methods("POST") router.HandleFunc("/tests/v1_httptogrpctest", testV1RequestHTTPToGRPC).Methods("POST") router.HandleFunc("/tests/v1_grpctogrpctest", testV1RequestGRPCToGRPC).Methods("POST") router.HandleFunc("/tests/v1_grpctohttptest", testV1RequestGRPCToHTTP).Methods("POST") router.HandleFunc("/retrieve_request_object", retrieveRequestObject).Methods("POST") // Load balancing test router.HandleFunc("/tests/loadbalancing", testLoadBalancing).Methods("POST") // test path for Dapr method invocation decode router.PathPrefix("/path/").HandlerFunc(testPathHTTPCall) // service invocation to external HTTPEndpoint resources + through overwriting the URL router.HandleFunc("/httptohttptest_external", httpTohttpTestExternal).Methods("POST") router.HandleFunc("/tests/v1_httptohttptest_external", testV1RequestHTTPToHTTPExternal).Methods("POST") // headers router.Use(mux.CORSMethodMiddleware(router)) return router } func retrieveRequestObject(w http.ResponseWriter, r *http.Request) { headers := map[string][]string{} for k, vals := range r.Header { headers[k] = vals log.Printf("headers: %s %q", k, vals) } serializedHeaders, _ := json.Marshal(headers) w.Header().Set("Content-Type", jsonContentType) w.Header().Set("DaprTest-Response-1", "DaprTest-Response-Value-1") w.Header().Set("DaprTest-Response-2", "DaprTest-Response-Value-2") w.Header().Add("DaprTest-Response-Multi", "DaprTest-Response-Multi-1") w.Header().Add("DaprTest-Response-Multi", "DaprTest-Response-Multi-2") if val, ok := headers["Daprtest-Traceid"]; ok { // val[0] is client app given trace id w.Header().Set("traceparent", val[0]) } w.WriteHeader(http.StatusOK) w.Write(serializedHeaders) } func requestHTTPToHTTP(w http.ResponseWriter, r *http.Request, send func(remoteApp, method string, data []byte, headers http.Header) (*http.Response, error)) { var commandBody testCommandRequest err := json.NewDecoder(r.Body).Decode(&commandBody) if err != nil { onBadRequest(w, err) return } log.Printf("httpTohttpTest - target app: %s\n", commandBody.RemoteApp) daprAddress := fmt.Sprintf("localhost:%d", daprHTTPPort) log.Printf("dapr address is %s\n", daprAddress) testMessage := guuid.New().String() b, err := json.Marshal(testMessage) if err != nil { log.Printf("marshal had error %s\n", err) onSerializationFailed(w, err) return } log.Printf("httpTohttpTest calling with message %s\n", string(b)) headers := map[string][]string{ "DaprTest-Request-1": {"DaprValue1"}, "DaprTest-Request-2": {"DaprValue2"}, "DaprTest-Multi": {"M'illumino", "d'immenso"}, } tracing, _ := strconv.ParseBool(commandBody.RemoteAppTracing) if tracing { headers["Daprtest-Traceid"] = []string{"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"} } resp, err := send(commandBody.RemoteApp, "retrieve_request_object", b, headers) if err != nil { log.Printf("response had error %s\n", err) onHTTPCallFailed(w, 0, err) return } respHeaders := map[string][]string{} for k, vals := range resp.Header { respHeaders[k] = vals } respHeaderString, _ := json.Marshal(respHeaders) reqHeadersString, err := io.ReadAll(resp.Body) resp.Body.Close() if err != nil { onBadRequest(w, err) return } respMessage := map[string]string{ "request": string(reqHeadersString), "response": string(respHeaderString), } respBody, err := json.Marshal(respMessage) if err != nil { onBadRequest(w, err) return } log.Printf("response was %s", respBody) logAndSetResponse(w, http.StatusOK, string(respBody)) } func requestHTTPToHTTPExternal(w http.ResponseWriter, r *http.Request, send func(remoteApp, method string, data []byte, headers http.Header) (*http.Response, error)) { var commandBody testCommandRequestExternal err := json.NewDecoder(r.Body).Decode(&commandBody) if err != nil { onBadRequest(w, err) return } log.Printf("httpTohttpTestExternal - target app: %s\n", commandBody.RemoteApp) daprAddress := fmt.Sprintf("localhost:%d", daprHTTPPort) log.Printf("dapr address is %s\n", daprAddress) testMessage := guuid.New().String() b, err := json.Marshal(testMessage) if err != nil { log.Printf("marshal had error %s\n", err) onSerializationFailed(w, err) return } log.Printf("httpTohttpTest calling with message %s\n", string(b)) headers := map[string][]string{ "DaprTest-Request-1": {"DaprValue1"}, "DaprTest-Request-2": {"DaprValue2"}, "DaprTest-Multi": {"M'illumino", "d'immenso"}, } tracing, _ := strconv.ParseBool(commandBody.RemoteAppTracing) if tracing { headers["Daprtest-Traceid"] = []string{"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"} } // case of overwritten URL var remoteApp string if commandBody.ExternalIP == "" { remoteApp = commandBody.RemoteApp } else { remoteApp = sanitizeHTTPURL(commandBody.ExternalIP) } resp, err := send(remoteApp, "retrieve_request_object", b, headers) if err != nil { log.Printf("response had error %s\n", err) onHTTPCallFailed(w, 0, err) return } respHeaders := map[string][]string{} for k, vals := range resp.Header { respHeaders[k] = vals } respHeaderString, _ := json.Marshal(respHeaders) reqHeadersString, err := io.ReadAll(resp.Body) resp.Body.Close() if err != nil { onBadRequest(w, err) return } respMessage := map[string]string{ "request": string(reqHeadersString), "response": string(respHeaderString), } respBody, err := json.Marshal(respMessage) if err != nil { onBadRequest(w, err) return } log.Printf("response was %s\n", respBody) logAndSetResponse(w, http.StatusOK, string(respBody)) } func testLoadBalancing(w http.ResponseWriter, r *http.Request) { log.Println("Enter load balancing test") res, err := invokeServiceWithBodyHeader("serviceinvocation-callee-2", "pid", nil, nil) if err != nil { onBadRequest(w, err) return } defer res.Body.Close() w.WriteHeader(res.StatusCode) log.Print("Response: ") io.Copy(io.MultiWriter(w, os.Stdout), res.Body) } // testDaprIDRequestHTTPToHTTP calls from http caller to http callee without requiring the caller to use Dapr style URL. func testDaprIDRequestHTTPToHTTP(w http.ResponseWriter, r *http.Request) { log.Println("Enter service invocation with dapr-app-id header and shorter URL - http -> http") requestHTTPToHTTP(w, r, invokeServiceWithDaprAppIDHeader) } // testV1RequestHTTPToHTTP calls from http caller to http callee func testV1RequestHTTPToHTTP(w http.ResponseWriter, r *http.Request) { log.Println("Enter service invocation v1 - http -> http") requestHTTPToHTTP(w, r, invokeServiceWithBodyHeader) } // testV1RequestHTTPToHTTPExternal calls from http caller to http callee func testV1RequestHTTPToHTTPExternal(w http.ResponseWriter, r *http.Request) { log.Println("Enter service invocation external v1 - http -> http") requestHTTPToHTTPExternal(w, r, invokeServiceWithBodyHeader) } // testV1RequestHTTPToGRPC calls from http caller to grpc callee func testV1RequestHTTPToGRPC(w http.ResponseWriter, r *http.Request) { log.Println("Enter service invocation v1 - http -> grpc") var commandBody testCommandRequest err := json.NewDecoder(r.Body).Decode(&commandBody) if err != nil { onBadRequest(w, err) return } log.Printf("httpTogrpcTest - target app: %s\n", commandBody.RemoteApp) daprAddress := fmt.Sprintf("localhost:%d", daprHTTPPort) log.Printf("dapr address is %s\n", daprAddress) testMessage := guuid.New().String() b, err := json.Marshal(testMessage) if err != nil { log.Printf("marshal had error %s\n", err) onSerializationFailed(w, err) return } log.Printf("httpTogrpcTest calling with message %s\n", string(b)) headers := map[string][]string{ "DaprTest-Request-1": {"DaprValue1"}, "DaprTest-Request-2": {"DaprValue2"}, "DaprTest-Multi": {"M'illumino", "d'immenso"}, } tracing, _ := strconv.ParseBool(commandBody.RemoteAppTracing) if tracing { headers["Daprtest-Traceid"] = []string{"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"} } resp, err := invokeServiceWithBodyHeader(commandBody.RemoteApp, "retrieve_request_object", b, headers) if err != nil { log.Printf("response had error %s\n", err) onHTTPCallFailed(w, 0, err) return } respHeaders := map[string][]string{} for k, vals := range resp.Header { respHeaders[k] = vals } respHeaderString, _ := json.Marshal(respHeaders) reqHeadersString, err := io.ReadAll(resp.Body) resp.Body.Close() if err != nil { onBadRequest(w, err) return } respMessage := map[string]string{ "request": string(reqHeadersString), "response": string(respHeaderString), } respBody, err := json.Marshal(respMessage) if err != nil { onBadRequest(w, err) return } log.Printf("response was %s\n", respBody) logAndSetResponse(w, http.StatusOK, string(respBody)) } // testV1RequestGRPCToGRPC calls from http caller to grpc callee func testV1RequestGRPCToGRPC(w http.ResponseWriter, r *http.Request) { log.Println("Enter service invocation v1 - grpc -> grpc") var commandBody testCommandRequest err := json.NewDecoder(r.Body).Decode(&commandBody) if err != nil { onBadRequest(w, err) return } log.Printf("gRPCTogRPCTest - target app: %s\n", commandBody.RemoteApp) // Create the client tracing, _ := strconv.ParseBool(commandBody.RemoteAppTracing) ctx := r.Context() md, ok := metadata.FromOutgoingContext(ctx) if !ok { md = metadata.MD{} } md.Append("DaprTest-Request-1", "DaprValue1") md.Append("DaprTest-Request-2", "DaprValue2") md.Append("DaprTest-Multi", "M'illumino", "d'immenso") if tracing { md.Append("Daprtest-Traceid", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01") } ctx = metadata.NewOutgoingContext(ctx, md) req := &runtimev1pb.InvokeServiceRequest{ Id: commandBody.RemoteApp, Message: &commonv1pb.InvokeRequest{ Method: "retrieve_request_object", Data: &anypb.Any{Value: []byte("GRPCToGRPCTest")}, ContentType: "text/plain; utf-8", }, } var header, trailer metadata.MD resp, err := daprClient.InvokeService( ctx, req, grpc.Header(&header), // will retrieve header grpc.Trailer(&trailer), // will retrieve trailer ) if err != nil { log.Printf("response had error %s\n", err) onHTTPCallFailed(w, 0, err) return } reqHeadersString := resp.GetData().GetValue() respHeaders := map[string][]string{} for k, vals := range header { var listValue []string if strings.HasSuffix(k, "-bin") { for _, val := range vals { listValue = append(listValue, base64.StdEncoding.EncodeToString([]byte(val))) } } else { listValue = vals } respHeaders[k] = listValue } respHeaderString, _ := json.Marshal(respHeaders) respTrailers := map[string][]string{} for k, vals := range trailer { respTrailers[k] = vals } respTrailerString, _ := json.Marshal(respTrailers) respMessage := map[string]string{ "request": string(reqHeadersString), "response": string(respHeaderString), "trailers": string(respTrailerString), } respBody, err := json.Marshal(respMessage) if err != nil { onBadRequest(w, err) return } log.Printf("response was %s\n", respBody) logAndSetResponse(w, http.StatusOK, string(respBody)) } // testV1RequestGRPCToHTTP calls from grpc caller to http callee func testV1RequestGRPCToHTTP(w http.ResponseWriter, r *http.Request) { log.Println("Enter service invocation v1 - grpc -> http") var commandBody testCommandRequest err := json.NewDecoder(r.Body).Decode(&commandBody) if err != nil { onBadRequest(w, err) return } log.Printf("grpcToHTTPTest - target app: %s\n", commandBody.RemoteApp) tracing, _ := strconv.ParseBool(commandBody.RemoteAppTracing) ctx := r.Context() md, ok := metadata.FromOutgoingContext(ctx) if !ok { md = metadata.MD{} } md.Append("DaprTest-Request-1", "DaprValue1") md.Append("DaprTest-Request-2", "DaprValue2") md.Append("DaprTest-Multi", "M'illumino", "d'immenso") if tracing { md.Append("Daprtest-Traceid", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01") } ctx = metadata.NewOutgoingContext(ctx, md) req := &runtimev1pb.InvokeServiceRequest{ Id: commandBody.RemoteApp, Message: &commonv1pb.InvokeRequest{ Method: "retrieve_request_object", Data: &anypb.Any{Value: []byte("GRPCToHTTPTest")}, ContentType: "text/plain; utf-8", HttpExtension: &commonv1pb.HTTPExtension{ Verb: commonv1pb.HTTPExtension_POST, //nolint:nosnakecase }, }, } var header metadata.MD resp, err := daprClient.InvokeService( ctx, req, grpc.Header(&header), // will retrieve header ) if err != nil { log.Printf("response had error %s\n", err) onHTTPCallFailed(w, 0, err) return } reqHeadersString := resp.GetData().GetValue() respHeaders := map[string][]string{} for k, vals := range header { var listValue []string if strings.HasSuffix(k, "-bin") { for _, val := range vals { listValue = append(listValue, base64.StdEncoding.EncodeToString([]byte(val))) } } else { listValue = vals } respHeaders[k] = listValue } respHeaderString, _ := json.Marshal(respHeaders) respMessage := map[string]string{ "request": string(reqHeadersString), "response": string(respHeaderString), } respBody, err := json.Marshal(respMessage) if err != nil { onBadRequest(w, err) return } log.Printf("response was %s\n", respBody) logAndSetResponse(w, http.StatusOK, string(respBody)) } // Performs calls from grpc client to grpc server. It sends a random string to the other app // and expects the response to contain the same string inside an appResponse. func grpcToGrpcTest(w http.ResponseWriter, r *http.Request) { log.Println("Enter grpcToGrpcTest") var commandBody testCommandRequest err := json.NewDecoder(r.Body).Decode(&commandBody) if err != nil { onBadRequest(w, err) return } log.Printf("%s - target app: %s\n", commandBody.Method, commandBody.RemoteApp) testMessage := guuid.New().String() b, err := json.Marshal(testMessage) if err != nil { log.Printf("marshal had error %s\n", err) onSerializationFailed(w, err) return } log.Printf("%s calling with message %s\n", commandBody.Method, string(b)) req := constructRequest(commandBody.RemoteApp, commandBody.Method, "", b) resp, err := daprClient.InvokeService(r.Context(), req) if err != nil { logAndSetResponse(w, http.StatusInternalServerError, "grpc call failed with "+err.Error()) return } body := resp.GetData().GetValue() log.Printf("resp was %s\n", string(body)) var responseMessage appResponse err = json.Unmarshal(body, &responseMessage) if err != nil { onDeserializationFailed(w, err) return } // validate response ends with "[testMessage] | [httpMethod]" if testMessage != responseMessage.Message { errorMessage := "Expected " + testMessage + " received " + responseMessage.Message logAndSetResponse(w, http.StatusInternalServerError, errorMessage) return } // caller of this method doesn't inspect response, it only looks for status logAndSetResponse(w, http.StatusOK, "success") } // Performs calls from http client to grpc server. It sends a random string to the other app // and expects the response to contain the same string inside an appResponse. func httpToGrpcTest(w http.ResponseWriter, r *http.Request) { log.Println("Enter httpToGrpcTest") var commandBody testCommandRequest err := json.NewDecoder(r.Body).Decode(&commandBody) if err != nil { onBadRequest(w, err) return } log.Printf("httpToGrpcTest - target app: %s\n", commandBody.RemoteApp) daprAddress := fmt.Sprintf("localhost:%d", daprHTTPPort) log.Printf("dapr address is %s\n", daprAddress) testMessage := guuid.New().String() b, err := json.Marshal(testMessage) if err != nil { log.Printf("marshal had error %s\n", err) onSerializationFailed(w, err) return } log.Printf("httpToGrpcTest calling with message %s\n", string(b)) resp, statusCode, err := invokeServiceWithBody(commandBody.RemoteApp, "httpToGrpcTest", b) if err != nil { log.Printf("response had error %s\n", err) onHTTPCallFailed(w, statusCode, err) return } log.Printf("response was %s\n", resp.Message) logAndSetResponse(w, http.StatusOK, "success") } // Performs calls from http client to http server. It sends a random string to the other app // and expects the response to contain the same string inside an appResponse. // It calls methods with all 4 http methods (verbs) func httpTohttpTest(w http.ResponseWriter, r *http.Request) { log.Println("Enter httpTohttpTest") defer r.Body.Close() var commandBody testCommandRequest err := json.NewDecoder(r.Body).Decode(&commandBody) if err != nil { onBadRequest(w, err) return } log.Printf("httpTohttpTest - target app: %s\n", commandBody.RemoteApp) daprAddress := fmt.Sprintf("localhost:%d", daprHTTPPort) log.Printf("dapr address is %s\n", daprAddress) testMessage := guuid.New().String() log.Printf("httpTohttpTest calling with message %s\n", testMessage) for _, test := range testMethods { testMessage := "ok" if test.SendBody { if commandBody.Message != nil { testMessage = *commandBody.Message } else { testMessage = guuid.New().String() } } url := fmt.Sprintf( "http://localhost:%s/v1.0/invoke/%s/method/%s", strconv.Itoa(daprHTTPPort), commandBody.RemoteApp, test.Callback) log.Printf("%s invoke url is %s\n", test.Verb, url) var b []byte if test.SendBody { var err error b, err = json.Marshal(testMessage) if err != nil { log.Printf("marshal had error %s\n", err) onSerializationFailed(w, err) return } log.Printf("sending body: %s\n", string(b)) } resp, err := httpWrapper(test.Verb, url, b) if err != nil { log.Printf("response had error %s\n", err) onHTTPCallFailed(w, 0, err) return } if test.ExpectBody && testMessage != resp.Message { errorMessage := "Expected " + testMessage + " received " + resp.Message logAndSetResponse(w, http.StatusInternalServerError, errorMessage) return } log.Printf("httpTohttpTest - %s test successful\n", test.Verb) } logAndSetResponse(w, http.StatusOK, "success") } // Performs calls from http client to http server. // It sends a random string to the non-Daprized app, // and expects the response to contain the same string inside an appResponse. func httpTohttpTestExternal(w http.ResponseWriter, r *http.Request) { log.Println("Enter httpTohttpTestExternal") defer r.Body.Close() var commandBody testCommandRequestExternal err := json.NewDecoder(r.Body).Decode(&commandBody) if err != nil { onBadRequest(w, err) return } daprAddress := fmt.Sprintf("localhost:%d", daprHTTPPort) log.Printf("dapr address is %s", daprAddress) log.Printf("httpTohttpTestExternal calling with method %s", commandBody.Method) for _, test := range testMethods { testMessage := "success" if test.SendBody { if commandBody.Message != nil { testMessage = *commandBody.Message } else { testMessage = guuid.New().String() } } // case of overwritten URL var url string if commandBody.ExternalIP == "" { url = fmt.Sprintf( "http://localhost:%s/v1.0/invoke/%s/method/%s", strconv.Itoa(daprHTTPPort), commandBody.RemoteApp, commandBody.Method) } else { url = fmt.Sprintf( "http://localhost:%s/v1.0/invoke/%s/method/%s", strconv.Itoa(daprHTTPPort), sanitizeHTTPURL(commandBody.ExternalIP), commandBody.Method) } log.Printf("%s invoke url is %s", test.Verb, url) var b []byte if test.SendBody { var err error b, err = json.Marshal(testMessage) if err != nil { log.Printf("marshal had error %s", err) onSerializationFailed(w, err) return } log.Printf("sending body: %s", string(b)) } resp, err := httpWrapper(test.Verb, url, b) if err != nil { log.Printf("response had error %s", err) onHTTPCallFailed(w, 0, err) return } if test.ExpectBody && testMessage != resp.Message { errorMessage := "Expected " + testMessage + " received " + resp.Message logAndSetResponse(w, http.StatusInternalServerError, errorMessage) return } log.Printf("httpTohttpTestExternal - %s test successful", test.Verb) } logAndSetResponse(w, http.StatusOK, "success") } // data should be serialized by caller func httpWrapper(httpMethod string, url string, data []byte) (appResponse, error) { var appResp appResponse var requestBody io.Reader if len(data) > 0 { requestBody = bytes.NewReader(data) } req, err := http.NewRequest(httpMethod, sanitizeHTTPURL(url), requestBody) if err != nil { return appResp, err } res, err := httpClient.Do(req) if res != nil { log.Printf("res in httpWrapper() %v with status code %d", res, res.StatusCode) } log.Printf("res error in httpWrapper() %v", err) if err != nil { return appResp, err } defer func() { // Drain before closing _, _ = io.Copy(io.Discard, res.Body) _ = res.Body.Close() }() actualVerb := res.Header.Get("x-dapr-tests-request-method") if httpMethod != actualVerb { return appResp, fmt.Errorf("Expected HTTP verb: %s actual %s", httpMethod, actualVerb) //nolint:stylecheck } body, err := io.ReadAll(res.Body) log.Printf("response body: %s\n", string(body)) if err != nil { return appResp, err } if len(body) > 0 { err = json.Unmarshal(body, &appResp) if err != nil { return appResp, err } } return appResp, nil } // Performs calls from grpc client to http server. It sends a random string to the other app // and expects the response to contain the same string inside an appResponse. // It uses all 4 http methods (verbs) in metadata to invoke the proper http method. func grpcToHTTPTest(w http.ResponseWriter, r *http.Request) { fmt.Println("Enter grpcToHTTPTest") var commandBody testCommandRequest err := json.NewDecoder(r.Body).Decode(&commandBody) if err != nil { onBadRequest(w, err) return } fmt.Printf("grpcToHTTPTest - target app: %s\n", commandBody.RemoteApp) var b []byte for _, v := range httpMethods { testMessage := guuid.New().String() b, err = json.Marshal(testMessage) if err != nil { fmt.Printf("marshal had error %s\n", err) onSerializationFailed(w, err) return } fmt.Printf("grpcToHTTPTest calling with verb %s, message %s\n", v, testMessage) req := constructRequest(commandBody.RemoteApp, "posthandler", v, b) var resp *commonv1pb.InvokeResponse var err error switch v { case "POST": req.Message.Method = "posthandler" case "GET": req.Message.Method = "gethandler" case "PUT": req.Message.Method = "puthandler" case "DELETE": req.Message.Method = "deletehandler" default: fmt.Println("Unexpected option") if err != nil { logAndSetResponse(w, http.StatusInternalServerError, "unexpected option "+v) return } } resp, err = daprClient.InvokeService(r.Context(), req) if err != nil { logAndSetResponse(w, http.StatusInternalServerError, "error returned from grpc client") return } body := resp.GetData().GetValue() fmt.Printf("resp was %s\n", string(body)) // var responseMessage string var appResp appResponse err = json.Unmarshal(body, &appResp) if err != nil { onDeserializationFailed(w, err) return } // We don't send a body with GET. The receiving method just // returns the body, so skip. if v == "GET" { continue } if testMessage != appResp.Message { errorMessage := "Expected " + testMessage + " received " + appResp.Message logAndSetResponse(w, http.StatusInternalServerError, errorMessage) return } } logAndSetResponse(w, http.StatusOK, "success") } func badServiceCallTestHTTP(w http.ResponseWriter, r *http.Request) { fmt.Println("Enter badServiceCallTestHTTP") var commandBody testCommandRequest err := json.NewDecoder(r.Body).Decode(&commandBody) if err != nil { onBadRequest(w, err) return } fmt.Printf("badServiceCallTestHTTP - target app: %s\n", commandBody.RemoteApp) daprAddress := fmt.Sprintf("localhost:%s", strconv.Itoa(daprHTTPPort)) fmt.Printf("dapr address is %s\n", daprAddress) var testMessage struct { Data string `json:"data"` } testMessage.Data = guuid.New().String() fmt.Printf("badServiceCallTestHTTP calling with message %v\n", testMessage) // post url := fmt.Sprintf( "http://localhost:%s/v1.0/invoke/%s/method/%s", strconv.Itoa(daprHTTPPort), commandBody.RemoteApp, commandBody.Method, ) fmt.Printf("%s invoke url is %s\n", commandBody.Method, url) b, err := json.Marshal(testMessage) if err != nil { fmt.Printf("marshal had error %s\n", err) onSerializationFailed(w, err) return } fmt.Printf("%s method body is %s\n", commandBody.Method, string(b)) var testResponse negativeTestResult prevTimeout := httpClient.Timeout // Explicitly set the timeout to force an error if commandBody.Method == "timeouterror" { httpClient.Timeout = 5 * time.Second } resp, err := httpClient.Post(sanitizeHTTPURL(url), jsonContentType, bytes.NewReader(b)) if commandBody.Method == "timeouterror" { httpClient.Timeout = prevTimeout } testResponse.MainCallSuccessful = err == nil && resp.StatusCode == 200 if resp != nil && resp.Body != nil { fmt.Printf("badServiceCallTestHTTP - Response Code: %d\n", resp.StatusCode) w.WriteHeader(resp.StatusCode) rawBody, _ := io.ReadAll(resp.Body) resp.Body.Close() testResponse.RawBody = rawBody json.NewDecoder(strings.NewReader(string(rawBody))).Decode(&testResponse.Results) } if err != nil { testResponse.RawError = err.Error() if resp == nil { w.WriteHeader(http.StatusInternalServerError) } } json.NewEncoder(w).Encode(testResponse) } // echoPathHandler is a test endpoint that returns the path of the request as // is. func echoPathHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte(r.URL.EscapedPath())) w.WriteHeader(http.StatusOK) } func badServiceCallTestGrpc(w http.ResponseWriter, r *http.Request) { fmt.Println("Enter badServiceCallTestGrpc") var commandBody testCommandRequest err := json.NewDecoder(r.Body).Decode(&commandBody) if err != nil { onBadRequest(w, err) return } fmt.Printf("badServiceCallTestGrpc - target app: %s\n", commandBody.RemoteApp) timeoutDuration := 30 * time.Second // Shorten the timeout if we want to force the error if commandBody.Method == "timeouterror" { timeoutDuration = 5 * time.Second } ctx, cancel := context.WithTimeout(r.Context(), timeoutDuration) defer cancel() var testMessage struct { Data string `json:"data"` } testMessage.Data = guuid.New().String() fmt.Printf("badServiceCallTestGrpc calling with message %v\n", testMessage) b, _ := json.Marshal(testMessage) req := constructRequest(commandBody.RemoteApp, commandBody.Method, "POST", b) var testResponse negativeTestResult resp, err := daprClient.InvokeService(ctx, req) testResponse.MainCallSuccessful = true if err != nil { testResponse.MainCallSuccessful = false testResponse.RawError = err.Error() w.WriteHeader(http.StatusInternalServerError) } if resp != nil && resp.GetData() != nil { rawBody := resp.GetData().GetValue() testResponse.RawBody = rawBody json.NewDecoder(strings.NewReader(string(rawBody))).Decode(&testResponse.Results) } json.NewEncoder(w).Encode(testResponse) } func timeoutServiceCall(w http.ResponseWriter, r *http.Request) { fmt.Println("Entering timeoutServiceCall") // Timeout for the client is 5 seconds, we just need to wait longer than that. time.Sleep(10 * time.Second) logAndSetResponse(w, 200, "Client waited longer than it should have.") } func parseErrorServiceCall(w http.ResponseWriter, r *http.Request) { fmt.Println("Entering parseErrorServiceCall") var data struct { Data int `json:"data"` } err := json.NewDecoder(r.Body).Decode(&data) if err != nil { onSerializationFailed(w, err) return } // We shouldn't get here. logAndSetResponse(w, 200, fmt.Sprintf("Request should have failed to parse: %v", data)) } func largeDataErrorServiceCallHTTP(w http.ResponseWriter, r *http.Request) { largeDataErrorServiceCall(w, r, true) } func largeDataErrorServiceCallGrpc(w http.ResponseWriter, r *http.Request) { largeDataErrorServiceCall(w, r, false) } func largeDataErrorServiceCall(w http.ResponseWriter, r *http.Request, isHTTP bool) { fmt.Println("Entering largeDataErrorServiceCall") // post url := fmt.Sprintf( "http://localhost:%s/v1.0/invoke/serviceinvocation-callee-0/method/posthandler", strconv.Itoa(daprHTTPPort)) testSizes := []struct { size int name string }{ { size: 1024 * 1024, name: "1MB", }, { size: 1024*1024*3 - 454, name: "4MB", }, { size: 1024*1024*3 + 10, name: "4MB+", }, { size: 1024 * 1024 * 8, name: "8MB", }, } results := make([]individualTestResult, len(testSizes)) for i, test := range testSizes { var result individualTestResult result.TestCase = test.name body := make([]byte, test.size) jsonBody, _ := json.Marshal(body) fmt.Printf("largeDataErrorServiceCall %s - Request size: %d\n", test.name, len(jsonBody)) if isHTTP { resp, err := httpClient.Post(sanitizeHTTPURL(url), jsonContentType, bytes.NewReader(jsonBody)) result.CallSuccessful = !((resp != nil && resp.StatusCode != 200) || err != nil) if resp != nil { // Drain before closing _, _ = io.Copy(io.Discard, resp.Body) resp.Body.Close() } } else { req := constructRequest("serviceinvocation-callee-0", "posthandler", "POST", jsonBody) _, err := daprClient.InvokeService(r.Context(), req) result.CallSuccessful = err == nil } results[i] = result } json.NewEncoder(w).Encode(results) } // testPathHTTPCall return the path received form request. func testPathHTTPCall(w http.ResponseWriter, r *http.Request) { logAndSetResponse(w, http.StatusOK, r.RequestURI) } func main() { daprClient = utils.GetGRPCClient(daprGRPCPort) httpMethods = []string{"POST", "GET", "PUT", "DELETE"} // Generate a random "process ID" of 48 bits pidBytes := make([]byte, 6) io.ReadFull(rand.Reader, pidBytes) pid = hex.EncodeToString(pidBytes) log.Printf("Dapr service_invocation - listening on http://localhost:%d", appPort) log.Printf("PID: %s", pid) utils.StartServer(appPort, appRouter, true, false) } // Bad http request func onBadRequest(w http.ResponseWriter, err error) { msg := "deserialization failed with " + err.Error() logAndSetResponse(w, http.StatusBadRequest, msg) } func onDeserializationFailed(w http.ResponseWriter, err error) { msg := "deserialization failed with " + err.Error() logAndSetResponse(w, http.StatusInternalServerError, msg) } func onSerializationFailed(w http.ResponseWriter, err error) { msg := "serialization failed with " + err.Error() logAndSetResponse(w, http.StatusInternalServerError, msg) } func onHTTPCallFailed(w http.ResponseWriter, statusCode int, err error) { msg := "HTTP call failed with " + err.Error() if statusCode == 0 { statusCode = http.StatusInternalServerError } logAndSetResponse(w, statusCode, msg) } func logAndSetResponse(w http.ResponseWriter, statusCode int, message string) { log.Println(message) w.WriteHeader(statusCode) json.NewEncoder(w). Encode(appResponse{Message: message}) } //--- The functions below are copied from utils/helpers.go to workaround the package include in a container problem. func sanitizeHTTPURL(url string) string { if !strings.Contains(url, "http") { url = fmt.Sprintf("http://%s", url) } return url }
mikeee/dapr
tests/apps/service_invocation/app.go
GO
mit
43,311
# In e2e test, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing e2e test. kind: Service apiVersion: v1 metadata: name: service-invocation labels: testapp: service-invocation spec: selector: testapp: service-invocation ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer --- apiVersion: apps/v1 kind: Deployment metadata: name: service-invocation labels: testapp: service-invocation spec: replicas: 1 selector: matchLabels: testapp: service-invocation template: metadata: labels: testapp: service-invocation annotations: dapr.io/enabled: "true" dapr.io/app-id: "myapp" dapr.io/app-port: "3000" spec: containers: - name: service-invocation image: docker.io/[YOUR ALIAS]/e2e-service_invocation:dev ports: - containerPort: 3000 imagePullPolicy: Always
mikeee/dapr
tests/apps/service_invocation/service.yaml
YAML
mit
1,018
../../../dapr/proto/common/v1/*.proto ../../../dapr/proto/runtime/v1/*.proto ../utils/*.go
mikeee/dapr
tests/apps/service_invocation_external/.cache-include
none
mit
90
/* Copyright 2023 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "encoding/json" "io" "log" "net/http" "os" "github.com/gorilla/mux" "github.com/dapr/dapr/tests/apps/utils" ) const ( jsonContentType = "application/json" tlsCertEnvKey = "DAPR_TESTS_TLS_CERT" tlsKeyEnvKey = "DAPR_TESTS_TLS_KEY" ) type httpTestMethods struct { Verb string SendBody bool ExpectBody bool } var testMethods = []httpTestMethods{ { Verb: "GET", SendBody: false, ExpectBody: true, }, { Verb: "HEAD", SendBody: false, ExpectBody: false, }, { Verb: "POST", SendBody: true, ExpectBody: true, }, { Verb: "PUT", SendBody: true, ExpectBody: true, }, { Verb: "DELETE", SendBody: true, ExpectBody: true, }, // Go's net/http library does not support sending requests with the CONNECT method /*{ Verb: "CONNECT", Callback: "connecthandler", SendBody: true, ExpectBody: true, },*/ { Verb: "OPTIONS", SendBody: true, ExpectBody: true, }, { Verb: "TRACE", SendBody: true, ExpectBody: true, }, { Verb: "PATCH", SendBody: true, ExpectBody: true, }, } var ( appPort = 3000 securedAppPort = 3001 ) type appResponse struct { Message string `json:"message,omitempty"` } func main() { log.Print("Service_invocation_external started") log.Printf("HTTP Listening on http://localhost:%d ", appPort) log.Printf("HTTPS Listening on https://localhost:%d ", securedAppPort) go func() { os.Setenv(tlsCertEnvKey, "/tmp/testdata/certs/tls.crt") os.Setenv(tlsKeyEnvKey, "/tmp/testdata/certs/tls.key") utils.StartServer(securedAppPort, appRouter, true, true) }() utils.StartServer(appPort, appRouter, true, false) } // appRouter initializes restful api router func appRouter() http.Handler { router := mux.NewRouter().StrictSlash(true) // Log requests and their processing time router.Use(utils.LoggerMiddleware) router.HandleFunc("/", indexHandler).Methods("GET") router.HandleFunc("/retrieve_request_object", retrieveRequestObject).Methods("POST") // these are called through dapr service invocation for _, test := range testMethods { if test.SendBody { router.HandleFunc("/externalInvocation", withBodyHandler).Methods(test.Verb) } else { router.HandleFunc("/externalInvocation", noBodyHandler).Methods(test.Verb) } } router.Use(mux.CORSMethodMiddleware(router)) return router } func retrieveRequestObject(w http.ResponseWriter, r *http.Request) { headers := map[string][]string{} for k, vals := range r.Header { headers[k] = vals log.Printf("headers: %s %q", k, vals) } serializedHeaders, _ := json.Marshal(headers) w.Header().Set("Content-Type", jsonContentType) w.Header().Set("DaprTest-Response-1", "DaprTest-Response-Value-1") w.Header().Set("DaprTest-Response-2", "DaprTest-Response-Value-2") w.Header().Add("DaprTest-Response-Multi", "DaprTest-Response-Multi-1") w.Header().Add("DaprTest-Response-Multi", "DaprTest-Response-Multi-2") if val, ok := headers["Daprtest-Traceid"]; ok { // val[0] is client app given trace id w.Header().Set("traceparent", val[0]) } w.WriteHeader(http.StatusOK) w.Write(serializedHeaders) } // indexHandler is the handler for root path func indexHandler(w http.ResponseWriter, r *http.Request) { log.Println("indexHandler is called") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{Message: "success"}) } // Bad http request func onBadRequest(w http.ResponseWriter, err error) { msg := "deserialization failed with " + err.Error() logAndSetResponse(w, http.StatusBadRequest, msg) } func onDeserializationFailed(w http.ResponseWriter, err error) { msg := "deserialization failed with " + err.Error() logAndSetResponse(w, http.StatusInternalServerError, msg) } func logAndSetResponse(w http.ResponseWriter, statusCode int, message string) { log.Println(message) w.WriteHeader(statusCode) json.NewEncoder(w). Encode(appResponse{Message: message}) } // Handles a request with a JSON body. Extracts s string from the input json and returns in it an appResponse. func withBodyHandler(w http.ResponseWriter, r *http.Request) { log.Printf("withBodyHandler called. HTTP Verb: %s", r.Method) body, err := io.ReadAll(r.Body) if err != nil { onBadRequest(w, err) return } log.Printf("withBodyHandler body: %s", string(body)) var s string err = json.Unmarshal(body, &s) if err != nil { onDeserializationFailed(w, err) return } w.Header().Add("x-dapr-tests-request-method", r.Method) w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(appResponse{Message: s}) } // Handles a request with no body. Returns an appResponse with appResponse.Message "ok", which caller validates. func noBodyHandler(w http.ResponseWriter, r *http.Request) { log.Printf("noBodyHandler called. HTTP Verb: %s", r.Method) w.Header().Add("x-dapr-tests-request-method", r.Method) logAndSetResponse(w, http.StatusOK, "success") }
mikeee/dapr
tests/apps/service_invocation_external/app.go
GO
mit
5,517
# In e2e test, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing e2e test. kind: Service apiVersion: v1 metadata: name: service-invocation-external labels: testapp: service-invocation-external spec: selector: testapp: service-invocation-external ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer --- apiVersion: apps/v1 kind: Deployment metadata: name: service-invocation-external labels: testapp: service-invocation-external spec: replicas: 1 selector: matchLabels: testapp: service-invocation-external template: metadata: labels: testapp: service-invocation-external annotations: dapr.io/enabled: "false" spec: containers: - name: service-invocation-external image: docker.io/[YOUR ALIAS]/e2e-service_invocation_external:dev ports: - containerPort: 3000 imagePullPolicy: Always
mikeee/dapr
tests/apps/service_invocation_external/service.yaml
YAML
mit
1,035
../../../dapr/proto/common/v1/*.proto ../../../dapr/proto/runtime/v1/*.proto
mikeee/dapr
tests/apps/service_invocation_grpc/.cache-include
none
mit
76
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //nolint:forbidigo package main import ( "context" "encoding/json" "fmt" "log" "net" "os" "strconv" "go.opentelemetry.io/otel/trace" "google.golang.org/protobuf/types/known/anypb" "google.golang.org/protobuf/types/known/emptypb" "google.golang.org/grpc" "google.golang.org/grpc/metadata" diagUtils "github.com/dapr/dapr/pkg/diagnostics/utils" commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" ) var appPort = 3000 func init() { p := os.Getenv("PORT") if p != "" && p != "0" { appPort, _ = strconv.Atoi(p) } } // server is our user app type server struct{} type appResponse struct { Message string `json:"message,omitempty"` } func main() { log.Printf("Initializing grpc") /* #nosec */ lis, err := net.Listen("tcp", fmt.Sprintf(":%d", appPort)) if err != nil { log.Fatalf("failed to listen: %v", err) } /* #nosec */ s := grpc.NewServer() runtimev1pb.RegisterAppCallbackServer(s, &server{}) fmt.Println("Client starting...") if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } } // This is the server side in a grpc -> grpc test. It responds with the same string it was sent. func (s *server) grpcTestHandler(data []byte) ([]byte, error) { var t string err := json.Unmarshal(data, &t) if err != nil { return nil, err } fmt.Printf("received %s\n", t) resp, err := json.Marshal(appResponse{Message: t}) if err != nil { fmt.Println("not marshal") } return resp, err } func (s *server) retrieveRequestObject(ctx context.Context) ([]byte, error) { md, _ := metadata.FromIncomingContext(ctx) requestMD := map[string][]string{} fmt.Print("incoming md: ") for k, vals := range md { requestMD[k] = vals fmt.Printf("%s='%q' ", k, vals) } fmt.Print("\n") header := metadata.Pairs( "DaprTest-Response-1", "DaprTest-Response-Value-1", "DaprTest-Response-2", "DaprTest-Response-Value-2", ) header.Append("DaprTest-Response-Multi", "DaprTest-Response-Multi-1", "DaprTest-Response-Multi-2") // following traceid byte is of expectedTraceID "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" scConfig := trace.SpanContextConfig{ TraceID: trace.TraceID{75, 249, 47, 53, 119, 179, 77, 166, 163, 206, 146, 157, 14, 14, 71, 54}, SpanID: trace.SpanID{0, 240, 103, 170, 11, 169, 2, 183}, TraceFlags: trace.TraceFlags(1), } sc := trace.NewSpanContext(scConfig) header.Set("grpc-trace-bin", string(diagUtils.BinaryFromSpanContext(sc))) grpc.SendHeader(ctx, header) trailer := metadata.Pairs( "DaprTest-Trailer-1", "DaprTest-Trailer-Value-1", "DaprTest-Trailer-2", "DaprTest-Trailer-Value-2", ) trailer.Append("DaprTest-Trailer-Multi", "DaprTest-Trailer-Multi-1", "DaprTest-Trailer-Multi-2") grpc.SetTrailer(ctx, trailer) return json.Marshal(requestMD) } // OnInvoke This method gets invoked when a remote service has called the app through Dapr // The payload carries a Method to identify the method, a set of metadata properties and an optional payload func (s *server) OnInvoke(ctx context.Context, in *commonv1pb.InvokeRequest) (*commonv1pb.InvokeResponse, error) { fmt.Printf("Got invoked method %s and data: %s\n", in.GetMethod(), string(in.GetData().GetValue())) var err error var response []byte switch in.GetMethod() { case "httpToGrpcTest": // not a typo, the handling is the same as the case below fallthrough case "grpcToGrpcTest", "grpcToGrpcWithoutVerbTest": response, err = s.grpcTestHandler(in.GetData().GetValue()) case "retrieve_request_object": response, err = s.retrieveRequestObject(ctx) } if err != nil { msg := "Error: " + err.Error() response, _ = json.Marshal(msg) } respBody := &anypb.Any{Value: response} return &commonv1pb.InvokeResponse{Data: respBody, ContentType: "application/json"}, nil } // ListTopicSubscriptions Dapr will call this method to get the list of topics the app wants to subscribe to. In this example, we are telling Dapr // To subscribe to a topic named TopicA func (s *server) ListTopicSubscriptions(ctx context.Context, in *emptypb.Empty) (*runtimev1pb.ListTopicSubscriptionsResponse, error) { return &runtimev1pb.ListTopicSubscriptionsResponse{ Subscriptions: []*runtimev1pb.TopicSubscription{ { Topic: "TopicA", }, }, }, nil } // ListInputBindings Dapr will call this method to get the list of bindings the app will get invoked by. In this example, we are telling Dapr // To invoke our app with a binding named storage func (s *server) ListInputBindings(ctx context.Context, in *emptypb.Empty) (*runtimev1pb.ListInputBindingsResponse, error) { return &runtimev1pb.ListInputBindingsResponse{ Bindings: []string{"storage"}, }, nil } // OnBindingEvent This method gets invoked every time a new event is fired from a registered binding. // The message carries the binding name, a payload and optional metadata func (s *server) OnBindingEvent(ctx context.Context, in *runtimev1pb.BindingEventRequest) (*runtimev1pb.BindingEventResponse, error) { fmt.Println("Invoked from binding") return &runtimev1pb.BindingEventResponse{}, nil } // OnTopicEvent This method is fired whenever a message has been published to a topic that has been subscribed. // Dapr sends published messages in a CloudEvents 1.0 envelope. func (s *server) OnTopicEvent(ctx context.Context, in *runtimev1pb.TopicEventRequest) (*runtimev1pb.TopicEventResponse, error) { fmt.Println("Topic message arrived") return &runtimev1pb.TopicEventResponse{}, nil }
mikeee/dapr
tests/apps/service_invocation_grpc/app.go
GO
mit
6,067
# In e2e test, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing e2e test. kind: Service apiVersion: v1 metadata: name: service-invocation labels: testapp: service-invocation spec: selector: testapp: service-invocation ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer --- apiVersion: apps/v1 kind: Deployment metadata: name: service-invocation labels: testapp: service-invocation spec: replicas: 1 selector: matchLabels: testapp: service-invocation template: metadata: labels: testapp: service-invocation annotations: dapr.io/enabled: "true" dapr.io/app-id: "myapp" dapr.io/app-port: "3000" dapr.io/app-protocol: "grpc" spec: containers: - name: service-invocation image: docker.io/[YOUR ALIAS]/e2e-service_invocation_grpc:dev ports: - containerPort: 3000 imagePullPolicy: Always
mikeee/dapr
tests/apps/service_invocation_grpc/service.yaml
YAML
mit
1,060
../utils/*.go
mikeee/dapr
tests/apps/service_invocation_grpc_proxy_client/.cache-include
none
mit
13
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "context" "encoding/json" "fmt" "log" "net/http" "strings" "time" "github.com/dapr/dapr/tests/apps/utils" "github.com/gorilla/mux" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" pb "google.golang.org/grpc/examples/helloworld/helloworld" "google.golang.org/grpc/metadata" ) type appResponse struct { Message string `json:"message,omitempty"` } type testCommandRequest struct { RemoteApp string `json:"remoteApp,omitempty"` Method string `json:"method,omitempty"` RemoteAppTracing string `json:"remoteAppTracing"` Message *string `json:"message"` } func run(w http.ResponseWriter, r *http.Request) { var request testCommandRequest err := json.NewDecoder(r.Body).Decode(&request) if err != nil { log.Fatalf("could not decode request body: %v", err) } conn, err := grpc.Dial("localhost:50001", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(6*1024*1024), grpc.MaxCallSendMsgSize(6*1024*1024)), ) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() c := pb.NewGreeterClient(conn) ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) defer cancel() ctx = metadata.AppendToOutgoingContext(ctx, "dapr-app-id", "grpcproxyserver") var name string if request.Method == "maxsize" { name = strings.Repeat("d", 5*1024*1024) } else { name = "Darth Tyranus" } resp, err := c.SayHello(ctx, &pb.HelloRequest{Name: name}) if err != nil { log.Printf("could not greet: %v\n", err) w.WriteHeader(500) w.Write([]byte(fmt.Sprintf("failed to proxy request: %s", err))) return } if request.Method == "maxsize" { log.Printf("Message bytes exchanged: %d", len(resp.GetMessage())) } else { log.Printf("Greeting: %s", resp.GetMessage()) } appResp := appResponse{ Message: "success", } b, err := json.Marshal(appResp) if err != nil { log.Fatal(err) } w.WriteHeader(200) w.Write(b) } func appRouter() http.Handler { router := mux.NewRouter().StrictSlash(true) // Log requests and their processing time router.Use(utils.LoggerMiddleware) router.HandleFunc("/tests/invoke_test", run).Methods("POST") return router } func main() { log.Printf("Hello Dapr - listening on http://localhost:%d", 3000) utils.StartServer(3000, appRouter, true, false) }
mikeee/dapr
tests/apps/service_invocation_grpc_proxy_client/app.go
GO
mit
2,976
module github.com/dapr/dapr/tests/apps/service_invocation_grpc_proxy_client go 1.22.3 require ( github.com/dapr/dapr v0.0.0-00010101000000-000000000000 github.com/gorilla/mux v1.8.1 google.golang.org/grpc v1.64.0 google.golang.org/grpc/examples v0.0.0-20230224211313-3775f633ce20 ) require ( github.com/google/uuid v1.6.0 // indirect go.opentelemetry.io/otel v1.24.0 // indirect go.opentelemetry.io/otel/trace v1.24.0 // indirect golang.org/x/net v0.24.0 // indirect golang.org/x/sys v0.19.0 // indirect golang.org/x/text v0.14.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20240318140521-94a12d6c2237 // indirect google.golang.org/protobuf v1.33.0 // indirect ) replace github.com/dapr/dapr => ../../../
mikeee/dapr
tests/apps/service_invocation_grpc_proxy_client/go.mod
mod
mit
738
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo= go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo= go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI= go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU= golang.org/x/exp v0.0.0-20240119083558-1b970713d09a h1:Q8/wZp0KX97QFTc2ywcOE0YRjZPVIx+MXInMzdvQqcA= golang.org/x/exp v0.0.0-20240119083558-1b970713d09a/go.mod h1:idGWGoKP1toJGkd5/ig9ZLuPcZBC3ewk7SzmH0uou08= golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= google.golang.org/genproto/googleapis/rpc v0.0.0-20240318140521-94a12d6c2237 h1:NnYq6UN9ReLM9/Y01KWNOWyI5xQ9kbIms5GGJVwS/Yc= google.golang.org/genproto/googleapis/rpc v0.0.0-20240318140521-94a12d6c2237/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY= google.golang.org/grpc v1.64.0 h1:KH3VH9y/MgNQg1dE7b3XfVK0GsPSIzJwdF617gUSbvY= google.golang.org/grpc v1.64.0/go.mod h1:oxjF8E3FBnjp+/gVFYdWacaLDx9na1aqy9oovLpxQYg= google.golang.org/grpc/examples v0.0.0-20230224211313-3775f633ce20 h1:MLBCGN1O7GzIx+cBiwfYPwtmZ41U3Mn/cotLJciaArI= google.golang.org/grpc/examples v0.0.0-20230224211313-3775f633ce20/go.mod h1:Nr5H8+MlGWr5+xX/STzdoEqJrO+YteqFbMyCsrb6mH0= google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
mikeee/dapr
tests/apps/service_invocation_grpc_proxy_client/go.sum
sum
mit
3,135
# In e2e test, this will not be used to deploy the app to test cluster. # This is created for testing purpose in order to deploy this app using kubectl # before writing e2e test. kind: Service apiVersion: v1 metadata: name: service-invocation-grpc-proxy-client labels: testapp: service-invocation-grpc-proxy-client spec: selector: testapp: service-invocation-grpc-proxy-client ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer --- apiVersion: apps/v1 kind: Deployment metadata: name: service-invocation-grpc-proxy-client labels: testapp: service-invocation-grpc-proxy-client spec: replicas: 1 selector: matchLabels: testapp: service-invocation-grpc-proxy-client template: metadata: labels: testapp: service-invocation-grpc-proxy-client annotations: dapr.io/enabled: "true" dapr.io/app-id: "grpcproxyclient" dapr.io/http-max-request-size: "6" spec: containers: - name: service-invocation-grpc-proxy-client image: docker.io/[YOUR ALIAS]/e2e-service_invocation_grpc_proyx_client:dev ports: - containerPort: 50051 - containerPort: 3000 imagePullPolicy: Always
mikeee/dapr
tests/apps/service_invocation_grpc_proxy_client/service.yaml
YAML
mit
1,231
/* Copyright 2021 The Dapr Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "context" "log" "net" "google.golang.org/grpc" pb "google.golang.org/grpc/examples/helloworld/helloworld" ) const ( port = ":50051" ) // server is used to implement helloworld.GreeterServer. type server struct { pb.UnimplementedGreeterServer } // SayHello implements helloworld.GreeterServer func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { log.Printf("Received: %v", in.GetName()) return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil } func main() { lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer(grpc.MaxRecvMsgSize(6<<20), grpc.MaxSendMsgSize(6<<20)) pb.RegisterGreeterServer(s, &server{}) log.Printf("server listening at %v", lis.Addr()) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } }
mikeee/dapr
tests/apps/service_invocation_grpc_proxy_server/app.go
GO
mit
1,452