@@ -19,7 +19,15 @@ import {
1919 parseChecksums ,
2020} from "@t3tools/shared/cliRelease" ;
2121
22+ import * as HostProcess from "@t3tools/shared/HostProcess" ;
23+
2224import * as ProcessRunner from "../processRunner.ts" ;
25+ import {
26+ compareExactServiceVersions ,
27+ isExactServiceVersion ,
28+ parseServiceState ,
29+ SERVICE_STATE_FILE ,
30+ } from "./serviceProtocol.ts" ;
2331
2432const PINNED_RUNTIME_DIR = "runtime" ;
2533const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration . minutes ( 10 ) ;
@@ -364,3 +372,139 @@ const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(
364372
365373export const ensurePinnedRuntimeInstalled = ( input : PinnedRuntimeInstallInput ) =>
366374 pinnedRuntimeInstallLock . withPermit ( installPinnedRuntime ( input ) ) ;
375+
376+ const PINNED_RUNTIME_PRUNED_PREFIX = ".pruned-" ;
377+
378+ /** Versions the `t3` shims written by the install scripts and `t3 update` point at. */
379+ const shellLauncherVersions = Effect . fn ( "cloud.pinned_runtime.shell_launcher_versions" ) ( function * (
380+ versionsDir : string ,
381+ ) {
382+ const fs = yield * FileSystem . FileSystem ;
383+ const path = yield * Path . Path ;
384+ const platform = yield * HostProcess . Platform ;
385+ const environment = yield * HostProcess . Environment ;
386+ const home = yield * HostProcess . HomeDirectory ;
387+ const directories = [
388+ environment [ "T3CODE_INSTALL_BIN_DIR" ] || path . join ( home , ".local" , "bin" ) ,
389+ ...( environment [ "PATH" ] ?? environment [ "Path" ] ?? "" ) . split ( platform === "win32" ? ";" : ":" ) ,
390+ ] . filter ( ( directory ) => directory . trim ( ) . length > 0 ) ;
391+ const versions = new Set < string > ( ) ;
392+ for ( const directory of directories ) {
393+ const target =
394+ platform === "win32"
395+ ? yield * fs . readFileString ( path . join ( directory , "t3.cmd" ) ) . pipe (
396+ Effect . map ( ( contents ) => / ^ " ( [ ^ " ] + ) " / m. exec ( contents ) ?. [ 1 ] ) ,
397+ Effect . orElseSucceed ( ( ) => undefined ) ,
398+ )
399+ : yield * fs . readLink ( path . join ( directory , "t3" ) ) . pipe (
400+ Effect . map ( ( link ) => path . resolve ( directory , link ) ) ,
401+ Effect . orElseSucceed ( ( ) => undefined ) ,
402+ ) ;
403+ if ( target === undefined ) continue ;
404+ const relative = path . relative ( versionsDir , path . resolve ( target ) ) ;
405+ if ( relative . startsWith ( ".." ) || path . isAbsolute ( relative ) ) continue ;
406+ const version = relative . split ( path . sep ) [ 0 ] ;
407+ if ( version ) versions . add ( version ) ;
408+ }
409+ return versions ;
410+ } ) ;
411+
412+ const runningCommandLines = Effect . fn ( "cloud.pinned_runtime.running_command_lines" ) ( function * ( ) {
413+ const runner = yield * ProcessRunner . ProcessRunner ;
414+ const platform = yield * HostProcess . Platform ;
415+ const result = yield * runner . run ( {
416+ ...( platform === "win32"
417+ ? {
418+ command : "powershell.exe" ,
419+ args : [
420+ "-NoProfile" ,
421+ "-NonInteractive" ,
422+ "-Command" ,
423+ "Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine" ,
424+ ] ,
425+ }
426+ : { command : "ps" , args : [ "-ax" , "-o" , "command=" ] } ) ,
427+ timeout : Duration . seconds ( 10 ) ,
428+ maxOutputBytes : 16 * 1024 * 1024 ,
429+ } ) ;
430+ return result . code === 0 && result . stdout . length > 0 ? Option . some ( result . stdout ) : Option . none ( ) ;
431+ } ) ;
432+
433+ /**
434+ * Every update publishes a new immutable runtime, so without pruning they pile up. Removes
435+ * completed runtimes nothing can start again and keeps: the caller's versions, everything the
436+ * service state references (active, rollback, pending), the `t3` shell launcher's target, any
437+ * runtime a running process uses (an older service launcher keeps serving newer children), and
438+ * anything newer than the caller's versions, which another process may be installing. Staging
439+ * directories, symlinks, and unexpected entries are never touched.
440+ */
441+ export const prunePinnedRuntimes = Effect . fn ( "cloud.pinned_runtime.prune" ) ( function * ( input : {
442+ readonly baseDir : string ;
443+ readonly keep : ReadonlyArray < string > ;
444+ } ) {
445+ const fs = yield * FileSystem . FileSystem ;
446+ const path = yield * Path . Path ;
447+ const versionsDir = pinnedRuntimeVersionsDir ( path , input . baseDir ) ;
448+ const entries = yield * fs . readDirectory ( versionsDir ) . pipe ( Effect . orElseSucceed ( ( ) => [ ] ) ) ;
449+
450+ // An interrupted prune has already renamed its runtime out of the way.
451+ for ( const entry of entries ) {
452+ if ( entry . startsWith ( PINNED_RUNTIME_PRUNED_PREFIX ) ) {
453+ yield * fs . remove ( path . join ( versionsDir , entry ) , { recursive : true , force : true } ) ;
454+ }
455+ }
456+
457+ const completed : Array < string > = [ ] ;
458+ for ( const version of entries ) {
459+ if ( ! isExactServiceVersion ( version ) ) continue ;
460+ const versionDir = path . join ( versionsDir , version ) ;
461+ const isLink = yield * fs . readLink ( versionDir ) . pipe ( Effect . isSuccess ) ;
462+ const sentinel = yield * fs
463+ . readFileString ( path . join ( versionDir , ".install-complete" ) )
464+ . pipe ( Effect . option ) ;
465+ if ( ! isLink && Option . isSome ( sentinel ) && sentinel . value . trim ( ) === version ) {
466+ completed . push ( version ) ;
467+ }
468+ }
469+ if ( completed . length === 0 ) return [ ] ;
470+
471+ const keep = new Set ( input . keep ) ;
472+ const stateText = yield * fs
473+ . readFileString ( path . join ( input . baseDir , "runtime" , SERVICE_STATE_FILE ) )
474+ . pipe ( Effect . option ) ;
475+ if ( Option . isSome ( stateText ) ) {
476+ const state = parseServiceState ( stateText . value ) ;
477+ // State this version cannot read may reference runtimes in ways it does not know.
478+ if ( state === undefined ) return [ ] ;
479+ keep . add ( state . activeVersion ) ;
480+ if ( state . update !== undefined ) {
481+ keep . add ( state . update . fromVersion ) ;
482+ keep . add ( state . update . targetVersion ) ;
483+ }
484+ }
485+ for ( const version of yield * shellLauncherVersions ( versionsDir ) ) keep . add ( version ) ;
486+ const commandLines = yield * runningCommandLines ( ) ;
487+ // Without a process list, a runtime in use would look unused.
488+ if ( Option . isNone ( commandLines ) ) return [ ] ;
489+
490+ const removable = completed . filter (
491+ ( version ) =>
492+ ! keep . has ( version ) &&
493+ input . keep . every ( ( kept ) => compareExactServiceVersions ( version , kept ) < 0 ) &&
494+ ! commandLines . value . includes ( path . join ( versionsDir , version ) + path . sep ) ,
495+ ) ;
496+ const removed : Array < string > = [ ] ;
497+ for ( const version of removable ) {
498+ const pruned = path . join ( versionsDir , `${ PINNED_RUNTIME_PRUNED_PREFIX } ${ version } ` ) ;
499+ // Renaming first means an interrupted removal never leaves a partial tree that still carries
500+ // its sentinel and would pass for a complete install.
501+ yield * fs . rename ( path . join ( versionsDir , version ) , pruned ) . pipe (
502+ Effect . andThen ( fs . remove ( pruned , { recursive : true , force : true } ) ) ,
503+ Effect . andThen ( Effect . sync ( ( ) => removed . push ( version ) ) ) ,
504+ Effect . catch ( ( cause ) =>
505+ Effect . logWarning ( "Could not remove an unused t3 runtime." , { version, cause } ) ,
506+ ) ,
507+ ) ;
508+ }
509+ return removed ;
510+ } , pinnedRuntimeInstallLock . withPermit ) ;
0 commit comments