compile.grpc.ex 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. defmodule Mix.Tasks.Compile.Grpc do
  2. use Mix.Task.Compiler
  3. @recursive true
  4. @manifest_vsn 1
  5. @manifest "compile.grpc"
  6. # TODO: use manifest to track generated files?
  7. @impl true
  8. def manifests(), do: [manifest()]
  9. defp manifest(), do: Path.join(Mix.Project.manifest_path(), @manifest)
  10. @impl true
  11. def run(_args) do
  12. Mix.Project.get!()
  13. config = Mix.Project.config()
  14. %{
  15. gpb_opts: gpb_opts,
  16. proto_dirs: proto_dirs,
  17. out_dir: out_dir
  18. } = config[:grpc_opts]
  19. add_to_path_and_cache(:syntax_tools)
  20. :ok = Application.ensure_loaded(:syntax_tools)
  21. :ok = Application.ensure_loaded(:gpb)
  22. app_root = File.cwd!()
  23. app_build_path = Mix.Project.app_path(config)
  24. proto_srcs =
  25. proto_dirs
  26. |> Enum.map(& Path.join([app_root, &1]))
  27. |> Mix.Utils.extract_files([:proto])
  28. manifest_data = read_manifest(manifest())
  29. context = %{
  30. manifest_data: manifest_data,
  31. app_root: app_root,
  32. app_build_path: app_build_path,
  33. out_dir: out_dir,
  34. gpb_opts: gpb_opts,
  35. }
  36. Enum.each(proto_srcs, & compile_pb(&1, context))
  37. write_manifest(manifest(), manifest_data)
  38. {:noop, []}
  39. end
  40. defp compile_pb(proto_src, context) do
  41. %{
  42. app_root: app_root,
  43. app_build_path: app_build_path,
  44. out_dir: out_dir,
  45. gpb_opts: gpb_opts,
  46. } = context
  47. manifest_modified_time = Mix.Utils.last_modified(manifest())
  48. ebin_path = Path.join([app_build_path, "ebin"])
  49. basename = proto_src |> Path.basename(".proto") |> to_charlist()
  50. prefix = Keyword.get(gpb_opts, :module_name_prefix, '')
  51. suffix = Keyword.get(gpb_opts, :module_name_suffix, '')
  52. mod_name = '#{prefix}#{basename}#{suffix}'
  53. opts = [
  54. :use_packages,
  55. :maps,
  56. :strings_as_binaries,
  57. i: '.',
  58. o: out_dir,
  59. report_errors: false,
  60. rename: {:msg_name, :snake_case},
  61. rename: {:msg_fqname, :base_name},
  62. ]
  63. if stale?(proto_src, manifest_modified_time) do
  64. Mix.shell().info("compiling proto file: #{proto_src}")
  65. File.mkdir_p!(out_dir)
  66. # TODO: better error logging...
  67. :ok = :gpb_compile.file(
  68. to_charlist(proto_src),
  69. opts ++ gpb_opts
  70. )
  71. else
  72. Mix.shell().info("proto file up to date, not compiling: #{proto_src}")
  73. end
  74. generated_src = Path.join([app_root, out_dir, "#{mod_name}.erl"])
  75. gpb_include_dir = :code.lib_dir(:gpb, :include)
  76. if stale?(generated_src, manifest_modified_time) do
  77. Mix.shell().info("compiling proto module: #{generated_src}")
  78. compile_res = :compile.file(
  79. to_charlist(generated_src),
  80. [
  81. :return_errors,
  82. i: to_charlist(gpb_include_dir),
  83. outdir: to_charlist(ebin_path)
  84. ]
  85. )
  86. # todo: error handling & logging
  87. case compile_res do
  88. {:ok, _} ->
  89. :ok
  90. {:ok, _, _warnings} ->
  91. :ok
  92. end
  93. else
  94. Mix.shell().info("file up to date, not compiling: #{generated_src}")
  95. end
  96. mod_name
  97. |> List.to_atom()
  98. |> :code.purge()
  99. {:module, _mod} =
  100. ebin_path
  101. |> Path.join(mod_name)
  102. |> to_charlist()
  103. |> :code.load_abs()
  104. mod_name = List.to_atom(mod_name)
  105. service_quoted =
  106. [__DIR__, "../../", "emqx/grpc/template/service.eex"]
  107. |> Path.join()
  108. |> Path.expand()
  109. |> EEx.compile_file()
  110. client_quoted =
  111. [__DIR__, "../../", "emqx/grpc/template/client.eex"]
  112. |> Path.join()
  113. |> Path.expand()
  114. |> EEx.compile_file()
  115. mod_name.get_service_names()
  116. |> Enum.each(fn service ->
  117. service
  118. |> mod_name.get_service_def()
  119. |> then(fn {{:service, service_name}, methods} ->
  120. methods = Enum.map(methods, fn method ->
  121. snake_case = method.name |> to_string() |> Macro.underscore()
  122. message_type = mod_name.msg_name_to_fqbin(method.input)
  123. method
  124. |> Map.put(:message_type, message_type)
  125. |> Map.put(:snake_case, snake_case)
  126. |> Map.put(:pb_module, mod_name)
  127. |> Map.put(:unmodified_method, method.name)
  128. end)
  129. snake_service =
  130. service_name
  131. |> to_string()
  132. |> Macro.underscore()
  133. |> String.replace("/", "_")
  134. |> String.replace(~r/(.)([0-9]+)/, "\\1_\\2")
  135. bindings = [
  136. methods: methods,
  137. pb_module: mod_name,
  138. module_name: snake_service,
  139. unmodified_service_name: service_name
  140. ]
  141. bhvr_output_src = Path.join([app_root, out_dir, "#{snake_service}_bhvr.erl"])
  142. if stale?(bhvr_output_src, manifest_modified_time) do
  143. render_and_write(service_quoted, bhvr_output_src, bindings)
  144. else
  145. Mix.shell().info("file up to date, not compiling: #{bhvr_output_src}")
  146. end
  147. client_output_src = Path.join([app_root, out_dir, "#{snake_service}_client.erl"])
  148. if stale?(client_output_src, manifest_modified_time) do
  149. render_and_write(client_quoted, client_output_src, bindings)
  150. else
  151. Mix.shell().info("file up to date, not compiling: #{client_output_src}")
  152. end
  153. :ok
  154. end)
  155. end)
  156. :ok
  157. end
  158. defp stale?(file, manifest_modified_time) do
  159. with true <- File.exists?(file),
  160. false <- Mix.Utils.stale?([file], [manifest_modified_time]) do
  161. false
  162. else
  163. _ -> true
  164. end
  165. end
  166. defp read_manifest(file) do
  167. try do
  168. file |> File.read!() |> :erlang.binary_to_term()
  169. rescue
  170. _ -> %{}
  171. else
  172. {@manifest_vsn, data} when is_map(data) -> data
  173. _ -> %{}
  174. end
  175. end
  176. defp write_manifest(file, data) do
  177. Mix.shell().info("writing manifest #{file}")
  178. File.mkdir_p!(Path.dirname(file))
  179. File.write!(file, :erlang.term_to_binary({@manifest_vsn, data}))
  180. end
  181. defp render_and_write(quoted_file, output_src, bindings) do
  182. {result, _bindings} = Code.eval_quoted(quoted_file, bindings)
  183. result = String.replace(result, ~r/\n\n\n+/, "\n\n\n")
  184. File.write!(output_src, result)
  185. end
  186. def add_to_path_and_cache(lib_name) do
  187. :code.lib_dir()
  188. |> Path.join("#{lib_name}-*")
  189. |> Path.wildcard()
  190. |> hd()
  191. |> Path.join("ebin")
  192. |> to_charlist()
  193. |> :code.add_path(:cache)
  194. end
  195. end