package protocol import ( "encoding/json" "reflect" "sort" "strings" "sync" ) // ProtocolVersion is the integer wire protocol this build speaks. Ordering // between peers compares this integer; build strings are for naming only and are // never parsed or sorted to infer ordering. const ProtocolVersion = 1 // MaxSupportedProtocol is the newest server protocol this client can interpret. // A server reporting a higher value is refused rather than silently misread. const MaxSupportedProtocol = ProtocolVersion var ( knownFieldsOnce sync.Once knownFields map[string]struct{} ) // KnownFields returns the set of top-level JSON keys protocol.Message models, // derived once from the struct tags and cached. The map is read-only. func KnownFields() map[string]struct{} { knownFieldsOnce.Do(func() { knownFields = map[string]struct{}{} message := reflect.TypeOf(Message{}) for index := 0; index < message.NumField(); index++ { name := strings.Split(message.Field(index).Tag.Get("json"), ",")[0] if name == "" || name == "-" { continue } knownFields[name] = struct{}{} } }) return knownFields } // UnknownFields returns the sorted top-level JSON keys in data that protocol.Message // does not model. It performs one bounded map decode plus O(1) set lookups, so a // forward-compatible frame is never a per-frame reflection walk. A frame that is // not a JSON object (or cannot be parsed) reports no unknown fields. func UnknownFields(data []byte) []string { var raw map[string]json.RawMessage if err := json.Unmarshal(data, &raw); err != nil { return nil } known := KnownFields() var unknown []string for key := range raw { if _, ok := known[key]; !ok { unknown = append(unknown, key) } } sort.Strings(unknown) return unknown }