Class ::nsmcp::AccessAnalytics

::nsmcp::AccessAnalytics[i] create ... \
           [ -database:required database:required ] \
           [ -evictionLimit:integer (default "64") ] \
           [ -maxLineBytes:integer (default "65536") ] \
           [ -maxReadBytes:integer (default "16777216") ] \
           [ -maxRows:integer (default "2000000") ] \
           [ -maxSeconds:integer (default "2") ] \
           [ -mutex (default "") ] \
           [ -parser (default "::nsmcp::accessRecordParser") ] \
           [ -path:required path:required ] \
           [ -retentionSeconds:double (default "86400") ]

Defined in /usr/local/ns/tcl/nsmcp/log-peer-context.tcl

Class Relations

  • class: ::nx::Class[i]
  • superclass: ::nsmcp::AccessLogIngestor[i]
  • subclass: ::nsmcp::UnifiedAccessAnalytics[i]
::nx::Class create ::nsmcp::AccessAnalytics \
     -superclass ::nsmcp::AccessLogIngestor

Methods (to be applied on the object)

  • invalidRequestContextSQL (scripted, public)

     nsmcp::AccessAnalytics[i] invalidRequestContextSQL peerKey side

    Build the bounded SQL query for one side of a warning timestamp.

    Parameters:
    peerKey (required)
    Private peer digest as lowercase SHA-256 hex.
    side (required)
    Select requests before or at and after the warning.
    Returns:
    SQL with bind parameters for the time window.

    Testcases:
    No testcase defined.
    if {![regexp {^[0-9a-f]{64}$} $peerKey] || $side ni {before after}} {
        error "invalid warning context query"
    }
    if {$side eq "before"} {
        set condition {r.t>=:lo AND r.t<:at}
        set order DESC
        set limit 17
    } else {
        set condition {r.t>=:at AND r.t>=:lo AND r.t<:hi}
        set order ASC
        set limit 6
    }
    # Only a validated SHA-256 hex literal enters SQL. Values use bindings.
    return "SELECT r.t, r.status, substr(r.path,1,512) AS path,
        substr(r.method,1,32) AS method, substr(r.pool,1,128) AS pool,
        substr(r.source,1,32) AS source, substr(r.driver,1,128) AS driver,
        substr(r.label,1,1024) AS userAgent, r.clipped
        FROM main.rows r WHERE r.kind=0 AND $condition
        AND r.peer=X'$peerKey'
        AND EXISTS(SELECT 1 FROM main.files f WHERE f.fid=r.fid AND f.active=1)
        ORDER BY r.t $order LIMIT $limit"

Methods (to be applied on instances)

  • correlateDuplicatePeers (scripted, public)

     <instance of nsmcp::AccessAnalytics[i]> correlateDuplicatePeers \
        candidates total omitted

    Match bounded duplicate-parameter warnings to stored access requests. Called only for a peer-authorized summary. The identifier/time index bounds each lookup; ambiguous matches and missing retained addresses stay unknown.

    Parameters:
    candidates (required)
    At most 512 warning identifiers with time and direct metadata.
    total (required)
    All physical duplicate warnings in the selected window.
    omitted (required)
    Warnings without a usable identifier or beyond the bound.
    Returns:
    Typed JSON fields with peer and attention rankings.

    Testcases:
    No testcase defined.
    if {[llength $candidates]>512 || $total != [llength $candidates]+$omitted} {
        error "invalid duplicate warning correlation bounds"
    }
    if {![info exists :settings] || ![nsf::object::exists ${:database}]
        || ![${:database} info has type ::nsmcp::UnifiedAccessDatabase]} {
        return [list {} object [list available boolean false reason string continuous-access-store-required  warningRecords number $total candidateRecords number [llength $candidates] omittedRecords number $omitted]]
    }
    set began [clock milliseconds]
    set store [:accessRecordReaderOpen ${:settings}]
    try {
        set db [$store session]
        $db execute BEGIN
        set peerFloor [expr {[clock seconds]-[dict get ${:settings} peerRetention]}]
        set peers {}
        set resolved {}
        set missing 0
        set ambiguous 0
        set unknownAddress 0
        set botClaim 0
        set noBotClaim 0
        set unknownAgent 0
        set authenticated 0
        foreach candidate $candidates {
            set requestId [dict get $candidate requestIdentifier]
            set at [dict get $candidate timestamp]
            if {![::nsmcp::logRecordParser validConnectionIdentifier $requestId]
                || ![string match "-conn:[ns_info server]:*" $requestId]
                || ![string is double -strict $at]} {
                incr missing
                continue
            }
            set lo [expr {$at-60}]
            set hi [expr {$at+1}]
            set rows [$db execute {SELECT lower(hex(r.peer)) AS peer FROM main.rows r
                WHERE r.identifier=:requestId AND r.t>=:lo AND r.t<=:hi AND r.kind=0
                AND EXISTS(SELECT 1 FROM main.files f WHERE f.fid=r.fid AND f.active=1)
                LIMIT 2}]
            if {![llength $rows]} {incr missing; continue}
            if {[llength $rows]>1} {incr ambiguous; continue}
            set digest [dict get [lindex $rows 0] peer]
            if {![regexp {^[0-9a-f]{64}$} $digest]} {incr unknownAddress; continue}
            if {![dict exists $resolved $digest]} {
                set lookup "SELECT address FROM main.peer_addresses WHERE k=X'$digest' AND seen>=:peerFloor"
                set address [$db scalar $lookup]
                if {![ns_ip valid $address]} {set address {}}
                dict set resolved $digest $address
            }
            set address [dict get $resolved $digest]
            if {$address eq {}} {incr unknownAddress; continue}
            set auth [dict get $candidate authenticationState]
            if {$auth ni {anonymous authenticated unknown}} {set auth unknown}
            set agent [dict get $candidate userAgent]
            if {$agent eq {}} {
                set claim unknown
                incr unknownAgent
            } elseif {[regexp -nocase {bot|spider|crawl|scrap} $agent]} {
                set claim bot
                incr botClaim
            } else {
                set claim no-bot
                incr noBotClaim
            }
            if {$auth eq "authenticated"} {incr authenticated}
            if {![dict exists $peers $address]} {
                dict set peers $address {count 0 authenticationStates {anonymous 0 authenticated 0 unknown 0} botClaimRecords 0 noBotClaimRecords 0 unknownAgentRecords 0}
            }
            set entry [dict get $peers $address]
            dict incr entry count
            set states [dict get $entry authenticationStates]
            dict incr states $auth
            dict set entry authenticationStates $states
            if {$claim eq "bot"} {
                dict incr entry botClaimRecords
            } elseif {$claim eq "no-bot"} {
                dict incr entry noBotClaimRecords
            } else {
                dict incr entry unknownAgentRecords
            }
            dict set peers $address $entry
        }
        $db execute COMMIT
        set ranked {}
        dict for {address entry} $peers {
            set priority [expr {[dict get $entry authenticationStates authenticated]>0 ? 2 :
                ([dict get $entry noBotClaimRecords]>0 ? 1 : 0)}]
            lappend ranked [list $priority [dict get $entry count] $address $entry]
        }
        set ranked [lsort -integer -decreasing -index 0 [lsort -integer -decreasing -index 1 [lsort -index 2 $ranked]]]
        set rows {}
        set index 0
        set rankedOmitted 0
        foreach item $ranked {
            lassign $item priority count address entry
            if {$index>=20} {incr rankedOmitted $count; continue}
            set states {}
            dict for {name n} [dict get $entry authenticationStates] {lappend states $name number $n}
            lappend rows $index object [list peer string $address count number $count  authenticationStates object $states botClaimRecords number [dict get $entry botClaimRecords]  noBotClaimRecords number [dict get $entry noBotClaimRecords]  unknownAgentRecords number [dict get $entry unknownAgentRecords]]
            incr index
        }
        return [list {} object [list available boolean true scope string selected-duplicate-warning-records  warningRecords number $total candidateRecords number [llength $candidates]  omittedRecords number $omitted matchedWithAddress number [expr {$total-$omitted-$missing-$ambiguous-$unknownAddress}]  missingAccessRecords number $missing ambiguousAccessRecords number $ambiguous  unknownAddressRecords number $unknownAddress authenticatedRecords number $authenticated  botClaimRecords number $botClaim noBotClaimRecords number $noBotClaim  unknownAgentRecords number $unknownAgent distinctPeers number [dict size $peers]  peerOutputLimit number 20 peerRanking string authenticated-then-no-bot-claim-then-count  peers array $rows rankedOmittedPeers number [expr {[llength $ranked]-$index}]  rankedOmittedRecords number $rankedOmitted queryMilliseconds number [expr {[clock milliseconds]-$began}]  limitations string {Matches physical duplicate warnings to committed active access records by exact connection identifier and request start within 60 seconds before to 1 second after the warning. At most 512 warnings are joined; omittedRecords includes missing identifiers and capacity overflow. Missing or ambiguous access matches and expired or absent peer addresses remain unknown. Peer retention can be shorter than request retention. Bot claim means a case-insensitive bot/spider/crawl/scrap token in the warning User-Agent; no-bot claim does not establish a human. Authentication comes from the warning diagnostic, not a User-Agent or pool. IP addresses do not identify people. Suppressed occurrences have no individual request identifiers and are excluded.}]]
    } finally {
        $store close
    }
  • correlateInvalidRequests (scripted, public)

     <instance of nsmcp::AccessAnalytics[i]> correlateInvalidRequests \
        samples redactor

    Return bounded all-status context for sampled invalid-request warnings. Query retained unified records by private peer digest and a short time range. Do not import logs, expose peer keys, or infer TCP connection identity.

    Parameters:
    samples (required)
    At most twelve dictionaries with timestamp, offset and peerKey.
    redactor (required)
    Output redactor for paths and self-reported User-Agents.
    Returns:
    JSON triples with sampled sequences, redirect counts and limits.

    Testcases:
    No testcase defined.
    if {[llength $samples]>12} {error "too many invalid-request warning samples"}
    foreach sample $samples {
        if {![dict exists $sample peerKey] || ![regexp {^[0-9a-f]{64}$} [dict get $sample peerKey]]
            || ![dict exists $sample timestamp] || ![string is double -strict [dict get $sample timestamp]]
            || ![dict exists $sample offset] || ![string is wideinteger -strict [dict get $sample offset]]} {
            error "invalid invalid-request warning sample"
        }
        set timestamp [dict get $sample timestamp]
        if {[catch {expr {$timestamp>=0 && $timestamp<[clock seconds]+3600}} valid] || !$valid} {
            error "invalid invalid-request warning timestamp"
        }
    }
    if {![info exists :settings] || ![nsf::object::exists ${:database}]
        || ![${:database} info has type ::nsmcp::UnifiedAccessDatabase]} {
        return [list {} object [list available boolean false reason string continuous-access-store-required]]
    }
    set began [clock milliseconds]
    set store [:accessRecordReaderOpen ${:settings}]
    try {
        set db [$store session]
        $db execute BEGIN
        set floor [expr {max([$store stateGet retentionFloor 0],
            wide(floor(([clock seconds]-[dict get ${:settings} retention])/60.0))*60)}]
        set entries {}
        set index 0
        set matched 0
        set redirects 0
        set redirects302 0
        set limited 0
        foreach sample $samples {
            set at [dict get $sample timestamp]
            set lo [expr {max($floor,$at-30)}]
            set hi [expr {$at+6}]
            set peerKey [dict get $sample peerKey]
            set before [$db execute [::nsmcp::AccessAnalytics invalidRequestContextSQL $peerKey before]]
            set after [$db execute [::nsmcp::AccessAnalytics invalidRequestContextSQL $peerKey after]]
            set truncated [expr {[llength $before]>16 || [llength $after]>5}]
            incr limited $truncated
            set before [lrange $before 0 15]
            set after [lrange $after 0 4]
            set records {}
            set n 0
            set hasRedirect false
            set has302 false
            foreach row [concat [lreverse $before] $after] {
                set time [dict get $row t]
                set relation [expr {$time<$at ? "before" : ($time<$at+1 ? "same-second" : "after")}]
                set status [dict get $row status]
                if {$relation eq "before" && $status in {300 301 302 303 307 308}} {
                    set hasRedirect true
                    if {$status==302} {set has302 true}
                }
                set fields [list requestStart number $time requestStartOffsetSeconds number [expr {$time-$at}]  relation string $relation status number $status]
                foreach key {path method pool source driver userAgent} {
                    set text [dict get $row $key]
                    if {$key eq "path"} {set text [lindex [split $text ?] 0]}
                    lappend fields $key string [$redactor message $text]
                }
                lappend fields userAgentMayBeTruncated boolean [expr {[dict get $row clipped] || [string length [dict get $row userAgent]]>=1024}]
                lappend records $n object $fields
                incr n
            }
            if {$n>0} {incr matched}
            if {$hasRedirect} {incr redirects}
            if {$has302} {incr redirects302}
            lappend entries $index object [list warningTimestamp number $at warningOffset number [dict get $sample offset]  records array $records returnedRecords number $n recordsTruncated boolean $truncated  precedingRedirectObserved boolean $hasRedirect preceding302Observed boolean $has302  retentionClipped boolean [expr {$lo>$at-30}]]
            incr index
        }
        $db execute COMMIT
        set sourcePaths [list ${:path} {*}${:additionalPaths}]
        if {[nsv_exists nsmcp:access-sources:[ns_info server] paths]} {
            set sourcePaths [nsv_get nsmcp:access-sources:[ns_info server] paths]
        }
        set sourceNames [lsort -unique [lmap path $sourcePaths {
            file tail $path
        }]]
        set sourceFields {}
        set sourceIndex 0
        foreach name $sourceNames {
            lappend sourceFields $sourceIndex string $name
            incr sourceIndex
        }
        return [list {} object [list available boolean true scope string sampled-warning-same-peer-context  searchedAccessLogFiles array $sourceFields  beforeSeconds number 30 afterSeconds number 5 warningTimestampResolutionSeconds number 1  beforeRecordLimit number 16 afterRecordLimit number 5  matchedWarnings number $matched missingWarnings number [expr {[llength $samples]-$matched}]  warningsWithPrecedingRedirect number $redirects warningsWithPreceding302 number $redirects302  recordLimitedWarnings number $limited sequences array $entries  queryMilliseconds number [expr {max(0,[clock milliseconds]-$began)}]  limitations string {Same logged peer and nearby request start times are contextual association, not proof of one TCP connection, client identity, redirect following or causation. Multiple clients can share an address. Warning times have one-second resolution: requests in that second are labeled same-second, not preceding. A preceding start does not establish response completion before the warning. No redirect Location is available. Includes all statuses, not just 400. Only committed, active-source records within retention are queried. The searchedAccessLogFiles list names the configured files; a warning from another virtual server may have no corresponding access log in this store. Ingestion lag, missing imports and retention can also hide context. Missing context is unknown, not proof of probing. Counts describe sampled warnings and bounded returned records, not population rates. No peer addresses or peer digests are returned.}]]
    } finally {
        $store close
    }
  • correlatePeerHistory (scripted, public)

     <instance of nsmcp::AccessAnalytics[i]> correlatePeerHistory \
        candidates redactor

    Read at most five peers and 128 recent requests per peer from partitions with a peer/time index. No unindexed fallback or log import is attempted.

    Parameters:
    candidates (required)
    redactor (required)

    Testcases:
    No testcase defined.
    if {[llength $candidates]>5} {error "too many peer history candidates"}
    if {![info exists :settings] || ![nsf::object::exists ${:database}]} {
        return [dict create available false reason continuous-access-store-required histories {}]
    }
    if {![dict exists ${:settings} partitionInterval] || [dict get ${:settings} partitionInterval]<=0} {
        return [dict create available false reason partitioned-peer-index-required histories {}]
    }
    set store [:accessRecordReaderOpen ${:settings}]
    try {
        set db [$store session]
        set histories {}
        set index 0
        foreach candidate $candidates {
            set samples [dict get $candidate samples]
            set at [dict get [lindex $samples 0] timestamp]
            set peerKey [dict get [lindex $samples 0] peerKey]
            if {![regexp {^[0-9a-f]{64}$} $peerKey]} {error "invalid peer history key"}
            set lo [expr {max($at-43200,[clock seconds]-[dict get ${:settings} retention])}]
            set hi [expr {min($at+43200,[clock seconds]+1)}]
            set rows {}
            set indexed true
            foreach part [$db execute {SELECT name FROM main.partitions
                WHERE stop>:lo AND start<:hi ORDER BY start}] {
                set name [dict get $part name]
                if {![regexp {^p_[0-9]+$} $name]} {error "record-store-invalid-partition"}
                if {![$db scalar "SELECT EXISTS(SELECT 1 FROM main.sqlite_schema
                    WHERE type='index' AND name='${name}_peer_time')"]} {
                    set indexed false
                    break
                }
                foreach row [$db execute "SELECT r.t,r.status,substr(r.path,1,512) AS path,
                    substr(r.method,1,32) AS method,substr(r.label,1,1024) AS userAgent
                    FROM main.$name r WHERE r.kind=0 AND r.peer=X'$peerKey'
                    AND r.t>=:lo AND r.t<:hi
                    AND EXISTS(SELECT 1 FROM main.files f WHERE f.fid=r.fid AND f.active=1)
                    ORDER BY r.t DESC LIMIT 129"] {
                    lappend rows [list [dict get $row t] $row]
                }
            }
            set records {}
            if {$indexed} {
                set rows [lrange [lsort -real -decreasing -index 0 $rows] 0 128]
                set clipped [expr {[llength $rows]>128}]
                foreach pair [lrange $rows 0 127] {
                    set row [lindex $pair 1]
                    lappend records [dict create status [dict get $row status]  path [$redactor message [lindex [split [dict get $row path] ?] 0]]  method [dict get $row method]  userAgent [$redactor message [dict get $row userAgent]]]
                }
            } else {
                set clipped false
            }
            lappend histories [dict create available $indexed  reason [expr {$indexed ? {} : "peer-index-unavailable"}]  from $lo to $hi  returnedRecords [llength $records] recordsTruncated $clipped  records $records]
            incr index
        }
        return [dict create available true histories $histories scope indexed-same-peer-history]
    } finally {$store close}
  • correlateWarnings (scripted, public)

     <instance of nsmcp::AccessAnalytics[i]> correlateWarnings samples \
        redactor

    Correlate bounded warning examples with retained access records. Use the existing start-time index only; do not scan raw logs or trigger ingestion or historical backfill. Peer addresses are never selected.

    Parameters:
    samples (required)
    Up to three dictionaries with requestIdentifier and timestamp; optional system-log User-Agent fields take precedence over the cached agent.
    redactor (required)
    Redactor object applied before returning diagnostic evidence.
    Returns:
    Rooted JSON triples with sampled evidence and explicit missing and ambiguous counts.

    Testcases:
    No testcase defined.
    if {[llength $samples] > 3} {
        error "Too many warning correlation samples"
    }
    set fields {}
    set matched 0
    set missing 0
    set ambiguous 0
    set i 0
    # UnifiedAccessDatabase supplies a multi-call record-store adapter here;
    # keep its connect/close ownership rather than checking out another handle.
    set db [${:database} connect]
    try {
        foreach sample $samples {
            set request_id [dict get $sample requestIdentifier]
            set at [dict get $sample timestamp]
            if {![::nsmcp::logRecordParser validConnectionIdentifier $request_id]
                || ![string match "-conn:[ns_info server]:*" $request_id]
                || ![string is double -strict $at]} {
                incr missing
                continue
            }
            set lower [expr {$at-60}]
            set upper [expr {$at+1}]
            set rows [$db execute {SELECT request_id,start,path,pool,method,status,authenticationState,userAgent
                FROM nsmcp_access_requests WHERE start >= :lower AND start <= :upper
                AND request_id=:request_id LIMIT 2}]
            if {[llength $rows] == 0} {
                incr missing
                continue
            }
            if {[llength $rows] > 1} {
                incr ambiguous
                continue
            }
            set row [lindex $rows 0]
            set item {}
            set uaSource access-cache
            set authSource access-cache
            if {[dict exists $sample authenticationState] && [dict get $sample authenticationState] in {anonymous authenticated}} {
                dict set row authenticationState [dict get $sample authenticationState]
                set authSource system-log
            }
            set uaTruncated [expr {[string length [dict get $row userAgent]] >= 1024}]
            if {[dict exists $sample userAgent]} {
                dict set row userAgent [dict get $sample userAgent]
                set uaSource system-log
                set uaTruncated [dict get $sample userAgentMayBeTruncated]
            }
            foreach key {path pool method authenticationState userAgent} {
                lappend item $key string [$redactor message [dict get $row $key]]
            }
            lappend item requestIdentifier string $request_id start number [dict get $row start]  status number [dict get $row status] warningTimestamp number $at authenticationSource string $authSource  userAgentAvailable boolean [expr {[dict get $row userAgent] ne ""}]  userAgentSource string $uaSource userAgentMayBeTruncated boolean $uaTruncated
            lappend fields $i object $item
            incr i
            incr matched
        }
    } finally {
        $db close
    }
    return [list {} object [list available boolean true scope string sampled-warning-requests  requested number [llength $samples] matched number $matched missing number $missing ambiguous number $ambiguous  records array $fields limitations string {Bounded examples, not aggregate bot attribution. Exact connection identifier and start time within 60 seconds before to 1 second after the warning are required. Cache lag, eviction, long requests, legacy rows without User-Agent, and absent identifiers can prevent matches. No raw access-log scan or cache refresh was performed. Multiple candidates are not attributed. Pool and User-Agent alone do not prove bot or human identity. No peer addresses are returned.}]]
  • summary (scripted, public)

     <instance of nsmcp::AccessAnalytics[i]> summary options

    Summarize stored access traffic in one database snapshot. Compute coverage and aggregates together under the instance mutex, closing the session on every exit.

    Parameters:
    options (required)
    Tcl dictionary containing the operation options.
    Returns:
    The summary dictionary with aggregates and explicit coverage.

    Testcases:
    No testcase defined.
    # Use the scanner coverage and a single snapshot for all aggregates.
    # Hold a single SQLite snapshot for coverage and all aggregate queries.
    ns_mutex lock ${:mutex}
    try {
        # This shared reader also accepts UnifiedAccessDatabase adapters.
        set :db [${:database} connect]
        set :batchRows 0
        ${:db} execute {BEGIN}
        set options [:validateWindow $options]
        :peerSchema ${:db}
        set plain $options
        foreach key {path status pool peer authenticationState windowSeconds includePeerAddresses} {
            dict unset plain $key
        }
        # Coverage and counts share the same read transaction.
        set result [:summaryLocked $plain]
        set filters {}
        foreach key {path status pool peer authenticationState} {
            if {[dict exists $options $key]} {
                dict set filters $key [dict get $options $key]
            }
        }
        dict set result filters $filters
        set db ${:db}
        set from [dict get $result from]
        set to [dict get $result to]
        set where {start >= $from AND start < $to}
        foreach key {path status pool peer authenticationState} {
            if {[dict exists $options $key]} {
                set $key [dict get $options $key]
                append where " AND $key = \$$key"
            }
        }
        $db execute -arrayName row -script {
            foreach key $row(*) {
                dict set result $key $row($key)
            }
        } "SELECT count(*) AS requestCount,coalesce(sum(bytes),0) AS responseBytes,
            coalesce(sum(fallback),0) AS fallbackCount,coalesce(sum(excluded),0) AS excludedPaths,
            count(run) AS timingCount,coalesce(sum(accept),0) AS acceptTotal,
            coalesce(sum(queue),0) AS queueTotal,coalesce(sum(filter),0) AS filterTotal,
            coalesce(sum(run),0) AS runTotal,coalesce(max(run),0) AS runMax FROM nsmcp_access_requests WHERE $where"
        dict set result unavailableTimingCount [expr {[dict get $result requestCount]-[dict get $result timingCount]}]
        dict set result timingScope {Worker phase timings only; driver synthetic phases are unavailable, not measured zeros.}
        foreach {dimension column} {pools pool methods method statuses status paths path} {
            set counts {}
            # Bounded output, but count all matching rows in totals above.
            $db execute -arrayName row -script {
                if {$dimension eq "paths" && $row(label) eq ""} {
                    continue
                }
                dict set counts $row(label) $row(n)
            } "SELECT $column AS label,count(*) AS n FROM nsmcp_access_requests WHERE $where GROUP BY $column ORDER BY n DESC LIMIT 1000"
            dict set result $dimension $counts
        }
        set tracked 0
        dict for {label count} [dict get $result paths] {
            incr tracked $count
        }
        dict set result excludedPaths [expr {[dict get $result requestCount]-$tracked}]
        set statusTimings {}
        $db execute -arrayName row -script {
            lappend statusTimings [dict create status $row(status) requestCount $row(n) timingCount $row(timed) filterTotal $row(filters) runTotal $row(runs) runMax $row(maximum)]
        } "SELECT status,count(*) AS n,count(run) AS timed,coalesce(sum(filter),0) AS filters,
            coalesce(sum(run),0) AS runs,coalesce(max(run),0) AS maximum FROM nsmcp_access_requests WHERE $where GROUP BY status"
        dict set result statusTimings $statusTimings
        set authentication {}
        $db execute -arrayName row -script {
            dict set authentication $row(authenticationState) [dict create requestCount $row(n) status503Count $row(rejected) successfulCount $row(successful) successfulTimingCount $row(timed) successfulRunTotal $row(runs)]
        } "SELECT authenticationState,count(*) AS n,sum(status=503) AS rejected,
            sum(status BETWEEN 200 AND 299) AS successful,
            count(CASE WHEN status BETWEEN 200 AND 299 THEN run END) AS timed,
            coalesce(sum(CASE WHEN status BETWEEN 200 AND 299 THEN run END),0) AS runs
            FROM nsmcp_access_requests WHERE $where GROUP BY authenticationState"
        dict set result authenticationStates $authentication
        set unknownPeers [$db scalar "SELECT count(*) FROM nsmcp_access_requests WHERE $where AND peer = ''"]
        dict set result coverage unknownPeerCount $unknownPeers
        dict set result coverage peerCountsComplete [expr {$unknownPeers==0 && [dict get $result coverage windowComplete]}]
        if {[dict exists $options windowSeconds] && [dict get $options windowSeconds] > 0} {
            # RANGE counts all equal timestamps together and uses an inclusive
            # [end-windowSeconds,end] range clipped to the selected period.
            # SQLite performs the rolling calculation rather than Tcl fetching rows.
            set seconds [dict get $options windowSeconds]
            set burst [dict create windowSeconds $seconds requestCount 0 from {} to {}]
            $db execute -arrayName row -script {
                dict set burst requestCount $row(n)
                dict set burst from [expr {max(double($from),$row(start)-$seconds)}]
                dict set burst to $row(start)
                if {[dict exists $options includePeerAddresses] && [dict get $options includePeerAddresses]} {
                    dict set burst peerAddress $row(peer)
                }
            } "SELECT peer,start,n FROM (
                SELECT peer,start,count(*) OVER (
                    PARTITION BY peer ORDER BY start RANGE BETWEEN \$seconds PRECEDING AND CURRENT ROW) AS n
                FROM nsmcp_access_requests WHERE $where AND peer != ''
            ) ORDER BY n DESC,start,peer LIMIT 1"
            dict set result peerBurst $burst
        }
        set size [dict get $result bucketSeconds]
        set counts [dict get $result buckets]
        $db execute -arrayName row -script {
            dict set counts $row(slot) $row(n)
        } "SELECT cast(start/\$size AS INTEGER)*\$size AS slot,count(*) AS n FROM nsmcp_access_requests WHERE $where GROUP BY slot"
        dict set result buckets $counts
        dict set result pathCountsComplete [expr {[dict get $result excludedPaths]==0}]
        set retained [$db scalar {SELECT coalesce(min(start),'') FROM nsmcp_access_requests}]
        set through [$db scalar {SELECT value FROM nsmcp_access_metadata WHERE key='droppedThrough'}]
        set evictionAt [$db scalar {SELECT value FROM nsmcp_access_metadata WHERE key='lastEvictionAt'}]
        dict set result coverage source ${:path}
        dict set result coverage retainedRequestFrom $retained
        dict set result coverage droppedThrough $through
        dict set result coverage lastEvictionAt $evictionAt
        set evicted [expr {$through ne "" && $from <= $through}]
        dict set result coverage evictionOverlap $evicted
        if {$evicted} {
            dict set result coverage windowComplete false
            set reasons [dict get $result coverage incompleteReasons]
            lappend reasons eviction
            dict set result coverage incompleteReasons $reasons
        }
        dict set result coverage peerCountsComplete [expr {$unknownPeers==0 && [dict get $result coverage windowComplete]}]
        dict set result coverage observedPeerCountsComplete [expr {$unknownPeers==0}]
        set peerReasons {}
        if {$unknownPeers} {
            lappend peerReasons missing-peer-fields-in-cached-records
        }
        if {![dict get $result coverage windowComplete]} {
            lappend peerReasons window-coverage-incomplete
            foreach reason [dict get $result coverage incompleteReasons] {
                lappend peerReasons "window:$reason"
            }
        }
        dict set result coverage peerCountsIncompleteReasons $peerReasons
        dict set result coverage databaseBytes [file size [${:database} path]]
        dict set result coverage storageBudgetBytes [${:database} cget -maxBytes]
        set events {}
        $db execute -arrayName row -script {
            lappend events [dict create droppedAt $row(dropped_at) from $row(first_time) to $row(last_time) rowCount $row(rows) reason $row(reason)]
        } {SELECT * FROM nsmcp_access_evictions ORDER BY id DESC}
        dict set result evictions $events
        ${:db} execute {COMMIT}
        return $result
    } finally {
        if {[info exists :db]} {
            ${:db} close
            unset :db
        }
        unset -nocomplain :batchRows
        ns_mutex unlock ${:mutex}
    }
  • validateWindow (scripted, public)

     <instance of nsmcp::AccessAnalytics[i]> validateWindow options

    Validate summary windows and access-record filters. Keep supported filter options separate while the superclass validates time and bucket bounds.

    Parameters:
    options (required)
    Tcl dictionary containing the operation options.
    Returns:
    The normalized options dictionary, including retained filters.

    Testcases:
    No testcase defined.
    set extra {}
    foreach key {path status pool peer authenticationState windowSeconds includePeerAddresses} {
        if {![dict exists $options $key]} {
            continue
        }
        set value [dict get $options $key]
        if {$key eq "windowSeconds"} {
            if {![string is entier -strict $value] || $value<0 || $value>3600} {
                error "windowSeconds must be between 0 and 3600"
            }
        } elseif {$key eq "includePeerAddresses"} {
            if {![string is boolean -strict $value]} {
                error "includePeerAddresses must be boolean"
            }
        } elseif {$key eq "peer"} {
            if {![ns_ip valid $value]} {
                error "peer must be a valid IP address"
            }
        } elseif {$key eq "authenticationState"} {
            if {$value ni {anonymous authenticated unknown}} {
                error "Invalid authenticationState"
            }
        } elseif {$key eq "status"} {
            if {![string is entier -strict $value] || $value<100 || $value>599} {
                error "status must be between 100 and 599"
            }
        } elseif {$value eq "" || [string length $value]>512 || [string first \x00 $value]>=0} {
            error "invalid exact path or pool filter"
        }
        dict set extra $key $value
        dict unset options $key
    }
    return [dict merge [next [list $options]] $extra]