trpc-group / trpc-go

A pluggable, high-performance RPC framework written in golang
Other
742 stars 85 forks source link

question: trpc: Is there any way I could know whether an *server.Server is new-ed? #175

Closed Andrew-M-C closed 1 month ago

Andrew-M-C commented 1 month ago

Preliminary Research

Question

As we know, a trpc app should and should only invoke trpc.NewServer() once. After invoking this function, a server is initialized and all associated modules are ready to use.

I am now developing an plugin depending on other plugins, etcd for example. However, at start-up procedure, when I callled config.Get("etcd") and got nil, I am not sure of the reason. If it was because that etcd was not properly configurred? Or that etcd is confgurred but simply not initialized by trpc framework yet.

So, is there any way that I can know at least one Server is new-ed? Which indicates that trpc server is completely initialized.

Additional Information

N/A

WineChord commented 1 month ago

The design appearance of trpc.NewServer() implies that it is used to create a new server instance. However, the current implementation modifies a multitude of global variables found in packages such as config and client, as seen here. Encountering an error from config.Get returning nil is indicative of the plugins not being initialized, which is part of the trpc.NewServer() routine.

Another global variable could be introduced to indicate the creation of a new server instance. However, this approach might lead to further deterioration of the code and is unlikely to be a favorable solution.

A more viable strategy would be to refrain from using config.Get within init functions. Instead, it is advisable to access plugin-related information only after the execution of trpc.NewServer to ensure that all necessary initializations have been performed.

Andrew-M-C commented 1 month ago

What I am doing now is the second solution you mentioned, to implicitly invoke the initialization function after NewServer. I just wonder if there is another elegant way.

Is this acceptable: Allow plugins declaring its precondition? The plugin's Setup() will only be called if its depending plugins are set-up?

WineChord commented 1 month ago

Checkout the DependsOn and FlexDependsOn interface: https://github.com/trpc-group/trpc-go/blob/main/plugin/README.md#plugin-initialization-order

Andrew-M-C commented 1 month ago

wow, that seems to meet my case! I will try it at once, THX!