@orsetra/shared-ui 1.12.1 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  // Layout components exports
2
2
  export { MainSidebar, type SidebarMode } from './sidebar/main-sidebar'
3
- export { resolveIcon, type MainMenuItem, type SubMenuItem, type SidebarMenus, type SidebarMenuMeta, type MenuApiResponse, type ApiMenuData, type ApiMainMenuItem, type ApiSubMenuItem, type ApiSubMenu, type OrgInfo, type Project } from './sidebar/data'
3
+ export { MenuBadge } from './sidebar/menu-badge'
4
+ export { resolveIcon, type MenuBadge as MenuBadgeData, type MainMenuItem, type SubMenuItem, type SidebarMenus, type SidebarMenuMeta, type MenuApiResponse, type ApiMenuData, type ApiMainMenuItem, type ApiSubMenuItem, type ApiSubMenu, type OrgInfo, type Project } from './sidebar/data'
4
5
  export { QuickAccessTracker } from './sidebar/quick-access-tracker'
5
6
  export {
6
7
  Sidebar,
@@ -75,6 +75,7 @@ function LayoutContent({
75
75
  description: item.description,
76
76
  icon: resolveIcon(item.icon),
77
77
  href: item.href,
78
+ badge: item.badge,
78
79
  }))
79
80
  )
80
81
 
@@ -89,6 +90,7 @@ function LayoutContent({
89
90
  href: item.href,
90
91
  icon: resolveIcon(item.icon),
91
92
  target: item.target,
93
+ badge: item.badge,
92
94
  }))
93
95
  labels[key] = subMenu.header
94
96
  meta[key] = {
@@ -39,12 +39,22 @@ import {
39
39
  LifeBuoy,
40
40
  } from "lucide-react"
41
41
 
42
+ /**
43
+ * A badge on a menu item: a text, shown as it is given and never translated, and a color among
44
+ * blue, orange, yellow, green, red, purple, teal and gray (another color is drawn in gray).
45
+ */
46
+ export interface MenuBadge {
47
+ text: string
48
+ color: string
49
+ }
50
+
42
51
  export interface MainMenuItem {
43
52
  id: string
44
53
  label: string
45
54
  description?: string
46
55
  icon: LucideIcon
47
56
  href: string
57
+ badge?: MenuBadge
48
58
  }
49
59
 
50
60
  export interface SubMenuItem {
@@ -57,6 +67,7 @@ export interface SubMenuItem {
57
67
  target?: string
58
68
  /** True when the href still has an unresolved "${...}" placeholder (e.g. no project/environment selected yet) — render as non-navigable. */
59
69
  disabled?: boolean
70
+ badge?: MenuBadge
60
71
  }
61
72
 
62
73
  export interface SidebarMenus {
@@ -81,6 +92,7 @@ export interface ApiMainMenuItem {
81
92
  description?: string
82
93
  icon: string
83
94
  href: string
95
+ badge?: MenuBadge
84
96
  }
85
97
 
86
98
  export interface ApiSubMenuItem {
@@ -90,6 +102,7 @@ export interface ApiSubMenuItem {
90
102
  href: string
91
103
  icon: string
92
104
  target?: string
105
+ badge?: MenuBadge
93
106
  }
94
107
 
95
108
  export interface ApiSubMenu {
@@ -6,6 +6,7 @@ import type { MainMenuItem, SubMenuItem } from "./data"
6
6
  import { resolveIcon } from "./data"
7
7
  import { Home, ExternalLink, type LucideIcon } from "lucide-react"
8
8
  import type { QuickAccessItem } from "../../../hooks/use-quick-access"
9
+ import { MenuBadge } from "./menu-badge"
9
10
 
10
11
  export interface FlyoutDefaultLink {
11
12
  label: string
@@ -83,7 +84,7 @@ export function MainSidebarFlyout({
83
84
  title={sub.disabled ? "Select a project/environment first" : undefined}
84
85
  onClick={(e) => { if (sub.disabled) e.preventDefault() }}
85
86
  className={cn(
86
- "flex items-start transition-colors border-l-4",
87
+ "relative flex items-start transition-colors border-l-4",
87
88
  "px-2 lg:px-3 py-2 gap-x-3",
88
89
  sub.disabled
89
90
  ? "opacity-40 cursor-not-allowed border-transparent"
@@ -97,6 +98,7 @@ export function MainSidebarFlyout({
97
98
  <p className="text-xs text-text-secondary leading-relaxed mt-0.5 line-clamp-2">{sub.description}</p>
98
99
  )}
99
100
  </div>
101
+ <MenuBadge badge={sub.badge} />
100
102
  </a>
101
103
  )
102
104
  })}
@@ -12,6 +12,7 @@ import { useIsMobile } from "../../../hooks/use-mobile"
12
12
  import { MainSidebarFlyout, type FlyoutDefaultLink } from "./main-sidebar-flyout"
13
13
  import { useQuickAccess } from "../../../hooks/use-quick-access"
14
14
  import { resolveTemplateVars } from "./template-vars"
15
+ import { MenuBadge } from "./menu-badge"
15
16
 
16
17
  export type { FlyoutDefaultLink }
17
18
 
@@ -215,7 +216,7 @@ export function MainSidebar({
215
216
  : undefined
216
217
 
217
218
  const itemCls = cn(
218
- "w-full flex items-center text-left transition-all duration-150 font-medium",
219
+ "relative w-full flex items-center text-left transition-all duration-150 font-medium",
219
220
  isMinimized ? "justify-center p-2 lg:p-3" : "gap-2 lg:gap-3 px-2 lg:px-3 py-1.5 lg:py-2",
220
221
  isActive || isFlyActive
221
222
  ? "bg-ibm-blue-10 text-interactive border-l-4 border-interactive"
@@ -238,6 +239,7 @@ export function MainSidebar({
238
239
  )}
239
240
  </>
240
241
  )}
242
+ <MenuBadge badge={item.badge} dot={isMinimized} />
241
243
  </>
242
244
  )
243
245
 
@@ -284,7 +286,7 @@ export function MainSidebar({
284
286
  handleSubMenuClick(e, item.id, subItem.href, subItem.target)
285
287
  }}
286
288
  className={cn(
287
- "flex items-center gap-2 lg:gap-3 px-2 lg:px-3 py-1.5 lg:py-2 text-sm transition-colors no-underline border-l-2",
289
+ "relative flex items-center gap-2 lg:gap-3 px-2 lg:px-3 py-1.5 lg:py-2 text-sm transition-colors no-underline border-l-2",
288
290
  subDisabled
289
291
  ? "text-text-secondary/40 border-ui-border cursor-not-allowed"
290
292
  : "text-text-secondary hover:bg-ui-background hover:text-text-primary border-ui-border hover:border-interactive",
@@ -292,6 +294,7 @@ export function MainSidebar({
292
294
  >
293
295
  <subItem.icon className="h-4 w-4 flex-shrink-0 text-text-secondary" />
294
296
  {subItem.name}
297
+ <MenuBadge badge={subItem.badge} />
295
298
  </a>
296
299
  )
297
300
  })}
@@ -0,0 +1,48 @@
1
+ "use client"
2
+
3
+ import { cn } from "../../../lib/utils"
4
+ import { type MenuBadge as MenuBadgeData } from "./data"
5
+
6
+ /** Carbon colors a badge is drawn in; a color it does not know is drawn in gray. */
7
+ const COLORS: Record<string, { background: string; text: string }> = {
8
+ blue: { background: "#0f62fe", text: "#ffffff" },
9
+ orange: { background: "#ff832b", text: "#161616" },
10
+ yellow: { background: "#f1c21b", text: "#161616" },
11
+ green: { background: "#24a148", text: "#ffffff" },
12
+ red: { background: "#da1e28", text: "#ffffff" },
13
+ purple: { background: "#8a3ffc", text: "#ffffff" },
14
+ teal: { background: "#009d9a", text: "#ffffff" },
15
+ gray: { background: "#6f6f6f", text: "#ffffff" },
16
+ }
17
+
18
+ /**
19
+ * A menu item's badge, in the top right corner of the item (which is `relative`). Its text is
20
+ * shown as it is given, never translated. `dot` draws it as a dot, for an item shown as an icon.
21
+ */
22
+ export function MenuBadge({ badge, dot = false, className }: { badge?: MenuBadgeData; dot?: boolean; className?: string }) {
23
+ if (!badge?.text) return null
24
+ const color = COLORS[badge.color] ?? COLORS.gray
25
+
26
+ if (dot) {
27
+ return (
28
+ <span
29
+ aria-label={badge.text}
30
+ title={badge.text}
31
+ className={cn("absolute top-1 right-1 h-2 w-2 pointer-events-none", className)}
32
+ style={{ background: color.background }}
33
+ />
34
+ )
35
+ }
36
+
37
+ return (
38
+ <span
39
+ className={cn(
40
+ "absolute top-0.5 right-1 px-1 py-px text-[9px] font-medium uppercase leading-none tracking-wide pointer-events-none select-none",
41
+ className,
42
+ )}
43
+ style={{ background: color.background, color: color.text }}
44
+ >
45
+ {badge.text}
46
+ </span>
47
+ )
48
+ }
@@ -21,6 +21,7 @@ import {
21
21
  import { type SidebarMenus, type SubMenuItem, type MainMenuItem } from "./data"
22
22
  import { Skeleton } from "../skeleton"
23
23
  import { resolveTemplateVars } from "./template-vars"
24
+ import { MenuBadge } from "./menu-badge"
24
25
 
25
26
  // ── Dynamic secondary navigation ──────────────────────────────────────────────
26
27
 
@@ -347,7 +348,7 @@ function Sidebar({ currentMenu, sidebarMenus = {}, main_base_url = "", sectionLa
347
348
  }
348
349
 
349
350
  const linkCls = cn(
350
- "flex items-center transition-colors border-l-4",
351
+ "relative flex items-center transition-colors border-l-4",
351
352
  isCollapsed ? "justify-center p-2" : "px-2 lg:px-3 py-1.5 lg:py-2 gap-x-3 text-sm",
352
353
  isDisabled
353
354
  ? "opacity-40 cursor-not-allowed text-text-secondary border-transparent"
@@ -365,6 +366,7 @@ function Sidebar({ currentMenu, sidebarMenus = {}, main_base_url = "", sectionLa
365
366
  {!isCollapsed && (
366
367
  <span className="flex-1 truncate">{item.name}</span>
367
368
  )}
369
+ <MenuBadge badge={item.badge} dot={isCollapsed} />
368
370
  </>
369
371
  )
370
372
 
package/index.ts CHANGED
@@ -7,6 +7,7 @@ export * from './lib/config-selection'
7
7
  export * from './lib/environment-context'
8
8
  export * from './lib/environment-controller'
9
9
  export * from './lib/project-requirement'
10
+ export * from './lib/env-services'
10
11
  export * from './lib/quick-access-href'
11
12
  export * from './lib/status-indicator'
12
13
  export { createPlatformConfigSource, templateFilter, configOfHit, environmentWithTargets, type ConfigSource } from './lib/config-source'
@@ -0,0 +1,224 @@
1
+ import { applicationReadiness, environmentReadiness, type EnvironmentReadiness, type ReadableStatus } from "./readiness"
2
+ import { ENV_SERVICE_PLACES, PLATFORM_SERVICE_TYPES, envComponentName } from "./places"
3
+
4
+ export interface AppComponents {
5
+ components: { name: string; type?: string; componentType?: string }[]
6
+ appExists: boolean
7
+ }
8
+
9
+ export interface ServiceLocation {
10
+ /** Application the service lives in, or will be created in. */
11
+ appName: string
12
+ /** Whether that application exists. */
13
+ appExists: boolean
14
+ /** Whether the service is configured. */
15
+ exists: boolean
16
+ /** Whether its application holds something to deploy: the service, or what it holds besides. */
17
+ active?: boolean
18
+ /**
19
+ * Its own application, when the service itself lives in the shared one and what it holds
20
+ * besides lives there: both are then to be deployed.
21
+ */
22
+ besidesApp?: string
23
+ /**
24
+ * Whether it is deployed on its own, from its own page, and never with the rest of the
25
+ * environment: what it carries is too sensitive to go out with something else.
26
+ */
27
+ standalone?: boolean
28
+ /** Whether it still lives in an application it shares, from before it had its own. */
29
+ legacy?: boolean
30
+ }
31
+
32
+ const LINK_TYPE = "private-link"
33
+ const LINK_KEY = "link:"
34
+
35
+ /** The application a private link has to itself: one link, one application, deployed alone. */
36
+ export function linkAppName(envName: string, linkName: string): string {
37
+ return `${envName}-link-${linkName}`
38
+ }
39
+
40
+ /** The link an application of an environment is the application of; nothing when it is none. */
41
+ export function linkOfApp(envName: string, appName: string): string | null {
42
+ const prefix = `${envName}-link-`
43
+ return appName.startsWith(prefix) && appName.length > prefix.length ? appName.slice(prefix.length) : null
44
+ }
45
+
46
+ /** What a link is known by among the things an environment deploys. */
47
+ export function linkKey(linkName: string): string {
48
+ return `${LINK_KEY}${linkName}`
49
+ }
50
+
51
+ /** The link a key names; nothing when the key is the one of a service. */
52
+ export function linkOfKey(key: string): string | null {
53
+ return key.startsWith(LINK_KEY) && key.length > LINK_KEY.length ? key.slice(LINK_KEY.length) : null
54
+ }
55
+
56
+ /**
57
+ * Where each link of an environment lives: in its own application, or — for a link made
58
+ * before links had their own — still in the application of the network.
59
+ */
60
+ export function linkLocations(envName: string, existingApps: string[], network: AppComponents): Record<string, ServiceLocation> {
61
+ const locations: Record<string, ServiceLocation> = {}
62
+ for (const appName of existingApps) {
63
+ const linkName = linkOfApp(envName, appName)
64
+ if (linkName) locations[linkKey(linkName)] = { appName, appExists: true, exists: true, standalone: true }
65
+ }
66
+ const shared = envServiceAppName(envName, "network")
67
+ for (const component of network.appExists ? network.components : []) {
68
+ const key = linkKey(component.name)
69
+ if ((component.type ?? component.componentType) !== LINK_TYPE || locations[key]) continue
70
+ locations[key] = { appName: shared, appExists: true, exists: true, standalone: true, legacy: true }
71
+ }
72
+ return locations
73
+ }
74
+
75
+ const POLICY_TYPE = "networkpolicy"
76
+ const POLICY_KEY = "policy:"
77
+
78
+ /** The application a network policy has to itself: one policy, one application, deployed alone. */
79
+ export function policyAppName(envName: string, policyName: string): string {
80
+ return `${envName}-policy-${policyName}`
81
+ }
82
+
83
+ /** The policy an application of an environment is the application of; nothing when it is none. */
84
+ export function policyOfApp(envName: string, appName: string): string | null {
85
+ const prefix = `${envName}-policy-`
86
+ return appName.startsWith(prefix) && appName.length > prefix.length ? appName.slice(prefix.length) : null
87
+ }
88
+
89
+ /** What a policy is known by among the things an environment deploys. */
90
+ export function policyKey(policyName: string): string {
91
+ return `${POLICY_KEY}${policyName}`
92
+ }
93
+
94
+ /** The policy a key names; nothing when the key is the one of a service or of a link. */
95
+ export function policyOfKey(key: string): string | null {
96
+ return key.startsWith(POLICY_KEY) && key.length > POLICY_KEY.length ? key.slice(POLICY_KEY.length) : null
97
+ }
98
+
99
+ /**
100
+ * Where each network policy of an environment lives: in its own application, or — for the
101
+ * rules written when an environment had a single policy — still in the application of the
102
+ * network, or in the one that used to hold every service.
103
+ */
104
+ export function policyLocations(envName: string, existingApps: string[], network: AppComponents, shared: AppComponents): Record<string, ServiceLocation> {
105
+ const locations: Record<string, ServiceLocation> = {}
106
+ for (const appName of existingApps) {
107
+ const policyName = policyOfApp(envName, appName)
108
+ if (policyName) locations[policyKey(policyName)] = { appName, appExists: true, exists: true, standalone: true }
109
+ }
110
+ const older: [string, AppComponents][] = [[envServiceAppName(envName, "network"), network], [sharedEnvAppName(envName), shared]]
111
+ for (const [appName, held] of older) {
112
+ for (const component of held.appExists ? held.components : []) {
113
+ const key = policyKey(component.name)
114
+ if ((component.type ?? component.componentType) !== POLICY_TYPE || locations[key]) continue
115
+ locations[key] = { appName, appExists: true, exists: true, standalone: true, legacy: true }
116
+ }
117
+ }
118
+ return locations
119
+ }
120
+
121
+ export type OpenItemKind = "link" | "policy"
122
+
123
+ /** What a key names when it is not a service: a link or a policy, with its name. */
124
+ export function itemOfKey(key: string): { kind: OpenItemKind; name: string } | null {
125
+ const link = linkOfKey(key)
126
+ if (link !== null) return { kind: "link", name: link }
127
+ const policy = policyOfKey(key)
128
+ return policy !== null ? { kind: "policy", name: policy } : null
129
+ }
130
+
131
+ export function keyOfItem(kind: OpenItemKind, name: string): string {
132
+ return kind === "link" ? linkKey(name) : policyKey(name)
133
+ }
134
+
135
+ export type AppStatus = ReadableStatus
136
+
137
+ export type EnvHealth = "neutral" | "success" | "warning" | "failed"
138
+
139
+ /** Application a service of an environment has to itself. */
140
+ export function envServiceAppName(envName: string, routingKey: string): string {
141
+ return `${envName}-${ENV_SERVICE_PLACES[routingKey]?.appSuffix ?? routingKey}`
142
+ }
143
+
144
+ /** Application that used to hold every service of an environment. */
145
+ export function sharedEnvAppName(envName: string): string {
146
+ return envName
147
+ }
148
+
149
+ /** Every application the services of an environment may live in. */
150
+ export function envAppCandidates(envName: string): string[] {
151
+ return [...PLATFORM_SERVICE_TYPES.map(key => envServiceAppName(envName, key)), sharedEnvAppName(envName)]
152
+ }
153
+
154
+ function holds(app: AppComponents, compName: string): boolean {
155
+ return app.appExists && app.components.some(component => component.name === compName)
156
+ }
157
+
158
+ /**
159
+ * Where a service lives: in its own application, or in the shared one when it was
160
+ * configured there before services were separated. A service not configured yet goes to
161
+ * its own application.
162
+ */
163
+ export function locateService(envName: string, routingKey: string, own: AppComponents, shared: AppComponents): ServiceLocation {
164
+ const compName = envComponentName(envName, routingKey)
165
+ const besides = holdsBesides(routingKey, own)
166
+ if (holds(own, compName)) {
167
+ return { appName: envServiceAppName(envName, routingKey), appExists: true, exists: true, ...(besides ? { active: true } : {}) }
168
+ }
169
+ if (holds(shared, compName)) {
170
+ return {
171
+ appName: sharedEnvAppName(envName), appExists: true, exists: true,
172
+ ...(besides ? { besidesApp: envServiceAppName(envName, routingKey) } : {}),
173
+ }
174
+ }
175
+ return { appName: envServiceAppName(envName, routingKey), appExists: own.appExists, exists: false, ...(besides ? { active: true } : {}) }
176
+ }
177
+
178
+ /** Whether the application of a service holds any of what the service holds besides itself. */
179
+ export function holdsBesides(routingKey: string, own: AppComponents): boolean {
180
+ const types = ENV_SERVICE_PLACES[routingKey]?.holds ?? []
181
+ return own.appExists && own.components.some(component => types.includes(component.type ?? component.componentType ?? ""))
182
+ }
183
+
184
+ /** Whether there is something of a service to deploy. */
185
+ export function isActive(location: ServiceLocation | null | undefined): boolean {
186
+ return !!location && (location.exists || location.active === true)
187
+ }
188
+
189
+ /** The applications of one service that hold something to deploy. */
190
+ export function appsOf(location: ServiceLocation | null | undefined): string[] {
191
+ if (!location || !isActive(location)) return []
192
+ return location.besidesApp && location.besidesApp !== location.appName
193
+ ? [location.appName, location.besidesApp]
194
+ : [location.appName]
195
+ }
196
+
197
+ /** Applications to act on when acting on the whole environment: those holding something to deploy. */
198
+ export function configuredApps(locations: Record<string, ServiceLocation>): string[] {
199
+ return Array.from(new Set(Object.values(locations).flatMap(appsOf)))
200
+ }
201
+
202
+ /** The status of one of the applications a service lives in, as it was last read. */
203
+ export function statusIn<S>(service: (ServiceLocation & { status: S | null; besidesStatus?: S | null }) | null | undefined, appName: string): S | null {
204
+ if (!service) return null
205
+ if (service.appName === appName) return service.status
206
+ if (service.besidesApp === appName) return service.besidesStatus ?? null
207
+ return null
208
+ }
209
+
210
+ const HEALTH_OF: Record<EnvironmentReadiness, EnvHealth> = {
211
+ notConfigured: "neutral",
212
+ ready: "success",
213
+ deploying: "neutral",
214
+ notReady: "warning",
215
+ failed: "failed",
216
+ }
217
+
218
+ export function summarizeHealth(statuses: (AppStatus | null | undefined)[]): { health: EnvHealth; message: string | null } {
219
+ const overall = environmentReadiness(statuses.map(status => applicationReadiness(status)))
220
+ const reported = statuses
221
+ .flatMap(status => status?.status?.services ?? [])
222
+ .find(service => service.message)?.message ?? null
223
+ return { health: HEALTH_OF[overall.state], message: overall.reason ?? reported }
224
+ }
@@ -0,0 +1,64 @@
1
+ import { BaseService, type AuthHeadersProvider } from "../base-service"
2
+ import type { AppComponents } from "./apps"
3
+ import type { EnvAppStatus, EnvServiceBackend } from "./reader"
4
+
5
+ const statusOfError = (error: any): number | undefined =>
6
+ error?.status ?? error?.statusCode ?? error?.response?.status ?? error?.raw?.status
7
+
8
+ /**
9
+ * The three questions about the services of an environment, asked to the backend
10
+ * (`/platform/v1/env-configs`), with the business unit of the page.
11
+ */
12
+ export class EnvServicesClient extends BaseService {
13
+ constructor(apiUrl: string, authHeaders?: AuthHeadersProvider) {
14
+ super(apiUrl, authHeaders)
15
+ }
16
+
17
+ private headers(project: string) {
18
+ return { headers: { "x-business-unit-id": project } }
19
+ }
20
+
21
+ /** The names of the applications of an environment. */
22
+ async listApps(envName: string, project: string): Promise<string[]> {
23
+ const data = await this.httpClient.get<{ applications?: { name: string }[] }>(
24
+ `/platform/v1/env-configs?env=${encodeURIComponent(envName)}`,
25
+ this.headers(project),
26
+ )
27
+ return (data?.applications ?? []).map(application => application.name)
28
+ }
29
+
30
+ /**
31
+ * What an application holds. An environment with no service yet has no application: that
32
+ * is an answer, not a failure. Anything else is one, and saying "nothing" would hide it.
33
+ */
34
+ async components(appName: string, project: string): Promise<AppComponents> {
35
+ try {
36
+ const data = await this.httpClient.get<{ components?: AppComponents["components"] }>(
37
+ `/platform/v1/env-configs/${appName}/components`,
38
+ this.headers(project),
39
+ )
40
+ return { components: data?.components ?? [], appExists: true }
41
+ } catch (error) {
42
+ if (statusOfError(error) === 404) return { components: [], appExists: false }
43
+ throw error
44
+ }
45
+ }
46
+
47
+ /** The status of an application in the environment. */
48
+ async status(appName: string, envName: string, project: string): Promise<EnvAppStatus> {
49
+ const data = await this.httpClient.get<{ status?: EnvAppStatus[] }>(
50
+ `/platform/v1/env-configs/${appName}/status`,
51
+ this.headers(project),
52
+ )
53
+ return Array.isArray(data?.status) && data.status.length > 0 ? data.status[0] : { envName, status: null }
54
+ }
55
+ }
56
+
57
+ /** The client as a backend of the reader, for one business unit. */
58
+ export function envServicesBackend(client: EnvServicesClient, project: string): EnvServiceBackend {
59
+ return {
60
+ listApps: envName => client.listApps(envName, project),
61
+ components: appName => client.components(appName, project),
62
+ status: (appName, envName) => client.status(appName, envName, project),
63
+ }
64
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./signal"
2
+ export * from "./readiness"
3
+ export * from "./places"
4
+ export * from "./apps"
5
+ export * from "./reader"
6
+ export * from "./client"
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Where each service of an environment lives: the application it has to itself,
3
+ * `<environment>-<appSuffix>`, and the component it is there, `<environment>-<compType>`.
4
+ */
5
+ export interface EnvServicePlace {
6
+ /** Suffix of the application the service has to itself: `<environment>-<suffix>`. */
7
+ appSuffix: string
8
+ /** The component type, when it is not the key of the service. */
9
+ compType?: string
10
+ /** Component types the application of the service also holds, any number of each. */
11
+ holds?: string[]
12
+ /** False for a service that only configures, with nothing running to follow. */
13
+ hasRuntimeStatus?: boolean
14
+ }
15
+
16
+ export const ENV_SERVICE_PLACES: Record<string, EnvServicePlace> = {
17
+ "camel-integration-service": { appSuffix: "camel" },
18
+ "camel-messaging-service": { appSuffix: "messaging" },
19
+ "logging": { appSuffix: "logging" },
20
+ "network": { appSuffix: "network", compType: "networkpolicy", hasRuntimeStatus: false },
21
+ "network-policy": { appSuffix: "network", compType: "networkpolicy", hasRuntimeStatus: false },
22
+ "private-link": { appSuffix: "network" },
23
+ }
24
+
25
+ /** The services an environment can have. */
26
+ export const PLATFORM_SERVICE_TYPES = [
27
+ "camel-integration-service",
28
+ "camel-messaging-service",
29
+ "logging",
30
+ "network",
31
+ ] as const
32
+ export type PlatformServiceType = typeof PLATFORM_SERVICE_TYPES[number]
33
+
34
+ /** Component name a platform service takes inside an environment's config app. */
35
+ export function envComponentName(envName: string, routingKey: string): string {
36
+ return `${envName}-${ENV_SERVICE_PLACES[routingKey]?.compType ?? routingKey}`
37
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Reading the services of an environment: where each lives, the status of its application, and
3
+ * how it is doing. Every application of the console reads them this way, through a backend that
4
+ * answers three questions: which applications the environment has, what one holds, and its status.
5
+ */
6
+ import { ENV_SERVICE_PLACES, PLATFORM_SERVICE_TYPES, envComponentName } from "./places"
7
+ import {
8
+ configuredApps, envAppCandidates, envServiceAppName, isActive, linkLocations, locateService, policyLocations,
9
+ sharedEnvAppName, summarizeHealth, type AppComponents, type EnvHealth, type ServiceLocation,
10
+ } from "./apps"
11
+ import { serviceReadiness, type ReadableStatus, type Readiness } from "./readiness"
12
+
13
+ /** The status of an application of an environment, as the backend gives it. */
14
+ export interface EnvAppStatus extends ReadableStatus {
15
+ envName: string
16
+ }
17
+
18
+ export interface EnvServiceBackend<S extends ReadableStatus = EnvAppStatus> {
19
+ /** The names of the applications of the environment. */
20
+ listApps(envName: string): Promise<string[]>
21
+ /** What an application holds; an application that is not there holds nothing. */
22
+ components(appName: string): Promise<AppComponents>
23
+ /** Its status in the environment; null when it has none. */
24
+ status(appName: string, envName: string): Promise<S | null>
25
+ }
26
+
27
+ export interface EnvServiceState<S = EnvAppStatus> extends ServiceLocation {
28
+ /** Status of the application the service lives in (null until deployed, or when it cannot be read). */
29
+ status: S | null
30
+ /** Status of its own application, when what it holds besides lives apart from it. */
31
+ besidesStatus?: S | null
32
+ }
33
+
34
+ export type EnvServices<S = EnvAppStatus> = Record<string, EnvServiceState<S>>
35
+
36
+ const NO_APP: AppComponents = { components: [], appExists: false }
37
+
38
+ function withStatuses<S>(location: ServiceLocation, statuses: Map<string, S | null>): EnvServiceState<S> {
39
+ return {
40
+ ...location,
41
+ status: isActive(location) ? statuses.get(location.appName) ?? null : null,
42
+ ...(location.besidesApp ? { besidesStatus: statuses.get(location.besidesApp) ?? null } : {}),
43
+ }
44
+ }
45
+
46
+ /** The statuses of applications; one that cannot be read is null, and the others are kept. */
47
+ async function statusesOf<S extends ReadableStatus>(appNames: string[], envName: string, backend: EnvServiceBackend<S>): Promise<Map<string, S | null>> {
48
+ const statuses = await Promise.all(appNames.map(appName => backend.status(appName, envName).catch(() => null)))
49
+ return new Map(appNames.map((appName, index) => [appName, statuses[index]]))
50
+ }
51
+
52
+ /**
53
+ * What an application of an environment holds. An application that is not among those of
54
+ * the environment is not asked for: it holds nothing, and asking would be refused.
55
+ */
56
+ function componentsOf<S extends ReadableStatus>(appName: string, existing: string[], backend: EnvServiceBackend<S>): Promise<AppComponents> {
57
+ return existing.includes(appName) ? backend.components(appName) : Promise.resolve(NO_APP)
58
+ }
59
+
60
+ /** Where each service of an environment lives, and the status of the application it lives in. */
61
+ export async function readEnvServices<S extends ReadableStatus>(envName: string, backend: EnvServiceBackend<S>): Promise<EnvServices<S>> {
62
+ const keys = [...PLATFORM_SERVICE_TYPES]
63
+ const existing = await backend.listApps(envName)
64
+ const [shared, ...own] = await Promise.all([
65
+ componentsOf(sharedEnvAppName(envName), existing, backend),
66
+ ...keys.map(key => componentsOf(envServiceAppName(envName, key), existing, backend)),
67
+ ])
68
+
69
+ const locations: Record<string, ServiceLocation> = {}
70
+ keys.forEach((key, index) => {
71
+ locations[key] = locateService(envName, key, own[index] ?? NO_APP, shared ?? NO_APP)
72
+ })
73
+
74
+ // Links are not services: each lives in an application of its own and is deployed alone.
75
+ // They are located with the rest so that their statuses are followed the same way.
76
+ const network = own[keys.indexOf("network" as typeof keys[number])] ?? NO_APP
77
+ Object.assign(locations, linkLocations(envName, existing, network))
78
+ Object.assign(locations, policyLocations(envName, existing, network, shared ?? NO_APP))
79
+
80
+ const statuses = await statusesOf(configuredApps(locations), envName, backend)
81
+ const services: EnvServices<S> = {}
82
+ for (const key of Object.keys(locations)) {
83
+ services[key] = withStatuses(locations[key], statuses)
84
+ }
85
+ return services
86
+ }
87
+
88
+ /** The same services with their statuses read again. */
89
+ export async function readEnvServiceStatuses<S extends ReadableStatus>(
90
+ envName: string, services: EnvServices<S>, backend: EnvServiceBackend<S>,
91
+ ): Promise<EnvServices<S>> {
92
+ const statuses = await statusesOf(configuredApps(services), envName, backend)
93
+ const refreshed: EnvServices<S> = {}
94
+ for (const [key, service] of Object.entries(services)) {
95
+ refreshed[key] = withStatuses(service, statuses)
96
+ }
97
+ return refreshed
98
+ }
99
+
100
+ /** One state for an environment, read from the applications its services live in. */
101
+ export async function readEnvHealth<S extends ReadableStatus>(envName: string, backend: EnvServiceBackend<S>): Promise<{ health: EnvHealth; message: string | null }> {
102
+ const existing = await backend.listApps(envName)
103
+ const statuses = await statusesOf(envAppCandidates(envName).filter(appName => existing.includes(appName)), envName, backend)
104
+ return summarizeHealth(Array.from(statuses.values()))
105
+ }
106
+
107
+ /**
108
+ * How each service of the environment is doing: `none` when it is not configured, `ready`,
109
+ * `deploying`, `notReady` or `failed` otherwise, with the reason.
110
+ */
111
+ export function readinessOfServices<S extends ReadableStatus>(envName: string, services: EnvServices<S>): Record<string, Readiness> {
112
+ return Object.fromEntries(PLATFORM_SERVICE_TYPES.map(key => [
113
+ key,
114
+ serviceReadiness(envComponentName(envName, key), services[key], ENV_SERVICE_PLACES[key]?.hasRuntimeStatus !== false),
115
+ ]))
116
+ }
@@ -0,0 +1,189 @@
1
+ import { combineSignals, type Signal } from "./signal"
2
+
3
+ export type ServiceReadiness = "none" | "deploying" | "ready" | "notReady" | "failed"
4
+
5
+ export interface Readiness {
6
+ state: ServiceReadiness
7
+ reason: string | null
8
+ }
9
+
10
+ interface ReportedService {
11
+ name?: string
12
+ healthy?: boolean
13
+ message?: string
14
+ }
15
+
16
+ interface ReportedCondition {
17
+ type?: string
18
+ status?: string
19
+ message?: string
20
+ }
21
+
22
+ export interface ReadableStatus {
23
+ status?: {
24
+ status?: string
25
+ services?: ReportedService[]
26
+ conditions?: ReportedCondition[]
27
+ workflow?: { steps?: { phase?: string; message?: string }[] }
28
+ } | null
29
+ }
30
+
31
+ const DEPLOYING_PHASES = new Set(["starting", "rendering", "generatingpolicy", "runningworkflow", "workflowsuspending"])
32
+ const FAILED_PHASES = new Set(["workflowfailed", "workflowterminated"])
33
+ const PREPARE_CONDITIONS = new Set(["Parsed", "Revision", "Policy", "Render", "Workflow"])
34
+ const NEVER_CLEARED_CONDITIONS = new Set(["StateKeep", "GC"])
35
+ const REASON_LIMIT = 240
36
+
37
+ function clean(value: unknown): string | null {
38
+ if (typeof value !== "string") return null
39
+ const flat = value.replace(/\s+/g, " ").trim()
40
+ if (!flat) return null
41
+ return flat.length > REASON_LIMIT ? `${flat.slice(0, REASON_LIMIT - 1)}…` : flat
42
+ }
43
+
44
+ function phaseOf(status: ReadableStatus | null | undefined): string {
45
+ return (status?.status?.status || "").toLowerCase()
46
+ }
47
+
48
+ function failedCondition(status: ReadableStatus | null | undefined, only?: ReadonlySet<string>): string | null {
49
+ const condition = (status?.status?.conditions ?? [])
50
+ .find(candidate => candidate.status !== "True" && !NEVER_CLEARED_CONDITIONS.has(candidate.type ?? "")
51
+ && (!only || only.has(candidate.type ?? "")) && clean(candidate.message))
52
+ return condition ? clean(condition.message) : null
53
+ }
54
+
55
+ function failedStep(status: ReadableStatus | null | undefined): string | null {
56
+ const step = (status?.status?.workflow?.steps ?? [])
57
+ .find(candidate => (candidate.phase || "").toLowerCase() === "failed" && clean(candidate.message))
58
+ return step ? clean(step.message) : null
59
+ }
60
+
61
+ export function applicationReadiness(status: ReadableStatus | null | undefined): Readiness {
62
+ const phase = phaseOf(status)
63
+ if (!phase) return { state: "none", reason: null }
64
+
65
+ const cannotPrepare = failedCondition(status, PREPARE_CONDITIONS)
66
+ if (FAILED_PHASES.has(phase) || phase.includes("error")) {
67
+ return { state: "failed", reason: failedStep(status) ?? failedCondition(status) }
68
+ }
69
+ if (DEPLOYING_PHASES.has(phase)) {
70
+ return cannotPrepare ? { state: "failed", reason: cannotPrepare } : { state: "deploying", reason: null }
71
+ }
72
+
73
+ const unhealthy = (status?.status?.services ?? []).find(service => service.healthy === false)
74
+ if (unhealthy) return { state: "notReady", reason: clean(unhealthy.message) }
75
+ if (phase !== "running") return { state: "notReady", reason: failedCondition(status) }
76
+ return { state: "ready", reason: null }
77
+ }
78
+
79
+ export interface ServiceElement {
80
+ name: string
81
+ readiness: Readiness
82
+ }
83
+
84
+ interface ReadableService {
85
+ exists?: boolean
86
+ status?: ReadableStatus | null
87
+ besidesApp?: string
88
+ besidesStatus?: ReadableStatus | null
89
+ }
90
+
91
+ const SIGNAL_OF: Record<ServiceReadiness, Signal> = {
92
+ none: "gray",
93
+ deploying: "gray",
94
+ ready: "green",
95
+ notReady: "orange",
96
+ failed: "red",
97
+ }
98
+
99
+ const READY: Readiness = { state: "ready", reason: null }
100
+ const NOTHING: Readiness = { state: "none", reason: null }
101
+
102
+ function isSettled(readiness: Readiness): boolean {
103
+ return readiness.state === "ready" || readiness.state === "notReady"
104
+ }
105
+
106
+ function firstIn(parts: readonly Readiness[], state: ServiceReadiness): Readiness | undefined {
107
+ return parts.find(part => part.state === state)
108
+ }
109
+
110
+ function ownReadiness(componentName: string, status: ReadableStatus | null | undefined, reportsRuntime: boolean): Readiness {
111
+ const application = applicationReadiness(status)
112
+ if (application.state === "none") return { state: "notReady", reason: "Not deployed yet" }
113
+ if (!isSettled(application) || !reportsRuntime) return application
114
+
115
+ const own = (status?.status?.services ?? []).find(candidate => candidate.name === componentName)
116
+ if (!own) return { state: "notReady", reason: "Deployed, but it reports nothing yet" }
117
+ if (own.healthy === false) return { state: "notReady", reason: clean(own.message) }
118
+ return READY
119
+ }
120
+
121
+ function reportedElements(status: ReadableStatus | null | undefined, except?: string): ServiceElement[] {
122
+ return (status?.status?.services ?? [])
123
+ .filter(reported => reported.name && reported.name !== except)
124
+ .map(reported => ({
125
+ name: reported.name as string,
126
+ readiness: reported.healthy === false ? { state: "notReady", reason: clean(reported.message) } : READY,
127
+ }))
128
+ }
129
+
130
+ function besidesElements(service: ReadableService): ServiceElement[] {
131
+ const application = applicationReadiness(service.besidesStatus)
132
+ if (application.state === "none") return []
133
+ const reported = isSettled(application) ? reportedElements(service.besidesStatus) : []
134
+ return reported.length > 0 ? reported : [{ name: service.besidesApp ?? "", readiness: application }]
135
+ }
136
+
137
+ export function serviceElements(
138
+ componentName: string,
139
+ service: ReadableService | null | undefined,
140
+ reportsRuntime: boolean,
141
+ ): ServiceElement[] {
142
+ if (!service?.exists) return []
143
+ const own = ownReadiness(componentName, service.status, reportsRuntime)
144
+ const others = isSettled(applicationReadiness(service.status)) ? reportedElements(service.status, componentName) : []
145
+ return [{ name: componentName, readiness: own }, ...others, ...besidesElements(service)]
146
+ }
147
+
148
+ export function combineReadiness(parts: readonly Readiness[]): Readiness {
149
+ const signal = combineSignals(parts.map(part => SIGNAL_OF[part.state]))
150
+ if (signal === "red") return firstIn(parts, "failed") ?? NOTHING
151
+ if (signal === "orange") return firstIn(parts, "notReady") ?? NOTHING
152
+ return firstIn(parts, "deploying") ?? (signal === "green" ? READY : NOTHING)
153
+ }
154
+
155
+ export function serviceReadiness(
156
+ componentName: string,
157
+ service: ReadableService | null | undefined,
158
+ reportsRuntime: boolean,
159
+ ): Readiness {
160
+ return combineReadiness(serviceElements(componentName, service, reportsRuntime).map(element => element.readiness))
161
+ }
162
+
163
+ export type EnvironmentReadiness = "notConfigured" | "ready" | "deploying" | "notReady" | "failed"
164
+
165
+ export function environmentReadiness(parts: readonly Readiness[]): { state: EnvironmentReadiness; reason: string | null } {
166
+ const signal = combineSignals(parts.map(part => SIGNAL_OF[part.state]))
167
+ if (signal === "red") return { state: "failed", reason: firstIn(parts, "failed")?.reason ?? null }
168
+ if (signal === "orange") return { state: "notReady", reason: firstIn(parts, "notReady")?.reason ?? null }
169
+ if (signal === "green") return { state: "ready", reason: null }
170
+ return { state: firstIn(parts, "deploying") ? "deploying" : "notConfigured", reason: null }
171
+ }
172
+
173
+ export interface ReadinessMark {
174
+ loading: boolean
175
+ tone: "success" | "warning" | "error" | null
176
+ label: string
177
+ }
178
+
179
+ const MARK_OF: Record<ServiceReadiness, ReadinessMark | null> = {
180
+ none: null,
181
+ deploying: { loading: true, tone: null, label: "Deploying" },
182
+ ready: { loading: false, tone: "success", label: "Ready" },
183
+ notReady: { loading: false, tone: "warning", label: "Not ready" },
184
+ failed: { loading: false, tone: "error", label: "Failed" },
185
+ }
186
+
187
+ export function readinessMark(readiness: Readiness): ReadinessMark | null {
188
+ return MARK_OF[readiness.state]
189
+ }
@@ -0,0 +1,7 @@
1
+ export type Signal = "green" | "orange" | "red" | "gray"
2
+
3
+ export function combineSignals(signals: readonly Signal[]): Signal {
4
+ if (signals.includes("red")) return "red"
5
+ if (signals.includes("orange")) return "orange"
6
+ return signals.includes("green") ? "green" : "gray"
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orsetra/shared-ui",
3
- "version": "1.12.1",
3
+ "version": "1.14.0",
4
4
  "description": "Shared UI components for Orsetra platform",
5
5
  "main": "./index.ts",
6
6
  "types": "./index.ts",
@@ -10,6 +10,7 @@
10
10
  "./components/layout": "./components/layout/index.ts",
11
11
  "./hooks": "./hooks/index.ts",
12
12
  "./auth": "./auth/index.ts",
13
+ "./env-services": "./lib/env-services/index.ts",
13
14
  "./lib/*": "./lib/*.ts"
14
15
  },
15
16
  "files": [