aboutsummaryrefslogtreecommitdiffstats
path: root/documentapi/src/vespa/documentapi/messagebus/policies/asyncinitializationpolicy.h
blob: fe1585eb62499b5982fefc06dcb98f6d6c8b113b (plain) (blame)
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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once

#include <vespa/messagebus/routing/iroutingpolicy.h>
#include <vespa/vespalib/util/executor.h>
#include <vespa/documentapi/common.h>
#include <map>
#include <mutex>

namespace documentapi {

class AsyncInitializationPolicy : public mbus::IRoutingPolicy {
public:
    AsyncInitializationPolicy(const std::map<string, string>& parameters);
    ~AsyncInitializationPolicy() override;

    static std::map<string, string> parse(string parameters);

    /**
     * This function is called asynchronously at some point after the
     * first select() is called.
     *
     * @return
     */
    virtual string init() = 0;

    void select(mbus::RoutingContext &context) override;

    virtual void doSelect(mbus::RoutingContext& context) = 0;

    const string& getError() {
        return _error;
    }

    void initSynchronous();

    /**
     * Signal that subclass should be async initialized. Must be called prior
     * to the first invocation of select().
     */
    void needAsynchronousInit() { _syncInit = false; }

private:
    class Task : public vespalib::Executor::Task
    {
    public:
        Task(AsyncInitializationPolicy& owner)
            : _owner(owner)
        {
        }

        Task(const Task&) = delete;
        Task& operator=(const Task&) = delete;

        void run() override;

    private:
        AsyncInitializationPolicy& _owner;
    };

    friend class Task;

    std::unique_ptr<vespalib::Executor> _executor;
    std::mutex _lock;

    enum class State {
        NOT_STARTED,
        RUNNING,
        FAILED,
        DONE
    };

    State _state;

protected:
    string _error;
    bool _syncInit;
};

}