starling-devex 0.1.2

Starling: a local dev orchestrator with a central daemon, shared named-URL proxy, and a k9s-style TUI (a Rust port of Tilt + portless)
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import React, { useCallback, useEffect, useRef, useState } from "react"
import { Link } from "react-router-dom"
import styled from "styled-components"
import { ReactComponent as CheckmarkSmallSvg } from "./assets/svg/checkmark-small.svg"
import { ReactComponent as CloseSvg } from "./assets/svg/close.svg"
import { ReactComponent as DisabledSvg } from "./assets/svg/not-allowed.svg"
import { ReactComponent as PendingSvg } from "./assets/svg/pending.svg"
import { ReactComponent as WarningSvg } from "./assets/svg/warning.svg"
import { linkToTiltAsset } from "./constants"
import { FilterLevel } from "./logfilters"
import { useLogStore } from "./LogStore"
import { RowValues } from "./OverviewTableColumns"
import { usePathBuilder } from "./PathBuilder"
import SidebarItem from "./SidebarItem"
import { buildStatus, combinedStatus, runtimeStatus } from "./status"
import {
  Color,
  Font,
  FontSize,
  mixinResetListStyle,
  SizeUnit,
  spin,
} from "./style-helpers"
import Tooltip from "./Tooltip"
import { ResourceName, ResourceStatus, UIResource } from "./types"

const ResourceGroupStatusLabel = styled.p`
  text-transform: uppercase;
  margin-right: ${SizeUnit(0.5)};
`
const ResourceGroupStatusSummaryList = styled.ul`
  display: flex;
  ${mixinResetListStyle}
`
const ResourceGroupStatusSummaryItemRoot = styled.li`
  display: flex;
  align-items: center;

  & + & {
    margin-left: ${SizeUnit(0.25)};
    border-left: 1px solid ${Color.gray40};
    padding-left: ${SizeUnit(0.25)};
  }
  &.is-highlightError {
    color: ${Color.red};
    .fillStd {
      fill: ${Color.red};
    }
  }
  &.is-highlightWarning {
    color: ${Color.yellow};
    .fillStd {
      fill: ${Color.yellow};
    }
  }
  &.is-highlightPending {
    color: ${Color.gray70};
    stroke: ${Color.gray70};
    .fillStd {
      fill: ${Color.gray70};
    }
  }
  &.is-highlightHealthy {
    color: ${Color.green};
    .fillStd {
      fill: ${Color.green};
    }
  }
`
export const ResourceGroupStatusSummaryItemCount = styled.span`
  font-weight: bold;
  padding-left: 4px;
  padding-right: 4px;
`
export const ResourceStatusSummaryRoot = styled.aside`
  display: flex;
  font-family: ${Font.sansSerif};
  font-size: ${FontSize.smallest};
  align-items: center;
  color: ${Color.grayLightest};

  .fillStd {
    fill: ${Color.gray40};
  }

  & + & {
    margin-left: ${SizeUnit(1.5)};
  }
`
export const PendingIcon = styled(PendingSvg)`
  animation: ${spin} 4s linear infinite;
`

const DisabledIcon = styled(DisabledSvg)`
  .fillStd {
    fill: ${Color.gray60};
  }
`

type ResourceGroupStatusItemProps = {
  label: string
  icon: JSX.Element
  className: string
  count: number
  countOutOf?: number
  href?: string
}
export function ResourceGroupStatusItem(props: ResourceGroupStatusItemProps) {
  const count = (
    <>
      <ResourceGroupStatusSummaryItemCount aria-label={`${props.label} count`}>
        {props.count}
      </ResourceGroupStatusSummaryItemCount>
      {props.countOutOf && (
        <>
          /
          <ResourceGroupStatusSummaryItemCount aria-label="Out of total resource count">
            {props.countOutOf}
          </ResourceGroupStatusSummaryItemCount>
        </>
      )}
    </>
  )

  const summaryContent = props.href ? (
    <Link to={props.href}>{count}</Link>
  ) : (
    <>{count}</>
  )

  return (
    <Tooltip title={props.label}>
      <ResourceGroupStatusSummaryItemRoot className={props.className}>
        {props.icon}
        {summaryContent}
      </ResourceGroupStatusSummaryItemRoot>
    </Tooltip>
  )
}

type ResourceGroupStatusProps = {
  counts: StatusCounts
  displayText?: string
  labelText: string // Used for a11y markup, should be a descriptive title.
  healthyLabel: string
  unhealthyLabel: string
  warningLabel: string
  linkToLogFilters: boolean
}

export function ResourceGroupStatus(props: ResourceGroupStatusProps) {
  if (props.counts.totalEnabled === 0 && props.counts.disabled === 0) {
    return null
  }
  let pb = usePathBuilder()

  let items = new Array<JSX.Element>()

  if (props.counts.unhealthy) {
    const errorHref = props.linkToLogFilters
      ? pb.encpath`/r/${ResourceName.all}/overview?level=${FilterLevel.error}`
      : undefined
    items.push(
      <ResourceGroupStatusItem
        key={props.unhealthyLabel}
        label={props.unhealthyLabel}
        count={props.counts.unhealthy}
        href={errorHref}
        className="is-highlightError"
        icon={<CloseSvg role="presentation" width="11" key="icon" />}
      />
    )
  }

  if (props.counts.warning) {
    const warningHref = props.linkToLogFilters
      ? pb.encpath`/r/${ResourceName.all}/overview?level=${FilterLevel.warn}`
      : undefined
    items.push(
      <ResourceGroupStatusItem
        key={props.warningLabel}
        label={props.warningLabel}
        count={props.counts.warning}
        href={warningHref}
        className="is-highlightWarning"
        icon={<WarningSvg role="presentation" width="7" key="icon" />}
      />
    )
  }

  if (props.counts.pending) {
    items.push(
      <ResourceGroupStatusItem
        key="pending"
        label="pending"
        count={props.counts.pending}
        className="is-highlightPending"
        icon={<PendingIcon role="presentation" width="8" key="icon" />}
      />
    )
  }

  // There might not always be enabled resources
  // if all resources are disabled
  if (props.counts.totalEnabled) {
    items.push(
      <ResourceGroupStatusItem
        key={props.healthyLabel}
        label={props.healthyLabel}
        count={props.counts.healthy}
        countOutOf={props.counts.totalEnabled}
        className="is-highlightHealthy"
        icon={<CheckmarkSmallSvg role="presentation" key="icon" />}
      />
    )
  }

  if (props.counts.disabled) {
    items.push(
      <ResourceGroupStatusItem
        key="disabled"
        label="disabled"
        count={props.counts.disabled}
        className="is-highlightDisabled"
        icon={<DisabledIcon role="presentation" width="15" key="icon" />}
      />
    )
  }

  const displayLabel = props.displayText ? (
    <ResourceGroupStatusLabel>{props.displayText}</ResourceGroupStatusLabel>
  ) : null

  return (
    <>
      {displayLabel}
      <ResourceGroupStatusSummaryList>{items}</ResourceGroupStatusSummaryList>
    </>
  )
}

export type StatusCounts = {
  totalEnabled: number
  healthy: number
  unhealthy: number
  pending: number
  warning: number
  disabled: number
}

function statusCounts(statuses: ResourceStatus[]): StatusCounts {
  let allEnabledStatusCount = 0
  let healthyStatusCount = 0
  let unhealthyStatusCount = 0
  let pendingStatusCount = 0
  let warningCount = 0
  let disabledCount = 0
  statuses.forEach((status) => {
    switch (status) {
      case ResourceStatus.Warning:
        allEnabledStatusCount++
        healthyStatusCount++
        warningCount++
        break
      case ResourceStatus.Healthy:
        allEnabledStatusCount++
        healthyStatusCount++
        break
      case ResourceStatus.Unhealthy:
        allEnabledStatusCount++
        unhealthyStatusCount++
        break
      case ResourceStatus.Pending:
      case ResourceStatus.Building:
        allEnabledStatusCount++
        pendingStatusCount++
        break
      case ResourceStatus.Disabled:
        disabledCount++
        break
      default:
      // Don't count None status in the overall resource count.
      // These might be manual tasks we haven't run yet.
    }
  })

  return {
    totalEnabled: allEnabledStatusCount,
    healthy: healthyStatusCount,
    unhealthy: unhealthyStatusCount,
    pending: pendingStatusCount,
    warning: warningCount,
    disabled: disabledCount,
  }
}

export function getDocumentTitle(
  counts: StatusCounts,
  isSnapshot: boolean,
  isSocketConnected: boolean
) {
  const { totalEnabled, healthy, pending, unhealthy } = counts
  let faviconHref = "/static/ico/favicon-green.ico"
  let title = `✔︎ ${healthy}/${totalEnabled} ┊ Tilt`
  if (!isSocketConnected && !isSnapshot) {
    title = "Disconnected ┊ Tilt"
    // Use a publicly-hosted favicon since Tilt is disconnected
    // and it's not guaranteed that the favicon will be cached
    faviconHref = linkToTiltAsset("ico", "dashboard-favicon-gray.ico")
  } else if (unhealthy > 0) {
    title = `✖︎ ${unhealthy} ┊ Tilt`
    faviconHref = "/static/ico/favicon-red.ico"
  } else if (pending) {
    title = `… ${healthy}/${totalEnabled} ┊ Tilt`
    faviconHref = "/static/ico/favicon-gray.ico"
  } else if (totalEnabled === 0) {
    title = `✔︎ 0/0 ┊ Tilt`
    faviconHref = "/static/ico/favicon-gray.ico"
  }

  if (isSnapshot) {
    title = `Snapshot: ${title}`
  }

  return { title, faviconHref }
}

function ResourceMetadata(props: {
  counts: StatusCounts
  isSocketConnected?: boolean
}) {
  let { totalEnabled, healthy, pending, unhealthy } = props.counts
  const pb = usePathBuilder()
  const isSnapshot = pb.isSnapshot()

  useEffect(() => {
    // Determine the document title and favicon based
    // on Tilt's connection, resource statuses, and whether
    // or not Tilt is displaying a snapshot
    const existingFavicon =
      document.head.querySelector<HTMLLinkElement>("#favicon")
    const { title, faviconHref } = getDocumentTitle(
      props.counts,
      isSnapshot,
      props.isSocketConnected ?? true
    )
    document.title = title
    if (existingFavicon) {
      existingFavicon.href = faviconHref
    }
  }, [totalEnabled, healthy, pending, unhealthy, props.isSocketConnected])
  return <></>
}

type NotificationSpec = { tag: string } & (
  | { action: "show"; body: string }
  | { action: "close" }
)

export function ResourceNotification(props: {
  counts: StatusCounts
  isSocketConnected?: boolean
}) {
  const { pending, unhealthy } = props.counts
  const [allowed, setAllowed] = useState<boolean>(false)
  const firstRun = useRef(true)
  const [notification, setNotification] = useState<Notification | undefined>()

  useEffect(() => {
    try {
      Notification.requestPermission().then((result) =>
        setAllowed(result === "granted")
      )
    } catch (e) {
      console.error("failed to request notification permissions", e)
    }
  })

  const buildSpec: () => NotificationSpec = useCallback(() => {
    if (unhealthy > 0) {
      return {
        tag: "unhealthy",
        action: "show",
        body: `Unhealthy resources: ${unhealthy}`,
      }
    } else if (pending == 0) {
      return {
        tag: "ready",
        action: "show",
        body: "Ready",
      }
    } else {
      // close existing 'ready' so later changes renotify
      return {
        tag: "ready",
        action: "close",
      }
    }
  }, [allowed, pending, unhealthy])

  useEffect(() => {
    if (allowed) {
      if (firstRun.current) {
        firstRun.current = false
        return
      }

      const spec = buildSpec()
      if (notification) {
        if (notification.tag !== spec.tag || spec.action === "close") {
          notification.close()
        }
      }

      if (spec.action === "show") {
        setNotification(
          new Notification("Tilt", {
            body: spec.body,
            tag: spec.tag,
          })
        )
      }
    }
  }, [allowed, buildSpec])

  return <></>
}

type ResourceStatusSummaryOptions = {
  displayText?: string
  labelText?: string
  updateMetadata?: boolean
  linkToLogFilters?: boolean
  showNotifications?: boolean
}

type ResourceStatusSummaryProps = {
  statuses: ResourceStatus[]
  isSocketConnected?: boolean
} & ResourceStatusSummaryOptions

function ResourceStatusSummary(props: ResourceStatusSummaryProps) {
  // Default the display options if no option is provided
  const updateMetadata = props.updateMetadata ?? true
  const linkToLogFilters = props.linkToLogFilters ?? true
  const labelText = props.labelText ?? "Resource status summary"
  const showNotifications = props.showNotifications ?? true

  return (
    <ResourceStatusSummaryRoot aria-label={labelText}>
      {updateMetadata && (
        <ResourceMetadata
          counts={statusCounts(props.statuses)}
          isSocketConnected={props.isSocketConnected}
        />
      )}
      {showNotifications && (
        <ResourceNotification counts={statusCounts(props.statuses)} />
      )}
      <ResourceGroupStatus
        counts={statusCounts(props.statuses)}
        displayText={props.displayText}
        labelText={labelText}
        healthyLabel={"healthy"}
        unhealthyLabel={"err"}
        warningLabel={"warn"}
        linkToLogFilters={linkToLogFilters}
      />
    </ResourceStatusSummaryRoot>
  )
}

// The generic StatusSummaryProps takes a template type
// for the resources it will summarize, so that it can be used
// throughout the app with different data types.

type StatusSummaryProps<T> = {
  resources: readonly T[]
  isSocketConnected?: boolean
} & ResourceStatusSummaryOptions

export function SidebarGroupStatusSummary(
  props: StatusSummaryProps<SidebarItem>
) {
  const allStatuses = props.resources.map((item: SidebarItem) =>
    combinedStatus(item.buildStatus, item.runtimeStatus)
  )

  return (
    <ResourceStatusSummary
      statuses={allStatuses}
      linkToLogFilters={false}
      updateMetadata={false}
      showNotifications={false}
      {...props}
    />
  )
}

export function TableGroupStatusSummary(props: StatusSummaryProps<RowValues>) {
  const allStatuses = props.resources.map((r: RowValues) =>
    combinedStatus(r.statusLine.buildStatus, r.statusLine.runtimeStatus)
  )

  return (
    <ResourceStatusSummary
      statuses={allStatuses}
      linkToLogFilters={false}
      updateMetadata={false}
      showNotifications={false}
      {...props}
    />
  )
}

export function AllResourceStatusSummary(
  props: StatusSummaryProps<UIResource>
) {
  const logStore = useLogStore()
  const allStatuses = props.resources.map((r: UIResource) =>
    combinedStatus(buildStatus(r, logStore), runtimeStatus(r, logStore))
  )

  return <ResourceStatusSummary statuses={allStatuses} {...props} />
}