11import * as NodeOS from "node:os" ;
2- import * as NodeTimersPromises from "node:timers/promises" ;
32import type { HostResourcesSnapshot } from "@t3tools/contracts" ;
43import { HostProcessPlatform } from "@t3tools/shared/hostProcess" ;
4+ import * as Context from "effect/Context" ;
55import * as DateTime from "effect/DateTime" ;
66import * as Effect from "effect/Effect" ;
77import * as FileSystem from "effect/FileSystem" ;
8+ import * as Layer from "effect/Layer" ;
9+ import { ChildProcess , ChildProcessSpawner } from "effect/unstable/process" ;
810
9- const CACHE_MS = 5_000 ;
10-
11- // All sockets share the sample. Idle servers do no polling or process scans.
12- let latest : HostResourcesSnapshot | undefined ;
13- let pending : Promise < HostResourcesSnapshot > | undefined ;
11+ export class HostResources extends Context . Service <
12+ HostResources ,
13+ { readonly read : Effect . Effect < HostResourcesSnapshot > }
14+ > ( ) ( "t3/resourceTelemetry/HostResources" ) { }
1415
1516function readCpu ( ) {
1617 const cpus = NodeOS . cpus ( ) ;
@@ -24,53 +25,64 @@ function readCpu() {
2425 return { ...cpu , count : cpus . length } ;
2526}
2627
27- async function sample (
28- sampledAt : number ,
29- platform : NodeJS . Platform ,
30- readMeminfo : ( ) => Promise < string > ,
31- ) : Promise < HostResourcesSnapshot > {
32- const previousCpu = readCpu ( ) ;
33- // CPU counters need two readings; a bounded demand-only sample also works on Windows.
34- await NodeTimersPromises . setTimeout ( 200 ) ;
35- const cpu = readCpu ( ) ;
36- const totalDelta = cpu . total - previousCpu . total ;
37- const idleDelta = cpu . idle - previousCpu . idle ;
38- const cpuUtilization =
39- previousCpu . count === cpu . count && totalDelta > 0 && idleDelta >= 0
40- ? Math . min ( 1 , Math . max ( 0 , 1 - idleDelta / totalDelta ) )
41- : null ;
42- const totalMemoryBytes = NodeOS . totalmem ( ) ;
43- let availableMemoryBytes = NodeOS . freemem ( ) ;
44- if ( platform === "linux" ) {
45- const meminfo = await readMeminfo ( ) ;
46- const available = / ^ M e m A v a i l a b l e : \s + ( \d + ) \s + k B $ / m. exec ( meminfo ) ?. [ 1 ] ;
47- if ( available ) availableMemoryBytes = Number ( available ) * 1024 ;
48- }
49- latest = {
50- sampledAt,
51- cpuUtilization,
52- cpuCount : cpu . count ,
53- availableMemoryBytes : Math . min ( totalMemoryBytes , Math . max ( 0 , availableMemoryBytes ) ) ,
54- totalMemoryBytes,
55- } ;
56- return latest ;
28+ function darwinAvailableMemory ( output : string ) : number | null {
29+ const pageSize = / p a g e s i z e o f ( \d + ) b y t e s / . exec ( output ) ?. [ 1 ] ;
30+ const free = / ^ P a g e s f r e e : \s + ( \d + ) \. / m. exec ( output ) ?. [ 1 ] ;
31+ const inactive = / ^ P a g e s i n a c t i v e : \s + ( \d + ) \. / m. exec ( output ) ?. [ 1 ] ;
32+ const speculative = / ^ P a g e s s p e c u l a t i v e : \s + ( \d + ) \. / m. exec ( output ) ?. [ 1 ] ;
33+ if ( ! pageSize || ! free || ! inactive || ! speculative ) return null ;
34+ // vm_stat subtracts speculative pages from its printed "Pages free" count.
35+ // Adding them here counts each reclaimable page once; purgeable pages overlap.
36+ const available = ( Number ( free ) + Number ( inactive ) + Number ( speculative ) ) * Number ( pageSize ) ;
37+ return Number . isSafeInteger ( available ) && Number ( pageSize ) > 0 ? available : null ;
5738}
5839
59- export const readHostResources = Effect . fn ( "HostResources.read" ) ( function * ( ) {
60- const sampledAt = DateTime . toEpochMillis ( yield * DateTime . now ) ;
61- if ( latest && sampledAt >= latest . sampledAt && sampledAt - latest . sampledAt < CACHE_MS ) {
62- return latest ;
63- }
40+ export const make = Effect . fn ( "makeHostResources" ) ( function * ( ) {
6441 const fs = yield * FileSystem . FileSystem ;
6542 const platform = yield * HostProcessPlatform ;
66- return yield * Effect . promise ( ( ) => {
67- pending ??= sample ( sampledAt , platform , ( ) =>
68- Effect . runPromise (
69- fs . readFileString ( "/proc/meminfo" ) . pipe ( Effect . catch ( ( ) => Effect . succeed ( "" ) ) ) ,
70- ) ,
71- ) . finally ( ( ) => {
72- pending = undefined ;
73- } ) ;
74- return pending ;
43+ const spawner = yield * ChildProcessSpawner . ChildProcessSpawner ;
44+
45+ const sample = Effect . fn ( "HostResources.sample" ) ( function * ( ) {
46+ const previousCpu = readCpu ( ) ;
47+ // CPU counters need two readings; idle servers do no polling or process scans.
48+ yield * Effect . sleep ( "200 millis" ) ;
49+ const cpu = readCpu ( ) ;
50+ const totalDelta = cpu . total - previousCpu . total ;
51+ const idleDelta = cpu . idle - previousCpu . idle ;
52+ const cpuUtilization =
53+ previousCpu . count === cpu . count && totalDelta > 0 && idleDelta >= 0
54+ ? Math . min ( 1 , Math . max ( 0 , 1 - idleDelta / totalDelta ) )
55+ : null ;
56+ const totalMemoryBytes = NodeOS . totalmem ( ) ;
57+ // On Windows libuv returns GlobalMemoryStatusEx.ullAvailPhys, including standby memory.
58+ let availableMemoryBytes = NodeOS . freemem ( ) ;
59+ if ( platform === "linux" ) {
60+ const meminfo = yield * fs
61+ . readFileString ( "/proc/meminfo" )
62+ . pipe ( Effect . catch ( ( ) => Effect . succeed ( "" ) ) ) ;
63+ const available = / ^ M e m A v a i l a b l e : \s + ( \d + ) \s + k B $ / m. exec ( meminfo ) ?. [ 1 ] ;
64+ if ( available ) availableMemoryBytes = Number ( available ) * 1024 ;
65+ } else if ( platform === "darwin" ) {
66+ const output = yield * spawner
67+ . string ( ChildProcess . make ( "/usr/bin/vm_stat" , [ ] , { stdin : "ignore" , stderr : "ignore" } ) )
68+ . pipe (
69+ Effect . timeout ( "1 second" ) ,
70+ Effect . catch ( ( ) => Effect . succeed ( "" ) ) ,
71+ ) ;
72+ availableMemoryBytes = darwinAvailableMemory ( output ) ?? availableMemoryBytes ;
73+ }
74+ return {
75+ sampledAt : DateTime . toEpochMillis ( yield * DateTime . now ) ,
76+ cpuUtilization,
77+ cpuCount : cpu . count ,
78+ availableMemoryBytes : Math . min ( totalMemoryBytes , Math . max ( 0 , availableMemoryBytes ) ) ,
79+ totalMemoryBytes,
80+ } ;
7581 } ) ;
82+
83+ // One server-lifetime cache deduplicates simultaneous requests from all sockets.
84+ const read = yield * Effect . cachedWithTTL ( sample ( ) , "5 seconds" ) ;
85+ return HostResources . of ( { read } ) ;
7686} ) ;
87+
88+ export const layer = Layer . effect ( HostResources , make ( ) ) ;
0 commit comments