├── .gitignore ├── images ├── Gopher_Dropping_Mic.png └── Getting_Endpoint_and_APIKeys.png ├── Dockerfile.integration.test ├── go.mod ├── .github └── workflows │ └── srclient.yml ├── schemaRegistryClientIntegration_test.go ├── go.sum ├── docker-compose.yml ├── README.md ├── EXAMPLES_AVRO.md ├── EXAMPLES_PROTOBUF.md ├── LICENSE ├── mockSchemaRegistryClient.go ├── mockSchemaRegistryClient_test.go ├── schemaRegistryClient_test.go └── schemaRegistryClient.go /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | .idea 3 | *.iml 4 | -------------------------------------------------------------------------------- /images/Gopher_Dropping_Mic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/riferrei/srclient/HEAD/images/Gopher_Dropping_Mic.png -------------------------------------------------------------------------------- /images/Getting_Endpoint_and_APIKeys.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/riferrei/srclient/HEAD/images/Getting_Endpoint_and_APIKeys.png -------------------------------------------------------------------------------- /Dockerfile.integration.test: -------------------------------------------------------------------------------- 1 | FROM golang:1.18-alpine 2 | 3 | RUN apk update 4 | RUN apk add build-base 5 | RUN apk add git 6 | 7 | WORKDIR /srclient 8 | COPY go.mod ./ 9 | COPY go.sum ./ 10 | RUN go mod download 11 | COPY *.go ./ 12 | 13 | CMD ["go", "test", "-tags", "integration", "."] -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/riferrei/srclient 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/golang/snappy v1.0.0 // indirect 7 | github.com/linkedin/goavro/v2 v2.14.1 8 | github.com/santhosh-tekuri/jsonschema/v5 v5.0.0 9 | github.com/stretchr/testify v1.7.5 10 | golang.org/x/sync v0.0.0-20220513210516-0976fa681c29 11 | ) 12 | -------------------------------------------------------------------------------- /.github/workflows/srclient.yml: -------------------------------------------------------------------------------- 1 | name: srclient Main Workflow 2 | on: [push, pull_request] 3 | jobs: 4 | unit-tests: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - name: Checkout repository 8 | uses: actions/checkout@v3 9 | - name: Download dependencies 10 | run: go mod download 11 | - name: Run unit tests 12 | run: go test -cover -v ./... 13 | integration-tests: 14 | needs: unit-tests 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout repository 18 | uses: actions/checkout@v3 19 | - name: Run containerized integration tests 20 | run: docker compose up --exit-code-from srclient-integration-test -------------------------------------------------------------------------------- /schemaRegistryClientIntegration_test.go: -------------------------------------------------------------------------------- 1 | //go:build integration 2 | // +build integration 3 | 4 | package srclient 5 | 6 | import ( 7 | "os" 8 | "testing" 9 | 10 | "github.com/stretchr/testify/assert" 11 | ) 12 | 13 | var srclientUrlEnvName = "SRCLIENT_URL" 14 | var srclientUrl string = os.Getenv(srclientUrlEnvName) 15 | var client *SchemaRegistryClient = CreateSchemaRegistryClient(srclientUrl) 16 | 17 | func TestGetSubjects(t *testing.T) { 18 | t.Parallel() 19 | subjects, err := client.GetSubjects() 20 | if err != nil { 21 | t.Fatal(err.Error()) 22 | } 23 | t.Log("Test passes: ", subjects) 24 | } 25 | 26 | func TestCreateSchema(t *testing.T) { 27 | t.Parallel() 28 | subject := "LongList" 29 | schema := `{ 30 | "type": "record", 31 | "name": "LongList", 32 | "aliases": ["LinkedLongs"], 33 | "fields" : [ 34 | {"name": "value", "type": "long"}, 35 | {"name": "next", "type": ["null", "LongList"]} 36 | ] 37 | }` 38 | 39 | _, err := client.CreateSchema(subject, schema, Avro) 40 | if err != nil { 41 | t.Fatal(err.Error()) 42 | } 43 | 44 | subjects, err := client.GetSubjects() 45 | if err != nil { 46 | t.Fatal(err.Error()) 47 | } 48 | 49 | assert.Contains(t, subjects, subject) 50 | } 51 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 2 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= 5 | github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= 6 | github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs= 7 | github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= 8 | github.com/linkedin/goavro/v2 v2.12.0 h1:rIQQSj8jdAUlKQh6DttK8wCRv4t4QO09g1C4aBWXslg= 9 | github.com/linkedin/goavro/v2 v2.12.0/go.mod h1:KXx+erlq+RPlGSPmLF7xGo6SAbh8sCQ53x064+ioxhk= 10 | github.com/linkedin/goavro/v2 v2.13.1 h1:4qZ5M0QzQFDRqccsroJlgOJznqAS/TpdvXg55h429+I= 11 | github.com/linkedin/goavro/v2 v2.13.1/go.mod h1:KXx+erlq+RPlGSPmLF7xGo6SAbh8sCQ53x064+ioxhk= 12 | github.com/linkedin/goavro/v2 v2.14.1 h1:/8VjDpd38PRsy02JS0jflAu7JZPfJcGTwqWgMkFS2iI= 13 | github.com/linkedin/goavro/v2 v2.14.1/go.mod h1:KXx+erlq+RPlGSPmLF7xGo6SAbh8sCQ53x064+ioxhk= 14 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 15 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 16 | github.com/santhosh-tekuri/jsonschema/v5 v5.0.0 h1:TToq11gyfNlrMFZiYujSekIsPd9AmsA2Bj/iv+s4JHE= 17 | github.com/santhosh-tekuri/jsonschema/v5 v5.0.0/go.mod h1:FKdcjfQW6rpZSnxxUvEA5H/cDPdvJ/SZJQLWWXWGrZ0= 18 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 19 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 20 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 21 | github.com/stretchr/testify v1.7.5 h1:s5PTfem8p8EbKQOctVV53k6jCJt3UX4IEJzwh+C324Q= 22 | github.com/stretchr/testify v1.7.5/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 23 | golang.org/x/sync v0.0.0-20220513210516-0976fa681c29 h1:w8s32wxx3sY+OjLlv9qltkLU5yvJzxjjgiHWLjdIcw4= 24 | golang.org/x/sync v0.0.0-20220513210516-0976fa681c29/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 25 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 26 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 27 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 28 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 29 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 30 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | --- 2 | version: '2' 3 | 4 | networks: 5 | integration-test-network: 6 | driver: bridge 7 | 8 | services: 9 | 10 | zookeeper: 11 | image: confluentinc/cp-zookeeper:7.1.0 12 | hostname: zookeeper 13 | container_name: zookeeper 14 | ports: 15 | - "2181:2181" 16 | environment: 17 | ZOOKEEPER_CLIENT_PORT: 2181 18 | ZOOKEEPER_TICK_TIME: 2000 19 | healthcheck: 20 | test: nc -z localhost 2181 || exit -1 21 | interval: 10s 22 | timeout: 5s 23 | retries: 3 24 | start_period: 10s 25 | networks: 26 | - integration-test-network 27 | 28 | broker: 29 | image: confluentinc/cp-kafka:7.1.0 30 | hostname: broker 31 | container_name: broker 32 | depends_on: 33 | zookeeper: 34 | condition: service_healthy 35 | ports: 36 | - "29092:29092" 37 | - "9092:9092" 38 | - "9101:9101" 39 | environment: 40 | KAFKA_BROKER_ID: 1 41 | KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181' 42 | KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT 43 | KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:29092,PLAINTEXT_HOST://localhost:9092 44 | KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 45 | KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 46 | KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1 47 | KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0 48 | KAFKA_JMX_PORT: 9101 49 | KAFKA_JMX_HOSTNAME: localhost 50 | healthcheck: 51 | test: nc -z localhost 29092 || exit -1 52 | start_period: 20s 53 | interval: 10s 54 | retries: 6 55 | timeout: 5s 56 | networks: 57 | - integration-test-network 58 | 59 | schema-registry: 60 | image: confluentinc/cp-schema-registry:7.1.0 61 | hostname: schema-registry 62 | container_name: schema-registry 63 | depends_on: 64 | broker: 65 | condition: service_healthy 66 | ports: 67 | - "8081:8081" 68 | environment: 69 | SCHEMA_REGISTRY_HOST_NAME: schema-registry 70 | SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: 'broker:29092' 71 | SCHEMA_REGISTRY_LISTENERS: http://0.0.0.0:8081 72 | healthcheck: 73 | test: nc -z localhost 8081 || exit -1 74 | interval: 10s 75 | timeout: 5s 76 | retries: 6 77 | start_period: 30s 78 | networks: 79 | - integration-test-network 80 | 81 | srclient-integration-test: 82 | build: 83 | context: . 84 | dockerfile: ./Dockerfile.integration.test 85 | depends_on: 86 | schema-registry: 87 | condition: service_healthy 88 | environment: 89 | SRCLIENT_URL: http://schema-registry:8081 90 | networks: 91 | - integration-test-network -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Schema Registry Client for Go 2 | 3 | [![Go Report Card](https://goreportcard.com/badge/github.com/riferrei/srclient)](https://goreportcard.com/report/github.com/riferrei/srclient) [![Go Reference](https://pkg.go.dev/badge/github.com/riferrei/srclient.svg)](https://pkg.go.dev/github.com/riferrei/srclient) 4 | 5 | 6 | 7 | **srclient** is a Golang client for [Schema Registry](https://www.confluent.io/confluent-schema-registry/), a software that provides a RESTful interface for developers to define standard schemas for their events, share them across the organization, and safely evolve them in a way that is backward compatible and future proof. 8 | Using this client allows developers to build Golang programs that write and read schema compatible records to/from [Apache Kafka](https://kafka.apache.org/) using [Avro](https://avro.apache.org/), [Protobuf](https://developers.google.com/protocol-buffers), and [JSON Schemas](https://json-schema.org) while Schema Registry is used to manage the schemas used. 9 | Using this architecture, producers programs interact with Schema Registry to retrieve schemas and use it to serialize records. Then consumer programs can retrieve the same schema from Schema Registry to deserialize the records. 10 | You can read more about the benefits of using Schema Registry [here](https://www.confluent.io/blog/schemas-contracts-compatibility). 11 | 12 | ## Features 13 | 14 | * **Simple to Use** - This client provides a very high-level abstraction over the operations developers writing programs for Apache Kafka typically need. 15 | Thus, it will feel natural for them to use this client's functions. 16 | Moreover, developers don't need to handle low-level HTTP details to communicate with Schema Registry. 17 | * **Performance** - This client provides caching capabilities. 18 | This means that any data retrieved from Schema Registry can be cached locally to improve the performance of subsequent requests. 19 | This allows programs not co-located with Schema Registry to reduce the latency necessary on each request. 20 | This functionality can be disabled programmatically. 21 | 22 | **License**: [Apache License v2.0](http://www.apache.org/licenses/LICENSE-2.0) 23 | 24 | ## Installation 25 | 26 | Module install: 27 | 28 | This client is a Go module, therefore you can have it simply by adding the following import to your code: 29 | 30 | ```go 31 | import "github.com/riferrei/srclient" 32 | ``` 33 | 34 | Then run a build to have this client automatically added to your go.mod file as a dependency. 35 | 36 | Manual install: 37 | 38 | ```bash 39 | go get -u github.com/riferrei/srclient 40 | ``` 41 | 42 | ## Testing 43 | 44 | Unit testing can be run with the generic go test command: 45 | 46 | ```bash 47 | go test -cover -v ./... 48 | ``` 49 | 50 | You can also run integration testing in your local machine given you have docker installed: 51 | 52 | ```bash 53 | docker compose up --exit-code-from srclient-integration-test 54 | docker compose down --rmi local 55 | ``` 56 | 57 | ## Getting Started & Examples 58 | 59 | * [Package documentation](https://pkg.go.dev/github.com/riferrei/srclient) is a good place to start 60 | * For Avro examples see [EXAMPLES_AVRO.md](EXAMPLES_AVRO.md) 61 | * For Protobuf examples, see [EXAMPLES_PROTOBUF.md](EXAMPLES_PROTOBUF.md) 62 | * Consult [Confluent's Schema Registry documentation](https://docs.confluent.io/platform/current/schema-registry/index.html) for details 63 | 64 | 65 | ## Acknowledgements 66 | * Apache, Apache Kafka, Kafka, and associated open source project names are trademarks of the [Apache Software Foundation](https://www.apache.org/). 67 | * The [Go Gopher](https://blog.golang.org/gopher), is an artistic creation of [Renee French](http://reneefrench.blogspot.com/). -------------------------------------------------------------------------------- /EXAMPLES_AVRO.md: -------------------------------------------------------------------------------- 1 | # Avro Usage Examples 2 | 3 | ## Producer 4 | ```go 5 | import ( 6 | "encoding/binary" 7 | "encoding/json" 8 | "fmt" 9 | "io/ioutil" 10 | 11 | "github.com/google/uuid" 12 | "github.com/riferrei/srclient" 13 | "gopkg.in/confluentinc/confluent-kafka-go.v1/kafka" 14 | ) 15 | 16 | type ComplexType struct { 17 | ID int `json:"id"` 18 | Name string `json:"name"` 19 | } 20 | 21 | func main() { 22 | 23 | topic := "myTopic" 24 | 25 | // 1) Create the producer as you would normally do using Confluent's Go client 26 | p, err := kafka.NewProducer(&kafka.ConfigMap{"bootstrap.servers": "localhost"}) 27 | if err != nil { 28 | panic(err) 29 | } 30 | defer p.Close() 31 | 32 | go func() { 33 | for event := range p.Events() { 34 | switch ev := event.(type) { 35 | case *kafka.Message: 36 | message := ev 37 | if ev.TopicPartition.Error != nil { 38 | fmt.Printf("Error delivering the message '%s'\n", message.Key) 39 | } else { 40 | fmt.Printf("Message '%s' delivered successfully!\n", message.Key) 41 | } 42 | } 43 | } 44 | }() 45 | 46 | // 2) Fetch the latest version of the schema, or create a new one if it is the first 47 | schemaRegistryClient := srclient.NewSchemaRegistryClient("http://localhost:8081") 48 | schema, err := schemaRegistryClient.GetLatestSchema(topic) 49 | if schema == nil { 50 | schemaBytes, _ := ioutil.ReadFile("complexType.avsc") 51 | schema, err = schemaRegistryClient.CreateSchema(topic, string(schemaBytes), srclient.Avro) 52 | if err != nil { 53 | panic(fmt.Sprintf("Error creating the schema %s", err)) 54 | } 55 | } 56 | schemaIDBytes := make([]byte, 4) 57 | binary.BigEndian.PutUint32(schemaIDBytes, uint32(schema.ID())) 58 | 59 | // 3) Serialize the record using the schema provided by the client, 60 | // making sure to include the schema id as part of the record. 61 | newComplexType := ComplexType{ID: 1, Name: "Gopher"} 62 | value, _ := json.Marshal(newComplexType) 63 | native, _, _ := schema.Codec().NativeFromTextual(value) 64 | valueBytes, _ := schema.Codec().BinaryFromNative(nil, native) 65 | 66 | var recordValue []byte 67 | recordValue = append(recordValue, byte(0)) 68 | recordValue = append(recordValue, schemaIDBytes...) 69 | recordValue = append(recordValue, valueBytes...) 70 | 71 | key, _ := uuid.NewUUID() 72 | p.Produce(&kafka.Message{ 73 | TopicPartition: kafka.TopicPartition{ 74 | Topic: &topic, Partition: kafka.PartitionAny}, 75 | Key: []byte(key.String()), Value: recordValue}, nil) 76 | 77 | p.Flush(15 * 1000) 78 | 79 | } 80 | ``` 81 | 82 | ## Consumer 83 | 84 | ```go 85 | import ( 86 | "encoding/binary" 87 | "fmt" 88 | 89 | "github.com/riferrei/srclient" 90 | "gopkg.in/confluentinc/confluent-kafka-go.v1/kafka" 91 | ) 92 | 93 | func main() { 94 | 95 | // 1) Create the consumer as you would 96 | // normally do using Confluent's Go client 97 | c, err := kafka.NewConsumer(&kafka.ConfigMap{ 98 | "bootstrap.servers": "localhost", 99 | "group.id": "myGroup", 100 | "auto.offset.reset": "earliest", 101 | }) 102 | if err != nil { 103 | panic(err) 104 | } 105 | c.SubscribeTopics([]string{"myTopic", "^aRegex.*[Tt]opic"}, nil) 106 | 107 | // 2) Create a instance of the client to retrieve the schemas for each message 108 | schemaRegistryClient := srclient.NewSchemaRegistryClient("http://localhost:8081") 109 | 110 | for { 111 | msg, err := c.ReadMessage(-1) 112 | if err == nil { 113 | // 3) Recover the schema id from the message and use the 114 | // client to retrieve the schema from Schema Registry. 115 | // Then use it to deserialize the record accordingly. 116 | schemaID := binary.BigEndian.Uint32(msg.Value[1:5]) 117 | schema, err := schemaRegistryClient.GetSchema(int(schemaID)) 118 | if err != nil { 119 | panic(fmt.Sprintf("Error getting the schema with id '%d' %s", schemaID, err)) 120 | } 121 | native, _, _ := schema.Codec().NativeFromBinary(msg.Value[5:]) 122 | value, _ := schema.Codec().TextualFromNative(nil, native) 123 | fmt.Printf("Here is the message %s\n", string(value)) 124 | } else { 125 | fmt.Printf("Error consuming the message: %v (%v)\n", err, msg) 126 | } 127 | } 128 | 129 | c.Close() 130 | 131 | } 132 | ``` -------------------------------------------------------------------------------- /EXAMPLES_PROTOBUF.md: -------------------------------------------------------------------------------- 1 | # Protobuf Usage Examples 2 | 3 | If you plan to use srclient with Protobuf schemas, please do give the issues #16 and #17 a read for a better understanding on how to do so. 4 | 5 | * [Issue #16](https://github.com/riferrei/srclient/issues/16) 6 | * [Issue #17](https://github.com/riferrei/srclient/issues/17) 7 | 8 | ## Example In #16 9 | 10 | ### Producer 11 | 12 | ```go 13 | 14 | func makeNotifEventMessage() []byte { 15 | event := &metrics.Event{ # My Protobuf message 16 | Desc: "Email got sent successfully", 17 | SourceSystem: "test-producer", 18 | Ts: timestamppb.Now(), 19 | Type: metrics.Event_EMAIL_SUCCESS, 20 | }, 21 | } 22 | metricAny, _ := anypb.New(event) # This wraps the "event" protobuf object in an "Any" protobuf type. 23 | 24 | out, _ := proto.Marshal(metricAny) 25 | return out 26 | } 27 | ``` 28 | 29 | ### Consumer 30 | 31 | ```go 32 | 33 | # Handle getting Kafka messages 34 | 35 | # Unmarshal in to an "Any" type, which is wrapping the "real" message. 36 | wrapper := &anypb.Any{} 37 | if err := proto.Unmarshal(kafkaMessage.Value, wrapper); err != nil { 38 | c.log.Error("Failed to parse event", zap.Error(err)) 39 | continue 40 | } 41 | 42 | // This is probably where you could involve protoregistry in some fancy way 43 | // and anypb.UnmarshalNew(), but for now we can keep it simple. 44 | 45 | var msgBytes []byte 46 | 47 | // Iterate over the possible message types and process them. 48 | switch wrapper.MessageName() { # The "Any" type has a MessageName field which allows you to see what kind of protobuf message the wrapped object is. 49 | case "metrics.Event": 50 | me := &metrics.Event{} 51 | 52 | anypb.UnmarshalTo(wrapper, me, proto.UnmarshalOptions{}) 53 | msgBytes = processMetricsEvent(me) 54 | default: 55 | c.log.Info(fmt.Sprintf("Unknown message: %s, skipping.", wrapper.MessageName())) 56 | c.commitMessages(ctx, []kafka.Message{}) 57 | continue 58 | } 59 | ``` 60 | 61 | ## Example in #17 62 | 63 | ### Protobuf Resolver 64 | ```go 65 | // SchemaRegistryProtobufResolver 66 | type SchemaRegistryProtobufResolver struct { 67 | schemaRegistry SchemaRegistryClient 68 | protobufRegistry ProtobufRegistry 69 | deserializationType DeserializationType 70 | } 71 | 72 | // NewSchemaRegistryProtobufResolver 73 | func NewSchemaRegistryProtobufResolver( 74 | schemaRegistry SchemaRegistryClient, 75 | protobufRegistry ProtobufRegistry, 76 | deserializationType DeserializationType, 77 | ) *SchemaRegistryProtobufResolver { 78 | return &SchemaRegistryProtobufResolver{ 79 | schemaRegistry: schemaRegistry, 80 | protobufRegistry: protobufRegistry, 81 | deserializationType: deserializationType, 82 | } 83 | } 84 | 85 | // This should probably exist in srclient 86 | func (reg *SchemaRegistryProtobufResolver) parseSchema(schemaId int) (*desc.FileDescriptor, error) { 87 | parser := protoparse.Parser{ 88 | Accessor: func(filename string) (io.ReadCloser, error) { 89 | var schema *srclient.Schema 90 | var err error 91 | 92 | // filename is a schema id, fetch it directly 93 | if schemaId, err = strconv.Atoi(filename); err == nil { 94 | schema, err = reg.schemaRegistry.GetSchema(schemaId) 95 | } else { 96 | // otherwise its likely an import and we look it up by its filename 97 | schema, err = reg.schemaRegistry.GetLatestSchema(filename) 98 | } 99 | 100 | if err != nil { 101 | return nil, err 102 | } 103 | if *(schema.SchemaType()) != srclient.Protobuf { 104 | return nil, fmt.Errorf("schema %v is not a Protobuf schema", schemaId) 105 | } 106 | return io.NopCloser(strings.NewReader(schema.Schema())), nil 107 | }, 108 | } 109 | 110 | fileDescriptors, err := parser.ParseFiles(strconv.Itoa(schemaId)) 111 | if err != nil { 112 | return nil, err 113 | } 114 | 115 | if len(fileDescriptors) != 1 { 116 | return nil, fmt.Errorf("unexpected schema from schema registry") 117 | } 118 | return fileDescriptors[0], nil 119 | } 120 | 121 | // ResolveProtobuf 122 | func (reg *SchemaRegistryProtobufResolver) ResolveProtobuf( 123 | schemaId int, 124 | msgIndexes []int, 125 | ) (proto.Message, error) { 126 | 127 | fileDescriptor, err := reg.parseSchema(schemaId) 128 | if err != nil { 129 | return nil, err 130 | } 131 | 132 | msg := resolveDescriptorByIndexes(msgIndexes, fileDescriptor) 133 | 134 | var mt protoreflect.MessageType 135 | reg.protobufRegistry.RangeMessages(func(messageType protoreflect.MessageType) bool { 136 | if string(messageType.Descriptor().Name()) == msg.GetName() { 137 | mt = messageType 138 | return false 139 | } 140 | return true 141 | }) 142 | if mt != nil { 143 | pb := mt.New() 144 | return pb.Interface(), nil 145 | } 146 | return nil, fmt.Errorf("unable to find MessageType for messageIndex %v inside schema %v", msgIndexes, schemaId) 147 | } 148 | 149 | func resolveDescriptorByIndexes(msgIndexes []int, descriptor desc.Descriptor) desc.Descriptor { 150 | if len(msgIndexes) == 0 { 151 | return descriptor 152 | } 153 | 154 | index := msgIndexes[0] 155 | msgIndexes = msgIndexes[1:] 156 | 157 | switch v := descriptor.(type) { 158 | case *desc.FileDescriptor: 159 | return resolveDescriptorByIndexes(msgIndexes, v.GetMessageTypes()[index]) 160 | case *desc.MessageDescriptor: 161 | if len(msgIndexes) > 0 { 162 | return resolveDescriptorByIndexes(msgIndexes, v.GetNestedMessageTypes()[index]) 163 | } else { 164 | return v.GetNestedMessageTypes()[index] 165 | } 166 | default: 167 | fmt.Printf("no match: %v\n", v) 168 | return nil 169 | } 170 | } 171 | ``` 172 | 173 | ### Example Usage 174 | 175 | ```go 176 | schemaRegistryClient := srclient.CreateSchemaRegistryClient(lib.SchemaRegistryUrl) 177 | schemaRegistryClient.SetCredentials(lib.SchemaRegistryUsername, lib.SchemaRegistryPassword) 178 | protobufResolver := lib.NewSchemaRegistryProtobufResolver(schemaRegistryClient, protoregistry.GlobalTypes, lib.ValueDeserialization) 179 | deserializer := lib.NewProtobufDeserializer(protobufResolver) 180 | 181 | for { 182 | msg, err := c.ReadMessage(60 * time.Second) 183 | if err == nil { 184 | value, err := deserializer.Deserialize(msg.Value) 185 | if err != nil { 186 | sugar.Fatal(err) 187 | } 188 | 189 | switch v := value.(type) { 190 | case *schema.SampleRecord: 191 | sugar.Infof("Here is the sample record: (%s), headers (%v)", v.String(), msg.Headers) 192 | case *schema.OtherRecord_NestedRecord: 193 | sugar.Infof("Here is the nested record: (%s), headers (%v)", v.String(), msg.Headers) 194 | case *schema.OtherRecord: 195 | sugar.Infof("Here is the other record: (%s), headers (%v)", v.String(), msg.Headers) 196 | default: 197 | sugar.Infof("unrecognized message type: %T", v) 198 | } 199 | } else { 200 | sugar.Infof("Error consuming the message: %v (%v)", err, msg) 201 | } 202 | } 203 | ``` 204 | 205 | ### Protobuf Schema 206 | 207 | ```protobuf 208 | syntax = "proto3"; 209 | package com.mycorp.mynamespace; 210 | 211 | message SampleRecord { 212 | int32 my_field1 = 1; 213 | double my_field2 = 2; 214 | string my_field3 = 3; 215 | string my_field4 = 4; 216 | } 217 | message OtherRecord { 218 | string field = 1; 219 | 220 | message NestedRecord { 221 | string nestedfield = 1; 222 | } 223 | } 224 | ``` -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /mockSchemaRegistryClient.go: -------------------------------------------------------------------------------- 1 | package srclient 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "net/url" 7 | "regexp" 8 | "sort" 9 | "time" 10 | 11 | "github.com/linkedin/goavro/v2" 12 | ) 13 | 14 | // Compile-time interface check 15 | var _ ISchemaRegistryClient = new(MockSchemaRegistryClient) 16 | 17 | // Currently unexported to not pollute the interface 18 | var ( 19 | errInvalidSchemaType = errors.New("invalid schema type. valid values are Avro, Json, or Protobuf") 20 | errSchemaAlreadyRegistered = errors.New("schema already registered") 21 | errSchemaNotFound = errors.New("schema not found") 22 | errSubjectNotFound = errors.New("subject not found") 23 | errNotImplemented = errors.New("not implemented") 24 | ) 25 | 26 | // MockSchemaRegistryClient represents an in-memory SchemaRegistryClient for testing purposes. 27 | type MockSchemaRegistryClient struct { 28 | // schemaRegistryURL is used to form errors 29 | schemaRegistryURL string 30 | 31 | // schemaVersions is a map of subject to a map of versions to the actual schema 32 | schemaVersions map[string]map[int]*Schema 33 | 34 | // schemaIDs is a map of schema ID to the actual schema 35 | schemaIDs map[int]*Schema 36 | 37 | // idCounter is used to generate unique IDs for each schema 38 | idCounter int 39 | 40 | // track whether to use full json codec or regular avro json codec 41 | codecJsonEnabled bool 42 | } 43 | 44 | // CreateMockSchemaRegistryClient initializes a MockSchemaRegistryClient 45 | func CreateMockSchemaRegistryClient(mockURL string) *MockSchemaRegistryClient { 46 | mockClient := &MockSchemaRegistryClient{ 47 | schemaRegistryURL: mockURL, 48 | schemaVersions: map[string]map[int]*Schema{}, 49 | schemaIDs: map[int]*Schema{}, 50 | codecJsonEnabled: false, 51 | } 52 | 53 | return mockClient 54 | } 55 | 56 | // avroRegex is used to remove whitespace from the schema string 57 | var avroRegex = regexp.MustCompile(`\r?\n`) 58 | 59 | // CreateSchema generates a new schema with the given details, references are unused 60 | func (mck *MockSchemaRegistryClient) CreateSchema(subject string, schema string, schemaType SchemaType, _ ...Reference) (*Schema, error) { 61 | mck.idCounter++ 62 | return mck.SetSchema(mck.idCounter, subject, schema, schemaType, -1) 63 | } 64 | 65 | // SetSchema overwrites a schema with the given id. Allows you to set a schema with a specific ID for testing purposes. 66 | // Sets the ID counter to the given id if it is greater than the current counter. Version 67 | // is used to set the version of the schema. If version is -1, the version will be set to the next available version. 68 | func (mck *MockSchemaRegistryClient) SetSchema(id int, subject string, schema string, schemaType SchemaType, version int) (*Schema, error) { 69 | if id > mck.idCounter { 70 | mck.idCounter = id 71 | } 72 | 73 | switch schemaType { 74 | case Avro, Json: 75 | schema = avroRegex.ReplaceAllString(schema, " ") 76 | case Protobuf: 77 | break 78 | default: 79 | return nil, errInvalidSchemaType 80 | } 81 | 82 | resultFromSchemaCache, ok := mck.schemaVersions[subject] 83 | if !ok { 84 | return mck.generateVersion(id, subject, schema, schemaType, version) 85 | } 86 | 87 | // Verify if it's not the same schema as an existing version 88 | for _, existing := range resultFromSchemaCache { 89 | if existing.schema == schema { 90 | posErr := url.Error{ 91 | Op: "POST", 92 | URL: fmt.Sprintf("%s/subjects/%s/versions", mck.schemaRegistryURL, subject), 93 | Err: errSchemaAlreadyRegistered, 94 | } 95 | return nil, &posErr 96 | } 97 | } 98 | 99 | return mck.generateVersion(id, subject, schema, schemaType, version) 100 | } 101 | 102 | // GetSchema Returns a Schema for the given ID 103 | func (mck *MockSchemaRegistryClient) GetSchema(schemaID int) (*Schema, error) { 104 | thisSchema, ok := mck.schemaIDs[schemaID] 105 | if !ok { 106 | posErr := url.Error{ 107 | Op: "GET", 108 | URL: fmt.Sprintf("%s/schemas/ids/%d", mck.schemaRegistryURL, schemaID), 109 | Err: errSchemaNotFound, 110 | } 111 | 112 | return nil, &posErr 113 | } 114 | return thisSchema, nil 115 | } 116 | 117 | // GetLatestSchema Returns the highest ordinal version of a Schema for a given `concrete subject` 118 | func (mck *MockSchemaRegistryClient) GetLatestSchema(subject string) (*Schema, error) { 119 | // Error is never returned 120 | versions, _ := mck.GetSchemaVersions(subject) 121 | if len(versions) == 0 { 122 | return nil, errSchemaNotFound 123 | } 124 | 125 | latestVersion := versions[len(versions)-1] 126 | 127 | // This can't realistically throw an error 128 | thisSchema, _ := mck.GetSchemaByVersion(subject, latestVersion) 129 | 130 | return thisSchema, nil 131 | } 132 | 133 | // GetSchemaVersions Returns the array of versions this subject has previously registered 134 | func (mck *MockSchemaRegistryClient) GetSchemaVersions(subject string) ([]int, error) { 135 | versions := mck.allVersions(subject) 136 | return versions, nil 137 | } 138 | 139 | // GetSubjectVersionsById Returns subject-version pairs identified by the schema ID. 140 | func (mck *MockSchemaRegistryClient) GetSubjectVersionsById(schemaID int) (SubjectVersionResponse, error) { 141 | for subjectName, schemaVersionsMap := range mck.schemaVersions { 142 | for _, schema := range schemaVersionsMap { 143 | if schema.id == schemaID { 144 | subjectVersionResponse := make(SubjectVersionResponse, 0, len(schemaVersionsMap)) 145 | for schemaVersionKey := range schemaVersionsMap { 146 | subjectVersionResponse = append( 147 | subjectVersionResponse, 148 | subjectVersionPair{ 149 | Subject: subjectName, 150 | Version: schemaVersionKey, 151 | }, 152 | ) 153 | } 154 | return subjectVersionResponse, nil 155 | } 156 | } 157 | } 158 | 159 | posErr := url.Error{ 160 | Op: "GET", 161 | URL: fmt.Sprintf("%s/schemas/ids/%d/versions", mck.schemaRegistryURL, schemaID), 162 | Err: errSchemaNotFound, 163 | } 164 | 165 | return nil, &posErr 166 | } 167 | 168 | // GetSchemaByVersion Returns the given Schema according to the passed in subject and version number 169 | func (mck *MockSchemaRegistryClient) GetSchemaByVersion(subject string, version int) (*Schema, error) { 170 | var schema *Schema 171 | schemaVersionMap, ok := mck.schemaVersions[subject] 172 | if !ok { 173 | posErr := url.Error{ 174 | Op: "GET", 175 | URL: mck.schemaRegistryURL + fmt.Sprintf("/subjects/%s/versions/%d", subject, version), 176 | Err: errSubjectNotFound, 177 | } 178 | return nil, &posErr 179 | } 180 | for id, schemaL := range schemaVersionMap { 181 | if id == version { 182 | schema = schemaL 183 | } 184 | } 185 | 186 | if schema == nil { 187 | posErr := url.Error{ 188 | Op: "GET", 189 | URL: mck.schemaRegistryURL + fmt.Sprintf("/subjects/%s/versions/%d", subject, version), 190 | Err: errSchemaNotFound, 191 | } 192 | return nil, &posErr 193 | } 194 | 195 | return schema, nil 196 | } 197 | 198 | // GetSubjects Returns all registered subjects 199 | func (mck *MockSchemaRegistryClient) GetSubjects() ([]string, error) { 200 | allSubjects := make([]string, len(mck.schemaVersions)) 201 | 202 | var count int 203 | for subject := range mck.schemaVersions { 204 | allSubjects[count] = subject 205 | count++ 206 | } 207 | 208 | return allSubjects, nil 209 | } 210 | 211 | // GetSchemaRegistryURL returns the URL of the schema registry 212 | func (mck *MockSchemaRegistryClient) GetSchemaRegistryURL() string { 213 | return mck.schemaRegistryURL 214 | } 215 | 216 | // GetSubjectsIncludingDeleted is not implemented and returns an error 217 | func (mck *MockSchemaRegistryClient) GetSubjectsIncludingDeleted() ([]string, error) { 218 | return nil, errNotImplemented 219 | } 220 | 221 | // DeleteSubject removes given subject from the cache 222 | func (mck *MockSchemaRegistryClient) DeleteSubject(subject string, _ bool) error { 223 | delete(mck.schemaVersions, subject) 224 | return nil 225 | } 226 | 227 | // DeleteSubjectByVersion removes given subject's version from cache 228 | func (mck *MockSchemaRegistryClient) DeleteSubjectByVersion(subject string, version int, _ bool) error { 229 | _, ok := mck.schemaVersions[subject] 230 | if !ok { 231 | posErr := url.Error{ 232 | Op: "DELETE", 233 | URL: fmt.Sprintf("%s/subjects/%s/versions/%d", mck.schemaRegistryURL, subject, version), 234 | Err: errSubjectNotFound, 235 | } 236 | return &posErr 237 | } 238 | 239 | for schemaVersion := range mck.schemaVersions[subject] { 240 | if schemaVersion == version { 241 | delete(mck.schemaVersions[subject], schemaVersion) 242 | return nil 243 | } 244 | } 245 | 246 | posErr := url.Error{ 247 | Op: "GET", 248 | URL: fmt.Sprintf("%s/subjects/%s/versions/%d", mck.schemaRegistryURL, subject, version), 249 | Err: errSchemaNotFound, 250 | } 251 | return &posErr 252 | } 253 | 254 | // ChangeSubjectCompatibilityLevel is not implemented 255 | func (mck *MockSchemaRegistryClient) ChangeSubjectCompatibilityLevel(string, CompatibilityLevel) (*CompatibilityLevel, error) { 256 | return nil, errNotImplemented 257 | } 258 | 259 | // DeleteSubjectCompatibilityLevel is not implemented 260 | func (mck *MockSchemaRegistryClient) DeleteSubjectCompatibilityLevel(string) (*CompatibilityLevel, error) { 261 | return nil, errNotImplemented 262 | } 263 | 264 | // GetGlobalCompatibilityLevel is not implemented 265 | func (mck *MockSchemaRegistryClient) GetGlobalCompatibilityLevel() (*CompatibilityLevel, error) { 266 | return nil, errNotImplemented 267 | } 268 | 269 | // GetCompatibilityLevel is not implemented 270 | func (mck *MockSchemaRegistryClient) GetCompatibilityLevel(string, bool) (*CompatibilityLevel, error) { 271 | return nil, errNotImplemented 272 | } 273 | 274 | // SetCredentials is not implemented 275 | func (mck *MockSchemaRegistryClient) SetCredentials(string, string) { 276 | // Nothing because mockSchemaRegistryClient is actually very vulnerable 277 | } 278 | 279 | // SetBearerToken is not implemented 280 | func (mck *MockSchemaRegistryClient) SetBearerToken(string) { 281 | // Nothing because mockSchemaRegistryClient is actually very vulnerable 282 | } 283 | 284 | // SetTimeout is not implemented 285 | func (mck *MockSchemaRegistryClient) SetTimeout(time.Duration) { 286 | // Nothing because there is no timeout for cache 287 | } 288 | 289 | // CachingEnabled is not implemented 290 | func (mck *MockSchemaRegistryClient) CachingEnabled(bool) { 291 | // Nothing because caching is always enabled, duh 292 | } 293 | 294 | // ResetCache is not implemented 295 | func (mck *MockSchemaRegistryClient) ResetCache() { 296 | // Nothing because there is no lock for cache 297 | } 298 | 299 | // CodecCreationEnabled is not implemented 300 | func (mck *MockSchemaRegistryClient) CodecCreationEnabled(bool) { 301 | // Nothing because codecs do not matter in the inMem storage of schemas 302 | } 303 | 304 | // CodecJsonEnabled is not implemented 305 | func (mck *MockSchemaRegistryClient) CodecJsonEnabled(value bool) { 306 | mck.codecJsonEnabled = value 307 | } 308 | 309 | // IsSchemaCompatible is not implemented 310 | func (mck *MockSchemaRegistryClient) IsSchemaCompatible(string, string, string, SchemaType, ...Reference) (bool, error) { 311 | return false, errNotImplemented 312 | } 313 | 314 | // LookupSchema is not implemented 315 | func (mck *MockSchemaRegistryClient) LookupSchema(string, string, SchemaType, ...Reference) (*Schema, error) { 316 | return nil, errNotImplemented 317 | } 318 | 319 | func (client *MockSchemaRegistryClient) getCodecForSchema(schema string) (*goavro.Codec, error) { 320 | if client.codecJsonEnabled { 321 | return goavro.NewCodecForStandardJSONFull(schema) 322 | } 323 | return goavro.NewCodec(schema) 324 | } 325 | 326 | /* 327 | These classes are written as helpers and therefore, are not exported. 328 | generateVersion will register a new version of the schema passed, it will NOT do any checks 329 | for the schema being already registered, or for the advancing of the schema ID, these are expected to be 330 | handled beforehand by the environment. 331 | allVersions returns an ordered int[] with all versions for a given subject. It does NOT 332 | qualify for key/value subjects, it expects to have a `concrete subject` passed on to do the checks. 333 | */ 334 | 335 | // generateVersion the next version of the schema for the given subject, givenVersion can be set to -1 to generate one. 336 | func (mck *MockSchemaRegistryClient) generateVersion(id int, subject string, schema string, schemaType SchemaType, givenVersion int) (*Schema, error) { 337 | schemaVersionMap := map[int]*Schema{} 338 | currentVersion := 1 339 | 340 | if givenVersion >= 0 { 341 | currentVersion = givenVersion 342 | } 343 | 344 | // if existing versions are found, make sure to load in the version map 345 | if existingMap := mck.schemaVersions[subject]; len(existingMap) > 0 { 346 | schemaVersionMap = existingMap 347 | 348 | // If no version was given, and existing versions are found, +1 the new number from the latest version 349 | if givenVersion <= 0 { 350 | versions := mck.allVersions(subject) 351 | currentVersion = versions[len(versions)-1] + 1 352 | } 353 | } 354 | 355 | // Add a codec, required otherwise Codec() panics and the mock registry is unusable 356 | codec, err := mck.getCodecForSchema(schema) 357 | if err != nil { 358 | return nil, err 359 | } 360 | 361 | schemaToRegister := &Schema{ 362 | id: id, 363 | schema: schema, 364 | version: currentVersion, 365 | codec: codec, 366 | schemaType: &schemaType, 367 | } 368 | 369 | schemaVersionMap[currentVersion] = schemaToRegister 370 | mck.schemaVersions[subject] = schemaVersionMap 371 | mck.schemaIDs[schemaToRegister.id] = schemaToRegister 372 | 373 | return schemaToRegister, nil 374 | } 375 | 376 | // allVersions returns all versions for a given subject, assumes it exists 377 | func (mck *MockSchemaRegistryClient) allVersions(subject string) []int { 378 | var versions []int 379 | result, ok := mck.schemaVersions[subject] 380 | 381 | if ok { 382 | versions = make([]int, len(result)) 383 | 384 | var count int 385 | 386 | for version := range result { 387 | versions[count] = version 388 | count++ 389 | } 390 | } 391 | 392 | sort.Ints(versions) 393 | 394 | return versions 395 | } 396 | -------------------------------------------------------------------------------- /mockSchemaRegistryClient_test.go: -------------------------------------------------------------------------------- 1 | package srclient 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | var ( 10 | avroType = Avro 11 | protobuf = Protobuf 12 | ) 13 | 14 | var ( 15 | testSchema1 = `{"type": "record", "name": "cupcake", "fields": [{"name": "flavor", "type": "string"}]}` 16 | testSchema2 = `{"type": "record", "name": "bakery", "fields": [{"name": "number", "type": "int"}]}` 17 | ) 18 | 19 | func TestMockSchemaRegistryClient_CreateSchema_RegistersSchemaCorrectly(t *testing.T) { 20 | t.Parallel() 21 | tests := map[string]struct { 22 | subject string 23 | schema string 24 | schemaType SchemaType 25 | 26 | currentIdCounter int 27 | existingSchemas map[int]string 28 | 29 | expectedSchema *Schema 30 | }{ 31 | "first avro schema": { 32 | subject: "cupcake", 33 | schema: testSchema1, 34 | schemaType: Avro, 35 | 36 | currentIdCounter: 1, 37 | 38 | expectedSchema: &Schema{ 39 | id: 2, 40 | version: 1, 41 | schemaType: &avroType, 42 | schema: testSchema1, 43 | }, 44 | }, 45 | "second avro schema": { 46 | subject: "bakery", 47 | schema: testSchema2, 48 | schemaType: Avro, 49 | 50 | currentIdCounter: 6, 51 | existingSchemas: map[int]string{ 52 | 10: testSchema1, 53 | }, 54 | 55 | expectedSchema: &Schema{ 56 | id: 7, 57 | version: 11, 58 | schemaType: &avroType, 59 | schema: testSchema2, 60 | }, 61 | }, 62 | "second protobuf schema": { 63 | subject: "bakery", 64 | schema: testSchema2, 65 | schemaType: protobuf, 66 | 67 | currentIdCounter: 23, 68 | existingSchemas: map[int]string{ 69 | 75: testSchema1, 70 | }, 71 | 72 | expectedSchema: &Schema{ 73 | id: 24, 74 | version: 76, 75 | schemaType: &protobuf, 76 | schema: testSchema2, 77 | }, 78 | }, 79 | } 80 | 81 | for name, testData := range tests { 82 | testData := testData 83 | t.Run(name, func(t *testing.T) { 84 | t.Parallel() 85 | // Arrange 86 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 87 | registry.idCounter = testData.currentIdCounter 88 | 89 | // Add existing schemas 90 | for version, schema := range testData.existingSchemas { 91 | _, err := registry.SetSchema(-1, testData.subject, schema, testData.schemaType, version) 92 | if err != nil { 93 | t.Fatal(err) 94 | } 95 | } 96 | 97 | // Act 98 | schema, err := registry.CreateSchema(testData.subject, testData.schema, testData.schemaType) 99 | 100 | // Assert 101 | if assert.NoError(t, err) { 102 | assert.Equal(t, testData.expectedSchema.id, schema.id) 103 | assert.Equal(t, testData.expectedSchema.version, schema.version) 104 | assert.Equal(t, testData.expectedSchema.schemaType, schema.schemaType) 105 | assert.Equal(t, testData.expectedSchema.schema, schema.schema) 106 | 107 | assert.Equal(t, schema, registry.schemaIDs[schema.id]) 108 | assert.Equal(t, schema, registry.schemaVersions[testData.subject][schema.version]) 109 | } 110 | }) 111 | } 112 | } 113 | 114 | func TestMockSchemaRegistryClient_SetSchema_RegistersSchemaCorrectly(t *testing.T) { 115 | t.Parallel() 116 | tests := map[string]struct { 117 | subject string 118 | schema string 119 | schemaType SchemaType 120 | id int 121 | version int 122 | 123 | existingSchemas map[int]string 124 | 125 | expectedSchema *Schema 126 | }{ 127 | "first avro schema": { 128 | subject: "cupcake", 129 | schema: testSchema1, 130 | schemaType: Avro, 131 | id: 52, 132 | version: -1, // Ensures it's generated 133 | 134 | expectedSchema: &Schema{ 135 | id: 52, 136 | version: 1, 137 | schemaType: &avroType, 138 | schema: testSchema1, 139 | }, 140 | }, 141 | "second avro schema": { 142 | subject: "bakery", 143 | schema: testSchema2, 144 | schemaType: Avro, 145 | id: 7, 146 | version: -1, // Ensures it's generated 147 | 148 | existingSchemas: map[int]string{ 149 | 1: testSchema1, 150 | }, 151 | 152 | expectedSchema: &Schema{ 153 | id: 7, 154 | version: 2, 155 | schemaType: &avroType, 156 | schema: testSchema2, 157 | }, 158 | }, 159 | "first protobuf schema": { 160 | subject: "bakery", 161 | schema: testSchema2, 162 | schemaType: Protobuf, 163 | id: 24, 164 | version: -1, // Ensures it's generated 165 | 166 | expectedSchema: &Schema{ 167 | id: 24, 168 | version: 1, 169 | schemaType: &protobuf, 170 | schema: testSchema2, 171 | }, 172 | }, 173 | "with given version": { 174 | subject: "bakery", 175 | schema: testSchema2, 176 | schemaType: Avro, 177 | id: 7, 178 | version: 634, 179 | 180 | expectedSchema: &Schema{ 181 | id: 7, 182 | version: 634, 183 | schemaType: &avroType, 184 | schema: testSchema2, 185 | }, 186 | }, 187 | } 188 | 189 | for name, testData := range tests { 190 | testData := testData 191 | t.Run(name, func(t *testing.T) { 192 | t.Parallel() 193 | // Arrange 194 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 195 | 196 | // Add existing schemas 197 | for version, schema := range testData.existingSchemas { 198 | _, err := registry.SetSchema(-1, testData.subject, schema, testData.schemaType, version) 199 | if err != nil { 200 | t.Fatal(err) 201 | } 202 | } 203 | 204 | // Act 205 | schema, err := registry.SetSchema(testData.id, testData.subject, testData.schema, testData.schemaType, testData.version) 206 | 207 | // Assert 208 | if assert.NoError(t, err) { 209 | assert.Equal(t, testData.expectedSchema.id, schema.id) 210 | assert.Equal(t, testData.expectedSchema.version, schema.version) 211 | assert.Equal(t, testData.expectedSchema.schemaType, schema.schemaType) 212 | assert.Equal(t, testData.expectedSchema.schema, schema.schema) 213 | 214 | assert.Equal(t, schema, registry.schemaIDs[schema.id]) 215 | assert.Equal(t, schema, registry.schemaVersions[testData.subject][schema.version]) 216 | } 217 | }) 218 | } 219 | } 220 | 221 | func TestMockSchemaRegistryClient_SetSchema_CorrectlyUpdatesIdCounter(t *testing.T) { 222 | t.Parallel() 223 | tests := map[string]struct { 224 | currentId int 225 | newId int 226 | expectedId int 227 | }{ 228 | "0 to 1": { 229 | currentId: 0, 230 | newId: 1, 231 | expectedId: 1, 232 | }, 233 | "5 to 19": { 234 | currentId: 5, 235 | newId: 19, 236 | expectedId: 19, 237 | }, 238 | "no change": { 239 | currentId: 9, 240 | newId: 2, 241 | expectedId: 9, 242 | }, 243 | } 244 | 245 | for name, testData := range tests { 246 | testData := testData 247 | t.Run(name, func(t *testing.T) { 248 | t.Parallel() 249 | // Arrange 250 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 251 | registry.idCounter = testData.currentId 252 | 253 | // Act 254 | _, _ = registry.SetSchema(testData.newId, "cupcake", `{}`, Avro, 0) 255 | 256 | // Assert 257 | assert.Equal(t, testData.expectedId, registry.idCounter) 258 | }) 259 | } 260 | } 261 | 262 | func TestMockSchemaRegistryClient_CreateSchema_ReturnsErrorOnInvalidSchemaType(t *testing.T) { 263 | t.Parallel() 264 | // Arrange 265 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 266 | 267 | // Act 268 | schema, err := registry.CreateSchema("", "", "random") 269 | 270 | // Assert 271 | assert.Nil(t, schema) 272 | assert.Equal(t, errInvalidSchemaType, err) 273 | } 274 | 275 | func TestMockSchemaRegistryClient_CreateSchema_ReturnsErrorOnDuplicateSchema(t *testing.T) { 276 | t.Parallel() 277 | // Arrange 278 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 279 | 280 | registry.schemaVersions["cupcake"] = map[int]*Schema{ 281 | 23: { 282 | schema: "{}", 283 | }, 284 | } 285 | 286 | // Act 287 | schema, err := registry.CreateSchema("cupcake", "{}", avroType) 288 | 289 | // Assert 290 | assert.Nil(t, schema) 291 | assert.ErrorIs(t, err, errSchemaAlreadyRegistered) 292 | } 293 | 294 | func TestMockSchemaRegistryClient_GetSchema_ReturnsSchema(t *testing.T) { 295 | t.Parallel() 296 | // Arrange 297 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 298 | 299 | schema := &Schema{} 300 | 301 | registry.schemaIDs = map[int]*Schema{ 302 | 234: schema, 303 | } 304 | 305 | // Act 306 | result, err := registry.GetSchema(234) 307 | 308 | // Assert 309 | assert.Nil(t, err) 310 | assert.Same(t, schema, result) 311 | } 312 | 313 | func TestMockSchemaRegistryClient_GetSchema_ReturnsErrOnNotFound(t *testing.T) { 314 | t.Parallel() 315 | // Arrange 316 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 317 | 318 | // Act 319 | result, err := registry.GetSchema(234) 320 | 321 | // Assert 322 | assert.ErrorIs(t, err, errSchemaNotFound) 323 | 324 | assert.Nil(t, result) 325 | } 326 | 327 | func TestMockSchemaRegistryClient_GetSubjectVersionsById_ReturnsSubjectVersions(t *testing.T) { 328 | t.Parallel() 329 | // Arrange 330 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 331 | registry.schemaVersions["cupcake"] = map[int]*Schema{ 332 | 1: {id: 1, version: 1}, 333 | 2: {id: 2, version: 2}, 334 | 3: {id: 3, version: 3}, 335 | } 336 | registry.schemaVersions["bakery"] = map[int]*Schema{ 337 | 1: {id: 4, version: 1}, 338 | 2: {id: 5, version: 2}, 339 | } 340 | 341 | // Act 342 | result, err := registry.GetSubjectVersionsById(2) 343 | 344 | // Assert 345 | assert.Nil(t, err) 346 | 347 | assert.Len(t, result, 3) 348 | assert.Equal(t, "cupcake", result[0].Subject) 349 | assert.Equal(t, "cupcake", result[1].Subject) 350 | assert.Equal(t, "cupcake", result[2].Subject) 351 | } 352 | 353 | func TestMockSchemaRegistryClient_GetSubjectVersionsById_ReturnsErrOnNotFound(t *testing.T) { 354 | t.Parallel() 355 | // Arrange 356 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 357 | 358 | // Act 359 | result, err := registry.GetSubjectVersionsById(2) 360 | 361 | // Assert 362 | assert.ErrorIs(t, err, errSchemaNotFound) 363 | 364 | assert.Nil(t, result) 365 | } 366 | 367 | func TestMockSchemaRegistryClient_GetLatestSchema_ReturnsErrorOn0SchemaVersions(t *testing.T) { 368 | t.Parallel() 369 | // Arrange 370 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 371 | 372 | // Act 373 | result, err := registry.GetLatestSchema("cupcake") 374 | 375 | // Assert 376 | assert.Nil(t, result) 377 | assert.ErrorIs(t, err, errSchemaNotFound) 378 | } 379 | 380 | func TestMockSchemaRegistryClient_GetLatestSchema_ReturnsExpectedSchema(t *testing.T) { 381 | t.Parallel() 382 | tests := map[string]struct { 383 | subject string 384 | existingSchemas map[int]*Schema 385 | expectedSchema *Schema 386 | }{ 387 | "cupcake": { 388 | subject: "cupcake", 389 | existingSchemas: map[int]*Schema{23: {id: 23}}, 390 | expectedSchema: &Schema{id: 23}, 391 | }, 392 | "bakery": { 393 | subject: "bakery", 394 | existingSchemas: map[int]*Schema{ 395 | 1: {id: 1}, 396 | 2: {id: 2}, 397 | 5: {id: 5}, 398 | }, 399 | expectedSchema: &Schema{id: 5}, 400 | }, 401 | } 402 | 403 | for name, testData := range tests { 404 | testData := testData 405 | t.Run(name, func(t *testing.T) { 406 | t.Parallel() 407 | // Arrange 408 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 409 | registry.schemaVersions[testData.subject] = testData.existingSchemas 410 | 411 | // Act 412 | result, err := registry.GetLatestSchema(testData.subject) 413 | 414 | // Assert 415 | assert.Nil(t, err) 416 | 417 | assert.Equal(t, testData.expectedSchema.id, result.id) 418 | }) 419 | } 420 | } 421 | 422 | func TestMockSchemaRegistryClient_GetSchemaVersions_ReturnsSchemaVersions(t *testing.T) { 423 | t.Parallel() 424 | // Arrange 425 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 426 | registry.schemaVersions["cupcake"] = map[int]*Schema{ 427 | 1: {id: 1}, 428 | 2: {id: 2}, 429 | 3: {id: 3}, 430 | } 431 | 432 | // Act 433 | result, err := registry.GetSchemaVersions("cupcake") 434 | 435 | // Assert 436 | assert.Nil(t, err) 437 | 438 | assert.Equal(t, []int{1, 2, 3}, result) 439 | } 440 | 441 | func TestMockSchemaRegistryClient_GetSchemaByVersion_ReturnsErrorOnSubjectNotFound(t *testing.T) { 442 | t.Parallel() 443 | // Arrange 444 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 445 | 446 | // Act 447 | result, err := registry.GetSchemaByVersion("cupcake", 0) 448 | 449 | // Assert 450 | assert.Nil(t, result) 451 | assert.ErrorIs(t, err, errSubjectNotFound) 452 | } 453 | 454 | func TestMockSchemaRegistryClient_GetSchemaByVersion_ReturnsErrorOnSchemaNotFound(t *testing.T) { 455 | t.Parallel() 456 | // Arrange 457 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 458 | registry.schemaVersions = map[string]map[int]*Schema{ 459 | "cupcake": {}, 460 | } 461 | 462 | // Act 463 | result, err := registry.GetSchemaByVersion("cupcake", 0) 464 | 465 | // Assert 466 | assert.Nil(t, result) 467 | assert.ErrorIs(t, err, errSchemaNotFound) 468 | } 469 | 470 | func TestMockSchemaRegistryClient_GetSchemaByVersion_ReturnsSchema(t *testing.T) { 471 | t.Parallel() 472 | tests := map[string]struct { 473 | subject string 474 | version int 475 | 476 | existingSchemas map[int]*Schema 477 | expectedSchema *Schema 478 | }{ 479 | "cupcake": { 480 | subject: "cupcake", 481 | version: 23, 482 | 483 | existingSchemas: map[int]*Schema{23: {id: 1}}, 484 | expectedSchema: &Schema{id: 1}, 485 | }, 486 | "bakery": { 487 | subject: "bakery", 488 | version: 2, 489 | 490 | existingSchemas: map[int]*Schema{ 491 | 1: {id: 4}, 492 | 2: {id: 5}, 493 | 5: {id: 6}, 494 | }, 495 | expectedSchema: &Schema{id: 5}, 496 | }, 497 | } 498 | 499 | for name, testData := range tests { 500 | testData := testData 501 | t.Run(name, func(t *testing.T) { 502 | t.Parallel() 503 | // Arrange 504 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 505 | registry.schemaVersions[testData.subject] = testData.existingSchemas 506 | 507 | // Act 508 | result, err := registry.GetSchemaByVersion(testData.subject, testData.version) 509 | 510 | // Assert 511 | assert.Nil(t, err) 512 | 513 | assert.Equal(t, testData.expectedSchema.id, result.id) 514 | }) 515 | } 516 | } 517 | 518 | func TestMockSchemaRegistryClient_GetSubjects_ReturnsAllSubjects(t *testing.T) { 519 | t.Parallel() 520 | // Arrange 521 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 522 | registry.schemaVersions = map[string]map[int]*Schema{ 523 | "1": {}, 524 | "2": {}, 525 | "3": {}, 526 | } 527 | 528 | // Act 529 | result, err := registry.GetSubjects() 530 | 531 | // Assert 532 | assert.Nil(t, err) 533 | assert.Contains(t, result, "1") 534 | assert.Contains(t, result, "2") 535 | assert.Contains(t, result, "3") 536 | } 537 | 538 | func TestMockSchemaRegistryClient_GetSubjectsIncludingDeleted_IsNotImplemented(t *testing.T) { 539 | t.Parallel() 540 | // Arrange 541 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 542 | 543 | // Act 544 | result, err := registry.GetSubjectsIncludingDeleted() 545 | 546 | // Assert 547 | assert.Nil(t, result) 548 | assert.ErrorIs(t, err, errNotImplemented) 549 | } 550 | 551 | func TestMockSchemaRegistryClient_DeleteSubject_DeletesSubject(t *testing.T) { 552 | t.Parallel() 553 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 554 | registry.schemaVersions = map[string]map[int]*Schema{ 555 | "b": {}, 556 | } 557 | 558 | // Act 559 | err := registry.DeleteSubject("b", false) 560 | 561 | // Assert 562 | assert.Nil(t, err) 563 | assert.Equal(t, map[string]map[int]*Schema{}, registry.schemaVersions) 564 | } 565 | 566 | func TestMockSchemaRegistryClient_DeleteSubjectByVersion_DeletesSubjectVersion(t *testing.T) { 567 | t.Parallel() 568 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 569 | registry.schemaVersions = map[string]map[int]*Schema{ 570 | "b": { 571 | 1: {id: 1}, 572 | 2: {id: 2}, 573 | 3: {id: 3}, 574 | }, 575 | } 576 | 577 | // Act 578 | err := registry.DeleteSubjectByVersion("b", 2, false) 579 | 580 | // Assert 581 | assert.Nil(t, err) 582 | if assert.NotNil(t, registry.schemaVersions["b"]) { 583 | assert.Nil(t, registry.schemaVersions["b"][2]) 584 | } 585 | } 586 | 587 | func TestMockSchemaRegistryClient_DeleteSubjectByVersion_ReturnsErrorOnSubjectNotFound(t *testing.T) { 588 | t.Parallel() 589 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 590 | 591 | // Act 592 | err := registry.DeleteSubjectByVersion("cupcake", 5, false) 593 | 594 | // Assert 595 | assert.ErrorIs(t, err, errSubjectNotFound) 596 | } 597 | 598 | func TestMockSchemaRegistryClient_DeleteSubjectByVersion_ReturnsErrorOnVersionNotFound(t *testing.T) { 599 | t.Parallel() 600 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 601 | registry.schemaVersions = map[string]map[int]*Schema{ 602 | "cupcake": { 603 | 1: {id: 1}, 604 | 3: {id: 3}, 605 | }, 606 | } 607 | 608 | // Act 609 | err := registry.DeleteSubjectByVersion("cupcake", 5, false) 610 | 611 | // Assert 612 | assert.ErrorIs(t, err, errSchemaNotFound) 613 | } 614 | 615 | func TestMockSchemaRegistryClient_ChangeSubjectCompatibilityLevel_IsNotImplemented(t *testing.T) { 616 | t.Parallel() 617 | // Arrange 618 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 619 | 620 | // Act 621 | result, err := registry.ChangeSubjectCompatibilityLevel("", "") 622 | 623 | // Assert 624 | assert.Nil(t, result) 625 | assert.ErrorIs(t, err, errNotImplemented) 626 | } 627 | 628 | func TestMockSchemaRegistryClient_GetGlobalCompatibilityLevel_IsNotImplemented(t *testing.T) { 629 | t.Parallel() 630 | // Arrange 631 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 632 | 633 | // Act 634 | result, err := registry.GetGlobalCompatibilityLevel() 635 | 636 | // Assert 637 | assert.Nil(t, result) 638 | assert.ErrorIs(t, err, errNotImplemented) 639 | } 640 | 641 | func TestMockSchemaRegistryClient_GetCompatibilityLevel_IsNotImplemented(t *testing.T) { 642 | t.Parallel() 643 | // Arrange 644 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 645 | 646 | // Act 647 | result, err := registry.GetCompatibilityLevel("", false) 648 | 649 | // Assert 650 | assert.Nil(t, result) 651 | assert.ErrorIs(t, err, errNotImplemented) 652 | } 653 | 654 | func TestMockSchemaRegistryClient_IsSchemaCompatible_IsNotImplemented(t *testing.T) { 655 | t.Parallel() 656 | // Arrange 657 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 658 | 659 | // Act 660 | result, err := registry.IsSchemaCompatible("", "", "", "") 661 | 662 | // Assert 663 | assert.False(t, result) 664 | assert.ErrorIs(t, err, errNotImplemented) 665 | } 666 | 667 | func TestMockSchemaRegistryClient_LookupSchema_IsNotImplemented(t *testing.T) { 668 | t.Parallel() 669 | // Arrange 670 | registry := CreateMockSchemaRegistryClient("http://localhost:8081") 671 | 672 | // Act 673 | result, err := registry.LookupSchema("", "", "") 674 | 675 | // Assert 676 | assert.Nil(t, result) 677 | assert.ErrorIs(t, err, errNotImplemented) 678 | } 679 | -------------------------------------------------------------------------------- /schemaRegistryClient_test.go: -------------------------------------------------------------------------------- 1 | package srclient 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "io" 8 | "net/http" 9 | "net/http/httptest" 10 | "testing" 11 | 12 | "github.com/linkedin/goavro/v2" 13 | "github.com/santhosh-tekuri/jsonschema/v5" 14 | "github.com/stretchr/testify/assert" 15 | "github.com/stretchr/testify/require" 16 | ) 17 | 18 | func bodyToString(in io.ReadCloser) string { 19 | result, _ := io.ReadAll(in) 20 | return string(result) 21 | } 22 | 23 | func TestNewSchemaRegistryClient_SetsExpectedOptions(t *testing.T) { 24 | t.Parallel() 25 | 26 | tests := map[string]struct { 27 | registryUrl string 28 | options []Option 29 | 30 | expectedClient *http.Client 31 | expectedSemaphoreWeight int64 32 | }{ 33 | "no options": { 34 | registryUrl: "localhost:8080", 35 | 36 | expectedClient: &http.Client{Timeout: defaultTimeout}, 37 | expectedSemaphoreWeight: defaultSemaphoreWeight, 38 | }, 39 | "custom semaphore weight": { 40 | registryUrl: "local:8080", 41 | options: []Option{WithSemaphoreWeight(32)}, 42 | 43 | expectedClient: &http.Client{Timeout: defaultTimeout}, 44 | expectedSemaphoreWeight: 32, 45 | }, 46 | "custom client": { 47 | registryUrl: "172.0.0.1:8080", 48 | options: []Option{WithClient(&http.Client{Timeout: 32})}, 49 | 50 | expectedClient: &http.Client{Timeout: 32}, 51 | expectedSemaphoreWeight: defaultSemaphoreWeight, 52 | }, 53 | } 54 | 55 | for name, testData := range tests { 56 | testData := testData 57 | t.Run(name, func(t *testing.T) { 58 | t.Parallel() 59 | // Act 60 | result := NewSchemaRegistryClient(testData.registryUrl, testData.options...) 61 | 62 | // Assert 63 | assert.Equal(t, testData.registryUrl, result.schemaRegistryURL) 64 | assert.Equal(t, testData.expectedClient, result.httpClient) 65 | 66 | // We should be able to acquire the semaphore by the size we specified 67 | assert.True(t, result.sem.TryAcquire(testData.expectedSemaphoreWeight)) 68 | result.sem.Release(testData.expectedSemaphoreWeight) 69 | 70 | // Anthing bigger than that weight should fail 71 | assert.False(t, result.sem.TryAcquire(testData.expectedSemaphoreWeight+1)) 72 | }) 73 | } 74 | } 75 | 76 | func TestSchemaRegistryClient_CreateSchemaWithoutReferences(t *testing.T) { 77 | t.Parallel() 78 | 79 | { 80 | server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { 81 | responsePayload := schemaResponse{ 82 | Subject: "test1", 83 | Version: 1, 84 | Schema: "test2", 85 | ID: 1, 86 | } 87 | response, _ := json.Marshal(responsePayload) 88 | switch req.URL.String() { 89 | case "/subjects/test1-value/versions": 90 | 91 | requestPayload := schemaRequest{ 92 | Schema: "test2", 93 | SchemaType: Protobuf.String(), 94 | References: []Reference{}, 95 | } 96 | expected, _ := json.Marshal(requestPayload) 97 | // Test payload 98 | assert.Equal(t, bodyToString(req.Body), string(expected)) 99 | // Send response to be tested 100 | rw.Write(response) 101 | case fmt.Sprintf("/schemas/ids/%d", responsePayload.Version): 102 | // Send response to be tested 103 | rw.Write(response) 104 | default: 105 | assert.Error(t, errors.New("unhandled request")) 106 | } 107 | 108 | })) 109 | 110 | srClient := CreateSchemaRegistryClient(server.URL) 111 | srClient.CodecCreationEnabled(false) 112 | schema, err := srClient.CreateSchema("test1-value", "test2", Protobuf) 113 | 114 | // Test response 115 | assert.NoError(t, err) 116 | assert.Equal(t, schema.id, 1) 117 | assert.Nil(t, schema.codec) 118 | assert.Equal(t, schema.schema, "test2") 119 | assert.Equal(t, schema.version, 1) 120 | } 121 | 122 | { 123 | server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { 124 | responsePayload := schemaResponse{ 125 | Subject: "test1", 126 | Version: 1, 127 | Schema: "test2", 128 | ID: 1, 129 | } 130 | response, _ := json.Marshal(responsePayload) 131 | 132 | switch req.URL.String() { 133 | case "/subjects/test1/versions": 134 | requestPayload := schemaRequest{ 135 | Schema: "test2", 136 | SchemaType: Avro.String(), 137 | References: []Reference{}, 138 | } 139 | expected, _ := json.Marshal(requestPayload) 140 | // Test payload 141 | assert.Equal(t, bodyToString(req.Body), string(expected)) 142 | // Send response to be tested 143 | rw.Write(response) 144 | case fmt.Sprintf("/schemas/ids/%d", responsePayload.Version): 145 | // Send response to be tested 146 | rw.Write(response) 147 | default: 148 | assert.Error(t, errors.New("unhandled request")) 149 | } 150 | 151 | })) 152 | 153 | srClient := CreateSchemaRegistryClient(server.URL) 154 | srClient.CodecCreationEnabled(false) 155 | schema, err := srClient.CreateSchema("test1", "test2", Avro) 156 | 157 | // Test response 158 | assert.NoError(t, err) 159 | assert.Equal(t, schema.id, 1) 160 | assert.Nil(t, schema.codec) 161 | assert.Equal(t, schema.schema, "test2") 162 | assert.Equal(t, schema.version, 1) 163 | } 164 | } 165 | 166 | func TestSchemaRegistryClient_LookupSchemaWithoutReferences(t *testing.T) { 167 | t.Parallel() 168 | var errorCode int 169 | var errorMessage string 170 | { 171 | server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { 172 | responsePayload := schemaResponse{ 173 | Subject: "test1", 174 | Version: 1, 175 | Schema: "test2", 176 | ID: 1, 177 | } 178 | response, _ := json.Marshal(responsePayload) 179 | switch req.URL.String() { 180 | case "/subjects/test1-value": 181 | 182 | requestPayload := schemaRequest{ 183 | Schema: "test2", 184 | SchemaType: Protobuf.String(), 185 | References: []Reference{}, 186 | } 187 | expected, _ := json.Marshal(requestPayload) 188 | // Test payload 189 | assert.Equal(t, bodyToString(req.Body), string(expected)) 190 | // Send response to be tested 191 | rw.Write(response) 192 | default: 193 | assert.Error(t, errors.New("unhandled request")) 194 | } 195 | 196 | })) 197 | 198 | srClient := CreateSchemaRegistryClient(server.URL) 199 | srClient.CodecCreationEnabled(false) 200 | schema, err := srClient.LookupSchema("test1-value", "test2", Protobuf) 201 | 202 | // Test response 203 | assert.NoError(t, err) 204 | assert.Equal(t, schema.id, 1) 205 | assert.Nil(t, schema.codec) 206 | assert.Equal(t, schema.schema, "test2") 207 | assert.Equal(t, schema.version, 1) 208 | } 209 | 210 | { 211 | server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { 212 | responsePayload := schemaResponse{ 213 | Subject: "test1", 214 | Version: 1, 215 | Schema: "test2", 216 | ID: 1, 217 | } 218 | response, _ := json.Marshal(responsePayload) 219 | switch req.URL.String() { 220 | case "/subjects/test1-value": 221 | 222 | requestPayload := schemaRequest{ 223 | Schema: "test2", 224 | SchemaType: Avro.String(), 225 | References: []Reference{}, 226 | } 227 | expected, _ := json.Marshal(requestPayload) 228 | // Test payload 229 | assert.Equal(t, bodyToString(req.Body), string(expected)) 230 | // Send response to be tested 231 | rw.Write(response) 232 | default: 233 | assert.Error(t, errors.New("unhandled request")) 234 | } 235 | 236 | })) 237 | 238 | srClient := CreateSchemaRegistryClient(server.URL) 239 | srClient.CodecCreationEnabled(false) 240 | schema, err := srClient.LookupSchema("test1-value", "test2", Avro) 241 | 242 | // Test response 243 | assert.NoError(t, err) 244 | assert.Equal(t, schema.id, 1) 245 | assert.Nil(t, schema.codec) 246 | assert.Equal(t, schema.schema, "test2") 247 | assert.Equal(t, schema.version, 1) 248 | } 249 | 250 | { 251 | errorCode = 40401 252 | errorMessage = "Subject 'test1' not found" 253 | server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { 254 | var errorResp struct { 255 | ErrorCode int `json:"error_code"` 256 | Message string `json:"message"` 257 | } 258 | errorResp.ErrorCode = errorCode 259 | errorResp.Message = errorMessage 260 | 261 | response, _ := json.Marshal(errorResp) 262 | switch req.URL.String() { 263 | case "/subjects/test1-value": 264 | 265 | requestPayload := schemaRequest{ 266 | Schema: "test2", 267 | SchemaType: Avro.String(), 268 | References: []Reference{}, 269 | } 270 | expected, _ := json.Marshal(requestPayload) 271 | // Test payload 272 | assert.Equal(t, bodyToString(req.Body), string(expected)) 273 | // Send error response to simulate the subject not being found 274 | rw.WriteHeader(http.StatusNotFound) 275 | rw.Write(response) 276 | default: 277 | assert.Error(t, errors.New("unhandled request")) 278 | } 279 | 280 | })) 281 | 282 | srClient := CreateSchemaRegistryClient(server.URL) 283 | srClient.CodecCreationEnabled(false) 284 | _, err := srClient.LookupSchema("test1-value", "test2", Avro) 285 | 286 | // Test response is 404 error 287 | assert.Error(t, err) 288 | castedErr, ok := err.(Error) 289 | assert.True(t, ok, "convert api error to Error struct") 290 | assert.Equal(t, errorCode, castedErr.Code) 291 | assert.Equal(t, errorMessage, castedErr.Message) 292 | } 293 | 294 | { 295 | errorCode = 40403 296 | errorMessage = "Schema not found" 297 | server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { 298 | var errorResp struct { 299 | ErrorCode int `json:"error_code"` 300 | Message string `json:"message"` 301 | } 302 | errorResp.ErrorCode = errorCode 303 | errorResp.Message = errorMessage 304 | 305 | response, _ := json.Marshal(errorResp) 306 | switch req.URL.String() { 307 | case "/subjects/test1-value": 308 | 309 | requestPayload := schemaRequest{ 310 | Schema: "test2", 311 | SchemaType: Avro.String(), 312 | References: []Reference{}, 313 | } 314 | expected, _ := json.Marshal(requestPayload) 315 | // Test payload 316 | assert.Equal(t, bodyToString(req.Body), string(expected)) 317 | // Send error response to simulate the schema not being found 318 | rw.WriteHeader(http.StatusNotFound) 319 | rw.Write(response) 320 | default: 321 | assert.Error(t, errors.New("unhandled request")) 322 | } 323 | 324 | })) 325 | 326 | srClient := CreateSchemaRegistryClient(server.URL) 327 | srClient.CodecCreationEnabled(false) 328 | _, err := srClient.LookupSchema("test1-value", "test2", Avro) 329 | 330 | // Test response is 404 error 331 | assert.Error(t, err) 332 | castedErr, ok := err.(Error) 333 | assert.True(t, ok, "convert api error to Error struct") 334 | assert.Equal(t, errorCode, castedErr.Code) 335 | assert.Equal(t, errorMessage, castedErr.Message) 336 | } 337 | } 338 | 339 | func TestSchemaRegistryClient_GetSchemaByIDWithReferences(t *testing.T) { 340 | t.Parallel() 341 | { 342 | refs := []Reference{ 343 | {Name: "name1", Subject: "subject1", Version: 1}, 344 | {Name: "name2", Subject: "subject2", Version: 2}, 345 | } 346 | 347 | server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { 348 | responsePayload := schemaResponse{ 349 | Subject: "test1", 350 | Version: 1, 351 | Schema: "payload", 352 | ID: 1, 353 | References: refs, 354 | } 355 | response, _ := json.Marshal(responsePayload) 356 | 357 | switch req.URL.String() { 358 | case "/schemas/ids/1": 359 | // Send response to be tested 360 | rw.Write(response) 361 | default: 362 | require.Fail(t, "unhandled request") 363 | } 364 | 365 | })) 366 | 367 | srClient := CreateSchemaRegistryClient(server.URL) 368 | srClient.CodecCreationEnabled(false) 369 | schema, err := srClient.GetSchema(1) 370 | 371 | // Test response 372 | assert.NoError(t, err) 373 | assert.Equal(t, schema.ID(), 1) 374 | assert.Nil(t, schema.codec) 375 | assert.Equal(t, schema.Schema(), "payload") 376 | assert.Equal(t, schema.Version(), 1) 377 | assert.Equal(t, schema.References(), refs) 378 | assert.Equal(t, len(schema.References()), 2) 379 | } 380 | { 381 | server, call := mockServerFromIDWithSchemaResponse(t, 1, schemaResponse{ 382 | Subject: "test1", 383 | Version: 1, 384 | Schema: "payload", 385 | ID: 1, 386 | References: nil, 387 | }) 388 | 389 | srClient := CreateSchemaRegistryClient(server.URL) 390 | srClient.CodecCreationEnabled(false) 391 | schema, err := srClient.GetSchema(1) 392 | 393 | // Test response 394 | assert.NoError(t, err) 395 | 396 | assert.Equal(t, 1, *call) 397 | assert.Equal(t, schema.ID(), 1) 398 | assert.Nil(t, schema.codec) 399 | assert.Equal(t, schema.Schema(), "payload") 400 | assert.Equal(t, schema.Version(), 1) 401 | assert.Nil(t, schema.References()) 402 | assert.Equal(t, len(schema.References()), 0) 403 | } 404 | } 405 | 406 | func TestSchemaRegistryClient_GetSchemaByVersionWithReferences(t *testing.T) { 407 | t.Parallel() 408 | { 409 | refs := []Reference{ 410 | {Name: "name1", Subject: "subject1", Version: 1}, 411 | {Name: "name2", Subject: "subject2", Version: 2}, 412 | } 413 | 414 | server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { 415 | responsePayload := schemaResponse{ 416 | Subject: "test1", 417 | Version: 1, 418 | Schema: "payload", 419 | ID: 1, 420 | References: refs, 421 | } 422 | response, _ := json.Marshal(responsePayload) 423 | 424 | switch req.URL.String() { 425 | case "/subjects/test1/versions/1": 426 | // Send response to be tested 427 | rw.Write(response) 428 | default: 429 | require.Fail(t, "unhandled request") 430 | } 431 | 432 | })) 433 | 434 | srClient := CreateSchemaRegistryClient(server.URL) 435 | srClient.CodecCreationEnabled(false) 436 | schema, err := srClient.GetSchemaByVersion("test1", 1) 437 | 438 | // Test response 439 | assert.NoError(t, err) 440 | assert.Equal(t, schema.ID(), 1) 441 | assert.Nil(t, schema.codec) 442 | assert.Equal(t, schema.Schema(), "payload") 443 | assert.Equal(t, schema.Version(), 1) 444 | assert.Equal(t, schema.References(), refs) 445 | assert.Equal(t, len(schema.References()), 2) 446 | } 447 | { 448 | server, call := mockServerFromSubjectVersionPairWithSchemaResponse(t, "test1", "1", schemaResponse{ 449 | Subject: "test1", 450 | Version: 1, 451 | Schema: "payload", 452 | ID: 1, 453 | References: nil, 454 | }) 455 | 456 | srClient := CreateSchemaRegistryClient(server.URL) 457 | srClient.CodecCreationEnabled(false) 458 | schema, err := srClient.GetSchemaByVersion("test1", 1) 459 | 460 | // Test response 461 | assert.NoError(t, err) 462 | 463 | assert.Equal(t, 1, *call) 464 | assert.Equal(t, schema.ID(), 1) 465 | assert.Nil(t, schema.codec) 466 | assert.Equal(t, schema.Schema(), "payload") 467 | assert.Equal(t, schema.Version(), 1) 468 | assert.Nil(t, schema.References()) 469 | assert.Equal(t, len(schema.References()), 0) 470 | } 471 | } 472 | 473 | func TestSchemaRegistryClient_GetSchemaByVersionReturnsValueFromCache(t *testing.T) { 474 | t.Parallel() 475 | { 476 | server, call := mockServerFromSubjectVersionPairWithSchemaResponse(t, "test1", "1", schemaResponse{ 477 | Subject: "test1", 478 | Version: 1, 479 | Schema: "payload", 480 | ID: 1, 481 | References: nil, 482 | }) 483 | 484 | srClient := CreateSchemaRegistryClient(server.URL) 485 | schema1, err := srClient.GetSchemaByVersion("test1", 1) 486 | 487 | // Test response 488 | assert.NoError(t, err) 489 | 490 | // When called twice 491 | schema2, err := srClient.GetSchemaByVersion("test1", 1) 492 | 493 | assert.NoError(t, err) 494 | assert.Equal(t, 1, *call) 495 | assert.Equal(t, schema1, schema2) 496 | } 497 | } 498 | 499 | func TestSchemaRegistryClient_GetLatestSchemaReturnsValueFromCache(t *testing.T) { 500 | t.Parallel() 501 | server, call := mockServerFromSubjectVersionPairWithSchemaResponse(t, "test1-value", "latest", schemaResponse{ 502 | Subject: "test1", 503 | Version: 1, 504 | Schema: "payload", 505 | ID: 1, 506 | References: nil, 507 | }) 508 | 509 | srClient := CreateSchemaRegistryClient(server.URL) 510 | schema1, err := srClient.GetLatestSchema("test1-value") 511 | 512 | // Test response 513 | assert.NoError(t, err) 514 | 515 | // When called twice 516 | schema2, err := srClient.GetLatestSchema("test1-value") 517 | 518 | assert.NoError(t, err) 519 | assert.Equal(t, 1, *call) 520 | assert.Equal(t, schema1, schema2) 521 | } 522 | 523 | func TestSchemaRegistryClient_GetSchemaType(t *testing.T) { 524 | t.Parallel() 525 | { 526 | expectedSchemaType := Json 527 | server, call := mockServerFromSubjectVersionPairWithSchemaResponse(t, "test1-value", "latest", schemaResponse{ 528 | Subject: "test1", 529 | Version: 1, 530 | Schema: "payload", 531 | SchemaType: &expectedSchemaType, 532 | ID: 1, 533 | References: nil, 534 | }) 535 | 536 | srClient := CreateSchemaRegistryClient(server.URL) 537 | schema, err := srClient.GetLatestSchema("test1-value") 538 | 539 | // Test response 540 | assert.NoError(t, err) 541 | assert.Equal(t, 1, *call) 542 | assert.Equal(t, *schema.SchemaType(), expectedSchemaType) 543 | } 544 | { 545 | server, call := mockServerFromSubjectVersionPairWithSchemaResponse(t, "test1-value", "latest", schemaResponse{ 546 | Subject: "test1", 547 | Version: 1, 548 | Schema: "payload", 549 | ID: 1, 550 | References: nil, 551 | }) 552 | 553 | srClient := CreateSchemaRegistryClient(server.URL) 554 | schema, err := srClient.GetLatestSchema("test1-value") 555 | 556 | // Test response 557 | assert.NoError(t, err) 558 | assert.Equal(t, 1, *call) 559 | assert.Nil(t, schema.SchemaType()) 560 | } 561 | } 562 | 563 | func TestSchemaRegistryClient_GetSubjectVersionsById(t *testing.T) { 564 | t.Parallel() 565 | { 566 | server, call := mockServerWithSubjectVersionResponse(t, fmt.Sprintf("/schemas/ids/%d/versions", 1), SubjectVersionResponse{ 567 | subjectVersionPair{ 568 | Subject: "test1", 569 | Version: 1, 570 | }, 571 | subjectVersionPair{ 572 | Subject: "test1", 573 | Version: 2, 574 | }, 575 | }) 576 | 577 | srClient := CreateSchemaRegistryClient(server.URL) 578 | response, err := srClient.GetSubjectVersionsById(1) 579 | 580 | // Test response 581 | assert.NoError(t, err) 582 | assert.Equal(t, 1, *call) 583 | assert.Len(t, response, 2) 584 | assert.Equal(t, response[0].Subject, "test1") 585 | assert.Equal(t, response[0].Version, 1) 586 | assert.Equal(t, response[1].Subject, "test1") 587 | assert.Equal(t, response[1].Version, 2) 588 | } 589 | } 590 | 591 | func TestSchemaRegistryClient_GetSchemaRegistryURL(t *testing.T) { 592 | t.Parallel() 593 | server, _ := mockServerFromSubjectVersionPairWithSchemaResponse(t, "test1-value", "latest", schemaResponse{ 594 | Subject: "test1", 595 | Version: 1, 596 | Schema: "payload", 597 | ID: 1, 598 | References: nil, 599 | }) 600 | 601 | srClient := CreateSchemaRegistryClient(server.URL) 602 | // when 603 | actual := srClient.GetSchemaRegistryURL() 604 | // then 605 | assert.Equal(t, actual, server.URL) 606 | } 607 | 608 | func TestSchemaRegistryClient_JsonSchemaParses(t *testing.T) { 609 | t.Parallel() 610 | { 611 | server, call := mockServerFromSubjectVersionPairWithSchemaResponse(t, "test1-value", "latest", schemaResponse{ 612 | Subject: "test1", 613 | Version: 1, 614 | Schema: "{\"type\": \"object\",\n\"properties\": {\n \"f1\": {\n \"type\": \"string\"\n }}}", 615 | ID: 1, 616 | References: nil, 617 | }) 618 | 619 | srClient := CreateSchemaRegistryClient(server.URL) 620 | schema1, err := srClient.GetLatestSchema("test1-value") 621 | 622 | // Test valid schema response 623 | assert.NoError(t, err) 624 | assert.Equal(t, 1, *call) 625 | var v interface{} 626 | assert.NotNil(t, schema1.JsonSchema()) 627 | assert.NoError(t, json.Unmarshal([]byte("{\"f1\": \"v1\"}"), &v)) 628 | assert.NoError(t, schema1.JsonSchema().Validate(v)) 629 | } 630 | { 631 | server, call := mockServerFromSubjectVersionPairWithSchemaResponse(t, "test1-value", "latest", schemaResponse{ 632 | Subject: "test1", 633 | Version: 1, 634 | Schema: "payload", 635 | ID: 1, 636 | References: nil, 637 | }) 638 | 639 | srClient := CreateSchemaRegistryClient(server.URL) 640 | schema1, err := srClient.GetLatestSchema("test1-value") 641 | 642 | // Test invalid schema response 643 | assert.NoError(t, err) 644 | assert.Equal(t, 1, *call) 645 | assert.Nil(t, schema1.JsonSchema()) 646 | } 647 | } 648 | 649 | func TestNewSchema(t *testing.T) { 650 | t.Parallel() 651 | const ( 652 | anId = 3 653 | aSchema = "payload" 654 | aSchemaType = Protobuf 655 | aVersion = 2 656 | ) 657 | var ( 658 | reference1 Reference = Reference{ 659 | Name: "reference1", 660 | Subject: "subject1", 661 | Version: 5, 662 | } 663 | reference2 Reference = Reference{ 664 | Name: "reference2", 665 | Subject: "subject2", 666 | Version: 2, 667 | } 668 | references = []Reference{reference1, reference2} 669 | jsonSchema *jsonschema.Schema = &jsonschema.Schema{ 670 | Location: "aLocation", 671 | } 672 | ) 673 | mockCodec, _ := goavro.NewCodec(`"string"`) 674 | { 675 | _, err := NewSchema(anId, "", aSchemaType, aVersion, nil, nil, nil) 676 | assert.EqualError(t, err, "schema cannot be nil") 677 | } 678 | { 679 | schema, err := NewSchema(anId, aSchema, aSchemaType, aVersion, nil, nil, nil) 680 | assert.NoError(t, err) 681 | assert.Equal(t, anId, schema.ID()) 682 | assert.Equal(t, aSchema, schema.Schema()) 683 | assert.Equal(t, aSchemaType, *schema.SchemaType()) 684 | assert.Equal(t, aVersion, schema.Version()) 685 | assert.Nil(t, schema.References()) 686 | assert.Nil(t, schema.Codec()) 687 | assert.Nil(t, schema.JsonSchema()) 688 | 689 | } 690 | { 691 | schema, err := NewSchema( 692 | anId, 693 | aSchema, 694 | aSchemaType, 695 | aVersion, 696 | references, 697 | mockCodec, 698 | jsonSchema, 699 | ) 700 | assert.NoError(t, err) 701 | assert.Equal(t, anId, schema.ID()) 702 | assert.Equal(t, aSchema, schema.Schema()) 703 | assert.Equal(t, aSchemaType, *schema.SchemaType()) 704 | assert.Equal(t, aVersion, schema.Version()) 705 | assert.Equal(t, references, schema.References()) 706 | assert.Equal(t, mockCodec, schema.Codec()) 707 | assert.Equal(t, jsonSchema, schema.JsonSchema()) 708 | } 709 | } 710 | 711 | func TestSchemaRequestMarshal(t *testing.T) { 712 | t.Parallel() 713 | tests := map[string]struct { 714 | schema string 715 | schemaType SchemaType 716 | references []Reference 717 | expected string 718 | }{ 719 | "avro": { 720 | schema: `test2`, 721 | schemaType: Avro, 722 | expected: `{"schema":"test2"}`, 723 | }, 724 | "protobuf": { 725 | schema: `test2`, 726 | schemaType: Protobuf, 727 | expected: `{"schema":"test2","schemaType":"PROTOBUF"}`, 728 | }, 729 | "json": { 730 | schema: `test2`, 731 | schemaType: Json, 732 | expected: `{"schema":"test2","schemaType":"JSON"}`, 733 | }, 734 | "avro-empty-ref": { 735 | schema: `test2`, 736 | schemaType: Avro, 737 | references: make([]Reference, 0), 738 | expected: `{"schema":"test2"}`, 739 | }, 740 | "protobuf-empty-ref": { 741 | schema: `test2`, 742 | schemaType: Protobuf, 743 | references: make([]Reference, 0), 744 | expected: `{"schema":"test2","schemaType":"PROTOBUF"}`, 745 | }, 746 | "json-empty-ref": { 747 | schema: `test2`, 748 | schemaType: Json, 749 | references: make([]Reference, 0), 750 | expected: `{"schema":"test2","schemaType":"JSON"}`, 751 | }, 752 | "avro-ref": { 753 | schema: `test2`, 754 | schemaType: Avro, 755 | references: []Reference{{Name: "name1", Subject: "subject1", Version: 1}}, 756 | expected: `{"schema":"test2","references":[{"name":"name1","subject":"subject1","version":1}]}`, 757 | }, 758 | "protobuf-ref": { 759 | schema: `test2`, 760 | schemaType: Protobuf, 761 | references: []Reference{{Name: "name1", Subject: "subject1", Version: 1}}, 762 | expected: `{"schema":"test2","schemaType":"PROTOBUF","references":[{"name":"name1","subject":"subject1","version":1}]}`, 763 | }, 764 | "json-ref": { 765 | schema: `test2`, 766 | schemaType: Json, 767 | references: []Reference{{Name: "name1", Subject: "subject1", Version: 1}}, 768 | expected: `{"schema":"test2","schemaType":"JSON","references":[{"name":"name1","subject":"subject1","version":1}]}`, 769 | }, 770 | } 771 | 772 | for name, testData := range tests { 773 | testData := testData 774 | t.Run(name, func(t *testing.T) { 775 | t.Parallel() 776 | schemaReq := schemaRequest{ 777 | Schema: testData.schema, 778 | SchemaType: testData.schemaType.String(), 779 | References: testData.references, 780 | } 781 | actual, err := json.Marshal(schemaReq) 782 | assert.NoError(t, err) 783 | assert.Equal(t, testData.expected, string(actual)) 784 | }) 785 | } 786 | } 787 | 788 | func mockServerFromSubjectVersionPairWithSchemaResponse(t *testing.T, subject, version string, schemaResponse schemaResponse) (*httptest.Server, *int) { 789 | return mockServerWithSchemaResponse(t, fmt.Sprintf("/subjects/%s/versions/%s", subject, version), schemaResponse) 790 | } 791 | 792 | func mockServerFromIDWithSchemaResponse(t *testing.T, id int, schemaResponse schemaResponse) (*httptest.Server, *int) { 793 | return mockServerWithSchemaResponse(t, fmt.Sprintf("/schemas/ids/%d", id), schemaResponse) 794 | } 795 | 796 | func mockServerWithSchemaResponse(t *testing.T, url string, schemaResponse schemaResponse) (*httptest.Server, *int) { 797 | var count int 798 | return httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { 799 | count++ 800 | response, _ := json.Marshal(schemaResponse) 801 | 802 | switch req.URL.String() { 803 | case url: 804 | // Send response to be tested 805 | _, err := rw.Write(response) 806 | if err != nil { 807 | t.Errorf("could not write response %s", err) 808 | } 809 | default: 810 | require.Fail(t, "unhandled request") 811 | } 812 | })), &count 813 | } 814 | 815 | func mockServerWithSubjectVersionResponse(t *testing.T, url string, subjectVersionResponse SubjectVersionResponse) (*httptest.Server, *int) { 816 | var count int 817 | return httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { 818 | count++ 819 | response, _ := json.Marshal(subjectVersionResponse) 820 | 821 | switch req.URL.String() { 822 | case url: 823 | // Send response to be tested 824 | _, err := rw.Write(response) 825 | if err != nil { 826 | t.Errorf("could not write response %s", err) 827 | } 828 | default: 829 | require.Fail(t, "unhandled request") 830 | } 831 | })), &count 832 | } 833 | -------------------------------------------------------------------------------- /schemaRegistryClient.go: -------------------------------------------------------------------------------- 1 | package srclient 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "encoding/json" 7 | "errors" 8 | "fmt" 9 | "io" 10 | "io/ioutil" 11 | "net/http" 12 | "net/url" 13 | "regexp" 14 | "strconv" 15 | "strings" 16 | "sync" 17 | "time" 18 | 19 | "github.com/linkedin/goavro/v2" 20 | "github.com/santhosh-tekuri/jsonschema/v5" 21 | "golang.org/x/sync/semaphore" 22 | ) 23 | 24 | const defaultSemaphoreWeight int64 = 16 25 | const defaultTimeout = 5 * time.Second 26 | 27 | // ISchemaRegistryClient provides the 28 | // definition of the operations that 29 | // this Schema Registry client provides. 30 | type ISchemaRegistryClient interface { 31 | GetGlobalCompatibilityLevel() (*CompatibilityLevel, error) 32 | GetCompatibilityLevel(subject string, defaultToGlobal bool) (*CompatibilityLevel, error) 33 | GetSubjects() ([]string, error) 34 | GetSubjectsIncludingDeleted() ([]string, error) 35 | GetSchema(schemaID int) (*Schema, error) 36 | GetLatestSchema(subject string) (*Schema, error) 37 | GetSchemaVersions(subject string) ([]int, error) 38 | GetSubjectVersionsById(schemaID int) (SubjectVersionResponse, error) 39 | GetSchemaByVersion(subject string, version int) (*Schema, error) 40 | GetSchemaRegistryURL() string 41 | CreateSchema(subject string, schema string, schemaType SchemaType, references ...Reference) (*Schema, error) 42 | LookupSchema(subject string, schema string, schemaType SchemaType, references ...Reference) (*Schema, error) 43 | ChangeSubjectCompatibilityLevel(subject string, compatibility CompatibilityLevel) (*CompatibilityLevel, error) 44 | DeleteSubjectCompatibilityLevel(subject string) (*CompatibilityLevel, error) 45 | DeleteSubject(subject string, permanent bool) error 46 | DeleteSubjectByVersion(subject string, version int, permanent bool) error 47 | SetCredentials(username string, password string) 48 | SetBearerToken(token string) 49 | SetTimeout(timeout time.Duration) 50 | CachingEnabled(value bool) 51 | ResetCache() 52 | CodecCreationEnabled(value bool) 53 | CodecJsonEnabled(value bool) 54 | IsSchemaCompatible(subject, schema, version string, schemaType SchemaType, references ...Reference) (bool, error) 55 | } 56 | 57 | // SchemaRegistryClient allows interactions with 58 | // Schema Registry over HTTP. Applications using 59 | // this client can retrieve data about schemas, 60 | // which in turn can be used to serialize and 61 | // deserialize data. 62 | type SchemaRegistryClient struct { 63 | schemaRegistryURL string 64 | credentials *credentials 65 | httpClient *http.Client 66 | cachingEnabled bool 67 | cachingEnabledLock sync.RWMutex 68 | codecCreationEnabled bool 69 | codecAsFullJson bool 70 | codecCreationEnabledLock sync.RWMutex 71 | idSchemaCache map[int]*Schema 72 | idSchemaCacheLock sync.RWMutex 73 | subjectSchemaCache map[string]*Schema 74 | subjectSchemaCacheLock sync.RWMutex 75 | sem *semaphore.Weighted 76 | preReqFn func(req *http.Request) error 77 | } 78 | 79 | var _ ISchemaRegistryClient = new(SchemaRegistryClient) 80 | 81 | type SchemaType string 82 | 83 | const ( 84 | Protobuf SchemaType = "PROTOBUF" 85 | Avro SchemaType = "AVRO" 86 | Json SchemaType = "JSON" 87 | ) 88 | 89 | func (s SchemaType) String() string { 90 | // Avro is the default schemaType. 91 | // Returning "" omits schemaType from the schemaRequest JSON for compatibility with older API versions. 92 | if s == Avro { 93 | return "" 94 | } 95 | 96 | return string(s) 97 | } 98 | 99 | type CompatibilityLevel string 100 | 101 | const ( 102 | None CompatibilityLevel = "NONE" 103 | Backward CompatibilityLevel = "BACKWARD" 104 | BackwardTransitive CompatibilityLevel = "BACKWARD_TRANSITIVE" 105 | Forward CompatibilityLevel = "FORWARD" 106 | ForwardTransitive CompatibilityLevel = "FORWARD_TRANSITIVE" 107 | Full CompatibilityLevel = "FULL" 108 | FullTransitive CompatibilityLevel = "FULL_TRANSITIVE" 109 | ) 110 | 111 | func (s CompatibilityLevel) String() string { 112 | return string(s) 113 | } 114 | 115 | // Reference references use the import statement of Protobuf and 116 | // the $ref field of JSON Schema. They are defined by the name 117 | // of the import or $ref and the associated subject in the registry. 118 | type Reference struct { 119 | Name string `json:"name"` 120 | Subject string `json:"subject"` 121 | Version int `json:"version"` 122 | } 123 | 124 | // Schema is a data structure that holds all 125 | // the relevant information about schemas. 126 | type Schema struct { 127 | id int 128 | schema string 129 | schemaType *SchemaType 130 | version int 131 | references []Reference 132 | codec *goavro.Codec 133 | jsonSchema *jsonschema.Schema 134 | } 135 | 136 | // credentials can have either username AND password 137 | // OR a bearerToken, it cannot have both forms of authentication 138 | type credentials struct { 139 | // Username and Password for Schema Basic Auth 140 | username string 141 | password string 142 | 143 | // Bearer Authorization token 144 | bearerToken string 145 | } 146 | 147 | type schemaRequest struct { 148 | Schema string `json:"schema"` 149 | SchemaType string `json:"schemaType,omitempty"` 150 | References []Reference `json:"references,omitempty"` 151 | } 152 | 153 | type schemaResponse struct { 154 | Subject string `json:"subject"` 155 | Version int `json:"version"` 156 | Schema string `json:"schema"` 157 | SchemaType *SchemaType `json:"schemaType"` 158 | ID int `json:"id"` 159 | References []Reference `json:"references"` 160 | } 161 | 162 | type isCompatibleResponse struct { 163 | IsCompatible bool `json:"is_compatible"` 164 | } 165 | 166 | type configResponse struct { 167 | CompatibilityLevel CompatibilityLevel `json:"compatibilityLevel"` 168 | } 169 | 170 | type configChangeRequest struct { 171 | CompatibilityLevel CompatibilityLevel `json:"compatibility"` 172 | } 173 | 174 | type configChangeResponse configChangeRequest 175 | 176 | type SubjectVersionResponse []subjectVersionPair 177 | 178 | type subjectVersionPair struct { 179 | Subject string `json:"subject"` 180 | Version int `json:"version"` 181 | } 182 | 183 | const ( 184 | schemaByID = "/schemas/ids/%d" 185 | subjectVersionsByID = "/schemas/ids/%d/versions" 186 | subjectBySubject = "/subjects/%s" 187 | subjectVersions = "/subjects/%s/versions" 188 | subjectByVersion = "/subjects/%s/versions/%s" 189 | subjects = "/subjects" 190 | config = "/config" 191 | configBySubject = "/config/%s" 192 | contentType = "application/vnd.schemaregistry.v1+json" 193 | ) 194 | 195 | // Option serves as an input for NewSchemaRegistryClient 196 | type Option func(*SchemaRegistryClient) 197 | 198 | // WithClient is used in NewSchemaRegistryClient to override the default client 199 | func WithClient(client *http.Client) Option { 200 | return func(registryConfig *SchemaRegistryClient) { 201 | registryConfig.httpClient = client 202 | } 203 | } 204 | 205 | // WithSemaphoreWeight is used in NewSchemaRegistryClient to override the default semaphoreWeight 206 | func WithSemaphoreWeight(semaphoreWeight int64) Option { 207 | return func(client *SchemaRegistryClient) { 208 | client.sem = semaphore.NewWeighted(semaphoreWeight) 209 | } 210 | } 211 | 212 | func WithPreReqFn(preReq func(req *http.Request) error) Option { 213 | return func(registryConfig *SchemaRegistryClient) { 214 | registryConfig.preReqFn = preReq 215 | } 216 | } 217 | 218 | // NewSchemaRegistryClient creates a client that allows 219 | // interactions with Schema Registry over HTTP. Applications 220 | // using this client can retrieve data about schemas, which 221 | // in turn can be used to serialize and deserialize records. 222 | func NewSchemaRegistryClient(schemaRegistryURL string, options ...Option) *SchemaRegistryClient { 223 | client := &SchemaRegistryClient{ 224 | schemaRegistryURL: schemaRegistryURL, 225 | httpClient: &http.Client{Timeout: defaultTimeout}, 226 | cachingEnabled: true, 227 | codecCreationEnabled: false, 228 | idSchemaCache: make(map[int]*Schema), 229 | subjectSchemaCache: make(map[string]*Schema), 230 | sem: semaphore.NewWeighted(defaultSemaphoreWeight), 231 | } 232 | for _, option := range options { 233 | option(client) 234 | } 235 | 236 | return client 237 | } 238 | 239 | // CreateSchemaRegistryClient creates a client that allows 240 | // interactions with Schema Registry over HTTP. Applications 241 | // using this client can retrieve data about schemas, which 242 | // in turn can be used to serialize and deserialize records. 243 | // Deprecated: Prefer NewSchemaRegistryClient(schemaRegistryURL) 244 | func CreateSchemaRegistryClient(schemaRegistryURL string) *SchemaRegistryClient { 245 | return NewSchemaRegistryClient(schemaRegistryURL) 246 | } 247 | 248 | // CreateSchemaRegistryClientWithOptions provides the ability to pass the http.Client to be used, as well as the semaphoreWeight for concurrent requests 249 | // Deprecated: Prefer NewSchemaRegistryClient(schemaRegistryURL, WithClient(*http.Client), WithSemaphoreWeight(int64)) 250 | func CreateSchemaRegistryClientWithOptions(schemaRegistryURL string, client *http.Client, semaphoreWeight int) *SchemaRegistryClient { 251 | return NewSchemaRegistryClient(schemaRegistryURL, WithClient(client), WithSemaphoreWeight(int64(semaphoreWeight))) 252 | } 253 | 254 | // GetSchemaRegistryURL returns the URL of the Schema Registry 255 | func (client *SchemaRegistryClient) GetSchemaRegistryURL() string { 256 | return client.schemaRegistryURL 257 | } 258 | 259 | // ResetCache resets the schema caches to be able to get updated schemas. 260 | func (client *SchemaRegistryClient) ResetCache() { 261 | client.idSchemaCacheLock.Lock() 262 | client.subjectSchemaCacheLock.Lock() 263 | client.idSchemaCache = make(map[int]*Schema) 264 | client.subjectSchemaCache = make(map[string]*Schema) 265 | client.idSchemaCacheLock.Unlock() 266 | client.subjectSchemaCacheLock.Unlock() 267 | } 268 | 269 | // GetSchema gets the schema associated with the given id. 270 | func (client *SchemaRegistryClient) GetSchema(schemaID int) (*Schema, error) { 271 | 272 | if client.getCachingEnabled() { 273 | client.idSchemaCacheLock.RLock() 274 | cachedSchema := client.idSchemaCache[schemaID] 275 | client.idSchemaCacheLock.RUnlock() 276 | if cachedSchema != nil { 277 | return cachedSchema, nil 278 | } 279 | } 280 | 281 | resp, err := client.httpRequest("GET", fmt.Sprintf(schemaByID, schemaID), nil) 282 | if err != nil { 283 | return nil, err 284 | } 285 | 286 | var schemaResp = new(schemaResponse) 287 | if err := json.Unmarshal(resp, &schemaResp); err != nil { 288 | return nil, err 289 | } 290 | 291 | var codec *goavro.Codec 292 | if client.getCodecCreationEnabled() { 293 | codec, err = client.getCodecForSchema(schemaResp.Schema) 294 | if err != nil { 295 | return nil, err 296 | } 297 | } 298 | 299 | var schema = &Schema{ 300 | id: schemaID, 301 | schema: schemaResp.Schema, 302 | version: schemaResp.Version, 303 | schemaType: schemaResp.SchemaType, 304 | references: schemaResp.References, 305 | codec: codec, 306 | } 307 | 308 | if client.getCachingEnabled() { 309 | client.idSchemaCacheLock.Lock() 310 | client.idSchemaCache[schemaID] = schema 311 | client.idSchemaCacheLock.Unlock() 312 | } 313 | 314 | return schema, nil 315 | } 316 | 317 | // GetLatestSchema gets the schema associated with the given subject. 318 | // The schema returned contains the last version for that subject. 319 | func (client *SchemaRegistryClient) GetLatestSchema(subject string) (*Schema, error) { 320 | return client.getVersion(subject, "latest") 321 | } 322 | 323 | // GetSubjectVersionsById returns subject-version pairs identified by the schema ID. 324 | func (client *SchemaRegistryClient) GetSubjectVersionsById(schemaID int) (SubjectVersionResponse, error) { 325 | resp, err := client.httpRequest("GET", fmt.Sprintf(subjectVersionsByID, schemaID), nil) 326 | if err != nil { 327 | return nil, err 328 | } 329 | 330 | var response = new(SubjectVersionResponse) 331 | err = json.Unmarshal(resp, &response) 332 | if err != nil { 333 | return nil, err 334 | } 335 | 336 | return *response, nil 337 | } 338 | 339 | // GetSchemaVersions returns a list of versions from a given subject. 340 | func (client *SchemaRegistryClient) GetSchemaVersions(subject string) ([]int, error) { 341 | resp, err := client.httpRequest("GET", fmt.Sprintf(subjectVersions, url.PathEscape(subject)), nil) 342 | if err != nil { 343 | return nil, err 344 | } 345 | 346 | var versions = []int{} 347 | err = json.Unmarshal(resp, &versions) 348 | if err != nil { 349 | return nil, err 350 | } 351 | 352 | return versions, nil 353 | } 354 | 355 | // ChangeSubjectCompatibilityLevel changes the compatibility level of the subject. 356 | func (client *SchemaRegistryClient) ChangeSubjectCompatibilityLevel(subject string, compatibility CompatibilityLevel) (*CompatibilityLevel, error) { 357 | configChangeReq := configChangeRequest{CompatibilityLevel: compatibility} 358 | configChangeReqBytes, err := json.Marshal(configChangeReq) 359 | if err != nil { 360 | return nil, err 361 | } 362 | payload := bytes.NewBuffer(configChangeReqBytes) 363 | 364 | resp, err := client.httpRequest("PUT", fmt.Sprintf(configBySubject, url.PathEscape(subject)), payload) 365 | if err != nil { 366 | return nil, err 367 | } 368 | 369 | var cfgChangeResp = new(configChangeResponse) 370 | err = json.Unmarshal(resp, &cfgChangeResp) 371 | if err != nil { 372 | return nil, err 373 | } 374 | 375 | return &cfgChangeResp.CompatibilityLevel, nil 376 | } 377 | 378 | // DeleteSubjectCompatibilityLevel deletes subject-level compatibility level config and reverts to the global default. 379 | func (client *SchemaRegistryClient) DeleteSubjectCompatibilityLevel(subject string) (*CompatibilityLevel, error) { 380 | resp, err := client.httpRequest("DELETE", fmt.Sprintf(configBySubject, url.QueryEscape(subject)), nil) 381 | if err != nil { 382 | return nil, err 383 | } 384 | var cfgChangeResp = new(configChangeResponse) 385 | err = json.Unmarshal(resp, &cfgChangeResp) 386 | if err != nil { 387 | return nil, err 388 | } 389 | return &cfgChangeResp.CompatibilityLevel, nil 390 | } 391 | 392 | // GetGlobalCompatibilityLevel returns the global compatibility level of the registry. 393 | func (client *SchemaRegistryClient) GetGlobalCompatibilityLevel() (*CompatibilityLevel, error) { 394 | resp, err := client.httpRequest("GET", config, nil) 395 | if err != nil { 396 | return nil, err 397 | } 398 | 399 | var configResponse = new(configResponse) 400 | err = json.Unmarshal(resp, &configResponse) 401 | if err != nil { 402 | return nil, err 403 | } 404 | 405 | return &configResponse.CompatibilityLevel, nil 406 | } 407 | 408 | // GetCompatibilityLevel returns the compatibility level of the subject. 409 | // If defaultToGlobal is set to true and no compatibility level is set on the subject, the global compatibility level is returned. 410 | func (client *SchemaRegistryClient) GetCompatibilityLevel(subject string, defaultToGlobal bool) (*CompatibilityLevel, error) { 411 | resp, err := client.httpRequest("GET", fmt.Sprintf(configBySubject+"?defaultToGlobal=%t", url.PathEscape(subject), defaultToGlobal), nil) 412 | if err != nil { 413 | return nil, err 414 | } 415 | 416 | var configResponse = new(configResponse) 417 | if err := json.Unmarshal(resp, &configResponse); err != nil { 418 | return nil, err 419 | } 420 | 421 | return &configResponse.CompatibilityLevel, nil 422 | } 423 | 424 | // GetSubjects returns a list of all subjects in the registry 425 | func (client *SchemaRegistryClient) GetSubjects() ([]string, error) { 426 | resp, err := client.httpRequest("GET", subjects, nil) 427 | if err != nil { 428 | return nil, err 429 | } 430 | 431 | var allSubjects []string 432 | if err = json.Unmarshal(resp, &allSubjects); err != nil { 433 | return nil, err 434 | } 435 | 436 | return allSubjects, nil 437 | } 438 | 439 | // GetSubjectsIncludingDeleted returns a list of all subjects in the registry including those which have been soft deleted 440 | func (client *SchemaRegistryClient) GetSubjectsIncludingDeleted() ([]string, error) { 441 | resp, err := client.httpRequest("GET", subjects+"?deleted=true", nil) 442 | if err != nil { 443 | return nil, err 444 | } 445 | var allSubjects []string 446 | if err = json.Unmarshal(resp, &allSubjects); err != nil { 447 | return nil, err 448 | } 449 | 450 | return allSubjects, nil 451 | } 452 | 453 | // GetSchemaByVersion gets the schema associated with the given subject. 454 | // The schema returned contains the version specified as a parameter. 455 | func (client *SchemaRegistryClient) GetSchemaByVersion(subject string, version int) (*Schema, error) { 456 | return client.getVersion(subject, strconv.Itoa(version)) 457 | } 458 | 459 | // CreateSchema creates a new schema in Schema Registry and associates 460 | // with the subject provided. It returns the newly created schema with 461 | // all its associated information. 462 | func (client *SchemaRegistryClient) CreateSchema(subject string, schema string, 463 | schemaType SchemaType, references ...Reference) (*Schema, error) { 464 | switch schemaType { 465 | case Avro, Json: 466 | compiledRegex := regexp.MustCompile(`\r?\n`) 467 | schema = compiledRegex.ReplaceAllString(schema, " ") 468 | case Protobuf: 469 | break 470 | default: 471 | return nil, fmt.Errorf("invalid schema type. valid values are Avro, Json, or Protobuf") 472 | } 473 | 474 | if references == nil { 475 | references = make([]Reference, 0) 476 | } 477 | 478 | schemaReq := schemaRequest{Schema: schema, SchemaType: schemaType.String(), References: references} 479 | schemaBytes, err := json.Marshal(schemaReq) 480 | if err != nil { 481 | return nil, err 482 | } 483 | payload := bytes.NewBuffer(schemaBytes) 484 | resp, err := client.httpRequest("POST", fmt.Sprintf(subjectVersions, url.PathEscape(subject)), payload) 485 | if err != nil { 486 | return nil, err 487 | } 488 | 489 | schemaResp := new(schemaResponse) 490 | err = json.Unmarshal(resp, &schemaResp) 491 | if err != nil { 492 | return nil, err 493 | } 494 | 495 | newSchema, err := client.GetSchema(schemaResp.ID) 496 | if err != nil { 497 | return nil, err 498 | } 499 | 500 | if client.getCachingEnabled() { 501 | 502 | // Update the subject-2-schema cache 503 | cacheKey := cacheKey(subject, 504 | strconv.Itoa(newSchema.version)) 505 | client.subjectSchemaCacheLock.Lock() 506 | client.subjectSchemaCache[cacheKey] = newSchema 507 | client.subjectSchemaCacheLock.Unlock() 508 | 509 | // Update the id-2-schema cache 510 | client.idSchemaCacheLock.Lock() 511 | client.idSchemaCache[newSchema.id] = newSchema 512 | client.idSchemaCacheLock.Unlock() 513 | 514 | } 515 | 516 | return newSchema, nil 517 | } 518 | 519 | // LookupSchema looks up the schema by subject and schema string. If it finds the schema it returns it with all its associated information. 520 | func (client *SchemaRegistryClient) LookupSchema(subject string, schema string, schemaType SchemaType, references ...Reference) (*Schema, error) { 521 | switch schemaType { 522 | case Avro, Json: 523 | compiledRegex := regexp.MustCompile(`\r?\n`) 524 | schema = compiledRegex.ReplaceAllString(schema, " ") 525 | case Protobuf: 526 | break 527 | default: 528 | return nil, fmt.Errorf("invalid schema type. valid values are Avro, Json, or Protobuf") 529 | } 530 | 531 | if references == nil { 532 | references = make([]Reference, 0) 533 | } 534 | 535 | schemaReq := schemaRequest{Schema: schema, SchemaType: schemaType.String(), References: references} 536 | schemaBytes, err := json.Marshal(schemaReq) 537 | if err != nil { 538 | return nil, err 539 | } 540 | payload := bytes.NewBuffer(schemaBytes) 541 | resp, err := client.httpRequest("POST", fmt.Sprintf(subjectBySubject, url.PathEscape(subject)), payload) 542 | if err != nil { 543 | return nil, err 544 | } 545 | 546 | schemaResp := new(schemaResponse) 547 | err = json.Unmarshal(resp, &schemaResp) 548 | if err != nil { 549 | return nil, err 550 | } 551 | 552 | var codec *goavro.Codec 553 | if client.getCodecCreationEnabled() && schemaType == Avro { 554 | codec, err = client.getCodecForSchema(schemaResp.Schema) 555 | if err != nil { 556 | return nil, err 557 | } 558 | } 559 | var gotSchema = &Schema{ 560 | id: schemaResp.ID, 561 | schema: schemaResp.Schema, 562 | schemaType: schemaResp.SchemaType, 563 | version: schemaResp.Version, 564 | references: schemaResp.References, 565 | codec: codec, 566 | } 567 | 568 | if client.getCachingEnabled() { 569 | 570 | // Update the subject-2-schema cache 571 | cacheKey := cacheKey(subject, 572 | strconv.Itoa(gotSchema.version)) 573 | client.subjectSchemaCacheLock.Lock() 574 | client.subjectSchemaCache[cacheKey] = gotSchema 575 | client.subjectSchemaCacheLock.Unlock() 576 | 577 | // Update the id-2-schema cache 578 | client.idSchemaCacheLock.Lock() 579 | client.idSchemaCache[gotSchema.id] = gotSchema 580 | client.idSchemaCacheLock.Unlock() 581 | 582 | } 583 | 584 | return gotSchema, nil 585 | } 586 | 587 | // IsSchemaCompatible checks if the given schema is compatible with the given subject and version 588 | // valid versions are versionID and "latest" 589 | func (client *SchemaRegistryClient) IsSchemaCompatible(subject, schema, version string, schemaType SchemaType, references ...Reference) (bool, error) { 590 | if references == nil { 591 | references = make([]Reference, 0) 592 | } 593 | 594 | schemaReq := schemaRequest{Schema: schema, SchemaType: schemaType.String(), References: references} 595 | schemaReqBytes, err := json.Marshal(schemaReq) 596 | if err != nil { 597 | return false, err 598 | } 599 | payload := bytes.NewBuffer(schemaReqBytes) 600 | 601 | url := fmt.Sprintf("/compatibility/subjects/%s/versions/%s", url.PathEscape(subject), version) 602 | resp, err := client.httpRequest("POST", url, payload) 603 | if err != nil { 604 | return false, err 605 | } 606 | 607 | compatibilityResponse := new(isCompatibleResponse) 608 | err = json.Unmarshal(resp, compatibilityResponse) 609 | if err != nil { 610 | return false, err 611 | } 612 | 613 | return compatibilityResponse.IsCompatible, nil 614 | } 615 | 616 | // DeleteSubject deletes 617 | func (client *SchemaRegistryClient) DeleteSubject(subject string, permanent bool) error { 618 | uri := "/subjects/" + url.PathEscape(subject) 619 | 620 | if permanent { 621 | _, err := client.httpRequest("DELETE", uri+"?permanent=true", nil) 622 | return err 623 | } 624 | 625 | _, err := client.httpRequest("DELETE", uri, nil) 626 | return err 627 | } 628 | 629 | // DeleteSubjectByVersion deletes the version of the scheme 630 | func (client *SchemaRegistryClient) DeleteSubjectByVersion(subject string, version int, permanent bool) error { 631 | uri := fmt.Sprintf(subjectByVersion, url.PathEscape(subject), strconv.Itoa(version)) 632 | _, err := client.httpRequest("DELETE", uri, nil) 633 | if err != nil || !permanent { 634 | return err 635 | } 636 | 637 | uri += "?permanent=true" 638 | _, err = client.httpRequest("DELETE", uri, nil) 639 | return err 640 | } 641 | 642 | // SetCredentials allows users to set credentials to be 643 | // used with Schema Registry, for scenarios when Schema 644 | // Registry has authentication enabled. 645 | func (client *SchemaRegistryClient) SetCredentials(username string, password string) { 646 | if len(username) > 0 && len(password) > 0 { 647 | credentials := credentials{username: username, password: password, bearerToken: ""} 648 | client.credentials = &credentials 649 | } 650 | } 651 | 652 | // SetBearerToken allows users to add a Bearer Token 653 | // http header with calls to Schema Registry 654 | // The BearerToken will override Schema Registry credentials 655 | func (client *SchemaRegistryClient) SetBearerToken(token string) { 656 | if len(token) > 0 { 657 | credentials := credentials{username: "", password: "", bearerToken: token} 658 | client.credentials = &credentials 659 | } 660 | } 661 | 662 | // SetTimeout allows the client to be reconfigured about 663 | // how much time internal HTTP requests will take until 664 | // they timeout. FYI, It defaults to five seconds. 665 | func (client *SchemaRegistryClient) SetTimeout(timeout time.Duration) { 666 | client.httpClient.Timeout = timeout 667 | } 668 | 669 | // CachingEnabled allows the client to cache any values 670 | // that have been returned, which may speed up performance 671 | // if these values rarely changes. 672 | func (client *SchemaRegistryClient) CachingEnabled(value bool) { 673 | client.cachingEnabledLock.Lock() 674 | defer client.cachingEnabledLock.Unlock() 675 | client.cachingEnabled = value 676 | } 677 | 678 | // CodecCreationEnabled allows the application to enable/disable 679 | // the automatic creation of codec's when schemas are returned. 680 | func (client *SchemaRegistryClient) CodecCreationEnabled(value bool) { 681 | client.codecCreationEnabledLock.Lock() 682 | defer client.codecCreationEnabledLock.Unlock() 683 | client.codecCreationEnabled = value 684 | } 685 | 686 | // CodecJsonEnabled allows the application to create codec, 687 | // which will serialize/deserialize data as standard json. 688 | // Should be used with CodecCreationEnabled, otherwise it will be ignored. 689 | func (client *SchemaRegistryClient) CodecJsonEnabled(value bool) { 690 | client.codecCreationEnabledLock.Lock() 691 | defer client.codecCreationEnabledLock.Unlock() 692 | client.codecAsFullJson = value 693 | } 694 | 695 | func (client *SchemaRegistryClient) getVersion(subject string, version string) (*Schema, error) { 696 | 697 | if client.getCachingEnabled() { 698 | cacheKey := cacheKey(subject, version) 699 | client.subjectSchemaCacheLock.RLock() 700 | cachedResult := client.subjectSchemaCache[cacheKey] 701 | client.subjectSchemaCacheLock.RUnlock() 702 | if cachedResult != nil { 703 | return cachedResult, nil 704 | } 705 | } 706 | 707 | resp, err := client.httpRequest("GET", fmt.Sprintf(subjectByVersion, url.PathEscape(subject), version), nil) 708 | if err != nil { 709 | return nil, err 710 | } 711 | 712 | schemaResp := new(schemaResponse) 713 | err = json.Unmarshal(resp, &schemaResp) 714 | if err != nil { 715 | return nil, err 716 | } 717 | var codec *goavro.Codec 718 | if client.getCodecCreationEnabled() { 719 | codec, err = client.getCodecForSchema(schemaResp.Schema) 720 | if err != nil { 721 | return nil, err 722 | } 723 | } 724 | var schema = &Schema{ 725 | id: schemaResp.ID, 726 | schema: schemaResp.Schema, 727 | schemaType: schemaResp.SchemaType, 728 | version: schemaResp.Version, 729 | references: schemaResp.References, 730 | codec: codec, 731 | } 732 | 733 | if client.getCachingEnabled() { 734 | 735 | // Update the subject-2-schema cache 736 | cacheKey := cacheKey(subject, version) 737 | client.subjectSchemaCacheLock.Lock() 738 | client.subjectSchemaCache[cacheKey] = schema 739 | client.subjectSchemaCacheLock.Unlock() 740 | 741 | // Update the id-2-schema cache 742 | client.idSchemaCacheLock.Lock() 743 | client.idSchemaCache[schema.id] = schema 744 | client.idSchemaCacheLock.Unlock() 745 | 746 | } 747 | 748 | return schema, nil 749 | } 750 | 751 | func (client *SchemaRegistryClient) httpRequest(method, uri string, payload io.Reader) ([]byte, error) { 752 | 753 | url := fmt.Sprintf("%s%s", client.schemaRegistryURL, uri) 754 | req, err := http.NewRequest(method, url, payload) 755 | if err != nil { 756 | return nil, err 757 | } 758 | if client.credentials != nil { 759 | if len(client.credentials.username) > 0 && len(client.credentials.password) > 0 { 760 | req.SetBasicAuth(client.credentials.username, client.credentials.password) 761 | } else if len(client.credentials.bearerToken) > 0 { 762 | if strings.Contains(strings.ToLower(uri), "confluent.cloud") { 763 | req.Header.Add("Authorization", "Basic "+client.credentials.bearerToken) 764 | } else { 765 | req.Header.Add("Authorization", "Bearer "+client.credentials.bearerToken) 766 | } 767 | } 768 | } 769 | req.Header.Set("Content-Type", contentType) 770 | 771 | if client.preReqFn != nil { 772 | if err := client.preReqFn(req); err != nil { 773 | return nil, fmt.Errorf("pre-request function failed: %w", err) 774 | } 775 | } 776 | 777 | client.sem.Acquire(context.Background(), 1) 778 | defer client.sem.Release(1) 779 | resp, err := client.httpClient.Do(req) 780 | if err != nil { 781 | return nil, err 782 | } 783 | 784 | if resp != nil { 785 | defer resp.Body.Close() 786 | } 787 | if resp.StatusCode < 200 || resp.StatusCode > 299 { 788 | return nil, createError(resp) 789 | } 790 | 791 | return ioutil.ReadAll(resp.Body) 792 | } 793 | 794 | func (client *SchemaRegistryClient) getCachingEnabled() bool { 795 | client.cachingEnabledLock.RLock() 796 | defer client.cachingEnabledLock.RUnlock() 797 | return client.cachingEnabled 798 | } 799 | 800 | func (client *SchemaRegistryClient) getCodecCreationEnabled() bool { 801 | client.codecCreationEnabledLock.RLock() 802 | defer client.codecCreationEnabledLock.RUnlock() 803 | return client.codecCreationEnabled 804 | } 805 | 806 | func (client *SchemaRegistryClient) getCodecForSchema(schema string) (*goavro.Codec, error) { 807 | client.codecCreationEnabledLock.RLock() 808 | defer client.codecCreationEnabledLock.RUnlock() 809 | if client.codecAsFullJson { 810 | return goavro.NewCodecForStandardJSONFull(schema) 811 | } 812 | return goavro.NewCodec(schema) 813 | } 814 | 815 | // NewSchema instantiates a new Schema struct. 816 | func NewSchema( 817 | id int, 818 | schema string, 819 | schemaType SchemaType, 820 | version int, 821 | references []Reference, 822 | codec *goavro.Codec, 823 | jsonSchema *jsonschema.Schema, 824 | ) (*Schema, error) { 825 | if schema == "" { 826 | return nil, errors.New("schema cannot be nil") 827 | } 828 | return &Schema{ 829 | id: id, 830 | schema: schema, 831 | schemaType: &schemaType, 832 | version: version, 833 | references: references, 834 | codec: codec, 835 | jsonSchema: jsonSchema, 836 | }, nil 837 | } 838 | 839 | // ID ensures access to ID 840 | func (schema *Schema) ID() int { 841 | return schema.id 842 | } 843 | 844 | // Schema ensures access to Schema 845 | func (schema *Schema) Schema() string { 846 | return schema.schema 847 | } 848 | 849 | // SchemaType ensures access to SchemaType 850 | func (schema *Schema) SchemaType() *SchemaType { 851 | return schema.schemaType 852 | } 853 | 854 | // Version ensures access to Version 855 | func (schema *Schema) Version() int { 856 | return schema.version 857 | } 858 | 859 | // References ensures access to References 860 | func (schema *Schema) References() []Reference { 861 | return schema.references 862 | } 863 | 864 | // Codec ensures access to Codec 865 | // Will try to initialize a new one if it hasn't been initialized before 866 | // Will return nil if it can't initialize a codec from the schema 867 | func (schema *Schema) Codec() *goavro.Codec { 868 | if schema.codec == nil { 869 | codec, err := goavro.NewCodec(schema.Schema()) 870 | if err == nil { 871 | schema.codec = codec 872 | } 873 | } 874 | return schema.codec 875 | } 876 | 877 | // JsonSchema ensures access to JsonSchema 878 | // Will try to initialize a new one if it hasn't been initialized before 879 | // Will return nil if it can't initialize a json schema from the schema 880 | func (schema *Schema) JsonSchema() *jsonschema.Schema { 881 | if schema.jsonSchema == nil { 882 | jsonSchema, err := jsonschema.CompileString("schema.json", schema.Schema()) 883 | if err == nil { 884 | schema.jsonSchema = jsonSchema 885 | } 886 | } 887 | return schema.jsonSchema 888 | } 889 | 890 | func cacheKey(subject string, version string) string { 891 | return fmt.Sprintf("%s-%s", subject, version) 892 | } 893 | 894 | // Error implements error, encodes HTTP errors from Schema Registry. 895 | type Error struct { 896 | Code int `json:"error_code"` 897 | Message string `json:"message"` 898 | str *bytes.Buffer 899 | } 900 | 901 | func (e Error) Error() string { 902 | return e.str.String() 903 | } 904 | 905 | func createError(resp *http.Response) error { 906 | err := Error{str: bytes.NewBuffer(make([]byte, 0))} 907 | decoder := json.NewDecoder(io.TeeReader(resp.Body, err.str)) 908 | marshalErr := decoder.Decode(&err) 909 | if marshalErr != nil { 910 | return fmt.Errorf("%s", resp.Status) 911 | } 912 | 913 | return err 914 | } 915 | --------------------------------------------------------------------------------