From d1c36d18480298cc161318dafc815d5ed61c0c62 Mon Sep 17 00:00:00 2001 From: marisa Date: Fri, 16 Feb 2024 18:16:38 -0300 Subject: [PATCH] wip --- source/net/request_pool.d | 67 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 source/net/request_pool.d diff --git a/source/net/request_pool.d b/source/net/request_pool.d new file mode 100644 index 0000000..d715ddf --- /dev/null +++ b/source/net/request_pool.d @@ -0,0 +1,67 @@ +module net.request_pool; + +import core.thread; +import core.sync.semaphore; + +import std.container; +import std.uuid; + +import requests; +import slf4d; + +struct PRequest { + string method = "GET"; + string url; + string[string] params; + UUID uuid; /// Used internally +} + +class RequestPool { + private int m_totalWorkers; + private ThreadGroup m_threads; + private bool m_shouldRun = false; + private Semaphore m_semaphore; + + protected DList!PRequest m_requestsQueue; + + this(int totalWorkers = 4) { + this.m_totalWorkers = totalWorkers; + this.m_semaphore = new Semaphore(); + } + + void startBackground() { + debugF!"Starting RequestPool with %d workers"(this.m_totalWorkers); + this.m_shouldRun = true; + + for (int i = 0; i < this.m_totalWorkers; i++) { + Thread t = new Thread(() => this.m_run(i)); + this.m_threads.add(t); + } + + } + + void enqueue(PRequest request) { + request.uuid = randomUUID(); + this.m_requestsQueue.insertBack(request); + this.m_semaphore.notify(); + } + + void stop() { + this.m_shouldRun = false; + this.m_threads.joinAll(); + } + + private void m_run(immutable int tid) { + Request rq = Request(); + + while (this.m_shouldRun) { + this.m_semaphore.wait(); + PRequest request = this.m_requestsQueue.front(); + this.m_requestsQueue.removeFront(); + + debugF!"Requesting %s with tid %d"(request.url, tid); + + Response rs = rq.execute(request.method, request.url); + } + } +}