Module: Magicprotorb::Loader

Defined in:
lib/magicprotorb/loader.rb

Overview

Orchestrates a single import: resolve -> compile -> register (-> services). Compilation results are memoized per canonical proto path; a process-wide mutex serializes the descriptor-pool mutations.

Constant Summary collapse

MUTEX =
Mutex.new

Class Method Summary collapse

Class Method Details

.compile(proto_path) ⇒ Object

Compile proto_path to a FileDescriptorSet via the native protox-backed compiler, using the current include roots. Memoized.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/magicprotorb/loader.rb', line 31

def compile(proto_path)
  @compiled[proto_path] ||= begin
    if IncludePath.resolve(proto_path).nil?
      raise LoadError,
            "magicprotorb: cannot find #{proto_path} on #{IncludePath::ENV_VAR} or $LOAD_PATH"
    end

    bytes =
      begin
        Compiler._compile(proto_path, IncludePath.roots)
      rescue StandardError => e
        raise CompileError, e.message
      end

    Google::Protobuf::FileDescriptorSet.decode(bytes)
  end
end

.load_messages(proto_path) ⇒ Object

Register messages/enums for proto_path (and its imports). Idempotent.



14
15
16
# File 'lib/magicprotorb/loader.rb', line 14

def load_messages(proto_path)
  MUTEX.synchronize { Registrar.register(compile(proto_path)) }
end

.load_services(proto_path) ⇒ Object

As load_messages, plus synthesize gRPC Service/Stub for the proto’s own services (not those of its imports — matching protoc’s per-file output).



20
21
22
23
24
25
26
27
# File 'lib/magicprotorb/loader.rb', line 20

def load_services(proto_path)
  MUTEX.synchronize do
    fds = compile(proto_path)
    Registrar.register(fds)
    primary = fds.file.find { |file| file.name == proto_path } || fds.file.last
    ServiceBuilder.build(primary)
  end
end