schema_http.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. package services
  2. import (
  3. "fmt"
  4. "github.com/emqx/kuiper/common"
  5. dpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
  6. "github.com/jhump/protoreflect/desc"
  7. "github.com/jhump/protoreflect/dynamic"
  8. "google.golang.org/protobuf/reflect/protoreflect"
  9. "net/http"
  10. "regexp"
  11. "strings"
  12. )
  13. type httpConnMeta struct {
  14. Method string
  15. Uri string // The Uri is a relative path which must start with /
  16. Body []byte
  17. }
  18. type httpMapping interface {
  19. ConvertHttpMapping(method string, params []interface{}) (*httpConnMeta, error)
  20. }
  21. const (
  22. httpAPI = "google.api.http"
  23. wildcardBody = "*"
  24. emptyBody = ""
  25. )
  26. type httpOptions struct {
  27. Method string
  28. UriTemplate *uriTempalte // must not nil
  29. BodyField string
  30. }
  31. type uriTempalte struct {
  32. Template string
  33. Fields []*field
  34. }
  35. type field struct {
  36. name string
  37. prefix string
  38. }
  39. func (d *wrappedProtoDescriptor) parseHttpOptions() error {
  40. optionsMap := make(map[string]*httpOptions)
  41. var err error
  42. for _, s := range d.GetServices() {
  43. for _, m := range s.GetMethods() {
  44. options := m.GetMethodOptions()
  45. var ho *httpOptions
  46. // Find http option and exit loop at once. If not found, http option is nil
  47. options.ProtoReflect().Range(func(d protoreflect.FieldDescriptor, v protoreflect.Value) bool {
  48. if d.FullName() == httpAPI {
  49. if d.Kind() == protoreflect.MessageKind {
  50. var (
  51. uriOpt string
  52. bodyOpt string
  53. err error
  54. )
  55. ho = &httpOptions{}
  56. v.Message().Range(func(din protoreflect.FieldDescriptor, vin protoreflect.Value) bool {
  57. switch din.Name() {
  58. case "get":
  59. ho.Method = http.MethodGet
  60. uriOpt, err = getUriOpt(din, vin)
  61. case "put":
  62. ho.Method = http.MethodPut
  63. uriOpt, err = getUriOpt(din, vin)
  64. case "delete":
  65. ho.Method = http.MethodDelete
  66. uriOpt, err = getUriOpt(din, vin)
  67. case "post":
  68. ho.Method = http.MethodPost
  69. uriOpt, err = getUriOpt(din, vin)
  70. case "patch":
  71. ho.Method = http.MethodPatch
  72. uriOpt, err = getUriOpt(din, vin)
  73. case "body":
  74. bodyOpt, err = getUriOpt(din, vin)
  75. default:
  76. err = fmt.Errorf("unsupported option %s", din.Name())
  77. }
  78. if err != nil {
  79. return false
  80. }
  81. return true
  82. })
  83. if err != nil {
  84. return false
  85. }
  86. err = ho.convertUri(m, uriOpt, bodyOpt)
  87. if err != nil {
  88. return false
  89. }
  90. } else {
  91. err = fmt.Errorf("invalid http option for method %s in proto", m.GetName())
  92. }
  93. return false
  94. }
  95. if err != nil {
  96. return false
  97. }
  98. return true
  99. })
  100. if err != nil {
  101. return err
  102. }
  103. if ho != nil {
  104. optionsMap[m.GetName()] = ho
  105. }
  106. }
  107. }
  108. d.methodOptions = optionsMap
  109. return err
  110. }
  111. func (d *wrappedProtoDescriptor) ConvertHttpMapping(method string, params []interface{}) (*httpConnMeta, error) {
  112. hcm := &httpConnMeta{}
  113. var (
  114. json []byte
  115. err error
  116. )
  117. if ho, ok := d.methodOptions[method]; ok {
  118. message, err := d.ConvertParamsToMessage(method, params)
  119. if err != nil {
  120. return nil, err
  121. }
  122. if len(ho.UriTemplate.Fields) > 0 {
  123. args := make([]interface{}, len(ho.UriTemplate.Fields))
  124. for i, v := range ho.UriTemplate.Fields {
  125. fv, err := getMessageFieldWithDots(message, v.name)
  126. if err != nil {
  127. return nil, err
  128. }
  129. args[i], err = common.ToString(fv, common.CONVERT_ALL)
  130. if err != nil {
  131. return nil, fmt.Errorf("invalid field %s(%v) as http option, must be string", v.name, fv)
  132. }
  133. // Remove all params to be used in the params, the left params are for BODY
  134. level1Names := strings.Split(v.name, ".")
  135. message.ClearFieldByName(level1Names[0])
  136. if v.prefix != "" {
  137. if strings.HasPrefix(args[i].(string), v.prefix) {
  138. continue
  139. } else {
  140. return nil, fmt.Errorf("invalid field %s(%s) as http option, must have prefix %s", v.name, args[i], v.prefix)
  141. }
  142. }
  143. }
  144. hcm.Uri = fmt.Sprintf(ho.UriTemplate.Template, args...)
  145. } else {
  146. hcm.Uri = ho.UriTemplate.Template
  147. }
  148. hcm.Method = ho.Method
  149. switch ho.BodyField {
  150. case wildcardBody:
  151. json, err = message.MarshalJSON()
  152. case emptyBody:
  153. json = nil
  154. default:
  155. bodyMessage := message.GetFieldByName(ho.BodyField)
  156. if bm, ok := bodyMessage.(*dynamic.Message); ok {
  157. json, err = bm.MarshalJSON()
  158. } else {
  159. return nil, fmt.Errorf("invalid body field %s, must be a message", ho.BodyField)
  160. }
  161. }
  162. } else { // If options are not set, use the default setting
  163. hcm.Method = "POST"
  164. hcm.Uri = "/" + method
  165. json, err = d.ConvertParamsToJson(method, params)
  166. }
  167. if err != nil {
  168. return nil, err
  169. }
  170. hcm.Body = json
  171. return hcm, nil
  172. }
  173. func getMessageFieldWithDots(message *dynamic.Message, name string) (interface{}, error) {
  174. secs := strings.Split(name, ".")
  175. currentMessage := message
  176. for i, sec := range secs {
  177. if i == len(secs)-1 {
  178. return currentMessage.GetFieldByName(sec), nil
  179. } else {
  180. c := currentMessage.GetFieldByName(sec)
  181. if cm, ok := c.(*dynamic.Message); ok {
  182. currentMessage = cm
  183. } else {
  184. return nil, fmt.Errorf("fail to find field %s", name)
  185. }
  186. }
  187. }
  188. return nil, fmt.Errorf("fail to find field %s", name)
  189. }
  190. func getUriOpt(d protoreflect.FieldDescriptor, v protoreflect.Value) (string, error) {
  191. if d.Kind() != protoreflect.StringKind {
  192. return "", fmt.Errorf("invalid type for %s option, string required", d.Name())
  193. }
  194. return v.String(), nil
  195. }
  196. func (ho *httpOptions) convertUri(md *desc.MethodDescriptor, uriOpt string, bodyOpt string) error {
  197. fmap := make(map[string]bool) // the value represents if the key is still available (not used) so that they can be removed from *
  198. for _, f := range md.GetInputType().GetFields() {
  199. fmap[f.GetName()] = true
  200. }
  201. result := &uriTempalte{}
  202. re := regexp.MustCompile(`\{(.*?)\}`)
  203. m := re.FindAllStringSubmatch(uriOpt, -1)
  204. if len(m) > 0 {
  205. result.Template = re.ReplaceAllString(uriOpt, "%s")
  206. var fields []*field
  207. for _, e := range m {
  208. f := &field{}
  209. rr := strings.Split(e[1], "=")
  210. if len(rr) == 2 {
  211. if strings.HasSuffix(rr[1], "*") {
  212. f.name = rr[0]
  213. f.prefix = rr[1][:len(rr[1])-1]
  214. } else {
  215. return fmt.Errorf("invalid uri %s in http option", uriOpt)
  216. }
  217. } else if len(rr) == 1 {
  218. f.name = e[1]
  219. } else {
  220. return fmt.Errorf("invalid uri %s in http option", uriOpt)
  221. }
  222. _, ok := fmap[f.name]
  223. if !ok {
  224. return fmt.Errorf("invalid uri %s in http option, %s field not found", uriOpt, f.name)
  225. }
  226. fmap[f.name] = false
  227. fields = append(fields, f)
  228. }
  229. result.Fields = fields
  230. } else {
  231. result.Template = uriOpt
  232. }
  233. switch bodyOpt {
  234. case wildcardBody:
  235. ho.BodyField = bodyOpt
  236. default:
  237. if bodyOpt != emptyBody {
  238. if _, ok := fmap[bodyOpt]; !ok {
  239. return fmt.Errorf("invalid body %s, field not found", bodyOpt)
  240. } else {
  241. fmap[bodyOpt] = false
  242. }
  243. }
  244. ho.BodyField = bodyOpt
  245. paramAdded := false
  246. result.updateUriParams(md.GetInputType(), "", fmap, paramAdded)
  247. }
  248. ho.UriTemplate = result
  249. return nil
  250. }
  251. func (u *uriTempalte) updateUriParams(md *desc.MessageDescriptor, prefix string, fmap map[string]bool, paramAdded bool) bool {
  252. var jointer string
  253. for _, mf := range md.GetFields() {
  254. if fmap[mf.GetName()] || prefix != "" { // The first level field which are not consumed or the second level field
  255. if mf.GetType() == dpb.FieldDescriptorProto_TYPE_MESSAGE {
  256. paramAdded = u.updateUriParams(mf.GetMessageType(), prefix+mf.GetName()+".", fmap, paramAdded)
  257. continue
  258. }
  259. if !paramAdded {
  260. paramAdded = true
  261. jointer = "?"
  262. } else {
  263. jointer = "&"
  264. }
  265. u.Template = fmt.Sprintf("%s%s%s%s=%s", u.Template, jointer, prefix, mf.GetName(), "%s")
  266. u.Fields = append(u.Fields, &field{name: prefix + mf.GetName()})
  267. }
  268. }
  269. return paramAdded
  270. }