Scoop API

scoop:scoop.asyncio:0.1.0

src/tcp_connect_trace.scoop

Selected production source · src/tcp_connect_trace.scoop

1package scoop.asyncio
3import scoop.platform.time.MonotonicTimeSource
4import scoop.time.TimeMark
6/**
7 * Distinguishes name resolution from connecting to an address.
8 */
9public enum TcpConnectPhase {
10 /**
11 * An address-family lookup phase.
12 */
13 Resolve,
14 /**
15 * A TCP connection-attempt phase.
16 */
17 Connect }
18/**
19 * The start or completion boundary of a traced phase.
20 */
21public enum TcpConnectEventKind {
22 /**
23 * The phase began.
24 */
25 Started,
26 /**
27 * The phase ended, including failure or cancellation.
28 */
29 Finished }
31/**
32 * A phase boundary recorded at a monotonic time mark.
33 */
34public class TcpConnectEvent internal constructor(
35 /**
36 * The operation phase being observed.
37 */
38 public val phase: TcpConnectPhase,
39 /**
40 * Whether this event starts or finishes the phase.
41 */
42 public val kind: TcpConnectEventKind,
43 /**
44 * The monotonic time mark at the phase boundary.
45 */
46 public val at: TimeMark
49internal class TcpConnectTrace(private val callback: (TcpConnectEvent) -> Unit) {
50 private var resolving: Boolean = false
51 private var resolved: Boolean = false
52 private var connecting: Boolean = false
53 private var connected: Boolean = false
54 private var failed: Boolean = false
56 fun start(phase: TcpConnectPhase) {
57 if (failed) return
58 when (phase) {
59 case Resolve -> { if (resolving) return; resolving = true }
60 case Connect -> { if (connecting) return; connecting = true }
61 }
62 notify(phase, TcpConnectEventKind.Started)
63 }
65 fun finish(phase: TcpConnectPhase) {
66 if (failed) return
67 when (phase) {
68 case Resolve -> { if (!resolving || resolved) return; resolved = true }
69 case Connect -> { if (!connecting || connected) return; connected = true }
70 }
71 notify(phase, TcpConnectEventKind.Finished)
72 }
74 private fun notify(phase: TcpConnectPhase, kind: TcpConnectEventKind) {
75 try { callback(TcpConnectEvent(phase, kind, MonotonicTimeSource.markNow())) }
76 catch (error: Throwable) { failed = true; throw error }
77 }