query.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. package runtime
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "net/url"
  6. "reflect"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/golang/protobuf/proto"
  12. "github.com/grpc-ecosystem/grpc-gateway/utilities"
  13. "google.golang.org/grpc/grpclog"
  14. )
  15. // PopulateQueryParameters populates "values" into "msg".
  16. // A value is ignored if its key starts with one of the elements in "filter".
  17. func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error {
  18. for key, values := range values {
  19. re, err := regexp.Compile("^(.*)\\[(.*)\\]$")
  20. if err != nil {
  21. return err
  22. }
  23. match := re.FindStringSubmatch(key)
  24. if len(match) == 3 {
  25. key = match[1]
  26. values = append([]string{match[2]}, values...)
  27. }
  28. fieldPath := strings.Split(key, ".")
  29. if filter.HasCommonPrefix(fieldPath) {
  30. continue
  31. }
  32. if err := populateFieldValueFromPath(msg, fieldPath, values); err != nil {
  33. return err
  34. }
  35. }
  36. return nil
  37. }
  38. // PopulateFieldFromPath sets a value in a nested Protobuf structure.
  39. // It instantiates missing protobuf fields as it goes.
  40. func PopulateFieldFromPath(msg proto.Message, fieldPathString string, value string) error {
  41. fieldPath := strings.Split(fieldPathString, ".")
  42. return populateFieldValueFromPath(msg, fieldPath, []string{value})
  43. }
  44. func populateFieldValueFromPath(msg proto.Message, fieldPath []string, values []string) error {
  45. m := reflect.ValueOf(msg)
  46. if m.Kind() != reflect.Ptr {
  47. return fmt.Errorf("unexpected type %T: %v", msg, msg)
  48. }
  49. var props *proto.Properties
  50. m = m.Elem()
  51. for i, fieldName := range fieldPath {
  52. isLast := i == len(fieldPath)-1
  53. if !isLast && m.Kind() != reflect.Struct {
  54. return fmt.Errorf("non-aggregate type in the mid of path: %s", strings.Join(fieldPath, "."))
  55. }
  56. var f reflect.Value
  57. var err error
  58. f, props, err = fieldByProtoName(m, fieldName)
  59. if err != nil {
  60. return err
  61. } else if !f.IsValid() {
  62. grpclog.Infof("field not found in %T: %s", msg, strings.Join(fieldPath, "."))
  63. return nil
  64. }
  65. switch f.Kind() {
  66. case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, reflect.String, reflect.Uint32, reflect.Uint64:
  67. if !isLast {
  68. return fmt.Errorf("unexpected nested field %s in %s", fieldPath[i+1], strings.Join(fieldPath[:i+1], "."))
  69. }
  70. m = f
  71. case reflect.Slice:
  72. if !isLast {
  73. return fmt.Errorf("unexpected repeated field in %s", strings.Join(fieldPath, "."))
  74. }
  75. // Handle []byte
  76. if f.Type().Elem().Kind() == reflect.Uint8 {
  77. m = f
  78. break
  79. }
  80. return populateRepeatedField(f, values, props)
  81. case reflect.Ptr:
  82. if f.IsNil() {
  83. m = reflect.New(f.Type().Elem())
  84. f.Set(m.Convert(f.Type()))
  85. }
  86. m = f.Elem()
  87. continue
  88. case reflect.Struct:
  89. m = f
  90. continue
  91. case reflect.Map:
  92. if !isLast {
  93. return fmt.Errorf("unexpected nested field %s in %s", fieldPath[i+1], strings.Join(fieldPath[:i+1], "."))
  94. }
  95. return populateMapField(f, values, props)
  96. default:
  97. return fmt.Errorf("unexpected type %s in %T", f.Type(), msg)
  98. }
  99. }
  100. switch len(values) {
  101. case 0:
  102. return fmt.Errorf("no value of field: %s", strings.Join(fieldPath, "."))
  103. case 1:
  104. default:
  105. grpclog.Infof("too many field values: %s", strings.Join(fieldPath, "."))
  106. }
  107. return populateField(m, values[0], props)
  108. }
  109. // fieldByProtoName looks up a field whose corresponding protobuf field name is "name".
  110. // "m" must be a struct value. It returns zero reflect.Value if no such field found.
  111. func fieldByProtoName(m reflect.Value, name string) (reflect.Value, *proto.Properties, error) {
  112. props := proto.GetProperties(m.Type())
  113. // look up field name in oneof map
  114. if op, ok := props.OneofTypes[name]; ok {
  115. v := reflect.New(op.Type.Elem())
  116. field := m.Field(op.Field)
  117. if !field.IsNil() {
  118. return reflect.Value{}, nil, fmt.Errorf("field already set for %s oneof", props.Prop[op.Field].OrigName)
  119. }
  120. field.Set(v)
  121. return v.Elem().Field(0), op.Prop, nil
  122. }
  123. for _, p := range props.Prop {
  124. if p.OrigName == name {
  125. return m.FieldByName(p.Name), p, nil
  126. }
  127. if p.JSONName == name {
  128. return m.FieldByName(p.Name), p, nil
  129. }
  130. }
  131. return reflect.Value{}, nil, nil
  132. }
  133. func populateMapField(f reflect.Value, values []string, props *proto.Properties) error {
  134. if len(values) != 2 {
  135. return fmt.Errorf("more than one value provided for key %s in map %s", values[0], props.Name)
  136. }
  137. key, value := values[0], values[1]
  138. keyType := f.Type().Key()
  139. valueType := f.Type().Elem()
  140. if f.IsNil() {
  141. f.Set(reflect.MakeMap(f.Type()))
  142. }
  143. keyConv, ok := convFromType[keyType.Kind()]
  144. if !ok {
  145. return fmt.Errorf("unsupported key type %s in map %s", keyType, props.Name)
  146. }
  147. valueConv, ok := convFromType[valueType.Kind()]
  148. if !ok {
  149. return fmt.Errorf("unsupported value type %s in map %s", valueType, props.Name)
  150. }
  151. keyV := keyConv.Call([]reflect.Value{reflect.ValueOf(key)})
  152. if err := keyV[1].Interface(); err != nil {
  153. return err.(error)
  154. }
  155. valueV := valueConv.Call([]reflect.Value{reflect.ValueOf(value)})
  156. if err := valueV[1].Interface(); err != nil {
  157. return err.(error)
  158. }
  159. f.SetMapIndex(keyV[0].Convert(keyType), valueV[0].Convert(valueType))
  160. return nil
  161. }
  162. func populateRepeatedField(f reflect.Value, values []string, props *proto.Properties) error {
  163. elemType := f.Type().Elem()
  164. // is the destination field a slice of an enumeration type?
  165. if enumValMap := proto.EnumValueMap(props.Enum); enumValMap != nil {
  166. return populateFieldEnumRepeated(f, values, enumValMap)
  167. }
  168. conv, ok := convFromType[elemType.Kind()]
  169. if !ok {
  170. return fmt.Errorf("unsupported field type %s", elemType)
  171. }
  172. f.Set(reflect.MakeSlice(f.Type(), len(values), len(values)).Convert(f.Type()))
  173. for i, v := range values {
  174. result := conv.Call([]reflect.Value{reflect.ValueOf(v)})
  175. if err := result[1].Interface(); err != nil {
  176. return err.(error)
  177. }
  178. f.Index(i).Set(result[0].Convert(f.Index(i).Type()))
  179. }
  180. return nil
  181. }
  182. func populateField(f reflect.Value, value string, props *proto.Properties) error {
  183. i := f.Addr().Interface()
  184. // Handle protobuf well known types
  185. var name string
  186. switch m := i.(type) {
  187. case interface{ XXX_WellKnownType() string }:
  188. name = m.XXX_WellKnownType()
  189. case proto.Message:
  190. const wktPrefix = "google.protobuf."
  191. if fullName := proto.MessageName(m); strings.HasPrefix(fullName, wktPrefix) {
  192. name = fullName[len(wktPrefix):]
  193. }
  194. }
  195. switch name {
  196. case "Timestamp":
  197. if value == "null" {
  198. f.FieldByName("Seconds").SetInt(0)
  199. f.FieldByName("Nanos").SetInt(0)
  200. return nil
  201. }
  202. t, err := time.Parse(time.RFC3339Nano, value)
  203. if err != nil {
  204. return fmt.Errorf("bad Timestamp: %v", err)
  205. }
  206. f.FieldByName("Seconds").SetInt(int64(t.Unix()))
  207. f.FieldByName("Nanos").SetInt(int64(t.Nanosecond()))
  208. return nil
  209. case "Duration":
  210. if value == "null" {
  211. f.FieldByName("Seconds").SetInt(0)
  212. f.FieldByName("Nanos").SetInt(0)
  213. return nil
  214. }
  215. d, err := time.ParseDuration(value)
  216. if err != nil {
  217. return fmt.Errorf("bad Duration: %v", err)
  218. }
  219. ns := d.Nanoseconds()
  220. s := ns / 1e9
  221. ns %= 1e9
  222. f.FieldByName("Seconds").SetInt(s)
  223. f.FieldByName("Nanos").SetInt(ns)
  224. return nil
  225. case "DoubleValue":
  226. fallthrough
  227. case "FloatValue":
  228. float64Val, err := strconv.ParseFloat(value, 64)
  229. if err != nil {
  230. return fmt.Errorf("bad DoubleValue: %s", value)
  231. }
  232. f.FieldByName("Value").SetFloat(float64Val)
  233. return nil
  234. case "Int64Value":
  235. fallthrough
  236. case "Int32Value":
  237. int64Val, err := strconv.ParseInt(value, 10, 64)
  238. if err != nil {
  239. return fmt.Errorf("bad DoubleValue: %s", value)
  240. }
  241. f.FieldByName("Value").SetInt(int64Val)
  242. return nil
  243. case "UInt64Value":
  244. fallthrough
  245. case "UInt32Value":
  246. uint64Val, err := strconv.ParseUint(value, 10, 64)
  247. if err != nil {
  248. return fmt.Errorf("bad DoubleValue: %s", value)
  249. }
  250. f.FieldByName("Value").SetUint(uint64Val)
  251. return nil
  252. case "BoolValue":
  253. if value == "true" {
  254. f.FieldByName("Value").SetBool(true)
  255. } else if value == "false" {
  256. f.FieldByName("Value").SetBool(false)
  257. } else {
  258. return fmt.Errorf("bad BoolValue: %s", value)
  259. }
  260. return nil
  261. case "StringValue":
  262. f.FieldByName("Value").SetString(value)
  263. return nil
  264. case "BytesValue":
  265. bytesVal, err := base64.StdEncoding.DecodeString(value)
  266. if err != nil {
  267. return fmt.Errorf("bad BytesValue: %s", value)
  268. }
  269. f.FieldByName("Value").SetBytes(bytesVal)
  270. return nil
  271. case "FieldMask":
  272. p := f.FieldByName("Paths")
  273. for _, v := range strings.Split(value, ",") {
  274. if v != "" {
  275. p.Set(reflect.Append(p, reflect.ValueOf(v)))
  276. }
  277. }
  278. return nil
  279. }
  280. // Handle Time and Duration stdlib types
  281. switch t := i.(type) {
  282. case *time.Time:
  283. pt, err := time.Parse(time.RFC3339Nano, value)
  284. if err != nil {
  285. return fmt.Errorf("bad Timestamp: %v", err)
  286. }
  287. *t = pt
  288. return nil
  289. case *time.Duration:
  290. d, err := time.ParseDuration(value)
  291. if err != nil {
  292. return fmt.Errorf("bad Duration: %v", err)
  293. }
  294. *t = d
  295. return nil
  296. }
  297. // is the destination field an enumeration type?
  298. if enumValMap := proto.EnumValueMap(props.Enum); enumValMap != nil {
  299. return populateFieldEnum(f, value, enumValMap)
  300. }
  301. conv, ok := convFromType[f.Kind()]
  302. if !ok {
  303. return fmt.Errorf("field type %T is not supported in query parameters", i)
  304. }
  305. result := conv.Call([]reflect.Value{reflect.ValueOf(value)})
  306. if err := result[1].Interface(); err != nil {
  307. return err.(error)
  308. }
  309. f.Set(result[0].Convert(f.Type()))
  310. return nil
  311. }
  312. func convertEnum(value string, t reflect.Type, enumValMap map[string]int32) (reflect.Value, error) {
  313. // see if it's an enumeration string
  314. if enumVal, ok := enumValMap[value]; ok {
  315. return reflect.ValueOf(enumVal).Convert(t), nil
  316. }
  317. // check for an integer that matches an enumeration value
  318. eVal, err := strconv.Atoi(value)
  319. if err != nil {
  320. return reflect.Value{}, fmt.Errorf("%s is not a valid %s", value, t)
  321. }
  322. for _, v := range enumValMap {
  323. if v == int32(eVal) {
  324. return reflect.ValueOf(eVal).Convert(t), nil
  325. }
  326. }
  327. return reflect.Value{}, fmt.Errorf("%s is not a valid %s", value, t)
  328. }
  329. func populateFieldEnum(f reflect.Value, value string, enumValMap map[string]int32) error {
  330. cval, err := convertEnum(value, f.Type(), enumValMap)
  331. if err != nil {
  332. return err
  333. }
  334. f.Set(cval)
  335. return nil
  336. }
  337. func populateFieldEnumRepeated(f reflect.Value, values []string, enumValMap map[string]int32) error {
  338. elemType := f.Type().Elem()
  339. f.Set(reflect.MakeSlice(f.Type(), len(values), len(values)).Convert(f.Type()))
  340. for i, v := range values {
  341. result, err := convertEnum(v, elemType, enumValMap)
  342. if err != nil {
  343. return err
  344. }
  345. f.Index(i).Set(result)
  346. }
  347. return nil
  348. }
  349. var (
  350. convFromType = map[reflect.Kind]reflect.Value{
  351. reflect.String: reflect.ValueOf(String),
  352. reflect.Bool: reflect.ValueOf(Bool),
  353. reflect.Float64: reflect.ValueOf(Float64),
  354. reflect.Float32: reflect.ValueOf(Float32),
  355. reflect.Int64: reflect.ValueOf(Int64),
  356. reflect.Int32: reflect.ValueOf(Int32),
  357. reflect.Uint64: reflect.ValueOf(Uint64),
  358. reflect.Uint32: reflect.ValueOf(Uint32),
  359. reflect.Slice: reflect.ValueOf(Bytes),
  360. }
  361. )