├── LICENSE ├── README.md ├── go.mod ├── go.sum ├── main.go ├── sample.json ├── schema_registry.go └── schema_registry_test.go /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NATS Schema Registry Example 2 | 3 | This example shows how to build a NATS Schema Registry using the NATS Service API and NATS KV Store. 4 | 5 | This example allows you to register a schema, and then essentially become a "Gatekeeper" for your JetStream streams. 6 | 7 | ## Usage 8 | 9 | Run a NATS server with JetStream enabled: 10 | ```bash 11 | nats-server -js 12 | ``` 13 | 14 | Run the example against a local NATS server: 15 | ```bash 16 | go run . 17 | ``` 18 | 19 | Register a schema (you can use the sample.json in this repo): 20 | ```bash 21 | cat sample.json | nats req '$SCHEMA.REGISTER.my_cool_schema' 22 | ``` 23 | 24 | Publish a message to a stream that uses the schema: 25 | 26 | ```bash 27 | nats req '$SCHEMA.VALIDATE.numbers.foobar' 1 # This should work, and the message is passed to numbers.foobar 28 | nats req '$SCHEMA.VALIDATE.numbers.foobar' abc # This should fail 29 | ``` 30 | 31 | 32 | ## TODO 33 | I wrote this while on a stream, there is still plenty to add or improve: 34 | - [ ] Use natscontext to support different server addresses and credentials 35 | - [ ] Add a way to list all registered schemas 36 | - [ ] Respond with more appropriate error codes that are JetStream compatible when validation fails 37 | - [ ] Support a more graceful shutdown 38 | - [ ] Make KV backing configurable 39 | - [ ] Support more than just jsonschema 40 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/codegangsta/schema_registry 2 | 3 | go 1.20 4 | 5 | require ( 6 | github.com/iancoleman/orderedmap v0.0.0-20190318233801-ac98e3ecb4b0 // indirect 7 | github.com/invopop/jsonschema v0.7.0 // indirect 8 | github.com/nats-io/nats.go v1.24.0 // indirect 9 | github.com/nats-io/nkeys v0.3.0 // indirect 10 | github.com/nats-io/nuid v1.0.1 // indirect 11 | github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect 12 | github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect 13 | github.com/xeipuuv/gojsonschema v1.2.0 // indirect 14 | golang.org/x/crypto v0.5.0 // indirect 15 | ) 16 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 2 | github.com/iancoleman/orderedmap v0.0.0-20190318233801-ac98e3ecb4b0 h1:i462o439ZjprVSFSZLZxcsoAe592sZB1rci2Z8j4wdk= 3 | github.com/iancoleman/orderedmap v0.0.0-20190318233801-ac98e3ecb4b0/go.mod h1:N0Wam8K1arqPXNWjMo21EXnBPOPp36vB07FNRdD2geA= 4 | github.com/invopop/jsonschema v0.7.0 h1:2vgQcBz1n256N+FpX3Jq7Y17AjYt46Ig3zIWyy770So= 5 | github.com/invopop/jsonschema v0.7.0/go.mod h1:O9uiLokuu0+MGFlyiaqtWxwqJm41/+8Nj0lD7A36YH0= 6 | github.com/nats-io/nats.go v1.24.0 h1:CRiD8L5GOQu/DcfkmgBcTTIQORMwizF+rPk6T0RaHVQ= 7 | github.com/nats-io/nats.go v1.24.0/go.mod h1:dVQF+BK3SzUZpwyzHedXsvH3EO38aVKuOPkkHlv5hXA= 8 | github.com/nats-io/nkeys v0.3.0 h1:cgM5tL53EvYRU+2YLXIK0G2mJtK12Ft9oeooSZMA2G8= 9 | github.com/nats-io/nkeys v0.3.0/go.mod h1:gvUNGjVcM2IPr5rCsRsC6Wb3Hr2CQAm08dsxtV6A5y4= 10 | github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= 11 | github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= 12 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 13 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 14 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 15 | github.com/stretchr/testify v1.3.1-0.20190311161405-34c6fa2dc709/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 16 | github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= 17 | github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= 18 | github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= 19 | github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= 20 | github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= 21 | github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= 22 | golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= 23 | golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE= 24 | golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU= 25 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 26 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 27 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 28 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 29 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 30 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | "runtime" 7 | 8 | "github.com/invopop/jsonschema" 9 | "github.com/nats-io/nats.go" 10 | "github.com/nats-io/nats.go/micro" 11 | ) 12 | 13 | func main() { 14 | err := Connect() 15 | if err != nil { 16 | panic(err) 17 | } 18 | 19 | runtime.Goexit() 20 | } 21 | 22 | func Connect() error { 23 | nc, err := nats.Connect(nats.DefaultURL) 24 | if err != nil { 25 | return err 26 | } 27 | 28 | js, err := nc.JetStream() 29 | if err != nil { 30 | return err 31 | } 32 | 33 | kv, err := js.CreateKeyValue(&nats.KeyValueConfig{ 34 | Bucket: "schema_registry", 35 | Description: "Register and manages schemas.", 36 | History: 10, 37 | }) 38 | if err != nil { 39 | return err 40 | } 41 | 42 | // Create our schema registry 43 | registry := NewSchemaRegistry(kv, nc) 44 | err = registry.Watch(context.Background()) 45 | if err != nil { 46 | return err 47 | } 48 | 49 | svc, err := micro.AddService(nc, micro.Config{ 50 | Name: "schema_registry", 51 | Description: "Register and manage schemas. Validate payloads against schemas.", 52 | Version: "0.0.1", 53 | }) 54 | if err != nil { 55 | return err 56 | } 57 | 58 | reflector := jsonschema.Reflector{ 59 | DoNotReference: true, 60 | } 61 | 62 | schema, err := reflector.Reflect(&Schema{}).MarshalJSON() 63 | if err != nil { 64 | return err 65 | } 66 | 67 | svc.AddEndpoint("register", micro.HandlerFunc(registry.RegisterSchema), 68 | micro.WithEndpointSubject("$SCHEMA.REGISTER.*"), 69 | micro.WithEndpointSchema(µ.Schema{ 70 | Request: string(schema), 71 | Response: string(schema), 72 | })) 73 | 74 | svc.AddEndpoint("get", micro.HandlerFunc(registry.GetSchema), 75 | micro.WithEndpointSubject("$SCHEMA.GET.*"), 76 | micro.WithEndpointSchema(µ.Schema{ 77 | Response: string(schema), 78 | })) 79 | 80 | svc.AddEndpoint("unregister", micro.HandlerFunc(registry.UnregisterSchema), 81 | micro.WithEndpointSubject("$SCHEMA.UNREGISTER.*")) 82 | 83 | svc.AddEndpoint("update", micro.HandlerFunc(registry.UpdateSchema), 84 | micro.WithEndpointSubject("$SCHEMA.UPDATE.*"), 85 | micro.WithEndpointSchema(µ.Schema{ 86 | Request: string(schema), 87 | Response: string(schema), 88 | })) 89 | 90 | svc.AddEndpoint("validate", micro.HandlerFunc(func(r micro.Request) {}), 91 | micro.WithEndpointSubject("$SCHEMA.VALIDATE.>")) 92 | 93 | // Schema validation needs to have more access to the NATS message, namely the reply subject, 94 | // so we need to use a raw subscription instead of the service API. 95 | _, err = nc.QueueSubscribe("$SCHEMA.VALIDATE.>", "schema_registry", registry.ValidatePayload) 96 | if err != nil { 97 | return err 98 | } 99 | 100 | log.Println("Connected to NATS for schema_registry", nc.ConnectedUrl()) 101 | 102 | return nil 103 | } 104 | -------------------------------------------------------------------------------- /sample.json: -------------------------------------------------------------------------------- 1 | { 2 | "subject": "numbers.>", 3 | "type": "jsonschema", 4 | "body": "{ \"type\": \"integer\" }" 5 | } 6 | -------------------------------------------------------------------------------- /schema_registry.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "log" 8 | "strings" 9 | "sync" 10 | 11 | "github.com/nats-io/nats.go" 12 | "github.com/nats-io/nats.go/micro" 13 | "github.com/xeipuuv/gojsonschema" 14 | ) 15 | 16 | type Schema struct { 17 | Name string `json:"name"` 18 | Subject string `json:"subject"` 19 | Revision uint64 `json:"revision,omitempty"` 20 | Type string `json:"type"` 21 | Body string `json:"body"` 22 | } 23 | 24 | type SchemaRegistry struct { 25 | // Contain nats kv and have methods for schema crud and validation 26 | kv nats.KeyValue 27 | nc *nats.Conn 28 | 29 | schemas map[string]Schema 30 | schemasMu sync.RWMutex 31 | } 32 | 33 | func NewSchemaRegistry(kv nats.KeyValue, nc *nats.Conn) *SchemaRegistry { 34 | return &SchemaRegistry{ 35 | nc: nc, 36 | kv: kv, 37 | schemas: map[string]Schema{}, 38 | } 39 | } 40 | 41 | // Watch watches the kv store for changes and adds them to a 42 | // local cache of schemas. It runs this in a goroutine and takes a context for 43 | // cancelation. 44 | func (reg *SchemaRegistry) Watch(c context.Context) error { 45 | // Watch the kv store for changes 46 | watcher, err := reg.kv.WatchAll() 47 | if err != nil { 48 | return err 49 | } 50 | 51 | // Run this in a goroutine 52 | go func() { 53 | for { 54 | select { 55 | case <-c.Done(): 56 | return 57 | case entry, ok := <-watcher.Updates(): 58 | if !ok { 59 | return 60 | } 61 | if entry == nil { 62 | log.Println("Loaded initial schemas") 63 | continue 64 | } 65 | 66 | var schema Schema 67 | err := json.Unmarshal(entry.Value(), &schema) 68 | if err != nil { 69 | log.Printf("error unmarshaling schema: %v", err) 70 | continue 71 | } 72 | schema.Revision = entry.Revision() 73 | 74 | reg.schemasMu.Lock() 75 | reg.schemas[schema.Name] = schema 76 | reg.schemasMu.Unlock() 77 | log.Printf("Loaded schema: %q revision %d", schema.Name, schema.Revision) 78 | } 79 | } 80 | }() 81 | 82 | return nil 83 | } 84 | 85 | // Register subject: $SCHEMA.REGISTER. 86 | func (reg *SchemaRegistry) RegisterSchema(r micro.Request) { 87 | var schema Schema 88 | err := json.Unmarshal(r.Data(), &schema) 89 | if err != nil { 90 | r.Error("400", err.Error(), nil) 91 | return 92 | } 93 | 94 | // Pull out the schema name from the subject 95 | parts := strings.Split(r.Subject(), ".") 96 | schema.Name = parts[len(parts)-1] 97 | 98 | // Put the schema in the kv store 99 | data, err := json.Marshal(schema) 100 | if err != nil { 101 | r.Error("400", err.Error(), nil) 102 | return 103 | } 104 | 105 | rev, err := reg.kv.Create(schema.Name, data) 106 | if err != nil { 107 | r.Error("500", err.Error(), nil) 108 | return 109 | } 110 | 111 | schema.Revision = rev 112 | r.RespondJSON(schema) 113 | } 114 | 115 | // Register subject: $SCHEMA.UNREGISTER. 116 | func (reg *SchemaRegistry) UnregisterSchema(r micro.Request) { 117 | parts := strings.Split(r.Subject(), ".") 118 | name := parts[len(parts)-1] 119 | 120 | // remove the schema from the kv store 121 | err := reg.kv.Delete(name) 122 | if err != nil { 123 | r.Error("500", err.Error(), nil) 124 | return 125 | } 126 | 127 | r.Respond(nil) 128 | } 129 | 130 | // Get subject: $SCHEMA.GET. 131 | func (reg *SchemaRegistry) GetSchema(r micro.Request) { 132 | parts := strings.Split(r.Subject(), ".") 133 | name := parts[len(parts)-1] 134 | 135 | // Get the schema from the kv store 136 | schema, ok := reg.schemas[name] 137 | if !ok { 138 | r.Error("404", "Not found", nil) 139 | return 140 | } 141 | r.RespondJSON(schema) 142 | } 143 | 144 | // Update subject: $SCHEMA.UPDATE. 145 | func (reg *SchemaRegistry) UpdateSchema(r micro.Request) { 146 | var schema Schema 147 | err := json.Unmarshal(r.Data(), &schema) 148 | if err != nil { 149 | r.Error("400", err.Error(), nil) 150 | return 151 | } 152 | 153 | // Pull out the schema name from the subject 154 | parts := strings.Split(r.Subject(), ".") 155 | schema.Name = parts[len(parts)-1] 156 | 157 | // Put the schema in the kv store 158 | data, err := json.Marshal(schema) 159 | if err != nil { 160 | r.Error("400", err.Error(), nil) 161 | return 162 | } 163 | 164 | rev, err := reg.kv.Put(schema.Name, data) 165 | if err != nil { 166 | r.Error("500", err.Error(), nil) 167 | return 168 | } 169 | 170 | schema.Revision = rev 171 | r.RespondJSON(schema) 172 | } 173 | 174 | // Validate subject: $SCHEMA.VALIDATE. 175 | func (reg *SchemaRegistry) ValidatePayload(m *nats.Msg) { 176 | reg.schemasMu.RLock() 177 | defer reg.schemasMu.RUnlock() 178 | 179 | // Pull out the subject from the request subject 180 | parts := strings.Split(m.Subject, ".") 181 | subject := strings.Join(parts[2:], ".") 182 | 183 | // find a schema that matches the subject 184 | for _, schema := range reg.schemas { 185 | if !SubjectsMatch(subject, schema.Subject) { 186 | continue 187 | } 188 | 189 | // validate the payload 190 | err := reg.validate(m.Data, schema) 191 | if err != nil { 192 | m.Respond([]byte(err.Error())) 193 | return 194 | } 195 | 196 | msg := nats.NewMsg(subject) 197 | msg.Reply = m.Reply 198 | msg.Data = m.Data 199 | msg.Header = m.Header 200 | if msg.Header == nil { 201 | msg.Header = nats.Header{} 202 | } 203 | msg.Header.Set("Schema-Name", schema.Name) 204 | msg.Header.Set("Schema-Revision", fmt.Sprintf("%d", schema.Revision)) 205 | msg.Header.Set("Schema-Subject", schema.Subject) 206 | msg.Header.Set("Schema-Type", schema.Type) 207 | msg.Header.Set("Schema-Validated", "true") 208 | err = reg.nc.PublishMsg(msg) 209 | 210 | if err != nil { 211 | log.Printf("error publishing message: %v", err) 212 | m.Respond([]byte(err.Error())) 213 | return 214 | } 215 | 216 | return 217 | } 218 | 219 | errorMessage := fmt.Sprintf("could not find schema for subject %q", subject) 220 | fmt.Println(errorMessage) 221 | m.Respond([]byte(errorMessage)) 222 | } 223 | 224 | func (reg *SchemaRegistry) validate(data []byte, schema Schema) error { 225 | dataBody := gojsonschema.NewStringLoader(string(data)) 226 | schemaBody := gojsonschema.NewStringLoader(schema.Body) 227 | 228 | result, err := gojsonschema.Validate(schemaBody, dataBody) 229 | if err != nil { 230 | return err 231 | } 232 | if !result.Valid() { 233 | var errors []string 234 | for _, desc := range result.Errors() { 235 | errors = append(errors, desc.String()) 236 | } 237 | return fmt.Errorf("invalid payload: %v", strings.Join(errors, ", ")) 238 | } 239 | 240 | return nil 241 | } 242 | 243 | // SubjectsMatch returns true if the literal subject matches the wildcard subject. 244 | // Subjects are case sensitive and can contain tokens delimited by the dot (.) character. 245 | // The wildcard subject can contain the * wildcard. 246 | // Examples: foo.bar, foo.bar.baz, foo.*.baz 247 | // Wildcards can also have a catch all suffix of > 248 | // Examples: foo.>, foo.bar.> 249 | func SubjectsMatch(literal string, wildcard string) bool { 250 | if literal == wildcard { 251 | return true 252 | } 253 | 254 | lparts := strings.Split(literal, ".") 255 | wparts := strings.Split(wildcard, ".") 256 | 257 | for i, wpart := range wparts { 258 | if len(lparts) <= i { 259 | return false 260 | } 261 | if wpart == "*" { 262 | continue 263 | } 264 | if wpart == ">" { 265 | return true 266 | } 267 | if lparts[i] != wpart { 268 | return false 269 | } 270 | } 271 | 272 | return true 273 | } 274 | -------------------------------------------------------------------------------- /schema_registry_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "testing" 4 | 5 | func TestSubjectsMatch(t *testing.T) { 6 | // Test that the subjects match 7 | if SubjectsMatch("foo.bar", "foo.bar") == false { 8 | t.Errorf("Expected subject to match") 9 | } 10 | if SubjectsMatch("foo.bar", "foo.*") == false { 11 | t.Errorf("Expected subject to match") 12 | } 13 | if SubjectsMatch("foo.bar", "foo.>") == false { 14 | t.Errorf("Expected subject to match") 15 | } 16 | if SubjectsMatch("foo.bar", ">") == false { 17 | t.Errorf("Expected subject to match") 18 | } 19 | 20 | // Test that the subjects do not match 21 | if SubjectsMatch("foo.bar", "bar.>") == true { 22 | t.Errorf("Expected subject to not match") 23 | } 24 | } 25 | --------------------------------------------------------------------------------