1 module tagion.services.locator;
2 
3 import core.thread;
4 import core.time;
5 import std.format;
6 import tagion.basic.tagionexceptions;
7 import tagion.logger.Logger;
8 import tagion.utils.pretend_safe_concurrency;
9 
10 /++
11 +/
12 @safe
13 class LocatorException : TagionException {
14     this(string msg, string file = __FILE__, size_t line = __LINE__) pure {
15         super(msg, file, line);
16     }
17 }
18 
19 @safe
20 struct LocatorOptions {
21     uint max_attempts = 5; // The number of times we try to locate the thread.
22     uint delay = 5; // Delay in msecs between next time we try to locate.
23 }
24 
25 public shared static immutable(LocatorOptions)* locator_options;
26 
27 /** 
28  * Tries to locate the the thread id. If it is not found we try until max_attempts. 
29  * Throws if no thread id was found.
30  * Params:
31  *   task_name = task name to locate
32  * Returns: Tid
33  */
34 Tid tryLocate(const(string) task_name) @trusted {
35     import std.stdio;
36 
37     assert(locator_options !is null, "The locator option was not set");
38 
39     uint tries;
40 
41     do {
42         auto task_id = locate(task_name);
43         if (task_id !is Tid.init) {
44             return task_id;
45         }
46         log.trace("trying to locate %s", task_name);
47         Thread.sleep(locator_options.delay.msecs);
48         tries++;
49     }
50     while (tries < locator_options.max_attempts);
51 
52     log.error("Thread with name: %s not found", task_name);
53     throw new LocatorException(format("task_name %s could not be located", task_name));
54     assert(0);
55 }