Class ::nsmcp::UnifiedAccessAnalytics

::nsmcp::UnifiedAccessAnalytics[i] create ... \
           [ -additionalPaths (default "") ] \
           [ -database:required database:required ] \
           [ -dynamicSources (default "false") ] \
           [ -evictionLimit:integer (default "64") ] \
           [ -ingestBytes:integer (default "16777216") ] \
           [ -ingestMilliseconds:integer (default "2000") ] \
           [ -legacyDatabase (default "") ] \
           [ -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 ] \
           [ -retentionBatchRows:integer (default "1000") ] \
           [ -retentionInterval (default "30") ] \
           [ -retentionMilliseconds:integer (default "1000") ] \
           [ -retentionRetryInterval (default "5") ] \
           [ -retentionSeconds:double (default "86400") ] \
           [ -settings:required settings:required ] \
           [ -sourceReady (default "false") ]

Defined in /usr/local/ns/tcl/nsmcp/log-traffic-unified.tcl

Class Relations

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

Methods (to be applied on instances)

  • correlateWarnings (scripted, public)

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

    Correlate warnings with unified stored requests. Delegate through bounded store retry while preserving the caller's sample list and redactor.

    Parameters:
    samples (required)
    Bounded warning sample records to correlate with retained access evidence.
    redactor (required)
    Redactor object applied before returning diagnostic evidence.
    Returns:
    The warning correlation evidence.

    Testcases:
    No testcase defined.
    return [:accessRecordRetry ${:settings} [list next [list $samples $redactor]]]
  • ingest (scripted, public)

     <instance of nsmcp::UnifiedAccessAnalytics[i]> ingest [ from ] \
        [ allowHistory ]

    Provide the compatibility entry point for an administrative refresh. Legacy range arguments remain accepted; the unified ingestor controls its live and historical work through refresh.

    Parameters:
    from (optional)
    Starting timestamp or byte position, as required by the operation.
    allowHistory (optional, defaults to "true")
    Whether this pass may process historical sources. Defaults to 'true'.
    Returns:
    The bounded refresh result.

    Testcases:
    No testcase defined.
    # Compatibility entry point for explicit administrative refreshes only.
    return [:refresh]
  • ingestionStatus (scripted, public)

     <instance of nsmcp::UnifiedAccessAnalytics[i]> ingestionStatus

    Read current and last-run ingestion progress. Use the retained ingestion status instead of triggering a scan or ingestion pass.

    Returns:
    The ingestion status dictionary.

    Testcases:
    No testcase defined.
    return [::nsmcp::AccessWorkerStatus ingestion]
  • refresh (scripted, public)

     <instance of nsmcp::UnifiedAccessAnalytics[i]> refresh

    Run a bounded unified ingestion pass under the writer gate. Reject overlapping writers, publish phase and commit statistics, and always finish the run token before releasing the gate.

    Returns:
    The ingestion result, or a busy dictionary when another writer owns the gate.

    Testcases:
    No testcase defined.
    set gate nsmcp:unified-writer:[ns_info server]
    # Give a waiting maintenance callback one bounded opportunity to run.
    # Expiry prevents a lost callback from indefinitely stopping ingestion.
    set backlog [accessBacklogStatus]
    if {[nsv_exists $gate retentionUntil]
        && [nsv_get $gate retentionUntil]>[clock seconds]
        && (![dict get $backlog available] || [dict get $backlog caughtUp])} {
        return {busy true}
    }
    if {[nsv_incr $gate busy]!=1} {
        nsv_incr $gate busy -1
        return {busy true}
    }
    set run {}
    set outcome error
    set result {}
    set ::nsmcp::accessIngestionActive 1
    try {
        set run [accessIngestionBegin]
        set result [:accessRecordRetry ${:settings} [list :refreshLocked $run] {} [list ::nsmcp::accessIngestionProgress $run retry]]
        set outcome [expr {[dict exists $result busy] ? "pool-busy" : "ok"}]
        if {![dict exists $result busy]} {
            nsv_unset -nocomplain nsmcp:access-store:[ns_info server] lastFailure
        }
        return $result
    } on error {message options} {
        set result [accessUnifiedFailure ${:settings} $options ingestion $message]
        return $result
    } finally {
        try {
            accessIngestionFinish $run $outcome $result
        } finally {
            nsv_incr $gate busy -1
            unset ::nsmcp::accessIngestionActive
        }
    }
  • retain (scripted, public)

     <instance of nsmcp::UnifiedAccessAnalytics[i]> retain

    Perform bounded retention maintenance under the writer gate. Avoid overlapping ingestion while pruning expired store state and retaining maintenance statistics.

    Returns:
    The retention result, including a busy indication when the gate is occupied.

    Testcases:
    No testcase defined.
    # Share the writer gate: maintenance never overlaps ingestion and never
    # waits for a running importer. Readers retain their WAL snapshots.
    set gate nsmcp:unified-writer:[ns_info server]
    set backlog [accessBacklogStatus]
    if {![dict get $backlog available] || [dict get $backlog caughtUp]} {
        nsv_set $gate retentionUntil [expr {[clock seconds]+5}]
    } else {
        nsv_unset -nocomplain $gate retentionUntil
    }
    if {[nsv_incr $gate busy]!=1} {
        nsv_incr $gate busy -1
        return {busy true}
    }
    nsv_unset -nocomplain $gate retentionUntil
    set key nsmcp:access-retention:[ns_info server]
    set token [nsv_incr $key sequence]
    set began [clock clicks -milliseconds]
    set store {}
    set outcome error
    set counts {requests 0 diagnostics 0 minutes 0 peers 0}
    set batches 0
    set more false
    set code {}
    set last [expr {[nsv_exists $key state] ? [dict get [nsv_get $key state] lastRun] : {}}]
    nsv_set $key state [dict create token $token running true startedAt [clock seconds] startedTicks $began phaseTicks $began phase open-store phaseMilliseconds {} deleted $counts lastRun $last]
    try {
        set store [:accessRecordStoreOpen ${:settings} writer [list ::nsmcp::accessRetentionPhase $token]]
        if {![$store available]} {
            set outcome pool-busy
            return {busy true}
        }
        while {$batches==0 || [clock clicks -milliseconds]-$began<${:retentionMilliseconds}} {
            accessRetentionPhase $token prune
            set removed [$store prune ${:retentionBatchRows}]
            incr batches
            set total 0
            dict for {table n} $removed {
                dict incr counts $table $n
                incr total $n
            }
            set state [nsv_get $key state]
            dict set state deleted $counts
            nsv_set $key state $state
            if {$total==0} {
                break
            }
        }
        accessRetentionPhase $token pressure-check
        set pressure [$store maintenancePressure]
        set more [dict get $pressure expired]
        set outcome ok
        return [dict create deleted $counts batches $batches more $more  durationMs [expr {max(0,[clock clicks -milliseconds]-$began)}]]
    } on error {message options} {
        set code {NSMCP RETENTION operation-failed}
        set candidate [dict get $options -errorcode]
        if {[lrange $candidate 0 1] eq {NSMCP RECORD_STORE} && [regexp {^[a-z][a-z0-9-]{0,63}$} [lindex $candidate 2]]} {
            set code [lrange $candidate 0 2]
        }
        ns_log warning "nsmcp: retention cleanup paused ($code); ingestion checkpoints preserved"
        return [dict create failed true code $code]
    } finally {
        try {
            if {$store ne {}} {
                accessRetentionPhase $token close-store
                $store close
            }
        } finally {
            accessRetentionPhase $token finished
            set state [nsv_get $key state]
            set last [dict create startedAt [dict get $state startedAt] finishedAt [clock seconds] durationMs [expr {max(0,[clock clicks -milliseconds]-$began)}] outcome $outcome deleted $counts batches $batches more $more phaseMilliseconds [dict get $state phaseMilliseconds]]
            if {$code ne {}} {
                dict set last code $code
            }
            dict set state running false
            dict set state lastRun $last
            nsv_set $key state $state
            nsv_incr $gate busy -1
        }
    }
  • retentionStatus (scripted, public)

     <instance of nsmcp::UnifiedAccessAnalytics[i]> retentionStatus

    Read current retention-maintenance status. Return retained maintenance observations without starting another pruning pass.

    Returns:
    The retention status dictionary.

    Testcases:
    No testcase defined.
    return [::nsmcp::AccessWorkerStatus retention]
  • retentionTick (scripted, public)

     <instance of nsmcp::UnifiedAccessAnalytics[i]> retentionTick

    Run and reschedule one retention-maintenance callback. Use a one-shot scheduling chain so maintenance retries do not phase-lock with the ingestion timer.

    Returns:
    The scheduler callback result.

    Testcases:
    No testcase defined.
    # A single threaded one-shot chain avoids phase-locking a periodic
    # maintenance timer to the ingestion timer. Busy work retries later.
    set delay ${:retentionInterval}
    set began [clock clicks -milliseconds]
    try {
        set result [:retain]
        if {[dict exists $result busy] || [:dict getdef $result more false]} {
            # Leave at least two run durations idle after cleanup. The cap
            # bounds adaptive backoff; the configured minimum always wins.
            set duration [expr {max([:dict getdef $result durationMs 0],
                                   [clock clicks -milliseconds]-$began)}]
            set delay [expr {max(${:retentionRetryInterval},
                                min(${:retentionInterval},ceil(2.0*$duration/1000.0)))}]
        }
        set key nsmcp:access-retention:[ns_info server]
        if {[nsv_exists $key state]} {
            set state [nsv_get $key state]
            dict set state nextDelaySeconds $delay
            dict set state nextRunAt [expr {[clock seconds]+int(ceil($delay))}]
            nsv_set $key state $state
        }
        return $result
    } finally {
        catch {
            ns_schedule_proc -once -thread $delay [self] retentionTick
        }
    }
  • slowDay (scripted, public)

     <instance of nsmcp::UnifiedAccessAnalytics[i]> slowDay options

    The day chart reads only the ingestion minute rollup. It never runs access_summary's detailed-row aggregation over a whole day.

    Parameters:
    options (required)

    Testcases:
    No testcase defined.
    set date [dict get $options date]
    set timezone [dict get $options timezone]
    set from [clock scan $date -format %Y-%m-%d -timezone $timezone]
    set next [clock add $from 1 day -timezone $timezone]
    set to [expr {min($next,([clock seconds]/60)*60)}]
    if {$to<=$from || ($to-$from)/60>1500} {error "invalid chart day"}
    set repair [dict create requested false status none minutesProcessed 0]
    if {[dict exists $options focusTime] || [dict exists $options rangeStart]} {
        set range [dict exists $options rangeStart]
        if {$range} {
            set repairFrom [clock scan "$date [dict get $options rangeStart]"  -format {%Y-%m-%d %H:%M} -timezone $timezone]
            set repairTo [clock scan "$date [dict get $options rangeEnd]"  -format {%Y-%m-%d %H:%M} -timezone $timezone]
            set repairTo [expr {min($to,$repairTo)}]
            set maxSlots 512
        } else {
            set at [clock scan "$date [dict get $options focusTime]"  -format {%Y-%m-%d %H:%M} -timezone $timezone]
            set focusMinutes [dict get $options focusMinutes]
            set repairFrom [expr {max($from,$at-$focusMinutes*60)}]
            set repairTo [expr {min($to,$at+60)}]
            set maxSlots [expr {min(64,4*($focusMinutes+1))}]
        }
        set repair [dict create requested true status unavailable minutesProcessed 0  from $repairFrom to $repairTo]
        if {$repairTo>$repairFrom} {
            set gate nsmcp:unified-writer:[ns_info server]
            if {[nsv_incr $gate busy]==1} {
                try {
                    set store [:accessRecordStoreOpen ${:settings} writer]
                    try {
                        if {[$store available]} {
                            set repairStarted [clock milliseconds]
                            set processed [$store slowMinuteBackfill $maxSlots $repairFrom $repairTo]
                            dict set repair minutesProcessed $processed
                            dict set repair durationMs [expr {[clock milliseconds]-$repairStarted}]
                            dict set repair status [expr {$processed == $maxSlots ? "partial" : "complete"}]
                        } else {
                            dict set repair status pool-busy
                        }
                    } finally {
                        $store close
                    }
                } on error {message options} {
                    dict set repair status failed
                } finally {
                    nsv_incr $gate busy -1
                }
            } else {
                nsv_incr $gate busy -1
                dict set repair status writer-busy
            }
        }
    }
    set db [${:database} connect]
    try {
        set rows [$db slowMinutes $from $to [dict get $options pool]]
    } finally {
        $db close
    }
    set bySlot {}
    foreach row $rows {dict set bySlot [dict get $row slot] $row}
    set requests {}
    set over1s {}
    set over2s {}
    set incomplete {}
    set timed {}
    set incompleteMinutes 0
    set firstSlow1 {}
    set firstSlow2 {}
    set peakSlow1 [dict create from {} count 0]
    set peakSlow2 [dict create from {} count 0]
    for {set slot $from} {$slot<$to} {incr slot 60} {
        set row [expr {[dict exists $bySlot $slot] ? [dict get $bySlot $slot] :
            {requests 0 timed 0 over1s 0 over2s 0 incompleteRequests 0}}]
        set invalid [expr {[dict get $row incompleteRequests]>0}]
        foreach key {requests timed over1s over2s incompleteRequests} {
            set value [dict get $row $key]
            if {$invalid && $key in {over1s over2s}} {set value {}}
            if {$key eq "incompleteRequests"} {lappend incomplete $value} else {lappend $key $value}
        }
        if {$invalid} {incr incompleteMinutes; continue}
        foreach {key first peak} {over1s firstSlow1 peakSlow1 over2s firstSlow2 peakSlow2} {
            set value [dict get $row $key]
            if {$value>0 && [set $first] eq {}} {set $first $slot}
            if {$value>[dict get [set $peak] count]} {set $peak [dict create from $slot count $value]}
        }
    }
    return [dict create server [ns_info server] date $date timezone $timezone from $from to $to  bucketSeconds 60 requests $requests timed $timed over1s $over1s over2s $over2s  incompleteRequests $incomplete incompleteMinutes $incompleteMinutes  firstSlow1 $firstSlow1 firstSlow2 $firstSlow2 peakSlow1 $peakSlow1 peakSlow2 $peakSlow2  repair $repair]
  • summary (scripted, public)

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

    Query unified access summaries with bounded lock retry. Delegate to the superclass using the same normalized options after eligible transient store failures.

    Parameters:
    options (required)
    Tcl dictionary containing the operation options.
    Returns:
    The access summary dictionary.

    Testcases:
    No testcase defined.
    return [:accessRecordRetry ${:settings} [list next [list $options]]]