File: service.cpp

package info (click to toggle)
sight 25.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 42,180 kB
  • sloc: cpp: 289,476; xml: 17,257; ansic: 9,878; python: 1,379; sh: 144; makefile: 33
file content (532 lines) | stat: -rw-r--r-- 18,988 bytes parent folder | download
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/************************************************************************
 *
 * Copyright (C) 2022-2025 IRCAD France
 *
 * This file is part of Sight.
 *
 * Sight is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Sight is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Sight. If not, see <https://www.gnu.org/licenses/>.
 *
 ***********************************************************************/

#include "service/detail/service.hpp"

#include "service/registry.hpp"

#include <core/com/helper/sig_slot_connection.hpp>
#include <core/com/signal.hxx>
#include <core/com/slots.hxx>
#include <core/runtime/helper.hpp>
#include <core/thread/worker.hpp>

#include <ranges>

namespace sight::service::detail
{

// To avoid any conflict with other slots
const auto MAKE_PROPERTY_SLOT_NAME = [](const std::string& _property){return core::id::join(_property, "property");};

//-----------------------------------------------------------------------------

service::service(sight::service::base& _service) :
    m_service(_service)
{
}

//-----------------------------------------------------------------------------

service::~service()
{
    SIGHT_ASSERT(
        "service " << m_id_copy << " not stopped upon destruction, call stop() beforehand",
        m_global_state == base::global_status::stopped
    );

    {
        const auto started = m_service.m_start_property.lock();
        if(started)
        {
            auto sig = started->signal(sight::data::signals::MODIFIED);
            if(auto conn = sig->get_connection(m_service.slot(sight::service::slots::START_ON_PROPERTY));
               not conn.expired())
            {
                conn.disconnect();
            }
        }
    }
    m_connections.disconnect_start_slot(m_service);
}

//-----------------------------------------------------------------------------

void service::set_config(const config_t& _config)
{
    m_configuration       = _config;
    m_configuration_state = base::configuration_status::unconfigured;
}

//-----------------------------------------------------------------------------

const config_t& service::get_config() const
{
    return m_configuration;
}

//-----------------------------------------------------------------------------

void service::configure()
{
    if(m_configuration_state == base::configuration_status::unconfigured)
    {
        m_configuration_state = base::configuration_status::configuring;
        if(m_global_state == base::global_status::stopped)
        {
            try
            {
                // Collect all input/output configurations
                std::map<std::string, std::string> properties_cfgs;
                if(const auto& properties = m_configuration.get_child_optional("properties"); properties.has_value())
                {
                    if(const auto& attributes = properties->get_child_optional("<xmlattr>"); attributes.has_value())
                    {
                        for(const auto& attribute : *attributes)
                        {
                            properties_cfgs[attribute.first] = attribute.second.get_value<std::string>();
                        }
                    }

                    auto properties_attrs = properties->equal_range("property");
                    for(auto it_prop = properties_attrs.first ; it_prop != properties_attrs.second ; ++it_prop)
                    {
                        if(auto obj_cfg = it_prop->second.get_child_optional("<xmlattr>"); obj_cfg.has_value())
                        {
                            // We take only the first element
                            auto first_element = *obj_cfg->begin();
                            properties_cfgs[first_element.first] = first_element.second.get_value<std::string>();
                        }
                    }
                }

                const auto properties_obj = m_service.m_properties_map.lock();
                const auto properties_map = std::dynamic_pointer_cast<data::map>(properties_obj.get_shared());

                // Look for properties
                auto is_property = [](auto& _p){return dynamic_cast<data::property_base*>(_p.second) != nullptr;};

                auto obj_from_property_map = [&](const std::string& _key) -> sight::data::object::sptr
                                             {
                                                 if(properties_map != nullptr)
                                                 {
                                                     if(const auto& prop_key = properties_map->find(_key);
                                                        prop_key != properties_map->end())
                                                     {
                                                         return prop_key->second;
                                                     }
                                                 }

                                                 return nullptr;
                                             };

                for(const auto& [key, ptr] : m_service.container() | std::views::filter(is_property))
                {
                    auto weak_obj = m_service.inout(key.first);
                    auto obj      = weak_obj.lock();

                    const auto& obj_from_map = obj_from_property_map(std::string(key.first));

                    if(obj == nullptr)
                    {
                        auto* property = dynamic_cast<data::property_base*>(ptr);
                        SIGHT_ASSERT("Data pointer is not convertible to a property", property);

                        if(obj_from_map != nullptr)
                        {
                            // We found a key in the map
                            m_service.set_object(obj_from_map, key.first, {}, ptr->access(), true, false);
                        }
                        else
                        {
                            auto new_obj = property->make_default();
                            m_created_properties.emplace_back(new_obj);

                            if(const auto& prop_cfg = properties_cfgs.find(std::string(key.first));
                               prop_cfg != properties_cfgs.end())
                            {
                                new_obj->from_string(prop_cfg->second);
                            }
                        }
                    }
                    else
                    {
                        SIGHT_ERROR_IF(
                            "Properties " << std::quoted(key.first)
                            << " set with an object while there is already a key in the property map",
                            obj_from_map != nullptr
                        );
                    }
                }

                // Create a slot for each property - avoid recreating them if configured multiple times
                for(const auto& [key, ptr] : m_service.container())
                {
                    const auto& key_str = key.first;

                    if(dynamic_cast<data::property_base*>(ptr) != nullptr)
                    {
                        const auto slot_name = MAKE_PROPERTY_SLOT_NAME(std::string(key_str));
                        const auto& slots    = dynamic_cast<sight::core::com::has_slots&>(m_service).slots();
                        if(not slots.contains(slot_name))
                        {
                            auto slot = m_service.new_slot(
                                MAKE_PROPERTY_SLOT_NAME(std::string(key_str)),
                                [&]()
                                {
                                    m_service.on_property_set(key_str);
                                });
                            slot->set_worker(m_service.worker());
                        }
                    }
                }

                m_service.configuring();
                m_service.configuring(m_configuration);
            }
            catch(const boost::property_tree::ptree_bad_path& e)
            {
                SIGHT_ERROR("Error while configuring the service '" + m_service.get_id() + "' : " + e.what());

                auto config = m_service.get_config();
                SIGHT_ERROR("With the given configuration:\n" + core::ptree::to_string(config));
            }
            catch(std::exception& e)
            {
                SIGHT_ERROR("Error while configuring service '" + m_service.get_id() + "' : " + e.what());
                throw; // Rethrow the error for unit tests
            }
        }
        else if(m_global_state == base::global_status::started)
        {
            SIGHT_ERROR(
                "Error trying to configure the service '" + m_service.get_id() + "' whereas it is already started."
            );
        }

        {
            const auto started = m_service.m_start_property.lock();
            auto sig           = started->signal(sight::data::signals::MODIFIED);
            if(auto conn = sig->get_connection(m_service.slot(sight::service::slots::START_ON_PROPERTY));
               conn.expired())
            {
                sig->connect(m_service.slot(sight::service::slots::START_ON_PROPERTY));
            }
        }
        m_configuration_state = base::configuration_status::configured;
    }

    m_connections.connect_start_slot(m_service);
}

//-----------------------------------------------------------------------------

base::shared_future_t service::start(bool _async)
{
    m_id_copy = m_service.get_id();
    if(m_configuration_state == base::configuration_status::unconfigured)
    {
        // Well we could be stricter and require this to be done before, but a lot of legacy code would need
        // to be fixed and I don't think this bring so much value
        this->configure();
    }

    SIGHT_ASSERT(
        "service " << m_service.get_id() << " requested to start, but it is not configured",
        m_configuration_state == base::configuration_status::configured
    );
    SIGHT_FATAL_IF(
        "service " << m_service.get_id() << " already started",
        m_global_state != base::global_status::stopped
    );

    m_connections.connect(m_service);

    m_global_state = base::global_status::starting;

    packaged_task_t task([this](auto&& ...){m_service.starting();});
    base::shared_future_t future = task.get_future();
    task();

    try
    {
        // This allows to trigger the exception if there was one
        future.get();
    }
    catch(const std::exception& e)
    {
        SIGHT_ERROR("Error while STARTING service '" + m_service.get_id() + "' : " + e.what());
        SIGHT_ERROR("service '" + m_service.get_id() + "' is still STOPPED.");
        m_global_state = base::global_status::stopped;
        m_connections.disconnect(m_service);

        if(!_async)
        {
            // The future is shared, thus the caller can still catch the exception if needed with future.get()
            return future;
        }

        // Rethrow the same exception
        throw;
    }
    m_global_state = base::global_status::started;

    this->auto_connect();

    {
        const auto started = m_service.m_start_property.lock();
        *started = true;
        started->async_emit(&m_service, sight::data::signals::MODIFIED);
    }

    auto sig = m_service.signal<sight::service::signals::started_t>(sight::service::signals::STARTED);
    sig->async_emit(m_service.get_sptr());

    return future;
}

//-----------------------------------------------------------------------------

base::shared_future_t service::stop(bool _async)
{
    SIGHT_FATAL_IF(
        "service " << m_service.get_id() << " already stopped",
        m_global_state != base::global_status::started
    );

    this->auto_disconnect();

    packaged_task_t task([this](auto&& ...){m_service.stopping();});
    base::shared_future_t future = task.get_future();

    m_global_state = base::global_status::stopping;
    task();

    try
    {
        // This allows to trigger the exception if there was one
        future.get();
    }
    catch(std::exception& e)
    {
        SIGHT_ERROR("Error while STOPPING service '" + m_service.get_id() + "' : " + e.what());
        SIGHT_ERROR("service '" + m_service.get_id() + "' is still STARTED.");
        m_global_state = base::global_status::started;
        this->auto_connect();

        if(!_async)
        {
            // The future is shared, thus the caller can still catch the exception if needed with future.get()
            return future;
        }

        // Rethrow the same exception
        throw;
    }
    m_global_state = base::global_status::stopped;

    auto sig = m_service.signal<sight::service::signals::stopped_t>(sight::service::signals::STOPPED);
    sig->async_emit(m_service.get_sptr());

    {
        const auto started = m_service.m_start_property.lock();
        *started = false;
        started->async_emit(&m_service, sight::data::signals::MODIFIED);
    }

    m_connections.disconnect(m_service);

    // Reset all output objects to inform other services they are no longer available
    m_service.reset_all_out();

    return future;
}

//-----------------------------------------------------------------------------

base::shared_future_t service::swap_key(std::string_view _key, data::object::sptr _obj, bool _async)
{
    SIGHT_FATAL_IF(
        "service " << m_service.get_id() << " is not STARTED, no swapping with Object "
        << (_obj ? _obj->get_id() : "nullptr"),
        m_global_state != base::global_status::started
    );

    auto fn = [this, _key]{m_service.swapping(_key);};
    packaged_task_t task(fn);
    base::shared_future_t future = task.get_future();

    this->auto_disconnect();

    m_global_state = base::global_status::swapping;
    task();
    m_global_state = base::global_status::started;

    try
    {
        // This allows to trigger the exception if there was one
        future.get();
    }
    catch(std::exception& e)
    {
        SIGHT_ERROR("Error while SWAPPING service '" + m_service.get_id() + "' : " + e.what());

        if(!_async)
        {
            // The future is shared, thus the caller can still catch the exception if needed with future.get()
            return future;
        }

        // Rethrow the same exception
        throw;
    }

    this->auto_connect();

    auto sig = m_service.signal<sight::service::signals::swapped_t>(sight::service::signals::SWAPPED);
    sig->async_emit(m_service.get_sptr());

    return future;
}

//-----------------------------------------------------------------------------

base::shared_future_t service::update(bool _async)
{
    if(m_global_state != base::global_status::started)
    {
        SIGHT_WARN(
            "Update() called while not started: service '" << m_service.get_id() << "' of type '"
            << m_service.get_classname() << "': update is discarded."
        );
        return {};
    }

    SIGHT_ASSERT(
        "Update() called while already updating '" << m_service.get_id()
        << "' of type '" << m_service.get_classname() << "'",
        m_updating_state == base::updating_status::notupdating
    );

    packaged_task_t task([this](auto&& ...){m_service.updating();});
    base::shared_future_t future = task.get_future();
    m_updating_state = base::updating_status::updating;
    task();

    try
    {
        // This allows to trigger the exception if there was one
        future.get();
    }
    catch(std::exception& e)
    {
        SIGHT_ERROR("Error while UPDATING service '" + m_service.get_id() + "' : " + e.what());

        m_updating_state = base::updating_status::notupdating;
        if(!_async)
        {
            // The future is shared, thus the caller can still catch the exception if needed with future.get()
            return future;
        }

        // Rethrow the same exception
        throw;
    }
    m_updating_state = base::updating_status::notupdating;

    auto sig = m_service.signal<sight::service::signals::updated_t>(sight::service::signals::UPDATED);
    sig->async_emit(m_service.get_sptr());

    return future;
}

//-----------------------------------------------------------------------------

void service::auto_connect()
{
    sight::service::connections_t connection_map = m_service.auto_connections();
    m_auto_connected = false;

    for(const auto& [key, ptr] : m_service.container())
    {
        const auto& key_str     = key.first;
        data::object::csptr obj = ptr->get();
        const bool auto_connect = !ptr->auto_connect().has_value() || ptr->auto_connect().value();
        if(auto_connect && obj)
        {
            core::com::helper::sig_slot_connection::key_connections_t connections;
            bool connected = false;

            if(auto it = connection_map.find(key_str); it != connection_map.end())
            {
                connections = it->second;
                m_auto_connections.connect(obj, m_service.get_sptr(), connections);
                connected = true;
                if(dynamic_cast<data::property_base*>(ptr) == nullptr)
                {
                    m_auto_connected = true;
                }
            }

            // Connect the properties
            if(!connected && dynamic_cast<data::property_base*>(ptr) != nullptr)
            {
                const auto sig = obj->signal<data::signals::modified_t>(data::signals::MODIFIED);

                auto slot = m_service.slot(MAKE_PROPERTY_SLOT_NAME(std::string(key_str)));
                SIGHT_ASSERT("Slot not found for property: " << key_str, slot);
                m_auto_connections.add_connection(sig->connect(slot));
            }
        }
    }
}

//-----------------------------------------------------------------------------

void service::auto_disconnect()
{
    m_auto_connections.disconnect();
    m_auto_connected = false;
}

//------------------------------------------------------------------------------

bool service::is_auto_connected() const
{
    return m_auto_connected;
}

//------------------------------------------------------------------------------

bool service::is_key_optional(const std::string& _key) const
{
    const auto& container = m_service.container();
    if(auto it_data = container.find({_key, {}}); it_data != container.end())
    {
        return it_data->second->optional();
    }

    return false;
}

//-----------------------------------------------------------------------------

} // namespace sight::service::detail