Repository navigation
Expand file tree
/
Copy pathserver-runtime.ts
More file actions
189 lines (173 loc) · 6.64 KB
/
Copy pathserver-runtime.ts
File metadata and controls
189 lines (173 loc) · 6.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import { FetchHttpClient } from "@effect/platform"
import * as FileSystem from "@effect/platform/FileSystem"
import * as CommandExecutor from "@effect/platform/CommandExecutor"
import * as HttpClient from "@effect/platform/HttpClient"
import * as Path from "@effect/platform/Path"
import * as Terminal from "@effect/platform/Terminal"
import { BunContext } from "@effect/platform-bun"
import { formatLocalModelDisplayName } from "@magnitudedev/client-common"
import {
MAGNITUDE_SERVICE_ORIGIN,
} from "@magnitudedev/sdk"
import { Effect, Layer, Option } from "effect"
import {
confirmServicePublicReady,
installService,
serviceStatus,
startServiceManager,
stopService,
uninstallService,
} from "../server/service"
import { probeTerminalAppearance } from "../platform/terminal-appearance"
import {
makeInlineServiceStartupPresenter,
} from "../startup/inline-service-lifecycle"
import { resolveCliTheme } from "../utils/theme"
import { makeCliUpdater, updateReleaseNotesUrl } from "../features/update/updater"
import { CLI_VERSION } from "../version"
import { isDevelopmentBuild } from "../runtime/environment"
import { existingAcnConnection, startingAcnConnection } from "../server/acn-connection"
import { explainServiceStartupFailure } from "../startup/service-startup-error"
import { runCommand } from "./output"
interface ActiveModel {
readonly displayName: string
readonly status: "Loading" | "Ready" | "Stopping"
}
interface ServiceStatusPresentation {
readonly status: "Stopped" | "Starting" | "Ready" | "Stopping"
readonly address: string
readonly version: Option.Option<string>
readonly startsAutomaticallyOnLogin: boolean
readonly activeModel: Option.Option<ActiveModel>
}
const serviceAddress = new URL(MAGNITUDE_SERVICE_ORIGIN).host
const runServiceStartEffect = Effect.scoped(Effect.gen(function* () {
const appearance = yield* probeTerminalAppearance()
const theme = resolveCliTheme(appearance)
const startup = yield* makeInlineServiceStartupPresenter(theme, {
showReadyWhenNoWork: true,
})
const updater = yield* makeCliUpdater({
currentVersion: CLI_VERSION,
developmentBuild: isDevelopmentBuild(),
})
const discovery = yield* updater.discover
const started = yield* Effect.exit(startServiceManager(Option.some(startup.acquisitionObserver)))
if (started._tag === "Failure") {
return yield* Effect.failCause(started.cause)
}
yield* startup.acquisitionSucceeded
const connection = yield* startingAcnConnection
yield* startup.run(connection.startup)
yield* confirmServicePublicReady
const latest = yield* discovery.fresh
if (Option.isSome(latest)) {
yield* Effect.sync(() => {
process.stdout.write([
`Update available! ${CLI_VERSION} → ${latest.value}`,
`Release notes: ${updateReleaseNotesUrl(latest.value)}`,
"Run `magnitude update` to install it.",
"",
].join("\n"))
})
}
}))
type ServiceRequirements =
| FileSystem.FileSystem
| CommandExecutor.CommandExecutor
| Path.Path
| HttpClient.HttpClient
| Terminal.Terminal
const run = (
effect: Effect.Effect<void, unknown, ServiceRequirements>,
explain: (error: unknown) => string,
) => Effect.runPromise(effect.pipe(
Effect.provide([BunContext.layer, FetchHttpClient.layer]),
Effect.catchAll((error) => Effect.sync(() => {
process.stderr.write(`${explain(error)}\n`)
process.exitCode = 1
})),
))
type ServiceActionRequirements =
| FileSystem.FileSystem
| CommandExecutor.CommandExecutor
| Path.Path
| HttpClient.HttpClient
const live = <A, E>(effect: Effect.Effect<A, E, ServiceActionRequirements>) => effect.pipe(
Effect.provide([BunContext.layer, FetchHttpClient.layer]),
)
export const runServiceInstall = () => runCommand({
effect: live(installService),
render: () => "Magnitude will start automatically when you log in.\n",
})
export const runServiceUninstall = () => runCommand({
effect: live(uninstallService),
render: () => "Magnitude service stopped and was removed from login startup.\nModels, settings, and sessions were kept.\n",
})
export const runServiceStart = () => run(runServiceStartEffect, explainServiceStartupFailure)
export const runServiceStop = () => runCommand({
effect: live(stopService),
render: () => "Magnitude service stopped.\n",
})
const readActiveModel = Effect.scoped(Effect.gen(function* () {
const connection = yield* existingAcnConnection
const catalog = yield* connection.client.models.getCatalog({})
if (catalog._tag === "Initializing") return Option.none<ActiveModel>()
for (const entry of catalog.models) {
if (entry._tag !== "Local") continue
const model = entry.product
const residency = model._tag === "Discovered"
? model.state._tag === "Ready" ? model.state.residencyState : undefined
: "residencyState" in model.acquisitionState
? model.acquisitionState.residencyState
: undefined
if (residency === undefined) continue
if (residency._tag !== "Requested"
&& residency._tag !== "Loading"
&& residency._tag !== "Ready"
&& residency._tag !== "Stopping") continue
return Option.some({
displayName: formatLocalModelDisplayName(model),
status: residency._tag === "Requested" ? "Loading" as const : residency._tag,
})
}
return Option.none<ActiveModel>()
}))
const publicServiceStatus = live(serviceStatus).pipe(
Effect.flatMap((status) => {
const activeModel = status.running && status.state === "Ready"
? readActiveModel.pipe(
Effect.timeoutOption("2 seconds"),
Effect.map(Option.flatten),
Effect.orElseSucceed(() => Option.none<ActiveModel>()),
)
: Effect.succeed(Option.none<ActiveModel>())
return activeModel.pipe(Effect.map((model) => ({
status: status.state,
address: serviceAddress,
version: status.running ? Option.some(String(status.version)) : Option.none<string>(),
startsAutomaticallyOnLogin: status.enabled,
activeModel: model,
})))
}),
)
export const renderServiceStatus = (status: ServiceStatusPresentation): string => [
"Magnitude service",
` Runtime ${status.status}`,
` Starts at login ${status.startsAutomaticallyOnLogin ? "Yes" : "No"}`,
...(Option.isSome(status.version) ? [
` Version ${status.version.value}`,
` Address ${status.address}`,
] : []),
...(status.status === "Ready" ? [` Active model ${Option.match(status.activeModel, {
onNone: () => "None",
onSome: (model) => model.status === "Ready"
? model.displayName
: `${model.displayName} - ${model.status}`,
})}`] : []),
"",
].join("\n")
export const runServiceStatus = () => runCommand({
effect: publicServiceStatus,
render: renderServiceStatus,
})