File: AsyncPluginValidator.cpp

package info (click to toggle)
audacity 3.7.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 125,252 kB
  • sloc: cpp: 358,238; ansic: 75,458; lisp: 7,761; sh: 3,410; python: 1,503; xml: 1,385; perl: 854; makefile: 122
file content (257 lines) | stat: -rw-r--r-- 6,849 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/**********************************************************************

  Audacity: A Digital Audio Editor

  @file AsyncPluginValidation.cpp

  @author Vitaly Sverchinsky

  Part of lib-module-manager library

**********************************************************************/

#include "AsyncPluginValidator.h"

#include <optional>
#include <mutex>

#include "BasicUI.h"
#include "IPCChannel.h"
#include "IPCServer.h"
#include "spinlock.h"
#include "XMLTagHandler.h"

#include "PluginIPCUtils.h"
#include "PluginDescriptor.h"
#include "PluginHost.h"
#include "XMLFileReader.h"

AsyncPluginValidator::Delegate::~Delegate() = default;

class AsyncPluginValidator::Impl final : 
   public IPCChannelStatusCallback,
   public std::enable_shared_from_this<Impl>
{
   //Variables below are accessed from any thread

   IPCChannel* mChannel{nullptr};
   std::optional<wxString> mRequest;
   std::atomic<std::chrono::system_clock::duration::rep> mLastTimeActive;

   //The main reason to use spinlock instead of std::mutex here
   //is that in most cases there will be no attempts for simultaneous
   //data access (except OnConnect/Disconnect cases), because of
   //protocol design
   spinlock mSync;

   //Variable below is accessed only from the main/UI thread

   Delegate* mDelegate{nullptr};
   std::unique_ptr<IPCServer> mServer;

   //Variables below is accessed only from worker threads

   detail::InputMessageReader mMessageReader;

   //called on main thread only!
   void StartHost()
   {
      auto server = std::make_unique<IPCServer>(*this);
      if(!PluginHost::Start(server->GetConnectPort()))
         throw std::runtime_error("cannot start plugin host process");
      mLastTimeActive = std::chrono::system_clock::now().time_since_epoch().count();
      mServer = std::move(server);
   }
   
   void HandleInternalError(const wxString& msg) noexcept
   {
      try
      {
         BasicUI::CallAfter([wptr = weak_from_this(), msg]
         {
            if(auto self = wptr.lock(); self && self->mDelegate != nullptr)
               self->mDelegate->OnInternalError(msg);
         });
      }
      catch(...)
      {
         //no way to report about a problem, though shouldn't be the case...
      }
   }

   void HandleResult(detail::PluginValidationResult&& result) noexcept
   {
      try
      {
         BasicUI::CallAfter([wptr = weak_from_this(), result = detail::PluginValidationResult { result }]
         {
            if(auto self = wptr.lock())
            {
               if(self->mDelegate == nullptr)
                  return;

               //Release the current value to keep state invariant
               //Caller is free to use Validate now
               std::optional<wxString> request;
               {
                  std::lock_guard lck_sync(self->mSync);
                  self->mRequest.swap(request);
               }

               if(!request.has_value())
               {
                  //Invalid state error
                  self->mDelegate->OnInternalError(result.GetErrorMessage());
                  return;
               }

               if(result.IsValid())
               {
                  for(auto& desc : result.GetDescriptors())
                     self->mDelegate->OnPluginFound(PluginDescriptor { desc });
               }
               else
               {
                  wxString providerId;
                  wxString pluginPath;
                  detail::ParseRequestString(*request, providerId, pluginPath);

                  self->mDelegate->OnPluginValidationFailed(providerId, pluginPath);
               }
               self->mDelegate->OnValidationFinished();
            }
         });
      }
      catch(...)
      {
         ///no way to report about a problem, though shouldn't be the case...
      }
   }

public:

   Impl(Impl&) = delete;
   Impl(Impl&&) = delete;
   Impl& operator=(Impl&) = delete;
   Impl& operator=(Impl&&) = delete;

   Impl(Delegate& delegate) : mDelegate(&delegate) { }

   ~Impl() override
   {
      //important to reset delegate before IPCChannelStatusCallback::OnDisconnect
      //is called by server
      mDelegate = nullptr;
      mServer.reset();
   }

   void SetDelegate(Delegate* delegate)
   {
      mDelegate = delegate;
   }

   std::chrono::system_clock::time_point InactiveSince() const noexcept
   {
      using std::chrono::system_clock;

      return system_clock::time_point { system_clock::duration{mLastTimeActive.load()} };
   }

   void OnConnect(IPCChannel& channel) noexcept override
   {
      std::lock_guard lck(mSync);

      mChannel = &channel;
      if(mRequest)
      {
         try
         {
            detail::PutMessage(channel, *mRequest);
         }
         catch(...)
         {
            HandleInternalError("Can't send message to host");
         }
      }
   }

   void OnDisconnect() noexcept override
   {
      {
         std::lock_guard lck(mSync);
         mChannel = nullptr;
      }
      detail::PluginValidationResult result;
      result.SetError("Disconnect");
      HandleResult(std::move(result));
   }

   void OnConnectionError() noexcept override
   {
      HandleInternalError("Can't connect");
   }

   void OnDataAvailable(const void* data, size_t size) noexcept override
   {
      try
      {
         mMessageReader.ConsumeBytes(data, size);
         mLastTimeActive = std::chrono::system_clock::now().time_since_epoch().count();
         while(mMessageReader.CanPop())
         {
            auto message = mMessageReader.Pop();
            if(message.IsEmpty())
               continue;

            detail::PluginValidationResult result;
            XMLFileReader xmlReader;
            xmlReader.ParseString(&result, message);

            HandleResult(std::move(result));
         }
      }
      catch(...)
      {
         HandleInternalError("Can't process response from the host");
      }
   }

   void Validate(const wxString& providerId, const wxString& pluginPath)
   {
      std::lock_guard lck(mSync);

      //one request at a time
      assert(!mRequest.has_value());

      mRequest = detail::MakeRequestString(providerId, pluginPath);
      if(mChannel)
         detail::PutMessage(*mChannel, *mRequest);
      else
         //create host process on demand
         StartHost();
   }
};

AsyncPluginValidator::AsyncPluginValidator(Delegate& delegate)
{
   mImpl = std::make_unique<Impl>(delegate);
}

AsyncPluginValidator::~AsyncPluginValidator() = default;

void AsyncPluginValidator::Validate(const wxString& providerId, const wxString& pluginPath)
{
   mImpl->Validate(providerId, pluginPath);
}

void AsyncPluginValidator::SetDelegate(Delegate* delegate)
{
   mImpl->SetDelegate(delegate);
}

std::chrono::system_clock::time_point AsyncPluginValidator::InactiveSince() const noexcept
{
   return mImpl->InactiveSince();
}