dymokomi/luce-server
Source of release 0.5.1
0.5.1 / src / internal / pool.lucb
## A fixed pool accepts from one nonblocking listener. There is no thread per
## connection and no unbounded userspace accept queue; the OS backlog is bounded.
import io
import internal.dispatch_queue
import internal.http_connection
import internal.lifecycle
from internal.model import State, WorkKind
import internal.request_state
import internal.shutdown
import internal.wire
import memory
from luce_std import net
import thread
func worker(context: void*?):
let state = (State*)(context else return)
while not state.cancellation.is_requested() and not state.lifecycle.draining.load(.acquire):
let deadline = net.Deadline.after(100000000) catch:
lifecycle.stop(state)
return
_ = state.listener.wait(deadline = deadline, cancellation = &state.cancellation) catch failure:
if failure.code == net.timed_out:
continue
if failure.code != net.cancelled:
_ = state.counters.failures.add(1, .relaxed)
lifecycle.stop(state)
return
var accepted = state.listener.accept(true) catch failure:
if failure.code == io.would_block:
continue
_ = state.counters.failures.add(1, .relaxed)
thread.sleep(10)
continue
let slot = new net.Connection[1] --- in memory.heap catch failure:
accepted.destroy()
_ = state.counters.failures.add(1, .relaxed)
continue
defer free(slot) in memory.heap
slot[0] = accepted
let connection = &slot[0]
defer connection.destroy()
if state.cancellation.is_requested() or state.lifecycle.draining.load(.acquire):
return
_ = state.counters.accepted.add(1, .relaxed)
_ = state.counters.active.add(1, .acq_rel)
defer _ = state.counters.active.sub(1, .acq_rel)
if state.config.raw_socket:
let pending = request_state.make_request(state, false) catch failure:
_ = state.counters.failures.add(1, .relaxed)
continue
defer request_state.release_request(pending)
pending.kind = WorkKind.tcp
pending.session_connection = connection
_ = dispatch_queue.submit(pending)
else:
var final_started = false
http_connection.serve(connection, state, &final_started) catch failure:
_ = state.counters.failures.add(1, .relaxed)
if not final_started:
wire.fail(connection, state, wire.error_status(failure.code))
pub func start(state: State*) -> !:
errdefer shutdown.join(state)
state.lifecycle.threads[0] = try thread.spawn(lifecycle.clock_worker, (void*)state, name = "luce-clock")
state.lifecycle.thread_count = 1
for index in 0..<state.config.network_threads:
state.lifecycle.threads[state.lifecycle.thread_count] = try thread.spawn(worker, (void*)state, name = "luce-network")
state.lifecycle.thread_count += 1
state.lifecycle.started.store(true, .release)